Skip to content

Commit b69ab3c

Browse files
authored
Fix panic when accessing the package name of a built-in object (#45)
Patches a bug introduced in v1.12.0.
1 parent f3602b0 commit b69ab3c

File tree

5 files changed

+25
-1
lines changed

5 files changed

+25
-1
lines changed

tenv.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,13 @@ func checkAssignStmt(pass *analysis.Pass, stmt *ast.AssignStmt, funcName, argNam
169169
}
170170

171171
func checkObj(pass *analysis.Pass, obj types.Object, pos token.Pos, funcName, argName string) bool {
172-
targetName := fmt.Sprintf("%s.%s", obj.Pkg().Name(), obj.Name())
172+
// For built-in objects, obj.Pkg() returns nil.
173+
var pkgPrefix string
174+
if pkg := obj.Pkg(); pkg != nil {
175+
pkgPrefix = pkg.Name() + "."
176+
}
177+
178+
targetName := pkgPrefix + obj.Name()
173179
if targetName == "os.Setenv" {
174180
if argName == "" {
175181
argName = "testing"

tenv_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,8 @@ func TestAnalyzer(t *testing.T) {
1414
testdata := testutil.WithModules(t, analysistest.TestData(), nil)
1515
analysistest.Run(t, testdata, tenv.Analyzer, "a")
1616
}
17+
18+
func TestRegression(t *testing.T) {
19+
testdata := testutil.WithModules(t, analysistest.TestData(), nil)
20+
analysistest.Run(t, testdata, tenv.Analyzer, "regression")
21+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package regression_test
2+
3+
import "testing"
4+
5+
func TestBuiltInFunctionsHaveNoPkg(t *testing.T) {
6+
// Built-in definitions have no package, which means that "go/types".Object.Pkg() returns nil,
7+
// which in turn panics when its method Name() is called.
8+
var items []int
9+
items = append(items, 0)
10+
}

testdata/src/regression/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module regression
2+
3+
go 1.22.3

testdata/src/regression/go.sum

Whitespace-only changes.

0 commit comments

Comments
 (0)