From 64fe55e5ce0b4bd0d1241a95a39024d04820d1c5 Mon Sep 17 00:00:00 2001 From: MikaelVallenet Date: Thu, 1 Aug 2024 18:44:30 +0700 Subject: [PATCH] fix(gnovm): add recursiv check on unary & binary operands --- gnovm/pkg/gnolang/type_check.go | 31 +++++++++++++++++++++++++------ 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/gnovm/pkg/gnolang/type_check.go b/gnovm/pkg/gnolang/type_check.go index 6aa736d3e5e..88772d246d6 100644 --- a/gnovm/pkg/gnolang/type_check.go +++ b/gnovm/pkg/gnolang/type_check.go @@ -215,17 +215,36 @@ func assertAssignableTo(xt, dt Type, autoNative bool) { } } -// TODO: check operands unary & binary expr are const func checkValConstType(d *ValueDecl) { - for _, vx := range d.Values { - switch vx.(type) { - case *BasicLitExpr, *BinaryExpr, *UnaryExpr: - // Valid constant expression - break + if d.Type != nil { + switch d.Type.(type) { + case *BasicLitExpr, *NameExpr: + // Valid constant type expression, in case of NameExpr should evaluate if underlying type is a basic type default: panic("const type should be a basic type") } } + for _, vx := range d.Values { + isBasicExpr(vx) + } +} + +// Function to validate an operand, which could be another expression +// TODO: Verify the typed value linked to the expression is a constant +func isBasicExpr(expr Expr) { + switch x := expr.(type) { + case *BasicLitExpr, *NameExpr: + // Valid, as basic literals are always constant + case *BinaryExpr: + // Recursively validate the operands of the binary expression + isBasicExpr(x.Left) + isBasicExpr(x.Right) + case *UnaryExpr: + // Recursively validate the operand of the unary expression + isBasicExpr(x.X) + default: + panic("const values should be basic literals") + } } // checkValDefineMismatch checks for mismatch between the number of variables and values in a ValueDecl or AssignStmt.