Skip to content

Commit

Permalink
chore(gnovm): prevent assignment to non-assignable expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
omarsy committed Oct 3, 2024
1 parent 8a62a28 commit 2835a06
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
6 changes: 6 additions & 0 deletions gnovm/pkg/gnolang/preprocess.go
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,9 @@ func Preprocess(store Store, ctx BlockNode, n Node) Node {
case *AssignStmt:
checkValDefineMismatch(n)

for _, rx := range n.Rhs {
checkExprIsAssignable(rx)
}
if n.Op == DEFINE {
for _, lx := range n.Lhs {
ln := lx.(*NameExpr).Name
Expand Down Expand Up @@ -489,6 +492,9 @@ func Preprocess(store Store, ctx BlockNode, n Node) Node {
d := n.(Decl)
if cd, ok := d.(*ValueDecl); ok {
checkValDefineMismatch(cd)
for _, rx := range cd.Values {
checkExprIsAssignable(rx)
}
}
// recursively predefine dependencies.
d2, ppd := predefineNow(store, last, d)
Expand Down
23 changes: 23 additions & 0 deletions gnovm/pkg/gnolang/type_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,29 @@ func checkValDefineMismatch(n Node) {
panic(fmt.Sprintf("assignment mismatch: %d variable(s) but %d value(s)", numNames, numValues))
}

func checkExprIsAssignable(exp Expr) {
switch exp.(type) {
case *NameExpr,
*BasicLitExpr,
*BinaryExpr,
*CallExpr,
*IndexExpr,
*SelectorExpr,
*SliceExpr,
*StarExpr,
*RefExpr,
*TypeAssertExpr,
*UnaryExpr,
*CompositeLitExpr,
*KeyValueExpr,
*FuncLitExpr,
*ConstExpr:
return
}

panic(fmt.Sprintf("%s (type) is not an expression", exp.String()))
}

// Assert that xt can be assigned as dt (dest type).
// If autoNative is true, a broad range of xt can match against
// a target native dt type, if and only if dt is a native type.
Expand Down
8 changes: 8 additions & 0 deletions gnovm/tests/files/assign29.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package main

func main() {
t := struct{}
}

// Error:
// main/files/assign29.gno:4:2: struct { } (type) is not an expression
8 changes: 8 additions & 0 deletions gnovm/tests/files/var31.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package main

func main() {
var t = struct{}
}

// Error:
// main/files/var31.gno:4:6: struct { } (type) is not an expression

0 comments on commit 2835a06

Please sign in to comment.