From 73e7568166c826ce68b820da2757b510362a9d76 Mon Sep 17 00:00:00 2001 From: visualfc Date: Wed, 31 Jul 2024 08:34:58 +0800 Subject: [PATCH] cl: fix slicelit for assignStmt/returnStmt --- cl/compile_test.go | 41 ++++++++++++++++++++++++++++++ cl/stmt.go | 11 +++++++- demo/sliceliteral/sliceliteral.gop | 6 +++++ 3 files changed, 57 insertions(+), 1 deletion(-) diff --git a/cl/compile_test.go b/cl/compile_test.go index 851e15300..c70734e8f 100644 --- a/cl/compile_test.go +++ b/cl/compile_test.go @@ -4122,3 +4122,44 @@ func _() { } `) } + +func TestSliceLitAssign(t *testing.T) { + gopClTest(t, ` +var n = 1 +var a []any = [10, 3.14, 200] +n, a = 100, [10, 3.14, 200] +echo a, n +`, `package main + +import "fmt" + +var n = 1 +var a []interface{} = []interface{}{10, 3.14, 200} + +func main() { + n, a = 100, []interface{}{10, 3.14, 200} + fmt.Println(a, n) +} +`) +} + +func TestSliceLitReturn(t *testing.T) { + gopClTest(t, ` +func anyslice() (int, []any) { + return 100, [10, 3.14, 200] +} +n, a := anyslice() +echo n, a +`, `package main + +import "fmt" + +func anyslice() (int, []interface{}) { + return 100, []interface{}{10, 3.14, 200} +} +func main() { + n, a := anyslice() + fmt.Println(n, a) +} +`) +} diff --git a/cl/stmt.go b/cl/stmt.go index 90b784c9c..771fa33a2 100644 --- a/cl/stmt.go +++ b/cl/stmt.go @@ -227,6 +227,9 @@ func compileReturnStmt(ctx *blockCtx, expr *ast.ReturnStmt) { ret.Pos(), "cannot use lambda expression as type %v in return statement", rtyp)) } compileLambda(ctx, v, sig) + case *ast.SliceLit: + rtyp := ctx.cb.Func().Type().(*types.Signature).Results().At(i).Type() + compileSliceLit(ctx, v, rtyp) default: compileExpr(ctx, ret, inFlags) } @@ -291,7 +294,7 @@ func compileAssignStmt(ctx *blockCtx, expr *ast.AssignStmt) { for _, lhs := range expr.Lhs { compileExprLHS(ctx, lhs) } - for _, rhs := range expr.Rhs { + for i, rhs := range expr.Rhs { switch e := rhs.(type) { case *ast.LambdaExpr, *ast.LambdaExpr2: if len(expr.Lhs) == 1 && len(expr.Rhs) == 1 { @@ -304,6 +307,12 @@ func compileAssignStmt(ctx *blockCtx, expr *ast.AssignStmt) { } else { panic(ctx.newCodeErrorf(e.Pos(), "lambda unsupport multiple assignment")) } + case *ast.SliceLit: + var typ types.Type + if len(expr.Lhs) == len(expr.Rhs) { + typ, _ = gogen.DerefType(ctx.cb.Get(-1 - i).Type) + } + compileSliceLit(ctx, e, typ) default: compileExpr(ctx, rhs, inFlags) } diff --git a/demo/sliceliteral/sliceliteral.gop b/demo/sliceliteral/sliceliteral.gop index 6f57aa092..4e42a163f 100644 --- a/demo/sliceliteral/sliceliteral.gop +++ b/demo/sliceliteral/sliceliteral.gop @@ -2,8 +2,14 @@ func echoF32s(vals []float32) { echo vals } +func anyslice() []any { + return [10, 3.14, 200] +} + echo [10, 3.14, 200] echoF32s [10, 3.14, 200] var a []any = [10, 3.14, 200] +a = [10, 3.14, 200] echo a +echo anyslice()