|
| 1 | +// Copyright 2021 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +// This file contains tests for the lostcancel checker. |
| 6 | + |
| 7 | +//go:build go1.18 |
| 8 | + |
| 9 | +package typeparams |
| 10 | + |
| 11 | +import ( |
| 12 | + "context" |
| 13 | + "time" |
| 14 | +) |
| 15 | + |
| 16 | +var bg = context.Background() |
| 17 | + |
| 18 | +func _[T any]() { |
| 19 | + var _, cancel = context.WithCancel(bg) // want `the cancel function is not used on all paths \(possible context leak\)` |
| 20 | + if false { |
| 21 | + _ = cancel |
| 22 | + } |
| 23 | +} // want "this return statement may be reached without using the cancel var defined on line 19" |
| 24 | + |
| 25 | +func _[T any]() { |
| 26 | + _, cancel := context.WithCancel(bg) |
| 27 | + defer cancel() // ok |
| 28 | +} |
| 29 | + |
| 30 | +// User-defined Context that matches type "context.Context" |
| 31 | +type C1[P1 any, P2 any] interface { |
| 32 | + Deadline() (deadline time.Time, ok P1) |
| 33 | + Done() <-chan struct{} |
| 34 | + Err() error |
| 35 | + Value(key P2) P2 |
| 36 | +} |
| 37 | + |
| 38 | +func _(bg C1[bool, interface{}]) { |
| 39 | + ctx, _ := context.WithCancel(bg) // want "the cancel function returned by context.WithCancel should be called, not discarded, to avoid a context leak" |
| 40 | + ctx, _ = context.WithTimeout(bg, 0) // want "the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak" |
| 41 | + _ = ctx |
| 42 | +} |
| 43 | + |
| 44 | +// User-defined Context that doesn't match type "context.Context" |
| 45 | +type C2[P any] interface { |
| 46 | + WithCancel(parent C1[P, bool]) (ctx C1[P, bool], cancel func()) |
| 47 | +} |
| 48 | + |
| 49 | +func _(c C2[interface{}]) { |
| 50 | + ctx, _ := c.WithCancel(nil) // not "context.WithCancel()" |
| 51 | + _ = ctx |
| 52 | +} |
| 53 | + |
| 54 | +// Further regression test for Go issue 16143. |
| 55 | +func _() { |
| 56 | + type C[P any] struct{ f func() P } |
| 57 | + var x C[int] |
| 58 | + x.f() |
| 59 | +} |
0 commit comments