Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/analysis/nilaway/nilaway.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
// Analyzer reports a nil value that flows to a dereference. It is the upstream
// analyzer with constable's generated-file policy applied and with the
// analyzed packages limited to the module that constable runs on.
var Analyzer = generated.Skip(nilaway.Analyzer)
var Analyzer = generated.Skip(skipEmptyNoLintFiles(scopeSSA(nilaway.Analyzer)))

// includeAllPkgs keeps nilaway's own default, every package that it loads.
var includeAllPkgs bool
Expand Down
41 changes: 41 additions & 0 deletions internal/analysis/nilaway/nolint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package nilaway

import (
"go/ast"
"strings"

"go.uber.org/nilaway/diagnostic"
"golang.org/x/tools/go/analysis"
)

// skipEmptyNoLintFiles avoids constructing comment maps for files without
// suppression comments. Still run the upstream analyzer for every package:
// it imports and exports suppression facts used by downstream diagnostics,
// even for packages outside NilAway's configured analysis scope.
func skipEmptyNoLintFiles(root *analysis.Analyzer) *analysis.Analyzer {
filtered := *diagnostic.NoLintAnalyzer
filtered.Run = func(pass *analysis.Pass) (any, error) {
copy := *pass
copy.Files = nil
for _, file := range pass.Files {
if mayHaveNoLint(file) {
copy.Files = append(copy.Files, file)
}
}
return diagnostic.NoLintAnalyzer.Run(&copy)
}
return replacePrerequisite(root, diagnostic.NoLintAnalyzer, &filtered)
}

func mayHaveNoLint(file *ast.File) bool {
for _, group := range file.Comments {
for _, comment := range group.List {
// Deliberately accept more than the upstream parser. It remains
// responsible for recognizing valid directives and their ranges.
if strings.Contains(comment.Text, "nolint") {
return true
}
}
}
return false
}
31 changes: 31 additions & 0 deletions internal/analysis/nilaway/nolint_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package nilaway_test

import (
"os"
"testing"

"github.com/stretchr/testify/require"
upstream "go.uber.org/nilaway"
"golang.org/x/tools/go/analysis/analysistest"
"golang.org/x/tools/go/packages"

"github.com/nnutter/constable/internal/analysis/nilaway"
"github.com/nnutter/constable/internal/generated"
)

func TestSuppressionFactsMatchUpstream(t *testing.T) {
setIncludePkgs(t, "suppression")
pkgs, err := packages.Load(&packages.Config{
Mode: packages.LoadAllSyntax,
Dir: analysistest.TestData(),
Env: append(os.Environ(), "GO111MODULE=off", "GOPATH="+analysistest.TestData()),
}, "suppression/...")
require.NoError(t, err)
require.NotEmpty(t, pkgs)
require.Zero(t, packages.PrintErrors(pkgs))

want := analyzerDiagnostics(t, generated.Skip(upstream.Analyzer), pkgs)
require.NotEmpty(t, want, "the unsuppressed nil flow must still be reported")
got := analyzerDiagnostics(t, nilaway.Analyzer, pkgs)
require.Equal(t, want, got)
}
81 changes: 81 additions & 0 deletions internal/analysis/nilaway/ssa.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package nilaway

import (
"slices"

"go.uber.org/nilaway/config"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/buildssa"
)

// scopeSSA copies NilAway's requirement graph so that its SSA prerequisite
// observes the same scope as the function-contract analyzer that consumes it.
// The checker runs prerequisites before their consumers, so the consumer's
// own scope check cannot prevent building SSA for excluded dependencies.
// Copy only the changed prerequisite and its consumers. Other prerequisites
// retain their identities because analyzers outside NilAway may share their
// fact types. Upstream analyzers remain unchanged for other users.
func scopeSSA(root *analysis.Analyzer) *analysis.Analyzer {
scoped := *buildssa.Analyzer
scoped.Requires = append(slices.Clone(scoped.Requires), config.Analyzer)
scoped.Run = runScopedSSA
return replacePrerequisite(root, buildssa.Analyzer, &scoped)
}

// replacePrerequisite copies only the consumers of a changed prerequisite,
// preserving shared identities and the keys upstream uses in ResultOf.
func replacePrerequisite(root, target, replacement *analysis.Analyzer) *analysis.Analyzer {
copies := make(map[*analysis.Analyzer]*analysis.Analyzer)
var clone func(*analysis.Analyzer) *analysis.Analyzer
clone = func(a *analysis.Analyzer) *analysis.Analyzer {
if copy := copies[a]; copy != nil {
return copy
}
copy := *a
copies[a] = &copy
requires, run := a.Requires, a.Run
changed := a == target
if changed {
requires, run = replacement.Requires, replacement.Run
}
copy.Requires = make([]*analysis.Analyzer, len(requires))
for i, req := range requires {
copy.Requires[i] = clone(req)
if copy.Requires[i] != req {
changed = true
}
}
if !changed {
copies[a] = a
return a
}
copy.Run = originalPass(a, requires, copies, run)
return &copy
}
return clone(root)
}

// originalPass restores the analyzer identities that upstream Run functions
// use to look up prerequisite results. Copy the pass rather than changing the
// checker's pass, including when another adapter has installed an overlay.
func originalPass(a *analysis.Analyzer, requires []*analysis.Analyzer, copies map[*analysis.Analyzer]*analysis.Analyzer, run func(*analysis.Pass) (any, error)) func(*analysis.Pass) (any, error) {
return func(pass *analysis.Pass) (any, error) {
original := *pass
original.Analyzer = a
original.ResultOf = make(map[*analysis.Analyzer]any, len(requires))
for _, req := range requires {
original.ResultOf[req] = pass.ResultOf[copies[req]]
}
return run(&original)
}
}

func runScopedSSA(pass *analysis.Pass) (any, error) {
conf := pass.ResultOf[config.Analyzer].(*config.Config)
if !conf.IsPkgInScope(pass.Pkg) {
// The function-contract analyzer returns before reading SSA for these
// packages. Return the declared result type without constructing SSA.
return new(buildssa.SSA), nil
}
return buildssa.Analyzer.Run(pass)
}
82 changes: 82 additions & 0 deletions internal/analysis/nilaway/ssa_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package nilaway_test

import (
"fmt"
"os"
"slices"
"testing"

"github.com/stretchr/testify/require"
upstream "go.uber.org/nilaway"
"go.uber.org/nilaway/config"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/analysistest"
"golang.org/x/tools/go/analysis/checker"
"golang.org/x/tools/go/packages"

"github.com/nnutter/constable/internal/analysis/nilaway"
"github.com/nnutter/constable/internal/generated"
)

// Compare at the analyzer boundary against unmodified upstream analysis with
// the same generated-file policy. Inferred contracts and facts cross package
// boundaries in the fixture, so dropping useful SSA can change diagnostics.
func TestScopedSSAMatchesUpstream(t *testing.T) {
pkgs, err := packages.Load(&packages.Config{
Mode: packages.LoadAllSyntax,
Dir: analysistest.TestData(),
Env: append(os.Environ(), "GO111MODULE=off", "GOPATH="+analysistest.TestData()),
}, "scope/...")
require.NoError(t, err)
require.NotEmpty(t, pkgs)
require.Zero(t, packages.PrintErrors(pkgs))

cases := []struct {
name string
include string
exclude string
}{
{name: "all"},
{name: "module", include: "scope"},
{name: "client_only", include: "scope/client"},
{name: "library_only", include: "scope/lib"},
{name: "exclude_library", include: "scope", exclude: "scope/lib"},
{name: "excluded", include: "another/module"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
setIncludePkgs(t, tc.include)
exclude := config.Analyzer.Flags.Lookup(config.ExcludePkgsFlag)
require.NotNil(t, exclude)
previous := exclude.Value.String()
require.NoError(t, exclude.Value.Set(tc.exclude))
t.Cleanup(func() { require.NoError(t, exclude.Value.Set(previous)) })
want := analyzerDiagnostics(t, generated.Skip(upstream.Analyzer), pkgs)
got := analyzerDiagnostics(t, nilaway.Analyzer, pkgs)
require.Equal(t, want, got)
if tc.name == "module" {
require.NotEmpty(t, got, "the fixture must exercise reported nil flows")
}
if tc.name == "excluded" {
require.Empty(t, got)
}
})
}
}

func analyzerDiagnostics(t *testing.T, a *analysis.Analyzer, pkgs []*packages.Package) []string {
t.Helper()
graph, err := checker.Analyze([]*analysis.Analyzer{a}, pkgs, nil)
require.NoError(t, err)
var diagnostics []string
for act := range graph.All() {
require.NoError(t, act.Err)
if act.IsRoot {
for _, d := range act.Diagnostics {
diagnostics = append(diagnostics, fmt.Sprintf("%s: %s", act.Package.Fset.Position(d.Pos), d.Message))
}
}
}
slices.Sort(diagnostics)
return diagnostics
}
25 changes: 25 additions & 0 deletions internal/analysis/nilaway/testdata/src/scope/client/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package client

import (
"strings"

"scope/lib"
)

func Safe() int {
value := 1
return *lib.Identity(&value)
}

func Unsafe() int {
return *lib.Missing()
}

func Local() int {
var p *int
return *p
}

func StandardLibrary() string {
return strings.TrimSpace(" safe ")
}
14 changes: 14 additions & 0 deletions internal/analysis/nilaway/testdata/src/scope/lib/lib.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package lib

// Identity's nonnil-to-nonnil contract is inferred from SSA.
func Identity(p *int) *int {
return p
}

func Missing() *int {
return nil
}

func Dereference() int {
return *Missing()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package client

import "suppression/lib"

func CrossPackage() int {
return *lib.Missing()
}

func SuppressedUpstream() int {
return lib.Dereference(nil)
}

func Unsuppressed() int {
var p *int
return *p
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package client

// This file has comments but no suppression directive.
func Safe(p *int) int {
if p == nil {
return 0
}
return *p
}
25 changes: 25 additions & 0 deletions internal/analysis/nilaway/testdata/src/suppression/lib/lib.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package lib

func Missing() *int {
return nil //nolint:nilaway
}

func Dereference(p *int) int {
return *p //nolint:nilaway
}

func Inline() int {
var p *int
return *p //nolint:nilaway
}

func Block() int {
var p *int
return *p /*nolint:nilaway*/
}

//nolint:all
func Declaration() int {
var p *int
return *p
}
55 changes: 55 additions & 0 deletions internal/driver/ambient_git_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package driver_test

import (
"os"
"path/filepath"
"strings"
"testing"

"github.com/stretchr/testify/require"
"golang.org/x/tools/go/analysis"

"github.com/nnutter/constable/internal/driver"
)

// git rebase --exec exports GIT_DIR for the repository being rebased. Git
// treats that variable as stronger than -C, so fixture setup must not follow it.
func TestFixLeavesAmbientRepositoryUntouched(t *testing.T) {
outer := t.TempDir()
runGit(t, outer, "init", "-q")
runGit(t, outer, "config", "user.email", "keep@example.com")
runGit(t, outer, "config", "user.name", "Keep")
require.NoError(t, os.WriteFile(filepath.Join(outer, "keep.txt"), []byte("keep\n"), 0o644))
runGit(t, outer, "add", ".")
runGit(t, outer, "commit", "-qm", "keep")
worktree := t.TempDir()
runGit(t, outer, "worktree", "add", "--detach", "-q", worktree)
common := strings.TrimSpace(runGit(t, worktree, "rev-parse", "--path-format=absolute", "--git-common-dir"))
gitDir := strings.TrimSpace(runGit(t, worktree, "rev-parse", "--absolute-git-dir"))
configPath := filepath.Join(common, "config")
before, err := os.ReadFile(configPath)
require.NoError(t, err)

t.Setenv("GIT_DIR", gitDir)
t.Setenv("GIT_PREFIX", "")

dir := t.TempDir()
require.NoError(t, os.WriteFile(filepath.Join(dir, "go.mod"), []byte("module example.com/fix\n\ngo 1.25\n"), 0o644))
require.NoError(t, os.WriteFile(filepath.Join(dir, "a.go"), []byte("package fix\nfunc a() { Broken := 1; _ = Broken }\n"), 0o644))
runGit(t, dir, "init", "-q")
runGit(t, dir, "config", "user.email", "test@example.com")
runGit(t, dir, "config", "user.name", "Test")
runGit(t, dir, "add", ".")
runGit(t, dir, "commit", "-qm", "initial")
t.Chdir(dir)
code := driver.Run([]string{"."}, []*analysis.Analyzer{fixAnalyzer("", false, false, false)}, driver.Options{Fix: true, Context: -1})
require.Equal(t, 0, code)
after, err := os.ReadFile("a.go")
require.NoError(t, err)
require.Contains(t, string(after), "Fixed")

config, err := os.ReadFile(configPath)
require.NoError(t, err)
require.Equal(t, string(before), string(config))
runGit(t, worktree, "status", "--porcelain")
}
Loading
Loading