Generate an AST in C++

前端 未结 4 760
谎友^
谎友^ 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条回答
  •  猫巷女王i
    2021-02-04 22:51

    You could use some parser generator like bison or ANTLR. Both have good documentations with tutorial part. The action part of your grammar rules (fed to bisonor antlr, which generates C++ code for parsing) would build the abstract syntax tree.

    We can't help more without knowing more the syntax (and the semantics) of the formal language you want to parse and interpret.

    If your language is an infix calculator, bison has such an example.

    You probably should think of a class hierarchy to represent the nodes of your AST. You'll have a class for leafs (e.g. numbers), a class for addition node (with two sons as smart pointers to other nodes), etc...

    e.g.

    class ASTNode {
    /// from http://stackoverflow.com/a/28530559/841108
    ///... add some things here, e.g. a virtual print method
    };
    
    class NumberNode : public ASTNode {
       long number;
       /// etc...
    };
    
    class BinaryOpNode : public ASTNode {
       std::unique_ptr left;
       std::unique_ptr right;
     /// etc....
    };
    
    class AdditionNode : public BinaryOpNode {
    /// etc....
    };
    
    class CallNode : public ASTNode {
       std::shared_ptr func;
       std::vector> args;
    };
    

    for nodes of variadic arity (i.e. any number of sons) you'll need a vector of smart pointers, like args above.

    To traverse the tree, you'll do a recursive traversal so you better use smart pointers. Read also about the visitor pattern. And with C++11 std::function-s and anonymous closures -i.e lambdas- , you could have a visit virtual function (to which you give a closure visiting each node). The Unix nftw(3) function which visits file trees could be inspirational.

提交回复
热议问题