debtmap 0.16.3

Code complexity and technical debt analyzer
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
use super::{
    ResourceDetector, ResourceField, ResourceImpact, ResourceManagementIssue, ResourceSeverity,
    SourceLocation,
};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use syn::{visit::Visit, ImplItem, ItemImpl, ItemStruct, Type};

/// Classification of resource cleanup patterns
#[derive(Debug, PartialEq, Eq)]
enum ResourceCleanupType {
    AutoClose,     // Resources that are automatically closed (e.g., File, Socket)
    ThreadJoin,    // Thread handles that need explicit joining
    ExplicitClose, // Resources requiring explicit close() calls (e.g., Connection)
    Generic,       // Generic resources requiring custom cleanup
}

pub struct DropDetector {
    #[allow(dead_code)]
    resource_type_patterns: HashMap<String, ResourcePattern>,
    #[allow(dead_code)]
    known_resource_types: HashSet<String>,
}

impl Default for DropDetector {
    fn default() -> Self {
        Self::new()
    }
}

impl DropDetector {
    pub fn new() -> Self {
        let mut known_resource_types = HashSet::new();

        // Add known resource types
        for rt in RESOURCE_TYPES {
            known_resource_types.insert(rt.to_string());
        }

        Self {
            resource_type_patterns: HashMap::new(),
            known_resource_types,
        }
    }

    fn analyze_type_for_resources(&self, type_def: &TypeDefinition) -> ResourceAnalysis {
        let mut analysis = ResourceAnalysis {
            has_drop_impl: type_def.has_drop_impl,
            ..Default::default()
        };

        // Analyze fields for resource types
        for field in &type_def.fields {
            if let Some(resource_info) = self.classify_field_as_resource(field) {
                analysis.resource_fields.push(resource_info);
                analysis.needs_drop = true;
            }
        }

        // Check for manual cleanup methods
        analysis.has_manual_cleanup = type_def.has_cleanup_methods;

        analysis
    }

    fn classify_field_as_resource(&self, field: &FieldInfo) -> Option<ResourceField> {
        // Check against known resource types
        if self.is_known_resource_type(&field.type_name) {
            return Some(ResourceField {
                field_name: field.name.clone(),
                field_type: field.type_name.clone(),
                is_owning: self.is_owning_type(&field.type_name),
                cleanup_required: self.requires_cleanup(&field.type_name),
            });
        }

        // Pattern-based detection
        if self.matches_resource_pattern(&field.type_name) {
            return Some(ResourceField {
                field_name: field.name.clone(),
                field_type: field.type_name.clone(),
                is_owning: true,
                cleanup_required: true,
            });
        }

        None
    }

    fn is_known_resource_type(&self, type_name: &str) -> bool {
        RESOURCE_TYPES.iter().any(|rt| type_name.contains(rt))
    }

    fn matches_resource_pattern(&self, type_name: &str) -> bool {
        RESOURCE_PATTERNS
            .iter()
            .any(|pattern| type_name.contains(pattern))
    }

    fn is_owning_type(&self, type_name: &str) -> bool {
        // Most resource types are owning by default
        !type_name.contains("Ref") && !type_name.contains("&")
    }

    fn requires_cleanup(&self, type_name: &str) -> bool {
        // Most resource types require cleanup
        !type_name.contains("Arc") && !type_name.contains("Rc")
    }

    /// Classifies a resource type to determine its cleanup pattern
    fn classify_resource_type(field_type: &str) -> ResourceCleanupType {
        match () {
            _ if field_type.contains("File") => ResourceCleanupType::AutoClose,
            _ if field_type.contains("Thread") || field_type.contains("JoinHandle") => {
                ResourceCleanupType::ThreadJoin
            }
            _ if field_type.contains("Connection") => ResourceCleanupType::ExplicitClose,
            _ if field_type.contains("TcpStream") || field_type.contains("Socket") => {
                ResourceCleanupType::AutoClose
            }
            _ => ResourceCleanupType::Generic,
        }
    }

    /// Generates cleanup code for a specific field based on its resource type
    fn generate_field_cleanup(field: &ResourceField) -> String {
        let cleanup_type = Self::classify_resource_type(&field.field_type);

        match cleanup_type {
            ResourceCleanupType::AutoClose => match field.field_type.as_str() {
                t if t.contains("File") => {
                    "        // File handles are automatically closed\n".to_string()
                }
                _ => "        // Network streams are automatically closed\n".to_string(),
            },
            ResourceCleanupType::ThreadJoin => {
                format!(
                    "        if let Some(handle) = self.{}.take() {{\n            let _ = handle.join();\n        }}\n",
                    field.field_name
                )
            }
            ResourceCleanupType::ExplicitClose => {
                format!(
                    "        self.{}.close().unwrap_or_else(|e| {{\n            eprintln!(\"Failed to close connection: {{}}\", e);\n        }});\n",
                    field.field_name
                )
            }
            ResourceCleanupType::Generic => {
                format!("        // Cleanup {} resource\n", field.field_name)
            }
        }
    }

    fn generate_drop_implementation(&self, analysis: &ResourceAnalysis, type_name: &str) -> String {
        let mut drop_impl = String::new();
        drop_impl.push_str(&format!("impl Drop for {} {{\n", type_name));
        drop_impl.push_str("    fn drop(&mut self) {\n");

        for field in &analysis.resource_fields {
            drop_impl.push_str(&Self::generate_field_cleanup(field));
        }

        drop_impl.push_str("    }\n");
        drop_impl.push_str("}\n");
        drop_impl
    }

    fn assess_resource_severity(&self, analysis: &ResourceAnalysis) -> ResourceSeverity {
        let critical_resources = analysis
            .resource_fields
            .iter()
            .filter(|field| self.is_critical_resource(&field.field_type))
            .count();

        if critical_resources > 0 {
            ResourceSeverity::Critical
        } else if analysis.resource_fields.len() > 3 {
            ResourceSeverity::High
        } else if analysis.resource_fields.len() > 1 {
            ResourceSeverity::Medium
        } else {
            ResourceSeverity::Low
        }
    }

    fn is_critical_resource(&self, type_name: &str) -> bool {
        CRITICAL_TYPES.iter().any(|ct| type_name.contains(ct))
    }
}

impl ResourceDetector for DropDetector {
    fn detect_issues(&self, file: &syn::File, _path: &Path) -> Vec<ResourceManagementIssue> {
        let mut visitor = DropVisitor::new();
        visitor.visit_file(file);

        let mut issues = Vec::new();

        for type_def in visitor.type_definitions {
            let resource_analysis = self.analyze_type_for_resources(&type_def);

            if resource_analysis.needs_drop && !resource_analysis.has_drop_impl {
                let severity = self.assess_resource_severity(&resource_analysis);
                let suggested_drop_impl =
                    self.generate_drop_implementation(&resource_analysis, &type_def.name);
                issues.push(ResourceManagementIssue::MissingDrop {
                    type_name: type_def.name.clone(),
                    resource_fields: resource_analysis.resource_fields,
                    suggested_drop_impl,
                    severity,
                    location: SourceLocation {
                        file: String::new(),
                        line: 1,
                        column: 0,
                    }, // TODO: Extract actual location
                });
            }
        }

        issues
    }

    fn detector_name(&self) -> &'static str {
        "DropDetector"
    }

    fn assess_resource_impact(&self, issue: &ResourceManagementIssue) -> ResourceImpact {
        match issue {
            ResourceManagementIssue::MissingDrop { severity, .. } => match severity {
                ResourceSeverity::Critical => ResourceImpact::Critical,
                ResourceSeverity::High => ResourceImpact::High,
                ResourceSeverity::Medium => ResourceImpact::Medium,
                ResourceSeverity::Low => ResourceImpact::Low,
            },
            _ => ResourceImpact::Medium,
        }
    }
}

struct DropVisitor {
    type_definitions: Vec<TypeDefinition>,
    drop_implementations: HashSet<String>,
}

impl DropVisitor {
    fn new() -> Self {
        Self {
            type_definitions: Vec::new(),
            drop_implementations: HashSet::new(),
        }
    }
}

impl<'ast> Visit<'ast> for DropVisitor {
    fn visit_item_struct(&mut self, node: &'ast ItemStruct) {
        let mut fields = Vec::new();

        match &node.fields {
            syn::Fields::Named(named) => {
                for field in &named.named {
                    if let Some(ident) = &field.ident {
                        let type_name = extract_type_name(&field.ty);
                        fields.push(FieldInfo {
                            name: ident.to_string(),
                            type_name,
                        });
                    }
                }
            }
            syn::Fields::Unnamed(unnamed) => {
                for (idx, field) in unnamed.unnamed.iter().enumerate() {
                    let type_name = extract_type_name(&field.ty);
                    fields.push(FieldInfo {
                        name: format!("{}", idx),
                        type_name,
                    });
                }
            }
            _ => {}
        }

        let type_name = node.ident.to_string();
        let has_drop_impl = self.drop_implementations.contains(&type_name);

        self.type_definitions.push(TypeDefinition {
            name: type_name,
            fields,
            has_drop_impl,
            has_cleanup_methods: false, // Will be populated later
        });
    }

    fn visit_item_impl(&mut self, node: &'ast ItemImpl) {
        // Check if this is a Drop implementation
        if is_drop_impl(&node.trait_) {
            if let Some(type_name) = extract_impl_type_name(&node.self_ty) {
                self.drop_implementations.insert(type_name);
            }
        }

        // Check for manual cleanup methods
        if let Some(type_name) = extract_impl_type_name(&node.self_ty) {
            if has_cleanup_methods(&node.items) {
                mark_type_as_having_cleanup(&mut self.type_definitions, &type_name);
            }
        }
    }
}

/// Checks if a trait implementation is for the Drop trait
fn is_drop_impl(trait_ref: &Option<(Option<syn::token::Not>, syn::Path, syn::token::For)>) -> bool {
    if let Some((_, path, _)) = trait_ref {
        path.segments.last().is_some_and(|s| s.ident == "Drop")
    } else {
        false
    }
}

/// Extracts the type name from an impl block's self type
fn extract_impl_type_name(self_ty: &Type) -> Option<String> {
    if let Type::Path(type_path) = self_ty {
        type_path.path.segments.last().map(|s| s.ident.to_string())
    } else {
        None
    }
}

/// Checks if any of the impl items are cleanup methods
fn has_cleanup_methods(items: &[ImplItem]) -> bool {
    items.iter().any(|item| {
        if let ImplItem::Fn(method) = item {
            is_cleanup_method(&method.sig.ident.to_string())
        } else {
            false
        }
    })
}

/// Checks if a method name is a known cleanup method
fn is_cleanup_method(method_name: &str) -> bool {
    CLEANUP_METHOD_NAMES.contains(&method_name)
}

/// Marks a type as having cleanup methods in the type definitions
fn mark_type_as_having_cleanup(type_definitions: &mut [TypeDefinition], type_name: &str) {
    for type_def in type_definitions {
        if type_def.name == type_name {
            type_def.has_cleanup_methods = true;
            break;
        }
    }
}

fn extract_type_name(ty: &Type) -> String {
    match ty {
        Type::Path(type_path) => type_path
            .path
            .segments
            .iter()
            .map(|s| s.ident.to_string())
            .collect::<Vec<_>>()
            .join("::"),
        Type::Reference(reference) => extract_type_name(&reference.elem),
        _ => "Unknown".to_string(),
    }
}

#[derive(Debug, Clone)]
struct TypeDefinition {
    name: String,
    fields: Vec<FieldInfo>,
    has_drop_impl: bool,
    has_cleanup_methods: bool,
}

#[derive(Debug, Clone)]
struct FieldInfo {
    name: String,
    type_name: String,
}

#[derive(Debug, Default)]
struct ResourceAnalysis {
    needs_drop: bool,
    has_drop_impl: bool,
    has_manual_cleanup: bool,
    resource_fields: Vec<ResourceField>,
}

#[derive(Debug, Clone)]
struct ResourcePattern {
    #[allow(dead_code)]
    pattern: String,
    #[allow(dead_code)]
    is_critical: bool,
}

const RESOURCE_TYPES: &[&str] = &[
    "File",
    "TcpStream",
    "UdpSocket",
    "TcpListener",
    "Mutex",
    "RwLock",
    "Condvar",
    "Barrier",
    "Thread",
    "JoinHandle",
    "Child",
    "Process",
    "Box",
    "Rc",
    "Arc",
    "RefCell",
    "BufReader",
    "BufWriter",
    "Cursor",
    "Connection",
    "Client",
    "Database",
    "Transaction",
    "Channel",
    "Sender",
    "Receiver",
    "oneshot",
];

const RESOURCE_PATTERNS: &[&str] = &[
    "Handle",
    "Manager",
    "Pool",
    "Connection",
    "Client",
    "Stream",
    "Reader",
    "Writer",
    "Buffer",
    "Cache",
    "Guard",
    "Lock",
    "Session",
    "Context",
    "Resource",
];

const CRITICAL_TYPES: &[&str] = &[
    "File",
    "TcpStream",
    "Process",
    "Thread",
    "Connection",
    "Database",
];

const CLEANUP_METHOD_NAMES: &[&str] = &[
    "cleanup", "close", "shutdown", "dispose", "destroy", "release", "free", "clear",
];

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

    #[test]
    fn test_classify_resource_type_file() {
        assert_eq!(
            DropDetector::classify_resource_type("std::fs::File"),
            ResourceCleanupType::AutoClose
        );
        assert_eq!(
            DropDetector::classify_resource_type("FileHandle"),
            ResourceCleanupType::AutoClose
        );
    }

    #[test]
    fn test_classify_resource_type_thread() {
        assert_eq!(
            DropDetector::classify_resource_type("std::thread::JoinHandle<()>"),
            ResourceCleanupType::ThreadJoin
        );
        assert_eq!(
            DropDetector::classify_resource_type("Thread"),
            ResourceCleanupType::ThreadJoin
        );
    }

    #[test]
    fn test_classify_resource_type_connection() {
        assert_eq!(
            DropDetector::classify_resource_type("Connection"),
            ResourceCleanupType::ExplicitClose
        );
        assert_eq!(
            DropDetector::classify_resource_type("DatabaseConnection"),
            ResourceCleanupType::ExplicitClose
        );
    }

    #[test]
    fn test_classify_resource_type_network() {
        assert_eq!(
            DropDetector::classify_resource_type("TcpStream"),
            ResourceCleanupType::AutoClose
        );
        assert_eq!(
            DropDetector::classify_resource_type("Socket"),
            ResourceCleanupType::AutoClose
        );
    }

    #[test]
    fn test_classify_resource_type_generic() {
        assert_eq!(
            DropDetector::classify_resource_type("CustomResource"),
            ResourceCleanupType::Generic
        );
        assert_eq!(
            DropDetector::classify_resource_type("Buffer"),
            ResourceCleanupType::Generic
        );
    }

    #[test]
    fn test_generate_field_cleanup() {
        // Test file cleanup
        let file_field = ResourceField {
            field_name: "log_file".to_string(),
            field_type: "std::fs::File".to_string(),
            is_owning: true,
            cleanup_required: true,
        };
        assert_eq!(
            DropDetector::generate_field_cleanup(&file_field),
            "        // File handles are automatically closed\n"
        );

        // Test thread cleanup
        let thread_field = ResourceField {
            field_name: "worker".to_string(),
            field_type: "JoinHandle<()>".to_string(),
            is_owning: true,
            cleanup_required: true,
        };
        assert_eq!(
            DropDetector::generate_field_cleanup(&thread_field),
            "        if let Some(handle) = self.worker.take() {\n            let _ = handle.join();\n        }\n"
        );

        // Test connection cleanup
        let conn_field = ResourceField {
            field_name: "db_conn".to_string(),
            field_type: "Connection".to_string(),
            is_owning: true,
            cleanup_required: true,
        };
        assert_eq!(
            DropDetector::generate_field_cleanup(&conn_field),
            "        self.db_conn.close().unwrap_or_else(|e| {\n            eprintln!(\"Failed to close connection: {}\", e);\n        });\n"
        );

        // Test network stream cleanup
        let stream_field = ResourceField {
            field_name: "tcp".to_string(),
            field_type: "TcpStream".to_string(),
            is_owning: true,
            cleanup_required: true,
        };
        assert_eq!(
            DropDetector::generate_field_cleanup(&stream_field),
            "        // Network streams are automatically closed\n"
        );

        // Test generic resource cleanup
        let generic_field = ResourceField {
            field_name: "buffer".to_string(),
            field_type: "Buffer".to_string(),
            is_owning: true,
            cleanup_required: true,
        };
        assert_eq!(
            DropDetector::generate_field_cleanup(&generic_field),
            "        // Cleanup buffer resource\n"
        );
    }

    #[test]
    fn test_generate_drop_implementation_multiple_resources() {
        let detector = DropDetector::new();
        let analysis = ResourceAnalysis {
            resource_fields: vec![
                ResourceField {
                    field_name: "file".to_string(),
                    field_type: "File".to_string(),
                    is_owning: true,
                    cleanup_required: true,
                },
                ResourceField {
                    field_name: "worker".to_string(),
                    field_type: "JoinHandle<()>".to_string(),
                    is_owning: true,
                    cleanup_required: true,
                },
                ResourceField {
                    field_name: "conn".to_string(),
                    field_type: "Connection".to_string(),
                    is_owning: true,
                    cleanup_required: true,
                },
            ],
            needs_drop: true,
            has_drop_impl: false,
            has_manual_cleanup: false,
        };

        let drop_impl = detector.generate_drop_implementation(&analysis, "MyStruct");

        // Check that the implementation contains expected parts
        assert!(drop_impl.contains("impl Drop for MyStruct"));
        assert!(drop_impl.contains("fn drop(&mut self)"));
        assert!(drop_impl.contains("// File handles are automatically closed"));
        assert!(drop_impl.contains("if let Some(handle) = self.worker.take()"));
        assert!(drop_impl.contains("self.conn.close().unwrap_or_else"));
    }

    #[test]
    fn test_is_drop_impl() {
        use syn::parse_quote;

        // Test with Drop trait implementation
        let drop_trait: Option<(Option<syn::token::Not>, syn::Path, syn::token::For)> =
            Some((None, parse_quote!(Drop), parse_quote!(for)));
        assert!(is_drop_impl(&drop_trait));

        // Test with another trait
        let other_trait: Option<(Option<syn::token::Not>, syn::Path, syn::token::For)> =
            Some((None, parse_quote!(Debug), parse_quote!(for)));
        assert!(!is_drop_impl(&other_trait));

        // Test with qualified Drop trait
        let qualified_drop: Option<(Option<syn::token::Not>, syn::Path, syn::token::For)> =
            Some((None, parse_quote!(std::ops::Drop), parse_quote!(for)));
        assert!(is_drop_impl(&qualified_drop));

        // Test with None
        assert!(!is_drop_impl(&None));
    }

    #[test]
    fn test_extract_impl_type_name() {
        use syn::parse_quote;

        // Test with simple type path
        let simple_type: Type = parse_quote!(MyStruct);
        assert_eq!(
            extract_impl_type_name(&simple_type),
            Some("MyStruct".to_string())
        );

        // Test with qualified type path
        let qualified_type: Type = parse_quote!(module::MyStruct);
        assert_eq!(
            extract_impl_type_name(&qualified_type),
            Some("MyStruct".to_string())
        );

        // Test with generic type
        let generic_type: Type = parse_quote!(MyStruct<T>);
        assert_eq!(
            extract_impl_type_name(&generic_type),
            Some("MyStruct".to_string())
        );

        // Test with reference type (should return None)
        let ref_type: Type = parse_quote!(&MyStruct);
        assert_eq!(extract_impl_type_name(&ref_type), None);

        // Test with tuple type (should return None)
        let tuple_type: Type = parse_quote!((String, i32));
        assert_eq!(extract_impl_type_name(&tuple_type), None);
    }

    #[test]
    fn test_is_cleanup_method() {
        // Test known cleanup method names
        assert!(is_cleanup_method("cleanup"));
        assert!(is_cleanup_method("close"));
        assert!(is_cleanup_method("shutdown"));
        assert!(is_cleanup_method("dispose"));
        assert!(is_cleanup_method("destroy"));
        assert!(is_cleanup_method("release"));
        assert!(is_cleanup_method("free"));
        assert!(is_cleanup_method("clear"));

        // Test non-cleanup method names
        assert!(!is_cleanup_method("new"));
        assert!(!is_cleanup_method("create"));
        assert!(!is_cleanup_method("open"));
        assert!(!is_cleanup_method("run"));
        assert!(!is_cleanup_method("execute"));
        assert!(!is_cleanup_method("process"));
    }

    #[test]
    fn test_has_cleanup_methods() {
        use syn::parse_quote;

        // Test with cleanup methods present
        let items_with_cleanup: Vec<ImplItem> = vec![
            parse_quote!(
                fn new() -> Self {
                    Self {}
                }
            ),
            parse_quote!(
                fn cleanup(&mut self) { /* cleanup logic */
                }
            ),
            parse_quote!(
                fn process(&self) { /* process logic */
                }
            ),
        ];
        assert!(has_cleanup_methods(&items_with_cleanup));

        // Test with only close method
        let items_with_close: Vec<ImplItem> = vec![parse_quote!(
            fn close(&mut self) { /* close logic */
            }
        )];
        assert!(has_cleanup_methods(&items_with_close));

        // Test without cleanup methods
        let items_without_cleanup: Vec<ImplItem> = vec![
            parse_quote!(
                fn new() -> Self {
                    Self {}
                }
            ),
            parse_quote!(
                fn process(&self) { /* process logic */
                }
            ),
            parse_quote!(
                fn get_data(&self) -> String {
                    String::new()
                }
            ),
        ];
        assert!(!has_cleanup_methods(&items_without_cleanup));

        // Test with empty items
        let empty_items: Vec<ImplItem> = vec![];
        assert!(!has_cleanup_methods(&empty_items));

        // Test with const item (not a function)
        let items_with_const: Vec<ImplItem> = vec![
            parse_quote!(
                const SIZE: usize = 100;
            ),
            parse_quote!(
                fn process(&self) { /* process logic */
                }
            ),
        ];
        assert!(!has_cleanup_methods(&items_with_const));
    }

    #[test]
    fn test_mark_type_as_having_cleanup() {
        let mut type_definitions = vec![
            TypeDefinition {
                name: "TypeA".to_string(),
                fields: vec![],
                has_drop_impl: false,
                has_cleanup_methods: false,
            },
            TypeDefinition {
                name: "TypeB".to_string(),
                fields: vec![],
                has_drop_impl: false,
                has_cleanup_methods: false,
            },
            TypeDefinition {
                name: "TypeC".to_string(),
                fields: vec![],
                has_drop_impl: true,
                has_cleanup_methods: false,
            },
        ];

        // Mark TypeB as having cleanup
        mark_type_as_having_cleanup(&mut type_definitions, "TypeB");
        assert!(!type_definitions[0].has_cleanup_methods);
        assert!(type_definitions[1].has_cleanup_methods);
        assert!(!type_definitions[2].has_cleanup_methods);

        // Mark TypeC as having cleanup (already has drop impl)
        mark_type_as_having_cleanup(&mut type_definitions, "TypeC");
        assert!(!type_definitions[0].has_cleanup_methods);
        assert!(type_definitions[1].has_cleanup_methods);
        assert!(type_definitions[2].has_cleanup_methods);

        // Try to mark non-existent type (should do nothing)
        mark_type_as_having_cleanup(&mut type_definitions, "TypeD");
        assert!(!type_definitions[0].has_cleanup_methods);
        assert!(type_definitions[1].has_cleanup_methods);
        assert!(type_definitions[2].has_cleanup_methods);
    }
}