How to use espree - 10 common examples

To help you get started, we’ve selected a few espree 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 learningequality / kolibri / packages / kolibri-tools / lib / extract$trs.js View on Github external
// these messages have been put in too!
                    } else if (property.key.name === 'name') {
                      messageNameSpace = property.value.value;
                    }
                  });
                }
                registerFoundMessages(messageNameSpace, messages, module);
              }
            });
          } else if (
            module.resource &&
            module.resource.indexOf('.js') === module.resource.length - 3 &&
            !module.resource.includes('node_modules')
          ) {
            // Inspect each source file in the chunk if it is a js file too.
            ast = espree.parse(module._source.source(), {
              sourceType: 'module',
            });
            var createTranslateFn;
            // First find the reference being used for the create translator function
            ast.body.forEach(node => {
              // Check if an import
              if (
                node.type === espree.Syntax.ImportDeclaration &&
                // Check if importing from the i18n alias
                node.source.value === i18nAlias
              ) {
                node.specifiers.forEach(spec => {
                  // Check if this import spec is for the createTranslator function
                  if (spec.imported.name === 'createTranslator') {
                    // If so store the locally imported variable name it was assigned to
                    createTranslateFn = spec.local.name;
github angelozerr / tern.java / core / ternjs / node_modules / tern-eslint / node_modules / eslint / lib / eslint.js View on Github external
eventGenerator = new CommentEventGenerator(eventGenerator, sourceCode);

            /*
             * Each node has a type property. Whenever a particular type of node is found,
             * an event is fired. This allows any listeners to automatically be informed
             * that this type of node has been found and react accordingly.
             */
            controller.traverse(ast, {
                enter: function(node, parent) {
                    node.parent = parent;
                    eventGenerator.enterNode(node);
                },
                leave: function(node) {
                    eventGenerator.leaveNode(node);
                },
                keys: espree.VisitorKeys
            });
        }

        // sort by line and column
        messages.sort(function(a, b) {
            var lineDiff = a.line - b.line;

            if (lineDiff === 0) {
                return a.column - b.column;
            } else {
                return lineDiff;
            }
        });

        return messages;
    };
github angelozerr / tern.java / core / ternjs / node_modules / tern-eslint / node_modules / eslint / lib / eslint.js View on Github external
// save config so rules can access as necessary
            currentConfig = config;
            controller = new estraverse.Controller();

            ecmaFeatures = currentConfig.parserOptions.ecmaFeatures || {};
            ecmaVersion = currentConfig.parserOptions.ecmaVersion || 5;

            // gather data that may be needed by the rules
            scopeManager = escope.analyze(ast, {
                ignoreEval: true,
                nodejsScope: ecmaFeatures.globalReturn,
                impliedStrict: ecmaFeatures.impliedStrict,
                ecmaVersion: ecmaVersion,
                sourceType: currentConfig.parserOptions.sourceType || "script",
                childVisitorKeys: espree.VisitorKeys,
                fallback: "none"
            });
            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
                // handled later in a known way, so just don't overwrite here.
                if (!scopeMap[range]) {
                    scopeMap[range] = index;
github eslint / eslint / tests / lib / rules / utils / ast-utils.js View on Github external
it("should return empty array if there are no directives in FunctionDeclaration body", () => {
            const ast = espree.parse("function foo() { return bar; }");
            const node = ast.body[0];

            assert.deepStrictEqual(astUtils.getDirectivePrologue(node), []);
        });
github babel / babel-eslint / test / z_parser-for-eslint-after-patched.js View on Github external
it("does not visit type annotations multiple times after monkeypatching and calling parseForESLint()", () => {
    assertImplementsAST(
      espree.parse("foo", { sourceType: "module" }),
      babelEslint.parse("foo", {})
    );
    const parseResult = babelEslint.parseForESLint(
      "type Foo = {}; function x(): Foo {}",
      {
        eslintVisitorKeys: true,
        eslintScopeManager: true,
      }
    );
    assert(parseResult.visitorKeys);
    assert(parseResult.scopeManager);

    const fooVariable = parseResult.scopeManager.getDeclaredVariables(
      parseResult.ast.body[0]
    )[0];
github benjamn / ast-types / test / ecmascript.ts View on Github external
("should work for ES6 syntax (espree)", function() {
    var names;

    var ast = espree.parse([
      "var zap;",
      "export default function(zom) {",
      "    var innerFn = function(zip) {};",
      "    return innerFn(zom);",
      "};"
    ].join("\n"), {
      sourceType: "module",
      ecmaVersion: 6
    });

    visit(ast, {
      visitFunctionDeclaration: function(path) {
        names = Object.keys(path.scope.lookup("zap").getBindings()).sort();
        assert.deepEqual(names, ["zap"]);
        this.traverse(path);
      }
github eslint / eslint / tests / lib / source-code / source-code.js View on Github external
it("should get proper lines when using \\u2028 as a line break", () => {
            const code = "a;\u2028b;",
                ast = espree.parse(code, DEFAULT_CONFIG),
                sourceCode = new SourceCode(code, ast);

            const lines = sourceCode.getLines();

            assert.strictEqual(lines[0], "a;");
            assert.strictEqual(lines[1], "b;");
        });
github eslint / eslint / tests / lib / rules / utils / ast-utils.js View on Github external
it(`should return ${expectedResults[key]} for ${key}`, () => {
                    assert.strictEqual(astUtils.isDecimalIntegerNumericToken(espree.tokenize(key)[0]), expectedResults[key]);
                });
            });
github jfmengels / eslint-ast-utils / test / helpers / espree.js View on Github external
function program(code) {
	return espree.parse(code, {
		sourceType: 'module',
		ecmaVersion: 8,
		ecmaFeatures: {
			jsx: true,
			experimentalObjectRestSpread: true
		}
	});
}
github t2ym / i18n-behavior / demo / gulpfile.js View on Github external
valueExpression = 'effectiveLang';
                    }
                    while (tmpPart = partPath.shift()) {
                      valueExpression += `["${tmpPart}"]`;
                    }
                    if (isJSON) {
                      valueExpression = `JSON.stringify(${valueExpression})`;
                    }
                  }
                  valueExpressions.push(valueExpression);
                }
                let valueExpressionAst;
                if (isI18nFormat) {
                  valueExpression = valueExpressions.join(',');
                  valueExpression = `_bind.element.i18nFormat(${valueExpression})`;
                  valueExpressionAst = espree.parse(valueExpression, espreeModuleOptions).body[0].expression;
                  valueExpressions.forEach((param, index) => {
                    let tmpMatch = param.match(/^parts\[([0-9]*)\]$/);
                    if (tmpMatch) {
                      valueExpressionAst.arguments[index] = ast.quasi.expressions[parseInt(tmpMatch[1]) + offset]
                    }
                  });
                }
                else {
                  //console.log('html: part ' + part + ' = ' + valueExpression);
                  valueExpressionAst = espree.parse(valueExpression, espreeModuleOptions).body[0].expression;
                }
                parts.push(valueExpressionAst);
              }
            }
            strings.push({
              "type": "Literal",

espree

An Esprima-compatible JavaScript parser built on Acorn

BSD-2-Clause
Latest version published 2 months ago

Package Health Score

94 / 100
Full package analysis