benjamn / ast-types

Esprima-compatible implementation of the Mozilla JS Parser API

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Scope of a var in catch is catchclause

robz opened this issue · comments

commented

A var that is declared in catch clauses should have the scope that the try/catch is in, but instead .scope returns a scope that is the catch clause itself.

For example, this code:

var recast = require("recast");
var types = require("ast-types");

var ast = recast.parse(`
  function f() {
    try {
      var a = 4;
    } catch (e) {
      var b = 3;
    }
  }
`);

types.visit(ast, {
  visitVariableDeclarator: function(path) {
    var name = path.node.id.name;
    var scope = path.scope;
    console.log(name, scope.node.type, scope.declares(name));
    scope = scope.parent;
    console.log(name, scope.node.type, scope.declares(name));
    return false;
  }
});

Outputs this:

a FunctionDeclaration true
a Program false
b CatchClause false
b FunctionDeclaration true

But I think it should output this:

a FunctionDeclaration true
a Program false
b FunctionDeclaration true
b Program false

Actually, I just tried

(function () {
	try {
		var a = 4;
	} catch (_) {
		var b = 3;
	}
	return typeof b !== "undefined";
})()

and Node is giving me false. So it should probably output:

a FunctionDeclaration true
a Program false
b CatchClause true
b FunctionDeclaration false

Seems to me that although the variable declaration for b is bound to the function's scope, b is not explicitly defined and hence will still be undefined. That is to say, I believe your original code should be the correct behaviour.