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