Skip to content

cmd/fix,x/tools/go/analysis/passes/modernize: reflect.TypeOf(nil) transformed into reflect.TypeFor[untyped nil]() #77636

@oeguchi

Description

@oeguchi

Description
The modernize pass in go fix (introduced/enhanced in Go 1.26) attempts to replace reflect.TypeOf(x) with reflect.TypeFor[T](). However, it does not correctly handle cases where the argument is an untyped nil.

When reflect.TypeOf(nil) is encountered, the tool generates reflect.TypeFor[untyped nil](), which is not valid Go syntax and results in a compilation error.

Steps to Reproduce
Create a file main.go with the following content:

package main

import (
	"reflect"
)

func main() {
	_ = reflect.TypeOf(nil)
}

Run the modernize fix (via Go 1.26 toolchain):

go fix main.go

Expected Result
The code should remain unchanged because nil does not have a static type that can be used as a generic type argument, OR it should be transformed into something valid like reflect.TypeFor[any]().

// Remain as is
_ = reflect.TypeOf(nil)

Actual Result
The tool produces invalid syntax:

func main() {
	_ = reflect.TypeFor[untyped nil]()
}

Attempting to build this results in:

syntax error: unexpected name nil, expected comma, : or ]

Additional Context
This issue was discovered while building a database driver (SQLite) where reflect.TypeOf(nil) is commonly used to represent the type of a NULL value. The current implementation in cmd/vendor/golang.org/x/tools/go/analysis/passes/modernize/reflect.go appears to lack validation for types.UntypedNil before performing the transformation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugReportIssues describing a possible bug in the Go implementation.CherryPickCandidateUsed during the release process for point releasesNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions