ast-types icon indicating copy to clipboard operation
ast-types copied to clipboard

path.scope not accurate for const and let

Open robz opened this issue 9 years ago • 4 comments

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".

robz avatar Jun 07 '16 21:06 robz

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.

benjamn avatar Jun 07 '16 21:06 benjamn

@bmeck is working on this as part of https://github.com/benjamn/ast-types/pull/157

benjamn avatar Jun 27 '16 14:06 benjamn

I hit this as well, while working on a project of my own. Glad to know you guys are aware & working on it.

sigriston avatar Jul 03 '16 06:07 sigriston

@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.

jedwards1211 avatar Apr 08 '20 00:04 jedwards1211