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