Consider the following Jison grammar:

%lex
%%

\s+                   { /* skip whitespace */ }
"["                   { return "LBRACKET";    }
"]"                   { return "RBRACKET";    }
<<EOF>>               { return "EOF";         }
.                     { return "INVALID";     }

%start program
/lex
%% 

program
    : s "EOF"
      { return $1; }
    ;
s
    : /* empty */
      { $$ = 0; }
    | "LBRACKET" s "RBRACKET" s
      { $$ = 1 + $2 + $4; }
    ;

Now consider the following four strings:

  • [ ]
  • [ ] [ ]
  • [ [ ] ]
  • [ [ [ ] [ ] ] [ ] ] [ ]

First, convince yourself that all of these strings are in the language defined by this grammar. Second, answer the following question: what are the values returned by the interpreter when fed these strings in the order given above?

1, 2, 2, 6
  • 2, 4, 4, 12
  • 1, 2, 4, 6
  • 2, 4, 2, 12

First, make sure to understand the grammar only: disregard the JavaScript annotations.

Once you understand the structure of the generated strings, try to correlate that structure with the single value that is computed at each step.