Skip to content

Commit

Permalink
Fix ErrorWithPosition panic when less than two lines
Browse files Browse the repository at this point in the history
  • Loading branch information
xoltia committed Nov 22, 2024
1 parent b7406c0 commit 4be4c72
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
17 changes: 12 additions & 5 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,17 +124,24 @@ func (pe ParseError) ErrorWithPosition() string {
if pe.Position.Line > 2 {
fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-2, expandTab(lines[pe.Position.Line-3]))
}
if pe.Position.Line > 1 {
fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-1, expandTab(lines[pe.Position.Line-2]))
}

/// Expand tabs, so that the ^^^s are at the correct position, but leave
/// "column 10-13" intact. Adjusting this to the visual column would be
/// better, but we don't know the tabsize of the user in their editor, which
/// can be 8, 4, 2, or something else. We can't know. So leaving it as the
/// character index is probably the "most correct".
expanded := expandTab(lines[pe.Position.Line-1])
diff := len(expanded) - len(lines[pe.Position.Line-1])
var (
expanded string
diff int
)
if pe.Position.Line > 1 {
fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line-1, expandTab(lines[pe.Position.Line-2]))
expanded = expandTab(lines[pe.Position.Line-1])
diff = len(expanded) - len(lines[pe.Position.Line-1])
} else {
expanded = expandTab(lines[0])
diff = len(expanded) - len(lines[0])
}

fmt.Fprintf(b, "% 7d | %s\n", pe.Position.Line, expanded)
fmt.Fprintf(b, "% 10s%s%s\n", "", strings.Repeat(" ", pe.Position.Col-1+diff), strings.Repeat("^", pe.Position.Len))
Expand Down
13 changes: 13 additions & 0 deletions error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,19 @@ func TestParseError(t *testing.T) {
| 15:04:05.856018510
`,
},

{
&struct{ String string }{},
`string = "test`,
`
| toml: error: unexpected EOF; expected '"'
|
| At line 0, column 14:
|
| 0 | string = "test
| ^
`,
},
}

prep := func(s string) string {
Expand Down

0 comments on commit 4be4c72

Please sign in to comment.