Created
September 28, 2015 15:55
-
-
Save sundarj/25fd581fee3dece9dda6 to your computer and use it in GitHub Desktop.
top-down operator parsing in JS (port of http://eli.thegreenplace.net/2010/01/02/top-down-operator-precedence-parsing)
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
var currentToken, tokens; | |
function nextToken() { | |
return tokens.next().value; | |
} | |
function express(precedence) { | |
var token = currentToken; | |
currentToken = nextToken(); | |
precedence = precedence || 0; | |
var left = token.nud(); | |
while (precedence < currentToken.precedence) { | |
token = currentToken; | |
currentToken = nextToken(); | |
left = token.led(left); | |
} | |
return left; | |
} | |
function Literal(value) { | |
this.value = parseInt(value, 10); | |
this.nud = function () { | |
return this.value; | |
} | |
} | |
function Add(left) { | |
this.precedence = 10; | |
this.led = function (left) { | |
return left + express(this.precedence); | |
} | |
} | |
function Mul(left) { | |
this.precedence = 20; | |
this.led = function (left) { | |
return left * express(this.precedence); | |
} | |
} | |
function End() { | |
this.precedence = 0; | |
} | |
var tokenRegex = /\s*(?:(\d+)|(.))/g; | |
function *tokenize(program) { | |
var toks = program.match(tokenRegex); | |
for (var i of toks) { | |
if (/\d+/.test(i)) | |
yield (new Literal(i)); | |
else if (i === '+') | |
yield (new Add) | |
else if (i === '*') | |
yield (new Mul) | |
} | |
yield (new End); | |
} | |
function parse(program) { | |
tokens = tokenize(program); | |
currentToken = nextToken(); | |
return express(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment