|
| 1 | +package liquidjava.rj_language.ast.formatter; |
| 2 | + |
| 3 | +import java.util.HashSet; |
| 4 | +import java.util.Set; |
| 5 | +import java.util.function.Function; |
| 6 | + |
| 7 | +import liquidjava.rj_language.ast.Expression; |
| 8 | +import liquidjava.rj_language.ast.FunctionInvocation; |
| 9 | +import liquidjava.rj_language.ast.Var; |
| 10 | +import liquidjava.utils.Utils; |
| 11 | + |
| 12 | +/** Simplifies unambiguous qualified names within one expression */ |
| 13 | +final class ExpressionNameResolver { |
| 14 | + private final Set<String> variables = new HashSet<>(); |
| 15 | + private final Set<String> functions = new HashSet<>(); |
| 16 | + |
| 17 | + public static ExpressionNameResolver forExpression(Expression expression) { |
| 18 | + ExpressionNameResolver resolver = new ExpressionNameResolver(); |
| 19 | + resolver.collect(expression); |
| 20 | + return resolver; |
| 21 | + } |
| 22 | + |
| 23 | + public String resolveVariable(String name) { |
| 24 | + String formatted = VariableFormatter.format(name); |
| 25 | + return isAmbiguous(name, variables, ExpressionNameResolver::getVariableSimpleName) ? formatted |
| 26 | + : Utils.getSimpleName(formatted); |
| 27 | + } |
| 28 | + |
| 29 | + public String resolveFunction(String name) { |
| 30 | + return isAmbiguous(name, functions, Utils::getSimpleName) ? name : Utils.getSimpleName(name); |
| 31 | + } |
| 32 | + |
| 33 | + private void collect(Expression expression) { |
| 34 | + if (expression instanceof Var var) |
| 35 | + variables.add(var.getName()); |
| 36 | + else if (expression instanceof FunctionInvocation fun) |
| 37 | + functions.add(fun.getName()); |
| 38 | + expression.getChildren().forEach(this::collect); |
| 39 | + } |
| 40 | + |
| 41 | + private static String getVariableSimpleName(String name) { |
| 42 | + return Utils.getSimpleName(VariableFormatter.withoutInstance(name)); |
| 43 | + } |
| 44 | + |
| 45 | + private static boolean isAmbiguous(String name, Set<String> names, Function<String, String> getSimpleName) { |
| 46 | + String simpleName = getSimpleName.apply(name); |
| 47 | + return names.stream().anyMatch(other -> !other.equals(name) && getSimpleName.apply(other).equals(simpleName)); |
| 48 | + } |
| 49 | +} |
0 commit comments