123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- 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
- }
- }
|