alef 0.110.4

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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
use crate::codegen::naming::{PublicIdentifierKind, public_host_identifier};
use crate::core::config::{Language, ResolvedCrateConfig};
use crate::core::ir::{ApiSurface, EnumDef, FieldDef, PrimitiveType, TypeDef, TypeRef};
use std::collections::{BTreeSet, HashMap};

pub(super) fn find_r_options_type<'a>(api: &'a ApiSurface, config: &ResolvedCrateConfig) -> Option<&'a TypeDef> {
    config
        .trait_bridges_for(Language::R)
        .filter(|bridge| bridge.bind_via == crate::core::config::BridgeBinding::OptionsField)
        .filter_map(|bridge| bridge.options_type.as_deref())
        .find_map(|type_name| api.types.iter().find(|t| t.name == type_name && !t.is_trait))
        .or_else(|| find_r_options_type_from_api(api))
}

pub(super) fn find_r_options_type_from_api(api: &ApiSurface) -> Option<&TypeDef> {
    let input_type_names = crate::codegen::conversions::input_type_names(api);
    api.types
        .iter()
        .find(|t| !t.is_trait && t.has_default && input_type_names.contains(&t.name))
}

/// Generate the `options.R` file for the R package from the configured options IR type.
///
/// Produces a roxygen-documented `conversion_options()` helper function with one parameter per
/// field (all defaulting to `NULL`). R callers use named arguments to override individual
/// settings; unset parameters remain `NULL` and are omitted from the resulting list so that the
/// Rust side applies its own defaults.
pub(super) fn gen_conversion_options_r(opts_type: &TypeDef) -> String {
    let params: Vec<String> = opts_type
        .fields
        .iter()
        .map(|f| format!("{} = NULL", f.name.trim_start_matches('_')))
        .collect();

    let fields: Vec<minijinja::Value> = opts_type
        .fields
        .iter()
        .map(|field| {
            let rname = field.name.trim_start_matches('_');
            let doc_text = if field.doc.is_empty() {
                rname.to_string()
            } else {
                let first = field.doc.lines().next().unwrap_or(rname);
                first.trim_end_matches('.').to_string()
            };

            let needs_int = matches!(
                &field.ty,
                TypeRef::Primitive(PrimitiveType::U8)
                    | TypeRef::Primitive(PrimitiveType::U16)
                    | TypeRef::Primitive(PrimitiveType::U32)
                    | TypeRef::Primitive(PrimitiveType::U64)
                    | TypeRef::Primitive(PrimitiveType::I8)
                    | TypeRef::Primitive(PrimitiveType::I16)
                    | TypeRef::Primitive(PrimitiveType::I32)
                    | TypeRef::Primitive(PrimitiveType::I64)
                    | TypeRef::Primitive(PrimitiveType::Usize)
            );
            let assign_val = if needs_int {
                format!("as.integer({rname})")
            } else {
                rname.to_string()
            };

            crate::alef_context! {
                rname => rname,
                doc => doc_text,
                cfg => field.cfg.is_some(),
                assign_val => assign_val,
            }
        })
        .collect();

    crate::backends::extendr::template_env::render(
        "conversion_options.jinja",
        crate::alef_context! {
            params => params,
            fields => fields,
        },
    )
}

/// Generate the Rust-side `options.rs` module with `decode_options` function.
///
/// The `decode_options` function handles input from R in three main forms:
/// 1. ExternalPtr<T> (from $default() / builder methods) — unwraps and converts to core
/// 2. NULL — uses the configured options type's default
/// 3. Named list with field names matching struct fields — decodes field by field
///
/// This allows R callers to pass `OptionsType$default()`, NULL, or a named list.
pub(super) fn gen_options_rs(api: &ApiSurface, opts_type: &TypeDef, _core_import: &str) -> String {
    let mut code = String::new();
    code.push_str("//! Option decoding for R bindings.\n\n");
    code.push_str("use extendr_api::prelude::*;\n\n");

    let type_defs: HashMap<_, _> = api.types.iter().map(|t| (t.name.as_str(), t)).collect();
    let enum_defs: HashMap<_, _> = api.enums.iter().map(|e| (e.name.as_str(), e)).collect();

    let mut enum_decoders = BTreeSet::new();
    let mut struct_decoders = BTreeSet::new();
    for field in &opts_type.fields {
        collect_option_decoder_types(
            &field.ty,
            opts_type.name.as_str(),
            &type_defs,
            &enum_defs,
            &mut enum_decoders,
            &mut struct_decoders,
        );
    }

    code.push_str("/// Helper: extract and convert a value from an R list by name.\n");
    code.push_str("fn list_get(list: &List, key: &str) -> Option<Robj> {\n");
    code.push_str("    list.iter().find(|(n, _)| *n == key).map(|(_, v)| v)\n");
    code.push_str("}\n\n");

    for enum_name in enum_decoders {
        if let Some(enum_def) = enum_defs.get(enum_name.as_str()) {
            gen_enum_decoder(&mut code, enum_def);
        }
    }

    for struct_name in struct_decoders {
        if let Some(struct_def) = type_defs.get(struct_name.as_str()) {
            gen_struct_decoder(&mut code, struct_def, &enum_defs, &type_defs);
        }
    }

    code.push_str("/// Decode an R ExternalPtr, NULL, or named list into ");
    code.push_str(&opts_type.name);
    code.push_str(".\n");
    code.push_str("///\n");
    code.push_str("/// Accepts:\n");
    code.push_str("/// - ExternalPtr of the configured options type (from $default() or builder methods) — unwraps and converts\n");
    code.push_str("/// - NULL — returns the configured options type's default\n");
    code.push_str("/// - Named list with field names matching struct fields — decodes field by field\n");
    code.push_str("///\n");
    code.push_str("/// Fields are optional: omitted fields retain their defaults. Unknown fields are ignored.\n");
    code.push_str("pub fn decode_options(options: Robj) -> std::result::Result<crate::");
    code.push_str(&opts_type.name);
    code.push_str(", String> {\n");
    code.push_str("    if options.is_null() {\n");
    code.push_str("        return Ok(crate::");
    code.push_str(&opts_type.name);
    code.push_str("::default());\n");
    code.push_str("    }\n\n");

    code.push_str("    // Accept the wrapper struct returned by the options type's default() / builder methods,\n");
    code.push_str("    // which extendr exposes as an `ExternalPtr`. The binding struct is returned directly\n");
    code.push_str("    // from the #[extendr] impl methods, so unwrap it as the binding type.\n");
    code.push_str("    if let Ok(ext) = ExternalPtr::<crate::");
    code.push_str(&opts_type.name);
    code.push_str(">::try_from(&options) {\n");
    code.push_str("        return Ok((*ext).clone());\n");
    code.push_str("    }\n\n");

    code.push_str("    // Try to decode as a named list\n");
    code.push_str("    let list = List::try_from(&options)\n");
    code.push_str("        .map_err(|e| format!(\"options must be NULL, ExternalPtr, or named list: {e}\"))?;\n");
    code.push_str("    let mut opts = crate::");
    code.push_str(&opts_type.name);
    code.push_str("::default();\n\n");

    for field in &opts_type.fields {
        gen_field_decoder(&mut code, field, &enum_defs, &type_defs);
    }

    code.push_str(
        "    // Note: visitor field is skipped — R has no visitor concept, so it remains at default None\n\n",
    );
    code.push_str("    Ok(opts)\n");
    code.push_str("}\n");

    code
}

pub(super) fn collect_option_decoder_types(
    ty: &TypeRef,
    root_type_name: &str,
    type_defs: &HashMap<&str, &TypeDef>,
    enum_defs: &HashMap<&str, &EnumDef>,
    enum_decoders: &mut BTreeSet<String>,
    struct_decoders: &mut BTreeSet<String>,
) {
    let TypeRef::Named(name) = ty else {
        if let TypeRef::Optional(inner) = ty {
            collect_option_decoder_types(
                inner,
                root_type_name,
                type_defs,
                enum_defs,
                enum_decoders,
                struct_decoders,
            );
        }
        return;
    };
    if enum_defs.contains_key(name.as_str()) {
        enum_decoders.insert(name.clone());
        return;
    }
    let Some(type_def) = type_defs.get(name.as_str()) else {
        return;
    };
    if type_def.name == root_type_name || type_def.is_opaque || type_def.is_trait {
        return;
    }
    if struct_decoders.insert(type_def.name.clone()) {
        for field in &type_def.fields {
            collect_option_decoder_types(
                &field.ty,
                root_type_name,
                type_defs,
                enum_defs,
                enum_decoders,
                struct_decoders,
            );
        }
    }
}

/// Generate an enum decoder function for the given enum definition.
pub(super) fn gen_enum_decoder(code: &mut String, enum_def: &EnumDef) {
    if enum_def.variants.iter().any(|variant| !variant.fields.is_empty()) {
        return;
    }

    let enum_name = &enum_def.name;
    let field_name_snake = r_function_component(enum_name);
    let fn_name = format!("decode_{}", field_name_snake);

    code.push_str("/// Decode a ");
    code.push_str(&field_name_snake.replace('_', " "));
    code.push_str(" enum from its string representation.\n");
    code.push_str("fn ");
    code.push_str(&fn_name);
    code.push_str("(val: Robj) -> std::result::Result<crate::");
    code.push_str(enum_name);
    code.push_str(", String> {\n");
    code.push_str("    let s = String::try_from(&val).map_err(|e| format!(\"");
    code.push_str(&field_name_snake);
    code.push_str(": {e}\"))?;\n");
    code.push_str("    match s.as_str() {\n");

    for variant in &enum_def.variants {
        code.push_str("        \"");
        code.push_str(&variant.name);
        code.push_str("\" => Ok(crate::");
        code.push_str(enum_name);
        code.push_str("::");
        code.push_str(&variant.name);
        code.push_str("),\n");
    }

    code.push_str("        _ => Err(format!(\"");
    code.push_str(&field_name_snake);
    code.push_str(": unknown variant '{}'\", s)),\n");
    code.push_str("    }\n");
    code.push_str("}\n\n");
}

/// Generate decoder for a nested options struct.
pub(super) fn gen_struct_decoder(
    code: &mut String,
    typ: &TypeDef,
    enum_defs: &HashMap<&str, &EnumDef>,
    type_defs: &HashMap<&str, &TypeDef>,
) {
    let decoder_name = format!("decode_{}", r_function_component(&typ.name));
    let label = r_function_component(&typ.name);
    code.push_str("/// Decode ");
    code.push_str(&typ.name);
    code.push_str(" from an R list.\n");
    code.push_str("fn ");
    code.push_str(&decoder_name);
    code.push_str("(val: Robj) -> std::result::Result<crate::");
    code.push_str(&typ.name);
    code.push_str(", String> {\n");
    code.push_str("    if val.is_null() {\n");
    code.push_str("        return Ok(crate::");
    code.push_str(&typ.name);
    code.push_str("::default());\n");
    code.push_str("    }\n");
    code.push_str("    let list = List::try_from(&val).map_err(|e| format!(\"");
    code.push_str(&label);
    code.push_str(": {e}\"))?;\n");
    code.push_str("    let mut opts = crate::");
    code.push_str(&typ.name);
    code.push_str("::default();\n\n");

    for field in &typ.fields {
        gen_field_decoder(code, field, enum_defs, type_defs);
    }

    code.push_str("    Ok(opts)\n");
    code.push_str("}\n\n");
}

/// Map a core type to its binding type for the R extendr backend.
/// This applies the type transformations used in the binding layer:
/// - u64, i64, usize, isize -> f64
/// - Other primitives stay the same
/// - Optional wrapping is preserved
pub(super) fn map_type_to_binding(ty: &TypeRef) -> TypeRef {
    match ty {
        TypeRef::Primitive(
            _prim @ (PrimitiveType::U64 | PrimitiveType::I64 | PrimitiveType::Usize | PrimitiveType::Isize),
        ) => TypeRef::Primitive(PrimitiveType::F64),
        TypeRef::Optional(inner) => TypeRef::Optional(Box::new(map_type_to_binding(inner))),
        other => other.clone(),
    }
}

/// Generate field decoding logic for a single field.
///
/// `FieldDef` carries optionality in two places: `ty` is `TypeRef::Optional` only for a nested
/// option (`Option<Option<T>>`), while a plain `Option<T>` is recorded as `ty: T` with
/// `optional: true`. The struct emitter reads the flag and declares `Option<T>`; this decoder
/// matched on `ty` alone and so assigned a bare `T` into it. For the first `Option<String>` field
/// on an options struct that produced
/// `opts.<field> = String::try_from(&v)...?;` — `error[E0308]: expected Option<String>, found
/// String`, which broke the whole R package build. Nothing had exercised the combination before,
/// because it needs a plain `Option<T>` on a struct the named-list decoder handles. ~keep
pub(super) fn gen_field_decoder(
    code: &mut String,
    field: &FieldDef,
    enum_defs: &HashMap<&str, &EnumDef>,
    type_defs: &HashMap<&str, &TypeDef>,
) {
    if field.name == "visitor" {
        return;
    }

    // ~keep Emit into a buffer so the assignment can be wrapped once, uniformly, instead of
    // teaching each of the ten type arms about optionality. The wrap is idempotent: some arms
    // (the `optional_numeric_field` template) already emit `Some(...)` themselves, and keying the
    // decision off `field.ty` instead got that wrong — `Option<usize>` reaches the numeric arm
    // through `map_type_to_binding`, not as a `TypeRef::Optional`, so it produced
    // `Some(Some(f64_val))`. Deciding from the emitted text is what holds for every arm.
    if field.optional {
        let mut decoded = String::new();
        gen_field_decoder_unwrapped(&mut decoded, field, enum_defs, type_defs);
        code.push_str(&wrap_assigned_value_in_some(&decoded, &field.name));
        return;
    }
    gen_field_decoder_unwrapped(code, field, enum_defs, type_defs);
}

/// Wrap the right-hand side of `opts.<field> = <value>;` in `Some(...)`, unless it already is.
///
/// Operates on this module's own output, where the assignment is always a single line ending in
/// `;`, so the value is exactly the text between the `= ` and that terminator. A decoder that
/// emits no assignment at all (an unsupported type falling through to `_ => {}`) is returned
/// unchanged rather than silently corrupted, and a value the arm already wrapped is left alone so
/// the transform cannot produce `Some(Some(_))`. ~keep
fn wrap_assigned_value_in_some(decoded: &str, field_name: &str) -> String {
    let assignment = format!("opts.{field_name} = ");
    let mut out = String::with_capacity(decoded.len() + 8);
    for line in decoded.split_inclusive('\n') {
        match line.find(&assignment).and_then(|start| {
            let value_start = start + assignment.len();
            line.rfind(';')
                .filter(|end| *end > value_start)
                .map(|end| (value_start, end))
        }) {
            Some((value_start, end)) if !line[value_start..end].starts_with("Some(") => {
                out.push_str(&line[..value_start]);
                out.push_str("Some(");
                out.push_str(&line[value_start..end]);
                out.push(')');
                out.push_str(&line[end..]);
            }
            Some(_) => out.push_str(line),
            None => out.push_str(line),
        }
    }
    out
}

fn gen_field_decoder_unwrapped(
    code: &mut String,
    field: &FieldDef,
    enum_defs: &HashMap<&str, &EnumDef>,
    type_defs: &HashMap<&str, &TypeDef>,
) {
    let binding_ty = map_type_to_binding(&field.ty);

    let field_name = &field.name;
    let field_name_trim = field_name.trim_start_matches('_');

    match &binding_ty {
        TypeRef::Primitive(PrimitiveType::Bool) => {
            code.push_str("    if let Some(v) = list_get(&list, \"");
            code.push_str(field_name_trim);
            code.push_str("\") {\n");
            code.push_str("        opts.");
            code.push_str(field_name);
            code.push_str(" = bool::try_from(&v).map_err(|e| format!(\"");
            code.push_str(field_name_trim);
            code.push_str(": {e}\"))?;\n");
            code.push_str("    }\n");
        }
        TypeRef::String => {
            code.push_str("    if let Some(v) = list_get(&list, \"");
            code.push_str(field_name_trim);
            code.push_str("\") {\n");
            code.push_str("        opts.");
            code.push_str(field_name);
            code.push_str(" = String::try_from(&v).map_err(|e| format!(\"");
            code.push_str(field_name_trim);
            code.push_str(": {e}\"))?;\n");
            code.push_str("    }\n");
        }
        TypeRef::Char => {
            code.push_str("    if let Some(v) = list_get(&list, \"");
            code.push_str(field_name_trim);
            code.push_str("\") {\n");
            code.push_str("        opts.");
            code.push_str(field_name);
            code.push_str(" = String::try_from(&v).map_err(|e| format!(\"");
            code.push_str(field_name_trim);
            code.push_str(": {e}\"))?;\n");
            code.push_str("    }\n");
        }
        TypeRef::Primitive(
            prim @ (PrimitiveType::U8
            | PrimitiveType::U16
            | PrimitiveType::U32
            | PrimitiveType::I8
            | PrimitiveType::I16
            | PrimitiveType::I32),
        ) => {
            let ty = match prim {
                PrimitiveType::U8 => "u8",
                PrimitiveType::U16 => "u16",
                PrimitiveType::U32 => "u32",
                PrimitiveType::I8 => "i8",
                PrimitiveType::I16 => "i16",
                PrimitiveType::I32 => "i32",
                _ => unreachable!(),
            };
            code.push_str("    if let Some(v) = list_get(&list, \"");
            code.push_str(field_name_trim);
            code.push_str("\") {\n");
            code.push_str("        opts.");
            code.push_str(field_name);
            code.push_str(" = ");
            code.push_str(ty);
            code.push_str("::try_from(&v).map_err(|e| format!(\"");
            code.push_str(field_name_trim);
            code.push_str(": {e}\"))?;\n");
            code.push_str("    }\n");
        }
        TypeRef::Primitive(
            prim @ (PrimitiveType::U64 | PrimitiveType::I64 | PrimitiveType::Usize | PrimitiveType::Isize),
        ) => {
            let core_ty = match prim {
                PrimitiveType::U64 => "u64",
                PrimitiveType::I64 => "i64",
                PrimitiveType::Usize => "usize",
                PrimitiveType::Isize => "isize",
                _ => unreachable!(),
            };
            if field.optional {
                code.push_str(&gen_optional_numeric_field(field, "f64", Some(core_ty)));
                return;
            }
            code.push_str("    if let Some(v) = list_get(&list, \"");
            code.push_str(field_name_trim);
            code.push_str("\") {\n");
            code.push_str("        let f64_val = f64::try_from(&v).map_err(|e| format!(\"");
            code.push_str(field_name_trim);
            code.push_str(": {e}\"))?;\n");
            code.push_str("        opts.");
            code.push_str(field_name);
            code.push_str(" = f64_val as ");
            code.push_str(core_ty);
            code.push_str(";\n");
            code.push_str("    }\n");
        }
        TypeRef::Primitive(PrimitiveType::F32 | PrimitiveType::F64) => {
            let ty = match &binding_ty {
                TypeRef::Primitive(PrimitiveType::F32) => "f32",
                _ => "f64",
            };
            if field.optional {
                code.push_str(&gen_optional_numeric_field(field, ty, None));
                return;
            }
            code.push_str("    if let Some(v) = list_get(&list, \"");
            code.push_str(field_name_trim);
            code.push_str("\") {\n");
            code.push_str("        opts.");
            code.push_str(field_name);
            code.push_str(" = ");
            code.push_str(ty);
            code.push_str("::try_from(&v).map_err(|e| format!(\"");
            code.push_str(field_name_trim);
            code.push_str(": {e}\"))?;\n");
            code.push_str("    }\n");
        }
        TypeRef::Vec(inner) => {
            if matches!(inner.as_ref(), TypeRef::String) {
                code.push_str("    if let Some(v) = list_get(&list, \"");
                code.push_str(field_name_trim);
                code.push_str("\") {\n");
                code.push_str("        let strings = Strings::try_from(&v).map_err(|e| format!(\"");
                code.push_str(field_name_trim);
                code.push_str(": {e}\"))?;\n");
                code.push_str("        let vec: Vec<String> = strings\n");
                code.push_str("            .iter()\n");
                code.push_str("            .map(|s| s.to_string())\n");
                code.push_str("            .collect();\n");
                code.push_str("        opts.");
                code.push_str(field_name);
                code.push_str(" = vec;\n");
                code.push_str("    }\n");
            }
        }
        TypeRef::Named(enum_name)
            if (enum_defs.contains_key(enum_name.as_str()) || type_defs.contains_key(enum_name.as_str())) =>
        {
            let fn_name = format!("decode_{}", r_function_component(enum_name));
            code.push_str("    if let Some(v) = list_get(&list, \"");
            code.push_str(field_name_trim);
            code.push_str("\") {\n");
            code.push_str("        opts.");
            code.push_str(field_name);
            code.push_str(" = ");
            code.push_str(&fn_name);
            code.push_str("(v)?;\n");
            code.push_str("    }\n");
        }
        TypeRef::Optional(inner) => match inner.as_ref() {
            TypeRef::Named(name) if enum_defs.contains_key(name.as_str()) => {
                let fn_name = format!("decode_{}", r_function_component(name));
                code.push_str("    if let Some(v) = list_get(&list, \"");
                code.push_str(field_name_trim);
                code.push_str("\") {\n");
                code.push_str("        opts.");
                code.push_str(field_name);
                code.push_str(" = Some(");
                code.push_str(&fn_name);
                code.push_str("(v)?);\n");
                code.push_str("    }\n");
            }
            TypeRef::Named(name) if type_defs.contains_key(name.as_str()) => {
                let fn_name = format!("decode_{}", r_function_component(name));
                code.push_str("    if let Some(v) = list_get(&list, \"");
                code.push_str(field_name_trim);
                code.push_str("\") {\n");
                code.push_str("        opts.");
                code.push_str(field_name);
                code.push_str(" = Some(");
                code.push_str(&fn_name);
                code.push_str("(v)?);\n");
                code.push_str("    }\n");
            }
            TypeRef::Primitive(
                prim @ (PrimitiveType::U64
                | PrimitiveType::I64
                | PrimitiveType::Usize
                | PrimitiveType::Isize
                | PrimitiveType::F64),
            ) => {
                let cast_type = match prim {
                    PrimitiveType::U64 => Some("u64"),
                    PrimitiveType::I64 => Some("i64"),
                    PrimitiveType::Usize => Some("usize"),
                    PrimitiveType::Isize => Some("isize"),
                    PrimitiveType::F64 => None,
                    _ => unreachable!(),
                };
                code.push_str(&gen_optional_numeric_field(field, "f64", cast_type));
            }
            _ => {}
        },
        _ => {}
    }
}

/// Convert a CamelCase type name to snake_case for function names.
fn r_function_component(name: &str) -> String {
    public_host_identifier(Language::R, PublicIdentifierKind::Function, name)
}

fn gen_optional_numeric_field(field: &FieldDef, decode_type: &str, cast_type: Option<&str>) -> String {
    crate::backends::extendr::template_env::render(
        "optional_numeric_field.jinja",
        crate::alef_context! {
            field_name => &field.name,
            lookup_name => field.name.trim_start_matches('_'),
            decode_type => decode_type,
            cast_type => cast_type,
        },
    )
}

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

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

    fn decode(field: &FieldDef) -> String {
        let mut code = String::new();
        gen_field_decoder(&mut code, field, &HashMap::new(), &HashMap::new());
        code
    }

    /// `ConversionOptions::base_url` — the shape that broke the R package build. The struct
    /// emitter declares `Option<String>` from `optional: true`, so the decoder must assign a
    /// `Some(...)` or the generated crate does not compile. ~keep
    #[test]
    fn an_optional_string_field_is_assigned_as_some() {
        let decoded = decode(&field("base_url", TypeRef::String, true));

        assert!(
            decoded.contains("opts.base_url = Some(String::try_from(&v).map_err(|e| format!(\"base_url: {e}\"))?);"),
            "optional string must be wrapped, got:\n{decoded}"
        );
    }

    #[test]
    fn a_required_string_field_is_assigned_bare() {
        let decoded = decode(&field("output_format", TypeRef::String, false));

        assert!(
            decoded.contains("opts.output_format = String::try_from(&v)"),
            "required string must not be wrapped, got:\n{decoded}"
        );
        // ~keep Assert on the assignment, not the whole block: every arm opens with
        // `if let Some(v) = list_get(...)`, so a bare `contains("Some(")` is true regardless.
        assert!(
            !decoded.contains("opts.output_format = Some("),
            "required string must not be wrapped, got:\n{decoded}"
        );
    }

    #[test]
    fn an_optional_bool_and_an_optional_string_vec_are_also_wrapped() {
        let boolean = decode(&field("wrap", TypeRef::Primitive(PrimitiveType::Bool), true));
        assert!(
            boolean.contains("opts.wrap = Some(bool::try_from(&v)"),
            "got:\n{boolean}"
        );

        let strings = decode(&field("strip_tags", TypeRef::Vec(Box::new(TypeRef::String)), true));
        assert!(strings.contains("opts.strip_tags = Some(vec);"), "got:\n{strings}");
    }

    /// A type the decoder has no arm for emits nothing; the wrapper must not invent an assignment
    /// or corrupt the empty output. ~keep
    #[test]
    fn an_unsupported_optional_type_emits_nothing_rather_than_broken_code() {
        let decoded = decode(&field("visitor_hooks", TypeRef::Vec(Box::new(TypeRef::Char)), true));

        assert_eq!(decoded, "", "unsupported type must stay empty, got:\n{decoded}");
    }

    /// An optional numeric reaches the `optional_numeric_field` template, which emits its own
    /// `Some(...)`. This is the case that produced `Some(Some(f64_val))` and failed to compile
    /// when the wrap was keyed off `field.ty` instead of the emitted text. ~keep
    #[test]
    fn an_optional_numeric_is_not_double_wrapped() {
        for ty in [
            TypeRef::Primitive(PrimitiveType::Usize),
            TypeRef::Optional(Box::new(TypeRef::Primitive(PrimitiveType::Usize))),
        ] {
            let decoded = decode(&field("max_depth", ty, true));

            assert!(!decoded.contains("Some(Some("), "must not double-wrap, got:\n{decoded}");
            assert!(
                decoded.contains("opts.max_depth = Some("),
                "must still wrap once, got:\n{decoded}"
            );
        }
    }
}