by justin_oaks · 3y ago · 0 comments
To those knowledgeable in lexing and parsing, I pose a question: How do you determine what should be part of the lexing phase and what should be part of the parsing phase? Do you choose arbitrarily and move things from one phase to another if it's simpler one way or another? Or is there a better way?
The benefit is that this keeps each stage much simpler: lexing doesn't have to do much if any lookaround, and parsing mostly doesn't have to do anything character-wise.
The example of using the same tokens but for different purposes makes it clear that the lexer shouldn't be in the business of assigning meaning (semantics) to the tokens, and the parser shouldn't be in the business of fiddling with characters when it's something the lexer can do.
Recursion. If your thing can contain other things, it requires a full parser. Otherwise a lexer can handle it.
In other words, use a lexer when a regular language is sufficient to describe the input and a parser when it's not.
Lexer:
12345
Parser: [123 [45]]The parser groups the tokens into meaningful statements, it implements the grammar. If the parser sees an "if", it expects some condition next (depending on the grammar of course). If the parser detects statements that are not consistent with the grammar of the language, it should reject the program.
Tldr they work on different levels, lexers just finds the individual building blocks, the parser builds the program