1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use std::mem::replace;

use crate::{Span, DUMMY_SP};

/// Helper for people who are working on `VisitMut`.
///
///
/// This trait is implemented for ast nodes. If not and you need it, please file
/// an issue.
pub trait Take: Sized {
    fn take(&mut self) -> Self {
        replace(self, Self::dummy())
    }

    /// Create a dummy value of this type.
    fn dummy() -> Self;

    /// Mutate `self` using `op`, which accepts owned data.
    #[inline]
    fn map_with_mut<F>(&mut self, op: F)
    where
        F: FnOnce(Self) -> Self,
    {
        let dummy = Self::dummy();
        let cur_val = replace(self, dummy);
        let new_val = op(cur_val);
        let _dummy = replace(self, new_val);
    }
}

impl<T> Take for Option<T> {
    fn dummy() -> Self {
        None
    }
}

impl<T> Take for Box<T>
where
    T: Take,
{
    fn dummy() -> Self {
        Box::new(T::dummy())
    }
}

impl<T> Take for Vec<T> {
    fn dummy() -> Self {
        vec![]
    }
}

impl Take for Span {
    fn dummy() -> Self {
        DUMMY_SP
    }
}