Ejemplo n.º 1
0
        public void Evaluate(string exp)
        {
            ExpressionBuilder expBuilder = new ExpressionBuilder();

            // build the exp form the input string
            IEvaluableExp evaluableExp = expBuilder.BuildExp(exp, m_EnvironmentVars);

            // update new var
            m_EnvironmentVars[expBuilder.Variable] = evaluableExp.GetEvaluateExpValue();
        }
Ejemplo n.º 2
0
        private IEvaluableExp BuildExpAfterAss(string exp, Dictionary <char, int> envVars)
        {
            if (string.IsNullOrEmpty(exp))
            {
                throw new InvalidExpressionException();
            }

            // special case "++/--" excluding ( '5++'+j )
            if (exp.Length > 2 && !Char.IsDigit(exp[0]) && (exp.Substring(0, 3).Contains("++") || exp.Substring(0, 3).Contains("--")))
            {
                IEvaluableExp leftexp = BuildExpPre(exp.Substring(0, 3), envVars);
                return(exp.Length == 3 ? leftexp :
                       new RegularExp(leftexp, GetOP(exp[3]), BuildExpAfterAss(exp.Substring(4), envVars)));
            }

            // +/- evalutint first order not important
            if (exp.Contains('+'))
            {
                var pivot = exp.IndexOf('+');
                (string lefExp, string rightExp) = SplitExpByPivot(exp, pivot);
                return(new RegularExp(BuildExpAfterAss(lefExp, envVars), OpEnum.Add, BuildExpAfterAss(rightExp, envVars)));
            }
            else if (exp.Contains('-'))
            {
                var pivot = exp.IndexOf('-');
                (string lefExp, string rightExp) = SplitExpByPivot(exp, pivot);
                return(new RegularExp(BuildExpAfterAss(lefExp, envVars), OpEnum.Sub, BuildExpAfterAss(rightExp, envVars)));
            }

            // mul is evaluted last because it has priorty in calculation over (+, -)
            else if (exp.Contains('*'))
            {
                var pivot = exp.IndexOf('*');
                (string lefExp, string rightExp) = SplitExpByPivot(exp, pivot);
                return(new RegularExp(BuildExpAfterAss(lefExp, envVars), OpEnum.Mul, BuildExpAfterAss(rightExp, envVars)));
            }

            // base case: exp is var('j') or num(79)
            if (IsSimpleExp(exp))
            {
                return(new SimpleExp(int.Parse(exp)));
            }
            else
            {
                if (exp.Length > 1)
                {
                    throw new InvalidExpressionException();
                }

                return(new VariableExp(exp[0], envVars));
            }
        }
Ejemplo n.º 3
0
 public RegularExp(IEvaluableExp leftExp, OpEnum op, IEvaluableExp rightExp)
 {
     m_LeftExp  = leftExp;
     c_Op       = op;
     m_RightExp = rightExp;
 }