A Go linter that detects functions accepting pointer arguments but failing to check for nil
values. This helps enforce best practices in Go programs, ensuring safer and more robust code.
The NilCheck Linter analyzes Go code to identify functions that:
- Accept pointer arguments.
- Do not verify if the pointers are
nil
before using them.
This ensures that potential runtime nil
dereference errors are avoided, promoting cleaner and safer Go code.
- Detects functions with pointer arguments.
- Analyzes the function body for
nil
checks on pointer arguments. - Reports functions missing
nil
checks with specific line numbers and function names.
To install the linter, use go install
:
go install github.com/jtbonhomme/go-nilcheck@latest
Run the linter on your Go project using:
nilcheck ./...
This will analyze all .go files in the specified directory (and subdirectories) and report any violations.
- Identify Functions: The linter inspects the abstract syntax tree (AST) of Go files to identify all function declarations.
- Extract Pointer Arguments: It checks the function's parameters for pointer arguments.
- Analyze Function Body: It searches the function body to ensure nil checks are performed for all pointer arguments.
- Report Issues: If any pointer argument is not checked for nil, the linter reports an issue with the function's name and position.
The main logic resides in the analyzer.go
file:
getPointerArguments
: Extracts all pointer arguments from a function's parameters.checkNilInBody
: Ensures the function body contains appropriate nil checks.hasNilCheck
: Recursively inspects expressions to detect nil checks.
The main.go
file integrates the linter with the golang.org/x/tools/go/analysis/singlechecker
package, enabling command-line usage.
func ExampleFunc(p *int) {
*p = 42 // Potential runtime panic if `p` is nil
}
Output:
main.go:5: Function ExampleFunc has pointer arguments but does not check for nil
func ExampleFunc(p *int) {
if p != nil {
*p = 42
}
}
No issues are reported.
Contributions are welcome! To contribute:
- Fork the repository.
- Create a feature branch.
- Commit your changes.
- Submit a pull request.
This project is licensed under the MIT License. See the LICENSE file for details.