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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#![allow(clippy::match_ref_pats)] // clearer borrowing semantics

use ::std::{*,
    collections::HashMap as Map,
    ops::Not,
};
extern crate proc_macro; use ::proc_macro::{
    TokenStream,
};
use ::proc_macro2::{
    Span,
};
use ::quote::{
    quote_spanned,
};
use ::syn::{self,
    DeriveInput,
    Ident,
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
    spanned::Spanned,
    Visibility,
};

#[macro_use]
mod helper_macros;

macro_rules! error_spanned {($span:expr => $msg:expr) => ({
    let msg = syn::LitStr::new($msg, $span);
    return TokenStream::from(quote_spanned! { $span =>
        compile_error!(#msg);
    });
})}

#[cfg_attr(feature = "extra-traits",
    derive(Debug)
)]
#[derive(Default)]
struct DerivePinParams {
    drop: Option<Span>,
    unpin: Option<Span>,
}
impl Parse for DerivePinParams {
    fn parse (params: ParseStream<'_>) -> Result<Self, syn::Error>
    {
        let mut ret = Self::default();
        let idents = Punctuated::<Ident, syn::Token![,]>::
            parse_terminated(params)?
        ;
        for ident in idents {
            if ident == "Drop" {
                let prev_drop = ret.drop.replace(ident.span());
                if prev_drop.is_some() {
                    return Err(syn::Error::new(
                        ident.span(),
                        "Error, duplicated param `Drop`",
                    ));
                }
            } else if ident == "Unpin" {
                let prev_unpin = ret.unpin.replace(ident.span());
                if prev_unpin.is_some() {
                    return Err(syn::Error::new(
                        ident.span(),
                        "Error, duplicated param `Unpin`",
                    ));
                }
            } else {
                return Err(syn::Error::new(
                    ident.span(),
                    "Invalid parameter; expected `Drop` or `Unpin`",
                ));
            }
        }
        Ok(ret)
    }
}

#[cfg_attr(feature = "extra-traits",
    derive(Debug)
)]
struct SpecialField {
    pin_transitiveness: PinTransitiveness,
    vis: Visibility,
    ty: syn::Type,
}
#[cfg_attr(feature = "extra-traits",
    derive(Debug)
)]
enum PinTransitiveness {
    PinTransitive,
    Unpinned,
}
use PinTransitiveness::*;

impl SpecialField {
    fn collect_from<'fields> (
        fields: impl
            Iterator<Item = &'fields mut syn::Field> +
            iter::ExactSizeIterator +
        ,
    ) -> Result<
        Map<Ident, Self>,
        (Span, impl AsRef<str> + 'static),
    >
    {
        let mut ret = Map::with_capacity(fields.len());
        for (i, &mut syn::Field {
            attrs: ref mut field_attrs,
            ident: ref field_ident,
            ty: ref field_ty,
            ..
        })      in fields.enumerate()
        {
            let mut error_spanned = None;
            let mut had_attr = false;
            field_attrs.retain(|attr: &syn::Attribute| -> bool {
                macro_rules! ignore_attr {() => (return true)}
                if error_spanned.is_some() { ignore_attr!() }
                macro_rules! error_spanned {
                    ($span:expr =>
                        $msg:expr
                    ) => ({
                        error_spanned = Some(($span, $msg));
                        ignore_attr!()
                    });
                }

                // Ignore outer attributes (#![...])
                match &attr.style { //
                    | &syn::AttrStyle::Inner(_) => ignore_attr!(),
                    | &syn::AttrStyle::Outer => {},
                }

                // Ignore badly ill-formed attributes
                let attr_meta = if let Ok(attr_meta) = attr.parse_meta() {
                    attr_meta
                } else {
                    ignore_attr!();
                };

                // Treat only transitively_pinned / unpinned
                let pin_transitiveness = match &attr_meta { //
                    | &syn::Meta::Word(ref ident)
                    | &syn::Meta::NameValue(syn::MetaNameValue {
                        ref ident,
                        ..
                    })
                    | &syn::Meta::List(syn::MetaList {
                        ref ident,
                        ..
                    })
                    => if ident == "transitively_pinned" {
                        PinTransitive
                    } else if ident == "unpinned" {
                        Unpinned
                    } else {
                        ignore_attr!();
                    },
                };
                had_attr = true;
                // From now on, instead of ignoring, we error.

                let span = attr_meta.span();
                let visibility = match attr_meta { //
                    | syn::Meta::Word(_)
                    => Visibility::Inherited,

                    | syn::Meta::List(syn::MetaList {
                        nested,
                        ..
                    }) => {
                        let span = nested.span();
                        let mut nested = nested.into_iter();
                        if nested.len() != 1 {
                            error_spanned!(span =>
                                "Too many parameters, at most 1 expected"
                            );
                        }
                        match nested.next() { //
                            | Some(
                                syn::NestedMeta::Meta(
                                    syn::Meta::NameValue(
                                        syn::MetaNameValue {
                                            ref ident,
                                            lit: syn::Lit::Str(ref string_literal),
                                            ..
                                        }
                                    )
                                )
                            ) if *ident == "pub"
                            => match syn::parse_str::<Visibility>(&format!(
                                "pub ({})", string_literal.value(),
                            )) {//
                                | Ok(vis) => vis,
                                | _ => error_spanned!(string_literal.span() =>
                                    "expected visibility specifier"
                                ),
                            },

                            | Some(
                                syn::NestedMeta::Meta(
                                    syn::Meta::Word(ident)
                                )
                            ) => {
                                let span = ident.span();
                                if ident != "pub" {
                                    error_spanned!(span =>
                                        "expected `pub`"
                                    );
                                }
                                Visibility::Public(syn::VisPublic {
                                    pub_token: syn::token::Pub { span },
                                })
                            },

                            | Some(otherwise) => {
                                error_spanned!(otherwise.span() =>
                                    r#"Expected `pub = "..."`"#
                                );
                            },

                            | _ => error_spanned!(span =>
                                r#"Expected `pub = "..."`"#
                            ),
                        }
                    },

                    | _ => error_spanned!(attr_meta.span() =>
                        r#"Expected `pub = "..."`"#
                    ),
                };
                let ident =
                    field_ident
                        .clone()
                        .unwrap_or_else(|| Ident::new(
                            &i.to_string(),
                            field_ty.span(),
                        ))
                ;
                let prev = ret.insert(ident, SpecialField {
                    pin_transitiveness,
                    vis: visibility,
                    ty: field_ty.clone(),
                });
                if prev.is_some() {
                    error_spanned!(span => concat!(
                        "#[unpinned] / #[transitively_pinned] ",
                        "must be specified exactly once per field",
                    ));
                }
                false
            });
            if let Some((span, msg)) = error_spanned { //
                return Err((span, msg));
            }
            if had_attr.not() {
                let span =
                    field_ident
                        .as_ref()
                        .map(Ident::span)
                        .unwrap_or_else(|| field_ty.span())
                ;
                return Err((span, concat!(
                    "Missing #[unpinned] or #[transitively_pinned] attribute; ",
                    "when in doubt, use #[unpinned].",
                )));
            }
        }
        Ok(ret)
    }
}

#[proc_macro_attribute] pub
fn easy_pin (params: TokenStream, input: TokenStream) -> TokenStream
{
    mk_render!(ret);

    // attribute should apply on a struct
    let mut input: DeriveInput = syn::parse_macro_input!(input);
    let (impl_generics, ty_generics, where_clause) =
        input
            .generics
            .split_for_impl()
    ;
    let at_struct = {
        use syn::{Data, DataEnum, DataUnion};
        use syn::token::{Enum, Union};
        match &mut input.data { //
            | &mut Data::Struct(ref mut at_struct) => at_struct,

            | &mut Data::Enum(DataEnum {
                enum_token: Enum { span, .. },
                ..
            })
            | &mut Data::Union(DataUnion {
                union_token: Union { span, .. },
                ..
            }) => error_spanned!(span =>
                "#[easy_pin] only works on structs (currently)"
            ),
        }
    };
    let struct_name = &input.ident;

    // parse each field to identify those "special"
    // (i.e. marked #[transitively_pinned] / #[unpinned])
    // note: this does mutate the original fields to strip these attributes
    // to avoid Rust erroring on unknown attributes
    let special_fields = {
        match SpecialField::collect_from(at_struct.fields.iter_mut()) {//
            | Ok(special_fields) => special_fields,
            | Err((span, msg)) => error_spanned!(span => msg.as_ref()),
        }
    };

    // Now that our custom attributes have been parsed and stripped,
    // we may render the input struct, thus almost acting like a #[derive()]
    render! {
        #input
    }

    // Handle the Drop optional input parameter on the main proc_macro_attribute
    let params: DerivePinParams = syn::parse_macro_input!(params);
    if let Some(span) = params.drop {
        render_spanned! { span =>
            impl #impl_generics Drop
                for #struct_name #ty_generics
            #where_clause
            {
                #[inline]
                fn drop (self: &'_ mut Self)
                {
                    unsafe {
                        <Self as easy_pin::PinDrop>::drop_pinned(
                            easy_pin::core::pin::Pin::new_unchecked(self)
                        )
                    }
                }
            }
        }
    } else {
        // To avoid an unsound impl of `Drop` that does not use PinDrop,
        // let's add a dummy empty Drop that should conflict with any such impl
        render! {
            impl #impl_generics Drop
                for #struct_name #ty_generics
            #where_clause
            {
                #[inline]
                fn drop (self: &'_ mut Self)
                {}
            }
        }
    }

    // Add Unpin when pinned fields are Unpin
    if let Some(span) = params.unpin {
        let mut where_clause =
            where_clause
                .cloned()
                .unwrap_or_else(|| syn::WhereClause {
                    where_token: syn::token::Where {
                        span/*: Span::call_site()*/,
                    },
                    predicates: Punctuated::new(),
                })
        ;
        let unpin_trait: syn::Path = syn::parse_quote! {
            easy_pin::core::marker::Unpin
        };
        where_clause.predicates.extend(special_fields.values().filter_map(
            |field: &'_ SpecialField| -> Option<syn::WherePredicate>
            {
                match field {//
                    | SpecialField { pin_transitiveness: Unpinned, ..} => {
                        None
                    },
                    | SpecialField { ty: field_ty, .. } => {
                        Some(syn::parse_quote! {
                            #field_ty : #unpin_trait
                        })
                    },
                }
            }
        ));
        render_spanned! { span =>
            impl #impl_generics #unpin_trait
                for #struct_name #ty_generics
            #where_clause
            {}
        }
    }

    // Add Pin/Unpin projections
    special_fields.into_iter().for_each(|(ident, field)| match field {
        // Pin projection
        | SpecialField {
            pin_transitiveness: PinTransitive,
            vis,
            ty,
        } => {
            // & _
            let pinned_ident = Ident::new(
                &format!("pinned_{}", ident),
                ident.span(),
            );
            render_spanned! { ident.span() =>
                impl #impl_generics
                    #struct_name #ty_generics
                #where_clause
                {
                    #[allow(dead_code)]
                    #[inline]
                    #vis
                    fn #pinned_ident<'__> (
                        self: easy_pin::core::pin::Pin<&'__ Self>,
                    ) -> easy_pin::core::pin::Pin<&'__ #ty>
                    {
                        unsafe {
                            self.map_unchecked(|slf| &slf.#ident)
                        }
                    }
                }
            }

            // &mut _
            let pinned_ident_mut = Ident::new(
                &format!("pinned_{}_mut", ident),
                ident.span(),
            );
            render_spanned! { ident.span() =>
                impl #impl_generics
                    #struct_name #ty_generics
                #where_clause
                {
                    #[allow(dead_code)]
                    #[inline]
                    #vis
                    fn #pinned_ident_mut<'__> (
                        self: easy_pin::core::pin::Pin<&'__ mut Self>,
                    ) -> easy_pin::core::pin::Pin<&'__ mut #ty>
                    {
                        unsafe {
                            self.map_unchecked_mut(|slf| &mut slf.#ident)
                        }
                    }
                }
            }
        },

        // Pin projection
        | SpecialField {
            pin_transitiveness: Unpinned,
            vis,
            ty,
        } => {
            // & _
            let unpinned_ident = Ident::new(
                &format!("unpinned_{}", ident),
                ident.span(),
            );
            render_spanned! { ident.span() =>
                impl #impl_generics #struct_name #ty_generics #where_clause {
                    #[allow(dead_code)]
                    #[inline]
                    #vis
                    fn #unpinned_ident<'__> (
                        self: easy_pin::core::pin::Pin<&'__ Self>,
                    ) -> &'__ #ty
                    {
                        &self.get_ref().#ident
                    }
                }
            }

            // &mut _
            let unpinned_ident_mut = Ident::new(
                &format!("unpinned_{}_mut", ident),
                ident.span(),
            );
            render_spanned! { ident.span() =>
                impl #impl_generics
                    #struct_name #ty_generics
                #where_clause
                {
                    #[allow(dead_code)]
                    #[inline]
                    #vis
                    fn #unpinned_ident_mut<'__> (
                        self: easy_pin::core::pin::Pin<&'__ mut Self>,
                    ) -> &'__ mut #ty
                    {
                        unsafe {
                            &mut self.get_unchecked_mut().#ident
                        }
                    }
                }
            }
        },
    });

    ret
}