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