Skip to content

Commit 9eae285

Browse files
committed
Added function for error reporting
1 parent 6b3e6a2 commit 9eae285

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

base/types.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,15 @@ type SourcePosition struct {
2626
Length int `json:"len,omitempty"`
2727
}
2828

29+
// Source position (for error reporting)
30+
type LineAndColPosition struct {
31+
LineIndex int
32+
Line int
33+
Col int
34+
Position int
35+
ErrSource string
36+
}
37+
2938
// Match result status
3039
type MatchStatusType int
3140

base/util.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package parser
2+
3+
import (
4+
"strings"
5+
)
6+
7+
//
8+
func GetLineAndColPosition(src string, pos SourcePosition) LineAndColPosition {
9+
prevLineIndex := 0
10+
lineIndex := 0
11+
line := 1
12+
col := 1
13+
14+
for i := 0; i < pos.Position; i++ {
15+
switch src[i] {
16+
case '\r':
17+
line++
18+
if i+1 < pos.Position && src[i+1] == '\n' {
19+
i++
20+
}
21+
prevLineIndex = lineIndex
22+
lineIndex = i + 1
23+
col = 1
24+
case '\n':
25+
line++
26+
prevLineIndex = lineIndex
27+
lineIndex = i + 1
28+
col = 1
29+
default:
30+
col++
31+
}
32+
}
33+
34+
srcLen := len(src)
35+
endIndex := pos.Position
36+
OUTER:
37+
for i := pos.Position; i < srcLen; i++ {
38+
switch src[i] {
39+
case '\r', '\n':
40+
break OUTER
41+
default:
42+
endIndex++
43+
}
44+
}
45+
46+
errGuideCol := col - 1
47+
if errGuideCol < 0 {
48+
errGuideCol = 0
49+
}
50+
51+
errSource := src[prevLineIndex:endIndex]
52+
if strings.Contains(errSource, "\n") {
53+
errSource = " | " + strings.Replace(errSource, "\n", "\n > | ", 1) + "\n"
54+
} else if strings.Contains(errSource, "\r") {
55+
errSource = " | " + strings.Replace(errSource, "\r", "\r > | ", 1) + "\r"
56+
} else {
57+
errSource = " > | " + errSource + "\n"
58+
}
59+
errSource += " | " + strings.Repeat(" ", errGuideCol) + "^^^^"
60+
61+
return LineAndColPosition{
62+
LineIndex: lineIndex,
63+
Line: line,
64+
Col: col,
65+
Position: pos.Position,
66+
ErrSource: errSource,
67+
}
68+
}

0 commit comments

Comments
 (0)