예제 #1
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));
        }
예제 #2
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);
     }
 }
 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);
     }
 }