babel-traverse: Mark appropriate template literals as pure (#5914)

* Identify pure template literals

* Mark template literals as pure where possible

* Changes based on code review

* nit
This commit is contained in:
Ash
2017-07-11 22:42:34 +01:00
committed by Henry Zhu
parent 2ce5f166d7
commit 960e1708a1
2 changed files with 27 additions and 0 deletions

View File

@@ -615,6 +615,17 @@ export default class Scope {
return this.isPure(node.value, constantsOnly);
} else if (t.isUnaryExpression(node)) {
return this.isPure(node.argument, constantsOnly);
} else if (t.isTaggedTemplateExpression(node)) {
return (
t.matchesPattern(node.tag, "String.raw") &&
!this.hasBinding("String", true) &&
this.isPure(node.quasi, constantsOnly)
);
} else if (t.isTemplateLiteral(node)) {
for (const expression of (node.expressions: Array<Object>)) {
if (!this.isPure(expression, constantsOnly)) return false;
}
return true;
} else {
return t.isPureish(node);
}

View File

@@ -77,6 +77,22 @@ describe("scope", function() {
assert.ok(
getPath("({ x: 1 })").get("body")[0].get("expression").isPure(),
);
assert.ok(!getPath("`${a}`").get("body")[0].get("expression").isPure());
assert.ok(
getPath("let a = 1; `${a}`").get("body")[1].get("expression").isPure(),
);
assert.ok(
!getPath("let a = 1; `${a++}`")
.get("body")[1]
.get("expression")
.isPure(),
);
assert.ok(
!getPath("tagged`foo`").get("body")[0].get("expression").isPure(),
);
assert.ok(
getPath("String.raw`foo`").get("body")[0].get("expression").isPure(),
);
});
test("label", function() {