Search code examples
c++parsingprogramming-languages

What should a parser for a programming language do?


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?


Solution

  • 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.