Skip to content

Commit

Permalink
Refactor variable definition parsing.
Browse files Browse the repository at this point in the history
  • Loading branch information
aleury committed Jan 20, 2024
1 parent 38319aa commit 72d09cf
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 24 deletions.
33 changes: 9 additions & 24 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,27 +86,8 @@ func (p *Parser) parseStatement() ast.Statement {

func (p *Parser) parseVariableDefinitionStatement() ast.Statement {
stmt := ast.VariableDefinitionStatement{Token: p.curToken}

if p.peekToken.Type != token.IDENT {
p.errors = append(p.errors, fmt.Errorf("%w: %s at line %d", ErrInvalidVariableDefinition, p.peekToken.Literal, p.peekToken.Line))
return nil
}

p.nextToken()
stmt.Name = ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}

switch p.peekToken.Type {
case token.INT:
p.nextToken()
stmt.Value = p.parseIntegerLiteral()
case token.STRING:
p.nextToken()
stmt.Value = p.parseStringLiteral()
default:
p.errors = append(p.errors, fmt.Errorf("%w: %s at line %d", ErrInvalidVariableDefinition, p.peekToken.Literal, p.peekToken.Line))
return nil
}

stmt.Name = p.expectOneOf(token.IDENT).(ast.Identifier)
stmt.Value = p.expectOneOf(token.INT, token.STRING)
return stmt
}

Expand Down Expand Up @@ -144,9 +125,13 @@ func (p *Parser) expectOneOf(tokTypes ...token.TokenType) ast.Expression {

switch p.curToken.Type {
case token.REGISTER:
return ast.RegisterLiteral{Token: p.curToken}
return p.parseRegisterLiteral()
case token.IDENT:
return ast.Identifier{Token: p.curToken}
return p.parseIdentifier()
case token.INT:
return p.parseIntegerLiteral()
case token.STRING:
return p.parseStringLiteral()
default:
return nil
}
Expand Down Expand Up @@ -174,7 +159,7 @@ func (p *Parser) parseRegisterLiteral() ast.Expression {
}

func (p *Parser) parseIdentifier() ast.Expression {
return ast.Identifier{Token: p.curToken}
return ast.Identifier{Token: p.curToken, Value: p.curToken.Literal}
}

func (p *Parser) parseIntegerLiteral() ast.Expression {
Expand Down
3 changes: 3 additions & 0 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@ func TestParseProgram_ParsesInstructionWithAnIdentifierOperand(t *testing.T) {
Literal: "start",
Line: 1,
},
Value: "start",
},
},
}
Expand Down Expand Up @@ -382,6 +383,7 @@ MOVE var -> A
Literal: "var",
Line: 2,
},
Value: "var",
},
},
ast.InstructionStatement{
Expand All @@ -396,6 +398,7 @@ MOVE var -> A
Literal: "var",
Line: 3,
},
Value: "var",
},
Operand2: ast.RegisterLiteral{
Token: token.Token{
Expand Down

0 comments on commit 72d09cf

Please sign in to comment.