zaach / jison

Bison in JavaScript.
http://jison.org
4.33k stars 448 forks source link

%empty directive doesn't execute semantic actions, /* empty */ does #386

Closed fcruzel closed 5 years ago

fcruzel commented 5 years ago

%empty directive used in a rule won't execute the semantic action. Using comments or nothing (like /* empty */) will execute the action. Consider this example:

index
  : %empty                                    { $$ = []; }
  | '[' expression ']' index                  { $index.push($expression); $$ = $index; }
  ;

Jison says that $index is undefined when executing it.

$$[$0].push($$[$0-2]); this.$ = $$[$0];
        ^

TypeError: Cannot read property 'push' of undefined

If instead of %empty, comments or nothing are used, there's no error and the generated parser work as expected:

index
  : /* empty  */                              { $$ = []; }
  | '[' expression ']' index                  { $index.push($expression); $$ = $index; }
  ;

The example above works as it should, returning [] from $index when the rule matchs the empty string.

GerHobbelt commented 5 years ago

IIRC %empty is not supported by vanilla jison. jison-gho does support %empty though.

(You can check this by looking at the generated parser JS code: I bet jison treats %empty as a token and assigns it a token ID, which, of course, is never output by the lexer and thus resulting in a unreachable code section of your grammar.)

fcruzel commented 5 years ago

Didn't know there was a fork of Jison. Thank you. Since this repo it's no longer maintained I'm closing the issue.