1use std::fmt::Write as _;
15
16use serde::{Deserialize, Serialize};
17
18use crate::bridge::{Kind, Manifest, snake_case};
19use crate::codegen::{PortApi, PortFn};
20
21#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
23pub struct Batch {
24 pub function: String,
25 pub param: String,
26}
27
28impl Batch {
29 pub fn parse(spec: &str) -> Option<Self> {
30 let (function, param) = spec.split_once(':')?;
31 Some(Self {
32 function: function.trim().into(),
33 param: param.trim().into(),
34 })
35 }
36}
37
38pub fn pascal(name: &str) -> String {
39 let mut out = String::new();
40 let mut up = true;
41 for c in name.chars() {
42 if c == '_' || c == '-' {
43 up = true;
44 } else if up {
45 out.extend(c.to_uppercase());
46 up = false;
47 } else {
48 out.push(c);
49 }
50 }
51 out
52}
53
54pub(crate) struct Spec<'a> {
56 pub f: &'a PortFn,
57 pub item: usize,
58 pub item_ty: String,
60 pub class: String,
61 pub index: String,
62 pub custom: bool,
63 pub custom_rank: bool,
65}
66
67const ITEMS: &[&str] = &["String", "&str", "f64", "i64", "bool"];
68pub(crate) fn is_copy(ty: &str) -> bool {
70 let ty = ty.trim();
71 if let Some(inner) = ty.strip_prefix("Option<").and_then(|t| t.strip_suffix('>')) {
72 return is_copy(inner);
73 }
74 if let Some(items) = ty.strip_prefix('(').and_then(|t| t.strip_suffix(')')) {
75 return items
76 .split(',')
77 .filter(|t| !t.trim().is_empty())
78 .all(is_copy);
79 }
80 matches!(
81 ty,
82 "f64"
83 | "f32"
84 | "i64"
85 | "i32"
86 | "i16"
87 | "i8"
88 | "u64"
89 | "u32"
90 | "u16"
91 | "u8"
92 | "usize"
93 | "isize"
94 | "bool"
95 | "char"
96 )
97}
98
99const RESULTS: &[&str] = &["f64", "i64", "bool", "String"];
100
101fn spec<'a>(b: &Batch, api: &'a PortApi) -> Result<Spec<'a>, String> {
103 spec_with(b, api, false)
104}
105
106pub(crate) fn spec_with<'a>(
109 b: &Batch,
110 api: &'a PortApi,
111 dynamic: bool,
112) -> Result<Spec<'a>, String> {
113 let f = api
114 .functions
115 .iter()
116 .find(|f| f.js_name == b.function)
117 .ok_or_else(|| format!("`{}` is not a function of src/port.rs", b.function))?;
118 let wanted = snake_case(&b.param);
119 let item = f
120 .params
121 .iter()
122 .position(|(n, _)| *n == wanted || *n == b.param)
123 .ok_or_else(|| format!("`{}` has no parameter `{}`", b.function, b.param))?;
124 let ty = f.params[item].1.trim();
125 let value = |t: &str| dynamic && matches!(t, "Value" | "serde_json::Value");
126 if !ITEMS.contains(&ty) && !value(ty) {
127 return Err(format!(
128 "batch items must be strings, numbers or booleans; `{}` is `{ty}`",
129 b.param
130 ));
131 }
132 if f.is_async {
133 return Err(format!("`{}` is async", b.function));
134 }
135 if !RESULTS.contains(&f.ret.trim()) && !value(f.ret.trim()) {
136 return Err(format!(
137 "batch results must be numbers, booleans or strings; `{}` returns `{}`",
138 b.function, f.ret
139 ));
140 }
141 let base = pascal(&f.js_name);
142 let custom = api.structs.iter().any(|s| *s == format!("{base}Index"));
143 let custom_rank = custom && api.ranked.iter().any(|s| *s == format!("{base}Index"));
144 Ok(Spec {
145 f,
146 item,
147 item_ty: if ty == "&str" {
148 "String".into()
149 } else {
150 ty.into()
151 },
152 class: format!("{base}Batch"),
153 index: if custom {
154 format!("port::{base}Index")
155 } else {
156 format!("{base}DefaultIndex")
157 },
158 custom,
159 custom_rank,
160 })
161}
162
163pub(crate) fn fixed(s: &Spec) -> Vec<(String, String)> {
165 s.f.params
166 .iter()
167 .enumerate()
168 .filter(|(i, _)| *i != s.item)
169 .map(|(_, (n, t))| {
170 (
171 n.clone(),
172 if t.trim() == "&str" {
173 "String".to_string()
174 } else {
175 t.clone()
176 },
177 )
178 })
179 .collect()
180}
181
182pub(crate) fn default_index(s: &Spec, parallel: bool) -> String {
184 let fixed = fixed(s);
185 let params: Vec<String> = fixed.iter().map(|(n, t)| format!("{n}: {t}")).collect();
186 let args: Vec<String> =
187 s.f.params
188 .iter()
189 .enumerate()
190 .map(|(i, (n, t))| {
191 let by_ref = t.trim() == "&str";
192 match (i == s.item, by_ref) {
193 (true, true) => "item.as_str()".to_string(),
194 (true, false) if is_copy(&s.item_ty) => "*item".into(),
195 (true, false) => "item.clone()".into(),
196 (false, true) => format!("{n}.as_str()"),
197 (false, false) if is_copy(t) => n.clone(),
198 (false, false) => format!("{n}.clone()"),
199 }
200 })
201 .collect();
202 let call = format!("port::{}({})", s.f.rust_name, args.join(", "));
203 let call = if s.f.fallible {
204 call
205 } else {
206 format!("Ok::<_, String>({call})")
207 };
208 let iter = if parallel { "par_iter" } else { "iter" };
209 format!(
210 "\n/// The items of `{class}` as the port takes them; the port runs per item. Define\n\
211 /// `pub struct {base}Index` in `port.rs` (with `new` and `run`) to prepare items once.\n\
212 pub struct {index} {{\n items: Vec<{item}>,\n}}\n\n\
213 impl {index} {{\n pub fn new(items: Vec<{item}>) -> Self {{\n Self {{ items }}\n }}\n\n \
214 pub fn run(&self, {params}) -> Result<Vec<{ret}>, String> {{\n \
215 {use_rayon}self.items.{iter}().map(|item| {call}).collect::<Vec<_>>().into_iter().collect()\n }}\n}}\n",
216 class = s.class,
217 base = s.class.trim_end_matches("Batch"),
218 index = s.index,
219 item = s.item_ty,
220 params = params.join(", "),
221 ret = s.f.ret,
222 use_rayon = if parallel {
223 "use rayon::prelude::*;\n "
224 } else {
225 ""
226 },
227 )
228}
229
230fn napi_out(ret: &str) -> (&'static str, &'static str) {
232 match ret {
233 "f64" => (
234 "napi::bindgen_prelude::Float64Array",
235 "napi::bindgen_prelude::Float64Array::new(out)",
236 ),
237 "i64" => (
238 "napi::bindgen_prelude::Float64Array",
239 "napi::bindgen_prelude::Float64Array::new(out.into_iter().map(|x| x as f64).collect())",
240 ),
241 "bool" => (
242 "napi::bindgen_prelude::Uint8Array",
243 "napi::bindgen_prelude::Uint8Array::new(out.into_iter().map(u8::from).collect())",
244 ),
245 _ => ("Vec<String>", "out"),
246 }
247}
248
249pub(crate) fn rank_for(s: &Spec) -> Option<String> {
252 let body = rank_body(s.f.ret.trim())?;
253 Some(if s.custom_rank {
254 "let order: Vec<u32> = out;".to_string()
255 } else {
256 body
257 })
258}
259
260pub(crate) fn use_custom_rank(out: &mut String, from: usize, s: &Spec, names: &[&str]) {
263 if !s.custom_rank {
264 return;
265 }
266 let args = names.join(", ");
267 let with_min = if args.is_empty() {
268 "min".to_string()
269 } else {
270 format!("{args}, min")
271 };
272 let tail = out.split_off(from);
273 out.push_str(&tail.replacen(&format!(".run({args})"), &format!(".rank({with_min})"), 1));
274}
275
276pub(crate) fn rank_body(ret: &str) -> Option<String> {
277 let value = match ret {
278 "f64" => "r",
279 "i64" => "r as f64",
280 _ => return None,
281 };
282 Some(format!(
283 "let mut hits: Vec<(f64, u32)> = out\n .into_iter()\n .enumerate()\n \
284 .map(|(i, r)| ({value}, u32::try_from(i).unwrap_or(u32::MAX)))\n .filter(|(r, _)| *r >= min)\n .collect();\n \
285 // Stable: equal results keep the items' order, as JS `sort` and Python `sorted` do.\n \
286 hits.sort_by(|a, b| b.0.total_cmp(&a.0));\n let order: Vec<u32> = hits.into_iter().map(|(_, i)| i).collect();"
287 ))
288}
289
290pub fn js_rs(m: &Manifest, api: &PortApi) -> Result<String, String> {
292 let mut out = String::new();
293 let parallel = m.kind == Kind::Napi;
294 for b in &m.batches {
295 let s = spec(b, api)?;
296 if !s.custom {
297 out.push_str(&default_index(&s, parallel));
298 }
299 let fixed = fixed(&s);
300 let params: Vec<String> = fixed.iter().map(|(n, t)| format!("{n}: {t}")).collect();
301 let names: Vec<&str> = fixed.iter().map(|(n, _)| n.as_str()).collect();
302 let ret = s.f.ret.trim();
303 let (out_ty, out_expr) = napi_out(ret);
304 let wasm = m.kind == Kind::Wasm;
305 let (attr, ctor_attr, err, res) = if wasm {
306 (
307 "wasm_bindgen",
308 "#[wasm_bindgen(constructor)]",
309 ".map_err(|e| JsError::new(&e))",
310 "Result<{T}, JsError>",
311 )
312 } else {
313 ("napi", "#[napi(constructor)]", "", "napi::Result<{T}>")
314 };
315 let call = |body: &str| -> String {
316 if wasm {
317 format!(
318 "let out = self.inner.run({}){err}?;\n {body}",
319 names.join(", ")
320 )
321 } else {
322 format!(
323 "let out = run(|| self.inner.run({}))?;\n {body}",
324 names.join(", ")
325 )
326 }
327 };
328 let out_ty = if wasm {
329 out_ty
330 .replace("napi::bindgen_prelude::", "Vec<")
331 .replace("Float64Array", "f64>")
332 .replace("Uint8Array", "u8>")
333 } else {
334 out_ty.to_string()
335 };
336 let out_expr = if wasm {
337 match ret {
338 "i64" => "out.into_iter().map(|x| x as f64).collect()".to_string(),
339 "bool" => "out.into_iter().map(u8::from).collect()".to_string(),
340 _ => "out".to_string(),
341 }
342 } else {
343 out_expr.to_string()
344 };
345 let _ = write!(
346 out,
347 "\n/// `{js}` over many `{param}` values kept in Rust: `run` maps them all in one call{cores};\n\
348 /// `rank` returns the indexes of results >= `min`, best first.\n\
349 #[{attr}(js_name = \"{class}\")]\npub struct {class} {{\n inner: {index},\n}}\n\n\
350 {impl_attr}\nimpl {class} {{\n {ctor_attr}\n pub fn new(items: Vec<{item}>) -> Self {{\n Self {{ inner: {index}::new(items) }}\n }}\n\n \
351 /// The result for every item, in order.\n #[{attr}]\n pub fn run(&self, {params}) -> {res_run} {{\n {run_body}\n }}\n",
352 impl_attr = if wasm {
353 format!("#[wasm_bindgen(js_class = \"{}\")]", s.class)
354 } else {
355 "#[napi]".to_string()
356 },
357 js = s.f.js_name,
358 param = b.param,
359 cores = if parallel { ", on all cores" } else { "" },
360 class = s.class,
361 index = s.index,
362 item = s.item_ty,
363 params = params.join(", "),
364 res_run = res.replace("{T}", &out_ty),
365 run_body = call(&format!("Ok({out_expr})")),
366 );
367 if let Some(rank) = rank_for(&s) {
368 let from = out.len();
369 let order_ty = if wasm {
370 "Vec<u32>"
371 } else {
372 "napi::bindgen_prelude::Uint32Array"
373 };
374 let order_expr = if wasm {
375 "order"
376 } else {
377 "napi::bindgen_prelude::Uint32Array::new(order)"
378 };
379 let sep = if params.is_empty() { "" } else { ", " };
380 let _ = write!(
381 out,
382 "\n /// Indexes of the items whose result is at least `min`, highest result first.\n #[{attr}]\n \
383 pub fn rank(&self, {}{sep}min: f64) -> {} {{\n {}\n }}\n",
384 params.join(", "),
385 res.replace("{T}", order_ty),
386 call(&format!("{rank}\n Ok({order_expr})"))
387 );
388 use_custom_rank(&mut out, from, &s, &names);
389 }
390 out.push_str("}\n");
391 }
392 Ok(out)
393}
394
395pub fn py_rs(m: &Manifest, api: &PortApi) -> Result<(String, Vec<String>), String> {
397 let mut out = String::new();
398 let mut classes = Vec::new();
399 for b in &m.batches {
400 let s = spec(b, api)?;
401 if !s.custom {
402 out.push_str(&default_index(&s, true));
403 }
404 let fixed = fixed(&s);
405 let params: Vec<String> = fixed.iter().map(|(n, t)| format!("{n}: {t}")).collect();
406 let names: Vec<&str> = fixed.iter().map(|(n, _)| n.as_str()).collect();
407 let ret = s.f.ret.trim();
408 let sep = if params.is_empty() { "" } else { ", " };
409 let _ = write!(
410 out,
411 "\n/// `{js}` over many `{param}` values kept in Rust: `run` maps them all in one call, on all\n\
412 /// cores, without the GIL; `rank` returns the indexes of results >= `min`, best first.\n\
413 #[pyclass(name = \"{class}\")]\npub struct {class} {{\n inner: {index},\n}}\n\n#[pymethods]\nimpl {class} {{\n \
414 #[new]\n fn new(items: Vec<{item}>) -> Self {{\n Self {{ inner: {index}::new(items) }}\n }}\n\n \
415 /// The result for every item, in order.\n fn run(&self, py: Python<'_>{sep}{params}) -> PyResult<Vec<{ret}>> {{\n \
416 py.detach(|| self.inner.run({names})).map_err(error)\n }}\n",
417 js = s.f.js_name,
418 param = b.param,
419 class = s.class,
420 index = s.index,
421 item = s.item_ty,
422 params = params.join(", "),
423 names = names.join(", "),
424 );
425 if let Some(rank) = rank_for(&s) {
426 let from = out.len();
427 let _ = write!(
428 out,
429 "\n /// Indexes of the items whose result is at least `min`, highest result first.\n \
430 fn rank(&self, py: Python<'_>{sep}{params}, min: f64) -> PyResult<Vec<u32>> {{\n \
431 let out = py.detach(|| self.inner.run({names})).map_err(error)?;\n {rank}\n Ok(order)\n }}\n",
432 params = params.join(", "),
433 names = names.join(", "),
434 );
435 use_custom_rank(&mut out, from, &s, &names);
436 }
437 out.push_str("}\n");
438 classes.push(s.class);
439 }
440 Ok((out, classes))
441}
442
443pub fn needs_rayon(m: &Manifest) -> bool {
447 !m.batches.is_empty()
448}
449
450#[cfg(test)]
451mod tests {
452 use super::*;
453
454 #[test]
455 fn copies_only_copy_types() {
456 for t in ["f64", "Option<i64>", "(f64, bool)", "Option<(u32, char)>"] {
457 assert!(is_copy(t), "{t}");
458 }
459 for t in [
460 "String",
461 "Option<String>",
462 "Vec<f64>",
463 "(f64, String)",
464 "serde_json::Value",
465 ] {
466 assert!(!is_copy(t), "{t}");
467 }
468 }
469
470 #[test]
471 fn parses_and_names() {
472 let b = Batch::parse("fuzzyScore:text").unwrap();
473 assert_eq!(
474 b,
475 Batch {
476 function: "fuzzyScore".into(),
477 param: "text".into()
478 }
479 );
480 assert_eq!(pascal("fuzzyScore"), "FuzzyScore");
481 assert_eq!(pascal("rgb_to_hsv"), "RgbToHsv");
482 }
483}