interp: fix computation of array size from constant expression

The result of the expression giving the size of an array may be an `int` instead of `constant.Value` in case of an out of order declaration. Handle both cases.

Fixes #1536.
This commit is contained in:
Marc Vertes
2023-04-11 17:54:05 +02:00
committed by GitHub
parent 8de3add6fa
commit d124954a7d
2 changed files with 23 additions and 5 deletions

15
_test/issue-1536.go Normal file
View File

@@ -0,0 +1,15 @@
package main
var a [len(prefix+path) + 2]int
const (
prefix = "/usr/"
path = prefix + "local/bin"
)
func main() {
println(len(a))
}
// Output:
// 21

View File

@@ -484,6 +484,7 @@ func nodeType2(interp *Interpreter, sc *scope, n *node, seen []*node) (t *itype,
length = int(vInt(sym.rval))
default:
// Size is defined by a numeric constant expression.
ok := false
if _, err := interp.cfg(c0, sc, sc.pkgID, sc.pkgName); err != nil {
if strings.Contains(err.Error(), " undefined: ") {
incomplete = true
@@ -491,12 +492,14 @@ func nodeType2(interp *Interpreter, sc *scope, n *node, seen []*node) (t *itype,
}
return nil, err
}
v, ok := c0.rval.Interface().(constant.Value)
if !ok {
incomplete = true
break
if length, ok = c0.rval.Interface().(int); !ok {
v, ok := c0.rval.Interface().(constant.Value)
if !ok {
incomplete = true
break
}
length = constToInt(v)
}
length = constToInt(v)
}
val, err := nodeType2(interp, sc, n.child[1], seen)
if err != nil {