alef 0.25.13

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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
use super::*;
use crate::core::ir::*;
use ahash::AHashSet;

fn simple_type() -> TypeDef {
    TypeDef {
        name: "Config".to_string(),
        rust_path: "my_crate::Config".to_string(),
        original_rust_path: String::new(),
        fields: vec![
            FieldDef {
                name: "name".into(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                doc: String::new(),
                sanitized: false,
                is_boxed: false,
                type_rust_path: None,
                cfg: None,
                typed_default: None,
                core_wrapper: CoreWrapper::None,
                vec_inner_core_wrapper: CoreWrapper::None,
                newtype_wrapper: None,
                serde_rename: None,
                serde_flatten: false,
                binding_excluded: false,
                binding_exclusion_reason: None,
                original_type: None,
            },
            FieldDef {
                name: "timeout".into(),
                ty: TypeRef::Primitive(PrimitiveType::U64),
                optional: true,
                default: None,
                doc: String::new(),
                sanitized: false,
                is_boxed: false,
                type_rust_path: None,
                cfg: None,
                typed_default: None,
                core_wrapper: CoreWrapper::None,
                vec_inner_core_wrapper: CoreWrapper::None,
                newtype_wrapper: None,
                serde_rename: None,
                serde_flatten: false,
                binding_excluded: false,
                binding_exclusion_reason: None,
                original_type: None,
            },
            FieldDef {
                name: "backend".into(),
                ty: TypeRef::Named("Backend".into()),
                optional: true,
                default: None,
                doc: String::new(),
                sanitized: false,
                is_boxed: false,
                type_rust_path: None,
                cfg: None,
                typed_default: None,
                core_wrapper: CoreWrapper::None,
                vec_inner_core_wrapper: CoreWrapper::None,
                newtype_wrapper: None,
                serde_rename: None,
                serde_flatten: false,
                binding_excluded: false,
                binding_exclusion_reason: None,
                original_type: None,
            },
        ],
        methods: vec![],
        is_opaque: false,
        is_clone: true,
        is_copy: false,
        is_trait: false,
        has_default: false,
        has_stripped_cfg_fields: false,
        is_return_type: false,
        serde_rename_all: None,
        has_serde: false,
        super_traits: vec![],
        doc: String::new(),
        cfg: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        is_variant_wrapper: false,
        has_lifetime_params: false,
        version: Default::default(),
    }
}

fn simple_enum() -> EnumDef {
    EnumDef {
        name: "Backend".to_string(),
        rust_path: "my_crate::Backend".to_string(),
        original_rust_path: String::new(),
        variants: vec![
            EnumVariant {
                name: "Cpu".into(),
                fields: vec![],
                doc: String::new(),
                is_default: false,
                serde_rename: None,
                binding_excluded: false,
                binding_exclusion_reason: None,
                is_tuple: false,
                originally_had_data_fields: false,
                cfg: None,
                version: Default::default(),
            },
            EnumVariant {
                name: "Gpu".into(),
                fields: vec![],
                doc: String::new(),
                is_default: false,
                serde_rename: None,
                binding_excluded: false,
                binding_exclusion_reason: None,
                is_tuple: false,
                originally_had_data_fields: false,
                cfg: None,
                version: Default::default(),
            },
        ],
        doc: String::new(),
        cfg: None,
        is_copy: false,
        has_serde: false,
        serde_tag: None,
        serde_untagged: false,
        serde_rename_all: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        excluded_variants: vec![],
        version: Default::default(),
    }
}

#[test]
fn test_from_binding_to_core() {
    let typ = simple_type();
    let result = gen_from_binding_to_core(&typ, "my_crate");
    assert!(result.contains("impl From<Config> for my_crate::Config"));
    assert!(result.contains("name: val.name"));
    assert!(result.contains("timeout: val.timeout"));
    assert!(result.contains("backend: val.backend.map(Into::into)"));
}

#[test]
fn test_from_core_to_binding() {
    let typ = simple_type();
    let result = gen_from_core_to_binding(&typ, "my_crate", &AHashSet::new());
    assert!(result.contains("impl From<my_crate::Config> for Config"));
}

#[test]
fn test_enum_from_binding_to_core() {
    let enum_def = simple_enum();
    let result = gen_enum_from_binding_to_core(&enum_def, "my_crate");
    assert!(result.contains("impl From<Backend> for my_crate::Backend"));
    assert!(result.contains("Backend::Cpu => Self::Cpu"));
    assert!(result.contains("Backend::Gpu => Self::Gpu"));
}

#[test]
fn test_enum_from_core_to_binding() {
    let enum_def = simple_enum();
    let result = gen_enum_from_core_to_binding(&enum_def, "my_crate");
    assert!(result.contains("impl From<my_crate::Backend> for Backend"));
    assert!(result.contains("my_crate::Backend::Cpu => Self::Cpu"));
    assert!(result.contains("my_crate::Backend::Gpu => Self::Gpu"));
}

#[test]
fn test_enum_from_core_to_binding_no_excluded_variants_no_catchall() {
    let enum_def = simple_enum();
    let result = gen_enum_from_core_to_binding(&enum_def, "my_crate");
    assert!(
        !result.contains("_ => Default::default()"),
        "catch-all arm should not be emitted when there are no excluded variants"
    );
}

#[test]
fn test_enum_from_binding_to_core_no_excluded_variants_no_catchall() {
    let enum_def = simple_enum();
    let result = gen_enum_from_binding_to_core(&enum_def, "my_crate");
    assert!(
        !result.contains("_ => Default::default()"),
        "catch-all arm should not be emitted when there are no excluded variants"
    );
}

#[test]
fn test_enum_from_core_to_binding_with_excluded_variants_has_catchall() {
    let mut enum_def = simple_enum();
    enum_def.excluded_variants.push(EnumVariant {
        name: "Tpu".into(),
        fields: vec![],
        doc: String::new(),
        is_default: false,
        serde_rename: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        is_tuple: false,
        originally_had_data_fields: false,
        cfg: None,
        version: Default::default(),
    });
    let result = gen_enum_from_core_to_binding(&enum_def, "my_crate");
    assert!(
        result.contains("_ => Default::default()"),
        "catch-all arm should be emitted when there are excluded variants"
    );
}

#[test]
fn test_enum_from_binding_to_core_with_excluded_variants_no_catchall() {
    // From<BindingEnum> for CoreEnum matches on the *binding* type, which never
    // contains excluded variants — the match is always exhaustive. A wildcard
    // arm would be unreachable and must not be emitted even when the core enum
    // has excluded (binding-skipped) variants.
    let mut enum_def = simple_enum();
    enum_def.excluded_variants.push(EnumVariant {
        name: "Tpu".into(),
        fields: vec![],
        doc: String::new(),
        is_default: false,
        serde_rename: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        is_tuple: false,
        originally_had_data_fields: false,
        cfg: None,
        version: Default::default(),
    });
    let result = gen_enum_from_binding_to_core(&enum_def, "my_crate");
    assert!(
        !result.contains("_ => Default::default()"),
        "catch-all arm must not be emitted for From<BindingEnum>→core; the binding match is always exhaustive"
    );
}

#[test]
fn test_enum_from_core_to_binding_unit_only_with_struct_variants_no_catchall() {
    // Regression: when the binding is unit-only (binding_enums_have_data=false) but the
    // core enum has named-field (struct) variants, every variant still gets its own
    // explicit arm (`CoreT::V { .. } => Self::V,`).  The match is exhaustive; emitting
    // `_ => Default::default()` produces an "unreachable pattern" error under -D warnings.
    let mut enum_def = simple_enum();
    // Add a named-field (struct) variant to simulate e.g. WebSocketMessage::Close { code, reason }.
    enum_def.variants.push(EnumVariant {
        name: "Disconnect".into(),
        fields: vec![FieldDef {
            name: "code".into(),
            ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::U16),
            optional: false,
            default: None,
            doc: String::new(),
            sanitized: false,
            is_boxed: false,
            type_rust_path: None,
            cfg: None,
            typed_default: None,
            core_wrapper: CoreWrapper::None,
            vec_inner_core_wrapper: CoreWrapper::None,
            newtype_wrapper: None,
            serde_rename: None,
            serde_flatten: false,
            binding_excluded: false,
            binding_exclusion_reason: None,
            original_type: None,
        }],
        doc: String::new(),
        is_default: false,
        serde_rename: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        is_tuple: false,
        originally_had_data_fields: false,
        cfg: None,
        version: Default::default(),
    });
    // Unit-only binding (default config has binding_enums_have_data=false).
    let result = gen_enum_from_core_to_binding(&enum_def, "my_crate");
    assert!(
        !result.contains("_ => Default::default()"),
        "catch-all must not be emitted when all core variants are covered by explicit arms; got:\n{result}"
    );
    // The struct variant must still get its own arm (not silently dropped).
    assert!(
        result.contains("Backend::Disconnect { .. } => Self::Disconnect"),
        "struct variant must have an explicit arm; got:\n{result}"
    );
}

fn untagged_tuple_enum() -> EnumDef {
    EnumDef {
        name: "UserContent".to_string(),
        rust_path: "my_crate::UserContent".to_string(),
        original_rust_path: String::new(),
        variants: vec![
            EnumVariant {
                name: "Text".into(),
                fields: vec![FieldDef {
                    name: "_0".into(),
                    ty: TypeRef::String,
                    optional: false,
                    default: None,
                    doc: String::new(),
                    sanitized: false,
                    is_boxed: false,
                    type_rust_path: None,
                    cfg: None,
                    typed_default: None,
                    core_wrapper: CoreWrapper::None,
                    vec_inner_core_wrapper: CoreWrapper::None,
                    newtype_wrapper: None,
                    serde_rename: None,
                    serde_flatten: false,
                    binding_excluded: false,
                    binding_exclusion_reason: None,
                    original_type: None,
                }],
                is_tuple: true,
                doc: String::new(),
                is_default: false,
                serde_rename: None,
                binding_excluded: false,
                binding_exclusion_reason: None,
                originally_had_data_fields: false,
                cfg: None,
                version: Default::default(),
            },
            EnumVariant {
                name: "Parts".into(),
                fields: vec![FieldDef {
                    name: "_0".into(),
                    ty: TypeRef::Vec(Box::new(TypeRef::String)),
                    optional: false,
                    default: None,
                    doc: String::new(),
                    sanitized: false,
                    is_boxed: false,
                    type_rust_path: None,
                    cfg: None,
                    typed_default: None,
                    core_wrapper: CoreWrapper::None,
                    vec_inner_core_wrapper: CoreWrapper::None,
                    newtype_wrapper: None,
                    serde_rename: None,
                    serde_flatten: false,
                    binding_excluded: false,
                    binding_exclusion_reason: None,
                    original_type: None,
                }],
                is_tuple: true,
                doc: String::new(),
                is_default: false,
                serde_rename: None,
                binding_excluded: false,
                binding_exclusion_reason: None,
                originally_had_data_fields: false,
                cfg: None,
                version: Default::default(),
            },
        ],
        doc: String::new(),
        cfg: None,
        is_copy: false,
        has_serde: true,
        serde_tag: None,
        serde_untagged: true,
        serde_rename_all: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        excluded_variants: vec![],
        version: Default::default(),
    }
}

#[test]
fn test_enum_from_binding_to_core_untagged_tuple_emits_tuple_pattern() {
    // Regression: untagged enums with tuple variants emit tuple-form `Variant(T)` in
    // the binding (Magnus template since commit a715f378). Conversion match arms must
    // destructure tuple-form, not struct-form `Variant { _0 }`.
    let enum_def = untagged_tuple_enum();
    let config = ConversionConfig {
        binding_enums_have_data: true,
        binding_tuple_form_for_untagged_variants: true,
        ..ConversionConfig::default()
    };
    let result = gen_enum_from_binding_to_core_cfg(&enum_def, "my_crate", &config);
    // MUST destructure as tuple, not struct
    assert!(
        result.contains("UserContent::Text(_0)"),
        "expected tuple-form binding pattern, got: {result}"
    );
    assert!(
        !result.contains("UserContent::Text { _0 }"),
        "must NOT use struct-form for untagged enums, got: {result}"
    );
    // Construct core as tuple
    assert!(result.contains("Self::Text("));
}

#[test]
fn test_enum_from_core_to_binding_untagged_tuple_emits_tuple_constructor() {
    // Regression: untagged enums with tuple variants emit tuple-form `Variant(T)` in
    // the binding. Constructor must use tuple form, not `Self::Variant { _0 }`.
    let enum_def = untagged_tuple_enum();
    let config = ConversionConfig {
        binding_enums_have_data: true,
        binding_tuple_form_for_untagged_variants: true,
        ..ConversionConfig::default()
    };
    let result = gen_enum_from_core_to_binding_cfg(&enum_def, "my_crate", &config);
    // Core destructured as tuple (already correct), binding constructed as tuple
    assert!(
        result.contains("my_crate::UserContent::Text(_0) => Self::Text("),
        "expected tuple-form binding constructor, got: {result}"
    );
    assert!(
        !result.contains("Self::Text { _0 }"),
        "must NOT use struct-form constructor for untagged enums, got: {result}"
    );
}

#[test]
fn test_enum_tagged_data_keeps_struct_form_pattern() {
    // Counter-regression: tagged (non-untagged) data enums must keep struct-form
    // `Variant { _0 }` pattern/constructor — only untagged enums switch to tuple form.
    let mut enum_def = untagged_tuple_enum();
    enum_def.serde_untagged = false;
    enum_def.serde_tag = Some("type".to_string());
    let config = ConversionConfig {
        binding_enums_have_data: true,
        binding_tuple_form_for_untagged_variants: true,
        ..ConversionConfig::default()
    };
    let result = gen_enum_from_binding_to_core_cfg(&enum_def, "my_crate", &config);
    assert!(
        result.contains("UserContent::Text { _0 }"),
        "tagged enums must keep struct-form, got: {result}"
    );
}

#[test]
fn test_enum_untagged_keeps_struct_form_when_backend_does_not_opt_in() {
    // Counter-regression for the Rustler backend: untagged enums must remain in
    // struct-form when the backend's enum body emitter does not switch to tuple
    // form (every backend except Magnus). `binding_tuple_form_for_untagged_variants`
    // is the opt-in flag.
    let enum_def = untagged_tuple_enum();
    let config = ConversionConfig {
        binding_enums_have_data: true,
        binding_tuple_form_for_untagged_variants: false,
        ..ConversionConfig::default()
    };
    let result = gen_enum_from_binding_to_core_cfg(&enum_def, "my_crate", &config);
    assert!(
        result.contains("UserContent::Text { _0 }"),
        "backends without the opt-in must keep struct-form, got: {result}"
    );
    let result2 = gen_enum_from_core_to_binding_cfg(&enum_def, "my_crate", &config);
    assert!(
        result2.contains("Self::Text { _0:"),
        "backends without the opt-in must construct struct-form, got: {result2}"
    );
}

#[test]
fn test_from_binding_to_core_with_cfg_gated_field() {
    // Create a type with a cfg-gated field
    let mut typ = simple_type();
    typ.has_stripped_cfg_fields = true;
    typ.fields.push(FieldDef {
        name: "layout".into(),
        ty: TypeRef::String,
        optional: false,
        default: None,
        doc: String::new(),
        sanitized: false,
        is_boxed: false,
        type_rust_path: None,
        cfg: Some("feature = \"layout-detection\"".into()),
        typed_default: None,
        core_wrapper: CoreWrapper::None,
        vec_inner_core_wrapper: CoreWrapper::None,
        newtype_wrapper: None,
        serde_rename: None,
        serde_flatten: false,
        binding_excluded: false,
        binding_exclusion_reason: None,
        original_type: None,
    });

    let result = gen_from_binding_to_core(&typ, "my_crate");

    // The impl should exist
    assert!(result.contains("impl From<Config> for my_crate::Config"));
    // Regular fields should be present
    assert!(result.contains("name: val.name"));
    assert!(result.contains("timeout: val.timeout"));
    // Cfg-gated fields are now preserved on the binding struct, so the conversion
    // accesses them directly rather than padding with ..Default::default().
    assert!(result.contains("layout: val.layout"));
}

#[test]
fn test_from_core_to_binding_with_cfg_gated_field() {
    // Create a type with a cfg-gated field
    let mut typ = simple_type();
    typ.fields.push(FieldDef {
        name: "layout".into(),
        ty: TypeRef::String,
        optional: false,
        default: None,
        doc: String::new(),
        sanitized: false,
        is_boxed: false,
        type_rust_path: None,
        cfg: Some("feature = \"layout-detection\"".into()),
        typed_default: None,
        core_wrapper: CoreWrapper::None,
        vec_inner_core_wrapper: CoreWrapper::None,
        newtype_wrapper: None,
        serde_rename: None,
        serde_flatten: false,
        binding_excluded: false,
        binding_exclusion_reason: None,
        original_type: None,
    });

    let result = gen_from_core_to_binding(&typ, "my_crate", &AHashSet::new());

    // The impl should exist
    assert!(result.contains("impl From<my_crate::Config> for Config"));
    // Regular fields should be present
    assert!(result.contains("name: val.name"));
    // Cfg-gated fields are now preserved on the binding struct and round-tripped.
    assert!(result.contains("layout: val.layout"));
}

#[test]
fn test_field_conversion_from_core_map_named_non_optional() {
    // Map<K, Named> non-optional: each value needs .into() core→binding
    let result = field_conversion_from_core(
        "tags",
        &TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::Named("Tag".into()))),
        false,
        false,
        &AHashSet::new(),
    );
    assert_eq!(
        result,
        "tags: val.tags.into_iter().map(|(k, v)| (k, v.into())).collect()"
    );
}

#[test]
fn test_field_conversion_from_core_option_map_named() {
    // Option<Map<K, Named>>: .map() wrapper + per-element .into()
    let result = field_conversion_from_core(
        "tags",
        &TypeRef::Optional(Box::new(TypeRef::Map(
            Box::new(TypeRef::String),
            Box::new(TypeRef::Named("Tag".into())),
        ))),
        false,
        false,
        &AHashSet::new(),
    );
    assert_eq!(
        result,
        "tags: val.tags.map(|m| m.into_iter().map(|(k, v)| (k, v.into())).collect())"
    );
}

#[test]
fn test_field_conversion_from_core_vec_named_non_optional() {
    // Vec<Named> non-optional: each element needs .into() core→binding
    let result = field_conversion_from_core(
        "items",
        &TypeRef::Vec(Box::new(TypeRef::Named("Item".into()))),
        false,
        false,
        &AHashSet::new(),
    );
    assert_eq!(result, "items: val.items.into_iter().map(Into::into).collect()");
}

#[test]
fn test_field_conversion_from_core_option_vec_named() {
    // Option<Vec<Named>>: .map() wrapper + per-element .into()
    let result = field_conversion_from_core(
        "items",
        &TypeRef::Optional(Box::new(TypeRef::Vec(Box::new(TypeRef::Named("Item".into()))))),
        false,
        false,
        &AHashSet::new(),
    );
    assert_eq!(
        result,
        "items: val.items.map(|v| v.into_iter().map(Into::into).collect())"
    );
}

#[test]
fn test_field_conversion_to_core_option_map_named_applies_per_value_into() {
    // Bug A1 regression: Option<Map<K, Named>> must apply per-value .into() so that
    // binding-side wrapper types (e.g. PyO3 / Magnus structs) are converted correctly.
    let result = field_conversion_to_core(
        "patterns",
        &TypeRef::Map(
            Box::new(TypeRef::String),
            Box::new(TypeRef::Named("ExtractionPattern".into())),
        ),
        true,
    );
    assert!(
        result.contains("m.into_iter().map(|(k, v)| (k.into(), v.into())).collect()"),
        "expected per-value v.into() in optional Map<Named> conversion, got: {result}"
    );
    assert_eq!(
        result,
        "patterns: val.patterns.map(|m| m.into_iter().map(|(k, v)| (k.into(), v.into())).collect())"
    );
}

#[test]
fn test_optionalized_defaultable_struct_uses_core_default_as_base() {
    let mut typ = simple_type();
    typ.has_default = true;
    typ.fields = vec![
        FieldDef {
            name: "language".into(),
            ty: TypeRef::String,
            optional: false,
            default: None,
            doc: String::new(),
            sanitized: false,
            is_boxed: false,
            type_rust_path: None,
            cfg: None,
            typed_default: None,
            core_wrapper: CoreWrapper::Cow,
            vec_inner_core_wrapper: CoreWrapper::None,
            newtype_wrapper: None,
            serde_rename: None,
            serde_flatten: false,
            binding_excluded: false,
            binding_exclusion_reason: None,
            original_type: None,
        },
        FieldDef {
            name: "structure".into(),
            ty: TypeRef::Primitive(PrimitiveType::Bool),
            optional: false,
            default: None,
            doc: String::new(),
            sanitized: false,
            is_boxed: false,
            type_rust_path: None,
            cfg: None,
            typed_default: None,
            core_wrapper: CoreWrapper::None,
            vec_inner_core_wrapper: CoreWrapper::None,
            newtype_wrapper: None,
            serde_rename: None,
            serde_flatten: false,
            binding_excluded: false,
            binding_exclusion_reason: None,
            original_type: None,
        },
    ];
    let config = ConversionConfig {
        type_name_prefix: "Js",
        optionalize_defaults: true,
        ..ConversionConfig::default()
    };

    let result = gen_from_binding_to_core_cfg(&typ, "my_crate", &config);

    assert!(result.contains("let mut __result = my_crate::Config::default();"));
    assert!(result.contains("if let Some(__v) = val.language { __result.language = __v.into(); }"));
    assert!(result.contains("if let Some(__v) = val.structure { __result.structure = __v; }"));
    assert!(!result.contains("unwrap_or_default()"));
}

fn arc_field_type(field: FieldDef) -> TypeDef {
    TypeDef {
        name: "State".to_string(),
        rust_path: "my_crate::State".to_string(),
        original_rust_path: String::new(),
        fields: vec![field],
        methods: vec![],
        is_opaque: false,
        is_clone: true,
        is_copy: false,
        is_trait: false,
        has_default: false,
        has_stripped_cfg_fields: false,
        is_return_type: false,
        serde_rename_all: None,
        has_serde: false,
        super_traits: vec![],
        doc: String::new(),
        cfg: None,
        binding_excluded: false,
        binding_exclusion_reason: None,
        is_variant_wrapper: false,
        has_lifetime_params: false,
        version: Default::default(),
    }
}

fn arc_field(name: &str, ty: TypeRef, optional: bool) -> FieldDef {
    FieldDef {
        name: name.into(),
        ty,
        optional,
        default: None,
        doc: String::new(),
        sanitized: false,
        is_boxed: false,
        type_rust_path: None,
        cfg: None,
        typed_default: None,
        core_wrapper: CoreWrapper::Arc,
        vec_inner_core_wrapper: CoreWrapper::None,
        newtype_wrapper: None,
        serde_rename: None,
        serde_flatten: false,
        binding_excluded: false,
        binding_exclusion_reason: None,
        original_type: None,
    }
}

/// Regression: Option<Arc<serde_json::Value>> must not chain `(*v).clone().into()`
/// on top of `as_ref().map(ToString::to_string)`, which would emit invalid
/// `(*String).clone()` (str: !Clone).
#[test]
fn test_arc_json_option_field_no_double_chain() {
    let typ = arc_field_type(arc_field("registered_spec", TypeRef::Json, true));
    let result = gen_from_core_to_binding(&typ, "my_crate", &AHashSet::new());
    assert!(
        result.contains("val.registered_spec.as_ref().map(ToString::to_string)"),
        "expected as_ref().map(ToString::to_string) for Option<Arc<Value>>, got: {result}"
    );
    assert!(
        !result.contains("map(ToString::to_string).map("),
        "must not chain a second map() on top of ToString::to_string, got: {result}"
    );
}

/// Non-optional Arc<Value>: `(*val.X).clone().to_string()` is valid (Value: Clone).
#[test]
fn test_arc_json_non_optional_field() {
    let typ = arc_field_type(arc_field("spec", TypeRef::Json, false));
    let result = gen_from_core_to_binding(&typ, "my_crate", &AHashSet::new());
    assert!(
        result.contains("(*val.spec).clone().to_string()"),
        "expected (*val.spec).clone().to_string() for Arc<Value>, got: {result}"
    );
}

/// Option<Arc<String>>: the base string conversion already handles Arc via Deref/Display.
/// Verifies the Arc wrapper does not append a second map over the converted String.
#[test]
fn test_arc_string_option_field_passthrough() {
    let typ = arc_field_type(arc_field("label", TypeRef::String, true));
    let result = gen_from_core_to_binding(&typ, "my_crate", &AHashSet::new());
    assert!(
        result.contains("val.label.map(|v| v.to_string())"),
        "expected single .map(|v| v.to_string()) for Option<Arc<String>>, got: {result}"
    );
    assert!(
        !result.contains("map(|v| v.to_string()).map("),
        "must not chain a second map() after string conversion, got: {result}"
    );
}

/// Regression: `Arc<HashMap<String, String>>` field — synthetic shape representative
/// of structs that share an immutable map via Arc for zero-copy FFI. The plain `Arc`
/// CoreWrapper must transparently unwrap the inner `val.<name>` reference via
/// `(*val.<name>).clone()` so the downstream map iteration sees the owned `HashMap`,
/// and the binding side reconstructs an `Arc` around the binding-shaped map.
#[test]
fn test_arc_hashmap_string_string_field_transparent() {
    let field = arc_field(
        "headers",
        TypeRef::Map(Box::new(TypeRef::String), Box::new(TypeRef::String)),
        false,
    );
    let typ = arc_field_type(field);
    let to_binding = gen_from_core_to_binding(&typ, "my_crate", &AHashSet::new());
    assert!(
        to_binding.contains("(*val.headers).clone()"),
        "expected (*val.headers).clone() deref-clone for Arc<HashMap<...>>, got: {to_binding}"
    );
    let to_core = gen_from_binding_to_core(&typ, "my_crate");
    assert!(
        to_core.contains("headers:"),
        "expected headers field in binding→core conversion, got: {to_core}"
    );
}

/// Regression: `Arc<Vec<String>>` field — plain Arc unwraps via deref-clone on the
/// non-optional branch, just like the HashMap shape.
#[test]
fn test_arc_vec_string_field_transparent() {
    let field = arc_field("tags", TypeRef::Vec(Box::new(TypeRef::String)), false);
    let typ = arc_field_type(field);
    let to_binding = gen_from_core_to_binding(&typ, "my_crate", &AHashSet::new());
    assert!(
        to_binding.contains("(*val.tags).clone()"),
        "expected (*val.tags).clone() deref-clone for Arc<Vec<...>>, got: {to_binding}"
    );
    let to_core = gen_from_binding_to_core(&typ, "my_crate");
    assert!(
        to_core.contains("tags:"),
        "expected tags field in binding→core conversion, got: {to_core}"
    );
}

/// Regression: `Arc<Mutex<String>>` field — the `ArcMutex` CoreWrapper drives
/// codegen to emit `.lock().unwrap().clone()` on the read path (core→binding) and
/// `Arc::new(Mutex::new(...))` on the write path (binding→core). Verifies the
/// ArcMutex branch is wired end-to-end.
#[test]
fn test_arc_mutex_string_field_transparent() {
    let mut field = arc_field("state", TypeRef::String, false);
    field.core_wrapper = CoreWrapper::ArcMutex;
    let typ = arc_field_type(field);
    let to_binding = gen_from_core_to_binding(&typ, "my_crate", &AHashSet::new());
    assert!(
        to_binding.contains("val.state.lock().unwrap().clone().into()"),
        "expected .lock().unwrap().clone().into() for Arc<Mutex<String>>, got: {to_binding}"
    );
    let to_core = gen_from_binding_to_core(&typ, "my_crate");
    assert!(
        to_core.contains("std::sync::Arc::new(std::sync::Mutex::new(val.state.into()))"),
        "expected Arc::new(Mutex::new(...)) construction for Arc<Mutex<String>>, got: {to_core}"
    );
}