How to use the @babel/types.numericLiteral function in @babel/types

To help you get started, we’ve selected a few @babel/types examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rpetrich / swift-to-js / values.ts View on Github external
export function literal(value: LiteralValue, location?: LocationSource): ExpressionValue | VariableValue {
	if (typeof value === "boolean") {
		return expr(booleanLiteral(value), location);
	} else if (typeof value === "number") {
		return expr(numericLiteral(value), location);
	} else if (typeof value === "string") {
		return expr(stringLiteral(value), location);
	} else if (value === null) {
		return expr(nullLiteral(), location);
	} else if (Array.isArray(value)) {
		return expr(arrayExpression(value.map((element) => literal(element, location).expression)), location);
	} else if (typeof value === "object") {
		return expr(objectExpression(Object.keys(value).map((key) => {
			const expression = literal((value as LiteralMap)[key], location).expression;
			if (validIdentifier.test(key)) {
				return objectProperty(identifier(key), expression);
			} else {
				// Case where key is not a valid identifier
				return objectProperty(stringLiteral(key), expression, true);
			}
		})), location) as ExpressionValue;
github Kiikurage / babel-plugin-flow-to-typescript / dist / converters / convert_flow_type.js View on Github external
return types_1.tsUnionType([tsT, types_1.tsNullKeyword()]);
            }
            else {
                // { key: ?T } -> { key: T | null | undefined }
                return types_1.tsUnionType([tsT, types_1.tsUndefinedKeyword(), types_1.tsNullKeyword()]);
            }
        }
        // var x: X -> var x: X
        // var x:?T -> var x:T | null | undefined
        return types_1.tsUnionType([tsT, types_1.tsUndefinedKeyword(), types_1.tsNullKeyword()]);
    }
    if (util_1.isNodePath(types_1.isNullLiteralTypeAnnotation, path)) {
        return types_1.tsNullKeyword();
    }
    if (util_1.isNodePath(types_1.isNumberLiteralTypeAnnotation, path)) {
        return types_1.tsLiteralType(types_1.numericLiteral(path.node.value));
    }
    if (util_1.isNodePath(types_1.isNumberTypeAnnotation, path)) {
        return types_1.tsNumberKeyword();
    }
    if (util_1.isNodePath(types_1.isObjectTypeAnnotation, path)) {
        const members = [];
        const spreads = [];
        const objectTypeNode = path.node;
        if (objectTypeNode.exact) {
            util_1.warnOnlyOnce("Exact object type annotation in Flow is ignored. In TypeScript, it's always regarded as exact type");
            objectTypeNode.exact = false;
        }
        if (objectTypeNode.properties && objectTypeNode.properties.length > 0) {
            for (const [i, property] of objectTypeNode.properties.entries()) {
                if (types_1.isObjectTypeProperty(property)) {
                    const tsPropSignature = types_1.tsPropertySignature(property.key, types_1.tsTypeAnnotation(convertFlowType(path.get(`properties.${i}`).get('value'))));
github salesforce / lwc / packages / lwc-template-compiler / src / codegen / index.ts View on Github external
if (props) {
            const propsObj = objectToAST(props, key => {
                return computeAttrValue(props[key], element);
            });
            data.push(t.objectProperty(t.identifier('props'), propsObj));
        }

        if (lwc || locator) {
            generateContext(element, data, codeGen);
        }

        // Key property on VNode
        if (forKey) {
            // If element has user-supplied `key` or is in iterator, call `api.k`
            const { expression: forKeyExpression } = bindExpression(forKey, element);
            const generatedKey = codeGen.genKey(t.numericLiteral(element.key!), forKeyExpression);
            data.push(t.objectProperty(t.identifier('key'), generatedKey));
        } else {
            // If stand alone element with no user-defined key
            // member expression id
            data.push(t.objectProperty(t.identifier('key'), t.numericLiteral(element.key!)));
        }

        // Event handler
        if (on) {
            const onObj = objectToAST(on, key => {
                const { expression: componentHandler } = bindExpression(on[key], element);
                let handler: t.Expression;
                if (locator !== undefined && key === 'click') {
                    let locatorContext: t.Expression | undefined;
                    if (locator.context) {
                        locatorContext = bindExpression(locator.context, element).expression;
github firefox-devtools / debugger / src / workers / parser / mapBindings.js View on Github external
return node.declarations.map(declaration =>
    t.expressionStatement(
      t.assignmentExpression(
        "=",
        getAssignmentTarget(declaration.id, bindings),
        declaration.init || t.unaryExpression("void", t.numericLiteral(0))
      )
    )
  );
github facebook / prepack / src / serializer / ResidualOperationSerializer.js View on Github external
_serializeInvariant(
    { appendLastToInvariantOperationDescriptor, violationConditionOperationDescriptor }: OperationDescriptorData,
    nodes: Array
  ): BabelNodeStatement {
    invariant(violationConditionOperationDescriptor !== undefined);
    let messageComponents = [
      t.stringLiteral("Prepack model invariant violation ("),
      t.numericLiteral(this.preludeGenerator.nextInvariantId++),
    ];
    if (appendLastToInvariantOperationDescriptor) {
      let propName = nodes[0];
      let last = nodes.pop();
      messageComponents.push(t.stringLiteral("): "));
      messageComponents.push(this.serializeExpression(appendLastToInvariantOperationDescriptor, [propName, last]));
    } else {
      messageComponents.push(t.stringLiteral(")"));
    }
    let throwString = messageComponents[0];
    for (let i = 1; i < messageComponents.length; i++)
      throwString = t.binaryExpression("+", throwString, messageComponents[i]);
    let condition = this.serializeExpression(violationConditionOperationDescriptor, nodes);
    let consequent = this.getErrorStatement(throwString);
    return t.ifStatement(condition, consequent);
  }
github babel / babel / packages / babel-traverse / src / path / conversion.js View on Github external
computedKey
            ? t.assignmentExpression("=", computedKey, superProp.node.property)
            : superProp.node.property,
          superProp.node.computed,
        ),
      ),
      t.assignmentExpression(
        "=",
        t.memberExpression(
          superProp.node.object,
          computedKey
            ? t.identifier(computedKey.name)
            : superProp.node.property,
          superProp.node.computed,
        ),
        t.binaryExpression("+", t.identifier(tmp.name), t.numericLiteral(1)),
      ),
    ];

    if (!superProp.parentPath.node.prefix) {
      parts.push(t.identifier(tmp.name));
    }

    updateExpr.replaceWith(t.sequenceExpression(parts));

    const left = updateExpr.get("expressions.0.right");
    const right = updateExpr.get("expressions.1.left");
    return [left, right];
  }

  return [superProp];
}
github babel / babel / packages / babel-plugin-transform-es2015-parameters / src / rest.js View on Github external
function optimiseLengthGetter(path, argsId, offset) {
  if (offset) {
    path.parentPath.replaceWith(
      restLength({
        ARGUMENTS: argsId,
        OFFSET: t.numericLiteral(offset),
      }),
    );
  } else {
    path.replaceWith(argsId);
  }
}
github facebook / prepack / src / serializer / ResidualOperationSerializer.js View on Github external
_serializeUpdateIncrementor(
    { incrementor }: OperationDescriptorData,
    [oldValNode]: Array
  ): BabelNodeExpression {
    invariant(incrementor !== undefined);
    return t.binaryExpression(incrementor, oldValNode, t.numericLiteral(1));
  }
github babel / babel / packages / babel-helper-module-imports / src / import-injector.js View on Github external
}
      }
    } else {
      throw new Error(`Unknown importedInterop "${importedInterop}".`);
    }

    const { statements, resultName } = builder.done();

    this._insertStatements(statements, blockHoist);

    if (
      (isDefault || isNamed) &&
      ensureNoContext &&
      resultName.type !== "Identifier"
    ) {
      return t.sequenceExpression([t.numericLiteral(0), resultName]);
    }
    return resultName;
  }
github Heigvd / Wegas / wegas-app / src / main / webapp / 2 / src / Editor / Components / FormView / Script / ExpressionStatement.tsx View on Github external
function valueToAST(value: unknown, type: parameterType) {
  if (value === undefined) {
    return identifier('undefined');
  }
  if (type === 'identifier' && typeof value === 'string') {
    return identifier(value);
  }
  switch (typeof value) {
    case 'string':
      return stringLiteral(value);
    case 'number':
      return numericLiteral(value);
    case 'boolean':
      return booleanLiteral(value);
    case 'object': {
      return parseExpression(JSON.stringify(value));
    }
    default:
      throw Error(`Unknown type ${type}`);
  }
}