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