aboutsummaryrefslogtreecommitdiff
path: root/src/transform.rs
blob: c56bec155a5801dfc9a20556329d661c697f4fb8 (plain)
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
use std::{
    collections::{HashMap, HashSet},
    rc::Rc,
};

use proc_macro2::Span;
use quote::quote;
use syn::{
    spanned::Spanned, GenericArgument, Generics, Ident, PathArguments, TraitBound, Type,
    TypeParamBound, TypePath, TypeReference, TypeTraitObject, WherePredicate,
};

use crate::{
    filter_map_assoc_paths, match_assoc_type,
    parse_assoc_type::{BoxType, DestType},
    parse_attrs::Convert,
    syn_utils::{iter_path, iter_type, type_arguments_mut},
    trait_sig::{MethodError, TypeTransform},
};

pub struct TypeConverter {
    pub assoc_type_conversions: HashMap<Ident, DestType>,
    pub collections: HashMap<Ident, usize>,
    pub trait_ident: Ident,
    pub type_conversions: HashMap<Type, Rc<Convert>>,
    pub used_conversions: HashSet<Type>,
}

#[derive(Debug)]
pub enum TransformError {
    AssocTypeWithoutDestType,
    UnsupportedType,
    ExpectedAtLeastNTypes(usize),
    AssocTypeAfterFirstNTypes(usize, Ident),
    QualifiedAssociatedType,
    SelfQualifiedAsOtherTrait,
}

impl TypeConverter {
    /// A return type of Some(1) means that the type implements
    /// IntoIterator<Item=T1> and FromIterator<T1>
    /// with T1 being its first generic type parameter.
    ///
    /// A return type of Some(2) means that the type implements
    /// IntoIterator<Item=(T1, T2)> and FromIterator<(T1, T2)>
    /// with T1 and T2 being its first two generic type parameters.
    ///
    /// ... etc. A return type of None means the type isn't recognized.
    #[rustfmt::skip]
    fn get_collection_type_count(&self, ident: &Ident) -> Option<usize> {
        if let Some(count) = self.collections.get(ident) {
            return Some(*count);
        }

        // when adding a type here don't forget to document it in the README
        if ident == "Vec"        { return Some(1); }
        if ident == "VecDeque"   { return Some(1); }
        if ident == "LinkedList" { return Some(1); }
        if ident == "HashSet"    { return Some(1); }
        if ident == "BinaryHeap" { return Some(1); }
        if ident == "BTreeSet"   { return Some(1); }
        if ident == "HashMap"    { return Some(2); }
        if ident == "BTreeMap"   { return Some(2); }
        None
    }

    pub fn convert_type(
        &mut self,
        type_: &mut Type,
    ) -> Result<TypeTransform, (Span, TransformError)> {
        if let Some(conv) = self.type_conversions.get(type_) {
            self.used_conversions.insert(conv.original_type.clone());
            *type_ = conv.dest_type.clone();
            return Ok(TypeTransform::Verbatim(conv.clone()));
        }
        if !iter_type(type_).any(match_assoc_type) {
            return Ok(TypeTransform::NoOp);
        }

        if let Type::Tuple(tuple) = type_ {
            let mut types = Vec::new();
            for elem in &mut tuple.elems {
                types.push(self.convert_type(elem)?);
            }
            return Ok(TypeTransform::Tuple(types));
        } else if let Type::Reference(TypeReference {
            lifetime: None,
            mutability: Some(_),
            elem,
            ..
        }) = type_
        {
            if let Type::TraitObject(TypeTraitObject {
                dyn_token: Some(_),
                bounds,
            }) = elem.as_mut()
            {
                if bounds.len() == 1 {
                    if let TypeParamBound::Trait(bound) = &mut bounds[0] {
                        if bound.path.segments.len() == 1 {
                            let first = &mut bound.path.segments[0];
                            if first.ident == "Iterator" {
                                if let PathArguments::AngleBracketed(args) = &mut first.arguments {
                                    if args.args.len() == 1 {
                                        if let GenericArgument::Binding(binding) = &mut args.args[0]
                                        {
                                            if binding.ident == "Item"
                                                && iter_type(&binding.ty).any(match_assoc_type)
                                            {
                                                let inner = self.convert_type(&mut binding.ty)?;
                                                let box_type = BoxType {
                                                    inner: quote! {#elem},
                                                    placeholder_lifetime: true,
                                                };
                                                *type_ = Type::Verbatim(quote! {#box_type});
                                                return Ok(TypeTransform::Iterator(
                                                    box_type,
                                                    inner.into(),
                                                ));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if let Type::Path(TypePath {
            path,
            qself: Some(qself),
        }) = type_
        {
            if let Type::Path(self_path) = qself.ty.as_ref() {
                if self_path.path.segments[0].ident == "Self" {
                    if !self_path.path.is_ident("Self") {
                        return Err((self_path.span(), TransformError::QualifiedAssociatedType));
                    }

                    if qself.position == 1
                        && path.segments.len() == 2
                        && path.segments[0].arguments.is_empty()
                        && path.segments[0].ident == self.trait_ident
                    {
                        let ident = &path.segments[1].ident;
                        let dest_type =
                            self.assoc_type_conversions.get(ident).ok_or_else(|| {
                                (ident.span(), TransformError::AssocTypeWithoutDestType)
                            })?;
                        *type_ = dest_type.get_dest();
                        return Ok(dest_type.type_transformation());
                    }

                    return Err((type_.span(), TransformError::SelfQualifiedAsOtherTrait));
                }
            }
        } else if let Type::Path(TypePath { path, qself: None }) = type_ {
            if path.segments[0].ident == "Self" {
                if path.segments.len() == 2 {
                    let ident = &path.segments.last().unwrap().ident;
                    let dest_type = self
                        .assoc_type_conversions
                        .get(ident)
                        .ok_or_else(|| (ident.span(), TransformError::AssocTypeWithoutDestType))?;
                    *type_ = dest_type.get_dest();
                    return Ok(dest_type.type_transformation());
                }
            } else {
                let path_len = path.segments.len();
                let last_seg = path.segments.last_mut().unwrap();

                if let PathArguments::AngleBracketed(args) = &mut last_seg.arguments {
                    let mut args: Vec<_> = type_arguments_mut(&mut args.args).collect();

                    if path_len == 1 {
                        if let Some(type_count) = self.get_collection_type_count(&last_seg.ident) {
                            if args.len() < type_count {
                                return Err((
                                    last_seg.span(),
                                    TransformError::ExpectedAtLeastNTypes(type_count),
                                ));
                            }
                            for ty in args.iter().skip(type_count) {
                                if iter_type(ty).any(match_assoc_type) {
                                    return Err((
                                        ty.span(),
                                        TransformError::AssocTypeAfterFirstNTypes(
                                            type_count,
                                            last_seg.ident.clone(),
                                        ),
                                    ));
                                }
                            }
                            let mut transforms = Vec::new();
                            for arg in args {
                                transforms.push(self.convert_type(arg)?);
                            }
                            return Ok(TypeTransform::IntoIterMapCollect(transforms));
                        }
                    }

                    if args.len() == 1 {
                        if iter_type(args[0]).any(match_assoc_type)
                            && ((last_seg.ident == "Option" && path_len == 1)
                                || last_seg.ident == "Result")
                        {
                            return Ok(TypeTransform::Map(self.convert_type(args[0])?.into()));
                        }
                    } else if args.len() == 2
                        && path_len == 1
                        && (iter_type(args[0]).any(match_assoc_type)
                            || iter_type(args[1]).any(match_assoc_type))
                        && last_seg.ident == "Result"
                    {
                        return Ok(TypeTransform::Result(
                            self.convert_type(args[0])?.into(),
                            self.convert_type(args[1])?.into(),
                        ));
                    }
                }
            }
        }

        // the type contains an associated type but we
        // don't know how to deal with it so we abort
        Err((type_.span(), TransformError::UnsupportedType))
    }
}

pub fn dynamize_function_bounds(
    generics: &mut Generics,
    type_converter: &mut TypeConverter,
) -> Result<HashMap<Ident, Vec<TypeTransform>>, (Span, MethodError)> {
    let mut type_param_transforms = HashMap::new();

    for type_param in generics.type_params_mut() {
        for bound in &mut type_param.bounds {
            if let TypeParamBound::Trait(bound) = bound {
                dynamize_trait_bound(
                    bound,
                    type_converter,
                    &type_param.ident,
                    &mut type_param_transforms,
                )?;
            }
        }
    }

    if let Some(where_clause) = &mut generics.where_clause {
        for predicate in &mut where_clause.predicates {
            if let WherePredicate::Type(predicate_type) = predicate {
                if let Type::Path(path) = &mut predicate_type.bounded_ty {
                    if let Some(ident) = path.path.get_ident() {
                        for bound in &mut predicate_type.bounds {
                            if let TypeParamBound::Trait(bound) = bound {
                                dynamize_trait_bound(
                                    bound,
                                    type_converter,
                                    ident,
                                    &mut type_param_transforms,
                                )?;
                            }
                        }
                        continue;
                    }
                }

                // just to provide better error messages
                if let Some(assoc_type) =
                    iter_type(&predicate_type.bounded_ty).find_map(filter_map_assoc_paths)
                {
                    return Err((assoc_type.span(), MethodError::UnconvertedAssocType));
                }

                // just to provide better error messages
                for bound in &mut predicate_type.bounds {
                    if let TypeParamBound::Trait(bound) = bound {
                        if let Some(assoc_type) =
                            iter_path(&bound.path).find_map(filter_map_assoc_paths)
                        {
                            return Err((assoc_type.span(), MethodError::UnconvertedAssocType));
                        }
                    }
                }
            }
        }
    }

    Ok(type_param_transforms)
}

fn dynamize_trait_bound(
    bound: &mut TraitBound,
    type_converter: &mut TypeConverter,
    type_ident: &Ident,
    type_param_transforms: &mut HashMap<Ident, Vec<TypeTransform>>,
) -> Result<(), (Span, MethodError)> {
    if bound.path.segments.len() == 1 {
        let segment = &mut bound.path.segments[0];

        if let PathArguments::Parenthesized(args) = &mut segment.arguments {
            if segment.ident == "Fn" || segment.ident == "FnOnce" || segment.ident == "FnMut" {
                let mut transforms = Vec::new();
                for input_type in &mut args.inputs {
                    match type_converter.convert_type(input_type) {
                        Ok(ret_type) => {
                            transforms.push(ret_type);
                        }
                        Err((span, err)) => {
                            return Err((span, err.into()));
                        }
                    }
                }
                if transforms.iter().any(|t| !matches!(t, TypeTransform::NoOp)) {
                    type_param_transforms.insert(type_ident.clone(), transforms);
                }
            }
        }
    }
    if let Some(path) = iter_path(&bound.path)
        .filter_map(filter_map_assoc_paths)
        .next()
    {
        return Err((path.span(), MethodError::UnconvertedAssocType));
    }
    Ok(())
}