-
Notifications
You must be signed in to change notification settings - Fork 453
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to parse Variable #379
Comments
Hi, Well you don't have a lex rule for variables. The post you mentioned doesn't include this rule, neither does the calculator example. An example would be:
You need to define this rule after all your constants and before your EOF rule. It is a but more permissive than required, but it works and it is easy to read. ps. I can really suggest using a .jison file and use the cmd like ( |
Hi @felixfrtz 👋🏻 It is a really old question but I came across this today and would like to share my thoughts. As per @blackshadev suggestion, it would be good to use /* description: Parses and executes mathematical expressions. */
/* lexical grammar */
%lex
%%
\s+ /* skip whitespace */
[0-9]+("."[0-9]+)?\b return 'NUMBER'
"*" return '*'
"/" return '/'
"-" return '-'
"+" return '+'
"^" return '^'
"!" return '!'
"%" return '%'
"(" return '('
")" return ')'
"PI" return 'PI'
"E" return 'E'
+[a-zA-Z_][a-zA-Z0-9_]* return 'NAME'
+\'[^\']*\' return 'STRING'
+\"[^\"]*\" return 'STRING'
+"TRUE" return 'TRUE'
+"true" return 'TRUE'
+"FALSE" return 'FALSE'
+"false" return 'FALSE'
+"NULL" return 'NULL'
<<EOF>> 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;}
| NUMBER
{$$ = Number(yytext);}
+ | NAME
+ { $$ = yy[yytext]; }
+ | STRING
+ {$$ = yytext.substring(1, yytext.length - 1);}
+ | TRUE
+ {$$ = true}
+ | FALSE
+ {$$ = false}
+ | NULL
+ {$$ = null}
| E
{$$ = Math.E;}
| PI
{$$ = Math.PI;}
; |
Hey,
I am trying to parse variables within the calculator example. My Code is as follows:
This leads to the following:
I used this post to accomplish this, but it isn't working. Any idea what is wrong with the example?
The text was updated successfully, but these errors were encountered: