package parser import ( "code.osinet.fr/fgm/waiig15/ast" "code.osinet.fr/fgm/waiig15/lexer" "code.osinet.fr/fgm/waiig15/token" "fmt" ) type Parser struct { errors []string l *lexer.Lexer curToken token.Token peekToken token.Token } func New(l *lexer.Lexer) *Parser { p := &Parser{ l: l, errors: []string{}, } // Read two tokens, so curToken and peeToken are both set. p.nextToken() p.nextToken() return p } func (p *Parser) Errors() []string { return p.errors } 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 } else { p.peekError(t) return false } } func (p *Parser) nextToken() { p.curToken = p.peekToken p.peekToken = p.l.NextToken() } func (p *Parser) parseLetStatement() *ast.LetStatement { stmt := &ast.LetStatement{ Token: p.curToken, } // Let statement starts with an IDENT token, so if next token is not an // IDENT, the next statement cannot be a Let statement. if !p.expectPeek(token.IDENT) { return nil } stmt.Name = &ast.Identifier{ Token: p.curToken, Value: p.curToken.Literal, } // The previous expectPeek() call fetched the next token, so we should now // be on the assignment. if !p.expectPeek(token.ASSIGN) { return nil } // Skip the expression for now, progress to the semicolon terminating the // statement. for !p.curTokenIs(token.SEMICOLON) { p.nextToken() } return stmt } func (p *Parser) parseStatement() ast.Statement { switch p.curToken.Type { case token.LET: return p.parseLetStatement() default: return nil } } // 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 }