コード例 #1
0
 public static void PrintTree(TreeNode tree, string spacing)
 {
     if (tree.Op != null)
     {
         Console.WriteLine(spacing + "+" + tree.Op);
         PrintTree(tree.Left, spacing + " ");
         PrintTree(tree.Right, spacing + " ");
     }
     else
         Console.WriteLine(spacing + tree.Value);
 }
コード例 #2
0
 public static void PrintTree(TreeNode tree)
 {
     PrintTree(tree, "");
 }
コード例 #3
0
        public static int Execute(TreeNode root)
        {
            DynamicMethod method = new DynamicMethod("Exec_" + i++,
                                                     typeof(int),
                                                     new Type[] { },
                                                     typeof(Program).Module);

            ILGenerator generator = method.GetILGenerator();

            ILStack = new Stack<MathOpOrVal>();
            BuildStack(ILStack, root);

            while (ILStack.Count > 0)
            {
                MathOpOrVal mv = ILStack.Pop();
                if (mv.Op != null)
                {
                    switch (mv.Op)
                    {
                        case MathOp.Add:
                            Console.WriteLine("add");
                            generator.Emit(OpCodes.Add);
                            break;

                        case MathOp.Sub:
                            Console.WriteLine("sub");
                            generator.Emit(OpCodes.Sub);
                            break;

                        case MathOp.Mul:
                            Console.WriteLine("mul");
                            generator.Emit(OpCodes.Mul);
                            break;

                        case MathOp.Div:
                            Console.WriteLine("div");
                            generator.Emit(OpCodes.Div);
                            break;
                    }
                }
                else
                {
                    Console.WriteLine("ldc " + mv.Value.Value);
                    generator.Emit(OpCodes.Ldc_I4, mv.Value.Value);
                }
            }

            generator.Emit(OpCodes.Ret);

            return (int)method.Invoke(null,
                                      BindingFlags.ExactBinding,
                                      null,
                                      new object[] { },
                                      null);
        }
コード例 #4
0
 public TreeNode(MathOp op, TreeNode left, TreeNode right)
 {
     Op = op;
     Left = left;
     Right = right;
 }
コード例 #5
0
 public static void BuildStack(Stack<MathOpOrVal> stack, TreeNode root)
 {
     if (root.Op != null)
     {
         MathOpOrVal mv = new MathOpOrVal(root.Op.Value);
         stack.Push(mv);
         BuildStack(stack, root.Right);
         BuildStack(stack, root.Left);
     }
     else
     {
         MathOpOrVal mv = new MathOpOrVal(root.Value.Value);
         stack.Push(mv);
     }
 }