Skip to content

Commit b401790

Browse files
committed
Optimize VisitorState#getConstantExpression
By avoiding a second pass over the string.
1 parent be99217 commit b401790

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

check_api/src/main/java/com/google/errorprone/VisitorState.java

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
5252
import com.sun.tools.javac.tree.TreeMaker;
5353
import com.sun.tools.javac.util.Context;
54+
import com.sun.tools.javac.util.Convert;
5455
import com.sun.tools.javac.util.Name;
5556
import com.sun.tools.javac.util.Names;
5657
import com.sun.tools.javac.util.Options;
@@ -770,24 +771,20 @@ private static final class SharedState {
770771
* Like {@link Elements#getConstantExpression}, but doesn't over-escape single quotes in strings.
771772
*/
772773
public String getConstantExpression(Object value) {
773-
String escaped = getElements().getConstantExpression(value);
774-
if (value instanceof String) {
775-
// Don't escape single-quotes in string literals
776-
StringBuilder sb = new StringBuilder();
777-
for (int i = 0; i < escaped.length(); i++) {
778-
char c = escaped.charAt(i);
779-
if (c == '\\' && i + 1 < escaped.length()) {
780-
char next = escaped.charAt(++i);
781-
if (next != '\'') {
782-
sb.append(c);
783-
}
784-
sb.append(next);
785-
} else {
786-
sb.append(c);
787-
}
774+
if (!(value instanceof String str)) {
775+
return getElements().getConstantExpression(value);
776+
}
777+
778+
// Don't escape single-quotes in string literals.
779+
StringBuilder sb = new StringBuilder("\"");
780+
for (int i = 0; i < str.length(); i++) {
781+
char c = str.charAt(i);
782+
if (c == '\'') {
783+
sb.append('\'');
784+
} else {
785+
sb.append(Convert.quote(c));
788786
}
789-
return sb.toString();
790787
}
791-
return escaped;
788+
return sb.append('"').toString();
792789
}
793790
}

0 commit comments

Comments
 (0)