1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // This file implements various error reporters.
14 . "internal/types/errors"
22 msg := "assertion failed"
23 // Include information about the assertion location. Due to panic recovery,
24 // this location is otherwise buried in the middle of the panicking stack.
25 if _, file, line, ok := runtime.Caller(1); ok {
26 msg = fmt.Sprintf("%s:%d: %s", file, line, msg)
36 // An error_ represents a type-checking error.
37 // To report an error_, call Checker.report.
41 soft bool // TODO(gri) eventually determine this from an error code
44 // An errorDesc describes part of a type-checking error.
45 type errorDesc struct {
51 func (err *error_) empty() bool {
52 return err.desc == nil
55 func (err *error_) pos() token.Pos {
59 return err.desc[0].posn.Pos()
62 func (err *error_) msg(fset *token.FileSet, qf Qualifier) string {
66 var buf strings.Builder
67 for i := range err.desc {
70 fmt.Fprint(&buf, "\n\t")
71 if p.posn.Pos().IsValid() {
72 fmt.Fprintf(&buf, "%s: ", fset.Position(p.posn.Pos()))
75 buf.WriteString(sprintf(fset, qf, false, p.format, p.args...))
80 // String is for testing.
81 func (err *error_) String() string {
85 return fmt.Sprintf("%d: %s", err.pos(), err.msg(nil, nil))
88 // errorf adds formatted error information to err.
89 // It may be called multiple times to provide additional information.
90 func (err *error_) errorf(at token.Pos, format string, args ...interface{}) {
91 err.desc = append(err.desc, errorDesc{atPos(at), format, args})
94 func (check *Checker) qualifier(pkg *Package) string {
95 // Qualify the package unless it's the package being type-checked.
97 if check.pkgPathMap == nil {
98 check.pkgPathMap = make(map[string]map[string]bool)
99 check.seenPkgMap = make(map[*Package]bool)
100 check.markImports(check.pkg)
102 // If the same package name was used by multiple packages, display the full path.
103 if len(check.pkgPathMap[pkg.name]) > 1 {
104 return strconv.Quote(pkg.path)
111 // markImports recursively walks pkg and its imports, to record unique import
112 // paths in pkgPathMap.
113 func (check *Checker) markImports(pkg *Package) {
114 if check.seenPkgMap[pkg] {
117 check.seenPkgMap[pkg] = true
119 forName, ok := check.pkgPathMap[pkg.name]
121 forName = make(map[string]bool)
122 check.pkgPathMap[pkg.name] = forName
124 forName[pkg.path] = true
126 for _, imp := range pkg.imports {
127 check.markImports(imp)
132 func (check *Checker) sprintf(format string, args ...any) string {
133 var fset *token.FileSet
139 return sprintf(fset, qf, false, format, args...)
142 func sprintf(fset *token.FileSet, qf Qualifier, tpSubscripts bool, format string, args ...any) string {
143 for i, arg := range args {
144 switch a := arg.(type) {
148 panic("got operand instead of *operand")
150 arg = operandString(a, qf)
153 arg = fset.Position(a).String()
160 writeExprList(&buf, a)
164 arg = ObjectString(a, qf)
167 w := newTypeWriter(&buf, qf)
168 w.tpSubscripts = tpSubscripts
173 w := newTypeWriter(&buf, qf)
174 w.tpSubscripts = tpSubscripts
176 for i, x := range a {
178 buf.WriteString(", ")
186 w := newTypeWriter(&buf, qf)
187 w.tpSubscripts = tpSubscripts
189 for i, x := range a {
191 buf.WriteString(", ")
200 return fmt.Sprintf(format, args...)
203 func (check *Checker) trace(pos token.Pos, format string, args ...any) {
204 fmt.Printf("%s:\t%s%s\n",
205 check.fset.Position(pos),
206 strings.Repeat(". ", check.indent),
207 sprintf(check.fset, check.qualifier, true, format, args...),
211 // dump is only needed for debugging
212 func (check *Checker) dump(format string, args ...any) {
213 fmt.Println(sprintf(check.fset, check.qualifier, true, format, args...))
216 // Report records the error pointed to by errp, setting check.firstError if
218 func (check *Checker) report(errp *error_) {
220 panic("empty error details")
223 msg := errp.msg(check.fset, check.qualifier)
225 case InvalidSyntaxTree:
226 msg = "invalid AST: " + msg
228 panic("no error code provided")
231 span := spanOf(errp.desc[0].posn)
237 go116code: errp.code,
238 go116start: span.start,
242 // Cheap trick: Don't report errors with messages containing
243 // "invalid operand" or "invalid type" as those tend to be
244 // follow-on errors which don't add useful information. Only
245 // exclude them if these strings are not at the beginning,
246 // and only if we have at least one error already reported.
247 isInvalidErr := strings.Index(e.Msg, "invalid operand") > 0 || strings.Index(e.Msg, "invalid type") > 0
248 if check.firstErr != nil && isInvalidErr {
252 e.Msg = stripAnnotations(e.Msg)
253 if check.errpos != nil {
254 // If we have an internal error and the errpos override is set, use it to
255 // augment our error positioning.
256 // TODO(rFindley) we may also want to augment the error message and refer
257 // to the position (pos) in the original expression.
258 span := spanOf(check.errpos)
260 e.go116start = span.start
261 e.go116end = span.end
265 if check.firstErr == nil {
272 check.trace(pos, "ERROR: %s", msg)
275 f := check.conf.Error
277 panic(bailout{}) // report only first error
283 invalidArg = "invalid argument: "
284 invalidOp = "invalid operation: "
287 // newErrorf creates a new error_ for later reporting with check.report.
288 func newErrorf(at positioner, code Code, format string, args ...any) *error_ {
290 desc: []errorDesc{{at, format, args}},
295 func (check *Checker) error(at positioner, code Code, msg string) {
296 check.report(newErrorf(at, code, msg))
299 func (check *Checker) errorf(at positioner, code Code, format string, args ...any) {
300 check.report(newErrorf(at, code, format, args...))
303 func (check *Checker) softErrorf(at positioner, code Code, format string, args ...any) {
304 err := newErrorf(at, code, format, args...)
309 func (check *Checker) versionErrorf(at positioner, goVersion string, format string, args ...interface{}) {
310 msg := check.sprintf(format, args...)
312 err = newErrorf(at, UnsupportedFeature, "%s requires %s or later", msg, goVersion)
316 // The positioner interface is used to extract the position of type-checker
318 type positioner interface {
322 // posSpan holds a position range along with a highlighted position within that
323 // range. This is used for positioning errors, with pos by convention being the
324 // first position in the source where the error is known to exist, and start
325 // and end defining the full span of syntax being considered when the error was
326 // detected. Invariant: start <= pos < end || start == pos == end.
327 type posSpan struct {
328 start, pos, end token.Pos
331 func (e posSpan) Pos() token.Pos {
335 // inNode creates a posSpan for the given node.
336 // Invariant: node.Pos() <= pos < node.End() (node.End() is the position of the
337 // first byte after node within the source).
338 func inNode(node ast.Node, pos token.Pos) posSpan {
339 start, end := node.Pos(), node.End()
341 assert(start <= pos && pos < end)
343 return posSpan{start, pos, end}
346 // atPos wraps a token.Pos to implement the positioner interface.
349 func (s atPos) Pos() token.Pos {
353 // spanOf extracts an error span from the given positioner. By default this is
354 // the trivial span starting and ending at pos, but this span is expanded when
355 // the argument naturally corresponds to a span of source code.
356 func spanOf(at positioner) posSpan {
357 switch x := at.(type) {
359 panic("nil positioner")
364 return posSpan{pos, pos, x.End()}
368 return posSpan{pos, pos, x.expr.End()}
370 return posSpan{token.NoPos, token.NoPos, token.NoPos}
373 return posSpan{pos, pos, pos}
377 // stripAnnotations removes internal (type) annotations from s.
378 func stripAnnotations(s string) string {
379 var buf strings.Builder
380 for _, r := range s {
381 // strip #'s and subscript digits
382 if r < '₀' || '₀'+10 <= r { // '₀' == U+2080
386 if buf.Len() < len(s) {