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