Skip to content

Commit

Permalink
Merge pull request #1959 from visualfc/fixslicelit
Browse files Browse the repository at this point in the history
cl: fix slicelit for assignStmt/returnStmt
  • Loading branch information
xushiwei authored Jul 31, 2024
2 parents 43deb05 + 73e7568 commit 5ce3b8d
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 1 deletion.
41 changes: 41 additions & 0 deletions cl/compile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
`)
}
11 changes: 10 additions & 1 deletion cl/stmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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 {
Expand All @@ -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)
}
Expand Down
6 changes: 6 additions & 0 deletions demo/sliceliteral/sliceliteral.gop
Original file line number Diff line number Diff line change
Expand Up @@ -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()

0 comments on commit 5ce3b8d

Please sign in to comment.