How to use acorn-walk - 10 common examples

To help you get started, we’ve selected a few acorn-walk 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 stdlib-js / stdlib / lib / node_modules / @stdlib / _tools / eslint / rules / doctest-marker / lib / main.js View on Github external
function checkComment( comment, ast, offset ) {
		var matches;
		var node;
		var prev;
		var type;

		matches = comment.value.match( RE_ANNOTATION );
		if ( matches ) {
			offset += 1 + comment.loc.start.column;
			prev = walk.findNodeAt( ast, null, comment.start-offset );
			type = matches[ 1 ];
			if ( !prev ) {
				// Handle case when comment refers to node on the same line:
				if ( walk.findNodeAt( ast, null, comment.start-1 ) ) {
					return null;
				}
				return 'Encountered an orphaned return annotation without a preceding node';
			}
			node = prev.node;
			switch ( type ) {
			case 'returns':
				if (
					node.type !== 'VariableDeclaration' &&
					( node.type !== 'ExpressionStatement' || node.expression.type !== 'AssignmentExpression' )
				) {
					return 'Only include `// returns` after variable declarations or assignment expressions (use `=>` after `console.log`)';
github ternjs / tern / test / runcases.js View on Github external
if (!match)
            fail(m, "Completion set failed at hint: " + parts[i - 1] +
                 "\n     got: " + resp.completions.join(", ") + "\n  wanted: " + args);
        });
      } else if (kind == "exports:") {
        server.request({query: {type: "exports", file: fname}}, function(err, resp) {
          if (err) throw err;
          if (resp.type != args) fail(m, "Export type failed. Got:\n    " + resp.type + "\nwanted:\n    " + args);
        });
      } else {
        var start, end;
        if (directlyHere) {
          for (end = m.index; end && /[\s:,;]/.test(text.charAt(end - 1)); --end) {}
          start = null;
        } else {
          var expr = walk.findNodeBefore(ast, m.index, "Expression");
          if (!expr) {
            fail(m, "No expresion found");
            return;
          }
          start = expr.node.start; end = expr.node.end;
        }
        var query = {type: /doc/.test(kind) ? "documentation" : kind == "loc:" ? "definition" : kind == "refs:" ? "refs" : "type",
                     start: start, end: end,
                     docFormat: kind == "doc+:" ? "full" : null,
                     file: fname,
                     depth: kind == "::" ? 5 : null,
                     lineCharPositions: true};
        server.request({query: query}, function(err, resp) {
          if (err) throw err;

          if (/doc/.test(kind)) { // Docstring test
github stdlib-js / stdlib / lib / node_modules / @stdlib / repl / lib / resolve_local_scope.js View on Github external
function resolveScope( ast, node ) {
	var visitors;
	var scope;

	visitors = {};
	visitors[ node.type ] = onVisit;

	scope = [];
	walk( ast, visitors );

	return scope;

	/**
	* Callback invoked upon encountering an AST node.
	*
	* @private
	* @param {Node} n - AST node
	* @param {Array} parents - array of parent AST nodes
	*/
	function onVisit( n, parents ) {
		var locals;
		var i;
		var j;
		if ( n === node ) {
			// Note: the direction in which we traverse the list of parents does not matter, as we only care about identifier names, not where they were declared and to what value they are assigned. Meaning, we don't need to concern ourselves with whether a local scope redeclares a variable in a higher scope, as we are only concerned with a general list of identifier names available at the location of the provided AST node.
github surma / rollup-plugin-workz0r / index.js View on Github external
transform(code, id) {
      if (!/new\s+Worker/.test(code)) return;

      const ast = this.parse(code);

      // The walker calls a method for each node type on a “base” before calling
      // the method on our visitor object. The default base doesn’t handle
      // dynamic import. Here we create a copy of the original base
      // using `make()` and put add an empty handler for dynamic imports
      // ourselves. Seems to work :shrug:
      const newBase = walker.make({
        Import(node) {}
      });

      const warn = this.warn.bind(this);
      // Collect all the worker calls in this array.
      const newWorkerCalls = [];
      walker.simple(
        ast,
        {
          NewExpression(node) {
            if (node.callee.name !== "Worker") {
              return;
            }
            const workerFile = node.arguments[0].value;
            if (!/^\.*\//.test(workerFile)) {
              warn(
github storybookjs / storybook / addons / docs / src / frameworks / react / inspection / acornParser.ts View on Github external
function parseClass(
  classNode: estree.ClassExpression
): ParsingResult {
  let innerJsxElementNode;

  // If there is at least a JSXElement in the body of the class, then it's a React component.
  acornWalk.simple(
    classNode.body,
    {
      JSXElement(node: any) {
        innerJsxElementNode = node;
      },
    },
    ACORN_WALK_VISITORS
  );

  const inferedType: any = {
    type: !isNil(innerJsxElementNode) ? InspectionType.ELEMENT : InspectionType.CLASS,
    identifier: extractIdentifierName(classNode.id),
  };

  return {
    inferedType,
github sverweij / dependency-cruiser / src / extract / ast-extractors / extract-commonJS-deps.js View on Github external
module.exports = (
  pAST,
  pDependencies,
  pModuleSystem,
  pExoticRequireStrings
) => {
  // var/const lalala = require('./lalala');
  // require('./lalala');
  // require('./lalala').doFunkyStuff();
  // require('zoinks!./wappie')
  // require(`./withatemplateliteral`)
  // as well as renamed requires/ require wrappers
  // as passed in pExoticRequireStrings ("need", "window.require")
  walk.simple(
    pAST,
    {
      CallExpression: pushRequireCallsToDependencies(
        pDependencies,
        pModuleSystem,
        pExoticRequireStrings
      )
    },
    // see https://github.com/acornjs/acorn/issues/746
    walk.base
  );
};
github LavaMoat / lavamoat-browserify / src / inspectEnvironment.js View on Github external
function walkForProtectedAssignment (ast, results) {
  walk.ancestor(ast, {
    'AssignmentExpression': function (node, parents) {
      const { left } = node
      // select for assignment to a property
      if (left.type !== 'MemberExpression') return
      const { property, computed } = left
      // skip if property name is a variable
      if (computed) return
      if (property.type !== 'Identifier') return
      // check for assignment to primordial
      const memberPath = memberExpressionChainToPath(left)
      const match = primordialPaths.some(
        primordial => partialArrayMatch(primordial, memberPath)
      )
      if (match) {
        results.push(node)
      }
github stdlib-js / stdlib / lib / node_modules / @stdlib / repl / lib / resolve_globals.js View on Github external
throw new TypeError( 'invalid argument. Must provide a program AST node.' );
	}
	globals = [];

	// Resolve local scopes:
	ast = resolveLocalScopes( ast );

	// Define callbacks for relevant AST nodes:
	visitors = {
		'VariablePattern': Identifier,
		'Identifier': Identifier,
		'ThisExpression': ThisExpression
	};

	// Walk the AST to resolve globals:
	walk( ast, visitors );

	return globals;

	/**
	* Callback invoked upon encountering an identifier AST node.
	*
	* @private
	* @param {Node} node - AST node
	* @param {Array} parents - array of parent AST nodes
	*/
	function Identifier( node, parents ) {
		var locals;
		var name;
		var i;

		name = node.name;
github neftjs / neft / packages / compiler / neft-compiler-binding / src / index.js View on Github external
if (parent.argument === leaf) {
          parent.argument = getNewNode(leaf)
        }
        break
      case 'Property':
        if (parent.value === leaf) {
          parent.shorthand = false
          parent.value = getNewNode(leaf)
        }
        break
      default:
        // NOP
    }
  }

  walk.ancestor(ast, types.reduce((target, type) => ({
    ...target,
    [type]: typeCallback,
  }), {}))
}
github sverweij / dependency-cruiser / src / extract / ast-extractors / extract-ES6-deps.js View on Github external
dynamic: false,
        exoticallyRequired: false
      });
    }
  }

  walk.simple(
    pAST,
    {
      ImportDeclaration: pushSourceValue,
      ImportExpression: pushImportNodeValue(pDependencies),
      ExportAllDeclaration: pushSourceValue,
      ExportNamedDeclaration: pushSourceValue
    },
    // see https://github.com/acornjs/acorn/issues/746
    walk.base
  );
};