circom/src/c_gen.js
src/c_gen.jsRaw
1const bigInt = require("big-integer");
2const utils = require("./utils");
3const assert = require("assert");
4const iterateAST = require("./iterateast");
5
6module.exports.gen = gen;
7module.exports.newRef = newRef;
8module.exports.createRefs = createRefs;
9
10function newRef(ctx, type, name, value, sizes) {
11 let label;
12 if (!name) {
13 label = ctx.getUniqueName();
14 } else {
15 label = ctx.getUniqueName(name);
16 }
17 if (Array.isArray(sizes)) {
18 // sizes = sizes;
19 } else if (utils.isDefined(value)) {
20 sizes = utils.accSizes(utils.extractSizes(value));
21 } else {
22 sizes = [1, 0];
23 }
24
25 const refId = ctx.refs.length;
26 const entry = {
27 type: type,
28 used: false,
29 sizes: sizes,
30 label: label
31 };
32 if (utils.isDefined(value)) {
33 entry.value = utils.flatArray(value);
34 }
35
36 ctx.refs.push(entry);
37 return refId;
38}
39
40function instantiateRef(ctx, refId, initValue) {
41 const v = ctx.refs[refId];
42 if (v.used) return;
43 if (!v.sizes) v.sizes = [1,0];
44
45 if (v.type=="BIGINT") {
46 ctx.codeHeader += `PBigInt ${v.label} = ctx->allocBigInts(${v.sizes[0]});\n`;
47 ctx.codeFooter += `ctx->freeBigInts(${v.label}, ${v.sizes[0]});\n`;
48 } else if (v.type=="INT") {
49 ctx.codeHeader += `int ${v.label};\n`;
50 } else if (v.type=="SIZES") {
51 ctx.codeHeader += `Circom_Sizes ${v.label};\n`;
52 }
53 v.used = true;
54 if (utils.isDefined(initValue)) {
55 if (v.type == "BIGINT") {
56 for (let i=0; i<initValue.length; i++) {
57 if (utils.isDefined(initValue[i])) {
58 const c = `mpz_set_str(${v.label}[${i}], "${initValue[i].toString(10)}", 10);\n`;
59 ctx.code += c;
60 }
61 }
62 }
63 }
64}
65
66function instantiateConstant(ctx, value) {
67 const sizes = utils.accSizes(utils.extractSizes(value));
68 const flatedValue = utils.flatArray(value);
69 const label = ctx.getUniqueName("_const");
70 ctx.codeHeader += `PBigInt ${label};\n`;
71 ctx.codeHeader += `${label} = ctx->allocBigInts(${sizes[0]});\n`;
72 for (let i=0; i<flatedValue.length; i++) {
73 ctx.codeHeader += `mpz_set_str(${label}[${i}], "${flatedValue[i].toString(10)}", 10);\n`;
74 }
75 ctx.codeFooter += `ctx->freeBigInts(${label}, ${sizes[0]});\n`;
76 const refId = ctx.refs.length;
77 ctx.refs.push({
78 type: "BIGINT",
79 used: true,
80 sizes: sizes,
81 label: label
82 });
83 return refId;
84}
85
86
87function createRefs(ctx, ast) {
88 const scopeLabels = [];
89 iterateAST(ast, (ast, level) => {
90 while ((scopeLabels.length>0)&&(!scopeLabels[scopeLabels.length-1].startsWith(level))) {
91 ctx.scopes.pop();
92 scopeLabels.pop();
93 }
94 if (ast.type == "DECLARE") {
95 if (ctx.scopes[ctx.scopes.length-1][ast.name.name]) return ctx.throwError(ast, `Name already defined: ${ast.name.name}`);
96 for (let i=ctx.scopes.length-2; i>=0; i--) {
97 if (ctx.scopes[i][ast.name.name]) ctx.logWarning(ast, `Shadowing variable: ${ast.name.name}`);
98 }
99 let entry = {};
100 if (ast.declareType == "COMPONENT") {
101 entry.type= "COMPONENT";
102 entry.label = ast.name.name;
103 } else if ((ast.declareType == "SIGNALIN")||
104 (ast.declareType == "SIGNALOUT")||
105 (ast.declareType == "SIGNAL")) {
106 entry.type = "SIGNAL";
107 entry.label = ast.name.name;
108 } else if (ast.declareType == "VARIABLE") {
109 entry.type = "BIGINT";
110 entry.used = false;
111 entry.sizes = null;
112 entry.label = ctx.getUniqueName(ast.name.name);
113 } else {
114 return ctx.throwError(ast, "Invalid declaration: " + ast.declareType);
115 }
116
117 const refId = ctx.refs.length;
118 ctx.refs.push(entry);
119 ast.refId = refId;
120 ctx.scopes[ctx.scopes.length-1][ast.name.name] = refId;
121 } else if (["BLOCK", "FOR", "IF", "WHILE", "COMPUTE"].indexOf(ast.type) >= 0) {
122 scopeLabels.push(level);
123 ctx.scopes.push({});
124 } else if (ast.type == "VARIABLE") {
125 ast.refId = name2ref(ast.name);
126 }
127 });
128
129 function name2ref(n) {
130 for (let i=ctx.scopes.length-1; i>=0; i--) {
131 if (typeof ctx.scopes[i][n] !== "undefined") return ctx.scopes[i][n];
132 }
133 return -1;
134 }
135}
136
137function gen(ctx, ast) {
138 if ((ast.type == "NUMBER") ) {
139 return genNumber(ctx, ast);
140 } else if (ast.type == "VARIABLE") {
141 return genVariable(ctx, ast);
142 } else if (ast.type == "PIN") {
143 return genPin(ctx, ast);
144 } else if (ast.type == "OP") {
145 if (ast.op == "=") {
146 return genAssignement(ctx, ast);
147 } else if (ast.op == "<--") {
148 return genAssignement(ctx, ast);
149 } else if (ast.op == "<==") {
150 return genSignalAssignConstraint(ctx, ast);
151 } else if (ast.op == "===") {
152 return genConstraint(ctx, ast);
153 } else if (ast.op == "+=") {
154 return genVarAddAssignement(ctx, ast);
155 } else if (ast.op == "*=") {
156 return genVarMulAssignement(ctx, ast);
157 } else if (ast.op == "+") {
158 return genOp(ctx, ast, "add", 2);
159 } else if (ast.op == "-") {
160 return genOp(ctx, ast, "sub", 2);
161 } else if (ast.op == "UMINUS") {
162 return genOp(ctx, ast, "neg", 1);
163 } else if (ast.op == "*") {
164 return genOp(ctx, ast, "mul", 2);
165 } else if (ast.op == "%") {
166 return genOp(ctx, ast, "mod", 2);
167 } else if (ast.op == "PLUSPLUSRIGHT") {
168 return genOpOp(ctx, ast, "add", "RIGHT");
169 } else if (ast.op == "PLUSPLUSLEFT") {
170 return genOpOp(ctx, ast, "add", "LEFT");
171 } else if (ast.op == "MINUSMINUSRIGHT") {
172 return genOpOp(ctx, ast, "sub", "RIGHT");
173 } else if (ast.op == "MINUSMINUSLEFT") {
174 return genOpOp(ctx, ast, "sub", "LEFT");
175 } else if (ast.op == "**") {
176 return genOp(ctx, ast, "pow", 2);
177 } else if (ast.op == "/") {
178 return genOp(ctx, ast, "div", 2);
179 } else if (ast.op == "\\") {
180 return genOp(ctx, ast, "idiv", 2);
181 } else if (ast.op == "&") {
182 return genOp(ctx, ast, "band", 2);
183 } else if (ast.op == "|") {
184 return genOp(ctx, ast, "bor", 2);
185 } else if (ast.op == "^") {
186 return genOp(ctx, ast, "bxor", 2);
187 } else if (ast.op == "~") {
188 return genOp(ctx, ast, "bnot", 1);
189 } else if (ast.op == "&&") {
190 return genOp(ctx, ast, "land", 2);
191 } else if (ast.op == "||") {
192 return genOp(ctx, ast, "lor", 2);
193 } else if (ast.op == "!") {
194 return genOp(ctx, ast, "lnot", 1);
195 } else if (ast.op == "<<") {
196 return genOp(ctx, ast, "shl", 2);
197 } else if (ast.op == ">>") {
198 return genOp(ctx, ast, "shr", 2);
199 } else if (ast.op == "<") {
200 return genOp(ctx, ast, "lt", 2);
201 } else if (ast.op == ">") {
202 return genOp(ctx, ast, "gt", 2);
203 } else if (ast.op == "<=") {
204 return genOp(ctx, ast, "leq", 2);
205 } else if (ast.op == ">=") {
206 return genOp(ctx, ast, "geq", 2);
207 } else if (ast.op == "==") {
208 return genOp(ctx, ast, "eq", 2);
209 } else if (ast.op == "!=") {
210 return genOp(ctx, ast, "neq", 2);
211 } else if (ast.op == "?") {
212 return genTerCon(ctx, ast);
213 } else {
214 ctx.throwError(ast, "Invalid operation: " + ast.op);
215 }
216 } else if (ast.type == "DECLARE") {
217 if (ast.declareType == "COMPONENT") {
218 return genDeclareComponent(ctx, ast);
219 } else if ((ast.declareType == "SIGNALIN")||
220 (ast.declareType == "SIGNALOUT")||
221 (ast.declareType == "SIGNAL")) {
222 return genDeclareSignal(ctx, ast);
223 } else if (ast.declareType == "VARIABLE") {
224 return genDeclareVariable(ctx, ast);
225 } else {
226 ctx.throwError(ast, "Invalid declaration: " + ast.declareType);
227 }
228 } else if (ast.type == "FUNCTIONCALL") {
229 return genFunctionCall(ctx, ast);
230 } else if (ast.type == "BLOCK") {
231 return genBlock(ctx, ast);
232 } else if (ast.type == "COMPUTE") {
233 return gen(ctx, ast.body);
234 } else if (ast.type == "FOR") {
235 return genLoop(ctx, ast);
236 } else if (ast.type == "WHILE") {
237 return genLoop(ctx, ast);
238 } else if (ast.type == "IF") {
239 return genIf(ctx, ast);
240 } else if (ast.type == "RETURN") {
241 return genReturn(ctx, ast);
242 } else if (ast.type == "INCLUDE") {
243 return genInclude(ctx, ast);
244 } else if (ast.type == "ARRAY") {
245 return genArray(ctx, ast);
246 } else {
247 ctx.throwError(ast, "GEN -> Invalid AST node type: " + ast.type);
248 }
249}
250
251function genBlock(ctx, ast) {
252 ctx.scopes.push({});
253 const oldCode = ctx.code;
254 let res = null;
255 ctx.code = "";
256 for (let i=0; i<ast.statements.length; i++) {
257 if (["BLOCK", "COMPUTE", "FOR", "WHILE", "IF"].indexOf(ast.statements[i].type)<0) {
258 genSrcComment(ctx, ast.statements[i]);
259 }
260 res = gen(ctx, ast.statements[i]);
261 if (ctx.error) return;
262 }
263 ctx.code = oldCode + ctx.code;
264 ctx.scopes.pop();
265 return res;
266}
267
268function getSource(ctx, ast) {
269 let codes = [];
270 const fl= ast.first_line-1;
271 const ll = ast.last_line-1;
272 const fc = ast.first_column;
273 const lc = ast.last_column;
274 for (let i=fl; i<=ll; i++) {
275 const p1 = i==fl ? fc : 0;
276 const p2 = i==ll ? lc : -1;
277 codes.push(ctx.includedFiles[ctx.fileName][i].slice(p1, p2>=0 ? p2 : undefined));
278 }
279 return codes.join("\n");
280}
281
282function genSrcComment(ctx, ast) {
283 const code = getSource(ctx, ast);
284 ctx.code += "\n/* "+code+" */\n";
285}
286
287function genLoopSrcComment(ctx, ast) {
288 if (ast.type == "FOR") {
289 const init = getSource(ctx, ast.init);
290 const condition = getSource(ctx, ast.condition);
291 const step = getSource(ctx, ast.step);
292 ctx.code += `\n/* for (${init},${condition},${step}) */\n`;
293 } else if (ast.type == "WHILE") {
294 const condition = getSource(ctx, ast.condition);
295 ctx.code += `\n/* while (${condition}) */\n`;
296 } else {
297 assert(false, "Invalid loop type: "+ ast.type);
298 }
299}
300
301function genIfSrcComment(ctx, ast) {
302 const condition = getSource(ctx, ast.condition);
303 ctx.code += `\n/* if (${condition}) */\n`;
304}
305
306
307function genDeclareComponent(ctx, ast) {
308 return ast.refId;
309}
310
311function genDeclareSignal(ctx, ast) {
312 return ast.refId;
313}
314
315function genDeclareVariable(ctx, ast) {
316
317
318 const v = ctx.refs[ast.refId];
319
320 let sizes;
321 if (ast.name.selectors.length>0) {
322 sizes=[];
323 for (let i=0; i< ast.name.selectors.length; i++) {
324 const sizeRef = gen(ctx, ast.name.selectors[i]);
325 const size = ctx.refs[sizeRef];
326 if (size.sizes[0] != 1) return ctx.throwError(ast, "A selector cannot be an array");
327 if (size.used) return ctx.throwError(ast, "Variable size variables not allowed");
328 sizes.push(size.value[0].toJSNumber());
329 }
330 sizes = utils.accSizes(sizes);
331 } else {
332 sizes = null; // If not sizes, the sized are defined in the first assignement.
333 }
334
335 if ((!v.sizes)&&(sizes)) {
336 v.sizes = sizes;
337 v.value = new Array(sizes[0]);
338 }
339
340 if (v.sizes) {
341 if (!utils.sameSizes(v.sizes, sizes)) return ctx.throwError(ast, "Redefined a var with different sized");
342 }
343
344 return ast.refId;
345}
346
347function genNumber(ctx, ast) {
348 return newRef(ctx, "BIGINT", "_num", bigInt(ast.value));
349}
350
351
352
353function genGetOffset(ctx, refOffset, vSizes, sels) {
354
355 let rN = 0;
356 let rStr = "";
357 let offset;
358
359 if (refOffset) {
360 offset = ctx.refs[refOffset];
361 if (offset.used) {
362 rStr += offset.label;
363 } else {
364 rN += offset.value.toJSNumber();
365 }
366 }
367
368 if ((sels)&&(sels.length>0)) {
369
370 let iSizes;
371 if (Array.isArray(vSizes)) {
372 iSizes = {
373 used: false,
374 sizes: vSizes
375 };
376 } else {
377 iSizes = ctx.refs[vSizes];
378 }
379
380 for (let i=0; i<sels.length; i++) {
381 const idxRef = gen(ctx, sels[i]);
382 const iIdx = ctx.refs[idxRef];
383
384 if ((!iIdx.used) && (!iSizes.used)) {
385 rN = rN + iIdx.value * iSizes.sizes[i+1];
386 } else {
387 if (rN>0) {
388 if (rStr != "") rStr += " + ";
389 rStr += rN;
390 rN =0;
391 }
392
393 if (rStr != "") rStr += " + ";
394 if (iIdx.used) {
395 rStr += `ctx->field->toInt(${iIdx.label})`;
396 } else {
397 rStr += iIdx.value[0].toString();
398 }
399 rStr += "*";
400 if (iSizes.used) {
401 rStr += `${iSizes.label}[${i+1}]`;
402 } else {
403 rStr += iSizes.sizes[i+1];
404 }
405 }
406 }
407 }
408
409 if (rStr == "") {
410 const o = newRef(ctx, "INT", "_offset", rN);
411 return o;
412 } else {
413 if (rN>0) {
414 if (rStr != "") rStr += " + ";
415 rStr += rN;
416 rN =0;
417 }
418 if ((refOffset)&&(rStr == offset.label)) {
419 return offset.label;
420 } else {
421 const resRef = newRef(ctx, "INT", "_offset");
422 instantiateRef(ctx, resRef);
423 const res = ctx.refs[resRef];
424 ctx.code += `${res.label} = ${rStr};\n`;
425 return resRef;
426 }
427 }
428}
429
430function genVariable(ctx, ast) {
431 const v = ctx.refs[ast.refId];
432
433 const l = ast.selectors ? ast.selectors.length : 0;
434
435 if (v.type == "SIGNAL") {
436 let vOffset;
437 if (l>0) {
438 const vsOffset = genGetSigalOffset(ctx, -1, ast.name);
439 const vsSizes = genGetSignalSizes(ctx, -1, ast.name);
440 vOffset = genGetOffset(ctx, vsOffset, vsSizes, ast.selectors );
441 } else {
442 vOffset = genGetSigalOffset(ctx, -1, ast.name);
443 }
444 return genGetSignal(ctx, -1, vOffset);
445
446 } else if (v.type == "BIGINT") {
447 const refOffset = genGetOffset(ctx, 0, v.sizes, ast.selectors );
448 const offset = ctx.refs[refOffset];
449 if (v.used) {
450 if (offset.used) {
451 const refRes = newRef(ctx, "BIGINT", "_v", null, v.sizes.slice(l));
452 const res = ctx.refs[refRes];
453 res.used = true;
454 ctx.codeHeader += `PBigInt ${res.label};\n`;
455 ctx.code += `${res.label} = ${v.label} + ${offset.label};\n`;
456 return refRes;
457 } else if ((offset.value[0])||(l>0)) {
458 const refRes = newRef(ctx, "BIGINT", "_v", null, v.sizes.slice(l));
459 const res = ctx.refs[refRes];
460 res.used = true;
461 ctx.codeHeader += `PBigInt ${res.label};\n`;
462 ctx.code += `${res.label} = ${v.label} + ${offset.value[0]};\n`;
463 return refRes;
464 } else {
465 return ast.refId;
466 }
467 } else {
468 if (offset.used) {
469 instantiateRef(ctx, ast.refId, v.value);
470 const resRef = newRef(ctx, "BIGINT", "_v", null, v.sizes.slice(l));
471 const res = ctx.refs[resRef];
472 res.used = true;
473 ctx.codeHeader += `PBigInt ${res};\n`;
474 ctx.code += `${res.label} = ${v.label} + ${offset.label};\n`;
475 return res;
476 } else {
477 // return newSubRef(ctx, ast.name, ast.selectors);
478 return newRef(ctx, "BIGINT", "_v", v.value.slice(offset.value[0], offset.value[0] + v.sizes[l]),v.sizes.slice(l));
479 }
480 }
481 }
482}
483
484
485function genPin(ctx, ast) {
486 let vcIdx;
487 if (ast.component.selectors.length>0) {
488 const vcOffset = genGetSubComponentOffset(ctx, -1, ast.component.name);
489 const vcSizes = genGetSubComponentSizes(ctx, -1, ast.component.name);
490 vcIdx = genGetOffset(ctx, vcOffset, vcSizes, ast.component.selectors );
491 } else {
492 vcIdx = genGetSubComponentOffset(ctx, -1, ast.component.name);
493 }
494
495 let vsIdx;
496 if (ast.pin.selectors.length>0) {
497 const vsOffset = genGetSigalOffset(ctx, vcIdx, ast.pin.name);
498 const vsSizes = genGetSignalSizes(ctx, vcIdx, ast.pin.name);
499 vsIdx = genGetOffset(ctx, vsOffset, vsSizes, ast.pin.selectors );
500 } else {
501 vsIdx = genGetSigalOffset(ctx, vcIdx, ast.pin.name);
502 }
503
504 return genGetSignal(ctx, vcIdx, vsIdx);
505}
506
507function genGetSubComponentOffset(ctx, cIdxRef, label) {
508 const refOffset = newRef(ctx, "INT", "_compIdx");
509 const offset = ctx.refs[refOffset];
510 instantiateRef(ctx, refOffset);
511
512 const h = utils.fnvHash(label);
513 let s;
514 if (cIdxRef>=0) {
515 const cIdx = ctx.refs[cIdxRef];
516 s = cIdx.label;
517 } else {
518 s = "ctx->cIdx";
519 }
520 ctx.code += `${offset.label} = ctx->getSubComponentOffset(${s}, 0x${h}LL /* ${label} */);\n`;
521 return refOffset;
522}
523
524function genGetSubComponentSizes(ctx, cIdxRef, label) {
525 const sizesRef = newRef(ctx, "SIZES", "_compSizes");
526 const sizes = ctx.refs[sizesRef];
527 instantiateRef(ctx, sizesRef);
528
529 const h = utils.fnvHash(label);
530 let s;
531 if (cIdxRef>=0) {
532 const cIdx = ctx.refs[cIdxRef];
533 s = cIdx.label;
534 } else {
535 s = "ctx->cIdx";
536 }
537 ctx.code += `${sizes.label} = ctx->getSubComponentSizes(${s}, 0x${h}LL /* ${label} */);\n`;
538 return sizesRef;
539}
540
541function genGetSigalOffset(ctx, cIdxRef, label) {
542 const refOffset = newRef(ctx, "INT", "_sigIdx");
543 const offset = ctx.refs[refOffset];
544 instantiateRef(ctx, refOffset);
545
546 const h = utils.fnvHash(label);
547 let s;
548 if (cIdxRef>=0) {
549 const cIdx = ctx.refs[cIdxRef];
550 s = cIdx.label;
551 } else {
552 s = "ctx->cIdx";
553 }
554 ctx.code += `${offset.label} = ctx->getSignalOffset(${s}, 0x${h}LL /* ${label} */);\n`;
555 return refOffset;
556}
557
558function genGetSignalSizes(ctx, cIdxRef, label) {
559 const sizesRef = newRef(ctx, "SIZES", "_sigSizes");
560 const sizes = ctx.refs[sizesRef];
561 instantiateRef(ctx, sizesRef);
562
563 let s;
564 if (cIdxRef>=0) {
565 const cIdx = ctx.refs[cIdxRef];
566 s = cIdx.label;
567 } else {
568 s = "ctx->cIdx";
569 }
570 const h = utils.fnvHash(label);
571 ctx.code += `${sizes.label} = ctx->getSignalSizes(${s}, 0x${h}LL /* ${label} */);\n`;
572 return sizesRef;
573}
574
575function genSetSignal(ctx, cIdxRef, sIdxRef, valueRef) {
576 const v = ctx.refs[valueRef];
577 if (!v.used) {
578 instantiateRef(ctx, valueRef, v.value);
579 }
580 let s;
581 if (cIdxRef>=0) {
582 const cIdx = ctx.refs[cIdxRef];
583 s = cIdx.label;
584 } else {
585 s = "ctx->cIdx";
586 }
587 const sIdx = ctx.refs[sIdxRef];
588 ctx.code += `ctx->setSignal(${s}, ${sIdx.label}, ${v.label});\n`;
589
590 return valueRef;
591}
592
593function genGetSignal(ctx, cIdxRef, sIdxRef) {
594 const resRef = newRef(ctx, "BIGINT", "_sigValue");
595 const res = ctx.refs[resRef];
596 instantiateRef(ctx, resRef);
597 let s;
598 if (cIdxRef>=0) {
599 const cIdx = ctx.refs[cIdxRef];
600 s = cIdx.label;
601 } else {
602 s = "ctx->cIdx";
603 }
604 const sIdx = ctx.refs[sIdxRef];
605 ctx.code += `ctx->getSignal(${s}, ${sIdx.label}, ${res.label});\n`;
606 return resRef;
607}
608
609function genPinAssignement(ctx, ast) {
610 let vcIdx;
611 if (ast.values[0].component.selectors.length>0) {
612 const vcOffset = genGetSubComponentOffset(ctx, -1, ast.values[0].component.name);
613 const vcSizes = genGetSubComponentSizes(ctx, -1, ast.values[0].component.name);
614 vcIdx = genGetOffset(ctx, vcOffset, vcSizes, ast.values[0].component.selectors );
615 } else {
616 vcIdx = genGetSubComponentOffset(ctx, -1, ast.values[0].component.name);
617 }
618
619 let vsIdx;
620 if (ast.values[0].pin.selectors.length>0) {
621 const vsOffset = genGetSigalOffset(ctx, vcIdx, ast.values[0].pin.name);
622 const vsSizes = genGetSignalSizes(ctx, vcIdx, ast.values[0].pin.name);
623 vsIdx = genGetOffset(ctx, vsOffset, vsSizes, ast.values[0].pin.selectors );
624 } else {
625 vsIdx = genGetSigalOffset(ctx, vcIdx, ast.values[0].pin.name);
626 }
627
628 const vVal = gen(ctx, ast.values[1]);
629
630 genSetSignal(ctx, vcIdx, vsIdx, vVal);
631
632 return vVal;
633}
634
635function genSignalAssignmen(ctx, ast, lName, sels, rName) {
636 let vsIdx;
637 const signal = ctx.refs[lName];
638 if (sels.length>0) {
639 const vsOffset = genGetSigalOffset(ctx, -1, signal.label);
640 const vsSizes = genGetSignalSizes(ctx, -1, signal.label);
641 vsIdx = genGetOffset(ctx, vsOffset, vsSizes, sels );
642 } else {
643 vsIdx = genGetSigalOffset(ctx, -1, signal.label);
644 }
645
646 return genSetSignal(ctx, -1, vsIdx, rName);
647}
648
649function genVarAssignment(ctx, ast, lRef, sels, rRef) {
650
651 const left = ctx.refs[lRef];
652 const right = ctx.refs[rRef];
653 if (!utils.isDefined(left.sizes)) {
654 left.sizes = right.sizes;
655 left.value = new Array(left.sizes[0]);
656 }
657 if (!utils.sameSizes(left.sizes.slice(sels.length), right.sizes)) return ctx.throwError(ast, "Sizes do not match");
658
659 const oRef = genGetOffset(ctx, 0, left.sizes, sels);
660 const offset = ctx.refs[oRef];
661
662 let instantiated=false;
663 if (left.used) {
664 instantiateRef(ctx, rRef, right.value);
665 instantiated=true;
666 } else if (right.used) {
667 if (sels.length == 0) {
668 instantiateRef(ctx,lRef);
669 } else {
670 instantiateRef(ctx,lRef, left.value);
671 }
672 instantiated=true;
673 } else if (offset.used) {
674 instantiateRef(ctx, rRef, right.value);
675 if (sels.length == 0) {
676 instantiateRef(ctx,lRef);
677 } else {
678 instantiateRef(ctx,lRef, left.value);
679 }
680 instantiated=true;
681 }
682
683 if (instantiated) {
684 if (offset.used) {
685 ctx.code += `ctx->field->copyn(${left.label} + ${offset.label}, ${right.label}, ${right.sizes[0]});\n`;
686 } else {
687 if (offset.value[0]>0) {
688 ctx.code += `ctx->field->copyn(${left.label} + ${offset.value[0]}, ${right.label}, ${right.sizes[0]});\n`;
689 } else {
690 ctx.code += `ctx->field->copyn(${left.label}, ${right.label}, ${right.sizes[0]});\n`;
691 }
692 }
693 } else {
694 if (offset.value[0]>0) {
695 for (let i=0; i<right.sizes[0]; i++) left.value[offset.value[0] + i] = right.value[i];
696 } else {
697 for (let i=0; i<right.sizes[0]; i++) left.value[i] = right.value[i];
698 }
699 }
700}
701
702function genAssignement(ctx, ast) {
703
704 let lRef;
705 let sels;
706
707 if (ctx.error) return;
708
709 if (ast.values[0].type == "PIN") return genPinAssignement(ctx, ast);
710
711 if (ast.values[0].type == "DECLARE") {
712 lRef = gen(ctx, ast.values[0]);
713 if (ctx.error) return;
714 sels = [];
715 } else {
716 lRef = ast.values[0].refId;
717 sels = ast.values[0].selectors;
718 }
719
720
721 const left = ctx.refs[lRef];
722 if (!left) return ctx.throwError(ast, "Variable does not exists: "+ast.values[0].name);
723
724 // Component instantiation is already done.
725 if (left.type == "COMPONENT") return;
726
727 const rRef = gen(ctx, ast.values[1]);
728 if (ctx.error) return;
729
730 if (left.type == "SIGNAL") return genSignalAssignmen(ctx, ast, lRef, sels, rRef);
731
732 if (left.type == "BIGINT") return genVarAssignment(ctx, ast, lRef, sels, rRef);
733
734 return ctx.throwError(ast, "Assigning to invalid");
735}
736
737function genConstraint(ctx, ast) {
738 const aRef = gen(ctx, ast.values[0]);
739 const a = ctx.refs[aRef];
740 if (ctx.error) return;
741 const bRef = gen(ctx, ast.values[1]);
742 const b = ctx.refs[bRef];
743 if (ctx.error) return;
744 const strErr = ast.fileName + ":" + ast.first_line + ":" + ast.first_column;
745 instantiateRef(ctx, aRef);
746 instantiateRef(ctx, bRef);
747 ctx.code += `ctx->checkConstraint(${a.label}, ${b.label}, "${strErr}");`;
748}
749
750
751function genArray(ctx, ast) {
752 let subSizes;
753 let instantiate = false;
754 if (ast.values.length == 0) return ctx.throwError(ast, "Arrays with zero elements not allowed");
755 const value = [];
756 const refs = [];
757 for (let i=0; i<ast.values.length; i++) {
758 const eRef = gen(ctx, ast.values[i]);
759 const e = ctx.refs[eRef];
760
761 if (i==0) {
762 subSizes = e.sizes;
763 } else {
764 if (!utils.sameSizes(subSizes, e.sizes)) return ctx.throwError(ast, "Heteroeneus array not allowed");
765 }
766 if (e.used) {
767 instantiate = true;
768 }
769 if (!instantiate) {
770 value.push(...e.value);
771 }
772 refs.push(eRef);
773 }
774
775 const newSize = [subSizes[0]*ast.values.length , ...subSizes];
776
777 if (instantiate) {
778 const rRef = newRef(ctx, "BIGINT", "_arr", null, newSize);
779 instantiateRef(ctx, rRef);
780 for (let i=0; i<ast.values.length; i++) {
781 const v = ctx.refs[refs[i]];
782 const r = ctx.refs[rRef];
783 ctx.code += `ctx->field->copyn(${r.label}+${i*subSizes[0]}, ${v.label}, ${subSizes[0]});\n`;
784 }
785 return rRef;
786 } else {
787 const rRef = newRef(ctx, "BIGINT", "_arr", value, newSize);
788 return rRef;
789 }
790
791}
792
793
794function genFunctionCall(ctx, ast) {
795 const params = [];
796 for (let i=0; i<ast.params.length; i++) {
797 const pRef = gen(ctx, ast.params[i]);
798 params.push(ctx.refs[pRef]);
799 }
800
801 const fn = ctx.buildFunction(ast.name, params);
802 if (ctx.error) return;
803
804 if (fn.type == "VARVAL_CONSTSIZE") {
805 const resRef = newRef(ctx, "BIGINT", `_ret${ast.name}Sizes`, null, fn.returnSizes);
806 const res = ctx.refs[resRef];
807 instantiateRef(ctx, resRef);
808
809 ctx.code +=`${fn.fnName}(ctx, ${res.label}`;
810 for (let i=0; i<params.length; i++) {
811 if (params[i].used) ctx.code+=`,${params[i].label}`;
812 }
813 ctx.code+=");\n";
814
815 return resRef;
816 } else {
817 const res = newRef(ctx, "BIGINT", "_retVal", fn.returnValue, fn.returnSizes);
818 return res;
819 }
820}
821
822function enterConditionalCode(ctx, ast) {
823 if (!ctx.conditionalCode) {
824 iterateAST(ast, (ast) => {
825 if (ast.type == "OP") {
826 if (["=", "+=", "*=", "PLUSPLUSLEFT", "PLUSPLUSRIGHT", "MINUSMINUSLEFT", "MINUSMINUSRIGHT"].indexOf(ast.op) >= 0) {
827 let refId;
828 refId = ast.values[0].refId;
829 const ref = ctx.refs[refId];
830 instantiateRef(ctx, refId, ref.value);
831 }
832 }
833 });
834 ctx.conditionalCode = 1;
835 } else {
836 ctx.conditionalCode ++;
837 }
838}
839
840function leaveConditionalCode(ctx) {
841 assert(ctx.conditionalCode, "Leaving conditional code too many times");
842 ctx.conditionalCode --;
843 if (!ctx.conditionalCode) {
844 delete ctx.conditionalCode;
845 }
846}
847
848function genLoop(ctx, ast) {
849 genLoopSrcComment(ctx, ast);
850 let inLoop = false;
851
852 if (ast.init) {
853 gen(ctx, ast.init);
854 if (ctx.error) return;
855 }
856
857 let end=false;
858 let condVarRef;
859 let condVar;
860
861
862 const condRef = gen(ctx, ast.condition);
863 if (ctx.error) return;
864
865 const cond = ctx.refs[condRef];
866 if (!utils.sameSizes(cond.sizes, [1,0])) return ctx.throwError(ast.condition, "Operation cannot be done on an array");
867
868 if (cond.used) {
869 inLoop = true;
870 enterConditionalCode(ctx, ast);
871 condVarRef = newRef(ctx, "INT", "_cond");
872 condVar = ctx.refs[condVarRef];
873 instantiateRef(ctx, condVarRef);
874
875 ctx.code +=
876 `${condVar.label} = ctx->field->isTrue(${cond.label});\n` +
877 `while (${condVar.label}) {\n`;
878 } else {
879 if (!utils.isDefined(cond.value)) return ctx.throwError(ast, "condition value not assigned");
880 if (cond.value[0].isZero()) end=true;
881 }
882
883
884 while (!end) {
885
886 const oldCode = ctx.code;
887 ctx.code = "";
888
889 if (ast.body.type != "BLOCK") genSrcComment(ctx, ast.body);
890 gen(ctx, ast.body);
891 if (ctx.error) return;
892
893 if (ast.step) {
894 gen(ctx, ast.step);
895 if (ctx.error) return;
896 }
897
898 const condRef2 = gen(ctx, ast.condition);
899 if (ctx.error) return;
900
901 const cond2 = ctx.refs[condRef2];
902
903 if ((!cond2.used) &&(haveCode(ctx.code))) {
904 instantiateRef(ctx, condRef2, cond2.value);
905 }
906
907 if (!inLoop) {
908 if (cond2.used) {
909 ctx.code = oldCode + ctx.code;
910 inLoop = true;
911 enterConditionalCode(ctx, ast);
912 condVarRef = newRef(ctx, "INT", "_cond");
913 condVar = ctx.refs[condVarRef];
914 instantiateRef(ctx, condVarRef);
915
916 ctx.code =
917 oldCode +
918 ctx.code +
919 `${condVar.label} = ctx->field->isTrue(${cond2.label});\n` +
920 `while (${condVar.label}) {\n`;
921 } else {
922 ctx.code = oldCode + ctx.code;
923 if (cond2.value[0].isZero()) end=true;
924 }
925 } else {
926 ctx.code =
927 oldCode +
928 utils.ident(
929 ctx.code +
930 `${condVar.label} = ctx->field->isTrue(${cond2.label});\n`);
931 end=true;
932 }
933 }
934 if (inLoop) {
935 ctx.code += "}\n";
936 leaveConditionalCode(ctx);
937 }
938 ctx.scopes.pop();
939
940 function haveCode(c) {
941 return c.replace(/\/\*[\s\S]*?\*\/|\/\/.*/g, "").trim() != "";
942 }
943}
944
945function genIf(ctx, ast) {
946 genIfSrcComment(ctx, ast);
947 const condRef = gen(ctx, ast.condition);
948 if (ctx.error) return;
949 const cond = ctx.refs[condRef];
950 if (!utils.sameSizes(cond.sizes, [1,0])) return ctx.throwError(ast.condition, "Operation cannot be done on an array");
951
952 if (cond.used) {
953 enterConditionalCode(ctx, ast);
954
955 ctx.code += `if (ctx->field->isTrue(${cond.label})) {\n`;
956
957 const oldCode = ctx.code;
958 ctx.code = "";
959
960 gen(ctx, ast.then);
961 if (ctx.error) return;
962
963 ctx.code = oldCode + utils.ident(ctx.code);
964
965 if (ast.else) {
966 ctx.code += "} else {\n";
967 const oldCode = ctx.code;
968 ctx.code = "";
969 gen(ctx, ast.else);
970 if (ctx.error) return;
971 ctx.code = oldCode + utils.ident(ctx.code);
972 }
973
974 ctx.code += "}\n";
975
976 } else {
977 if (!utils.isDefined(cond.value)) return ctx.throwError(ast, "condition value not assigned");
978 if (!cond.value[0].isZero()) {
979 gen(ctx, ast.then);
980 } else {
981 if (ast.else) {
982 gen(ctx, ast.else);
983 }
984 }
985 }
986}
987
988
989function genReturn(ctx, ast) {
990 const vRef = gen(ctx, ast.value);
991 const v= ctx.refs[vRef];
992 if (ctx.returnSizes) {
993 if (!utils.sizesEqual(v.sizes, ctx.returnSizes)) return ctx.throwError(ast, "Diferent return sizes");
994 } else {
995 ctx.returnSizes = v.sizes;
996 }
997 if (ctx.conditionalCode) {
998 instantiateRef(ctx, vRef, v.value);
999 }
1000 if (v.used) {
1001 ctx.code += `ctx->field->copyn(__retValue, ${v.label}, ${v.sizes[0]});\n`;
1002 } else {
1003 if (!utils.isDefined(v.value)) return ctx.throwError(ast, "Returning an unknown value");
1004 if (!utils.isDefined(ctx.returnValue)) {
1005 ctx.returnValue = v.value;
1006 }
1007 }
1008 ctx.code += "goto returnFunc;\n";
1009 return vRef;
1010}
1011
1012
1013
1014function genSignalAssignConstraint(ctx, ast) {
1015 const res = genAssignement(ctx, ast);
1016 // genConstraint(ctx, ast);
1017 return res;
1018 // return genVarAssignement(ctx, ast);
1019}
1020
1021function genVarAddAssignement(ctx, ast) {
1022 return genAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "+", values: ast.values}]});
1023}
1024
1025function genVarMulAssignement(ctx, ast) {
1026 return genAssignement(ctx, {values: [ast.values[0], {type: "OP", op: "*", values: ast.values}]});
1027}
1028
1029function genOpOp(ctx, ast, op, lr) {
1030
1031 if (ast.values[0].type != "VARIABLE") return ctx.throwError(ast, "incrementing a non variable");
1032
1033 const vRef = ast.values[0].refId;
1034
1035 const vevalRef = gen(ctx, ast.values[0]);
1036 if (ctx.error) return;
1037 const veval = ctx.refs[vevalRef];
1038
1039 if (veval.type != "BIGINT") return ctx.throwError(ast, "incrementing a non variable");
1040
1041 const resRef = newRef(ctx, "BIGINT", "_tmp");
1042 const res = ctx.refs[resRef];
1043 if (veval.used) {
1044 instantiateRef(ctx, resRef);
1045 ctx.code += `ctx->field->${op}(${res.label}, ${veval.label}, &(ctx->field->one));\n`;
1046 } else {
1047 res.value = [ctx.field[op](veval.value[0], bigInt(1))];
1048 }
1049 genVarAssignment(ctx, ast, vRef, ast.values[0].selectors, resRef);
1050 if (lr == "RIGHT") {
1051 return vevalRef;
1052 } else if (lr == "LEFT") {
1053 return resRef;
1054 }
1055}
1056
1057function genOp(ctx, ast, op, nOps) {
1058 const vals = [];
1059 const valRefs = [];
1060
1061 var anyUsed=false;
1062
1063 for (let i=0; i<nOps; i++) {
1064 const ref = gen(ctx, ast.values[i]);
1065 if (ctx.error) return;
1066 let v = ctx.refs[ref];
1067 valRefs.push(ref);
1068 vals.push(v);
1069
1070 if (!utils.sameSizes(v.sizes, [1,0])) return ctx.throwError(ast, "Operation cannot be done on an array");
1071 if ( (!v.used)
1072 &&( (!utils.isDefined(v.value))
1073 ||(!utils.isDefined(v.value[0]))))
1074 return ctx.throwError(ast, "Using a not assigned varialble: ");
1075
1076 if (v.used) anyUsed=true;
1077 }
1078
1079 let rRef;
1080 if (anyUsed) {
1081 for (let i=0; i<nOps; i++) {
1082 if (!vals[i].used) {
1083 valRefs[i] = instantiateConstant(ctx, vals[i].value);
1084 vals[i] = ctx.refs[valRefs[i]];
1085 }
1086 }
1087
1088 rRef = newRef(ctx, "BIGINT", "_tmp");
1089 instantiateRef(ctx, rRef);
1090 const r = ctx.refs[rRef];
1091 let c = `ctx->field->${op}(${r.label}`;
1092 for (let i=0; i<nOps; i++) {
1093 c+=`,${vals[i].label}`;
1094 }
1095 c += ");\n";
1096 ctx.code += c;
1097 } else {
1098 const params = [];
1099 for (let i=0; i<nOps; i++) {
1100 params.push(vals[i].value[0]);
1101 }
1102 rRef = newRef(ctx, "BIGINT", "_tmp", ctx.field[op](...params));
1103 }
1104 return rRef;
1105}
1106
1107
1108function genTerCon(ctx, ast) {
1109 const condRef = gen(ctx, ast.values[0]);
1110 if (ctx.error) return;
1111 const cond = ctx.refs[condRef];
1112 if (!utils.sameSizes(cond.sizes, [1,0])) return ctx.throwError(ast.condition, "Operation cannot be done on an array");
1113
1114 let oldCode;
1115 if (cond.used) {
1116 enterConditionalCode(ctx, ast);
1117
1118 const rLabel = ctx.getUniqueName("_ter");
1119
1120 ctx.codeHeader += `PBigInt ${rLabel};\n`;
1121 ctx.code += `if (ctx->field->isTrue(${cond.label})) {\n`;
1122
1123 oldCode = ctx.code;
1124 ctx.code = "";
1125
1126 const thenRef = gen(ctx, ast.values[1]);
1127 if (ctx.error) return;
1128 const then = ctx.refs[thenRef];
1129
1130 ctx.code = oldCode + utils.ident(ctx.code);
1131
1132 ctx.code += `${rLabel} = ${then.label};\n`;
1133
1134 ctx.code += "} else {\n";
1135
1136 oldCode = ctx.code;
1137 ctx.code = "";
1138 const elseRef = gen(ctx, ast.values[2]);
1139 if (ctx.error) return;
1140 const els = ctx.refs[elseRef];
1141
1142 ctx.code = oldCode + utils.ident(ctx.code);
1143
1144 ctx.code += `${rLabel} = ${els.label};\n`;
1145
1146 ctx.code += "}\n";
1147
1148
1149 if (!utils.sameSizes(then.sizes, els.sizes)) return ctx.throwError(ast, "Ternary op must return the same sizes");
1150
1151 const refId = ctx.refs.length;
1152 ctx.refs.push({
1153 type: "BIGINT",
1154 sizes: then.sizes,
1155 used: true,
1156 label: rLabel
1157 });
1158
1159 return refId;
1160
1161 } else {
1162 if (!utils.isDefined(cond.value)) return ctx.throwError(ast, "condition value not assigned");
1163 if (!cond.value[0].isZero()) {
1164 return gen(ctx, ast.values[1]);
1165 } else {
1166 return gen(ctx, ast.values[2]);
1167 }
1168 }
1169}
1170
1171function genInclude(ctx, ast) {
1172 return ast.block ? gen(ctx, ast.block) : "";
1173}
1174
1175