Skip to content

Commit a9e107c

Browse files
committed
cmd/compile: make sure to initialize static entries of slices
If a slice's entries are sparse, we decide to initialize it dynamically instead of statically. That's CL 151319. But if we do initialize it dynamically, we still need to initialize the static entries. Typically we do that, but the bug fixed here is that we don't if the entry's value is itself an array or struct. To fix, use initKindLocalCode to ensure that both static and dynamic entries are initialized via code. Fixes #31987 Change-Id: I1192ffdbfb5cd50445c1206c4a3d8253295201dd Reviewed-on: https://go-review.googlesource.com/c/go/+/176904 Run-TryBot: Keith Randall <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Josh Bleecher Snyder <[email protected]>
1 parent 2637f1f commit a9e107c

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

src/cmd/compile/internal/gc/sinit.go

+14-1
Original file line numberDiff line numberDiff line change
@@ -561,6 +561,13 @@ const (
561561
inNonInitFunction
562562
)
563563

564+
func (c initContext) String() string {
565+
if c == inInitFunction {
566+
return "inInitFunction"
567+
}
568+
return "inNonInitFunction"
569+
}
570+
564571
// from here down is the walk analysis
565572
// of composite literals.
566573
// most of the work is to generate
@@ -920,7 +927,13 @@ func slicelit(ctxt initContext, n *Node, var_ *Node, init *Nodes) {
920927
break
921928

922929
case OARRAYLIT, OSTRUCTLIT:
923-
fixedlit(ctxt, initKindDynamic, value, a, init)
930+
k := initKindDynamic
931+
if vstat == nil {
932+
// Generate both static and dynamic initializations.
933+
// See issue #31987.
934+
k = initKindLocalCode
935+
}
936+
fixedlit(ctxt, k, value, a, init)
924937
continue
925938
}
926939

test/fixedbugs/issue31987.go

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// run
2+
3+
// Copyright 2019 The Go Authors. All rights reserved.
4+
// Use of this source code is governed by a BSD-style
5+
// license that can be found in the LICENSE file.
6+
7+
package main
8+
9+
import "fmt"
10+
11+
type container struct {
12+
Value string
13+
}
14+
15+
func main() {
16+
s := []container{
17+
7: {Value: "string value"},
18+
}
19+
if s[7].Value != "string value" {
20+
panic(fmt.Errorf("wanted \"string value\", got \"%s\"", s[7].Value))
21+
}
22+
}

0 commit comments

Comments
 (0)