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 tracePos {
52 check.pushPos(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.Alias
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 && tname.IsAlias() {
324
325
326 if !check.conf.EnableAlias {
327 check.validAlias(tname, Typ[Invalid])
328 }
329 }
330
331
332 if len(cycle) == 1 {
333 if tname != nil {
334 check.errorf(obj, InvalidDeclCycle, "invalid recursive type: %s refers to itself", name(obj))
335 } else {
336 check.errorf(obj, InvalidDeclCycle, "invalid cycle in declaration: %s refers to itself", name(obj))
337 }
338 return
339 }
340
341 err := check.newError(InvalidDeclCycle)
342 if tname != nil {
343 err.addf(obj, "invalid recursive type %s", name(obj))
344 } else {
345 err.addf(obj, "invalid cycle in declaration of %s", name(obj))
346 }
347
348 for i := range cycle {
349 next := cycle[(start+i+1)%len(cycle)]
350 err.addf(obj, "%s refers to %s", name(obj), name(next))
351 obj = next
352 }
353 err.report()
354 }
355
356
357
358 func firstInSrc(path []Object) int {
359 fst, pos := 0, path[0].Pos()
360 for i, t := range path[1:] {
361 if cmpPos(t.Pos(), pos) < 0 {
362 fst, pos = i+1, t.Pos()
363 }
364 }
365 return fst
366 }
367
368 func (check *Checker) constDecl(obj *Const, typ, init syntax.Expr, inherited bool) {
369 assert(obj.typ == nil)
370
371
372 defer func(iota constant.Value, errpos syntax.Pos) {
373 check.iota = iota
374 check.errpos = errpos
375 }(check.iota, check.errpos)
376 check.iota = obj.val
377 check.errpos = nopos
378
379
380 obj.val = constant.MakeUnknown()
381
382
383 if typ != nil {
384 t := check.typ(typ)
385 if !isConstType(t) {
386
387
388 if isValid(under(t)) {
389 check.errorf(typ, InvalidConstType, "invalid constant type %s", t)
390 }
391 obj.typ = Typ[Invalid]
392 return
393 }
394 obj.typ = t
395 }
396
397
398 var x operand
399 if init != nil {
400 if inherited {
401
402
403
404
405
406
407 check.errpos = obj.pos
408 }
409 check.expr(nil, &x, init)
410 }
411 check.initConst(obj, &x)
412 }
413
414 func (check *Checker) varDecl(obj *Var, lhs []*Var, typ, init syntax.Expr) {
415 assert(obj.typ == nil)
416
417
418 if typ != nil {
419 obj.typ = check.varType(typ)
420
421
422
423
424
425
426
427
428 }
429
430
431 if init == nil {
432 if typ == nil {
433
434 obj.typ = Typ[Invalid]
435 }
436 return
437 }
438
439 if lhs == nil || len(lhs) == 1 {
440 assert(lhs == nil || lhs[0] == obj)
441 var x operand
442 check.expr(newTarget(obj.typ, obj.name), &x, init)
443 check.initVar(obj, &x, "variable declaration")
444 return
445 }
446
447 if debug {
448
449 if !slices.Contains(lhs, obj) {
450 panic("inconsistent lhs")
451 }
452 }
453
454
455
456
457
458 if typ != nil {
459 for _, lhs := range lhs {
460 lhs.typ = obj.typ
461 }
462 }
463
464 check.initVars(lhs, []syntax.Expr{init}, nil)
465 }
466
467
468 func (check *Checker) isImportedConstraint(typ Type) bool {
469 named := asNamed(typ)
470 if named == nil || named.obj.pkg == check.pkg || named.obj.pkg == nil {
471 return false
472 }
473 u, _ := named.under().(*Interface)
474 return u != nil && !u.IsMethodSet()
475 }
476
477 func (check *Checker) typeDecl(obj *TypeName, tdecl *syntax.TypeDecl, def *TypeName) {
478 assert(obj.typ == nil)
479
480
481 versionErr := false
482
483 var rhs Type
484 check.later(func() {
485 if t := asNamed(obj.typ); t != nil {
486 check.validType(t)
487 }
488
489 _ = !versionErr && check.isImportedConstraint(rhs) && check.verifyVersionf(tdecl.Type, go1_18, "using type constraint %s", rhs)
490 }).describef(obj, "validType(%s)", obj.Name())
491
492
493 var tparam0 *syntax.Field
494 if len(tdecl.TParamList) > 0 {
495 tparam0 = tdecl.TParamList[0]
496 }
497
498
499 if tdecl.Alias {
500
501
502 if !versionErr && tparam0 != nil && !check.verifyVersionf(tparam0, go1_23, "generic type alias") {
503 versionErr = true
504 }
505 if !versionErr && !check.verifyVersionf(tdecl, go1_9, "type alias") {
506 versionErr = true
507 }
508
509 if check.conf.EnableAlias {
510
511
512
513
514
515
516
517
518 alias := check.newAlias(obj, Typ[Invalid])
519 setDefType(def, alias)
520
521
522 if tparam0 != nil {
523 if !versionErr && !buildcfg.Experiment.AliasTypeParams {
524 check.error(tdecl, UnsupportedFeature, "generic type alias requires GOEXPERIMENT=aliastypeparams")
525 versionErr = true
526 }
527 check.openScope(tdecl, "type parameters")
528 defer check.closeScope()
529 check.collectTypeParams(&alias.tparams, tdecl.TParamList)
530 }
531
532 rhs = check.definedType(tdecl.Type, obj)
533 assert(rhs != nil)
534 alias.fromRHS = rhs
535 Unalias(alias)
536 } else {
537 if !versionErr && tparam0 != nil {
538 check.error(tdecl, UnsupportedFeature, "generic type alias requires GODEBUG=gotypesalias=1 or unset")
539 versionErr = true
540 }
541
542 check.brokenAlias(obj)
543 rhs = check.typ(tdecl.Type)
544 check.validAlias(obj, rhs)
545 }
546 return
547 }
548
549
550 if !versionErr && tparam0 != nil && !check.verifyVersionf(tparam0, go1_18, "type parameter") {
551 versionErr = true
552 }
553
554 named := check.newNamed(obj, nil, nil)
555 setDefType(def, named)
556
557 if tdecl.TParamList != nil {
558 check.openScope(tdecl, "type parameters")
559 defer check.closeScope()
560 check.collectTypeParams(&named.tparams, tdecl.TParamList)
561 }
562
563
564 rhs = check.definedType(tdecl.Type, obj)
565 assert(rhs != nil)
566 named.fromRHS = rhs
567
568
569
570 if named.underlying == nil {
571 named.underlying = Typ[Invalid]
572 }
573
574
575
576
577
578
579 if isTypeParam(rhs) {
580 check.error(tdecl.Type, MisplacedTypeParam, "cannot use a type parameter as RHS in type declaration")
581 named.underlying = Typ[Invalid]
582 }
583 }
584
585 func (check *Checker) collectTypeParams(dst **TypeParamList, list []*syntax.Field) {
586 tparams := make([]*TypeParam, len(list))
587
588
589
590
591 if len(list) > 0 {
592 scopePos := list[0].Pos()
593 for i, f := range list {
594 tparams[i] = check.declareTypeParam(f.Name, scopePos)
595 }
596 }
597
598
599
600
601 *dst = bindTParams(tparams)
602
603
604
605
606
607
608
609
610 assert(!check.inTParamList)
611 check.inTParamList = true
612 defer func() {
613 check.inTParamList = false
614 }()
615
616
617 var bound Type
618 for i, f := range list {
619
620
621
622 if i == 0 || f.Type != list[i-1].Type {
623 bound = check.bound(f.Type)
624 if isTypeParam(bound) {
625
626
627
628
629 check.error(f.Type, MisplacedTypeParam, "cannot use a type parameter as constraint")
630 bound = Typ[Invalid]
631 }
632 }
633 tparams[i].bound = bound
634 }
635 }
636
637 func (check *Checker) bound(x syntax.Expr) Type {
638
639
640
641 if op, _ := x.(*syntax.Operation); op != nil && (op.Op == syntax.Tilde || op.Op == syntax.Or) {
642 t := check.typ(&syntax.InterfaceType{MethodList: []*syntax.Field{{Type: x}}})
643
644 if t, _ := t.(*Interface); t != nil {
645 t.implicit = true
646 }
647 return t
648 }
649 return check.typ(x)
650 }
651
652 func (check *Checker) declareTypeParam(name *syntax.Name, scopePos syntax.Pos) *TypeParam {
653
654
655
656
657
658
659 tname := NewTypeName(name.Pos(), check.pkg, name.Value, nil)
660 tpar := check.newTypeParam(tname, Typ[Invalid])
661 check.declare(check.scope, name, tname, scopePos)
662 return tpar
663 }
664
665 func (check *Checker) collectMethods(obj *TypeName) {
666
667
668
669
670 methods := check.methods[obj]
671 if methods == nil {
672 return
673 }
674 delete(check.methods, obj)
675 assert(!check.objMap[obj].tdecl.Alias)
676
677
678 var mset objset
679
680
681
682 base := asNamed(obj.typ)
683 if base != nil {
684 assert(base.TypeArgs().Len() == 0)
685
686
687
688 check.later(func() {
689 check.checkFieldUniqueness(base)
690 }).describef(obj, "verifying field uniqueness for %v", base)
691
692
693
694
695 for i := 0; i < base.NumMethods(); i++ {
696 m := base.Method(i)
697 assert(m.name != "_")
698 assert(mset.insert(m) == nil)
699 }
700 }
701
702
703 for _, m := range methods {
704
705
706 assert(m.name != "_")
707 if alt := mset.insert(m); alt != nil {
708 if alt.Pos().IsKnown() {
709 check.errorf(m.pos, DuplicateMethod, "method %s.%s already declared at %v", obj.Name(), m.name, alt.Pos())
710 } else {
711 check.errorf(m.pos, DuplicateMethod, "method %s.%s already declared", obj.Name(), m.name)
712 }
713 continue
714 }
715
716 if base != nil {
717 base.AddMethod(m)
718 }
719 }
720 }
721
722 func (check *Checker) checkFieldUniqueness(base *Named) {
723 if t, _ := base.under().(*Struct); t != nil {
724 var mset objset
725 for i := 0; i < base.NumMethods(); i++ {
726 m := base.Method(i)
727 assert(m.name != "_")
728 assert(mset.insert(m) == nil)
729 }
730
731
732
733 for _, fld := range t.fields {
734 if fld.name != "_" {
735 if alt := mset.insert(fld); alt != nil {
736
737
738 _ = alt.(*Func)
739
740
741
742 err := check.newError(DuplicateFieldAndMethod)
743 err.addf(alt, "field and method with the same name %s", fld.name)
744 err.addAltDecl(fld)
745 err.report()
746 }
747 }
748 }
749 }
750 }
751
752 func (check *Checker) funcDecl(obj *Func, decl *declInfo) {
753 assert(obj.typ == nil)
754
755
756 assert(check.iota == nil)
757
758 sig := new(Signature)
759 obj.typ = sig
760
761
762
763
764
765
766
767 saved := obj.color_
768 obj.color_ = black
769 fdecl := decl.fdecl
770 check.funcType(sig, fdecl.Recv, fdecl.TParamList, fdecl.Type)
771 obj.color_ = saved
772
773
774
775 sig.scope.pos = fdecl.Pos()
776 sig.scope.end = syntax.EndPos(fdecl)
777
778 if len(fdecl.TParamList) > 0 && fdecl.Body == nil {
779 check.softErrorf(fdecl, BadDecl, "generic function is missing function body")
780 }
781
782
783
784 if !check.conf.IgnoreFuncBodies && fdecl.Body != nil {
785 check.later(func() {
786 check.funcBody(decl, obj.name, sig, fdecl.Body, nil)
787 }).describef(obj, "func %s", obj.name)
788 }
789 }
790
791 func (check *Checker) declStmt(list []syntax.Decl) {
792 pkg := check.pkg
793
794 first := -1
795 var last *syntax.ConstDecl
796 for index, decl := range list {
797 if _, ok := decl.(*syntax.ConstDecl); !ok {
798 first = -1
799 }
800
801 switch s := decl.(type) {
802 case *syntax.ConstDecl:
803 top := len(check.delayed)
804
805
806 if first < 0 || s.Group == nil || list[index-1].(*syntax.ConstDecl).Group != s.Group {
807 first = index
808 last = nil
809 }
810 iota := constant.MakeInt64(int64(index - first))
811
812
813 inherited := true
814 switch {
815 case s.Type != nil || s.Values != nil:
816 last = s
817 inherited = false
818 case last == nil:
819 last = new(syntax.ConstDecl)
820 inherited = false
821 }
822
823
824 lhs := make([]*Const, len(s.NameList))
825 values := syntax.UnpackListExpr(last.Values)
826 for i, name := range s.NameList {
827 obj := NewConst(name.Pos(), pkg, name.Value, nil, iota)
828 lhs[i] = obj
829
830 var init syntax.Expr
831 if i < len(values) {
832 init = values[i]
833 }
834
835 check.constDecl(obj, last.Type, init, inherited)
836 }
837
838
839 check.arity(s.Pos(), s.NameList, values, true, inherited)
840
841
842 check.processDelayed(top)
843
844
845
846
847
848 scopePos := syntax.EndPos(s)
849 for i, name := range s.NameList {
850 check.declare(check.scope, name, lhs[i], scopePos)
851 }
852
853 case *syntax.VarDecl:
854 top := len(check.delayed)
855
856 lhs0 := make([]*Var, len(s.NameList))
857 for i, name := range s.NameList {
858 lhs0[i] = newVar(LocalVar, name.Pos(), pkg, name.Value, nil)
859 }
860
861
862 values := syntax.UnpackListExpr(s.Values)
863 for i, obj := range lhs0 {
864 var lhs []*Var
865 var init syntax.Expr
866 switch len(values) {
867 case len(s.NameList):
868
869 init = values[i]
870 case 1:
871
872 lhs = lhs0
873 init = values[0]
874 default:
875 if i < len(values) {
876 init = values[i]
877 }
878 }
879 check.varDecl(obj, lhs, s.Type, init)
880 if len(values) == 1 {
881
882
883
884
885
886 if debug {
887 for _, obj := range lhs0 {
888 assert(obj.typ != nil)
889 }
890 }
891 break
892 }
893 }
894
895
896 if s.Type == nil || values != nil {
897 check.arity(s.Pos(), s.NameList, values, false, false)
898 }
899
900
901 check.processDelayed(top)
902
903
904
905 scopePos := syntax.EndPos(s)
906 for i, name := range s.NameList {
907
908 check.declare(check.scope, name, lhs0[i], scopePos)
909 }
910
911 case *syntax.TypeDecl:
912 obj := NewTypeName(s.Name.Pos(), pkg, s.Name.Value, nil)
913
914
915
916 scopePos := s.Name.Pos()
917 check.declare(check.scope, s.Name, obj, scopePos)
918
919 obj.setColor(grey + color(check.push(obj)))
920 check.typeDecl(obj, s, nil)
921 check.pop().setColor(black)
922
923 default:
924 check.errorf(s, InvalidSyntaxTree, "unknown syntax.Decl node %T", s)
925 }
926 }
927 }
928
View as plain text