From 76108a11f1ebf59b5ebdd43e27831d9cef206317 Mon Sep 17 00:00:00 2001 From: Sergey Vilgelm Date: Thu, 9 Feb 2023 23:22:21 -0800 Subject: [PATCH] do not panic on nil object fix #20 for the panic on `json.Marshal(nil)` code --- musttag.go | 3 +++ testdata/src/tests/tests.go | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/musttag.go b/musttag.go index 121777b..1c57e14 100644 --- a/musttag.go +++ b/musttag.go @@ -160,6 +160,9 @@ func run(pass *analysis.Pass, funcs map[string]Func) (any, error) { initialPos := token.NoPos switch arg := arg.(type) { case *ast.Ident: // e.g. json.Marshal(foo) + if arg.Obj == nil { + return // e.g. json.Marshal(nil) + } initialPos = arg.Obj.Pos() case *ast.CompositeLit: // e.g. json.Marshal(struct{}{}) initialPos = arg.Pos() diff --git a/testdata/src/tests/tests.go b/testdata/src/tests/tests.go index 007328c..7db8eef 100644 --- a/testdata/src/tests/tests.go +++ b/testdata/src/tests/tests.go @@ -468,3 +468,8 @@ func nonStructArgument() { custom.Marshal(0) custom.Unmarshal(nil, &[]int{}) } + +// test for panic with nil object issue: https://github.com/junk1tm/musttag/issues/20 +func nilObject() { + json.Marshal(nil) +}