Skip to content

Instantly share code, notes, and snippets.

@zuchmanski
Last active January 3, 2016 07:19
Show Gist options
  • Save zuchmanski/8428382 to your computer and use it in GitHub Desktop.
Save zuchmanski/8428382 to your computer and use it in GitHub Desktop.
/* description: Parses end executes mathematical expressions. */
/* lexical grammar */
%lex
%%
\n return 'NL'
\s+ /* skip whitespace */
\/\/\s(.+)?\b /* skip comments */
("2"\')([0-9]+)\b return 'BINARY'
("10"\')([0-9]+)\b return 'DECIMAL'
R[0-9]\b return 'REGISTRY'
"MOV" return 'MOV'
"ADD" return 'ADD'
<<EOF>> return 'EOF'
. return 'INVALID'
/lex
/* operator associations and precedence */
%start file
%% /* language grammar */
file
: expressions EOF
{ console.log($1); return 1 }
;
expressions
:
| expressions line
{
$$ = $expressions || [];
if($line.constructor == Array) $$.push($line)
}
;
line
: 'NL'
| e 'NL'
{ $$ = $1 }
;
e
: 'MOV' REGISTRY REGISTRY
{ console.log('MOV1', $2, $3); $$ = ['MOV1', $2, $3] }
| 'MOV' REGISTRY number
{ console.log('MOV2', $2, $3); $$ = ['MOV2', $2, $3] }
| 'ADD' REGISTRY REGISTRY
{ console.log('ADD', $2, $3); $$ = ['ADD', $2, $3] }
;
number
: BINARY
{ var r = /2\'([0-9]+)/.exec($1); $$ = r[1]; }
| DECIMAL
{ var dec = /10\'([0-9]+)/.exec($1)[1]; var bin = parseInt(dec, 10).toString(2); console.log('dec:', bin); $$ = bin; }
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment