Skip to main content

rust_anything/
codegen_batch.rs

1//! Batch classes: a function run over many items that stay on the Rust side.
2//!
3//! `bridge --batch fuzzyScore:text` gives the crate a `FuzzyScoreBatch` class: the constructor
4//! takes the items (the `text` values) once; `run(query)` applies the port to every item on all
5//! cores and returns the results as one typed array; `rank(query, min)` returns the indexes of
6//! the items whose result is at least `min`, best first. One call does what a loop of per-item
7//! calls did, so the crossing is paid once instead of per item.
8//!
9//! The default index calls the port per item. A port can do better by defining
10//! `pub struct FuzzyScoreIndex` in `port.rs` with `pub fn new(items: Vec<T>) -> Self` and
11//! `pub fn run(&self, <other params>) -> Result<Vec<R>, String>`: it can prepare the items once
12//! (lowercase them, build masks) and the class uses it instead.
13
14use std::fmt::Write as _;
15
16use serde::{Deserialize, Serialize};
17
18use crate::bridge::{Kind, Manifest, snake_case};
19use crate::codegen::{PortApi, PortFn};
20
21/// `--batch function:param`: run `function` over many values of `param`.
22#[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        let (function, param) = (function.trim(), param.trim());
32        if function.is_empty() || param.is_empty() {
33            return None;
34        }
35        Some(Self {
36            function: function.into(),
37            param: param.into(),
38        })
39    }
40}
41
42pub fn pascal(name: &str) -> String {
43    let mut out = String::new();
44    let mut up = true;
45    for c in name.chars() {
46        if c == '_' || c == '-' {
47            up = true;
48        } else if up {
49            out.extend(c.to_uppercase());
50            up = false;
51        } else {
52            out.push(c);
53        }
54    }
55    out
56}
57
58/// A batch the port's signature allows.
59pub(crate) struct Spec<'a> {
60    pub f: &'a PortFn,
61    pub item: usize,
62    /// The stored item type (`&str` items are stored as `String`).
63    pub item_ty: String,
64    pub class: String,
65    pub index: String,
66    pub custom: bool,
67    /// The custom index has its own `rank(&self, <fixed>, min: f64) -> Result<Vec<u32>, String>`.
68    pub custom_rank: bool,
69}
70
71const ITEMS: &[&str] = &["String", "&str", "f64", "i64", "bool"];
72/// Whether a parameter type is `Copy`, so each item's call takes it as is; the rest are cloned.
73pub(crate) fn is_copy(ty: &str) -> bool {
74    let ty = ty.trim();
75    if let Some(inner) = ty.strip_prefix("Option<").and_then(|t| t.strip_suffix('>')) {
76        return is_copy(inner);
77    }
78    if let Some(items) = ty.strip_prefix('(').and_then(|t| t.strip_suffix(')')) {
79        return items
80            .split(',')
81            .filter(|t| !t.trim().is_empty())
82            .all(is_copy);
83    }
84    matches!(
85        ty,
86        "f64"
87            | "f32"
88            | "i64"
89            | "i32"
90            | "i16"
91            | "i8"
92            | "u64"
93            | "u32"
94            | "u16"
95            | "u8"
96            | "usize"
97            | "isize"
98            | "bool"
99            | "char"
100    )
101}
102
103const RESULTS: &[&str] = &["f64", "i64", "bool", "String"];
104
105/// `names` joined with commas, or `none`.
106fn listed<'a>(names: impl Iterator<Item = &'a str>) -> String {
107    let names: Vec<&str> = names.collect();
108    if names.is_empty() {
109        "none".into()
110    } else {
111        names.join(", ")
112    }
113}
114
115/// Why a batch cannot be generated, or its spec.
116fn spec<'a>(b: &Batch, api: &'a PortApi) -> Result<Spec<'a>, String> {
117    spec_with(b, api, false)
118}
119
120/// The spec; `dynamic` also accepts `serde_json::Value` items and results (Ruby converts them
121/// per item in Rust).
122pub(crate) fn spec_with<'a>(
123    b: &Batch,
124    api: &'a PortApi,
125    dynamic: bool,
126) -> Result<Spec<'a>, String> {
127    let f = api
128        .functions
129        .iter()
130        .find(|f| f.js_name == b.function)
131        .ok_or_else(|| {
132            format!(
133                "`{}` is not a function of src/port.rs (functions: {})",
134                b.function,
135                listed(api.functions.iter().map(|f| f.js_name.as_str()))
136            )
137        })?;
138    let wanted = snake_case(&b.param);
139    let item = f
140        .params
141        .iter()
142        .position(|(n, _)| *n == wanted || *n == b.param)
143        .ok_or_else(|| {
144            format!(
145                "`{}` has no parameter `{}` (parameters: {})",
146                b.function,
147                b.param,
148                listed(f.params.iter().map(|(n, _)| n.as_str()))
149            )
150        })?;
151    let ty = f.params[item].1.trim();
152    let value = |t: &str| dynamic && matches!(t, "Value" | "serde_json::Value");
153    if !ITEMS.contains(&ty) && !value(ty) {
154        return Err(format!(
155            "batch items must be strings, numbers or booleans; `{}` is `{ty}`",
156            b.param
157        ));
158    }
159    if f.is_async {
160        return Err(format!("`{}` is async", b.function));
161    }
162    if !RESULTS.contains(&f.ret.trim()) && !value(f.ret.trim()) {
163        return Err(format!(
164            "batch results must be numbers, booleans or strings; `{}` returns `{}`",
165            b.function, f.ret
166        ));
167    }
168    let base = pascal(&f.js_name);
169    let custom = api.structs.iter().any(|s| *s == format!("{base}Index"));
170    let custom_rank = custom && api.ranked.iter().any(|s| *s == format!("{base}Index"));
171    Ok(Spec {
172        f,
173        item,
174        item_ty: if ty == "&str" {
175            "String".into()
176        } else {
177            ty.into()
178        },
179        class: format!("{base}Batch"),
180        index: if custom {
181            format!("port::{base}Index")
182        } else {
183            format!("{base}DefaultIndex")
184        },
185        custom,
186        custom_rank,
187    })
188}
189
190/// The non-item parameters, as `name: Type` (by value: `&str` becomes `String`).
191pub(crate) fn fixed(s: &Spec) -> Vec<(String, String)> {
192    s.f.params
193        .iter()
194        .enumerate()
195        .filter(|(i, _)| *i != s.item)
196        .map(|(_, (n, t))| {
197            (
198                n.clone(),
199                if t.trim() == "&str" {
200                    "String".to_string()
201                } else {
202                    t.clone()
203                },
204            )
205        })
206        .collect()
207}
208
209/// The default index: the items as the port takes them, the port called per item.
210pub(crate) fn default_index(s: &Spec, parallel: bool) -> String {
211    let fixed = fixed(s);
212    let params: Vec<String> = fixed.iter().map(|(n, t)| format!("{n}: {t}")).collect();
213    let args: Vec<String> =
214        s.f.params
215            .iter()
216            .enumerate()
217            .map(|(i, (n, t))| {
218                let by_ref = t.trim() == "&str";
219                match (i == s.item, by_ref) {
220                    (true, true) => "item.as_str()".to_string(),
221                    (true, false) if is_copy(&s.item_ty) => "*item".into(),
222                    (true, false) => "item.clone()".into(),
223                    (false, true) => format!("{n}.as_str()"),
224                    (false, false) if is_copy(t) => n.clone(),
225                    (false, false) => format!("{n}.clone()"),
226                }
227            })
228            .collect();
229    let call = format!("port::{}({})", s.f.rust_name, args.join(", "));
230    let call = if s.f.fallible {
231        call
232    } else {
233        format!("Ok::<_, String>({call})")
234    };
235    let iter = if parallel { "par_iter" } else { "iter" };
236    format!(
237        "\n/// The items of `{class}` as the port takes them; the port runs per item. Define\n\
238         /// `pub struct {base}Index` in `port.rs` (with `new` and `run`) to prepare items once.\n\
239         pub struct {index} {{\n    items: Vec<{item}>,\n}}\n\n\
240         impl {index} {{\n    pub fn new(items: Vec<{item}>) -> Self {{\n        Self {{ items }}\n    }}\n\n    \
241         pub fn run(&self, {params}) -> Result<Vec<{ret}>, String> {{\n        \
242         {use_rayon}self.items.{iter}().map(|item| {call}).collect::<Vec<_>>().into_iter().collect()\n    }}\n}}\n",
243        class = s.class,
244        base = s.class.trim_end_matches("Batch"),
245        index = s.index,
246        item = s.item_ty,
247        params = params.join(", "),
248        ret = s.f.ret,
249        use_rayon = if parallel {
250            "use rayon::prelude::*;\n        "
251        } else {
252            ""
253        },
254    )
255}
256
257/// How each language hands back a `Vec<R>`.
258fn napi_out(ret: &str) -> (&'static str, &'static str) {
259    match ret {
260        "f64" => (
261            "napi::bindgen_prelude::Float64Array",
262            "napi::bindgen_prelude::Float64Array::new(out)",
263        ),
264        "i64" => (
265            "napi::bindgen_prelude::Float64Array",
266            "napi::bindgen_prelude::Float64Array::new(out.into_iter().map(|x| x as f64).collect())",
267        ),
268        "bool" => (
269            "napi::bindgen_prelude::Uint8Array",
270            "napi::bindgen_prelude::Uint8Array::new(out.into_iter().map(u8::from).collect())",
271        ),
272        _ => ("Vec<String>", "out"),
273    }
274}
275
276/// The ranking code for a spec: the index's own `rank` when it has one, else the generic body
277/// over `run`'s results (the generated call is switched by [`use_custom_rank`]).
278pub(crate) fn rank_for(s: &Spec) -> Option<String> {
279    let body = rank_body(s.f.ret.trim())?;
280    Some(if s.custom_rank {
281        "let order: Vec<u32> = out;".to_string()
282    } else {
283        body
284    })
285}
286
287/// In code appended to `out` since `from`: calls the index's `rank(<fixed>, min)` instead of
288/// `run(<fixed>)`, when it has one.
289pub(crate) fn use_custom_rank(out: &mut String, from: usize, s: &Spec, names: &[&str]) {
290    if !s.custom_rank {
291        return;
292    }
293    let args = names.join(", ");
294    let with_min = if args.is_empty() {
295        "min".to_string()
296    } else {
297        format!("{args}, min")
298    };
299    let tail = out.split_off(from);
300    out.push_str(&tail.replacen(&format!(".run({args})"), &format!(".rank({with_min})"), 1));
301}
302
303pub(crate) fn rank_body(ret: &str) -> Option<String> {
304    let value = match ret {
305        "f64" => "r",
306        "i64" => "r as f64",
307        _ => return None,
308    };
309    Some(format!(
310        "let mut hits: Vec<(f64, u32)> = out\n            .into_iter()\n            .enumerate()\n            \
311         .map(|(i, r)| ({value}, u32::try_from(i).unwrap_or(u32::MAX)))\n            .filter(|(r, _)| *r >= min)\n            .collect();\n        \
312         // Stable: equal results keep the items' order, as JS `sort` and Python `sorted` do.\n        \
313         hits.sort_by(|a, b| b.0.total_cmp(&a.0));\n        let order: Vec<u32> = hits.into_iter().map(|(_, i)| i).collect();"
314    ))
315}
316
317/// Batch classes for a napi-rs or wasm-bindgen `lib.rs`.
318pub fn js_rs(m: &Manifest, api: &PortApi) -> Result<String, String> {
319    let mut out = String::new();
320    let parallel = m.kind == Kind::Napi;
321    let fast = if parallel {
322        fast_batches(m, api)
323    } else {
324        Vec::new()
325    };
326    let strings_out = fast.iter().any(|b| b.strings_out);
327    if strings_out {
328        out.push_str(JOINED_OUT_RS);
329    }
330    if fast.iter().any(|b| b.items == Items::Strings) {
331        out.push_str(JOINED_IN_RS);
332    }
333    for b in &m.batches {
334        let s = spec(b, api)?;
335        if !s.custom {
336            out.push_str(&default_index(&s, parallel));
337        }
338        let fixed = fixed(&s);
339        let params: Vec<String> = fixed.iter().map(|(n, t)| format!("{n}: {t}")).collect();
340        let names: Vec<&str> = fixed.iter().map(|(n, _)| n.as_str()).collect();
341        let ret = s.f.ret.trim();
342        let (out_ty, out_expr) = napi_out(ret);
343        let wasm = m.kind == Kind::Wasm;
344        let (attr, ctor_attr, err, res) = if wasm {
345            (
346                "wasm_bindgen",
347                "#[wasm_bindgen(constructor)]",
348                ".map_err(|e| JsError::new(&e))",
349                "Result<{T}, JsError>",
350            )
351        } else {
352            ("napi", "#[napi(constructor)]", "", "napi::Result<{T}>")
353        };
354        let call = |body: &str| -> String {
355            if wasm {
356                format!(
357                    "let out = self.inner.run({}){err}?;\n        {body}",
358                    names.join(", ")
359                )
360            } else {
361                format!(
362                    "let out = run(|| self.inner.run({}))?;\n        {body}",
363                    names.join(", ")
364                )
365            }
366        };
367        let out_ty = if wasm {
368            out_ty
369                .replace("napi::bindgen_prelude::", "Vec<")
370                .replace("Float64Array", "f64>")
371                .replace("Uint8Array", "u8>")
372        } else {
373            out_ty.to_string()
374        };
375        let out_expr = if wasm {
376            match ret {
377                "i64" => "out.into_iter().map(|x| x as f64).collect()".to_string(),
378                "bool" => "out.into_iter().map(u8::from).collect()".to_string(),
379                _ => "out".to_string(),
380            }
381        } else {
382            out_expr.to_string()
383        };
384        let _ = write!(
385            out,
386            "\n/// `{js}` over many `{param}` values kept in Rust: `run` maps them all in one call{cores};\n\
387             /// `rank` returns the indexes of results >= `min`, best first.\n\
388             #[{attr}(js_name = \"{class}\")]\npub struct {class} {{\n    inner: {index},\n}}\n\n\
389             {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    \
390             /// The result for every item, in order.\n    #[{attr}]\n    pub fn run(&self, {params}) -> {res_run} {{\n        {run_body}\n    }}\n{run_joined}",
391            impl_attr = if wasm {
392                format!("#[wasm_bindgen(js_class = \"{}\")]", s.class)
393            } else {
394                "#[napi]".to_string()
395            },
396            js = s.f.js_name,
397            param = b.param,
398            cores = if parallel { ", on all cores" } else { "" },
399            class = s.class,
400            index = s.index,
401            item = s.item_ty,
402            params = params.join(", "),
403            res_run = res.replace("{T}", &out_ty),
404            run_body = call(&format!("Ok({out_expr})")),
405            from_joined = if parallel && s.item_ty == "String" {
406                format!(
407                    "\n    /// `new` for items sent as one joined string and their UTF-16 end offsets.\n    \
408                     #[napi(factory, js_name = \"fromJoined\")]\n    \
409                     pub fn from_joined(text: String, ends: napi::bindgen_prelude::Uint32Array) -> Self {{\n        \
410                     Self {{ inner: {}::new(split_joined(&text, &ends)) }}\n    }}\n",
411                    s.index
412                )
413            } else if parallel && s.item_ty == "f64" {
414                format!(
415                    "\n    /// `new` for items sent as one `Float64Array`.\n    \
416                     #[napi(factory, js_name = \"fromFloat64\")]\n    \
417                     pub fn from_float64(items: napi::bindgen_prelude::Float64Array) -> Self {{\n        \
418                     Self {{ inner: {}::new(items.to_vec()) }}\n    }}\n",
419                    s.index
420                )
421            } else {
422                String::new()
423            },
424            run_joined = if parallel && ret == "String" {
425                format!(
426                    "\n    /// `run` with the results joined into one string and their UTF-16 end offsets.\n    \
427                     #[napi(js_name = \"runJoined\")]\n    \
428                     pub fn run_joined(&self, {}) -> napi::Result<JoinedStrings> {{\n        {}\n    }}\n",
429                    params.join(", "),
430                    call("Ok(joined(out))")
431                )
432            } else {
433                String::new()
434            },
435        );
436        if let Some(rank) = rank_for(&s) {
437            let from = out.len();
438            let order_ty = if wasm {
439                "Vec<u32>"
440            } else {
441                "napi::bindgen_prelude::Uint32Array"
442            };
443            let order_expr = if wasm {
444                "order"
445            } else {
446                "napi::bindgen_prelude::Uint32Array::new(order)"
447            };
448            let sep = if params.is_empty() { "" } else { ", " };
449            let _ = write!(
450                out,
451                "\n    /// Indexes of the items whose result is at least `min`, highest result first.\n    #[{attr}]\n    \
452                 pub fn rank(&self, {}{sep}min: f64) -> {} {{\n        {}\n    }}\n",
453                params.join(", "),
454                res.replace("{T}", order_ty),
455                call(&format!("{rank}\n        Ok({order_expr})"))
456            );
457            use_custom_rank(&mut out, from, &s, &names);
458        }
459        out.push_str("}\n");
460    }
461    Ok(out)
462}
463
464#[derive(Clone, Copy, PartialEq, Eq)]
465pub(crate) enum Items {
466    Strings,
467    Numbers,
468    Other,
469}
470
471/// A napi batch whose values cross in bulk instead of one JS value per item.
472pub(crate) struct FastBatch {
473    class: String,
474    items: Items,
475    strings_out: bool,
476}
477
478/// The napi batches whose items or results cross in bulk. One JS value per item costs more than
479/// the work of a small function, so `index.cjs` joins string items into one string, packs number
480/// items into a `Float64Array`, and splits joined string results with `slice`.
481pub(crate) fn fast_batches(m: &Manifest, api: &PortApi) -> Vec<FastBatch> {
482    if m.kind != Kind::Napi {
483        return Vec::new();
484    }
485    m.batches
486        .iter()
487        .filter_map(|b| spec(b, api).ok())
488        .map(|s| FastBatch {
489            class: s.class.clone(),
490            items: match s.item_ty.as_str() {
491                "String" => Items::Strings,
492                "f64" => Items::Numbers,
493                _ => Items::Other,
494            },
495            strings_out: s.f.ret.trim() == "String",
496        })
497        .filter(|b| b.items != Items::Other || b.strings_out)
498        .collect()
499}
500
501const JOINED_OUT_RS: &str = r#"
502/// Strings joined into one, with the UTF-16 end offset of each (what JS `slice` takes).
503#[napi(object)]
504pub struct JoinedStrings {
505    pub text: String,
506    pub ends: napi::bindgen_prelude::Uint32Array,
507}
508
509fn joined(out: Vec<String>) -> JoinedStrings {
510    let mut text = String::with_capacity(out.iter().map(String::len).sum());
511    let mut ends = Vec::with_capacity(out.len());
512    let mut at = 0u32;
513    for s in &out {
514        text.push_str(s);
515        let units = if s.is_ascii() { s.len() } else { s.encode_utf16().count() };
516        at = at.saturating_add(u32::try_from(units).unwrap_or(u32::MAX));
517        ends.push(at);
518    }
519    JoinedStrings {
520        text,
521        ends: napi::bindgen_prelude::Uint32Array::new(ends),
522    }
523}
524
525"#;
526
527const JOINED_IN_RS: &str = r#"
528/// Splits `text` at UTF-16 end offsets. A lone surrogate arrived as U+FFFD, one unit as before.
529fn split_joined(text: &str, ends: &[u32]) -> Vec<String> {
530    let ascii = text.is_ascii()
531        && ends.last().is_none_or(|&e| e as usize == text.len())
532        && ends.windows(2).all(|w| w[0] <= w[1]);
533    let mut out = Vec::with_capacity(ends.len());
534    if ascii {
535        let mut from = 0;
536        for &e in ends {
537            out.push(text[from..e as usize].to_string());
538            from = e as usize;
539        }
540        return out;
541    }
542    let mut chars = text.chars();
543    let mut unit = 0usize;
544    for &e in ends {
545        let mut s = String::new();
546        while unit < e as usize {
547            let Some(c) = chars.next() else { break };
548            unit += c.len_utf16();
549            s.push(c);
550        }
551        out.push(s);
552    }
553    out
554}
555"#;
556
557/// The `index.cjs` part that sends and receives the values of [`fast_batches`] in bulk.
558pub fn index_cjs(m: &Manifest, api: &PortApi) -> String {
559    let batches = fast_batches(m, api);
560    if batches.is_empty() {
561        return String::new();
562    }
563    let list = |pick: &dyn Fn(&FastBatch) -> bool| -> String {
564        batches
565            .iter()
566            .filter(|b| pick(b))
567            .map(|b| format!("'{}'", b.class))
568            .collect::<Vec<_>>()
569            .join(", ")
570    };
571    format!(
572        "{JOINED_CJS}for (const name of [{}]) joinItems(name)\n\
573         for (const name of [{}]) packNumbers(name)\n\
574         for (const name of [{}]) splitResults(name)\n",
575        list(&|b| b.items == Items::Strings),
576        list(&|b| b.items == Items::Numbers),
577        list(&|b| b.strings_out)
578    )
579}
580
581const JOINED_CJS: &str = r#"
582// Batches: strings cross as one joined string and the UTF-16 end offset of each, numbers as one
583// Float64Array, which costs far less than one JS value per item. `new Batch(items)` and
584// `batch.run()` keep their shape.
585const joinItems = name => {
586  const Native = native[name]
587  const Batch = { [name]: function (items) {
588    if (!Array.isArray(items)) throw new TypeError(`${name}: items must be an array of strings`)
589    const ends = new Uint32Array(items.length)
590    let at = 0
591    for (let i = 0; i < items.length; i++) {
592      if (typeof items[i] !== 'string') throw new TypeError(`${name}: items must be an array of strings`)
593      ends[i] = at += items[i].length
594    }
595    return Native.fromJoined(items.join(''), ends)
596  } }[name]
597  Batch.prototype = Native.prototype
598  Batch.fromJoined = Native.fromJoined
599  module.exports[name] = Batch
600}
601const packNumbers = name => {
602  const Native = native[name]
603  const Batch = { [name]: function (items) {
604    if (!Array.isArray(items)) throw new TypeError(`${name}: items must be an array of numbers`)
605    const packed = new Float64Array(items.length)
606    for (let i = 0; i < items.length; i++) {
607      if (typeof items[i] !== 'number') throw new TypeError(`${name}: items must be an array of numbers`)
608      packed[i] = items[i]
609    }
610    return Native.fromFloat64(packed)
611  } }[name]
612  Batch.prototype = Native.prototype
613  Batch.fromFloat64 = Native.fromFloat64
614  module.exports[name] = Batch
615}
616const splitResults = name => {
617  Object.defineProperty(native[name].prototype, 'run', {
618    value: function (...a) {
619      const { text, ends } = this.runJoined(...a)
620      const out = new Array(ends.length)
621      for (let i = 0, from = 0; i < ends.length; from = ends[i++]) out[i] = text.slice(from, ends[i])
622      return out
623    },
624    writable: true,
625    configurable: true,
626  })
627}
628"#;
629
630/// Batch classes for a PyO3 `lib.rs`, and the names to register.
631pub fn py_rs(m: &Manifest, api: &PortApi) -> Result<(String, Vec<String>), String> {
632    let mut out = String::new();
633    let mut classes = Vec::new();
634    for b in &m.batches {
635        let s = spec(b, api)?;
636        if !s.custom {
637            out.push_str(&default_index(&s, true));
638        }
639        let fixed = fixed(&s);
640        let params: Vec<String> = fixed.iter().map(|(n, t)| format!("{n}: {t}")).collect();
641        let names: Vec<&str> = fixed.iter().map(|(n, _)| n.as_str()).collect();
642        let ret = s.f.ret.trim();
643        let sep = if params.is_empty() { "" } else { ", " };
644        let _ = write!(
645            out,
646            "\n/// `{js}` over many `{param}` values kept in Rust: `run` maps them all in one call, on all\n\
647             /// cores, without the GIL; `rank` returns the indexes of results >= `min`, best first.\n\
648             #[pyclass(name = \"{class}\")]\npub struct {class} {{\n    inner: {index},\n}}\n\n#[pymethods]\nimpl {class} {{\n    \
649             #[new]\n    fn new(items: Vec<{item}>) -> Self {{\n        Self {{ inner: {index}::new(items) }}\n    }}\n\n    \
650             /// The result for every item, in order.\n    fn run(&self, py: Python<'_>{sep}{params}) -> PyResult<Vec<{ret}>> {{\n        \
651             py.detach(|| self.inner.run({names})).map_err(error)\n    }}\n",
652            js = s.f.js_name,
653            param = b.param,
654            class = s.class,
655            index = s.index,
656            item = s.item_ty,
657            params = params.join(", "),
658            names = names.join(", "),
659        );
660        if let Some(rank) = rank_for(&s) {
661            let from = out.len();
662            let _ = write!(
663                out,
664                "\n    /// Indexes of the items whose result is at least `min`, highest result first.\n    \
665                 fn rank(&self, py: Python<'_>{sep}{params}, min: f64) -> PyResult<Vec<u32>> {{\n        \
666                 let out = py.detach(|| self.inner.run({names})).map_err(error)?;\n        {rank}\n        Ok(order)\n    }}\n",
667                params = params.join(", "),
668                names = names.join(", "),
669            );
670            use_custom_rank(&mut out, from, &s, &names);
671        }
672        out.push_str("}\n");
673        classes.push(s.class);
674    }
675    Ok((out, classes))
676}
677
678/// Whether the crate depends on rayon: every crate with batches. Wasm gets it too, so a
679/// `port.rs` index using it builds for both kinds: without threads, rayon runs on the calling
680/// thread.
681pub fn needs_rayon(m: &Manifest) -> bool {
682    !m.batches.is_empty()
683}
684
685#[cfg(test)]
686mod tests {
687    use super::*;
688
689    #[test]
690    fn copies_only_copy_types() {
691        for t in ["f64", "Option<i64>", "(f64, bool)", "Option<(u32, char)>"] {
692            assert!(is_copy(t), "{t}");
693        }
694        for t in [
695            "String",
696            "Option<String>",
697            "Vec<f64>",
698            "(f64, String)",
699            "serde_json::Value",
700        ] {
701            assert!(!is_copy(t), "{t}");
702        }
703    }
704
705    #[test]
706    fn unknown_names_list_the_choices() {
707        let api = crate::codegen::parse_port(
708            "pub fn add(a: f64, b: f64) -> f64 {\n    a + b\n}\npub fn neg(x: f64) -> f64 {\n    -x\n}\n",
709        );
710        let batch = |spec: &str| Batch::parse(spec).unwrap();
711        let err = spec(&batch("nope:a"), &api).err().unwrap();
712        assert!(err.contains("(functions: add, neg)"), "{err}");
713        let err = spec(&batch("add:zz"), &api).err().unwrap();
714        assert!(err.contains("(parameters: a, b)"), "{err}");
715        for empty in ["add:", ":a", " : ", "add: "] {
716            assert_eq!(Batch::parse(empty), None, "{empty:?}");
717        }
718    }
719
720    #[test]
721    fn parses_and_names() {
722        let b = Batch::parse("fuzzyScore:text").unwrap();
723        assert_eq!(
724            b,
725            Batch {
726                function: "fuzzyScore".into(),
727                param: "text".into()
728            }
729        );
730        assert_eq!(pascal("fuzzyScore"), "FuzzyScore");
731        assert_eq!(pascal("rgb_to_hsv"), "RgbToHsv");
732    }
733}