deslop 0.2.0

A static analyzer that spots low-context and AI-assisted code patterns across naming, concurrency, security, performance, and test quality.
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
use std::collections::BTreeMap;

use tree_sitter::Node;

/// Detect `sorted(x)[0]` or `sorted(x)[-1]` patterns.
pub(super) fn collect_sorted_first_lines(body_node: Node<'_>, source: &str) -> Vec<usize> {
    let mut lines = Vec::new();
    visit_sorted_first(body_node, source, &mut lines);
    lines.sort_unstable();
    lines.dedup();
    lines
}

fn visit_sorted_first(node: Node<'_>, source: &str, lines: &mut Vec<usize>) {
    if should_skip_nested_scope(node) {
        return;
    }

    if node.kind() == "subscript"
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        if (trimmed.ends_with("[0]") || trimmed.ends_with("[-1]")) && trimmed.starts_with("sorted(")
        {
            lines.push(node.start_position().row + 1);
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_sorted_first(child, source, lines);
    }
}

/// Detect `len([x for x in ... if ...])` patterns — list built only for length.
pub(super) fn collect_len_comprehension_lines(body_node: Node<'_>, source: &str) -> Vec<usize> {
    let mut lines = Vec::new();
    visit_len_comprehension(body_node, source, &mut lines);
    lines.sort_unstable();
    lines.dedup();
    lines
}

fn visit_len_comprehension(node: Node<'_>, source: &str, lines: &mut Vec<usize>) {
    if should_skip_nested_scope(node) {
        return;
    }

    if node.kind() == "call"
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        if trimmed.starts_with("len(")
            && trimmed.ends_with(')')
            && (trimmed.contains(" for ") && trimmed.contains(" in "))
        {
            // Verify the argument is a list comprehension
            let inner = &trimmed[4..trimmed.len() - 1];
            if inner.starts_with('[') && inner.ends_with(']') {
                lines.push(node.start_position().row + 1);
            }
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_len_comprehension(child, source, lines);
    }
}

/// Detect `x in [literal, literal, ...]` membership on list literals.
pub(super) fn collect_in_list_literal_lines(body_node: Node<'_>, source: &str) -> Vec<usize> {
    let mut lines = Vec::new();
    visit_in_list_literal(body_node, source, &mut lines);
    lines.sort_unstable();
    lines.dedup();
    lines
}

fn visit_in_list_literal(node: Node<'_>, source: &str, lines: &mut Vec<usize>) {
    if should_skip_nested_scope(node) {
        return;
    }

    // Match comparison operators: `x in [...]`
    if node.kind() == "comparison_operator"
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        // Look for `<expr> in [<elements>]` but not `for <x> in [...]`
        if let Some(in_idx) = trimmed.find(" in [") {
            let before_in = &trimmed[..in_idx];
            // Make sure it's not a `for x in [...]` — check no `for` prefix
            if !before_in.trim_start().starts_with("for ")
                && !before_in.trim_start().starts_with("not ")
            {
                let after_in = &trimmed[in_idx + 4..]; // skip " in "
                if after_in.starts_with('[') && after_in.ends_with(']') {
                    // Count elements — only flag if 3+ items (trivial lists don't matter)
                    let inner = &after_in[1..after_in.len() - 1];
                    let element_count = inner.split(',').count();
                    if element_count >= 3 {
                        lines.push(node.start_position().row + 1);
                    }
                }
            }
        }
        // Also check `<expr> not in [<elements>]`
        if let Some(in_idx) = trimmed.find(" not in [") {
            let after_not_in = &trimmed[in_idx + 8..]; // skip " not in "
            if after_not_in.starts_with('[') && after_not_in.ends_with(']') {
                let inner = &after_not_in[1..after_not_in.len() - 1];
                let element_count = inner.split(',').count();
                if element_count >= 3 {
                    lines.push(node.start_position().row + 1);
                }
            }
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_in_list_literal(child, source, lines);
    }
}

/// Detect `.startswith(a) or .startswith(b)` chains where a tuple form is better.
pub(super) fn collect_startswith_chain_lines(body_node: Node<'_>, source: &str) -> Vec<usize> {
    let mut lines = Vec::new();
    visit_startswith_chains(body_node, source, &mut lines);
    lines.sort_unstable();
    lines.dedup();
    lines
}

fn visit_startswith_chains(node: Node<'_>, source: &str, lines: &mut Vec<usize>) {
    if should_skip_nested_scope(node) {
        return;
    }

    if node.kind() == "boolean_operator"
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        // Count .startswith(...) or .endswith(...) calls joined by `or`
        let parts: Vec<&str> = trimmed.split(" or ").collect();
        if parts.len() >= 2 {
            let starts_count = parts
                .iter()
                .filter(|part| {
                    let p = part.trim();
                    p.contains(".startswith(") || p.contains(".endswith(")
                })
                .count();
            if starts_count >= 2 {
                // Verify they are on the same receiver
                lines.push(node.start_position().row + 1);
            }
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_startswith_chains(child, source, lines);
    }
}

/// Detect `for i, x in enumerate(range(len(collection)))` anti-patterns.
pub(super) fn collect_enumerate_range_len_lines(body_node: Node<'_>, source: &str) -> Vec<usize> {
    let mut lines = Vec::new();
    visit_enumerate_range_len(body_node, source, &mut lines);
    lines.sort_unstable();
    lines.dedup();
    lines
}

fn visit_enumerate_range_len(node: Node<'_>, source: &str, lines: &mut Vec<usize>) {
    if should_skip_nested_scope(node) {
        return;
    }

    if node.kind() == "for_statement"
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        // Detect `for ... in enumerate(range(len(...))):` and `for ... in range(len(...)):`
        if let Some(in_idx) = trimmed.find(" in ") {
            let iterable = &trimmed[in_idx + 4..];
            if iterable.starts_with("enumerate(range(len(") || iterable.starts_with("range(len(") {
                lines.push(node.start_position().row + 1);
            }
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_enumerate_range_len(child, source, lines);
    }
}

/// Detect `list(d.keys())`, `list(d.values())`, `list(d.items())` inside loops.
pub(super) fn collect_dict_materialization_in_loop_lines(
    body_node: Node<'_>,
    source: &str,
) -> Vec<usize> {
    let mut lines = Vec::new();
    visit_dict_materialization_in_loop(body_node, source, false, &mut lines);
    lines.sort_unstable();
    lines.dedup();
    lines
}

fn visit_dict_materialization_in_loop(
    node: Node<'_>,
    source: &str,
    inside_loop: bool,
    lines: &mut Vec<usize>,
) {
    if should_skip_nested_scope(node) {
        return;
    }

    let next_inside_loop =
        inside_loop || matches!(node.kind(), "for_statement" | "while_statement");

    if next_inside_loop
        && node.kind() == "call"
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        if trimmed.starts_with("list(")
            && (trimmed.contains(".keys()")
                || trimmed.contains(".values()")
                || trimmed.contains(".items()"))
        {
            lines.push(node.start_position().row + 1);
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_dict_materialization_in_loop(child, source, next_inside_loop, lines);
    }
}

/// Detect repeated calls to the same callee with the same first argument in one function.
/// Returns later duplicate call lines, skipping the first occurrence.
pub(super) fn collect_repeated_call_same_arg_lines(
    body_node: Node<'_>,
    source: &str,
    callees: &[&str],
) -> Vec<(String, usize)> {
    let mut call_map: BTreeMap<String, Vec<usize>> = BTreeMap::new();
    visit_repeated_calls(body_node, source, callees, &mut call_map);

    let mut results = Vec::new();
    for (key, call_lines) in &call_map {
        if call_lines.len() >= 2 {
            for line in call_lines.iter().skip(1) {
                results.push((key.clone(), *line));
            }
        }
    }
    results
}

fn visit_repeated_calls(
    node: Node<'_>,
    source: &str,
    callees: &[&str],
    call_map: &mut BTreeMap<String, Vec<usize>>,
) {
    if should_skip_nested_scope(node) {
        return;
    }

    if node.kind() == "call"
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        for &callee in callees {
            if trimmed.starts_with(&format!("{callee}(")) {
                // Extract first argument (simplified: up to first comma or closing paren)
                let after_open = &trimmed[callee.len() + 1..];
                if let Some(end) = after_open.find([',', ')']) {
                    let first_arg = after_open[..end].trim();
                    if !first_arg.is_empty() && looks_like_binding(first_arg) {
                        let key = format!("{callee}({first_arg})");
                        call_map
                            .entry(key)
                            .or_default()
                            .push(node.start_position().row + 1);
                    }
                }
            }
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_repeated_calls(child, source, callees, call_map);
    }
}

/// Detect `file.readlines()` followed by iteration (readlines then iterate).
pub(super) fn collect_readlines_then_iterate_lines(
    body_node: Node<'_>,
    source: &str,
) -> Vec<usize> {
    let mut lines = Vec::new();
    // Look for readlines() calls and flag them if the result is iterated
    visit_readlines_iterate(body_node, source, &mut lines);
    lines.sort_unstable();
    lines.dedup();
    lines
}

fn visit_readlines_iterate(node: Node<'_>, source: &str, lines: &mut Vec<usize>) {
    if should_skip_nested_scope(node) {
        return;
    }

    // Detect patterns like:
    //   lines = f.readlines()
    //   for line in lines:
    // Or: for line in f.readlines():
    if node.kind() == "for_statement"
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        if let Some(in_idx) = trimmed.find(" in ") {
            let iterable_part = &trimmed[in_idx + 4..];
            if iterable_part.contains(".readlines()") {
                lines.push(node.start_position().row + 1);
            }
        }
    }

    // Also detect: x = f.readlines() (standalone call suggesting full materialization)
    if matches!(node.kind(), "assignment" | "annotated_assignment")
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        if trimmed.contains(".readlines()") && trimmed.contains('=') {
            lines.push(node.start_position().row + 1);
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_readlines_iterate(child, source, lines);
    }
}

/// Detect `f.read().splitlines()` or `f.read().split('\n')`.
pub(super) fn collect_read_splitlines_lines(body_node: Node<'_>, source: &str) -> Vec<usize> {
    let mut lines = Vec::new();
    visit_read_splitlines(body_node, source, &mut lines);
    lines.sort_unstable();
    lines.dedup();
    lines
}

fn visit_read_splitlines(node: Node<'_>, source: &str, lines: &mut Vec<usize>) {
    if should_skip_nested_scope(node) {
        return;
    }

    if (node.kind() == "call" || matches!(node.kind(), "assignment" | "expression_statement"))
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        if trimmed.contains(".read().splitlines()")
            || trimmed.contains(".read().split('\\n')")
            || trimmed.contains(".read().split(\"\\n\")")
        {
            lines.push(node.start_position().row + 1);
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_read_splitlines(child, source, lines);
    }
}

/// Detect `file.write(...)` inside tight loops without buffering.
pub(super) fn collect_write_in_loop_lines(body_node: Node<'_>, source: &str) -> Vec<usize> {
    let mut lines = Vec::new();
    visit_write_in_loop(body_node, source, false, &mut lines);
    lines.sort_unstable();
    lines.dedup();
    lines
}

fn visit_write_in_loop(node: Node<'_>, source: &str, inside_loop: bool, lines: &mut Vec<usize>) {
    if should_skip_nested_scope(node) {
        return;
    }

    let next_inside_loop =
        inside_loop || matches!(node.kind(), "for_statement" | "while_statement");

    if next_inside_loop
        && node.kind() == "call"
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        if trimmed.contains(".write(")
            && !trimmed.contains("writer.write")
            && !trimmed.contains("csv_writer")
        {
            lines.push(node.start_position().row + 1);
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_write_in_loop(child, source, next_inside_loop, lines);
    }
}

/// Detect multiple `open(same_path, ...)` calls in one function.
pub(super) fn collect_repeated_open_lines(
    body_node: Node<'_>,
    source: &str,
) -> Vec<(String, usize)> {
    let mut open_calls: BTreeMap<String, Vec<usize>> = BTreeMap::new();
    visit_repeated_opens(body_node, source, &mut open_calls);

    let mut results = Vec::new();
    for (path_arg, call_lines) in &open_calls {
        if call_lines.len() >= 2 {
            for line in call_lines {
                results.push((path_arg.clone(), *line));
            }
        }
    }
    results
}

fn visit_repeated_opens(
    node: Node<'_>,
    source: &str,
    open_calls: &mut BTreeMap<String, Vec<usize>>,
) {
    if should_skip_nested_scope(node) {
        return;
    }

    if node.kind() == "call"
        && let Some(text) = source.get(node.byte_range())
    {
        let trimmed = text.trim();
        if let Some(after_open) = trimmed.strip_prefix("open(") {
            // Extract first argument
            if let Some(end) = after_open.find([',', ')']) {
                let first_arg = after_open[..end].trim();
                if !first_arg.is_empty() && looks_like_binding(first_arg) {
                    open_calls
                        .entry(first_arg.to_string())
                        .or_default()
                        .push(node.start_position().row + 1);
                }
            }
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_repeated_opens(child, source, open_calls);
    }
}

/// Detect `csv.writer().writerow()` with flush per row or `writer.flush()` inside loops.
pub(super) fn collect_csv_flush_per_row_lines(body_node: Node<'_>, source: &str) -> Vec<usize> {
    let mut lines = Vec::new();
    visit_csv_flush_per_row(body_node, source, false, &mut lines);
    lines.sort_unstable();
    lines.dedup();
    lines
}

fn visit_csv_flush_per_row(
    node: Node<'_>,
    source: &str,
    inside_loop: bool,
    lines: &mut Vec<usize>,
) {
    if should_skip_nested_scope(node) {
        return;
    }

    let next_inside_loop =
        inside_loop || matches!(node.kind(), "for_statement" | "while_statement");

    if next_inside_loop && let Some(text) = source.get(node.byte_range()) {
        let trimmed = text.trim();
        if trimmed.contains(".flush()") && !trimmed.starts_with('#') {
            lines.push(node.start_position().row + 1);
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_csv_flush_per_row(child, source, next_inside_loop, lines);
    }
}

/// Detect `re.compile(...)` inside loops or functions that look like handlers.
pub(super) fn collect_regex_in_hotpath_lines(body_node: Node<'_>, source: &str) -> Vec<usize> {
    let mut lines = Vec::new();
    visit_regex_compile(body_node, source, false, &mut lines);
    lines.sort_unstable();
    lines.dedup();
    lines
}

fn visit_regex_compile(node: Node<'_>, source: &str, inside_loop: bool, lines: &mut Vec<usize>) {
    if should_skip_nested_scope(node) {
        return;
    }

    let next_inside_loop =
        inside_loop || matches!(node.kind(), "for_statement" | "while_statement");

    if let Some(text) = source.get(node.byte_range()) {
        let trimmed = text.trim();
        // Flag re.compile inside loops specifically
        if next_inside_loop
            && (trimmed.starts_with("re.compile(") || trimmed.starts_with("regex.compile("))
        {
            lines.push(node.start_position().row + 1);
        }
    }

    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        visit_regex_compile(child, source, next_inside_loop, lines);
    }
}

fn looks_like_binding(text: &str) -> bool {
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return false;
    }
    // Accept identifiers (potentially with dots for attribute access)
    // Reject string literals, function calls with parens, etc.
    if trimmed.starts_with('"') || trimmed.starts_with('\'') || trimmed.starts_with('(') {
        return false;
    }
    trimmed
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '[' || c == ']')
}

fn should_skip_nested_scope(node: Node<'_>) -> bool {
    matches!(node.kind(), "function_definition" | "class_definition")
}