ast-types
ast-types copied to clipboard
path.scope not accurate for const and let
Variables declared with let and const are block-scoped, not function-scoped. Yet path.scope is the same for both blocked-scoped variables and function-scoped variables declared with var. The following
var recast = require("recast");
var types = require("ast-types");
var ast = recast.parse(`
function f() {
if (true) {
const x = 3;
}
}
`);
types.visit(ast, {
visitVariableDeclaration: function(path) {
console.log(path.scope.node.type);
return false;
}
});
Outputs "FunctionDeclaration", but I think it should be "BlockStatement".
The Scope code was written before let and const were so universally supported, but that's no excuse. I should definitely fix this. Thanks for bringing it to my attention.
@bmeck is working on this as part of https://github.com/benjamn/ast-types/pull/157
I hit this as well, while working on a project of my own. Glad to know you guys are aware & working on it.
@benjamn is there a way to use @babel/traverse with a recastified ast-types AST? Even if I use jscodeshift.withParser('babel'), the nodes don't seem to work with @babel/traverse. I'm implementing a promise chain unwinding transform, and I need to be able to guarantee that I can correctly rename identifiers I move between scopes to prevent conflicts, so I can't use ast-types' Path right now.