Source file
src/go/types/literals.go
1
2
3
4
5
6
7
8
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
21
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
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
54
55
56
57
58
59
60
61
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
72
73
74
75 check.errorf(e, InvalidConstVal, "malformed constant: %s", e.Value)
76 x.invalidate()
77 return
78 }
79
80 x.expr = e
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
87
88 sig.scope.pos = e.Pos()
89 sig.scope.end = endPos(e)
90 if !check.conf.IgnoreFuncBodies && e.Body != nil {
91
92
93
94 decl := check.decl
95 iota := check.iota
96
97
98
99
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
115
116 switch {
117 case e.Type != nil:
118
119
120
121 if atyp, _ := e.Type.(*ast.ArrayType); atyp != nil && isdddArray(atyp) {
122
123
124
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
133 assert(T.typ != nil)
134
135 _ = T.hint || check.verifyVersionf(e, go1_28, "missing type in composite literal")
136 typ = T.typ
137 base = typ
138
139 u := CommonUnderlying(base)
140 if b, ok := deref(u); ok {
141 base = b
142 }
143 isElem = T.hint
144
145 default:
146
147
148 check.error(e, UntypedLit, "missing type in composite literal")
149
150 typ = Typ[Invalid]
151 base = typ
152 }
153
154
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
166
167
168 fields := utyp.fields
169 if _, ok := e.Elts[0].(*ast.KeyValueExpr); ok {
170
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
181
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
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 {
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
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
235 }
236
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
256 }
257 }
258
259 case *Array:
260 n := check.indexedElts(e.Elts, utyp.elem, utyp.len)
261
262
263
264
265
266
267
268
269 if utyp.len < 0 {
270 utyp.len = n
271
272
273
274
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
285
286
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
327
328 for _, e := range e.Elts {
329 if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
330
331
332
333 e = kv.Value
334 }
335 check.use(e)
336 }
337
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
358
359
360
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
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
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
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
405
406
407
408
409
410
411
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