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
#![recursion_limit = "128"]
extern crate proc_macro;

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

use std::iter::Iterator;

/// A macro to derive fair [ComponentDefinition](ComponentDefinition) implementations
///
/// Implementations will set up ports and the component context correctly, and
/// during execution check ports in a fair round-robin manner.
///
/// Using this macro will also derive implementations of [ProvideRef](ProvideRef)
/// or [RequireRef](RequireRef) for each declared port.
#[proc_macro_derive(ComponentDefinition)]
pub fn component_definition(input: TokenStream) -> TokenStream {
    // Parse the input stream
    let ast = parse_macro_input!(input as DeriveInput);

    // Build the impl
    let gen = impl_component_definition(&ast);

    //println!("Derived code:\n{}", gen);

    // Return the generated impl
    gen.into()
}

fn impl_component_definition(ast: &syn::DeriveInput) -> TokenStream2 {
    let name = &ast.ident;
    let name_str = format!("{}", name);
    if let syn::Data::Struct(ref vdata) = ast.data {
        let generics = &ast.generics;
        let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

        let fields = &vdata.fields;
        let mut ports: Vec<(&syn::Field, PortField)> = Vec::new();
        let mut ctx_field: Option<&syn::Field> = None;
        for field in fields.iter() {
            let cf = identify_field(field);
            match cf {
                ComponentField::Ctx => {
                    ctx_field = Some(field);
                }
                ComponentField::Port(pf) => ports.push((field, pf)),
                ComponentField::Other => (),
            }
        }
        let (ctx_setup, ctx_access) = match ctx_field {
            Some(f) => {
                let id = &f.ident;
                let setup = quote! { self.#id.initialise(self_component.clone()); };
                let access = quote! { self.#id };
                (setup, access)
            }
            None => panic!("No ComponentContext found for {:?}!", name),
        };
        let port_setup = ports
            .iter()
            .map(|&(f, _)| {
                let id = &f.ident;
                quote! { self.#id.set_parent(self_component.clone()); }
            })
            .collect::<Vec<_>>();
        let port_handles_skip = ports
            .iter()
            .enumerate()
            .map(|(i, &(f, ref t))| {
                let id = &f.ident;
                //let ref ty = f.ty;
                let handle = t.as_handle();
                quote! {
                    if skip <= #i {
                        if count >= max_events {
                            return ExecuteResult::new(false, count, #i);
                        }
                        #[allow(unreachable_code)]
                        { // can be Never type, which is ok, so just suppress this warning
                            if let Some(event) = self.#id.dequeue() {
                                let res = #handle
                                count += 1;
                                done_work = true;
                                if let Handled::BlockOn(blocking_future) = res {
                                    self.ctx_mut().set_blocking(blocking_future);
                                    return ExecuteResult::new(true, count, #i);
                                }
                            }
                        }
                    }
                }
            })
            .collect::<Vec<_>>();
        let port_handles = ports
            .iter()
            .enumerate()
            .map(|(i, &(f, ref t))| {
                let id = &f.ident;
                //let ref ty = f.ty;
                let handle = t.as_handle();
                quote! {
                    if count >= max_events {
                        return ExecuteResult::new(false, count, #i);
                    }
                    #[allow(unreachable_code)]
                    { // can be Never type, which is ok, so just suppress this warning
                        if let Some(event) = self.#id.dequeue() {
                            let res = #handle
                            count += 1;
                            done_work = true;
                            if let Handled::BlockOn(blocking_future) = res {
                                self.ctx_mut().set_blocking(blocking_future);
                                return ExecuteResult::new(true, count, #i);
                            }
                        }
                    }
                }
            })
            .collect::<Vec<_>>();
        let exec = if port_handles.is_empty() {
            quote! {
                fn execute(&mut self, _max_events: usize, _skip: usize) -> ExecuteResult {
                    ExecuteResult::new(false, 0, 0)
                }
            }
        } else {
            quote! {
                fn execute(&mut self, max_events: usize, skip: usize) -> ExecuteResult {
                    let mut count: usize = 0;
                    let mut done_work = true; // might skip queues that have work
                    #(#port_handles_skip)*
                    while done_work {
                        done_work = false;
                        #(#port_handles)*
                    }
                    ExecuteResult::new(false, count, 0)
                }
            }
        };
        let port_ref_impls = ports
            .iter()
            .map(|p| {
                let (field, port_field) = p;
                let id = &field.ident;
                match port_field {
                    PortField::Required(ty) => quote! {
                        impl #impl_generics RequireRef< #ty > for #name #ty_generics #where_clause {
                            fn required_ref(&mut self) -> RequiredRef< #ty > {
                                self.#id.share()
                            }
                            fn connect_to_provided(&mut self, prov: ProvidedRef< #ty >) -> () {
                                self.#id.connect(prov)
                            }
                        }
                    },
                    PortField::Provided(ty) => quote! {
                        impl #impl_generics ProvideRef< #ty > for #name #ty_generics #where_clause {
                            fn provided_ref(&mut self) -> ProvidedRef< #ty > {
                                self.#id.share()
                            }
                            fn connect_to_required(&mut self, req: RequiredRef< #ty >) -> () {
                                self.#id.connect(req)
                            }
                        }
                    },
                }
            })
            .collect::<Vec<_>>();
        // if !port_ref_impls.is_empty() {
        // println!("PortRefImpls: {}",port_ref_impls[0]);
        // }

        fn make_match(f: &syn::Field, t: &syn::Type) -> TokenStream2 {
            let f = &f.ident;
            quote! {
                id if id == ::std::any::TypeId::of::<#t>() =>
                    Some(&mut self.#f as &mut dyn ::std::any::Any),
            }
        }

        let provided_matches: Vec<_> = ports
            .iter()
            .filter_map(|(f, p)| match p {
                PortField::Provided(t) => Some((*f, t)),
                _ => None,
            })
            .map(|(f, t)| make_match(f, t))
            .collect();

        let required_matches: Vec<_> = ports
            .iter()
            .filter_map(|(f, p)| match p {
                PortField::Required(t) => Some((*f, t)),
                _ => None,
            })
            .map(|(f, t)| make_match(f, t))
            .collect();

        quote! {
            impl #impl_generics ComponentDefinition for #name #ty_generics #where_clause {
                fn setup(&mut self, self_component: ::std::sync::Arc<Component<Self>>) -> () {
                    #ctx_setup
                    //println!("Setting up ports");
                    #(#port_setup)*
                }
                #exec
                fn ctx_mut(&mut self) -> &mut ComponentContext<Self> {
                    &mut #ctx_access
                }
                fn ctx(&self) -> &ComponentContext<Self> {
                    &#ctx_access
                }
                fn type_name() -> &'static str {
                    #name_str
                }
            }
            impl #impl_generics DynamicPortAccess for #name #ty_generics #where_clause {
                fn get_provided_port_as_any(&mut self, port_id: ::std::any::TypeId) -> Option<&mut dyn ::std::any::Any> {
                    match port_id {
                        #(#provided_matches)*
                        _ => None,
                    }
                }

                fn get_required_port_as_any(&mut self, port_id: ::std::any::TypeId) -> Option<&mut dyn ::std::any::Any> {
                    match port_id {
                        #(#required_matches)*
                        _ => None,
                    }
                }
            }
            #(#port_ref_impls)*
        }
    } else {
        //Nope. This is an Enum. We cannot handle these!
        panic!("#[derive(ComponentDefinition)] is only defined for structs, not for enums!");
    }
}

#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
enum ComponentField {
    Ctx,
    Port(PortField),
    Other,
}

#[derive(Debug)]
enum PortField {
    Required(syn::Type),
    Provided(syn::Type),
}

impl PortField {
    fn as_handle(&self) -> TokenStream2 {
        match *self {
            PortField::Provided(ref ty) => quote! { Provide::<#ty>::handle(self, event); },
            PortField::Required(ref ty) => quote! { Require::<#ty>::handle(self, event); },
        }
    }
}

const REQP: &str = "RequiredPort";
const PROVP: &str = "ProvidedPort";
const CTX: &str = "ComponentContext";
const KOMPICS: &str = "kompact";

fn identify_field(f: &syn::Field) -> ComponentField {
    if let syn::Type::Path(ref patht) = f.ty {
        let path = &patht.path;
        let port_seg_opt = if path.segments.len() == 1 {
            Some(&path.segments[0])
        } else if path.segments.len() == 2 {
            if path.segments[0].ident == KOMPICS {
                Some(&path.segments[1])
            } else {
                //println!("Module is not 'kompact': {:?}", path);
                None
            }
        } else {
            //println!("Path too long for port: {:?}", path);
            None
        };
        if let Some(seg) = port_seg_opt {
            if seg.ident == REQP {
                ComponentField::Port(PortField::Required(extract_port_type(seg)))
            } else if seg.ident == PROVP {
                ComponentField::Port(PortField::Provided(extract_port_type(seg)))
            } else if seg.ident == CTX {
                ComponentField::Ctx
            } else {
                //println!("Not a port: {:?}", path);
                ComponentField::Other
            }
        } else {
            ComponentField::Other
        }
    } else {
        ComponentField::Other
    }
}

fn extract_port_type(seg: &syn::PathSegment) -> syn::Type {
    match seg.arguments {
        syn::PathArguments::AngleBracketed(ref abppd) => {
            match abppd.args.first().expect("Invalid type argument!") {
                syn::GenericArgument::Type(ty) => ty.clone(),
                _ => panic!("Wrong generic argument type in {:?}", seg),
            }
        }
        _ => panic!("Wrong path parameter type! {:?}", seg),
    }
}