debtmap 0.17.0

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
use super::{
    AsyncResourceIssueType, CancellationSafety, ResourceDetector, ResourceImpact,
    ResourceManagementIssue, ResourceType, SourceLocation,
};
use std::path::Path;
use syn::{visit::Visit, Expr, ExprAwait, ExprCall, ExprMethodCall, ItemFn, Stmt};

pub struct AsyncResourceDetector {
    cancellation_analyzer: CancellationAnalyzer,
}

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

impl AsyncResourceDetector {
    pub fn new() -> Self {
        Self {
            cancellation_analyzer: CancellationAnalyzer::new(),
        }
    }

    /// Pure function to classify resource type based on path string patterns
    /// This is extracted to reduce complexity and enable better testing
    fn classify_resource_type_from_path(path_str: &str) -> ResourceType {
        match () {
            _ if path_str.contains("File") => ResourceType::FileHandle,
            _ if path_str.contains("TcpStream") || path_str.contains("Socket") => {
                ResourceType::NetworkConnection
            }
            _ if path_str.contains("Connection") || path_str.contains("Database") => {
                ResourceType::DatabaseConnection
            }
            _ if path_str.contains("Thread") => ResourceType::ThreadHandle,
            _ if path_str.contains("Mutex") => ResourceType::Mutex,
            _ if path_str.contains("Channel") => ResourceType::Channel,
            _ => ResourceType::SystemHandle,
        }
    }

    fn analyze_async_resource_usage(&self, async_fn: &AsyncFunction) -> AsyncResourceUsage {
        let mut usage = AsyncResourceUsage::default();

        // Track resource acquisition and cleanup across await points
        let await_points = self.find_await_points(async_fn);
        let resource_operations = self.find_resource_operations(async_fn);

        for resource_op in resource_operations {
            let cancellation_analysis = self
                .cancellation_analyzer
                .analyze_resource_cancellation_safety(&resource_op, &await_points);

            if !cancellation_analysis.is_safe {
                usage.issues.push(AsyncResourceIssueInfo {
                    issue_type: AsyncResourceIssueType::CancellationUnsafe,
                    cancellation_safety: CancellationSafety::Unsafe,
                    mitigation_strategy: self.suggest_cancellation_mitigation(&resource_op),
                    location: resource_op.location.clone(),
                });
            }
        }

        // Check for Drop implementations in async context
        let drop_calls = self.find_drop_calls_in_async(async_fn);
        for drop_call in drop_calls {
            usage.issues.push(AsyncResourceIssueInfo {
                issue_type: AsyncResourceIssueType::DropInAsync,
                cancellation_safety: CancellationSafety::Unknown,
                mitigation_strategy: "Move resource cleanup outside async context".to_string(),
                location: drop_call.location,
            });
        }

        usage
    }

    fn find_await_points(&self, async_fn: &AsyncFunction) -> Vec<AwaitPoint> {
        let mut await_points = Vec::new();
        let mut visitor = AwaitVisitor::new();

        for stmt in &async_fn.stmts {
            visitor.visit_stmt(stmt);
        }

        for (expr, line) in visitor.await_exprs {
            await_points.push(AwaitPoint {
                location: SourceLocation {
                    file: String::new(),
                    line,
                    column: 0,
                },
                expression: format!("{:?}", expr),
                is_resource_operation: self.is_resource_operation_expr(&expr),
            });
        }

        await_points
    }

    fn find_resource_operations(&self, async_fn: &AsyncFunction) -> Vec<ResourceOperation> {
        let mut operations = Vec::new();
        let mut visitor = ResourceOpVisitor::new();

        for stmt in &async_fn.stmts {
            visitor.visit_stmt(stmt);
        }

        for (op_type, expr, line) in visitor.resource_ops {
            operations.push(ResourceOperation {
                operation_type: op_type,
                resource_type: self.infer_resource_type_from_expr(&expr),
                location: SourceLocation {
                    file: String::new(),
                    line,
                    column: 0,
                },
                variable_name: None,
            });
        }

        operations
    }

    fn find_drop_calls_in_async(&self, async_fn: &AsyncFunction) -> Vec<DropCall> {
        let mut drop_calls = Vec::new();
        let mut visitor = DropCallVisitor::new();

        for stmt in &async_fn.stmts {
            visitor.visit_stmt(stmt);
        }

        for line in visitor.drop_calls {
            drop_calls.push(DropCall {
                location: SourceLocation {
                    file: String::new(),
                    line,
                    column: 0,
                },
            });
        }

        drop_calls
    }

    fn is_resource_operation_expr(&self, expr: &Expr) -> bool {
        match expr {
            Expr::Call(call) => self.is_resource_function_call(call),
            Expr::MethodCall(method) => self.is_resource_method_call(method),
            _ => false,
        }
    }

    fn is_resource_function_call(&self, call: &ExprCall) -> bool {
        // Check if this is a resource-related function call
        if let Expr::Path(path) = &*call.func {
            let path_str = path
                .path
                .segments
                .iter()
                .map(|s| s.ident.to_string())
                .collect::<Vec<_>>()
                .join("::");

            RESOURCE_FUNCTIONS.iter().any(|rf| path_str.contains(rf))
        } else {
            false
        }
    }

    fn is_resource_method_call(&self, method: &ExprMethodCall) -> bool {
        let method_name = method.method.to_string();
        RESOURCE_METHODS.iter().any(|rm| method_name == *rm)
    }

    fn infer_resource_type_from_expr(&self, expr: &Expr) -> ResourceType {
        match expr {
            Expr::Call(call) => {
                if let Expr::Path(path) = &*call.func {
                    let path_str = path
                        .path
                        .segments
                        .iter()
                        .map(|s| s.ident.to_string())
                        .collect::<Vec<_>>()
                        .join("::");

                    Self::classify_resource_type_from_path(&path_str)
                } else {
                    ResourceType::SystemHandle
                }
            }
            _ => ResourceType::SystemHandle,
        }
    }

    fn suggest_cancellation_mitigation(&self, resource_op: &ResourceOperation) -> String {
        match resource_op.resource_type {
            ResourceType::FileHandle => {
                "Use tokio::fs or async-std::fs for cancellation-safe file operations".to_string()
            }
            ResourceType::NetworkConnection => {
                "Use connection pools or ensure proper cleanup in Drop implementation".to_string()
            }
            ResourceType::DatabaseConnection => {
                "Use async database drivers with proper cancellation handling".to_string()
            }
            _ => "Ensure resource cleanup in cancellation scenarios using RAII or finally blocks"
                .to_string(),
        }
    }
}

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

        let mut issues = Vec::new();

        for async_fn in visitor.async_functions {
            let resource_usage = self.analyze_async_resource_usage(&async_fn);

            for issue in resource_usage.issues {
                issues.push(ResourceManagementIssue::AsyncResourceIssue {
                    function_name: async_fn.name.clone(),
                    issue_type: issue.issue_type,
                    cancellation_safety: issue.cancellation_safety,
                    mitigation_strategy: issue.mitigation_strategy,
                    location: SourceLocation {
                        file: String::new(),
                        line: 1,
                        column: 0,
                    }, // TODO: Extract actual location
                });
            }
        }

        issues
    }

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

    fn assess_resource_impact(&self, issue: &ResourceManagementIssue) -> ResourceImpact {
        match issue {
            ResourceManagementIssue::AsyncResourceIssue { issue_type, .. } => match issue_type {
                AsyncResourceIssueType::ResourceNotCleaned => ResourceImpact::High,
                AsyncResourceIssueType::CancellationUnsafe => ResourceImpact::Critical,
                AsyncResourceIssueType::SharedResourceRace => ResourceImpact::Critical,
                AsyncResourceIssueType::DropInAsync => ResourceImpact::Medium,
            },
            _ => ResourceImpact::Medium,
        }
    }
}

struct AsyncFnVisitor {
    async_functions: Vec<AsyncFunction>,
}

impl AsyncFnVisitor {
    fn new() -> Self {
        Self {
            async_functions: Vec::new(),
        }
    }
}

impl<'ast> Visit<'ast> for AsyncFnVisitor {
    fn visit_item_fn(&mut self, node: &'ast ItemFn) {
        if node.sig.asyncness.is_some() {
            let name = node.sig.ident.to_string();
            let stmts = node.block.stmts.clone();

            self.async_functions.push(AsyncFunction { name, stmts });
        }
    }
}

struct AwaitVisitor {
    await_exprs: Vec<(Expr, usize)>,
    current_line: usize,
}

impl AwaitVisitor {
    fn new() -> Self {
        Self {
            await_exprs: Vec::new(),
            current_line: 1,
        }
    }
}

impl<'ast> Visit<'ast> for AwaitVisitor {
    fn visit_expr_await(&mut self, node: &'ast ExprAwait) {
        self.await_exprs
            .push((*node.base.clone(), self.current_line));
        self.current_line += 1;
    }
}

struct ResourceOpVisitor {
    resource_ops: Vec<(ResourceOperationType, Expr, usize)>,
    current_line: usize,
}

impl ResourceOpVisitor {
    fn new() -> Self {
        Self {
            resource_ops: Vec::new(),
            current_line: 1,
        }
    }
}

impl<'ast> Visit<'ast> for ResourceOpVisitor {
    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
        if let Some(operation) = resource_operation_from_call(node, self.current_line) {
            self.resource_ops.push(operation);
            self.current_line += 1;
        }
    }
}

fn resource_operation_from_call(
    node: &ExprCall,
    line: usize,
) -> Option<(ResourceOperationType, Expr, usize)> {
    resource_path_from_call(node)
        .filter(|path| is_resource_function_path(path))
        .map(|path| {
            (
                classify_resource_operation_type(&path),
                Expr::Call(node.clone()),
                line,
            )
        })
}

fn resource_path_from_call(node: &ExprCall) -> Option<String> {
    match &*node.func {
        Expr::Path(path) => Some(path_to_string(&path.path)),
        _ => None,
    }
}

fn path_to_string(path: &syn::Path) -> String {
    path.segments
        .iter()
        .map(|segment| segment.ident.to_string())
        .collect::<Vec<_>>()
        .join("::")
}

fn is_resource_function_path(path: &str) -> bool {
    RESOURCE_FUNCTIONS
        .iter()
        .any(|resource| path.contains(resource))
}

fn classify_resource_operation_type(path: &str) -> ResourceOperationType {
    match () {
        _ if path.contains("open") || path.contains("new") => ResourceOperationType::Acquisition,
        _ if path.contains("close") || path.contains("drop") => ResourceOperationType::Release,
        _ => ResourceOperationType::Transfer,
    }
}

struct DropCallVisitor {
    drop_calls: Vec<usize>,
    current_line: usize,
}

impl DropCallVisitor {
    fn new() -> Self {
        Self {
            drop_calls: Vec::new(),
            current_line: 1,
        }
    }
}

impl<'ast> Visit<'ast> for DropCallVisitor {
    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
        if let Expr::Path(path) = &*node.func {
            if path.path.segments.last().is_some_and(|s| s.ident == "drop") {
                self.drop_calls.push(self.current_line);
            }
        }
        self.current_line += 1;
    }
}

pub struct CancellationAnalyzer;

impl CancellationAnalyzer {
    pub fn new() -> Self {
        Self
    }

    pub fn analyze_resource_cancellation_safety(
        &self,
        resource_op: &ResourceOperation,
        await_points: &[AwaitPoint],
    ) -> CancellationAnalysis {
        // Check if resource is acquired before an await point
        // and not properly cleaned up after
        let mut analysis = CancellationAnalysis {
            is_safe: true,
            reason: String::new(),
        };

        if resource_op.operation_type == ResourceOperationType::Acquisition {
            // Check if there's an await point after acquisition
            let has_await_after = await_points
                .iter()
                .any(|ap| ap.location.line > resource_op.location.line);

            if has_await_after {
                analysis.is_safe = false;
                analysis.reason =
                    "Resource acquired before await point without proper cleanup".to_string();
            }
        }

        analysis
    }
}

#[derive(Debug, Clone)]
struct AsyncFunction {
    name: String,
    stmts: Vec<Stmt>,
}

#[derive(Debug, Default)]
struct AsyncResourceUsage {
    issues: Vec<AsyncResourceIssueInfo>,
}

#[derive(Debug)]
struct AsyncResourceIssueInfo {
    issue_type: AsyncResourceIssueType,
    cancellation_safety: CancellationSafety,
    mitigation_strategy: String,
    #[allow(dead_code)]
    location: SourceLocation,
}

#[derive(Debug)]
pub(super) struct AwaitPoint {
    location: SourceLocation,
    #[allow(dead_code)]
    expression: String,
    #[allow(dead_code)]
    is_resource_operation: bool,
}

#[derive(Debug)]
pub(super) struct ResourceOperation {
    operation_type: ResourceOperationType,
    resource_type: ResourceType,
    location: SourceLocation,
    #[allow(dead_code)]
    variable_name: Option<String>,
}

#[derive(Debug)]
struct DropCall {
    location: SourceLocation,
}

#[derive(Debug, PartialEq)]
enum ResourceOperationType {
    Acquisition,
    Release,
    Transfer,
}

#[derive(Debug)]
pub struct CancellationAnalysis {
    pub is_safe: bool,
    pub reason: String,
}

const RESOURCE_FUNCTIONS: &[&str] = &[
    "File::open",
    "File::create",
    "TcpStream::connect",
    "TcpListener::bind",
    "Thread::spawn",
    "Connection::open",
    "Database::connect",
];

const RESOURCE_METHODS: &[&str] = &[
    "open", "create", "connect", "bind", "spawn", "close", "shutdown", "join",
];

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

    #[test]
    fn test_classify_resource_type_file_handle() {
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("std::fs::File::open"),
            ResourceType::FileHandle
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("tokio::fs::File"),
            ResourceType::FileHandle
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("OpenFile"),
            ResourceType::FileHandle
        );
    }

    #[test]
    fn test_classify_resource_type_network_connection() {
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("TcpStream::connect"),
            ResourceType::NetworkConnection
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("tokio::net::TcpStream"),
            ResourceType::NetworkConnection
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("Socket::new"),
            ResourceType::NetworkConnection
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("UdpSocket::bind"),
            ResourceType::NetworkConnection
        );
    }

    #[test]
    fn test_classify_resource_type_database_connection() {
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("Connection::open"),
            ResourceType::DatabaseConnection
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("Database::connect"),
            ResourceType::DatabaseConnection
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("PgConnection::new"),
            ResourceType::DatabaseConnection
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("MySqlDatabase"),
            ResourceType::DatabaseConnection
        );
    }

    #[test]
    fn test_classify_resource_type_thread_handle() {
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("Thread::spawn"),
            ResourceType::ThreadHandle
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("std::thread::Thread"),
            ResourceType::ThreadHandle
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("JoinThread"),
            ResourceType::ThreadHandle
        );
    }

    #[test]
    fn test_classify_resource_type_mutex() {
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("Mutex::new"),
            ResourceType::Mutex
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("std::sync::Mutex"),
            ResourceType::Mutex
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("RwLockMutex"),
            ResourceType::Mutex
        );
    }

    #[test]
    fn test_classify_resource_type_channel() {
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("Channel::new"),
            ResourceType::Channel
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("mpsc::Channel"),
            ResourceType::Channel
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("SyncChannel"),
            ResourceType::Channel
        );
    }

    #[test]
    fn test_classify_resource_type_system_handle_default() {
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("SomeOtherType"),
            ResourceType::SystemHandle
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("UnknownResource"),
            ResourceType::SystemHandle
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path(""),
            ResourceType::SystemHandle
        );
    }

    #[test]
    fn test_classify_resource_type_priority_order() {
        // Test that File takes precedence over Connection when both are present
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("FileConnection"),
            ResourceType::FileHandle
        );

        // Test that TcpStream takes precedence over generic Connection
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("TcpStreamConnection"),
            ResourceType::NetworkConnection
        );
    }

    #[test]
    fn test_classify_resource_type_case_sensitive() {
        // The function is case-sensitive, so lowercase variants should not match
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("file"),
            ResourceType::SystemHandle
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("mutex"),
            ResourceType::SystemHandle
        );
    }

    #[test]
    fn test_classify_resource_type_partial_matches() {
        // Test that partial matches work correctly
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("AsyncFileReader"),
            ResourceType::FileHandle
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("TcpStreamWrapper"),
            ResourceType::NetworkConnection
        );
        assert_eq!(
            AsyncResourceDetector::classify_resource_type_from_path("DatabasePool"),
            ResourceType::DatabaseConnection
        );
    }

    #[test]
    fn test_resource_path_from_call_extracts_path_segments() {
        let call = parse_call_expr("tokio::fs::File::open(path)");

        assert_eq!(
            resource_path_from_call(&call),
            Some("tokio::fs::File::open".to_string())
        );
    }

    #[test]
    fn test_resource_path_from_call_ignores_non_path_callee() {
        let call = parse_call_expr("(factory())(path)");

        assert_eq!(resource_path_from_call(&call), None);
    }

    #[test]
    fn test_classify_resource_operation_type() {
        assert_eq!(
            classify_resource_operation_type("std::fs::File::open"),
            ResourceOperationType::Acquisition
        );
        assert_eq!(
            classify_resource_operation_type("resource::drop"),
            ResourceOperationType::Release
        );
        assert_eq!(
            classify_resource_operation_type("TcpStream::connect"),
            ResourceOperationType::Transfer
        );
    }

    #[test]
    fn test_resource_operation_from_call_records_resource_function() {
        let call = parse_call_expr("std::fs::File::open(path)");
        let operation = resource_operation_from_call(&call, 42);

        assert!(matches!(
            operation,
            Some((ResourceOperationType::Acquisition, Expr::Call(_), 42))
        ));
    }

    #[test]
    fn test_resource_operation_from_call_ignores_untracked_function() {
        let call = parse_call_expr("std::mem::drop(resource)");

        assert!(resource_operation_from_call(&call, 1).is_none());
    }

    fn parse_call_expr(source: &str) -> ExprCall {
        match syn::parse_str(source).expect("test expression should parse") {
            Expr::Call(call) => call,
            _ => panic!("test expression should be a call"),
        }
    }
}