ruchy 4.2.1

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
//! Type transpilation and struct/trait definitions
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::wildcard_imports)]
#![allow(clippy::collapsible_else_if)]
#![allow(clippy::only_used_in_recursion)]
use super::*;
use crate::frontend::ast::{
    ClassMethod, Constructor, EnumVariant, ImplMethod, StructField, TraitMethod, Type, TypeKind,
};
use anyhow::{bail, Result};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::Lifetime;
impl Transpiler {
    /// Transpiles type annotations
    ///
    /// # Examples
    ///
    /// ```
    /// use ruchy::{Transpiler, Parser};
    ///
    /// // Basic types
    /// let mut transpiler = Transpiler::new();
    /// let mut parser = Parser::new("let x: i32 = 42");
    /// let ast = parser.parse().expect("Failed to parse");
    ///
    /// let result = transpiler.transpile(&ast).expect("operation should succeed in test");
    /// let code = result.to_string();
    /// assert!(code.contains("i32"));
    /// assert!(code.contains("42"));
    /// ```
    ///
    /// ```
    /// use ruchy::{Transpiler, Parser};
    ///
    /// // Generic types
    /// let mut transpiler = Transpiler::new();
    /// let mut parser = Parser::new("let v = [1, 2, 3]");
    /// let ast = parser.parse().expect("operation should succeed in test");
    ///
    /// let result = transpiler.transpile(&ast).expect("operation should succeed in test");
    /// // Basic transpilation test - just check it compiles
    /// assert!(!result.to_string().is_empty());
    /// ```
    ///
    /// ```
    /// use ruchy::{Transpiler, Parser};
    ///
    /// // Optional types
    /// let mut transpiler = Transpiler::new();
    /// let mut parser = Parser::new("let opt = Some(42)");
    /// let ast = parser.parse().expect("operation should succeed in test");
    ///
    /// let result = transpiler.transpile(&ast).expect("operation should succeed in test");
    /// let code = result.to_string();
    /// assert!(code.contains("Some"));
    /// ```
    pub fn transpile_type(&self, ty: &Type) -> Result<TokenStream> {
        use crate::frontend::ast::TypeKind;
        match &ty.kind {
            TypeKind::Named(name) => self.transpile_named_type(name),
            TypeKind::Generic { base, params } => self.transpile_generic_type(base, params),
            TypeKind::Optional(inner) => self.transpile_optional_type(inner),
            TypeKind::List(elem_type) => self.transpile_list_type(elem_type),
            TypeKind::Array { elem_type, size } => self.transpile_array_type(elem_type, *size),
            TypeKind::Tuple(types) => self.transpile_tuple_type(types),
            TypeKind::Function { params, ret } => self.transpile_function_type(params, ret),
            TypeKind::DataFrame { .. } => Ok(quote! { polars::prelude::DataFrame }),
            TypeKind::Series { .. } => Ok(quote! { polars::prelude::Series }),
            TypeKind::Reference {
                is_mut,
                lifetime,
                inner,
            } => self.transpile_reference_type(*is_mut, lifetime.as_deref(), inner),
            // SPEC-001-H: Refined types - transpile base type only, ignore constraint
            // Rust's type system doesn't support runtime refinement checking
            // The constraint is a compile-time annotation in Ruchy
            TypeKind::Refined { base, .. } => self.transpile_type(base),
        }
    }
    /// Transpile named types with built-in type mapping
    pub(crate) fn transpile_named_type(&self, name: &str) -> Result<TokenStream> {
        let rust_type = match name {
            "int" => quote! { i64 },
            "float" => quote! { f64 },
            "bool" => quote! { bool },
            "str" => quote! { &str }, // String slice reference (sized type for function parameters)
            "string" | "String" => quote! { String },
            "char" => quote! { char },
            "()" => quote! { () },       // Unit type
            "_" | "Any" => quote! { _ }, // Use Rust type inference
            "Object" => quote! { std::collections::BTreeMap<String, String> }, // TRANSPILER-013 FIX: Use String for standalone rustc compatibility
            _ => {
                // TRANSPILER-DEFECT-005: Handle namespaced types (e.g., trace::Sampler, std::io::Error)
                if name.contains("::") {
                    // Split into path segments and build path token
                    let segments: Vec<_> = name
                        .split("::")
                        .map(|seg| format_ident!("{}", seg))
                        .collect();
                    quote! { #(#segments)::* }
                } else {
                    // Simple identifier
                    let type_ident = format_ident!("{}", name);
                    quote! { #type_ident }
                }
            }
        };
        Ok(rust_type)
    }
    /// Transpile generic types with type parameters
    /// BOOK-COMPAT-007: Auto-box recursive types in Option (e.g., Option<Node> -> Option<Box<Node>>)
    pub(crate) fn transpile_generic_type(
        &self,
        base: &str,
        params: &[Type],
    ) -> Result<TokenStream> {
        use crate::frontend::ast::TypeKind;

        // BOOK-COMPAT-007: Special handling for Option<RecursiveType> pattern
        if base == "Option" && params.len() == 1 {
            if let TypeKind::Named(inner_name) = &params[0].kind {
                let current_struct = self.current_struct_name.borrow();
                let is_recursive = current_struct.as_ref().is_some_and(|c| c == inner_name);

                if is_recursive {
                    // BOOK-COMPAT-007B: Record this field as auto-boxed for struct literal handling
                    // Note: We need access to the field name, which comes from the caller context
                    // For now, we'll record by struct name and inner type
                    if let Some(struct_name) = current_struct.as_ref() {
                        // Store in auto_boxed_fields - key is (struct_name, inner_type)
                        // This will be used during struct literal transpilation
                        self.auto_boxed_fields.borrow_mut().insert(
                            (struct_name.clone(), inner_name.clone()),
                            inner_name.clone(),
                        );
                    }
                    drop(current_struct); // Release borrow before returning
                    let inner_ident = format_ident!("{}", inner_name);
                    return Ok(quote! { Option<Box<#inner_ident>> });
                }
            }
        }

        let base_ident = format_ident!("{}", base);
        let param_tokens: Result<Vec<_>> = params.iter().map(|p| self.transpile_type(p)).collect();
        let param_tokens = param_tokens?;
        Ok(quote! { #base_ident<#(#param_tokens),*> })
    }
    /// Transpile optional types to Option<T>
    /// BOOK-COMPAT-007: Auto-box recursive types (e.g., Option<Node> -> Option<Box<Node>>)
    pub(crate) fn transpile_optional_type(&self, inner: &Type) -> Result<TokenStream> {
        use crate::frontend::ast::TypeKind;

        // Check if this is a recursive type reference
        let is_recursive = if let TypeKind::Named(name) = &inner.kind {
            self.current_struct_name
                .borrow()
                .as_ref()
                .is_some_and(|current| current == name)
        } else {
            false
        };

        let inner_tokens = self.transpile_type(inner)?;

        if is_recursive {
            // BOOK-COMPAT-007: Wrap recursive type in Box to break infinite size
            Ok(quote! { Option<Box<#inner_tokens>> })
        } else {
            Ok(quote! { Option<#inner_tokens> })
        }
    }
    /// Transpile list types to Vec<T>
    pub(crate) fn transpile_list_type(&self, elem_type: &Type) -> Result<TokenStream> {
        let elem_tokens = self.transpile_type(elem_type)?;
        Ok(quote! { Vec<#elem_tokens> })
    }
    /// Transpile array types with fixed size
    pub(crate) fn transpile_array_type(
        &self,
        elem_type: &Type,
        size: usize,
    ) -> Result<TokenStream> {
        let elem_tokens = self.transpile_type(elem_type)?;
        let size_lit = proc_macro2::Literal::usize_unsuffixed(size);
        Ok(quote! { [#elem_tokens; #size_lit] })
    }
    /// Transpile tuple types
    pub(crate) fn transpile_tuple_type(&self, types: &[Type]) -> Result<TokenStream> {
        let type_tokens: Result<Vec<_>> = types.iter().map(|t| self.transpile_type(t)).collect();
        let type_tokens = type_tokens?;
        Ok(quote! { (#(#type_tokens),*) })
    }
    /// Transpile function types
    pub(crate) fn transpile_function_type(
        &self,
        params: &[Type],
        ret: &Type,
    ) -> Result<TokenStream> {
        let param_tokens: Result<Vec<_>> = params.iter().map(|p| self.transpile_type(p)).collect();
        let param_tokens = param_tokens?;
        let ret_tokens = self.transpile_type(ret)?;
        Ok(quote! { fn(#(#param_tokens),*) -> #ret_tokens })
    }
    /// Transpile reference types with special handling for &str and lifetimes
    pub(crate) fn transpile_reference_type(
        &self,
        is_mut: bool,
        lifetime: Option<&str>,
        inner: &Type,
    ) -> Result<TokenStream> {
        use crate::frontend::ast::TypeKind;

        // Create lifetime token if provided
        let lifetime_token = if let Some(lt) = lifetime {
            let lifetime = Lifetime::new(lt, proc_macro2::Span::call_site());
            quote! { #lifetime }
        } else {
            quote! {}
        };

        // Special case: &str should not become &&str
        if let TypeKind::Named(name) = &inner.kind {
            if name == "str" {
                return if is_mut {
                    Ok(quote! { &#lifetime_token mut str })
                } else {
                    Ok(quote! { &#lifetime_token str })
                };
            }
        }
        let inner_tokens = self.transpile_type(inner)?;
        if is_mut {
            Ok(quote! { &#lifetime_token mut #inner_tokens })
        } else {
            Ok(quote! { &#lifetime_token #inner_tokens })
        }
    }
    /// Transpiles tuple struct definitions
    pub fn transpile_tuple_struct(
        &self,
        name: &str,
        type_params: &[String],
        fields: &[Type],
        derives: &[String],
        is_pub: bool,
    ) -> Result<TokenStream> {
        let struct_name = format_ident!("{}", name);
        let type_param_tokens: Vec<TokenStream> = type_params
            .iter()
            .map(|p| Self::parse_type_param_to_tokens(p))
            .collect();

        // Convert field types to tokens
        let field_tokens: Vec<TokenStream> = fields
            .iter()
            .map(|ty| self.transpile_type(ty).unwrap_or_else(|_| quote! { _ }))
            .collect();

        let visibility = if is_pub {
            quote! { pub }
        } else {
            quote! {}
        };

        // DEFECT-014: Auto-add Clone to derives for Vec indexing support
        let mut extended_derives = derives.to_vec();
        if !extended_derives.contains(&"Clone".to_string()) {
            extended_derives.push("Clone".to_string());
        }

        // Generate derive attributes using helper (PARSER-077 fix)
        let derive_attrs = self.generate_derive_attributes(&extended_derives);

        // Generate tuple struct definition
        let struct_def = if type_params.is_empty() {
            quote! {
                #derive_attrs
                #visibility struct #struct_name(#(pub #field_tokens),*);
            }
        } else {
            quote! {
                #derive_attrs
                #visibility struct #struct_name<#(#type_param_tokens),*>(#(pub #field_tokens),*);
            }
        };

        Ok(struct_def)
    }

    /// Helper: Check if any field has a reference type (for lifetime detection)
    /// Complexity: 2 (simple iteration + match)
    pub(crate) fn has_reference_fields(&self, fields: &[StructField]) -> bool {
        use crate::frontend::ast::TypeKind;
        fields
            .iter()
            .any(|field| matches!(field.ty.kind, TypeKind::Reference { .. }))
    }

    /// Helper: Check if type params already contain a lifetime
    /// Complexity: 1 (simple predicate)
    pub(crate) fn has_lifetime_params(&self, type_params: &[String]) -> bool {
        type_params.iter().any(|p| p.starts_with('\''))
    }

    /// DEFECT-021 FIX: Parse type parameter string to `TokenStream`
    /// Handles both simple params ("T") and params with bounds ("T: Clone + Debug")
    pub(crate) fn parse_type_param_to_tokens(p: &str) -> TokenStream {
        if p.starts_with('\'') {
            // Lifetime parameter
            let lifetime = Lifetime::new(p, proc_macro2::Span::call_site());
            quote! { #lifetime }
        } else if p.contains(':') {
            // Type parameter with trait bounds (e.g., "T: Clone + Debug")
            syn::parse_str::<syn::TypeParam>(p).map_or_else(
                |_| {
                    // Fallback: just use the name part
                    let name = p.split(':').next().unwrap_or(p).trim();
                    let ident = format_ident!("{}", name);
                    quote! { #ident }
                },
                |tp| quote! { #tp },
            )
        } else {
            // Simple type parameter
            let ident = format_ident!("{}", p);
            quote! { #ident }
        }
    }

    /// Helper: Transpile type with explicit lifetime annotation for struct fields
    /// Complexity: 3 (type matching + recursive call)
    pub(crate) fn transpile_struct_field_type_with_lifetime(
        &self,
        ty: &Type,
        lifetime: &str,
    ) -> Result<TokenStream> {
        use crate::frontend::ast::TypeKind;
        match &ty.kind {
            TypeKind::Reference { is_mut, inner, .. } => {
                // Override lifetime for references
                self.transpile_reference_type(*is_mut, Some(lifetime), inner)
            }
            _ => {
                // For non-reference types, use regular transpilation
                self.transpile_type(ty)
            }
        }
    }

    /// Transpiles struct definitions
    pub fn transpile_struct(
        &self,
        name: &str,
        type_params: &[String],
        fields: &[StructField],
        derives: &[String],
        is_pub: bool,
    ) -> Result<TokenStream> {
        self.transpile_struct_with_methods(name, type_params, fields, &[], derives, is_pub)
    }

    pub fn transpile_struct_with_methods(
        &self,
        name: &str,
        type_params: &[String],
        fields: &[StructField],
        methods: &[ClassMethod],
        derives: &[String],
        is_pub: bool,
    ) -> Result<TokenStream> {
        // BOOK-COMPAT-007: Track current struct name for recursive type detection
        *self.current_struct_name.borrow_mut() = Some(name.to_string());

        let struct_name = format_ident!("{}", name);

        // BOOK-COMPAT-001: Auto-add lifetime parameter if struct has reference fields
        let needs_lifetime =
            self.has_reference_fields(fields) && !self.has_lifetime_params(type_params);
        let effective_type_params: Vec<String> = if needs_lifetime {
            let mut params = vec!["'a".to_string()];
            params.extend_from_slice(type_params);
            params
        } else {
            type_params.to_vec()
        };

        let type_param_tokens: Vec<TokenStream> = effective_type_params
            .iter()
            .map(|p| Self::parse_type_param_to_tokens(p))
            .collect();
        let field_tokens: Vec<TokenStream> = fields
            .iter()
            .map(|field| {
                let field_name = format_ident!("{}", field.name);

                // BOOK-COMPAT-001: Add lifetime to reference types if needed
                let field_type = if needs_lifetime {
                    self.transpile_struct_field_type_with_lifetime(&field.ty, "'a")
                        .unwrap_or_else(|_| quote! { _ })
                } else {
                    self.transpile_type(&field.ty)
                        .unwrap_or_else(|_| quote! { _ })
                };

                use crate::frontend::ast::Visibility;
                match &field.visibility {
                    Visibility::Public => quote! { pub #field_name: #field_type },
                    Visibility::PubCrate => quote! { pub(crate) #field_name: #field_type },
                    Visibility::PubSuper => quote! { pub(super) #field_name: #field_type },
                    Visibility::Private | Visibility::Protected => {
                        quote! { #field_name: #field_type }
                    }
                }
            })
            .collect();
        let visibility = if is_pub {
            quote! { pub }
        } else {
            quote! {}
        };

        // DEFECT-014: Auto-add Clone to derives for Vec indexing support
        let mut extended_derives = derives.to_vec();
        if !extended_derives.contains(&"Clone".to_string()) {
            extended_derives.push("Clone".to_string());
        }

        // Generate derive attributes using helper (PARSER-077 fix)
        let derive_attrs = self.generate_derive_attributes(&extended_derives);

        // BOOK-COMPAT-002: Store struct field types for proper string literal conversion
        // When transpiling struct literals, we need to know if a field is String type
        // to add .to_string() for string literal values
        {
            use crate::frontend::ast::TypeKind;
            let mut field_types = self.struct_field_types.borrow_mut();
            for field in fields {
                // Extract type name from TypeKind::Named
                let type_name = match &field.ty.kind {
                    TypeKind::Named(n) => n.clone(),
                    _ => format!("{:?}", field.ty.kind), // Fallback for complex types
                };
                field_types.insert((name.to_string(), field.name.clone()), type_name);
            }
        }

        // Generate struct definition
        let struct_def = if effective_type_params.is_empty() {
            quote! {
                #derive_attrs
                #visibility struct #struct_name {
                    #(#field_tokens,)*
                }
            }
        } else {
            quote! {
                #derive_attrs
                #visibility struct #struct_name<#(#type_param_tokens),*> {
                    #(#field_tokens,)*
                }
            }
        };

        // Check if any fields have default values
        let has_defaults = fields.iter().any(|f| f.default_value.is_some());

        // Generate Default impl if there are default values
        if has_defaults {
            use crate::frontend::ast::{ExprKind, Literal};
            let default_field_tokens: Result<Vec<_>> = fields
                .iter()
                .map(|field| -> Result<TokenStream> {
                    let field_name = format_ident!("{}", field.name);
                    if let Some(ref default_expr) = field.default_value {
                        let default_value = self.transpile_expr(default_expr)?;
                        // BOOK-COMPAT-004: Add .to_string() for String fields with string literal defaults
                        let is_string_field =
                            matches!(&field.ty.kind, TypeKind::Named(n) if n == "String");
                        let is_string_literal =
                            matches!(&default_expr.kind, ExprKind::Literal(Literal::String(_)));
                        if is_string_field && is_string_literal {
                            Ok(quote! { #field_name: #default_value.to_string() })
                        } else {
                            Ok(quote! { #field_name: #default_value })
                        }
                    } else {
                        Ok(quote! { #field_name: Default::default() })
                    }
                })
                .collect();
            let default_field_tokens = default_field_tokens?;

            let default_impl = if type_params.is_empty() {
                quote! {
                    impl Default for #struct_name {
                        fn default() -> Self {
                            Self {
                                #(#default_field_tokens,)*
                            }
                        }
                    }
                }
            } else {
                // For generic structs, we need to add Default bounds
                let where_clause_tokens: Vec<_> = type_params
                    .iter()
                    .map(|p| {
                        let param_ident = format_ident!("{}", p);
                        quote! { #param_ident: Default }
                    })
                    .collect();

                quote! {
                    impl<#(#type_param_tokens),*> Default for #struct_name<#(#type_param_tokens),*>
                    where
                        #(#where_clause_tokens),*
                    {
                        fn default() -> Self {
                            Self {
                                #(#default_field_tokens,)*
                            }
                        }
                    }
                }
            };

            if methods.is_empty() {
                Ok(quote! {
                    #struct_def

                    #default_impl
                })
            } else {
                let method_tokens = self.transpile_class_methods(methods)?;
                let type_param_tokens = self.generate_class_type_param_tokens(type_params);
                let impl_block = if type_param_tokens.is_empty() {
                    quote! {
                        impl #struct_name {
                            #(#method_tokens)*
                        }
                    }
                } else {
                    quote! {
                        impl<#(#type_param_tokens),*> #struct_name<#(#type_param_tokens),*> {
                            #(#method_tokens)*
                        }
                    }
                };
                Ok(quote! {
                    #struct_def

                    #default_impl

                    #impl_block
                })
            }
        } else {
            if methods.is_empty() {
                Ok(struct_def)
            } else {
                let method_tokens = self.transpile_class_methods(methods)?;
                let type_param_tokens = self.generate_class_type_param_tokens(type_params);
                let impl_block = if type_param_tokens.is_empty() {
                    quote! {
                        impl #struct_name {
                            #(#method_tokens)*
                        }
                    }
                } else {
                    quote! {
                        impl<#(#type_param_tokens),*> #struct_name<#(#type_param_tokens),*> {
                            #(#method_tokens)*
                        }
                    }
                };
                Ok(quote! {
                    #struct_def

                    #impl_block
                })
            }
        }
    }

    /// Transpiles class definitions to struct + impl blocks following Ruchy class sugar specification
    /// Transpile class to struct with impl blocks
    /// Complexity: 5 (within Toyota Way limits)
    pub fn transpile_class(
        &self,
        name: &str,
        type_params: &[String],
        _traits: &[String],
        fields: &[StructField],
        constructors: &[Constructor],
        methods: &[ClassMethod],
        constants: &[crate::frontend::ast::ClassConstant],
        derives: &[String],
        is_pub: bool,
    ) -> Result<TokenStream> {
        let struct_tokens = self.transpile_struct(name, type_params, fields, derives, is_pub)?;
        let type_param_tokens = self.generate_class_type_param_tokens(type_params);
        let struct_name = format_ident!("{}", name);

        let constructor_tokens = self.transpile_constructors(constructors)?;
        let method_tokens = self.transpile_class_methods(methods)?;
        let constant_tokens = self.transpile_class_constants(constants)?;

        let impl_tokens = self.generate_impl_block(
            &struct_name,
            &type_param_tokens,
            &constant_tokens,
            &constructor_tokens,
            &method_tokens,
        );

        let default_impl = self.generate_default_impl(fields, &struct_name, &type_param_tokens)?;

        Ok(quote! {
            #struct_tokens
            #impl_tokens
            #default_impl
        })
    }

    /// Generate derive attributes
    /// Complexity: 1 (within Toyota Way limits)
    pub(crate) fn generate_derive_attributes(&self, derives: &[String]) -> TokenStream {
        if derives.is_empty() {
            quote! {}
        } else {
            let derive_idents: Vec<_> = derives.iter().map(|d| format_ident!("{}", d)).collect();
            quote! { #[derive(#(#derive_idents),*)] }
        }
    }

    /// Generate type parameter tokens for classes
    /// Complexity: 2 (within Toyota Way limits)
    pub(crate) fn generate_class_type_param_tokens(
        &self,
        type_params: &[String],
    ) -> Vec<TokenStream> {
        type_params
            .iter()
            .map(|p| {
                if p.starts_with('\'') {
                    let lifetime = Lifetime::new(p, proc_macro2::Span::call_site());
                    quote! { #lifetime }
                } else {
                    let ident = format_ident!("{}", p);
                    quote! { #ident }
                }
            })
            .collect()
    }

    /// BOOK-COMPAT-010: Transform constructor body with self.field = value patterns
    /// into proper struct initialization: Self { field: value, ... }
    fn transpile_constructor_body(&self, body: &Expr) -> Result<TokenStream> {
        use crate::frontend::ast::ExprKind;

        // Extract self-assignments from block body
        if let ExprKind::Block(exprs) = &body.kind {
            let mut field_inits: Vec<(String, TokenStream)> = Vec::new();

            for expr in exprs {
                if let ExprKind::Assign { target, value } = &expr.kind {
                    // Check if target is self.field
                    if let ExprKind::FieldAccess { object, field } = &target.kind {
                        if let ExprKind::Identifier(name) = &object.kind {
                            if name == "self" {
                                let value_tokens = self.transpile_expr(value)?;
                                field_inits.push((field.clone(), value_tokens));
                                continue;
                            }
                        }
                    }
                }
                // Non-self-assignment in constructor - fall back to regular transpilation
                return self.transpile_expr(body);
            }

            // Generate Self { field1: value1, field2: value2, ... }
            if !field_inits.is_empty() {
                let fields: Vec<TokenStream> = field_inits
                    .into_iter()
                    .map(|(name, value)| {
                        let field_ident = format_ident!("{}", name);
                        quote! { #field_ident: #value }
                    })
                    .collect();
                return Ok(quote! { Self { #(#fields),* } });
            }
        }

        // Single self-assignment expression
        if let ExprKind::Assign { target, value } = &body.kind {
            if let ExprKind::FieldAccess { object, field } = &target.kind {
                if let ExprKind::Identifier(name) = &object.kind {
                    if name == "self" {
                        let field_ident = format_ident!("{}", field);
                        let value_tokens = self.transpile_expr(value)?;
                        return Ok(quote! { Self { #field_ident: #value_tokens } });
                    }
                }
            }
        }

        // Default: transpile as regular expression
        self.transpile_expr(body)
    }

    /// Transpile constructors to methods
    /// Complexity: 6 (within Toyota Way limits)
    pub(crate) fn transpile_constructors(
        &self,
        constructors: &[Constructor],
    ) -> Result<Vec<TokenStream>> {
        constructors
            .iter()
            .map(|ctor| {
                let params = self.transpile_params(&ctor.params)?;
                // BOOK-COMPAT-010: Use special constructor body transpilation
                let body = self.transpile_constructor_body(&ctor.body)?;
                let visibility = if ctor.is_pub {
                    quote! { pub }
                } else {
                    quote! {}
                };
                let method_name = ctor
                    .name
                    .as_ref()
                    .map_or_else(|| format_ident!("new"), |n| format_ident!("{}", n));
                let return_type = if let Some(ref ret_ty) = ctor.return_type {
                    let ret_tokens = self.transpile_type(ret_ty)?;
                    quote! { -> #ret_tokens }
                } else {
                    quote! { -> Self }
                };

                Ok(quote! {
                    #visibility fn #method_name(#(#params),*) #return_type {
                        #body
                    }
                })
            })
            .collect()
    }

    /// Transpile class methods
    /// Complexity: 5 (within Toyota Way limits)
    pub(crate) fn transpile_class_methods(
        &self,
        methods: &[ClassMethod],
    ) -> Result<Vec<TokenStream>> {
        methods
            .iter()
            .map(|method| {
                let method_name = format_ident!("{}", method.name);
                let params = self.transpile_params(&method.params)?;
                let return_type = if let Some(ref ret_ty) = method.return_type {
                    let ret_tokens = self.transpile_type(ret_ty)?;
                    quote! { -> #ret_tokens }
                } else {
                    quote! {}
                };
                let body = self.transpile_expr(&method.body)?;
                let visibility = if method.is_pub {
                    quote! { pub }
                } else {
                    quote! {}
                };

                Ok(quote! {
                    #visibility fn #method_name(#(#params),*) #return_type {
                        #body
                    }
                })
            })
            .collect()
    }

    /// Transpile class constants
    /// Complexity: 3 (within Toyota Way limits)
    pub(crate) fn transpile_class_constants(
        &self,
        constants: &[crate::frontend::ast::ClassConstant],
    ) -> Result<Vec<TokenStream>> {
        constants
            .iter()
            .map(|constant| {
                let const_name = format_ident!("{}", constant.name);
                let const_type = self.transpile_type(&constant.ty)?;
                let const_value = self.transpile_expr(&constant.value)?;
                let visibility = if constant.is_pub {
                    quote! { pub }
                } else {
                    quote! {}
                };

                Ok(quote! {
                    #visibility const #const_name: #const_type = #const_value;
                })
            })
            .collect()
    }

    /// Generate impl block
    /// Complexity: 1 (within Toyota Way limits)
    pub(crate) fn generate_impl_block(
        &self,
        struct_name: &proc_macro2::Ident,
        type_param_tokens: &[TokenStream],
        constant_tokens: &[TokenStream],
        constructor_tokens: &[TokenStream],
        method_tokens: &[TokenStream],
    ) -> TokenStream {
        if type_param_tokens.is_empty() {
            quote! {
                impl #struct_name {
                    #(#constant_tokens)*
                    #(#constructor_tokens)*
                    #(#method_tokens)*
                }
            }
        } else {
            quote! {
                impl<#(#type_param_tokens),*> #struct_name<#(#type_param_tokens),*> {
                    #(#constant_tokens)*
                    #(#constructor_tokens)*
                    #(#method_tokens)*
                }
            }
        }
    }

    /// Generate Default impl if needed
    /// Complexity: 4 (within Toyota Way limits)
    pub(crate) fn generate_default_impl(
        &self,
        fields: &[StructField],
        struct_name: &proc_macro2::Ident,
        type_param_tokens: &[TokenStream],
    ) -> Result<TokenStream> {
        let has_defaults = fields.iter().any(|f| f.default_value.is_some());
        if !has_defaults {
            return Ok(quote! {});
        }

        let default_field_tokens: Result<Vec<_>> = fields
            .iter()
            .map(|field| {
                let field_name = format_ident!("{}", field.name);
                if let Some(ref default_expr) = field.default_value {
                    let default_value = self.transpile_expr(default_expr)?;
                    Ok(quote! { #field_name: #default_value })
                } else {
                    Ok(quote! { #field_name: Default::default() })
                }
            })
            .collect();
        let default_field_tokens = default_field_tokens?;

        Ok(if type_param_tokens.is_empty() {
            quote! {
                impl Default for #struct_name {
                    fn default() -> Self {
                        Self {
                            #(#default_field_tokens,)*
                        }
                    }
                }
            }
        } else {
            quote! {
                impl<#(#type_param_tokens),*> Default for #struct_name<#(#type_param_tokens),*> {
                    fn default() -> Self {
                        Self {
                            #(#default_field_tokens,)*
                        }
                    }
                }
            }
        })
    }

    /// Simple parameter transpilation for class methods (no body analysis needed)
    pub(crate) fn transpile_params(
        &self,
        params: &[crate::frontend::ast::Param],
    ) -> Result<Vec<TokenStream>> {
        params
            .iter()
            .map(|param| -> Result<TokenStream> {
                let param_name = param.name();

                // Handle self parameters specially
                if param_name == "self" {
                    use crate::frontend::ast::TypeKind;
                    match &param.ty.kind {
                        TypeKind::Reference { is_mut: true, .. } => Ok(quote! { &mut self }),
                        TypeKind::Reference { is_mut: false, .. } => Ok(quote! { &self }),
                        _ => {
                            // Check if it's a mutable move (mut self)
                            if param.is_mutable {
                                Ok(quote! { mut self })
                            } else {
                                Ok(quote! { self })
                            }
                        }
                    }
                } else {
                    // Regular parameter
                    // TRANSPILER-005 FIX: Preserve mut keyword for mutable parameters
                    let param_ident = format_ident!("{}", param_name);
                    let type_tokens = self.transpile_type(&param.ty)?;
                    if param.is_mutable {
                        Ok(quote! { mut #param_ident: #type_tokens })
                    } else {
                        Ok(quote! { #param_ident: #type_tokens })
                    }
                }
            })
            .collect()
    }

    /// Transpiles trait definitions
    pub fn transpile_enum(
        &self,
        name: &str,
        type_params: &[String],
        variants: &[EnumVariant],
        is_pub: bool,
    ) -> Result<TokenStream> {
        let enum_name = format_ident!("{}", name);
        let type_param_tokens: Vec<_> = type_params
            .iter()
            .map(|p| Self::parse_type_param_to_tokens(p))
            .collect();
        // Check if any variant has discriminant values
        let has_discriminants = variants.iter().any(|v| v.discriminant.is_some());
        let variant_tokens: Vec<TokenStream> = variants
            .iter()
            .map(|variant| {
                use crate::frontend::ast::EnumVariantKind;
                let variant_name = format_ident!("{}", variant.name);

                match &variant.kind {
                    EnumVariantKind::Tuple(fields) => {
                        // Tuple variant: Write(String)
                        let field_types: Vec<TokenStream> = fields
                            .iter()
                            .map(|ty| self.transpile_type(ty).unwrap_or_else(|_| quote! { _ }))
                            .collect();
                        quote! { #variant_name(#(#field_types),*) }
                    }
                    EnumVariantKind::Struct(fields) => {
                        // Struct variant: Move { x: i32, y: i32 }
                        let field_defs: Vec<TokenStream> = fields
                            .iter()
                            .map(|field| {
                                let field_name = format_ident!("{}", field.name);
                                let field_type = self
                                    .transpile_type(&field.ty)
                                    .unwrap_or_else(|_| quote! { _ });
                                quote! { #field_name: #field_type }
                            })
                            .collect();
                        quote! { #variant_name { #(#field_defs),* } }
                    }
                    EnumVariantKind::Unit => {
                        // Unit variant with optional discriminant
                        if let Some(disc_value) = variant.discriminant {
                            let disc_literal =
                                proc_macro2::Literal::i32_unsuffixed(disc_value as i32);
                            quote! { #variant_name = #disc_literal }
                        } else {
                            quote! { #variant_name }
                        }
                    }
                }
            })
            .collect();
        let visibility = if is_pub {
            quote! { pub }
        } else {
            quote! {}
        };
        // Add #[derive(Debug, Clone, PartialEq)] for better usability
        let derive_attr = quote! { #[derive(Debug, Clone, PartialEq)] };

        // Add #[repr(i32)] attribute if enum has discriminant values
        let repr_attr = if has_discriminants {
            quote! { #[repr(i32)] }
        } else {
            quote! {}
        };
        if type_params.is_empty() {
            Ok(quote! {
                #derive_attr
                #repr_attr
                #visibility enum #enum_name {
                    #(#variant_tokens,)*
                }
            })
        } else {
            Ok(quote! {
                #derive_attr
                #repr_attr
                #visibility enum #enum_name<#(#type_param_tokens),*> {
                    #(#variant_tokens,)*
                }
            })
        }
    }
    pub fn transpile_trait(
        &self,
        name: &str,
        type_params: &[String],
        associated_types: &[String],
        methods: &[TraitMethod],
        is_pub: bool,
    ) -> Result<TokenStream> {
        let trait_name = format_ident!("{}", name);

        // Generate associated type declarations: type Item;
        let associated_type_tokens: Vec<TokenStream> = associated_types
            .iter()
            .map(|type_name| {
                let type_ident = format_ident!("{}", type_name);
                quote! { type #type_ident; }
            })
            .collect();

        let method_tokens: Result<Vec<_>> = methods
            .iter()
            .map(|method| {
                let method_name = format_ident!("{}", method.name);
                // TRANSPILER-TRAIT-001 FIX: Determine if self is mutated for &mut self inference
                // For traits with default implementations, check the body for mutations
                let self_is_mutated = method.body.as_ref().is_some_and(|body| {
                    crate::backend::transpiler::mutation_detection::is_variable_mutated(
                        "self", body,
                    )
                });
                // Process parameters
                let param_tokens: Vec<TokenStream> = method
                    .params
                    .iter()
                    .enumerate()
                    .map(|(i, param)| {
                        if i == 0 && (param.name() == "self" || param.name() == "&self") {
                            // TRANSPILER-TRAIT-001 FIX: Handle self parameter consistently
                            // Check the TYPE for reference/mutable reference
                            if let TypeKind::Reference { is_mut, .. } = &param.ty.kind {
                                if *is_mut {
                                    quote! { &mut self }
                                } else {
                                    quote! { &self }
                                }
                            } else if param.name().starts_with('&') {
                                // Legacy: name-based detection (e.g., "&self" as name)
                                quote! { &self }
                            } else {
                                // TRANSPILER-TRAIT-001 FIX: Default to &self or &mut self based on mutation
                                // In Ruchy, `self` without explicit type defaults to reference
                                // This matches Python's implicit self and Rust's common patterns
                                if self_is_mutated {
                                    quote! { &mut self }
                                } else {
                                    quote! { &self }
                                }
                            }
                        } else {
                            let param_name = format_ident!("{}", param.name());
                            let type_tokens = self
                                .transpile_type(&param.ty)
                                .unwrap_or_else(|_| quote! { _ });
                            quote! { #param_name: #type_tokens }
                        }
                    })
                    .collect();
                // Process return type
                let return_type_tokens = if let Some(ref ty) = method.return_type {
                    let ty_tokens = self.transpile_type(ty)?;
                    quote! { -> #ty_tokens }
                } else {
                    quote! {}
                };
                // TRANSPILER-TRAIT-001 FIX: Trait methods cannot have visibility modifiers
                // In Rust, trait method declarations are implicitly public.
                // Adding `pub` causes prettyplease to fail with "not implemented: TraitItem::Verbatim"
                // Process method body (if default implementation)
                if let Some(ref body) = method.body {
                    let body_tokens = self.transpile_expr(body)?;
                    Ok(quote! {
                        fn #method_name(#(#param_tokens),*) #return_type_tokens {
                            #body_tokens
                        }
                    })
                } else {
                    Ok(quote! {
                        fn #method_name(#(#param_tokens),*) #return_type_tokens;
                    })
                }
            })
            .collect();
        let method_tokens = method_tokens?;
        let type_param_tokens: Vec<_> = type_params
            .iter()
            .map(|p| Self::parse_type_param_to_tokens(p))
            .collect();
        let visibility = if is_pub {
            quote! { pub }
        } else {
            quote! {}
        };
        if type_params.is_empty() {
            Ok(quote! {
                #visibility trait #trait_name {
                    #(#associated_type_tokens)*
                    #(#method_tokens)*
                }
            })
        } else {
            Ok(quote! {
                #visibility trait #trait_name<#(#type_param_tokens),*> {
                    #(#associated_type_tokens)*
                    #(#method_tokens)*
                }
            })
        }
    }
    /// Transpiles impl blocks
    pub fn transpile_impl(
        &self,
        for_type: &str,
        type_params: &[String],
        trait_name: Option<&str>,
        methods: &[ImplMethod],
        _is_pub: bool,
    ) -> Result<TokenStream> {
        // DEFECT-027 FIX: Strip generic parameters from for_type if present
        // e.g., "Container<T>" -> "Container"
        let base_type = for_type.split('<').next().unwrap_or(for_type).trim();
        let type_ident = format_ident!("{}", base_type);
        let method_tokens: Result<Vec<_>> = methods
            .iter()
            .map(|method| {
                let method_name = format_ident!("{}", method.name);
                // TRANSPILER-METHOD-SELF-001 FIX: Check if self is mutated in method body
                // to infer &mut self vs &self when not explicitly annotated
                let self_is_mutated =
                    crate::backend::transpiler::mutation_detection::is_variable_mutated(
                        "self",
                        &method.body,
                    );
                // Process parameters
                let param_tokens: Vec<TokenStream> = method
                    .params
                    .iter()
                    .map(|param| {
                        let name = param.name();
                        // QUALITY-001: Handle special Rust receiver syntax (&self, &mut self, self)
                        // Method receivers in Rust have special syntax that differs from normal parameters
                        if name == "self" {
                            // Check if it's a reference type (in the TYPE, not the name)
                            if let TypeKind::Reference { is_mut, .. } = &param.ty.kind {
                                if *is_mut {
                                    quote! { &mut self }
                                } else {
                                    quote! { &self }
                                }
                            } else {
                                // TRANSPILER-METHOD-SELF-001 FIX: Infer &mut self or &self
                                // based on whether self is mutated in the method body
                                // This makes Ruchy more Python-like where self is always a reference
                                if self_is_mutated {
                                    quote! { &mut self }
                                } else {
                                    quote! { &self }
                                }
                            }
                        } else {
                            let param_name = format_ident!("{}", param.name());
                            let type_tokens = self
                                .transpile_type(&param.ty)
                                .unwrap_or_else(|_| quote! { _ });
                            quote! { #param_name: #type_tokens }
                        }
                    })
                    .collect();
                // Process return type
                let return_type_tokens = if let Some(ref ty) = method.return_type {
                    let ty_tokens = self.transpile_type(ty)?;
                    quote! { -> #ty_tokens }
                } else {
                    quote! {}
                };
                // BOOK-COMPAT-016: Check if we need auto-clone for &self method returning owned type
                let needs_auto_clone = !self_is_mutated
                    && method
                        .return_type
                        .as_ref()
                        .is_some_and(Self::is_owned_type)
                    && Self::body_returns_self_field(&method.body);
                // Process method body (always present in ImplMethod)
                let body_tokens = if needs_auto_clone {
                    self.transpile_body_with_auto_clone(&method.body)?
                } else {
                    self.transpile_expr(&method.body)?
                };
                // Process method visibility
                let visibility = if method.is_pub {
                    quote! { pub }
                } else {
                    quote! {}
                };
                Ok(quote! {
                    #visibility fn #method_name(#(#param_tokens),*) #return_type_tokens {
                        #body_tokens
                    }
                })
            })
            .collect();
        let method_tokens = method_tokens?;
        let type_param_tokens: Vec<_> = type_params
            .iter()
            .map(|p| Self::parse_type_param_to_tokens(p))
            .collect();
        if let Some(trait_name) = trait_name {
            let trait_ident = format_ident!("{}", trait_name);
            if type_params.is_empty() {
                Ok(quote! {
                    impl #trait_ident for #type_ident {
                        #(#method_tokens)*
                    }
                })
            } else {
                Ok(quote! {
                    impl<#(#type_param_tokens),*> #trait_ident for #type_ident<#(#type_param_tokens),*> {
                        #(#method_tokens)*
                    }
                })
            }
        } else {
            if type_params.is_empty() {
                Ok(quote! {
                    impl #type_ident {
                        #(#method_tokens)*
                    }
                })
            } else {
                Ok(quote! {
                    impl<#(#type_param_tokens),*> #type_ident<#(#type_param_tokens),*> {
                        #(#method_tokens)*
                    }
                })
            }
        }
    }
    /// Transpiles property test attributes
    pub fn transpile_property_test(&self, expr: &Expr, _attr: &Attribute) -> Result<TokenStream> {
        // Property tests in Rust typically use proptest or quickcheck
        // We'll generate proptest-compatible code
        if let ExprKind::Function {
            name, params, body, ..
        } = &expr.kind
        {
            let fn_name = format_ident!("{}", name);
            // Generate property test parameters
            let param_tokens: Vec<TokenStream> = params
                .iter()
                .map(|p| {
                    let param_name = format_ident!("{}", p.name());
                    let type_tokens = self
                        .transpile_type(&p.ty)
                        .unwrap_or_else(|_| quote! { i32 });
                    quote! { #param_name: #type_tokens }
                })
                .collect();
            let body_tokens = self.transpile_expr(body)?;
            // Generate the proptest macro invocation
            Ok(quote! {
                #[cfg(test)]
                mod #fn_name {
                    use super::*;
                    proptest! {
                        #[test]
                        fn #fn_name(#(#param_tokens),*) {
                            #body_tokens
                        }
                    }
                }
            })
        } else {
            bail!("Property test attribute can only be applied to functions");
        }
    }
    /// Transpiles extension methods into trait + impl
    ///
    /// Generates both a trait definition and an implementation according to the specification:
    /// ```text
    /// Ruchy: extend String { fun is_palindrome(&self) -> bool { ... } }
    /// Rust:  trait StringExt { fn is_palindrome(&self) -> bool; }
    ///        impl StringExt for String { fn is_palindrome(&self) -> bool { ... } }
    /// ```
    pub fn transpile_extend(
        &self,
        target_type: &str,
        methods: &[ImplMethod],
    ) -> Result<TokenStream> {
        let target_ident = format_ident!("{}", target_type);
        let trait_name = format_ident!("{}Ext", target_type); // e.g., StringExt
                                                              // Generate trait definition
        let trait_method_tokens: Result<Vec<_>> = methods
            .iter()
            .map(|method| {
                let method_name = format_ident!("{}", method.name);
                // Process parameters
                let param_tokens: Vec<TokenStream> = method
                    .params
                    .iter()
                    .map(|param| {
                        let name = param.name();
                        // QUALITY-001: Handle special Rust receiver syntax (&self, &mut self, self)
                        // Method receivers in Rust have special syntax that differs from normal parameters
                        if name == "self" {
                            // Check if it's a reference type (in the TYPE, not the name)
                            if let TypeKind::Reference { is_mut, .. } = &param.ty.kind {
                                if *is_mut {
                                    quote! { &mut self }
                                } else {
                                    quote! { &self }
                                }
                            } else {
                                quote! { self }
                            }
                        } else {
                            let param_name = format_ident!("{}", param.name());
                            let type_tokens = self
                                .transpile_type(&param.ty)
                                .unwrap_or_else(|_| quote! { _ });
                            quote! { #param_name: #type_tokens }
                        }
                    })
                    .collect();
                // Process return type
                let return_type_tokens = if let Some(ref ty) = method.return_type {
                    let ty_tokens = self.transpile_type(ty)?;
                    quote! { -> #ty_tokens }
                } else {
                    quote! {}
                };
                // Trait methods are just signatures (no body)
                Ok(quote! {
                    fn #method_name(#(#param_tokens),*) #return_type_tokens;
                })
            })
            .collect();
        let trait_method_tokens = trait_method_tokens?;
        // Generate impl definition
        let impl_method_tokens: Result<Vec<_>> = methods
            .iter()
            .map(|method| {
                let method_name = format_ident!("{}", method.name);
                // Process parameters (same as trait)
                let param_tokens: Vec<TokenStream> = method
                    .params
                    .iter()
                    .enumerate()
                    .map(|(i, param)| {
                        if i == 0 && (param.name() == "self" || param.name() == "&self") {
                            if param.name().starts_with('&') {
                                quote! { &self }
                            } else {
                                quote! { self }
                            }
                        } else {
                            let param_name = format_ident!("{}", param.name());
                            let type_tokens = self
                                .transpile_type(&param.ty)
                                .unwrap_or_else(|_| quote! { _ });
                            quote! { #param_name: #type_tokens }
                        }
                    })
                    .collect();
                // Process return type
                let return_type_tokens = if let Some(ref ty) = method.return_type {
                    let ty_tokens = self.transpile_type(ty)?;
                    quote! { -> #ty_tokens }
                } else {
                    quote! {}
                };
                // Impl methods have bodies
                let body_tokens = self.transpile_expr(&method.body)?;
                Ok(quote! {
                    fn #method_name(#(#param_tokens),*) #return_type_tokens {
                        #body_tokens
                    }
                })
            })
            .collect();
        let impl_method_tokens = impl_method_tokens?;
        // Generate both trait and impl
        Ok(quote! {
            trait #trait_name {
                #(#trait_method_tokens)*
            }
            impl #trait_name for #target_ident {
                #(#impl_method_tokens)*
            }
        })
    }

    /// BOOK-COMPAT-016: Check if a type is an owned type that would need cloning
    fn is_owned_type(ty: &Type) -> bool {
        matches!(&ty.kind, TypeKind::Named(name) if name == "String" || name == "Vec" || name == "HashMap")
    }

    /// BOOK-COMPAT-016: Check if body returns a self.field expression
    fn body_returns_self_field(body: &Expr) -> bool {
        match &body.kind {
            ExprKind::FieldAccess { object, .. } => {
                matches!(&object.kind, ExprKind::Identifier(name) if name == "self")
            }
            ExprKind::Block(exprs) => {
                if let Some(last) = exprs.last() {
                    Self::body_returns_self_field(last)
                } else {
                    false
                }
            }
            _ => false,
        }
    }

    /// BOOK-COMPAT-016: Transpile body with auto-clone for self.field
    fn transpile_body_with_auto_clone(&self, body: &Expr) -> Result<TokenStream> {
        match &body.kind {
            ExprKind::FieldAccess { object, field } => {
                if matches!(&object.kind, ExprKind::Identifier(name) if name == "self") {
                    let field_ident = format_ident!("{}", field);
                    Ok(quote! { self.#field_ident.clone() })
                } else {
                    self.transpile_expr(body)
                }
            }
            ExprKind::Block(exprs) if !exprs.is_empty() => {
                let mut tokens = Vec::new();
                for expr in exprs.iter().take(exprs.len() - 1) {
                    tokens.push(self.transpile_expr(expr)?);
                }
                if let Some(last) = exprs.last() {
                    let last_tokens = self.transpile_body_with_auto_clone(last)?;
                    tokens.push(last_tokens);
                }
                Ok(quote! { { #(#tokens)* } })
            }
            _ => self.transpile_expr(body),
        }
    }
}


#[cfg(test)]
#[path = "types_extreme_tdd_tests.rs"]
mod extreme_tdd_tests;