贾森递归

时间:2015-04-15 16:30:00

标签: javascript parsing jison

我试图抓住Jison。我虽然有点麻烦。无论你给它什么,下面的解析器总是返回[]。

%lex
%%

"data"\s*             return 'DATA'
[A-Za-z][A-Za-z0-9_]* return 'IDENTIFIER'
[0-9]+("."[0-9]+)?\b  return 'NUMBER'
"="                   return 'ASSIGN'
("<-"|"<+-")          return 'REACT'
"+"                   return '+'
"-"                   return '-'
"*"                   return '*'
"/"                   return '/'
"^"                   return '^'
\n+                   return 'NL'
<<EOF>>               return 'EOF'
.                     return 'INVALID'

/lex

%token NL

/* operator associations and precedence */

%left ASSIGN
%left REACT
%left '+' '-'
%left '*' '/'
%left '^'
%left UMINUS

%start program

%% /* language grammar */

program
    :
        {return [];}
    | program statement
        {return $1.concat([$2]);}
    | program statement EOF
        {return $1.concat([$2]);}
    ;

statement
    : assign NL
        {return $1;}
    ;

assign
    : IDENTIFIER ASSIGN expression
        {return ['assign', $1, $3];}
    | IDENTIFIER REACT expression
        {return ['react', $1, $2, $3];}
    ;

expression
    : NUMBER
        {return +$1;}
    | IDENTIFIER
    ;

问题显然在于我对非终端program的定义。宣布它的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

正如Aadit M. Shah在评论中指出的那样,问题是在解析完成之前你不能{1}}进行一个jison语法动作。如果解析器规则执行return,则解析器本身将返回。您需要将语义值分配给return

答案 1 :(得分:1)

尝试:

%start program

%% /* language grammar */

program
    : EOF
        { return []; }
    | statements EOF
        { return $1; }
    ;
statements
    : statement
        { $$ = [$1]; }
    | statements statement
        { $1.push($2); $$ = $1; }
    ;

另外,用“$$ =”

替换回报
statement
    : assign NL
        { $$ = $1; }
    ;

assign
    : IDENTIFIER ASSIGN expression
        { $$ = ['assign', $1, $3]; }
    | IDENTIFIER REACT expression
        { $$ = ['react', $1, $2, $3]; }
    ;

expression
    : NUMBER
        { $$ = $1; }
    | IDENTIFIER
        {/*add something here like $$ = $1 to keep the original value*/}
    ;