-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExpressionHelper.ts
More file actions
330 lines (272 loc) · 9.07 KB
/
ExpressionHelper.ts
File metadata and controls
330 lines (272 loc) · 9.07 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
import {
CircomParser,
ExpressionContext,
PAnonymousCallContext,
PArrayContext,
PCallContext,
PIdentifierStatementContext,
PNumberContext,
PParenthesesContext,
PUnderscoreContext,
} from "../generated";
import { CircomValueType, ParserErrorItem, VariableContext } from "../types";
import { ExtendedCircomVisitor } from "../ExtendedCircomVisitor";
export class ExpressionHelper {
private _expressionContext: ExpressionContext | null = null;
private _variableContext: VariableContext = {};
constructor(public templateIdentifier: string) {}
public setExpressionContext(
expressionContext: ExpressionContext,
): ExpressionHelper {
this._expressionContext = expressionContext;
return this;
}
public setVariableContext(
variableContext: VariableContext,
): ExpressionHelper {
this._variableContext = variableContext;
return this;
}
public addVariablesToTheContext(
variables: VariableContext,
): ExpressionHelper {
for (const key in variables) {
this._variableContext[key] = variables[key];
}
return this;
}
/**
* This function can throw an error if the expression context is not set.
* All other errors related to the parsing of the expression can be retrieved by the function `getErrors()`
* inside the `ExtendedCircomVisitor` class.
*/
public parseExpression(): [CircomValueType | null, ParserErrorItem[]] {
if (!this._expressionContext) {
throw new Error("Expression context is not set");
}
const visitor = new ExpressionVisitor(
this.templateIdentifier,
this._variableContext,
);
const result = visitor.visitExpression(this._expressionContext);
if (result === null || result === undefined) {
return [null, visitor.getErrors()];
}
return [result, visitor.getErrors()];
}
}
class ExpressionVisitor extends ExtendedCircomVisitor<CircomValueType | null> {
constructor(
templateIdentifier: string,
public variableContext: VariableContext,
) {
super(templateIdentifier);
}
visitExpression = (ctx: ExpressionContext): CircomValueType | null => {
if (ctx.PARALLEL()) {
return this.visit(ctx.expression(0));
}
if (ctx.primaryExpression()) {
return this.visit(ctx.primaryExpression());
}
if (ctx.TERNARY_CONDITION() && ctx.TERNARY_ALTERNATIVE()) {
const conditionResult = this.visit(ctx._cond);
if (conditionResult === null || conditionResult === undefined) {
this.addError(
"Failed to resolve the condition of a ternary expression",
ctx._cond,
);
return null;
}
if (Array.isArray(conditionResult)) {
this.addError(
"Ternary expression condition cannot be an array",
ctx._cond,
);
return null;
}
if (conditionResult === 1n) {
return this.visit(ctx._ifTrue);
} else {
return this.visit(ctx._ifFalse);
}
}
return this._parseOperation(ctx);
};
visitPIdentifierStatement = (
ctx: PIdentifierStatementContext,
): CircomValueType | null => {
if (ctx.identifierStatement().idetifierAccess_list().length == 0) {
const variableValue =
this.variableContext[ctx.identifierStatement().ID().getText()];
if (variableValue === undefined || variableValue === null) {
this.addError(
`Variable ${ctx.identifierStatement().ID().getText()} is not defined`,
ctx.identifierStatement(),
);
return null;
}
return variableValue;
}
const reference = ctx
.identifierStatement()
.idetifierAccess_list()
.map((access) => access.getText())
.join("");
if (reference.indexOf(".") !== -1) {
this.addError(
"IdentifierStatement is not supported with access references that are not arrays",
ctx,
);
return null;
}
const variableName = ctx.identifierStatement().ID().getText() + reference;
if (
this.variableContext[variableName] === undefined ||
this.variableContext[variableName] === null
) {
this.addError(
`Variable ${variableName} is not defined`,
ctx.identifierStatement(),
);
return null;
}
return this.variableContext[variableName];
};
visitPUnderscore = (_ctx: PUnderscoreContext): CircomValueType | null => {
return null;
};
visitPNumber = (ctx: PNumberContext): CircomValueType | null => {
return BigInt(ctx.NUMBER().getText());
};
visitPParentheses = (ctx: PParenthesesContext): CircomValueType | null => {
let expressions = ctx.expressionList().expression_list();
if (expressions.length !== 1) {
this.addError("Parentheses can only contain one expression", ctx);
return null;
}
return this.visit(expressions[0]);
};
visitPArray = (ctx: PArrayContext): CircomValueType | null => {
let arrayItems: CircomValueType | null = [];
for (let i = 0; i < ctx.expressionList().expression_list().length; i++) {
const resolvedItem = this.visit(ctx.expressionList().expression(i));
if (resolvedItem === null || resolvedItem === undefined) {
this.addError(
`Failed to resolve the ${i} element of an array.`,
ctx.expressionList().expression(i),
);
arrayItems = null;
continue;
}
if (arrayItems) {
arrayItems.push(resolvedItem);
}
}
return arrayItems;
};
visitPCall = (ctx: PCallContext): CircomValueType | null => {
this.addError("Calls are not supported", ctx);
return null;
};
visitPAnonymousCall = (
ctx: PAnonymousCallContext,
): CircomValueType | null => {
this.addError("Anonymous calls are not supported", ctx);
return null;
};
private _parseOperation(ctx: ExpressionContext): CircomValueType | null {
const operationType = ctx._op.type;
const firstExpression = this.visit(ctx.expression(0));
if (firstExpression === null || firstExpression === undefined) {
this.addError(
"Failed to resolve the first expression of an operation",
ctx.expression(0),
);
return null;
}
if (Array.isArray(firstExpression)) {
this.addError(
"Performing operations on arrays is not allowed",
ctx.expression(0),
);
return null;
}
switch (operationType) {
case CircomParser.NOT:
if (firstExpression !== 0n && firstExpression !== 1n) {
this.addError(
"NOT operation can be performed only on boolean values",
ctx.expression(0),
);
return null;
}
return firstExpression ? 0n : 1n;
case CircomParser.BNOT:
return ~firstExpression;
}
if (operationType == CircomParser.SUB && ctx.expression(1) == null) {
return -firstExpression;
}
const secondExpression = this.visit(ctx.expression(1));
if (secondExpression === null || secondExpression === undefined) {
this.addError(
"Failed to resolve the second expression of an operation",
ctx.expression(1),
);
return null;
}
if (Array.isArray(secondExpression)) {
this.addError(
"Performing operations on arrays is not allowed",
ctx.expression(1),
);
return null;
}
switch (operationType) {
case CircomParser.POW:
return firstExpression ** secondExpression;
case CircomParser.MUL:
return firstExpression * secondExpression;
case CircomParser.DIV:
return firstExpression / secondExpression;
case CircomParser.QUO:
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Division
return firstExpression / secondExpression;
case CircomParser.MOD:
return firstExpression % secondExpression;
case CircomParser.ADD:
return firstExpression + secondExpression;
case CircomParser.SUB:
return firstExpression - secondExpression;
case CircomParser.SHL:
return firstExpression << secondExpression;
case CircomParser.SHR:
return firstExpression >> secondExpression;
case CircomParser.BAND:
return firstExpression & secondExpression;
case CircomParser.BXOR:
return firstExpression ^ secondExpression;
case CircomParser.BOR:
return firstExpression | secondExpression;
case CircomParser.EQ:
return firstExpression === secondExpression ? 1n : 0n;
case CircomParser.NEQ:
return firstExpression !== secondExpression ? 1n : 0n;
case CircomParser.LT:
return firstExpression < secondExpression ? 1n : 0n;
case CircomParser.GT:
return firstExpression > secondExpression ? 1n : 0n;
case CircomParser.LE:
return firstExpression <= secondExpression ? 1n : 0n;
case CircomParser.GE:
return firstExpression >= secondExpression ? 1n : 0n;
case CircomParser.AND:
return firstExpression && secondExpression ? 1n : 0n;
case CircomParser.OR:
return firstExpression || secondExpression ? 1n : 0n;
}
this.addError("Reached unknown operation", ctx);
return null;
}
}