2015-10-14 84 views
2

有没有办法将数据传递给Jison,以便它可以在解析过程中引用它?作为起始时,比方说,我们正在使用的calculator.jison,并希望通过它的对象,说将数据传递给Jison解析器

var parser = new jison.Parser(bnf); 
var data = `{m: 4, b: 2, x: 10}; 
parser.parse("m*x + b", data); 

这里有一个新的情况下VARIABLE { $$ = data[text]; }增加,从而解决了使用数据对象提供的变量calculator.jison :

%start expressions 

%% /* language grammar */ 

expressions : e EOF { return $1; }; 

e 
    : e '+' e 
     {$$ = $1+$3;} 
    | e '-' e 
     {$$ = $1-$3;} 
    | e '*' e 
     {$$ = $1*$3;} 
    | e '/' e 
     {$$ = $1/$3;} 
    | e '^' e 
     {$$ = Math.pow($1, $3);} 
    | e '!' 
     {{ 
      $$ = (function fact (n) { return n==0 ? 1 : fact(n-1) * n })($1); 
     }} 
    | e '%' 
     {$$ = $1/100;} 
    | '-' e %prec UMINUS 
     {$$ = -$2;} 
    | '(' e ')' 
     {$$ = $2;} 
    | VARIABLE 
     { $$ = data[text]; } 
    | NUMBER 
     {$$ = Number(yytext);} 
    | E 
     {$$ = Math.E;} 
    | PI 
     {$$ = Math.PI;} 
    ; 
+0

卫生署,现在,我已经写的问题,我终于能理解的文档。在这里回答https://zaach.github.io/jison/docs/#sharing-scope – prototype

回答

2

VARIABLE = { $$ = yy.data[text]; }

var parser = new jison.Parser(bnf); 
parser.yy = {data: {m: 4, b: 2, x: 10}}; 
parser.parse("m*x + b");