craby_codegen 0.1.0-rc.3

Craby code generator
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
use std::collections::BTreeMap;

use craby_common::{
    constants::{HASH_COMMENT_PREFIX, crate_dir, impl_mod_name},
    utils::string::{pascal_case, snake_case},
};
use indoc::formatdoc;

use crate::{
    common::IntoCode,
    generators::types::TemplateResult,
    platform::rust::RsCxxBridge,
    types::{CodegenContext, CxxNamespace, Schema},
    utils::indent_str,
};

use super::types::{Generator, GeneratorInvoker, Template};

pub struct RsTemplate;
pub struct RsGenerator;

pub enum RsFileType {
    /// lib.rs
    CrateEntry,
    /// ffi.rs
    FFIEntry,
    /// generated.rs
    Generated,
    /// impl.rs
    ModImpl,
}

impl RsTemplate {
    fn impl_mods(&self, schemas: &[Schema]) -> Vec<String> {
        schemas
            .iter()
            .map(|schema| impl_mod_name(&schema.module_name))
            .collect::<Vec<String>>()
    }

    fn rs_cxx_bridges(&self, schemas: &[Schema]) -> Result<Vec<RsCxxBridge>, anyhow::Error> {
        let res = schemas
            .iter()
            .map(|schema| schema.as_rs_cxx_bridge())
            .collect::<Result<Vec<_>, _>>()?;

        Ok(res)
    }

    /// Generates Rust FFI extern declarations for C++ bridging.
    ///
    /// # Generated Code
    ///
    /// ```rust,ignore
    /// #[cxx::bridge(namespace = "craby::mymodule::bridging")]
    /// pub mod bridging {
    ///     struct MyStruct {
    ///         foo: String,
    ///         bar: f64,
    ///     }
    ///
    ///     enum MyEnum {
    ///         Foo,
    ///         Bar,
    ///     }
    ///
    ///     extern "Rust" {
    ///         type MyModule;
    ///
    ///         #[cxx_name = "createMyModule"]
    ///         fn create_my_module(id: usize, data_path: &str) -> Box<MyModule>;
    ///
    ///         #[cxx_name = "multiply"]
    ///         fn my_module_multiply(it_: &mut MyModule, a: f64, b: f64) -> Result<f64>;
    ///     }
    /// }
    /// ```
    fn rs_cxx_extern(
        &self,
        cxx_ns: &CxxNamespace,
        rs_cxx_bridges: &[RsCxxBridge],
        has_signals: bool,
        schemas: &[Schema],
    ) -> String {
        let (impl_types, cxx_externs, struct_defs, enum_defs) = rs_cxx_bridges.iter().fold(
            (vec![], vec![], vec![], vec![]),
            |(mut impl_types, mut externs, mut structs, mut enums), bridge| {
                impl_types.push(bridge.impl_type.clone());
                externs.extend(bridge.func_extern_sigs.clone());
                structs.extend(bridge.struct_defs.clone());
                enums.extend(bridge.enum_defs.clone());
                (impl_types, externs, structs, enums)
            },
        );

        let cxx_extern_stmts = indent_str(&[impl_types, cxx_externs].concat().join("\n\n"), 4);
        let cxx_extern = formatdoc! {
            r#"
            extern "Rust" {{
            {cxx_extern_stmts}
            }}"#,
        };

        // Add signal enum and payload extraction functions
        let signal_ffi_functions = if has_signals {
            schemas.iter().flat_map(|schema| {
                if schema.signals.is_empty() {
                    return vec![];
                }
                
                let signal_enum_name = format!("{}Signal", schema.module_name);
                let mut functions = vec![format!("type {};", signal_enum_name)];
                
                // Generate payload extraction function for each signal
                for signal in &schema.signals {
                    if let Some(payload_type) = &signal.payload_type {
                        let payload_type_name = payload_type.as_rs_type()
                            .map(|t| t.into_code())
                            .unwrap_or_else(|_| "String".to_string());
                        let function_name = format!("get_{}_payload", snake_case(&signal.name));
                        functions.push(format!(
                            "fn {}(s: &{}) -> {};",
                            function_name, signal_enum_name, payload_type_name
                        ));
                    }
                }
                
                // Add drop_signal function for memory management
                functions.push(format!(
                    "unsafe fn drop_signal(signal: *mut {});",
                    signal_enum_name
                ));
                
                functions
            }).collect::<Vec<_>>()
        } else {
            vec![]
        };

        let signal_ffi = if !signal_ffi_functions.is_empty() {
            formatdoc! {
                r#"
                extern "Rust" {{
                {signal_ffi_functions}
                }}"#,
                signal_ffi_functions = indent_str(&signal_ffi_functions.join("\n"), 4),
            }
        } else {
            String::new()
        };

        let cxx_signal_manager = if has_signals {
            // Get signal enum type for each schema
            let signal_enum_types: Vec<String> = schemas.iter()
                .filter(|s| !s.signals.is_empty())
                .map(|s| format!("{}Signal", s.module_name))
                .collect();
            
            let signal_type = signal_enum_types.first().unwrap().clone();
            
            formatdoc! {
                r#"
                #[namespace = "{cxx_ns}::signals"]
                unsafe extern "C++" {{
                    include!("CrabySignals.h");

                    type SignalManager;

                    unsafe fn emit(self: &SignalManager, id: usize, name: &str, signal: *mut {signal_type});
                    
                    #[rust_name = "get_signal_manager"]
                    fn getSignalManager() -> &'static SignalManager;
                }}"#,
                signal_type = signal_type,
            }
        } else {
            String::new()
        };

        let code = indent_str(
            &[
                struct_defs.join("\n\n"),
                enum_defs.join("\n\n"),
                cxx_extern,
                signal_ffi,
                cxx_signal_manager,
            ]
            .iter()
            .filter(|s| !s.is_empty())
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join("\n\n"),
            4,
        );

        formatdoc! {
            r#"
            #[cxx::bridge(namespace = "{cxx_ns}::bridging")]
            pub mod bridging {{
            {code}
            }}"#,
        }
    }

    /// Generates Rust FFI function implementations.
    ///
    /// # Generated Code
    ///
    /// ```rust,ignore
    /// fn create_my_module(id: usize, data_path: &str) -> Box<MyModule> {
    ///     let ctx = Context::new(id, data_path);
    ///     Box::new(MyModule::new(ctx))
    /// }
    ///
    /// fn my_module_multiply(it_: &mut MyModule, a: f64, b: f64) -> Result<f64> {
    ///     craby::catch_panic!({
    ///         let ret = it_.multiply(a, b);
    ///         ret
    ///     })
    /// }
    /// ```
    fn rs_cxx_impl(&self, rs_cxx_bridges: &[RsCxxBridge]) -> Vec<String> {
        rs_cxx_bridges
            .iter()
            .map(|bridge| bridge.func_impls.join("\n\n"))
            .collect::<Vec<_>>()
    }

    /// Generate the traits code for the given schema.
    ///
    /// ```rust,ignore
    /// pub trait MyModuleSpec {
    ///     fn multiply(&mut self, a: f64, b: f64) -> f64;
    /// }
    /// ```
    fn rs_spec(&self, schema: &Schema) -> Result<String, anyhow::Error> {
        let trait_name = pascal_case(&format!("{}Spec", schema.module_name));
        let mut methods = schema
            .methods
            .iter()
            .map(|spec| -> Result<String, anyhow::Error> {
                let sig = spec.try_into_impl_sig()?;
                Ok(format!("{sig};"))
            })
            .collect::<Result<Vec<_>, _>>()?;

        let signal_enum = if !schema.signals.is_empty() {
            let signal_enum_name = format!("{}Signal", schema.module_name);
            let (signal_members, pattern_matches, pattern_matches_with_data) = schema
                .signals
                .iter()
                .map(|signal| {
                    let member_name = pascal_case(&signal.name);
                    
                    // Create enum variant based on payload type
                    let enum_member = if let Some(payload_type) = &signal.payload_type {
                        // Convert payload_type to Rust type
                        match payload_type.as_rs_type() {
                            Ok(rs_type) => format!("{member_name}({}),", rs_type.into_code()),
                            Err(_) => format!("{member_name},"), // Create without payload if conversion fails
                        }
                    } else {
                        format!("{member_name},")
                    };
                    
                    let enum_pattern_match = formatdoc! {
                        r#"{signal_enum_name}::{member_name} => {{
                            unsafe {{
                                manager.emit(self.id(), "{raw}", std::ptr::null_mut());
                            }}
                        }}"#,
                        raw = signal.name,
                    };
                    
                    // if there is a data payload
                    let enum_pattern_match_with_data = if signal.payload_type.is_some() {
                        formatdoc! {
                            r#"{signal_enum_name}::{member_name}(data) => {{
                                let signal = Box::new({signal_enum_name}::{member_name}(data));
                                let signal_ptr = Box::into_raw(signal);
                                unsafe {{
                                    manager.emit(self.id(), "{raw}", signal_ptr);
                                }}
                            }}"#,
                            signal_enum_name = signal_enum_name,
                            raw = signal.name,
                        }
                    } else {
                        enum_pattern_match.clone()
                    };

                    (enum_member, enum_pattern_match, enum_pattern_match_with_data)
                })
                .fold(
                    (Vec::new(), Vec::new(), Vec::new()),
                    |(mut members, mut patterns, mut patterns_with_data), (member, pattern, pattern_with_data)| {
                        members.push(member);
                        patterns.push(pattern);
                        patterns_with_data.push(pattern_with_data);
                        (members, patterns, patterns_with_data)
                    },
                );

            let signal_members_exprs = indent_str(&signal_members.join("\n"), 4);
            let signal_enum = formatdoc! {
                r#"
                pub enum {signal_enum_name} {{
                {signal_members_exprs}
                }}"#,
            };

            // Distinguish signals with and without payload_type
            let has_payload_signals = schema.signals.iter().any(|s| s.payload_type.is_some());
            
            let pattern_match_stmts = if has_payload_signals {
                // Handle both cases with and without data payload
                // Actual implementation may be more complex
                indent_str(&pattern_matches_with_data.join("\n"), 8)
            } else {
                indent_str(&pattern_matches.join("\n"), 8)
            };
            
            let emit_impl = formatdoc! {
                r#"
                fn emit(&self, signal_name: {signal_enum_name}) {{
                    let manager = crate::ffi::bridging::get_signal_manager();
                    match signal_name {{
                {pattern_match_stmts}
                    }}
                }}"#,
            };

            methods.insert(0, emit_impl);

            Some(signal_enum)
        } else {
            None
        };

        let method_defs = indent_str(&methods.join("\n"), 4);
        let spec_trait = formatdoc! {
            r#"
            pub trait {trait_name} {{
                fn new(ctx: Context) -> Self;
                fn id(&self) -> usize;
            {method_defs}
            }}"#
        };

        let content = [Some(spec_trait), signal_enum]
            .into_iter()
            .flatten()
            .collect::<Vec<_>>()
            .join("\n\n");

        Ok(content)
    }

    /// Generates default implementation structure for module.
    ///
    /// # Generated Code
    ///
    /// ```rust,ignore
    /// use craby::{prelude::*, throw};
    ///
    /// use crate::ffi::bridging::*;
    /// use crate::generated::*;
    ///
    /// pub struct MyModule {
    ///     ctx: Context,
    /// }
    ///
    /// impl MyModuleSpec for MyModule {
    ///     fn new(ctx: Context) -> Self {
    ///         MyModule { ctx }
    ///     }
    ///
    ///     fn id(&self) -> usize {
    ///         self.ctx.id
    ///     }
    ///
    ///     fn multiply(&mut self, a: Number, b: Number) -> Number {
    ///         unimplemented!();
    ///     }
    /// }
    /// ```
    fn rs_impl(&self, schema: &Schema) -> Result<String, anyhow::Error> {
        let struct_name = pascal_case(&schema.module_name);
        let trait_name = pascal_case(&format!("{}Spec", schema.module_name));
        let methods = schema
            .methods
            .iter()
            .map(|spec| -> Result<String, anyhow::Error> {
                let func_sig = spec.try_into_impl_sig()?;
                let code = formatdoc! {
                  r#"
                  {func_sig} {{
                      unimplemented!();
                  }}"#,
                };

                Ok(code)
            })
            .collect::<Result<Vec<_>, _>>()?;

        let method_impls = indent_str(&methods.join("\n\n"), 4);
        let content = formatdoc! {
            r#"
            use craby::{{prelude::*, throw}};

            use crate::ffi::bridging::*;
            use crate::generated::*;

            pub struct {struct_name} {{
                ctx: Context,
            }}

            #[craby_module]
            impl {trait_name} for {struct_name} {{
            {method_impls}
            }}"#,
        };

        Ok(content)
    }

    /// Generate the `lib.rs` file for the given code generation results.
    ///
    /// ```rust,ignore
    /// pub(crate) mod generated;
    /// pub(crate) mod ffi;
    ///
    /// pub(crate) mod my_module_impl;
    /// ```
    fn lib_rs(&self, schemas: &[Schema]) -> Result<String, anyhow::Error> {
        let impl_mods = self
            .impl_mods(schemas)
            .iter()
            .map(|impl_mod| format!("pub(crate) mod {impl_mod};"))
            .collect::<Vec<String>>();

        let impl_mod_defs = impl_mods.join("\n");
        let content = formatdoc! {
            r#"
            #[rustfmt::skip]
            pub(crate) mod ffi;
            pub(crate) mod generated;

            {impl_mod_defs}"#,
        };

        Ok(content)
    }

    /// Generate the `ffi.rs` file for the given code generation results.
    ///
    /// ```rust,ignore
    /// use craby::prelude::*;
    ///
    /// use crate::my_module_impl::*;
    /// use crate::generated::*;
    ///
    /// use bridging::*;
    ///
    /// #[cxx::bridge(namespace = "craby::mymodule")]
    /// pub mod bridging {
    ///     extern "Rust" {
    ///         #[cxx_name = "numericMethod"]
    ///         fn my_module_numeric_method(arg: f64) -> f64;
    ///     }
    /// }
    ///
    /// fn my_module_numeric_method(arg: f64) -> f64 {
    ///     MyModule::numeric_method(arg)
    /// }
    /// ```
    fn ffi_rs(&self, ctx: &CodegenContext) -> Result<String, anyhow::Error> {
        let cxx_ns = CxxNamespace::from(&ctx.project_name);
        let impl_mods = self
            .impl_mods(&ctx.schemas)
            .iter()
            .map(|impl_mod| format!("use crate::{impl_mod}::*;"))
            .collect::<Vec<String>>();

        let has_signals = ctx.schemas.iter().any(|schema| !schema.signals.is_empty());
        let rs_cxx_bridges = self.rs_cxx_bridges(&ctx.schemas)?;
        let cxx_impls = self.rs_cxx_impl(&rs_cxx_bridges);
        let cxx_externs = self.rs_cxx_extern(&cxx_ns, &rs_cxx_bridges, has_signals, &ctx.schemas);
        
        // Generate signal payload extraction function implementation
        let signal_payload_impls = if has_signals {
            ctx.schemas.iter().flat_map(|schema| {
                if schema.signals.is_empty() {
                    return vec![];
                }
                
                let signal_enum_name = format!("{}Signal", schema.module_name);
                let mut impls: Vec<String> = schema.signals.iter().filter_map(|signal| {
                    signal.payload_type.as_ref().map(|payload_type| {
                        let payload_type_name = payload_type.as_rs_type()
                            .map(|t| t.into_code())
                            .unwrap_or_else(|_| "String".to_string());
                        let function_name = format!("get_{}_payload", snake_case(&signal.name));
                        let signal_variant = pascal_case(&signal.name);
                        
                        formatdoc! {
                            r#"
                            fn {function_name}(s: &{signal_enum_name}) -> {payload_type_name} {{
                                match s {{
                                    {signal_enum_name}::{signal_variant}(payload) => (*payload).clone(),
                                    _ => panic!("Invalid signal type for {function_name}"),
                                }}
                            }}"#,
                        }
                    })
                }).collect();
                
                // Add drop_signal implementation
                impls.push(formatdoc! {
                    r#"
                    unsafe fn drop_signal(signal: *mut {signal_enum_name}) {{
                        if !signal.is_null() {{
                            drop(Box::from_raw(signal));
                        }}
                    }}"#,
                    signal_enum_name = signal_enum_name,
                });
                
                impls
            }).collect::<Vec<_>>()
        } else {
            vec![]
        };
        
        let impl_mods = impl_mods.join("\n");
        let cxx_impls = cxx_impls.join("\n\n");
        let signal_impls = signal_payload_impls.join("\n\n");
        let content = formatdoc! {
            r#"
            #[rustfmt::skip]
            use craby::prelude::*;

            {impl_mods}
            use crate::generated::*;

            use bridging::*;

            {cxx_externs}

            {cxx_impls}

            {signal_impls}"#,
        };

        Ok(content)
    }

    /// Generate the `generated.rs` file for the given code generation results.
    ///
    /// ```rust,ignore
    /// use craby::prelude::*;
    ///
    /// use crate::ffi::bridging::*;
    ///
    /// pub trait MyModuleSpec {
    ///     fn multiply(&mut self, a: f64, b: f64) -> f64;
    /// }
    /// ```
    pub fn generated_rs(&self, schemas: &[Schema]) -> Result<String, anyhow::Error> {
        let mut spec_codes = Vec::with_capacity(schemas.len());
        let mut type_aliases = BTreeMap::new();

        for schema in schemas {
            // Collect the type implementations
            schema.try_collect_type_impls(&mut type_aliases)?;
            spec_codes.push(self.rs_spec(schema)?);
        }

        let hash = Schema::to_hash(schemas);
        let hash_comment = format!("{HASH_COMMENT_PREFIX} {hash}");
        let type_impls = type_aliases.into_values().collect::<Vec<_>>();

        let content = [
            vec![formatdoc! {
                r#"
                {hash_comment}
                #[rustfmt::skip]
                use craby::prelude::*;

                use crate::ffi::bridging::*;"#,
            }],
            spec_codes,
            type_impls,
        ]
        .concat()
        .join("\n\n");

        Ok(content)
    }
}

impl Template for RsTemplate {
    type FileType = RsFileType;

    fn render(
        &self,
        ctx: &CodegenContext,
        file_type: &Self::FileType,
    ) -> Result<Vec<TemplateResult>, anyhow::Error> {
        let base_path = crate_dir(&ctx.root).join("src");
        let res = match file_type {
            RsFileType::CrateEntry => vec![TemplateResult {
                path: base_path.join("lib.rs"),
                content: self.lib_rs(&ctx.schemas)?,
                overwrite: false,
            }],
            RsFileType::FFIEntry => vec![TemplateResult {
                path: base_path.join("ffi.rs"),
                content: self.ffi_rs(ctx)?,
                overwrite: true,
            }],
            RsFileType::Generated => vec![TemplateResult {
                path: base_path.join("generated.rs"),
                content: self.generated_rs(&ctx.schemas)?,
                overwrite: true,
            }],
            RsFileType::ModImpl => ctx
                .schemas
                .iter()
                .map(|schema| -> Result<TemplateResult, anyhow::Error> {
                    let impl_code = self.rs_impl(schema)?;

                    Ok(TemplateResult {
                        path: base_path.join(format!("{}.rs", impl_mod_name(&schema.module_name))),
                        content: impl_code,
                        overwrite: false,
                    })
                })
                .collect::<Result<Vec<_>, _>>()?,
        };

        Ok(res)
    }
}

impl Default for RsGenerator {
    fn default() -> Self {
        Self::new()
    }
}

impl RsGenerator {
    pub fn new() -> Self {
        Self
    }
}

impl Generator<RsTemplate> for RsGenerator {
    fn cleanup(_: &CodegenContext) -> Result<(), anyhow::Error> {
        Ok(())
    }

    fn generate(&self, ctx: &CodegenContext) -> Result<Vec<TemplateResult>, anyhow::Error> {
        let template = self.template_ref();
        let res = [
            template.render(ctx, &RsFileType::CrateEntry)?,
            template.render(ctx, &RsFileType::FFIEntry)?,
            template.render(ctx, &RsFileType::Generated)?,
            template.render(ctx, &RsFileType::ModImpl)?,
        ]
        .into_iter()
        .flatten()
        .collect::<Vec<_>>();

        Ok(res)
    }

    fn template_ref(&self) -> &RsTemplate {
        &RsTemplate
    }
}

impl GeneratorInvoker for RsGenerator {
    fn invoke_generate(&self, ctx: &CodegenContext) -> Result<Vec<TemplateResult>, anyhow::Error> {
        self.generate(ctx)
    }
}

#[cfg(test)]
mod tests {
    use insta::assert_snapshot;

    use crate::tests::get_codegen_context;

    use super::*;

    #[test]
    fn test_rs_generator() {
        let ctx = get_codegen_context();
        let generator = RsGenerator::new();
        let results = generator.generate(&ctx).unwrap();
        let result = results
            .iter()
            .map(|res| format!("{}\n{}", res.path.display(), res.content))
            .collect::<Vec<_>>()
            .join("\n\n");

        assert_snapshot!(result);
    }
}