alef 0.61.1

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
use super::*;
use crate::core::ir::TypeRef;

#[test]
fn test_swift_type_name_bool_returns_bool() {
    assert_eq!(swift_type_name(&TypeRef::Primitive(PrimitiveType::Bool)), "Bool");
}

#[test]
fn test_swift_type_name_usize_returns_uint() {
    assert_eq!(swift_type_name(&TypeRef::Primitive(PrimitiveType::Usize)), "UInt");
}

#[test]
fn test_swift_type_name_u8_returns_uint8() {
    assert_eq!(swift_type_name(&TypeRef::Primitive(PrimitiveType::U8)), "UInt8");
}

#[test]
fn test_swift_type_name_u32_returns_uint32() {
    assert_eq!(swift_type_name(&TypeRef::Primitive(PrimitiveType::U32)), "UInt32");
}

#[test]
fn test_swift_type_name_u64_returns_uint64() {
    assert_eq!(swift_type_name(&TypeRef::Primitive(PrimitiveType::U64)), "UInt64");
}

#[test]
fn test_swift_type_name_i32_returns_int32() {
    assert_eq!(swift_type_name(&TypeRef::Primitive(PrimitiveType::I32)), "Int32");
}

#[test]
fn test_swift_type_name_f32_returns_float() {
    assert_eq!(swift_type_name(&TypeRef::Primitive(PrimitiveType::F32)), "Float");
}

fn make_function(name: &str, params: Vec<(&str, TypeRef)>, return_type: TypeRef) -> FunctionDef {
    FunctionDef {
        name: name.to_string(),
        rust_path: format!("sample::{name}"),
        params: params
            .into_iter()
            .map(|(pname, ty)| crate::core::ir::ParamDef {
                name: pname.to_string(),
                ty,
                ..crate::core::ir::ParamDef::default()
            })
            .collect(),
        return_type,
        ..FunctionDef::default()
    }
}

#[test]
fn skips_forwarder_when_param_type_is_excluded() {
    let func = make_function(
        "extract_keywords",
        vec![("config", TypeRef::Named("KeywordConfig".to_string()))],
        TypeRef::Unit,
    );
    let mut exclude: HashSet<String> = HashSet::new();
    exclude.insert("KeywordConfig".to_string());
    assert!(function_references_excluded_type(&func, &exclude));
}

#[test]
fn skips_forwarder_when_return_type_is_excluded() {
    let func = make_function(
        "build_keyword",
        vec![("text", TypeRef::String)],
        TypeRef::Named("Keyword".to_string()),
    );
    let mut exclude: HashSet<String> = HashSet::new();
    exclude.insert("Keyword".to_string());
    assert!(function_references_excluded_type(&func, &exclude));
}

#[test]
fn keeps_forwarder_when_only_primitives_are_used() {
    let func = make_function(
        "echo_count",
        vec![("count", TypeRef::Primitive(PrimitiveType::U32))],
        TypeRef::Primitive(PrimitiveType::U32),
    );
    let mut exclude: HashSet<String> = HashSet::new();
    exclude.insert("KeywordConfig".to_string());
    exclude.insert("Keyword".to_string());
    assert!(!function_references_excluded_type(&func, &exclude));
}

#[test]
fn skips_forwarder_when_vec_named_param_is_excluded() {
    let func = make_function(
        "score_keywords",
        vec![(
            "keywords",
            TypeRef::Vec(Box::new(TypeRef::Named("Keyword".to_string()))),
        )],
        TypeRef::Unit,
    );
    let mut exclude: HashSet<String> = HashSet::new();
    exclude.insert("Keyword".to_string());
    assert!(function_references_excluded_type(&func, &exclude));
}

#[test]
fn skips_forwarder_when_optional_named_return_is_excluded() {
    let func = make_function(
        "maybe_yake",
        vec![],
        TypeRef::Optional(Box::new(TypeRef::Named("YakeParams".to_string()))),
    );
    let mut exclude: HashSet<String> = HashSet::new();
    exclude.insert("YakeParams".to_string());
    assert!(function_references_excluded_type(&func, &exclude));
}

#[test]
fn empty_exclude_set_keeps_every_function() {
    let func = make_function(
        "extract_keywords",
        vec![("config", TypeRef::Named("KeywordConfig".to_string()))],
        TypeRef::Named("Keyword".to_string()),
    );
    let exclude: HashSet<String> = HashSet::new();
    assert!(!function_references_excluded_type(&func, &exclude));
}

#[test]
fn skips_forwarder_when_map_value_is_excluded_type() {
    let func = make_function(
        "score_map",
        vec![(
            "table",
            TypeRef::Map(
                Box::new(TypeRef::String),
                Box::new(TypeRef::Named("Keyword".to_string())),
            ),
        )],
        TypeRef::Unit,
    );
    let mut exclude: HashSet<String> = HashSet::new();
    exclude.insert("Keyword".to_string());
    assert!(function_references_excluded_type(&func, &exclude));
}

fn make_capsule_fn() -> FunctionDef {
    make_function(
        "get_language",
        vec![("name", TypeRef::String)],
        TypeRef::Named("Language".to_string()),
    )
}

#[test]
fn capsule_forwarder_emits_opaque_pointer_reconstruction() {
    let func = make_capsule_fn();
    let cfg = crate::core::config::HostCapsuleTypeConfig {
        host_type: "MyLib.Language".to_string(),
        package: String::new(),
        package_version: String::new(),
        construct_expr: "MyLib.Language({ptr})".to_string(),
        ..Default::default()
    };
    let mut out = String::new();
    emit_capsule_free_function_forwarder(&func, "GetLanguage", &cfg, &mut out);
    assert!(
        out.contains("OpaquePointer(bitPattern:"),
        "capsule forwarder must reconstruct OpaquePointer via bitPattern. Got:\n{out}"
    );
    assert!(
        out.contains("addr != 0"),
        "capsule forwarder must check for 0 sentinel. Got:\n{out}"
    );
}

#[test]
fn capsule_forwarder_errors_when_construct_expr_empty() {
    let func = make_capsule_fn();
    let cfg = crate::core::config::HostCapsuleTypeConfig {
        host_type: "MyLib.Language".to_string(),
        package: String::new(),
        package_version: String::new(),
        construct_expr: String::new(),
        ..Default::default()
    };
    let mut out = String::new();
    emit_capsule_free_function_forwarder(&func, "GetLanguage", &cfg, &mut out);
    assert!(
        out.contains("ALEF ERROR"),
        "empty construct_expr must produce ALEF ERROR. Got:\n{out}"
    );
    assert!(
        out.contains("construct_expr"),
        "error must name the missing field. Got:\n{out}"
    );
}

fn make_async_enum_return_fn() -> FunctionDef {
    let mut func = make_function(
        "refresh_catalog",
        vec![("config", TypeRef::Named("CatalogRefreshConfig".to_string()))],
        TypeRef::Named("RefreshOutcome".to_string()),
    );
    func.is_async = true;
    func.error_type = Some("String".to_string());
    func
}

/// Regression test: a service function returning a `String`-backed enum (e.g. serde
/// `RefreshOutcome`) must not be constructed via the struct positional-init pattern
/// `EnumName(_rb_obj)` — enums only synthesize `init(from: Decoder)`, so that call fails
/// to compile. The async forwarder must decode via the enum's `RawValue` initializer
/// instead.
#[test]
fn async_forwarder_decodes_unit_enum_return_via_raw_value_not_positional_init() {
    let func = make_async_enum_return_fn();
    let mut known_dto_names: HashSet<String> = HashSet::new();
    // `known_dto_names` mirrors `compute_first_class_dto_names`, which intentionally
    // includes unit-serde enum names alongside true struct DTOs. ~keep
    known_dto_names.insert("RefreshOutcome".to_string());
    let enum_names: HashSet<String> = known_dto_names.clone();
    let unit_enum_names: HashSet<String> = known_dto_names.clone();

    let mut out = String::new();
    emit_async_free_function_forwarder(
        &func,
        "refreshCatalog",
        &known_dto_names,
        &enum_names,
        &unit_enum_names,
        "MyLibError",
        &mut out,
    );

    assert!(
        !out.contains("RefreshOutcome(_rb_obj)"),
        "must not emit the struct-init pattern for an enum return. Got:\n{out}"
    );
    assert!(
        out.contains("RefreshOutcome(rawValue:"),
        "must decode the enum via its RawValue initializer. Got:\n{out}"
    );
    assert!(
        out.contains("MyLibError.validation(message: \"Unknown RefreshOutcome variant\""),
        "must throw a validation error naming the enum on an unrecognized raw value. Got:\n{out}"
    );
}

fn make_sync_enum_return_fn() -> FunctionDef {
    let mut func = make_function("current_outcome", vec![], TypeRef::Named("RefreshOutcome".to_string()));
    func.error_type = Some("String".to_string());
    func
}

/// Same regression as the async case, but for the synchronous free-function forwarder
/// path (`emit_single_free_function_forwarder`), which shares the same
/// `known_dto_names`-conflates-structs-and-enums root cause.
#[test]
fn sync_forwarder_decodes_unit_enum_return_via_raw_value_not_positional_init() {
    let func = make_sync_enum_return_fn();
    let mut known_dto_names: HashSet<String> = HashSet::new();
    known_dto_names.insert("RefreshOutcome".to_string());
    let unit_enum_names: HashSet<String> = known_dto_names.clone();
    let client_class_names: HashSet<String> = HashSet::new();

    let mut out = String::new();
    emit_single_free_function_forwarder(
        &func,
        "currentOutcome",
        &known_dto_names,
        &unit_enum_names,
        "MyLibError",
        &client_class_names,
        &mut out,
    );

    assert!(
        !out.contains("RefreshOutcome(_rb)"),
        "must not emit the struct-init pattern for an enum return. Got:\n{out}"
    );
    assert!(
        out.contains("RefreshOutcome(rawValue:"),
        "must decode the enum via its RawValue initializer. Got:\n{out}"
    );
    assert!(
        out.contains("MyLibError.validation(message: \"Unknown RefreshOutcome variant\""),
        "must throw a validation error naming the enum on an unrecognized raw value. Got:\n{out}"
    );
}

/// Regression test: `TypeRef::Path` used to fall through to the default match arm in
/// `forwarder_param_signature`, which returns `setup_line: None`, so a `Path` param was
/// passed unwrapped as a Swift `String` while a sibling `String` param was wrapped into
/// `RustString` -- producing "conflicting arguments to generic parameter
/// 'GenericIntoRustString' ('RustString' vs. 'String')". `Path` must take the same wrapping
/// arm as `String`. ~keep
#[test]
fn string_and_path_params_produce_identical_forwarder_arg_shape() {
    let known_dto_names: HashSet<String> = HashSet::new();
    let (string_ty, string_arg) = forwarder_param_signature(&TypeRef::String, "path", false, &known_dto_names);
    let (path_ty, path_arg) = forwarder_param_signature(&TypeRef::Path, "path", false, &known_dto_names);

    assert_eq!(
        string_ty, path_ty,
        "String and Path params must produce the same Swift parameter type"
    );
    assert_eq!(
        path_arg.setup_line, string_arg.setup_line,
        "Path must wrap into RustString exactly like String, not fall through with setup_line: None"
    );
    assert_eq!(path_arg.arg_expr, string_arg.arg_expr);
    assert_eq!(path_ty, "String");
    assert_eq!(path_arg.setup_line, Some("let _rb_path = RustString(path)".to_string()));
    assert_eq!(path_arg.arg_expr, "_rb_path");
}

#[test]
fn optional_path_param_wraps_like_optional_string() {
    let known_dto_names: HashSet<String> = HashSet::new();
    let ty = TypeRef::Optional(Box::new(TypeRef::Path));
    let (swift_ty, arg) = forwarder_param_signature(&ty, "path", true, &known_dto_names);
    assert_eq!(swift_ty, "String?");
    assert_eq!(
        arg.setup_line,
        Some("let _rb_path = path.map { RustString($0) }".to_string())
    );
    assert_eq!(arg.arg_expr, "_rb_path");
}

/// Regression test: `Vec<DTO>` returns must be recognized as throwing conversions so the
/// forwarder wrapper gets a `throws` clause and the return statement gets `try` -- otherwise
/// `try Dto(ref)` sits in a non-throwing context and fails to compile. ~keep
#[test]
fn vec_dto_return_throws_when_element_type_is_known_dto() {
    let mut known_dto_names: HashSet<String> = HashSet::new();
    known_dto_names.insert("PatternMatch".to_string());
    let ty = TypeRef::Vec(Box::new(TypeRef::Named("PatternMatch".to_string())));
    assert!(return_value_conversion_throws(&ty, &known_dto_names));
}

#[test]
fn vec_dto_return_does_not_throw_when_element_type_is_not_a_known_dto() {
    let known_dto_names: HashSet<String> = HashSet::new();
    let ty = TypeRef::Vec(Box::new(TypeRef::Named("PatternMatch".to_string())));
    assert!(!return_value_conversion_throws(&ty, &known_dto_names));
}

#[test]
fn bare_named_dto_return_throws_when_known() {
    let mut known_dto_names: HashSet<String> = HashSet::new();
    known_dto_names.insert("PatternMatch".to_string());
    let ty = TypeRef::Named("PatternMatch".to_string());
    assert!(return_value_conversion_throws(&ty, &known_dto_names));
}

#[test]
fn optional_named_dto_return_throws_when_known() {
    let mut known_dto_names: HashSet<String> = HashSet::new();
    known_dto_names.insert("PatternMatch".to_string());
    let ty = TypeRef::Optional(Box::new(TypeRef::Named("PatternMatch".to_string())));
    assert!(return_value_conversion_throws(&ty, &known_dto_names));
}

#[test]
fn vec_string_return_never_throws() {
    let known_dto_names: HashSet<String> = HashSet::new();
    let ty = TypeRef::Vec(Box::new(TypeRef::String));
    assert!(!return_value_conversion_throws(&ty, &known_dto_names));
}

/// Regression test: the `Vec<DTO>` return-conversion suffix used to embed a leading `try`
/// (`RustBridge.func(...)try .map { ... }`), which is a syntax error -- `try` belongs at
/// the call-site/statement level, not inside the trailing `.map` chain. ~keep
#[test]
fn vec_dto_return_suffix_maps_with_try_and_has_no_leading_try() {
    let mut known_dto_names: HashSet<String> = HashSet::new();
    known_dto_names.insert("PatternMatch".to_string());
    let ty = TypeRef::Vec(Box::new(TypeRef::Named("PatternMatch".to_string())));
    let suffix = forwarder_return_conversion_suffix_with_throws(&ty, &known_dto_names, true);
    assert_eq!(
        suffix, ".map { ref in try PatternMatch(ref) }",
        "Vec<DTO> suffix must map each element with try inside the closure. Got:\n{suffix}"
    );
    assert!(
        suffix.starts_with(".map"),
        "suffix must start with .map. Got:\n{suffix}"
    );
    assert!(
        !suffix.starts_with("try"),
        "suffix must not start with a leading try. Got:\n{suffix}"
    );
}

#[test]
fn vec_opaque_return_suffix_uses_ptr_based_reconstruction_and_has_no_leading_try() {
    let known_dto_names: HashSet<String> = HashSet::new();
    let ty = TypeRef::Vec(Box::new(TypeRef::Named("Thing".to_string())));
    let suffix = forwarder_return_conversion_suffix_with_throws(&ty, &known_dto_names, true);
    assert_eq!(
        suffix, ".map { ref in var item = try RustBridge.Thing(ptr: ref.ptr); item.isOwned = false; return item }",
        "Vec<opaque> suffix must reconstruct via ptr-based init. Got:\n{suffix}"
    );
    assert!(
        !suffix.starts_with("try"),
        "suffix must not start with a leading try. Got:\n{suffix}"
    );
}

#[test]
fn capsule_forwarder_errors_when_host_type_empty() {
    let func = make_capsule_fn();
    let cfg = crate::core::config::HostCapsuleTypeConfig {
        host_type: String::new(),
        package: String::new(),
        package_version: String::new(),
        construct_expr: "MyLib.Language({ptr})".to_string(),
        ..Default::default()
    };
    let mut out = String::new();
    emit_capsule_free_function_forwarder(&func, "GetLanguage", &cfg, &mut out);
    assert!(
        out.contains("ALEF ERROR"),
        "empty host_type must produce ALEF ERROR. Got:\n{out}"
    );
    assert!(
        out.contains("host_type"),
        "error must name the missing field. Got:\n{out}"
    );
}

fn make_async_enum_param_fn() -> FunctionDef {
    let mut func = make_function(
        "set_region",
        vec![("region_kind", TypeRef::Named("RegionKind".to_string()))],
        TypeRef::Unit,
    );
    func.is_async = true;
    func.error_type = Some("String".to_string());
    func
}

/// Regression test: an async fn's enum-typed parameter must be JSON-encoded to a String,
/// then wrapped in `RustString(...)` before being passed to the bridge. The Rust bridge
/// declares the param as `String` (enums cross the FFI boundary pre-converted), so calling
/// `.intoRust()` on the high-level enum type -- which returns an opaque type, not a String --
/// fails to compile. Skipping the `RustString` wrap is also wrong: it collides with sibling
/// `RustString` args ("conflicting arguments to generic parameter 'GenericIntoRustString'"). ~keep
#[test]
fn async_forwarder_json_encodes_enum_param_and_wraps_in_rust_string() {
    let func = make_async_enum_param_fn();
    let mut known_dto_names: HashSet<String> = HashSet::new();
    // Mirrors real generator input: unit-serde enums are also first-class DTOs, so the
    // enum branch must win over the known-DTO `.intoRust()` branch, not just be untested. ~keep
    known_dto_names.insert("RegionKind".to_string());
    let mut enum_names: HashSet<String> = HashSet::new();
    enum_names.insert("RegionKind".to_string());
    let unit_enum_names: HashSet<String> = HashSet::new();

    let mut out = String::new();
    emit_async_free_function_forwarder(
        &func,
        "setRegion",
        &known_dto_names,
        &enum_names,
        &unit_enum_names,
        "MyLibError",
        &mut out,
    );

    assert!(
        out.contains(
            "let _rb_regionKind = RustString(try String(data: JSONEncoder().encode(regionKind), encoding: .utf8) ?? \"null\")"
        ),
        "enum param must be JSON-encoded and the result wrapped in RustString(...). Got:\n{out}"
    );
    assert!(
        !out.contains("regionKind.intoRust()"),
        "enum param must not be passed via .intoRust() -- that returns an opaque type, not a String. Got:\n{out}"
    );
}

fn make_async_unit_return_fn() -> FunctionDef {
    let mut func = make_function("delete_catalog", vec![("catalog_id", TypeRef::String)], TypeRef::Unit);
    func.is_async = true;
    func.error_type = Some("String".to_string());
    func
}

/// Regression test: an async fn with a void (`TypeRef::Unit`) return must not emit a
/// `let result = ...` binding or a `return result`. Before the fix the facade emitted both,
/// so a local `result` of type `()` shadowed a same-named parameter, producing "constant
/// 'result' inferred to have type '()', which may be unexpected". The body must be the bare
/// bridge call with no binding and no return statement. ~keep
#[test]
fn async_forwarder_void_return_emits_no_result_binding_or_return() {
    let func = make_async_unit_return_fn();
    let known_dto_names: HashSet<String> = HashSet::new();
    let enum_names: HashSet<String> = HashSet::new();
    let unit_enum_names: HashSet<String> = HashSet::new();

    let mut out = String::new();
    emit_async_free_function_forwarder(
        &func,
        "deleteCatalog",
        &known_dto_names,
        &enum_names,
        &unit_enum_names,
        "MyLibError",
        &mut out,
    );

    assert!(
        !out.contains("let result ="),
        "void async return must not bind an unused `let result`. Got:\n{out}"
    );
    assert!(
        !out.contains("return result"),
        "void async return must not emit `return result` -- there is nothing to return. Got:\n{out}"
    );
    assert!(
        out.contains("try RustBridge.deleteCatalog(_rb_catalogId)"),
        "void async body must call the bridge directly with no binding. Got:\n{out}"
    );
}

fn make_async_string_return_fn() -> FunctionDef {
    let mut func = make_function("fetch_status", vec![("catalog_id", TypeRef::String)], TypeRef::String);
    func.is_async = true;
    func.error_type = Some("String".to_string());
    func
}

/// Regression test: an async fn returning `String` must convert the bridge's `RustString`
/// result to a native Swift `String` via `.toString()`, not return the opaque bridge type
/// directly. ~keep
#[test]
fn async_forwarder_string_return_converts_via_to_string() {
    let func = make_async_string_return_fn();
    let known_dto_names: HashSet<String> = HashSet::new();
    let enum_names: HashSet<String> = HashSet::new();
    let unit_enum_names: HashSet<String> = HashSet::new();

    let mut out = String::new();
    emit_async_free_function_forwarder(
        &func,
        "fetchStatus",
        &known_dto_names,
        &enum_names,
        &unit_enum_names,
        "MyLibError",
        &mut out,
    );

    assert!(
        out.contains("let result = try RustBridge.fetchStatus(_rb_catalogId)"),
        "String async return must bind the bridge's RustString result. Got:\n{out}"
    );
    assert!(
        out.contains("return result.toString()"),
        "String async return must convert the RustString result to a native Swift String via .toString(). Got:\n{out}"
    );
}