Skip to content

Can't locate variable within named function's scope when function assigned to other variable #125

Open
@lainverse

Description

@lainverse

Here is an example code:

let escope = require('escope');
let esprima = require('esprima');
let estraverse = require('estraverse');

let ast = esprima.parse(`
    var a = function a() {
        var b = 1;
    }, c = function () {
        var d = 2
    };
    function x() {
        var z = 3;
    }
`);

let scopeman = escope.analyze(ast);
let scope = scopeman.acquire(ast);
let fname = void 0;

estraverse.traverse(ast, {
    enter: (n, p) => {
        if (n.type === 'VariableDeclarator') {
            console.log(fname, n.id.name, !!scope.set.get(n.id.name));
            if (fname && scope.childScopes.length === 1)
                console.log('!!!subscope:', !!scope.childScopes[0].set.get(n.id.name));
        }
        if (/Function/.test(n.type)) {
            fname = n.id ? n.id.name : void 0;
            scope = scopeman.acquire(n);
        }
    },
    leave: (n, p) => {
        if (/Function/.test(n.type)) {
            fname = void 0;
            scope = scope.upper
        }
    }
});

Expected result:
undefined 'a' true
a b true
undefined 'c' true
undefined 'd' true
x z true

Actual result (notice second and third rows):
undefined 'a' true
a b false
!!!subscope: true
undefined 'c' true
undefined 'd' true
x z true

Why is it like that?

Also, the only variable available in the scope of function 'a' is 'a' which points to function itself.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions