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
//! Config resolution helpers and bytes classification for Python e2e tests.

use std::collections::{HashMap, HashSet};

use crate::e2e::config::E2eConfig;
use crate::e2e::fixture::Fixture;

// ---------------------------------------------------------------------------
// Config resolution
// ---------------------------------------------------------------------------

pub(super) fn resolve_function_name(e2e_config: &E2eConfig) -> String {
    resolve_function_name_for_call(&e2e_config.call)
}

pub(super) fn resolve_function_name_for_call(call_config: &crate::e2e::config::CallConfig) -> String {
    call_config
        .overrides
        .get("python")
        .and_then(|o| o.function.clone())
        .unwrap_or_else(|| call_config.function.clone())
}

pub(super) fn resolve_module(e2e_config: &E2eConfig) -> String {
    e2e_config
        .call
        .overrides
        .get("python")
        .and_then(|o| o.module.clone())
        .unwrap_or_else(|| e2e_config.call.module.replace('-', "_"))
}

pub(super) fn resolve_options_type(e2e_config: &E2eConfig) -> Option<String> {
    e2e_config
        .call
        .overrides
        .get("python")
        .and_then(|o| o.options_type.clone())
}

/// Resolve the client factory function name from the Python override config.
///
/// When set, the generated test creates a client instance via `factory("test-key", base_url)`
/// and dispatches API calls as methods on the client rather than top-level functions.
pub(super) fn resolve_client_factory(e2e_config: &E2eConfig) -> Option<String> {
    e2e_config
        .call
        .overrides
        .get("python")
        .and_then(|o| o.client_factory.clone())
}

/// Resolve how json_object args are passed: "kwargs" (default), "dict", or "json".
pub(super) fn resolve_options_via(e2e_config: &E2eConfig) -> &str {
    e2e_config
        .call
        .overrides
        .get("python")
        .and_then(|o| o.options_via.as_deref())
        .unwrap_or("kwargs")
}

/// Compute the exact type-name set the pyo3 backend injects a `from_json()` staticmethod for.
///
/// pyo3's gate (`src/backends/pyo3/gen_bindings/mod.rs`) is the conjunction
/// `has_serde && core_to_binding_convertible_types(api, &[]).contains(&typ.name)` — `has_serde`
/// alone is necessary but not sufficient, since a serde-derived type can still fail the
/// transitive core→binding convertibility fixpoint (e.g. a field whose type has no matching
/// binding conversion). Calling the real `core_to_binding_convertible_types` here — rather than
/// re-deriving convertibility from `type_defs`/`enums` by hand — keeps this in lockstep with
/// pyo3 even if that algorithm changes; it reads only `surface.types`/`surface.enums`, so the
/// synthetic surface built from the same two IR slices already threaded through e2e codegen is
/// faithful to the real one. ~keep
pub(super) fn core_to_binding_convertible_types(
    type_defs: &[crate::core::ir::TypeDef],
    enums: &[crate::core::ir::EnumDef],
) -> ahash::AHashSet<String> {
    let surface = crate::core::ir::ApiSurface {
        types: type_defs.to_vec(),
        enums: enums.to_vec(),
        ..Default::default()
    };
    crate::codegen::conversions::core_to_binding_convertible_types(&surface, &[])
}

/// Mirrors pyo3's own gate for injecting a `from_json()` staticmethod into a type's generated
/// Rust `impl` block — the shared [`crate::codegen::conversions::pyo3_from_json_eligible`]
/// predicate, requiring per-type serde derives, crate-level serde availability, and
/// core<->binding convertibility (see `src/backends/pyo3/gen_bindings/types.rs`). As of
/// `093c42f31`, `type_has_from_json` is the single predicate shared by both the raw-text
/// `#[pymethods]` injection and the `.pyi` stub generator, so passing this gate also means the
/// shipped stub declares the method — verified against a consumer's `CreateImageRequest`, where
/// `_internal_bindings.pyi` carries `def from_json`. ~keep
pub(super) fn pyo3_would_inject_from_json(
    name: &str,
    type_defs: &[crate::core::ir::TypeDef],
    convertible_types: &ahash::AHashSet<String>,
    crate_has_serde: bool,
) -> bool {
    type_defs
        .iter()
        .find(|t| t.name == name)
        .is_some_and(|t| crate::codegen::conversions::pyo3_from_json_eligible(t, crate_has_serde, convertible_types))
}

/// Downgrade `options_via` from `"from_json"` to `"kwargs"` unless the target type actually
/// passes pyo3's Rust-codegen gate ([`pyo3_would_inject_from_json`]) — the gate that also
/// controls whether the `.pyi` stub declares the method, so passing it guarantees the emitted
/// call type-checks against the shipped stub. Every generated DTO still exposes a plain kwargs
/// constructor, so falling back there keeps the emitted call valid for types that don't clear
/// the gate. ~keep
pub(super) fn effective_options_via_for_type<'a>(
    options_via: &'a str,
    options_type: Option<&str>,
    type_defs: &[crate::core::ir::TypeDef],
    convertible_types: &ahash::AHashSet<String>,
    crate_has_serde: bool,
) -> &'a str {
    if options_via != "from_json" {
        return options_via;
    }
    let is_declared = options_type
        .is_some_and(|name| pyo3_would_inject_from_json(name, type_defs, convertible_types, crate_has_serde));
    if is_declared { options_via } else { "kwargs" }
}

/// Resolve enum field mappings from the Python override config.
pub(super) fn resolve_enum_fields(e2e_config: &E2eConfig) -> &HashMap<String, String> {
    static EMPTY: std::sync::LazyLock<HashMap<String, String>> = std::sync::LazyLock::new(HashMap::new);
    e2e_config
        .call
        .overrides
        .get("python")
        .map(|o| &o.enum_fields)
        .unwrap_or(&EMPTY)
}

/// Resolve per-call result-field enum mappings from the Python override config.
///
/// Returns the `assert_enum_fields` map from the Python override block for
/// `call_config`, falling back to an empty map when no override is present.
pub(super) fn resolve_assert_enum_fields(call_config: &crate::e2e::config::CallConfig) -> &HashMap<String, String> {
    static EMPTY: std::sync::LazyLock<HashMap<String, String>> = std::sync::LazyLock::new(HashMap::new);
    call_config
        .overrides
        .get("python")
        .map(|o| &o.assert_enum_fields)
        .unwrap_or(&EMPTY)
}

/// Resolve handle nested type mappings from the Python override config.
pub(super) fn resolve_handle_nested_types(e2e_config: &E2eConfig) -> &HashMap<String, String> {
    static EMPTY: std::sync::LazyLock<HashMap<String, String>> = std::sync::LazyLock::new(HashMap::new);
    e2e_config
        .call
        .overrides
        .get("python")
        .map(|o| &o.handle_nested_types)
        .unwrap_or(&EMPTY)
}

/// Resolve handle dict type set from the Python override config.
pub(super) fn resolve_handle_dict_types(e2e_config: &E2eConfig) -> &HashSet<String> {
    static EMPTY: std::sync::LazyLock<HashSet<String>> = std::sync::LazyLock::new(HashSet::new);
    e2e_config
        .call
        .overrides
        .get("python")
        .map(|o| &o.handle_dict_types)
        .unwrap_or(&EMPTY)
}

pub(super) fn is_skipped(fixture: &Fixture, language: &str) -> bool {
    fixture.skip.as_ref().is_some_and(|s| s.should_skip(language))
}

// ---------------------------------------------------------------------------
// Bytes classification
// ---------------------------------------------------------------------------

/// How to represent a fixture `type = "bytes"` string value in generated Python.
pub(super) enum BytesKind {
    /// A relative file path like `"pdf/fake_memo.pdf"` — read with `Path(...).read_bytes()`.
    FilePath,
    /// Inline text content like `"<!DOCTYPE html>..."` — encode to `b"..."`.
    InlineText,
    /// A base64-encoded blob like `"/9j/4AAQ"` — decode with `base64.b64decode(...)`.
    Base64,
}

/// Classify a fixture string value that maps to a `bytes` argument.
pub(super) fn classify_bytes_value(s: &str) -> BytesKind {
    if s.starts_with('<') || s.starts_with('{') || s.starts_with('[') || s.contains(' ') {
        return BytesKind::InlineText;
    }

    let first = s.chars().next().unwrap_or('\0');
    if (first.is_ascii_alphanumeric() || first == '_')
        && let Some(slash_pos) = s.find('/')
        && slash_pos > 0
    {
        let after_slash = &s[slash_pos + 1..];
        if after_slash.contains('.') && !after_slash.is_empty() {
            return BytesKind::FilePath;
        }
    }

    BytesKind::Base64
}

/// Returns the Python import name for a method_result method that uses a
/// module-level helper function (not a method on the result object).
pub(super) fn python_method_helper_import(method_name: &str) -> Option<String> {
    match method_name {
        "has_error_nodes" => Some("tree_has_error_nodes".to_string()),
        "error_count" | "tree_error_count" => Some("tree_error_count".to_string()),
        "tree_to_sexp" => Some("tree_to_sexp".to_string()),
        "contains_node_type" => Some("tree_contains_node_type".to_string()),
        "find_nodes_by_type" => Some("find_nodes_by_type".to_string()),
        "run_query" => Some("run_query".to_string()),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classify_bytes_value_html_is_inline() {
        matches!(classify_bytes_value("<!DOCTYPE html>"), BytesKind::InlineText);
    }

    #[test]
    fn classify_bytes_value_pdf_path_is_file_path() {
        matches!(classify_bytes_value("pdf/fake_memo.pdf"), BytesKind::FilePath);
    }

    #[test]
    fn classify_bytes_value_base64_is_base64() {
        matches!(classify_bytes_value("/9j/4AAQSkZJRgABAQEASABIAAD"), BytesKind::Base64);
    }

    // --- pyo3_would_inject_from_json: the shared pyo3_from_json_eligible gate. All three
    // conditions — per-type has_serde, crate-level has_serde, and convertibility — are
    // independently necessary. ---

    #[test]
    fn pyo3_would_inject_from_json_true_when_all_three_conditions_hold() {
        let type_defs = vec![crate::core::ir::TypeDef {
            name: "WidgetRequest".to_string(),
            has_serde: true,
            ..Default::default()
        }];
        let convertible = core_to_binding_convertible_types(&type_defs, &[]);
        assert!(
            convertible.contains("WidgetRequest"),
            "test setup: a plain fieldless type must be convertible"
        );

        assert!(pyo3_would_inject_from_json(
            "WidgetRequest",
            &type_defs,
            &convertible,
            true
        ));
    }

    #[test]
    fn pyo3_would_inject_from_json_false_when_type_lacks_serde() {
        let type_defs = vec![crate::core::ir::TypeDef {
            name: "WidgetRequest".to_string(),
            has_serde: false,
            ..Default::default()
        }];
        let convertible = core_to_binding_convertible_types(&type_defs, &[]);

        assert!(!pyo3_would_inject_from_json(
            "WidgetRequest",
            &type_defs,
            &convertible,
            true
        ));
    }

    /// Mirrors the measured liter-llm defect: `has_serde` alone is not the pyo3 gate. A
    /// serde-derived type whose field references a type that never resolves fails the second
    /// half of pyo3's conjunction (`core_to_binding_convertible_types`), so pyo3 never injects
    /// `from_json()` for it even though `has_serde` is true.
    #[test]
    fn pyo3_would_inject_from_json_false_when_type_has_serde_but_is_not_convertible() {
        use crate::core::ir::{FieldDef, TypeDef, TypeRef};

        let type_defs = vec![TypeDef {
            name: "WidgetRequest".to_string(),
            has_serde: true,
            fields: vec![FieldDef {
                name: "extra".to_string(),
                ty: TypeRef::Named("UnresolvedExternalType".to_string()),
                ..Default::default()
            }],
            ..Default::default()
        }];
        let convertible = core_to_binding_convertible_types(&type_defs, &[]);
        assert!(
            !convertible.contains("WidgetRequest"),
            "test setup: an unresolved field type must fail convertibility"
        );

        assert!(!pyo3_would_inject_from_json(
            "WidgetRequest",
            &type_defs,
            &convertible,
            true
        ));
    }

    /// The unified predicate's third independent condition: even a per-type-serde,
    /// convertible type must not get `from_json` when the binding crate itself lacks
    /// `serde`/`serde_json` — `serde_json::from_str` wouldn't compile there.
    #[test]
    fn pyo3_would_inject_from_json_false_when_crate_lacks_serde() {
        let type_defs = vec![crate::core::ir::TypeDef {
            name: "WidgetRequest".to_string(),
            has_serde: true,
            ..Default::default()
        }];
        let convertible = core_to_binding_convertible_types(&type_defs, &[]);
        assert!(
            convertible.contains("WidgetRequest"),
            "test setup: a plain fieldless type must be convertible"
        );

        assert!(!pyo3_would_inject_from_json(
            "WidgetRequest",
            &type_defs,
            &convertible,
            false
        ));
    }

    // --- effective_options_via_for_type: what the emitter actually does today ---

    /// As of `093c42f31`, the pyo3 `.pyi` stub generator declares `from_json` under the exact
    /// same predicate as pyo3's Rust-codegen gate (`type_has_from_json` in
    /// `src/backends/pyo3/gen_bindings/types.rs`), so a type that passes the gate keeps
    /// `options_via = "from_json"` instead of downgrading. This is the exact liter-llm
    /// `CreateImageRequest` case: has_serde and convertible are both true, and
    /// `_internal_bindings.pyi` now declares `def from_json` for it.
    #[test]
    fn effective_options_via_for_type_keeps_from_json_when_pyo3_would_inject_it() {
        let type_defs = vec![crate::core::ir::TypeDef {
            name: "WidgetRequest".to_string(),
            has_serde: true,
            ..Default::default()
        }];
        let convertible = core_to_binding_convertible_types(&type_defs, &[]);
        assert!(pyo3_would_inject_from_json(
            "WidgetRequest",
            &type_defs,
            &convertible,
            true
        ));

        assert_eq!(
            effective_options_via_for_type("from_json", Some("WidgetRequest"), &type_defs, &convertible, true),
            "from_json"
        );
    }

    #[test]
    fn effective_options_via_for_type_downgrades_to_kwargs_when_type_lacks_serde() {
        let type_defs = vec![crate::core::ir::TypeDef {
            name: "WidgetRequest".to_string(),
            has_serde: false,
            ..Default::default()
        }];
        let convertible = core_to_binding_convertible_types(&type_defs, &[]);

        assert_eq!(
            effective_options_via_for_type("from_json", Some("WidgetRequest"), &type_defs, &convertible, true),
            "kwargs"
        );
    }

    #[test]
    fn effective_options_via_for_type_downgrades_to_kwargs_when_crate_lacks_serde() {
        let type_defs = vec![crate::core::ir::TypeDef {
            name: "WidgetRequest".to_string(),
            has_serde: true,
            ..Default::default()
        }];
        let convertible = core_to_binding_convertible_types(&type_defs, &[]);

        assert_eq!(
            effective_options_via_for_type("from_json", Some("WidgetRequest"), &type_defs, &convertible, false),
            "kwargs"
        );
    }

    #[test]
    fn effective_options_via_for_type_downgrades_to_kwargs_when_type_is_unknown() {
        let convertible = core_to_binding_convertible_types(&[], &[]);
        assert_eq!(
            effective_options_via_for_type("from_json", Some("WidgetRequest"), &[], &convertible, true),
            "kwargs"
        );
    }

    #[test]
    fn effective_options_via_for_type_leaves_non_from_json_values_untouched() {
        let convertible = core_to_binding_convertible_types(&[], &[]);
        assert_eq!(
            effective_options_via_for_type("dict", None, &[], &convertible, true),
            "dict"
        );
        assert_eq!(
            effective_options_via_for_type("kwargs", None, &[], &convertible, true),
            "kwargs"
        );
    }

    #[test]
    fn python_method_helper_import_recognizes_has_error_nodes() {
        assert_eq!(
            python_method_helper_import("has_error_nodes"),
            Some("tree_has_error_nodes".to_string())
        );
    }

    #[test]
    fn python_method_helper_import_returns_none_for_plain_method() {
        assert!(python_method_helper_import("root_child_count").is_none());
    }
}