Skip to content

Commit

Permalink
Fix panic when accessing the package name of a built-in object (#45)
Browse files Browse the repository at this point in the history
Patches a bug introduced in v1.12.0.
  • Loading branch information
jespert authored Oct 28, 2024
1 parent f3602b0 commit b69ab3c
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 1 deletion.
8 changes: 7 additions & 1 deletion tenv.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 objects, 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"
Expand Down
5 changes: 5 additions & 0 deletions tenv_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
10 changes: 10 additions & 0 deletions testdata/src/regression/builtin_functions_have_no_package.go
Original file line number Diff line number Diff line change
@@ -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)
}
3 changes: 3 additions & 0 deletions testdata/src/regression/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module regression

go 1.22.3
Empty file added testdata/src/regression/go.sum
Empty file.

0 comments on commit b69ab3c

Please sign in to comment.