package parser import ( "code.osinet.fr/fgm/waiig15/ast" "code.osinet.fr/fgm/waiig15/lexer" "code.osinet.fr/fgm/waiig15/token" ) type Parser struct { l *lexer.Lexer curToken token.Token peekToken token.Token } func New(l *lexer.Lexer) *Parser { p := &Parser{l: l} // Read two tokens, so curToken and peeToken are both set. p.nextToken() p.nextToken() return p } func (p *Parser) nextToken() { p.curToken = p.peekToken p.peekToken = p.l.NextToken() } 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 } func (p *Parser) parseStatement() ast.Statement { switch p.curToken.Type { case token.LET: return p.parseLetStatement() default: return nil } } 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 } // 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 ? Don't consume it. func (p *Parser) peekTokenIs(t token.TokenType) bool { return p.peekToken.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 { return false } }