Skip to content

Instantly share code, notes, and snippets.

@Etheresk
Created October 29, 2023 08:24
Show Gist options
  • Save Etheresk/511355aca925b4c3d693d73fa0ee47dc to your computer and use it in GitHub Desktop.
Save Etheresk/511355aca925b4c3d693d73fa0ee47dc to your computer and use it in GitHub Desktop.
Jison arithmetic grammar
%lex
%%
\s+ /* skip ws */
[0-9]+ return 'NUMBER'
\+ return 'ADD'
\- return 'SUB'
\* return 'MUL'
\/ return 'DIV'
\( return 'LPAREN'
\) return 'RPAREN'
<<EOF>> return 'EOF'
. return 'INVALID'
/lex
%start expressions
%%
expressions
: expression EOF { return $1; }
;
expression
: expression ADD term { $$ = $1 + $3; }
| expression SUB term { $$ = $1 - $3; }
| term { $$ = $1; }
;
term
: term MUL factor { $$ = $1 * $3; }
| term DIV factor { $$ = $1 / $3; }
| factor { $$ = $1; }
;
factor
: LPAREN expression RPAREN { $$ = $2; }
| NUMBER { $$ = parseFloat(yytext); }
;
%%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment