package common
import (
"fmt"
"sort"
"strings"
)
type Errors struct {
errors []*Error
source Source
numErrors int
maxErrorsToReport int
}
func NewErrors(source Source) *Errors {
return &Errors{
errors: []*Error{},
source: source,
maxErrorsToReport: 100,
}
}
func (e *Errors) ReportError(l Location, format string, args ...any) {
e.ReportErrorAtID(0, l, format, args...)
}
func (e *Errors) ReportErrorAtID(id int64, l Location, format string, args ...any) {
e.numErrors++
if e.numErrors > e.maxErrorsToReport {
return
}
err := &Error{
ExprID: id,
Location: l,
Message: fmt.Sprintf(format, args...),
}
e.errors = append(e.errors, err)
}
func (e *Errors) GetErrors() []*Error {
return e.errors[:]
}
func (e *Errors) Append(errs []*Error) *Errors {
return &Errors{
errors: append(e.errors[:], errs...),
source: e.source,
numErrors: e.numErrors + len(errs),
maxErrorsToReport: e.maxErrorsToReport,
}
}
func (e *Errors) ToDisplayString() string {
errorsInString := e.maxErrorsToReport
if e.numErrors > e.maxErrorsToReport {
errorsInString++
} else {
errorsInString = e.numErrors
}
result := make([]string, errorsInString)
sort.SliceStable(e.errors, func(i, j int) bool {
ei := e.errors[i].Location
ej := e.errors[j].Location
return ei.Line() < ej.Line() ||
(ei.Line() == ej.Line() && ei.Column() < ej.Column())
})
for i, err := range e.errors {
if i >= e.maxErrorsToReport {
break
}
result[i] = err.ToDisplayString(e.source)
}
if e.numErrors > e.maxErrorsToReport {
result[e.maxErrorsToReport] = fmt.Sprintf("%d more errors were truncated", e.numErrors-e.maxErrorsToReport)
}
return strings.Join(result, "\n")
}