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 let fast = if parallel {
295 fast_batches(m, api)
296 } else {
297 Vec::new()
298 };
299 let strings_out = fast.iter().any(|b| b.strings_out);
300 if strings_out {
301 out.push_str(JOINED_OUT_RS);
302 }
303 if fast.iter().any(|b| b.items == Items::Strings) {
304 out.push_str(JOINED_IN_RS);
305 }
306 for b in &m.batches {
307 let s = spec(b, api)?;
308 if !s.custom {
309 out.push_str(&default_index(&s, parallel));
310 }
311 let fixed = fixed(&s);
312 let params: Vec<String> = fixed.iter().map(|(n, t)| format!("{n}: {t}")).collect();
313 let names: Vec<&str> = fixed.iter().map(|(n, _)| n.as_str()).collect();
314 let ret = s.f.ret.trim();
315 let (out_ty, out_expr) = napi_out(ret);
316 let wasm = m.kind == Kind::Wasm;
317 let (attr, ctor_attr, err, res) = if wasm {
318 (
319 "wasm_bindgen",
320 "#[wasm_bindgen(constructor)]",
321 ".map_err(|e| JsError::new(&e))",
322 "Result<{T}, JsError>",
323 )
324 } else {
325 ("napi", "#[napi(constructor)]", "", "napi::Result<{T}>")
326 };
327 let call = |body: &str| -> String {
328 if wasm {
329 format!(
330 "let out = self.inner.run({}){err}?;\n {body}",
331 names.join(", ")
332 )
333 } else {
334 format!(
335 "let out = run(|| self.inner.run({}))?;\n {body}",
336 names.join(", ")
337 )
338 }
339 };
340 let out_ty = if wasm {
341 out_ty
342 .replace("napi::bindgen_prelude::", "Vec<")
343 .replace("Float64Array", "f64>")
344 .replace("Uint8Array", "u8>")
345 } else {
346 out_ty.to_string()
347 };
348 let out_expr = if wasm {
349 match ret {
350 "i64" => "out.into_iter().map(|x| x as f64).collect()".to_string(),
351 "bool" => "out.into_iter().map(u8::from).collect()".to_string(),
352 _ => "out".to_string(),
353 }
354 } else {
355 out_expr.to_string()
356 };
357 let _ = write!(
358 out,
359 "\n/// `{js}` over many `{param}` values kept in Rust: `run` maps them all in one call{cores};\n\
360 /// `rank` returns the indexes of results >= `min`, best first.\n\
361 #[{attr}(js_name = \"{class}\")]\npub struct {class} {{\n inner: {index},\n}}\n\n\
362 {impl_attr}\nimpl {class} {{\n {ctor_attr}\n pub fn new(items: Vec<{item}>) -> Self {{\n Self {{ inner: {index}::new(items) }}\n }}\n{from_joined}\n \
363 /// The result for every item, in order.\n #[{attr}]\n pub fn run(&self, {params}) -> {res_run} {{\n {run_body}\n }}\n{run_joined}",
364 impl_attr = if wasm {
365 format!("#[wasm_bindgen(js_class = \"{}\")]", s.class)
366 } else {
367 "#[napi]".to_string()
368 },
369 js = s.f.js_name,
370 param = b.param,
371 cores = if parallel { ", on all cores" } else { "" },
372 class = s.class,
373 index = s.index,
374 item = s.item_ty,
375 params = params.join(", "),
376 res_run = res.replace("{T}", &out_ty),
377 run_body = call(&format!("Ok({out_expr})")),
378 from_joined = if parallel && s.item_ty == "String" {
379 format!(
380 "\n /// `new` for items sent as one joined string and their UTF-16 end offsets.\n \
381 #[napi(factory, js_name = \"fromJoined\")]\n \
382 pub fn from_joined(text: String, ends: napi::bindgen_prelude::Uint32Array) -> Self {{\n \
383 Self {{ inner: {}::new(split_joined(&text, &ends)) }}\n }}\n",
384 s.index
385 )
386 } else if parallel && s.item_ty == "f64" {
387 format!(
388 "\n /// `new` for items sent as one `Float64Array`.\n \
389 #[napi(factory, js_name = \"fromFloat64\")]\n \
390 pub fn from_float64(items: napi::bindgen_prelude::Float64Array) -> Self {{\n \
391 Self {{ inner: {}::new(items.to_vec()) }}\n }}\n",
392 s.index
393 )
394 } else {
395 String::new()
396 },
397 run_joined = if parallel && ret == "String" {
398 format!(
399 "\n /// `run` with the results joined into one string and their UTF-16 end offsets.\n \
400 #[napi(js_name = \"runJoined\")]\n \
401 pub fn run_joined(&self, {}) -> napi::Result<JoinedStrings> {{\n {}\n }}\n",
402 params.join(", "),
403 call("Ok(joined(out))")
404 )
405 } else {
406 String::new()
407 },
408 );
409 if let Some(rank) = rank_for(&s) {
410 let from = out.len();
411 let order_ty = if wasm {
412 "Vec<u32>"
413 } else {
414 "napi::bindgen_prelude::Uint32Array"
415 };
416 let order_expr = if wasm {
417 "order"
418 } else {
419 "napi::bindgen_prelude::Uint32Array::new(order)"
420 };
421 let sep = if params.is_empty() { "" } else { ", " };
422 let _ = write!(
423 out,
424 "\n /// Indexes of the items whose result is at least `min`, highest result first.\n #[{attr}]\n \
425 pub fn rank(&self, {}{sep}min: f64) -> {} {{\n {}\n }}\n",
426 params.join(", "),
427 res.replace("{T}", order_ty),
428 call(&format!("{rank}\n Ok({order_expr})"))
429 );
430 use_custom_rank(&mut out, from, &s, &names);
431 }
432 out.push_str("}\n");
433 }
434 Ok(out)
435}
436
437#[derive(Clone, Copy, PartialEq, Eq)]
438pub(crate) enum Items {
439 Strings,
440 Numbers,
441 Other,
442}
443
444pub(crate) struct FastBatch {
446 class: String,
447 items: Items,
448 strings_out: bool,
449}
450
451pub(crate) fn fast_batches(m: &Manifest, api: &PortApi) -> Vec<FastBatch> {
455 if m.kind != Kind::Napi {
456 return Vec::new();
457 }
458 m.batches
459 .iter()
460 .filter_map(|b| spec(b, api).ok())
461 .map(|s| FastBatch {
462 class: s.class.clone(),
463 items: match s.item_ty.as_str() {
464 "String" => Items::Strings,
465 "f64" => Items::Numbers,
466 _ => Items::Other,
467 },
468 strings_out: s.f.ret.trim() == "String",
469 })
470 .filter(|b| b.items != Items::Other || b.strings_out)
471 .collect()
472}
473
474const JOINED_OUT_RS: &str = r#"
475/// Strings joined into one, with the UTF-16 end offset of each (what JS `slice` takes).
476#[napi(object)]
477pub struct JoinedStrings {
478 pub text: String,
479 pub ends: napi::bindgen_prelude::Uint32Array,
480}
481
482fn joined(out: Vec<String>) -> JoinedStrings {
483 let mut text = String::with_capacity(out.iter().map(String::len).sum());
484 let mut ends = Vec::with_capacity(out.len());
485 let mut at = 0u32;
486 for s in &out {
487 text.push_str(s);
488 let units = if s.is_ascii() { s.len() } else { s.encode_utf16().count() };
489 at = at.saturating_add(u32::try_from(units).unwrap_or(u32::MAX));
490 ends.push(at);
491 }
492 JoinedStrings {
493 text,
494 ends: napi::bindgen_prelude::Uint32Array::new(ends),
495 }
496}
497
498"#;
499
500const JOINED_IN_RS: &str = r#"
501/// Splits `text` at UTF-16 end offsets. A lone surrogate arrived as U+FFFD, one unit as before.
502fn split_joined(text: &str, ends: &[u32]) -> Vec<String> {
503 let ascii = text.is_ascii()
504 && ends.last().is_none_or(|&e| e as usize == text.len())
505 && ends.windows(2).all(|w| w[0] <= w[1]);
506 let mut out = Vec::with_capacity(ends.len());
507 if ascii {
508 let mut from = 0;
509 for &e in ends {
510 out.push(text[from..e as usize].to_string());
511 from = e as usize;
512 }
513 return out;
514 }
515 let mut chars = text.chars();
516 let mut unit = 0usize;
517 for &e in ends {
518 let mut s = String::new();
519 while unit < e as usize {
520 let Some(c) = chars.next() else { break };
521 unit += c.len_utf16();
522 s.push(c);
523 }
524 out.push(s);
525 }
526 out
527}
528"#;
529
530pub fn index_cjs(m: &Manifest, api: &PortApi) -> String {
532 let batches = fast_batches(m, api);
533 if batches.is_empty() {
534 return String::new();
535 }
536 let list = |pick: &dyn Fn(&FastBatch) -> bool| -> String {
537 batches
538 .iter()
539 .filter(|b| pick(b))
540 .map(|b| format!("'{}'", b.class))
541 .collect::<Vec<_>>()
542 .join(", ")
543 };
544 format!(
545 "{JOINED_CJS}for (const name of [{}]) joinItems(name)\n\
546 for (const name of [{}]) packNumbers(name)\n\
547 for (const name of [{}]) splitResults(name)\n",
548 list(&|b| b.items == Items::Strings),
549 list(&|b| b.items == Items::Numbers),
550 list(&|b| b.strings_out)
551 )
552}
553
554const JOINED_CJS: &str = r#"
555// Batches: strings cross as one joined string and the UTF-16 end offset of each, numbers as one
556// Float64Array, which costs far less than one JS value per item. `new Batch(items)` and
557// `batch.run()` keep their shape.
558const joinItems = name => {
559 const Native = native[name]
560 const Batch = { [name]: function (items) {
561 if (!Array.isArray(items)) throw new TypeError(`${name}: items must be an array of strings`)
562 const ends = new Uint32Array(items.length)
563 let at = 0
564 for (let i = 0; i < items.length; i++) {
565 if (typeof items[i] !== 'string') throw new TypeError(`${name}: items must be an array of strings`)
566 ends[i] = at += items[i].length
567 }
568 return Native.fromJoined(items.join(''), ends)
569 } }[name]
570 Batch.prototype = Native.prototype
571 Batch.fromJoined = Native.fromJoined
572 module.exports[name] = Batch
573}
574const packNumbers = name => {
575 const Native = native[name]
576 const Batch = { [name]: function (items) {
577 if (!Array.isArray(items)) throw new TypeError(`${name}: items must be an array of numbers`)
578 const packed = new Float64Array(items.length)
579 for (let i = 0; i < items.length; i++) {
580 if (typeof items[i] !== 'number') throw new TypeError(`${name}: items must be an array of numbers`)
581 packed[i] = items[i]
582 }
583 return Native.fromFloat64(packed)
584 } }[name]
585 Batch.prototype = Native.prototype
586 Batch.fromFloat64 = Native.fromFloat64
587 module.exports[name] = Batch
588}
589const splitResults = name => {
590 Object.defineProperty(native[name].prototype, 'run', {
591 value: function (...a) {
592 const { text, ends } = this.runJoined(...a)
593 const out = new Array(ends.length)
594 for (let i = 0, from = 0; i < ends.length; from = ends[i++]) out[i] = text.slice(from, ends[i])
595 return out
596 },
597 writable: true,
598 configurable: true,
599 })
600}
601"#;
602
603pub fn py_rs(m: &Manifest, api: &PortApi) -> Result<(String, Vec<String>), String> {
605 let mut out = String::new();
606 let mut classes = Vec::new();
607 for b in &m.batches {
608 let s = spec(b, api)?;
609 if !s.custom {
610 out.push_str(&default_index(&s, true));
611 }
612 let fixed = fixed(&s);
613 let params: Vec<String> = fixed.iter().map(|(n, t)| format!("{n}: {t}")).collect();
614 let names: Vec<&str> = fixed.iter().map(|(n, _)| n.as_str()).collect();
615 let ret = s.f.ret.trim();
616 let sep = if params.is_empty() { "" } else { ", " };
617 let _ = write!(
618 out,
619 "\n/// `{js}` over many `{param}` values kept in Rust: `run` maps them all in one call, on all\n\
620 /// cores, without the GIL; `rank` returns the indexes of results >= `min`, best first.\n\
621 #[pyclass(name = \"{class}\")]\npub struct {class} {{\n inner: {index},\n}}\n\n#[pymethods]\nimpl {class} {{\n \
622 #[new]\n fn new(items: Vec<{item}>) -> Self {{\n Self {{ inner: {index}::new(items) }}\n }}\n\n \
623 /// The result for every item, in order.\n fn run(&self, py: Python<'_>{sep}{params}) -> PyResult<Vec<{ret}>> {{\n \
624 py.detach(|| self.inner.run({names})).map_err(error)\n }}\n",
625 js = s.f.js_name,
626 param = b.param,
627 class = s.class,
628 index = s.index,
629 item = s.item_ty,
630 params = params.join(", "),
631 names = names.join(", "),
632 );
633 if let Some(rank) = rank_for(&s) {
634 let from = out.len();
635 let _ = write!(
636 out,
637 "\n /// Indexes of the items whose result is at least `min`, highest result first.\n \
638 fn rank(&self, py: Python<'_>{sep}{params}, min: f64) -> PyResult<Vec<u32>> {{\n \
639 let out = py.detach(|| self.inner.run({names})).map_err(error)?;\n {rank}\n Ok(order)\n }}\n",
640 params = params.join(", "),
641 names = names.join(", "),
642 );
643 use_custom_rank(&mut out, from, &s, &names);
644 }
645 out.push_str("}\n");
646 classes.push(s.class);
647 }
648 Ok((out, classes))
649}
650
651pub fn needs_rayon(m: &Manifest) -> bool {
655 !m.batches.is_empty()
656}
657
658#[cfg(test)]
659mod tests {
660 use super::*;
661
662 #[test]
663 fn copies_only_copy_types() {
664 for t in ["f64", "Option<i64>", "(f64, bool)", "Option<(u32, char)>"] {
665 assert!(is_copy(t), "{t}");
666 }
667 for t in [
668 "String",
669 "Option<String>",
670 "Vec<f64>",
671 "(f64, String)",
672 "serde_json::Value",
673 ] {
674 assert!(!is_copy(t), "{t}");
675 }
676 }
677
678 #[test]
679 fn parses_and_names() {
680 let b = Batch::parse("fuzzyScore:text").unwrap();
681 assert_eq!(
682 b,
683 Batch {
684 function: "fuzzyScore".into(),
685 param: "text".into()
686 }
687 );
688 assert_eq!(pascal("fuzzyScore"), "FuzzyScore");
689 assert_eq!(pascal("rgb_to_hsv"), "RgbToHsv");
690 }
691}