Skip to content

Commit

Permalink
parser: prefix expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
mcapell committed Sep 7, 2024
1 parent 9ac71ea commit d035dd9
Show file tree
Hide file tree
Showing 3 changed files with 101 additions and 0 deletions.
19 changes: 19 additions & 0 deletions ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,22 @@ func (es *ExpressionStatement) String() string {

return ""
}

type PrefixExpression struct {
Token token.Token // The prefix token. Eg: !
Operator string
Right Expression
}

func (pe *PrefixExpression) expressionNode() {}
func (pe *PrefixExpression) TokenLiteral() string { return pe.Token.Literal }
func (pe *PrefixExpression) String() string {
var out bytes.Buffer

out.WriteString("(")
out.WriteString(pe.Operator)
out.WriteString(pe.Right.String())
out.WriteString(")")

return out.String()
}
21 changes: 21 additions & 0 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ func New(l *lexer.Lexer) *Parser {
p.prefixParseFns = make(map[token.TokenType]prefixParseFn)
p.registerPrefix(token.IDENT, p.parseIdentifier)
p.registerPrefix(token.INT, p.parseIntegerLiteral)
p.registerPrefix(token.BANG, p.parsePrefixExpression)
p.registerPrefix(token.MINUS, p.parsePrefixExpression)

return p
}
Expand Down Expand Up @@ -145,6 +147,7 @@ func (p *Parser) parseExpressionStatement() *ast.ExpressionStatement {
func (p *Parser) parseExpression(precedence int) ast.Expression {
prefix := p.prefixParseFns[p.curToken.Type]
if prefix == nil {
p.noPrefixParseFnError(p.curToken.Type)
return nil
}

Expand All @@ -171,6 +174,19 @@ func (p *Parser) parseIntegerLiteral() ast.Expression {
return lit
}

func (p *Parser) parsePrefixExpression() ast.Expression {
expression := &ast.PrefixExpression{
Token: p.curToken,
Operator: p.curToken.Literal,
}

p.nextToken()

expression.Right = p.parseExpression(PREFIX)

return expression
}

func (p *Parser) expectPeek(t token.TokenType) bool {
if p.peekTokenIs(t) {
p.nextToken()
Expand All @@ -193,3 +209,8 @@ func (p *Parser) peekError(t token.TokenType) {
msg := fmt.Sprintf("expected next token to be %s, got %s instead", t, p.peekToken.Type)
p.errors = append(p.errors, msg)
}

func (p *Parser) noPrefixParseFnError(t token.TokenType) {
msg := fmt.Sprintf("no prefix parse function for %s found", t)
p.errors = append(p.errors, msg)
}
61 changes: 61 additions & 0 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package parser

import (
"fmt"
"testing"

"github.com/mcapell/go-monkey/ast"
Expand Down Expand Up @@ -134,6 +135,46 @@ func TestIntegerLiteralExpression(t *testing.T) {
}
}

func TestParsingPrefixExpressions(t *testing.T) {
prefixTests := []struct {
input string
operator string
integerValue int64
}{
{"!5", "!", 5},
{"-15", "-", 15},
}

for _, tt := range prefixTests {
l := lexer.New(tt.input)
p := New(l)
program := p.ParseProgram()
checkParserErrors(t, p)

if len(program.Statements) != 1 {
t.Fatalf("program.Statements does not contain %d statements. got=%d\n", 1, len(program.Statements))
}

stmt, ok := program.Statements[0].(*ast.ExpressionStatement)
if !ok {
t.Fatalf("program.Statements[0] is not ast.ExpressionStatement. got=%T\n", program.Statements[0])
}

exp, ok := stmt.Expression.(*ast.PrefixExpression)
if !ok {
t.Fatalf("stmt is not ast.PrefixExpression. got=%T", stmt.Expression)
}

if exp.Operator != tt.operator {
t.Fatalf("exp.Operator is not '%s'. got=%s", tt.operator, exp.Operator)
}

if !testIntegerLiteral(t, exp.Right, tt.integerValue) {
return
}
}
}

func testLetStatement(t *testing.T, s ast.Statement, name string) bool {
if s.TokenLiteral() != "let" {
t.Errorf("s.TokenLiteral not 'let'. got=%q", s.TokenLiteral())
Expand All @@ -159,6 +200,26 @@ func testLetStatement(t *testing.T, s ast.Statement, name string) bool {
return true
}

func testIntegerLiteral(t *testing.T, il ast.Expression, value int64) bool {
integ, ok := il.(*ast.IntegerLiteral)
if !ok {
t.Errorf("il not *ast.IntegerLiteral. got=%T", il)
return false
}

if integ.Value != value {
t.Errorf("integ.Value not %d. got=%d", value, integ.Value)
return false
}

if integ.TokenLiteral() != fmt.Sprintf("%d", value) {
t.Errorf("integ.TokenLiteral() not %d. got=%s", value, integ.TokenLiteral())
return false
}

return true
}

func checkParserErrors(t *testing.T, p *Parser) {
errors := p.Errors()
if len(errors) == 0 {
Expand Down

0 comments on commit d035dd9

Please sign in to comment.