Skip to content

Instantly share code, notes, and snippets.

@rob-gordon
Created March 6, 2025 15:14
Show Gist options
  • Save rob-gordon/239d851bb17034a34eccf653ac8b2ab3 to your computer and use it in GitHub Desktop.
Save rob-gordon/239d851bb17034a34eccf653ac8b2ab3 to your computer and use it in GitHub Desktop.
Unsound lisp ast parser for RC
function parse(str: string) {
let index = 0;
return walk(str);
function walk(str: string, container: any[] = []) {
let collect = "";
while (index < str.length) {
const char = str[index];
if (char === "(") {
next();
const children = walk(str, []);
container.push(children);
} else if (char === '"') {
const match = str.slice(index).match(/^"[^"\\]*(?:\\.[^"\\]*)*"/);
if (match) {
collect = "";
container.push(match[0]);
index += match[0].length;
continue;
}
} else if (char === ")") {
next();
return container;
} else if (char === " ") {
next();
} else {
collect += char;
index += 1;
}
}
if (collect) container.push(collect);
return container;
function next() {
if (collect && !/\r?\n+/.test(collect)) container.push(collect);
collect = "";
index += 1;
}
}
}
const ast = parse(`(map (lambda (x) (+ x 1)) (list 1 2 3 4)))`);
console.log(ast);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment