| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
package common |
| 16 |
|
| 17 |
import ( |
| 18 |
"fmt" |
| 19 |
"sort" |
| 20 |
"strings" |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
type Errors struct { |
| 25 |
errors []*Error |
| 26 |
source Source |
| 27 |
numErrors int |
| 28 |
maxErrorsToReport int |
| 29 |
} |
| 30 |
|
| 31 |
|
| 32 |
func NewErrors(source Source) *Errors { |
| 33 |
src := source |
| 34 |
if src == nil { |
| 35 |
src = NewTextSource("") |
| 36 |
} |
| 37 |
return &Errors{ |
| 38 |
errors: []*Error{}, |
| 39 |
source: src, |
| 40 |
maxErrorsToReport: 100, |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
func (e *Errors) ReportError(l Location, format string, args ...any) { |
| 46 |
e.ReportErrorAtID(0, l, format, args...) |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
func (e *Errors) ReportErrorString(l Location, message string) { |
| 51 |
e.ReportErrorAtID(0, l, "%s", message) |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
func (e *Errors) ReportErrorAtID(id int64, l Location, format string, args ...any) { |
| 56 |
e.numErrors++ |
| 57 |
if e.numErrors > e.maxErrorsToReport { |
| 58 |
return |
| 59 |
} |
| 60 |
err := &Error{ |
| 61 |
ExprID: id, |
| 62 |
Location: l, |
| 63 |
Message: fmt.Sprintf(format, args...), |
| 64 |
} |
| 65 |
e.errors = append(e.errors, err) |
| 66 |
} |
| 67 |
|
| 68 |
|
| 69 |
func (e *Errors) GetErrors() []*Error { |
| 70 |
return e.errors[:] |
| 71 |
} |
| 72 |
|
| 73 |
|
| 74 |
func (e *Errors) Append(errs []*Error) *Errors { |
| 75 |
return &Errors{ |
| 76 |
errors: append(e.errors[:], errs...), |
| 77 |
source: e.source, |
| 78 |
numErrors: e.numErrors + len(errs), |
| 79 |
maxErrorsToReport: e.maxErrorsToReport, |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
|
| 84 |
func (e *Errors) ToDisplayString() string { |
| 85 |
errorsInString := e.maxErrorsToReport |
| 86 |
if e.numErrors > e.maxErrorsToReport { |
| 87 |
|
| 88 |
errorsInString++ |
| 89 |
} else { |
| 90 |
|
| 91 |
errorsInString = e.numErrors |
| 92 |
} |
| 93 |
|
| 94 |
result := make([]string, errorsInString) |
| 95 |
sort.SliceStable(e.errors, func(i, j int) bool { |
| 96 |
ei := e.errors[i].Location |
| 97 |
ej := e.errors[j].Location |
| 98 |
return ei.Line() < ej.Line() || |
| 99 |
(ei.Line() == ej.Line() && ei.Column() < ej.Column()) |
| 100 |
}) |
| 101 |
for i, err := range e.errors { |
| 102 |
|
| 103 |
if i >= e.maxErrorsToReport { |
| 104 |
break |
| 105 |
} |
| 106 |
result[i] = err.ToDisplayString(e.source) |
| 107 |
} |
| 108 |
if e.numErrors > e.maxErrorsToReport { |
| 109 |
result[e.maxErrorsToReport] = fmt.Sprintf("%d more errors were truncated", e.numErrors-e.maxErrorsToReport) |
| 110 |
} |
| 111 |
return strings.Join(result, "\n") |
| 112 |
} |