From 284bb946986d9c6ee2694e87d3f4bd84f8c8ca0d Mon Sep 17 00:00:00 2001 From: Javier Espert Real Date: Sat, 26 Oct 2024 15:53:39 +0100 Subject: [PATCH] Fix panic when accessing the package name of a prelude object Patches a bug introduced in v1.12.0. --- tenv.go | 7 ++++++- tenv_test.go | 5 +++++ testdata/src/regression/go.mod | 3 +++ testdata/src/regression/go.sum | 0 .../regression/prelude_functions_have_no_package.go | 10 ++++++++++ 5 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 testdata/src/regression/go.mod create mode 100644 testdata/src/regression/go.sum create mode 100644 testdata/src/regression/prelude_functions_have_no_package.go diff --git a/tenv.go b/tenv.go index 647f368..10aecd6 100644 --- a/tenv.go +++ b/tenv.go @@ -169,7 +169,12 @@ func checkAssignStmt(pass *analysis.Pass, stmt *ast.AssignStmt, funcName, argNam } func checkObj(pass *analysis.Pass, obj types.Object, pos token.Pos, funcName, argName string) bool { - targetName := fmt.Sprintf("%s.%s", obj.Pkg().Name(), obj.Name()) + var pkgName string + if pkg := obj.Pkg(); pkg != nil { + pkgName = pkg.Name() + } + + targetName := fmt.Sprintf("%s.%s", pkgName, obj.Name()) if targetName == "os.Setenv" { if argName == "" { argName = "testing" diff --git a/tenv_test.go b/tenv_test.go index c4789c0..903d142 100644 --- a/tenv_test.go +++ b/tenv_test.go @@ -14,3 +14,8 @@ func TestAnalyzer(t *testing.T) { testdata := testutil.WithModules(t, analysistest.TestData(), nil) analysistest.Run(t, testdata, tenv.Analyzer, "a") } + +func TestRegression(t *testing.T) { + testdata := testutil.WithModules(t, analysistest.TestData(), nil) + analysistest.Run(t, testdata, tenv.Analyzer, "regression") +} diff --git a/testdata/src/regression/go.mod b/testdata/src/regression/go.mod new file mode 100644 index 0000000..2b43fec --- /dev/null +++ b/testdata/src/regression/go.mod @@ -0,0 +1,3 @@ +module regression + +go 1.22.3 diff --git a/testdata/src/regression/go.sum b/testdata/src/regression/go.sum new file mode 100644 index 0000000..e69de29 diff --git a/testdata/src/regression/prelude_functions_have_no_package.go b/testdata/src/regression/prelude_functions_have_no_package.go new file mode 100644 index 0000000..5372f0d --- /dev/null +++ b/testdata/src/regression/prelude_functions_have_no_package.go @@ -0,0 +1,10 @@ +package regression_test + +import "testing" + +func TestPreludeFunctionsHaveNoPkg(t *testing.T) { + // Prelude definitions have no package, which means that "go/types".Object.Pkg() returns nil, + // which in turn panics when its method Name() is called. + var items []int + items = append(items, 0) +}