Beispiel #1
0
        /**
         * 对某个AST节点求值,并打印求值过程。
         * @param node
         * @param indent  打印输出时的缩进量,用tab控制
         * @return
         */
        private int evaluate(IASTNode node, string indent)
        {
            int result = 0;

            Console.WriteLine(indent + "Calculating: " + node.getType());
            switch (node.getType())
            {
            case ASTNodeType.Programm:
                foreach (IASTNode child in node.getChildren())
                {
                    result = evaluate(child, indent + "\t");
                }
                break;

            case ASTNodeType.Additive:
                IASTNode child1 = node.getChildren()[0];
                int      value1 = evaluate(child1, indent + "\t");
                IASTNode child2 = node.getChildren()[1];
                int      value2 = evaluate(child2, indent + "\t");
                if (node.getText() == "+")
                {
                    result = value1 + value2;
                }
                else
                {
                    result = value1 - value2;
                }
                break;

            case ASTNodeType.Multiplicative:
                child1 = node.getChildren()[0];
                value1 = evaluate(child1, indent + "\t");
                child2 = node.getChildren()[1];
                value2 = evaluate(child2, indent + "\t");
                if (node.getText() == "*")
                {
                    result = value1 * value2;
                }
                else
                {
                    result = value1 / value2;
                }
                break;

            case ASTNodeType.IntLiteral:
                result = Convert.ToInt32(node.getText());
                break;

            default:
                break;
            }
            Console.WriteLine(indent + "结果:" + result);
            return(result);
        }
Beispiel #2
0
 private void dumpAST(IASTNode node, string indent)
 {
     Console.WriteLine(indent + node.getType() + " " + node.getText());
     recurCount++;
     if (recurCount < 9999) // 递归次数限制,防止过深递归
     {
         foreach (IASTNode childNode in node.getChildren())
         {
             dumpAST(childNode, indent + "\t");
         }
     }
     else
     {
         Console.WriteLine("递归层数超过9999");
     }
 }