How to use estree-walker - 10 common examples

To help you get started, we’ve selected a few estree-walker 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 sx1989827 / DOClever / Client / node_modules / rollup-pluginutils / dist / pluginutils.es6.js View on Github external
function attachScopes ( ast, propertyName ) {
	if ( propertyName === void 0 ) propertyName = 'scope';

	var scope = new Scope();

	walk( ast, {
		enter: function enter ( node, parent ) {
			// function foo () {...}
			// class Foo {...}
			if ( /(Function|Class)Declaration/.test( node.type ) ) {
				scope.addDeclaration( node, false, false );
			}

			// var foo = 1
			if ( node.type === 'VariableDeclaration' ) {
				var isBlockDeclaration = blockDeclarations[ node.kind ];

				node.declarations.forEach( function (declaration) {
					scope.addDeclaration( declaration, isBlockDeclaration, true );
				});
			}
github VadimDez / ngx-img-fallback / node_modules / angular-cli / node_modules / rollup / src / Module.js View on Github external
try {
				ast = parse( this.code, {
					ecmaVersion: 6,
					sourceType: 'module',
					onComment: ( block, text, start, end ) => this.comments.push({ block, text, start, end }),
					preserveParens: true
				});
			} catch ( err ) {
				err.code = 'PARSE_ERROR';
				err.file = this.id; // see above - not necessarily true, but true enough
				err.message += ` in ${this.id}`;
				throw err;
			}
		}

		walk( ast, {
			enter: node => {
				// eliminate dead branches early
				if ( node.type === 'IfStatement' ) {
					if ( isFalsy( node.test ) ) {
						this.magicString.overwrite( node.consequent.start, node.consequent.end, '{}' );
						node.consequent = emptyBlockStatement( node.consequent.start, node.consequent.end );
					} else if ( node.alternate && isTruthy( node.test ) ) {
						this.magicString.overwrite( node.alternate.start, node.alternate.end, '{}' );
						node.alternate = emptyBlockStatement( node.alternate.start, node.alternate.end );
					}
				}

				this.magicString.addSourcemapLocation( node.start );
				this.magicString.addSourcemapLocation( node.end );
			},
github FabricLabs / fabric / scripts / gen-i18n.js View on Github external
function getTranslationsJs(file) {
    const tree = flowParser.parse(fs.readFileSync(file, { encoding: 'utf8' }), FLOW_PARSER_OPTS);

    const trs = new Set();

    estreeWalker.walk(tree, {
        enter: function(node, parent) {
            if (
                node.type == 'CallExpression' &&
                TRANSLATIONS_FUNCS.includes(node.callee.name)
            ) {
                const tKey = getTKey(node.arguments[0]);
                // This happens whenever we call _t with non-literals (ie. whenever we've
                // had to use a _td to compensate) so is expected.
                if (tKey === null) return;

                // check the format string against the args
                // We only check _t: _td has no args
                if (node.callee.name === '_t') {
                    try {
                        const placeholders = getFormatStrings(tKey);
                        for (const placeholder of placeholders) {
github styleguidist / react-styleguidist / src / loaders / utils / getImports.js View on Github external
export default function getImports(code: string): string[] {
	// Parse example source code, but ignore errors:
	// 1. Adjacent JSX elements must be wrapped in an enclosing tag () -
	//    imports/requires are not allowed in this case, and we'll wrap the code
	//    in React.Fragment on the frontend
	// 2. All other errors - we'll deal with them on the frontend
	const ast = getAst(code, [acornJsx()]);
	if (!ast) {
		return [];
	}

	const imports = [];
	walk(ast, {
		enter: node => {
			// import foo from 'foo'
			// import 'foo'
			if (node.type === 'ImportDeclaration') {
				if (node.source) {
					imports.push(node.source.value);
				}
			}

			// require('foo')
			else if (node.type === 'CallExpression') {
				if (
					node.callee &&
					node.callee.name === 'require' &&
					node.arguments &&
					node.arguments[0].value
github rollup / rollup / src / Module.js View on Github external
try {
				ast = parse( this.code, {
					ecmaVersion: 6,
					sourceType: 'module',
					onComment: ( block, text, start, end ) => this.comments.push({ block, text, start, end }),
					preserveParens: true
				});
			} catch ( err ) {
				err.code = 'PARSE_ERROR';
				err.file = this.id; // see above - not necessarily true, but true enough
				err.message += ` in ${this.id}`;
				throw err;
			}
		}

		walk( ast, {
			enter: node => {
				this.magicString.addSourcemapLocation( node.start );
				this.magicString.addSourcemapLocation( node.end );
			}
		});

		let statements = [];
		let lastChar = 0;
		let commentIndex = 0;

		ast.body.forEach( node => {
			if ( node.type === 'EmptyStatement' ) return;

			if (
				node.type === 'ExportNamedDeclaration' &&
				node.declaration &&
github eight04 / rollup-plugin-external-globals / lib / import-to-globals.js View on Github external
function importToGlobals({ast, code, getName, getDynamicWrapper}) {
  let scope = attachScopes(ast, "scope");
  const bindings = new Map;
  const globals = new Set;
  let isTouched = false;
  const tempNames = new Set;

  for (const node of ast.body) {
    if (node.type === "ImportDeclaration") {
      isTouched = analyzeImport(node, bindings, code, getName, globals) || isTouched;
    } else if (node.type === "ExportNamedDeclaration") {
      isTouched = analyzeExportNamed(node, code, getName, tempNames) || isTouched;
    }
  }

  walk(ast, {
    enter(node, parent) {
      if (/^importdec/i.test(node.type)) {
        this.skip();
        return;
      }
      if (node.scope) {
        scope = node.scope;
      }
      if (isReference(node, parent)) {
        if (bindings.has(node.name) && !scope.contains(node.name)) {
          writeIdentifier(code, node, parent, bindings.get(node.name));
        } else if (globals.has(node.name) && scope.contains(node.name)) {
          writeIdentifier(code, node, parent, `_local_${node.name}`);
        }
      }
      const source = getDynamicImportSource(node);
github sveltejs / svelte / src / utils / annotateWithScopes.ts View on Github external
export function createScopes(expression: Node) {
	const map = new WeakMap();

	const globals = new Set();
	let scope = new Scope(null, false);

	walk(expression, {
		enter(node: Node, parent: Node) {
			if (/Function/.test(node.type)) {
				if (node.type === 'FunctionDeclaration') {
					scope.declarations.add(node.id.name);
				} else {
					scope = new Scope(scope, false);
					map.set(node, scope);
					if (node.id) scope.declarations.add(node.id.name);
				}

				node.params.forEach((param: Node) => {
					extractNames(param).forEach(name => {
						scope.declarations.add(name);
					});
				});
			} else if (/For(?:In|Of)Statement/.test(node.type)) {
github eight04 / cjs-es / lib / analyzer.js View on Github external
function analyze() {
    walk(context.ast, {
      enter(node, parent) {
        if (node.shouldSkip) {
          this.skip();
          return;
        }
        context.node = node;
        context.parent = parent;
        context.topLevel.enter(node, parent);
        context.assignment.enter(node);
        context.scope.enter(node);
        context.walkContext = this;
        analyzeNode(node, parent);
      },
      leave(node) {
        context.scope.leave(node);
      }
github sveltejs / svelte / src / compiler / compile / css / Stylesheet.ts View on Github external
render(file: string, should_transform_selectors: boolean) {
		if (!this.has_styles) {
			return { code: null, map: null };
		}

		const code = new MagicString(this.source);

		walk(this.ast.css as any, {
			enter: (node: any) => {
				code.addSourcemapLocation(node.start);
				code.addSourcemapLocation(node.end);
			}
		});

		if (should_transform_selectors) {
			const max = Math.max(...this.children.map(rule => rule.get_max_amount_class_specificity_increased()));
			this.children.forEach((child: (Atrule|Rule)) => {
				child.transform(code, this.id, this.keyframes, max);
			});
		}

		let c = 0;
		this.children.forEach(child => {
			if (child.is_used(this.dev)) {
github sveltejs / svelte / compiler / generate / index.js View on Github external
addSourcemapLocations ( node ) {
			walk( node, {
				enter ( node ) {
					generator.code.addSourcemapLocation( node.start );
					generator.code.addSourcemapLocation( node.end );
				}
			});
		},

estree-walker

Traverse an ESTree-compliant AST

MIT
Latest version published 2 years ago

Package Health Score

73 / 100
Full package analysis

Popular estree-walker functions

Similar packages