/
Error.go
74 lines (63 loc) · 1.25 KB
/
Error.go
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
69
70
71
72
73
74
package main
import (
"os"
"path/filepath"
"strings"
)
type Error struct {
ctx Context
end bool
msg string
}
// Doing this in two steps incurs some overhead
func IsError(e error) bool {
_, ok := e.(*Error)
return ok
}
func AssertError(e_ error) *Error {
e, ok := e_.(*Error)
if ok {
return e
} else {
panic("expected *Error")
}
}
func (e *Error) Error() string {
if strings.HasPrefix(e.ctx.src.Path(), "<") {
if TARGET == "repl" {
return "Error: " + e.msg
} else {
return writeError(e.ctx.src, e.ctx.end, e.msg, false)
}
} else if e.end {
return writeError(e.ctx.src, e.ctx.end, e.msg, true)
} else {
return writeError(e.ctx.src, e.ctx.start, e.msg, true)
}
}
func abbreviatePath(p string) string {
cwd, err := os.Getwd()
if err == nil {
alt, err := filepath.Rel(cwd, p)
if err == nil && len(alt) < len(p) && !strings.HasPrefix(alt, "../../") {
return alt
} else {
return p
}
} else {
return filepath.Base(p)
}
}
func writeError(src *Source, fp FilePos, msg string, writePos bool) string {
var b strings.Builder
b.WriteString(abbreviatePath(src.path))
if writePos {
b.WriteString(":")
b.WriteString(fp.ToString())
}
if len(msg) > 0 {
b.WriteString(": ")
b.WriteString(msg)
}
return b.String()
}