Skip to main content

rusteal_codegen/
lib.rs

1// rusteal-codegen: reads UHT JSON, generates Rust bindings + C++ wrappers + FuncId tables.
2
3pub mod schema;
4pub mod naming;
5pub mod config;
6pub mod context;
7pub mod type_map;
8pub mod defaults;
9pub mod filter;
10pub mod rust_gen;
11pub mod cpp_gen;
12
13use std::path::Path;
14
15use crate::config::{ProjectConfig, ProjectLayout};
16use crate::schema::{ClassesFile, EnumsFile, StructsFile};
17
18/// Run the generate command. Main entry point for codegen.
19///
20/// `project_root` is the directory holding the .uproject and `rusteal.toml`.
21pub fn run_generate(project_root: &Path) {
22    let config = ProjectConfig::load(project_root).unwrap_or_else(|e| {
23        eprintln!("rusteal-codegen: {e}");
24        std::process::exit(1);
25    });
26    let codegen = &config.codegen;
27    let layout = ProjectLayout::new(project_root);
28
29    let uht_input = layout.uht_json();
30    let classes_path = uht_input.join("rusteal_classes.json");
31    let structs_path = uht_input.join("rusteal_structs.json");
32    let enums_path = uht_input.join("rusteal_enums.json");
33    // The generated crate's directory; its sources go under `src/`.
34    let rust_out = layout.bindings_crate();
35    let rust_src = rust_out.join("src");
36    let cpp_out = layout.cpp_generated();
37
38    eprintln!("rusteal-codegen: loading JSON...");
39
40    // Parse JSON files
41    let classes_json: ClassesFile = {
42        let data = std::fs::read_to_string(&classes_path)
43            .unwrap_or_else(|e| panic!("Failed to read {}: {e}", classes_path.display()));
44        serde_json::from_str(&data)
45            .unwrap_or_else(|e| panic!("Failed to parse {}: {e}", classes_path.display()))
46    };
47
48    let structs_json: StructsFile = {
49        let data = std::fs::read_to_string(&structs_path)
50            .unwrap_or_else(|e| panic!("Failed to read {}: {e}", structs_path.display()));
51        serde_json::from_str(&data)
52            .unwrap_or_else(|e| panic!("Failed to parse {}: {e}", structs_path.display()))
53    };
54
55    let enums_json: EnumsFile = {
56        let data = std::fs::read_to_string(&enums_path)
57            .unwrap_or_else(|e| panic!("Failed to read {}: {e}", enums_path.display()));
58        serde_json::from_str(&data)
59            .unwrap_or_else(|e| panic!("Failed to parse {}: {e}", enums_path.display()))
60    };
61
62    eprintln!(
63        "  Loaded {} classes, {} structs, {} enums",
64        classes_json.classes.len(),
65        structs_json.structs.len(),
66        enums_json.enums.len()
67    );
68
69    // Build context
70    let mut ctx = context::CodegenContext::new(
71        classes_json.classes,
72        structs_json.structs,
73        enums_json.enums,
74        codegen,
75    );
76
77    eprintln!(
78        "  Enabled modules: {:?}",
79        ctx.enabled_modules.iter().collect::<Vec<_>>()
80    );
81    for (module, classes) in &ctx.module_classes {
82        eprintln!("    {}: {} classes", module, classes.len());
83    }
84    for (module, structs) in &ctx.module_structs {
85        eprintln!("    {}: {} structs", module, structs.len());
86    }
87    for (module, enums) in &ctx.module_enums {
88        eprintln!("    {}: {} enums", module, enums.len());
89    }
90
91    // Apply filters
92    eprintln!("rusteal-codegen: filtering...");
93    filter::apply_filters(&mut ctx, &codegen.blocklist);
94
95    // Build function table (assign FuncIds)
96    eprintln!("rusteal-codegen: building function table...");
97    build_func_table(&mut ctx);
98    eprintln!("  {} functions in func_table", ctx.func_table.len());
99
100    // Generate the Rust bindings crate: sources, extensions, prelude, manifest.
101    eprintln!("rusteal-codegen: generating Rust code...");
102    rust_gen::generate(&ctx, &rust_src);
103    rust_gen::manual::write_manual_module(&rust_src);
104    rust_gen::prelude::write_prelude(&rust_src, &ctx);
105    rust_gen::cargo_toml::write_crate_files(&rust_out, &ctx, codegen);
106
107    // Generate C++ code
108    eprintln!("rusteal-codegen: generating C++ code...");
109    cpp_gen::generate(&ctx, &cpp_out);
110
111    // Generate module_deps.txt for Rusteal.Build.cs
112    generate_module_deps(codegen, &cpp_out);
113
114    // Post-generate verification
115    eprintln!("rusteal-codegen: verifying output...");
116    verify_output(&ctx, &rust_src, &cpp_out);
117
118    eprintln!("rusteal-codegen: done!");
119}
120
121/// Generate module_deps.txt listing UE module names needed by enabled features.
122fn generate_module_deps(config: &crate::config::CodegenConfig, cpp_out: &Path) {
123    use std::collections::BTreeSet;
124
125    let enabled_features: std::collections::HashSet<&str> =
126        config.features.iter().map(|s| s.as_str()).collect();
127
128    // Collect UE package names whose feature is enabled.
129    // "Core" is always needed (UE base) and not in the modules map.
130    let mut ue_modules: BTreeSet<&str> = BTreeSet::new();
131    ue_modules.insert("Core");
132    for (pkg, mapping) in &config.modules {
133        if enabled_features.contains(mapping.feature.as_str()) {
134            ue_modules.insert(pkg.as_str());
135        }
136    }
137
138    let content = ue_modules.iter().copied().collect::<Vec<_>>().join("\n");
139
140    let path = cpp_out.join("module_deps.txt");
141    std::fs::write(&path, &content)
142        .unwrap_or_else(|e| panic!("Failed to write {}: {e}", path.display()));
143
144    eprintln!("  module_deps.txt: {:?}", ue_modules.iter().collect::<Vec<_>>());
145}
146
147/// Verify codegen output integrity.
148fn verify_output(ctx: &context::CodegenContext, rust_out: &Path, cpp_out: &Path) {
149    let mut errors: Vec<String> = Vec::new();
150
151    // 1. FuncId contiguity: IDs must be 0..N-1 with no gaps
152    for (i, entry) in ctx.func_table.iter().enumerate() {
153        if entry.func_id != i as u32 {
154            errors.push(format!(
155                "FuncId gap: expected {} for module '{}' {}.{}, got {} (total functions: {})",
156                i, entry.module_name, entry.class_name, entry.func_name,
157                entry.func_id, ctx.func_table.len()
158            ));
159            break; // one error is enough to flag the issue
160        }
161    }
162
163    // 2. Required Rust output files exist and are non-empty
164    let rust_required = ["lib.rs", "func_ids.rs"];
165    for name in &rust_required {
166        let path = rust_out.join(name);
167        match std::fs::metadata(&path) {
168            Ok(m) if m.len() == 0 => errors.push(format!("Rust output empty: {}", path.display())),
169            Err(_) => errors.push(format!("Rust output missing: {}", path.display())),
170            _ => {}
171        }
172    }
173
174    // 3. Per-module mod.rs exists for each enabled module
175    for module_name in ctx.enabled_modules.iter() {
176        let mod_path = rust_out.join(module_name).join("mod.rs");
177        if !mod_path.exists() {
178            errors.push(format!("Module mod.rs missing: {}", mod_path.display()));
179        }
180    }
181
182    // 4. Required C++ output files exist and are non-empty
183    let cpp_required = ["RustealFuncIds.h", "RustealFillFuncTable.cpp"];
184    for name in &cpp_required {
185        let path = cpp_out.join(name);
186        match std::fs::metadata(&path) {
187            Ok(m) if m.len() == 0 => errors.push(format!("C++ output empty: {}", path.display())),
188            Err(_) => errors.push(format!("C++ output missing: {}", path.display())),
189            _ => {}
190        }
191    }
192
193    // 5. Summary stats
194    let func_count = ctx.func_table.len();
195    let module_count = ctx.enabled_modules.len();
196    let class_count: usize = ctx.module_classes.values().map(|v| v.len()).sum();
197    let struct_count: usize = ctx.module_structs.values().map(|v| v.len()).sum();
198    let enum_count: usize = ctx.module_enums.values().map(|v| v.len()).sum();
199
200    if errors.is_empty() {
201        eprintln!(
202            "  OK: {} modules, {} classes, {} structs, {} enums, {} functions",
203            module_count, class_count, struct_count, enum_count, func_count
204        );
205    } else {
206        eprintln!("  Verification FAILED:");
207        for e in &errors {
208            eprintln!("    - {e}");
209        }
210        std::process::exit(1);
211    }
212}
213
214/// Assign deterministic FuncIds to all exportable functions.
215fn build_func_table(ctx: &mut context::CodegenContext) {
216    let mut entries = Vec::new();
217
218    for (module_name, classes) in &ctx.module_classes {
219        for class in classes {
220            // Skip UInterface classes — their functions can't be called directly
221            if class.super_class.as_deref() == Some("Interface") {
222                continue;
223            }
224            for func in &class.funcs {
225                // Skip functions with unsupported param types
226                let all_supported = func.params.iter().all(|p| {
227                    type_map::map_property_type(
228                        &p.prop_type,
229                        p.class_name.as_deref(),
230                        p.struct_name.as_deref(),
231                        p.enum_name.as_deref(),
232                        p.enum_underlying_type.as_deref(),
233                        p.meta_class_name.as_deref(),
234                        p.interface_name.as_deref(),
235                    )
236                    .supported
237                });
238                if !all_supported {
239                    continue;
240                }
241                entries.push(context::FuncEntry {
242                    func_id: 0, // assigned below
243                    module_name: module_name.clone(),
244                    class_name: class.name.clone(),
245                    func_name: func.name.clone(),
246                    rust_func_name: naming::to_snake_case(&func.name),
247                    func: func.clone(),
248                    cpp_class_name: class.cpp_name.clone(),
249                    header: class.header.clone(),
250                });
251            }
252        }
253    }
254
255    // Sort by (module, class, func) for deterministic IDs
256    entries.sort_by(|a, b| {
257        a.module_name
258            .cmp(&b.module_name)
259            .then_with(|| a.class_name.cmp(&b.class_name))
260            .then_with(|| a.func_name.cmp(&b.func_name))
261    });
262
263    // Assign sequential IDs
264    for (i, entry) in entries.iter_mut().enumerate() {
265        entry.func_id = i as u32;
266    }
267
268    ctx.func_table = entries;
269}