]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/errors.go
go/types, types2: always use missingMethodReason in checker.Implements
[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         "errors"
12         "fmt"
13         "go/ast"
14         "go/token"
15         "strconv"
16         "strings"
17 )
18
19 func assert(p bool) {
20         if !p {
21                 panic("assertion failed")
22         }
23 }
24
25 func unreachable() {
26         panic("unreachable")
27 }
28
29 func (check *Checker) qualifier(pkg *Package) string {
30         // Qualify the package unless it's the package being type-checked.
31         if pkg != check.pkg {
32                 if check.pkgPathMap == nil {
33                         check.pkgPathMap = make(map[string]map[string]bool)
34                         check.seenPkgMap = make(map[*Package]bool)
35                         check.markImports(check.pkg)
36                 }
37                 // If the same package name was used by multiple packages, display the full path.
38                 if len(check.pkgPathMap[pkg.name]) > 1 {
39                         return strconv.Quote(pkg.path)
40                 }
41                 return pkg.name
42         }
43         return ""
44 }
45
46 // markImports recursively walks pkg and its imports, to record unique import
47 // paths in pkgPathMap.
48 func (check *Checker) markImports(pkg *Package) {
49         if check.seenPkgMap[pkg] {
50                 return
51         }
52         check.seenPkgMap[pkg] = true
53
54         forName, ok := check.pkgPathMap[pkg.name]
55         if !ok {
56                 forName = make(map[string]bool)
57                 check.pkgPathMap[pkg.name] = forName
58         }
59         forName[pkg.path] = true
60
61         for _, imp := range pkg.imports {
62                 check.markImports(imp)
63         }
64 }
65
66 // check may be nil.
67 func (check *Checker) sprintf(format string, args ...any) string {
68         var fset *token.FileSet
69         var qf Qualifier
70         if check != nil {
71                 fset = check.fset
72                 qf = check.qualifier
73         }
74         return sprintf(fset, qf, false, format, args...)
75 }
76
77 func sprintf(fset *token.FileSet, qf Qualifier, debug bool, format string, args ...any) string {
78         for i, arg := range args {
79                 switch a := arg.(type) {
80                 case nil:
81                         arg = "<nil>"
82                 case operand:
83                         panic("got operand instead of *operand")
84                 case *operand:
85                         arg = operandString(a, qf)
86                 case token.Pos:
87                         if fset != nil {
88                                 arg = fset.Position(a).String()
89                         }
90                 case ast.Expr:
91                         arg = ExprString(a)
92                 case []ast.Expr:
93                         var buf bytes.Buffer
94                         buf.WriteByte('[')
95                         writeExprList(&buf, a)
96                         buf.WriteByte(']')
97                         arg = buf.String()
98                 case Object:
99                         arg = ObjectString(a, qf)
100                 case Type:
101                         arg = typeString(a, qf, debug)
102                 case []Type:
103                         var buf bytes.Buffer
104                         buf.WriteByte('[')
105                         for i, x := range a {
106                                 if i > 0 {
107                                         buf.WriteString(", ")
108                                 }
109                                 buf.WriteString(typeString(x, qf, debug))
110                         }
111                         buf.WriteByte(']')
112                         arg = buf.String()
113                 }
114                 args[i] = arg
115         }
116         return fmt.Sprintf(format, args...)
117 }
118
119 func (check *Checker) trace(pos token.Pos, format string, args ...any) {
120         fmt.Printf("%s:\t%s%s\n",
121                 check.fset.Position(pos),
122                 strings.Repeat(".  ", check.indent),
123                 sprintf(check.fset, check.qualifier, true, format, args...),
124         )
125 }
126
127 // dump is only needed for debugging
128 func (check *Checker) dump(format string, args ...any) {
129         fmt.Println(sprintf(check.fset, check.qualifier, true, format, args...))
130 }
131
132 func (check *Checker) err(err error) {
133         if err == nil {
134                 return
135         }
136         var e Error
137         isInternal := errors.As(err, &e)
138         // Cheap trick: Don't report errors with messages containing
139         // "invalid operand" or "invalid type" as those tend to be
140         // follow-on errors which don't add useful information. Only
141         // exclude them if these strings are not at the beginning,
142         // and only if we have at least one error already reported.
143         isInvalidErr := isInternal && (strings.Index(e.Msg, "invalid operand") > 0 || strings.Index(e.Msg, "invalid type") > 0)
144         if check.firstErr != nil && isInvalidErr {
145                 return
146         }
147
148         if isInternal {
149                 e.Msg = stripAnnotations(e.Msg)
150                 if check.errpos != nil {
151                         // If we have an internal error and the errpos override is set, use it to
152                         // augment our error positioning.
153                         // TODO(rFindley) we may also want to augment the error message and refer
154                         // to the position (pos) in the original expression.
155                         span := spanOf(check.errpos)
156                         e.Pos = span.pos
157                         e.go116start = span.start
158                         e.go116end = span.end
159                 }
160                 err = e
161         }
162
163         if check.firstErr == nil {
164                 check.firstErr = err
165         }
166
167         if trace {
168                 pos := e.Pos
169                 msg := e.Msg
170                 if !isInternal {
171                         msg = err.Error()
172                         pos = token.NoPos
173                 }
174                 check.trace(pos, "ERROR: %s", msg)
175         }
176
177         f := check.conf.Error
178         if f == nil {
179                 panic(bailout{}) // report only first error
180         }
181         f(err)
182 }
183
184 func (check *Checker) newError(at positioner, code errorCode, soft bool, msg string) error {
185         span := spanOf(at)
186         return Error{
187                 Fset:       check.fset,
188                 Pos:        span.pos,
189                 Msg:        msg,
190                 Soft:       soft,
191                 go116code:  code,
192                 go116start: span.start,
193                 go116end:   span.end,
194         }
195 }
196
197 // newErrorf creates a new Error, but does not handle it.
198 func (check *Checker) newErrorf(at positioner, code errorCode, soft bool, format string, args ...any) error {
199         msg := check.sprintf(format, args...)
200         return check.newError(at, code, soft, msg)
201 }
202
203 func (check *Checker) error(at positioner, code errorCode, msg string) {
204         check.err(check.newError(at, code, false, msg))
205 }
206
207 func (check *Checker) errorf(at positioner, code errorCode, format string, args ...any) {
208         check.error(at, code, check.sprintf(format, args...))
209 }
210
211 func (check *Checker) softErrorf(at positioner, code errorCode, format string, args ...any) {
212         check.err(check.newErrorf(at, code, true, format, args...))
213 }
214
215 func (check *Checker) invalidAST(at positioner, format string, args ...any) {
216         check.errorf(at, 0, "invalid AST: "+format, args...)
217 }
218
219 func (check *Checker) invalidArg(at positioner, code errorCode, format string, args ...any) {
220         check.errorf(at, code, "invalid argument: "+format, args...)
221 }
222
223 func (check *Checker) invalidOp(at positioner, code errorCode, format string, args ...any) {
224         check.errorf(at, code, "invalid operation: "+format, args...)
225 }
226
227 // The positioner interface is used to extract the position of type-checker
228 // errors.
229 type positioner interface {
230         Pos() token.Pos
231 }
232
233 // posSpan holds a position range along with a highlighted position within that
234 // range. This is used for positioning errors, with pos by convention being the
235 // first position in the source where the error is known to exist, and start
236 // and end defining the full span of syntax being considered when the error was
237 // detected. Invariant: start <= pos < end || start == pos == end.
238 type posSpan struct {
239         start, pos, end token.Pos
240 }
241
242 func (e posSpan) Pos() token.Pos {
243         return e.pos
244 }
245
246 // inNode creates a posSpan for the given node.
247 // Invariant: node.Pos() <= pos < node.End() (node.End() is the position of the
248 // first byte after node within the source).
249 func inNode(node ast.Node, pos token.Pos) posSpan {
250         start, end := node.Pos(), node.End()
251         if debug {
252                 assert(start <= pos && pos < end)
253         }
254         return posSpan{start, pos, end}
255 }
256
257 // atPos wraps a token.Pos to implement the positioner interface.
258 type atPos token.Pos
259
260 func (s atPos) Pos() token.Pos {
261         return token.Pos(s)
262 }
263
264 // spanOf extracts an error span from the given positioner. By default this is
265 // the trivial span starting and ending at pos, but this span is expanded when
266 // the argument naturally corresponds to a span of source code.
267 func spanOf(at positioner) posSpan {
268         switch x := at.(type) {
269         case nil:
270                 panic("nil positioner")
271         case posSpan:
272                 return x
273         case ast.Node:
274                 pos := x.Pos()
275                 return posSpan{pos, pos, x.End()}
276         case *operand:
277                 if x.expr != nil {
278                         pos := x.Pos()
279                         return posSpan{pos, pos, x.expr.End()}
280                 }
281                 return posSpan{token.NoPos, token.NoPos, token.NoPos}
282         default:
283                 pos := at.Pos()
284                 return posSpan{pos, pos, pos}
285         }
286 }
287
288 // stripAnnotations removes internal (type) annotations from s.
289 func stripAnnotations(s string) string {
290         var b strings.Builder
291         for _, r := range s {
292                 // strip #'s and subscript digits
293                 if r < '₀' || '₀'+10 <= r { // '₀' == U+2080
294                         b.WriteRune(r)
295                 }
296         }
297         if b.Len() < len(s) {
298                 return b.String()
299         }
300         return s
301 }