...

Source file src/go/types/conversions.go

Documentation: go/types

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

View as plain text