arnaucube
arnaucube/circomPublic Self-hosted repository
circom/src/exec.js
src/exec.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 path = require("path");
  21const fs = require("fs");
  22
  23const bigInt = require("big-integer");
  24const __P__ = new bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
  25const __MASK__ = new bigInt(2).pow(253).minus(1);
  26
  27const lc = require("./lcalgebra");
  28const parser = require("../parser/jaz.js").parser;
  29
  30/* TODO: Add lines information
  31
  32function setLines(dst, first, last) {
  33    last = last || first;
  34    dst.first_line = first.first_line;
  35    dst.first_column = first.first_column;
  36    dst.last_line = last.last_line;
  37    dst.last_column = last.last_column;
  38}
  39*/
  40
  41module.exports = exec;
  42
  43
  44function exec(ctx, ast) {
  45    if (!ast) {
  46        return error(ctx, ast, "Null AST");
  47    }
  48    if ((ast.type == "NUMBER") || (ast.type == "LINEARCOMBINATION") || (ast.type =="SIGNAL") || (ast.type == "QEQ")) {
  49        return ast;
  50    } else if (ast.type == "VARIABLE") {
  51        return execVariable(ctx, ast);
  52    } else if (ast.type == "PIN") {
  53        return execPin(ctx, ast);
  54    } else if (ast.type == "OP") {
  55        if (ast.op == "=") {
  56            return execVarAssignement(ctx, ast);
  57        } else if (ast.op == "<--") {
  58            return execSignalAssign(ctx, ast);
  59        } else if (ast.op == "<==") {
  60            return execSignalAssignConstrain(ctx, ast);
  61        } else if (ast.op == "===") {
  62            return execConstrain(ctx, ast);
  63        } else if (ast.op == "+=") {
  64            return execVarAddAssignement(ctx, ast);
  65        } else if (ast.op == "*=") {
  66            return execVarMulAssignement(ctx, ast);
  67        } else if (ast.op == "+") {
  68            return execAdd(ctx, ast);
  69        } else if (ast.op == "-") {
  70            return execSub(ctx, ast);
  71        } else if (ast.op == "UMINUS") {
  72            return execUMinus(ctx, ast);
  73        } else if (ast.op == "*") {
  74            return execMul(ctx, ast);
  75        } else if (ast.op == "%") {
  76            return execMod(ctx, ast);
  77        } else if (ast.op == "PLUSPLUSRIGHT") {
  78            return execPlusPlusRight(ctx, ast);
  79        } else if (ast.op == "PLUSPLUSLEFT") {
  80            return execPlusPlusLeft(ctx, ast);
  81        } else if (ast.op == "MINUSMINUSRIGHT") {
  82            return execMinusMinusRight(ctx, ast);
  83        } else if (ast.op == "MINUSMINUSLEFT") {
  84            return execMinusMinusLeft(ctx, ast);
  85        } else if (ast.op == "/") {
  86            return execDiv(ctx, ast);
  87        } else if (ast.op == "\\") {
  88            return execIDiv(ctx, ast);
  89        } else if (ast.op == "**") {
  90            return execExp(ctx, ast);
  91        } else if (ast.op == "&") {
  92            return execBAnd(ctx, ast);
  93        } else if (ast.op == "&&") {
  94            return execAnd(ctx, ast);
  95        } else if (ast.op == "||") {
  96            return execOr(ctx, ast);
  97        } else if (ast.op == "<<") {
  98            return execShl(ctx, ast);
  99        } else if (ast.op == ">>") {
 100            return execShr(ctx, ast);
 101        } else if (ast.op == "<") {
 102            return execLt(ctx, ast);
 103        } else if (ast.op == ">") {
 104            return execGt(ctx, ast);
 105        } else if (ast.op == "<=") {
 106            return execLte(ctx, ast);
 107        } else if (ast.op == ">=") {
 108            return execGte(ctx, ast);
 109        } else if (ast.op == "==") {
 110            return execEq(ctx, ast);
 111        } else if (ast.op == "!=") {
 112            return execNeq(ctx, ast);
 113        } else if (ast.op == "?") {
 114            return execTerCon(ctx, ast);
 115        } else {
 116            error(ctx, ast, "Invalid operation: " + ast.op);
 117        }
 118    } else if (ast.type == "DECLARE") {
 119        if (ast.declareType == "COMPONENT") {
 120            return execDeclareComponent(ctx, ast);
 121        } else if ((ast.declareType == "SIGNALIN")||
 122                   (ast.declareType == "SIGNALOUT")||
 123                   (ast.declareType == "SIGNAL")) {
 124            return execDeclareSignal(ctx, ast);
 125        } else if (ast.declareType == "VARIABLE") {
 126            return execDeclareVariable(ctx, ast);
 127        } else {
 128            error(ctx, ast, "Invalid declaration: " + ast.declareType);
 129        }
 130    } else if (ast.type == "FUNCTIONCALL") {
 131        return execFunctionCall(ctx, ast);
 132    } else if (ast.type == "BLOCK") {
 133        return execBlock(ctx, ast);
 134    } else if (ast.type == "COMPUTE") {
 135        return ;
 136    } else if (ast.type == "FOR") {
 137        return execFor(ctx, ast);
 138    } else if (ast.type == "WHILE") {
 139        return execWhile(ctx, ast);
 140    } else if (ast.type == "IF") {
 141        return execIf(ctx, ast);
 142    } else if (ast.type == "RETURN") {
 143        return execReturn(ctx, ast);
 144    } else if (ast.type == "TEMPLATEDEF") {
 145        return execTemplateDef(ctx, ast);
 146    } else if (ast.type == "FUNCTIONDEF") {
 147        return execFunctionDef(ctx, ast);
 148    } else if (ast.type == "INCLUDE") {
 149        return execInclude(ctx, ast);
 150    } else if (ast.type == "ARRAY") {
 151        return execArray(ctx, ast);
 152    } else {
 153        error(ctx, ast, "Invalid AST node type: " + ast.type);
 154    }
 155}
 156
 157function error(ctx, ast, errStr) {
 158    ctx.error = {
 159        pos:   {
 160            first_line: ast.first_line,
 161            first_column: ast.first_column,
 162            last_line: ast.last_line,
 163            last_column: ast.last_column
 164        },
 165        errStr: errStr,
 166        errFile: ctx.fileName,
 167        ast: ast,
 168        message: errStr
 169    };
 170}
 171
 172function iterateSelectors(ctx, sizes, baseName, fn) {
 173    if (sizes.length == 0) {
 174        return fn(baseName);
 175    }
 176    const res = [];
 177    for (let i=0; i<sizes[0]; i++) {
 178        res.push(iterateSelectors(ctx, sizes.slice(1), baseName+"["+i+"]", fn));
 179        if (ctx.error) return null;
 180    }
 181    return res;
 182}
 183
 184function setScope(ctx, name, selectors, value) {
 185    let l = getScopeLevel(ctx, name);
 186    if (l==-1) l= ctx.scopes.length-1;
 187
 188    if (selectors.length == 0) {
 189        ctx.scopes[l][name] = value;
 190    } else {
 191        setScopeArray(ctx.scopes[l][name], selectors);
 192    }
 193
 194    function setScopeArray(a, sels) {
 195        if (sels.length == 1) {
 196            a[sels[0].value] = value;
 197        } else {
 198            setScopeArray(a[sels[0]], sels.slice(1));
 199        }
 200    }
 201}
 202
 203function getScope(ctx, name, selectors) {
 204
 205    const sels = [];
 206    if (selectors) {
 207        for (let i=0; i< selectors.length; i++) {
 208            const idx = exec(ctx, selectors[i]);
 209            if (ctx.error) return;
 210
 211            if (idx.type != "NUMBER") return error(ctx, selectors[i], "expected a number");
 212            sels.push( idx.value.toJSNumber() );
 213        }
 214    }
 215
 216
 217    function select(v, s) {
 218        s = s || [];
 219        if (s.length == 0)  return v;
 220        return select(v[s[0]], s.slice(1));
 221    }
 222
 223    for (let i=ctx.scopes.length-1; i>=0; i--) {
 224        if (ctx.scopes[i][name]) return select(ctx.scopes[i][name], sels);
 225    }
 226    return null;
 227}
 228
 229function getScopeLevel(ctx, name) {
 230    for (let i=ctx.scopes.length-1; i>=0; i--) {
 231        if (ctx.scopes[i][name]) return i;
 232    }
 233    return -1;
 234}
 235
 236function execBlock(ctx,  ast) {
 237    for (let i=0; i<ast.statements.length; i++) {
 238        exec(ctx, ast.statements[i]);
 239        if (ctx.returnValue) return;
 240        if (ctx.error) return;
 241    }
 242}
 243
 244function execTemplateDef(ctx, ast) {
 245    const scope = ctx.scopes[0];  // Lets put templates always in top scope.
 246    //    const scope = ctx.scopes[ctx.scopes.length-1];
 247    if (getScope(ctx, ast.name)) {
 248        return error(ctx, ast, "Name already exists: "+ast.name);
 249    }
 250    scope[ast.name] = {
 251        type: "TEMPLATE",
 252        params: ast.params,
 253        block: ast.block,
 254        fileName: ctx.fileName,
 255        filePath: ctx.filePath,
 256        scopes: copyScope(ctx.scopes)
 257    };
 258}
 259
 260function execFunctionDef(ctx, ast) {
 261    const scope = ctx.scopes[0]; // Lets put functions always in top scope.
 262    //    const scope = ctx.scopes[ctx.scopes.length-1];
 263    if (getScope(ctx, ast.name)) {
 264        return error(ctx, ast, "Name already exists: "+ast.name);
 265    }
 266    ctx.functionParams[ast.name] = ast.params;
 267    scope[ast.name] = {
 268        type: "FUNCTION",
 269        params: ast.params,
 270        block: ast.block,
 271        fileName: ctx.fileName,
 272        filePath: ctx.filePath,
 273        scopes: copyScope(ctx.scopes)
 274    };
 275}
 276
 277
 278function execDeclareComponent(ctx, ast) {
 279    const scope = ctx.scopes[ctx.scopes.length-1];
 280
 281    if (ast.name.type != "VARIABLE") return error(ctx, ast, "Invalid component name");
 282    if (getScope(ctx, ast.name.name)) return error(ctx, ast, "Name already exists: "+ast.name.name);
 283
 284    const baseName = ctx.currentComponent ? ctx.currentComponent + "." + ast.name.name : ast.name.name;
 285
 286    const sizes=[];
 287    for (let i=0; i< ast.name.selectors.length; i++) {
 288        const size = exec(ctx, ast.name.selectors[i]);
 289        if (ctx.error) return;
 290
 291        if (size.type != "NUMBER") return error(ctx, ast.name.selectors[i], "expected a number");
 292
 293        sizes.push( size.value.toJSNumber() );
 294    }
 295
 296
 297    scope[ast.name.name] = iterateSelectors(ctx, sizes, baseName, function(fullName) {
 298
 299        ctx.components[fullName] = "UNINSTANTIATED";
 300
 301        return {
 302            type: "COMPONENT",
 303            fullName: fullName
 304        };
 305    });
 306
 307    return {
 308        type: "VARIABLE",
 309        name: ast.name.name,
 310        selectors: []
 311    };
 312}
 313
 314function execInstantiateComponet(ctx, vr, fn) {
 315
 316    if (vr.type != "VARIABLE") return error(ctx, fn, "Left hand instatiate component must be a variable");
 317    if (fn.type != "FUNCTIONCALL") return error(ctx, fn, "Right type of instantiate component must be a function call");
 318
 319    const componentName = vr.name;
 320    const templateName = fn.name;
 321
 322    const scopeLevel = getScopeLevel(ctx, templateName);
 323    if (scopeLevel == -1) return error(ctx,fn, "Invalid Template");
 324    const template = getScope(ctx, templateName);
 325
 326    if (template.type != "TEMPLATE") return error(ctx, fn, "Invalid Template");
 327
 328
 329    const paramValues = [];
 330    for (let i=0; i< fn.params.length; i++) {
 331        const v = exec(ctx, fn.params[i]);
 332        if (ctx.error) return;
 333
 334        paramValues.push(v);
 335    }
 336    if (template.params.length != paramValues.length) error(ctx, fn, "Invalid Number of parameters");
 337
 338    const vv = getScope(ctx, componentName, vr.selectors);
 339
 340    if (!vv) return error(ctx, vr, "Component not defined"+ componentName);
 341
 342    instantiateComponent(vv);
 343
 344    function instantiateComponent(varVal) {
 345
 346        function extractValue(v) {
 347            if (Array.isArray(v)) {
 348                return v.map(extractValue);
 349            } else {
 350                return v.value.toString();
 351            }
 352        }
 353
 354        if (Array.isArray(varVal)) {
 355            for (let i =0; i<varVal.length; i++) {
 356                instantiateComponent(varVal[i]);
 357            }
 358            return;
 359        }
 360
 361        if (ctx.components[varVal.fullName] != "UNINSTANTIATED") error(ctx, fn, "Component already instantiated");
 362
 363        const oldComponent = ctx.currentComponent;
 364        const oldFileName = ctx.fileName;
 365        const oldFilePath = ctx.filePath;
 366        ctx.currentComponent = varVal.fullName;
 367
 368        ctx.components[ctx.currentComponent] = {
 369            signals: [],
 370            params: {}
 371        };
 372
 373        const oldScopes = ctx.scopes;
 374
 375        ctx.scopes = oldScopes.slice(0, scopeLevel+1);
 376
 377        if (template.params.length != paramValues.length) return error(ctx, fn, "Invalid number of parameters: " + templateName);
 378
 379        const scope = {};
 380        for (let i=0; i< template.params.length; i++) {
 381            scope[template.params[i]] = paramValues[i];
 382            ctx.components[ctx.currentComponent].params[template.params[i]] = extractValue(paramValues[i]);
 383        }
 384
 385        ctx.components[ctx.currentComponent].template = templateName;
 386        ctx.fileName = template.fileName;
 387        ctx.filePath = template.filePath;
 388        ctx.scopes = copyScope( template.scopes );
 389        ctx.scopes.push(scope);
 390
 391        execBlock(ctx, template.block);
 392
 393        ctx.fileName = oldFileName;
 394        ctx.filePath = oldFilePath;
 395        ctx.currentComponent = oldComponent;
 396        ctx.scopes = oldScopes;
 397    }
 398}
 399
 400function execFunctionCall(ctx, ast) {
 401
 402    if (ast.name == "log") {
 403        const v = exec(ctx, ast.params[0]);
 404        console.log(v.value.toString());
 405        return;
 406    }
 407
 408    const scopeLevel = getScopeLevel(ctx, ast.name);
 409    if (scopeLevel == -1) return error(ctx, ast, "Function not defined: " + ast.name);
 410    const fnc = getScope(ctx, ast.name);
 411
 412    if (fnc.type != "FUNCTION") return error(ctx, ast, "Not a function: " + ast.name);
 413
 414    const paramValues = [];
 415    for (let i=0; i< ast.params.length; i++) {
 416        const v = exec(ctx, ast.params[i]);
 417        if (ctx.error) return;
 418
 419        paramValues.push(v);
 420    }
 421
 422    if (ast.params.length != paramValues.length) error(ctx, ast, "Invalid Number of parameters");
 423
 424    const oldFileName = ctx.fileName;
 425    const oldFilePath = ctx.filePath;
 426
 427    const oldScopes = ctx.scopes;
 428
 429    ctx.scopes = oldScopes.slice(0, scopeLevel+1);
 430
 431    const scope = {};
 432    for (let i=0; i< fnc.params.length; i++) {
 433        scope[fnc.params[i]] = paramValues[i];
 434    }
 435
 436    ctx.fileName = fnc.fileName;
 437    ctx.filePath = fnc.filePath;
 438    ctx.scopes = copyScope( fnc.scopes );
 439    ctx.scopes.push(scope);
 440
 441    execBlock(ctx, fnc.block);
 442
 443    const res = ctx.returnValue;
 444    ctx.returnValue = null;
 445
 446    ctx.fileName = oldFileName;
 447    ctx.filePath = oldFilePath;
 448    ctx.scopes = oldScopes;
 449
 450    return res;
 451}
 452
 453function execReturn(ctx, ast) {
 454    ctx.returnValue = exec(ctx, ast.value);
 455    return;
 456}
 457
 458function execDeclareSignal(ctx, ast) {
 459    const scope = ctx.scopes[ctx.scopes.length-1];
 460
 461    if (ast.name.type != "VARIABLE") return error(ctx, ast, "Invalid component name");
 462    if (getScope(ctx, ast.name.name)) return error(ctx, ast, "Name already exists: "+ast.name.name);
 463
 464    const baseName = ctx.currentComponent ? ctx.currentComponent + "." + ast.name.name : ast.name.name;
 465
 466    const sizes=[];
 467    for (let i=0; i< ast.name.selectors.length; i++) {
 468        const size = exec(ctx, ast.name.selectors[i]);
 469        if (ctx.error) return;
 470
 471        if (size.type != "NUMBER") return error(ctx, ast.name.selectors[i], "expected a number");
 472        sizes.push( size.value.toJSNumber() );
 473    }
 474
 475    scope[ast.name.name] = iterateSelectors(ctx, sizes, baseName, function(fullName) {
 476        ctx.signals[fullName] = {
 477            fullName: fullName,
 478            direction: ast.declareType == "SIGNALIN" ? "IN" : (ast.declareType == "SIGNALOUT" ? "OUT" : ""),
 479            private: ast.private,
 480            component: ctx.currentComponent,
 481            equivalence: "",
 482            alias: [fullName]
 483        };
 484        ctx.components[ctx.currentComponent].signals.push(fullName);
 485        return {
 486            type: "SIGNAL",
 487            fullName: fullName,
 488        };
 489    });
 490    return {
 491        type: "VARIABLE",
 492        name: ast.name.name,
 493        selectors: []
 494    };
 495}
 496
 497function execDeclareVariable(ctx, ast) {
 498    const scope = ctx.scopes[ctx.scopes.length-1];
 499
 500    if (ast.name.type != "VARIABLE") return error(ctx, ast, "Invalid linear combination name");
 501    if (getScope(ctx, ast.name.name)) return error(ctx, ast, "Name already exists: "+ast.name.name);
 502
 503    const sizes=[];
 504    for (let i=0; i< ast.name.selectors.length; i++) {
 505        const size = exec(ctx, ast.name.selectors[i]);
 506        if (ctx.error) return;
 507
 508        if (size.type != "NUMBER") return error(ctx, ast.name.selectors[i], "expected a number");
 509        sizes.push( size.value.toJSNumber() );
 510    }
 511
 512    scope[ast.name.name] = iterateSelectors(ctx, sizes, "", function() {
 513        return {
 514            type: "NUMBER",
 515            value: bigInt(0)
 516        };
 517    });
 518
 519    return {
 520        type: "VARIABLE",
 521        name: ast.name.name,
 522        selectors: []
 523    };
 524}
 525
 526function execVariable(ctx, ast) {
 527    let v;
 528    try {
 529        v = getScope(ctx, ast.name, ast.selectors);
 530    } catch(err) {
 531        console.log(JSON.stringify(ast, null,1));
 532    }
 533    if (ctx.error) return;
 534
 535    if (!v) return error(ctx, ast, "Variable not defined");
 536
 537    // If the signal has an assigned value (constant) just return the constant
 538    if ((v.type == "SIGNAL") && (ctx.signals[v.fullName].value)) {
 539        return {
 540            type: "NUMBER",
 541            value: ctx.signals[v.fullName].value
 542        };
 543    }
 544    let res;
 545    res=v;
 546    return res;
 547}
 548
 549function execPin(ctx, ast) {
 550    const component = getScope(ctx, ast.component.name, ast.component.selectors);
 551    if (!component) return error(ctx, ast.component, "Component does not exists: "+ast.component.name);
 552    if (ctx.error) return;
 553    let signalFullName = component.fullName + "." + ast.pin.name;
 554    for (let i=0; i< ast.pin.selectors.length; i++) {
 555        const sel = exec(ctx, ast.pin.selectors[i]);
 556        if (ctx.error) return;
 557
 558        if (sel.type != "NUMBER") return error(ctx, ast.pin.selectors[i], "expected a number");
 559
 560        signalFullName += "[" + sel.value.toJSNumber() + "]";
 561    }
 562    if (!ctx.signals[signalFullName]) error(ctx, ast, "Signal not defined:" + signalFullName);
 563    return {
 564        type: "SIGNAL",
 565        fullName: signalFullName
 566    };
 567}
 568
 569function execFor(ctx, ast) {
 570
 571    ctx.scopes.push({});
 572    exec(ctx, ast.init);
 573    if (ctx.error) return;
 574
 575    let v = exec(ctx, ast.condition);
 576    if (ctx.error) return;
 577
 578    if (typeof v.value != "undefined") {
 579        while ((v.value.neq(0))&&(!ctx.returnValue)) {
 580            exec(ctx, ast.body);
 581            if (ctx.error) return;
 582
 583            exec(ctx, ast.step);
 584            if (ctx.error) return;
 585
 586            v = exec(ctx, ast.condition);
 587            if (ctx.error) return;
 588        }
 589    }
 590    ctx.scopes.pop();
 591}
 592
 593function execWhile(ctx, ast) {
 594    let v = exec(ctx, ast.condition);
 595    if (ctx.error) return;
 596
 597    if (typeof v.value != "undefined") {
 598        while ((v.value.neq(0))&&(!ctx.returnValue)) {
 599            exec(ctx, ast.body);
 600            if (ctx.error) return;
 601
 602            v = exec(ctx, ast.condition);
 603            if (ctx.error) return;
 604        }
 605    }
 606}
 607
 608function execIf(ctx, ast) {
 609    let v = exec(ctx, ast.condition);
 610    if (ctx.error) return;
 611
 612    if (typeof v.value != "undefined") {
 613        if ((v.value.neq(0))&&(!ctx.returnValue)) {
 614            exec(ctx, ast.then);
 615            if (ctx.error) return;
 616        } else {
 617            if (ast.else) {
 618                exec(ctx, ast.else);
 619                if (ctx.error) return;
 620            }
 621        }
 622    }
 623}
 624
 625
 626function execVarAssignement(ctx, ast) {
 627    let v;
 628    if (ast.values[0].type == "DECLARE") {
 629        v = exec(ctx, ast.values[0]);
 630        if (ctx.error) return;
 631    } else {
 632        v = ast.values[0];
 633    }
 634    const num = getScope(ctx, v.name, v.selectors);
 635    if (ctx.error) return;
 636
 637    if ((typeof(num) != "object")||(num == null)) return  error(ctx, ast, "Variable not defined");
 638
 639    if (num.type == "COMPONENT") return execInstantiateComponet(ctx, v, ast.values[1]);
 640    if (ctx.error) return;
 641//    if (num.type == "SIGNAL") return error(ctx, ast, "Cannot assign to a signal with `=` use <-- or <== ops");
 642
 643    const res = exec(ctx, ast.values[1]);
 644    if (ctx.error) return;
 645
 646    setScope(ctx, v.name, v.selectors, res);
 647
 648    return v;
 649}
 650
 651function execLt(ctx, ast) {
 652    const a = exec(ctx, ast.values[0]);
 653    if (ctx.error) return;
 654    if (a.type != "NUMBER") return { type: "NUMBER" };
 655    const b = exec(ctx, ast.values[1]);
 656    if (ctx.error) return;
 657    if (b.type != "NUMBER") return { type: "NUMBER" };
 658    if (!a.value || !b.value) return { type: "NUMBER" };
 659    return {
 660        type: "NUMBER",
 661        value: a.value.lt(b.value) ? bigInt(1) : bigInt(0)
 662    };
 663}
 664
 665function execGt(ctx, ast) {
 666    const a = exec(ctx, ast.values[0]);
 667    if (ctx.error) return;
 668    if (a.type != "NUMBER") return { type: "NUMBER" };
 669    const b = exec(ctx, ast.values[1]);
 670    if (ctx.error) return;
 671    if (b.type != "NUMBER") return { type: "NUMBER" };
 672    if (!a.value || !b.value) return { type: "NUMBER" };
 673    return {
 674        type: "NUMBER",
 675        value: a.value.gt(b.value) ? bigInt(1) : bigInt(0)
 676    };
 677}
 678
 679function execLte(ctx, ast) {
 680    const a = exec(ctx, ast.values[0]);
 681    if (ctx.error) return;
 682    if (a.type != "NUMBER") return { type: "NUMBER" };
 683    const b = exec(ctx, ast.values[1]);
 684    if (ctx.error) return;
 685    if (b.type != "NUMBER") return { type: "NUMBER" };
 686    if (!a.value || !b.value) return { type: "NUMBER" };
 687    return {
 688        type: "NUMBER",
 689        value: a.value.lesserOrEquals(b.value) ? bigInt(1) : bigInt(0)
 690    };
 691}
 692
 693function execGte(ctx, ast) {
 694    const a = exec(ctx, ast.values[0]);
 695    if (ctx.error) return;
 696    if (a.type != "NUMBER") return { type: "NUMBER" };
 697    const b = exec(ctx, ast.values[1]);
 698    if (ctx.error) return;
 699    if (b.type != "NUMBER") return { type: "NUMBER" };
 700    if (!a.value || !b.value) return { type: "NUMBER" };
 701    return {
 702        type: "NUMBER",
 703        value: a.value.greaterOrEquals(b.value) ? bigInt(1) : bigInt(0)
 704    };
 705}
 706
 707
 708function execEq(ctx, ast) {
 709    const a = exec(ctx, ast.values[0]);
 710    if (ctx.error) return;
 711    if (a.type != "NUMBER") return { type: "NUMBER" };
 712    const b = exec(ctx, ast.values[1]);
 713    if (ctx.error) return;
 714    if (b.type != "NUMBER") return { type: "NUMBER" };
 715    if (!a.value || !b.value) return { type: "NUMBER" };
 716    return {
 717        type: "NUMBER",
 718        value: a.value.eq(b.value) ? bigInt(1) : bigInt(0)
 719    };
 720}
 721
 722function execNeq(ctx, ast) {
 723    const a = exec(ctx, ast.values[0]);
 724    if (ctx.error) return;
 725    if (a.type != "NUMBER") return { type: "NUMBER" };
 726    const b = exec(ctx, ast.values[1]);
 727    if (ctx.error) return;
 728    if (b.type != "NUMBER") return { type: "NUMBER" };
 729    if (!a.value || !b.value) return { type: "NUMBER" };
 730    return {
 731        type: "NUMBER",
 732        value: a.value.eq(b.value) ? bigInt(0) : bigInt(1)
 733    };
 734}
 735
 736
 737function execBAnd(ctx, ast) {
 738    const a = exec(ctx, ast.values[0]);
 739    if (ctx.error) return;
 740    if (a.type != "NUMBER") return { type: "NUMBER" };
 741    const b = exec(ctx, ast.values[1]);
 742    if (ctx.error) return;
 743    if (b.type != "NUMBER") return { type: "NUMBER" };
 744    if (!a.value || !b.value) return { type: "NUMBER" };
 745    return {
 746        type: "NUMBER",
 747        value: a.value.and(b.value).and(__MASK__)
 748    };
 749}
 750
 751function execAnd(ctx, ast) {
 752    const a = exec(ctx, ast.values[0]);
 753    if (ctx.error) return;
 754    if (a.type != "NUMBER") return { type: "NUMBER" };
 755    const b = exec(ctx, ast.values[1]);
 756    if (ctx.error) return;
 757    if (b.type != "NUMBER") return { type: "NUMBER" };
 758    if (!a.value || !b.value) return { type: "NUMBER" };
 759    return {
 760        type: "NUMBER",
 761        value: (a.value.neq(0) && b.value.neq(0)) ? bigInt(1) : bigInt(0)
 762    };
 763}
 764
 765function execOr(ctx, ast) {
 766    const a = exec(ctx, ast.values[0]);
 767    if (ctx.error) return;
 768    if (a.type != "NUMBER") return { type: "NUMBER" };
 769    const b = exec(ctx, ast.values[1]);
 770    if (ctx.error) return;
 771    if (b.type != "NUMBER") return { type: "NUMBER" };
 772    if (!a.value || !b.value) return { type: "NUMBER" };
 773    return {
 774        type: "NUMBER",
 775        value: (a.value.neq(0) || b.value.neq(0)) ? bigInt(1) : bigInt(0)
 776    };
 777}
 778
 779function execShl(ctx, ast) {
 780    const a = exec(ctx, ast.values[0]);
 781    if (ctx.error) return;
 782    if (a.type != "NUMBER") return { type: "NUMBER" };
 783    const b = exec(ctx, ast.values[1]);
 784    if (ctx.error) return;
 785    if (b.type != "NUMBER") return { type: "NUMBER" };
 786    if (!a.value || !b.value) return { type: "NUMBER" };
 787    const v = b.value.greater(256) ? 256 : b.value.value;
 788    return {
 789        type: "NUMBER",
 790        value: a.value.shiftLeft(v).and(__MASK__)
 791    };
 792}
 793
 794function execShr(ctx, ast) {
 795    const a = exec(ctx, ast.values[0]);
 796    if (ctx.error) return;
 797    if (a.type != "NUMBER") return { type: "NUMBER" };
 798    const b = exec(ctx, ast.values[1]);
 799    if (ctx.error) return;
 800    if (b.type != "NUMBER") return { type: "NUMBER" };
 801    if (!a.value || !b.value) return { type: "NUMBER" };
 802    const v = b.value.greater(256) ? 256 : b.value.value;
 803    return {
 804        type: "NUMBER",
 805        value: a.value.shiftRight(v).and(__MASK__)
 806    };
 807}
 808
 809function execMod(ctx, ast) {
 810    const a = exec(ctx, ast.values[0]);
 811    if (ctx.error) return;
 812    if (a.type != "NUMBER") return { type: "NUMBER" };
 813    const b = exec(ctx, ast.values[1]);
 814    if (ctx.error) return;
 815    if (b.type != "NUMBER") return { type: "NUMBER" };
 816    if (!a.value || !b.value) return { type: "NUMBER" };
 817    return {
 818        type: "NUMBER",
 819        value: a.value.mod(b.value)
 820    };
 821}
 822
 823
 824function execExp(ctx, ast) {
 825    const a = exec(ctx, ast.values[0]);
 826    if (ctx.error) return;
 827    if (a.type != "NUMBER") return { type: "NUMBER" };
 828    const b = exec(ctx, ast.values[1]);
 829    if (ctx.error) return;
 830    if (b.type != "NUMBER") return { type: "NUMBER" };
 831    if (!a.value || !b.value) return { type: "NUMBER" };
 832    return {
 833        type: "NUMBER",
 834        value: a.value.modPow(b.value, __P__)
 835    };
 836}
 837
 838function execDiv(ctx, ast) {
 839    const a = exec(ctx, ast.values[0]);
 840    if (ctx.error) return;
 841    if (a.type != "NUMBER") return { type: "NUMBER" };
 842    const b = exec(ctx, ast.values[1]);
 843    if (ctx.error) return;
 844    if (b.type != "NUMBER") return { type: "NUMBER" };
 845    if (!a.value || !b.value) return { type: "NUMBER" };
 846    if (b.value.isZero()) return error(ctx, ast, "Division by zero");
 847    return {
 848        type: "NUMBER",
 849        value: a.value.times(b.value.modInv(__P__)).mod(__P__)
 850    };
 851}
 852
 853function execIDiv(ctx, ast) {
 854    const a = exec(ctx, ast.values[0]);
 855    if (ctx.error) return;
 856    if (a.type != "NUMBER") return { type: "NUMBER" };
 857    const b = exec(ctx, ast.values[1]);
 858    if (ctx.error) return;
 859    if (b.type != "NUMBER") return { type: "NUMBER" };
 860    if (!a.value || !b.value) return { type: "NUMBER" };
 861    if (b.value.isZero()) return error(ctx, ast, "Division by zero");
 862    return {
 863        type: "NUMBER",
 864        value: a.value.divide(b.value)
 865    };
 866}
 867
 868function execAdd(ctx, ast) {
 869    const a = exec(ctx, ast.values[0]);
 870    if (ctx.error) return;
 871    const b = exec(ctx, ast.values[1]);
 872    if (ctx.error) return;
 873
 874    const res = lc.add(a,b);
 875    if (res.type == "ERROR") return error(ctx, ast, res.errStr);
 876
 877    return res;
 878}
 879
 880function execSub(ctx, ast) {
 881    const a = exec(ctx, ast.values[0]);
 882    if (ctx.error) return;
 883    const b = exec(ctx, ast.values[1]);
 884    if (ctx.error) return;
 885
 886    const res = lc.sub(a,b);
 887    if (res.type == "ERROR") return error(ctx, ast, res.errStr);
 888
 889    return res;
 890}
 891
 892function execUMinus(ctx, ast) {
 893    const a = exec(ctx, ast.values[0]);
 894    if (ctx.error) return;
 895
 896    const res = lc.negate(a);
 897    if (res.type == "ERROR") return error(ctx, ast, res.errStr);
 898
 899    return res;
 900}
 901
 902function execMul(ctx, ast) {
 903    const a = exec(ctx, ast.values[0]);
 904    if (ctx.error) return;
 905    const b = exec(ctx, ast.values[1]);
 906    if (ctx.error) return;
 907
 908    const res = lc.mul(a,b);
 909    if (res.type == "ERROR") return error(ctx, ast, res.errStr);
 910
 911    return res;
 912}
 913
 914
 915function execVarAddAssignement(ctx, ast) {
 916    const res = execAdd(ctx,{ values: [ast.values[0], ast.values[1]] } );
 917    if (ctx.error) return;
 918    return execVarAssignement(ctx, { values: [ast.values[0], res] });
 919}
 920
 921function execVarMulAssignement(ctx, ast) {
 922    const res = execMul(ctx,{ values: [ast.values[0], ast.values[1]] } );
 923    if (ctx.error) return;
 924    return execVarAssignement(ctx, { values: [ast.values[0], res] });
 925}
 926
 927function execPlusPlusRight(ctx, ast) {
 928    const resBefore = exec(ctx, ast.values[0]);
 929    if (ctx.error) return;
 930    const resAfter = execAdd(ctx,{ values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}] } );
 931    if (ctx.error) return;
 932    execVarAssignement(ctx, { values: [ast.values[0], resAfter] });
 933    return resBefore;
 934}
 935
 936function execPlusPlusLeft(ctx, ast) {
 937    if (ctx.error) return;
 938    const resAfter = execAdd(ctx,{ values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}] } );
 939    if (ctx.error) return;
 940    execVarAssignement(ctx, { values: [ast.values[0], resAfter] });
 941    return resAfter;
 942}
 943
 944function execMinusMinusRight(ctx, ast) {
 945    const resBefore = exec(ctx, ast.values[0]);
 946    if (ctx.error) return;
 947    const resAfter = execSub(ctx,{ values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}] } );
 948    if (ctx.error) return;
 949    execVarAssignement(ctx, { values: [ast.values[0], resAfter] });
 950    return resBefore;
 951}
 952
 953function execMinusMinusLeft(ctx, ast) {
 954    if (ctx.error) return;
 955    const resAfter = execSub(ctx,{ values: [ast.values[0], {type: "NUMBER", value: bigInt(1)}] } );
 956    if (ctx.error) return;
 957    execVarAssignement(ctx, { values: [ast.values[0], resAfter] });
 958    return resAfter;
 959}
 960
 961function execTerCon(ctx, ast) {
 962    const cond = exec(ctx, ast.values[0]);
 963    if (ctx.error) return;
 964
 965    if (!cond.value) return { type: "NUMBER" };
 966
 967    if (cond.value.neq(0)) {
 968        return exec(ctx, ast.values[1]);
 969    } else {
 970        return exec(ctx, ast.values[2]);
 971    }
 972}
 973
 974function execSignalAssign(ctx, ast) {
 975    let vDest;
 976    if (ast.values[0].type == "DECLARE") {
 977        vDest = exec(ctx, ast.values[0]);
 978        if (ctx.error) return;
 979    } else {
 980        vDest = ast.values[0];
 981    }
 982
 983    let dst;
 984    if (vDest.type == "VARIABLE") {
 985        dst = getScope(ctx, vDest.name, vDest.selectors);
 986        if (ctx.error) return;
 987    } else if (vDest.type == "PIN") {
 988        dst = execPin(ctx, vDest);
 989        if (ctx.error) return;
 990    } else {
 991        error(ctx, ast, "Bad assignement");
 992    }
 993
 994    if (!dst) return  error(ctx, ast, "Signal not defined");
 995    if (dst.type != "SIGNAL") return  error(ctx, ast, "Signal assigned to a non signal");
 996
 997    let sDest=ctx.signals[dst.fullName];
 998    if (!sDest) return error(ctx, ast, "Invalid signal: "+dst.fullName);
 999
1000    let isOut = (sDest.component == "main")&&(sDest.direction=="OUT");
1001    while (sDest.equivalence) {
1002        sDest=ctx.signals[sDest.equivalence];
1003        isOut = isOut || ((sDest.component == "main")&&(sDest.direction=="OUT"));
1004    }
1005
1006    if (sDest.value) return error(ctx, ast, "Signals cannot be assigned twice");
1007
1008    let src = exec(ctx, ast.values[1]);
1009    if (ctx.error) return;
1010
1011
1012    /*
1013    let vSrc;
1014    if (ast.values[1].type == "DECLARE") {
1015        vSrc = exec(ctx, ast.values[1]);
1016        if (ctx.error) return;
1017    } else {
1018        vSrc = ast.values[1];
1019    }
1020
1021    if (vSrc.type == "VARIABLE") {
1022        src = getScope(ctx, vSrc.name, vSrc.selectors);
1023        if (!src) error(ctx, ast, "Variable not defined: " + vSrc.name);
1024        if (ctx.error) return;
1025    } else if (vSrc.type == "PIN") {
1026        src = execPin(ctx, vSrc);
1027    }
1028    */
1029
1030    let assignValue = true;
1031    if (src.type == "SIGNAL") {
1032        let sSrc = ctx.signals[src.fullName];
1033        let isIn  = (sSrc.component == "main")&&(sSrc.direction == "IN");
1034        while (sSrc.equivalence) {
1035            sSrc=ctx.signals[sSrc.equivalence];
1036            isIn = isIn || ((sSrc.component == "main")&&(sSrc.direction == "IN"));
1037        }
1038
1039        // Skip if an out is assigned directly to an input.
1040        if ((!isIn)||(!isOut)) {
1041            sDest.equivalence = src.fullName;
1042            sDest.alias = sDest.alias.concat(src.alias);
1043            while (sDest.equivalence) sDest=ctx.signals[sDest.equivalence];
1044            assignValue = false;
1045        }
1046    }
1047
1048    if (assignValue) {
1049        //        const resLC = exec(ctx, vSrc);
1050        if (ctx.error) return;
1051
1052        //        const v = lc.evaluate(ctx, resLC);
1053        const v = lc.evaluate(ctx, src);
1054
1055        if (v.value) {
1056            sDest.value = v.value;
1057        }
1058    }
1059
1060    return vDest;
1061}
1062
1063function execConstrain(ctx, ast) {
1064    ast.fileName = ctx.fileName;
1065    ast.filePath = ctx.filePath;
1066    const a = exec(ctx, ast.values[0]);
1067    if (ctx.error) return;
1068    const b = exec(ctx, ast.values[1]);
1069    if (ctx.error) return;
1070
1071    const res = lc.sub(a,b);
1072    if (res.type == "ERROR") return error(ctx, ast, res.errStr);
1073
1074    if (!lc.isZero(res)) {
1075        ctx.constraints.push(lc.toQEQ(res));
1076    }
1077
1078    if (ctx.constraints.length % 10000 == 0) console.log("Constraints: " + ctx.constraints.length);
1079
1080    return res;
1081}
1082
1083function execSignalAssignConstrain(ctx, ast) {
1084    const v = execSignalAssign(ctx,ast);
1085    if (ctx.error) return;
1086    execConstrain(ctx, ast);
1087    if (ctx.error) return;
1088    return v;
1089}
1090
1091function execInclude(ctx, ast) {
1092    const incFileName = path.resolve(ctx.filePath, ast.file);
1093    const incFilePath = path.dirname(incFileName);
1094
1095    ctx.includedFiles = ctx.includedFiles || [];
1096    if (ctx.includedFiles[incFileName]) return;
1097
1098    ctx.includedFiles[incFileName] = true;
1099
1100    const src = fs.readFileSync(incFileName, "utf8");
1101
1102    if (!src) return error(ctx, ast, "Include file not found: "+incFileName);
1103
1104    const incAst = parser.parse(src);
1105
1106    const oldFilePath = ctx.filePath;
1107    const oldFileName = ctx.fileName;
1108    ctx.filePath = incFilePath;
1109    ctx.fileName = incFileName;
1110
1111    exec(ctx, incAst);
1112
1113    ast.block = incAst;
1114
1115    ctx.filePath = oldFilePath;
1116    ctx.fileName = oldFileName;
1117}
1118
1119function execArray(ctx, ast) {
1120    const res = [];
1121
1122    for (let i=0; i<ast.values.length; i++) {
1123        res.push(exec(ctx, ast.values[i]));
1124    }
1125
1126    return res;
1127}
1128
1129function copyScope(scope) {
1130    var scopesClone = [];
1131    for (let i=0; i<scope.length; i++) {
1132        scopesClone.push(scope[i]);
1133    }
1134    return scopesClone;
1135}
1136