-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathExpression.java
More file actions
353 lines (318 loc) · 14.3 KB
/
Expression.java
File metadata and controls
353 lines (318 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package liquidjava.rj_language.ast;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import liquidjava.diagnostics.errors.ArgumentMismatchError;
import liquidjava.diagnostics.errors.LJError;
import liquidjava.diagnostics.errors.NotFoundError;
import liquidjava.processor.context.Context;
import liquidjava.processor.context.GhostFunction;
import liquidjava.processor.facade.AliasDTO;
import liquidjava.rj_language.ast.typing.TypeInfer;
import liquidjava.rj_language.visitors.ExpressionVisitor;
import liquidjava.utils.Utils;
import liquidjava.utils.constants.Keys;
import spoon.reflect.factory.Factory;
import spoon.reflect.reference.CtTypeReference;
public abstract class Expression {
public abstract <T> T accept(ExpressionVisitor<T> visitor) throws LJError;
public abstract void getVariableNames(List<String> toAdd);
public abstract void getStateInvocations(List<String> toAdd, List<String> all);
public abstract boolean isBooleanTrue();
public abstract int hashCode();
public abstract boolean equals(Object obj);
public abstract Expression clone();
public abstract String toString();
List<Expression> children = new ArrayList<>();
public void addChild(Expression e) {
children.add(e);
}
public List<Expression> getChildren() {
return children;
}
public boolean hasChildren() {
return !children.isEmpty();
}
public void setChild(int index, Expression element) {
children.set(index, element);
}
public boolean isLiteral() {
return this instanceof LiteralInt || this instanceof LiteralLong || this instanceof LiteralReal
|| this instanceof LiteralBoolean || this instanceof LiteralChar;
}
/**
* Checks if this expression produces a boolean type based on its structure
*
* @return true if it is a boolean expression, false otherwise
*/
public boolean isBooleanExpression() {
if (this instanceof LiteralBoolean || this instanceof Ite || this instanceof AliasInvocation
|| this instanceof FunctionInvocation) {
return true;
}
if (this instanceof GroupExpression ge) {
return ge.getExpression().isBooleanExpression();
}
if (this instanceof BinaryExpression be) {
return be.isBooleanOperation() || be.isLogicOperation();
}
if (this instanceof UnaryExpression ue) {
return ue.getOp().equals("!");
}
return false;
}
public List<Expression> getConjuncts() {
if (this instanceof BinaryExpression binaryExpression && "&&".equals(binaryExpression.getOperator())) {
List<Expression> conjuncts = new ArrayList<>();
conjuncts.addAll(binaryExpression.getFirstOperand().getConjuncts());
conjuncts.addAll(binaryExpression.getSecondOperand().getConjuncts());
return conjuncts;
}
return List.of(this);
}
/**
* Substitutes the expression first given expression by the second
*
* @param from
* @param to
*
* @return
*/
public Expression substitute(Expression from, Expression to) {
Expression e = clone();
if (this.equals(from))
e = to;
e.auxSubstitute(from, to);
return e;
}
private void auxSubstitute(Expression from, Expression to) {
if (hasChildren()) {
for (int i = 0; i < children.size(); i++) {
Expression exp = children.get(i);
if (exp.equals(from))
setChild(i, to);
exp.auxSubstitute(from, to);
}
}
}
/**
* Substitutes the function call with the given parameter to the expression e
*
* @param functionName
* @param parameters
* @param sub
*/
public void substituteFunction(String functionName, List<Expression> parameters, Expression sub) {
if (hasChildren())
for (int i = 0; i < children.size(); i++) {
Expression exp = children.get(i);
if (exp instanceof FunctionInvocation fi) {
if (fi.name.equals(functionName) && fi.argumentsEqual(parameters)) {
// substitute by sub in parent
setChild(i, sub);
}
}
exp.substituteFunction(functionName, parameters, sub);
}
}
public Expression substituteState(Map<String, Expression> subMap, String[] toChange) {
Expression e = clone();
if (this instanceof FunctionInvocation fi) {
String key = fi.name;
String simple = Utils.getSimpleName(key);
boolean has = subMap.containsKey(key) || subMap.containsKey(simple);
if (has && fi.children.size() == 1 && fi.children.get(0)instanceof Var v) { // object
// state
Expression sub = (subMap.containsKey(key) ? subMap.get(key) : subMap.get(simple)).clone();
for (String s : toChange) {
sub = sub.substitute(new Var(s), v);
}
// substitute by sub in parent
e = new GroupExpression(sub);
}
}
e.auxSubstituteState(subMap, toChange);
return e;
}
private void auxSubstituteState(Map<String, Expression> subMap, String[] toChange) {
if (hasChildren()) {
for (int i = 0; i < children.size(); i++) {
Expression exp = children.get(i);
if (exp instanceof FunctionInvocation fi) {
String key = fi.name;
String simple = Utils.getSimpleName(key);
boolean has = subMap.containsKey(key) || subMap.containsKey(simple);
if (has && fi.children.size() == 1 && fi.children.get(0)instanceof Var v) { // object
// state
Expression sub = (subMap.containsKey(key) ? subMap.get(key) : subMap.get(simple)).clone();
for (String s : toChange) {
sub = sub.substitute(new Var(s), v);
}
// substitute by sub in parent
setChild(i, (sub instanceof GroupExpression) ? sub : new GroupExpression(sub));
}
}
exp.auxSubstituteState(subMap, toChange);
}
}
}
public Expression changeAlias(Map<String, AliasDTO> alias, Context ctx, Factory f) throws LJError {
Expression e = clone();
if (this instanceof AliasInvocation ai) {
if (alias.containsKey(ai.name)) { // object state
AliasDTO dto = alias.get(ai.name);
// check argument count
if (children.size() != dto.getVarNames().size()) {
String msg = String.format(
"Wrong number of arguments in alias invocation '%s': expected %d, got %d", ai.name,
dto.getVarNames().size(), children.size());
throw new ArgumentMismatchError(msg);
}
Expression sub = dto.getExpression().clone();
for (int i = 0; i < children.size(); i++) {
Expression varExp = new Var(dto.getVarNames().get(i));
String varType = dto.getVarTypes().get(i);
Expression aliasExp = children.get(i);
// check argument types
boolean compatible = TypeInfer.checkCompatibleType(varType, aliasExp, ctx, f);
if (!compatible) {
String msg = String.format(
"Argument '%s' and parameter '%s' of alias '%s' types are incompatible: expected %s, got %s",
aliasExp, dto.getVarNames().get(i), ai.name, varType,
TypeInfer.getType(ctx, f, aliasExp).get().getQualifiedName());
throw new ArgumentMismatchError(msg);
}
sub = sub.substitute(varExp, aliasExp);
}
e = new GroupExpression(sub);
}
}
e.auxChangeAlias(alias, ctx, f);
return e;
}
private void auxChangeAlias(Map<String, AliasDTO> alias, Context ctx, Factory f) throws LJError {
if (hasChildren())
for (int i = 0; i < children.size(); i++) {
if (children.get(i)instanceof AliasInvocation ai) {
if (!alias.containsKey(ai.name))
throw new NotFoundError(ai.getName(), Keys.ALIAS);
AliasDTO dto = alias.get(ai.name);
// check argument count
if (ai.children.size() != dto.getVarNames().size()) {
String msg = String.format(
"Wrong number of arguments in alias invocation '%s': expected %d, got %d", ai.name,
dto.getVarNames().size(), ai.children.size());
throw new ArgumentMismatchError(msg);
}
Expression sub = dto.getExpression().clone();
if (ai.hasChildren())
for (int j = 0; j < ai.children.size(); j++) {
Expression varExp = new Var(dto.getVarNames().get(j));
String varType = dto.getVarTypes().get(j);
Expression aliasExp = ai.children.get(j);
// check argument types
boolean compatible = TypeInfer.checkCompatibleType(varType, aliasExp, ctx, f);
if (!compatible) {
String msg = String.format(
"Argument '%s' and parameter '%s' of alias '%s' types are incompatible: expected %s, got %s",
aliasExp, dto.getVarNames().get(i), ai.name, varType,
TypeInfer.getType(ctx, f, aliasExp).get().getQualifiedName());
throw new ArgumentMismatchError(msg);
}
sub = sub.substitute(varExp, aliasExp);
}
setChild(i, sub);
}
children.get(i).auxChangeAlias(alias, ctx, f);
}
}
/**
* Validates all ghost function invocations within this expression against the provided context This method supports
* overloading by iterating through all ghost functions with the matching name If a valid signature is found, no
* error is thrown If the invocation name exists but no overload matches the argument types, an
* {@link ArgumentMismatchError} is thrown.
*
* @param ctx
* @param f
*
* @throws LJError
*/
public void validateGhostInvocations(Context ctx, Factory f) throws LJError {
if (this instanceof FunctionInvocation fi) {
// get all ghosts with the matching name
List<GhostFunction> candidates = ctx.getGhosts().stream().filter(g -> g.matches(fi.name)).toList();
if (candidates.isEmpty())
return; // not found error is thrown elsewhere
// find matching overload
Optional<GhostFunction> found = candidates.stream().filter(g -> argumentsMatch(fi, g, ctx, f)).findFirst();
if (found.isEmpty()) {
// no overload found, use the first candidate to throw the error
throwArgumentMismatchError(fi, candidates.get(0), ctx, f);
}
}
// recurse children
if (hasChildren()) {
for (Expression child : children) {
child.validateGhostInvocations(ctx, f);
}
}
}
/**
* Checks if the arguments of the given function invocation match the parameters of the given ghost function
*
* @param fi
* @param g
* @param ctx
* @param f
*/
private boolean argumentsMatch(FunctionInvocation fi, GhostFunction g, Context ctx, Factory f) {
// check argument count
if (fi.children.size() != g.getParametersTypes().size())
return false;
// check argument types
for (int i = 0; i < fi.children.size(); i++) {
Expression arg = fi.children.get(i);
CtTypeReference<?> expected = g.getParametersTypes().get(i);
Optional<CtTypeReference<?>> actualOpt = TypeInfer.getType(ctx, f, arg);
if (actualOpt.isPresent()) {
CtTypeReference<?> actual = actualOpt.get();
if (!actual.equals(expected) && !actual.isSubtypeOf(expected)) {
return false;
}
}
}
return true;
}
/**
* Throws an ArgumentMismatchError for the given function invocation and ghost function
*
* @param fi
* @param g
* @param ctx
* @param f
*
* @throws ArgumentMismatchError
*/
private void throwArgumentMismatchError(FunctionInvocation fi, GhostFunction g, Context ctx, Factory f)
throws ArgumentMismatchError {
if (fi.children.size() != g.getParametersTypes().size()) {
throw new ArgumentMismatchError(
String.format("Wrong number of arguments in ghost invocation '%s': expected %d, got %d", fi.name,
g.getParametersTypes().size(), fi.children.size()));
}
for (int i = 0; i < fi.children.size(); i++) {
CtTypeReference<?> expected = g.getParametersTypes().get(i);
Optional<CtTypeReference<?>> actualOpt = TypeInfer.getType(ctx, f, fi.children.get(i));
if (actualOpt.isPresent()) {
CtTypeReference<?> actual = actualOpt.get();
if (!actual.equals(expected) && !actual.isSubtypeOf(expected)) {
Expression arg = fi.children.get(i);
throw new ArgumentMismatchError(String.format(
"Argument '%s' and its respective parameter of ghost '%s' types are incompatible: expected %s, got %s",
arg, fi.name, expected.getSimpleName(), actual.getSimpleName()));
}
}
}
}
}