Created
September 4, 2012 07:13
-
-
Save b0oh/3617903 to your computer and use it in GitHub Desktop.
js s-expr pareser
This file contains 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
String.prototype.fixSpaces = function () { | |
return this.replace(/\s+/g, ' ').trim(); | |
}; | |
var Symbol = String; | |
function tokenize(s) { | |
return s.replace(/([()])/g, ' $1 ').fixSpaces().split(' '); | |
}; | |
function read(s) { | |
return readTokens(tokenize(s)); | |
} | |
function readTokens(tokens) { | |
var token, readed; | |
if (tokens.length == 0) { | |
throw 'Unexpected end of file'; | |
} | |
token = tokens.shift(); | |
if (token == '(') { | |
readed = []; | |
while (tokens[0] != ')') { | |
readed.push(readTokens(tokens)); | |
} | |
tokens.shift(); | |
return readed; | |
} | |
else if (token == ')') { | |
throw 'Unexpected )'; | |
} | |
return atom(token); | |
} | |
function atom(token) { | |
if (token.match(/^-?(\d+)(\.\d+)?$/)) { | |
return Number(token); | |
} | |
return Symbol(token); | |
} | |
function repl() { | |
var inp = process.stdin, | |
out = process.stdout, | |
prompt = '> '; | |
inp.setEncoding('utf8'); | |
out.setEncoding('utf8'); | |
out.write(prompt); | |
inp.resume(); | |
inp.on('data', function (chunk) { | |
console.dir(read(chunk)); | |
out.write(prompt); | |
}); | |
} | |
repl(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment