package parser import ( "fmt" "code.osinet.fr/fgm/waiig15/ast" "code.osinet.fr/fgm/waiig15/lexer" "code.osinet.fr/fgm/waiig15/token" ) // Precedence constants. const ( _ int = iota LOWEST EQUALS // == LESSGREATER // > or < SUM // + PRODUCT // * PREFIX // -X or !X CALL // myFunction(X) ) // Parser implements the parsing mechanism top-level layer. type Parser struct { errors []string l *lexer.Lexer curToken token.Token peekToken token.Token prefixParseFns map[token.TokenType]prefixParseFn infixParseFns map[token.TokenType]infixParseFn } type ( prefixParseFn func() ast.Expression infixParseFn func(ast.Expression) ast.Expression ) // New returns a new Parser instance with the first two parser tokens already // loaded. func New(l *lexer.Lexer) *Parser { p := &Parser{ l: l, errors: []string{}, } p.prefixParseFns = make(map[token.TokenType]prefixParseFn) p.registerPrefix(token.IDENT, p.parseIdentifier) // Read two tokens, so curToken and peeToken are both set. p.nextToken() p.nextToken() return p } // Errors is a getter for Parser.errors. func (p *Parser) Errors() []string { return p.errors } // ParseProgram is the outermost parsing logic, accumulating statements in a // Program instance and returning that instance once parsing is done. func (p *Parser) ParseProgram() *ast.Program { program := &ast.Program{ Statements: []ast.Statement{}, } for !p.curTokenIs(token.EOF) { stmt := p.parseStatement() if stmt != nil { program.Statements = append(program.Statements, stmt) } p.nextToken() } return program } // Is the current token in the parser of the given type ? func (p *Parser) curTokenIs(t token.TokenType) bool { return p.curToken.Type == t } // Is the next token in the parser of the given type ? If it is, consume it, // else don't. func (p *Parser) expectPeek(t token.TokenType) bool { if p.peekTokenIs(t) { p.nextToken() return true } p.peekError(t) return false } func (p *Parser) nextToken() { p.curToken = p.peekToken p.peekToken = p.l.NextToken() } func (p *Parser) parseStatement() ast.Statement { switch p.curToken.Type { case token.LET: return p.parseLetStatement() case token.RETURN: return p.parseReturnStatement() default: return p.parseExpressionStatement() } } // Log a mismatch error on the peek token type in the parser instance. // // - t is the type of token that was expected func (p *Parser) peekError(t token.TokenType) { msg := fmt.Sprintf("expected next token to be %s, got %s instead", t, p.peekToken.Type) p.errors = append(p.errors, msg) } // Is the next token in the parser of the given type ? Don't consume it. func (p *Parser) peekTokenIs(t token.TokenType) bool { return p.peekToken.Type == t }