Taslima Akhter
Taslima Akhter

Reputation: 61

PEGjs | Multiple output issue

Why we can output once in PEG.js? do anyone know any other way to implement many output? I am using Stack 🙂 and a function , code below:

function evalStack() {
        for (var i = stack.length - 1; 0 <= i; i--) {
            stack[i]();
        }
        return result;
    }

My custom input:

start
A=4;
A
B=8;
B

Result I expected:

4
8

Result I got:

4

Please help me

Upvotes: 0

Views: 46

Answers (1)

Digital Alpha
Digital Alpha

Reputation: 300

try this dirty solution:

all
  = _ ptp:putThenPrint+ _
  {
    var all = [];
    ptp.forEach(it => {
        all.push(it);
    });
    var r = []
    all.forEach(tp => {
      tp.toPrint.forEach(p => {
        r.push(tp.values[p])
      });
    });
    return "\n" + r.join("\n") + "\n";
  }
  
putThenPrint
  = _ mn:multiPutN _ pn:multiPrintN _ 
  {
    return {values:mn,toPrint:pn};
  }

multiPrintN
  = _ mp:printN+ _ 
  {
    var r = [];
    mp.forEach(it => {
        r.push(it);
    });
    return r;
  }

multiPutN
  = _ mp:putN+ _ 
  {
    var r = {};
    mp.forEach(it => {
        r[it[0]]=it[1];
    });
    return r;
  }
  
putN
  = _ vn:varName _ "=" _ nn:n _ ";" _ nl+ { return [vn, nn]}

printN
  = _ n:varName _ nl+ {return n;}
  
varName
  = [a-zA-Z]+ {return text();}
  
n "integer number"
  = _ [0-9]+ { return parseInt(text(), 10); }
  
nl "new line"
  = [\n]

_ "whitespace or new line"
  = [ \t]*

in the above it only give you the value of the variable in the same section so once you print the variables you can not print them again however if you change the js code inside the grammar of "all" block you can make full scan first then print all variable if this what you want, but then you will print out values before assigning. as I mentioned this is just a dirty solution that need to optimise and clean up

Upvotes: 1

Related Questions