alef 0.79.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
use crate::backends::extendr::gen_bindings::ExtendrBackend;
use crate::backends::extendr::gen_bindings::bridges::{
    extendr_enum_variant_constructor_registrations, gen_extendr_enum_variant_constructors,
    gen_extendr_flat_data_enum_from_core, gen_extendr_flat_data_enum_struct, gen_extendr_flat_data_enum_to_core,
    gen_extendr_json_passthrough_enum_struct,
};
use crate::core::ir::{EnumDef, EnumVariant, FieldDef, MethodDef, PrimitiveType, TypeRef};

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

fn variant(name: &str, fields: Vec<FieldDef>) -> EnumVariant {
    EnumVariant {
        name: name.to_string(),
        fields,
        ..Default::default()
    }
}

/// A tagged data enum with struct variants — the JSON-passthrough shape.
fn shape_enum() -> EnumDef {
    EnumDef {
        name: "Shape".to_string(),
        rust_path: "test_lib::Shape".to_string(),
        variants: vec![
            variant("Circle", vec![field("radius", TypeRef::Primitive(PrimitiveType::F64))]),
            variant(
                "Rect",
                vec![
                    field("width", TypeRef::Primitive(PrimitiveType::F64)),
                    field("height", TypeRef::Primitive(PrimitiveType::F64)),
                ],
            ),
        ],
        serde_content: None,
        serde_tag: Some("type".to_string()),
        ..Default::default()
    }
}

#[test]
fn emits_constructor_per_struct_variant_building_core_then_into() {
    let core_path = "test_lib::Shape";
    let methods = gen_extendr_enum_variant_constructors(&shape_enum(), &ExtendrBackend, core_path, true);

    let code = methods.join("\n");
    assert!(code.contains("pub fn _factory_circle(radius: f64) -> Shape"), "{code}");
    assert!(code.contains("test_lib::Shape::Circle { radius }.into()"), "{code}");
    assert!(
        code.contains("pub fn _factory_rect(width: f64, height: f64) -> Shape"),
        "{code}"
    );
    assert!(
        code.contains("test_lib::Shape::Rect { width, height }.into()"),
        "{code}"
    );
}

#[test]
fn casts_remapped_primitive_back_to_core() {
    let def = EnumDef {
        name: "Sized_".to_string(),
        rust_path: "test_lib::Sized_".to_string(),
        variants: vec![variant(
            "Big",
            vec![field("count", TypeRef::Primitive(PrimitiveType::U64))],
        )],
        serde_content: None,
        serde_tag: Some("type".to_string()),
        ..Default::default()
    };
    let methods = gen_extendr_enum_variant_constructors(&def, &ExtendrBackend, "test_lib::Sized_", true);
    let code = methods.join("\n");
    assert!(code.contains("pub fn _factory_big(count: f64) -> Sized_"), "{code}");
    assert!(
        code.contains("test_lib::Sized_::Big { count: count as u64 }.into()"),
        "{code}"
    );
}

#[test]
fn skips_variant_constructor_with_named_dto_field() {
    // extendr derives `TryFrom<&Robj>` only for `&T` of #[extendr] types, never owned `T`, so a
    // `#[extendr]` proc-macro (`error[E0277]: T: TryFrom<&Robj> not satisfied`). Variants whose
    let def = EnumDef {
        name: "Wrapper".to_string(),
        rust_path: "test_lib::Wrapper".to_string(),
        variants: vec![
            variant("Llm", vec![field("llm", TypeRef::Named("LlmConfig".to_string()))]),
            variant("Tag", vec![field("name", TypeRef::String)]),
        ],
        serde_content: None,
        serde_tag: Some("type".to_string()),
        ..Default::default()
    };
    let methods = gen_extendr_enum_variant_constructors(&def, &ExtendrBackend, "test_lib::Wrapper", true);
    let code = methods.join("\n");
    assert!(
        !code.contains("_factory_llm"),
        "variant with a Named DTO field must be skipped: {code}"
    );
    assert!(
        code.contains("pub fn _factory_tag(name: String) -> Wrapper"),
        "primitive/String variant must still be generated: {code}"
    );
}

#[test]
fn skips_variant_constructor_when_any_field_is_unconstructible() {
    // field by value breaks the whole `#[extendr]` constructor.
    let def = EnumDef {
        name: "Job".to_string(),
        rust_path: "test_lib::Job".to_string(),
        variants: vec![
            variant(
                "Run",
                vec![
                    field("config", TypeRef::Named("RunConfig".to_string())),
                    field("retries", TypeRef::Primitive(PrimitiveType::U32)),
                    field("name", TypeRef::String),
                ],
            ),
            variant(
                "Tag",
                vec![field(
                    "entries",
                    TypeRef::Vec(Box::new(TypeRef::Named("Entry".to_string()))),
                )],
            ),
            variant("Ping", vec![field("seq", TypeRef::Primitive(PrimitiveType::U32))]),
        ],
        serde_content: None,
        serde_tag: Some("type".to_string()),
        ..Default::default()
    };
    let methods = gen_extendr_enum_variant_constructors(&def, &ExtendrBackend, "test_lib::Job", true);
    let code = methods.join("\n");
    assert!(
        !code.contains("_factory_run"),
        "Named-DTO-field variant must be skipped: {code}"
    );
    assert!(
        !code.contains("_factory_tag"),
        "Vec<DTO>-field variant must be skipped: {code}"
    );
    assert!(
        code.contains("test_lib::Job::Ping { seq: seq as u32 }.into()"),
        "primitive-only variant must still be generated: {code}"
    );
}

#[test]
fn skips_unit_tuple_and_excluded_variants() {
    let mut tuple_variant = variant("Pair", vec![field("_0", TypeRef::String)]);
    tuple_variant.is_tuple = true;
    let mut excluded = variant("Hidden", vec![field("value", TypeRef::String)]);
    excluded.binding_excluded = true;

    let def = EnumDef {
        name: "Mixed".to_string(),
        rust_path: "test_lib::Mixed".to_string(),
        variants: vec![
            variant("Empty", vec![]),
            tuple_variant,
            excluded,
            variant("Real", vec![field("value", TypeRef::String)]),
        ],
        serde_content: None,
        serde_tag: Some("type".to_string()),
        ..Default::default()
    };
    let methods = gen_extendr_enum_variant_constructors(&def, &ExtendrBackend, "test_lib::Mixed", true);
    let code = methods.join("\n");
    assert!(!code.contains("_factory_empty"), "{code}");
    assert!(!code.contains("_factory_pair"), "{code}");
    assert!(!code.contains("_factory_hidden"), "{code}");
    assert!(code.contains("pub fn _factory_real(value: String) -> Mixed"), "{code}");
}

/// Regression for the `ContentPart` bug: a hand-written inherent static method
/// (`enum_def.methods`, extracted from a separate `impl EnumType { .. }` block) is never forwarded
/// into the generated `#[extendr] impl` block, so suppressing the derived factory on a name
/// collision used to drop the constructor entirely (`ContentPart$text(...)` was unreachable from R).
/// Every data-carrying variant must always get a reachable factory.
#[test]
fn emits_factory_even_with_colliding_hand_written_method() {
    let def = EnumDef {
        methods: vec![MethodDef {
            name: "circle".to_string(),
            is_static: true,
            ..Default::default()
        }],
        ..shape_enum()
    };
    let methods = gen_extendr_enum_variant_constructors(&def, &ExtendrBackend, "test_lib::Shape", true);
    let code = methods.join("\n");
    assert!(
        code.contains("pub fn _factory_circle(radius: f64) -> Shape"),
        "Circle factory must stay reachable despite the colliding hand-written method: {code}"
    );
    assert!(code.contains("pub fn _factory_rect"), "{code}");
}

fn cfg_shape_enum(rust_path: &str) -> EnumDef {
    let mut gated = variant(
        "Rect",
        vec![
            field("width", TypeRef::Primitive(PrimitiveType::F64)),
            field("height", TypeRef::Primitive(PrimitiveType::F64)),
        ],
    );
    gated.cfg = Some(r#"feature = "extra-shapes""#.to_string());
    EnumDef {
        rust_path: rust_path.to_string(),
        variants: vec![
            variant("Circle", vec![field("radius", TypeRef::Primitive(PrimitiveType::F64))]),
            gated,
            variant("Point", vec![field("value", TypeRef::Primitive(PrimitiveType::F64))]),
        ],
        ..shape_enum()
    }
}

/// The factory body builds `<core_path>::<Variant> { .. }` directly (asserted by
/// `emits_constructor_per_struct_variant_building_core_then_into` above): a FOREIGN variant behind
/// a `#[cfg(...)]` this crate cannot declare as its own Cargo feature has no compile-safe fallback,
/// so its factory must be dropped entirely rather than reference a variant the dependency may not
/// have compiled in.
#[test]
fn drops_constructor_for_foreign_cfg_gated_variant() {
    let def = cfg_shape_enum("dep_crate::Shape");
    let methods = gen_extendr_enum_variant_constructors(&def, &ExtendrBackend, "dep_crate::Shape", false);
    let code = methods.join("\n");

    assert!(!code.contains("_factory_rect"), "{code}");
    assert!(code.contains("pub fn _factory_circle(radius: f64) -> Shape"), "{code}");
    assert!(code.contains("pub fn _factory_point(value: f64) -> Shape"), "{code}");
}

/// Control: the identical gate on a HOST-owned enum must never be dropped.
#[test]
fn keeps_constructor_for_host_owned_cfg_gated_variant() {
    let def = cfg_shape_enum("crate::Shape");
    let methods = gen_extendr_enum_variant_constructors(&def, &ExtendrBackend, "crate::Shape", true);
    let code = methods.join("\n");

    assert!(
        code.contains("pub fn _factory_rect(width: f64, height: f64) -> Shape"),
        "a host-owned cfg-gated variant's factory must stay reachable: {code}"
    );
}

/// `struct_embeds_constructors_in_impl_block` (below) exercises the same drop end-to-end through
/// `gen_extendr_json_passthrough_enum_struct`, which computes `is_host_enum` itself from
/// `core_import` -- this test pins that internal computation directly.
#[test]
fn struct_embeds_no_constructor_for_foreign_cfg_gated_variant() {
    let def = cfg_shape_enum("dep_crate::Shape");
    let code = gen_extendr_json_passthrough_enum_struct(&def, &ExtendrBackend, "crate");

    assert!(!code.contains("_factory_rect"), "{code}");
    assert!(code.contains("pub fn _factory_circle(radius: f64) -> Shape"), "{code}");
}

/// R-facing registrations must resolve the identical FOREIGN/host verdict as the Rust constructor
/// generator: registering an R wrapper for a name the Rust side dropped calls a
/// `wrap__<Name>___factory_<snake>` FFI symbol `extendr_module!` never registers.
#[test]
fn registrations_exclude_foreign_cfg_gated_variant() {
    let def = cfg_shape_enum("dep_crate::Shape");
    let regs = extendr_enum_variant_constructor_registrations(&def, false);
    let names: std::collections::BTreeSet<&str> = regs.iter().map(|(r_name, _, _)| r_name.as_str()).collect();

    assert_eq!(
        names,
        ["circle", "point"].into_iter().collect(),
        "registrations must exclude the dropped foreign cfg-gated `rect` variant: {regs:?}"
    );
}

#[test]
fn struct_embeds_constructors_in_impl_block() {
    // End to end: the generated `#[extendr] impl` block carries default/from_json AND the
    let code = gen_extendr_json_passthrough_enum_struct(&shape_enum(), &ExtendrBackend, "test_lib");
    assert!(code.contains("pub fn default() -> Shape"), "{code}");
    assert!(code.contains("pub fn from_json(json: String)"), "{code}");
    assert!(code.contains("pub fn _factory_circle(radius: f64) -> Shape"), "{code}");
}

#[test]
fn casts_optional_remapped_primitive_back_to_core() {
    let mut max_field = field("max", TypeRef::Primitive(PrimitiveType::U64));
    max_field.optional = true;
    let def = EnumDef {
        name: "Bounded".to_string(),
        rust_path: "test_lib::Bounded".to_string(),
        variants: vec![variant("Limit", vec![max_field])],
        serde_content: None,
        serde_tag: Some("type".to_string()),
        ..Default::default()
    };
    let methods = gen_extendr_enum_variant_constructors(&def, &ExtendrBackend, "test_lib::Bounded", true);
    let code = methods.join("\n");
    assert!(
        code.contains("pub fn _factory_limit(max: Option<f64>) -> Bounded"),
        "{code}"
    );
    assert!(
        code.contains("test_lib::Bounded::Limit { max: max.map(|v| v as u64) }.into()"),
        "{code}"
    );
}

#[test]
fn registrations_pair_r_name_with_factory_fn() {
    let regs = extendr_enum_variant_constructor_registrations(&shape_enum(), true);
    assert_eq!(
        regs,
        vec![
            (
                "circle".to_string(),
                "_factory_circle".to_string(),
                vec!["radius".to_string()]
            ),
            (
                "rect".to_string(),
                "_factory_rect".to_string(),
                vec!["width".to_string(), "height".to_string()]
            ),
        ]
    );
}

/// The R wrapper registration list must stay in lockstep with the generated `#[extendr]`
/// constructors: a colliding hand-written method must not drop the variant from either.
#[test]
fn registrations_include_variant_colliding_with_hand_written_method() {
    let def = EnumDef {
        methods: vec![MethodDef {
            name: "circle".to_string(),
            is_static: true,
            ..Default::default()
        }],
        ..shape_enum()
    };
    let regs = extendr_enum_variant_constructor_registrations(&def, true);
    assert_eq!(
        regs,
        vec![
            (
                "circle".to_string(),
                "_factory_circle".to_string(),
                vec!["radius".to_string()]
            ),
            (
                "rect".to_string(),
                "_factory_rect".to_string(),
                vec!["width".to_string(), "height".to_string()]
            ),
        ]
    );
}

#[test]
fn r_wrapper_binds_variant_constructor_under_snake_name() {
    use crate::core::backend::Backend;

    let backend = ExtendrBackend;
    let config = super::make_config();
    let mut api = super::make_api_surface();
    api.enums = vec![shape_enum()];

    let files = backend.generate_public_api(&api, &config).unwrap();
    let wrappers = files
        .iter()
        .find(|f| f.path.to_string_lossy().ends_with("extendr-wrappers.R"))
        .expect("extendr-wrappers.R must be generated");
    let content = &wrappers.content;

    assert!(
        content.contains("Shape$circle <- function(radius)"),
        "variant ctor must bind under the bare snake name: {content}"
    );
    assert!(
        content.contains(".Call(\"wrap__Shape___factory_circle\", radius"),
        "variant ctor must call the _factory_ symbol: {content}"
    );
    assert!(content.contains("Shape$rect <- function(width, height)"), "{content}");
    assert!(
        content.contains(".Call(\"wrap__Shape___factory_rect\", width, height"),
        "{content}"
    );
}

/// The discriminator field name a flat data enum's struct declares (`gen_extendr_flat_data_enum_struct`)
/// and the field its `From<core>`/`From<binding>` impls populate and read
/// (`gen_extendr_flat_data_enum_from_core`/`gen_extendr_flat_data_enum_to_core`) must be the exact
/// same string, whether it comes from the generic `"type"` fallback (`flat_data_enum_discriminator`
/// in `gen_bindings/bridges/mod.rs`) or an explicit `serde_tag`. All three call sites read that one
/// function instead of hard-coding the fallback independently, so a regression that reintroduces a
/// second hard-coded literal would surface here as a field name mismatch. ~keep
#[test]
fn flat_data_enum_discriminator_is_consistent_across_struct_and_from_impls() {
    let backend = ExtendrBackend;
    let lossy_skip_types: Vec<String> = vec![];
    let cfg = ExtendrBackend::binding_config("test_lib", &lossy_skip_types);

    let default_enum = EnumDef {
        name: "Payload".to_string(),
        rust_path: "test_lib::Payload".to_string(),
        variants: vec![variant("Text", vec![field("inner", TypeRef::String)])],
        serde_tag: None,
        ..Default::default()
    };

    let struct_src = gen_extendr_flat_data_enum_struct(&default_enum, &backend, &cfg, None);
    assert!(
        struct_src.contains("pub r#type: String"),
        "no explicit serde_tag should fall back to the generic `type` discriminator, not a \
         domain-specific default; got:\n{struct_src}"
    );

    let from_core = gen_extendr_flat_data_enum_from_core(&default_enum, "test_lib");
    assert!(
        from_core.contains("r#type: \"Text\".to_string()"),
        "From<core> impl must populate the exact field the struct declares; got:\n{from_core}"
    );

    let to_core = gen_extendr_flat_data_enum_to_core(&default_enum, "test_lib");
    assert!(
        to_core.contains("val.r#type.as_str()"),
        "From<binding> impl must dispatch on the exact field the struct declares; got:\n{to_core}"
    );

    let tagged_enum = EnumDef {
        serde_tag: Some("kind".to_string()),
        ..default_enum
    };
    let tagged_struct_src = gen_extendr_flat_data_enum_struct(&tagged_enum, &backend, &cfg, None);
    assert!(
        tagged_struct_src.contains("pub kind: String"),
        "an explicit serde_tag must be used verbatim as the discriminator field name; got:\n{tagged_struct_src}"
    );
    let tagged_from_core = gen_extendr_flat_data_enum_from_core(&tagged_enum, "test_lib");
    assert!(
        tagged_from_core.contains("kind: \"Text\".to_string()"),
        "an explicit serde_tag must thread into the From<core> impl too; got:\n{tagged_from_core}"
    );
}