swift_bridge_ir/
codegen.rs

1use crate::bridge_module_attributes::CfgAttr;
2use crate::SwiftBridgeModule;
3
4mod generate_c_header;
5mod generate_rust_tokens;
6mod generate_swift;
7
8#[cfg(test)]
9mod codegen_tests;
10
11/// The corresponding Swift code and C header for a bridge module.
12pub struct SwiftCodeAndCHeader {
13    /// The generated Swift code.
14    pub swift: String,
15    /// The generated C header.
16    pub c_header: String,
17}
18
19/// Configuration for how we will generate our Swift code.
20pub struct CodegenConfig {
21    /// Look up whether or not a feature is enabled for the crate that holds the bridge module.
22    /// This helps us decide whether or not to generate code for parts of the module
23    /// that are annotated with `#[cfg(feature = "some-feature")]`
24    pub crate_feature_lookup: Box<dyn Fn(&str) -> bool>,
25}
26
27#[cfg(test)]
28impl CodegenConfig {
29    pub(crate) fn no_features_enabled() -> Self {
30        CodegenConfig {
31            crate_feature_lookup: Box::new(|_| false),
32        }
33    }
34}
35
36impl SwiftBridgeModule {
37    /// Generate the corresponding Swift code and C header for a bridge module.
38    pub fn generate_swift_code_and_c_header(&self, config: CodegenConfig) -> SwiftCodeAndCHeader {
39        SwiftCodeAndCHeader {
40            swift: self.generate_swift(&config),
41            c_header: self.generate_c_header(&config),
42        }
43    }
44
45    /// Whether or not the module's conditional compilation flags willl lead it to being included
46    /// in the final binary.
47    /// If not, when we won't generate any C or Swift code for it.
48    fn module_will_be_compiled(&self, config: &CodegenConfig) -> bool {
49        for cfg_attr in &self.cfg_attrs {
50            match cfg_attr {
51                CfgAttr::Feature(feature_name) => {
52                    if !(config.crate_feature_lookup)(&feature_name.value()) {
53                        return false;
54                    }
55                }
56            }
57        }
58
59        true
60    }
61}