1 package org.simantics.scl.compiler.internal.codegen.utils;
3 public class NameMangling {
5 private static final boolean[] NORMAL_CHAR = new boolean[128];
6 private static final char[] REWRITE_CHAR = new char[128];
7 private static final char[] INVERSE_REWRITE_CHAR = new char[128];
8 private static final char ESCAPE_CHAR = (char)164;
11 for(char c='a';c<='z';++c)
12 NORMAL_CHAR[c] = true;
13 for(char c='A';c<='Z';++c)
14 NORMAL_CHAR[c] = true;
15 for(char c='0';c<='9';++c)
16 NORMAL_CHAR[c] = true;
17 NORMAL_CHAR['_'] = true;
18 NORMAL_CHAR['-'] = true;
19 NORMAL_CHAR['|'] = true;
20 NORMAL_CHAR['+'] = true;
21 NORMAL_CHAR['?'] = true;
22 NORMAL_CHAR['*'] = true;
23 NORMAL_CHAR['!'] = true;
24 NORMAL_CHAR['@'] = true;
25 NORMAL_CHAR[':'] = true;
26 NORMAL_CHAR['$'] = true;
27 NORMAL_CHAR['&'] = true;
28 NORMAL_CHAR['%'] = true;
29 NORMAL_CHAR['='] = true;
30 NORMAL_CHAR['#'] = true;
32 REWRITE_CHAR['/'] = 'd';
33 REWRITE_CHAR['>'] = 'g';
34 REWRITE_CHAR['<'] = 'l';
35 REWRITE_CHAR['.'] = 'p';
36 REWRITE_CHAR[';'] = 's';
38 for(char c=0;c<128;++c) {
39 char r = REWRITE_CHAR[c];
41 INVERSE_REWRITE_CHAR[r] = c;
46 public static String mangle(String name) {
47 int length = name.length();
48 for(int i=0;i<length;++i) {
49 char c = name.charAt(i);
50 if(c >= 128 || !NORMAL_CHAR[c]) {
51 StringBuilder b = new StringBuilder(name.substring(0, i));
52 boolean normalMode = true;
55 if(c < 128 && NORMAL_CHAR[c]) {
57 b.append(ESCAPE_CHAR);
64 b.append(ESCAPE_CHAR);
67 char r = c < 128 ? REWRITE_CHAR[c] : 0;
70 b.append(ESCAPE_CHAR);
83 public static String demangle(String name) {
84 int length = name.length();
85 for(int i=0;i<length;++i) {
86 char c = name.charAt(i);
87 if(c == ESCAPE_CHAR) {
88 StringBuilder b = new StringBuilder(name.substring(0, i));
89 boolean normalMode = false;
90 for(++i;i<length;++i) {
93 normalMode = !normalMode;
97 if(c >= '0' && c <= '9') {
98 int l = name.substring(i).indexOf(ESCAPE_CHAR);
99 char r = (char)Integer.parseInt(name.substring(i, i+l));
104 b.append(INVERSE_REWRITE_CHAR[c]);
113 public static void test(String name) {
114 String name2 = mangle(name);
115 String name3 = demangle(name2);
116 System.out.println(name + " -> " + name2 + " -> " + name3);
119 public static void main(String[] args) {
130 for(int i=28;i<256;++i) {
131 if(Character.isJavaIdentifierStart(i))
132 System.out.print(new String(Character.toChars(i)) + "(" + i + ")");
134 System.out.println();
135 System.out.println("----------------------------------------------------");
136 for(int i=28;i<256;++i) {
137 if(Character.isJavaIdentifierPart(i))
138 System.out.print(new String(Character.toChars(i)) + "(" + i + ")");
140 System.out.println();