private void Expect(Token.TokenType tokenType) { if (!IsNext(tokenType)) { throw new Exception($"Unexpected token {_lexer.Peek( )} at position {_lexer.Position}"); } }
private bool TryParseVariable(out ASTNode node) { node = null; if (IsNext(Token.TokenType.Identifier)) { var token = _lexer.Peek(); var stEntry = _symbolTable.Get(token.Value); if (stEntry == null) { throw new Exception($"Undefined Identifier {token.Value} at position {token.Position}"); } if (stEntry.Type == SymbolTableEntry.EntryType.Variable) { node = new VariableIdentifierASTNode(Accept( )); } } return(node != null); }
/// <summary> /// Parses the NUMBER Production Rule /// NUMBER: [0-9]+ /// </summary> /// <returns></returns> private static ASTNode ParseNumber(Lexer lexer) { var token = lexer.Peek(); if (token.Type != Token.TokenType.Number) { throw new Exception($"Invalid Expression. NUMBER Expected at position {lexer.Position}"); } lexer.Accept( ); //consume the token return(new NumberASTNode(token)); }
/// <summary> /// Parses the TERM Production Rule /// TERM: FACTOR [('*'|'/') FACTOR]* /// </summary> private static ASTNode ParseTerm(Lexer lexer) { var left = ParseFactor(lexer); var peekToken = lexer.Peek(); //look ahead 1 token while (peekToken.Type == Token.TokenType.Multiplication || peekToken.Type == Token.TokenType.Division) { var op = lexer.ReadNext( ); //read the operator var right = ParseFactor(lexer); if (right == null) { throw new Exception($"Invalid Expression. FACTOR Expected at position {lexer.Position}"); } left = CreateBinaryOperator(op, left, right); peekToken = lexer.Peek( ); //lookahead of 1 token LL(k) where K = 1 } return(left); }