Ejemplo n.º 1
0
 public void AddExpressionToken(ExpressionToken token)
 {
     ExpressionTokens.Add(token);
 }
Ejemplo n.º 2
0
        public static Expression ParseExpression(string expression)
        {
            List <ExpressionToken> parsedTokens = new List <ExpressionToken>();

            char?  parsedOperator = null;
            string parsedValue    = "";
            char?  parsedName     = null;

            for (int index = 0; index < expression.Length; index++)
            {
                char thisChar = expression[index];

                if (thisChar == '+' || thisChar == '-')   //plus or minus operator
                {
                    //could denote end of previous Expression token
                    if (parsedValue.Length > 0 || parsedName != null)
                    {
                        parsedTokens.Add(ToExpressionToken(parsedOperator, parsedValue, parsedName));
                        //reset parse state for next ExpressionToken
                        parsedOperator = null;
                        parsedValue    = "";
                        parsedName     = null;
                    }

                    if (parsedOperator != null)
                    {
                        throw new ArgumentException("Cannot have two consecutive operators");
                    }
                    else
                    {
                        parsedOperator = thisChar;
                    }
                }
                else if (thisChar == ' ') //ignore whitespace
                {
                    continue;
                }
                else if (int.TryParse(thisChar + "", out _))
                {
                    if (parsedName != null)
                    {
                        throw new ArgumentException("Cannot have another number after token name");
                    }
                    parsedValue += thisChar;
                }
                else if (ExpressionToken.IsValidName(thisChar))
                {
                    if (parsedName == null)
                    {
                        parsedName = thisChar;
                    }
                    else
                    {
                        throw new ArgumentException("Cannot have token names with multiple characters");
                    }
                }
                else
                {
                    throw new ArgumentException($"Didn't understand '{thisChar}'");
                }

                //if no more characters then need to add final token
                if (index == expression.Length - 1)
                {
                    parsedTokens.Add(ToExpressionToken(parsedOperator, parsedValue, parsedName));
                }
            }

            Expression parsedExpression = new Expression();

            parsedExpression.AddAllExpressionTokens(parsedTokens);
            return(parsedExpression);
        }