From fae0164b5e7e6dc8b5f4bd2203965e435f6e9a1e Mon Sep 17 00:00:00 2001 From: Anurag Vasanwala <75766877+AnuragVasanwala@users.noreply.github.com> Date: Fri, 25 Feb 2022 11:13:41 +0530 Subject: [PATCH 1/2] =?UTF-8?q?=E2=9C=A8=20Add=20new=20calculator=20exampl?= =?UTF-8?q?e=20with=20variable=20support?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/calculator2.jison | 75 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 examples/calculator2.jison diff --git a/examples/calculator2.jison b/examples/calculator2.jison new file mode 100644 index 000000000..b75b6767e --- /dev/null +++ b/examples/calculator2.jison @@ -0,0 +1,75 @@ + +/* description: Parses and executes mathematical expressions. Added support for variable evaluation. */ + +/* lexical grammar */ +%lex +%% + +\s+ /* skip whitespace */ +[a-zA-Z_][a-zA-Z0-9_]* return 'VARIABLE' +[0-9]+("."[0-9]+)?\b return 'NUMBER' +"*" return '*' +"/" return '/' +"-" return '-' +"+" return '+' +"^" return '^' +"!" return '!' +"%" return '%' +"(" return '(' +")" return ')' +"PI" return 'PI' +"E" return 'E' +<> return 'EOF' +. return 'INVALID' + +/lex + +/* operator associations and precedence */ + +%left '+' '-' +%left '*' '/' +%left '^' +%right '!' +%right '%' +%left UMINUS + +%start expressions + +%% /* language grammar */ + +expressions + : e EOF + { typeof console !== 'undefined' ? console.log($1) : print($1); + 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 + { $$ = yy[yytext]; } + | NUMBER + {$$ = Number(yytext);} + | E + {$$ = Math.E;} + | PI + {$$ = Math.PI;} + ; From 113f86772bdeddbca61a31a83808300d60fb65a8 Mon Sep 17 00:00:00 2001 From: Anurag Vasanwala <75766877+AnuragVasanwala@users.noreply.github.com> Date: Mon, 28 Feb 2022 10:39:48 +0530 Subject: [PATCH 2/2] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Remove=20extra=20white?= =?UTF-8?q?space?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/calculator2.jison | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/calculator2.jison b/examples/calculator2.jison index b75b6767e..fbace48e4 100644 --- a/examples/calculator2.jison +++ b/examples/calculator2.jison @@ -65,7 +65,7 @@ e | '(' e ')' {$$ = $2;} | VARIABLE - { $$ = yy[yytext]; } + {$$ = yy[yytext];} | NUMBER {$$ = Number(yytext);} | E