node_tree_derive 0.12.0

Provides the `NodeSys` macro for the `node_tree` crate.
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//===================================================================================================================================================================================//
//
//  /$$   /$$                 /$$            /$$$$$$                            /$$$$$$$                      /$$                    
// | $$$ | $$                | $$           /$$__  $$                          | $$__  $$                    |__/                    
// | $$$$| $$  /$$$$$$   /$$$$$$$  /$$$$$$ | $$  \__/ /$$   /$$  /$$$$$$$      | $$  \ $$  /$$$$$$   /$$$$$$  /$$ /$$    /$$ /$$$$$$ 
// | $$ $$ $$ /$$__  $$ /$$__  $$ /$$__  $$|  $$$$$$ | $$  | $$ /$$_____/      | $$  | $$ /$$__  $$ /$$__  $$| $$|  $$  /$$//$$__  $$
// | $$  $$$$| $$  \ $$| $$  | $$| $$$$$$$$ \____  $$| $$  | $$|  $$$$$$       | $$  | $$| $$$$$$$$| $$  \__/| $$ \  $$/$$/| $$$$$$$$
// | $$\  $$$| $$  | $$| $$  | $$| $$_____/ /$$  \ $$| $$  | $$ \____  $$      | $$  | $$| $$_____/| $$      | $$  \  $$$/ | $$_____/
// | $$ \  $$|  $$$$$$/|  $$$$$$$|  $$$$$$$|  $$$$$$/|  $$$$$$$ /$$$$$$$/      | $$$$$$$/|  $$$$$$$| $$      | $$   \  $/  |  $$$$$$$
// |__/  \__/ \______/  \_______/ \_______/ \______/  \____  $$|_______/       |_______/  \_______/|__/      |__/    \_/    \_______/
//                                                    /$$  | $$                                                                      
//                                                   |  $$$$$$/                                                                      
//                                                    \______/
//
//===================================================================================================================================================================================//

//?
//? Created by LunaticWyrm467 and others.
//? 
//? All code is licensed under the MIT license.
//? Feel free to reproduce, modify, and do whatever.
//?

//!
//! Contains the `Abstract` derive macro which helps reduce boilerplate in regards to trait
//! implementations.
//!

extern crate proc_macro;

mod parser;
mod generator;

use parser::*;
use generator::*;

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


/*
 * Node
 *      Abstract
 */


/// Implements all of the required traits for a `Node` type to be created aside from the `Node`
/// trait itself, which needs to be implemented manually.
#[proc_macro_derive(Abstract)]
pub fn r#abstract(input: TokenStream) -> TokenStream {
    
    // Parse the input tokens into a syntax tree,
    // and get the name of the struct.
    let input: DeriveInput = parse_macro_input!(input as DeriveInput);
    let name:  syn::Ident  = input.ident;

    // Expanded the code to host the boilerplate implementations of the NodeAbstract, Deref, and
    // DerefMut traits.
    let expanded = quote! {
        impl node_tree::traits::node::NodeAbstract for #name {
            fn base(&self) -> &node_tree::structs::node_base::NodeBase {
                &self.base
            }

            fn base_mut(&mut self) -> &mut node_tree::structs::node_base::NodeBase {
                &mut self.base
            }

            fn as_dyn(&self) -> &dyn node_tree::traits::node::Node {
                self
            }

            fn as_dyn_mut(&mut self) -> &mut dyn node_tree::traits::node::Node {
                self
            }

            fn as_dyn_raw(&self) -> *const dyn node_tree::traits::node::Node {
                self as *const dyn node_tree::traits::node::Node
            }
            
            fn as_dyn_raw_mut(&mut self) -> *mut dyn node_tree::traits::node::Node {
                self as *mut dyn node_tree::traits::node::Node
            }
            
            fn to_dyn_box(self) -> Box<dyn node_tree::traits::node::Node> {
                Box::new(self)
            }

            fn as_any_ref(&self) -> &dyn std::any::Any {
                self
            }

            fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
                self
            }

            fn clone_as_instance(&self) -> Box<dyn node_tree::traits::node::Node> {
                Box::new(self.clone())
            }

            fn name_as_type(&self) -> String {
                std::any::type_name::<Self>().to_string()
            }
        }

        impl std::ops::Deref for #name {
            type Target = node_tree::structs::node_base::NodeBase;
            fn deref(&self) -> &Self::Target {
                &self.base
            }
        }

        impl std::ops::DerefMut for #name {
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.base
            }
        }
    };

    // Return the generated impl as a TokenStream
    TokenStream::from(expanded)
}


/*
 * Register
 */


#[proc_macro_derive(Register)]
pub fn derive_registered(input: TokenStream) -> TokenStream {
    let ast:    DeriveInput             = parse_macro_input!(input as DeriveInput);
    let name:   &syn::Ident             = &ast.ident;
    let fields: &punc::Punctuated<_, _> = match &ast.data {
        syn::Data::Struct(data_struct) => match &data_struct.fields {
            syn::Fields::Named(syn::FieldsNamed { named, .. }) => named,
            _ => panic!("Registered trait can only be derived for structs with named fields"),
        },
        _ => panic!("Registered trait can only be derived for structs"),
    };

    let field_names: Vec<_> = fields
        .iter()
        .filter(|field| field.ident.as_ref().unwrap() != "base")
        .map(|field| field.ident.as_ref().unwrap())
        .collect();

    // Initialize deserialization lines from the fields.
    let mut type_definitions: Vec<TokenStream2>      = Vec::new();
    let     type_define_ptr:  *mut Vec<TokenStream2> = &mut type_definitions as *mut _;
    let     deserialization:  Vec<TokenStream2>      = fields.iter()
        .filter(|field| field.ident.as_ref().unwrap() != "base")
        .map(|field| {
            let field_name: &syn::Ident = field.ident.as_ref().expect("Field must be named");
            let field_type: &syn::Type  = &field.ty;
            
            // Create a unique ident for the type; this is to avoid having to parse colons between
            // generic arguments and the type.
            let unique_ident: syn::Ident = syn::Ident::new(&format!("Unique{}", type_definitions.len()), proc_macro::Span::call_site().into());
            unsafe { &mut *type_define_ptr }.push(quote! {
                type #unique_ident = #field_type;
            });
            
            quote! {
                #field_name: {
                    if #unique_ident::is_ghost_export_type() {
                        #unique_ident::void()
                    } else {
                        #unique_ident::from_value(
                            owned_state.remove(stringify!(#field_name)).ok_or(format!("corrupt save data; `{}` missing", stringify!(#field_name)))?
                        ).ok_or(format!("corrupt save data; `{}` invalid type", stringify!(#field_name)))?
                    }
                }
            }
        }).collect(); // We need to collect here so that the unique identities are created here and now!

    let static_name: syn::Ident   = syn::Ident::new(&format!("__static_init_{}", name.to_string().to_lowercase()), name.span());
    let expanded:    TokenStream2 = quote! {
        impl node_tree::traits::registered::Registered for #name {
            fn save_from_owned(&self) -> node_tree::services::node_registry::FieldMap {
                let mut map = node_tree::services::node_registry::FieldMap::new();
                #(
                    map.insert(
                        Box::<str>::from(stringify!(#field_names)),
                        Box::new(self.#field_names.clone()),
                    );
                )*
                map
            }

            fn load_from_owned(mut owned_state: node_tree::services::node_registry::SFieldMap) -> Result<Self, String> where Self: Sized {
                #(#type_definitions)*
                Ok(Self {
                    base: node_tree::prelude::NodeBase::new(stringify!(#name).to_string()),
                    #(#deserialization,)*
                })
            }
        }
        
        // Runs before main.
        #[node_tree::startup::ctor]
        unsafe fn #static_name() {
            use node_tree::prelude::Registered;
            
            node_tree::services::node_registry::register_deserializer(std::any::type_name::<#name>().into(), Box::new(|s_field_map| {
                let node: #name = #name::load_from_owned(s_field_map)?;
                Ok(Box::new(node) as Box<dyn node_tree::traits::node::Node>)
            }));
        };
    };

    expanded.into()
}


/*
 * Tree
 *      Abstract
 */


/// Implements all of the required traits for a `NodeTree` type to be created.
#[proc_macro_derive(Tree)]
pub fn tree(input: TokenStream) -> TokenStream {
    
    // Parse the input tokens into a syntax tree,
    // and get the name of the struct.
    let input: DeriveInput = parse_macro_input!(input as DeriveInput);
    let name:  syn::Ident  = input.ident;

    // Expanded the code to host the boilerplate implementations of the NodeTree, Deref, and
    // DerefMut traits.
    let expanded = quote! {
        impl node_tree::traits::node_tree::NodeTree for #name {
            unsafe fn set_base(&mut self, base: node_tree::structs::node_tree_base::NodeTreeBase) {
                self.base = Some(base);
            }
            
            fn base(&self) -> &node_tree::structs::node_tree_base::NodeTreeBase {
                unsafe {
                    self.base.as_ref().unwrap_unchecked()
                }
            }

            fn base_mut(&mut self) -> &mut node_tree::structs::node_tree_base::NodeTreeBase {
                unsafe {
                    self.base.as_mut().unwrap_unchecked()
                }
            }

            fn as_dyn(&self) -> &dyn node_tree::traits::node_tree::NodeTree {
                self
            }

            fn as_dyn_mut(&mut self) -> &mut dyn node_tree::traits::node_tree::NodeTree {
                self
            }

            fn as_dyn_raw(&self) -> *const dyn node_tree::traits::node_tree::NodeTree {
                self as *const dyn node_tree::traits::node_tree::NodeTree
            }
            
            fn as_dyn_raw_mut(&mut self) -> *mut dyn node_tree::traits::node_tree::NodeTree {
                self as *mut dyn node_tree::traits::node_tree::NodeTree
            }

            fn as_any(&self) -> &dyn std::any::Any {
                self
            }

            fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
                self
            }
        }

        impl std::ops::Deref for #name {
            type Target = node_tree::structs::node_tree_base::NodeTreeBase;
            fn deref(&self) -> &Self::Target {
                unsafe {
                    self.base.as_ref().unwrap_unchecked()
                }
            }
        }

        impl std::ops::DerefMut for #name {
            fn deref_mut(&mut self) -> &mut Self::Target {
                unsafe {
                    self.base.as_mut().unwrap_unchecked()
                }
            }
        }
    };

    // Return the generated impl as a TokenStream
    TokenStream::from(expanded)
}


/*
 * Scene
 *      Macro
 */


/// A simple short-hand way of initializing `NodeScene`s quickly and elegantly.
/// Here is an example of a `NodeScene` initialized in this manner:
/// ```rust, ignore
/// use node_tree::prelude::*;
///
/// let scene: NodeScene = scene! {
///     OwnerNode [
///         NodeWithNoArgs,
///         NodeWithArgs(1, "two"), // Required when _init() is defined with arguments.
///         NodeWithSettings {
///            field1: "value1", // These are public fields that are set on the node.
///            field2: 2
///         },
///         NodeWithChildren [
///             Foo,
///             Bar
///         ],
///         NodeWithChildrenAndSettings {
///             field1: "value1",
///             field2: 2,
///             [
///                 Foo,
///                 Bar
///             ]
///         }
///     ]
/// };
///
/// let named_scene: NodeScene = scene! {
///     Owner: "Owner" [
///         Child: "ChildA",
///         Child: "ChildB"
///     ]
/// };
///
/// let complex_scene: NodeScene = scene! {
///     RootNode [
///         NodeA,
///         NodeB [
///             NodeC,
///             $scene // Links a scene with the name following `$` to that position...
///         ]
///     ]
/// };
/// ```
#[proc_macro]
pub fn scene(input: TokenStream) -> TokenStream {
    let root:     SceneNode    = syn::parse_macro_input!(input as SceneNode);
    let expanded: TokenStream2 = generate_node(&root);

    TokenStream::from(quote! {
        {
            use node_tree::traits::element::AsElement;
            
            #expanded
        }
    })
}


/*
 * Class
 *      Macro
 */


/// An easy way to be able to define a Node.
/// 
/// # Example
/// ```rust, ignore
/// use node_tree::prelude::*;
///
/// class! {
///     
///     /// Documentation and attributes are supported!
///     pub declare NodeName extends UniqueTraitGroup1, UniqueTraitGroup2; // Will need to write a separate `impl` for each trait listed here.
///     
///     /// A signal can be connected to node functions and emitted.
///     /// Safety is guaranteed via the scene tree.
///     pub signal on_event(param_name: Type, ..);
///
///     /// Constants are supported.
///     const SOME_CONST: &str = "Hello";
///
///     /// Fields can be defined like so, with default or without default values.
///     let field_uninit:      u8;
///     let field_initialized: String = "These are not constant expressions!".to_string();
///
///     // Fields can have special attributes, like so:
///     default let field_default: u8; // Will automatically initialzie to zero.
///     unique  let field_unique: *mut c_void; // When cloned or serialized, this will safetly be initialized as a `None` value.
///
///     // Exportable fields will be saved and loaded from whenever a node scene is serialized.
///     // Note: All exported types will need to implement the `Exportable` trait.
///     export         let some_parameter: String;
///     export default let some_parameter_default: bool;
///
///     // Hooks are any system functions that can be overridden.
///     // This include the constructor `_init()`, `loaded()`, `ready()`, `process()`, `terminal()`, and `process_mode()`.
///
///     /// The constructor may only need to be implemented if there exists fields that do not have
///     /// a default value.
///     /// Note that this macro will automatically create a `new()` invokation, even without a
///     /// predefined `_init()` hook. All attributes given to this hook will be transferred to the
///     /// `new()` function.
///     hk _init(starter_value: u8) {
///         
///         // Initialize a value by creating a variable with the same field name:
///         let field_uninit: u8 = starter_value;
///     }
///
///     /// Functions can be declared as per usual.
///     fn foo(bar: Type) -> Type {
///         todo!();
///     }
/// }
/// ```
#[proc_macro]
pub fn class(input: TokenStream) -> TokenStream {
    
    // Parse the given macro as a class definition.
    let Class {
        name,
        extends,
        attribs,
        public,
        signals,
        consts,
        fields,
        hooks,
        funcs
    } = parse_macro_input!(input as Class);

    // Generate the class attributes, such as visibility and inherited traits.
    let visibility: TokenStream2 = if public { quote! { pub } } else { TokenStream2::new() };
    
    let extends = extends.iter().map(|inh_trait| {
        quote! {
            node_tree::intertrait::castable_to!(crate = node_tree::intertrait | #name => node_tree::traits::node::Node, #inh_trait);
        }
    });
    
    // Generate the constant fields.
    let const_fields = consts.iter().map(|Const { attribs, public, declare }| {
        let visibility: TokenStream2 = if *public { quote! { pub } } else { TokenStream2::new() };
        quote! {
            #(#attribs)*
            #visibility #declare
        }
    });

    // Generate the signal fields.
    let signal_fields = signals.iter().map(|signal| {
        let Signal {
            name,
            public,
            attribs,
            args
        } = signal;
        
        let visibility: TokenStream2 = if *public { quote! { pub } } else { TokenStream2::new() };
        match args.len() {
            0 => quote! { #(#attribs)* #visibility #name: node_tree::prelude::Signal<()> },
            1 => {
                let only_arg: &syn::Type = &args[0];
                quote! { #(#attribs)* #visibility #name: node_tree::prelude::Signal<#only_arg> }
            },
            _ => quote! { #(#attribs)* #visibility #name: node_tree::prelude::Signal<(#(#args,)*)>}
        }
    });

    // Generate the custom fields.
    let custom_fields = fields.iter().map(|field| {
        let Field {
            name,
            attribs,
            kind,
            public,
            ty,
            ..
        } = field;

        let visibility: TokenStream2 = if *public { quote! { pub } } else { TokenStream2::new() };
        match kind {
            FieldKind::Regular        => quote! { #(#attribs)* #visibility #name: node_tree::structs::node_field::Field<#ty>           },
            FieldKind::Export         => quote! { #(#attribs)* #visibility #name: node_tree::structs::node_field::ExportableField<#ty> },
            FieldKind::ExportDefault  => quote! { #(#attribs)* #visibility #name: node_tree::structs::node_field::ExportableField<#ty> },
            FieldKind::Unique         => quote! { #(#attribs)* #visibility #name: node_tree::structs::node_field::UniqueField<#ty>     },
            FieldKind::Default        => quote! { #(#attribs)* #visibility #name: node_tree::structs::node_field::DefaultField<#ty>    }
        }
    });

    // Generate the constructor.
    // Take note if an _init definition is not required.
    const INIT: &str = "_init";

    let needs_init: bool          = fields.iter().any(|field| field.init.is_none() && !field.kind.supports_default_init());
    let init_hook:  Option<&Hook> = hooks.iter().find(|hook| hook.name == INIT);

    let constructor_signals = signals.iter().map(|signal| {
        let signal_name: &syn::Ident = &signal.name;
        quote! {
            #signal_name: node_tree::prelude::Signal::new()
        }
    });

    let constructor_fields = fields.iter().map(|field| {
        let Field {
            name,
            kind,
            ty,
            ..
        } = field;

        match kind {
            FieldKind::Regular => if let Some(default_value) = &field.init {
                quote! {
                    #name: node_tree::structs::node_field::Field::new(#default_value)
                }
            } else {
                quote! {
                    #name: node_tree::structs::node_field::Field::new(#name)
                }
            },
            FieldKind::Export => if let Some(default_value) = &field.init {
                quote! {
                    #name: node_tree::structs::node_field::ExportableField::new(#default_value)
                }
            } else {
                quote! {
                    #name: node_tree::structs::node_field::ExportableField::new(#name)
                }
            },
            FieldKind::ExportDefault => quote! {
                #name: node_tree::structs::node_field::ExportableField::new(#ty::default())
            }, 
            FieldKind::Unique => if let Some(default_value) = &field.init {
                quote! {
                    #name: node_tree::structs::node_field::UniqueField::new(#default_value)
                }
            } else {
                quote! {
                    #name: node_tree::structs::node_field::UniqueField::new(#name)
                }
            },
            FieldKind::Default => quote! {
                #name: node_tree::structs::node_field::DefaultField::new(#ty::default())
            }
        }
    });

    // Generate other hook implementations.
    let hook_impls = hooks.iter().filter(|hook| hook.name != INIT).map(|hook| {
        let Hook {
            name,
            attribs,
            sig,
            args,
            out,
            body
        } = hook;

        let out: TokenStream2 = match out {
            Some(out) => quote! { -> #out },
            None      => TokenStream2::new()
        };

        quote! {
            #(#attribs)*
            fn #name(#sig #(, #args)*) #out {
                #body
            }
        }
    });

    // Generate the functions.
    let func_impls = funcs.iter().map(|Func { attribs, public, declare }| {
        let visibility: TokenStream2 = if *public { quote! { pub } } else { TokenStream2::new() };
        quote! {
            #(#attribs)*
            #visibility #declare
        }
    });

    // Generate the final implementation.
    let constructor: TokenStream2 = match init_hook {
        Some(init_hook) => {
            let init_attribs: &[syn::Attribute] = &init_hook.attribs;
            let init_args:    &[syn::PatType]   = &init_hook.args;
            let init_body:    &[syn::Stmt]      = &init_hook.body.stmts;

            quote! {
                #(#init_attribs)*
                #visibility fn new(#(#init_args),*) -> Self {
                    #(#init_body)*
                    Self {
                        base: node_tree::prelude::NodeBase::new(stringify!(#name).to_string()),
                        #(#constructor_signals,)*
                        #(#constructor_fields,)*
                    }
                }

            }
        },
        None => {
            if needs_init {
                panic!("Requires an _init() hook");
            }

            quote! {
                #visibility fn new() -> Self {
                    Self {
                        base: node_tree::prelude::NodeBase::new(stringify!(#name).to_string()),
                        #(#constructor_signals,)*
                        #(#constructor_fields,)*
                    }
                }
            }
        }
    };

    let expanded: TokenStream2 = quote! {
        #(#attribs)*
        #[derive(Debug, Clone, node_tree::prelude::Abstract, node_tree::prelude::Register)]
        #visibility struct #name {
            base: node_tree::prelude::NodeBase,
            #(#signal_fields,)*
            #(#custom_fields,)*
        }

        impl #name {
            #(#const_fields)*
            #constructor
            #(#func_impls)*
        }

        impl node_tree::prelude::Node for #name {
            #(#hook_impls)*
        }

        #(#extends)*
    };
    TokenStream::from(expanded)
}


/*
 * Connect
 *      Macro
 */


/// Allows for a safe abstraction for connecting listener functions in other nodes via `Tp<T>` to a
/// signal.
///
/// # Note
/// - This will enforce the use of tree pointers (`Tp<T>`).
/// - Must be called within a node's member function or hook.
///
/// # Example
/// ```rust, ignore
/// // Assuming that this is within a node's member function or hook.
/// let tp: Tp<YourNode> = todo!();
///
/// connect! { signal_name -> tp.constant_listener };
/// connect! { signal_name ~> tp.one_shot_listener };
/// ```
#[proc_macro]
pub fn connect(input: TokenStream) -> TokenStream {
    let Connection {
        signal_name,
        one_shot,
        tree_pointer,
        callback
    } = parse_macro_input!(input as Connection);

    // TODO: Support argument passing!
    
    let connect_type: TokenStream2 = if one_shot { quote! { connect_once } } else { quote! { connect } };
    TokenStream::from(quote! {
        unsafe { // Enforce `move,` as without it a segfault occurs!
            let tp_: node_tree::prelude::Tp<_> = #tree_pointer;
            self.#signal_name.#connect_type(move |args| {
                tp_.#callback(&args)
            });
        }
    })
}