Skip to content

Instantly share code, notes, and snippets.

@b0oh
Created September 4, 2012 07:13
Show Gist options
  • Save b0oh/3617903 to your computer and use it in GitHub Desktop.
Save b0oh/3617903 to your computer and use it in GitHub Desktop.
js s-expr pareser
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