github.com/bir3/gocompiler@v0.3.205/src/go/types/operand.go (about)

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