js2zig_core/
toml_config.rs1use crate::analyzer::sanitize_module_name;
11use crate::{HostConfig, HostFunction, HostType};
12use indexmap::IndexMap;
13use serde::Deserialize;
14use std::path::PathBuf;
15
16#[derive(Debug, Deserialize)]
18pub struct Js2rustConfig {
19 pub project: ProjectSection,
21 #[serde(default)]
23 pub build: BuildSection,
24 #[serde(default)]
26 pub host_functions: Vec<HostFnToml>,
27}
28
29#[derive(Debug, Deserialize)]
31pub struct ProjectSection {
32 #[serde(default = "default_js_dir")]
35 pub js_dir: String,
36 pub js_files: Vec<String>,
39}
40
41fn default_js_dir() -> String {
42 "js_src".to_string()
43}
44
45#[derive(Debug, Deserialize)]
47pub struct BuildSection {
48 #[serde(default)]
50 pub force_rebuild: bool,
51 #[serde(default = "default_run_zig_build")]
53 pub run_zig_build: bool,
54 #[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#[derive(Debug, Deserialize)]
79pub struct HostFnToml {
80 pub name: String,
82 pub params: Vec<String>,
84 #[serde(default)]
86 pub returns: Option<String>,
87 #[serde(default)]
89 pub is_async: bool,
90 #[serde(default)]
92 pub async_returns: IndexMap<String, String>,
93}
94
95impl Js2rustConfig {
96 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 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 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 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
187pub 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 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}