Source file src/go/types/operand.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 defines operands and associated operations.
     6  
     7  package types
     8  
     9  import (
    10  	"bytes"
    11  	"go/ast"
    12  	"go/constant"
    13  	"go/token"
    14  )
    15  
    16  // An operandMode specifies the (addressing) mode of an operand.
    17  type operandMode byte
    18  
    19  const (
    20  	invalid   operandMode = iota // operand is invalid
    21  	novalue                      // operand represents no value (result of a function call w/o result)
    22  	builtin                      // operand is a built-in function
    23  	typexpr                      // operand is a type
    24  	constant_                    // operand is a constant; the operand's typ is a Basic type
    25  	variable                     // operand is an addressable variable
    26  	mapindex                     // operand is a map index expression (acts like a variable on lhs, commaok on rhs of an assignment)
    27  	value                        // operand is a computed value
    28  	commaok                      // like value, but operand may be used in a comma,ok expression
    29  	commaerr                     // like commaok, but second value is error, not boolean
    30  	cgofunc                      // operand is a cgo function
    31  )
    32  
    33  var operandModeString = [...]string{
    34  	invalid:   "invalid operand",
    35  	novalue:   "no value",
    36  	builtin:   "built-in",
    37  	typexpr:   "type",
    38  	constant_: "constant",
    39  	variable:  "variable",
    40  	mapindex:  "map index expression",
    41  	value:     "value",
    42  	commaok:   "comma, ok expression",
    43  	commaerr:  "comma, error expression",
    44  	cgofunc:   "cgo function",
    45  }
    46  
    47  // An operand represents an intermediate value during type checking.
    48  // Operands have an (addressing) mode, the expression evaluating to
    49  // the operand, the operand's type, a value for constants, and an id
    50  // for built-in functions.
    51  // The zero value of operand is a ready to use invalid operand.
    52  //
    53  type operand struct {
    54  	mode operandMode
    55  	expr ast.Expr
    56  	typ  Type
    57  	val  constant.Value
    58  	id   builtinId
    59  }
    60  
    61  // Pos returns the position of the expression corresponding to x.
    62  // If x is invalid the position is token.NoPos.
    63  //
    64  func (x *operand) Pos() token.Pos {
    65  	// x.expr may not be set if x is invalid
    66  	if x.expr == nil {
    67  		return token.NoPos
    68  	}
    69  	return x.expr.Pos()
    70  }
    71  
    72  // Operand string formats
    73  // (not all "untyped" cases can appear due to the type system,
    74  // but they fall out naturally here)
    75  //
    76  // mode       format
    77  //
    78  // invalid    <expr> (               <mode>                    )
    79  // novalue    <expr> (               <mode>                    )
    80  // builtin    <expr> (               <mode>                    )
    81  // typexpr    <expr> (               <mode>                    )
    82  //
    83  // constant   <expr> (<untyped kind> <mode>                    )
    84  // constant   <expr> (               <mode>       of type <typ>)
    85  // constant   <expr> (<untyped kind> <mode> <val>              )
    86  // constant   <expr> (               <mode> <val> of type <typ>)
    87  //
    88  // variable   <expr> (<untyped kind> <mode>                    )
    89  // variable   <expr> (               <mode>       of type <typ>)
    90  //
    91  // mapindex   <expr> (<untyped kind> <mode>                    )
    92  // mapindex   <expr> (               <mode>       of type <typ>)
    93  //
    94  // value      <expr> (<untyped kind> <mode>                    )
    95  // value      <expr> (               <mode>       of type <typ>)
    96  //
    97  // commaok    <expr> (<untyped kind> <mode>                    )
    98  // commaok    <expr> (               <mode>       of type <typ>)
    99  //
   100  // commaerr   <expr> (<untyped kind> <mode>                    )
   101  // commaerr   <expr> (               <mode>       of type <typ>)
   102  //
   103  // cgofunc    <expr> (<untyped kind> <mode>                    )
   104  // cgofunc    <expr> (               <mode>       of type <typ>)
   105  //
   106  func operandString(x *operand, qf Qualifier) string {
   107  	// special-case nil
   108  	if x.mode == value && x.typ == Typ[UntypedNil] {
   109  		return "nil"
   110  	}
   111  
   112  	var buf bytes.Buffer
   113  
   114  	var expr string
   115  	if x.expr != nil {
   116  		expr = ExprString(x.expr)
   117  	} else {
   118  		switch x.mode {
   119  		case builtin:
   120  			expr = predeclaredFuncs[x.id].name
   121  		case typexpr:
   122  			expr = TypeString(x.typ, qf)
   123  		case constant_:
   124  			expr = x.val.String()
   125  		}
   126  	}
   127  
   128  	// <expr> (
   129  	if expr != "" {
   130  		buf.WriteString(expr)
   131  		buf.WriteString(" (")
   132  	}
   133  
   134  	// <untyped kind>
   135  	hasType := false
   136  	switch x.mode {
   137  	case invalid, novalue, builtin, typexpr:
   138  		// no type
   139  	default:
   140  		// should have a type, but be cautious (don't crash during printing)
   141  		if x.typ != nil {
   142  			if isUntyped(x.typ) {
   143  				buf.WriteString(x.typ.(*Basic).name)
   144  				buf.WriteByte(' ')
   145  				break
   146  			}
   147  			hasType = true
   148  		}
   149  	}
   150  
   151  	// <mode>
   152  	buf.WriteString(operandModeString[x.mode])
   153  
   154  	// <val>
   155  	if x.mode == constant_ {
   156  		if s := x.val.String(); s != expr {
   157  			buf.WriteByte(' ')
   158  			buf.WriteString(s)
   159  		}
   160  	}
   161  
   162  	// <typ>
   163  	if hasType {
   164  		if x.typ != Typ[Invalid] {
   165  			var intro string
   166  			if isGeneric(x.typ) {
   167  				intro = " of parameterized type "
   168  			} else {
   169  				intro = " of type "
   170  			}
   171  			buf.WriteString(intro)
   172  			WriteType(&buf, x.typ, qf)
   173  			if tpar, _ := x.typ.(*TypeParam); tpar != nil {
   174  				buf.WriteString(" constrained by ")
   175  				WriteType(&buf, tpar.bound, qf) // do not compute interface type sets here
   176  			}
   177  		} else {
   178  			buf.WriteString(" with invalid type")
   179  		}
   180  	}
   181  
   182  	// )
   183  	if expr != "" {
   184  		buf.WriteByte(')')
   185  	}
   186  
   187  	return buf.String()
   188  }
   189  
   190  func (x *operand) String() string {
   191  	return operandString(x, nil)
   192  }
   193  
   194  // setConst sets x to the untyped constant for literal lit.
   195  func (x *operand) setConst(tok token.Token, lit string) {
   196  	var kind BasicKind
   197  	switch tok {
   198  	case token.INT:
   199  		kind = UntypedInt
   200  	case token.FLOAT:
   201  		kind = UntypedFloat
   202  	case token.IMAG:
   203  		kind = UntypedComplex
   204  	case token.CHAR:
   205  		kind = UntypedRune
   206  	case token.STRING:
   207  		kind = UntypedString
   208  	default:
   209  		unreachable()
   210  	}
   211  
   212  	val := constant.MakeFromLiteral(lit, tok, 0)
   213  	if val.Kind() == constant.Unknown {
   214  		x.mode = invalid
   215  		x.typ = Typ[Invalid]
   216  		return
   217  	}
   218  	x.mode = constant_
   219  	x.typ = Typ[kind]
   220  	x.val = val
   221  }
   222  
   223  // isNil reports whether x is the nil value.
   224  func (x *operand) isNil() bool {
   225  	return x.mode == value && x.typ == Typ[UntypedNil]
   226  }
   227  
   228  // assignableTo reports whether x is assignable to a variable of type T. If the
   229  // result is false and a non-nil reason is provided, it may be set to a more
   230  // detailed explanation of the failure (result != ""). The returned error code
   231  // is only valid if the (first) result is false. The check parameter may be nil
   232  // if assignableTo is invoked through an exported API call, i.e., when all
   233  // methods have been type-checked.
   234  func (x *operand) assignableTo(check *Checker, T Type, reason *string) (bool, errorCode) {
   235  	if x.mode == invalid || T == Typ[Invalid] {
   236  		return true, 0 // avoid spurious errors
   237  	}
   238  
   239  	V := x.typ
   240  
   241  	// x's type is identical to T
   242  	if Identical(V, T) {
   243  		return true, 0
   244  	}
   245  
   246  	Vu := under(V)
   247  	Tu := under(T)
   248  	Vp, _ := V.(*TypeParam)
   249  	Tp, _ := T.(*TypeParam)
   250  
   251  	// x is an untyped value representable by a value of type T.
   252  	if isUntyped(Vu) {
   253  		assert(Vp == nil)
   254  		if Tp != nil {
   255  			// T is a type parameter: x is assignable to T if it is
   256  			// representable by each specific type in the type set of T.
   257  			return Tp.is(func(t *term) bool {
   258  				if t == nil {
   259  					return false
   260  				}
   261  				// A term may be a tilde term but the underlying
   262  				// type of an untyped value doesn't change so we
   263  				// don't need to do anything special.
   264  				newType, _, _ := check.implicitTypeAndValue(x, t.typ)
   265  				return newType != nil
   266  			}), _IncompatibleAssign
   267  		}
   268  		newType, _, _ := check.implicitTypeAndValue(x, T)
   269  		return newType != nil, _IncompatibleAssign
   270  	}
   271  	// Vu is typed
   272  
   273  	// x's type V and T have identical underlying types
   274  	// and at least one of V or T is not a named type
   275  	// and neither V nor T is a type parameter.
   276  	if Identical(Vu, Tu) && (!hasName(V) || !hasName(T)) && Vp == nil && Tp == nil {
   277  		return true, 0
   278  	}
   279  
   280  	// T is an interface type and x implements T and T is not a type parameter.
   281  	// Also handle the case where T is a pointer to an interface.
   282  	if _, ok := Tu.(*Interface); ok && Tp == nil || isInterfacePtr(Tu) {
   283  		if err := check.implements(V, T); err != nil {
   284  			if reason != nil {
   285  				*reason = err.Error()
   286  			}
   287  			return false, _InvalidIfaceAssign
   288  		}
   289  		return true, 0
   290  	}
   291  
   292  	// If V is an interface, check if a missing type assertion is the problem.
   293  	if Vi, _ := Vu.(*Interface); Vi != nil && Vp == nil {
   294  		if check.implements(T, V) == nil {
   295  			// T implements V, so give hint about type assertion.
   296  			if reason != nil {
   297  				*reason = "need type assertion"
   298  			}
   299  			return false, _IncompatibleAssign
   300  		}
   301  	}
   302  
   303  	// x is a bidirectional channel value, T is a channel
   304  	// type, x's type V and T have identical element types,
   305  	// and at least one of V or T is not a named type.
   306  	if Vc, ok := Vu.(*Chan); ok && Vc.dir == SendRecv {
   307  		if Tc, ok := Tu.(*Chan); ok && Identical(Vc.elem, Tc.elem) {
   308  			return !hasName(V) || !hasName(T), _InvalidChanAssign
   309  		}
   310  	}
   311  
   312  	// optimization: if we don't have type parameters, we're done
   313  	if Vp == nil && Tp == nil {
   314  		return false, _IncompatibleAssign
   315  	}
   316  
   317  	errorf := func(format string, args ...any) {
   318  		if check != nil && reason != nil {
   319  			msg := check.sprintf(format, args...)
   320  			if *reason != "" {
   321  				msg += "\n\t" + *reason
   322  			}
   323  			*reason = msg
   324  		}
   325  	}
   326  
   327  	// x's type V is not a named type and T is a type parameter, and
   328  	// x is assignable to each specific type in T's type set.
   329  	if !hasName(V) && Tp != nil {
   330  		ok := false
   331  		code := _IncompatibleAssign
   332  		Tp.is(func(T *term) bool {
   333  			if T == nil {
   334  				return false // no specific types
   335  			}
   336  			ok, code = x.assignableTo(check, T.typ, reason)
   337  			if !ok {
   338  				errorf("cannot assign %s to %s (in %s)", x.typ, T.typ, Tp)
   339  				return false
   340  			}
   341  			return true
   342  		})
   343  		return ok, code
   344  	}
   345  
   346  	// x's type V is a type parameter and T is not a named type,
   347  	// and values x' of each specific type in V's type set are
   348  	// assignable to T.
   349  	if Vp != nil && !hasName(T) {
   350  		x := *x // don't clobber outer x
   351  		ok := false
   352  		code := _IncompatibleAssign
   353  		Vp.is(func(V *term) bool {
   354  			if V == nil {
   355  				return false // no specific types
   356  			}
   357  			x.typ = V.typ
   358  			ok, code = x.assignableTo(check, T, reason)
   359  			if !ok {
   360  				errorf("cannot assign %s (in %s) to %s", V.typ, Vp, T)
   361  				return false
   362  			}
   363  			return true
   364  		})
   365  		return ok, code
   366  	}
   367  
   368  	return false, _IncompatibleAssign
   369  }
   370  

View as plain text