【问题标题】:AST interpreter?AST 解释器?
【发布时间】:2015-04-23 16:51:53
【问题描述】:

我有一个 AST(抽象语法树),现在我想通过给它 2 个或更多数字来测试我的编译器,并期望输出带有数学运算结果的输出(如计算器)。

我的问题是,构建解释器的最佳方式是什么? AST 节点的访问是递归的,所以在我到达树的末尾之前,我不知道存在多少封装计算。但是既然这是一个接一个的迭代,那我到底要怎么做所有的操作呢?

谢谢

【问题讨论】:

    标签: interpreter abstract-syntax-tree


    【解决方案1】:

    一旦你有了 AST,解释器就很容易编写代码:

     int interpret(tree t)
     { /* left to right, top down scan of tree */
       switch (t->nodetype) {
         case NodeTypeInt:
            return t->value;
         case NodeTypeVariable:
            return t->symbtable_entry->value
         case NodeTypeAdd:
            { int leftvalue= interpret(t->leftchild);
              int rightvalue= interpret(t->rightchild);
              return leftvalue+rightvalue;
            }
         case NodeTypeMultiply:
            { int leftvalue= interpret(t->leftchild);
              int rightvalue= interpret(t->rightchild);
              return leftvalue*rightvalue;
            }
         ...
         case NodeTypeStatementSequence: // assuming a right-leaning tree
            { interpret(t->leftchild);
              interpret(t->rightchild);
              return 0;
            }
         case NodeTypeAssignment:
            { int right_value=interpret(t->rightchild);
              assert: t->leftchild->Nodetype==NodeTypeVariable;
              t->leftchild->symbtable_entry->value=right_value;
              return right_value;
            }
         case NodeTypeCompareForEqual:
            { int leftvalue= interpret(t->leftchild);
              int rightvalue= interpret(t->rightchild);
              return leftvalue==rightvalue;
            }
         case NodeTypeIfThenElse
            { int condition=interpret(t->leftchild);
              if (condition) interpret(t->secondchild);
              else intepret(t->thirdchild);
              return 0;
         case NodeTypeWhile
            { int condition;
              while (condition=interpret(t->leftchild))
                    interpret(t->rightchild);
              return 0;
    
         ...
       }
     }
    

    令人讨厌的是“goto”,因为这会改变解释器的注意点。要实现 goto 或函数调用,必须在树中搜索标签或函数声明,然后在那里继续执行。 [可以通过预扫描树并在查找表中收集所有标签位置/函数声明来加快这一速度。这是构建编译器的第一步。] 即使这还不够;您必须调整递归堆栈,我们将其隐藏在函数调用中,因此这并不容易。如果将此代码转换为具有显式管理的递归堆栈的迭代循环,则修复堆栈会容易得多。

    【讨论】:

    • 如果中间有 if 语句和比较运算符,你会怎么做?
    • 查看解释器补丁以支持 CompareForEqual,Assignment,IfThenElse
    • 这种递归方法是否适合解释大型 ast
    • 这种方法不关心 AST 有多大,以查找函数名称和语句标签的时间为模,如果 AST 很大,则需要有效处理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    • 2023-04-01
    • 2022-10-02
    • 1970-01-01
    相关资源
    最近更新 更多