Source file
src/go/types/decl.go
1
2
3
4
5 package types
6
7 import (
8 "fmt"
9 "go/ast"
10 "go/constant"
11 "go/token"
12 . "internal/types/errors"
13 )
14
15 func (check *Checker) reportAltDecl(obj Object) {
16 if pos := obj.Pos(); pos.IsValid() {
17
18
19
20 check.errorf(obj, DuplicateDecl, "\tother declaration of %s", obj.Name())
21 }
22 }
23
24 func (check *Checker) declare(scope *Scope, id *ast.Ident, obj Object, pos token.Pos) {
25
26
27
28
29 if obj.Name() != "_" {
30 if alt := scope.Insert(obj); alt != nil {
31 check.errorf(obj, DuplicateDecl, "%s redeclared in this block", obj.Name())
32 check.reportAltDecl(alt)
33 return
34 }
35 obj.setScopePos(pos)
36 }
37 if id != nil {
38 check.recordDef(id, obj)
39 }
40 }
41
42
43 func pathString(path []Object) string {
44 var s string
45 for i, p := range path {
46 if i > 0 {
47 s += "->"
48 }
49 s += p.Name()
50 }
51 return s
52 }
53
54
55
56 func (check *Checker) objDecl(obj Object, def *TypeName) {
57 if check.conf._Trace && obj.Type() == nil {
58 if check.indent == 0 {
59 fmt.Println()
60 }
61 check.trace(obj.Pos(), "-- checking %s (%s, objPath = %s)", obj, obj.color(), pathString(check.objPath))
62 check.indent++
63 defer func() {
64 check.indent--
65 check.trace(obj.Pos(), "=> %s (%s)", obj, obj.color())
66 }()
67 }
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96 if obj.color() == white && obj.Type() != nil {
97 obj.setColor(black)
98 return
99 }
100
101 switch obj.color() {
102 case white:
103 assert(obj.Type() == nil)
104
105
106
107 obj.setColor(grey + color(check.push(obj)))
108 defer func() {
109 check.pop().setColor(black)
110 }()
111
112 case black:
113 assert(obj.Type() != nil)
114 return
115
116 default:
117
118 fallthrough
119
120 case grey:
121
122
123
124
125
126
127
128
129
130
131 switch obj := obj.(type) {
132 case *Const:
133 if !check.validCycle(obj) || obj.typ == nil {
134 obj.typ = Typ[Invalid]
135 }
136
137 case *Var:
138 if !check.validCycle(obj) || obj.typ == nil {
139 obj.typ = Typ[Invalid]
140 }
141
142 case *TypeName:
143 if !check.validCycle(obj) {
144
145
146
147
148
149 obj.typ = Typ[Invalid]
150 }
151
152 case *Func:
153 if !check.validCycle(obj) {
154
155
156
157
158
159
160 }
161
162 default:
163 unreachable()
164 }
165 assert(obj.Type() != nil)
166 return
167 }
168
169 d := check.objMap[obj]
170 if d == nil {
171 check.dump("%v: %s should have been declared", obj.Pos(), obj)
172 unreachable()
173 }
174
175
176 defer func(env environment) {
177 check.environment = env
178 }(check.environment)
179 check.environment = environment{
180 scope: d.file,
181 }
182
183
184
185
186
187
188 switch obj := obj.(type) {
189 case *Const:
190 check.decl = d
191 check.constDecl(obj, d.vtyp, d.init, d.inherited)
192 case *Var:
193 check.decl = d
194 check.varDecl(obj, d.lhs, d.vtyp, d.init)
195 case *TypeName:
196
197 check.typeDecl(obj, d.tdecl, def)
198 check.collectMethods(obj)
199 case *Func:
200
201 check.funcDecl(obj, d)
202 default:
203 unreachable()
204 }
205 }
206
207
208
209 func (check *Checker) validCycle(obj Object) (valid bool) {
210
211 if debug {
212 info := check.objMap[obj]
213 inObjMap := info != nil && (info.fdecl == nil || info.fdecl.Recv == nil)
214 isPkgObj := obj.Parent() == check.pkg.scope
215 if isPkgObj != inObjMap {
216 check.dump("%v: inconsistent object map for %s (isPkgObj = %v, inObjMap = %v)", obj.Pos(), obj, isPkgObj, inObjMap)
217 unreachable()
218 }
219 }
220
221
222 assert(obj.color() >= grey)
223 start := obj.color() - grey
224 cycle := check.objPath[start:]
225 tparCycle := false
226 nval := 0
227 ndef := 0
228 loop:
229 for _, obj := range cycle {
230 switch obj := obj.(type) {
231 case *Const, *Var:
232 nval++
233 case *TypeName:
234
235
236
237 if check.inTParamList && isGeneric(obj.typ) {
238 tparCycle = true
239 break loop
240 }
241
242
243
244
245
246
247
248
249
250
251 var alias bool
252 if check.enableAlias {
253 alias = obj.IsAlias()
254 } else {
255 if d := check.objMap[obj]; d != nil {
256 alias = d.tdecl.Assign.IsValid()
257 } else {
258 alias = obj.IsAlias()
259 }
260 }
261 if !alias {
262 ndef++
263 }
264 case *Func:
265
266 default:
267 unreachable()
268 }
269 }
270
271 if check.conf._Trace {
272 check.trace(obj.Pos(), "## cycle detected: objPath = %s->%s (len = %d)", pathString(cycle), obj.Name(), len(cycle))
273 if tparCycle {
274 check.trace(obj.Pos(), "## cycle contains: generic type in a type parameter list")
275 } else {
276 check.trace(obj.Pos(), "## cycle contains: %d values, %d type definitions", nval, ndef)
277 }
278 defer func() {
279 if valid {
280 check.trace(obj.Pos(), "=> cycle is valid")
281 } else {
282 check.trace(obj.Pos(), "=> error: cycle is invalid")
283 }
284 }()
285 }
286
287 if !tparCycle {
288
289
290
291 if nval == len(cycle) {
292 return true
293 }
294
295
296
297
298 if nval == 0 && ndef > 0 {
299 return true
300 }
301 }
302
303 check.cycleError(cycle)
304 return false
305 }
306
307
308
309 func (check *Checker) cycleError(cycle []Object) {
310
311
312
313
314 name := func(obj Object) string {
315 return packagePrefix(obj.Pkg(), check.qualifier) + obj.Name()
316 }
317
318
319
320
321 i := firstInSrc(cycle)
322 obj := cycle[i]
323 objName := name(obj)
324
325 tname, _ := obj.(*TypeName)
326 if tname != nil && tname.IsAlias() {
327
328
329 if !check.enableAlias {
330 check.validAlias(tname, Typ[Invalid])
331 }
332 }
333
334
335 if len(cycle) == 1 {
336 if tname != nil {
337 check.errorf(obj, InvalidDeclCycle, "invalid recursive type: %s refers to itself", objName)
338 } else {
339 check.errorf(obj, InvalidDeclCycle, "invalid cycle in declaration: %s refers to itself", objName)
340 }
341 return
342 }
343
344 if tname != nil {
345 check.errorf(obj, InvalidDeclCycle, "invalid recursive type %s", objName)
346 } else {
347 check.errorf(obj, InvalidDeclCycle, "invalid cycle in declaration of %s", objName)
348 }
349 for range cycle {
350 check.errorf(obj, InvalidDeclCycle, "\t%s refers to", objName)
351 i++
352 if i >= len(cycle) {
353 i = 0
354 }
355 obj = cycle[i]
356 objName = name(obj)
357 }
358 check.errorf(obj, InvalidDeclCycle, "\t%s", objName)
359 }
360
361
362
363 func firstInSrc(path []Object) int {
364 fst, pos := 0, path[0].Pos()
365 for i, t := range path[1:] {
366 if cmpPos(t.Pos(), pos) < 0 {
367 fst, pos = i+1, t.Pos()
368 }
369 }
370 return fst
371 }
372
373 type (
374 decl interface {
375 node() ast.Node
376 }
377
378 importDecl struct{ spec *ast.ImportSpec }
379 constDecl struct {
380 spec *ast.ValueSpec
381 iota int
382 typ ast.Expr
383 init []ast.Expr
384 inherited bool
385 }
386 varDecl struct{ spec *ast.ValueSpec }
387 typeDecl struct{ spec *ast.TypeSpec }
388 funcDecl struct{ decl *ast.FuncDecl }
389 )
390
391 func (d importDecl) node() ast.Node { return d.spec }
392 func (d constDecl) node() ast.Node { return d.spec }
393 func (d varDecl) node() ast.Node { return d.spec }
394 func (d typeDecl) node() ast.Node { return d.spec }
395 func (d funcDecl) node() ast.Node { return d.decl }
396
397 func (check *Checker) walkDecls(decls []ast.Decl, f func(decl)) {
398 for _, d := range decls {
399 check.walkDecl(d, f)
400 }
401 }
402
403 func (check *Checker) walkDecl(d ast.Decl, f func(decl)) {
404 switch d := d.(type) {
405 case *ast.BadDecl:
406
407 case *ast.GenDecl:
408 var last *ast.ValueSpec
409 for iota, s := range d.Specs {
410 switch s := s.(type) {
411 case *ast.ImportSpec:
412 f(importDecl{s})
413 case *ast.ValueSpec:
414 switch d.Tok {
415 case token.CONST:
416
417 inherited := true
418 switch {
419 case s.Type != nil || len(s.Values) > 0:
420 last = s
421 inherited = false
422 case last == nil:
423 last = new(ast.ValueSpec)
424 inherited = false
425 }
426 check.arityMatch(s, last)
427 f(constDecl{spec: s, iota: iota, typ: last.Type, init: last.Values, inherited: inherited})
428 case token.VAR:
429 check.arityMatch(s, nil)
430 f(varDecl{s})
431 default:
432 check.errorf(s, InvalidSyntaxTree, "invalid token %s", d.Tok)
433 }
434 case *ast.TypeSpec:
435 f(typeDecl{s})
436 default:
437 check.errorf(s, InvalidSyntaxTree, "unknown ast.Spec node %T", s)
438 }
439 }
440 case *ast.FuncDecl:
441 f(funcDecl{d})
442 default:
443 check.errorf(d, InvalidSyntaxTree, "unknown ast.Decl node %T", d)
444 }
445 }
446
447 func (check *Checker) constDecl(obj *Const, typ, init ast.Expr, inherited bool) {
448 assert(obj.typ == nil)
449
450
451 defer func(iota constant.Value, errpos positioner) {
452 check.iota = iota
453 check.errpos = errpos
454 }(check.iota, check.errpos)
455 check.iota = obj.val
456 check.errpos = nil
457
458
459 obj.val = constant.MakeUnknown()
460
461
462 if typ != nil {
463 t := check.typ(typ)
464 if !isConstType(t) {
465
466
467 if isValid(under(t)) {
468 check.errorf(typ, InvalidConstType, "invalid constant type %s", t)
469 }
470 obj.typ = Typ[Invalid]
471 return
472 }
473 obj.typ = t
474 }
475
476
477 var x operand
478 if init != nil {
479 if inherited {
480
481
482
483
484
485
486 check.errpos = atPos(obj.pos)
487 }
488 check.expr(nil, &x, init)
489 }
490 check.initConst(obj, &x)
491 }
492
493 func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init ast.Expr) {
494 assert(obj.typ == nil)
495
496
497 if typ != nil {
498 obj.typ = check.varType(typ)
499
500
501
502
503
504
505
506
507 }
508
509
510 if init == nil {
511 if typ == nil {
512
513 obj.typ = Typ[Invalid]
514 }
515 return
516 }
517
518 if lhs == nil || len(lhs) == 1 {
519 assert(lhs == nil || lhs[0] == obj)
520 var x operand
521 check.expr(newTarget(obj.typ, obj.name), &x, init)
522 check.initVar(obj, &x, "variable declaration")
523 return
524 }
525
526 if debug {
527
528 found := false
529 for _, lhs := range lhs {
530 if obj == lhs {
531 found = true
532 break
533 }
534 }
535 if !found {
536 panic("inconsistent lhs")
537 }
538 }
539
540
541
542
543
544 if typ != nil {
545 for _, lhs := range lhs {
546 lhs.typ = obj.typ
547 }
548 }
549
550 check.initVars(lhs, []ast.Expr{init}, nil)
551 }
552
553
554 func (check *Checker) isImportedConstraint(typ Type) bool {
555 named := asNamed(typ)
556 if named == nil || named.obj.pkg == check.pkg || named.obj.pkg == nil {
557 return false
558 }
559 u, _ := named.under().(*Interface)
560 return u != nil && !u.IsMethodSet()
561 }
562
563 func (check *Checker) typeDecl(obj *TypeName, tdecl *ast.TypeSpec, def *TypeName) {
564 assert(obj.typ == nil)
565
566 var rhs Type
567 check.later(func() {
568 if t := asNamed(obj.typ); t != nil {
569 check.validType(t)
570 }
571
572 _ = check.isImportedConstraint(rhs) && check.verifyVersionf(tdecl.Type, go1_18, "using type constraint %s", rhs)
573 }).describef(obj, "validType(%s)", obj.Name())
574
575 aliasDecl := tdecl.Assign.IsValid()
576 if aliasDecl && tdecl.TypeParams.NumFields() != 0 {
577
578
579 check.error(atPos(tdecl.Assign), BadDecl, "generic type cannot be alias")
580 aliasDecl = false
581 }
582
583
584 if aliasDecl {
585 check.verifyVersionf(atPos(tdecl.Assign), go1_9, "type aliases")
586 if check.enableAlias {
587
588
589
590 alias := check.newAlias(obj, Typ[Invalid])
591 setDefType(def, alias)
592 rhs = check.definedType(tdecl.Type, obj)
593 assert(rhs != nil)
594 alias.fromRHS = rhs
595 Unalias(alias)
596 } else {
597 check.brokenAlias(obj)
598 rhs = check.typ(tdecl.Type)
599 check.validAlias(obj, rhs)
600 }
601 return
602 }
603
604
605 named := check.newNamed(obj, nil, nil)
606 setDefType(def, named)
607
608 if tdecl.TypeParams != nil {
609 check.openScope(tdecl, "type parameters")
610 defer check.closeScope()
611 check.collectTypeParams(&named.tparams, tdecl.TypeParams)
612 }
613
614
615 rhs = check.definedType(tdecl.Type, obj)
616 assert(rhs != nil)
617 named.fromRHS = rhs
618
619
620
621 if named.underlying == nil {
622 named.underlying = Typ[Invalid]
623 }
624
625
626
627
628
629
630 if isTypeParam(rhs) {
631 check.error(tdecl.Type, MisplacedTypeParam, "cannot use a type parameter as RHS in type declaration")
632 named.underlying = Typ[Invalid]
633 }
634 }
635
636 func (check *Checker) collectTypeParams(dst **TypeParamList, list *ast.FieldList) {
637 var tparams []*TypeParam
638
639
640
641 scopePos := list.Pos()
642 for _, f := range list.List {
643 tparams = check.declareTypeParams(tparams, f.Names, scopePos)
644 }
645
646
647
648
649 *dst = bindTParams(tparams)
650
651
652
653
654
655
656
657
658 assert(!check.inTParamList)
659 check.inTParamList = true
660 defer func() {
661 check.inTParamList = false
662 }()
663
664 index := 0
665 for _, f := range list.List {
666 var bound Type
667
668
669 if f.Type != nil {
670 bound = check.bound(f.Type)
671 if isTypeParam(bound) {
672
673
674
675
676 check.error(f.Type, MisplacedTypeParam, "cannot use a type parameter as constraint")
677 bound = Typ[Invalid]
678 }
679 } else {
680 bound = Typ[Invalid]
681 }
682 for i := range f.Names {
683 tparams[index+i].bound = bound
684 }
685 index += len(f.Names)
686 }
687 }
688
689 func (check *Checker) bound(x ast.Expr) Type {
690
691
692
693 wrap := false
694 switch op := x.(type) {
695 case *ast.UnaryExpr:
696 wrap = op.Op == token.TILDE
697 case *ast.BinaryExpr:
698 wrap = op.Op == token.OR
699 }
700 if wrap {
701 x = &ast.InterfaceType{Methods: &ast.FieldList{List: []*ast.Field{{Type: x}}}}
702 t := check.typ(x)
703
704 if t, _ := t.(*Interface); t != nil {
705 t.implicit = true
706 }
707 return t
708 }
709 return check.typ(x)
710 }
711
712 func (check *Checker) declareTypeParams(tparams []*TypeParam, names []*ast.Ident, scopePos token.Pos) []*TypeParam {
713
714
715
716
717
718
719 for _, name := range names {
720 tname := NewTypeName(name.Pos(), check.pkg, name.Name, nil)
721 tpar := check.newTypeParam(tname, Typ[Invalid])
722 check.declare(check.scope, name, tname, scopePos)
723 tparams = append(tparams, tpar)
724 }
725
726 if check.conf._Trace && len(names) > 0 {
727 check.trace(names[0].Pos(), "type params = %v", tparams[len(tparams)-len(names):])
728 }
729
730 return tparams
731 }
732
733 func (check *Checker) collectMethods(obj *TypeName) {
734
735
736
737
738 methods := check.methods[obj]
739 if methods == nil {
740 return
741 }
742 delete(check.methods, obj)
743 assert(!check.objMap[obj].tdecl.Assign.IsValid())
744
745
746 var mset objset
747
748
749
750 base := asNamed(obj.typ)
751 if base != nil {
752 assert(base.TypeArgs().Len() == 0)
753
754
755
756 check.later(func() {
757 check.checkFieldUniqueness(base)
758 }).describef(obj, "verifying field uniqueness for %v", base)
759
760
761
762
763 for i := 0; i < base.NumMethods(); i++ {
764 m := base.Method(i)
765 assert(m.name != "_")
766 assert(mset.insert(m) == nil)
767 }
768 }
769
770
771 for _, m := range methods {
772
773
774 assert(m.name != "_")
775 if alt := mset.insert(m); alt != nil {
776 if alt.Pos().IsValid() {
777 check.errorf(m, DuplicateMethod, "method %s.%s already declared at %s", obj.Name(), m.name, alt.Pos())
778 } else {
779 check.errorf(m, DuplicateMethod, "method %s.%s already declared", obj.Name(), m.name)
780 }
781 continue
782 }
783
784 if base != nil {
785 base.AddMethod(m)
786 }
787 }
788 }
789
790 func (check *Checker) checkFieldUniqueness(base *Named) {
791 if t, _ := base.under().(*Struct); t != nil {
792 var mset objset
793 for i := 0; i < base.NumMethods(); i++ {
794 m := base.Method(i)
795 assert(m.name != "_")
796 assert(mset.insert(m) == nil)
797 }
798
799
800
801 for _, fld := range t.fields {
802 if fld.name != "_" {
803 if alt := mset.insert(fld); alt != nil {
804
805
806 _ = alt.(*Func)
807
808
809
810 check.errorf(alt, DuplicateFieldAndMethod, "field and method with the same name %s", fld.name)
811 check.reportAltDecl(fld)
812 }
813 }
814 }
815 }
816 }
817
818 func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
819 assert(obj.typ == nil)
820
821
822 assert(check.iota == nil)
823
824 sig := new(Signature)
825 obj.typ = sig
826
827
828
829
830
831
832
833 saved := obj.color_
834 obj.color_ = black
835 fdecl := decl.fdecl
836 check.funcType(sig, fdecl.Recv, fdecl.Type)
837 obj.color_ = saved
838
839
840
841 sig.scope.pos = fdecl.Pos()
842 sig.scope.end = fdecl.End()
843
844 if fdecl.Type.TypeParams.NumFields() > 0 && fdecl.Body == nil {
845 check.softErrorf(fdecl.Name, BadDecl, "generic function is missing function body")
846 }
847
848
849
850 if !check.conf.IgnoreFuncBodies && fdecl.Body != nil {
851 check.later(func() {
852 check.funcBody(decl, obj.name, sig, fdecl.Body, nil)
853 }).describef(obj, "func %s", obj.name)
854 }
855 }
856
857 func (check *Checker) declStmt(d ast.Decl) {
858 pkg := check.pkg
859
860 check.walkDecl(d, func(d decl) {
861 switch d := d.(type) {
862 case constDecl:
863 top := len(check.delayed)
864
865
866 lhs := make([]*Const, len(d.spec.Names))
867 for i, name := range d.spec.Names {
868 obj := NewConst(name.Pos(), pkg, name.Name, nil, constant.MakeInt64(int64(d.iota)))
869 lhs[i] = obj
870
871 var init ast.Expr
872 if i < len(d.init) {
873 init = d.init[i]
874 }
875
876 check.constDecl(obj, d.typ, init, d.inherited)
877 }
878
879
880 check.processDelayed(top)
881
882
883
884
885
886 scopePos := d.spec.End()
887 for i, name := range d.spec.Names {
888 check.declare(check.scope, name, lhs[i], scopePos)
889 }
890
891 case varDecl:
892 top := len(check.delayed)
893
894 lhs0 := make([]*Var, len(d.spec.Names))
895 for i, name := range d.spec.Names {
896 lhs0[i] = NewVar(name.Pos(), pkg, name.Name, nil)
897 }
898
899
900 for i, obj := range lhs0 {
901 var lhs []*Var
902 var init ast.Expr
903 switch len(d.spec.Values) {
904 case len(d.spec.Names):
905
906 init = d.spec.Values[i]
907 case 1:
908
909 lhs = lhs0
910 init = d.spec.Values[0]
911 default:
912 if i < len(d.spec.Values) {
913 init = d.spec.Values[i]
914 }
915 }
916 check.varDecl(obj, lhs, d.spec.Type, init)
917 if len(d.spec.Values) == 1 {
918
919
920
921
922
923 if debug {
924 for _, obj := range lhs0 {
925 assert(obj.typ != nil)
926 }
927 }
928 break
929 }
930 }
931
932
933 check.processDelayed(top)
934
935
936
937 scopePos := d.spec.End()
938 for i, name := range d.spec.Names {
939
940 check.declare(check.scope, name, lhs0[i], scopePos)
941 }
942
943 case typeDecl:
944 obj := NewTypeName(d.spec.Name.Pos(), pkg, d.spec.Name.Name, nil)
945
946
947
948 scopePos := d.spec.Name.Pos()
949 check.declare(check.scope, d.spec.Name, obj, scopePos)
950
951 obj.setColor(grey + color(check.push(obj)))
952 check.typeDecl(obj, d.spec, nil)
953 check.pop().setColor(black)
954 default:
955 check.errorf(d.node(), InvalidSyntaxTree, "unknown ast.Decl node %T", d.node())
956 }
957 })
958 }
959
View as plain text