Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

parser: add line number and column to syntax errors #71

Merged
merged 1 commit into from
Jan 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2722,19 +2722,36 @@ func (p *parser) advanceOffset(delta int) {

// syntaxError represents a synax error in the Pushup template language.
type syntaxError struct {
// err is the underlying error that caused this syntax error
err error
// lineNo and column are the positions in the source code where the
// error occurred
lineNo int
column int
}

func (e syntaxError) Error() string {
return e.err.Error()
// TODO(paulsmith): add source file name
return fmt.Sprintf("%d:%d: %s", e.lineNo, e.column, e.err.Error())
}

// errorf signals that a syntax error in the Pushup template language has been
// detected. The Pushup parser uses panic mode error handling, so a function
// calling the parser higher up in the call stack can recover from the panic
// and test for a syntax error (syntaxError type).
func (p *parser) errorf(format string, args ...any) {
panic(syntaxError{fmt.Errorf(format, args...)})
offset := p.offset
if offset >= len(p.src) {
offset = len(p.src) - 1
}
upToErr := p.src[:offset]
lineNo := strings.Count(upToErr, "\n") + 1
lastNL := strings.LastIndex(upToErr, "\n")
column := p.offset + 1
if lastNL > -1 {
column = p.offset - lastNL
}
panic(syntaxError{fmt.Errorf(format, args...), lineNo, column})
}

// htmlParser is the Pushup HTML parser. It wraps the golang.org/x/net/html
Expand Down
17 changes: 16 additions & 1 deletion main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -930,8 +930,16 @@ func TestParse(t *testing.T) {
func TestParseSyntaxErrors(t *testing.T) {
tests := []struct {
input string
// expected error conditions
lineNo int
column int
}{
{"^if"},
{"^if", 1, 4},
{
`^if true {
<illegal />
}`, 2, 13,
},
// FIXME(paulsmith): add more syntax errors
}

Expand All @@ -944,6 +952,13 @@ func TestParseSyntaxErrors(t *testing.T) {
if err == nil {
t.Errorf("expected parse error, got nil")
}
serr, ok := err.(syntaxError)
if !ok {
t.Errorf("expected syntax error type, got %T", err)
}
if tt.lineNo != serr.lineNo || tt.column != serr.column {
t.Errorf("line:column: want %d:%d, got %d:%d", tt.lineNo, tt.column, serr.lineNo, serr.column)
}
})
}
}
Expand Down