oxicop 0.2.0

A blazing-fast Ruby linter and formatter, reimplemented in Rust
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
//! Lint cops for detecting code quality issues.

use regex::Regex;
use std::collections::HashMap;

use crate::cop::{Category, Cop, Severity};
use crate::offense::{Location, Offense};
use crate::source::SourceFile;

/// Detects leftover debugging calls like `binding.pry`, `byebug`, etc.
pub struct Debugger {
    patterns: Vec<(&'static str, Regex)>,
}

impl Debugger {
    pub fn new() -> Self {
        let debug_methods = vec![
            "binding.pry",
            "binding.irb",
            "byebug",
            "debugger",
            "binding.break",
            "pry",
            "save_and_open_page",
            "save_and_open_screenshot",
        ];

        let patterns = debug_methods
            .into_iter()
            .map(|method| {
                // Use word boundaries to match whole words/expressions
                // \b works for word characters, but for dots we need special handling
                let pattern = if method.contains('.') {
                    // For dotted expressions, match them exactly with word boundary at start and end
                    format!(r"\b{}\b", regex::escape(method))
                } else {
                    // For single words, use simple word boundaries
                    format!(r"\b{}\b", regex::escape(method))
                };
                (method, Regex::new(&pattern).unwrap())
            })
            .collect();

        Self { patterns }
    }
}

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

impl Cop for Debugger {
    fn name(&self) -> &str {
        "Lint/Debugger"
    }

    fn category(&self) -> Category {
        Category::Lint
    }

    fn severity(&self) -> Severity {
        Severity::Warning
    }

    fn description(&self) -> &str {
        "Checks for leftover debugging code like `binding.pry` or `byebug`."
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        for (line_num, line_content) in source.lines.iter().enumerate() {
            let line_number = line_num + 1; // Convert to 1-based

            // Quick check: if column 1 is in a comment, skip the entire line
            if source.in_string_or_comment(line_number, 1) {
                // Check if it's a comment by looking for '#' at the start or after whitespace
                if line_content.trim_start().starts_with('#') {
                    continue;
                }
            }

            // Collect all matches with their positions to avoid overlapping detections
            let mut matches: Vec<(usize, usize, &str)> = Vec::new();

            // Check each debug pattern
            for (method_name, pattern) in &self.patterns {
                for match_obj in pattern.find_iter(line_content) {
                    let start = match_obj.start();
                    let end = match_obj.end();
                    let column = start + 1; // Convert to 1-based

                    // Skip if this match is inside a string or comment
                    if source.in_string_or_comment(line_number, column) {
                        continue;
                    }

                    matches.push((start, end, method_name));
                }
            }

            // Sort by start position and filter out overlapping matches
            matches.sort_by_key(|m| m.0);
            let mut last_end = 0;
            for (start, end, method_name) in matches {
                // Skip if this match overlaps with a previous match
                if start < last_end {
                    continue;
                }

                let column = start + 1; // Convert to 1-based
                let length = end - start;

                offenses.push(Offense::new(
                    self.name(),
                    format!("Remove debugger entry point `{}`.", method_name),
                    self.severity(),
                    Location::new(line_number, column, length),
                ));

                last_end = end;
            }
        }

        offenses
    }
}

/// Detects literal values used as conditions (e.g., `if true`, `if false`, `if nil`).
pub struct LiteralInCondition {
    pattern: Regex,
}

impl LiteralInCondition {
    pub fn new() -> Self {
        // Match if/unless followed by whitespace and then true/false/nil
        // We use \b for word boundaries to avoid matching `if true_value`
        let pattern = Regex::new(r#"\b(if|unless)\s+(true|false|nil)\b"#).unwrap();
        Self { pattern }
    }
}

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

impl Cop for LiteralInCondition {
    fn name(&self) -> &str {
        "Lint/LiteralInCondition"
    }

    fn category(&self) -> Category {
        Category::Lint
    }

    fn severity(&self) -> Severity {
        Severity::Warning
    }

    fn description(&self) -> &str {
        "Checks for literals used in conditions."
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();

        for (line_num, line_content) in source.lines.iter().enumerate() {
            let line_number = line_num + 1; // Convert to 1-based

            for captures in self.pattern.captures_iter(line_content) {
                let full_match = captures.get(0).unwrap();
                let keyword = captures.get(1).unwrap().as_str();
                let literal = captures.get(2).unwrap().as_str();
                let column = full_match.start() + 1; // Convert to 1-based

                // Skip if inside a string or comment
                if source.in_string_or_comment(line_number, column) {
                    continue;
                }

                offenses.push(Offense::new(
                    self.name(),
                    format!(
                        "Literal `{}` used in `{}` condition.",
                        literal, keyword
                    ),
                    self.severity(),
                    Location::new(line_number, column, full_match.len()),
                ));
            }
        }

        offenses
    }
}

/// Detects duplicate method definitions in the same scope.
pub struct DuplicateMethods {
    pattern: Regex,
}

impl DuplicateMethods {
    pub fn new() -> Self {
        // Match method definitions: `def method_name`
        // Exclude class methods: `def self.method_name`
        // We capture the method name for grouping
        let pattern = Regex::new(r#"^\s*def\s+([a-zA-Z_][a-zA-Z0-9_]*[?!]?)"#).unwrap();
        Self { pattern }
    }
}

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

impl Cop for DuplicateMethods {
    fn name(&self) -> &str {
        "Lint/DuplicateMethods"
    }

    fn category(&self) -> Category {
        Category::Lint
    }

    fn severity(&self) -> Severity {
        Severity::Warning
    }

    fn description(&self) -> &str {
        "Checks for duplicate method definitions."
    }

    fn check(&self, source: &SourceFile) -> Vec<Offense> {
        let mut offenses = Vec::new();
        let mut method_definitions: HashMap<String, Vec<(usize, usize)>> = HashMap::new();

        // First pass: collect all method definitions
        for (line_num, line_content) in source.lines.iter().enumerate() {
            let line_number = line_num + 1; // Convert to 1-based

            if let Some(captures) = self.pattern.captures(line_content) {
                let method_name = captures.get(1).unwrap().as_str();
                let column = captures.get(0).unwrap().start() + 1; // Convert to 1-based

                // Skip if inside a string or comment
                if source.in_string_or_comment(line_number, column) {
                    continue;
                }

                method_definitions
                    .entry(method_name.to_string())
                    .or_default()
                    .push((line_number, column));
            }
        }

        // Second pass: flag duplicates
        for (method_name, locations) in method_definitions {
            if locations.len() > 1 {
                // Report all occurrences after the first as duplicates
                for &(line_number, column) in &locations[1..] {
                    offenses.push(Offense::new(
                        self.name(),
                        format!("Method `{}` is defined multiple times.", method_name),
                        self.severity(),
                        Location::new(line_number, column, 3), // length of "def"
                    ));
                }
            }
        }

        offenses
    }
}

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

    fn test_source(content: &str) -> SourceFile {
        SourceFile::from_string(PathBuf::from("test.rb"), content.to_string())
    }

    // ===== Debugger Tests =====

    #[test]
    fn test_debugger_no_offense() {
        let cop = Debugger::new();
        let source = test_source("puts 'hello world'\nx = 42\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_debugger_detects_binding_pry() {
        let cop = Debugger::new();
        let source = test_source("def foo\n  binding.pry\n  x = 1\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert_eq!(offenses[0].location.line, 2);
        assert!(offenses[0].message.contains("binding.pry"));
    }

    #[test]
    fn test_debugger_detects_byebug() {
        let cop = Debugger::new();
        let source = test_source("x = 1\nbyebug\ny = 2\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert_eq!(offenses[0].location.line, 2);
        assert!(offenses[0].message.contains("byebug"));
    }

    #[test]
    fn test_debugger_detects_debugger() {
        let cop = Debugger::new();
        let source = test_source("debugger\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert_eq!(offenses[0].location.line, 1);
        assert!(offenses[0].message.contains("debugger"));
    }

    #[test]
    fn test_debugger_detects_pry() {
        let cop = Debugger::new();
        let source = test_source("pry\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert_eq!(offenses[0].location.line, 1);
        assert!(offenses[0].message.contains("pry"));
    }

    #[test]
    fn test_debugger_skips_in_string() {
        let cop = Debugger::new();
        let source = test_source("puts 'binding.pry'\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_debugger_skips_in_double_quoted_string() {
        let cop = Debugger::new();
        let source = test_source("puts \"binding.pry\"\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_debugger_skips_in_comment() {
        let cop = Debugger::new();
        let source = test_source("# binding.pry\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_debugger_skips_in_inline_comment() {
        let cop = Debugger::new();
        let source = test_source("x = 1 # binding.pry\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_debugger_multiple_on_same_line() {
        let cop = Debugger::new();
        let source = test_source("binding.pry; byebug\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 2);
    }

    #[test]
    fn test_debugger_empty_file() {
        let cop = Debugger::new();
        let source = test_source("");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_debugger_does_not_match_partial_words() {
        let cop = Debugger::new();
        let source = test_source("my_pry_method\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_debugger_all_patterns() {
        let cop = Debugger::new();
        let source = test_source(
            "binding.pry\n\
             binding.irb\n\
             byebug\n\
             debugger\n\
             binding.break\n\
             pry\n\
             save_and_open_page\n\
             save_and_open_screenshot\n",
        );
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 8);
    }

    // ===== LiteralInCondition Tests =====

    #[test]
    fn test_literal_in_condition_no_offense() {
        let cop = LiteralInCondition::new();
        let source = test_source("if x\n  puts 'hello'\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_literal_in_condition_if_true() {
        let cop = LiteralInCondition::new();
        let source = test_source("if true\n  puts 'hello'\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert_eq!(offenses[0].location.line, 1);
        assert!(offenses[0].message.contains("true"));
        assert!(offenses[0].message.contains("if"));
    }

    #[test]
    fn test_literal_in_condition_if_false() {
        let cop = LiteralInCondition::new();
        let source = test_source("if false\n  puts 'hello'\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert_eq!(offenses[0].location.line, 1);
        assert!(offenses[0].message.contains("false"));
    }

    #[test]
    fn test_literal_in_condition_if_nil() {
        let cop = LiteralInCondition::new();
        let source = test_source("if nil\n  puts 'hello'\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert_eq!(offenses[0].location.line, 1);
        assert!(offenses[0].message.contains("nil"));
    }

    #[test]
    fn test_literal_in_condition_unless_true() {
        let cop = LiteralInCondition::new();
        let source = test_source("unless true\n  puts 'hello'\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("unless"));
    }

    #[test]
    fn test_literal_in_condition_unless_false() {
        let cop = LiteralInCondition::new();
        let source = test_source("unless false\n  puts 'hello'\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("unless"));
    }

    #[test]
    fn test_literal_in_condition_skips_while_true() {
        let cop = LiteralInCondition::new();
        let source = test_source("while true\n  break if done\nend\n");
        let offenses = cop.check(&source);
        // while true is a common idiom and should not be flagged
        // Our regex only matches if/unless, so this should pass
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_literal_in_condition_skips_in_string() {
        let cop = LiteralInCondition::new();
        let source = test_source("puts 'if true'\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_literal_in_condition_skips_in_comment() {
        let cop = LiteralInCondition::new();
        let source = test_source("# if true\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_literal_in_condition_empty_file() {
        let cop = LiteralInCondition::new();
        let source = test_source("");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_literal_in_condition_does_not_match_variables() {
        let cop = LiteralInCondition::new();
        let source = test_source("if true_value\n  puts 'hello'\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_literal_in_condition_inline() {
        let cop = LiteralInCondition::new();
        let source = test_source("puts 'hello' if true\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
    }

    // ===== DuplicateMethods Tests =====

    #[test]
    fn test_duplicate_methods_no_offense() {
        let cop = DuplicateMethods::new();
        let source = test_source("def foo\nend\n\ndef bar\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_duplicate_methods_detects_duplicate() {
        let cop = DuplicateMethods::new();
        let source = test_source("def foo\nend\n\ndef foo\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert_eq!(offenses[0].location.line, 4);
        assert!(offenses[0].message.contains("foo"));
    }

    #[test]
    fn test_duplicate_methods_detects_multiple_duplicates() {
        let cop = DuplicateMethods::new();
        let source = test_source("def foo\nend\n\ndef foo\nend\n\ndef foo\nend\n");
        let offenses = cop.check(&source);
        // Should report 2 offenses (2nd and 3rd occurrences)
        assert_eq!(offenses.len(), 2);
    }

    #[test]
    fn test_duplicate_methods_with_question_mark() {
        let cop = DuplicateMethods::new();
        let source = test_source("def valid?\nend\n\ndef valid?\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("valid?"));
    }

    #[test]
    fn test_duplicate_methods_with_exclamation_mark() {
        let cop = DuplicateMethods::new();
        let source = test_source("def save!\nend\n\ndef save!\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
        assert!(offenses[0].message.contains("save!"));
    }

    #[test]
    fn test_duplicate_methods_skips_class_methods() {
        let cop = DuplicateMethods::new();
        let source = test_source("def self.foo\nend\n\ndef foo\nend\n");
        let offenses = cop.check(&source);
        // self.foo and foo are different, and we don't match self.foo anyway
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_duplicate_methods_skips_in_string() {
        let cop = DuplicateMethods::new();
        let source = test_source("def foo\nend\n\nputs 'def foo'\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_duplicate_methods_skips_in_comment() {
        let cop = DuplicateMethods::new();
        let source = test_source("def foo\nend\n\n# def foo\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_duplicate_methods_empty_file() {
        let cop = DuplicateMethods::new();
        let source = test_source("");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }

    #[test]
    fn test_duplicate_methods_with_indentation() {
        let cop = DuplicateMethods::new();
        let source = test_source("  def foo\n  end\n\n  def foo\n  end\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 1);
    }

    #[test]
    fn test_duplicate_methods_different_methods_same_prefix() {
        let cop = DuplicateMethods::new();
        let source = test_source("def foo\nend\n\ndef foobar\nend\n");
        let offenses = cop.check(&source);
        assert_eq!(offenses.len(), 0);
    }
}