Skip to content

Commit

Permalink
parserErrorDetail: fix '^' location of lines starting with tabs
Browse files Browse the repository at this point in the history
Fixes #1129 for the most part.

What still is wrongly put, but also harder to fix, is the case where
there's tabs INSIDE the line:

	p = TAB true TAB { TAB as }

or a space before the tab, like

	SPACE TAB p = true { as }

will still have a misaligned "^", as in that case, not all tabs are
fully expanded.

This merely trims leading tabs, and fixes the error maker location if
there's no other tabs used in the line.

However, that should fit common usage: Leading tabs is what `opa fmt`
proposes; and I'm doubtful of too many uses of tabs in other places
in Rego code.

Signed-off-by: Stephan Renatus <srenatus@chef.io>
  • Loading branch information
srenatus authored and tsandall committed Jan 8, 2019
1 parent a353f25 commit 59f7020
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
4 changes: 3 additions & 1 deletion ast/parser_ext.go
Original file line number Diff line number Diff line change
Expand Up @@ -749,7 +749,9 @@ func newParserErrorDetail(bs []byte, pos position) *parserErrorDetail {
}

func (d parserErrorDetail) Lines() []string {
return []string{d.line, strings.Repeat(" ", d.idx) + "^"}
line := strings.TrimLeft(d.line, "\t") // remove leading tabs
tabCount := len(d.line) - len(line)
return []string{line, strings.Repeat(" ", d.idx-tabCount) + "^"}
}

func isNewLineChar(b byte) bool {
Expand Down
30 changes: 30 additions & 0 deletions ast/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1417,6 +1417,7 @@ func TestParseErrorDetails(t *testing.T) {
tests := []struct {
note string
exp *parserErrorDetail
err string
input string
}{
{
Expand Down Expand Up @@ -1474,6 +1475,32 @@ p { }`},
input: `
package test
p = "foo`},
{
note: "rule with error begins with one tab",
exp: &parserErrorDetail{
line: "\tas",
idx: 2,
},
input: `
package test
as`,
err: `1 error occurred: test.rego:3: rego_parse_error: no match found
as
^`},
{
note: "rule term with error begins with two tabs",
exp: &parserErrorDetail{
line: "\t\tas",
idx: 3,
},
input: `
package test
p = true {
as
}`,
err: `1 error occurred: test.rego:5: rego_parse_error: no match found
as
^`},
}

for _, tc := range tests {
Expand All @@ -1485,6 +1512,9 @@ p = "foo`},
if !reflect.DeepEqual(detail, tc.exp) {
t.Fatalf("Expected %v but got: %v", tc.exp, detail)
}
if tc.err != "" && tc.err != err.Error() {
t.Fatalf("Expected error string %q but got: %q", tc.err, err.Error())
}
}
}

Expand Down

0 comments on commit 59f7020

Please sign in to comment.