Mako/parser/parser.go
2025-05-06 11:14:36 -05:00

111 lines
2.4 KiB
Go

package parser
import (
"fmt"
"strconv"
"git.sharkk.net/Sharkk/Mako/lexer"
)
type Parser struct {
l *lexer.Lexer
curToken lexer.Token
peekToken lexer.Token
errors []string
}
func New(l *lexer.Lexer) *Parser {
p := &Parser{l: l, errors: []string{}}
p.nextToken()
p.nextToken()
return p
}
func (p *Parser) nextToken() {
p.curToken = p.peekToken
p.peekToken = p.l.NextToken()
}
func (p *Parser) Errors() []string {
return p.errors
}
func (p *Parser) ParseProgram() *Program {
program := &Program{Statements: []Statement{}}
for p.curToken.Type != lexer.TokenEOF {
stmt := p.parseStatement()
if stmt != nil {
program.Statements = append(program.Statements, stmt)
}
p.nextToken()
}
return program
}
func (p *Parser) parseStatement() Statement {
switch p.curToken.Type {
case lexer.TokenIdentifier:
if p.peekToken.Type == lexer.TokenEqual {
return p.parseVariableStatement()
}
case lexer.TokenEcho:
return p.parseEchoStatement()
}
return nil
}
func (p *Parser) parseVariableStatement() *VariableStatement {
stmt := &VariableStatement{Token: p.curToken}
stmt.Name = &Identifier{Token: p.curToken, Value: p.curToken.Value}
p.nextToken() // Skip identifier
p.nextToken() // Skip =
switch p.curToken.Type {
case lexer.TokenString:
stmt.Value = &StringLiteral{Token: p.curToken, Value: p.curToken.Value}
case lexer.TokenNumber:
num, err := strconv.ParseFloat(p.curToken.Value, 64)
if err != nil {
p.errors = append(p.errors, fmt.Sprintf("could not parse %q as float", p.curToken.Value))
}
stmt.Value = &NumberLiteral{Token: p.curToken, Value: num}
case lexer.TokenIdentifier:
stmt.Value = &Identifier{Token: p.curToken, Value: p.curToken.Value}
}
if p.peekToken.Type == lexer.TokenSemicolon {
p.nextToken()
}
return stmt
}
func (p *Parser) parseEchoStatement() *EchoStatement {
stmt := &EchoStatement{Token: p.curToken}
p.nextToken()
switch p.curToken.Type {
case lexer.TokenString:
stmt.Value = &StringLiteral{Token: p.curToken, Value: p.curToken.Value}
case lexer.TokenNumber:
num, err := strconv.ParseFloat(p.curToken.Value, 64)
if err != nil {
p.errors = append(p.errors, fmt.Sprintf("could not parse %q as float", p.curToken.Value))
}
stmt.Value = &NumberLiteral{Token: p.curToken, Value: num}
case lexer.TokenIdentifier:
stmt.Value = &Identifier{Token: p.curToken, Value: p.curToken.Value}
}
if p.peekToken.Type == lexer.TokenSemicolon {
p.nextToken()
}
return stmt
}