Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
grammar pseudo language
/* description: Parses end executes mathematical expressions. */
/* lexical grammar */
%lex
%%
\s+ /* skip whitespace */
[0-9]+("."[0-9]+)?\b return 'NUMBER'
"true" return 'TRUE'
"false" return 'FALSE'
"not" return 'NOT'
"and" return 'AND'
"or" return 'OR'
"def" return 'DEF'
"end" return 'END'
"println" return 'PRINTLN'
[a-zA-Z_][a-zA-Z0-9_]* return 'ID'
"%" return '%'
"=" return 'EQUAL'
"!=" return '='
"*" return '*'
"/" return '/'
"-" return '-'
"+" return '+'
">" return '>'
"<" return '<'
">=" return '>='
"<=" return '<='
"^" return '^'
"(" return 'PAR_OPEN'
")" return 'PAR_CLOSE'
"PI" return 'PI'
"E" return 'E'
";" return 'SEMICOL'
\"(?:\"\"|[^"])*\" return 'STRING'
<<EOF>> return 'EOF'
. return 'INVALID'
/lex
/* operator associations and precedence */
%left '%'
%left '+' '-'
%left '*' '/'
%left '^'
%left '>' '<' '>=' '<='
%left 'NOT'
%left 'AND' 'OR'
%left '=' '<>'
%left UMINUS
%start expressions
%% /* language grammar */
expressions
: e EOF
{return $1;}
| FUNCTION EOF
{return $1;}
;
e
: e '+' e
{$$ = $1+$3;}
| 'NOT' e
{$$ = !$2;}
| e 'OR' e
{$$ = $1 || $3;}
| e 'AND' e
{$$ = $1 && $3;}
| e '=' e
{$$ = $1 == $3;}
| e '<>' e
{$$ = $1 != $3;}
| e '-' e
{$$ = $1-$3;}
| e '*' e
{$$ = $1*$3;}
| e '/' e
{$$ = $1/$3;}
| e '>' e
{$$ = $1>$3;}
| e '<' e
{$$ = $1<$3;}
| e '>=' e
{$$ = $1>=$3;}
| e '<=' e
{$$ = $1<=$3;}
| e '^' e
{$$ = Math.pow($1, $3);}
| '-' e %prec UMINUS
{$$ = -$2;}
| '(' e PAR_CLOSE
{$$ = $2;}
| e '%'
{$$ = $1 / 100;}
| TRUE
{$$ = true;}
| FALSE
{$$ = false;}
| NUMBER
{$$ = Number(yytext);}
| STRING
{$$ = $1;}
| IDENT
{$$ = __data__[$1];}
| E
{$$ = Math.E;}
| PI
{$$ = Math.PI;}
;
FUNCTION
: DEF ID PAR_OPEN PAR_CLOSE
SENTENCE*
END
{ $$ = 'function ' + $2 + '(){' + $5 + '}' };
SENTENCE
: PRINT
| VAR_ASSIGN
|;
PRINT
: PRINTLN PAR_OPEN? e PAR_CLOSE?
{ $$ = 'echo ' + $e + ';' }
| PRINTLN e
{ $$ = 'echo ' + $e + ';' };
VAR_ASSIGN
: ID EQUAL e { $$ = '$' + $1 + '=' + $3 };
UNARY_OPERATOR
: '&'
| '*'
| '+'
| '-'
| '~'
| '!'
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment