|
| 1 | +package liquidjava.utils; |
| 2 | + |
| 3 | +import java.util.regex.Matcher; |
| 4 | +import java.util.regex.Pattern; |
| 5 | + |
| 6 | +public final class VariableFormatter { |
| 7 | + private static final Pattern INSTACE_VAR_PATTERN = Pattern.compile("^#(.+)_([0-9]+)$"); |
| 8 | + private static final Pattern INSTANCE_VAR_TEXT_PATTERN = Pattern.compile("#[^\\s,;:()\\[\\]{}]+_[0-9]+"); |
| 9 | + private static final char[] SUPERSCRIPT_CHARS = { '⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹' }; |
| 10 | + |
| 11 | + public static String formatVariable(String name) { |
| 12 | + if (name == null) |
| 13 | + return null; |
| 14 | + |
| 15 | + Matcher matcher = INSTACE_VAR_PATTERN.matcher(name); |
| 16 | + if (!matcher.matches()) |
| 17 | + return name; |
| 18 | + |
| 19 | + String baseName = matcher.group(1); |
| 20 | + String counter = matcher.group(2); |
| 21 | + String prefix = isSpecialIdentifier(baseName) ? "#" : ""; |
| 22 | + return prefix + baseName + toSuperscript(counter); |
| 23 | + } |
| 24 | + |
| 25 | + public static String formatText(String text) { |
| 26 | + if (text == null) |
| 27 | + return null; |
| 28 | + |
| 29 | + Matcher textMatcher = INSTANCE_VAR_TEXT_PATTERN.matcher(text); |
| 30 | + StringBuilder sb = new StringBuilder(); |
| 31 | + while (textMatcher.find()) { |
| 32 | + String token = textMatcher.group(); |
| 33 | + textMatcher.appendReplacement(sb, Matcher.quoteReplacement(formatVariable(token))); |
| 34 | + } |
| 35 | + textMatcher.appendTail(sb); |
| 36 | + return sb.toString(); |
| 37 | + } |
| 38 | + |
| 39 | + private static String toSuperscript(String number) { |
| 40 | + StringBuilder sb = new StringBuilder(number.length()); |
| 41 | + for (char c : number.toCharArray()) { |
| 42 | + int index = c - '0'; |
| 43 | + if (index < 0 || index >= SUPERSCRIPT_CHARS.length) |
| 44 | + return number; |
| 45 | + sb.append(SUPERSCRIPT_CHARS[index]); |
| 46 | + } |
| 47 | + return sb.toString(); |
| 48 | + } |
| 49 | + |
| 50 | + private static boolean isSpecialIdentifier(String id) { |
| 51 | + return id.equals("fresh") || id.equals("ret"); |
| 52 | + } |
| 53 | +} |
0 commit comments