Skip to content

Commit

Permalink
AliasStrings: no aliasing in template literals
Browse files Browse the repository at this point in the history
Fixes a bug in which AliasStrings created an invalid AST, because it doesn't
understand how to correctly modify template literals.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=175608155
  • Loading branch information
brad4d authored and Tyler Breisacher committed Nov 14, 2017
1 parent 488f3a3 commit f7bae0d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/com/google/javascript/jscomp/AliasStrings.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

package com.google.javascript.jscomp;

import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.Node;
import java.util.ArrayList;
Expand Down Expand Up @@ -47,8 +46,7 @@
* duplicate strings.
*
*/
class AliasStrings extends AbstractPostOrderCallback
implements CompilerPass {
class AliasStrings implements CompilerPass, NodeTraversal.Callback {

private static final Logger logger =
Logger.getLogger(AliasStrings.class.getName());
Expand Down Expand Up @@ -131,6 +129,20 @@ public void process(Node externs, Node root) {
}
}

@Override
public boolean shouldTraverse(NodeTraversal nodeTraversal, Node n, Node parent) {
switch (n.getToken()) {
case TEMPLATELIT:
case TAGGED_TEMPLATELIT:
case TEMPLATELIT_SUB: // technically redundant, since it must be a child of the others
// TODO(bradfordcsmith): Consider replacing long and/or frequently occurring substrings
// within template literals with template substitutions.
return false;
default:
return true;
}
}

@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isString() && !parent.isGetProp() && !parent.isRegExp()) {
Expand Down
15 changes: 15 additions & 0 deletions test/com/google/javascript/jscomp/AliasStringsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,21 @@ protected CompilerPass getProcessor(Compiler compiler) {
return pass;
}

public void testTemplateLiteral() {
strings = ImmutableSet.of("aliasable string");
// TODO(bradfordcsmith): Maybe implement using aliases in template literals?
test(
lines(
"const A = 'aliasable string';",
"const B = 'aliasable string';",
"const AB = `${A}aliasable string${B}`;"),
lines(
"var $$S_aliasable$20string = 'aliasable string';",
"const A = $$S_aliasable$20string;",
"const B = $$S_aliasable$20string;",
"const AB = `${A}aliasable string${B}`"));
}

public void testAssignment() {
strings = ImmutableSet.of("none", "width", "overimaginative");

Expand Down

0 comments on commit f7bae0d

Please sign in to comment.