alef 0.25.13

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
use crate::core::ir::{ParamDef, TypeRef};
use ahash::AHashSet;

/// Generate let bindings for non-opaque Named params, converting them to core types.
pub fn gen_named_let_bindings_pub(params: &[ParamDef], opaque_types: &AHashSet<String>, core_import: &str) -> String {
    gen_named_let_bindings(params, opaque_types, core_import)
}

/// Like `gen_named_let_bindings_pub` but for augmented params where non-optional Named params
/// with defaults have been promoted to `Option<T>` in the binding signature.
///
/// Augmented optional params (original `optional=false`, augmented to `optional=true`) must use
/// the "promoted" template (`unwrap_or_default().into()`) rather than the "optional" template
/// (`map(Into::into)`) because the call-site still uses `&param_core` (non-optional borrow from
/// original params). The optional_ref template produces `Option<&T>` which cannot satisfy `&T`.
///
/// Naturally optional params (original `optional=true`) continue using the optional template.
pub fn gen_named_let_bindings_with_augmented(
    augmented_params: &[ParamDef],
    original_params: &[ParamDef],
    opaque_types: &AHashSet<String>,
    core_import: &str,
) -> String {
    gen_named_let_bindings_inner_augmented(augmented_params, original_params, opaque_types, core_import)
}

/// Like `gen_named_let_bindings_pub` but without optional-promotion semantics.
/// Use this for backends (e.g. WASM) that do not promote non-optional params to `Option<T>`.
pub fn gen_named_let_bindings_no_promote(
    params: &[ParamDef],
    opaque_types: &AHashSet<String>,
    core_import: &str,
) -> String {
    gen_named_let_bindings_inner(params, opaque_types, core_import, false)
}

pub(in crate::codegen::generators) fn gen_named_let_bindings(
    params: &[ParamDef],
    opaque_types: &AHashSet<String>,
    core_import: &str,
) -> String {
    gen_named_let_bindings_inner(params, opaque_types, core_import, true)
}

/// Variant of `gen_named_let_bindings` for backends where Named non-opaque params
/// are passed by reference (`&T`) in the function signature (e.g. extendr).
/// Uses `.clone().into()` instead of `.into()` to convert the borrowed value.
pub(in crate::codegen::generators) fn gen_named_let_bindings_by_ref(
    params: &[ParamDef],
    opaque_types: &AHashSet<String>,
    core_import: &str,
) -> String {
    let mut bindings = String::new();
    for (idx, p) in params.iter().enumerate() {
        match &p.ty {
            TypeRef::Named(name) if !opaque_types.contains(name.as_str()) => {
                let promoted = crate::codegen::shared::is_promoted_optional(params, idx);
                let core_type_path = format!("{core_import}::{name}");
                let binding = if p.optional {
                    crate::codegen::template_env::render(
                        "binding_helpers/named_let_binding_by_ref_optional.jinja",
                        minijinja::context! {
                            name => &p.name,
                            core_type_path => &core_type_path,
                        },
                    )
                } else if promoted {
                    crate::codegen::template_env::render(
                        "binding_helpers/named_let_binding_by_ref_promoted.jinja",
                        minijinja::context! {
                            name => &p.name,
                            core_type_path => &core_type_path,
                        },
                    )
                } else {
                    crate::codegen::template_env::render(
                        "binding_helpers/named_let_binding_by_ref_simple.jinja",
                        minijinja::context! {
                            name => &p.name,
                            core_type_path => &core_type_path,
                        },
                    )
                };
                bindings.push_str(&binding);
                bindings.push_str("\n    ");
            }
            TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(n) if !opaque_types.contains(n.as_str())) => {
                let binding = if p.optional {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_named_let_binding_by_ref_optional.jinja",
                        minijinja::context! {
                            name => &p.name,
                        },
                    )
                } else {
                    let promoted = crate::codegen::shared::is_promoted_optional(params, idx);
                    if promoted {
                        crate::codegen::template_env::render(
                            "binding_helpers/vec_named_let_binding_by_ref_promoted.jinja",
                            minijinja::context! {
                                name => &p.name,
                            },
                        )
                    } else {
                        crate::codegen::template_env::render(
                            "binding_helpers/vec_named_let_binding_by_ref_simple.jinja",
                            minijinja::context! {
                                name => &p.name,
                            },
                        )
                    }
                };
                bindings.push_str(&binding);
                bindings.push_str("\n    ");
            }
            TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::String | TypeRef::Char) && p.is_ref => {
                let binding = if p.optional {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_string_refs_binding_optional.jinja",
                        minijinja::context! {
                            name => &p.name,
                        },
                    )
                } else {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_string_refs_binding_simple.jinja",
                        minijinja::context! {
                            name => &p.name,
                        },
                    )
                };
                bindings.push_str(&binding);
                bindings.push_str("\n    ");
            }
            _ => {}
        }
    }
    bindings
}

fn gen_named_let_bindings_inner(
    params: &[ParamDef],
    opaque_types: &AHashSet<String>,
    core_import: &str,
    promote: bool,
) -> String {
    let mut bindings = String::new();
    for (idx, p) in params.iter().enumerate() {
        match &p.ty {
            TypeRef::Named(name) if !opaque_types.contains(name.as_str()) => {
                let promoted = promote && crate::codegen::shared::is_promoted_optional(params, idx);
                let core_type_path = format!("{}::{}", core_import, name);
                let binding = if p.optional {
                    if p.is_ref {
                        crate::codegen::template_env::render(
                            "binding_helpers/named_let_binding_optional_ref.jinja",
                            minijinja::context! {
                                name => &p.name,
                                core_type_path => &core_type_path,
                            },
                        )
                    } else {
                        crate::codegen::template_env::render(
                            "binding_helpers/named_let_binding_optional.jinja",
                            minijinja::context! {
                                name => &p.name,
                                core_type_path => &core_type_path,
                            },
                        )
                    }
                } else if promoted {
                    crate::codegen::template_env::render(
                        "binding_helpers/named_let_binding_promoted.jinja",
                        minijinja::context! {
                            name => &p.name,
                            core_type_path => &core_type_path,
                            // Mutable: core function expects &mut T, so the _core binding must
                            // be declared mut to allow borrowing as mutable reference.
                            is_mut => p.is_mut,
                        },
                    )
                } else {
                    crate::codegen::template_env::render(
                        "binding_helpers/named_let_binding_simple.jinja",
                        minijinja::context! {
                            name => &p.name,
                            core_type_path => &core_type_path,
                            // Mutable: core function expects &mut T, so the _core binding must
                            // be declared mut to allow borrowing as mutable reference.
                            is_mut => p.is_mut,
                        },
                    )
                };
                bindings.push_str(&binding);
                bindings.push_str("\n    ");
            }
            TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(n) if !opaque_types.contains(n.as_str())) => {
                let promoted = promote && crate::codegen::shared::is_promoted_optional(params, idx);
                let binding = if p.optional && p.is_ref {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_named_let_binding_optional.jinja",
                        minijinja::context! {
                            name => &p.name,
                        },
                    )
                } else if p.optional {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_named_let_binding_optional_no_ref.jinja",
                        minijinja::context! {
                            name => &p.name,
                        },
                    )
                } else if promoted {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_named_let_binding_promoted.jinja",
                        minijinja::context! {
                            name => &p.name,
                        },
                    )
                } else {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_named_let_binding_simple.jinja",
                        minijinja::context! {
                            name => &p.name,
                        },
                    )
                };
                bindings.push_str(&binding);
                bindings.push_str("\n    ");
            }
            // Vec<String> with is_ref=true: create a refs binding for call sites that
            // need `&[&str]`; callers that only need `&[String]` may ignore it.
            // Convert Vec<String> to Vec<&str> via intermediate binding.
            TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::String | TypeRef::Char) && p.is_ref => {
                let binding = if p.optional {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_string_refs_binding_optional.jinja",
                        minijinja::context! {
                            name => &p.name,
                        },
                    )
                } else {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_string_refs_binding_simple.jinja",
                        minijinja::context! {
                            name => &p.name,
                        },
                    )
                };
                bindings.push_str(&binding);
                bindings.push_str("\n    ");
            }
            // Sanitized Vec<String> (originally Vec<tuple>): deserialize each JSON string.
            TypeRef::Vec(inner)
                if matches!(inner.as_ref(), TypeRef::String) && p.sanitized && p.original_type.is_some() =>
            {
                let template = if p.optional {
                    "binding_helpers/sanitized_vec_string_filter_optional.jinja"
                } else {
                    "binding_helpers/sanitized_vec_string_filter_simple.jinja"
                };
                bindings.push_str(&crate::codegen::template_env::render(
                    template,
                    minijinja::context! {
                        name => &p.name,
                    },
                ));
            }
            _ => {}
        }
    }
    bindings
}

/// Like `gen_named_let_bindings_inner` but aware of augmented params.
///
/// When `augmented_params[idx].optional = true` but `original_params[idx].optional = false`,
/// the param was augmented (it has a default). Such params must use the "promoted" template
/// (`unwrap_or_default().into()`) because the call-site emits `&param_core` (non-optional borrow
/// from the original params). The optional_ref template produces `Option<&T>` which doesn't
/// satisfy `&T`.
fn gen_named_let_bindings_inner_augmented(
    augmented_params: &[ParamDef],
    original_params: &[ParamDef],
    opaque_types: &AHashSet<String>,
    core_import: &str,
) -> String {
    let mut bindings = String::new();
    for (idx, p) in augmented_params.iter().enumerate() {
        let is_augmented_optional = p.optional && original_params.get(idx).map(|orig| !orig.optional).unwrap_or(false);
        match &p.ty {
            TypeRef::Named(name) if !opaque_types.contains(name.as_str()) => {
                let core_type_path = format!("{}::{}", core_import, name);
                let binding = if is_augmented_optional {
                    // Augmented: was non-optional in core, promoted to Option<T> in the binding
                    // signature. Use promoted template so the let binding produces T (not Option<T>),
                    // allowing the call-site to borrow it as &T.
                    crate::codegen::template_env::render(
                        "binding_helpers/named_let_binding_promoted.jinja",
                        minijinja::context! {
                            name => &p.name,
                            core_type_path => &core_type_path,
                            is_mut => p.is_mut,
                        },
                    )
                } else if p.optional {
                    if p.is_ref {
                        crate::codegen::template_env::render(
                            "binding_helpers/named_let_binding_optional_ref.jinja",
                            minijinja::context! {
                                name => &p.name,
                                core_type_path => &core_type_path,
                            },
                        )
                    } else {
                        crate::codegen::template_env::render(
                            "binding_helpers/named_let_binding_optional.jinja",
                            minijinja::context! {
                                name => &p.name,
                                core_type_path => &core_type_path,
                            },
                        )
                    }
                } else {
                    let promoted = crate::codegen::shared::is_promoted_optional(augmented_params, idx);
                    if promoted {
                        crate::codegen::template_env::render(
                            "binding_helpers/named_let_binding_promoted.jinja",
                            minijinja::context! {
                                name => &p.name,
                                core_type_path => &core_type_path,
                                is_mut => p.is_mut,
                            },
                        )
                    } else {
                        crate::codegen::template_env::render(
                            "binding_helpers/named_let_binding_simple.jinja",
                            minijinja::context! {
                                name => &p.name,
                                core_type_path => &core_type_path,
                                is_mut => p.is_mut,
                            },
                        )
                    }
                };
                bindings.push_str(&binding);
                bindings.push_str("\n    ");
            }
            TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::Named(n) if !opaque_types.contains(n.as_str())) => {
                let binding = if p.optional && p.is_ref {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_named_let_binding_optional.jinja",
                        minijinja::context! {
                            name => &p.name,
                        },
                    )
                } else if p.optional {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_named_let_binding_optional_no_ref.jinja",
                        minijinja::context! {
                            name => &p.name,
                        },
                    )
                } else {
                    let promoted = crate::codegen::shared::is_promoted_optional(augmented_params, idx);
                    let template = if promoted {
                        "binding_helpers/vec_named_let_binding_promoted.jinja"
                    } else {
                        "binding_helpers/vec_named_let_binding_simple.jinja"
                    };
                    crate::codegen::template_env::render(template, minijinja::context! { name => &p.name })
                };
                bindings.push_str(&binding);
                bindings.push_str("\n    ");
            }
            TypeRef::Vec(inner) if matches!(inner.as_ref(), TypeRef::String | TypeRef::Char) && p.is_ref => {
                let binding = if p.optional {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_string_refs_binding_optional.jinja",
                        minijinja::context! { name => &p.name },
                    )
                } else {
                    crate::codegen::template_env::render(
                        "binding_helpers/vec_string_refs_binding_simple.jinja",
                        minijinja::context! { name => &p.name },
                    )
                };
                bindings.push_str(&binding);
                bindings.push_str("\n    ");
            }
            _ => {}
        }
    }
    bindings
}

/// Generate serde-based let bindings for non-opaque Named params.
/// Serializes binding types to JSON and deserializes to core types.
/// Used when From impls don't exist (e.g., types with sanitized fields).
/// `indent` is the whitespace prefix for each generated line (e.g., "    " for functions, "        " for methods).
/// NOTE: This function should only be called when `cfg.has_serde` is true.
/// The caller (functions.rs, methods.rs) must gate the call behind a `has_serde` check.
pub fn gen_serde_let_bindings(
    params: &[ParamDef],
    opaque_types: &AHashSet<String>,
    core_import: &str,
    err_conv: &str,
    indent: &str,
) -> String {
    let mut bindings = String::new();
    for (idx, p) in params.iter().enumerate() {
        let promoted = crate::codegen::shared::is_promoted_optional(params, idx);
        match &p.ty {
            TypeRef::Named(name) if !opaque_types.contains(name.as_str()) => {
                let core_path = format!("{}::{}", core_import, name);
                if p.optional {
                    bindings.push_str(&crate::codegen::template_env::render(
                        "binding_helpers/serde_named_let_binding_optional.jinja",
                        minijinja::context! {
                            name => &p.name,
                            core_path => core_path,
                            err_conv => err_conv,
                            indent => indent,
                        },
                    ));
                } else if promoted {
                    // Promoted-optional: param is required in core but wrapped in Option<T>
                    // in the binding because an earlier param is optional. Use unwrap_or_default()
                    // so JS callers can omit it (pass undefined/null) to get default behaviour.
                    bindings.push_str(&crate::codegen::template_env::render(
                        "binding_helpers/serde_named_let_binding_promoted.jinja",
                        minijinja::context! {
                            name => &p.name,
                            core_path => core_path,
                            err_conv => err_conv,
                            indent => indent,
                        },
                    ));
                } else {
                    bindings.push_str(&crate::codegen::template_env::render(
                        "binding_helpers/serde_named_let_binding_simple.jinja",
                        minijinja::context! {
                            name => &p.name,
                            core_path => core_path,
                            err_conv => err_conv,
                            indent => indent,
                        },
                    ));
                }
            }
            TypeRef::Vec(inner) => {
                if let TypeRef::Named(name) = inner.as_ref() {
                    if !opaque_types.contains(name.as_str()) {
                        let core_path = format!("{}::{}", core_import, name);
                        if p.optional {
                            bindings.push_str(&crate::codegen::template_env::render(
                                "binding_helpers/serde_vec_named_optional.jinja",
                                minijinja::context! {
                                    name => &p.name,
                                    core_path => core_path,
                                    err_conv => err_conv,
                                    indent => indent,
                                },
                            ));
                        } else {
                            bindings.push_str(&crate::codegen::template_env::render(
                                "binding_helpers/serde_vec_named_simple.jinja",
                                minijinja::context! {
                                    name => &p.name,
                                    core_path => core_path,
                                    err_conv => err_conv,
                                    indent => indent,
                                },
                            ));
                        }
                    }
                } else if matches!(inner.as_ref(), TypeRef::String) && p.sanitized && p.original_type.is_some() {
                    // Sanitized Vec<tuple>: binding accepts Vec<String> (JSON-encoded tuple items).
                    // Deserialize each JSON string as a tuple using serde_json.
                    let template = if p.optional {
                        "binding_helpers/serde_sanitized_vec_string_optional.jinja"
                    } else {
                        "binding_helpers/serde_sanitized_vec_string_simple.jinja"
                    };
                    bindings.push_str(&crate::codegen::template_env::render(
                        template,
                        minijinja::context! {
                            name => &p.name,
                            err_conv => err_conv,
                            indent => indent,
                        },
                    ));
                }
            }
            _ => {}
        }
    }
    bindings
}