Skip to content

Commit 0374a67

Browse files
committed
Fix Circular References in Variable Resolver
1 parent b3d1518 commit 0374a67

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

liquidjava-verifier/src/main/java/liquidjava/rj_language/opt/VariableResolver.java

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package liquidjava.rj_language.opt;
22

33
import java.util.HashMap;
4+
import java.util.HashSet;
45
import java.util.Map;
6+
import java.util.Set;
7+
58
import liquidjava.rj_language.ast.BinaryExpression;
69
import liquidjava.rj_language.ast.Expression;
710
import liquidjava.rj_language.ast.Var;
@@ -15,9 +18,9 @@ public static Map<String, Expression> resolve(Expression exp) {
1518
}
1619

1720
private static void resolveRecursive(Expression exp, Map<String, Expression> map) {
18-
if (!(exp instanceof BinaryExpression)) {
21+
if (!(exp instanceof BinaryExpression))
1922
return;
20-
}
23+
2124
BinaryExpression be = (BinaryExpression) exp;
2225
String op = be.getOperator();
2326
if ("&&".equals(op)) {
@@ -38,19 +41,24 @@ private static void resolveRecursive(Expression exp, Map<String, Expression> map
3841
private static Map<String, Expression> resolveTransitive(Map<String, Expression> map) {
3942
Map<String, Expression> result = new HashMap<>();
4043
for (Map.Entry<String, Expression> entry : map.entrySet()) {
41-
result.put(entry.getKey(), lookup(entry.getValue(), map));
44+
result.put(entry.getKey(), lookup(entry.getValue(), map, new HashSet<>()));
4245
}
4346
return result;
4447
}
4548

46-
private static Expression lookup(Expression exp, Map<String, Expression> map) {
47-
if (!(exp instanceof Var)) {
49+
private static Expression lookup(Expression exp, Map<String, Expression> map, Set<String> seen) {
50+
if (!(exp instanceof Var))
4851
return exp;
49-
}
50-
Expression value = map.get(exp.toString());
51-
if (value == null) {
52+
53+
String name = exp.toString();
54+
if (seen.contains(name))
55+
return exp; // circular reference
56+
57+
Expression value = map.get(name);
58+
if (value == null)
5259
return exp;
53-
}
54-
return lookup(value, map);
60+
61+
seen.add(name);
62+
return lookup(value, map, seen);
5563
}
5664
}

0 commit comments

Comments
 (0)