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 continue
177 }
178 key, _ := kv.Key.(*ast.Ident)
179
180
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
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 {
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
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
233 }
234
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
254 }
255 }
256
257 case *Array:
258 n := check.indexedElts(e.Elts, utyp.elem, utyp.len)
259
260
261
262
263
264
265
266
267 if utyp.len < 0 {
268 utyp.len = n
269
270
271
272
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
283
284
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
324
325 for _, e := range e.Elts {
326 if kv, _ := e.(*ast.KeyValueExpr); kv != nil {
327
328
329
330 e = kv.Value
331 }
332 check.use(e)
333 }
334
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
355
356
357
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
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
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
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
402
403
404
405
406
407
408
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