From 35e67c4e2b52240eef34052b817ef1239a5d5f3d Mon Sep 17 00:00:00 2001 From: visualfc Date: Tue, 4 Mar 2025 10:39:35 +0800 Subject: [PATCH] cl: fix mapLit to any --- cl/compile_gop_test.go | 19 +++++++++++++++++++ cl/error_msg_test.go | 6 ++++++ cl/expr.go | 35 ++++++++++++++++++++--------------- 3 files changed, 45 insertions(+), 15 deletions(-) diff --git a/cl/compile_gop_test.go b/cl/compile_gop_test.go index 8b7e9d8ef..d6fa13e09 100644 --- a/cl/compile_gop_test.go +++ b/cl/compile_gop_test.go @@ -1706,3 +1706,22 @@ func main() { } `) } + +func TestMapLitType(t *testing.T) { + gopClTest(t, ` +var a any = { + "Monday": 1, + "Tuesday": 2, +} +echo a +`, `package main + +import "fmt" + +var a interface{} = map[string]int{"Monday": 1, "Tuesday": 2} + +func main() { + fmt.Println(a) +} +`) +} diff --git a/cl/error_msg_test.go b/cl/error_msg_test.go index a9553ee39..10cb6b764 100644 --- a/cl/error_msg_test.go +++ b/cl/error_msg_test.go @@ -603,6 +603,12 @@ bar.gop:3:27: cannot use "Go" + "+" (type untyped string) as type int in map val ` a := map[string]int{1+2: 2} b := map[string]int{"Hi": "Go" + "+"} +`) + codeErrorTest(t, `bar.gop:2:13: invalid map literal`, ` +var v any = {1:2,1} +`) + codeErrorTest(t, `bar.gop:2:21: invalid map literal`, ` +var v map[int]int = {1:2,1} `) } diff --git a/cl/expr.go b/cl/expr.go index 68e862322..09d044355 100644 --- a/cl/expr.go +++ b/cl/expr.go @@ -1277,22 +1277,25 @@ func compileCompositeLitEx(ctx *blockCtx, v *ast.CompositeLit, expected types.Ty return err } n := len(v.Elts) - if isMap(underlying) { + switch underlying.(type) { + case *types.Slice: + ctx.cb.SliceLitEx(typ, n< 0 { return ctx.newCodeError(v.Pos(), "missing key in map literal") } - if err := ctx.cb.MapLitEx(typ, n<<1, v); err != nil { + if err := compileMapLitEx(ctx, typ, n, v); err != nil { return err } - } else { - switch underlying.(type) { - case *types.Slice: - ctx.cb.SliceLitEx(typ, n< 0 { return ctx.newCodeErrorf(v.Pos(), "invalid composite literal type %v", typ) } + if err := compileMapLitEx(ctx, nil, n, v); err != nil { + return err + } } } if hasPtr { @@ -1305,12 +1308,14 @@ func compileCompositeLitEx(ctx *blockCtx, v *ast.CompositeLit, expected types.Ty return nil } -func isMap(tu types.Type) bool { - if tu == nil { // map can omit type - return true - } - _, ok := tu.(*types.Map) - return ok +func compileMapLitEx(ctx *blockCtx, typ types.Type, n int, v *ast.CompositeLit) (err error) { + defer func() { + if e := recover(); e != nil { + err = ctx.newCodeError(v.Pos(), "invalid map literal") + } + }() + err = ctx.cb.MapLitEx(typ, n<<1, v) + return } func isMapOrStruct(tu types.Type) bool {