From 17098495f2db08f8a4bf35e9aea5c89b519582f8 Mon Sep 17 00:00:00 2001 From: Alexey Andreev Date: Mon, 6 Jul 2020 12:11:03 +0300 Subject: [PATCH] JS: fix compilation of class files that contain methods and field names containing non-identifier characters --- .../codegen/DefaultAliasProvider.java | 36 ++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/core/src/main/java/org/teavm/backend/javascript/codegen/DefaultAliasProvider.java b/core/src/main/java/org/teavm/backend/javascript/codegen/DefaultAliasProvider.java index bc5569545..233123f88 100644 --- a/core/src/main/java/org/teavm/backend/javascript/codegen/DefaultAliasProvider.java +++ b/core/src/main/java/org/teavm/backend/javascript/codegen/DefaultAliasProvider.java @@ -26,7 +26,7 @@ import org.teavm.model.MethodDescriptor; import org.teavm.model.MethodReference; public class DefaultAliasProvider implements AliasProvider { - int topLevelAliasLimit; + private int topLevelAliasLimit; private final Map classAliases = new HashMap<>(); private final Set knownAliases = new HashSet<>(200, 0.5f); private final ObjectIntMap knowAliasesCounter = new ObjectIntHashMap<>(); @@ -142,7 +142,41 @@ public class DefaultAliasProvider implements AliasProvider { } } + private String sanitize(String s) { + if (s.isEmpty()) { + return "_"; + } + boolean changed = false; + StringBuilder sb = new StringBuilder(s.length()); + char c = s.charAt(0); + if (isIdentifierStart(c)) { + sb.append(c); + } else { + sb.append('_'); + changed = true; + } + for (int i = 1; i < s.length(); ++i) { + c = s.charAt(i); + if (isIdentifierPart(c)) { + sb.append(c); + } else { + sb.append('_'); + changed = true; + } + } + return changed ? sb.toString() : s; + } + + private static boolean isIdentifierStart(char c) { + return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_' || c == '$'; + } + + private static boolean isIdentifierPart(char c) { + return isIdentifierStart(c) || c >= '0' && c <= '9'; + } + private String makeUnique(Set knowAliases, ObjectIntMap indexMap, String alias) { + alias = sanitize(alias); String uniqueAlias = alias; int index = indexMap.get(alias); if (index > 0) {