From f0f04ba0df17312b859ec126931f9d6a76574091 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 built-in object Patches a bug introduced in v1.12.0. --- tenv.go | 8 +++++++- tenv_test.go | 5 +++++ .../regression/builtin_functions_have_no_package.go | 10 ++++++++++ testdata/src/regression/go.mod | 3 +++ testdata/src/regression/go.sum | 0 5 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 testdata/src/regression/builtin_functions_have_no_package.go create mode 100644 testdata/src/regression/go.mod create mode 100644 testdata/src/regression/go.sum diff --git a/tenv.go b/tenv.go index 647f368..89f6aab 100644 --- a/tenv.go +++ b/tenv.go @@ -169,7 +169,13 @@ 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()) + // For built-in functions, obj.Pkg() returns nil. + var pkgPrefix string + if pkg := obj.Pkg(); pkg != nil { + pkgPrefix = pkg.Name() + "." + } + + targetName := pkgPrefix + 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/builtin_functions_have_no_package.go b/testdata/src/regression/builtin_functions_have_no_package.go new file mode 100644 index 0000000..902c9a8 --- /dev/null +++ b/testdata/src/regression/builtin_functions_have_no_package.go @@ -0,0 +1,10 @@ +package regression_test + +import "testing" + +func TestBuiltInFunctionsHaveNoPkg(t *testing.T) { + // Built-in 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) +} 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