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
use crate::core::{DebtItem, DebtType, Priority};
use crate::debt::suppression::SuppressionContext;
use std::path::Path;
use syn::visit::Visit;
use syn::{Expr, ExprMethodCall, ExprTry, File, ItemFn};

pub struct ContextLossAnalyzer<'a> {
    items: Vec<DebtItem>,
    current_file: &'a Path,
    suppression: Option<&'a SuppressionContext>,
    in_test_function: bool,
    question_mark_count: usize,
    current_function: Option<usize>,
}

impl<'a> ContextLossAnalyzer<'a> {
    pub fn new(file_path: &'a Path, suppression: Option<&'a SuppressionContext>) -> Self {
        Self {
            items: Vec::new(),
            current_file: file_path,
            suppression,
            in_test_function: false,
            question_mark_count: 0,
            current_function: None,
        }
    }

    pub fn detect(mut self, file: &File) -> Vec<DebtItem> {
        self.visit_file(file);
        self.items
    }

    fn get_line_number(&self, span: proc_macro2::Span) -> usize {
        span.start().line
    }

    fn add_debt_item(&mut self, line: usize, pattern: ContextLossPattern, context: &str) {
        let debt_type = DebtType::ErrorSwallowing {
            pattern: pattern.to_string(),
            context: Some(context.to_string()),
        };

        // Check if this item is suppressed
        if let Some(checker) = self.suppression {
            if checker.is_suppressed(line, &debt_type) {
                return;
            }
        }

        let priority = self.determine_priority(&pattern);
        let message = format!("{}: {}", pattern.description(), pattern.remediation());

        self.items.push(DebtItem {
            id: format!("context-loss-{}-{}", self.current_file.display(), line),
            debt_type,
            priority,
            file: self.current_file.to_path_buf(),
            line,
            column: None,
            message,
            context: Some(context.to_string()),
        });
    }

    fn determine_priority(&self, pattern: &ContextLossPattern) -> Priority {
        // Lower priority for test code
        if self.in_test_function {
            return Priority::Low;
        }

        match pattern {
            ContextLossPattern::MapErrDiscardingOriginal => Priority::Medium,
            ContextLossPattern::AnyhowWithoutContext => Priority::Medium,
            ContextLossPattern::QuestionMarkChain => Priority::Low,
            ContextLossPattern::StringErrorConversion => Priority::High,
            ContextLossPattern::IntoErrorConversion => Priority::Medium,
        }
    }

    fn check_map_err_patterns(&mut self, method_call: &ExprMethodCall) {
        if method_call.method == "map_err" {
            let line = self.get_line_number(method_call.method.span());

            // Check if the closure discards the original error
            if let Some(arg) = method_call.args.first() {
                let discards_original = match arg {
                    Expr::Closure(closure) => {
                        // Check if the closure ignores its parameter
                        if closure
                            .inputs
                            .iter()
                            .any(|pat| matches!(pat, syn::Pat::Wild(_)))
                        {
                            true
                        } else {
                            // Check if the body doesn't reference the error parameter
                            // This is a simplified check
                            match &*closure.body {
                                Expr::Lit(_) => true, // Just returns a literal
                                Expr::Call(call) => {
                                    // Check if it's a simple constructor without using the error
                                    !format!("{}", quote::quote!(#call)).contains("e")
                                }
                                Expr::Path(_) => true, // Simple enum variant like MyError::Simple
                                Expr::Macro(mac) => {
                                    // For macros like format!, check if error param is used
                                    let tokens = format!("{}", quote::quote!(#mac));
                                    // format! macro with error parameter is considered context loss
                                    // because it converts to string
                                    tokens.contains("format") || !tokens.contains("e")
                                }
                                _ => false,
                            }
                        }
                    }
                    _ => false,
                };

                if discards_original {
                    self.add_debt_item(
                        line,
                        ContextLossPattern::MapErrDiscardingOriginal,
                        "map_err discards original error context",
                    );
                }
            }
        }
    }

    fn check_context_methods(&mut self, method_call: &ExprMethodCall) {
        let method_name = method_call.method.to_string();

        // Check for anyhow-style methods without context
        if method_name == "with_context" || method_name == "context" {
            // This is good - they're adding context
            return;
        }

        // Check for into() conversions that might lose context
        // Only flag if the receiver looks like an error variable
        if method_name == "into" {
            if !Self::receiver_looks_like_error(&method_call.receiver) {
                return;
            }

            let line = self.get_line_number(method_call.method.span());
            self.add_debt_item(
                line,
                ContextLossPattern::IntoErrorConversion,
                "into() conversion may lose error context",
            );
        }
    }

    fn check_string_conversions(&mut self, method_call: &ExprMethodCall) {
        let method_name = method_call.method.to_string();

        if method_name == "to_string" || method_name == "to_owned" {
            // Only flag if the receiver looks like an error variable
            // Without type information, we use naming heuristics
            if !Self::receiver_looks_like_error(&method_call.receiver) {
                return;
            }

            let line = self.get_line_number(method_call.method.span());
            self.add_debt_item(
                line,
                ContextLossPattern::StringErrorConversion,
                "Converting error to string loses type information",
            );
        }
    }

    /// Check if the receiver of a method call looks like an error variable.
    /// Uses naming heuristics since we don't have type information.
    fn receiver_looks_like_error(receiver: &Expr) -> bool {
        match receiver {
            // Direct variable access: err.to_string(), e.to_string(), error.to_string()
            Expr::Path(path) => {
                if let Some(ident) = path.path.get_ident() {
                    let name = ident.to_string().to_lowercase();
                    matches!(name.as_str(), "err" | "error" | "e")
                } else {
                    false
                }
            }
            // Method call chain: something.unwrap_err().to_string()
            Expr::MethodCall(inner) => {
                let method = inner.method.to_string();
                matches!(method.as_str(), "unwrap_err" | "expect_err")
            }
            // Try expression: (expr?).to_string() - unlikely but check anyway
            Expr::Try(_) => false,
            _ => false,
        }
    }
}

impl<'a> Visit<'_> for ContextLossAnalyzer<'a> {
    fn visit_item_fn(&mut self, node: &ItemFn) {
        let was_in_test = self.in_test_function;
        let prev_count = self.question_mark_count;
        let prev_func = self.current_function;

        self.in_test_function = node
            .attrs
            .iter()
            .any(|attr| attr.path().get_ident().map(|i| i.to_string()).as_deref() == Some("test"));

        // Reset question mark count for each function
        self.question_mark_count = 0;
        self.current_function = Some(self.get_line_number(node.sig.fn_token.span));

        syn::visit::visit_item_fn(self, node);

        self.in_test_function = was_in_test;
        self.question_mark_count = prev_count;
        self.current_function = prev_func;
    }

    fn visit_expr_method_call(&mut self, node: &ExprMethodCall) {
        self.check_map_err_patterns(node);
        self.check_context_methods(node);
        self.check_string_conversions(node);
        syn::visit::visit_expr_method_call(self, node);
    }

    fn visit_expr_try(&mut self, node: &ExprTry) {
        // Track total number of ? operators in current function
        self.question_mark_count += 1;

        if self.question_mark_count > 3 {
            let line = self.get_line_number(node.question_token.span);
            self.add_debt_item(
                line,
                ContextLossPattern::QuestionMarkChain,
                "Long chain of ? operators without context",
            );
        }

        syn::visit::visit_expr_try(self, node);
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ContextLossPattern {
    MapErrDiscardingOriginal,
    AnyhowWithoutContext,
    QuestionMarkChain,
    StringErrorConversion,
    IntoErrorConversion,
}

impl std::fmt::Display for ContextLossPattern {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.description())
    }
}

impl ContextLossPattern {
    fn description(&self) -> &'static str {
        match self {
            Self::MapErrDiscardingOriginal => "map_err discards original error",
            Self::AnyhowWithoutContext => "anyhow error without context",
            Self::QuestionMarkChain => "Long ? operator chain",
            Self::StringErrorConversion => "Error converted to string",
            Self::IntoErrorConversion => "Generic into() error conversion",
        }
    }

    fn remediation(&self) -> &'static str {
        match self {
            Self::MapErrDiscardingOriginal => "Include original error as source or in message",
            Self::AnyhowWithoutContext => "Use .context() or .with_context() to add information",
            Self::QuestionMarkChain => "Add context at key points in the error chain",
            Self::StringErrorConversion => "Preserve error type or use structured error types",
            Self::IntoErrorConversion => "Use explicit error conversion with context preservation",
        }
    }
}

pub fn analyze_error_context(
    file: &File,
    file_path: &Path,
    suppression: Option<&SuppressionContext>,
) -> Vec<DebtItem> {
    let analyzer = ContextLossAnalyzer::new(file_path, suppression);
    analyzer.detect(file)
}

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

    #[test]
    fn test_map_err_discarding_original() {
        let code = r#"
            fn example() -> Result<i32, String> {
                some_function()
                    .map_err(|_| "Something went wrong".to_string())
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        assert!(!items.is_empty());
        assert!(items[0].message.contains("map_err"));
        assert!(items[0].message.contains("discards"));
    }

    #[test]
    fn test_string_error_conversion() {
        let code = r#"
            fn example() {
                let err = std::io::Error::new(std::io::ErrorKind::Other, "test");
                let msg = err.to_string();
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        assert!(!items.is_empty());
        assert!(items[0].message.contains("string"));
    }

    #[test]
    fn test_question_mark_chain() {
        let code = r#"
            fn example() -> Result<i32, Box<dyn std::error::Error>> {
                let a = func1()?;
                let b = func2()?;
                let c = func3()?;
                let d = func4()?;
                let e = func5()?;
                Ok(e)
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        // Should detect long chain of ? operators
        assert!(!items.is_empty());
    }

    #[test]
    fn test_into_conversion() {
        let code = r#"
            fn example() -> Result<(), Box<dyn std::error::Error>> {
                let err = std::io::Error::new(std::io::ErrorKind::Other, "test");
                Err(err.into())
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        assert!(!items.is_empty());
        assert!(items[0].message.contains("into()"));
    }

    #[test]
    fn test_good_context_handling() {
        let code = r#"
            fn example() -> Result<i32, anyhow::Error> {
                some_function()
                    .with_context(|| "Failed to call some_function")?;
                Ok(42)
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let _items = analyze_error_context(&file, Path::new("test.rs"), None);

        // Should not detect issues when context is properly added
        // Note: Our simple analysis might still flag the ?, but that's ok
        // In a real implementation we'd have more sophisticated analysis
    }

    #[test]
    fn test_map_err_with_proper_context() {
        let code = r#"
            fn example() -> Result<i32, String> {
                some_function()
                    .map_err(|e| format!("Failed to process: {}", e))
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        // Should still detect issue because we're using format! which includes original error
        // but the heuristic might not catch this properly
        assert!(!items.is_empty());
    }

    #[test]
    fn test_map_err_closure_with_wildcard() {
        let code = r#"
            fn example() -> Result<i32, String> {
                some_function()
                    .map_err(|_| "Generic error".to_string())
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        assert!(!items.is_empty());
        assert!(items[0].message.contains("map_err"));
        assert!(items[0].message.contains("discards"));
    }

    #[test]
    fn test_map_err_simple_constructor() {
        let code = r#"
            fn example() -> Result<i32, MyError> {
                some_function()
                    .map_err(|e| MyError::Simple)
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        assert!(!items.is_empty());
        assert!(items[0].message.contains("map_err"));
    }

    #[test]
    fn test_into_conversion_detection() {
        let code = r#"
            fn example() -> Result<(), Box<dyn std::error::Error>> {
                let err = std::io::Error::new(std::io::ErrorKind::Other, "test");
                result.map_err(|e| e.into())
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        assert!(!items.is_empty());
        let into_items: Vec<_> = items
            .iter()
            .filter(|item| item.message.contains("into()"))
            .collect();
        assert!(!into_items.is_empty());
    }

    #[test]
    fn test_context_loss_priority_test_function() {
        let code = r#"
            #[test]
            fn test_example() {
                some_function()
                    .map_err(|_| "test error".to_string())
                    .unwrap();
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        if !items.is_empty() {
            // Should have low priority for test functions
            assert_eq!(items[0].priority, Priority::Low);
        }
    }

    #[test]
    fn test_long_question_mark_chain() {
        let code = r#"
            fn example() -> Result<i32, Box<dyn std::error::Error>> {
                let a = func1()?;
                let b = func2()?;
                let c = func3()?;
                let d = func4()?;
                let e = func5()?; // This should trigger the warning
                Ok(e)
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        let question_mark_items: Vec<_> = items
            .iter()
            .filter(|item| item.message.contains("? operator"))
            .collect();
        assert!(!question_mark_items.is_empty());
    }

    #[test]
    fn test_error_to_owned_conversion() {
        let code = r#"
            fn example() {
                let err = std::io::Error::new(std::io::ErrorKind::Other, "test");
                let owned = err.to_owned();
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        let string_conversion_items: Vec<_> = items
            .iter()
            .filter(|item| item.message.contains("string"))
            .collect();
        assert!(!string_conversion_items.is_empty());
    }

    #[test]
    fn test_context_loss_pattern_descriptions() {
        use ContextLossPattern::*;

        assert_eq!(
            MapErrDiscardingOriginal.description(),
            "map_err discards original error"
        );
        assert_eq!(
            AnyhowWithoutContext.description(),
            "anyhow error without context"
        );
        assert_eq!(QuestionMarkChain.description(), "Long ? operator chain");
        assert_eq!(
            StringErrorConversion.description(),
            "Error converted to string"
        );
        assert_eq!(
            IntoErrorConversion.description(),
            "Generic into() error conversion"
        );
    }

    #[test]
    fn test_context_loss_pattern_remediations() {
        use ContextLossPattern::*;

        assert!(MapErrDiscardingOriginal
            .remediation()
            .contains("Include original error"));
        assert!(AnyhowWithoutContext.remediation().contains("context"));
        assert!(QuestionMarkChain.remediation().contains("Add context"));
        assert!(StringErrorConversion
            .remediation()
            .contains("Preserve error type"));
        assert!(IntoErrorConversion
            .remediation()
            .contains("explicit error conversion"));
    }

    #[test]
    fn test_suppression_integration() {
        use crate::debt::suppression::SuppressionContext;

        let code = r#"
            fn example() -> Result<i32, String> {
                some_function()
                    .map_err(|_| "Something went wrong".to_string())
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");

        // Create a suppression context that suppresses line 3
        let suppression = SuppressionContext::new();
        // Note: This would need actual implementation of suppression logic

        let items = analyze_error_context(&file, Path::new("test.rs"), Some(&suppression));
        // Test should verify suppression works when implemented
        assert!(!items.is_empty()); // Currently no suppression is actually implemented
    }

    // False positive tests - these patterns should NOT be flagged as error swallowing

    #[test]
    fn test_path_to_string_lossy_is_not_error_swallowing() {
        // This is a common pattern for converting paths to strings
        // It has nothing to do with error handling
        let code = r#"
            fn example(path: &std::path::Path) -> String {
                path.to_string_lossy().to_string()
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        // Filter for StringErrorConversion items specifically
        let string_conversion_items: Vec<_> = items
            .iter()
            .filter(|item| item.message.contains("string"))
            .collect();

        assert!(
            string_conversion_items.is_empty(),
            "path.to_string_lossy().to_string() should NOT be flagged as error swallowing. Found: {:?}",
            string_conversion_items
        );
    }

    #[test]
    fn test_display_to_string_is_not_error_swallowing() {
        // Converting Display types to String is normal, not error swallowing
        let code = r#"
            fn example(name: &str) -> String {
                format!("Hello, {}", name).to_string()
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        let string_conversion_items: Vec<_> = items
            .iter()
            .filter(|item| item.message.contains("string"))
            .collect();

        assert!(
            string_conversion_items.is_empty(),
            "Normal to_string() calls should NOT be flagged. Found: {:?}",
            string_conversion_items
        );
    }

    #[test]
    fn test_into_for_type_conversion_is_not_error_swallowing() {
        // Using into() for normal type conversions is not error swallowing
        let code = r#"
            fn example(s: &str) -> String {
                s.into()
            }
        "#;

        let file = parse_str::<File>(code).expect("Failed to parse test code");
        let items = analyze_error_context(&file, Path::new("test.rs"), None);

        let into_items: Vec<_> = items
            .iter()
            .filter(|item| item.message.contains("into()"))
            .collect();

        assert!(
            into_items.is_empty(),
            "Normal into() type conversions should NOT be flagged. Found: {:?}",
            into_items
        );
    }
}