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