circom/src/gencode.js
src/gencode.jsRaw
1/*
2 Copyright 2018 0KIMS association.
3
4 This file is part of jaz (Zero Knowledge Circuit Compiler).
5
6 jaz is a free software: you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 jaz is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
14 License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with jaz. If not, see <https://www.gnu.org/licenses/>.
18*/
19
20const bigInt = require("big-integer");
21
22module.exports = genCode;
23
24function ident(text) {
25 let lines = text.split("\n");
26 for (let i=0; i<lines.length; i++) {
27 if (lines[i]) lines[i] = " "+lines[i];
28 }
29 return lines.join("\n");
30}
31
32function gen(ctx, ast) {
33 if ((ast.type == "NUMBER") ) {
34 return genNumber(ctx, ast);
35 } else if (ast.type == "VARIABLE") {
36 return genVariable(ctx, ast);
37 } else if (ast.type == "PIN") {
38 return genPin(ctx, ast);
39 } else if (ast.type == "OP") {
40 if (ast.op == "=") {
41 return genVarAssignement(ctx, ast);
42 } else if (ast.op == "<--") {
43 return genVarAssignement(ctx, ast);
44 } else if (ast.op == "<==") {
45 return genSignalAssignConstrain(ctx, ast);
46 } else if (ast.op == "===") {
47 return genConstrain(ctx, ast);
48 } else if (ast.op == "+=") {
49 return genVarAddAssignement(ctx, ast);
50 } else if (ast.op == "*=") {
51 return genVarMulAssignement(ctx, ast);
52 } else if (ast.op == "+") {
53 return genAdd(ctx, ast);
54 } else if (ast.op == "-") {
55 return genSub(ctx, ast);
56 } else if (ast.op == "UMINUS") {
57 return genUMinus(ctx, ast);
58 } else if (ast.op == "*") {
59 return genMul(ctx, ast);
60 } else if (ast.op == "%") {
61 return genMod(ctx, ast);
62 } else if (ast.op == "PLUSPLUSRIGHT") {
63 return genPlusPlusRight(ctx, ast);
64 } else if (ast.op == "PLUSPLUSLEFT") {
65 return genPlusPlusLeft(ctx, ast);
66 } else if (ast.op == "**") {
67 return genExp(ctx, ast);
68 } else if (ast.op == "&") {
69 return genBAnd(ctx, ast);
70 } else if (ast.op == "<<") {
71 return genShl(ctx, ast);
72 } else if (ast.op == ">>") {
73 return genShr(ctx, ast);
74 } else if (ast.op == "<") {
75 return genLt(ctx, ast);
76 } else if (ast.op == ">") {
77 return genGt(ctx, ast);
78 } else if (ast.op == "<=") {
79 return genLte(ctx, ast);
80 } else if (ast.op == ">=") {
81 return genGte(ctx, ast);
82 } else if (ast.op == "==") {
83 return genEq(ctx, ast);
84 } else if (ast.op == "?") {
85 return genTerCon(ctx, ast);
86 } else {
87 error(ctx, ast, "Invalid operation: " + ast.op);
88 }
89 } else if (ast.type == "DECLARE") {
90 if (ast.declareType == "COMPONENT") {
91 return genDeclareComponent(ctx, ast);
92 } else if ((ast.declareType == "SIGNALIN")||
93 (ast.declareType == "SIGNALOUT")||
94 (ast.declareType == "SIGNAL")) {
95 return genDeclareSignal(ctx, ast);
96 } else if (ast.declareType == "VARIABLE") {
97 return genDeclareVariable(ctx, ast);
98 } else {
99 error(ctx, ast, "Invalid declaration: " + ast.declareType);
100 }
101 } else if (ast.type == "FUNCTIONCALL") {
102 return genFunctionCall(ctx, ast);
103 } else if (ast.type == "BLOCK") {
104 return genBlock(ctx, ast);
105 } else if (ast.type == "FOR") {
106 return genFor(ctx, ast);
107 } else if (ast.type == "WHILE") {
108 return genWhile(ctx, ast);
109 } else if (ast.type == "IF") {
110 return genIf(ctx, ast);
111 } else if (ast.type == "RETURN") {
112 return genReturn(ctx, ast);
113 } else if (ast.type == "TEMPLATEDEF") {
114 return genTemplateDef(ctx, ast);
115 } else if (ast.type == "FUNCTIONDEF") {
116 return genFunctionDef(ctx, ast);
117 } else if (ast.type == "INCLUDE") {
118 return genInclude(ctx, ast);
119 } else if (ast.type == "ARRAY") {
120 return genArray(ctx, ast);
121 } else {
122 error(ctx, ast, "GEN -> Invalid AST node type: " + ast.type);
123 }
124}
125
126
127function error(ctx, ast, errStr) {
128 ctx.error = {
129 pos: {
130 first_line: ast.first_line,
131 first_column: ast.first_column,
132 last_line: ast.last_line,
133 last_column: ast.last_column
134 },
135 errStr: errStr,
136 ast: ast
137 };
138}
139
140
141function getScope(ctx, name) {
142 for (let i=ctx.scopes.length-1; i>=0; i--) {
143 if (ctx.scopes[i][name]) return ctx.scopes[i][name];
144 }
145 return null;
146}
147
148
149function genFunctionCall(ctx, ast) {
150 let S = "[";
151 for (let i=0; i<ast.params.length; i++) {
152 if (i>0) S += ",";
153 S += gen(ctx, ast.params[i]);
154 }
155 S+="]";
156
157 return `ctx.callFunction("${ast.name}", ${S})`;
158}
159
160function genBlock(ctx, ast) {
161 let body = "";
162 for (let i=0; i<ast.statements.length; i++) {
163 const l = gen(ctx, ast.statements[i]);
164 if (ctx.error) return;
165 if (l) {
166 body += l;
167 if (body[body.length-1] != "\n") body += ";\n";
168 }
169 }
170 return "{\n"+ident(body)+"}\n";
171}
172
173
174function genTemplateDef(ctx, ast) {
175 let S = `function ${ast.name}(ctx)\n`;
176
177 const newScope = {};
178 for (let i=0; i< ast.params.length; i++) {
179 newScope[ast.params[i]] = { type: "VARIABLE" };
180 }
181
182 ctx.scopes.push(newScope);
183 S += genBlock(ctx, ast.block);
184 S += "\n";
185 ctx.scopes.pop();
186
187// const scope = ctx.scopes[ctx.scopes.length-1];
188 const scope = ctx.scopes[0]; // Scope for templates is top
189
190 scope[ast.name] = {
191 type: "TEMPLATE"
192 };
193
194 ctx.templates[ast.name] = S;
195 return S;
196}
197
198function genFunctionDef(ctx, ast) {
199 let S = `function ${ast.name}(ctx) `;
200
201 const newScope = {};
202 const params = [];
203 for (let i=0; i< ast.params.length; i++) {
204 newScope[ast.params[i]] = { type: "VARIABLE" };
205 params.push(ast.params[i]);
206 }
207
208 ctx.scopes.push(newScope);
209 S += genBlock(ctx, ast.block);
210 ctx.scopes.pop();
211
212// const scope = ctx.scopes[0]; // Scope for templates is top
213 const scope = ctx.scopes[ctx.scopes.length-1];
214
215 scope[ast.name] = {
216 type: "FUNCTION"
217 };
218
219 ctx.functions[ast.name] = S;
220 ctx.functionParams[ast.name] = params;
221 return S;
222}
223
224function genFor(ctx, ast) {
225 const init = gen(ctx, ast.init);
226 if (ctx.error) return;
227 const condition = gen(ctx, ast.condition);
228 if (ctx.error) return;
229 const step = gen(ctx, ast.step);
230 if (ctx.error) return;
231 const body = gen(ctx, ast.body);
232 if (ctx.error) return;
233 return `for (${init};${condition};${step})\n${body}\n`;
234}
235
236function genWhile(ctx, ast) {
237 const condition = gen(ctx, ast.condition);
238 if (ctx.error) return;
239 const body = gen(ctx, ast.body);
240 if (ctx.error) return;
241 return `while (${condition}) ${body}\n`;
242}
243
244function genIf(ctx, ast) {
245 const condition = gen(ctx, ast.condition);
246 if (ctx.error) return;
247 const thenBody = gen(ctx, ast.then);
248 if (ctx.error) return;
249 const elseBody = gen(ctx, ast.else);
250 if (ctx.error) return;
251 return `if (${condition}) ${thenBody} else ${elseBody}\n`;
252}
253
254
255function genReturn(ctx, ast) {
256 const value = gen(ctx, ast.value);
257 if (ctx.error) return;
258 return `return ${value};`;
259}
260
261function genDeclareComponent(ctx, ast) {
262 const scope = ctx.scopes[ctx.scopes.length - 1];
263
264 if (ast.name.type != "VARIABLE") return error(ctx, ast, "Invalid component name");
265 if (getScope(ctx, ast.name.name)) return error(ctx, ast, "Name already exists: "+ast.name.name);
266
267 scope[ast.name.name] = {
268 type: "COMPONENT"
269 };
270
271 return "";
272}
273
274function genDeclareSignal(ctx, ast) {
275 const scope = ctx.scopes[ctx.scopes.length-1];
276
277 if (ast.name.type != "VARIABLE") return error(ctx, ast, "Invalid component name");
278 if (getScope(ctx, ast.name.name)) return error(ctx, ast, "Name already exists: "+ast.name.name);
279
280 scope[ast.name.name] = {
281 type: "SIGNAL"
282 };
283
284 return "";
285}
286
287function genDeclareVariable(ctx, ast) {
288 const scope = ctx.scopes[ctx.scopes.length-1];
289
290 if (ast.name.type != "VARIABLE") return error(ctx, ast, "Invalid component name");
291 if (getScope(ctx, ast.name.name)) return error(ctx, ast, "Name already exists: "+ast.name.name);
292
293 scope[ast.name.name] = {
294 type: "VARIABLE"
295 };
296
297 return "";
298}
299
300function genNumber(ctx, ast) {
301 return `"${ast.value.toString()}"`;
302}
303
304function genVariable(ctx, ast) {
305 const v = getScope(ctx, ast.name);
306
307 const sels = [];
308 for (let i=0; i<ast.selectors.length; i++) {
309 sels.push(gen(ctx, ast.selectors[i]));
310 if (ctx.error) return;
311 }
312
313
314 if (v.type == "VARIABLE") {
315 return `ctx.getVar("${ast.name}",[${sels.join(",")}])`;
316 } else if (v.type == "SIGNAL") {
317 return `ctx.getSignal("${ast.name}", [${sels.join(",")}])`;
318 } else {
319 error(ctx, ast, "Invalid Variable type");
320 }
321}
322
323function genPin(ctx, ast) {
324 let componentName = ast.component.name;
325 let componentSelectors = [];
326 for (let i=0; i<ast.component.selectors.length; i++) {
327 componentSelectors.push(gen(ctx, ast.component.selectors[i]));
328 }
329 componentSelectors = "["+ componentSelectors.join(",") + "]";
330 let pinName = ast.pin.name;
331 let pinSelectors = [];
332 for (let i=0; i<ast.pin.selectors.length; i++) {
333 pinSelectors.push(gen(ctx, ast.pin.selectors[i]));
334 }
335 pinSelectors = "["+ pinSelectors.join(",") + "]";
336 return `ctx.getPin("${componentName}", ${componentSelectors}, "${pinName}", ${pinSelectors})`;
337}
338
339function genVarAssignement(ctx, ast) {
340
341 const sels = [];
342 let vName;
343
344 if (ctx.error) return;
345
346 if (ast.values[0].type == "PIN") {
347 let componentName = ast.values[0].component.name;
348 let componentSelectors = [];
349 for (let i=0; i<ast.values[0].component.selectors.length; i++) {
350 componentSelectors.push(gen(ctx, ast.values[0].component.selectors[i]));
351 }
352 componentSelectors = "["+ componentSelectors.join(",") + "]";
353 let pinName = ast.values[0].pin.name;
354 let pinSelectors = [];
355 for (let i=0; i<ast.values[0].pin.selectors.length; i++) {
356 pinSelectors.push(gen(ctx, ast.values[0].pin.selectors[i]));
357 }
358 pinSelectors = "["+ pinSelectors.join(",") + "]";
359 const res = gen(ctx, ast.values[1]);
360 return `ctx.setPin("${componentName}", ${componentSelectors}, "${pinName}", ${pinSelectors}, ${res})`;
361 }
362
363 if (ast.values[0].type == "DECLARE") {
364 gen(ctx, ast.values[0]);
365 if (ctx.error) return;
366 vName = ast.values[0].name.name;
367 } else {
368 vName = ast.values[0].name;
369 for (let i=0; i<ast.values[0].selectors.length; i++) {
370 sels.push(gen(ctx, ast.values[0].selectors[i]));
371 if (ctx.error) return;
372 }
373 }
374
375
376 const v = getScope(ctx, vName);
377
378 // Component instantiation is already done.
379 if (v.type == "COMPONENT") return "";
380
381 const res = gen(ctx, ast.values[1]);
382 if (v.type == "VARIABLE") {
383 return `ctx.setVar("${vName}", [${sels.join(",")}], ${res})`;
384 } else if (v.type == "SIGNAL") {
385 return `ctx.setSignal("${vName}", [${sels.join(",")}], ${res})`;
386 } else {
387 return error(ctx, ast, "Assigning to invalid");
388 }
389}
390
391function genConstrain(ctx, ast) {
392 const a = gen(ctx, ast.values[0]);
393 if (ctx.error) return;
394 const b = gen(ctx, ast.values[1]);
395 if (ctx.error) return;
396 return `ctx.assert(${a}, ${b})`;
397}
398
399function genSignalAssignConstrain(ctx, ast) {
400 return genVarAssignement(ctx, ast) + ";\n" + genConstrain(ctx, ast);
401}
402
403function genVarAddAssignement(ctx, ast) {
404 return genVarAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "+", values: ast.values}]});
405}
406
407function genVarMulAssignement(ctx, ast) {
408 return genVarAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "*", values: ast.values}]});
409}
410
411function genPlusPlusRight(ctx, ast) {
412 return `(${genVarAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "+", values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}]}]})}).add(__P__).sub(bigInt(1)).mod(__P__)`;
413}
414
415function genPlusPlusLeft(ctx, ast) {
416 return genVarAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "+", values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}]}]});
417}
418
419function genAdd(ctx, ast) {
420 const a = gen(ctx, ast.values[0]);
421 if (ctx.error) return;
422 const b = gen(ctx, ast.values[1]);
423 if (ctx.error) return;
424 return `bigInt(${a}).add(bigInt(${b})).mod(__P__)`;
425}
426
427function genMul(ctx, ast) {
428 const a = gen(ctx, ast.values[0]);
429 if (ctx.error) return;
430 const b = gen(ctx, ast.values[1]);
431 if (ctx.error) return;
432 return `bigInt(${a}).mul(bigInt(${b})).mod(__P__)`;
433}
434
435function genSub(ctx, ast) {
436 const a = gen(ctx, ast.values[0]);
437 if (ctx.error) return;
438 const b = gen(ctx, ast.values[1]);
439 if (ctx.error) return;
440 return `bigInt(${a}).add(__P__).sub(bigInt(${b})).mod(__P__)`;
441}
442
443function genExp(ctx, ast) {
444 const a = gen(ctx, ast.values[0]);
445 if (ctx.error) return;
446 const b = gen(ctx, ast.values[1]);
447 if (ctx.error) return;
448 return `bigInt(${a}).modPow(bigInt(${b}), __P__)`;
449}
450
451function genBAnd(ctx, ast) {
452 const a = gen(ctx, ast.values[0]);
453 if (ctx.error) return;
454 const b = gen(ctx, ast.values[1]);
455 if (ctx.error) return;
456 return `bigInt(${a}).and(bigInt(${b})).and(__MASK__)`;
457}
458
459function genShl(ctx, ast) {
460 const a = gen(ctx, ast.values[0]);
461 if (ctx.error) return;
462 const b = gen(ctx, ast.values[1]);
463 if (ctx.error) return;
464 return `bigInt(${b}).greater(bigInt(256)) ? 0 : bigInt(${a}).shl(bigInt(${b})).and(__MASK__)`;
465}
466
467function genShr(ctx, ast) {
468 const a = gen(ctx, ast.values[0]);
469 if (ctx.error) return;
470 const b = gen(ctx, ast.values[1]);
471 if (ctx.error) return;
472 return `bigInt(${b}).greater(bigInt(256)) ? 0 : bigInt(${a}).shr(bigInt(${b})).and(__MASK__)`;
473}
474
475function genMod(ctx, ast) {
476 const a = gen(ctx, ast.values[0]);
477 if (ctx.error) return;
478 const b = gen(ctx, ast.values[1]);
479 if (ctx.error) return;
480 return `bigInt(${a}).mod(bigInt(${b}))`;
481}
482
483function genLt(ctx, ast) {
484 const a = gen(ctx, ast.values[0]);
485 if (ctx.error) return;
486 const b = gen(ctx, ast.values[1]);
487 if (ctx.error) return;
488 return `bigInt(${a}).lt(bigInt(${b})) ? 1 : 0`;
489}
490
491function genGt(ctx, ast) {
492 const a = gen(ctx, ast.values[0]);
493 if (ctx.error) return;
494 const b = gen(ctx, ast.values[1]);
495 if (ctx.error) return;
496 return `bigInt(${a}).gt(bigInt(${b})) ? 1 : 0`;
497}
498
499function genLte(ctx, ast) {
500 const a = gen(ctx, ast.values[0]);
501 if (ctx.error) return;
502 const b = gen(ctx, ast.values[1]);
503 if (ctx.error) return;
504 return `bigInt(${a}).lesserOrEquals(bigInt(${b})) ? 1 : 0`;
505}
506
507function genGte(ctx, ast) {
508 const a = gen(ctx, ast.values[0]);
509 if (ctx.error) return;
510 const b = gen(ctx, ast.values[1]);
511 if (ctx.error) return;
512 return `bigInt(${a}).greaterOrEquals(bigInt(${b})) ? 1 : 0`;
513}
514
515function genEq(ctx, ast) {
516 const a = gen(ctx, ast.values[0]);
517 if (ctx.error) return;
518 const b = gen(ctx, ast.values[1]);
519 if (ctx.error) return;
520 return `bigInt(${a}).eq(bigInt(${b})) ? 1 : 0`;
521}
522
523function genUMinus(ctx, ast) {
524 const a = gen(ctx, ast.values[0]);
525 if (ctx.error) return;
526 return `__P__.sub(bigInt(${a})).mod(__P__)`;
527}
528
529function genTerCon(ctx, ast) {
530 const a = gen(ctx, ast.values[0]);
531 if (ctx.error) return;
532 const b = gen(ctx, ast.values[1]);
533 if (ctx.error) return;
534 const c = gen(ctx, ast.values[2]);
535 if (ctx.error) return;
536 return `bigInt(${a}).neq(bigInt(0)) ? (${b}) : (${c})`;
537}
538
539function genInclude(ctx, ast) {
540 let body = genCode(ctx, ast.block);
541 return `// File: ${ast.file}\n` +body+"\n";
542}
543
544function genCode(ctx, ast) {
545 let body = "";
546 for (let i=0; i<ast.statements.length; i++) {
547 const l = gen(ctx, ast.statements[i]);
548 if (ctx.error) return;
549 if (l) {
550 body += l;
551 if (body[body.length-1] != "\n") body += ";\n";
552 }
553 }
554 return body;
555}
556
557function genArray(ctx, ast) {
558 let S = "[";
559 for (let i=0; i<ast.values.length; i++) {
560 if (i>0) S += ",";
561 S += gen(ctx, ast.values[i]);
562 }
563 S+="]";
564 return S;
565}
566