Skip to content
Open
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
8 changes: 7 additions & 1 deletion simple/s1024/s1024.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,13 @@ var (

func run(pass *analysis.Pass) (any, error) {
for node := range code.Matches(pass, checkTimeUntilQ) {
if sel, ok := node.(*ast.CallExpr).Fun.(*ast.SelectorExpr); ok {
// The fix rewrites 'x.Sub(time.Now())' into 'time.Until(x)', which only compiles
// when x is itself a time.Time. Sub is also reachable when x embeds a time.Time,
// or when x is a *time.Time; in both cases 'time.Until(x)' does not type-check.
// Naming the embedded field instead is not always possible either, because it can
// be unexported and declared in another package, so we keep the diagnostic and
// drop the fix.
if sel, ok := node.(*ast.CallExpr).Fun.(*ast.SelectorExpr); ok && code.IsOfTypeWithName(pass, sel.X, "time.Time") {
r := pattern.NodeToAST(checkTimeUntilR.Root, map[string]any{"arg": sel.X}).(ast.Node)
report.Report(pass, node, "should use time.Until instead of t.Sub(time.Now())",
report.FilterGenerated(),
Expand Down
14 changes: 14 additions & 0 deletions simple/s1024/testdata/go1.8/CheckTimeUntil/LimeTimeUntil.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,23 @@ package pkg

import "time"

type embedTime struct {
time.Time
}

func fn(t time.Time) {
t.Sub(time.Now()) //@ diag(`time.Until`)
t.Sub(t)
t2 := time.Now()
t.Sub(t2)
}

func fnEmbedded(t embedTime) {
// Sub is promoted from the embedded time.Time; 'time.Until(t)' would not compile.
t.Sub(time.Now()) //@ diag(`time.Until`)
}

func fnPointer(t *time.Time) {
// 'time.Until(t)' would not compile either, t needs to be dereferenced.
t.Sub(time.Now()) //@ diag(`time.Until`)
}
14 changes: 14 additions & 0 deletions simple/s1024/testdata/go1.8/CheckTimeUntil/LimeTimeUntil.go.golden
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,23 @@ package pkg

import "time"

type embedTime struct {
time.Time
}

func fn(t time.Time) {
time.Until(t) //@ diag(`time.Until`)
t.Sub(t)
t2 := time.Now()
t.Sub(t2)
}

func fnEmbedded(t embedTime) {
// Sub is promoted from the embedded time.Time; 'time.Until(t)' would not compile.
t.Sub(time.Now()) //@ diag(`time.Until`)
}

func fnPointer(t *time.Time) {
// 'time.Until(t)' would not compile either, t needs to be dereferenced.
t.Sub(time.Now()) //@ diag(`time.Until`)
}