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