Skip to content

Commit 58b165c

Browse files
committed
2.4 Parser (error handling)
1 parent b54dc0a commit 58b165c

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

parser/parser.go

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ package parser
44
// lexer and produces as output an AST (Abstract Syntax Tree).
55

66
import (
7+
"fmt"
8+
79
"github.com/cedrickchee/hou/ast"
810
"github.com/cedrickchee/hou/lexer"
911
"github.com/cedrickchee/hou/token"
@@ -13,13 +15,18 @@ import (
1315
type Parser struct {
1416
l *lexer.Lexer
1517

18+
errors []string
19+
1620
curToken token.Token
1721
peekToken token.Token
1822
}
1923

2024
// New constructs a new Parser with a Lexer as input.
2125
func New(l *lexer.Lexer) *Parser {
22-
p := &Parser{l: l}
26+
p := &Parser{
27+
l: l,
28+
errors: []string{},
29+
}
2330

2431
// Read two tokens, so curToken and peekToken are both set.
2532
p.nextToken()
@@ -28,6 +35,19 @@ func New(l *lexer.Lexer) *Parser {
2835
return p
2936
}
3037

38+
// Errors check if the parser encountered any errors.
39+
func (p *Parser) Errors() []string {
40+
return p.errors
41+
}
42+
43+
// Add an error to errors when the type of peekToken doesn’t match the
44+
// expectation.
45+
func (p *Parser) peekError(t token.TokenType) {
46+
msg := fmt.Sprintf("expected next token to be %s, got %s instead",
47+
t, p.peekToken.Type)
48+
p.errors = append(p.errors, msg)
49+
}
50+
3151
// Helper method that advances both curToken and peekToken.
3252
func (p *Parser) nextToken() {
3353
p.curToken = p.peekToken
@@ -98,9 +118,9 @@ func (p *Parser) expectPeek(t token.TokenType) bool {
98118
if p.peekTokenIs(t) {
99119
p.nextToken()
100120
return true
101-
} else {
102-
return false
103121
}
122+
p.peekError(t)
123+
return false
104124
}
105125

106126
func (p *Parser) peekTokenIs(t token.TokenType) bool {

parser/parser_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ let foobar = 838383;
1717
p := New(l)
1818

1919
program := p.ParseProgram()
20+
checkParserErrors(t, p)
21+
2022
if program == nil {
2123
t.Fatalf("ParseProgram() returned nil")
2224
}
@@ -65,3 +67,18 @@ func testLetStatement(t *testing.T, s ast.Statement, name string) bool {
6567

6668
return true
6769
}
70+
71+
// Check the parser for errors and if it has any it prints them as test errors
72+
// and stops the execution of the current test.
73+
func checkParserErrors(t *testing.T, p *Parser) {
74+
errors := p.Errors()
75+
if len(errors) == 0 {
76+
return
77+
}
78+
79+
t.Errorf("parser has %d errors", len(errors))
80+
for _, msg := range errors {
81+
t.Errorf("parser error: %q", msg)
82+
}
83+
t.FailNow()
84+
}

0 commit comments

Comments
 (0)