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 signature %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, nil, check.context()).(*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, check.context()); 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 }).describef(atPos(pos), "verify instantiation")
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 err := newErrorf(at, _WrongArgCount, "%s arguments in call to %s", qualifier, call.Fun)
372 err.errorf(token.NoPos, "have %s", check.typesSummary(operandTypes(args), false))
373 err.errorf(token.NoPos, "want %s", check.typesSummary(varTypes(params), sig.variadic))
374 check.report(err)
375 return
376 }
377
378
379 if sig.TypeParams().Len() > 0 {
380 if !check.allowVersion(check.pkg, 1, 18) {
381 switch call.Fun.(type) {
382 case *ast.IndexExpr, *ast.IndexListExpr:
383 ix := typeparams.UnpackIndexExpr(call.Fun)
384 check.softErrorf(inNode(call.Fun, ix.Lbrack), _UnsupportedFeature, "function instantiation requires go1.18 or later")
385 default:
386 check.softErrorf(inNode(call, call.Lparen), _UnsupportedFeature, "implicit function instantiation requires go1.18 or later")
387 }
388 }
389 targs := check.infer(call, sig.TypeParams().list(), targs, sigParams, args)
390 if targs == nil {
391 return
392 }
393
394
395 rsig = check.instantiateSignature(call.Pos(), sig, targs, xlist)
396 assert(rsig.TypeParams().Len() == 0)
397 check.recordInstance(call.Fun, targs, rsig)
398
399
400
401
402 if adjusted {
403 sigParams = check.subst(call.Pos(), sigParams, makeSubstMap(sig.TypeParams().list(), targs), nil, check.context()).(*Tuple)
404 } else {
405 sigParams = rsig.params
406 }
407 }
408
409
410 if len(args) > 0 {
411 context := check.sprintf("argument to %s", call.Fun)
412 for i, a := range args {
413 check.assignment(a, sigParams.vars[i].typ, context)
414 }
415 }
416
417 return
418 }
419
420 var cgoPrefixes = [...]string{
421 "_Ciconst_",
422 "_Cfconst_",
423 "_Csconst_",
424 "_Ctype_",
425 "_Cvar_",
426 "_Cfpvar_fp_",
427 "_Cfunc_",
428 "_Cmacro_",
429 }
430
431 func (check *Checker) selector(x *operand, e *ast.SelectorExpr, def *Named) {
432
433 var (
434 obj Object
435 index []int
436 indirect bool
437 )
438
439 sel := e.Sel.Name
440
441
442
443
444 if ident, ok := e.X.(*ast.Ident); ok {
445 obj := check.lookup(ident.Name)
446 if pname, _ := obj.(*PkgName); pname != nil {
447 assert(pname.pkg == check.pkg)
448 check.recordUse(ident, pname)
449 pname.used = true
450 pkg := pname.imported
451
452 var exp Object
453 funcMode := value
454 if pkg.cgo {
455
456
457
458 if sel == "malloc" {
459 sel = "_CMalloc"
460 } else {
461 funcMode = cgofunc
462 }
463 for _, prefix := range cgoPrefixes {
464
465
466 _, exp = check.scope.LookupParent(prefix+sel, check.pos)
467 if exp != nil {
468 break
469 }
470 }
471 if exp == nil {
472 check.errorf(e.Sel, _UndeclaredImportedName, "%s not declared by package C", sel)
473 goto Error
474 }
475 check.objDecl(exp, nil)
476 } else {
477 exp = pkg.scope.Lookup(sel)
478 if exp == nil {
479 if !pkg.fake {
480 check.errorf(e.Sel, _UndeclaredImportedName, "%s not declared by package %s", sel, pkg.name)
481 }
482 goto Error
483 }
484 if !exp.Exported() {
485 check.errorf(e.Sel, _UnexportedName, "%s not exported by package %s", sel, pkg.name)
486
487 }
488 }
489 check.recordUse(e.Sel, exp)
490
491
492
493 switch exp := exp.(type) {
494 case *Const:
495 assert(exp.Val() != nil)
496 x.mode = constant_
497 x.typ = exp.typ
498 x.val = exp.val
499 case *TypeName:
500 x.mode = typexpr
501 x.typ = exp.typ
502 case *Var:
503 x.mode = variable
504 x.typ = exp.typ
505 if pkg.cgo && strings.HasPrefix(exp.name, "_Cvar_") {
506 x.typ = x.typ.(*Pointer).base
507 }
508 case *Func:
509 x.mode = funcMode
510 x.typ = exp.typ
511 if pkg.cgo && strings.HasPrefix(exp.name, "_Cmacro_") {
512 x.mode = value
513 x.typ = x.typ.(*Signature).results.vars[0].typ
514 }
515 case *Builtin:
516 x.mode = builtin
517 x.typ = exp.typ
518 x.id = exp.id
519 default:
520 check.dump("%v: unexpected object %v", e.Sel.Pos(), exp)
521 unreachable()
522 }
523 x.expr = e
524 return
525 }
526 }
527
528 check.exprOrType(x, e.X, false)
529 switch x.mode {
530 case typexpr:
531
532 if def != nil && x.typ == def {
533 check.cycleError([]Object{def.obj})
534 goto Error
535 }
536 case builtin:
537
538 check.errorf(e.Sel, _UncalledBuiltin, "cannot select on %s", x)
539 goto Error
540 case invalid:
541 goto Error
542 }
543
544 obj, index, indirect = LookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, sel)
545 if obj == nil {
546
547 if under(x.typ) == Typ[Invalid] {
548 goto Error
549 }
550
551 if index != nil {
552
553 check.errorf(e.Sel, _AmbiguousSelector, "ambiguous selector %s.%s", x.expr, sel)
554 goto Error
555 }
556
557 if indirect {
558 check.errorf(e.Sel, _InvalidMethodExpr, "cannot call pointer method %s on %s", sel, x.typ)
559 goto Error
560 }
561
562 var why string
563 if isInterfacePtr(x.typ) {
564 why = check.interfacePtrError(x.typ)
565 } else {
566 why = check.sprintf("type %s has no field or method %s", x.typ, sel)
567
568
569
570
571 if len(sel) > 0 {
572 var changeCase string
573 if r := rune(sel[0]); unicode.IsUpper(r) {
574 changeCase = string(unicode.ToLower(r)) + sel[1:]
575 } else {
576 changeCase = string(unicode.ToUpper(r)) + sel[1:]
577 }
578 if obj, _, _ = LookupFieldOrMethod(x.typ, x.mode == variable, check.pkg, changeCase); obj != nil {
579 why += ", but does have " + changeCase
580 }
581 }
582 }
583 check.errorf(e.Sel, _MissingFieldOrMethod, "%s.%s undefined (%s)", x.expr, sel, why)
584 goto Error
585 }
586
587
588 if m, _ := obj.(*Func); m != nil {
589 check.objDecl(m, nil)
590 }
591
592 if x.mode == typexpr {
593
594 m, _ := obj.(*Func)
595 if m == nil {
596
597 check.errorf(e.Sel, _MissingFieldOrMethod, "%s.%s undefined (type %s has no method %s)", x.expr, sel, x.typ, sel)
598 goto Error
599 }
600
601 check.recordSelection(e, MethodExpr, x.typ, m, index, indirect)
602
603 sig := m.typ.(*Signature)
604 if sig.recv == nil {
605 check.error(e, _InvalidDeclCycle, "illegal cycle in method declaration")
606 goto Error
607 }
608
609
610
611 var params []*Var
612 if sig.params != nil {
613 params = sig.params.vars
614 }
615
616
617
618
619
620
621 name := ""
622 if len(params) > 0 && params[0].name != "" {
623
624 name = sig.recv.name
625 if name == "" {
626 name = "_"
627 }
628 }
629 params = append([]*Var{NewVar(sig.recv.pos, sig.recv.pkg, name, x.typ)}, params...)
630 x.mode = value
631 x.typ = &Signature{
632 tparams: sig.tparams,
633 params: NewTuple(params...),
634 results: sig.results,
635 variadic: sig.variadic,
636 }
637
638 check.addDeclDep(m)
639
640 } else {
641
642 switch obj := obj.(type) {
643 case *Var:
644 check.recordSelection(e, FieldVal, x.typ, obj, index, indirect)
645 if x.mode == variable || indirect {
646 x.mode = variable
647 } else {
648 x.mode = value
649 }
650 x.typ = obj.typ
651
652 case *Func:
653
654
655 check.recordSelection(e, MethodVal, x.typ, obj, index, indirect)
656
657
658
659
660
661
662
663 disabled := true
664 if !disabled && debug {
665
666
667
668
669
670 typ := x.typ
671 if x.mode == variable {
672
673
674
675
676
677 if _, ok := typ.(*Pointer); !ok && !IsInterface(typ) {
678 typ = &Pointer{base: typ}
679 }
680 }
681
682
683
684
685
686
687
688
689 mset := NewMethodSet(typ)
690 if m := mset.Lookup(check.pkg, sel); m == nil || m.obj != obj {
691 check.dump("%v: (%s).%v -> %s", e.Pos(), typ, obj.name, m)
692 check.dump("%s\n", mset)
693
694
695
696
697
698 panic("method sets and lookup don't agree")
699 }
700 }
701
702 x.mode = value
703
704
705 sig := *obj.typ.(*Signature)
706 sig.recv = nil
707 x.typ = &sig
708
709 check.addDeclDep(obj)
710
711 default:
712 unreachable()
713 }
714 }
715
716
717 x.expr = e
718 return
719
720 Error:
721 x.mode = invalid
722 x.expr = e
723 }
724
725
726
727
728
729 func (check *Checker) use(arg ...ast.Expr) {
730 var x operand
731 for _, e := range arg {
732
733
734 if e != nil {
735 check.rawExpr(&x, e, nil, false)
736 }
737 }
738 }
739
740
741
742
743
744 func (check *Checker) useLHS(arg ...ast.Expr) {
745 var x operand
746 for _, e := range arg {
747
748
749
750 var v *Var
751 var v_used bool
752 if ident, _ := unparen(e).(*ast.Ident); ident != nil {
753
754 if ident.Name == "_" {
755 continue
756 }
757 if _, obj := check.scope.LookupParent(ident.Name, token.NoPos); obj != nil {
758
759
760
761 if w, _ := obj.(*Var); w != nil && w.pkg == check.pkg {
762 v = w
763 v_used = v.used
764 }
765 }
766 }
767 check.rawExpr(&x, e, nil, false)
768 if v != nil {
769 v.used = v_used
770 }
771 }
772 }
773
View as plain text