1 // FIXME: Ideally these suggestions would be fixed via rustfix. Blocked by rust-lang/rust#53934
3 #![warn(clippy::significant_drop_in_scrutinee)]
4 #![allow(dead_code, unused_assignments)]
5 #![allow(clippy::match_single_binding, clippy::single_match, clippy::uninlined_format_args)]
7 use std::num::ParseIntError;
9 use std::sync::atomic::{AtomicU64, Ordering};
10 use std::sync::RwLock;
11 use std::sync::{Mutex, MutexGuard};
16 fn foo(&self) -> bool {
23 fn should_not_trigger_lint_with_mutex_guard_outside_match() {
24 let mutex = Mutex::new(State {});
26 // Should not trigger lint because the temporary should drop at the `;` on line before the match
27 let is_foo = mutex.lock().unwrap().foo();
30 mutex.lock().unwrap().bar();
36 fn should_not_trigger_lint_with_mutex_guard_when_taking_ownership_in_match() {
37 let mutex = Mutex::new(State {});
39 // Should not trigger lint because the scrutinee is explicitly returning the MutexGuard,
40 // so its lifetime should not be surprising.
44 mutex.lock().unwrap().bar();
50 fn should_trigger_lint_with_mutex_guard_in_match_scrutinee() {
51 let mutex = Mutex::new(State {});
53 // Should trigger lint because the lifetime of the temporary MutexGuard is surprising because it
54 // is preserved until the end of the match, but there is no clear indication that this is the
56 match mutex.lock().unwrap().foo() {
58 mutex.lock().unwrap().bar();
64 fn should_not_trigger_lint_with_mutex_guard_in_match_scrutinee_when_lint_allowed() {
65 let mutex = Mutex::new(State {});
67 // Lint should not be triggered because it is "allowed" below.
68 #[allow(clippy::significant_drop_in_scrutinee)]
69 match mutex.lock().unwrap().foo() {
71 mutex.lock().unwrap().bar();
77 fn should_not_trigger_lint_for_insignificant_drop() {
78 // Should not trigger lint because there are no temporaries whose drops have a significant
80 match 1u64.to_string().is_empty() {
82 println!("It was empty")
85 println!("It was not empty")
90 struct StateWithMutex {
94 struct MutexGuardWrapper<'a> {
95 mg: MutexGuard<'a, u64>,
98 impl<'a> MutexGuardWrapper<'a> {
99 fn get_the_value(&self) -> u64 {
104 struct MutexGuardWrapperWrapper<'a> {
105 mg: MutexGuardWrapper<'a>,
108 impl<'a> MutexGuardWrapperWrapper<'a> {
109 fn get_the_value(&self) -> u64 {
114 impl StateWithMutex {
115 fn lock_m(&self) -> MutexGuardWrapper<'_> {
117 mg: self.m.lock().unwrap(),
121 fn lock_m_m(&self) -> MutexGuardWrapperWrapper<'_> {
122 MutexGuardWrapperWrapper {
123 mg: MutexGuardWrapper {
124 mg: self.m.lock().unwrap(),
129 fn foo(&self) -> bool {
136 fn should_trigger_lint_with_wrapped_mutex() {
137 let s = StateWithMutex { m: Mutex::new(1) };
139 // Should trigger lint because a temporary contains a type with a significant drop and its
140 // lifetime is not obvious. Additionally, it is not obvious from looking at the scrutinee that
141 // the temporary contains such a type, making it potentially even more surprising.
142 match s.lock_m().get_the_value() {
144 println!("Got 1. Is it still 1?");
145 println!("{}", s.lock_m().get_the_value());
148 println!("Got 2. Is it still 2?");
149 println!("{}", s.lock_m().get_the_value());
153 println!("All done!");
156 fn should_trigger_lint_with_double_wrapped_mutex() {
157 let s = StateWithMutex { m: Mutex::new(1) };
159 // Should trigger lint because a temporary contains a type which further contains a type with a
160 // significant drop and its lifetime is not obvious. Additionally, it is not obvious from
161 // looking at the scrutinee that the temporary contains such a type, making it potentially even
163 match s.lock_m_m().get_the_value() {
165 println!("Got 1. Is it still 1?");
166 println!("{}", s.lock_m().get_the_value());
169 println!("Got 2. Is it still 2?");
170 println!("{}", s.lock_m().get_the_value());
174 println!("All done!");
181 #[clippy::has_significant_drop]
182 struct CounterWrapper<'a> {
183 counter: &'a Counter,
186 impl<'a> CounterWrapper<'a> {
187 fn new(counter: &Counter) -> CounterWrapper {
188 counter.i.fetch_add(1, Ordering::Relaxed);
189 CounterWrapper { counter }
193 impl<'a> Drop for CounterWrapper<'a> {
195 self.counter.i.fetch_sub(1, Ordering::Relaxed);
200 fn temp_increment(&self) -> Vec<CounterWrapper> {
201 vec![CounterWrapper::new(self), CounterWrapper::new(self)]
205 fn should_trigger_lint_for_vec() {
206 let counter = Counter { i: AtomicU64::new(0) };
208 // Should trigger lint because the temporary in the scrutinee returns a collection of types
209 // which have significant drops. The types with significant drops are also non-obvious when
210 // reading the expression in the scrutinee.
211 match counter.temp_increment().len() {
213 let current_count = counter.i.load(Ordering::Relaxed);
214 println!("Current count {}", current_count);
215 assert_eq!(current_count, 0);
223 struct StateWithField {
227 // Should trigger lint only on the type in the tuple which is created using a temporary
228 // with a significant drop. Additionally, this test ensures that the format of the tuple
229 // is preserved correctly in the suggestion.
230 fn should_trigger_lint_for_tuple_in_scrutinee() {
231 let mutex1 = Mutex::new(StateWithField { s: "one".to_owned() });
234 match (mutex1.lock().unwrap().s.len(), true) {
237 mutex1.lock().unwrap().s.len();
243 match (true, mutex1.lock().unwrap().s.len(), true) {
246 mutex1.lock().unwrap().s.len();
252 let mutex2 = Mutex::new(StateWithField { s: "two".to_owned() });
253 match (mutex1.lock().unwrap().s.len(), true, mutex2.lock().unwrap().s.len()) {
256 mutex1.lock().unwrap().s.len();
257 mutex2.lock().unwrap().s.len();
263 let mutex3 = Mutex::new(StateWithField { s: "three".to_owned() });
264 match mutex3.lock().unwrap().s.as_str() {
267 mutex1.lock().unwrap().s.len();
268 mutex2.lock().unwrap().s.len();
274 match (true, mutex3.lock().unwrap().s.as_str()) {
277 mutex1.lock().unwrap().s.len();
278 mutex2.lock().unwrap().s.len();
286 // Should trigger lint when either side of a binary operation creates a temporary with a
288 // To avoid potential unnecessary copies or creating references that would trigger the significant
289 // drop problem, the lint recommends moving the entire binary operation.
290 fn should_trigger_lint_for_accessing_field_in_mutex_in_one_side_of_binary_op() {
291 let mutex = Mutex::new(StateWithField { s: "state".to_owned() });
293 match mutex.lock().unwrap().s.len() > 1 {
295 mutex.lock().unwrap().s.len();
300 match 1 < mutex.lock().unwrap().s.len() {
302 mutex.lock().unwrap().s.len();
308 // Should trigger lint when both sides of a binary operation creates a temporary with a
310 // To avoid potential unnecessary copies or creating references that would trigger the significant
311 // drop problem, the lint recommends moving the entire binary operation.
312 fn should_trigger_lint_for_accessing_fields_in_mutex_in_both_sides_of_binary_op() {
313 let mutex1 = Mutex::new(StateWithField { s: "state".to_owned() });
314 let mutex2 = Mutex::new(StateWithField {
315 s: "statewithfield".to_owned(),
318 match mutex1.lock().unwrap().s.len() < mutex2.lock().unwrap().s.len() {
322 mutex1.lock().unwrap().s.len(),
323 mutex2.lock().unwrap().s.len()
329 match mutex1.lock().unwrap().s.len() >= mutex2.lock().unwrap().s.len() {
333 mutex1.lock().unwrap().s.len(),
334 mutex2.lock().unwrap().s.len()
341 fn should_not_trigger_lint_for_closure_in_scrutinee() {
342 let mutex1 = Mutex::new(StateWithField { s: "one".to_owned() });
344 let get_mutex_guard = || mutex1.lock().unwrap().s.len();
346 // Should not trigger lint because the temporary with a significant drop will be dropped
347 // at the end of the closure, so the MutexGuard will be unlocked and not have a potentially
348 // surprising lifetime.
349 match get_mutex_guard() > 1 {
351 mutex1.lock().unwrap().s.len();
357 fn should_trigger_lint_for_return_from_closure_in_scrutinee() {
358 let mutex1 = Mutex::new(StateWithField { s: "one".to_owned() });
360 let get_mutex_guard = || mutex1.lock().unwrap();
362 // Should trigger lint because the temporary with a significant drop is returned from the
363 // closure but not used directly in any match arms, so it has a potentially surprising lifetime.
364 match get_mutex_guard().s.len() > 1 {
366 mutex1.lock().unwrap().s.len();
372 fn should_trigger_lint_for_return_from_match_in_scrutinee() {
373 let mutex1 = Mutex::new(StateWithField { s: "one".to_owned() });
374 let mutex2 = Mutex::new(StateWithField { s: "two".to_owned() });
378 // Should trigger lint because the nested match within the scrutinee returns a temporary with a
379 // significant drop is but not used directly in any match arms, so it has a potentially
380 // surprising lifetime.
382 100 => mutex1.lock().unwrap(),
383 _ => mutex2.lock().unwrap(),
390 mutex1.lock().unwrap().s.len();
393 println!("nothing to do here");
398 fn should_trigger_lint_for_return_from_if_in_scrutinee() {
399 let mutex1 = Mutex::new(StateWithField { s: "one".to_owned() });
400 let mutex2 = Mutex::new(StateWithField { s: "two".to_owned() });
404 // Should trigger lint because the nested if-expression within the scrutinee returns a temporary
405 // with a significant drop is but not used directly in any match arms, so it has a potentially
406 // surprising lifetime.
408 mutex1.lock().unwrap()
410 mutex2.lock().unwrap()
417 mutex1.lock().unwrap().s.len();
423 fn should_not_trigger_lint_for_if_in_scrutinee() {
424 let mutex = Mutex::new(StateWithField { s: "state".to_owned() });
428 // Should not trigger the lint because the temporary with a significant drop *is* dropped within
429 // the body of the if-expression nested within the match scrutinee, and therefore does not have
430 // a potentially surprising lifetime.
432 mutex.lock().unwrap().s.len() > 1
437 mutex.lock().unwrap().s.len();
443 struct StateWithBoxedMutexGuard {
447 impl StateWithBoxedMutexGuard {
448 fn new() -> StateWithBoxedMutexGuard {
449 StateWithBoxedMutexGuard { u: Mutex::new(42) }
451 fn lock(&self) -> Box<MutexGuard<u64>> {
452 Box::new(self.u.lock().unwrap())
456 fn should_trigger_lint_for_boxed_mutex_guard() {
457 let s = StateWithBoxedMutexGuard::new();
459 // Should trigger lint because a temporary Box holding a type with a significant drop in a match
460 // scrutinee may have a potentially surprising lifetime.
461 match s.lock().deref().deref() {
462 0 | 1 => println!("Value was less than 2"),
463 _ => println!("Value is {}", s.lock().deref()),
467 struct StateStringWithBoxedMutexGuard {
471 impl StateStringWithBoxedMutexGuard {
472 fn new() -> StateStringWithBoxedMutexGuard {
473 StateStringWithBoxedMutexGuard {
474 s: Mutex::new("A String".to_owned()),
477 fn lock(&self) -> Box<MutexGuard<String>> {
478 Box::new(self.s.lock().unwrap())
482 fn should_trigger_lint_for_boxed_mutex_guard_holding_string() {
483 let s = StateStringWithBoxedMutexGuard::new();
485 let matcher = String::from("A String");
487 // Should trigger lint because a temporary Box holding a type with a significant drop in a match
488 // scrutinee may have a potentially surprising lifetime.
489 match s.lock().deref().deref() {
490 matcher => println!("Value is {}", s.lock().deref()),
491 _ => println!("Value was not a match"),
495 struct StateWithIntField {
499 // Should trigger lint when either side of an assign expression contains a temporary with a
500 // significant drop, because the temporary's lifetime will be extended to the end of the match.
501 // To avoid potential unnecessary copies or creating references that would trigger the significant
502 // drop problem, the lint recommends moving the entire binary operation.
503 fn should_trigger_lint_in_assign_expr() {
504 let mutex = Mutex::new(StateWithIntField { i: 10 });
508 match mutex.lock().unwrap().i = i {
510 println!("{}", mutex.lock().unwrap().i);
514 match i = mutex.lock().unwrap().i {
516 println!("{}", mutex.lock().unwrap().i);
520 match mutex.lock().unwrap().i += 1 {
522 println!("{}", mutex.lock().unwrap().i);
526 match i += mutex.lock().unwrap().i {
528 println!("{}", mutex.lock().unwrap().i);
535 Foo(Option<Box<RecursiveEnum>>),
539 enum GenericRecursiveEnum<T> {
540 Foo(T, Option<Box<GenericRecursiveEnum<T>>>),
543 fn should_not_cause_stack_overflow() {
544 // Test that when a type recursively contains itself, a stack overflow does not occur when
545 // checking sub-types for significant drops.
546 let f = RecursiveEnum::Foo(Some(Box::new(RecursiveEnum::Foo(None))));
548 RecursiveEnum::Foo(Some(f)) => {
551 RecursiveEnum::Foo(f) => {
556 let f = GenericRecursiveEnum::Foo(1u64, Some(Box::new(GenericRecursiveEnum::Foo(2u64, None))));
558 GenericRecursiveEnum::Foo(i, Some(f)) => {
559 println!("{} {:?}", i, f)
561 GenericRecursiveEnum::Foo(i, f) => {
562 println!("{} {:?}", i, f)
567 fn should_not_produce_lint_for_try_desugar() -> Result<u64, ParseIntError> {
568 // TryDesugar (i.e. using `?` for a Result type) will turn into a match but is out of scope
570 let rwlock = RwLock::new("1".to_string());
571 let result = rwlock.read().unwrap().parse::<u64>()?;
572 println!("{}", result);
573 rwlock.write().unwrap().push('2');
577 struct ResultReturner {
581 impl ResultReturner {
582 fn to_number(&self) -> Result<i64, ParseIntError> {
583 self.s.parse::<i64>()
587 fn should_trigger_lint_for_non_ref_move_and_clone_suggestion() {
588 let rwlock = RwLock::<ResultReturner>::new(ResultReturner { s: "1".to_string() });
589 match rwlock.read().unwrap().to_number() {
590 Ok(n) => println!("Converted to number: {}", n),
591 Err(e) => println!("Could not convert {} to number", e),
595 fn should_trigger_lint_for_read_write_lock_for_loop() {
596 // For-in loops desugar to match expressions and are prone to the type of deadlock this lint is
597 // designed to look for.
598 let rwlock = RwLock::<Vec<String>>::new(vec!["1".to_string()]);
599 for s in rwlock.read().unwrap().iter() {
604 fn do_bar(mutex: &Mutex<State>) {
605 mutex.lock().unwrap().bar();
608 fn should_trigger_lint_without_significant_drop_in_arm() {
609 let mutex = Mutex::new(State {});
611 // Should trigger lint because the lifetime of the temporary MutexGuard is surprising because it
612 // is preserved until the end of the match, but there is no clear indication that this is the
614 match mutex.lock().unwrap().foo() {
615 true => do_bar(&mutex),
620 fn should_not_trigger_on_significant_iterator_drop() {
621 let lines = std::io::stdin().lines();
623 println!("foo: {}", line.unwrap());