Source file src/cmd/compile/internal/types2/conversions.go

     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.
     4  
     5  // This file implements typechecking of conversions.
     6  
     7  package types2
     8  
     9  import (
    10  	"go/constant"
    11  	. "internal/types/errors"
    12  	"unicode"
    13  )
    14  
    15  // conversion type-checks the conversion T(x).
    16  // The result is in x.
    17  func (check *Checker) conversion(x *operand, T Type) {
    18  	constArg := x.mode == constant_
    19  
    20  	constConvertibleTo := func(T Type, val *constant.Value) bool {
    21  		switch t, _ := under(T).(*Basic); {
    22  		case t == nil:
    23  			// nothing to do
    24  		case representableConst(x.val, check, t, val):
    25  			return true
    26  		case isInteger(x.typ) && isString(t):
    27  			codepoint := unicode.ReplacementChar
    28  			if i, ok := constant.Uint64Val(x.val); ok && i <= unicode.MaxRune {
    29  				codepoint = rune(i)
    30  			}
    31  			if val != nil {
    32  				*val = constant.MakeString(string(codepoint))
    33  			}
    34  			return true
    35  		}
    36  		return false
    37  	}
    38  
    39  	var ok bool
    40  	var cause string
    41  	switch {
    42  	case constArg && isConstType(T):
    43  		// constant conversion
    44  		ok = constConvertibleTo(T, &x.val)
    45  		// A conversion from an integer constant to an integer type
    46  		// can only fail if there's overflow. Give a concise error.
    47  		// (go.dev/issue/63563)
    48  		if !ok && isInteger(x.typ) && isInteger(T) {
    49  			check.errorf(x, InvalidConversion, "constant %s overflows %s", x.val, T)
    50  			x.mode = invalid
    51  			return
    52  		}
    53  	case constArg && isTypeParam(T):
    54  		// x is convertible to T if it is convertible
    55  		// to each specific type in the type set of T.
    56  		// If T's type set is empty, or if it doesn't
    57  		// have specific types, constant x cannot be
    58  		// converted.
    59  		ok = T.(*TypeParam).underIs(func(u Type) bool {
    60  			// u is nil if there are no specific type terms
    61  			if u == nil {
    62  				cause = check.sprintf("%s does not contain specific types", T)
    63  				return false
    64  			}
    65  			if isString(x.typ) && isBytesOrRunes(u) {
    66  				return true
    67  			}
    68  			if !constConvertibleTo(u, nil) {
    69  				if isInteger(x.typ) && isInteger(u) {
    70  					// see comment above on constant conversion
    71  					cause = check.sprintf("constant %s overflows %s (in %s)", x.val, u, T)
    72  				} else {
    73  					cause = check.sprintf("cannot convert %s to type %s (in %s)", x, u, T)
    74  				}
    75  				return false
    76  			}
    77  			return true
    78  		})
    79  		x.mode = value // type parameters are not constants
    80  	case x.convertibleTo(check, T, &cause):
    81  		// non-constant conversion
    82  		ok = true
    83  		x.mode = value
    84  	}
    85  
    86  	if !ok {
    87  		if cause != "" {
    88  			check.errorf(x, InvalidConversion, "cannot convert %s to type %s: %s", x, T, cause)
    89  		} else {
    90  			check.errorf(x, InvalidConversion, "cannot convert %s to type %s", x, T)
    91  		}
    92  		x.mode = invalid
    93  		return
    94  	}
    95  
    96  	// The conversion argument types are final. For untyped values the
    97  	// conversion provides the type, per the spec: "A constant may be
    98  	// given a type explicitly by a constant declaration or conversion,...".
    99  	if isUntyped(x.typ) {
   100  		final := T
   101  		// - For conversions to interfaces, except for untyped nil arguments,
   102  		//   use the argument's default type.
   103  		// - For conversions of untyped constants to non-constant types, also
   104  		//   use the default type (e.g., []byte("foo") should report string
   105  		//   not []byte as type for the constant "foo").
   106  		// - For constant integer to string conversions, keep the argument type.
   107  		//   (See also the TODO below.)
   108  		if x.typ == Typ[UntypedNil] {
   109  			// ok
   110  		} else if isNonTypeParamInterface(T) || constArg && !isConstType(T) {
   111  			final = Default(x.typ)
   112  		} else if x.mode == constant_ && isInteger(x.typ) && allString(T) {
   113  			final = x.typ
   114  		}
   115  		check.updateExprType(x.expr, final, true)
   116  	}
   117  
   118  	x.typ = T
   119  }
   120  
   121  // TODO(gri) convertibleTo checks if T(x) is valid. It assumes that the type
   122  // of x is fully known, but that's not the case for say string(1<<s + 1.0):
   123  // Here, the type of 1<<s + 1.0 will be UntypedFloat which will lead to the
   124  // (correct!) refusal of the conversion. But the reported error is essentially
   125  // "cannot convert untyped float value to string", yet the correct error (per
   126  // the spec) is that we cannot shift a floating-point value: 1 in 1<<s should
   127  // be converted to UntypedFloat because of the addition of 1.0. Fixing this
   128  // is tricky because we'd have to run updateExprType on the argument first.
   129  // (go.dev/issue/21982.)
   130  
   131  // convertibleTo reports whether T(x) is valid. In the failure case, *cause
   132  // may be set to the cause for the failure.
   133  // The check parameter may be nil if convertibleTo is invoked through an
   134  // exported API call, i.e., when all methods have been type-checked.
   135  func (x *operand) convertibleTo(check *Checker, T Type, cause *string) bool {
   136  	// "x is assignable to T"
   137  	if ok, _ := x.assignableTo(check, T, cause); ok {
   138  		return true
   139  	}
   140  
   141  	// "V and T have identical underlying types if tags are ignored
   142  	// and V and T are not type parameters"
   143  	V := x.typ
   144  	Vu := under(V)
   145  	Tu := under(T)
   146  	Vp, _ := V.(*TypeParam)
   147  	Tp, _ := T.(*TypeParam)
   148  	if IdenticalIgnoreTags(Vu, Tu) && Vp == nil && Tp == nil {
   149  		return true
   150  	}
   151  
   152  	// "V and T are unnamed pointer types and their pointer base types
   153  	// have identical underlying types if tags are ignored
   154  	// and their pointer base types are not type parameters"
   155  	if V, ok := V.(*Pointer); ok {
   156  		if T, ok := T.(*Pointer); ok {
   157  			if IdenticalIgnoreTags(under(V.base), under(T.base)) && !isTypeParam(V.base) && !isTypeParam(T.base) {
   158  				return true
   159  			}
   160  		}
   161  	}
   162  
   163  	// "V and T are both integer or floating point types"
   164  	if isIntegerOrFloat(Vu) && isIntegerOrFloat(Tu) {
   165  		return true
   166  	}
   167  
   168  	// "V and T are both complex types"
   169  	if isComplex(Vu) && isComplex(Tu) {
   170  		return true
   171  	}
   172  
   173  	// "V is an integer or a slice of bytes or runes and T is a string type"
   174  	if (isInteger(Vu) || isBytesOrRunes(Vu)) && isString(Tu) {
   175  		return true
   176  	}
   177  
   178  	// "V is a string and T is a slice of bytes or runes"
   179  	if isString(Vu) && isBytesOrRunes(Tu) {
   180  		return true
   181  	}
   182  
   183  	// package unsafe:
   184  	// "any pointer or value of underlying type uintptr can be converted into a unsafe.Pointer"
   185  	if (isPointer(Vu) || isUintptr(Vu)) && isUnsafePointer(Tu) {
   186  		return true
   187  	}
   188  	// "and vice versa"
   189  	if isUnsafePointer(Vu) && (isPointer(Tu) || isUintptr(Tu)) {
   190  		return true
   191  	}
   192  
   193  	// "V is a slice, T is an array or pointer-to-array type,
   194  	// and the slice and array types have identical element types."
   195  	if s, _ := Vu.(*Slice); s != nil {
   196  		switch a := Tu.(type) {
   197  		case *Array:
   198  			if Identical(s.Elem(), a.Elem()) {
   199  				if check == nil || check.allowVersion(check.pkg, x, go1_20) {
   200  					return true
   201  				}
   202  				// check != nil
   203  				if cause != nil {
   204  					// TODO(gri) consider restructuring versionErrorf so we can use it here and below
   205  					*cause = "conversion of slices to arrays requires go1.20 or later"
   206  				}
   207  				return false
   208  			}
   209  		case *Pointer:
   210  			if a, _ := under(a.Elem()).(*Array); a != nil {
   211  				if Identical(s.Elem(), a.Elem()) {
   212  					if check == nil || check.allowVersion(check.pkg, x, go1_17) {
   213  						return true
   214  					}
   215  					// check != nil
   216  					if cause != nil {
   217  						*cause = "conversion of slices to array pointers requires go1.17 or later"
   218  					}
   219  					return false
   220  				}
   221  			}
   222  		}
   223  	}
   224  
   225  	// optimization: if we don't have type parameters, we're done
   226  	if Vp == nil && Tp == nil {
   227  		return false
   228  	}
   229  
   230  	errorf := func(format string, args ...interface{}) {
   231  		if check != nil && cause != nil {
   232  			msg := check.sprintf(format, args...)
   233  			if *cause != "" {
   234  				msg += "\n\t" + *cause
   235  			}
   236  			*cause = msg
   237  		}
   238  	}
   239  
   240  	// generic cases with specific type terms
   241  	// (generic operands cannot be constants, so we can ignore x.val)
   242  	switch {
   243  	case Vp != nil && Tp != nil:
   244  		x := *x // don't clobber outer x
   245  		return Vp.is(func(V *term) bool {
   246  			if V == nil {
   247  				return false // no specific types
   248  			}
   249  			x.typ = V.typ
   250  			return Tp.is(func(T *term) bool {
   251  				if T == nil {
   252  					return false // no specific types
   253  				}
   254  				if !x.convertibleTo(check, T.typ, cause) {
   255  					errorf("cannot convert %s (in %s) to type %s (in %s)", V.typ, Vp, T.typ, Tp)
   256  					return false
   257  				}
   258  				return true
   259  			})
   260  		})
   261  	case Vp != nil:
   262  		x := *x // don't clobber outer x
   263  		return Vp.is(func(V *term) bool {
   264  			if V == nil {
   265  				return false // no specific types
   266  			}
   267  			x.typ = V.typ
   268  			if !x.convertibleTo(check, T, cause) {
   269  				errorf("cannot convert %s (in %s) to type %s", V.typ, Vp, T)
   270  				return false
   271  			}
   272  			return true
   273  		})
   274  	case Tp != nil:
   275  		return Tp.is(func(T *term) bool {
   276  			if T == nil {
   277  				return false // no specific types
   278  			}
   279  			if !x.convertibleTo(check, T.typ, cause) {
   280  				errorf("cannot convert %s to type %s (in %s)", x.typ, T.typ, Tp)
   281  				return false
   282  			}
   283  			return true
   284  		})
   285  	}
   286  
   287  	return false
   288  }
   289  
   290  func isUintptr(typ Type) bool {
   291  	t, _ := under(typ).(*Basic)
   292  	return t != nil && t.kind == Uintptr
   293  }
   294  
   295  func isUnsafePointer(typ Type) bool {
   296  	t, _ := under(typ).(*Basic)
   297  	return t != nil && t.kind == UnsafePointer
   298  }
   299  
   300  func isPointer(typ Type) bool {
   301  	_, ok := under(typ).(*Pointer)
   302  	return ok
   303  }
   304  
   305  func isBytesOrRunes(typ Type) bool {
   306  	if s, _ := under(typ).(*Slice); s != nil {
   307  		t, _ := under(s.elem).(*Basic)
   308  		return t != nil && (t.kind == Byte || t.kind == Rune)
   309  	}
   310  	return false
   311  }
   312  

View as plain text