public List<Token> Lex(string str) { List<Token> TokenList = new List<Token>(); int iter = 0; while(true) { while (iter < str.Length && Char.IsWhiteSpace(str[iter])) iter++; Token token = new Token(); if (iter >= str.Length) { TokenList.Add(token); break; } else if (Char.IsNumber(str[iter])) { while (iter < str.Length && Char.IsNumber(str[iter])) token.Text += str[iter++]; token.Id = Token.TokenId.Number; } else { token.Text += str[iter++]; if (operators.Contains(token.Text)) token.Id = Token.TokenId.Operator; else token.Id = Token.TokenId.Unknown; } TokenList.Add(token); } return TokenList; }
public INode Parse(List<Token> Tokens) { iter = 0; tokens = Tokens; token = Tokens[iter++]; INode node = SumSub(); if (token.Id != Token.TokenId.END) throw new Exception("There is an excess part of expression"); return node; }
public INode Term() { INode node = null; if (token.Id == Token.TokenId.Number) { node = new ValueNode(double.Parse(token.Text)); token = tokens[iter++]; } else if (Accept("(")) { node = SumSub(); if (!Accept(")")) throw new Exception("Unmatched parentheses"); } else if (token.Id == Token.TokenId.Unknown) throw new Exception("unknown token " + token.Text); else if (token.Id == Token.TokenId.END) throw new Exception("Unexpected end of expression"); else throw new Exception("Unexpected token " + token.Text); return node; }
private bool Accept(string str) { if (token.Text == str) { token = tokens[iter++]; return true; } else return false; }