Created
October 31, 2014 13:56
-
-
Save maxrothman/b83607be8408d3500aaf to your computer and use it in GitHub Desktop.
spreadsheet-like formula jison language spec
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Parses end executes mathematical expressions with functions mixed in. | |
* TODO: add referencing symbols elsewhere on the page (via some selector). | |
**/ | |
%{ | |
var funcs = { | |
pow: function(a,b) { return Math.pow(a,b); }, | |
test: function(a) { return a*2; } | |
} | |
%} | |
/* lexical grammar */ | |
%lex | |
%% | |
\s+ /* skip whitespace */ | |
[0-9]+("."[0-9]+)?\b return 'NUMBER' | |
[a-zA-Z]+ return 'NAME' | |
"," return ',' | |
"*" return '*' | |
"/" return '/' | |
"-" return '-' | |
"+" return '+' | |
"(" return '(' | |
")" return ')' | |
<<EOF>> return 'EOF' | |
. return 'INVALID' | |
/lex | |
/* operator associations and precedence */ | |
%left '+' '-' | |
%left '*' '/' | |
%left UMINUS | |
%start expressions | |
%% /* language grammar */ | |
expressions | |
: e EOF | |
{ console.log($1); return $1; } | |
; | |
expression_list | |
: expression_list ',' e | |
{ $$ = $1.concat([$3]); } | |
| e | |
{ $$ = [$1]; } | |
; | |
e | |
: e '+' e | |
{$$ = $1+$3;} | |
| e '-' e | |
{$$ = $1-$3;} | |
| e '*' e | |
{$$ = $1*$3;} | |
| e '/' e | |
{$$ = $1/$3;} | |
| '-' e %prec UMINUS | |
{$$ = -$2;} | |
| '(' e ')' | |
{$$ = $2;} | |
| NUMBER | |
{$$ = Number(yytext);} | |
| NAME '(' expression_list ')' | |
{$$ = funcs[$1].apply(undefined, $3);} | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment