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

View as plain text