Skip to main content

js2zig_core/
toml_config.rs

1//! js2rust.toml configuration types and loading logic.
2//!
3//! Single source of truth for TOML configuration, shared by:
4//! - `js2rust-bridge` (build.rs path)
5//! - `js2rust-bridge-macro` (proc-macro path)
6//!
7//! Both crates previously duplicated these types and the loading function.
8//! Now they both delegate here.
9
10use crate::analyzer::sanitize_module_name;
11use crate::{HostConfig, HostFunction, HostType};
12use indexmap::IndexMap;
13use serde::Deserialize;
14use std::path::PathBuf;
15
16/// Root structure of `js2rust.toml`.
17#[derive(Debug, Deserialize)]
18pub struct Js2rustConfig {
19    /// `[project]` section.
20    pub project: ProjectSection,
21    /// `[build]` section — controls build.rs behavior.
22    #[serde(default)]
23    pub build: BuildSection,
24    /// `[[host_functions]]` entries.
25    #[serde(default)]
26    pub host_functions: Vec<HostFnToml>,
27}
28
29/// `[project]` section.
30#[derive(Debug, Deserialize)]
31pub struct ProjectSection {
32    /// Directory containing JS source files (relative to crate root).
33    /// Default: `"js_src"`.
34    #[serde(default = "default_js_dir")]
35    pub js_dir: String,
36    /// JS source file names (plain filenames relative to `js_dir`).
37    /// The first element is the entry point; additional elements are extra roots.
38    pub js_files: Vec<String>,
39}
40
41fn default_js_dir() -> String {
42    "js_src".to_string()
43}
44
45/// `[build]` section — controls build.rs behavior.
46#[derive(Debug, Deserialize)]
47pub struct BuildSection {
48    /// Force rebuild (skip incremental cache). Default: false.
49    #[serde(default)]
50    pub force_rebuild: bool,
51    /// Whether to run `zig build` after transpilation. Default: true.
52    #[serde(default = "default_run_zig_build")]
53    pub run_zig_build: bool,
54    /// Zig optimization level passed as `-Doptimize=...` to `zig build`.
55    ///
56    /// Valid values: `"Debug"`, `"ReleaseSafe"`, `"ReleaseFast"`, `"ReleaseSmall"`.
57    /// When set, this overrides the automatic inference from the Cargo profile.
58    /// Default: `None` (auto-detect from Cargo profile).
59    #[serde(default)]
60    pub zig_optimize: Option<String>,
61}
62
63fn default_run_zig_build() -> bool {
64    true
65}
66
67impl Default for BuildSection {
68    fn default() -> Self {
69        Self {
70            force_rebuild: false,
71            run_zig_build: true,
72            zig_optimize: None,
73        }
74    }
75}
76
77/// A single `[[host_functions]]` entry.
78#[derive(Debug, Deserialize)]
79pub struct HostFnToml {
80    /// Host function name (must match `host_` prefix convention in JS).
81    pub name: String,
82    /// Parameter types: "i64", "i32", "f64", "bool", "str".
83    pub params: Vec<String>,
84    /// Return type (optional for async struct returns).
85    #[serde(default)]
86    pub returns: Option<String>,
87    /// Whether this is an async host function.
88    #[serde(default)]
89    pub is_async: bool,
90    /// For async functions that return a struct: field_name → field_type.
91    #[serde(default)]
92    pub async_returns: IndexMap<String, String>,
93}
94
95impl Js2rustConfig {
96    /// Load `js2rust.toml` from the crate manifest directory.
97    ///
98    /// Panics with a descriptive message if the file is missing or malformed.
99    pub fn from_manifest_dir() -> Self {
100        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
101        let config_path = PathBuf::from(&manifest_dir).join("js2rust.toml");
102
103        let content = std::fs::read_to_string(&config_path).unwrap_or_else(|e| {
104            panic!(
105                "js2rust_bridge: failed to read {}: {}\n\
106                 Create a js2rust.toml in your crate root with:\n\
107                 \n\
108                 [project]\n\
109                 js_dir = \"js_src\"\n\
110                 js_files = [\"main.js\"]\n",
111                config_path.display(),
112                e
113            );
114        });
115
116        toml::from_str(&content).unwrap_or_else(|e| {
117            panic!(
118                "js2rust_bridge: failed to parse {}: {}\n\
119                 Make sure your js2rust.toml is valid TOML.",
120                config_path.display(),
121                e
122            );
123        })
124    }
125
126    /// Derive the Zig project name from the first `js_files` entry's file stem.
127    pub fn project_name(&self) -> String {
128        let default = "main.js".to_string();
129        let first = self.project.js_files.first().unwrap_or(&default);
130        // js_files are plain filenames (no directory prefix), so file_stem works directly.
131        let stem = std::path::Path::new(first)
132            .file_stem()
133            .and_then(|s| s.to_str())
134            .unwrap_or("main");
135        sanitize_module_name(stem)
136    }
137
138    /// Convert `host_functions` TOML entries to `HostConfig`.
139    ///
140    /// Returns `None` if there are no host functions.
141    pub fn to_host_config(&self) -> Result<Option<HostConfig>, String> {
142        if self.host_functions.is_empty() {
143            return Ok(None);
144        }
145        let functions: Result<Vec<HostFunction>, String> = self
146            .host_functions
147            .iter()
148            .map(|hf| {
149                let params: Result<Vec<HostType>, String> = hf
150                    .params
151                    .iter()
152                    .map(|t| HostType::from_toml_str(t))
153                    .collect();
154                let params = params?;
155
156                let return_type = hf.returns.as_deref().and_then(|t| {
157                    if t == "void" {
158                        None
159                    } else {
160                        Some(HostType::from_toml_str(t))
161                    }
162                });
163                let return_type = return_type.transpose()?;
164
165                let async_return_fields: Result<Vec<(String, HostType)>, String> = hf
166                    .async_returns
167                    .iter()
168                    .map(|(name, ty)| Ok((name.clone(), HostType::from_toml_str(ty)?)))
169                    .collect();
170                let async_return_fields = async_return_fields?;
171
172                Ok(HostFunction {
173                    name: hf.name.clone(),
174                    params,
175                    return_type,
176                    is_async: hf.is_async,
177                    async_return_fields,
178                })
179            })
180            .collect();
181        let functions = functions?;
182
183        Ok(Some(HostConfig { functions }))
184    }
185}
186
187/// Convert snake_case to PascalCase.
188///
189/// Shared utility used by both bridge and bridge-macro for generating
190/// struct names from host function names (e.g. "fetch_user" → "FetchUser").
191pub fn pascal_case(name: &str) -> String {
192    let mut result = String::with_capacity(name.len());
193    let mut capitalize = true;
194    for ch in name.chars() {
195        if ch == '_' {
196            capitalize = true;
197        } else if capitalize {
198            result.push(ch.to_ascii_uppercase());
199            capitalize = false;
200        } else {
201            result.push(ch);
202        }
203    }
204    result
205}
206
207impl HostType {
208    /// Convert a TOML type name string to `HostType`.
209    ///
210    /// Used by both bridge and bridge-macro to parse `js2rust.toml` host function types.
211    /// This was previously duplicated as `type_name_to_host_type()` in both crates.
212    ///
213    /// Returns `Err` with a descriptive message for unknown type names (P3-1:
214    /// previously used `panic!`, which produced a less informative build failure).
215    pub fn from_toml_str(name: &str) -> Result<HostType, String> {
216        match name {
217            "i64" => Ok(HostType::I64),
218            "i32" => Ok(HostType::I32),
219            "f64" => Ok(HostType::F64),
220            "bool" => Ok(HostType::Bool),
221            "str" => Ok(HostType::Str),
222            "void" => Ok(HostType::Void),
223            other => Err(format!(
224                "js2rust.toml: unknown host type '{}'. \
225                 Valid types: i64, i32, f64, bool, str, void",
226                other
227            )),
228        }
229    }
230}