@babel/types#Identifier TypeScript Examples

The following examples show how to use @babel/types#Identifier. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: structParser.ts    From engine with MIT License 6 votes vote down vote up
structParser = (
  babel: typeof Babel,
  obj: ObjectPattern
): StructOperation => {
  const t = babel.types;
  const result = obj.properties.reduce(
    (acc, x) => {
      if (t.isObjectProperty(x)) {
        const node = x as ObjectProperty;
        const propName = (node.key as Identifier).name;
        const propValue = processValue(babel, node);
        if (propValue) {
          acc.value[propName] = propValue;
        }
      } else {
        console.log("Not object property", x);
      }
      return acc;
    },
    {
      type: OperationTypes.STRUCT,
      value: {},
    } as StructOperation
  );
  return result;
}
Example #2
Source File: module.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
calculateFields(): void {
    this.originalCode = generator({
      ...this.originalFile.program,
      type: 'Program',
      body: [expressionStatement(this.rootPath.node)],
    }, { compact: true }).code;

    this.rootPath.traverse({
      StringLiteral: (path) => {
        this.moduleStrings.push(path.node.value);
      },
      Identifier: (path) => {
        if (path.node.name.length > 1) {
          this.variableNames.add(path.node.name);
        }
      },
    });

    this.moduleComments = this.originalFile.comments
      ?.filter((comment) => this.rootPath.node.start && this.rootPath.node.end && comment.start > this.rootPath.node.start && comment.end < this.rootPath.node.end)
      ?.map((comment) => comment.value) || [];
  }
Example #3
Source File: funcOperationCompiler.ts    From engine with MIT License 6 votes vote down vote up
funcOperationCompiler = (op: FuncOperation): ObjectExpression => {
  const type = objectProperty(identifier("type"), stringLiteral(op.type));
  const paramsList = op.value.params.map((x) => {
    const type = objectProperty(identifier("type"), stringLiteral(x.type));
    const value = objectProperty(identifier("value"), stringLiteral("value"));
    return objectExpression([type, value]);
  });
  const fn = objectProperty(identifier("fn"), stringLiteral("fn"));
  const paramsArray = arrayExpression(paramsList);
  const params = objectProperty(identifier("params"), paramsArray);
  const internal = objectExpression([params, fn]);
  const value = objectProperty(identifier("value"), internal);
  return objectExpression([type, value]);
}
Example #4
Source File: arrayDestructureEvaluator.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
afterPass(): void {
    if (this.destructureFunctionStart == null) return;

    this.variableDeclarators.forEach((data) => {
      if (!data.couldBeDestructure) return;
      if (data.destructureBindingStart !== this.destructureFunctionStart) return;

      const sourceArray = this.variableDeclarators.find((srcData) => srcData.varStart === data.destructureArrayBindingStart);
      const arrayUsages = this.variableDeclarators.filter((arrData) => arrData.arrayAccessBindingStart === data.varStart);
      if (!sourceArray || !arrayUsages.length) return;

      const arrayPatternElements: (Identifier | null)[] = [];
      arrayUsages.forEach((usage) => {
        if (usage.arrayAccessVal == null) throw new Error();
        arrayPatternElements[usage.arrayAccessVal] = identifier(usage.varName);
      });
      for (let i = 0; i < arrayPatternElements.length; i += 1) {
        if (arrayPatternElements[i] === undefined) {
          arrayPatternElements[i] = null;
        }
      }

      sourceArray.path.node.id = arrayPattern(arrayPatternElements);

      if (!this.destructureFunction?.removed) {
        this.destructureFunction?.remove();
      }
      if (!data.path.removed) {
        data.path.remove();
      }
      arrayUsages.forEach((usageData) => (usageData.path.removed ? null : usageData.path.remove()));
    });
  }
Example #5
Source File: pathCompiler.ts    From engine with MIT License 6 votes vote down vote up
pathCompiler = (path: InvokablePath): ArrayExpression => {
  const parts = path.map((x) => {
    let type = objectProperty(identifier("type"), stringLiteral(x.type));
    let value = objectProperty(identifier("ignored"), nullLiteral());
    if (x.type === ValueTypes.CONST) {
      let paramValue;
      if (x.value.__node__) {
        paramValue = x.value.__node__;
      } else {
        paramValue = stringLiteral(x.value.toString());
      }
      value = objectProperty(identifier("value"), paramValue);
    } else if (
      x.type === ValueTypes.INTERNAL ||
      x.type === ValueTypes.EXTERNAL
    ) {
      const path = x.path.map((y: string) => stringLiteral(y));
      value = objectProperty(identifier("path"), arrayExpression(path));
    } else if (x.type === ValueTypes.INVOKE) {
      const path = x.path.map((y: string) => stringLiteral(y));
      value = objectProperty(identifier("path"), arrayExpression(path));
    }
    return objectExpression([type, value]);
  });
  const result = arrayExpression(parts);
  return result;
}
Example #6
Source File: babel-polyfill.ts    From nota with MIT License 6 votes vote down vote up
importSpecifier = (
  local: Identifier,
  imported: Identifier | StringLiteral
): ImportSpecifier => ({
  type: "ImportSpecifier",
  local,
  imported,
  ...baseNode,
})
Example #7
Source File: babel-polyfill.ts    From nota with MIT License 6 votes vote down vote up
arrowFunctionExpression = (
  params: Array<Identifier | Pattern | RestElement>,
  body: BlockStatement | Expression
): ArrowFunctionExpression => ({
  type: "ArrowFunctionExpression",
  params,
  body,
  expression: false,
  ...baseNode,
})
Example #8
Source File: babel-polyfill.ts    From nota with MIT License 6 votes vote down vote up
memberExpression = (
  object: Expression,
  property: Expression | Identifier,
  computed: boolean = false
): MemberExpression => ({
  type: "MemberExpression",
  object,
  property,
  computed,
  ...baseNode,
})
Example #9
Source File: babel-polyfill.ts    From nota with MIT License 6 votes vote down vote up
objectProperty = (
  key: Expression | Identifier | StringLiteral | NumericLiteral,
  value: Expression | PatternLike,
  shorthand: boolean = false
): ObjectProperty => ({
  type: "ObjectProperty",
  key,
  value,
  computed: false,
  shorthand,
  ...baseNode,
})
Example #10
Source File: rawObjectCompiler.ts    From engine with MIT License 6 votes vote down vote up
rawObjectCompiler = (obj: any): ObjectExpression => {
  const props = Object.keys(obj).reduce((acc, x) => {
    let val: any = obj[x];
    let result;
    if (isString(val)) {
      result = stringLiteral(val);
    } else if (typeof val === "number") {
      result = numericLiteral(toNumber(val));
    } else if (isArray(val)) {
      let list = val.map((x) => stringLiteral(x));
      result = arrayExpression(list);
    } else if (isPlainObject(val)) {
      result = rawObjectCompiler(val);
    } else {
      throw new Error("Meta type for " + val + " not supported");
    }
    if (result) {
      acc.push(objectProperty(identifier(x), result));
    }
    return acc;
  }, [] as ObjectProperty[]);

  return objectExpression(props);
}
Example #11
Source File: structOperationCompiler.ts    From engine with MIT License 6 votes vote down vote up
structOperationCompiler = (
  opOrig: StructOperation
): ObjectExpression => {
  const type = objectProperty(identifier("type"), stringLiteral(opOrig.type));
  const keys: ObjectProperty[] = Object.keys(opOrig.value)
    .map((x) => {
      const op = opOrig.value[x];
      let result;
      if (op.type === OperationTypes.GET) {
        result = pathOperationCompiler(op);
      } else if (op.type === OperationTypes.OBSERVE) {
        result = pathOperationCompiler(op);
      } else if (op.type === OperationTypes.UPDATE) {
        result = pathOperationCompiler(op);
      } else if (op.type === OperationTypes.FUNC) {
        result = funcOperationCompiler(op);
      } else if (op.type === OperationTypes.STRUCT) {
        result = structOperationCompiler(op);
      } else if (op.type === OperationTypes.VALUE) {
        result = valueOperationCompiler(op);
      } else {
        throw new Error(`Operation ${op} not supported`);
      }
      return objectProperty(identifier(x), result, false, true);
    })
    .filter((x) => !!x);
  const value = objectProperty(identifier("value"), objectPattern(keys));
  if (opOrig.meta) {
    const meta = objectProperty(
      identifier("meta"),
      rawObjectCompiler(opOrig.meta)
    );
    return objectExpression([type, value, meta]);
  } else {
    return objectExpression([type, value]);
  }
}
Example #12
Source File: addPathImport.ts    From engine with MIT License 6 votes vote down vote up
addPathImport: AddPathImport = (babel, state, ref) => {
  const producerName = "@c11/engine.producer";
  const pathImport = importDeclaration(
    [importSpecifier(identifier("path"), identifier("path"))],
    stringLiteral(producerName)
  );

  const program = ref.findParent((p) => p.isProgram());

  if (!program) {
    throw new Error("Internal error. Cannot find program node");
  }

  const macroImport = program.get("body").find((p) => {
    const result =
      p.isImportDeclaration() &&
      p.node.source.value.indexOf("@c11/engine.macro") !== -1;
    return result;
  });

  if (macroImport) {
    // @ts-ignore
    macroImport.insertAfter(pathImport);
  }
}
Example #13
Source File: addWildcardImport.ts    From engine with MIT License 6 votes vote down vote up
addWildcardImport: AddWildcardImport = (babel, state, ref) => {
  const producerName = "@c11/engine.producer";
  const pathImport = importDeclaration(
    [importSpecifier(identifier("wildcard"), identifier("wildcard"))],
    stringLiteral(producerName)
  );
  const program = ref.findParent((p) => p.isProgram());
  if (!program) {
    throw new Error("");
  }

  const macroImport = program.get("body").find((p) => {
    const result =
      p.isImportDeclaration() &&
      p.node.source.value.indexOf("@c11/engine.macro") !== -1;
    return result;
  });

  if (macroImport) {
    // @ts-ignore
    macroImport.insertAfter(pathImport);
  }
}
Example #14
Source File: module.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
calculateFields(): void {
    this.originalCode = generator({
      ...this.originalFile.program,
      type: 'Program',
      body: [expressionStatement(this.rootPath.node)],
    }, { compact: true }).code;

    this.rootPath.traverse({
      StringLiteral: (path) => {
        this.moduleStrings.push(path.node.value);
      },
      Identifier: (path) => {
        if (path.node.name.length > 1) {
          this.variableNames.add(path.node.name);
        }
      },
    });

    this.moduleComments = this.originalFile.comments
      ?.filter((comment) => this.rootPath.node.start && this.rootPath.node.end && comment.start > this.rootPath.node.start && comment.end < this.rootPath.node.end)
      ?.map((comment) => comment.value) || [];
  }
Example #15
Source File: arrayDestructureEvaluator.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
afterPass(): void {
    if (this.destructureFunctionStart == null) return;

    this.variableDeclarators.forEach((data) => {
      if (!data.couldBeDestructure) return;
      if (data.destructureBindingStart !== this.destructureFunctionStart) return;

      const sourceArray = this.variableDeclarators.find((srcData) => srcData.varStart === data.destructureArrayBindingStart);
      const arrayUsages = this.variableDeclarators.filter((arrData) => arrData.arrayAccessBindingStart === data.varStart);
      if (!sourceArray || !arrayUsages.length) return;

      const arrayPatternElements: (Identifier | null)[] = [];
      arrayUsages.forEach((usage) => {
        if (usage.arrayAccessVal == null) throw new Error();
        arrayPatternElements[usage.arrayAccessVal] = identifier(usage.varName);
      });
      for (let i = 0; i < arrayPatternElements.length; i += 1) {
        if (arrayPatternElements[i] === undefined) {
          arrayPatternElements[i] = null;
        }
      }

      sourceArray.path.node.id = arrayPattern(arrayPatternElements);

      if (!this.destructureFunction?.removed) {
        this.destructureFunction?.remove();
      }
      if (!data.path.removed) {
        data.path.remove();
      }
      arrayUsages.forEach((usageData) => (usageData.path.removed ? null : usageData.path.remove()));
    });
  }
Example #16
Source File: arrayDestructureEvaluator.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
afterPass(): void {
    if (this.destructureFunctionStart == null) return;

    this.variableDeclarators.forEach((data) => {
      if (!data.couldBeDestructure) return;
      if (data.destructureBindingStart !== this.destructureFunctionStart) return;

      const sourceArray = this.variableDeclarators.find((srcData) => srcData.varStart === data.destructureArrayBindingStart);
      const arrayUsages = this.variableDeclarators.filter((arrData) => arrData.arrayAccessBindingStart === data.varStart);
      if (!sourceArray || !arrayUsages.length) return;

      const arrayPatternElements: (Identifier | null)[] = [];
      arrayUsages.forEach((usage) => {
        if (usage.arrayAccessVal == null) throw new Error();
        arrayPatternElements[usage.arrayAccessVal] = identifier(usage.varName);
      });
      for (let i = 0; i < arrayPatternElements.length; i += 1) {
        if (arrayPatternElements[i] === undefined) {
          arrayPatternElements[i] = null;
        }
      }

      sourceArray.path.node.id = arrayPattern(arrayPatternElements);

      if (!this.destructureFunction?.removed) {
        this.destructureFunction?.remove();
      }
      if (!data.path.removed) {
        data.path.remove();
      }
      arrayUsages.forEach((usageData) => (usageData.path.removed ? null : usageData.path.remove()));
    });
  }
Example #17
Source File: validateRef.ts    From engine with MIT License 6 votes vote down vote up
validateRef = (ref: Babel.NodePath): Result => {
  const result: Result = {
    error: true,
  };
  if (!ref) {
    return result;
  }
  const node = ref.parentPath?.node;
  const refNode = ref.node as Identifier;
  const parent = ref.findParent((p) => p.isVariableDeclarator());
  if (!parent) {
    throw new Error(
      "The producer or view types can only be used with variable declarations e.g. let foo: producer."
    );
  }
  const declaration = parent.node as VariableDeclarator;
  if (!(isTSTypeReference(node) || isTypeAnnotation(node))) {
    result.errorMessage = `\`${refNode.name}\` should be used as a type. Please see the engine documentation`;
  } else if (!isArrowFunctionExpression(declaration.init)) {
    result.errorMessage = `\`${refNode.name}\` should receive an arrow function expression. Please see the engine documentation`;
  } else if (
    declaration.init.params.length > 0 &&
    !isObjectPattern(declaration.init.params[0])
  ) {
    result.errorMessage = `\`${refNode.name}\` should receive a single argument which needs to be an object`;
  } else {
    result.error = false;
    result.success = true;
  }

  return result;
}
Example #18
Source File: arrayDestructureEvaluator.ts    From react-native-decompiler with GNU Affero General Public License v3.0 6 votes vote down vote up
afterPass(): void {
    if (this.destructureFunctionStart == null) return;

    this.variableDeclarators.forEach((data) => {
      if (!data.couldBeDestructure) return;
      if (data.destructureBindingStart !== this.destructureFunctionStart) return;

      const sourceArray = this.variableDeclarators.find((srcData) => srcData.varStart === data.destructureArrayBindingStart);
      const arrayUsages = this.variableDeclarators.filter((arrData) => arrData.arrayAccessBindingStart === data.varStart);
      if (!sourceArray || !arrayUsages.length) return;

      const arrayPatternElements: (Identifier | null)[] = [];
      arrayUsages.forEach((usage) => {
        if (usage.arrayAccessVal == null) throw new Error();
        arrayPatternElements[usage.arrayAccessVal] = identifier(usage.varName);
      });
      for (let i = 0; i < arrayPatternElements.length; i += 1) {
        if (arrayPatternElements[i] === undefined) {
          arrayPatternElements[i] = null;
        }
      }

      sourceArray.path.node.id = arrayPattern(arrayPatternElements);

      if (!this.destructureFunction?.removed) {
        this.destructureFunction?.remove();
      }
      if (!data.path.removed) {
        data.path.remove();
      }
      arrayUsages.forEach((usageData) => (usageData.path.removed ? null : usageData.path.remove()));
    });
  }
Example #19
Source File: structParser.ts    From engine with MIT License 6 votes vote down vote up
structParser = (obj: ObjectPattern): StructOperation => {
  const result = obj.properties.reduce(
    (acc, x) => {
      if (isObjectProperty(x)) {
        const node = x as ObjectProperty;
        const propName = (node.key as Identifier).name;
        const propValue = processValue(node);
        if (propValue) {
          acc.value[propName] = propValue;
        }
      } else {
        console.log("Not object property", x);
      }
      return acc;
    },
    {
      type: OperationTypes.STRUCT,
      value: {},
    } as StructOperation
  );
  return result;
}
Example #20
Source File: valueOperationCompiler.ts    From engine with MIT License 5 votes vote down vote up
valueOperationCompiler = (
  op: ValueOperation
): ObjectExpression => {
  let value = objectProperty(identifier("path"), stringLiteral("___"));
  const type = objectProperty(identifier("type"), stringLiteral(op.type));
  if (op.value.type === ValueTypes.CONST) {
    const val = op.value.value;

    let valType;
    if (val && val.__node__) {
      valType = val.__node__;
    } else if (typeof val === "string") {
      valType = stringLiteral(val);
    } else if (typeof val === "number") {
      valType = numericLiteral(val);
    } else if (typeof val === "boolean") {
      valType = booleanLiteral(val);
    } else {
      throw new Error("Value type not supported yet: " + typeof val);
    }

    value = objectProperty(
      identifier("value"),
      objectExpression([
        objectProperty(identifier("type"), stringLiteral(ValueTypes.CONST)),
        objectProperty(identifier("value"), valType),
      ])
    );
  } else if (
    op.value.type === ValueTypes.EXTERNAL ||
    op.value.type === ValueTypes.INTERNAL
  ) {
    const path = arrayExpression(op.value.path.map((x) => stringLiteral(x)));
    value = objectProperty(
      identifier("value"),
      objectExpression([
        objectProperty(identifier("type"), stringLiteral(op.value.type)),
        objectProperty(identifier("path"), path),
      ])
    );
  }
  return objectExpression([type, value]);
}
Example #21
Source File: prepareForEngine.ts    From engine with MIT License 5 votes vote down vote up
prepareForEngine: PrepareForEngine = (babel, state, ref, type) => {
  const validation = validateRef(ref);
  if (validation.error) {
    throw new Error(validation.errorMessage);
  }

  const config = getConfig(state);

  const op = parseRef(babel, state, ref);
  const props = structOperationCompiler(op);
  const parent = ref.findParent((p) => p.isVariableDeclarator());
  if (!parent) {
    throw new Error(
      "Misuse of the view/producer keyword. It needs to be a variable declaration e.g. let foo: view = ..."
    );
  }
  const node = parent.node as VariableDeclarator;
  const fn = node.init as ArrowFunctionExpression;

  fn.params = paramsCompiler(op);
  const result = objectExpression([
    objectProperty(identifier("props"), props),
    objectProperty(identifier("fn"), fn),
  ]);

  if (type === TransformType.PRODUCER) {
    node.init = result;
  } else if (type === TransformType.VIEW) {
    const viewCall = callExpression(identifier("view"), [result]);
    node.init = viewCall;
    const viewImport = config.view.importFrom;
    const program = ref.findParent((p) => p.isProgram());
    if (!program) {
      throw new Error("Internal error. Cannot find program node");
    }
    const macroImport = program.get("body").find((p) => {
      const result =
        p.isImportDeclaration() &&
        p.node.source.value.indexOf("@c11/engine.macro") !== -1;
      return result;
    });

    const engineImport = program.get("body").find((p) => {
      const result =
        p.isImportDeclaration() &&
        p.node.source.value.indexOf(viewImport) !== -1;
      return result;
    });

    if (macroImport) {
      if (!engineImport) {
        const importView = importDeclaration(
          [importSpecifier(identifier("view"), identifier("view"))],
          stringLiteral(viewImport)
        );
        // @ts-ignore
        macroImport.insertAfter(importView);
      } else {
        const node = engineImport.node as ImportDeclaration;
        const viewNode = node.specifiers.find((node) => {
          return (
            isImportSpecifier(node) &&
            isIdentifier(node.imported) &&
            node.imported.name === "view"
          );
        });
        if (!viewNode) {
          node.specifiers.push(
            importSpecifier(identifier("view"), identifier("view"))
          );
        }
      }
    } else {
      throw new Error("Could not find macro import");
    }
  }
}
Example #22
Source File: voidZeroToUndefined.ts    From react-native-decompiler with GNU Affero General Public License v3.0 5 votes vote down vote up
getVisitor(): Visitor {
    return {
      UnaryExpression(path) {
        if (path.node.operator !== 'void' || !isNumericLiteral(path.node.argument) || path.node.argument.value !== 0) return;
        path.replaceWith(identifier('undefined'));
      },
    };
  }
Example #23
Source File: pathOperationCompiler.ts    From engine with MIT License 5 votes vote down vote up
pathOperationCompiler = (
  op: GetOperation | UpdateOperation | ObserveOperation
): ObjectExpression => {
  const type = objectProperty(identifier("type"), stringLiteral(op.type));
  let value = objectProperty(identifier("path"), stringLiteral("___"));
  value = objectProperty(identifier("path"), pathCompiler(op.path));
  return objectExpression([type, value]);
}
Example #24
Source File: paramsCompiler.ts    From engine with MIT License 5 votes vote down vote up
paramsCompiler = (struct: StructOperation): ObjectPattern[] => {
  const properties = Object.keys(struct.value).reduce((acc, x) => {
    acc.push(objectProperty(identifier(x), identifier(x)));
    return acc;
  }, [] as ObjectProperty[]);
  const result = [objectPattern(properties)];
  return result;
}
Example #25
Source File: voidZeroToUndefined.ts    From react-native-decompiler with GNU Affero General Public License v3.0 5 votes vote down vote up
getVisitor(): Visitor {
    return {
      UnaryExpression(path) {
        if (path.node.operator !== 'void' || !isNumericLiteral(path.node.argument) || path.node.argument.value !== 0) return;
        path.replaceWith(identifier('undefined'));
      },
    };
  }
Example #26
Source File: module.ts    From react-native-decompiler with GNU Affero General Public License v3.0 5 votes vote down vote up
/** The module's exports variable */
  exportsParam?: Identifier;
Example #27
Source File: module.ts    From react-native-decompiler with GNU Affero General Public License v3.0 5 votes vote down vote up
/** The module's module variable */
  moduleParam?: Identifier;
Example #28
Source File: module.ts    From react-native-decompiler with GNU Affero General Public License v3.0 5 votes vote down vote up
/** The module's exports variable */
  exportsParam?: Identifier;
Example #29
Source File: paramsParser.ts    From engine with MIT License 5 votes vote down vote up
paramsParser = (params: ObjectPattern): StructOperation => {
  if (!params) {
    return {
      type: OperationTypes.STRUCT,
      value: {},
    };
  }
  const result = params.properties.reduce(
    (acc, x, idx) => {
      if (isObjectProperty(x)) {
        if (isIdentifier(x.value)) {
          const node = x.value as Identifier;
          const propName = node.name;
          const propValue = {
            type: OperationTypes.VALUE,
            value: {
              type: ValueTypes.EXTERNAL,
              path: [propName],
            },
          } as ValueOperation;
          acc.value[propName] = propValue;
        } else if (isAssignmentPattern(x.value)) {
          const node = x.value as AssignmentPattern;
          const left = node.left as Identifier;
          const propName = left.name;
          const propValue = processParamValue(node);
          if (propValue) {
            acc.value[propName] = propValue;
          } else {
            throw new Error(
              "Property " + propName + " could not be processed."
            );
          }
        } else {
          console.log("Not object property", x);
        }
      } else if (isRestElement(x)) {
        throw new Error("Rest operator is not supported.");
      }
      return acc;
    },
    {
      type: OperationTypes.STRUCT,
      value: {},
    } as StructOperation
  );

  result.meta = {};

  return result;
}