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 _, obj := range imp.scope.elems {
313
314
315 if obj.Exported() {
316
317
318
319
320
321 if alt := fileScope.Insert(obj); alt != nil {
322 check.errorf(d.spec.Name, _DuplicateDecl, "%s redeclared in this block", obj.Name())
323 check.reportAltDecl(alt)
324 } else {
325 check.dotImportMap[dotImportKey{fileScope, obj}] = pkgName
326 }
327 }
328 }
329 } else {
330
331
332 check.declare(fileScope, nil, pkgName, token.NoPos)
333 }
334 case constDecl:
335
336 for i, name := range d.spec.Names {
337 obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
338
339 var init ast.Expr
340 if i < len(d.init) {
341 init = d.init[i]
342 }
343
344 d := &declInfo{file: fileScope, vtyp: d.typ, init: init, inherited: d.inherited}
345 check.declarePkgObj(name, obj, d)
346 }
347
348 case varDecl:
349 lhs := make([]*Var, len(d.spec.Names))
350
351
352
353
354 var d1 *declInfo
355 if len(d.spec.Values) == 1 {
356
357
358
359 d1 = &declInfo{file: fileScope, lhs: lhs, vtyp: d.spec.Type, init: d.spec.Values[0]}
360 }
361
362
363 for i, name := range d.spec.Names {
364 obj := NewVar(name.Pos(), pkg, name.Name, nil)
365 lhs[i] = obj
366
367 di := d1
368 if di == nil {
369
370 var init ast.Expr
371 if i < len(d.spec.Values) {
372 init = d.spec.Values[i]
373 }
374 di = &declInfo{file: fileScope, vtyp: d.spec.Type, init: init}
375 }
376
377 check.declarePkgObj(name, obj, di)
378 }
379 case typeDecl:
380 obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
381 check.declarePkgObj(d.spec.Name, obj, &declInfo{file: fileScope, tdecl: d.spec})
382 case funcDecl:
383 info := &declInfo{file: fileScope, fdecl: d.decl}
384 name := d.decl.Name.Name
385 obj := NewFunc(d.decl.Name.Pos(), pkg, name, nil)
386 if d.decl.Recv.NumFields() == 0 {
387
388 if d.decl.Recv != nil {
389 check.error(d.decl.Recv, _BadRecv, "method is missing receiver")
390
391 }
392 if name == "init" || (name == "main" && check.pkg.name == "main") {
393 code := _InvalidInitDecl
394 if name == "main" {
395 code = _InvalidMainDecl
396 }
397 if tparams := typeparams.Get(d.decl.Type); tparams != nil {
398 check.softErrorf(tparams, code, "func %s must have no type parameters", name)
399 }
400 if t := d.decl.Type; t.Params.NumFields() != 0 || t.Results != nil {
401
402 check.softErrorf(d.decl, code, "func %s must have no arguments and no return values", name)
403 }
404 }
405 if name == "init" {
406
407 obj.parent = pkg.scope
408 check.recordDef(d.decl.Name, obj)
409
410 if d.decl.Body == nil {
411
412 check.softErrorf(obj, _MissingInitBody, "missing function body")
413 }
414 } else {
415 check.declare(pkg.scope, d.decl.Name, obj, token.NoPos)
416 }
417 } else {
418
419
420
421
422
423
424
425 ptr, recv, _ := check.unpackRecv(d.decl.Recv.List[0].Type, false)
426
427
428
429 if recv != nil && name != "_" {
430 methods = append(methods, methodInfo{obj, ptr, recv})
431 }
432 check.recordDef(d.decl.Name, obj)
433 }
434
435
436
437
438 check.objMap[obj] = info
439 obj.setOrder(uint32(len(check.objMap)))
440 }
441 })
442 }
443
444
445 for _, scope := range fileScopes {
446 for _, obj := range scope.elems {
447 if alt := pkg.scope.Lookup(obj.Name()); alt != nil {
448 if pkg, ok := obj.(*PkgName); ok {
449 check.errorf(alt, _DuplicateDecl, "%s already declared through import of %s", alt.Name(), pkg.Imported())
450 check.reportAltDecl(pkg)
451 } else {
452 check.errorf(alt, _DuplicateDecl, "%s already declared through dot-import of %s", alt.Name(), obj.Pkg())
453
454 check.reportAltDecl(obj)
455 }
456 }
457 }
458 }
459
460
461
462
463
464 if methods == nil {
465 return
466 }
467 check.methods = make(map[*TypeName][]*Func)
468 for i := range methods {
469 m := &methods[i]
470
471 ptr, base := check.resolveBaseTypeName(m.ptr, m.recv)
472 if base != nil {
473 m.obj.hasPtrRecv = ptr
474 check.methods[base] = append(check.methods[base], m.obj)
475 }
476 }
477 }
478
479
480
481
482
483
484 func (check *Checker) unpackRecv(rtyp ast.Expr, unpackParams bool) (ptr bool, rname *ast.Ident, tparams []*ast.Ident) {
485 L:
486
487
488
489 for {
490 switch t := rtyp.(type) {
491 case *ast.ParenExpr:
492 rtyp = t.X
493 case *ast.StarExpr:
494 ptr = true
495 rtyp = t.X
496 default:
497 break L
498 }
499 }
500
501
502 if ptyp, _ := rtyp.(*ast.IndexExpr); ptyp != nil {
503 rtyp = ptyp.X
504 if unpackParams {
505 for _, arg := range typeparams.UnpackExpr(ptyp.Index) {
506 var par *ast.Ident
507 switch arg := arg.(type) {
508 case *ast.Ident:
509 par = arg
510 case *ast.BadExpr:
511
512 case nil:
513 check.invalidAST(ptyp, "parameterized receiver contains nil parameters")
514 default:
515 check.errorf(arg, _Todo, "receiver type parameter %s must be an identifier", arg)
516 }
517 if par == nil {
518 par = &ast.Ident{NamePos: arg.Pos(), Name: "_"}
519 }
520 tparams = append(tparams, par)
521 }
522 }
523 }
524
525
526 if name, _ := rtyp.(*ast.Ident); name != nil {
527 rname = name
528 }
529
530 return
531 }
532
533
534
535
536
537 func (check *Checker) resolveBaseTypeName(seenPtr bool, name *ast.Ident) (ptr bool, base *TypeName) {
538
539
540
541
542
543 ptr = seenPtr
544 var seen map[*TypeName]bool
545 var typ ast.Expr = name
546 for {
547 typ = unparen(typ)
548
549
550 if pexpr, _ := typ.(*ast.StarExpr); pexpr != nil {
551
552 if ptr {
553 return false, nil
554 }
555 ptr = true
556 typ = unparen(pexpr.X)
557 }
558
559
560 name, _ := typ.(*ast.Ident)
561 if name == nil {
562 return false, nil
563 }
564
565
566
567 obj := check.pkg.scope.Lookup(name.Name)
568 if obj == nil {
569 return false, nil
570 }
571
572
573 tname, _ := obj.(*TypeName)
574 if tname == nil {
575 return false, nil
576 }
577
578
579 if seen[tname] {
580 return false, nil
581 }
582
583
584
585 tdecl := check.objMap[tname].tdecl
586 if !tdecl.Assign.IsValid() {
587 return ptr, tname
588 }
589
590
591 typ = tdecl.Type
592 if seen == nil {
593 seen = make(map[*TypeName]bool)
594 }
595 seen[tname] = true
596 }
597 }
598
599
600 func (check *Checker) packageObjects() {
601
602 objList := make([]Object, len(check.objMap))
603 i := 0
604 for obj := range check.objMap {
605 objList[i] = obj
606 i++
607 }
608 sort.Sort(inSourceOrder(objList))
609
610
611 for _, obj := range objList {
612 if obj, _ := obj.(*TypeName); obj != nil && obj.typ != nil {
613 check.collectMethods(obj)
614 }
615 }
616
617
618
619
620
621
622
623 var aliasList []*TypeName
624
625 for _, obj := range objList {
626
627 if tname, _ := obj.(*TypeName); tname != nil && check.objMap[tname].tdecl.Assign.IsValid() {
628 aliasList = append(aliasList, tname)
629 continue
630 }
631
632 check.objDecl(obj, nil)
633 }
634
635 for _, obj := range aliasList {
636 check.objDecl(obj, nil)
637 }
638
639
640
641
642
643 check.methods = nil
644 }
645
646
647 type inSourceOrder []Object
648
649 func (a inSourceOrder) Len() int { return len(a) }
650 func (a inSourceOrder) Less(i, j int) bool { return a[i].order() < a[j].order() }
651 func (a inSourceOrder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
652
653
654 func (check *Checker) unusedImports() {
655
656 if check.conf.IgnoreFuncBodies {
657 return
658 }
659
660
661
662
663
664 for _, obj := range check.imports {
665 if !obj.used && obj.name != "_" {
666 check.errorUnusedPkg(obj)
667 }
668 }
669 }
670
671 func (check *Checker) errorUnusedPkg(obj *PkgName) {
672
673
674
675
676
677
678 path := obj.imported.path
679 elem := path
680 if i := strings.LastIndex(elem, "/"); i >= 0 {
681 elem = elem[i+1:]
682 }
683 if obj.name == "" || obj.name == "." || obj.name == elem {
684 check.softErrorf(obj, _UnusedImport, "%q imported but not used", path)
685 } else {
686 check.softErrorf(obj, _UnusedImport, "%q imported but not used as %s", path, obj.name)
687 }
688 }
689
690
691
692
693
694 func dir(path string) string {
695 if i := strings.LastIndexAny(path, `/\`); i > 0 {
696 return path[:i]
697 }
698
699 return "."
700 }
701
View as plain text