-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy patherror.go
More file actions
68 lines (57 loc) · 1.32 KB
/
error.go
File metadata and controls
68 lines (57 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package mexpr
import (
"fmt"
"strings"
"unicode/utf8"
)
// Error represents an error at a specific location.
type Error interface {
Error() string
// Offset returns the rune offset of the error within the expression.
Offset() uint16
// Length returns the rune length after the offset where the error ends.
Length() uint8
// Pretty prints out a message with a pointer to the source location of the
// error.
Pretty(source string) string
}
type exprErr struct {
offset uint16
length uint8
message string
}
func (e *exprErr) Error() string {
return e.message
}
func (e *exprErr) Offset() uint16 {
return e.offset
}
func (e *exprErr) Length() uint8 {
return e.length
}
func (e *exprErr) Pretty(source string) string {
var msg strings.Builder
msg.WriteString(e.Error())
msg.WriteByte('\n')
msg.WriteString(source)
msg.WriteByte('\n')
for i := uint16(0); i < e.offset; i++ {
msg.WriteByte('.')
}
length := e.length
if length == 0 && utf8.RuneCountInString(source) > int(e.offset) {
length = 1
}
for i := uint8(0); i < length; i++ {
msg.WriteByte('^')
}
return msg.String()
}
// NewError creates a new error at a specific location.
func NewError(offset uint16, length uint8, format string, a ...any) Error {
return &exprErr{
offset: offset,
length: length,
message: fmt.Sprintf(format, a...),
}
}