Created
July 5, 2023 08:57
-
-
Save tluyben/0f9877bbe657d5f49122357f4a99d5c8 to your computer and use it in GitHub Desktop.
simple s-expression parser for typescript
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
export function parse(lisp: string) { | |
const lexer = /"[^"]*"|\(|\)|[^\s()]+/g; | |
const ts = lisp.match(lexer)!; | |
let i = 0 | |
const rec = () => { | |
let prg: any = undefined | |
while (i < ts.length) { | |
if (ts[i] === '(') { | |
if (!prg) { | |
prg = [] | |
} else { | |
prg.push(rec()) | |
} | |
} else if (ts[i] === ')') { | |
return prg | |
} else { | |
prg.push(ts[i]) | |
} | |
i++ | |
} | |
return prg | |
} | |
return rec() | |
} |
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
const test = ` | |
(progn | |
(dropempty query) | |
(keys result) | |
(drop result ('id 'access)) | |
(first result) | |
(if (ne result 'status) | |
(return 'Error "You cannot update this" 401) | |
(else (return 'Success))) | |
` | |
console.log(JSON.stringify(parse(test))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment