alef 0.103.17

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
use super::*;
use crate::core::ir::{ParamDef, ReceiverKind};
use std::collections::HashMap;

fn mapper() -> WasmMapper {
    WasmMapper::new(HashMap::new(), "Wasm".to_string())
}

fn param(name: &str, ty: TypeRef) -> ParamDef {
    ParamDef {
        name: name.to_string(),
        ty,
        optional: false,
        default: None,
        sanitized: false,
        typed_default: None,
        is_ref: false,
        is_mut: false,
        newtype_wrapper: None,
        original_type: None,
        map_is_ahash: false,
        map_key_is_cow: false,
        vec_inner_is_ref: false,
        map_is_btree: false,
        core_wrapper: crate::core::ir::CoreWrapper::None,
    }
}

/// A static `default()` method, as synthesized from a type's own custom `impl Default` (not
/// `#[derive(Default)]`) — the shape that put a bare-name path into `core_call` in the first
/// place: `gen_struct_methods` only falls back to the synthetic `<Wasm{T} as Default>::default()`
/// wrapper when `typ.methods` has no `default` entry, so a real custom `impl Default` routes
/// through this generic static-method path instead.
fn default_method(return_type_name: &str) -> MethodDef {
    MethodDef {
        name: "default".to_string(),
        is_static: true,
        return_type: TypeRef::Named(return_type_name.to_string()),
        receiver: None,
        ..Default::default()
    }
}

/// Regression coverage: a type whose `rust_path` nests it under a private module (mirroring
/// a real consumer shape where the type is never re-exported at the crate root)
/// must have its static core call built from that full module path, not from
/// `{core_import}::{typ.name}`. Before the fix, `gen_method`'s static branch built the call as
/// `format!("{core_import}::{type_name}::{method}(...)")`, ignoring `typ.rust_path` entirely —
/// for `RenderOptions` nested under `core::config::render`, that produced
/// `sample_core::RenderOptions::default()`, which rustc rejects with
/// "cannot find `RenderOptions` in `sample_core`" even though the feature gating the type is on.
#[test]
fn gen_method_static_default_uses_full_rust_path_for_nested_type() {
    let typ = TypeDef {
        name: "RenderOptions".to_string(),
        rust_path: "sample_core::config::render::RenderOptions".to_string(),
        ..Default::default()
    };
    let method = default_method("RenderOptions");

    let out = gen_method(
        &method,
        &mapper(),
        "RenderOptions",
        "sample_core",
        &AHashSet::default(),
        "Wasm",
        &typ,
        &AHashSet::default(),
        &ahash::AHashMap::default(),
        &[],
    );

    assert!(
        out.contains("sample_core::config::render::RenderOptions::default()"),
        "static default() must call the type's real module path: {out}"
    );
    assert!(
        !out.contains("sample_core::RenderOptions::default()"),
        "static default() must not assume the type is re-exported at the crate root: {out}"
    );
}

/// Negative control: when the type genuinely does live at the crate root — `rust_path` has no
/// `::` beyond what `core_type_path` treats as bare — the call still resolves to
/// `{core_import}::{name}`. This proves the fix is a real path lookup, not a blanket rewrite
/// that always nests the call under some fixed module.
#[test]
fn gen_method_static_default_uses_bare_path_for_root_type() {
    let typ = TypeDef {
        name: "PlainOptions".to_string(),
        rust_path: "PlainOptions".to_string(),
        ..Default::default()
    };
    let method = default_method("PlainOptions");

    let out = gen_method(
        &method,
        &mapper(),
        "PlainOptions",
        "sample_core",
        &AHashSet::default(),
        "Wasm",
        &typ,
        &AHashSet::default(),
        &ahash::AHashMap::default(),
        &[],
    );

    assert!(
        out.contains("sample_core::PlainOptions::default()"),
        "a crate-root type must still resolve to `{{core_import}}::{{name}}`: {out}"
    );
}

/// Same defect, different call shape: a non-static instance method on a nested type used
/// `format!("{core_import}::{type_name}::from(self.clone())...")`. Cover it too, since it shares
/// the same bare-name assumption and the same `qualified_type_path` fix.
#[test]
fn gen_method_instance_delegate_uses_full_rust_path_for_nested_type() {
    let typ = TypeDef {
        name: "RenderOptions".to_string(),
        rust_path: "sample_core::config::render::RenderOptions".to_string(),
        ..Default::default()
    };
    let method = MethodDef {
        name: "is_sane".to_string(),
        is_static: false,
        return_type: TypeRef::Primitive(crate::core::ir::PrimitiveType::Bool),
        receiver: Some(ReceiverKind::Ref),
        ..Default::default()
    };

    let out = gen_method(
        &method,
        &mapper(),
        "RenderOptions",
        "sample_core",
        &AHashSet::default(),
        "Wasm",
        &typ,
        &AHashSet::default(),
        &ahash::AHashMap::default(),
        &[],
    );

    assert!(
        out.contains("sample_core::config::render::RenderOptions::from(self.clone())"),
        "instance delegation must call the type's real module path: {out}"
    );
    assert!(
        !out.contains("sample_core::RenderOptions::from(self.clone())"),
        "instance delegation must not assume the type is re-exported at the crate root: {out}"
    );
}

/// `core_crate_override` makes the binding crate depend on the override crate *only*, while
/// the IR keeps every type's original source-crate prefix. `source_crate_remaps` is what
/// bridges the two, and this emitter was the one place that reached for the unremapped path:
/// every delegating method and every `Default` body named a crate the generated manifest does
/// not list, so the crate would not compile at all (E0433, once per site). ~keep
#[test]
fn gen_method_rewrites_the_source_crate_prefix_when_a_remap_is_configured() {
    let typ = TypeDef {
        name: "CorsConfig".to_string(),
        rust_path: "sample_core::CorsConfig".to_string(),
        ..Default::default()
    };
    let method = MethodDef {
        name: "is_sane".to_string(),
        is_static: false,
        return_type: TypeRef::Primitive(crate::core::ir::PrimitiveType::Bool),
        receiver: Some(ReceiverKind::Ref),
        ..Default::default()
    };

    let out = gen_method(
        &method,
        &mapper(),
        "CorsConfig",
        "sample_http",
        &AHashSet::default(),
        "Wasm",
        &typ,
        &AHashSet::default(),
        &ahash::AHashMap::default(),
        &[("sample_core", "sample_http")],
    );

    assert!(
        out.contains("sample_http::CorsConfig::from(self.clone())"),
        "the delegation must name the override crate the binding actually depends on: {out}"
    );
    assert!(
        !out.contains("sample_core::"),
        "no reference to the un-depended-on source crate may survive: {out}"
    );
}

#[test]
fn lifetime_static_method_deserializes_map_from_jsvalue_once_and_keeps_required_bool() {
    let typ = TypeDef {
        name: "NodeContext".to_string(),
        rust_path: "sample_fixture::NodeContext".to_string(),
        has_lifetime_params: true,
        ..Default::default()
    };
    let mut parent_tag = param("parent_tag", TypeRef::String);
    parent_tag.optional = true;
    let mut attributes = param(
        "attributes",
        TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::String)),
    );
    attributes.map_is_btree = true;
    let method = MethodDef {
        name: "with_owned_attributes".to_string(),
        is_static: true,
        params: vec![
            param("node_type", TypeRef::Named("NodeType".to_string())),
            param("tag_name", TypeRef::String),
            attributes,
            param("depth", TypeRef::Primitive(crate::core::ir::PrimitiveType::Usize)),
            param(
                "index_in_parent",
                TypeRef::Primitive(crate::core::ir::PrimitiveType::Usize),
            ),
            parent_tag,
            param("is_inline", TypeRef::Primitive(crate::core::ir::PrimitiveType::Bool)),
        ],
        return_type: TypeRef::Named("NodeContext".to_string()),
        ..Default::default()
    };

    let out = gen_method(
        &method,
        &mapper(),
        "NodeContext",
        "sample_fixture",
        &AHashSet::default(),
        "Wasm",
        &typ,
        &AHashSet::default(),
        &ahash::AHashMap::default(),
        &[],
    );

    assert!(
        out.contains("attributes: JsValue"),
        "map must enter through JsValue:\n{out}"
    );
    assert!(
        out.contains("serde_wasm_bindgen::from_value(attributes.clone())"),
        "the lifetime map conversion must read the incoming JsValue:\n{out}"
    );
    assert!(
        !out.contains("let attributes: std::collections::HashMap"),
        "a generic container conversion must not shadow the incoming JsValue:\n{out}"
    );
    let normalized = out.split_whitespace().collect::<Vec<_>>().join(" ");
    assert!(
        normalized.contains("parent_tag_converted, is_inline)"),
        "WASM keeps required parameters required even when they follow an optional one:\n{out}"
    );
    assert!(
        !out.contains("is_inline.expect"),
        "a required bool is not an Option and cannot be unwrapped:\n{out}"
    );
}

#[test]
fn lifetime_static_method_preserves_borrowed_map_newtype_binding() {
    let typ = TypeDef {
        name: "NodeContext".to_string(),
        rust_path: "sample_fixture::NodeContext".to_string(),
        has_lifetime_params: true,
        ..Default::default()
    };
    let mut attributes = param(
        "attributes",
        TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::String)),
    );
    attributes.is_ref = true;
    attributes.newtype_wrapper = Some(crate::core::ir::NewtypeWrapper::encode_explicit(&[
        crate::core::ir::NewtypeWrapperMetadata::transparent_string(
            "sample_fixture::AttributeValue",
            "from",
            "into_inner",
            vec![crate::core::ir::NewtypeContainer::MapValue],
        ),
    ]));
    let method = MethodDef {
        name: "with_attributes".to_string(),
        is_static: true,
        params: vec![attributes],
        return_type: TypeRef::Named("NodeContext".to_string()),
        ..Default::default()
    };

    let out = gen_method(
        &method,
        &mapper(),
        "NodeContext",
        "sample_fixture",
        &AHashSet::default(),
        "Wasm",
        &typ,
        &AHashSet::default(),
        &ahash::AHashMap::default(),
        &[],
    );

    assert!(
        out.contains(
            "let attributes: std::collections::HashMap<String, String> = serde_wasm_bindgen::from_value(attributes)"
        ),
        "a wrapped map must still deserialize before rebuilding its values:\n{out}"
    );
    assert!(
        out.contains("let attributes_newtype ="),
        "a borrowed wrapper requires a stable local for the core reference:\n{out}"
    );
    assert!(
        out.contains("sample_fixture::NodeContext::with_attributes(&attributes_newtype)"),
        "the core call must borrow the rebuilt wrapper local:\n{out}"
    );
    assert!(
        !out.contains("attributes_converted"),
        "the lifetime map conversion is superseded by explicit newtype reconstruction:\n{out}"
    );
}

/// Same defect as `functions::tests::sync_opaque_handle_param_is_taken_by_reference`, but for the
/// method-parameter path: wasm-bindgen's glue for a by-value exported struct calls
/// `arg.__destroy_into_raw()`, nulling the JS object's `__wbg_ptr`, so a handle passed by value is
/// dead after one call. Method params were built without consulting `opaque_types` at all, so
/// every opaque-handle method param leaked into the signature by value. ~keep
#[test]
fn sync_method_opaque_handle_param_is_taken_by_reference() {
    let typ = TypeDef {
        name: "Session".to_string(),
        rust_path: "sample_fixture::Session".to_string(),
        ..Default::default()
    };
    let method = MethodDef {
        name: "attach".to_string(),
        is_static: true,
        params: vec![param("engine", TypeRef::Named("CrawlEngineHandle".to_string()))],
        return_type: TypeRef::Unit,
        ..Default::default()
    };
    let opaque: AHashSet<String> = ["CrawlEngineHandle".to_string()].into_iter().collect();

    let out = gen_method(
        &method,
        &mapper(),
        "Session",
        "sample_fixture",
        &opaque,
        "Wasm",
        &typ,
        &AHashSet::default(),
        &ahash::AHashMap::default(),
        &[],
    );

    assert!(
        out.contains("engine: &WasmCrawlEngineHandle"),
        "opaque handle method param must be by reference so repeated calls do not hit a null pointer:\n{out}"
    );
    assert!(
        !out.contains("engine: WasmCrawlEngineHandle"),
        "by-value opaque handle method param leaks into the signature:\n{out}"
    );
}

/// Same contract for the async named-param reshaping path: the fall-through `_` arm handled every
/// param that was not a non-opaque `Named` type, including opaque handles, but built the type the
/// same unreferenced way as the base list. Requires a sibling non-opaque `Named` param to make
/// `has_named_params` true and route through the reshaping branch at all. ~keep
#[test]
fn async_method_opaque_handle_param_is_taken_by_reference() {
    let typ = TypeDef {
        name: "Session".to_string(),
        rust_path: "sample_fixture::Session".to_string(),
        ..Default::default()
    };
    let method = MethodDef {
        name: "run".to_string(),
        is_async: true,
        receiver: Some(ReceiverKind::Ref),
        params: vec![
            param("options", TypeRef::Named("RunOptions".to_string())),
            param("engine", TypeRef::Named("CrawlEngineHandle".to_string())),
        ],
        return_type: TypeRef::Unit,
        error_type: Some("CrawlError".to_string()),
        ..Default::default()
    };
    let opaque: AHashSet<String> = ["CrawlEngineHandle".to_string()].into_iter().collect();

    let out = gen_method(
        &method,
        &mapper(),
        "Session",
        "sample_fixture",
        &opaque,
        "Wasm",
        &typ,
        &AHashSet::default(),
        &ahash::AHashMap::default(),
        &[],
    );

    assert!(
        out.contains("engine: &WasmCrawlEngineHandle"),
        "opaque handle param must be by reference in the async named-reshape fall-through arm:\n{out}"
    );
    assert!(
        !out.contains("engine: WasmCrawlEngineHandle"),
        "by-value opaque handle param leaks into the async signature:\n{out}"
    );
}

#[test]
fn nonopaque_static_async_fallible_method_has_no_self_and_awaits_core_call() {
    let method = MethodDef {
        name: "create_async".to_string(),
        is_static: true,
        is_async: true,
        error_type: Some("Error".to_string()),
        return_type: TypeRef::String,
        ..Default::default()
    };
    let typ = TypeDef {
        name: "Factory".to_string(),
        rust_path: "sample_fixture::nested::Factory".to_string(),
        methods: vec![method.clone()],
        ..Default::default()
    };

    let out = gen_method(
        &method,
        &mapper(),
        "Factory",
        "sample_fixture",
        &AHashSet::new(),
        "Wasm",
        &typ,
        &AHashSet::new(),
        &ahash::AHashMap::new(),
        &[],
    );

    assert!(out.contains("pub async fn create_async()"), "{out}");
    assert!(
        out.contains("sample_fixture::nested::Factory::create_async().await"),
        "{out}"
    );
    assert!(
        !out.contains("self.clone()"),
        "static async dispatch must not use self: {out}"
    );
}