alef 0.79.3

Opinionated polyglot binding generator for Rust libraries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
//! NAPI-RS function and method code generation.

mod adapter_wrappers;
mod call_args;
mod conversion_bindings;
mod return_wrapping;

pub(super) use adapter_wrappers::{gen_adapter_wrapper, gen_tokio_runtime};
pub(super) use call_args::{
    core_prim_str, napi_apply_primitive_casts_to_call_args, napi_gen_call_args, needs_napi_cast,
};
use call_args::{is_bytes_param, needs_vec_f32_conversion};
use conversion_bindings::{gen_napi_buffer_conversion_bindings, gen_vec_f32_conversion_bindings};
pub(super) use return_wrapping::{napi_wrap_return, napi_wrap_return_fn};

use crate::codegen::generators::{self, RustBindingConfig};
use crate::codegen::naming::to_node_name;
use crate::codegen::shared::function_params;
use crate::codegen::type_mapper::TypeMapper;
use crate::core::ir::{FunctionDef, TypeRef};
use ahash::AHashSet;

use crate::backends::napi::type_map::NapiMapper;

#[allow(clippy::too_many_arguments)]
pub(super) fn gen_function(
    func: &FunctionDef,
    mapper: &NapiMapper,
    cfg: &RustBindingConfig,
    opaque_types: &AHashSet<String>,
    default_types: &AHashSet<String>,
    prefix: &str,
    capsule_types: &std::collections::HashMap<String, crate::core::config::NodeCapsuleTypeConfig>,
    mutex_types: &AHashSet<String>,
) -> String {
    let augmented_params: Vec<crate::core::ir::ParamDef> = func
        .params
        .iter()
        .map(|p| {
            let mut p2 = p.clone();
            if !p2.optional
                && let TypeRef::Named(n) = &p2.ty
                && default_types.contains(n.as_str())
                && !opaque_types.contains(n.as_str())
            {
                p2.optional = true;
            }
            p2
        })
        .collect();
    let params = function_params(&augmented_params, &|ty| {
        if let TypeRef::Named(n) = ty {
            if capsule_types.contains_key(n.as_str())
                && let Some(capsule_cfg) = capsule_types.get(n.as_str())
            {
                return capsule_cfg.from_module.clone();
            }
            if opaque_types.contains(n.as_str()) {
                return format!("&{prefix}{n}");
            }
        }
        mapper.map_type(ty)
    });
    let default_coerce_prefix: String = augmented_params
        .iter()
        .zip(func.params.iter())
        .enumerate()
        .filter_map(|(idx, (aug, orig))| {
            if aug.optional && !orig.optional && !crate::codegen::shared::is_promoted_optional(&func.params, idx) {
                let is_named_non_opaque = matches!(&orig.ty,
                    TypeRef::Named(n) if !opaque_types.contains(n.as_str())
                );
                if is_named_non_opaque {
                    return None;
                }
                let mut_kw = if orig.is_mut { "mut " } else { "" };
                Some(format!(
                    "    let {}{} = {}.unwrap_or_default();\n",
                    mut_kw, orig.name, orig.name
                ))
            } else {
                None
            }
        })
        .collect();
    // A `&mut T` DTO parameter on a unit-returning function (sync or async) cannot write back
    // through the mutated intermediate (the JS object handed to the binding is by-value), so the
    // binding returns the updated `T` instead. The async branch below special-cases the writeback
    // body directly rather than going through `gen_async_body`, since that helper's unit-return
    // handling hardcodes an `Ok(())` tail that would no longer match this declared return type.
    // See `mut_writeback` for the policy; `generate_bindings` calls `reject_unsupported_writeback`
    // before this function runs, so any shape this module cannot express has already been
    // rejected. ~keep
    let writeback_param = crate::codegen::mut_writeback::writeback_param(&func.params, &func.return_type, opaque_types);
    let writeback_var = writeback_param.map(|p| format!("{}_core", p.name));

    let return_type = match writeback_param {
        Some(p) => mapper.map_type(&p.ty),
        None => mapper.map_type(&func.return_type),
    };
    let return_annotation = mapper.wrap_return(&return_type, func.error_type.is_some());

    let js_name = to_node_name(&func.name);
    let js_name_attr = if js_name != func.name {
        format!("(js_name = \"{}\")", js_name)
    } else {
        String::new()
    };

    let core_import = cfg.core_import;
    let core_fn_path = {
        let path = func.rust_path.replace('-', "_");
        if path.starts_with(core_import) {
            path
        } else {
            format!("{core_import}::{}", func.name)
        }
    };

    let use_let_bindings = generators::has_named_params(&func.params, opaque_types)
        || func.params.iter().any(|p| needs_vec_f32_conversion(&p.ty))
        || func.params.iter().any(|p| is_bytes_param(&p.ty));
    let call_args = if use_let_bindings {
        let base_args = generators::gen_call_args_with_let_bindings_mutex(&func.params, opaque_types, mutex_types);
        napi_apply_primitive_casts_to_call_args(&base_args, &func.params)
    } else {
        napi_gen_call_args(&func.params, opaque_types)
    };

    let can_delegate_fn = generators::can_auto_delegate_function_with_named_let_bindings(func, opaque_types);

    let err_conv = ".map_err(|e| napi::Error::new(napi::Status::GenericFailure, e.to_string()))";

    let async_kw = if func.is_async { "async " } else { "" };

    let body = if !can_delegate_fn {
        if cfg.has_serde && use_let_bindings && func.error_type.is_some() {
            let serde_bindings =
                generators::gen_serde_let_bindings(&func.params, opaque_types, core_import, err_conv, "    ");
            let vec_str_bindings: String = func.params.iter().filter(|p| {
                p.is_ref && p.vec_inner_is_ref && matches!(&p.ty, TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::String | TypeRef::Char))
            }).map(|p| {
                format!("let {}_refs: Vec<&str> = {}.iter().map(|s| s.as_str()).collect();\n    ", p.name, p.name)
            }).collect();
            let core_call = format!("{core_fn_path}({call_args})");
            let await_kw = if func.is_async { ".await" } else { "" };

            if matches!(func.return_type, TypeRef::Unit) {
                format!("{vec_str_bindings}{serde_bindings}{core_call}{await_kw}{err_conv}?;\n    Ok(())")
            } else {
                let wrapped = napi_wrap_return_fn(
                    "val",
                    &func.return_type,
                    opaque_types,
                    func.returns_ref,
                    prefix,
                    Some(capsule_types),
                    mutex_types,
                );
                if wrapped == "val" {
                    format!("{vec_str_bindings}{serde_bindings}{core_call}{await_kw}{err_conv}")
                } else {
                    format!("{vec_str_bindings}{serde_bindings}{core_call}{await_kw}.map(|val| {wrapped}){err_conv}")
                }
            }
        } else {
            generators::gen_unimplemented_body(
                &func.return_type,
                &func.name,
                func.error_type.is_some(),
                cfg,
                &func.params,
                opaque_types,
            )
        }
    } else if func.is_async {
        let mut let_bindings = if use_let_bindings {
            generators::gen_named_let_bindings_with_augmented(
                &augmented_params,
                &func.params,
                opaque_types,
                core_import,
            )
        } else {
            String::new()
        };
        let_bindings.push_str(&gen_vec_f32_conversion_bindings(&func.params));
        let_bindings.push_str(&gen_napi_buffer_conversion_bindings(&func.params));
        let core_call = format!("{core_fn_path}({call_args})");
        if let Some(var) = &writeback_var {
            // Async `&mut` DTO write-back: the core future resolves to `()` (or `Result<(), E>`),
            // which the sync writeback branch below discards in favor of the mutated
            // intermediate. Mirror that here with an `.await` ahead of the discard. ~keep
            if func.error_type.is_some() {
                format!("{let_bindings}{core_call}.await.map(|_| {var}.into()){err_conv}")
            } else {
                format!("{let_bindings}{core_call}.await;\n            {var}.into()")
            }
        } else {
            let return_wrap = napi_wrap_return_fn(
                "result",
                &func.return_type,
                opaque_types,
                func.returns_ref,
                prefix,
                Some(capsule_types),
                mutex_types,
            );
            let return_type = mapper.map_type(&func.return_type);
            generators::gen_async_body(
                &core_call,
                cfg,
                func.error_type.is_some(),
                &return_wrap,
                false,
                &let_bindings,
                matches!(func.return_type, TypeRef::Unit),
                Some(&return_type),
            )
        }
    } else {
        let core_call = format!("{core_fn_path}({call_args})");
        let mut let_bindings = if use_let_bindings {
            generators::gen_named_let_bindings_with_augmented(
                &augmented_params,
                &func.params,
                opaque_types,
                core_import,
            )
        } else {
            String::new()
        };
        let_bindings.push_str(&gen_vec_f32_conversion_bindings(&func.params));
        let_bindings.push_str(&gen_napi_buffer_conversion_bindings(&func.params));

        if let Some(var) = &writeback_var {
            // The core call mutates `{var}` and returns `()`; the binding hands back the
            // mutated intermediate instead of the (discarded) unit value. ~keep
            if func.error_type.is_some() {
                format!("{let_bindings}{core_call}.map(|_| {var}.into()){err_conv}")
            } else {
                format!("{let_bindings}{core_call};\n    {var}.into()")
            }
        } else if func.error_type.is_some() {
            let wrapped = napi_wrap_return_fn(
                "val",
                &func.return_type,
                opaque_types,
                func.returns_ref,
                prefix,
                Some(capsule_types),
                mutex_types,
            );
            if wrapped == "val" {
                format!("{let_bindings}{core_call}{err_conv}")
            } else {
                format!("{let_bindings}{core_call}.map(|val| {wrapped}){err_conv}")
            }
        } else {
            format!(
                "{let_bindings}{}",
                napi_wrap_return_fn(
                    &core_call,
                    &func.return_type,
                    opaque_types,
                    func.returns_ref,
                    prefix,
                    Some(capsule_types),
                    mutex_types
                )
            )
        }
    };

    let mut attrs = String::new();
    let sanitized_doc =
        crate::codegen::doc_emission::sanitize_rust_idioms(&func.doc, crate::codegen::doc_emission::DocTarget::TsDoc);
    crate::codegen::doc_emission::emit_rustdoc(&mut attrs, &sanitized_doc, "");
    if func.params.len() > 7 {
        attrs.push_str("#[allow(clippy::too_many_arguments)]\n");
    }
    if func.error_type.is_some() {
        attrs.push_str("#[allow(clippy::missing_errors_doc)]\n");
    }
    let body = if default_coerce_prefix.is_empty() {
        body
    } else {
        format!("{}{}", default_coerce_prefix, body)
    };
    crate::backends::napi::template_env::render(
        "function_wrapper.jinja",
        minijinja::context! {
            attrs => attrs,
            js_name_attr => js_name_attr,
            async_kw => async_kw,
            func_name => &func.name,
            params => params,
            return_annotation => return_annotation,
            body => body,
        },
    )
}

#[cfg(test)]
mod tests {
    use super::gen_tokio_runtime;

    /// gen_tokio_runtime produces a static runtime with an enlarged worker stack so deep
    /// consumer futures (e.g. an OCR pipeline) do not overflow the default ~2 MB stack (SIGBUS).
    #[test]
    fn gen_tokio_runtime_contains_runtime() {
        let result = gen_tokio_runtime();
        assert!(result.contains("TOKIO_RUNTIME") || result.contains("Runtime") || result.contains("tokio"));
        assert!(
            result.contains("thread_stack_size"),
            "worker pool must enlarge the stack:\n{result}"
        );
    }

    fn record_param(is_ref: bool, is_mut: bool) -> crate::core::ir::ParamDef {
        crate::core::ir::ParamDef {
            name: "record".to_owned(),
            ty: crate::core::ir::TypeRef::Named("Record".to_owned()),
            is_ref,
            is_mut,
            ..crate::core::ir::ParamDef::default()
        }
    }

    fn gen_probe_function(func: &crate::core::ir::FunctionDef) -> String {
        use crate::backends::napi::gen_bindings::NapiBackend;
        use crate::backends::napi::type_map::NapiMapper;

        let mapper = NapiMapper::new("Js".to_owned());
        let cfg = NapiBackend::binding_config("sample_core", "Js", true);
        let opaque_types = ahash::AHashSet::new();
        let default_types = ahash::AHashSet::new();
        let capsule_types = std::collections::HashMap::new();
        let mutex_types = ahash::AHashSet::new();

        super::gen_function(
            func,
            &mapper,
            &cfg,
            &opaque_types,
            &default_types,
            "Js",
            &capsule_types,
            &mutex_types,
        )
    }

    /// Regression test for issue #380: a `&mut T` DTO parameter on a unit-returning sync
    /// function previously rendered as `pub fn tag_record(record: JsRecord) -> ()`, mutating a
    /// dropped `_core` intermediate and leaving the caller's JS object untouched with no
    /// diagnostic. The binding must instead return the mutated intermediate.
    #[test]
    fn napi_mut_dto_param_returns_the_updated_value() {
        use crate::core::ir::{FunctionDef, TypeRef};

        let func = FunctionDef {
            name: "tag_record".to_owned(),
            rust_path: "sample_core::tag_record".to_owned(),
            params: vec![record_param(true, true)],
            return_type: TypeRef::Unit,
            is_async: false,
            error_type: None,
            ..FunctionDef::default()
        };

        let output = gen_probe_function(&func);

        assert!(
            output.contains("-> JsRecord"),
            "expected the binding to return the mutated DTO type instead of `()`:\n{output}"
        );
        assert!(
            !output.contains("-> ()"),
            "must not still advertise a unit return:\n{output}"
        );
        // Load-bearing round-trip: the core call must still pass `&mut record_core` AND the tail
        // must hand back `record_core.into()`.
        assert!(
            output.contains("sample_core::tag_record(&mut record_core)"),
            "expected the core call to still pass `&mut record_core`:\n{output}"
        );
        assert!(
            output.contains("record_core.into()"),
            "expected the mutated intermediate to be returned:\n{output}"
        );
    }

    /// Negative control for issue #380: an immutable `&T` DTO param must not gain write-back
    /// semantics -- the return type must stay `()`.
    #[test]
    fn napi_immutable_dto_param_keeps_unit_return() {
        use crate::core::ir::{FunctionDef, TypeRef};

        let func = FunctionDef {
            name: "read_record".to_owned(),
            rust_path: "sample_core::read_record".to_owned(),
            params: vec![record_param(true, false)],
            return_type: TypeRef::Unit,
            is_async: false,
            error_type: None,
            ..FunctionDef::default()
        };

        let output = gen_probe_function(&func);

        assert!(
            output.contains("-> ()"),
            "immutable borrow must keep unit return:\n{output}"
        );
        assert!(
            !output.contains("record_core.into()"),
            "immutable borrow must not gain a write-back tail:\n{output}"
        );
    }

    /// Negative control for issue #380: an owned `T` DTO param must render unaffected by the
    /// write-back rewrite.
    #[test]
    fn napi_owned_dto_param_unaffected_by_writeback() {
        use crate::core::ir::{FunctionDef, TypeRef};

        let func = FunctionDef {
            name: "consume_record".to_owned(),
            rust_path: "sample_core::consume_record".to_owned(),
            params: vec![record_param(false, false)],
            return_type: TypeRef::Unit,
            is_async: false,
            error_type: None,
            ..FunctionDef::default()
        };

        let output = gen_probe_function(&func);

        assert!(output.contains("-> ()"), "owned param must keep unit return:\n{output}");
        assert!(
            !output.contains("record_core.into()"),
            "owned param must not gain a write-back tail:\n{output}"
        );
    }

    /// Regression test for issue #380 (async path): a `&mut T` DTO parameter on a unit-returning
    /// `async fn` previously rendered as `pub async fn tag_record_async(record: JsRecord) -> ()`
    /// with a body that mutated a dropped `_core` intermediate and then returned `Ok(())` -- the
    /// future resolved to nothing and the caller's JS object was left untouched with no
    /// diagnostic. The binding must instead resolve to the mutated intermediate.
    #[test]
    fn napi_async_mut_dto_param_returns_the_updated_value() {
        use crate::core::ir::{FunctionDef, TypeRef};

        let func = FunctionDef {
            name: "tag_record_async".to_owned(),
            rust_path: "sample_core::tag_record_async".to_owned(),
            params: vec![record_param(true, true)],
            return_type: TypeRef::Unit,
            is_async: true,
            error_type: None,
            ..FunctionDef::default()
        };

        let output = gen_probe_function(&func);

        assert!(
            output.contains("-> JsRecord"),
            "expected the binding to return the mutated DTO type instead of `()`:\n{output}"
        );
        assert!(
            !output.contains("-> ()"),
            "must not still advertise a unit return:\n{output}"
        );
        // Load-bearing round-trip: the core call must still `.await` while passing
        // `&mut record_core`, AND the tail must hand back `record_core.into()`.
        assert!(
            output.contains("sample_core::tag_record_async(&mut record_core)"),
            "expected the core call to still pass `&mut record_core`:\n{output}"
        );
        assert!(
            output.contains(".await"),
            "expected the core call to still be awaited:\n{output}"
        );
        assert!(
            output.contains("record_core.into()"),
            "expected the mutated intermediate to be returned:\n{output}"
        );
        assert!(
            !output.contains("Ok(())"),
            "must not resolve the future to unit and drop the mutated value:\n{output}"
        );
    }

    /// Async write-back must also work when the core function returns `Result<(), E>`: the
    /// binding must map the `Ok(())` to `Ok(record_core.into())` rather than discarding it.
    #[test]
    fn napi_async_mut_dto_param_with_error_returns_the_updated_value() {
        use crate::core::ir::{FunctionDef, TypeRef};

        let func = FunctionDef {
            name: "tag_record_async".to_owned(),
            rust_path: "sample_core::tag_record_async".to_owned(),
            params: vec![record_param(true, true)],
            return_type: TypeRef::Unit,
            is_async: true,
            error_type: Some("ProbeError".to_owned()),
            ..FunctionDef::default()
        };

        let output = gen_probe_function(&func);

        assert!(
            output.contains("Result<JsRecord>"),
            "expected a fallible write-back to return Result<JsRecord>:\n{output}"
        );
        assert!(
            output.contains("sample_core::tag_record_async(&mut record_core)"),
            "expected the core call to still pass `&mut record_core`:\n{output}"
        );
        assert!(
            output.contains(".map(|_| record_core.into())"),
            "expected the Result<(), E> to be mapped into the mutated intermediate:\n{output}"
        );
    }

    /// Negative control: an async immutable `&T` DTO param must not gain write-back semantics.
    #[test]
    fn napi_async_immutable_dto_param_keeps_unit_return() {
        use crate::core::ir::{FunctionDef, TypeRef};

        let func = FunctionDef {
            name: "read_record_async".to_owned(),
            rust_path: "sample_core::read_record_async".to_owned(),
            params: vec![record_param(true, false)],
            return_type: TypeRef::Unit,
            is_async: true,
            error_type: None,
            ..FunctionDef::default()
        };

        let output = gen_probe_function(&func);

        assert!(
            !output.contains("record_core.into()"),
            "immutable borrow must not gain a write-back tail:\n{output}"
        );
    }

    /// Negative control: an async owned `T` DTO param must render unaffected by write-back.
    #[test]
    fn napi_async_owned_dto_param_unaffected_by_writeback() {
        use crate::core::ir::{FunctionDef, TypeRef};

        let func = FunctionDef {
            name: "consume_record_async".to_owned(),
            rust_path: "sample_core::consume_record_async".to_owned(),
            params: vec![record_param(false, false)],
            return_type: TypeRef::Unit,
            is_async: true,
            error_type: None,
            ..FunctionDef::default()
        };

        let output = gen_probe_function(&func);

        assert!(
            !output.contains("record_core.into()"),
            "owned param must not gain a write-back tail:\n{output}"
        );
    }
}