Created
March 6, 2025 15:14
-
-
Save rob-gordon/239d851bb17034a34eccf653ac8b2ab3 to your computer and use it in GitHub Desktop.
Unsound lisp ast parser for RC
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 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