Change assignment into expressions
Some checks failed
Test / build (push) Waiting to run
Build / build (push) Has been cancelled

This commit is contained in:
Chuck Smith
2024-03-19 20:30:30 -04:00
parent aa0582ed72
commit be81b9a6d6
12 changed files with 478 additions and 153 deletions

View File

@@ -11,6 +11,7 @@ import (
const (
_ int = iota
LOWEST
ASSIGN // =
EQUALS // ==
LESSGREATER // > or <
SUM // +
@@ -21,6 +22,7 @@ const (
)
var precedences = map[token.TokenType]int{
token.ASSIGN: ASSIGN,
token.EQ: EQUALS,
token.NOT_EQ: EQUALS,
token.LT: LESSGREATER,
@@ -86,6 +88,7 @@ func New(l *lexer.Lexer) *Parser {
p.registerInfix(token.GTE, p.parseInfixExpression)
p.registerInfix(token.LPAREN, p.parseCallExpression)
p.registerInfix(token.LBRACKET, p.parseIndexExpression)
p.registerInfix(token.ASSIGN, p.parseAssignmentExpression)
// Read two tokens, so curToken and peekToken are both set
p.nextToken()
@@ -153,10 +156,6 @@ func (p *Parser) ParseProgram() *ast.Program {
}
func (p *Parser) parseStatement() ast.Statement {
if p.peekToken.Type == token.ASSIGN {
return p.parseAssignmentStatement()
}
switch p.curToken.Type {
case token.COMMENT:
return p.parseComment()
@@ -347,6 +346,18 @@ func (p *Parser) parseIfExpression() ast.Expression {
if p.peekTokenIs(token.ELSE) {
p.nextToken()
if p.peekTokenIs(token.IF) {
p.nextToken()
expression.Alternative = &ast.BlockStatement{
Statements: []ast.Statement{
&ast.ExpressionStatement{
Expression: p.parseIfExpression(),
},
},
}
return expression
}
if !p.expectPeek(token.LBRACE) {
return nil
}
@@ -534,20 +545,22 @@ func (p *Parser) parseWhileExpression() ast.Expression {
return expression
}
func (p *Parser) parseAssignmentStatement() ast.Statement {
stmt := &ast.AssignmentStatement{Token: p.peekToken}
stmt.Name = &ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}
p.nextToken()
p.nextToken()
stmt.Value = p.parseExpression(LOWEST)
if p.peekTokenIs(token.SEMICOLON) {
p.nextToken()
func (p *Parser) parseAssignmentExpression(exp ast.Expression) ast.Expression {
switch node := exp.(type) {
case *ast.Identifier, *ast.IndexExpression:
default:
msg := fmt.Sprintf("expected identifier or index expression on left but got %T %#v", node, exp)
p.errors = append(p.errors, msg)
return nil
}
return stmt
ae := &ast.AssignmentExpression{Token: p.curToken, Left: exp}
p.nextToken()
ae.Value = p.parseExpression(LOWEST)
return ae
}
func (p *Parser) parseComment() ast.Statement {