orbtk_proc_macros/
lib.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
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
extern crate proc_macro;

use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{parse_macro_input, DataStruct, DeriveInput, Ident, Meta, NestedMeta};

/// Derive an orbtk pipline. It returns a token stream object.
#[proc_macro_derive(Pipeline)]
pub fn derive_pipeline(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let ident = &input.ident;

    let gen = quote! {
        impl PipelineTrait for #ident {
            fn box_eq(&self, other: &dyn Any) -> bool {
                other.downcast_ref::<Self>().map_or(false, |a| self == a)
            }
            fn as_any(&self) -> &dyn Any {
                self
            }
            fn clone_box(&self) -> Box<dyn PipelineTrait> {
                Box::new(self.clone())
            }
        }
    };

    TokenStream::from(gen)
}

/// Derive an orbtk as_any type. It returns a token stream object.
#[proc_macro_derive(AsAny)]
pub fn derive_as_any(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let ident = &input.ident;

    let gen = quote! {
        impl AsAny for #ident {
            fn as_any(&self) -> &dyn Any {
                self
            }

            fn as_any_mut(&mut self) -> &mut dyn Any {
                self
            }
        }
    };

    TokenStream::from(gen)
}

/// Derive into an orbtk render object. It returns a token stream object.
#[proc_macro_derive(IntoRenderObject)]
pub fn derive_into_render_object(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let ident = &input.ident;

    let gen = quote! {
        impl From<#ident> for Box<dyn RenderObject> {
            fn from(i: #ident) -> Box<dyn RenderObject> {
                Box::new(i)
            }
        }
    };

    TokenStream::from(gen)
}

/// Derive into an orbtk layout object. It returns a token stream object.
#[proc_macro_derive(IntoLayout)]
pub fn derive_into_layout(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let ident = &input.ident;

    let gen = quote! {
        impl From<#ident> for Box<dyn Layout> {
            fn from(i: #ident) -> Box<dyn Layout> {
                Box::new(i)
            }
        }
    };

    TokenStream::from(gen)
}

/// Derive into an orbtk event object. It returns a token stream object.
#[proc_macro_derive(Event)]
pub fn derive_event(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let ident = &input.ident;

    let gen = quote! {
        impl Event for #ident {}
    };

    TokenStream::from(gen)
}

/// Derive into an orbtk handler object. It returns a token stream object.
#[proc_macro_derive(IntoHandler)]
pub fn derive_into_handler(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let ident = &input.ident;

    let gen = quote! {
        impl From<#ident> for Rc<dyn EventHandler> {
            fn from(i: #ident) -> Rc<dyn EventHandler> {
                Rc::new(i)
            }
        }
    };

    TokenStream::from(gen)
}

/// Derive into an orbtk widget context object. It returns a token stream object.
#[proc_macro_derive(WidgetCtx, attributes(property))]
pub fn derive_widget_ctx(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let ident = &input.ident;

    let mut generated = vec![];

    if let syn::Data::Struct(DataStruct { ref fields, .. }) = input.data {
        let filter_fields = fields
            .iter()
            .filter(|f| f.attrs.iter().any(|attr| attr.path.is_ident("property")));

        for field in filter_fields {
            let field_name = field
                .clone()
                .ident
                .unwrap_or_else(|| panic!("Expected the field to have a name"));

            let field_name_str = field_name.to_string();

            for attr in field.attrs.iter() {
                let last_attr_path = attr
                    .path
                    .segments
                    .iter()
                    .last()
                    .expect("Expected at least one segment where #[segment[::segment*](..)]");
                if (*last_attr_path).ident != "property" {
                    continue;
                }

                let meta = match attr.parse_meta() {
                    Ok(meta) => meta,
                    Err(_) => continue,
                };
                let list = match meta {
                    Meta::List(l) => l,
                    _ if meta.path().is_ident("property") => {
                        panic!("Invalid #[new] attribute, expected #[property(..)]")
                    }
                    _ => continue,
                };

                for item in list.nested.iter() {
                    match *item {
                        NestedMeta::Meta(Meta::Path(ref path)) => {
                            let ty = path.get_ident();

                            if let Some(ty) = ty {
                                let getter = Ident::new(
                                    format!("{}_ref", field_name).as_str(),
                                    Span::call_site(),
                                );

                                let setter = Ident::new(
                                    format!("{}_set", field_name).as_str(),
                                    Span::call_site(),
                                );

                                let clone = Ident::new(
                                    format!("{}_clone", field_name).as_str(),
                                    Span::call_site(),
                                );

                                let get_mut = Ident::new(
                                    format!("{}_mut", field_name).as_str(),
                                    Span::call_site(),
                                );

                                let gen = quote! {
                                    /// Gets a reference of the property value. Panics if it is the wrong widget type.
                                    #[inline(always)]
                                    pub fn #getter<'a>(widget: &'a WidgetContainer<'a>) -> &'a #ty {
                                        #ident::panics_on_wrong_type(widget);
                                        widget.get(#field_name_str)
                                    }

                                    /// Gets a mutable reference of the property value. Panics if it is the wrong widget type.
                                    #[inline(always)]
                                    pub fn #get_mut<'a>(widget: &'a mut WidgetContainer<'a>) -> &'a mut #ty {
                                        #ident::panics_on_wrong_type(widget);
                                        widget.get_mut(#field_name_str)
                                    }

                                    /// Sets the property value. Panics if it is the wrong widget type.
                                    #[inline(always)]
                                    pub fn #setter(widget: &mut WidgetContainer, value: impl Into<#ty>) {
                                        #ident::panics_on_wrong_type(widget);
                                        widget.set(#field_name_str, value.into());
                                    }

                                    /// Clones the property value. Panics if it is the wrong widget type.
                                    #[inline(always)]
                                    pub fn #clone(widget: &WidgetContainer) -> #ty {
                                        widget.clone(#field_name_str)
                                    }
                                };

                                generated.push(gen);
                            }

                            break;
                        }
                        _ => continue,
                    }
                }
            }
        }
    }

    let gen = quote! {
        impl #ident {
            #(#generated)*
        }
    };

    TokenStream::from(gen)
}