alef 0.83.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
//! Table-driven tests for `crate::e2e::field_access::ir_enum` and its integration into
//! `FieldResolver::is_enum` — the fix for the defect where enum-ness was decided purely from
//! a hand-written `alef.toml` `fields_enum` list instead of the crate's own IR.

use std::collections::HashSet;

use crate::core::ir::{EnumDef, EnumVariant, FieldDef, TypeDef, TypeRef};
use crate::e2e::field_access::FieldResolver;

use super::ir_enum::{build_ir_enum_map, is_enum_path};
use super::types::IrEnumMap;

fn field(name: &str, ty: TypeRef) -> FieldDef {
    FieldDef {
        name: name.to_string(),
        ty,
        ..FieldDef::default()
    }
}

fn type_def(name: &str, fields: Vec<FieldDef>) -> TypeDef {
    TypeDef {
        name: name.to_string(),
        fields,
        ..TypeDef::default()
    }
}

fn enum_def(name: &str) -> EnumDef {
    EnumDef {
        name: name.to_string(),
        ..EnumDef::default()
    }
}

/// The fixture at the heart of the reported defect: two structs each declare a field named
/// `kind`, but only one of them is actually enum-typed. `DataNode.kind: DataNodeKind` (a real
/// IR enum) sits beside `PlainNode.kind: String`. A name-keyed rule cannot get both right.
fn ambiguous_kind_type_defs() -> Vec<TypeDef> {
    vec![
        type_def(
            "DataNode",
            vec![field("kind", TypeRef::Named("DataNodeKind".to_string()))],
        ),
        type_def("PlainNode", vec![field("kind", TypeRef::String)]),
    ]
}

fn ambiguous_kind_enums() -> Vec<EnumDef> {
    vec![enum_def("DataNodeKind")]
}

#[test]
fn a_field_whose_declared_type_is_a_real_enum_is_derived_as_enum() {
    let map = build_ir_enum_map(&ambiguous_kind_type_defs(), &ambiguous_kind_enums());
    let map = IrEnumMap {
        root_type: Some("DataNode".to_string()),
        ..map
    };

    assert!(is_enum_path(&map, "kind"), "DataNode.kind is DataNodeKind, a real enum");
}

#[test]
fn a_field_with_the_same_name_but_a_string_type_on_a_different_owner_is_not_enum() {
    let map = build_ir_enum_map(&ambiguous_kind_type_defs(), &ambiguous_kind_enums());
    let map = IrEnumMap {
        root_type: Some("PlainNode".to_string()),
        ..map
    };

    assert!(
        !is_enum_path(&map, "kind"),
        "PlainNode.kind is String — the bare name 'kind' must not decide this"
    );
}

#[test]
fn an_option_wrapped_enum_field_is_derived_as_enum() {
    let type_defs = vec![type_def(
        "Response",
        vec![field(
            "status",
            TypeRef::Optional(Box::new(TypeRef::Named("Status".to_string()))),
        )],
    )];
    let enums = vec![enum_def("Status")];
    let map = build_ir_enum_map(&type_defs, &enums);
    let map = IrEnumMap {
        root_type: Some("Response".to_string()),
        ..map
    };

    assert!(is_enum_path(&map, "status"), "Option<Status> must unwrap to the enum");
}

#[test]
fn a_vec_wrapped_element_field_reached_via_wildcard_traversal_is_derived_as_enum() {
    // `Result.links: Vec<Link>`, `Link.link_type: LinkType` (enum) — mirrors the
    // `links[].link_type` path form the Rust wildcard-assertion renderer produces.
    let type_defs = vec![
        type_def(
            "Result",
            vec![field(
                "links",
                TypeRef::Vec(Box::new(TypeRef::Named("Link".to_string()))),
            )],
        ),
        type_def("Link", vec![field("link_type", TypeRef::Named("LinkType".to_string()))]),
    ];
    let enums = vec![enum_def("LinkType")];
    let map = build_ir_enum_map(&type_defs, &enums);
    let map = IrEnumMap {
        root_type: Some("Result".to_string()),
        ..map
    };

    assert!(
        is_enum_path(&map, "links[].link_type"),
        "Vec<Link>.link_type must be reached through the wildcard array segment"
    );
    // The already-split element sub-path (what a hand-written `fields_enum` entry would
    // name) must NOT resolve on its own without the array segment: `link_type` is not a
    // direct field of `Result`, the root type.
    assert!(
        !is_enum_path(&map, "link_type"),
        "a bare leaf name must not resolve against the wrong owner type"
    );
}

#[test]
fn a_nested_indexed_path_is_derived_as_enum() {
    // `Response.choices: Vec<Choice>`, `Choice.finish_reason: FinishReason` (enum) — mirrors
    // `choices[0].finish_reason`.
    let type_defs = vec![
        type_def(
            "Response",
            vec![field(
                "choices",
                TypeRef::Vec(Box::new(TypeRef::Named("Choice".to_string()))),
            )],
        ),
        type_def(
            "Choice",
            vec![field("finish_reason", TypeRef::Named("FinishReason".to_string()))],
        ),
    ];
    let enums = vec![enum_def("FinishReason")];
    let map = build_ir_enum_map(&type_defs, &enums);
    let map = IrEnumMap {
        root_type: Some("Response".to_string()),
        ..map
    };

    assert!(is_enum_path(&map, "choices[0].finish_reason"));
}

#[test]
fn a_missing_root_type_answers_false_rather_than_guessing() {
    let map = build_ir_enum_map(&ambiguous_kind_type_defs(), &ambiguous_kind_enums());
    // root_type left as None (build_ir_enum_map never sets it).
    assert!(!is_enum_path(&map, "kind"));
}

#[test]
fn a_path_through_an_unknown_field_answers_false() {
    let map = build_ir_enum_map(&ambiguous_kind_type_defs(), &ambiguous_kind_enums());
    let map = IrEnumMap {
        root_type: Some("DataNode".to_string()),
        ..map
    };

    assert!(!is_enum_path(&map, "nonexistent_field"));
    assert!(!is_enum_path(&map, "nonexistent_parent.kind"));
}

/// End-to-end proof that `FieldResolver::is_enum` actually consults the IR fallback once
/// `with_ir_enum_map` wires it in — not just the standalone `is_enum_path` helper.
#[test]
fn field_resolver_is_enum_consults_the_ir_fallback_when_config_is_silent() {
    let map = FieldResolver::ir_enum_fields(&ambiguous_kind_type_defs(), &ambiguous_kind_enums());
    let resolver = FieldResolver::new(
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
    )
    .with_ir_enum_map(map, Some("DataNode".to_string()));

    assert!(
        resolver.is_enum("kind"),
        "fields_enum was never configured; the IR alone must answer this"
    );
}

/// The companion case: the same field name on the type where it is genuinely a `String` must
/// stay `false`, proving the resolver-level integration is exactly as owner-aware as
/// `is_enum_path` itself.
#[test]
fn field_resolver_is_enum_does_not_misclassify_the_same_name_on_a_different_owner() {
    let map = FieldResolver::ir_enum_fields(&ambiguous_kind_type_defs(), &ambiguous_kind_enums());
    let resolver = FieldResolver::new(
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
    )
    .with_ir_enum_map(map, Some("PlainNode".to_string()));

    assert!(!resolver.is_enum("kind"));
}

/// Hard requirement: an explicitly-configured `fields_enum` entry must keep winning even when
/// the IR would (wrongly, or simply because the config author knows something the IR can't
/// see, e.g. a type alias) disagree — regressing an already-correct consumer config is
/// unacceptable.
#[test]
fn an_explicit_fields_enum_entry_wins_even_when_the_ir_disagrees() {
    let map = FieldResolver::ir_enum_fields(&ambiguous_kind_type_defs(), &ambiguous_kind_enums());
    let resolver = FieldResolver::new(
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
    )
    .with_enum_fields(HashSet::from(["kind".to_string()]))
    // Anchored at PlainNode, where the IR says `kind` is a plain String.
    .with_ir_enum_map(map, Some("PlainNode".to_string()));

    assert!(
        resolver.is_enum("kind"),
        "an explicit fields_enum entry must win over an IR disagreement"
    );
}

/// A resolver that never calls `with_ir_enum_map` at all (every existing call site before
/// this fix, and every backend that hasn't been wired up yet) must behave exactly as before:
/// `is_enum` answers strictly from `fields_enum`.
#[test]
fn a_resolver_with_no_ir_enum_map_wired_in_behaves_exactly_as_before() {
    let resolver = FieldResolver::new(
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
    );

    assert!(!resolver.is_enum("kind"));

    let resolver = resolver.with_enum_fields(HashSet::from(["kind".to_string()]));
    assert!(resolver.is_enum("kind"));
}

/// `variant_payload_is_collection` must distinguish a tuple variant whose single field is
/// itself `Vec<T>` (`Found(Vec<Entry>)`) from a variant wrapping a struct that merely contains
/// a collection field elsewhere (`Wrapped(Payload)`) — the shape distinction
/// `FieldResolver::union_variant_payload_is_collection` needs when a fixture path names only
/// the variant, with no field inside its payload (the "the payload itself is the list" case
/// `csharp`/`kotlin` count_min assertions used to silently drop).
#[test]
fn variant_payload_is_collection_distinguishes_a_direct_vec_payload_from_a_wrapping_struct() {
    let enums = vec![EnumDef {
        name: "Outcome".to_string(),
        variants: vec![
            EnumVariant {
                name: "Found".to_string(),
                fields: vec![field("_0", TypeRef::Vec(Box::new(TypeRef::Named("Entry".to_string()))))],
                ..EnumVariant::default()
            },
            EnumVariant {
                name: "Wrapped".to_string(),
                fields: vec![field("payload", TypeRef::Named("Payload".to_string()))],
                ..EnumVariant::default()
            },
            EnumVariant {
                name: "Empty".to_string(),
                ..EnumVariant::default()
            },
        ],
        ..EnumDef::default()
    }];
    let map = build_ir_enum_map(&[], &enums);

    assert!(
        map.variant_payload_is_collection
            .get("Outcome")
            .is_some_and(|variants| variants.contains("Found")),
        "Found(Vec<Entry>) wraps a collection directly"
    );
    assert!(
        !map.variant_payload_is_collection
            .get("Outcome")
            .is_some_and(|variants| variants.contains("Wrapped")),
        "Wrapped(Payload) wraps a struct, not a collection"
    );
    assert!(
        !map.variant_payload_is_collection
            .get("Outcome")
            .is_some_and(|variants| variants.contains("Empty")),
        "a fieldless variant has no payload to classify"
    );
}

/// The resolver-level surface `csharp`/`kotlin` call: `union_variant_payload_is_collection`
/// answers `true` for the direct-`Vec` variant and `false` for both the struct-wrapping variant
/// and an unknown union/variant name, without ever needing a field name — unlike
/// `union_variant_field_is_collection`, which requires one and cannot answer this question.
#[test]
fn resolver_union_variant_payload_is_collection_matches_the_ir() {
    let enums = vec![EnumDef {
        name: "Outcome".to_string(),
        variants: vec![
            EnumVariant {
                name: "Found".to_string(),
                fields: vec![field("_0", TypeRef::Vec(Box::new(TypeRef::Named("Entry".to_string()))))],
                ..EnumVariant::default()
            },
            EnumVariant {
                name: "Wrapped".to_string(),
                fields: vec![field("payload", TypeRef::Named("Payload".to_string()))],
                ..EnumVariant::default()
            },
        ],
        ..EnumDef::default()
    }];
    let resolver = FieldResolver::new(
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
        &Default::default(),
    )
    .with_ir_enum_map(FieldResolver::ir_enum_fields(&[], &enums), None);

    assert!(resolver.union_variant_payload_is_collection("Outcome", "Found"));
    assert!(!resolver.union_variant_payload_is_collection("Outcome", "Wrapped"));
    assert!(!resolver.union_variant_payload_is_collection("Outcome", "Missing"));
    assert!(!resolver.union_variant_payload_is_collection("UnknownUnion", "Found"));
}

/// Scope-boundary control (not a defect): `Vec<Vec<T>>` and `Option<Vec<T>>` payloads both
/// classify as collections through `is_vec_type`'s existing recursion (`Optional` unwraps once,
/// `Vec` matches immediately regardless of its element type), and `named_type` recurses through
/// BOTH layers of `Vec<Vec<T>>` to the same innermost named element `variant_payload_types`
/// already recorded for a single-layer `Vec<T>` -- so the collection-payload classification and
/// the payload type name it records are both anchored on the OUTER `Vec`, which is exactly what
/// `render_bare_variant_payload_assertion`'s `.size`/`.Count` ends up asserting against. Pinned
/// as-is; no production code changed to make this pass. ~keep
#[test]
fn variant_payload_is_collection_covers_nested_vec_and_optional_vec_payloads() {
    let enums = vec![EnumDef {
        name: "Outcome".to_string(),
        variants: vec![
            EnumVariant {
                name: "NestedVec".to_string(),
                fields: vec![field(
                    "_0",
                    TypeRef::Vec(Box::new(TypeRef::Vec(Box::new(TypeRef::Named("Entry".to_string()))))),
                )],
                ..EnumVariant::default()
            },
            EnumVariant {
                name: "OptionalVec".to_string(),
                fields: vec![field(
                    "_0",
                    TypeRef::Optional(Box::new(TypeRef::Vec(Box::new(TypeRef::Named("Entry".to_string()))))),
                )],
                ..EnumVariant::default()
            },
        ],
        ..EnumDef::default()
    }];
    let map = build_ir_enum_map(&[], &enums);

    assert!(
        map.variant_payload_is_collection
            .get("Outcome")
            .is_some_and(|variants| variants.contains("NestedVec")),
        "Vec<Vec<Entry>> classifies as a collection payload via the outer Vec"
    );
    assert_eq!(
        map.variant_payload_types
            .get("Outcome")
            .and_then(|v| v.get("NestedVec")),
        Some(&("_0".to_string(), "Entry".to_string())),
        "named_type recurses through both Vec layers to the innermost named element"
    );

    assert!(
        map.variant_payload_is_collection
            .get("Outcome")
            .is_some_and(|variants| variants.contains("OptionalVec")),
        "Option<Vec<Entry>> classifies as a collection payload via is_vec_type's Optional unwrap"
    );
    assert_eq!(
        map.variant_payload_types
            .get("Outcome")
            .and_then(|v| v.get("OptionalVec")),
        Some(&("_0".to_string(), "Entry".to_string())),
        "named_type unwraps Option then Vec to the same named element"
    );
}

fn variant(name: &str, serde_rename: Option<&str>) -> EnumVariant {
    EnumVariant {
        name: name.to_string(),
        serde_rename: serde_rename.map(str::to_string),
        ..EnumVariant::default()
    }
}

fn wire_variant_enum(rename_all: Option<&str>, variants: Vec<EnumVariant>) -> EnumDef {
    EnumDef {
        name: "Kind".to_string(),
        serde_rename_all: rename_all.map(str::to_string),
        variants,
        ..EnumDef::default()
    }
}

/// Table-driven contract for `enum_wire_variants`, the wire-value -> Rust-identifier reverse
/// lookup a generator needs when it renders an enum on the Rust surface (`{:?}`) but compares
/// against a fixture's serde wire value.
///
/// The map must be populated ONLY where the two spellings genuinely disagree and the answer is
/// unambiguous, because a caller reads a miss as "no rename to reconcile" and keeps the fixture
/// literal verbatim. Recording an entry that is not a real, unique rename would silently
/// rewrite a correct expectation into a different variant's.
#[test]
fn enum_wire_variants_records_only_unambiguous_renames() {
    struct Case {
        name: &'static str,
        rename_all: Option<&'static str>,
        variants: Vec<EnumVariant>,
        lookup: &'static str,
        expected: Option<&'static str>,
    }
    let cases = vec![
        Case {
            name: "explicit serde(rename) maps the wire value back to the identifier",
            rename_all: None,
            variants: vec![variant("KeyValue", Some("key-value"))],
            lookup: "key-value",
            expected: Some("KeyValue"),
        },
        Case {
            name: "rename_all alone is enough to separate the two spellings",
            rename_all: Some("kebab-case"),
            variants: vec![variant("KeyValue", None)],
            lookup: "key-value",
            expected: Some("KeyValue"),
        },
        Case {
            name: "serde(rename) wins over rename_all",
            rename_all: Some("kebab-case"),
            variants: vec![variant("KeyValue", Some("kv"))],
            lookup: "kv",
            expected: Some("KeyValue"),
        },
        Case {
            name: "the rename_all spelling is NOT recorded when serde(rename) overrode it",
            rename_all: Some("kebab-case"),
            variants: vec![variant("KeyValue", Some("kv"))],
            lookup: "key-value",
            expected: None,
        },
        Case {
            name: "an unrenamed variant has nothing to reconcile and is absent",
            rename_all: None,
            variants: vec![variant("Plain", None)],
            lookup: "Plain",
            expected: None,
        },
        Case {
            name: "a rename_all that is a no-op for this identifier is absent",
            rename_all: Some("PascalCase"),
            variants: vec![variant("Plain", None)],
            lookup: "Plain",
            expected: None,
        },
        Case {
            name: "two variants renamed onto one wire value are ambiguous and dropped",
            rename_all: None,
            variants: vec![variant("First", Some("shared")), variant("Second", Some("shared"))],
            lookup: "shared",
            expected: None,
        },
        Case {
            name: "a wire value that is another variant's identifier is valid on both surfaces and dropped",
            rename_all: None,
            variants: vec![variant("Alpha", Some("Beta")), variant("Beta", None)],
            lookup: "Beta",
            expected: None,
        },
    ];

    for case in cases {
        let enums = vec![wire_variant_enum(case.rename_all, case.variants)];
        let map = build_ir_enum_map(&[], &enums);
        let got = map
            .enum_wire_variants
            .get("Kind")
            .and_then(|by_wire| by_wire.get(case.lookup))
            .map(String::as_str);
        assert_eq!(got, case.expected, "case '{}'", case.name);
    }
}