public TreeNode Parse(PositionQueue <IToken> pTokens) { /* * 1. * Get the first item and initialise the tree with it. */ TreeNode root = new TreeNode(pTokens.Dequeue()); /* * 2. * Currently the root node is also the current node. * The current node is the node we currently lie on. */ TreeNode current = root; while (pTokens.Count > 0) { /* * 3. * Get the next item. * This will be called the new item. */ current = ProcessTokenToNode(pTokens.Dequeue(), current); } while (current.Parent != null) { current = current.Parent; } return(current); }
private static void Main(string[] args) { while (true) { System.Console.Write("Please input the expression: "); string lInput = System.Console.ReadLine(); try { Lexer lexer = new Lexer(); PositionQueue <IToken> tokens = lexer.Analyze(lInput); foreach (IToken token in tokens.ToArray()) { System.Console.WriteLine(token); } System.Console.ReadKey(); Parser parser = new Parser(); TreeNode tree = parser.Parse(tokens); BTreePrinter.Print(tree); System.Console.ReadKey(); double result = tree.Evaluate(); System.Console.WriteLine($" => {result}"); } catch (Exception e) { System.Console.WriteLine($"{e.GetType().Name}: {e.Message}"); System.Console.WriteLine(); } System.Console.ReadKey(); } }
public double Evaluate(string pExpression) { try { PositionQueue <IToken> tokens = Lexer.Analyze(pExpression); TreeNode treeNode = Parser.Parse(tokens); return(treeNode.Evaluate()); } catch (Exception e) { LastError = e; throw new CouldNotEvaluateException(e); } }
public bool IsValid(string pExpression) { try { PositionQueue <IToken> tokens = Lexer.Analyze(pExpression); TreeNode treeNode = Parser.Parse(tokens); return(true); } catch (Exception e) { LastError = e; } return(false); }
public PositionQueue <IToken> Analyze(string pInput) { Tokens = new PositionQueue <IToken>(); Chars = BuildQueue(pInput); while (Chars.Count > 0) { IToken token = null; if (IsWhitespace(Chars.Peek())) { Chars.Dequeue(); } else if (IsDigit(Chars.Peek())) { token = ReadNumber(); } else if (IsOperation(Chars.Peek())) { if (Tokens[Tokens.Count - 1].GetTokenType() == TokenType.Operator) { throw new NotImplementedException($"unexpected symbol \"{Chars.Dequeue()}\" at position {Chars.Position}"); } else { token = ReadOperation(); } } else { throw new NotImplementedException($"unexpected symbol \"{Chars.Dequeue()}\" at position {Chars.Position}"); } if (token != null) { Tokens.Enqueue(token); } } return(Tokens); }