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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
#![allow(non_snake_case, unused_imports)]

extern crate proc_macro;

#[macro_use]
extern crate fstrings;

use ::proc_macro::{
    TokenStream,
};
use ::proc_macro2::{
    Span,
    TokenStream as TokenStream2,
};
use ::quote::{
    quote,
    quote_spanned,
};
use ::syn::{*,
    parse::{
        Parse,
        ParseStream,
    },
    spanned::Spanned,
};
use ::std::{*,
    convert::{TryInto, TryFrom},
    iter::FromIterator,
    result::Result,
};

#[macro_use]
mod macros;

#[inline]
fn take<T : Default> (x: &'_ mut T)
  -> T
{
    mem::replace(x, T::default())
}

#[proc_macro_attribute] pub
fn inheritable (params: TokenStream, input: TokenStream)
  -> TokenStream
{
    // === Parse / extraction logic ===
    #[cfg_attr(feature = "verbose-expansions",
        derive(Debug),
    )]
    #[allow(dead_code)] // dumb compiler...
    struct Trait {
        ident: Ident,
        methods: Vec<TraitItemMethod>,
    }

    impl Parse for Trait {
        fn parse (input: ParseStream) -> syn::Result<Self>
        {Ok({
            let ItemTrait {
                    ident,
                    items,
                    generics,
                    ..
                } = input.parse()?
            ;
            match (
                generics.type_params().next(),
                generics.lifetimes().next(),
                generics.const_params().next(),
            )
            {
                | (None, None, None) => {},

                | _ => parse_error!(
                    generics.span(),
                    "Trait generics are not supported (yet)",
                ),
            }
            let methods: Vec<TraitItemMethod> =
                items
                    .into_iter()
                    //  error on non-function items
                    .map(|trait_item| match trait_item {
                        | TraitItem::Method(method) => Ok(method),
                        | _ => parse_error!(
                            trait_item.span(),
                            "`#[inheritable]` currently only supports methods"
                        ),
                    })
                    // error on non-method functions
                    .map(|x| x.and_then(|method| {
                        let ref sig = method.sig;
                        let mut span = sig.ident.span();
                        match sig.inputs.iter().next() {
                            // & [mut] self
                            | Some(&FnArg::Receiver(Receiver {
                                reference: Some(_),
                                ..
                            }))
                            => {},

                            // self: & [mut] _
                            | Some(&FnArg::Typed(PatType {
                                ref pat,
                                ref ty,
                                ..
                            }))
                                if match (&**pat, &**ty) {
                                    | (
                                        &Pat::Ident(PatIdent { ref ident, .. }),
                                        &Type::Reference(_),
                                    ) => {
                                        ident == "self"
                                    },

                                    | _ => false,
                                }
                            => {},

                            // otherwise
                            | opt_arg => {
                                if let Some(arg) = opt_arg {
                                    span = arg.span();
                                }
                                parse_error!(span, concat!(
                                    "associated function requires a ",
                                    "`&self` or `&mut self` receiver",
                                ));
                            },
                        }
                        Ok(method)
                    }))
                    .collect::<Result<_, _>>()?
            ;
            Self {
                ident,
                methods,
            }
        })}
    }


    set_output!( render => ret );

    debug!(concat!(
        "-------------------------\n",
        "#[inheritable({params})]\n",
        "{input}\n",
    ), params=params, input=input);


    // === This macro does not expect params ===
    let params = TokenStream2::from(params);
    if params.clone().into_iter().next().is_some() {
        error!(params.span(), "Unexpected parameter(s)");
    }

    // === Parse the input ===
    let Trait {
        ident: Trait,
        mut methods,
    } = {
        let input = input.clone();
        parse_macro_input!(input)
    };


    // === Render the decorated trait itself (as is) ===
    ret.extend(input);


    // === Render the helper `Inherits#Trait` trait ===
    let InheritsTrait = Ident::new(&f!(
        "__Inherits{Trait}__"
    ), Span::call_site());

    ret.extend({
        // Due to a bug in `quote!`, we need to render
        // `#[doc(hidden)]`
        // manually
        use ::proc_macro::*;
        iter::once(TokenTree::Punct(Punct::new(
            '#',
        Spacing::Alone))).chain(TokenStream::from(::quote::quote! {
            [doc(hidden)]
        }))
    });
    render! {
        pub(in crate)
        trait #InheritsTrait {
            type __Parent__
                : #Trait
            ;
            fn __parent__ (self: &'_ Self)
              -> &'_ Self::__Parent__
            ;
            fn __parent_mut__ (self: &'_ mut Self)
              -> &'_ mut Self::__Parent__
            ;
        }
    };


    // === Render the default impl of `Trait` for `InheritsTrait` implemetors ===
    methods
        .iter_mut()
        .for_each(|method| {
            let &mut TraitItemMethod {
                sig: Signature {
                    ref ident,
                    ref generics,
                    ref mut inputs,
                    ..
                },
                ref mut default,
                ref mut semi_token,
                ref mut attrs,
            } = method;
            *attrs = vec![];
            *semi_token = None;
            let mut args: Vec<Ident> =
                Vec::with_capacity(
                    inputs
                        .len()
                        .saturating_sub(1)
                )
            ;
            let mut inputs_iter = take(inputs).into_iter();
            let mut parent_mb_mut = TokenStream2::default();
            *inputs =
                inputs_iter
                    .next()
                    .map(|first_arg| {
                        if match first_arg {
                            | FnArg::Receiver(Receiver {
                                ref mutability,
                                ..
                            }) => {
                                mutability.is_some()
                            },
                        // with box patterns we'd be able to merge both cases...
                            | FnArg::Typed(PatType { ref ty, .. }) => {
                                match &**ty {
                                    | &Type::Reference(TypeReference {
                                        ref mutability,
                                        ..
                                    }) => {
                                        mutability.is_some()
                                    },

                                    | _ => unreachable!(),
                                }
                            },
                        } {
                            parent_mb_mut = quote!( __parent_mut__ );
                        } else {
                            parent_mb_mut = quote!( __parent__ );
                        }
                        first_arg
                    })
                    .into_iter()
                    .chain(
                        inputs_iter
                            .zip(1 ..)
                            .map(|(mut arg, i)| match arg {
                                | FnArg::Typed(PatType { ref mut pat, .. }) => {
                                    let ident = Ident::new(&f!(
                                        "arg_{i}"
                                    ), Span::call_site());
                                    *pat = parse_quote! {
                                        #ident
                                    };
                                    args.push(ident);
                                    arg
                                },

                                | _ => unreachable!("Invalid method signature"),
                            })
                    )
                    .collect()
            ;
            let generics = generics.split_for_impl().1;
            let generics = generics.as_turbofish();
            // method body
            *default = Some(parse_quote! {
                {
                    /* 100% guaranteed unambiguous version */
                    // <
                    //     <Self as #InheritsTrait>::__Parent__
                    //     as #Trait
                    // >::#ident #generics (
                    //     #InheritsTrait :: #parent_mb_mut(self),
                    //     #(#args),*
                    // )
                    /* This should nevertheless also be unambiguous */
                    self.#parent_mb_mut()
                        .#ident #generics (
                            #(#args),*
                        )
                }
            });
        })
    ;
    let default_if_specialization =
        if cfg!(feature = "specialization") {
            quote!( default )
        } else {
            TokenStream2::new()
        }
    ;
    render! {
        impl<__inheritable_T__ : #InheritsTrait> #Trait
            for __inheritable_T__
        {
            #(
                #[inline]
                #default_if_specialization
                #methods
            )*
        }
    }


    debug!("=> becomes =>\n\n{}\n-------------------------\n", ret);


    ret
}

#[proc_macro_derive(Inheritance, attributes(inherits))] pub
fn derive_Inheritance (input: TokenStream)
  -> TokenStream
{
    debug!(concat!(
        "-------------------------\n",
        "#[derive(Inheritance)]\n",
        "{input}\n",
        "\n",
    ), input=input);

    set_output!( render => ret );

    let DeriveInput {
            ident: Struct,
            generics,
            data,
            ..
        } = parse_macro_input!(input)
    ;
    let fields = match data {
        | Data::Struct(DataStruct { fields, .. }) => fields,
        | Data::Enum(r#enum) => {
            error!(r#enum.enum_token.span(),
                "enums are not supported"
            );
        },
        | Data::Union(r#union) => {
            error!(r#union.union_token.span(),
                "unions are not supported"
            );
        },
    };
    let (mut iter1, mut iter2);
    let fields: &mut dyn Iterator<Item = Field> = match fields {
        | Fields::Unit => {
            iter1 = iter::empty();
            &mut iter1
        },
        | Fields::Unnamed(fields) => {
            iter2 = fields.unnamed.into_iter();
            &mut iter2
        },
        | Fields::Named(fields) => {
            iter2 = fields.named.into_iter();
            &mut iter2
        },
    };
    let ref inherits: Ident = parse_quote! {
        inherits
    };
    for (i, mut field) in fields.enumerate() {
        let (path_to_InheritsTrait, span) =
            match take(&mut field.attrs)
                    .into_iter()
                    .find_map(|attr| if attr.path.is_ident(inherits) { Some({
                        let span = attr.span();
                        attr.parse_args_with(Path::parse_mod_style)
                            .map(|mut path| {
                                let last =
                                    path.segments
                                        .iter_mut()
                                        .last()
                                        .expect("path has at least one segment")
                                ;
                                let ref Trait = last.ident;
                                let InheritsTrait = Ident::new(&f!(
                                    "__Inherits{Trait}__"
                                ), span);
                                *last = parse_quote! {
                                    #InheritsTrait
                                };
                                (path, span)
                            })
                    })} else {
                        None
                    })
            {
                | None => continue,
                | Some(Err(err)) => return err.to_compile_error().into(),
                | Some(Ok(inner)) => inner,
            }
        ;
        let field_name =
            if let Some(ref ident) = field.ident {
                quote! {
                    #ident
                }
            } else {
                let i: Index = i.into();
                quote! {
                    #i
                }
            }
        ;
        let ref FieldType = field.ty;
        let (impl_generics, ty_generics, where_clause) =
            generics.split_for_impl()
        ;
        render! { span =>
            impl #impl_generics #path_to_InheritsTrait
                for #Struct #ty_generics
            #where_clause
            {
                type __Parent__ = #FieldType;

                #[inline]
                fn __parent__ (self: &'_ Self)
                  -> &'_ Self::__Parent__
                {
                    &self.#field_name
                }

                #[inline]
                fn __parent_mut__ (self: &'_ mut Self)
                  -> &'_ mut Self::__Parent__
                {
                    &mut self.#field_name
                }
            }
        }
    }
    debug!("=> generates =>\n\n{}\n-------------------------\n", ret);
    ret
}