alef 0.110.2

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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
use crate::backends::swift::naming::swift_rust_shim_ident as swift_ident;
use crate::codegen::type_mapper::TypeMapper;
use crate::core::config::{AdapterConfig, AdapterPattern, ResolvedCrateConfig};
use crate::core::ir::{ApiSurface, FunctionDef, MethodDef, TypeRef};
use heck::ToLowerCamelCase;

use super::streaming::render_streaming_chunk_decode;

pub(super) fn emit_doc_comment(doc: &str, indent: &str, out: &mut String) {
    if doc.is_empty() {
        return;
    }
    out.push_str(&crate::backends::swift::template_env::render(
        "doc_comment.jinja",
        crate::alef_context! {
            indent => indent,
            lines => doc.lines().collect::<Vec<_>>(),
        },
    ));
}

pub(super) fn first_param_is(func_def: &FunctionDef, ty: &TypeRef) -> bool {
    func_def.params.first().map(|p| &p.ty == ty).unwrap_or(false)
}

pub(super) fn emit_convenience_wrappers(
    api: &ApiSurface,
    exclude_types: &std::collections::HashSet<String>,
    out: &mut String,
) {
    let all_names: std::collections::HashSet<&str> = api.functions.iter().map(|f| f.name.as_str()).collect();

    let bytes_candidates: Vec<&FunctionDef> = api
        .functions
        .iter()
        .filter(|f| {
            first_param_is(f, &TypeRef::Bytes)
                && !f.is_async
                && !super::overloads::convenience_name_shadows_bridge(f)
                && !super::forwarders::function_references_excluded_type(f, exclude_types)
        })
        .collect();

    let path_candidates: Vec<&FunctionDef> = api
        .functions
        .iter()
        .filter(|f| {
            first_param_is(f, &TypeRef::Path)
                && !f.is_async
                && !super::overloads::convenience_name_shadows_bridge(f)
                && !super::forwarders::function_references_excluded_type(f, exclude_types)
        })
        .collect();

    if bytes_candidates.is_empty() && path_candidates.is_empty() {
        return;
    }

    out.push_str("// MARK: - Convenience Wrapper Functions\n");
    out.push_str("// These wrappers bridge String / [UInt8] inputs to RustBridge's\n");
    out.push_str("// RustVec<UInt8> requirement. The config parameter must be a fully\n");
    out.push_str("// constructed opaque type (built via the generated initializer);\n");
    out.push_str("// JSON-config decoding is not available because swift-bridge opaque\n");
    out.push_str("// proxy classes are not Codable Swift structs.\n\n");

    if !bytes_candidates.is_empty() {
        out.push_str("/// Converts a Swift `[UInt8]` array to a `RustVec<UInt8>` by pushing each byte.\n");
        out.push_str("/// swift-bridge's `RustVec<T>` runtime only exposes `init()` and `push(value:)`;\n");
        out.push_str("/// no array-initializer shorthand exists.\n");
        out.push_str("private func makeByteVec(_ bytes: [UInt8]) -> RustVec<UInt8> {\n");
        out.push_str("    let vec = RustVec<UInt8>()\n");
        out.push_str("    for b in bytes { vec.push(value: b) }\n");
        out.push_str("    return vec\n");
        out.push_str("}\n\n");
    }

    for func in &bytes_candidates {
        super::overloads::emit_bytes_overloads(func, &all_names, out);
    }

    for func in &path_candidates {
        super::overloads::emit_path_overload(func, &all_names, out);
    }

    let _ = api;
}

/// - Constructor bridge fn: `create_<snake_type_name>` → camelCase `create<PascalTypeName>`
/// - Method bridge fn: `<snake_type_name>_<method_name>` → camelCase `<camelTypeName><PascalMethod>`
pub(super) fn emit_client_class(
    type_name: &str,
    methods: &[MethodDef],
    mapper: &impl TypeMapper,
    config: &ResolvedCrateConfig,
    first_class_types: &std::collections::HashSet<String>,
    out: &mut String,
) {
    use heck::ToSnakeCase;

    let snake_name = type_name.to_snake_case();
    let constructor_fn = swift_ident(&format!("create_{snake_name}").to_lower_camel_case());

    let mut methods_body = String::new();
    for method in methods {
        if method.sanitized {
            continue;
        }
        let method_snake = method.name.to_snake_case();
        let method_camel = swift_ident(&method_snake.to_lower_camel_case());
        let bridge_fn_snake = format!("{snake_name}_{method_snake}");
        let bridge_fn_camel = swift_ident(&bridge_fn_snake.to_lower_camel_case());

        let params: Vec<String> = method
            .params
            .iter()
            .map(|p| {
                let swift_name = swift_ident(&p.name.to_lower_camel_case());
                let ty_str = if p.optional {
                    format!("{}?", mapper.map_type(&p.ty))
                } else {
                    mapper.map_type(&p.ty)
                };
                format!("_ {swift_name}: {ty_str}")
            })
            .collect();
        let params_str = params.join(", ");

        let has_dto_param = method
            .params
            .iter()
            .any(|p| matches!(&p.ty, TypeRef::Named(n) if first_class_types.contains(n)));
        let args: Vec<String> = method
            .params
            .iter()
            .map(|p| {
                let swift_name = swift_ident(&p.name.to_lower_camel_case());
                match &p.ty {
                    TypeRef::Named(n) if first_class_types.contains(n) => {
                        if p.optional {
                            format!("try {swift_name}?.intoRust()")
                        } else {
                            format!("try {swift_name}.intoRust()")
                        }
                    }
                    _ => swift_name,
                }
            })
            .collect();
        let args_str = if args.is_empty() {
            String::new()
        } else {
            format!(", {}", args.join(", "))
        };

        let return_ty = mapper.map_type(&method.return_type);
        let needs_return_init = matches!(&method.return_type, TypeRef::Named(n) if first_class_types.contains(n));
        // An async bridge function is always `async throws`: the Rust shim is forced fallible so a
        // spawned task's `JoinError` surfaces as an error instead of leaving the continuation
        // unresumed. ~keep
        let needs_throws = method.error_type.is_some() || has_dto_param || needs_return_init || method.is_async;
        let throws_clause = if needs_throws { " throws" } else { "" };
        let async_clause = if method.is_async { " async" } else { "" };
        let return_clause = if matches!(method.return_type, TypeRef::Unit) {
            String::new()
        } else {
            format!(" -> {return_ty}")
        };

        emit_doc_comment(&method.doc, "    ", &mut methods_body);
        let mut method_body = String::new();
        if matches!(method.return_type, TypeRef::Unit) {
            method_body.push_str(&crate::backends::swift::template_env::render(
                "swift_client_method_unit_body.swift.jinja",
                crate::alef_context! {
                    throws_kw => if needs_throws { "try " } else { "" },
                    await_kw => if method.is_async { "await " } else { "" },
                    bridge_function => &bridge_fn_camel,
                    args => &args_str,
                },
            ));
        } else {
            let await_kw = if method.is_async { "await " } else { "" };
            let try_kw = if needs_throws { "try " } else { "" };
            let bytes_suffix = if matches!(method.return_type, TypeRef::Bytes) {
                ".map { Data($0.map { $0 }) }"
            } else {
                ""
            };
            if bytes_suffix.is_empty() {
                if needs_return_init {
                    method_body.push_str(&crate::backends::swift::template_env::render(
                        "swift_client_method_dto_return_body.swift.jinja",
                        crate::alef_context! {
                            return_type => &return_ty,
                            try_kw => try_kw,
                            await_kw => await_kw,
                            bridge_function => &bridge_fn_camel,
                            args => &args_str,
                        },
                    ));
                } else {
                    method_body.push_str(&crate::backends::swift::template_env::render(
                        "swift_client_method_return_body.swift.jinja",
                        crate::alef_context! {
                            try_kw => try_kw,
                            await_kw => await_kw,
                            bridge_function => &bridge_fn_camel,
                            args => &args_str,
                        },
                    ));
                }
            } else {
                method_body.push_str(&crate::backends::swift::template_env::render(
                    "swift_client_method_bytes_body.swift.jinja",
                    crate::alef_context! {
                        try_kw => try_kw,
                        await_kw => await_kw,
                        bridge_function => &bridge_fn_camel,
                        args => &args_str,
                    },
                ));
            }
        }
        methods_body.push_str(&crate::backends::swift::template_env::render(
            "swift_client_method.swift.jinja",
            crate::alef_context! {
                method_name => &method_camel,
                params => &params_str,
                async_clause => async_clause,
                throws_clause => throws_clause,
                return_clause => return_clause,
                body => method_body,
            },
        ));
    }

    let mut streaming_methods = String::new();
    for adapter in config
        .adapters
        .iter()
        .filter(|a| matches!(a.pattern, AdapterPattern::Streaming))
        .filter(|a| a.owner_type.as_deref() == Some(type_name))
    {
        emit_streaming_client_method(adapter, &snake_name, first_class_types, &mut streaming_methods);
    }

    out.push_str(&crate::backends::swift::template_env::render(
        "swift_client_class.swift.jinja",
        crate::alef_context! {
            type_name => type_name,
            constructor_fn => constructor_fn,
            methods => methods_body,
            streaming_methods => streaming_methods,
        },
    ));
}

/// Emit an `AsyncThrowingStream<Item, Error>` wrapper for a streaming adapter
/// method on a Swift client class.
pub(super) fn emit_streaming_client_method(
    adapter: &AdapterConfig,
    owner_snake: &str,
    first_class_types: &std::collections::HashSet<String>,
    out: &mut String,
) {
    use heck::{AsSnakeCase, ToLowerCamelCase};
    let method_camel = swift_ident(&adapter.name.to_lower_camel_case());
    let start_fn_snake = format!("{owner_snake}_{}_start", adapter.name);
    let start_fn_camel = swift_ident(&start_fn_snake.to_lower_camel_case());

    let item_type = adapter.item_type.as_deref().unwrap_or("String");
    let item_type_from_json = swift_ident(&format!("{}_from_json", AsSnakeCase(item_type)).to_lower_camel_case());

    let params: Vec<String> = adapter
        .params
        .iter()
        .map(|p| {
            let swift_name = swift_ident(&p.name.to_lower_camel_case());
            let simple_ty = p.ty.rsplit("::").next().unwrap_or(&p.ty);
            format!("_ {swift_name}: {simple_ty}")
        })
        .collect();
    let params_str = params.join(", ");

    let call_args: Vec<String> = adapter
        .params
        .iter()
        .map(|p| {
            let swift_name = swift_ident(&p.name.to_lower_camel_case());
            let simple_ty = p.ty.rsplit("::").next().unwrap_or(&p.ty);
            if first_class_types.contains(simple_ty) {
                format!("(try {swift_name}.intoRust())")
            } else {
                swift_name
            }
        })
        .collect();
    let call_args_str = if call_args.is_empty() {
        String::new()
    } else {
        format!(", {}", call_args.join(", "))
    };

    let chunk_decode = render_streaming_chunk_decode(
        item_type,
        &item_type_from_json,
        first_class_types.contains(item_type),
        "                        ",
    );
    out.push_str(&crate::backends::swift::template_env::render(
        "swift_streaming_client_method.swift.jinja",
        crate::alef_context! {
            method_name => &method_camel,
            params => &params_str,
            item_type => item_type,
            start_fn => &start_fn_camel,
            call_args => call_args_str,
            chunk_decode => chunk_decode,
        },
    ));
}

/// Emit an `extension RustBridge.{Owner}{Adapter}StreamHandle: @unchecked Sendable {}`
/// declaration for the given streaming adapter.
pub(super) fn emit_stream_handle_sendable(adapter: &AdapterConfig, owner_type: &str, out: &mut String) {
    use heck::ToPascalCase;
    let owner_pascal = owner_type.to_pascal_case();
    let adapter_pascal = adapter.name.to_pascal_case();
    let handle_name = format!("{owner_pascal}{adapter_pascal}StreamHandle");
    super::emit_sendable_conformance(
        out,
        &handle_name,
        None,
        &[
            "swift-bridge opaque types are not automatically Sendable.  The Rust",
            "side uses Mutex<stream> + tokio Runtime — both Send + Sync — so",
            "@unchecked is correct: thread-safety is enforced by Rust.",
        ],
    );
}

/// Emit top-level `public func` streaming wrappers for adapters whose owner type
/// is **not** wrapped in a Swift client class (i.e. no `client_constructor_body` in
/// alef.toml).
pub(super) fn emit_streaming_free_functions(
    config: &ResolvedCrateConfig,
    first_class_types: &std::collections::HashSet<String>,
    sendable_emitted: &mut std::collections::HashSet<String>,
    out: &mut String,
) {
    use heck::{AsSnakeCase, ToLowerCamelCase, ToSnakeCase};

    let client_constructor_types: std::collections::HashSet<&str> = config
        .swift
        .as_ref()
        .map(|c| c.client_constructor_body.keys().map(String::as_str).collect())
        .unwrap_or_default();

    let orphan_adapters: Vec<&AdapterConfig> = config
        .adapters
        .iter()
        .filter(|a| matches!(a.pattern, AdapterPattern::Streaming))
        .filter(|a| !a.skip_languages.iter().any(|l| l == "swift"))
        .filter(|a| {
            a.owner_type
                .as_deref()
                .map(|t| !client_constructor_types.contains(t))
                .unwrap_or(false)
        })
        .collect();

    if orphan_adapters.is_empty() {
        return;
    }

    out.push_str("// MARK: - Streaming free functions\n");
    out.push_str(
        "// These adapters are owned by opaque handle types that do not have a\n\
         // Swift class wrapper (no client_constructor_body in alef.toml).  The\n\
         // streaming methods are therefore exposed as module-level free functions\n\
         // that accept the owner handle as their first parameter.\n\n",
    );
    for adapter in &orphan_adapters {
        let owner_type = adapter.owner_type.as_deref().unwrap_or("");
        if sendable_emitted.insert(owner_type.to_string()) {
            super::emit_sendable_conformance(
                out,
                owner_type,
                Some("streaming owner"),
                &[
                    "swift-bridge opaque types are not automatically Sendable.",
                    "Captured by Task.detached in streaming free functions — Rust type is Send + Sync.",
                ],
            );
            out.push('\n');
        }
        emit_stream_handle_sendable(adapter, owner_type, out);
        out.push('\n');
        for param in &adapter.params {
            let simple_ty = param.ty.rsplit("::").next().unwrap_or(&param.ty);
            if !first_class_types.contains(simple_ty) {
                let key = format!("param:{simple_ty}");
                if sendable_emitted.insert(key) {
                    super::emit_sendable_conformance(
                        out,
                        simple_ty,
                        Some("streaming request param"),
                        &[
                            "swift-bridge opaque types are not automatically Sendable.",
                            "Passed into Task.detached for streaming — Rust type is Send + Sync.",
                        ],
                    );
                    out.push('\n');
                }
            }
        }
    }

    for adapter in &orphan_adapters {
        let owner_type = adapter.owner_type.as_deref().unwrap_or("");
        let owner_snake = owner_type.to_snake_case();
        let method_camel = swift_ident(&adapter.name.to_lower_camel_case());
        let start_fn_snake = format!("{owner_snake}_{}_start", adapter.name);
        let start_fn_camel = swift_ident(&start_fn_snake.to_lower_camel_case());

        let item_type = adapter.item_type.as_deref().unwrap_or("String");
        let item_type_from_json = swift_ident(&format!("{}_from_json", AsSnakeCase(item_type)).to_lower_camel_case());

        let owner_camel = swift_ident(&owner_type.to_lower_camel_case());
        let mut sig_params: Vec<String> = vec![format!("_ {owner_camel}: {owner_type}")];
        let mut call_args: Vec<String> = vec![];

        for param in &adapter.params {
            let swift_name = swift_ident(&param.name.to_lower_camel_case());
            let simple_ty = param.ty.rsplit("::").next().unwrap_or(&param.ty);
            sig_params.push(format!("_ {swift_name}: {simple_ty}"));
            if first_class_types.contains(simple_ty) {
                call_args.push(format!("(try {swift_name}.intoRust())"));
            } else {
                call_args.push(swift_name);
            }
        }

        let params_str = sig_params.join(", ");
        let call_args_str = if call_args.is_empty() {
            String::new()
        } else {
            format!(", {}", call_args.join(", "))
        };

        let chunk_decode = render_streaming_chunk_decode(
            item_type,
            &item_type_from_json,
            first_class_types.contains(item_type),
            "                    ",
        );
        out.push_str(&crate::backends::swift::template_env::render(
            "swift_streaming_free_function.swift.jinja",
            crate::alef_context! {
                function_name => &method_camel,
                params => &params_str,
                item_type => item_type,
                start_fn => &start_fn_camel,
                owner_arg => &owner_camel,
                call_args => call_args_str,
                chunk_decode => chunk_decode,
            },
        ));
        out.push('\n');
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backends::swift::type_map::SwiftMapper;
    use crate::core::config::{AdapterConfig, AdapterPattern};
    use crate::core::ir::ParamDef;
    use std::collections::HashSet;

    fn client_method(name: &str, is_async: bool, error_type: Option<&str>, return_type: TypeRef) -> MethodDef {
        MethodDef {
            name: name.to_string(),
            params: vec![ParamDef {
                name: "id".to_string(),
                ty: TypeRef::String,
                ..Default::default()
            }],
            return_type,
            error_type: error_type.map(str::to_string),
            is_async,
            receiver: Some(crate::core::ir::ReceiverKind::Ref),
            ..Default::default()
        }
    }

    fn render(methods: &[MethodDef]) -> String {
        let mut out = String::new();
        emit_client_class(
            "Client",
            methods,
            &SwiftMapper,
            &ResolvedCrateConfig::default(),
            &HashSet::new(),
            &mut out,
        );
        out
    }

    /// The bridge function behind an async method is a swift-bridge `async fn`, so the facade must
    /// await it directly; wrapping the call in a detached task would park a pool thread again.
    #[test]
    fn async_methods_await_the_bridge_and_always_throw() {
        let out = render(&[
            client_method("fetch", true, Some("ClientError"), TypeRef::String),
            client_method("infallible", true, None, TypeRef::String),
            client_method("remove", true, Some("ClientError"), TypeRef::Unit),
        ]);

        assert!(
            out.contains("public func fetch(_ id: String) async throws -> String {"),
            "got:\n{out}"
        );
        assert!(
            out.contains("return try await RustBridge.clientFetch(self.inner, id)"),
            "got:\n{out}"
        );
        assert!(
            out.contains("public func infallible(_ id: String) async throws -> String {"),
            "an infallible async bridge function is forced fallible, so its facade must throw; got:\n{out}"
        );
        assert!(
            out.contains("        try await RustBridge.clientRemove(self.inner, id)"),
            "a unit-returning async method must await the bridge call too; got:\n{out}"
        );
        assert!(!out.contains("Task.detached"), "got:\n{out}");
    }

    #[test]
    fn sync_methods_are_not_awaited() {
        let out = render(&[client_method("fetch", false, Some("ClientError"), TypeRef::String)]);

        assert!(
            out.contains("public func fetch(_ id: String) throws -> String {"),
            "got:\n{out}"
        );
        assert!(
            out.contains("return try RustBridge.clientFetch(self.inner, id)"),
            "got:\n{out}"
        );
        assert!(!out.contains("await"), "got:\n{out}");
    }

    fn streaming_adapter() -> AdapterConfig {
        AdapterConfig {
            name: "chat_stream".to_string(),
            pattern: AdapterPattern::Streaming,
            core_path: "chat_stream".to_string(),
            params: vec![crate::core::config::AdapterParam {
                name: "req".to_string(),
                ty: "ChatRequest".to_string(),
                optional: false,
            }],
            returns: None,
            error_type: Some("String".to_string()),
            owner_type: Some("Client".to_string()),
            item_type: Some("Chunk".to_string()),
            gil_release: false,
            trait_name: None,
            trait_method: None,
            detect_async: false,
            request_type: Some("ChatRequest".to_string()),
            skip_languages: vec![],
        }
    }

    /// Opening the stream and pulling each chunk are `async fn` bridge calls, so the facade awaits
    /// them directly. A detached task around a synchronous call would pin a pool thread for the
    /// whole life of every open stream.
    #[test]
    fn streaming_method_awaits_the_async_start_and_next_bridge_calls() {
        let mut out = String::new();
        emit_streaming_client_method(&streaming_adapter(), "client", &HashSet::new(), &mut out);

        assert!(
            out.contains("let handle = try await RustBridge.clientChatStreamStart(self.inner, req)"),
            "got:\n{out}"
        );
        assert!(
            out.contains("let json = try await handle.next().toString()"),
            "got:\n{out}"
        );
        assert!(
            !out.contains("try RustBridge.clientChatStreamStart"),
            "the start call must not be a blocking synchronous call, got:\n{out}"
        );
    }

    #[test]
    fn streaming_free_function_awaits_the_async_start_and_next_bridge_calls() {
        let config = ResolvedCrateConfig {
            adapters: vec![streaming_adapter()],
            ..ResolvedCrateConfig::default()
        };
        let mut out = String::new();
        emit_streaming_free_functions(&config, &HashSet::new(), &mut HashSet::new(), &mut out);

        assert!(
            out.contains("let handle = try await RustBridge.clientChatStreamStart(client, req)"),
            "got:\n{out}"
        );
        assert!(
            out.contains("let json = try await handle.next().toString()"),
            "got:\n{out}"
        );
    }
}