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:
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
Reference in New Issue
Block a user