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
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ func badBlankAssign() {
_ = bw.Flush() // want `error return from Flush\(\) is discarded`
}

func deferBad() {
var sb strings.Builder
bw := bufio.NewWriter(&sb)
defer bw.Flush() // want `error return from Flush\(\) is discarded`
}

func good() {
var sb strings.Builder
bw := bufio.NewWriter(&sb)
Expand All @@ -44,3 +50,9 @@ func suppressed() {
tw := tabwriter.NewWriter(&sb, 0, 0, 1, ' ', 0)
tw.Flush() //nolint:uncheckedflushreturn
}

func deferSuppressed() {
var sb strings.Builder
bw := bufio.NewWriter(&sb)
defer bw.Flush() //nolint:uncheckedflushreturn
}
20 changes: 19 additions & 1 deletion pkg/linters/uncheckedflushreturn/uncheckedflushreturn.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func run(pass *analysis.Pass) (any, error) {
return nil, err
}

nodeFilter := []ast.Node{(*ast.ExprStmt)(nil), (*ast.AssignStmt)(nil)}
nodeFilter := []ast.Node{(*ast.ExprStmt)(nil), (*ast.AssignStmt)(nil), (*ast.DeferStmt)(nil)}
insp.Preorder(nodeFilter, func(n ast.Node) {
switch stmt := n.(type) {
case *ast.ExprStmt:
Expand All @@ -57,6 +57,12 @@ func run(pass *analysis.Pass) (any, error) {
return
}
checkDiscardedFlushAssign(pass, stmt, noLintIndex)
case *ast.DeferStmt:
position := pass.Fset.PositionFor(stmt.Pos(), false)
if filecheck.ShouldSkipFilename(position.Filename, generatedFiles) {
return
}
checkDiscardedFlushDefer(pass, stmt, noLintIndex)
}
})
return nil, nil
Expand Down Expand Up @@ -95,6 +101,18 @@ func checkDiscardedFlushAssign(pass *analysis.Pass, assign *ast.AssignStmt, noLi
reportUncheckedFlush(pass, call, noLintIndex)
}

// checkDiscardedFlushDefer flags defer x.Flush() statements where the error
// return is dropped when the deferred call executes.
func checkDiscardedFlushDefer(pass *analysis.Pass, stmt *ast.DeferStmt, noLintIndex nolint.DirectiveIndex) {
if stmt.Call == nil {
return
}
if !isFlushCallReturningError(pass, stmt.Call) {
return
}
reportUncheckedFlush(pass, stmt.Call, noLintIndex)
}

func reportUncheckedFlush(pass *analysis.Pass, call *ast.CallExpr, noLintIndex nolint.DirectiveIndex) {
position := pass.Fset.PositionFor(call.Pos(), false)
if nolint.HasDirectiveForLinter(position, noLintIndex, "uncheckedflushreturn") {
Expand Down
Loading