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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
//! Types for working with generics

use std::iter::Iterator;
use std::slice::Iter;

use syn;

use {FromGenericParam, FromGenerics, FromTypeParam, Result};

/// Extension trait for `GenericParam` to support getting values by variant.
///
/// # Usage
/// `darling::ast::Generics` needs a way to test its params array in order to iterate over type params.
/// Rather than require callers to use `darling::ast::GenericParam` in all cases, this trait makes that
/// polymorphic.
pub trait GenericParamExt {
    /// The type this GenericParam uses to represent type params and their bounds
    type TypeParam;
    type LifetimeDef;
    type ConstParam;

    /// If this GenericParam is a type param, get the underlying value.
    fn as_type_param(&self) -> Option<&Self::TypeParam> {
        None
    }

    /// If this GenericParam is a lifetime, get the underlying value.
    fn as_lifetime_def(&self) -> Option<&Self::LifetimeDef> {
        None
    }

    /// If this GenericParam is a const param, get the underlying value.
    fn as_const_param(&self) -> Option<&Self::ConstParam> {
        None
    }
}

impl GenericParamExt for syn::GenericParam {
    type TypeParam = syn::TypeParam;
    type LifetimeDef = syn::LifetimeDef;
    type ConstParam = syn::ConstParam;

    fn as_type_param(&self) -> Option<&Self::TypeParam> {
        if let syn::GenericParam::Type(ref val) = *self {
            Some(val)
        } else {
            None
        }
    }

    fn as_lifetime_def(&self) -> Option<&Self::LifetimeDef> {
        if let syn::GenericParam::Lifetime(ref val) = *self {
            Some(val)
        } else {
            None
        }
    }

    fn as_const_param(&self) -> Option<&Self::ConstParam> {
        if let syn::GenericParam::Const(ref val) = *self {
            Some(val)
        } else {
            None
        }
    }
}

impl GenericParamExt for syn::TypeParam {
    type TypeParam = syn::TypeParam;
    type LifetimeDef = ();
    type ConstParam = ();

    fn as_type_param(&self) -> Option<&Self::TypeParam> {
        Some(self)
    }
}

/// A mirror of `syn::GenericParam` which is generic over all its contents.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GenericParam<T = syn::TypeParam, L = syn::LifetimeDef, C = syn::ConstParam> {
    Type(T),
    Lifetime(L),
    Const(C),
}

impl<T: FromTypeParam> FromTypeParam for GenericParam<T> {
    fn from_type_param(type_param: &syn::TypeParam) -> Result<Self> {
        Ok(GenericParam::Type(FromTypeParam::from_type_param(
            type_param,
        )?))
    }
}

impl<T: FromTypeParam> FromGenericParam for GenericParam<T> {
    fn from_generic_param(param: &syn::GenericParam) -> Result<Self> {
        Ok(match *param {
            syn::GenericParam::Type(ref ty) => {
                GenericParam::Type(FromTypeParam::from_type_param(ty)?)
            }
            syn::GenericParam::Lifetime(ref val) => GenericParam::Lifetime(val.clone()),
            syn::GenericParam::Const(ref val) => GenericParam::Const(val.clone()),
        })
    }
}

impl<T, L, C> GenericParamExt for GenericParam<T, L, C> {
    type TypeParam = T;
    type LifetimeDef = L;
    type ConstParam = C;

    fn as_type_param(&self) -> Option<&T> {
        if let GenericParam::Type(ref val) = *self {
            Some(val)
        } else {
            None
        }
    }

    fn as_lifetime_def(&self) -> Option<&L> {
        if let GenericParam::Lifetime(ref val) = *self {
            Some(val)
        } else {
            None
        }
    }

    fn as_const_param(&self) -> Option<&C> {
        if let GenericParam::Const(ref val) = *self {
            Some(val)
        } else {
            None
        }
    }
}

/// A mirror of the `syn::Generics` type which can contain arbitrary representations
/// of params and where clauses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Generics<P, W = syn::WhereClause> {
    pub params: Vec<P>,
    pub where_clause: Option<W>,
}

impl<P, W> Generics<P, W> {
    pub fn type_params<'a>(&'a self) -> TypeParams<'a, P> {
        TypeParams(self.params.iter())
    }
}

impl<P: FromGenericParam> FromGenerics for Generics<P> {
    fn from_generics(generics: &syn::Generics) -> Result<Self> {
        Ok(Generics {
            params: generics
                .params
                .iter()
                .map(FromGenericParam::from_generic_param)
                .collect::<Result<Vec<P>>>()?,
            where_clause: generics.where_clause.clone(),
        })
    }
}

pub struct TypeParams<'a, P: 'a>(Iter<'a, P>);

impl<'a, P: GenericParamExt> Iterator for TypeParams<'a, P> {
    type Item = &'a <P as GenericParamExt>::TypeParam;

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.0.next();
        match next {
            None => None,
            Some(v) => match v.as_type_param() {
                Some(val) => Some(val),
                None => self.next(),
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use syn;

    use super::{GenericParam, Generics};
    use FromGenerics;

    #[test]
    fn generics() {
        let g: syn::Generics = parse_quote!(<T>);
        let deified: Generics<GenericParam<syn::Ident>> = FromGenerics::from_generics(&g).unwrap();
        assert!(deified.params.len() == 1);
        assert!(deified.where_clause.is_none());
    }
}