Skip to main content

rusteal_codegen/cpp_gen/
mod.rs

1// C++ code generation orchestrator.
2
3pub mod wrapper;
4pub mod func_ids;
5pub mod fill_table;
6
7use std::collections::BTreeMap;
8use std::path::Path;
9
10use crate::context::CodegenContext;
11
12/// Generate all C++ code into the output directory.
13pub fn generate(ctx: &CodegenContext, out_dir: &Path) {
14    std::fs::create_dir_all(out_dir).expect("Failed to create C++ output directory");
15    remove_stale_wrappers(out_dir);
16
17    // Group func entries by (module, class) for per-file generation
18    let mut by_class: BTreeMap<(String, String), Vec<&crate::context::FuncEntry>> = BTreeMap::new();
19    for entry in &ctx.func_table {
20        by_class
21            .entry((entry.module_name.clone(), entry.class_name.clone()))
22            .or_default()
23            .push(entry);
24    }
25
26    // Generate per-class wrapper files
27    for ((module, class), entries) in &by_class {
28        let code = wrapper::generate_wrapper_file(entries, ctx);
29        let filename = format!("RustealFunc_{}_{}.cpp", module, class);
30        std::fs::write(out_dir.join(&filename), code)
31            .unwrap_or_else(|e| panic!("Failed to write {filename}: {e}"));
32    }
33
34    // Generate RustealFuncIds.h
35    let ids_code = func_ids::generate_cpp_func_ids(&ctx.func_table);
36    std::fs::write(out_dir.join("RustealFuncIds.h"), ids_code)
37        .expect("Failed to write RustealFuncIds.h");
38
39    // Generate RustealFillFuncTable.cpp
40    let fill_code = fill_table::generate_fill_table(&ctx.func_table, &by_class);
41    std::fs::write(out_dir.join("RustealFillFuncTable.cpp"), fill_code)
42        .expect("Failed to write RustealFillFuncTable.cpp");
43}
44
45/// Delete the per-class wrapper files left by a previous run. UBT compiles every .cpp in the
46/// output directory, so a class that lost all its exportable functions (blocklist, feature
47/// change, engine upgrade) would otherwise keep a stale wrapper that no longer links.
48fn remove_stale_wrappers(out_dir: &Path) {
49    let Ok(entries) = std::fs::read_dir(out_dir) else {
50        return;
51    };
52    for entry in entries.flatten() {
53        let name = entry.file_name();
54        let name = name.to_string_lossy();
55        if name.starts_with("RustealFunc_") && name.ends_with(".cpp") {
56            std::fs::remove_file(entry.path())
57                .unwrap_or_else(|e| panic!("Failed to remove stale {name}: {e}"));
58        }
59    }
60}