Source file
src/go/types/call.go
1
2
3
4
5
6
7 package types
8
9 import (
10 "go/ast"
11 "go/internal/typeparams"
12 "go/token"
13 "strings"
14 "unicode"
15 )
16
17
18
19 func (check *Checker) funcInst(x *operand, ix *typeparams.IndexExpr) {
20 if !check.allowVersion(check.pkg, 1, 18) {
21 check.softErrorf(inNode(ix.Orig, ix.Lbrack), _UnsupportedFeature, "function instantiation requires go1.18 or later")
22 }
23
24 targs := check.typeList(ix.Indices)
25 if targs == nil {
26 x.mode = invalid
27 x.expr = ix.Orig
28 return
29 }
30 assert(len(targs) == len(ix.Indices))
31
32
33 sig := x.typ.(*Signature)
34 got, want := len(targs), sig.TypeParams().Len()
35 if got > want {
36 check.errorf(ix.Indices[got-1], _WrongTypeArgCount, "got %d type arguments but want %d", got, want)
37 x.mode = invalid
38 x.expr = ix.Orig
39 return
40 }
41
42 if got < want {
43 targs = check.infer(ix.Orig, sig.TypeParams().list(), targs, nil, nil)
44 if targs == nil {
45
46 x.mode = invalid
47 x.expr = ix.Orig
48 return
49 }
50 got = len(targs)
51 }
52 assert(got == want)
53
54
55 res := check.instantiateSignature(x.Pos(), sig, targs, ix.Indices)
56 assert(res.TypeParams().Len() == 0)
57 check.recordInstance(ix.Orig, targs, res)
58 x.typ = res
59 x.mode = value
60 x.expr = ix.Orig
61 }
62
63 func (check *Checker) instantiateSignature(pos token.Pos, typ *Signature, targs []Type, xlist []ast.Expr) (res *Signature) {
64 assert(check != nil)
65 assert(len(targs) == typ.TypeParams().Len())
66
67 if trace {
68 check.trace(pos, "-- instantiating %s with %s", typ, targs)
69 check.indent++
70 defer func() {
71 check.indent--
72 check.trace(pos, "=> %s (under = %s)", res, res.Underlying())
73 }()
74 }
75
76 inst := check.instance(pos, typ, targs, check.bestContext(nil)).(*Signature)
77 assert(len(xlist) <= len(targs))
78
79
80 check.later(func() {
81 tparams := typ.TypeParams().list()
82 if i, err := check.verify(pos, tparams, targs); err != nil {
83
84 pos := pos
85 if i < len(xlist) {
86 pos = xlist[i].Pos()
87 }
88 check.softErrorf(atPos(pos), _InvalidTypeArg, "%s", err)
89 } else {
90 check.mono.recordInstance(check.pkg, pos, tparams, targs, xlist)
91 }
92 })
93
94 return inst
95 }
96
97 func (check *Checker) callExpr(x *operand, call *ast.CallExpr) exprKind {
98 ix := typeparams.UnpackIndexExpr(call.Fun)
99 if ix != nil {
100 if check.indexExpr(x, ix) {
101
102
103
104 assert(x.mode == value)
105 } else {
106 ix = nil
107 }
108 x.expr = call.Fun
109 check.record(x)
110
111 } else {
112 check.exprOrType(x, call.Fun, true)
113 }
114
115
116 switch x.mode {
117 case invalid:
118 check.use(call.Args...)
119 x.expr = call
120 return statement
121
122 case typexpr:
123
124 check.nonGeneric(x)
125 if x.mode == invalid {
126 return conversion
127 }
128 T := x.typ
129 x.mode = invalid
130 switch n := len(call.Args); n {
131 case 0:
132 check.errorf(inNode(call, call.Rparen), _WrongArgCount, "missing argument in conversion to %s", T)
133 case 1:
134 check.expr(x, call.Args[0])
135 if x.mode != invalid {
136 if call.Ellipsis.IsValid() {
137 check.errorf(call.Args[0], _BadDotDotDotSyntax, "invalid use of ... in conversion to %s", T)
138 break
139 }
140 if t, _ := under(T).(*Interface); t != nil && !isTypeParam(T) {
141 if !t.IsMethodSet() {
142 check.errorf(call, _MisplacedConstraintIface, "cannot use interface %s in conversion (contains specific type constraints or is comparable)", T)
143 break
144 }
145 }
146 check.conversion(x, T)
147 }
148 default:
149 check.use(call.Args...)
150 check.errorf(call.Args[n-1], _WrongArgCount, "too many arguments in conversion to %s", T)
151 }
152 x.expr = call
153 return conversion
154
155 case builtin:
156
157 id := x.id
158 if !check.builtin(x, call, id) {
159 x.mode = invalid
160 }
161 x.expr = call
162
163 if x.mode != invalid && x.mode != constant_ {
164 check.hasCallOrRecv = true
165 }
166 return predeclaredFuncs[id].kind
167 }
168
169
170
171 cgocall := x.mode == cgofunc
172
173
174 sig, _ := coreType(x.typ).(*Signature)
175 if sig == nil {
176 check.invalidOp(x, _InvalidCall, "cannot call non-function %s", x)
177 x.mode = invalid
178 x.expr = call
179 return statement
180 }
181
182
183 var xlist []ast.Expr
184 var targs []Type
185 if ix != nil {
186 xlist = ix.Indices
187 targs = check.typeList(xlist)
188 if targs == nil {
189 check.use(call.Args...)
190 x.mode = invalid
191 x.expr = call
192 return statement
193 }
194 assert(len(targs) == len(xlist))
195
196
197 got, want := len(targs), sig.TypeParams().Len()
198 if got > want {
199 check.errorf(xlist[want], _WrongTypeArgCount, "got %d type arguments but want %d", got, want)
200 check.use(call.Args...)
201 x.mode = invalid
202 x.expr = call
203 return statement
204 }
205 }
206
207
208 args, _ := check.exprList(call.Args, false)
209 isGeneric := sig.TypeParams().Len() > 0
210 sig = check.arguments(call, sig, targs, args, xlist)
211
212 if isGeneric && sig.TypeParams().Len() == 0 {
213
214 check.recordTypeAndValue(call.Fun, value, sig, nil)
215 }
216
217
218 switch sig.results.Len() {
219 case 0:
220 x.mode = novalue
221 case 1:
222 if cgocall {
223 x.mode = commaerr
224 } else {
225 x.mode = value
226 }
227 x.typ = sig.results.vars[0].typ
228 default:
229 x.mode = value
230 x.typ = sig.results
231 }
232 x.expr = call
233 check.hasCallOrRecv = true
234
235
236
237 if x.mode == value && sig.TypeParams().Len() > 0 && isParameterized(sig.TypeParams().list(), x.typ) {
238 x.mode = invalid
239 }
240
241 return statement
242 }
243
244 func (check *Checker) exprList(elist []ast.Expr, allowCommaOk bool) (xlist []*operand, commaOk bool) {
245 switch len(elist) {
246 case 0:
247
248
249 case 1:
250
251 e := elist[0]
252 var x operand
253 check.multiExpr(&x, e)
254 if t, ok := x.typ.(*Tuple); ok && x.mode != invalid {
255
256 xlist = make([]*operand, t.Len())
257 for i, v := range t.vars {
258 xlist[i] = &operand{mode: value, expr: e, typ: v.typ}
259 }
260 break
261 }
262
263
264 xlist = []*operand{&x}
265 if allowCommaOk && (x.mode == mapindex || x.mode == commaok || x.mode == commaerr) {
266 x2 := &operand{mode: value, expr: e, typ: Typ[UntypedBool]}
267 if x.mode == commaerr {
268 x2.typ = universeError
269 }
270 xlist = append(xlist, x2)
271 commaOk = true
272 }
273
274 default:
275
276 xlist = make([]*operand, len(elist))
277 for i, e := range elist {
278 var x operand
279 check.expr(&x, e)
280 xlist[i] = &x
281 }
282 }
283
284 return
285 }
286
287
288 func (check *Checker) arguments(call *ast.CallExpr, sig *Signature, targs []Type, args []*operand, xlist []ast.Expr) (rsig *Signature) {
289 rsig = sig
290
291
292 for _, a := range args {
293 switch a.mode {
294 case typexpr:
295 check.errorf(a, 0, "%s used as value", a)
296 return
297 case invalid:
298 return
299 }
300 }
301
302
303
304
305
306
307
308
309
310
311 nargs := len(args)
312 npars := sig.params.Len()
313 ddd := call.Ellipsis.IsValid()
314
315
316 sigParams := sig.params
317 adjusted := false
318 if sig.variadic {
319 if ddd {
320
321 if len(call.Args) == 1 && nargs > 1 {
322
323 check.errorf(inNode(call, call.Ellipsis), _InvalidDotDotDot, "cannot use ... with %d-valued %s", nargs, call.Args[0])
324 return
325 }
326 } else {
327
328 if nargs >= npars-1 {
329
330
331
332 vars := make([]*Var, npars-1)
333 copy(vars, sig.params.vars)
334 last := sig.params.vars[npars-1]
335 typ := last.typ.(*Slice).elem
336 for len(vars) < nargs {
337 vars = append(vars, NewParam(last.pos, last.pkg, last.name, typ))
338 }
339 sigParams = NewTuple(vars...)
340 adjusted = true
341 npars = nargs
342 } else {
343
344 npars--
345 }
346 }
347 } else {
348 if ddd {
349
350 check.errorf(inNode(call, call.Ellipsis), _NonVariadicDotDotDot, "cannot use ... in call to non-variadic %s", call.Fun)
351 return
352 }
353
354 }
355
356
357 if nargs != npars {
358 var at positioner = call
359 qualifier := "not enough"
360 if nargs > npars {
361 at = args[npars].expr
362 qualifier = "too many"
363 } else {
364 at = atPos(call.Rparen)
365 }
366
367 var params []*Var
368 if sig.params != nil {
369 params = sig.params.vars
370 }
371 check.errorf(at, _WrongArgCount, "%s arguments in call to %s\n\thave %s\n\twant %s",
372 qualifier, call.Fun,
373 check.typesSummary(operandTypes(args), false),
374 check.typesSummary(varTypes(params), sig.variadic),
375 )
376 return
377 }
378
379
380 if sig.TypeParams().Len() > 0 {
381 if !check.allowVersion(check.pkg, 1, 18) {
382 switch call.Fun.(type) {
383 case *ast.IndexExpr, *ast.IndexListExpr:
384 ix := typeparams.UnpackIndexExpr(call.Fun)
385 check.softErrorf(inNode(call.Fun, ix.Lbrack), _UnsupportedFeature, "function instantiation requires go1.18 or later")
386 default:
387 check.softErrorf(inNode(call, call.Lparen), _UnsupportedFeature, "implicit function instantiation requires go1.18 or later")
388 }
389 }
390 targs := check.infer(call, sig.TypeParams().list(), targs, sigParams, args)
391 if targs == nil {
392 return
393 }
394
395
396 rsig = check.instantiateSignature(call.Pos(), sig, targs, xlist)
397 assert(rsig.TypeParams().Len() == 0)
398 check.recordInstance(call.Fun, targs, rsig)
399
400
401
402
403 if adjusted {
404 sigParams = check.subst(call.Pos(), sigParams, makeSubstMap(sig.TypeParams().list(), targs), nil).(*Tuple)
405 } else {
406 sigParams = rsig.params
407 }
408 }
409
410
411 if len(args) > 0 {
412 context := check.sprintf("argument to %s", call.Fun)
413 for i, a := range args {
414 check.assignment(a, sigParams.vars[i].typ, context)
415 }
416 }
417
418 return
419 }
420
421 var cgoPrefixes = [...]string{
422 "_Ciconst_",
423 "_Cfconst_",
424 "_Csconst_",
425 "_Ctype_",
426 "_Cvar_",
427 "_Cfpvar_fp_",
428 "_Cfunc_",
429 "_Cmacro_",
430 }
431
432 func (check *Checker) selector(x *operand, e *ast.SelectorExpr, def *Named) {
433
434 var (
435 obj Object
436 index []int
437 indirect bool
438 )
439
440 sel := e.Sel.Name
441
442
443
444
445 if ident, ok := e.X.(*ast.Ident); ok {
446 obj := check.lookup(ident.Name)
447 if pname, _ := obj.(*PkgName); pname != nil {
448 assert(pname.pkg == check.pkg)
449 check.recordUse(ident, pname)
450 pname.used = true
451 pkg := pname.imported
452
453 var exp Object
454 funcMode := value
455 if pkg.cgo {
456
457
458
459 if sel == "malloc" {
460 sel = "_CMalloc"
461 } else {
462 funcMode = cgofunc
463 }
464 for _, prefix := range cgoPrefixes {
465
466
467 _, exp = check.scope.LookupParent(prefix+sel, check.pos)
468 if exp != nil {
469 break
470 }
471 }
472 if exp == nil {
473 check.errorf(e.Sel, _UndeclaredImportedName, "%s not declared by package C", sel)
474 goto Error
475 }
476 check.objDecl(exp, nil)
477 } else {
478 exp = pkg.scope.Lookup(sel)
479 if exp == nil {
480 if !pkg.fake {
481 check.errorf(e.Sel, _UndeclaredImportedName, "%s not declared by package %s", sel, pkg.name)
482 }
483 goto Error
484 }
485 if !exp.Exported() {
486 check.errorf(e.Sel, _UnexportedName, "%s not exported by package %s", sel, pkg.name)
487
488 }
489 }
490 check.recordUse(e.Sel, exp)
491
492
493
494 switch exp := exp.(type) {
495 case *Const:
496 assert(exp.Val() != nil)
497 x.mode = constant_
498 x.typ = exp.typ
499 x.val = exp.val
500 case *TypeName:
501 x.mode = typexpr
502 x.typ = exp.typ
503 case *Var:
504 x.mode = variable
505 x.typ = exp.typ
506 if pkg.cgo && strings.HasPrefix(exp.name, "_Cvar_") {
507 x.typ = x.typ.(*Pointer).base
508 }
509 case *Func:
510 x.mode = funcMode
511 x.typ = exp.typ
512 if pkg.cgo && strings.HasPrefix(exp.name, "_Cmacro_") {
513 x.mode = value
514 x.typ = x.typ.(*Signature).results.vars[0].typ
515 }
516 case *Builtin:
517 x.mode = builtin
518 x.typ = exp.typ
519 x.id = exp.id
520 default:
521 check.dump("%v: unexpected object %v", e.Sel.Pos(), exp)
522 unreachable()
523 }
524 x.expr = e
525 return
526 }
527 }
528
529 check.exprOrType(x, e.X, false)
530 switch x.mode {
531 case typexpr:
532
533 if def != nil && x.typ == def {
534 check.cycleError([]Object{def.obj})
535 goto Error
536 }
537 case builtin:
538
539 check.errorf(e.Sel, _UncalledBuiltin, "cannot select on %s", x)
540 goto Error
541 case invalid:
542 goto Error
543 }
544
545 obj, index, indirect = LookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, sel)
546 if obj == nil {
547
548 if under(x.typ) == Typ[Invalid] {
549 goto Error
550 }
551
552 if index != nil {
553
554 check.errorf(e.Sel, _AmbiguousSelector, "ambiguous selector %s.%s", x.expr, sel)
555 goto Error
556 }
557
558 if indirect {
559 check.errorf(e.Sel, _InvalidMethodExpr, "cannot call pointer method %s on %s", sel, x.typ)
560 goto Error
561 }
562
563 var why string
564 if isInterfacePtr(x.typ) {
565 why = check.interfacePtrError(x.typ)
566 } else {
567 why = check.sprintf("type %s has no field or method %s", x.typ, sel)
568
569
570
571
572 if len(sel) > 0 {
573 var changeCase string
574 if r := rune(sel[0]); unicode.IsUpper(r) {
575 changeCase = string(unicode.ToLower(r)) + sel[1:]
576 } else {
577 changeCase = string(unicode.ToUpper(r)) + sel[1:]
578 }
579 if obj, _, _ = LookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, changeCase); obj != nil {
580 why += ", but does have " + changeCase
581 }
582 }
583 }
584 check.errorf(e.Sel, _MissingFieldOrMethod, "%s.%s undefined (%s)", x.expr, sel, why)
585 goto Error
586 }
587
588
589 if m, _ := obj.(*Func); m != nil {
590 check.objDecl(m, nil)
591 }
592
593 if x.mode == typexpr {
594
595 m, _ := obj.(*Func)
596 if m == nil {
597
598 check.errorf(e.Sel, _MissingFieldOrMethod, "%s.%s undefined (type %s has no method %s)", x.expr, sel, x.typ, sel)
599 goto Error
600 }
601
602 check.recordSelection(e, MethodExpr, x.typ, m, index, indirect)
603
604 sig := m.typ.(*Signature)
605 if sig.recv == nil {
606 check.error(e, _InvalidDeclCycle, "illegal cycle in method declaration")
607 goto Error
608 }
609
610
611
612 var params []*Var
613 if sig.params != nil {
614 params = sig.params.vars
615 }
616
617
618
619
620
621
622 name := ""
623 if len(params) > 0 && params[0].name != "" {
624
625 name = sig.recv.name
626 if name == "" {
627 name = "_"
628 }
629 }
630 params = append([]*Var{NewVar(sig.recv.pos, sig.recv.pkg, name, x.typ)}, params...)
631 x.mode = value
632 x.typ = &Signature{
633 tparams: sig.tparams,
634 params: NewTuple(params...),
635 results: sig.results,
636 variadic: sig.variadic,
637 }
638
639 check.addDeclDep(m)
640
641 } else {
642
643 switch obj := obj.(type) {
644 case *Var:
645 check.recordSelection(e, FieldVal, x.typ, obj, index, indirect)
646 if x.mode == variable || indirect {
647 x.mode = variable
648 } else {
649 x.mode = value
650 }
651 x.typ = obj.typ
652
653 case *Func:
654
655
656 check.recordSelection(e, MethodVal, x.typ, obj, index, indirect)
657
658
659
660
661
662
663
664 disabled := true
665 if !disabled && debug {
666
667
668
669
670
671 typ := x.typ
672 if x.mode == variable {
673
674
675
676
677
678 if _, ok := typ.(*Pointer); !ok && !IsInterface(typ) {
679 typ = &Pointer{base: typ}
680 }
681 }
682
683
684
685
686
687
688
689
690 mset := NewMethodSet(typ)
691 if m := mset.Lookup(check.pkg, sel); m == nil || m.obj != obj {
692 check.dump("%v: (%s).%v -> %s", e.Pos(), typ, obj.name, m)
693 check.dump("%s\n", mset)
694
695
696
697
698
699 panic("method sets and lookup don't agree")
700 }
701 }
702
703 x.mode = value
704
705
706 sig := *obj.typ.(*Signature)
707 sig.recv = nil
708 x.typ = &sig
709
710 check.addDeclDep(obj)
711
712 default:
713 unreachable()
714 }
715 }
716
717
718 x.expr = e
719 return
720
721 Error:
722 x.mode = invalid
723 x.expr = e
724 }
725
726
727
728
729
730 func (check *Checker) use(arg ...ast.Expr) {
731 var x operand
732 for _, e := range arg {
733
734
735 if e != nil {
736 check.rawExpr(&x, e, nil, false)
737 }
738 }
739 }
740
741
742
743
744
745 func (check *Checker) useLHS(arg ...ast.Expr) {
746 var x operand
747 for _, e := range arg {
748
749
750
751 var v *Var
752 var v_used bool
753 if ident, _ := unparen(e).(*ast.Ident); ident != nil {
754
755 if ident.Name == "_" {
756 continue
757 }
758 if _, obj := check.scope.LookupParent(ident.Name, token.NoPos); obj != nil {
759
760
761
762 if w, _ := obj.(*Var); w != nil && w.pkg == check.pkg {
763 v = w
764 v_used = v.used
765 }
766 }
767 }
768 check.rawExpr(&x, e, nil, false)
769 if v != nil {
770 v.used = v_used
771 }
772 }
773 }
774
View as plain text