Exemplo n.º 1
0
        private static decimal Execute(List <Token> inst, EvalContext param)
        {
            var     stack = new Stack <object>();
            object  obj;
            decimal d1, d2;

            foreach (var token in inst)
            {
                switch (token.Type)
                {
                case TokenType.Number: stack.Push(Convert.ToDecimal(token.Value)); break;

                case TokenType.ID:
                    if (param.TryGetValue(token.Value, out obj))
                    {
                        stack.Push(obj);
                    }
                    else
                    {
                        throw new Exception("ID '" + token.Value + "' not found.");
                    }
                    break;

                case TokenType.Operator:
                    if (token.Tag == Tag.Unary)
                    {
                        d1 = Convert.ToDecimal(stack.Pop());
                        switch (token.Value)
                        {
                        case "+": stack.Push(d1); break;

                        case "-": stack.Push(-d1); break;
                        }
                    }
                    else
                    {
                        d2 = Convert.ToDecimal(stack.Pop());
                        d1 = Convert.ToDecimal(stack.Pop());
                        switch (token.Value)
                        {
                        case "+": stack.Push(d1 + d2); break;

                        case "-": stack.Push(d1 - d2); break;

                        case "*": stack.Push(d1 * d2); break;

                        case "/": stack.Push(d1 / d2); break;
                        }
                    }
                    break;

                case TokenType.Dot:
                    throw new NotSupportedException();

                case TokenType.CallStart: stack.Push(TokenType.CallStart); break;

                case TokenType.CallEnd:
                    var p = new Stack <object>();
                    while (!TokenType.CallStart.Equals(obj = stack.Pop()))
                    {
                        p.Push(obj);
                    }
                    obj = (stack.Pop() as Delegate).DynamicInvoke(p.ToArray());
                    stack.Push(obj);
                    break;
                }
            }
            return(stack.Count <= 0 ? 0 : Convert.ToDecimal(stack.Pop()));
        }