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  					continue
   177  				}
   178  				key, _ := kv.Key.(*ast.Ident)
   179  				// do all possible checks early (before exiting due to errors)
   180  				// so we don't drop information on the floor
   181  				if key == nil {
   182  					check.genericExpr(nil, x, kv.Value)
   183  					check.errorf(kv, InvalidLitField, "invalid field name %s in struct literal", kv.Key)
   184  					continue
   185  				}
   186  				obj, index, indirect := lookupFieldOrMethod(utyp, false, check.pkg, key.Name, false)
   187  				if obj == nil {
   188  					check.genericExpr(nil, x, kv.Value)
   189  					alt, _, _ := lookupFieldOrMethod(utyp, false, check.pkg, key.Name, true)
   190  					msg := check.lookupError(base, key.Name, alt, true)
   191  					check.error(kv.Key, MissingLitField, msg)
   192  					continue
   193  				}
   194  				fld, _ := obj.(*Var)
   195  				if fld == nil {
   196  					check.genericExpr(nil, x, kv.Value)
   197  					check.errorf(kv.Key, MissingLitField, "%s is not a field", kv.Key)
   198  					continue
   199  				}
   200  				// we can now check the value using the field target type
   201  				etyp := fld.typ
   202  				check.genericExpr(newTarget(etyp, "struct field"), x, kv.Value)
   203  				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) {
   204  					continue
   205  				}
   206  				if indirect {
   207  					check.errorf(kv.Key, InvalidLitField, "invalid implicit pointer indirection to reach %s", kv.Key)
   208  					continue
   209  				}
   210  				check.recordUse(key, fld)
   211  				check.assignment(x, etyp, "struct literal")
   212  				if alt, n := visited.insert(index, fld); n != 0 {
   213  					if fld == alt {
   214  						check.errorf(kv, DuplicateLitField, "duplicate field name %s in struct literal", fld.name)
   215  					} else if n < len(index) {
   216  						check.errorf(kv, DuplicateLitField, "cannot specify promoted field %s and enclosing embedded field %s", fld.name, alt.name)
   217  					} else { // n > len(index)
   218  						check.errorf(kv, DuplicateLitField, "cannot specify embedded field %s and enclosed promoted field %s", fld.name, alt.name)
   219  					}
   220  				}
   221  			}
   222  		} else {
   223  			// no element must have a key
   224  			for i, e := range e.Elts {
   225  				if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
   226  					check.error(kv, MixedStructLit, "mixture of field:value and value elements in struct literal")
   227  					continue
   228  				}
   229  				if i >= len(fields) {
   230  					check.genericExpr(nil, x, e)
   231  					check.errorf(x, InvalidStructLit, "too many values in struct literal of type %s", base)
   232  					break // cannot continue
   233  				}
   234  				// i < len(fields)
   235  				fld := fields[i]
   236  				etyp := fld.typ
   237  				check.genericExpr(newTarget(etyp, "struct field"), x, e)
   238  				if !fld.Exported() && fld.pkg != check.pkg {
   239  					check.errorf(x, UnexportedLitField, "implicit assignment to unexported field %s in struct literal of type %s", fld.name, base)
   240  					continue
   241  				}
   242  				check.assignment(x, etyp, "struct literal")
   243  			}
   244  			if len(e.Elts) < len(fields) {
   245  				var hint string
   246  				for _, fld := range fields {
   247  					if !fld.Exported() && fld.pkg != check.pkg {
   248  						hint = " (type has unexported fields - use key:value pairs)"
   249  						break
   250  					}
   251  				}
   252  				check.errorf(inNode(e, e.Rbrace), InvalidStructLit, "too few values in struct literal of type %s%s", base, hint)
   253  				// ok to continue
   254  			}
   255  		}
   256  
   257  	case *Array:
   258  		n := check.indexedElts(e.Elts, utyp.elem, utyp.len)
   259  		// If we have an array of unknown length (usually [...]T arrays, but also
   260  		// arrays [n]T where n is invalid) set the length now that we know it and
   261  		// record the type for the array (usually done by check.typ which is not
   262  		// called for [...]T). We handle [...]T arrays and arrays with invalid
   263  		// length the same here because it makes sense to "guess" the length for
   264  		// the latter if we have a composite literal; e.g. for [n]int{1, 2, 3}
   265  		// where n is invalid for some reason, it seems fair to assume it should
   266  		// be 3 (see also Checked.arrayLength and go.dev/issue/27346).
   267  		if utyp.len < 0 {
   268  			utyp.len = n
   269  			// e.Type is missing if we have a composite literal element
   270  			// that is itself a composite literal with omitted type. In
   271  			// that case there is nothing to record (there is no type in
   272  			// the source at that point).
   273  			if e.Type != nil {
   274  				check.recordTypeAndValue(e.Type, typexpr, utyp, nil)
   275  			}
   276  		}
   277  
   278  	case *Slice:
   279  		check.indexedElts(e.Elts, utyp.elem, -1)
   280  
   281  	case *Map:
   282  		// If the map key type is an interface (but not a type parameter),
   283  		// the type of a constant key must be considered when checking for
   284  		// duplicates.
   285  		keyIsInterface := isNonTypeParamInterface(utyp.key)
   286  		visited := make(map[any][]Type, len(e.Elts))
   287  		for _, e := range e.Elts {
   288  			kv, _ := e.(*ast.KeyValueExpr)
   289  			if kv == nil {
   290  				check.error(e, MissingLitKey, "missing key in map literal")
   291  				continue
   292  			}
   293  			check.genericExpr(newHint(utyp.key, "map key"), x, kv.Key)
   294  			check.assignment(x, utyp.key, "map literal")
   295  			if !x.isValid() {
   296  				continue
   297  			}
   298  			if x.mode() == constant_ {
   299  				duplicate := false
   300  				xkey := keyVal(x.val)
   301  				if keyIsInterface {
   302  					for _, vtyp := range visited[xkey] {
   303  						if Identical(vtyp, x.typ()) {
   304  							duplicate = true
   305  							break
   306  						}
   307  					}
   308  					visited[xkey] = append(visited[xkey], x.typ())
   309  				} else {
   310  					_, duplicate = visited[xkey]
   311  					visited[xkey] = nil
   312  				}
   313  				if duplicate {
   314  					check.errorf(x, DuplicateLitKey, "duplicate key %s in map literal", x.val)
   315  					continue
   316  				}
   317  			}
   318  			check.genericExpr(newHint(utyp.elem, "map value"), x, kv.Value)
   319  			check.assignment(x, utyp.elem, "map literal")
   320  		}
   321  
   322  	default:
   323  		// when "using" all elements unpack KeyValueExpr
   324  		// explicitly because check.use doesn't accept them
   325  		for _, e := range e.Elts {
   326  			if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
   327  				// Ideally, we should also "use" kv.Key but we can't know
   328  				// if it's an externally defined struct key or not. Going
   329  				// forward anyway can lead to other errors. Give up instead.
   330  				e = kv.Value
   331  			}
   332  			check.use(e)
   333  		}
   334  		// if utyp is invalid, an error was reported before
   335  		if isValid(utyp) {
   336  			var qualifier string
   337  			if isElem {
   338  				qualifier = " element"
   339  			}
   340  			var cause string
   341  			if utyp == nil {
   342  				cause = " (no common underlying type)"
   343  			}
   344  			check.errorf(e, InvalidLit, "invalid composite literal%s type %s%s", qualifier, typ, cause)
   345  			x.invalidate()
   346  			return
   347  		}
   348  	}
   349  
   350  	x.mode_ = value
   351  	x.typ_ = typ
   352  }
   353  
   354  // indexedElts checks the elements (elts) of an array or slice composite literal
   355  // against the literal's element type (typ), and the element indices against
   356  // the literal length if known (length >= 0). It returns the length of the
   357  // literal (maximum index value + 1).
   358  func (check *Checker) indexedElts(elts []ast.Expr, typ Type, length int64) int64 {
   359  	visited := make(map[int64]bool, len(elts))
   360  	var index, max int64
   361  	for _, e := range elts {
   362  		// determine and check index
   363  		validIndex := false
   364  		eval := e
   365  		if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
   366  			if typ, i := check.index(kv.Key, length); isValid(typ) {
   367  				if i >= 0 {
   368  					index = i
   369  					validIndex = true
   370  				} else {
   371  					check.errorf(e, InvalidLitIndex, "index %s must be integer constant", kv.Key)
   372  				}
   373  			}
   374  			eval = kv.Value
   375  		} else if length >= 0 && index >= length {
   376  			check.errorf(e, OversizeArrayLit, "index %d is out of bounds (>= %d)", index, length)
   377  		} else {
   378  			validIndex = true
   379  		}
   380  
   381  		// if we have a valid index, check for duplicate entries
   382  		if validIndex {
   383  			if visited[index] {
   384  				check.errorf(e, DuplicateLitKey, "duplicate index %d in array or slice literal", index)
   385  			}
   386  			visited[index] = true
   387  		}
   388  		index++
   389  		if index > max {
   390  			max = index
   391  		}
   392  
   393  		// check element against composite literal element type
   394  		var x operand
   395  		check.genericExpr(newHint(typ, "array or slice element"), &x, eval)
   396  		check.assignment(&x, typ, "array or slice literal")
   397  	}
   398  	return max
   399  }
   400  
   401  // keyVal maps a complex, float, integer, string or boolean constant value
   402  // to the corresponding complex128, float64, int64, uint64, string, or bool
   403  // Go value if possible; otherwise it returns x.
   404  // A complex constant that can be represented as a float (such as 1.2 + 0i)
   405  // is returned as a floating point value; if a floating point value can be
   406  // represented as an integer (such as 1.0) it is returned as an integer value.
   407  // This ensures that constants of different kind but equal value (such as
   408  // 1.0 + 0i, 1.0, 1) result in the same value.
   409  func keyVal(x constant.Value) any {
   410  	switch x.Kind() {
   411  	case constant.Complex:
   412  		f := constant.ToFloat(x)
   413  		if f.Kind() != constant.Float {
   414  			r, _ := constant.Float64Val(constant.Real(x))
   415  			i, _ := constant.Float64Val(constant.Imag(x))
   416  			return complex(r, i)
   417  		}
   418  		x = f
   419  		fallthrough
   420  	case constant.Float:
   421  		i := constant.ToInt(x)
   422  		if i.Kind() != constant.Int {
   423  			v, _ := constant.Float64Val(x)
   424  			return v
   425  		}
   426  		x = i
   427  		fallthrough
   428  	case constant.Int:
   429  		if v, ok := constant.Int64Val(x); ok {
   430  			return v
   431  		}
   432  		if v, ok := constant.Uint64Val(x); ok {
   433  			return v
   434  		}
   435  	case constant.String:
   436  		return constant.StringVal(x)
   437  	case constant.Bool:
   438  		return constant.BoolVal(x)
   439  	}
   440  	return x
   441  }
   442  

View as plain text