Reputation:
I have already written a lexer which returns tokens, and now I'm working on a parser. I have one problem.
Imagine this code example:
print("Hello, world!")
The lexer returns four tokens (print
, (
, "Hello, world!"
and )
). The final program should print the string "Hello, world!".
But what should the parser do? Should the parser already execute the code, should it return something (and what) that is handled by another object?
Upvotes: 1
Views: 500
Reputation: 47749
The parser should basically do two things:
Upvotes: 0
Reputation: 300229
Typically, a parser does not execute anything. Parsers usually take an input (text or binary) and produce an in-memory representation, nothing more... but that's already much!
If you already have a Lexer, then the second step is normally to perform Semantic Analysis, to produce an Abstract Syntax Tree.
This means, producing something of the form:
(FunctionCall "print" [
(StringLiteral "Hello, World!")
]
)
Upvotes: 1
Reputation: 359986
What should the parser do?
The typical role of a parser is to read the stream of tokens and, from that, build a parse tree or abstract syntax tree.
Should the parser already execute the code
No. That's not parsing.
Upvotes: 1
Reputation: 21204
The parser should generate an abstract syntax tree, which is an in memory representation of the program. This tree can be traversed after parsing to do the code generation. I'd recommend to read some good book about the subject, maybe one involving dragons.
Upvotes: 5