r/ProgrammingLanguages • u/M1M1R0N • Apr 29 '26
Help significant whitespace-friendly Rust parser generator ?
Hello
I don't know if questions like this are accepted here. If they're not, please let me know.
I have been playing around with writing a tiny compiler to WASM. The syntax I have in mind is roughly something like this
fn div_rem(x: int, y: int) (int, int)
let div, rem = x / y, x % y
return div, remNow, I don't want to commit too hard into a specific syntax or grammar, so so far I have been just typing out the AST manually.
I never used a parser generator before, but I couldn't find one that's well documented and whitespace friendly. pest is the "friendliest" parser generator I found, but it doesn't play nice with significant indentation if it uses the same characters as the WHITESPACE rule.
So .. er .. long story short: I've read parser generators are easier to experiment with than writing parsers manually, but I am looking for suggestions for one that would let me do INDENT and DEDENT tokens ala Python and just let me go to work.
View all comments
Show parent comment
1
u/AustinVelonaut Admiran Apr 30 '26
I've actually found it simpler (at least in my case, using parser-combinators) to have the layout (offside-rule) processing in the parser, rather than the lexer. The lexer simply streams tokens with their line/col location, and the parser has 4 parser-combinators for layout handling:
p_indent,p_any,p_outdent, andp_inLayout:p_indentjust pushes the current token column onto the indent level stack.p_anygets the next token and compares its column to the top of the indent-level stack. If the token col is >= the indent level, it returns it, otherwise it inserts aToffsidetoken.p_outdentchecks for a terminator (either an explicit;or aToffsidetoken), then pops the indent-level stack.a
p_inLayoutcombinator simply performs a parser action betweenp_indentandp_outdent.Then the lexer is layout-agnostic, and the parser can isolate layout handling to whatever higher-level parsers need it, rather than dealing with it everywhere. And handling multiple
Toffsideinsertions occurs naturally as the indent-level stack is popped.