How to use recast - 10 common examples

To help you get started, we’ve selected a few recast 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 abuiles / ember-watson / lib / formulas / convert-tests-to-async-await.js View on Github external
module.exports = function transform(source) {
  const ast = parseAst(source);

  const tests = [];
  let currentTest;

  recast.visit(ast, {
    visitExpressionStatement(path) {
      let node = path.node;

      if (isTest(node)) {
        if (!testUsesAndThen(node)) {
          // don't transform this test
          return false;
        }

        currentTest = {
          test: path,
          asyncHelpers: [],
          andThens: [],
          dones: [],
          removeDone: testUsesDone(path.node)
        };
github empress / empress-blog / blueprints / empress-blog / index.js View on Github external
}).then(() => {
      const builders = recast.types.builders;

      const code = readFileSync('./ember-cli-build.js');
      const ast = recast.parse(code);

      recast.visit(ast, {
        visitNewExpression: function (path) {
          var node = path.node;

          if (node.callee.name === 'EmberApp'
              || node.callee.name === 'EmberAddon') {
            // console.log(node, node.arguments)
            const configNode = node.arguments.find(element => element.type === 'ObjectExpression');

            let fingerprint = configNode.properties.find(property => property.key.value === 'fingerprint');

            if(!fingerprint) {
              fingerprint = builders.property(
                'init',
                builders.identifier('fingerprint'),
github doczjs / docz / core / docz-core / src / utils / docgen / externalProptypesHandler.ts View on Github external
function getExports(ast: any) {
  const exports: any = []

  recast.visit(ast, {
    visitExportNamedDeclaration(path: any) {
      const node = path.node
      const specifiers = getSpecifiersOfNode(node.specifiers)
      const declarations = Object.keys(getIdentifiers(ast))

      exports.push(...new Set(specifiers.concat(declarations)))
      this.traverse(path)
    },
    visitExportDefaultDeclaration(path: any) {
      const node = path.node

      if (node.declaration.type === types.Identifier.name) {
        exports.push(node.declaration.name)
      }
      /* Commenting it for now, this might needed for further enhancements.
      else if (nodeType === types.Literal.name) {
github vuejs / function-api-converter / src / converter / groups.js View on Github external
function getStatementWords (node, setupVariables) {
  if (!wordNodeCache.has(node)) {
    /** @type {Word[]} */
    let words = []
    // Variable
    let varName = mayGetVariableDeclarationName(node)
    if (varName) {
      words.push({ value: varName, score: 1 })
    } else {
      // Contained identifiers
      visit(node, {
        visitIdentifier (path) {
          let identifier = path.value.name
          if (setupVariables.includes(identifier) && !words.includes(identifier)) {
            words.push({ value: identifier, score: 1 })
          }
          this.traverse(path)
        },
      })
    }

    // Processing
    const allWords = words.map(n => n.value).join('|')
    if (wordCache.has(allWords)) {
      words = wordCache.get(allWords)
    } else {
      words = processWords(words, true)
github vuejs / function-api-converter / src / converter / groups.js View on Github external
function generateGroupName (group, index) {
  if (group.declarations) {
    const vars = {}
    // Count variable identifiers
    visit(Array.from(group.nodes), {
      visitIdentifier (path) {
        let identifier = path.value.name
        if (group.declarations.includes(identifier)) {
          const words = processWords([{ value: identifier, score: 1 }])
          for (const word of words) {
            if (!vars[word.value]) {
              vars[word.value] = 1
            } else {
              vars[word.value]++
            }
          }
        }
        this.traverse(path)
      },
    })
    // Sort by count
github vue-styleguidist / vue-styleguidist / packages / vue-docgen-api / src / template-handlers / propHandler.ts View on Github external
function getPropsFromExpression(
	parentAst: ASTElement | undefined,
	item: ASTNode,
	expression: string,
	documentation: Documentation,
	options: TemplateParserOptions
) {
	// this allows for weird expressions like {[t]:val} to be parsed properly
	const ast = parser.parse(`(() => (${expression}))()`)
	const propsFound: string[] = []
	recast.visit(ast.program, {
		visitMemberExpression(path) {
			const obj = path.node ? path.node.object : undefined
			const propName = path.node ? path.node.property : undefined
			if (
				obj &&
				propName &&
				bt.isIdentifier(obj) &&
				obj.name === 'props' &&
				bt.isIdentifier(propName)
			) {
				const pName = propName.name
				const p = documentation.getPropDescriptor(pName)
				propsFound.push(pName)
				p.type = { name: 'undefined' }
			}
			return false
github binaryage / dirac / scripts / migration / refactor-to-es-module.ts View on Github external
import { parse, print, types } from 'recast';
import fs from 'fs';
import path from 'path';
import { promisify } from 'util';
import { IdentifierKind, MemberExpressionKind, ExpressionKind, CommentKind } from 'ast-types/gen/kinds';

const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);

const FRONT_END_FOLDER = path.join(__dirname, '..', '..', 'front_end')

function capitalizeFirstLetter(string: string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

const b = types.builders;

function createReplacementDeclaration(propertyName: IdentifierKind, declaration: any): any {
  // UI.ARIAUtils.Foo = class {} -> export class Foo {}
  if (declaration.type === 'ClassExpression') {
    return b.exportDeclaration(false, b.classDeclaration(propertyName, declaration.body));
  }
  // UI.ARIAUtils.Foo = expression; -> export const Foo = expression;
  if (declaration.type === 'Literal' || declaration.type.endsWith('Expression')) {
    return b.exportNamedDeclaration(b.variableDeclaration("const", [b.variableDeclarator(propertyName, declaration)]));
  }
  console.error(`Unable to refactor declaration of type "${declaration.type}" named "${propertyName.name}"`);
}

function getTopLevelMemberExpression(expression: MemberExpressionKind): any {
  while (expression.object.type === 'MemberExpression') {
    expression = expression.object;
github Caltech-IPAC / firefly / node_modules / babel-core / node_modules / regenerator / lib / emit.js View on Github external
// catch block to the fall-through location.
          self.jump(after);
        }

        self.updateContextPrevLoc(self.mark(catchLoc));

        var bodyPath = path.get("handler", "body");
        var safeParam = self.makeTempVar();
        self.clearPendingException(tryEntry.firstLoc, safeParam);

        var catchScope = bodyPath.scope;
        var catchParamName = handler.param.name;
        n.CatchClause.assert(catchScope.node);
        assert.strictEqual(catchScope.lookup(catchParamName), catchScope);

        types.visit(bodyPath, {
          visitIdentifier: function(path) {
            if (util.isReference(path, catchParamName) &&
                path.scope.lookup(catchParamName) === catchScope) {
              return safeParam;
            }

            this.traverse(path);
          },

          visitFunction: function(path) {
            if (path.scope.declares(catchParamName)) {
              // Don't descend into nested scopes that shadow the catch
              // parameter with their own declarations. This isn't
              // logically necessary because of the path.scope.lookup we
              // do in visitIdentifier, but it saves time.
              return false;
github facebook / regenerator / lib / emit.js View on Github external
// catch block to the fall-through location.
          self.jump(after);
        }

        self.updateContextPrevLoc(self.mark(catchLoc));

        var bodyPath = path.get("handler", "body");
        var safeParam = self.makeTempVar();
        self.clearPendingException(tryEntry.firstLoc, safeParam);

        var catchScope = bodyPath.scope;
        var catchParamName = handler.param.name;
        n.CatchClause.assert(catchScope.node);
        assert.strictEqual(catchScope.lookup(catchParamName), catchScope);

        types.visit(bodyPath, {
          visitIdentifier: function(path) {
            if (util.isReference(path, catchParamName) &&
                path.scope.lookup(catchParamName) === catchScope) {
              return safeParam;
            }

            this.traverse(path);
          },

          visitFunction: function(path) {
            if (path.scope.declares(catchParamName)) {
              // Don't descend into nested scopes that shadow the catch
              // parameter with their own declarations. This isn't
              // logically necessary because of the path.scope.lookup we
              // do in visitIdentifier, but it saves time.
              return false;
github facebook / regenerator / lib / hoist.js View on Github external
));
      } else if (includeIdentifiers) {
        exprs.push(dec.id);
      }
    });

    if (exprs.length === 0)
      return null;

    if (exprs.length === 1)
      return exprs[0];

    return b.sequenceExpression(exprs);
  }

  types.visit(funPath.get("body"), {
    visitVariableDeclaration: function(path) {
      var expr = varDeclToExpr(path.value, false);
      if (expr === null) {
        path.replace();
      } else {
        // We don't need to traverse this expression any further because
        // there can't be any new declarations inside an expression.
        return b.expressionStatement(expr);
      }

      // Since the original node has been either removed or replaced,
      // avoid traversing it any further.
      return false;
    },

    visitForStatement: function(path) {