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