1
2
3
4
5 package scanner
6
7 import (
8 "fmt"
9 "go/token"
10 "io"
11 "sort"
12 )
13
14
15
16
17
18 type Error struct {
19 Pos token.Position
20 Msg string
21 }
22
23
24 func (e Error) Error() string {
25 if e.Pos.Filename != "" || e.Pos.IsValid() {
26
27
28 return e.Pos.String() + ": " + e.Msg
29 }
30 return e.Msg
31 }
32
33
34
35 type ErrorList []*Error
36
37
38 func (p *ErrorList) Add(pos token.Position, msg string) {
39 *p = append(*p, &Error{pos, msg})
40 }
41
42
43 func (p *ErrorList) Reset() { *p = (*p)[0:0] }
44
45
46 func (p ErrorList) Len() int { return len(p) }
47 func (p ErrorList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
48
49 func (p ErrorList) Less(i, j int) bool {
50 e := &p[i].Pos
51 f := &p[j].Pos
52
53
54
55 if e.Filename != f.Filename {
56 return e.Filename < f.Filename
57 }
58 if e.Line != f.Line {
59 return e.Line < f.Line
60 }
61 if e.Column != f.Column {
62 return e.Column < f.Column
63 }
64 return p[i].Msg < p[j].Msg
65 }
66
67
68
69
70 func (p ErrorList) Sort() {
71 sort.Sort(p)
72 }
73
74
75 func (p *ErrorList) RemoveMultiples() {
76 sort.Sort(p)
77 var last token.Position
78 i := 0
79 for _, e := range *p {
80 if e.Pos.Filename != last.Filename || e.Pos.Line != last.Line {
81 last = e.Pos
82 (*p)[i] = e
83 i++
84 }
85 }
86 *p = (*p)[0:i]
87 }
88
89
90 func (p ErrorList) Error() string {
91 switch len(p) {
92 case 0:
93 return "no errors"
94 case 1:
95 return p[0].Error()
96 }
97 return fmt.Sprintf("%s (and %d more errors)", p[0], len(p)-1)
98 }
99
100
101
102 func (p ErrorList) Err() error {
103 if len(p) == 0 {
104 return nil
105 }
106 return p
107 }
108
109
110
111
112 func PrintError(w io.Writer, err error) {
113 if list, ok := err.(ErrorList); ok {
114 for _, e := range list {
115 fmt.Fprintf(w, "%s\n", e)
116 }
117 } else if err != nil {
118 fmt.Fprintf(w, "%s\n", err)
119 }
120 }
121
View as plain text