]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/errors.go
go/types, types2: don't print function parameter names when showing type differences
[gostls13.git] / src / go / types / errors.go
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.
4
5 // This file implements various error reporters.
6
7 package types
8
9 import (
10         "bytes"
11         "fmt"
12         "go/ast"
13         "go/token"
14         "runtime"
15         "strconv"
16         "strings"
17 )
18
19 func assert(p bool) {
20         if !p {
21                 msg := "assertion failed"
22                 // Include information about the assertion location. Due to panic recovery,
23                 // this location is otherwise buried in the middle of the panicking stack.
24                 if _, file, line, ok := runtime.Caller(1); ok {
25                         msg = fmt.Sprintf("%s:%d: %s", file, line, msg)
26                 }
27                 panic(msg)
28         }
29 }
30
31 func unreachable() {
32         panic("unreachable")
33 }
34
35 // An error_ represents a type-checking error.
36 // To report an error_, call Checker.report.
37 type error_ struct {
38         desc []errorDesc
39         code errorCode
40         soft bool // TODO(gri) eventually determine this from an error code
41 }
42
43 // An errorDesc describes part of a type-checking error.
44 type errorDesc struct {
45         posn   positioner
46         format string
47         args   []interface{}
48 }
49
50 func (err *error_) empty() bool {
51         return err.desc == nil
52 }
53
54 func (err *error_) pos() token.Pos {
55         if err.empty() {
56                 return token.NoPos
57         }
58         return err.desc[0].posn.Pos()
59 }
60
61 func (err *error_) msg(fset *token.FileSet, qf Qualifier) string {
62         if err.empty() {
63                 return "no error"
64         }
65         var buf strings.Builder
66         for i := range err.desc {
67                 p := &err.desc[i]
68                 if i > 0 {
69                         fmt.Fprint(&buf, "\n\t")
70                         if p.posn.Pos().IsValid() {
71                                 fmt.Fprintf(&buf, "%s: ", fset.Position(p.posn.Pos()))
72                         }
73                 }
74                 buf.WriteString(sprintf(fset, qf, false, p.format, p.args...))
75         }
76         return buf.String()
77 }
78
79 // String is for testing.
80 func (err *error_) String() string {
81         if err.empty() {
82                 return "no error"
83         }
84         return fmt.Sprintf("%d: %s", err.pos(), err.msg(nil, nil))
85 }
86
87 // errorf adds formatted error information to err.
88 // It may be called multiple times to provide additional information.
89 func (err *error_) errorf(at token.Pos, format string, args ...interface{}) {
90         err.desc = append(err.desc, errorDesc{atPos(at), format, args})
91 }
92
93 func (check *Checker) qualifier(pkg *Package) string {
94         // Qualify the package unless it's the package being type-checked.
95         if pkg != check.pkg {
96                 if check.pkgPathMap == nil {
97                         check.pkgPathMap = make(map[string]map[string]bool)
98                         check.seenPkgMap = make(map[*Package]bool)
99                         check.markImports(check.pkg)
100                 }
101                 // If the same package name was used by multiple packages, display the full path.
102                 if len(check.pkgPathMap[pkg.name]) > 1 {
103                         return strconv.Quote(pkg.path)
104                 }
105                 return pkg.name
106         }
107         return ""
108 }
109
110 // markImports recursively walks pkg and its imports, to record unique import
111 // paths in pkgPathMap.
112 func (check *Checker) markImports(pkg *Package) {
113         if check.seenPkgMap[pkg] {
114                 return
115         }
116         check.seenPkgMap[pkg] = true
117
118         forName, ok := check.pkgPathMap[pkg.name]
119         if !ok {
120                 forName = make(map[string]bool)
121                 check.pkgPathMap[pkg.name] = forName
122         }
123         forName[pkg.path] = true
124
125         for _, imp := range pkg.imports {
126                 check.markImports(imp)
127         }
128 }
129
130 // check may be nil.
131 func (check *Checker) sprintf(format string, args ...any) string {
132         var fset *token.FileSet
133         var qf Qualifier
134         if check != nil {
135                 fset = check.fset
136                 qf = check.qualifier
137         }
138         return sprintf(fset, qf, false, format, args...)
139 }
140
141 func sprintf(fset *token.FileSet, qf Qualifier, tpSubscripts bool, format string, args ...any) string {
142         for i, arg := range args {
143                 switch a := arg.(type) {
144                 case nil:
145                         arg = "<nil>"
146                 case operand:
147                         panic("got operand instead of *operand")
148                 case *operand:
149                         arg = operandString(a, qf)
150                 case token.Pos:
151                         if fset != nil {
152                                 arg = fset.Position(a).String()
153                         }
154                 case ast.Expr:
155                         arg = ExprString(a)
156                 case []ast.Expr:
157                         var buf bytes.Buffer
158                         buf.WriteByte('[')
159                         writeExprList(&buf, a)
160                         buf.WriteByte(']')
161                         arg = buf.String()
162                 case Object:
163                         arg = ObjectString(a, qf)
164                 case Type:
165                         var buf bytes.Buffer
166                         w := newTypeWriter(&buf, qf)
167                         w.tpSubscripts = tpSubscripts
168                         w.typ(a)
169                         arg = buf.String()
170                 case []Type:
171                         var buf bytes.Buffer
172                         w := newTypeWriter(&buf, qf)
173                         w.tpSubscripts = tpSubscripts
174                         buf.WriteByte('[')
175                         for i, x := range a {
176                                 if i > 0 {
177                                         buf.WriteString(", ")
178                                 }
179                                 w.typ(x)
180                         }
181                         buf.WriteByte(']')
182                         arg = buf.String()
183                 case []*TypeParam:
184                         var buf bytes.Buffer
185                         w := newTypeWriter(&buf, qf)
186                         w.tpSubscripts = tpSubscripts
187                         buf.WriteByte('[')
188                         for i, x := range a {
189                                 if i > 0 {
190                                         buf.WriteString(", ")
191                                 }
192                                 w.typ(x)
193                         }
194                         buf.WriteByte(']')
195                         arg = buf.String()
196                 }
197                 args[i] = arg
198         }
199         return fmt.Sprintf(format, args...)
200 }
201
202 func (check *Checker) trace(pos token.Pos, format string, args ...any) {
203         fmt.Printf("%s:\t%s%s\n",
204                 check.fset.Position(pos),
205                 strings.Repeat(".  ", check.indent),
206                 sprintf(check.fset, check.qualifier, true, format, args...),
207         )
208 }
209
210 // dump is only needed for debugging
211 func (check *Checker) dump(format string, args ...any) {
212         fmt.Println(sprintf(check.fset, check.qualifier, true, format, args...))
213 }
214
215 // Report records the error pointed to by errp, setting check.firstError if
216 // necessary.
217 func (check *Checker) report(errp *error_) {
218         if errp.empty() {
219                 panic("empty error details")
220         }
221
222         span := spanOf(errp.desc[0].posn)
223         e := Error{
224                 Fset:       check.fset,
225                 Pos:        span.pos,
226                 Msg:        errp.msg(check.fset, check.qualifier),
227                 Soft:       errp.soft,
228                 go116code:  errp.code,
229                 go116start: span.start,
230                 go116end:   span.end,
231         }
232
233         // Cheap trick: Don't report errors with messages containing
234         // "invalid operand" or "invalid type" as those tend to be
235         // follow-on errors which don't add useful information. Only
236         // exclude them if these strings are not at the beginning,
237         // and only if we have at least one error already reported.
238         isInvalidErr := strings.Index(e.Msg, "invalid operand") > 0 || strings.Index(e.Msg, "invalid type") > 0
239         if check.firstErr != nil && isInvalidErr {
240                 return
241         }
242
243         e.Msg = stripAnnotations(e.Msg)
244         if check.errpos != nil {
245                 // If we have an internal error and the errpos override is set, use it to
246                 // augment our error positioning.
247                 // TODO(rFindley) we may also want to augment the error message and refer
248                 // to the position (pos) in the original expression.
249                 span := spanOf(check.errpos)
250                 e.Pos = span.pos
251                 e.go116start = span.start
252                 e.go116end = span.end
253         }
254         err := e
255
256         if check.firstErr == nil {
257                 check.firstErr = err
258         }
259
260         if trace {
261                 pos := e.Pos
262                 msg := e.Msg
263                 check.trace(pos, "ERROR: %s", msg)
264         }
265
266         f := check.conf.Error
267         if f == nil {
268                 panic(bailout{}) // report only first error
269         }
270         f(err)
271 }
272
273 // newErrorf creates a new error_ for later reporting with check.report.
274 func newErrorf(at positioner, code errorCode, format string, args ...any) *error_ {
275         return &error_{
276                 desc: []errorDesc{{at, format, args}},
277                 code: code,
278         }
279 }
280
281 func (check *Checker) error(at positioner, code errorCode, msg string) {
282         check.report(newErrorf(at, code, msg))
283 }
284
285 func (check *Checker) errorf(at positioner, code errorCode, format string, args ...any) {
286         check.report(newErrorf(at, code, format, args...))
287 }
288
289 func (check *Checker) softErrorf(at positioner, code errorCode, format string, args ...any) {
290         err := newErrorf(at, code, format, args...)
291         err.soft = true
292         check.report(err)
293 }
294
295 func (check *Checker) versionErrorf(at positioner, code errorCode, goVersion string, format string, args ...interface{}) {
296         msg := check.sprintf(format, args...)
297         var err *error_
298         if compilerErrorMessages {
299                 err = newErrorf(at, code, "%s requires %s or later (-lang was set to %s; check go.mod)", msg, goVersion, check.conf.GoVersion)
300         } else {
301                 err = newErrorf(at, code, "%s requires %s or later", msg, goVersion)
302         }
303         check.report(err)
304 }
305
306 func (check *Checker) invalidAST(at positioner, format string, args ...any) {
307         check.errorf(at, 0, "invalid AST: "+format, args...)
308 }
309
310 func (check *Checker) invalidArg(at positioner, code errorCode, format string, args ...any) {
311         check.errorf(at, code, "invalid argument: "+format, args...)
312 }
313
314 func (check *Checker) invalidOp(at positioner, code errorCode, format string, args ...any) {
315         check.errorf(at, code, "invalid operation: "+format, args...)
316 }
317
318 // The positioner interface is used to extract the position of type-checker
319 // errors.
320 type positioner interface {
321         Pos() token.Pos
322 }
323
324 // posSpan holds a position range along with a highlighted position within that
325 // range. This is used for positioning errors, with pos by convention being the
326 // first position in the source where the error is known to exist, and start
327 // and end defining the full span of syntax being considered when the error was
328 // detected. Invariant: start <= pos < end || start == pos == end.
329 type posSpan struct {
330         start, pos, end token.Pos
331 }
332
333 func (e posSpan) Pos() token.Pos {
334         return e.pos
335 }
336
337 // inNode creates a posSpan for the given node.
338 // Invariant: node.Pos() <= pos < node.End() (node.End() is the position of the
339 // first byte after node within the source).
340 func inNode(node ast.Node, pos token.Pos) posSpan {
341         start, end := node.Pos(), node.End()
342         if debug {
343                 assert(start <= pos && pos < end)
344         }
345         return posSpan{start, pos, end}
346 }
347
348 // atPos wraps a token.Pos to implement the positioner interface.
349 type atPos token.Pos
350
351 func (s atPos) Pos() token.Pos {
352         return token.Pos(s)
353 }
354
355 // spanOf extracts an error span from the given positioner. By default this is
356 // the trivial span starting and ending at pos, but this span is expanded when
357 // the argument naturally corresponds to a span of source code.
358 func spanOf(at positioner) posSpan {
359         switch x := at.(type) {
360         case nil:
361                 panic("nil positioner")
362         case posSpan:
363                 return x
364         case ast.Node:
365                 pos := x.Pos()
366                 return posSpan{pos, pos, x.End()}
367         case *operand:
368                 if x.expr != nil {
369                         pos := x.Pos()
370                         return posSpan{pos, pos, x.expr.End()}
371                 }
372                 return posSpan{token.NoPos, token.NoPos, token.NoPos}
373         default:
374                 pos := at.Pos()
375                 return posSpan{pos, pos, pos}
376         }
377 }
378
379 // stripAnnotations removes internal (type) annotations from s.
380 func stripAnnotations(s string) string {
381         var buf strings.Builder
382         for _, r := range s {
383                 // strip #'s and subscript digits
384                 if r < '₀' || '₀'+10 <= r { // '₀' == U+2080
385                         buf.WriteRune(r)
386                 }
387         }
388         if buf.Len() < len(s) {
389                 return buf.String()
390         }
391         return s
392 }