use crate::analyzer::sanitize_module_name;
use crate::{HostConfig, HostFunction, HostType};
use indexmap::IndexMap;
use serde::Deserialize;
use std::path::PathBuf;
#[derive(Debug, Deserialize)]
pub struct Js2rustConfig {
pub project: ProjectSection,
#[serde(default)]
pub build: BuildSection,
#[serde(default)]
pub host_functions: Vec<HostFnToml>,
}
#[derive(Debug, Deserialize)]
pub struct ProjectSection {
#[serde(default = "default_js_dir")]
pub js_dir: String,
pub js_files: Vec<String>,
}
fn default_js_dir() -> String {
"js_src".to_string()
}
#[derive(Debug, Deserialize)]
pub struct BuildSection {
#[serde(default)]
pub force_rebuild: bool,
#[serde(default = "default_run_zig_build")]
pub run_zig_build: bool,
#[serde(default)]
pub zig_optimize: Option<String>,
}
fn default_run_zig_build() -> bool {
true
}
impl Default for BuildSection {
fn default() -> Self {
Self {
force_rebuild: false,
run_zig_build: true,
zig_optimize: None,
}
}
}
#[derive(Debug, Deserialize)]
pub struct HostFnToml {
pub name: String,
pub params: Vec<String>,
#[serde(default)]
pub returns: Option<String>,
#[serde(default)]
pub is_async: bool,
#[serde(default)]
pub async_returns: IndexMap<String, String>,
}
impl Js2rustConfig {
pub fn from_manifest_dir() -> Self {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
let config_path = PathBuf::from(&manifest_dir).join("js2rust.toml");
let content = std::fs::read_to_string(&config_path).unwrap_or_else(|e| {
panic!(
"js2rust_bridge: failed to read {}: {}\n\
Create a js2rust.toml in your crate root with:\n\
\n\
[project]\n\
js_dir = \"js_src\"\n\
js_files = [\"main.js\"]\n",
config_path.display(),
e
);
});
toml::from_str(&content).unwrap_or_else(|e| {
panic!(
"js2rust_bridge: failed to parse {}: {}\n\
Make sure your js2rust.toml is valid TOML.",
config_path.display(),
e
);
})
}
pub fn project_name(&self) -> String {
let default = "main.js".to_string();
let first = self.project.js_files.first().unwrap_or(&default);
let stem = std::path::Path::new(first)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("main");
sanitize_module_name(stem)
}
pub fn to_host_config(&self) -> Result<Option<HostConfig>, String> {
if self.host_functions.is_empty() {
return Ok(None);
}
let functions: Result<Vec<HostFunction>, String> = self
.host_functions
.iter()
.map(|hf| {
let params: Result<Vec<HostType>, String> = hf
.params
.iter()
.map(|t| HostType::from_toml_str(t))
.collect();
let params = params?;
let return_type = hf.returns.as_deref().and_then(|t| {
if t == "void" {
None
} else {
Some(HostType::from_toml_str(t))
}
});
let return_type = return_type.transpose()?;
let async_return_fields: Result<Vec<(String, HostType)>, String> = hf
.async_returns
.iter()
.map(|(name, ty)| Ok((name.clone(), HostType::from_toml_str(ty)?)))
.collect();
let async_return_fields = async_return_fields?;
Ok(HostFunction {
name: hf.name.clone(),
params,
return_type,
is_async: hf.is_async,
async_return_fields,
})
})
.collect();
let functions = functions?;
Ok(Some(HostConfig { functions }))
}
}
pub fn pascal_case(name: &str) -> String {
let mut result = String::with_capacity(name.len());
let mut capitalize = true;
for ch in name.chars() {
if ch == '_' {
capitalize = true;
} else if capitalize {
result.push(ch.to_ascii_uppercase());
capitalize = false;
} else {
result.push(ch);
}
}
result
}
impl HostType {
pub fn from_toml_str(name: &str) -> Result<HostType, String> {
match name {
"i64" => Ok(HostType::I64),
"i32" => Ok(HostType::I32),
"f64" => Ok(HostType::F64),
"bool" => Ok(HostType::Bool),
"str" => Ok(HostType::Str),
"void" => Ok(HostType::Void),
other => Err(format!(
"js2rust.toml: unknown host type '{}'. \
Valid types: i64, i32, f64, bool, str, void",
other
)),
}
}
}