arnaucube
arnaucube/circomPublic Self-hosted repository
circom/src/gencode.js
src/gencode.jsRaw
  1/*
  2    Copyright 2018 0KIMS association.
  3
  4    This file is part of circom (Zero Knowledge Circuit Compiler).
  5
  6    circom 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    circom 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 circom. If not, see <https://www.gnu.org/licenses/>.
 18*/
 19
 20const bigInt = require("big-integer");
 21
 22module.exports = gen;
 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 genDiv(ctx, ast);
 70        } else if (ast.op == "&") {
 71            return genBAnd(ctx, ast);
 72        } else if (ast.op == "<<") {
 73            return genShl(ctx, ast);
 74        } else if (ast.op == ">>") {
 75            return genShr(ctx, ast);
 76        } else if (ast.op == "<") {
 77            return genLt(ctx, ast);
 78        } else if (ast.op == ">") {
 79            return genGt(ctx, ast);
 80        } else if (ast.op == "<=") {
 81            return genLte(ctx, ast);
 82        } else if (ast.op == ">=") {
 83            return genGte(ctx, ast);
 84        } else if (ast.op == "==") {
 85            return genEq(ctx, ast);
 86        } else if (ast.op == "?") {
 87            return genTerCon(ctx, ast);
 88        } else {
 89            error(ctx, ast, "Invalid operation: " + ast.op);
 90        }
 91    } else if (ast.type == "DECLARE") {
 92        if (ast.declareType == "COMPONENT") {
 93            return genDeclareComponent(ctx, ast);
 94        } else if ((ast.declareType == "SIGNALIN")||
 95                   (ast.declareType == "SIGNALOUT")||
 96                   (ast.declareType == "SIGNAL")) {
 97            return genDeclareSignal(ctx, ast);
 98        } else if (ast.declareType == "VARIABLE") {
 99            return genDeclareVariable(ctx, ast);
100        } else {
101            error(ctx, ast, "Invalid declaration: " + ast.declareType);
102        }
103    } else if (ast.type == "FUNCTIONCALL") {
104        return genFunctionCall(ctx, ast);
105    } else if (ast.type == "BLOCK") {
106        return genBlock(ctx, ast);
107    } else if (ast.type == "FOR") {
108        return genFor(ctx, ast);
109    } else if (ast.type == "WHILE") {
110        return genWhile(ctx, ast);
111    } else if (ast.type == "IF") {
112        return genIf(ctx, ast);
113    } else if (ast.type == "RETURN") {
114        return genReturn(ctx, ast);
115    } else if (ast.type == "TEMPLATEDEF") {
116        return genTemplateDef(ctx, ast);
117    } else if (ast.type == "FUNCTIONDEF") {
118        return genFunctionDef(ctx, ast);
119    } else if (ast.type == "INCLUDE") {
120        return genInclude(ctx, ast);
121    } else if (ast.type == "ARRAY") {
122        return genArray(ctx, ast);
123    } else {
124        error(ctx, ast, "GEN -> Invalid AST node type: " + ast.type);
125    }
126}
127
128
129function error(ctx, ast, errStr) {
130    ctx.error = {
131        pos:   {
132            first_line: ast.first_line,
133            first_column: ast.first_column,
134            last_line: ast.last_line,
135            last_column: ast.last_column
136        },
137        errStr: errStr,
138        ast: ast
139    };
140}
141
142
143function getScope(ctx, name) {
144    for (let i=ctx.scopes.length-1; i>=0; i--) {
145        if (ctx.scopes[i][name]) return ctx.scopes[i][name];
146    }
147    return null;
148}
149
150
151function genFunctionCall(ctx, ast) {
152    let S = "[";
153    for (let i=0; i<ast.params.length; i++) {
154        if (i>0) S += ",";
155        S += gen(ctx, ast.params[i]);
156    }
157    S+="]";
158
159    return `ctx.callFunction("${ast.name}", ${S})`;
160}
161
162function genBlock(ctx, ast) {
163    let body = "";
164    for (let i=0; i<ast.statements.length; i++) {
165        const l = gen(ctx, ast.statements[i]);
166        if (ctx.error) return;
167        if (l) {
168            body += l;
169            if (body[body.length-1] != "\n") body += ";\n";
170        }
171    }
172    return "{\n"+ident(body)+"}\n";
173}
174
175function genTemplateDef(ctx, ast) {
176    let S = "function(ctx) ";
177
178    const newScope = {};
179    for (let i=0; i< ast.params.length; i++) {
180        newScope[ast.params[i]] = { type: "VARIABLE" };
181    }
182
183    ctx.scopes.push(newScope);
184    S += genBlock(ctx, ast.block);
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 "";
196}
197
198function genFunctionDef(ctx, ast) {
199    let S = "function(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 "";
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 }\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}) {\n${body}\n}\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}) {\n${thenBody}\n} else {\n${elseBody}\n}\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 genDiv(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
449    return `bigInt(${a}).mul( bigInt(${b}).inverse(__P__) ).mod(__P__)`;
450}
451
452function genExp(ctx, ast) {
453    const a = gen(ctx, ast.values[0]);
454    if (ctx.error) return;
455    const b = gen(ctx, ast.values[1]);
456    if (ctx.error) return;
457    return `bigInt(${a}).modPow(bigInt(${b}), __P__)`;
458}
459
460function genBAnd(ctx, ast) {
461    const a = gen(ctx, ast.values[0]);
462    if (ctx.error) return;
463    const b = gen(ctx, ast.values[1]);
464    if (ctx.error) return;
465    return `bigInt(${a}).and(bigInt(${b})).and(__MASK__)`;
466}
467
468function genShl(ctx, ast) {
469    const a = gen(ctx, ast.values[0]);
470    if (ctx.error) return;
471    const b = gen(ctx, ast.values[1]);
472    if (ctx.error) return;
473    return `bigInt(${b}).greater(bigInt(256)) ? 0 : bigInt(${a}).shl(bigInt(${b})).and(__MASK__)`;
474}
475
476function genShr(ctx, ast) {
477    const a = gen(ctx, ast.values[0]);
478    if (ctx.error) return;
479    const b = gen(ctx, ast.values[1]);
480    if (ctx.error) return;
481    return `bigInt(${b}).greater(bigInt(256)) ? 0 : bigInt(${a}).shr(bigInt(${b})).and(__MASK__)`;
482}
483
484function genMod(ctx, ast) {
485    const a = gen(ctx, ast.values[0]);
486    if (ctx.error) return;
487    const b = gen(ctx, ast.values[1]);
488    if (ctx.error) return;
489    return `bigInt(${a}).mod(bigInt(${b}))`;
490}
491
492function genLt(ctx, ast) {
493    const a = gen(ctx, ast.values[0]);
494    if (ctx.error) return;
495    const b = gen(ctx, ast.values[1]);
496    if (ctx.error) return;
497    return `bigInt(${a}).lt(bigInt(${b})) ? 1 : 0`;
498}
499
500function genGt(ctx, ast) {
501    const a = gen(ctx, ast.values[0]);
502    if (ctx.error) return;
503    const b = gen(ctx, ast.values[1]);
504    if (ctx.error) return;
505    return `bigInt(${a}).gt(bigInt(${b})) ? 1 : 0`;
506}
507
508function genLte(ctx, ast) {
509    const a = gen(ctx, ast.values[0]);
510    if (ctx.error) return;
511    const b = gen(ctx, ast.values[1]);
512    if (ctx.error) return;
513    return `bigInt(${a}).lesserOrEquals(bigInt(${b})) ? 1 : 0`;
514}
515
516function genGte(ctx, ast) {
517    const a = gen(ctx, ast.values[0]);
518    if (ctx.error) return;
519    const b = gen(ctx, ast.values[1]);
520    if (ctx.error) return;
521    return `bigInt(${a}).greaterOrEquals(bigInt(${b})) ? 1 : 0`;
522}
523
524function genEq(ctx, ast) {
525    const a = gen(ctx, ast.values[0]);
526    if (ctx.error) return;
527    const b = gen(ctx, ast.values[1]);
528    if (ctx.error) return;
529    return `bigInt(${a}).eq(bigInt(${b})) ? 1 : 0`;
530}
531
532function genUMinus(ctx, ast) {
533    const a = gen(ctx, ast.values[0]);
534    if (ctx.error) return;
535    return `__P__.sub(bigInt(${a})).mod(__P__)`;
536}
537
538function genTerCon(ctx, ast) {
539    const a = gen(ctx, ast.values[0]);
540    if (ctx.error) return;
541    const b = gen(ctx, ast.values[1]);
542    if (ctx.error) return;
543    const c = gen(ctx, ast.values[2]);
544    if (ctx.error) return;
545    return `bigInt(${a}).neq(bigInt(0)) ? (${b}) : (${c})`;
546}
547
548function genInclude(ctx, ast) {
549    return ast.block ? gen(ctx, ast.block) : "";
550}
551
552function genArray(ctx, ast) {
553    let S = "[";
554    for (let i=0; i<ast.values.length; i++) {
555        if (i>0) S += ",";
556        S += gen(ctx, ast.values[i]);
557    }
558    S+="]";
559    return S;
560}
561