1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // This file implements typechecking of builtin function calls.
13 . "internal/types/errors"
16 // builtin type-checks a call to the built-in specified by id and
17 // reports whether the call is valid, with *x holding the result;
18 // but x.expr is not set. If the call is invalid, the result is
19 // false, and *x is undefined.
20 func (check *Checker) builtin(x *operand, call *ast.CallExpr, id builtinId) (_ bool) {
23 // append is the only built-in that permits the use of ... for the last argument
24 bin := predeclaredFuncs[id]
25 if call.Ellipsis.IsValid() && id != _Append {
26 check.errorf(atPos(call.Ellipsis),
28 invalidOp+"invalid use of ... with built-in %s", bin.name)
33 // For len(x) and cap(x) we need to know if x contains any function calls or
34 // receive operations. Save/restore current setting and set hasCallOrRecv to
35 // false for the evaluation of x so that we can check it afterwards.
36 // Note: We must do this _before_ calling exprList because exprList evaluates
38 if id == _Len || id == _Cap {
40 check.hasCallOrRecv = b
41 }(check.hasCallOrRecv)
42 check.hasCallOrRecv = false
45 // Evaluate arguments for built-ins that use ordinary (value) arguments.
46 // For built-ins with special argument handling (make, new, etc.),
47 // evaluation is done by the respective built-in code.
48 var args []*operand // not valid for _Make, _New, _Offsetof, _Trace
52 // check all arguments
53 args = check.exprList(argList)
55 for _, a := range args {
56 if a.mode == invalid {
60 // first argument is always in x
64 case _Make, _New, _Offsetof, _Trace:
65 // arguments require special handling
69 // check argument count
72 if nargs < bin.nargs {
74 } else if !bin.variadic && nargs > bin.nargs {
78 check.errorf(inNode(call, call.Rparen), WrongArgCount, invalidOp+"%s arguments for %s (expected %d, found %d)", msg, call, bin.nargs, nargs)
85 // append(s S, x ...T) S, where T is the element type of S
86 // spec: "The variadic function append appends zero or more values x to s of type
87 // S, which must be a slice type, and returns the resulting slice, also of type S.
88 // The values x are passed to a parameter of type ...T where T is the element type
89 // of S and the respective parameter passing rules apply."
92 if s, _ := coreType(S).(*Slice); s != nil {
98 cause = "have untyped nil"
100 if u := coreType(S); u != nil {
101 cause = check.sprintf("%s has core type %s", x, u)
103 cause = check.sprintf("%s has no core type", x)
106 cause = check.sprintf("have %s", x)
108 // don't use invalidArg prefix here as it would repeat "argument" in the error message
109 check.errorf(x, InvalidAppend, "first argument to append must be a slice; %s", cause)
113 // spec: "As a special case, append also accepts a first argument assignable
114 // to type []byte with a second argument of string type followed by ... .
115 // This form appends the bytes of the string.
116 if nargs == 2 && call.Ellipsis.IsValid() {
117 if ok, _ := x.assignableTo(check, NewSlice(universeByte), nil); ok {
119 if t := coreString(y.typ); t != nil && isString(t) {
120 if check.recordTypes() {
121 sig := makeSig(S, S, y.typ)
123 check.recordBuiltinType(call.Fun, sig)
132 // check general case by creating custom signature
133 sig := makeSig(S, S, NewSlice(T)) // []T required for variadic signature
135 check.arguments(call, sig, nil, nil, args, nil, nil) // discard result (we know the result type)
136 // ok to continue even if check.arguments reported errors
140 if check.recordTypes() {
141 check.recordBuiltinType(call.Fun, sig)
148 var val constant.Value
149 switch t := arrayPtrDeref(under(x.typ)).(type) {
151 if isString(t) && id == _Len {
152 if x.mode == constant_ {
154 val = constant.MakeInt64(int64(len(constant.StringVal(x.val))))
162 // spec: "The expressions len(s) and cap(s) are constants
163 // if the type of s is an array or pointer to an array and
164 // the expression s does not contain channel receives or
165 // function calls; in this case s is not evaluated."
166 if !check.hasCallOrRecv {
169 val = constant.MakeInt64(t.len)
171 val = constant.MakeUnknown()
184 if !isTypeParam(x.typ) {
187 if t.typeSet().underIs(func(t Type) bool {
188 switch t := arrayPtrDeref(t).(type) {
190 if isString(t) && id == _Len {
193 case *Array, *Slice, *Chan:
207 // avoid error if underlying type is invalid
208 if under(x.typ) != Typ[Invalid] {
213 check.errorf(x, code, invalidArg+"%s for %s", x, bin.name)
218 // record the signature before changing x.typ
219 if check.recordTypes() && mode != constant_ {
220 check.recordBuiltinType(call.Fun, makeSig(Typ[Int], x.typ))
229 check.verifyVersionf(call.Fun, go1_21, "clear")
231 if !underIs(x.typ, func(u Type) bool {
236 check.errorf(x, InvalidClear, invalidArg+"cannot clear %s: argument must be (or constrained by) map or slice", x)
243 if check.recordTypes() {
244 check.recordBuiltinType(call.Fun, makeSig(nil, x.typ))
249 if !underIs(x.typ, func(u Type) bool {
252 check.errorf(x, InvalidClose, invalidOp+"cannot close non-channel %s", x)
255 if uch.dir == RecvOnly {
256 check.errorf(x, InvalidClose, invalidOp+"cannot close receive-only channel %s", x)
264 if check.recordTypes() {
265 check.recordBuiltinType(call.Fun, makeSig(nil, x.typ))
269 // complex(x, y floatT) complexT
272 // convert or check untyped arguments
274 if isUntyped(x.typ) {
277 if isUntyped(y.typ) {
282 // x and y are typed => nothing to do
284 // only x is untyped => convert to type of y
285 check.convertUntyped(x, y.typ)
287 // only y is untyped => convert to type of x
288 check.convertUntyped(y, x.typ)
290 // x and y are untyped =>
291 // 1) if both are constants, convert them to untyped
292 // floating-point numbers if possible,
293 // 2) if one of them is not constant (possible because
294 // it contains a shift that is yet untyped), convert
295 // both of them to float64 since they must have the
296 // same type to succeed (this will result in an error
297 // because shifts of floats are not permitted)
298 if x.mode == constant_ && y.mode == constant_ {
299 toFloat := func(x *operand) {
300 if isNumeric(x.typ) && constant.Sign(constant.Imag(x.val)) == 0 {
301 x.typ = Typ[UntypedFloat]
307 check.convertUntyped(x, Typ[Float64])
308 check.convertUntyped(y, Typ[Float64])
309 // x and y should be invalid now, but be conservative
313 if x.mode == invalid || y.mode == invalid {
317 // both argument types must be identical
318 if !Identical(x.typ, y.typ) {
319 check.errorf(x, InvalidComplex, invalidOp+"%v (mismatched types %s and %s)", call, x.typ, y.typ)
323 // the argument types must be of floating-point type
324 // (applyTypeFunc never calls f with a type parameter)
325 f := func(typ Type) Type {
326 assert(!isTypeParam(typ))
327 if t, _ := under(typ).(*Basic); t != nil {
330 return Typ[Complex64]
332 return Typ[Complex128]
334 return Typ[UntypedComplex]
339 resTyp := check.applyTypeFunc(f, x, id)
341 check.errorf(x, InvalidComplex, invalidArg+"arguments have type %s, expected floating-point", x.typ)
345 // if both arguments are constants, the result is a constant
346 if x.mode == constant_ && y.mode == constant_ {
347 x.val = constant.BinaryOp(constant.ToFloat(x.val), token.ADD, constant.MakeImag(constant.ToFloat(y.val)))
352 if check.recordTypes() && x.mode != constant_ {
353 check.recordBuiltinType(call.Fun, makeSig(resTyp, x.typ, x.typ))
359 // copy(x, y []T) int
360 dst, _ := coreType(x.typ).(*Slice)
363 src0 := coreString(y.typ)
364 if src0 != nil && isString(src0) {
365 src0 = NewSlice(universeByte)
367 src, _ := src0.(*Slice)
369 if dst == nil || src == nil {
370 check.errorf(x, InvalidCopy, invalidArg+"copy expects slice arguments; found %s and %s", x, y)
374 if !Identical(dst.elem, src.elem) {
375 check.errorf(x, InvalidCopy, invalidArg+"arguments to copy %s and %s have different element types %s and %s", x, y, dst.elem, src.elem)
379 if check.recordTypes() {
380 check.recordBuiltinType(call.Fun, makeSig(Typ[Int], x.typ, y.typ))
387 // map_ must be a map type or a type parameter describing map types.
388 // The key cannot be a type parameter for now.
391 if !underIs(map_, func(u Type) bool {
394 check.errorf(x, InvalidDelete, invalidArg+"%s is not a map", x)
397 if key != nil && !Identical(map_.key, key) {
398 check.errorf(x, InvalidDelete, invalidArg+"maps of %s must have identical key types", x)
408 check.assignment(x, key, "argument to delete")
409 if x.mode == invalid {
414 if check.recordTypes() {
415 check.recordBuiltinType(call.Fun, makeSig(nil, map_, key))
419 // imag(complexT) floatT
420 // real(complexT) floatT
422 // convert or check untyped argument
423 if isUntyped(x.typ) {
424 if x.mode == constant_ {
425 // an untyped constant number can always be considered
426 // as a complex constant
427 if isNumeric(x.typ) {
428 x.typ = Typ[UntypedComplex]
431 // an untyped non-constant argument may appear if
432 // it contains a (yet untyped non-constant) shift
433 // expression: convert it to complex128 which will
434 // result in an error (shift of complex value)
435 check.convertUntyped(x, Typ[Complex128])
436 // x should be invalid now, but be conservative and check
437 if x.mode == invalid {
443 // the argument must be of complex type
444 // (applyTypeFunc never calls f with a type parameter)
445 f := func(typ Type) Type {
446 assert(!isTypeParam(typ))
447 if t, _ := under(typ).(*Basic); t != nil {
454 return Typ[UntypedFloat]
459 resTyp := check.applyTypeFunc(f, x, id)
465 check.errorf(x, code, invalidArg+"argument has type %s, expected complex type", x.typ)
469 // if the argument is a constant, the result is a constant
470 if x.mode == constant_ {
472 x.val = constant.Real(x.val)
474 x.val = constant.Imag(x.val)
480 if check.recordTypes() && x.mode != constant_ {
481 check.recordBuiltinType(call.Fun, makeSig(resTyp, x.typ))
489 // (no argument evaluated yet)
491 T := check.varType(arg0)
492 if T == Typ[Invalid] {
496 var min int // minimum number of arguments
497 switch coreType(T).(type) {
503 check.errorf(arg0, InvalidMake, invalidArg+"cannot make %s: no core type", arg0)
506 check.errorf(arg0, InvalidMake, invalidArg+"cannot make %s; type must be slice, map, or channel", arg0)
509 if nargs < min || min+1 < nargs {
510 check.errorf(call, WrongArgCount, invalidOp+"%v expects %d or %d arguments; found %d", call, min, min+1, nargs)
515 var sizes []int64 // constant integer arguments, if any
516 for _, arg := range argList[1:] {
517 typ, size := check.index(arg, -1) // ok to continue with typ == Typ[Invalid]
518 types = append(types, typ)
520 sizes = append(sizes, size)
523 if len(sizes) == 2 && sizes[0] > sizes[1] {
524 check.error(argList[1], SwappedMakeArgs, invalidArg+"length and capacity swapped")
529 if check.recordTypes() {
530 check.recordBuiltinType(call.Fun, makeSig(x.typ, types...))
536 check.verifyVersionf(call.Fun, go1_21, bin.name)
543 for i, a := range args {
544 if a.mode == invalid {
548 if !allOrdered(a.typ) {
549 check.errorf(a, InvalidMinMaxOperand, invalidArg+"%s cannot be ordered", a)
553 // The first argument is already in x and there's nothing left to do.
555 check.matchTypes(x, a)
556 if x.mode == invalid {
560 if !Identical(x.typ, a.typ) {
561 check.errorf(a, MismatchedTypes, invalidArg+"mismatched types %s (previous argument) and %s (type of %s)", x.typ, a.typ, a.expr)
565 if x.mode == constant_ && a.mode == constant_ {
566 if constant.Compare(a.val, op, x.val) {
575 // If nargs == 1, make sure x.mode is either a value or a constant.
576 if x.mode != constant_ {
580 // Use the final type computed above for all arguments.
581 for _, a := range args {
582 check.updateExprType(a.expr, x.typ, true)
585 if check.recordTypes() && x.mode != constant_ {
586 types := make([]Type, nargs)
587 for i := range types {
590 check.recordBuiltinType(call.Fun, makeSig(x.typ, types...))
595 // (no argument evaluated yet)
596 T := check.varType(argList[0])
597 if T == Typ[Invalid] {
602 x.typ = &Pointer{base: T}
603 if check.recordTypes() {
604 check.recordBuiltinType(call.Fun, makeSig(x.typ, T))
609 // record panic call if inside a function with result parameters
610 // (for use in Checker.isTerminating)
611 if check.sig != nil && check.sig.results.Len() > 0 {
612 // function has result parameters
616 p = make(map[*ast.CallExpr]bool)
622 check.assignment(x, &emptyInterface, "argument to panic")
623 if x.mode == invalid {
628 if check.recordTypes() {
629 check.recordBuiltinType(call.Fun, makeSig(nil, &emptyInterface))
632 case _Print, _Println:
634 // println(x, y, ...)
637 params = make([]Type, nargs)
638 for i, a := range args {
639 check.assignment(a, nil, "argument to "+predeclaredFuncs[id].name)
640 if a.mode == invalid {
648 if check.recordTypes() {
649 check.recordBuiltinType(call.Fun, makeSig(nil, params...))
653 // recover() interface{}
655 x.typ = &emptyInterface
656 if check.recordTypes() {
657 check.recordBuiltinType(call.Fun, makeSig(x.typ))
661 // unsafe.Add(ptr unsafe.Pointer, len IntegerType) unsafe.Pointer
662 check.verifyVersionf(call.Fun, go1_17, "unsafe.Add")
664 check.assignment(x, Typ[UnsafePointer], "argument to unsafe.Add")
665 if x.mode == invalid {
670 if !check.isValidIndex(y, InvalidUnsafeAdd, "length", true) {
675 x.typ = Typ[UnsafePointer]
676 if check.recordTypes() {
677 check.recordBuiltinType(call.Fun, makeSig(x.typ, x.typ, y.typ))
681 // unsafe.Alignof(x T) uintptr
682 check.assignment(x, nil, "argument to unsafe.Alignof")
683 if x.mode == invalid {
687 if hasVarSize(x.typ, nil) {
689 if check.recordTypes() {
690 check.recordBuiltinType(call.Fun, makeSig(Typ[Uintptr], x.typ))
694 x.val = constant.MakeInt64(check.conf.alignof(x.typ))
695 // result is constant - no need to record signature
700 // unsafe.Offsetof(x T) uintptr, where x must be a selector
701 // (no argument evaluated yet)
703 selx, _ := unparen(arg0).(*ast.SelectorExpr)
705 check.errorf(arg0, BadOffsetofSyntax, invalidArg+"%s is not a selector expression", arg0)
710 check.expr(nil, x, selx.X)
711 if x.mode == invalid {
715 base := derefStructPtr(x.typ)
717 obj, index, indirect := LookupFieldOrMethod(base, false, check.pkg, sel)
720 check.errorf(x, MissingFieldOrMethod, invalidArg+"%s has no single field %s", base, sel)
723 // TODO(gri) Using derefStructPtr may result in methods being found
724 // that don't actually exist. An error either way, but the error
725 // message is confusing. See: https://play.golang.org/p/al75v23kUy ,
726 // but go/types reports: "invalid argument: x.m is a method value".
727 check.errorf(arg0, InvalidOffsetof, invalidArg+"%s is a method value", arg0)
731 check.errorf(x, InvalidOffsetof, invalidArg+"field %s is embedded via a pointer in %s", sel, base)
735 // TODO(gri) Should we pass x.typ instead of base (and have indirect report if derefStructPtr indirected)?
736 check.recordSelection(selx, FieldVal, base, obj, index, false)
738 // record the selector expression (was bug - go.dev/issue/47895)
741 if x.mode == variable || indirect {
744 check.record(&operand{mode, selx, obj.Type(), nil, 0})
747 // The field offset is considered a variable even if the field is declared before
748 // the part of the struct which is variable-sized. This makes both the rules
749 // simpler and also permits (or at least doesn't prevent) a compiler from re-
750 // arranging struct fields if it wanted to.
751 if hasVarSize(base, nil) {
753 if check.recordTypes() {
754 check.recordBuiltinType(call.Fun, makeSig(Typ[Uintptr], obj.Type()))
757 offs := check.conf.offsetof(base, index)
759 check.errorf(x, TypeTooLarge, "%s is too large", x)
763 x.val = constant.MakeInt64(offs)
764 // result is constant - no need to record signature
769 // unsafe.Sizeof(x T) uintptr
770 check.assignment(x, nil, "argument to unsafe.Sizeof")
771 if x.mode == invalid {
775 if hasVarSize(x.typ, nil) {
777 if check.recordTypes() {
778 check.recordBuiltinType(call.Fun, makeSig(Typ[Uintptr], x.typ))
781 size := check.conf.sizeof(x.typ)
783 check.errorf(x, TypeTooLarge, "%s is too large", x)
787 x.val = constant.MakeInt64(size)
788 // result is constant - no need to record signature
793 // unsafe.Slice(ptr *T, len IntegerType) []T
794 check.verifyVersionf(call.Fun, go1_17, "unsafe.Slice")
796 ptr, _ := under(x.typ).(*Pointer) // TODO(gri) should this be coreType rather than under?
798 check.errorf(x, InvalidUnsafeSlice, invalidArg+"%s is not a pointer", x)
803 if !check.isValidIndex(y, InvalidUnsafeSlice, "length", false) {
808 x.typ = NewSlice(ptr.base)
809 if check.recordTypes() {
810 check.recordBuiltinType(call.Fun, makeSig(x.typ, ptr, y.typ))
814 // unsafe.SliceData(slice []T) *T
815 check.verifyVersionf(call.Fun, go1_20, "unsafe.SliceData")
817 slice, _ := under(x.typ).(*Slice) // TODO(gri) should this be coreType rather than under?
819 check.errorf(x, InvalidUnsafeSliceData, invalidArg+"%s is not a slice", x)
824 x.typ = NewPointer(slice.elem)
825 if check.recordTypes() {
826 check.recordBuiltinType(call.Fun, makeSig(x.typ, slice))
830 // unsafe.String(ptr *byte, len IntegerType) string
831 check.verifyVersionf(call.Fun, go1_20, "unsafe.String")
833 check.assignment(x, NewPointer(universeByte), "argument to unsafe.String")
834 if x.mode == invalid {
839 if !check.isValidIndex(y, InvalidUnsafeString, "length", false) {
845 if check.recordTypes() {
846 check.recordBuiltinType(call.Fun, makeSig(x.typ, NewPointer(universeByte), y.typ))
850 // unsafe.StringData(str string) *byte
851 check.verifyVersionf(call.Fun, go1_20, "unsafe.StringData")
853 check.assignment(x, Typ[String], "argument to unsafe.StringData")
854 if x.mode == invalid {
859 x.typ = NewPointer(universeByte)
860 if check.recordTypes() {
861 check.recordBuiltinType(call.Fun, makeSig(x.typ, Typ[String]))
865 // assert(pred) causes a typechecker error if pred is false.
866 // The result of assert is the value of pred if there is no error.
867 // Note: assert is only available in self-test mode.
868 if x.mode != constant_ || !isBoolean(x.typ) {
869 check.errorf(x, Test, invalidArg+"%s is not a boolean constant", x)
872 if x.val.Kind() != constant.Bool {
873 check.errorf(x, Test, "internal error: value of %s should be a boolean constant", x)
876 if !constant.BoolVal(x.val) {
877 check.errorf(call, Test, "%v failed", call)
878 // compile-time assertion failure - safe to continue
880 // result is constant - no need to record signature
883 // trace(x, y, z, ...) dumps the positions, expressions, and
884 // values of its arguments. The result of trace is the value
885 // of the first argument.
886 // Note: trace is only available in self-test mode.
887 // (no argument evaluated yet)
889 check.dump("%v: trace() without arguments", call.Pos())
895 for _, arg := range argList {
896 check.rawExpr(nil, x1, arg, nil, false) // permit trace for types, e.g.: new(trace(T))
897 check.dump("%v: %s", x1.Pos(), x1)
898 x1 = &t // use incoming x only for first argument
900 if x.mode == invalid {
903 // trace is only available in test mode - no need to record signature
909 assert(x.mode != invalid)
913 // hasVarSize reports if the size of type t is variable due to type parameters
914 // or if the type is infinitely-sized due to a cycle for which the type has not
916 func hasVarSize(t Type, seen map[*Named]bool) (varSized bool) {
917 // Cycles are only possible through *Named types.
918 // The seen map is used to detect cycles and track
919 // the results of previously seen types.
920 if named, _ := t.(*Named); named != nil {
921 if v, ok := seen[named]; ok {
925 seen = make(map[*Named]bool)
927 seen[named] = true // possibly cyclic until proven otherwise
929 seen[named] = varSized // record final determination for named
933 switch u := under(t).(type) {
935 return hasVarSize(u.elem, seen)
937 for _, f := range u.fields {
938 if hasVarSize(f.typ, seen) {
943 return isTypeParam(t)
950 // applyTypeFunc applies f to x. If x is a type parameter,
951 // the result is a type parameter constrained by an new
952 // interface bound. The type bounds for that interface
953 // are computed by applying f to each of the type bounds
954 // of x. If any of these applications of f return nil,
955 // applyTypeFunc returns nil.
956 // If x is not a type parameter, the result is f(x).
957 func (check *Checker) applyTypeFunc(f func(Type) Type, x *operand, id builtinId) Type {
958 if tp, _ := x.typ.(*TypeParam); tp != nil {
959 // Test if t satisfies the requirements for the argument
960 // type and collect possible result types at the same time.
962 if !tp.is(func(t *term) bool {
966 if r := f(t.typ); r != nil {
967 terms = append(terms, NewTerm(t.tilde, r))
975 // We can type-check this fine but we're introducing a synthetic
976 // type parameter for the result. It's not clear what the API
977 // implications are here. Report an error for 1.18 (see go.dev/issue/50912),
978 // but continue type-checking.
986 code = InvalidComplex
990 check.softErrorf(x, code, "%s not supported as argument to %s for go1.18 (see go.dev/issue/50937)", x, predeclaredFuncs[id].name)
992 // Construct a suitable new type parameter for the result type.
993 // The type parameter is placed in the current package so export/import
994 // works as expected.
995 tpar := NewTypeName(nopos, check.pkg, tp.obj.name, nil)
996 ptyp := check.newTypeParam(tpar, NewInterfaceType(nil, []Type{NewUnion(terms)})) // assigns type to tpar as a side-effect
997 ptyp.index = tp.index
1005 // makeSig makes a signature for the given argument and result types.
1006 // Default types are used for untyped arguments, and res may be nil.
1007 func makeSig(res Type, args ...Type) *Signature {
1008 list := make([]*Var, len(args))
1009 for i, param := range args {
1010 list[i] = NewVar(nopos, nil, "", Default(param))
1012 params := NewTuple(list...)
1015 assert(!isUntyped(res))
1016 result = NewTuple(NewVar(nopos, nil, "", res))
1018 return &Signature{params: params, results: result}
1021 // arrayPtrDeref returns A if typ is of the form *A and A is an array;
1022 // otherwise it returns typ.
1023 func arrayPtrDeref(typ Type) Type {
1024 if p, ok := typ.(*Pointer); ok {
1025 if a, _ := under(p.base).(*Array); a != nil {
1032 func unparen(e ast.Expr) ast.Expr { return ast.Unparen(e) }