Generate an AST in C++

前端 未结 4 759
谎友^
谎友^ 2021-02-04 22:06

I\'m making an interpreter in C++, so far I\'ve got my lexer to generate tokens. The problem is I\'m not sure how to generate an \"walk\" a parse tree.

I was thinking of

4条回答
  •  被撕碎了的回忆
    2021-02-04 22:34

    I used a set of BNF production methods to generate nodes (struct inheritance) of a specific type for generating the AST. With std::move(), you can transfer the pointer ownership to avoid dangling pointers. Then there is a public recursive visit method (switch-case) that traverses the AST following a certain traversal pattern (post/pre order), checks for the AST node type and executes an accept() for each visit. The accepts are bind to a dispatcher interface which must be implemented by the user (print the tree, execute the tree, etc.). For each visit the corresponding method on user side is called.

提交回复
热议问题