alef 0.84.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
use super::{ValidationCode, ValidationDiagnostic};
use crate::core::config::Language;
use crate::core::ir::{ApiSurface, FunctionDef, HandlerContractDef, MethodDef, ReceiverKind, ServiceDef, TypeRef};
use ahash::AHashSet;

pub(super) fn backend_readiness_diagnostics(
    api: &ApiSurface,
    bridged_trait_names: &AHashSet<&str>,
    resolved_languages: Option<&[Language]>,
) -> Vec<ValidationDiagnostic> {
    let known_names = known_type_names(api);
    let mut trait_known_names = known_names.clone();
    trait_known_names.extend(substitutable_type_names(api));
    let opaque_names = opaque_type_names(api);
    let mut diagnostics = Vec::new();

    for function in &api.functions {
        if function.binding_excluded {
            continue;
        }
        let item_path = format!("function {}", function.name);
        collect_function_diagnostics(api, &known_names, &opaque_names, &item_path, function, &mut diagnostics);
    }

    for typ in &api.types {
        if typ.binding_excluded {
            continue;
        }
        collect_serde_container_conversion_diagnostics(api, typ, resolved_languages, &mut diagnostics);
        let method_known_names = if typ.is_trait && bridged_trait_names.contains(typ.name.as_str()) {
            &trait_known_names
        } else {
            &known_names
        };
        for method in &typ.methods {
            if method.binding_excluded {
                continue;
            }
            let item_path = format!("method {}.{}", typ.name, method.name);
            collect_method_diagnostics(
                api,
                method_known_names,
                &opaque_names,
                &item_path,
                method,
                typ.is_opaque,
                &mut diagnostics,
            );
        }
        for field in &typ.fields {
            if field.binding_excluded {
                continue;
            }
            collect_type_ref_diagnostics(
                api,
                &known_names,
                &format!("field {}.{}", typ.name, field.name),
                &field.ty,
                &mut diagnostics,
            );
        }
    }
    for enum_def in &api.enums {
        if enum_def.binding_excluded {
            continue;
        }
        for variant in &enum_def.variants {
            if variant.binding_excluded {
                continue;
            }
            for field in &variant.fields {
                if field.binding_excluded {
                    continue;
                }
                collect_type_ref_diagnostics(
                    api,
                    &known_names,
                    &format!("enum variant {}.{}", enum_def.name, variant.name),
                    &field.ty,
                    &mut diagnostics,
                );
            }
        }
    }
    for error_def in &api.errors {
        if error_def.binding_excluded {
            continue;
        }
        for method in &error_def.methods {
            if method.binding_excluded {
                continue;
            }
            let item_path = format!("error method {}.{}", error_def.name, method.name);
            collect_method_diagnostics(
                api,
                &known_names,
                &opaque_names,
                &item_path,
                method,
                false,
                &mut diagnostics,
            );
        }
        for variant in &error_def.variants {
            for field in &variant.fields {
                if field.binding_excluded {
                    continue;
                }
                collect_type_ref_diagnostics(
                    api,
                    &known_names,
                    &format!("error variant {}.{}", error_def.name, variant.name),
                    &field.ty,
                    &mut diagnostics,
                );
            }
        }
    }
    for service in &api.services {
        collect_service_diagnostics(api, &known_names, &opaque_names, service, &mut diagnostics);
    }
    for contract in &api.handler_contracts {
        collect_handler_contract_diagnostics(api, &known_names, &opaque_names, contract, &mut diagnostics);
    }

    diagnostics
}

fn known_type_names(api: &ApiSurface) -> AHashSet<&str> {
    api.types
        .iter()
        .map(|typ| typ.name.as_str())
        .chain(api.enums.iter().map(|item| item.name.as_str()))
        .chain(api.errors.iter().map(|item| item.name.as_str()))
        .collect()
}

/// Names of types that backends are expected to substitute at trait-bridge code-emit
/// time. Trait methods are allowed to reference these even though they no longer appear
/// in `api.types`, because the per-backend `trait_bridge.rs` swaps the reference for an
/// opaque JSON carrier (e.g. `json.RawMessage` in Go, `serde_json::Value` in Rust shims).
/// Free functions and fields can't be substituted that way, so they still hit
/// `unknown_named_type`.
fn substitutable_type_names(api: &ApiSurface) -> AHashSet<&str> {
    api.excluded_type_paths
        .keys()
        .map(String::as_str)
        .chain(api.types.iter().filter(|t| t.binding_excluded).map(|t| t.name.as_str()))
        .collect()
}

fn opaque_type_names(api: &ApiSurface) -> AHashSet<&str> {
    api.types
        .iter()
        .filter(|typ| typ.is_opaque)
        .map(|typ| typ.name.as_str())
        .collect()
}

/// Languages whose backend re-derives its own local Rust binding struct (via
/// `codegen::generators::structs.rs`'s `#[derive(serde::Serialize, serde::Deserialize)]`)
/// rather than round-tripping the core type's own `Serialize`/`Deserialize` directly.
///
/// `SerdeContainerConversionUnsupported` only affects these six: the FFI-derived backends
/// (Go/Java/C#/Dart/Swift/Kotlin/Zig/Jni) call `serde_json::from_str::<CoreType>` /
/// `serde_json::to_string(&CoreType)` against the real core type in
/// `backends/ffi/templates/type_{from,to}_json.jinja` -- confirmed by reading those templates
/// -- whose `Serialize`/`Deserialize` already honours the container conversion because it is
/// genuine compiled code in the consumer's own crate, not something alef re-derives. ~keep
const LANGUAGES_WITH_LOCAL_SERDE_DTO: [Language; 6] = [
    Language::Python,
    Language::Node,
    Language::Ruby,
    Language::Wasm,
    Language::Elixir,
    Language::R,
];

/// Flag a struct whose serde container attributes give it a wire shape at least one
/// in-scope backend's re-derived binding DTO cannot reproduce.
///
/// A container-level `#[serde(from/into/try_from = "...")]` routes the *real* wire shape
/// through a hand-written `From`/`TryFrom` impl alef cannot see (commonly a tuple/array for a
/// value type, not an object); `#[serde(transparent)]` collapses the wire shape to the
/// struct's single field with no wrapping object at all. `resolved_languages` scopes this to
/// a `Warning`, not an `Error`: a consumer targeting only FFI-derived backends has no actual
/// defect, and aborting their build on a diagnostic that names no real problem for their
/// output is worse than the silent bug it replaces. `None` means the caller does not yet know
/// the resolved language set (e.g. a test, or a validation pass run before language
/// resolution) -- fire unconditionally rather than risk silently hiding a real gap. ~keep
fn collect_serde_container_conversion_diagnostics(
    api: &ApiSurface,
    typ: &crate::core::ir::TypeDef,
    resolved_languages: Option<&[Language]>,
    diagnostics: &mut Vec<ValidationDiagnostic>,
) {
    let conversion = &typ.serde_container_conversion;
    if !conversion.is_present() {
        return;
    }
    let mut attrs = Vec::new();
    if let Some(path) = &conversion.from {
        attrs.push(format!("from = \"{path}\""));
    }
    if let Some(path) = &conversion.into {
        attrs.push(format!("into = \"{path}\""));
    }
    if let Some(path) = &conversion.try_from {
        attrs.push(format!("try_from = \"{path}\""));
    }
    if conversion.transparent {
        attrs.push("transparent".to_string());
    }
    let affected =
        resolved_languages.is_none_or(|langs| langs.iter().any(|lang| LANGUAGES_WITH_LOCAL_SERDE_DTO.contains(lang)));
    if !affected {
        return;
    }
    diagnostics.push(ValidationDiagnostic::warning(
        ValidationCode::SerdeContainerConversionUnsupported,
        api.crate_name.clone(),
        None,
        Some(format!("type {}", typ.name)),
        format!(
            "struct carries #[serde({})]; JSON will not round-trip on backends that re-derive their \
             own binding struct (pyo3, napi, magnus, wasm, rustler, extendr). FFI-derived backends \
             (Go, Java, C#, Dart, Swift, Kotlin, Zig) are unaffected",
            attrs.join(", ")
        ),
        "on the affected backends, exclude the type from generated bindings or hand-write its JSON bridge",
    ));
}

fn collect_function_diagnostics(
    api: &ApiSurface,
    known_names: &AHashSet<&str>,
    opaque_names: &AHashSet<&str>,
    item_path: &str,
    function: &FunctionDef,
    diagnostics: &mut Vec<ValidationDiagnostic>,
) {
    if function.sanitized {
        diagnostics.push(ValidationDiagnostic::error(
            ValidationCode::BackendStubPath,
            api.crate_name.clone(),
            Some(item_path.to_string()),
            "function signature was sanitized and may require backend stub generation",
            "exclude the item, configure an opaque/trait bridge, or expose a binding-safe DTO",
        ));
    }
    if fallback_body_would_require_opaque_return(
        function.sanitized,
        &function.params,
        &function.return_type,
        opaque_names,
    ) {
        diagnostics.push(opaque_stub_path_diagnostic(api, item_path, &function.return_type));
    }
    for param in &function.params {
        collect_type_ref_diagnostics(
            api,
            known_names,
            &format!("{item_path} param {}", param.name),
            &param.ty,
            diagnostics,
        );
    }
    collect_type_ref_diagnostics(api, known_names, item_path, &function.return_type, diagnostics);
}

fn collect_method_diagnostics(
    api: &ApiSurface,
    known_names: &AHashSet<&str>,
    opaque_names: &AHashSet<&str>,
    item_path: &str,
    method: &MethodDef,
    receiver_type_is_opaque: bool,
    diagnostics: &mut Vec<ValidationDiagnostic>,
) {
    if method.sanitized {
        diagnostics.push(ValidationDiagnostic::error(
            ValidationCode::BackendStubPath,
            api.crate_name.clone(),
            Some(item_path.to_string()),
            "method signature was sanitized and may require backend stub generation",
            "exclude the item, configure an opaque/trait bridge, or expose a binding-safe DTO",
        ));
    }
    let non_delegatable_ref_mut = matches!(method.receiver, Some(ReceiverKind::RefMut))
        && method.trait_source.is_none()
        && !receiver_type_is_opaque;
    if (non_delegatable_ref_mut && returns_opaque(&method.return_type, opaque_names))
        || fallback_body_would_require_opaque_return(
            method.sanitized,
            &method.params,
            &method.return_type,
            opaque_names,
        )
    {
        diagnostics.push(opaque_stub_path_diagnostic(api, item_path, &method.return_type));
    }
    for param in &method.params {
        collect_type_ref_diagnostics(
            api,
            known_names,
            &format!("{item_path} param {}", param.name),
            &param.ty,
            diagnostics,
        );
    }
    collect_type_ref_diagnostics(api, known_names, item_path, &method.return_type, diagnostics);
}

fn fallback_body_would_require_opaque_return(
    sanitized: bool,
    params: &[crate::core::ir::ParamDef],
    return_type: &TypeRef,
    opaque_names: &AHashSet<&str>,
) -> bool {
    returns_opaque(return_type, opaque_names)
        && (sanitized
            || params
                .iter()
                .any(|param| param.sanitized || is_named_ref_param(param, opaque_names)))
}

fn is_named_ref_param(param: &crate::core::ir::ParamDef, opaque_names: &AHashSet<&str>) -> bool {
    if !param.is_ref {
        return false;
    }
    match &param.ty {
        TypeRef::Named(name) => !opaque_names.contains(name.as_str()),
        TypeRef::Vec(inner) => matches!(inner.as_ref(), TypeRef::String | TypeRef::Char),
        _ => false,
    }
}

fn returns_opaque(ty: &TypeRef, opaque_names: &AHashSet<&str>) -> bool {
    match ty {
        TypeRef::Named(name) => opaque_names.contains(name.as_str()),
        TypeRef::Optional(inner) | TypeRef::Vec(inner) => returns_opaque(inner, opaque_names),
        TypeRef::Map(key, value) => returns_opaque(key, opaque_names) || returns_opaque(value, opaque_names),
        _ => false,
    }
}

fn opaque_stub_path_diagnostic(api: &ApiSurface, item_path: &str, return_type: &TypeRef) -> ValidationDiagnostic {
    ValidationDiagnostic::error(
        ValidationCode::BackendStubPath,
        api.crate_name.clone(),
        Some(item_path.to_string()),
        format!(
            "non-delegatable signature returns opaque type `{}`",
            type_ref_label(return_type)
        ),
        "exclude the item, add an adapter body, or change the API to return a binding-safe type",
    )
}

fn type_ref_label(ty: &TypeRef) -> String {
    match ty {
        TypeRef::Named(name) => name.clone(),
        TypeRef::Optional(inner) | TypeRef::Vec(inner) => type_ref_label(inner),
        TypeRef::Map(_, value) => type_ref_label(value),
        _ => format!("{ty:?}"),
    }
}

fn collect_service_diagnostics(
    api: &ApiSurface,
    known_names: &AHashSet<&str>,
    opaque_names: &AHashSet<&str>,
    service: &ServiceDef,
    diagnostics: &mut Vec<ValidationDiagnostic>,
) {
    collect_method_diagnostics(
        api,
        known_names,
        opaque_names,
        &format!("service {} constructor", service.name),
        &service.constructor,
        false,
        diagnostics,
    );
    for configurator in &service.configurators {
        collect_method_diagnostics(
            api,
            known_names,
            opaque_names,
            &format!("service {} configurator {}", service.name, configurator.name),
            configurator,
            false,
            diagnostics,
        );
    }
    for registration in &service.registrations {
        let item_path = format!("service {} registration {}", service.name, registration.method);
        for param in &registration.metadata_params {
            collect_type_ref_diagnostics(
                api,
                known_names,
                &format!("{item_path} metadata param {}", param.name),
                &param.ty,
                diagnostics,
            );
        }
        collect_type_ref_diagnostics(api, known_names, &item_path, &registration.return_type, diagnostics);
        for variant in &registration.variants {
            for param in &variant.signature_params {
                collect_type_ref_diagnostics(
                    api,
                    known_names,
                    &format!("{item_path} variant {} param {}", variant.name, param.name),
                    &param.ty,
                    diagnostics,
                );
            }
            if let Some(wrapper_call) = &variant.wrapper_call {
                for arg in &wrapper_call.args {
                    if let crate::core::ir::WrapperConstructorArg::Free { param } = arg {
                        collect_type_ref_diagnostics(
                            api,
                            known_names,
                            &format!("{item_path} variant {} wrapper param {}", variant.name, param.name),
                            &param.ty,
                            diagnostics,
                        );
                    }
                }
            }
        }
    }
    for entrypoint in &service.entrypoints {
        let item_path = format!("service {} entrypoint {}", service.name, entrypoint.method);
        for param in &entrypoint.params {
            collect_type_ref_diagnostics(
                api,
                known_names,
                &format!("{item_path} param {}", param.name),
                &param.ty,
                diagnostics,
            );
        }
        collect_type_ref_diagnostics(api, known_names, &item_path, &entrypoint.return_type, diagnostics);
    }
}

fn collect_handler_contract_diagnostics(
    api: &ApiSurface,
    known_names: &AHashSet<&str>,
    opaque_names: &AHashSet<&str>,
    contract: &HandlerContractDef,
    diagnostics: &mut Vec<ValidationDiagnostic>,
) {
    collect_method_diagnostics(
        api,
        known_names,
        opaque_names,
        &format!("handler contract {} dispatch", contract.trait_name),
        &contract.dispatch,
        false,
        diagnostics,
    );
    for method in &contract.optional_methods {
        collect_method_diagnostics(
            api,
            known_names,
            opaque_names,
            &format!(
                "handler contract {} optional method {}",
                contract.trait_name, method.name
            ),
            method,
            false,
            diagnostics,
        );
    }
    for (label, maybe_type) in [
        ("wire request", contract.wire_request_type.as_deref()),
        ("wire response", contract.wire_response_type.as_deref()),
    ] {
        if let Some(type_name) = maybe_type {
            collect_type_ref_diagnostics(
                api,
                known_names,
                &format!("handler contract {} {label}", contract.trait_name),
                &TypeRef::Named(type_name.to_string()),
                diagnostics,
            );
        }
    }
}

fn collect_type_ref_diagnostics(
    api: &ApiSurface,
    known_names: &AHashSet<&str>,
    item_path: &str,
    ty: &TypeRef,
    diagnostics: &mut Vec<ValidationDiagnostic>,
) {
    match ty {
        TypeRef::Named(name) if name == "Value" || name == "JsonValue" => {
            diagnostics.push(ValidationDiagnostic::error(
                ValidationCode::JsonValueResolutionAmbiguous,
                api.crate_name.clone(),
                Some(item_path.to_string()),
                format!("bare `{name}` cannot prove it is serde_json::Value"),
                "import or expose serde_json::Value with a resolved path, or configure the type explicitly",
            ))
        }
        TypeRef::Named(name) if !known_names.contains(name.as_str()) => {
            diagnostics.push(ValidationDiagnostic::error(
                ValidationCode::UnknownNamedType,
                api.crate_name.clone(),
                Some(item_path.to_string()),
                format!("named type `{name}` is not present in the extracted API surface"),
                "include the type in the public API, configure it as opaque/excluded, or add a bridge rule",
            ));
        }
        TypeRef::Optional(inner) | TypeRef::Vec(inner) => {
            collect_type_ref_diagnostics(api, known_names, item_path, inner, diagnostics);
        }
        TypeRef::Map(key, value) => {
            collect_type_ref_diagnostics(api, known_names, item_path, key, diagnostics);
            collect_type_ref_diagnostics(api, known_names, item_path, value, diagnostics);
        }
        _ => {}
    }
}