Exemple #1
0
        /* private static void DebugAstPrint(Node tree, int depth = 0)
         * {
         *  var top = tree as Operation;
         *  if (top != null)
         *  {
         *      if (depth != 0) Interpreter.Write("(");
         *      DebugAstPrint(top.left, depth + 1);
         *
         *      Interpreter.Write(" " + top.op.symbol + " ");
         *
         *      DebugAstPrint(top.right, depth + 1);
         *      if (depth != 0) Interpreter.Write(")");
         *
         *      return;
         *  }
         *
         *  var tvar = tree as Variable;
         *  if (tvar != null) Interpreter.Write(tvar.value);
         * } */

        public static Node OptimizeExpression(Node expression)
        {
            var eop = expression as Operation;

            if (eop != null)
            {
                var left  = OptimizeExpression(eop.left);
                var right = OptimizeExpression(eop.right);

                var var_l = left as Variable;
                var var_r = right as Variable;

                if (var_l != null && var_r != null)
                {
                    if (var_l.type != "variable" && var_r.type != "variable")
                    {
                        switch (eop.op.symbol)
                        {
                        case "+": return(VariableOperations.sum(var_l, var_r));

                        case "-": return(VariableOperations.sub(var_l, var_r));

                        case "*": return(VariableOperations.mul(var_l, var_r));

                        case "/": return(VariableOperations.div(var_l, var_r));

                        case "%": return(VariableOperations.res(var_l, var_r));
                        }
                    }
                }

                return(new Operation(eop.op, left, right));
            }

            return(expression);
        }