Source file
src/go/types/resolver.go
1
2
3
4
5 package types
6
7 import (
8 "fmt"
9 "go/ast"
10 "go/constant"
11 "go/internal/typeparams"
12 "go/token"
13 "sort"
14 "strconv"
15 "strings"
16 "unicode"
17 )
18
19
20 type declInfo struct {
21 file *Scope
22 lhs []*Var
23 vtyp ast.Expr
24 init ast.Expr
25 inherited bool
26 tdecl *ast.TypeSpec
27 fdecl *ast.FuncDecl
28
29
30 deps map[Object]bool
31 }
32
33
34
35 func (d *declInfo) hasInitializer() bool {
36 return d.init != nil || d.fdecl != nil && d.fdecl.Body != nil
37 }
38
39
40 func (d *declInfo) addDep(obj Object) {
41 m := d.deps
42 if m == nil {
43 m = make(map[Object]bool)
44 d.deps = m
45 }
46 m[obj] = true
47 }
48
49
50
51
52
53 func (check *Checker) arityMatch(s, init *ast.ValueSpec) {
54 l := len(s.Names)
55 r := len(s.Values)
56 if init != nil {
57 r = len(init.Values)
58 }
59
60 const code = _WrongAssignCount
61 switch {
62 case init == nil && r == 0:
63
64 if s.Type == nil {
65 check.errorf(s, code, "missing type or init expr")
66 }
67 case l < r:
68 if l < len(s.Values) {
69
70 n := s.Values[l]
71 check.errorf(n, code, "extra init expr %s", n)
72
73 } else {
74
75 check.errorf(s, code, "extra init expr at %s", check.fset.Position(init.Pos()))
76
77 }
78 case l > r && (init != nil || r != 1):
79 n := s.Names[r]
80 check.errorf(n, code, "missing init expr for %s", n)
81 }
82 }
83
84 func validatedImportPath(path string) (string, error) {
85 s, err := strconv.Unquote(path)
86 if err != nil {
87 return "", err
88 }
89 if s == "" {
90 return "", fmt.Errorf("empty string")
91 }
92 const illegalChars = `!"#$%&'()*,:;<=>?[\]^{|}` + "`\uFFFD"
93 for _, r := range s {
94 if !unicode.IsGraphic(r) || unicode.IsSpace(r) || strings.ContainsRune(illegalChars, r) {
95 return s, fmt.Errorf("invalid character %#U", r)
96 }
97 }
98 return s, nil
99 }
100
101
102
103 func (check *Checker) declarePkgObj(ident *ast.Ident, obj Object, d *declInfo) {
104 assert(ident.Name == obj.Name())
105
106
107
108 if ident.Name == "init" {
109 check.errorf(ident, _InvalidInitDecl, "cannot declare init - must be func")
110 return
111 }
112
113
114
115 if ident.Name == "main" && check.pkg.name == "main" {
116 check.errorf(ident, _InvalidMainDecl, "cannot declare main - must be func")
117 return
118 }
119
120 check.declare(check.pkg.scope, ident, obj, token.NoPos)
121 check.objMap[obj] = d
122 obj.setOrder(uint32(len(check.objMap)))
123 }
124
125
126 func (check *Checker) filename(fileNo int) string {
127 file := check.files[fileNo]
128 if pos := file.Pos(); pos.IsValid() {
129 return check.fset.File(pos).Name()
130 }
131 return fmt.Sprintf("file[%d]", fileNo)
132 }
133
134 func (check *Checker) importPackage(at positioner, path, dir string) *Package {
135
136
137
138
139
140 key := importKey{path, dir}
141 imp := check.impMap[key]
142 if imp != nil {
143 return imp
144 }
145
146
147 if path == "C" && (check.conf.FakeImportC || check.conf.go115UsesCgo) {
148 imp = NewPackage("C", "C")
149 imp.fake = true
150 imp.cgo = check.conf.go115UsesCgo
151 } else {
152
153 var err error
154 if importer := check.conf.Importer; importer == nil {
155 err = fmt.Errorf("Config.Importer not installed")
156 } else if importerFrom, ok := importer.(ImporterFrom); ok {
157 imp, err = importerFrom.ImportFrom(path, dir, 0)
158 if imp == nil && err == nil {
159 err = fmt.Errorf("Config.Importer.ImportFrom(%s, %s, 0) returned nil but no error", path, dir)
160 }
161 } else {
162 imp, err = importer.Import(path)
163 if imp == nil && err == nil {
164 err = fmt.Errorf("Config.Importer.Import(%s) returned nil but no error", path)
165 }
166 }
167
168
169 if err == nil && imp != nil && (imp.name == "_" || imp.name == "") {
170 err = fmt.Errorf("invalid package name: %q", imp.name)
171 imp = nil
172 }
173 if err != nil {
174 check.errorf(at, _BrokenImport, "could not import %s (%s)", path, err)
175 if imp == nil {
176
177
178 name := path
179 if i := len(name); i > 0 && name[i-1] == '/' {
180 name = name[:i-1]
181 }
182 if i := strings.LastIndex(name, "/"); i >= 0 {
183 name = name[i+1:]
184 }
185 imp = NewPackage(path, name)
186 }
187
188 imp.fake = true
189 }
190 }
191
192
193 if imp.complete || imp.fake {
194 check.impMap[key] = imp
195
196
197 if check.pkgPathMap != nil {
198 check.markImports(imp)
199 }
200 return imp
201 }
202
203
204 return nil
205 }
206
207
208
209
210 func (check *Checker) collectObjects() {
211 pkg := check.pkg
212
213
214
215
216
217
218
219 var pkgImports = make(map[*Package]bool)
220 for _, imp := range pkg.imports {
221 pkgImports[imp] = true
222 }
223
224 type methodInfo struct {
225 obj *Func
226 ptr bool
227 recv *ast.Ident
228 }
229 var methods []methodInfo
230 var fileScopes []*Scope
231 for fileNo, file := range check.files {
232
233
234 check.recordDef(file.Name, nil)
235
236
237
238
239 pos, end := file.Pos(), file.End()
240 if f := check.fset.File(file.Pos()); f != nil {
241 pos, end = token.Pos(f.Base()), token.Pos(f.Base()+f.Size())
242 }
243 fileScope := NewScope(check.pkg.scope, pos, end, check.filename(fileNo))
244 fileScopes = append(fileScopes, fileScope)
245 check.recordScope(file, fileScope)
246
247
248
249
250 fileDir := dir(check.fset.Position(file.Name.Pos()).Filename)
251
252 check.walkDecls(file.Decls, func(d decl) {
253 switch d := d.(type) {
254 case importDecl:
255
256 path, err := validatedImportPath(d.spec.Path.Value)
257 if err != nil {
258 check.errorf(d.spec.Path, _BadImportPath, "invalid import path (%s)", err)
259 return
260 }
261
262 imp := check.importPackage(d.spec.Path, path, fileDir)
263 if imp == nil {
264 return
265 }
266
267
268 name := imp.name
269 if d.spec.Name != nil {
270 name = d.spec.Name.Name
271 if path == "C" {
272
273 check.errorf(d.spec.Name, _ImportCRenamed, `cannot rename import "C"`)
274 return
275 }
276 }
277
278 if name == "init" {
279 check.errorf(d.spec, _InvalidInitDecl, "cannot import package as init - init must be a func")
280 return
281 }
282
283
284
285
286 if !pkgImports[imp] {
287 pkgImports[imp] = true
288 pkg.imports = append(pkg.imports, imp)
289 }
290
291 pkgName := NewPkgName(d.spec.Pos(), pkg, name, imp)
292 if d.spec.Name != nil {
293
294 check.recordDef(d.spec.Name, pkgName)
295 } else {
296 check.recordImplicit(d.spec, pkgName)
297 }
298
299 if path == "C" {
300
301 pkgName.used = true
302 }
303
304
305 check.imports = append(check.imports, pkgName)
306 if name == "." {
307
308 if check.dotImportMap == nil {
309 check.dotImportMap = make(map[dotImportKey]*PkgName)
310 }
311
312 for name, obj := range imp.scope.elems {
313
314
315
316
317
318 if token.IsExported(name) {
319
320
321
322
323
324 if alt := fileScope.Lookup(name); alt != nil {
325 check.errorf(d.spec.Name, _DuplicateDecl, "%s redeclared in this block", alt.Name())
326 check.reportAltDecl(alt)
327 } else {
328 fileScope.insert(name, obj)
329 check.dotImportMap[dotImportKey{fileScope, name}] = pkgName
330 }
331 }
332 }
333 } else {
334
335
336 check.declare(fileScope, nil, pkgName, token.NoPos)
337 }
338 case constDecl:
339
340 for i, name := range d.spec.Names {
341 obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
342
343 var init ast.Expr
344 if i < len(d.init) {
345 init = d.init[i]
346 }
347
348 d := &declInfo{file: fileScope, vtyp: d.typ, init: init, inherited: d.inherited}
349 check.declarePkgObj(name, obj, d)
350 }
351
352 case varDecl:
353 lhs := make([]*Var, len(d.spec.Names))
354
355
356
357
358 var d1 *declInfo
359 if len(d.spec.Values) == 1 {
360
361
362
363 d1 = &declInfo{file: fileScope, lhs: lhs, vtyp: d.spec.Type, init: d.spec.Values[0]}
364 }
365
366
367 for i, name := range d.spec.Names {
368 obj := NewVar(name.Pos(), pkg, name.Name, nil)
369 lhs[i] = obj
370
371 di := d1
372 if di == nil {
373
374 var init ast.Expr
375 if i < len(d.spec.Values) {
376 init = d.spec.Values[i]
377 }
378 di = &declInfo{file: fileScope, vtyp: d.spec.Type, init: init}
379 }
380
381 check.declarePkgObj(name, obj, di)
382 }
383 case typeDecl:
384 if d.spec.TypeParams.NumFields() != 0 && !check.allowVersion(pkg, 1, 18) {
385 check.softErrorf(d.spec.TypeParams.List[0], _UnsupportedFeature, "type parameters require go1.18 or later")
386 }
387 obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
388 check.declarePkgObj(d.spec.Name, obj, &declInfo{file: fileScope, tdecl: d.spec})
389 case funcDecl:
390 name := d.decl.Name.Name
391 obj := NewFunc(d.decl.Name.Pos(), pkg, name, nil)
392 hasTParamError := false
393 if d.decl.Recv.NumFields() == 0 {
394
395 if d.decl.Recv != nil {
396 check.error(d.decl.Recv, _BadRecv, "method is missing receiver")
397
398 }
399 if name == "init" || (name == "main" && check.pkg.name == "main") {
400 code := _InvalidInitDecl
401 if name == "main" {
402 code = _InvalidMainDecl
403 }
404 if d.decl.Type.TypeParams.NumFields() != 0 {
405 check.softErrorf(d.decl.Type.TypeParams.List[0], code, "func %s must have no type parameters", name)
406 hasTParamError = true
407 }
408 if t := d.decl.Type; t.Params.NumFields() != 0 || t.Results != nil {
409
410 check.softErrorf(d.decl, code, "func %s must have no arguments and no return values", name)
411 }
412 }
413 if name == "init" {
414
415 obj.parent = pkg.scope
416 check.recordDef(d.decl.Name, obj)
417
418 if d.decl.Body == nil {
419
420 check.softErrorf(obj, _MissingInitBody, "missing function body")
421 }
422 } else {
423 check.declare(pkg.scope, d.decl.Name, obj, token.NoPos)
424 }
425 } else {
426
427
428
429
430
431
432
433 ptr, recv, _ := check.unpackRecv(d.decl.Recv.List[0].Type, false)
434
435
436
437 if recv != nil && name != "_" {
438 methods = append(methods, methodInfo{obj, ptr, recv})
439 }
440 check.recordDef(d.decl.Name, obj)
441 }
442 if d.decl.Type.TypeParams.NumFields() != 0 && !check.allowVersion(pkg, 1, 18) && !hasTParamError {
443 check.softErrorf(d.decl.Type.TypeParams.List[0], _UnsupportedFeature, "type parameters require go1.18 or later")
444 }
445 info := &declInfo{file: fileScope, fdecl: d.decl}
446
447
448
449
450 check.objMap[obj] = info
451 obj.setOrder(uint32(len(check.objMap)))
452 }
453 })
454 }
455
456
457 for _, scope := range fileScopes {
458 for name, obj := range scope.elems {
459 if alt := pkg.scope.Lookup(name); alt != nil {
460 obj = resolve(name, obj)
461 if pkg, ok := obj.(*PkgName); ok {
462 check.errorf(alt, _DuplicateDecl, "%s already declared through import of %s", alt.Name(), pkg.Imported())
463 check.reportAltDecl(pkg)
464 } else {
465 check.errorf(alt, _DuplicateDecl, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
466
467 check.reportAltDecl(obj)
468 }
469 }
470 }
471 }
472
473
474
475
476
477 if methods == nil {
478 return
479 }
480 check.methods = make(map[*TypeName][]*Func)
481 for i := range methods {
482 m := &methods[i]
483
484 ptr, base := check.resolveBaseTypeName(m.ptr, m.recv)
485 if base != nil {
486 m.obj.hasPtrRecv_ = ptr
487 check.methods[base] = append(check.methods[base], m.obj)
488 }
489 }
490 }
491
492
493
494
495
496
497 func (check *Checker) unpackRecv(rtyp ast.Expr, unpackParams bool) (ptr bool, rname *ast.Ident, tparams []*ast.Ident) {
498 L:
499
500
501
502 for {
503 switch t := rtyp.(type) {
504 case *ast.ParenExpr:
505 rtyp = t.X
506 case *ast.StarExpr:
507 ptr = true
508 rtyp = t.X
509 default:
510 break L
511 }
512 }
513
514
515 switch rtyp.(type) {
516 case *ast.IndexExpr, *ast.IndexListExpr:
517 ix := typeparams.UnpackIndexExpr(rtyp)
518 rtyp = ix.X
519 if unpackParams {
520 for _, arg := range ix.Indices {
521 var par *ast.Ident
522 switch arg := arg.(type) {
523 case *ast.Ident:
524 par = arg
525 case *ast.BadExpr:
526
527 case nil:
528 check.invalidAST(ix.Orig, "parameterized receiver contains nil parameters")
529 default:
530 check.errorf(arg, _BadDecl, "receiver type parameter %s must be an identifier", arg)
531 }
532 if par == nil {
533 par = &ast.Ident{NamePos: arg.Pos(), Name: "_"}
534 }
535 tparams = append(tparams, par)
536 }
537 }
538 }
539
540
541 if name, _ := rtyp.(*ast.Ident); name != nil {
542 rname = name
543 }
544
545 return
546 }
547
548
549
550
551
552 func (check *Checker) resolveBaseTypeName(seenPtr bool, name *ast.Ident) (ptr bool, base *TypeName) {
553
554
555
556
557
558 ptr = seenPtr
559 var seen map[*TypeName]bool
560 var typ ast.Expr = name
561 for {
562 typ = unparen(typ)
563
564
565 if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
566
567 if ptr {
568 return false, nil
569 }
570 ptr = true
571 typ = unparen(pexpr.X)
572 }
573
574
575 name, _ := typ.(*ast.Ident)
576 if name == nil {
577 return false, nil
578 }
579
580
581
582 obj := check.pkg.scope.Lookup(name.Name)
583 if obj == nil {
584 return false, nil
585 }
586
587
588 tname, _ := obj.(*TypeName)
589 if tname == nil {
590 return false, nil
591 }
592
593
594 if seen[tname] {
595 return false, nil
596 }
597
598
599
600 tdecl := check.objMap[tname].tdecl
601 if !tdecl.Assign.IsValid() {
602 return ptr, tname
603 }
604
605
606 typ = tdecl.Type
607 if seen == nil {
608 seen = make(map[*TypeName]bool)
609 }
610 seen[tname] = true
611 }
612 }
613
614
615 func (check *Checker) packageObjects() {
616
617 objList := make([]Object, len(check.objMap))
618 i := 0
619 for obj := range check.objMap {
620 objList[i] = obj
621 i++
622 }
623 sort.Sort(inSourceOrder(objList))
624
625
626 for _, obj := range objList {
627 if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
628 check.collectMethods(obj)
629 }
630 }
631
632
633
634
635
636
637 var aliasList []*TypeName
638 var othersList []Object
639
640 for _, obj := range objList {
641 if tname, _ := obj.(*TypeName); tname != nil {
642 if check.objMap[tname].tdecl.Assign.IsValid() {
643 aliasList = append(aliasList, tname)
644 } else {
645 check.objDecl(obj, nil)
646 }
647 } else {
648 othersList = append(othersList, obj)
649 }
650 }
651
652 for _, obj := range aliasList {
653 check.objDecl(obj, nil)
654 }
655
656 for _, obj := range othersList {
657 check.objDecl(obj, nil)
658 }
659
660
661
662
663
664 check.methods = nil
665 }
666
667
668 type inSourceOrder []Object
669
670 func (a inSourceOrder) Len() int { return len(a) }
671 func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() }
672 func (a inSourceOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
673
674
675 func (check *Checker) unusedImports() {
676
677 if check.conf.IgnoreFuncBodies {
678 return
679 }
680
681
682
683
684
685 for _, obj := range check.imports {
686 if !obj.used && obj.name != "_" {
687 check.errorUnusedPkg(obj)
688 }
689 }
690 }
691
692 func (check *Checker) errorUnusedPkg(obj *PkgName) {
693
694
695
696
697
698
699 path := obj.imported.path
700 elem := path
701 if i := strings.LastIndex(elem, "/"); i >= 0 {
702 elem = elem[i+1:]
703 }
704 if obj.name == "" || obj.name == "." || obj.name == elem {
705 check.softErrorf(obj, _UnusedImport, "%q imported but not used", path)
706 } else {
707 check.softErrorf(obj, _UnusedImport, "%q imported but not used as %s", path, obj.name)
708 }
709 }
710
711
712
713
714
715 func dir(path string) string {
716 if i := strings.LastIndexAny(path, `/\`); i > 0 {
717 return path[:i]
718 }
719
720 return "."
721 }
722
View as plain text