debtmap 0.16.4

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
//! Detection of async boundaries and async context analysis

use std::collections::HashSet;
use syn::{
    visit::Visit, Block, Expr, ExprAsync, ExprAwait, ExprBlock, ExprCall, ExprClosure,
    ExprMethodCall, Item, ItemFn, Stmt, UseTree,
};

/// Detects async boundaries where blocking I/O would be problematic
pub struct AsyncBoundaryDetector {
    /// Stack of async contexts (true = in async context)
    async_stack: Vec<bool>,
    /// Whether we're currently in an async boundary
    pub in_async_boundary: bool,
    /// Detected blocking I/O calls in async context
    pub blocking_in_async: Vec<BlockingCall>,
    /// Track imports to disambiguate Command types
    imports: ImportTracker,
}

#[derive(Debug, Clone, Default)]
struct ImportTracker {
    /// Set of async command imports (tokio::process, async_std::process)
    has_async_command: bool,
    /// Set of blocking command imports (std::process)
    has_std_command: bool,
    /// Imported symbols and their sources
    imported_symbols: HashSet<String>,
}

#[derive(Debug, Clone)]
pub struct BlockingCall {
    pub function_name: String,
    pub is_blocking: bool,
    pub in_async_context: bool,
    pub line: usize,
}

impl AsyncBoundaryDetector {
    pub fn new() -> Self {
        Self {
            async_stack: vec![false],
            in_async_boundary: false,
            blocking_in_async: Vec::new(),
            imports: ImportTracker::default(),
        }
    }

    /// Analyze file with import tracking
    pub fn analyze_file(&mut self, file: &syn::File) {
        // First pass: analyze imports
        self.analyze_imports(&file.items);
        // Second pass: visit the file normally
        self.visit_file(file);
    }

    /// Analyze imports before visiting the rest of the file
    fn analyze_imports(&mut self, items: &[Item]) {
        for item in items {
            if let Item::Use(use_item) = item {
                self.process_use_tree(&use_item.tree, String::new());
            }
        }
    }

    fn process_use_tree(&mut self, tree: &UseTree, prefix: String) {
        match tree {
            UseTree::Path(path) => {
                let new_prefix = if prefix.is_empty() {
                    path.ident.to_string()
                } else {
                    format!("{}::{}", prefix, path.ident)
                };
                self.process_use_tree(&path.tree, new_prefix);
            }
            UseTree::Name(name) => {
                let full_path = if prefix.is_empty() {
                    name.ident.to_string()
                } else {
                    format!("{}::{}", prefix, name.ident)
                };

                // Track what kind of Command is imported
                if full_path == "tokio::process::Command"
                    || full_path == "async_std::process::Command"
                {
                    self.imports.has_async_command = true;
                    self.imports.imported_symbols.insert("Command".to_string());
                } else if full_path == "std::process::Command" {
                    self.imports.has_std_command = true;
                    self.imports.imported_symbols.insert("Command".to_string());
                }

                self.imports.imported_symbols.insert(full_path);
            }
            UseTree::Glob(_) => {
                // Handle glob imports
                if prefix == "tokio::process" || prefix == "async_std::process" {
                    self.imports.has_async_command = true;
                } else if prefix == "std::process" {
                    self.imports.has_std_command = true;
                }
            }
            UseTree::Group(group) => {
                for tree in &group.items {
                    self.process_use_tree(tree, prefix.clone());
                }
            }
            UseTree::Rename(rename) => {
                let full_path = if prefix.is_empty() {
                    rename.ident.to_string()
                } else {
                    format!("{}::{}", prefix, rename.ident)
                };

                if full_path == "tokio::process::Command"
                    || full_path == "async_std::process::Command"
                {
                    self.imports.has_async_command = true;
                    self.imports
                        .imported_symbols
                        .insert(rename.rename.to_string());
                } else if full_path == "std::process::Command" {
                    self.imports.has_std_command = true;
                    self.imports
                        .imported_symbols
                        .insert(rename.rename.to_string());
                }
            }
        }
    }

    /// Check if we're in an async context
    fn is_in_async(&self) -> bool {
        self.async_stack.last().copied().unwrap_or(false)
    }

    /// Push async context
    fn push_async(&mut self, is_async: bool) {
        self.async_stack.push(is_async || self.is_in_async());
    }

    /// Pop async context
    fn pop_async(&mut self) {
        self.async_stack.pop();
    }

    /// Check if a function call is blocking I/O
    fn is_blocking_io(&self, path: &str, method: &str) -> bool {
        // First check if it's an async I/O library - these are NOT blocking
        let async_patterns = ["tokio::", "async_std::", "futures::", "smol::"];

        for pattern in &async_patterns {
            if path.starts_with(pattern) {
                return false; // Async I/O is not blocking
            }
        }

        // Special case: If method is "output" or "status" on Command,
        // check our import tracking to determine if it's blocking
        if (method == "output" || method == "status" || method == "spawn") && path == "Command" {
            // If we have import information, use it
            if self.imports.has_async_command && !self.imports.has_std_command {
                return false; // Definitely async
            } else if self.imports.has_std_command && !self.imports.has_async_command {
                return true; // Definitely blocking
            } else {
                // Ambiguous or no imports - in async context, assume async
                return false;
            }
        }

        // Common blocking I/O patterns
        let blocking_patterns = [
            // File I/O (standard library)
            ("std::fs", "read"),
            ("std::fs", "write"),
            ("std::fs", "read_to_string"),
            ("std::fs", "read_dir"),
            ("std::fs", "copy"),
            ("std::fs", "rename"),
            ("std::fs", "remove_file"),
            ("File", "open"),
            ("File", "create"),
            // Network I/O (synchronous)
            ("std::net", "TcpStream"),
            ("std::net", "TcpListener"),
            ("std::net", "UdpSocket"),
            // Process/Command - only flag if explicitly std::process
            ("std::process::Command", "output"),
            ("std::process::Command", "status"),
            ("std::process::Command", "spawn"),
            // Thread blocking
            ("std::thread", "sleep"),
            ("thread", "sleep"),
            // Synchronous HTTP clients
            ("reqwest", "blocking"),
            ("ureq", "get"),
            ("ureq", "post"),
        ];

        // Check for blocking patterns
        for (module, func) in &blocking_patterns {
            // Check if the path contains the module pattern
            // For exact module matching (e.g., "std::fs" but not "tokio::fs")
            if (path == *module
                || path.starts_with(&format!("{}::", module))
                || path.ends_with(&format!("::{}", module)))
                && method == *func
            {
                return true;
            }
        }

        // Check for common blocking method names
        // But be careful - some of these could be async versions too
        let blocking_methods = [
            "read_to_string",
            "read_to_end",
            "read_exact",
            "write_all",
            "flush",
            "sync_all",
            "set_len",
            "sleep",
            "wait",
            "join",
        ];

        // Only flag these if path suggests it's std library, not async library
        if blocking_methods.contains(&method) {
            // If path is empty or doesn't indicate async library, might be blocking
            return path.is_empty() || path.starts_with("std::");
        }

        false
    }

    /// Detect if we're in an async block boundary
    fn detect_async_boundary(&mut self, block: &Block) -> bool {
        // Check if this block contains await expressions
        let mut has_await = false;
        for stmt in &block.stmts {
            match stmt {
                Stmt::Expr(expr, _) => {
                    has_await = contains_await(expr);
                    if has_await {
                        break;
                    }
                }
                Stmt::Local(local) => {
                    if let Some(init) = &local.init {
                        has_await = contains_await(&init.expr);
                        if has_await {
                            break;
                        }
                    }
                }
                _ => {}
            }
        }
        has_await
    }
}

impl<'ast> Visit<'ast> for AsyncBoundaryDetector {
    fn visit_item_fn(&mut self, node: &'ast ItemFn) {
        // Check if function is async
        let is_async = node.sig.asyncness.is_some();
        self.push_async(is_async);

        if is_async {
            self.in_async_boundary = true;
        }

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

        self.pop_async();
        if is_async {
            self.in_async_boundary = false;
        }
    }

    fn visit_expr_async(&mut self, node: &'ast ExprAsync) {
        // Entering async block
        self.push_async(true);
        self.in_async_boundary = true;
        syn::visit::visit_expr_async(self, node);
        self.pop_async();
    }

    fn visit_expr_closure(&mut self, node: &'ast ExprClosure) {
        // Check if closure is async
        let is_async = node.asyncness.is_some();
        self.push_async(is_async);
        syn::visit::visit_expr_closure(self, node);
        self.pop_async();
    }

    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
        if self.is_in_async() {
            // Check if this is a blocking call
            if let Expr::Path(path) = &*node.func {
                let path_str = path
                    .path
                    .segments
                    .iter()
                    .map(|s| s.ident.to_string())
                    .collect::<Vec<_>>()
                    .join("::");

                let last_segment = path
                    .path
                    .segments
                    .last()
                    .map(|s| s.ident.to_string())
                    .unwrap_or_default();

                if self.is_blocking_io(&path_str, &last_segment) {
                    self.blocking_in_async.push(BlockingCall {
                        function_name: path_str,
                        is_blocking: true,
                        in_async_context: true,
                        line: 0, // Would need span info for actual line
                    });
                }
            }
        }

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

    fn visit_expr_method_call(&mut self, node: &'ast ExprMethodCall) {
        if self.is_in_async() {
            let method_name = node.method.to_string();

            // Check receiver for type hints
            let receiver_str = match &*node.receiver {
                Expr::Path(path) => path
                    .path
                    .segments
                    .iter()
                    .map(|s| s.ident.to_string())
                    .collect::<Vec<_>>()
                    .join("::"),
                Expr::Call(call) => {
                    // Handle chained calls like Command::new("echo").output()
                    if let Expr::Path(path) = &*call.func {
                        let full_path = path
                            .path
                            .segments
                            .iter()
                            .map(|s| s.ident.to_string())
                            .collect::<Vec<_>>()
                            .join("::");

                        // Extract just the type name (e.g., "Command" from "Command::new")
                        if full_path.ends_with("::new") {
                            full_path
                                .strip_suffix("::new")
                                .unwrap_or(&full_path)
                                .to_string()
                        } else {
                            full_path
                        }
                    } else {
                        String::new()
                    }
                }
                _ => String::new(),
            };

            // Check if this is a blocking I/O call
            if self.is_blocking_io(&receiver_str, &method_name) {
                self.blocking_in_async.push(BlockingCall {
                    function_name: format!("{}.{}", receiver_str, method_name),
                    is_blocking: true,
                    in_async_context: true,
                    line: 0,
                });
            }
        }

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

    fn visit_expr_block(&mut self, node: &'ast ExprBlock) {
        // Check if this block has async boundary characteristics
        let has_boundary = self.detect_async_boundary(&node.block);
        if has_boundary {
            self.in_async_boundary = true;
        }

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

        if has_boundary {
            self.in_async_boundary = false;
        }
    }
}

/// Check if an expression contains await
fn contains_await(expr: &Expr) -> bool {
    struct AwaitChecker {
        has_await: bool,
    }

    impl<'ast> Visit<'ast> for AwaitChecker {
        fn visit_expr_await(&mut self, _: &'ast ExprAwait) {
            self.has_await = true;
        }
    }

    let mut checker = AwaitChecker { has_await: false };
    checker.visit_expr(expr);
    checker.has_await
}

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

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

    #[test]
    fn test_blocking_io_detection() {
        let detector = AsyncBoundaryDetector::new();
        assert!(detector.is_blocking_io("std::fs", "read"));
        assert!(detector.is_blocking_io("std::fs::read_to_string", "read_to_string"));
        assert!(detector.is_blocking_io("File", "open"));
        assert!(!detector.is_blocking_io("tokio::fs", "read"));
        assert!(!detector.is_blocking_io("async_std::fs", "read"));
    }

    #[test]
    fn test_async_context_detection() {
        let code = r#"
            async fn process_data() {
                let data = std::fs::read_to_string("file.txt").unwrap();
                process(data).await;
            }
        "#;

        let file = syn::parse_file(code).unwrap();
        let mut detector = AsyncBoundaryDetector::new();

        for item in file.items {
            if let syn::Item::Fn(func) = item {
                detector.visit_item_fn(&func);
            }
        }

        // Should detect blocking I/O in async context
        assert!(!detector.blocking_in_async.is_empty());
    }
}