Skip to content

Commit

Permalink
Make getBinding ignore labels; add Scope#getLabel, Scope#registerLabel (
Browse files Browse the repository at this point in the history
babel#4758)

* Make getBinding ignore labels; add Scope#getLabel, Scope#registerLabel

* generateUid: account for labels again
  • Loading branch information
kangax authored and panagosg7 committed Jan 17, 2017
1 parent f732bc2 commit f7375eb
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
18 changes: 16 additions & 2 deletions packages/babel-traverse/src/scope/index.js
Expand Up @@ -161,6 +161,8 @@ export default class Scope {
this.parentBlock = path.parent;
this.block = path.node;
this.path = path;

this.labels = new Map();
}

/**
Expand Down Expand Up @@ -218,7 +220,7 @@ export default class Scope {
do {
uid = this._generateUid(name, i);
i++;
} while (this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid));
} while (this.hasLabel(uid) || this.hasBinding(uid) || this.hasGlobal(uid) || this.hasReference(uid));

let program = this.getProgramParent();
program.references[uid] = true;
Expand Down Expand Up @@ -426,9 +428,21 @@ export default class Scope {
return t.callExpression(file.addHelper(helperName), args);
}

hasLabel(name: string) {
return !!this.getLabel(name);
}

getLabel(name: string) {
return this.labels.get(name);
}

registerLabel(path: NodePath) {
this.labels.set(path.node.label.name, path);
}

registerDeclaration(path: NodePath) {
if (path.isLabeledStatement()) {
this.registerBinding("label", path);
this.registerLabel(path);
} else if (path.isFunctionDeclaration()) {
this.registerBinding("hoisted", path.get("id"), path);
} else if (path.isVariableDeclaration()) {
Expand Down
22 changes: 22 additions & 0 deletions packages/babel-traverse/test/scope.js
Expand Up @@ -38,5 +38,27 @@ describe("scope", function () {
it("purity", function () {
assert.ok(getPath("({ x: 1 })").get("body")[0].get("expression").isPure());
});

test("label", function () {
assert.strictEqual(getPath("foo: { }").scope.getBinding("foo"), undefined);
assert.strictEqual(getPath("foo: { }").scope.getLabel("foo").type, "LabeledStatement");
assert.strictEqual(getPath("foo: { }").scope.getLabel("toString"), undefined);

assert.strictEqual(getPath(`
foo: { }
`).scope.generateUid("foo"), "_foo");
});

test("generateUid collision check with labels", function () {
assert.strictEqual(getPath(`
_foo: { }
`).scope.generateUid("foo"), "_foo2");

assert.strictEqual(getPath(`
_foo: { }
_foo1: { }
_foo2: { }
`).scope.generateUid("foo"), "_foo3");
});
});
});

0 comments on commit f7375eb

Please sign in to comment.