How to use the escope.analyze function in escope

To help you get started, we’ve selected a few escope 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 dumberjs / dumber / lib / parser.js View on Github external
function globalIndentifiers (code) {
  let ast = ensureParsed(code);
  let scopeManager = analyze(ast, {ecmaVersion: 6});
  let globalScope = scopeManager.acquire(ast);

  // This is very interesting.
  // If you do `let globals = {};`, globals actually has some properties inherited
  // like __defineSetter__, which makes globals['__defineSetter__'] not empty!
  // Check last test in spec/parser.uses-common-js.spec.js
  let globals = Object.create(null);

  globalScope.through.forEach(function (ref) {
    let name = ref.identifier.name;
    // user defined the variable in global scope
    let variable = globalScope.set.get(name);
    // amdefine will be ignored in browser,
    // don't remove 'define' from the list.
    if (variable && !(name === 'define' && extract(amdefinePattern, variable.defs[0].node))) {
      return;
github elastic / timelion / node_modules / gulp-eslint / node_modules / eslint / lib / eslint.js View on Github external
throw ex;
                }
            });

            // save config so rules can access as necessary
            currentConfig = config;
            controller = new estraverse.Controller();

            ecmaFeatures = currentConfig.ecmaFeatures;
            ecmaVersion = (ecmaFeatures.blockBindings || ecmaFeatures.classes ||
                    ecmaFeatures.modules || ecmaFeatures.defaultParams ||
                    ecmaFeatures.destructuring) ? 6 : 5;


            // gather data that may be needed by the rules
            scopeManager = escope.analyze(ast, {
                ignoreEval: true,
                nodejsScope: ecmaFeatures.globalReturn,
                ecmaVersion: ecmaVersion,
                sourceType: ecmaFeatures.modules ? "module" : "script"
            });
            currentScopes = scopeManager.scopes;

            /*
             * Index the scopes by the start range of their block for efficient
             * lookup in getScope.
             */
            scopeMap = [];
            currentScopes.forEach(function(scope, index) {
                var range = scope.block.range[0];

                // Sometimes two scopes are returned for a given node. This is
github mradionov / tleaf / src / parse.js View on Github external
function parse(source) {
  var ast;
  try {
    ast = esprima.parse(source);
  } catch (err) {
    throw new UserError('Source file is not valid.', err);
  }

  var scopeManager = escope.analyze(ast);

  // global scope
  var currentScope = scopeManager.acquire(ast);

  var calls = [];

  estraverse.traverse(ast, {
    enter: function (node) {
      // find all call expressions, because all angular unit types are
      // defined as function calls: .controller(), .service(), etc
      if (node.type === 'CallExpression') {

        var calleeProp = _.get(node, 'callee.property', {});

        if (_.contains(config.units.process, calleeProp.name)) {
          // save matching node with an appropriate scope
github ThomasR / minislides / build / varNameReplacer.js View on Github external
module.exports = input => {
    // create syntax tree and scope analysis
    let ast = esprima.parse(input);
    var scopes = escope.analyze(ast).scopes;

    // Determine global identifiers.
    let globalNames = scopes.filter(scope => scope.implicit && scope.implicit.left).reduce((result, scope) => {
        let found = scope.implicit.left.map(global => global.identifier.name);
        return result.concat(found);
    }, []);
    globalNames.forEach(global => {
        if (global.length === 1 && target.indexOf(global) > -1) {
            // This is too dangerous
            throw new Error(`Cannot replace global variable "${global}"`);
        }
    });

    // get local variables (AST nodes)
    let locals = scopes.reduce((result, scope) => {
        scope.variables.filter(v => v.name !== 'arguments').forEach(variable => {
github BladeRunnerJS / brjs / brjs-sdk / build-resources / includes / sdk / jsdoc-toolkit-resources / jsdoc-toolkit / node_modules / gulp-eslint / node_modules / eslint / lib / eslint.js View on Github external
ex.message = "Error while loading rule '" + key + "': " + ex.message;
                        throw ex;
                    }

                } else {
                    throw new Error("Definition for rule '" + key + "' was not found.");
                }
            });

            // save config so rules can access as necessary
            currentConfig = config;
            currentText = text;
            controller = new estraverse.Controller();

            // gather data that may be needed by the rules
            currentScopes = escope.analyze(ast, { ignoreEval: true }).scopes;

            /*
             * Index the scopes by the start range of their block for efficient
             * lookup in getScope.
             */
            scopeMap = [];
            currentScopes.forEach(function (scope, index) {
                var range = scope.block.range[0];

                // Sometimes two scopes are returned for a given node. This is
                // handled later in a known way, so just don't overwrite here.
                if (!scopeMap[range]) {
                    scopeMap[range] = index;
                }
            });
github SnakeskinTpl / Snakeskin / gulp / replacers.js View on Github external
}

			return sstr;
		});

		let ast = esprima.parse(text, {
			comment: true,
			range: true,
			loc: false,
			tokens: true,
			raw: false
		});

		ast = escodegen.attachComments(ast, ast.comments, ast.tokens);
		const
			vars = escope.analyze(ast, {optimistic: true}).scopes[0].variables;

		$C(vars).forEach((el) => {
			if (!/module_/.test(el.name)) {
				const
					newName = `${moduleId}_${el.name}`;

				el.references.forEach((ref) => {
					ref.identifier.name = newName;
				});

				el.identifiers.forEach((ident) => {
					ident.name = newName;
				});
			}
		});
github deranjer / goTorrent / goTorrentWebUI / node_modules / webpack / lib / optimize / ConcatenatedModule.js View on Github external
try {
					ast = acorn.parse(code, {
						ranges: true,
						locations: true,
						ecmaVersion: Parser.ECMA_VERSION,
						sourceType: "module"
					});
				} catch(err) {
					if(err.loc && typeof err.loc === "object" && typeof err.loc.line === "number") {
						const lineNumber = err.loc.line;
						const lines = code.split("\n");
						err.message += "\n| " + lines.slice(Math.max(0, lineNumber - 3), lineNumber + 2).join("\n| ");
					}
					throw err;
				}
				const scopeManager = escope.analyze(ast, {
					ecmaVersion: 6,
					sourceType: "module",
					optimistic: true,
					ignoreEval: true,
					impliedStrict: true
				});
				const globalScope = scopeManager.acquire(ast);
				const moduleScope = globalScope.childScopes[0];
				const resultSource = new ReplaceSource(source);
				info.ast = ast;
				info.source = resultSource;
				info.globalScope = globalScope;
				info.moduleScope = moduleScope;
			}
		});
github bakunin95 / wavi / src / parsers / javascript.js View on Github external
function (resolve, reject) {
                                let ast = result[1];
                                try {
                                        let scopeManager = escope.analyze(ast, { sourceType: "module", ecmaVersion: 6 });

                                        result[1] = scopeManager.acquire(ast);
                                        resolve(result);
                                } catch (e) {
                                        reject("Bad Scope");
                                }
                        }
                );
github buildize / locus / src / variables.js View on Github external
exports.get = function(filepath) {
  var variables = [];

  try {
    var ast = esprima.parse(fs.readFileSync(filepath, 'utf-8'));
  } catch(e) {
    return [];
  }

  var scopeManager = escope.analyze(ast);
  var currentScope = scopeManager.acquire(ast);

  estraverse.traverse(ast, {
    leave: function(node, parent) {
      var scope = scopeManager.acquire(node);

      if (scope) {
        var nodeVariables = _.values(scope.variables).map(function(item) {
          return item.name;
        });

        variables = variables.concat(nodeVariables)
      }
    }
  });

escope

ECMAScript scope analyzer

BSD-2-Clause
Latest version published 2 years ago

Package Health Score

77 / 100
Full package analysis