Skip to content

Commit

Permalink
Add makezero linter (#1520)
Browse files Browse the repository at this point in the history
makezero ensures that objects recognized as slices are initialized with length 0.  By default, this is only required when we find a subsequent append to the object, but can also be enabled at all times as a way of discouraging the use of integer variables (i.e. "i") to index slices.
  • Loading branch information
ashanbrown committed Dec 5, 2020
1 parent f7a0c3c commit cf32a7b
Show file tree
Hide file tree
Showing 8 changed files with 102 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .golangci.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,9 @@ linters-settings:
errorlint:
# Report non-wrapping error creation using fmt.Errorf
errorf: true
makezero:
# Allow only slices initialized with a length of zero. Default is false.
always: false

# The custom section can be used to define linter plugins to be loaded at runtime. See README doc
# for more info.
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require (
4d63.com/gochecknoglobals v0.0.0-20201008074935-acfc0b28355a
github.com/Djarvur/go-err113 v0.0.0-20200511133814-5174e21577d5
github.com/OpenPeeDeeP/depguard v1.0.1
github.com/ashanbrown/makezero v0.0.0-20201205152432-7b7cdbb3025a
github.com/bombsimon/wsl/v3 v3.1.0
github.com/daixiang0/gci v0.2.4
github.com/denis-tingajkin/go-header v0.3.1
Expand Down
5 changes: 5 additions & 0 deletions go.sum

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

5 changes: 5 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ type LintersSettings struct {
Exhaustive ExhaustiveSettings
Gofumpt GofumptSettings
ErrorLint ErrorLintSettings
Makezero MakezeroSettings

Custom map[string]CustomLinterSettings
}
Expand Down Expand Up @@ -386,6 +387,10 @@ type ErrorLintSettings struct {
Errorf bool `mapstructure:"errorf"`
}

type MakezeroSettings struct {
Always bool
}

var defaultLintersSettings = LintersSettings{
Lll: LllSettings{
LineLength: 120,
Expand Down
60 changes: 60 additions & 0 deletions pkg/golinters/makezero.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package golinters

import (
"sync"

"github.com/ashanbrown/makezero/makezero"
"github.com/pkg/errors"
"golang.org/x/tools/go/analysis"

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

const makezeroName = "makezero"

func NewMakezero() *goanalysis.Linter {
var mu sync.Mutex
var resIssues []goanalysis.Issue

analyzer := &analysis.Analyzer{
Name: makezeroName,
Doc: goanalysis.TheOnlyanalyzerDoc,
}
return goanalysis.NewLinter(
makezeroName,
"Finds slice declarations with non-zero initial length",
[]*analysis.Analyzer{analyzer},
nil,
).WithContextSetter(func(lintCtx *linter.Context) {
s := &lintCtx.Settings().Makezero

analyzer.Run = func(pass *analysis.Pass) (interface{}, error) {
var res []goanalysis.Issue
linter := makezero.NewLinter(s.Always)
for _, file := range pass.Files {
hints, err := linter.Run(pass.Fset, pass.TypesInfo, file)
if err != nil {
return nil, errors.Wrapf(err, "makezero linter failed on file %q", file.Name.String())
}
for _, hint := range hints {
res = append(res, goanalysis.NewIssue(&result.Issue{
Pos: hint.Position(),
Text: hint.Details(),
FromLinter: makezeroName,
}, pass))
}
}
if len(res) == 0 {
return nil, nil
}
mu.Lock()
resIssues = append(resIssues, res...)
mu.Unlock()
return nil, nil
}
}).WithIssuesReporter(func(*linter.Context) []goanalysis.Issue {
return resIssues
}).WithLoadMode(goanalysis.LoadModeSyntax | goanalysis.LoadModeTypesInfo)
}
3 changes: 3 additions & 0 deletions pkg/lint/lintersdb/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,9 @@ func (m Manager) GetAllSupportedLinterConfigs() []*linter.Config {
WithPresets(linter.PresetStyle).
WithLoadForGoAnalysis().
WithURL("https://github.com/kunwardeep/paralleltest"),
linter.NewConfig(golinters.NewMakezero()).
WithPresets(linter.PresetStyle, linter.PresetBugs).
WithURL("https://github.com/ashanbrown/makezero"),

// nolintlint must be last because it looks at the results of all the previous linters for unused nolint directives
linter.NewConfig(golinters.NewNoLintLint()).
Expand Down
12 changes: 12 additions & 0 deletions test/testdata/makezero.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
//args: -Emakezero
package testdata

func Makezero() []int {
x := make([]int, 5)
return append(x, 1) // ERROR "append to slice `x` with non-zero initialized length"
}

func MakezeroNolint() []int {
x := make([]int, 5)
return append(x, 1) //nolint:makezero // ok that we're appending to an uninitialized slice
}
13 changes: 13 additions & 0 deletions test/testdata/makezero_always.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
//args: -Emakezero
//config: linters-settings.makezero.always=true
package testdata

func MakezeroAlways() []int {
x := make([]int, 5) // ERROR "slice `x` does not have non-zero initial length"
return x
}

func MakezeroAlwaysNolint() []int {
x := make([]int, 5) //nolint:makezero // ok that this is not initialized
return x
}

0 comments on commit cf32a7b

Please sign in to comment.