Skip to content

Commit

Permalink
feat(gnovm): support constant evaluation of len and cap on arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
omarsy committed Jan 23, 2025
1 parent 92c41eb commit c3c3461
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 8 deletions.
37 changes: 29 additions & 8 deletions gnovm/pkg/gnolang/preprocess.go
Original file line number Diff line number Diff line change
Expand Up @@ -3369,15 +3369,36 @@ func getResultTypedValues(cx *CallExpr) []TypedValue {
func evalConst(store Store, last BlockNode, x Expr) *ConstExpr {
// TODO: some check or verification for ensuring x
// is constant? From the machine?
m := NewMachine(".dontcare", store)
m.PreprocessorMode = true
var cx *ConstExpr
if clx, ok := x.(*CallExpr); ok {
ar, ok := evalStaticTypeOf(store, last, clx.Args[0]).(*ArrayType)
if ok {
fv := clx.Func.(*ConstExpr).V.(*FuncValue)
switch {
case fv.Name == "cap":
fallthrough
case fv.Name == "len":
tv := TypedValue{T: IntType}
tv.SetInt(ar.Len)
cx = &ConstExpr{
Source: x,
TypedValue: tv,
}
default:
panic(fmt.Sprintf("unexpected const func %s", fv.Name))

Check warning on line 3388 in gnovm/pkg/gnolang/preprocess.go

View check run for this annotation

Codecov / codecov/patch

gnovm/pkg/gnolang/preprocess.go#L3387-L3388

Added lines #L3387 - L3388 were not covered by tests
}
}
}

cv := m.EvalStatic(last, x)
m.PreprocessorMode = false
m.Release()
cx := &ConstExpr{
Source: x,
TypedValue: cv,
if cx == nil {
m := NewMachine(".dontcare", store)
cv := m.EvalStatic(last, x)
m.PreprocessorMode = false
m.Release()
cx = &ConstExpr{
Source: x,
TypedValue: cv,
}
}
cx.SetLine(x.GetLine())
cx.SetAttribute(ATTR_PREPROCESSED, true)
Expand Down
14 changes: 14 additions & 0 deletions gnovm/tests/files/const51.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package main

type T struct {
x [2]string
}

func main() {
t := T{x: [2]string{"a", "b"}}
const v = len(t.x)
println(v)
}

// Output:
// 2

0 comments on commit c3c3461

Please sign in to comment.