Last active
October 11, 2016 04:47
-
-
Save kosamari/041282ca510f9d5e699dc4c419688422 to your computer and use it in GitHub Desktop.
parser function for sbn compiler
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
function parser (tokens) { | |
var AST = { | |
type: 'Drawing', | |
body: [] | |
} | |
// extract a token at a time as current_token. Loop until we are out of tokens. | |
while (tokens.length > 0){ | |
var current_token = tokens.shift() | |
// Since number token does not do anything by it self, we only analyze syntax when we find a word. | |
if (current_token.type === 'word') { | |
switch (current_token.value) { | |
case 'Paper' : | |
var expression = { | |
type: 'CallExpression', | |
name: 'Paper', | |
arguments: [] | |
} | |
// if current token is CallExpression of type Paper, next token should be color argument | |
var argument = tokens.shift() | |
if(argument.type === 'number') { | |
expression.arguments.push({ // add argument information to expression object | |
type: 'NumberLiteral', | |
value: argument.value | |
}) | |
AST.body.push(expression) // push the expression object to body of our AST | |
} else { | |
throw 'Paper command must be followed by a number.' | |
} | |
break | |
case 'Pen' : | |
... | |
case 'Line': | |
... | |
} | |
} | |
} | |
return AST | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment