Skip to content

Commit 508a2c1

Browse files
bangertcopybara-github
authored andcommitted
Allow concatenating compile-time constant strings via templates for Const.from
PiperOrigin-RevId: 326089965
1 parent 23a42ff commit 508a2c1

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/com/google/javascript/jscomp/ConstParamCheck.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import static com.google.common.base.Preconditions.checkState;
2121

2222
import com.google.common.annotations.VisibleForTesting;
23+
import com.google.common.collect.Streams;
2324
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
2425
import com.google.javascript.rhino.Node;
2526

@@ -107,6 +108,7 @@ public void visit(NodeTraversal traversal, Node node, Node parent) {
107108
*
108109
* <ol>
109110
* <li>The argument is a constant variable assigned from a string literal, or
111+
* <li>The argument is a template into which only string literals are inserted, or
110112
* <li>The argument is an expression that is a string literal, or
111113
* <li>The argument is a ternary expression choosing between string literals, or
112114
* <li>The argument is a concatenation of the above.
@@ -118,6 +120,13 @@ public void visit(NodeTraversal traversal, Node node, Node parent) {
118120
private boolean isSafeValue(Scope scope, Node argument) {
119121
if (NodeUtil.isSomeCompileTimeConstStringValue(argument)) {
120122
return true;
123+
} else if (argument.isTemplateLit()) {
124+
// Each templateLit child is either a TemplateLitString, or has children which are substituted
125+
return Streams.stream(argument.children())
126+
.filter(node -> !node.isTemplateLitString())
127+
.map(Node::children)
128+
.flatMap(Streams::stream)
129+
.allMatch(node -> isSafeValue(scope, node));
121130
} else if (argument.isAdd()) {
122131
Node left = argument.getFirstChild();
123132
Node right = argument.getLastChild();

test/com/google/javascript/jscomp/ConstParamCheckTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,24 @@ public void testTemplateLiteralWithSubstitutionsArgument2() {
8181
ConstParamCheck.CONST_NOT_STRING_LITERAL_ERROR);
8282
}
8383

84+
@Test
85+
public void testTemplateLiteralSubstitutesConstTemplate() {
86+
testNoWarning(
87+
CLOSURE_DEFS
88+
+ "var BAR = `bar`;" // An ESLint template
89+
+ "var FOO = `foo ${BAR}`;"
90+
+ "goog.string.Const.from(FOO);");
91+
}
92+
93+
@Test
94+
public void testTemplateLiteralSubstitutesConstString() {
95+
testNoWarning(
96+
CLOSURE_DEFS
97+
+ "var BAR = 'bar';" // A string literal
98+
+ "var FOO = `foo ${BAR}`;"
99+
+ "goog.string.Const.from(FOO);");
100+
}
101+
84102
@Test
85103
public void testConcatenatedStringLiteralArgument() {
86104
testSame(CLOSURE_DEFS

0 commit comments

Comments
 (0)