delegate 0.13.5

Method delegation with less boilerplate
Documentation
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
use proc_macro2::{Delimiter, TokenStream, TokenTree};
use quote::ToTokens;
use std::collections::VecDeque;
use std::ops::Not;
use syn::parse::ParseStream;
use syn::{Attribute, Error, Meta, Path, PathSegment, Token, TypePath};

pub struct CallMethodAttribute {
    name: syn::Ident,
}

impl syn::parse::Parse for CallMethodAttribute {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        Ok(CallMethodAttribute {
            name: input.parse()?,
        })
    }
}

#[derive(Default, Clone)]
pub struct GetFieldAttribute {
    reference: Option<(Token![&], Option<Token![mut]>)>,
    member: Option<syn::Member>,
}

impl GetFieldAttribute {
    pub fn reference_tokens(&self) -> Option<TokenStream> {
        let (ref_, mut_) = self.reference.as_ref()?;
        let mut tokens = ref_.to_token_stream();
        mut_.to_tokens(&mut tokens);
        Some(tokens)
    }
}

impl syn::parse::Parse for GetFieldAttribute {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let mut reference = None;
        if let Ok(ref_) = input.parse::<syn::Token![&]>() {
            reference = Some((ref_, None));
        }
        if let Some((_, mut_)) = &mut reference {
            *mut_ = input.parse::<syn::Token![mut]>().ok();
        }
        let member = input.is_empty().not().then(|| input.parse()).transpose()?;
        Ok(GetFieldAttribute { reference, member })
    }
}

struct GenerateAwaitAttribute {
    literal: syn::LitBool,
}

impl syn::parse::Parse for GenerateAwaitAttribute {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        Ok(GenerateAwaitAttribute {
            literal: input.parse()?,
        })
    }
}

struct IntoAttribute {
    type_path: Option<TypePath>,
}

impl syn::parse::Parse for IntoAttribute {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let type_path: TypePath = input.parse().map_err(|error| {
            Error::new(
                input.span(),
                format!("{error}\nExpected type name, e.g. #[into(u32)]"),
            )
        })?;

        Ok(IntoAttribute {
            type_path: Some(type_path),
        })
    }
}

pub struct AssociatedConstant {
    pub const_name: PathSegment,
    pub trait_path: Path,
}

impl syn::parse::Parse for AssociatedConstant {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let mut path = input.parse::<syn::Path>().map_err(|error| {
            Error::new(
                input.span(),
                format!(
                    "{error}\nExpected const path, e.g. #[const(path::to::MyTrait::CONST_NAME)]"
                ),
            )
        })?;

        let const_name = path.segments.pop().ok_or_else(|| {
            Error::new_spanned(
                &path,
                "Expected a path. e.g. #[const(path::to::MyTrait::CONST_NAME)]",
            )
        })?;
        // poping a segment leads to trailing `::`
        path.segments.pop_punct().ok_or_else(|| {
            Error::new_spanned(
                &path,
                "Expected a multipart path. e.g. #[const(path::to::MyTrait::CONST_NAME)]",
            )
        })?;

        Ok(Self {
            const_name: const_name.into_value(),
            trait_path: path,
        })
    }
}

#[derive(Clone)]
/// Represent the placeholder `$` found inside an expr attribute's template
pub struct ExprPlaceHolder;

impl syn::parse::Parse for ExprPlaceHolder {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        input.parse::<syn::Token![$]>()?;
        Ok(Self)
    }
}

/// Kind of allowed placeholders in an `expr` attribute template
#[derive(Clone)]
enum Placeholder {
    ExprPlaceholder(ExprPlaceHolder),
}

#[derive(Clone)]
/// Tokens found in the expr attribute's template
/// Token are either
/// - a replacable pattern (placeholder)
/// - a normal token
/// - a group containing a recursive representation of template tokens
enum TemplateToken {
    Normal(TokenTree),
    Placeholder(Placeholder),
    Group(Delimiter, TemplateExpr),
}

impl TemplateToken {
    /// Replace relevant placeholder tokens with the provided tokens
    fn replace(&self, replacement: &TokenStream) -> TokenStream {
        match self {
            Self::Group(del, template) => {
                let replaced_tokens = template
                    .tokens
                    .iter()
                    .map(|token| token.replace(replacement));
                proc_macro2::Group::new(*del, quote::quote! { #(#replaced_tokens)* })
                    .to_token_stream()
            }
            Self::Normal(token_tree) => token_tree.to_token_stream(),
            Self::Placeholder(_) => replacement.clone(),
        }
    }
}

#[derive(Clone)]
/// An expr attribute's template
pub struct TemplateExpr {
    tokens: Vec<TemplateToken>,
}

impl syn::parse::Parse for TemplateExpr {
    /// Parsing a template means storing the raw template while differenciating
    /// placeholders and "normal" tokens
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut tokens = Vec::new();
        while !input.is_empty() {
            if input.fork().parse::<ExprPlaceHolder>().is_ok() {
                let placeholder = input.parse()?;
                tokens.push(TemplateToken::Placeholder(Placeholder::ExprPlaceholder(
                    placeholder,
                )));
                continue;
            }

            match input.parse()? {
                TokenTree::Group(group) => {
                    let inner_stream = group.stream();
                    let inner_expr = syn::parse2(inner_stream)?;
                    tokens.push(TemplateToken::Group(group.delimiter(), inner_expr));
                }
                other => {
                    tokens.push(TemplateToken::Normal(other));
                }
            }
        }

        Ok(TemplateExpr { tokens })
    }
}

impl TemplateExpr {
    /// returns the template after expanding the relevant placeholders
    pub fn expand_template(&self, replacement: &TokenStream) -> TokenStream {
        self.tokens.iter().fold(TokenStream::new(), |mut ts, tok| {
            ts.extend(tok.replace(replacement));
            ts
        })
    }
}

pub struct TraitTarget {
    type_path: TypePath,
}

impl syn::parse::Parse for TraitTarget {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let type_path: TypePath = input.parse().map_err(|error| {
            Error::new(
                input.span(),
                format!("{error}\nExpected trait path, e.g. #[through(foo::MyTrait)]"),
            )
        })?;

        Ok(TraitTarget { type_path })
    }
}

#[derive(Clone)]
pub enum ReturnExpression {
    Into(Option<TypePath>),
    TryInto,
    Unwrap,
}

pub enum TargetSpecifier {
    Field(GetFieldAttribute),
    Method(CallMethodAttribute),
}

impl TargetSpecifier {
    pub fn get_member(&self, default: &syn::Ident) -> syn::Member {
        match self {
            Self::Field(GetFieldAttribute {
                member: Some(member),
                ..
            }) => member.clone(),
            Self::Field(_) => default.clone().into(),
            Self::Method(method) => method.name.clone().into(),
        }
    }
}

enum ParsedAttribute {
    ReturnExpression(ReturnExpression),
    Await(bool),
    TargetSpecifier(TargetSpecifier),
    ThroughTrait(TraitTarget),
    ConstantAccess(AssociatedConstant),
    Expr(TemplateExpr),
}

fn parse_attributes(
    attrs: &[Attribute],
) -> (
    impl Iterator<Item = ParsedAttribute> + '_,
    impl Iterator<Item = &Attribute>,
) {
    let (parsed, other): (Vec<_>, Vec<_>) = attrs
        .iter()
        .map(|attribute| {
            let parsed = if let syn::AttrStyle::Outer = attribute.style {
                let name = attribute
                    .path()
                    .get_ident()
                    .map(|i| i.to_string())
                    .unwrap_or_default();
                match name.as_str() {
                    "call" => {
                        let target = attribute
                            .parse_args::<CallMethodAttribute>()
                            .expect("Cannot parse `call` attribute");
                        let spec = TargetSpecifier::Method(target);
                        Some(ParsedAttribute::TargetSpecifier(spec))
                    }
                    "field" => {
                        let target = if let syn::Meta::Path(_) = &attribute.meta {
                            GetFieldAttribute::default()
                        } else {
                            attribute
                                .parse_args::<GetFieldAttribute>()
                                .expect("Cannot parse `field` attribute")
                        };
                        let spec = TargetSpecifier::Field(target);
                        Some(ParsedAttribute::TargetSpecifier(spec))
                    }
                    "into" => {
                        let into = match &attribute.meta {
                            Meta::NameValue(_) => {
                                panic!("Cannot parse `into` attribute: expected parentheses")
                            }
                            Meta::Path(_) => IntoAttribute { type_path: None },
                            Meta::List(meta) => meta
                                .parse_args::<IntoAttribute>()
                                .expect("Cannot parse `into` attribute"),
                        };
                        Some(ParsedAttribute::ReturnExpression(ReturnExpression::Into(
                            into.type_path,
                        )))
                    }
                    "try_into" => {
                        if let Meta::List(meta) = &attribute.meta {
                            meta.parse_nested_meta(|meta| {
                                if meta.path.is_ident("unwrap") {
                                    panic!(
                                        "Replace #[try_into(unwrap)] with\n#[try_into]\n#[unwrap]",
                                    );
                                }
                                Ok(())
                            })
                            .expect("Invalid `try_into` arguments");
                        }
                        Some(ParsedAttribute::ReturnExpression(ReturnExpression::TryInto))
                    }
                    "unwrap" => Some(ParsedAttribute::ReturnExpression(ReturnExpression::Unwrap)),
                    "await" => {
                        let generate = attribute
                            .parse_args::<GenerateAwaitAttribute>()
                            .expect("Cannot parse `await` attribute");
                        Some(ParsedAttribute::Await(generate.literal.value))
                    }
                    "through" => Some(ParsedAttribute::ThroughTrait(
                        attribute
                            .parse_args::<TraitTarget>()
                            .expect("Cannot parse `through` attribute"),
                    )),
                    "const" => Some(ParsedAttribute::ConstantAccess(
                        attribute
                            .parse_args::<AssociatedConstant>()
                            .expect("Cannot parse `const` attribute"),
                    )),
                    "expr" => Some(ParsedAttribute::Expr(
                        attribute
                            .parse_args::<TemplateExpr>()
                            .expect("Cannot parse `expr` attribute"),
                    )),
                    _ => None,
                }
            } else {
                None
            };

            (parsed, attribute)
        })
        .partition(|(parsed, _)| parsed.is_some());
    (
        parsed.into_iter().map(|(parsed, _)| parsed.unwrap()),
        other.into_iter().map(|(_, attr)| attr),
    )
}

pub struct MethodAttributes<'a> {
    pub attributes: Vec<&'a Attribute>,
    pub target_specifier: Option<TargetSpecifier>,
    pub expressions: VecDeque<ReturnExpression>,
    pub generate_await: Option<bool>,
    pub target_trait: Option<TypePath>,
    pub associated_constant: Option<AssociatedConstant>,
    pub expr_attr: Option<TemplateExpr>,
}

/// Iterates through the attributes of a method and filters special attributes.
/// - call => sets the name of the target method to call
/// - into => generates a `into()` call after the delegated expression
/// - try_into => generates a `try_into()` call after the delegated expression
/// - await => generates an `.await` expression after the delegated expression
/// - unwrap => generates a `unwrap()` call after the delegated expression
/// - through => generates a UFCS call (`Target::method(&<expr>, ...)`) around the delegated expression
/// - const => generates a getter to a trait associated constant
pub fn parse_method_attributes<'a>(
    attrs: &'a [Attribute],
    method: &syn::TraitItemFn,
) -> MethodAttributes<'a> {
    let mut target_spec: Option<TargetSpecifier> = None;
    let mut expressions: Vec<ReturnExpression> = vec![];
    let mut generate_await: Option<bool> = None;
    let mut target_trait: Option<TraitTarget> = None;
    let mut associated_constant: Option<AssociatedConstant> = None;
    let mut expr_attr: Option<TemplateExpr> = None;

    let (parsed, other) = parse_attributes(attrs);
    for attr in parsed {
        match attr {
            ParsedAttribute::ReturnExpression(expr) => expressions.push(expr),
            ParsedAttribute::Await(value) => {
                if generate_await.is_some() {
                    panic!(
                        "Multiple `await` attributes specified for {}",
                        method.sig.ident
                    )
                }
                generate_await = Some(value);
            }
            ParsedAttribute::TargetSpecifier(spec) => {
                if target_spec.is_some() {
                    panic!(
                        "Multiple field/call attributes specified for {}",
                        method.sig.ident
                    )
                }
                target_spec = Some(spec);
            }
            ParsedAttribute::ThroughTrait(target) => {
                if target_trait.is_some() {
                    panic!(
                        "Multiple through attributes specified for {}",
                        method.sig.ident
                    )
                }
                target_trait = Some(target);
            }
            ParsedAttribute::ConstantAccess(const_attr) => {
                if associated_constant.is_some() {
                    panic!(
                        "Multiple const attributes specified for {}",
                        method.sig.ident
                    )
                }
                associated_constant = Some(const_attr);
            }
            ParsedAttribute::Expr(token_tree) => {
                if expr_attr.is_some() {
                    panic!(
                        "Multiple expr attributes specified for {}",
                        method.sig.ident
                    )
                }
                expr_attr = Some(token_tree);
            }
        }
    }

    if associated_constant.is_some() && target_spec.is_some() {
        panic!("Cannot use both `call`/`field` and `const` attributes.");
    }

    MethodAttributes {
        attributes: other.into_iter().collect(),
        target_specifier: target_spec,
        generate_await,
        expressions: expressions.into(),
        target_trait: target_trait.map(|t| t.type_path),
        associated_constant,
        expr_attr,
    }
}

pub struct SegmentAttributes {
    pub expressions: Vec<ReturnExpression>,
    pub generate_await: Option<bool>,
    pub target_trait: Option<TypePath>,
    pub other_attrs: Vec<Attribute>,
    pub expr_attr: Option<TemplateExpr>,
}

pub fn parse_segment_attributes(attrs: &[Attribute]) -> SegmentAttributes {
    let mut expressions: Vec<ReturnExpression> = vec![];
    let mut generate_await: Option<bool> = None;
    let mut target_trait: Option<TraitTarget> = None;
    let mut expr_attr: Option<TemplateExpr> = None;

    let (parsed, other) = parse_attributes(attrs);

    for attribute in parsed {
        match attribute {
            ParsedAttribute::ReturnExpression(expr) => expressions.push(expr),
            ParsedAttribute::Await(value) => {
                if generate_await.is_some() {
                    panic!("Multiple `await` attributes specified for segment");
                }
                generate_await = Some(value);
            }
            ParsedAttribute::ThroughTrait(target) => {
                if target_trait.is_some() {
                    panic!("Multiple `through` attributes specified for segment");
                }
                target_trait = Some(target);
            }
            ParsedAttribute::TargetSpecifier(_) => {
                panic!("Field/call attribute cannot be specified on a `to <expr>` segment.");
            }
            ParsedAttribute::ConstantAccess(_) => {
                panic!("Const attribute cannot be specified on a `to <expr>` segment.");
            }
            ParsedAttribute::Expr(token_tree) => {
                if expr_attr.is_some() {
                    panic!("Multiple `expr` attributes specified for segment");
                }
                expr_attr = Some(token_tree);
            }
        }
    }
    SegmentAttributes {
        expressions,
        generate_await,
        target_trait: target_trait.map(|t| t.type_path),
        other_attrs: other.cloned().collect::<Vec<_>>(),
        expr_attr,
    }
}

/// Applies default values from the segment and adds them to the method attributes.
pub fn combine_attributes<'a>(
    mut method_attrs: MethodAttributes<'a>,
    segment_attrs: &'a SegmentAttributes,
) -> MethodAttributes<'a> {
    let SegmentAttributes {
        expressions,
        generate_await,
        target_trait,
        other_attrs,
        expr_attr,
    } = segment_attrs;

    if method_attrs.generate_await.is_none() {
        method_attrs.generate_await = *generate_await;
    }

    if method_attrs.target_trait.is_none() {
        method_attrs.target_trait.clone_from(target_trait);
    }

    if method_attrs.expr_attr.is_none() {
        method_attrs.expr_attr.clone_from(expr_attr);
    }

    for expr in expressions {
        match expr {
            ReturnExpression::Into(path) => {
                if !method_attrs
                    .expressions
                    .iter()
                    .any(|expr| matches!(expr, ReturnExpression::Into(_)))
                {
                    method_attrs
                        .expressions
                        .push_front(ReturnExpression::Into(path.clone()));
                }
            }
            _ => method_attrs.expressions.push_front(expr.clone()),
        }
    }

    for other_attr in other_attrs {
        if !method_attrs
            .attributes
            .iter()
            .any(|attr| attr.path().get_ident() == other_attr.path().get_ident())
        {
            method_attrs.attributes.push(other_attr);
        }
    }

    method_attrs
}