impl_tools_lib/
default.rs

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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
//     https://www.apache.org/licenses/LICENSE-2.0

use crate::fields::{Fields, FieldsNamed, FieldsUnnamed};
use crate::generics::{clause_to_toks, WhereClause};
use crate::scope::{Scope, ScopeAttr, ScopeItem};
use crate::SimplePath;
use proc_macro2::{Span, TokenStream};
use proc_macro_error2::emit_error;
use quote::quote;
use syn::parse::{Error, Parse, ParseStream, Result};
use syn::spanned::Spanned;
use syn::{parse2, Attribute, Expr, Generics, Ident, Item, Meta, Token};

/// `#[impl_default]` attribute
pub struct ImplDefault {
    expr: Option<Expr>,
    where_clause: Option<WhereClause>,
    span: Span,
}

impl ImplDefault {
    /// Expand over the given `item`
    ///
    /// This attribute (in this form of invocation) does not modify the item.
    /// The caller should append the result to `item` tokens.
    pub fn expand(self, item: TokenStream) -> TokenStream {
        let attr_span = self.span;
        if self.expr.is_some() {
            let item = match parse2::<Item>(item) {
                Ok(item) => item,
                Err(err) => {
                    emit_error!(err.span(), "{}", err);
                    return TokenStream::new();
                }
            };

            match item {
                Item::Enum(syn::ItemEnum {
                    ident, generics, ..
                })
                | Item::Struct(syn::ItemStruct {
                    ident, generics, ..
                })
                | Item::Type(syn::ItemType {
                    ident, generics, ..
                })
                | Item::Union(syn::ItemUnion {
                    ident, generics, ..
                }) => self.gen_expr(&ident, &generics),
                item => {
                    emit_error!(
                        item,
                        "default: only supports enum, struct, type alias and union items"
                    );
                    TokenStream::new()
                }
            }
        } else {
            emit_error!(attr_span, "invalid use outside of `impl_scope!` macro");
            TokenStream::new()
        }
    }

    fn gen_expr(self, ident: &Ident, generics: &Generics) -> TokenStream {
        let (impl_generics, ty_generics, _) = generics.split_for_impl();
        let wc = clause_to_toks(
            &self.where_clause,
            generics.where_clause.as_ref(),
            &quote! { Default },
        );
        let expr = self.expr.unwrap();

        quote! {
            #[automatically_derived]
            impl #impl_generics core::default::Default for #ident #ty_generics #wc {
                fn default() -> Self {
                    #expr
                }
            }
        }
    }

    fn parse_attr(attr: Attribute) -> Result<Self> {
        match attr.meta {
            Meta::Path(_) => Ok(ImplDefault {
                expr: None,
                where_clause: None,
                span: attr.span(),
            }),
            Meta::List(list) => list.parse_args(),
            Meta::NameValue(meta) => Err(Error::new_spanned(
                meta,
                "expected #[impl_default] or #[impl_default(EXPR)]",
            )),
        }
    }
}

/// [`ScopeAttr`] rule enabling `#[impl_default]` within `impl_scope!`
pub struct AttrImplDefault;
impl ScopeAttr for AttrImplDefault {
    fn path(&self) -> SimplePath {
        SimplePath(&["impl_default"])
    }

    fn apply(&self, attr: Attribute, scope: &mut Scope) -> Result<()> {
        let args = ImplDefault::parse_attr(attr)?;

        if args.expr.is_some() {
            scope
                .generated
                .push(args.gen_expr(&scope.ident, &scope.generics));
        } else {
            let fields = match &mut scope.item {
                ScopeItem::Struct { fields, .. } => match fields {
                    Fields::Named(FieldsNamed { fields, .. })
                    | Fields::Unnamed(FieldsUnnamed { fields, .. }) => {
                        let iter = fields.iter_mut().map(|field| {
                            let ident = &field.ident;
                            if let Some(expr) = field.assign.take().map(|a| a.1) {
                                quote! { #ident : #expr }
                            } else {
                                quote! { #ident : Default::default() }
                            }
                        });
                        quote! { #(#iter),* }
                    }
                    Fields::Unit => quote! {},
                },
                _ => {
                    return Err(Error::new(
                        args.span,
                        "must specify value as `#[impl_default(value)]` on non-struct type",
                    ));
                }
            };

            let ident = &scope.ident;
            let (impl_generics, ty_generics, _) = scope.generics.split_for_impl();
            let wc = clause_to_toks(
                &args.where_clause,
                scope.generics.where_clause.as_ref(),
                &quote! { Default },
            );

            scope.generated.push(quote! {
                #[automatically_derived]
                impl #impl_generics core::default::Default for #ident #ty_generics #wc {
                    fn default() -> Self {
                        #ident {
                            #fields
                        }
                    }
                }
            });
        }
        Ok(())
    }
}

impl Parse for ImplDefault {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut expr = None;
        let mut where_clause = None;
        let span = input.span();

        if !input.peek(Token![where]) && !input.is_empty() {
            expr = Some(input.parse()?);
        }

        if input.peek(Token![where]) {
            where_clause = Some(input.parse()?);
        }

        if !input.is_empty() {
            return Err(Error::new(input.span(), "unexpected"));
        }

        Ok(ImplDefault {
            expr,
            where_clause,
            span,
        })
    }
}

/// Helper fn which can be passed to [`Scope::apply_attrs`]
///
/// This optionally matches [`AttrImplDefault`].
pub fn find_impl_default(path: &syn::Path) -> Option<&'static dyn ScopeAttr> {
    AttrImplDefault
        .path()
        .matches(path)
        .then(|| &AttrImplDefault as &dyn ScopeAttr)
}