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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//! An attribute macro for easily writing [extension trait pattern](https://github.com/rust-lang/rfcs/blob/master/text/0445-extension-trait-conventions.md).
//!
//! ## Examples
//!
//! ```rust
//! use easy_ext::ext;
//!
//! #[ext(ResultExt)]
//! impl<T, E> Result<T, E> {
//!     pub fn err_into<U>(self) -> Result<T, U>
//!     where
//!         E: Into<U>,
//!     {
//!         self.map_err(Into::into)
//!     }
//! }
//! ```
//!
//! Code like this will be generated:
//!
//! ```rust
//! pub trait ResultExt<T, E> {
//!     fn err_into<U>(self) -> Result<T, U>
//!     where
//!         E: Into<U>;
//! }
//!
//! impl<T, E> ResultExt<T, E> for Result<T, E> {
//!     fn err_into<U>(self) -> Result<T, U>
//!     where
//!         E: Into<U>,
//!     {
//!         self.map_err(Into::into)
//!     }
//! }
//! ```
//!
//! See [`ext`] attribute for more details.
//!
//! [`ext`]: attr.ext.html

#![doc(html_root_url = "https://docs.rs/easy-ext/0.2.0")]
#![doc(test(
    no_crate_inject,
    attr(deny(warnings, rust_2018_idioms, single_use_lifetimes), allow(dead_code))
))]
#![forbid(unsafe_code)]
#![warn(rust_2018_idioms, unreachable_pub)]
// It cannot be included in the published code because these lints have false positives in the minimum required version.
#![cfg_attr(test, warn(single_use_lifetimes))]
#![warn(clippy::all)]
// mem::take requires Rust 1.40
#![allow(clippy::mem_replace_with_default)]

// older compilers require explicit `extern crate`.
#[allow(unused_extern_crates)]
extern crate proc_macro;

use std::{collections::hash_map::DefaultHasher, hash::Hasher, mem};

use proc_macro::TokenStream;
use quote::{format_ident, ToTokens};
use syn::{punctuated::Punctuated, visit_mut::VisitMut, *};

macro_rules! error {
    ($span:expr, $msg:expr) => {
        Err(syn::Error::new_spanned(&$span, $msg))
    };
    ($span:expr, $($tt:tt)*) => {
        error!($span, format!($($tt)*))
    };
}

/// An attribute macro for easily writing [extension trait pattern](https://github.com/rust-lang/rfcs/blob/master/text/0445-extension-trait-conventions.md).
///
/// ## Examples
///
/// ```rust
/// use easy_ext::ext;
///
/// #[ext(ResultExt)]
/// impl<T, E> Result<T, E> {
///     fn err_into<U>(self) -> Result<T, U>
///     where
///         E: Into<U>,
///     {
///         self.map_err(Into::into)
///     }
/// }
/// ```
///
/// Code like this will be generated:
///
/// ```rust
/// trait ResultExt<T, E> {
///     fn err_into<U>(self) -> Result<T, U>
///     where
///         E: Into<U>;
/// }
///
/// impl<T, E> ResultExt<T, E> for Result<T, E> {
///     fn err_into<U>(self) -> Result<T, U>
///     where
///         E: Into<U>,
///     {
///         self.map_err(Into::into)
///     }
/// }
/// ```
///
/// You can elide the trait name. Note that in this case, `#[ext]` assigns a random name, so you cannot import/export the generated trait.
///
/// ```rust
/// use easy_ext::ext;
///
/// #[ext]
/// impl<T, E> Result<T, E> {
///     fn err_into<U>(self) -> Result<T, U>
///     where
///         E: Into<U>,
///     {
///         self.map_err(Into::into)
///     }
/// }
/// ```
///
/// ### Visibility
///
/// * The generated extension trait inherits the visibility of the item in the original `impl`.
///
/// * The visibility of all the items in the original `impl` must be identical.
///
/// ### [Supertraits](https://doc.rust-lang.org/reference/items/traits.html#supertraits)
///
/// If you want the extension trait to be a subtrait of another trait,
/// add `Self: SubTrait` bound to the `where` clause.
///
/// ```rust
/// use easy_ext::ext;
///
/// #[ext(Ext)]
/// impl<T> T
/// where
///     Self: Default,
/// {
///     fn method(&self) {}
/// }
/// ```
///
/// ### Supported items
///
/// * [Methods](https://doc.rust-lang.org/book/ch05-03-method-syntax.html)
///
/// ```rust
/// use easy_ext::ext;
///
/// #[ext(Ext)]
/// impl<T> T {
///     fn method(&self) {}
/// }
/// ```
///
/// * [Associated constants](https://rust-lang-nursery.github.io/edition-guide/rust-2018/trait-system/associated-constants.html)
///
/// ```rust
/// use easy_ext::ext;
///
/// #[ext(Ext)]
/// impl<T> T {
///     const MSG: &'static str = "Hello!";
/// }
/// ```
#[proc_macro_attribute]
pub fn ext(args: TokenStream, input: TokenStream) -> TokenStream {
    let ext_ident = match syn::parse_macro_input!(args) {
        None => format_ident!("__ExtTrait{}", hash(&input)),
        Some(ext_ident) => ext_ident,
    };

    let mut item: ItemImpl = syn::parse_macro_input!(input);

    trait_from_item(&mut item, ext_ident)
        .map(ToTokens::into_token_stream)
        .map(|mut tokens| {
            tokens.extend(item.into_token_stream());
            tokens
        })
        .unwrap_or_else(|e| e.to_compile_error())
        .into()
}

fn determine_trait_generics<'a>(generics: &mut Generics, self_ty: &'a Type) -> Option<&'a Ident> {
    if let Type::Path(TypePath { path, qself: None }) = self_ty {
        if let Some(ident) = path.get_ident() {
            let i = generics.params.iter().position(|param| {
                if let GenericParam::Type(param) = param { param.ident == *ident } else { false }
            });
            if let Some(i) = i {
                let mut params = mem::replace(&mut generics.params, Punctuated::new())
                    .into_iter()
                    .collect::<Vec<_>>();
                let param = params.remove(i);
                generics.params = params.into_iter().collect();

                if let GenericParam::Type(TypeParam {
                    colon_token: Some(colon_token),
                    bounds,
                    ..
                }) = param
                {
                    generics.make_where_clause().predicates.push(WherePredicate::Type(
                        PredicateType {
                            lifetimes: None,
                            bounded_ty: syn::parse_quote!(Self),
                            colon_token,
                            bounds,
                        },
                    ));
                }

                return Some(ident);
            }
        }
    }
    None
}

fn trait_from_item(item: &mut ItemImpl, ident: Ident) -> Result<ItemTrait> {
    /// Replace `self_ty` with `Self`.
    struct ReplaceParam<'a> {
        self_ty: &'a Ident,
    }

    impl VisitMut for ReplaceParam<'_> {
        fn visit_ident_mut(&mut self, ident: &mut Ident) {
            if *ident == *self.self_ty {
                *ident = format_ident!("Self", span = ident.span());
            }
        }
    }

    let mut generics = item.generics.clone();
    let mut visitor = determine_trait_generics(&mut generics, &item.self_ty)
        .map(|self_ty| ReplaceParam { self_ty });

    if let Some(visitor) = &mut visitor {
        visitor.visit_generics_mut(&mut generics);
    }
    let ty_generics = generics.split_for_impl().1;
    let trait_ = parse_quote!(#ident #ty_generics);
    item.trait_ = Some((None, trait_, Default::default()));

    let mut vis = None;
    let mut items = Vec::with_capacity(item.items.len());
    item.items.iter_mut().try_for_each(|item| {
        trait_item_from_impl_item(item, &mut vis).map(|mut item| {
            if let Some(visitor) = &mut visitor {
                visitor.visit_trait_item_mut(&mut item);
            }
            items.push(item)
        })
    })?;

    let mut attrs = item.attrs.clone();
    attrs.push(parse_quote!(#[allow(patterns_in_fns_without_body)])); // mut self

    Ok(ItemTrait {
        attrs,
        vis: vis.unwrap_or(Visibility::Inherited),
        unsafety: item.unsafety,
        auto_token: None,
        trait_token: Default::default(),
        ident,
        generics,
        colon_token: None,
        supertraits: Punctuated::new(),
        brace_token: Default::default(),
        items,
    })
}

fn trait_item_from_impl_item(
    impl_item: &mut ImplItem,
    prev: &mut Option<Visibility>,
) -> Result<TraitItem> {
    fn compare_visibility(x: &Visibility, y: &Visibility) -> bool {
        match (x, y) {
            (Visibility::Public(_), Visibility::Public(_))
            | (Visibility::Crate(_), Visibility::Crate(_))
            | (Visibility::Inherited, Visibility::Inherited) => true,
            (Visibility::Restricted(x), Visibility::Restricted(y)) => {
                x.to_token_stream().to_string() == y.to_token_stream().to_string()
            }
            _ => false,
        }
    }

    fn check_visibility(
        current: Visibility,
        prev: &mut Option<Visibility>,
        span: &dyn ToTokens,
    ) -> Result<()> {
        match prev {
            None => *prev = Some(current),
            Some(prev) if compare_visibility(prev, &current) => {}
            Some(prev) => {
                if let Visibility::Inherited = prev {
                    return error!(current, "All items must have inherited visibility");
                } else {
                    return error!(
                        if let Visibility::Inherited = current { span } else { &current },
                        "All items must have a visibility of `{}`",
                        prev.to_token_stream(),
                    );
                }
            }
        }
        Ok(())
    }

    match impl_item {
        ImplItem::Const(item) => {
            let vis = mem::replace(&mut item.vis, Visibility::Inherited);
            check_visibility(vis, prev, &item.ident)?;
            Ok(TraitItem::Const(from_const(item)))
        }
        ImplItem::Method(item) => {
            let vis = mem::replace(&mut item.vis, Visibility::Inherited);
            check_visibility(vis, prev, &item.sig.ident)?;
            Ok(TraitItem::Method(from_method(item)))
        }
        _ => error!(impl_item, "unsupported item"),
    }
}

fn from_const(impl_const: &ImplItemConst) -> TraitItemConst {
    TraitItemConst {
        attrs: impl_const.attrs.clone(),
        const_token: Default::default(),
        ident: impl_const.ident.clone(),
        colon_token: Default::default(),
        ty: impl_const.ty.clone(),
        default: None,
        semi_token: Default::default(),
    }
}

fn from_method(impl_method: &ImplItemMethod) -> TraitItemMethod {
    let mut attrs = impl_method.attrs.clone();
    find_remove(&mut attrs, "inline"); // clippy::inline_fn_without_body

    TraitItemMethod {
        attrs,
        sig: impl_method.sig.clone(),
        default: None,
        semi_token: Some(Default::default()),
    }
}

fn find_remove(attrs: &mut Vec<Attribute>, ident: &str) -> Option<Attribute> {
    attrs.iter().position(|attr| attr.path.is_ident(ident)).map(|i| attrs.remove(i))
}

/// Returns the hash value of the input AST.
fn hash(input: &TokenStream) -> u64 {
    let mut hasher = DefaultHasher::new();
    hasher.write(input.to_string().as_bytes());
    hasher.finish()
}