Skip to content

Commit

Permalink
2.4 Parser (error handling)
Browse files Browse the repository at this point in the history
  • Loading branch information
cedrickchee committed Mar 27, 2020
1 parent b54dc0a commit 58b165c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
26 changes: 23 additions & 3 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ package parser
// lexer and produces as output an AST (Abstract Syntax Tree).

import (
"fmt"

"github.com/cedrickchee/hou/ast"
"github.com/cedrickchee/hou/lexer"
"github.com/cedrickchee/hou/token"
Expand All @@ -13,13 +15,18 @@ import (
type Parser struct {
l *lexer.Lexer

errors []string

curToken token.Token
peekToken token.Token
}

// New constructs a new Parser with a Lexer as input.
func New(l *lexer.Lexer) *Parser {
p := &Parser{l: l}
p := &Parser{
l: l,
errors: []string{},
}

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

// Errors check if the parser encountered any errors.
func (p *Parser) Errors() []string {
return p.errors
}

// Add an error to errors when the type of peekToken doesn’t match the
// expectation.
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)
}

// Helper method that advances both curToken and peekToken.
func (p *Parser) nextToken() {
p.curToken = p.peekToken
Expand Down Expand Up @@ -98,9 +118,9 @@ func (p *Parser) expectPeek(t token.TokenType) bool {
if p.peekTokenIs(t) {
p.nextToken()
return true
} else {
return false
}
p.peekError(t)
return false
}

func (p *Parser) peekTokenIs(t token.TokenType) bool {
Expand Down
17 changes: 17 additions & 0 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ let foobar = 838383;
p := New(l)

program := p.ParseProgram()
checkParserErrors(t, p)

if program == nil {
t.Fatalf("ParseProgram() returned nil")
}
Expand Down Expand Up @@ -65,3 +67,18 @@ func testLetStatement(t *testing.T, s ast.Statement, name string) bool {

return true
}

// Check the parser for errors and if it has any it prints them as test errors
// and stops the execution of the current test.
func checkParserErrors(t *testing.T, p *Parser) {
errors := p.Errors()
if len(errors) == 0 {
return
}

t.Errorf("parser has %d errors", len(errors))
for _, msg := range errors {
t.Errorf("parser error: %q", msg)
}
t.FailNow()
}

0 comments on commit 58b165c

Please sign in to comment.