Source file src/go/types/literals.go

     1  // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
     2  // Source: ../../cmd/compile/internal/types2/literals.go
     3  
     4  // Copyright 2024 The Go Authors. All rights reserved.
     5  // Use of this source code is governed by a BSD-style
     6  // license that can be found in the LICENSE file.
     7  
     8  // This file implements typechecking of literals.
     9  
    10  package types
    11  
    12  import (
    13  	"go/ast"
    14  	"go/constant"
    15  	"go/token"
    16  	. "internal/types/errors"
    17  	"strings"
    18  )
    19  
    20  // langCompat reports an error if the representation of a numeric
    21  // literal is not compatible with the current language version.
    22  func (check *Checker) langCompat(lit *ast.BasicLit) {
    23  	s := lit.Value
    24  	if len(s) <= 2 || check.allowVersion(go1_13) {
    25  		return
    26  	}
    27  	// len(s) > 2
    28  	if strings.Contains(s, "_") {
    29  		check.versionErrorf(lit, go1_13, "underscore in numeric literal")
    30  		return
    31  	}
    32  	if s[0] != '0' {
    33  		return
    34  	}
    35  	radix := s[1]
    36  	if radix == 'b' || radix == 'B' {
    37  		check.versionErrorf(lit, go1_13, "binary literal")
    38  		return
    39  	}
    40  	if radix == 'o' || radix == 'O' {
    41  		check.versionErrorf(lit, go1_13, "0o/0O-style octal literal")
    42  		return
    43  	}
    44  	if lit.Kind != token.INT && (radix == 'x' || radix == 'X') {
    45  		check.versionErrorf(lit, go1_13, "hexadecimal floating-point literal")
    46  	}
    47  }
    48  
    49  func (check *Checker) basicLit(x *operand, e *ast.BasicLit) {
    50  	switch e.Kind {
    51  	case token.INT, token.FLOAT, token.IMAG:
    52  		check.langCompat(e)
    53  		// The max. mantissa precision for untyped numeric values
    54  		// is 512 bits, or 4048 bits for each of the two integer
    55  		// parts of a fraction for floating-point numbers that are
    56  		// represented accurately in the go/constant package.
    57  		// Constant literals that are longer than this many bits
    58  		// are not meaningful; and excessively long constants may
    59  		// consume a lot of space and time for a useless conversion.
    60  		// Cap constant length with a generous upper limit that also
    61  		// allows for separators between all digits.
    62  		const limit = 10000
    63  		if len(e.Value) > limit {
    64  			check.errorf(e, InvalidConstVal, "excessively long constant: %s... (%d chars)", e.Value[:10], len(e.Value))
    65  			x.invalidate()
    66  			return
    67  		}
    68  	}
    69  	x.setConst(e.Kind, e.Value)
    70  	if !x.isValid() {
    71  		// The parser already establishes syntactic correctness.
    72  		// If we reach here it's because of number under-/overflow.
    73  		// TODO(gri) setConst (and in turn the go/constant package)
    74  		// should return an error describing the issue.
    75  		check.errorf(e, InvalidConstVal, "malformed constant: %s", e.Value)
    76  		x.invalidate()
    77  		return
    78  	}
    79  	// Ensure that integer values don't overflow (go.dev/issue/54280).
    80  	x.expr = e // make sure that check.overflow below has an error position
    81  	check.overflow(x, opPos(x.expr))
    82  }
    83  
    84  func (check *Checker) funcLit(x *operand, e *ast.FuncLit) {
    85  	if sig, ok := check.typ(e.Type).(*Signature); ok {
    86  		// Set the Scope's extent to the complete "func (...) {...}"
    87  		// so that Scope.Innermost works correctly.
    88  		sig.scope.pos = e.Pos()
    89  		sig.scope.end = endPos(e)
    90  		if !check.conf.IgnoreFuncBodies && e.Body != nil {
    91  			// Anonymous functions are considered part of the
    92  			// init expression/func declaration which contains
    93  			// them: use existing package-level declaration info.
    94  			decl := check.decl // capture for use in closure below
    95  			iota := check.iota // capture for use in closure below (go.dev/issue/22345)
    96  			// Don't type-check right away because the function may
    97  			// be part of a type definition to which the function
    98  			// body refers. Instead, type-check as soon as possible,
    99  			// but before the enclosing scope contents changes (go.dev/issue/22992).
   100  			check.later(func() {
   101  				check.funcBody(decl, "<function literal>", sig, e.Body, iota)
   102  			}).describef(e, "func literal")
   103  		}
   104  		x.mode_ = value
   105  		x.typ_ = sig
   106  	} else {
   107  		check.errorf(e, InvalidSyntaxTree, "invalid function literal %v", e)
   108  		x.invalidate()
   109  	}
   110  }
   111  
   112  func (check *Checker) compositeLit(T *target, x *operand, e *ast.CompositeLit) {
   113  	var typ, base Type
   114  	var isElem bool // true if composite literal is an untyped element of an enclosing composite literal
   115  
   116  	switch {
   117  	case e.Type != nil:
   118  		// composite literal type present - use it
   119  		// [...]T array types may only appear with composite literals.
   120  		// Check for them here so we don't have to handle ... in general.
   121  		if atyp, _ := e.Type.(*ast.ArrayType); atyp != nil && isdddArray(atyp) {
   122  			// We have an "open" [...]T array type.
   123  			// Create a new ArrayType with unknown length (-1)
   124  			// and finish setting it up after analyzing the literal.
   125  			typ = &Array{len: -1, elem: check.varType(atyp.Elt)}
   126  		} else {
   127  			typ = check.typ(e.Type)
   128  		}
   129  		base = typ
   130  
   131  	case T != nil:
   132  		// no composite literal type present - use assignment context
   133  		assert(T.typ != nil)
   134  		// report a version error only if we have an inferred type that is not a hint
   135  		_ = T.hint || check.verifyVersionf(e, go1_28, "missing type in composite literal")
   136  		typ = T.typ
   137  		base = typ
   138  		// *T implies &T{}
   139  		u := CommonUnderlying(base)
   140  		if b, ok := deref(u); ok {
   141  			base = b
   142  		}
   143  		isElem = T.hint
   144  
   145  	default:
   146  		// no composite literal type present
   147  		// TODO(gri) provide better error messages depending on context
   148  		check.error(e, UntypedLit, "missing type in composite literal")
   149  		// continue with invalid type so that elements are "used" (go.dev/issue/69092)
   150  		typ = Typ[Invalid]
   151  		base = typ
   152  	}
   153  
   154  	// We cannot create a literal of an incomplete type; make sure it's complete.
   155  	if !check.isComplete(base) {
   156  		x.invalidate()
   157  		return
   158  	}
   159  
   160  	switch utyp := CommonUnderlying(base).(type) {
   161  	case *Struct:
   162  		if len(e.Elts) == 0 {
   163  			break
   164  		}
   165  		// Convention for error messages on invalid struct literals:
   166  		// we mention the struct type only if it clarifies the error
   167  		// (e.g., a duplicate field error doesn't need the struct type).
   168  		fields := utyp.fields
   169  		if _, ok := e.Elts[0].(*ast.KeyValueExpr); ok {
   170  			// all elements must have keys
   171  			visited := make(trie[*Var])
   172  			for _, e := range e.Elts {
   173  				kv, _ := e.(*ast.KeyValueExpr)
   174  				if kv == nil {
   175  					check.error(e, MixedStructLit, "mixture of field:value and value elements in struct literal")
   176  					check.use(e)
   177  					continue
   178  				}
   179  				key, _ := kv.Key.(*ast.Ident)
   180  				// do all possible checks early (before exiting due to errors)
   181  				// so we don't drop information on the floor
   182  				if key == nil {
   183  					check.genericExpr(nil, x, kv.Value)
   184  					check.errorf(kv, InvalidLitField, "invalid field name %s in struct literal", kv.Key)
   185  					continue
   186  				}
   187  				obj, index, indirect := lookupFieldOrMethod(utyp, false, check.pkg, key.Name, false)
   188  				if obj == nil {
   189  					check.genericExpr(nil, x, kv.Value)
   190  					alt, _, _ := lookupFieldOrMethod(utyp, false, check.pkg, key.Name, true)
   191  					msg := check.lookupError(base, key.Name, alt, true)
   192  					check.error(kv.Key, MissingLitField, msg)
   193  					continue
   194  				}
   195  				fld, _ := obj.(*Var)
   196  				if fld == nil {
   197  					check.genericExpr(nil, x, kv.Value)
   198  					check.errorf(kv.Key, MissingLitField, "%s is not a field", kv.Key)
   199  					continue
   200  				}
   201  				// we can now check the value using the field target type
   202  				etyp := fld.typ
   203  				check.genericExpr(newTarget(etyp, "struct field"), x, kv.Value)
   204  				if len(index) > 1 && !check.verifyVersionf(kv.Key, go1_27, "use of promoted field %s in struct literal of type %s", fieldPath(utyp, index), base) {
   205  					continue
   206  				}
   207  				if indirect {
   208  					check.errorf(kv.Key, InvalidLitField, "invalid implicit pointer indirection to reach %s", kv.Key)
   209  					continue
   210  				}
   211  				check.recordUse(key, fld)
   212  				check.assignment(x, etyp, "struct literal")
   213  				if alt, n := visited.insert(index, fld); n != 0 {
   214  					if fld == alt {
   215  						check.errorf(kv, DuplicateLitField, "duplicate field name %s in struct literal", fld.name)
   216  					} else if n < len(index) {
   217  						check.errorf(kv, DuplicateLitField, "cannot specify promoted field %s and enclosing embedded field %s", fld.name, alt.name)
   218  					} else { // n > len(index)
   219  						check.errorf(kv, DuplicateLitField, "cannot specify embedded field %s and enclosed promoted field %s", fld.name, alt.name)
   220  					}
   221  				}
   222  			}
   223  		} else {
   224  			// no element must have a key
   225  			for i, e := range e.Elts {
   226  				if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
   227  					check.error(kv, MixedStructLit, "mixture of field:value and value elements in struct literal")
   228  					check.use(kv.Value)
   229  					continue
   230  				}
   231  				if i >= len(fields) {
   232  					check.genericExpr(nil, x, e)
   233  					check.errorf(x, InvalidStructLit, "too many values in struct literal of type %s", base)
   234  					break // cannot continue
   235  				}
   236  				// i < len(fields)
   237  				fld := fields[i]
   238  				etyp := fld.typ
   239  				check.genericExpr(newTarget(etyp, "struct field"), x, e)
   240  				if !fld.Exported() && fld.pkg != check.pkg {
   241  					check.errorf(x, UnexportedLitField, "implicit assignment to unexported field %s in struct literal of type %s", fld.name, base)
   242  					continue
   243  				}
   244  				check.assignment(x, etyp, "struct literal")
   245  			}
   246  			if len(e.Elts) < len(fields) {
   247  				var hint string
   248  				for _, fld := range fields {
   249  					if !fld.Exported() && fld.pkg != check.pkg {
   250  						hint = " (type has unexported fields - use key:value pairs)"
   251  						break
   252  					}
   253  				}
   254  				check.errorf(inNode(e, e.Rbrace), InvalidStructLit, "too few values in struct literal of type %s%s", base, hint)
   255  				// ok to continue
   256  			}
   257  		}
   258  
   259  	case *Array:
   260  		n := check.indexedElts(e.Elts, utyp.elem, utyp.len)
   261  		// If we have an array of unknown length (usually [...]T arrays, but also
   262  		// arrays [n]T where n is invalid) set the length now that we know it and
   263  		// record the type for the array (usually done by check.typ which is not
   264  		// called for [...]T). We handle [...]T arrays and arrays with invalid
   265  		// length the same here because it makes sense to "guess" the length for
   266  		// the latter if we have a composite literal; e.g. for [n]int{1, 2, 3}
   267  		// where n is invalid for some reason, it seems fair to assume it should
   268  		// be 3 (see also Checked.arrayLength and go.dev/issue/27346).
   269  		if utyp.len < 0 {
   270  			utyp.len = n
   271  			// e.Type is missing if we have a composite literal element
   272  			// that is itself a composite literal with omitted type. In
   273  			// that case there is nothing to record (there is no type in
   274  			// the source at that point).
   275  			if e.Type != nil {
   276  				check.recordTypeAndValue(e.Type, typexpr, utyp, nil)
   277  			}
   278  		}
   279  
   280  	case *Slice:
   281  		check.indexedElts(e.Elts, utyp.elem, -1)
   282  
   283  	case *Map:
   284  		// If the map key type is an interface (but not a type parameter),
   285  		// the type of a constant key must be considered when checking for
   286  		// duplicates.
   287  		keyIsInterface := isNonTypeParamInterface(utyp.key)
   288  		visited := make(map[any][]Type, len(e.Elts))
   289  		for _, e := range e.Elts {
   290  			kv, _ := e.(*ast.KeyValueExpr)
   291  			if kv == nil {
   292  				check.error(e, MissingLitKey, "missing key in map literal")
   293  				check.use(e)
   294  				continue
   295  			}
   296  			check.genericExpr(newHint(utyp.key, "map key"), x, kv.Key)
   297  			check.assignment(x, utyp.key, "map literal")
   298  			if !x.isValid() {
   299  				continue
   300  			}
   301  			if x.mode() == constant_ {
   302  				duplicate := false
   303  				xkey := keyVal(x.val)
   304  				if keyIsInterface {
   305  					for _, vtyp := range visited[xkey] {
   306  						if Identical(vtyp, x.typ()) {
   307  							duplicate = true
   308  							break
   309  						}
   310  					}
   311  					visited[xkey] = append(visited[xkey], x.typ())
   312  				} else {
   313  					_, duplicate = visited[xkey]
   314  					visited[xkey] = nil
   315  				}
   316  				if duplicate {
   317  					check.errorf(x, DuplicateLitKey, "duplicate key %s in map literal", x.val)
   318  					continue
   319  				}
   320  			}
   321  			check.genericExpr(newHint(utyp.elem, "map value"), x, kv.Value)
   322  			check.assignment(x, utyp.elem, "map literal")
   323  		}
   324  
   325  	default:
   326  		// when "using" all elements unpack KeyValueExpr
   327  		// explicitly because check.use doesn't accept them
   328  		for _, e := range e.Elts {
   329  			if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
   330  				// Ideally, we should also "use" kv.Key but we can't know
   331  				// if it's an externally defined struct key or not. Going
   332  				// forward anyway can lead to other errors. Give up instead.
   333  				e = kv.Value
   334  			}
   335  			check.use(e)
   336  		}
   337  		// if utyp is invalid, an error was reported before
   338  		if isValid(utyp) {
   339  			var qualifier string
   340  			if isElem {
   341  				qualifier = " element"
   342  			}
   343  			var cause string
   344  			if utyp == nil {
   345  				cause = " (no common underlying type)"
   346  			}
   347  			check.errorf(e, InvalidLit, "invalid composite literal%s type %s%s", qualifier, typ, cause)
   348  			x.invalidate()
   349  			return
   350  		}
   351  	}
   352  
   353  	x.mode_ = value
   354  	x.typ_ = typ
   355  }
   356  
   357  // indexedElts checks the elements (elts) of an array or slice composite literal
   358  // against the literal's element type (typ), and the element indices against
   359  // the literal length if known (length >= 0). It returns the length of the
   360  // literal (maximum index value + 1).
   361  func (check *Checker) indexedElts(elts []ast.Expr, typ Type, length int64) int64 {
   362  	visited := make(map[int64]bool, len(elts))
   363  	var index, max int64
   364  	for _, e := range elts {
   365  		// determine and check index
   366  		validIndex := false
   367  		eval := e
   368  		if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
   369  			if typ, i := check.index(kv.Key, length); isValid(typ) {
   370  				if i >= 0 {
   371  					index = i
   372  					validIndex = true
   373  				} else {
   374  					check.errorf(e, InvalidLitIndex, "index %s must be integer constant", kv.Key)
   375  				}
   376  			}
   377  			eval = kv.Value
   378  		} else if length >= 0 && index >= length {
   379  			check.errorf(e, OversizeArrayLit, "index %d is out of bounds (>= %d)", index, length)
   380  		} else {
   381  			validIndex = true
   382  		}
   383  
   384  		// if we have a valid index, check for duplicate entries
   385  		if validIndex {
   386  			if visited[index] {
   387  				check.errorf(e, DuplicateLitKey, "duplicate index %d in array or slice literal", index)
   388  			}
   389  			visited[index] = true
   390  		}
   391  		index++
   392  		if index > max {
   393  			max = index
   394  		}
   395  
   396  		// check element against composite literal element type
   397  		var x operand
   398  		check.genericExpr(newHint(typ, "array or slice element"), &x, eval)
   399  		check.assignment(&x, typ, "array or slice literal")
   400  	}
   401  	return max
   402  }
   403  
   404  // keyVal maps a complex, float, integer, string or boolean constant value
   405  // to the corresponding complex128, float64, int64, uint64, string, or bool
   406  // Go value if possible; otherwise it returns x.
   407  // A complex constant that can be represented as a float (such as 1.2 + 0i)
   408  // is returned as a floating point value; if a floating point value can be
   409  // represented as an integer (such as 1.0) it is returned as an integer value.
   410  // This ensures that constants of different kind but equal value (such as
   411  // 1.0 + 0i, 1.0, 1) result in the same value.
   412  func keyVal(x constant.Value) any {
   413  	switch x.Kind() {
   414  	case constant.Complex:
   415  		f := constant.ToFloat(x)
   416  		if f.Kind() != constant.Float {
   417  			r, _ := constant.Float64Val(constant.Real(x))
   418  			i, _ := constant.Float64Val(constant.Imag(x))
   419  			return complex(r, i)
   420  		}
   421  		x = f
   422  		fallthrough
   423  	case constant.Float:
   424  		i := constant.ToInt(x)
   425  		if i.Kind() != constant.Int {
   426  			v, _ := constant.Float64Val(x)
   427  			return v
   428  		}
   429  		x = i
   430  		fallthrough
   431  	case constant.Int:
   432  		if v, ok := constant.Int64Val(x); ok {
   433  			return v
   434  		}
   435  		if v, ok := constant.Uint64Val(x); ok {
   436  			return v
   437  		}
   438  	case constant.String:
   439  		return constant.StringVal(x)
   440  	case constant.Bool:
   441  		return constant.BoolVal(x)
   442  	}
   443  	return x
   444  }
   445  

View as plain text