Skip to content

Commit

Permalink
add nilassign linter (golangci#2131)
Browse files Browse the repository at this point in the history
Co-authored-by: Fernandez Ludovic <ldez@users.noreply.github.com>
  • Loading branch information
2 people authored and SeigeC committed Apr 4, 2023
1 parent f649a0f commit 54767db
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 0 deletions.
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ require (
github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c
github.com/shirou/gopsutil/v3 v3.21.6
github.com/sirupsen/logrus v1.8.1
github.com/sivchari/nilassign v0.1.0
github.com/sonatard/noctx v0.0.1
github.com/sourcegraph/go-diff v0.6.1
github.com/spf13/cobra v1.2.1
Expand Down
21 changes: 21 additions & 0 deletions go.sum

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions pkg/golinters/nilassign.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package golinters

import (
"github.com/sivchari/nilassign"
"golang.org/x/tools/go/analysis"

"github.com/golangci/golangci-lint/pkg/golinters/goanalysis"
)

func NewNilAssign() *goanalysis.Linter {
analyzers := []*analysis.Analyzer{
nilassign.Analyzer,
}

return goanalysis.NewLinter(
"nilassign",
"Finds that assigning to invalid memory address or nil pointer dereference.",
analyzers,
nil,
).WithLoadMode(goanalysis.LoadModeTypesInfo)
}
5 changes: 5 additions & 0 deletions pkg/lint/lintersdb/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,11 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config {
WithLoadForGoAnalysis().
WithPresets(linter.PresetBugs).
WithURL("https://github.com/gostaticanalysis/nilerr"),
linter.NewConfig(golinters.NewNilAssign()).
WithSince("v1.42.0").
WithLoadForGoAnalysis().
WithPresets(linter.PresetBugs).
WithURL("https://github.com/sivchari/nilassign"),
linter.NewConfig(golinters.NewForceTypeAssert()).
WithSince("v1.38.0").
WithPresets(linter.PresetStyle).
Expand Down
28 changes: 28 additions & 0 deletions test/testdata/nilassign.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//args: -Enilassign
package testdata

var num = 1

func pvar() {
var ii *int
*ii = 1 // ERROR "this assignment occurs invalid memory address or nil pointer dereference"

var i *int
i = &num // OK
_ = i // OK
}

func pstruct() {
n := new(Node)

*n.PVal = 1 // ERROR "this assignment occurs invalid memory address or nil pointer dereference"
*n.ChildNode.PVal = 1 // ERROR "this assignment occurs invalid memory address or nil pointer dereference"

n.ChildNode = &Node{PVal: &num} // OK
n.PVal = &num // OK
}

type Node struct {
PVal *int
ChildNode *Node
}

0 comments on commit 54767db

Please sign in to comment.