rubyfast 1.3.2

An ultra-fast Ruby performance linter rewritten in Rust — detects 19 common anti-patterns
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
use ruby_prism::Node;

/// Convert a byte offset to a 1-based line number using pre-computed newline positions.
pub fn byte_offset_to_line(newline_positions: &[usize], byte_offset: usize) -> usize {
    match newline_positions.binary_search(&byte_offset) {
        Ok(idx) => idx + 1,
        Err(idx) => idx + 1,
    }
}

/// Check if a node is a CallNode with the given method name.
pub fn receiver_is_call_with_name(recv: &Option<Node<'_>>, name: &[u8]) -> bool {
    match recv {
        Some(node) => {
            if let Some(call) = node.as_call_node() {
                call.name().as_slice() == name
            } else {
                false
            }
        }
        None => false,
    }
}

/// Extract the inner CallNode from a receiver, if it is one.
pub fn receiver_as_call<'pr>(recv: &'pr Option<Node<'pr>>) -> Option<ruby_prism::CallNode<'pr>> {
    match recv {
        Some(node) => node.as_call_node(),
        None => None,
    }
}

/// Check if a CallNode has a BlockArgumentNode in its block field.
pub fn has_block_pass(call: &ruby_prism::CallNode<'_>) -> bool {
    matches!(call.block(), Some(Node::BlockArgumentNode { .. }))
}

/// Check if a CallNode has a full BlockNode (not just a BlockArgumentNode).
pub fn has_full_block(call: &ruby_prism::CallNode<'_>) -> bool {
    matches!(call.block(), Some(Node::BlockNode { .. }))
}

/// Count arguments from a CallNode's arguments (excluding block argument which is in block field).
pub fn arg_count(call: &ruby_prism::CallNode<'_>) -> usize {
    match call.arguments() {
        Some(args) => args.arguments().iter().count(),
        None => 0,
    }
}

/// Get the first argument from a CallNode (without allocating a Vec).
pub fn first_call_arg<'pr>(call: &ruby_prism::CallNode<'pr>) -> Option<Node<'pr>> {
    call.arguments()
        .and_then(|args| args.arguments().iter().next())
}

/// Get the first two arguments from a CallNode as a tuple (without collecting all).
pub fn call_args_pair<'pr>(call: &ruby_prism::CallNode<'pr>) -> Option<(Node<'pr>, Node<'pr>)> {
    let args = call.arguments()?;
    let mut iter = args.arguments().iter();
    let first = iter.next()?;
    let second = iter.next()?;
    if iter.next().is_some() {
        return None; // more than 2 args
    }
    Some((first, second))
}

/// Check if a node is a single-character string literal.
pub fn is_single_char_string(node: &Node<'_>) -> bool {
    match node.as_string_node() {
        Some(s) => s.unescaped().len() == 1,
        None => false,
    }
}

/// Check if the receiver is a range (RangeNode, inclusive or exclusive).
/// Also handles parenthesized ranges: `(1..10)` parses as `ParenthesesNode(RangeNode)`.
pub fn receiver_is_range(recv: &Option<Node<'_>>) -> bool {
    match recv {
        Some(node) => {
            if node.as_range_node().is_some() {
                return true;
            }
            if let Some(paren) = node.as_parentheses_node()
                && let Some(body) = paren.body()
            {
                if let Some(stmts) = body.as_statements_node() {
                    let body_nodes: Vec<_> = stmts.body().iter().collect();
                    return body_nodes.len() == 1 && body_nodes[0].as_range_node().is_some();
                }
                return body.as_range_node().is_some();
            }
            false
        }
        None => false,
    }
}

/// Check if a node is a literal/primitive (not a variable reference or method call).
pub fn is_primitive(node: &Node<'_>) -> bool {
    matches!(
        node,
        Node::IntegerNode { .. }
            | Node::FloatNode { .. }
            | Node::StringNode { .. }
            | Node::SymbolNode { .. }
            | Node::TrueNode { .. }
            | Node::FalseNode { .. }
            | Node::NilNode { .. }
            | Node::ArrayNode { .. }
            | Node::HashNode { .. }
            | Node::RangeNode { .. }
            | Node::RationalNode { .. }
            | Node::ImaginaryNode { .. }
    )
}

/// Check if the first argument is a Hash/KeywordHash node with exactly one key-value pair.
/// `h.merge!(item: 1)` parses as KeywordHashNode, `h.merge!({item: 1})` parses as HashNode.
/// Check if the first argument of a CallNode is a Hash/KeywordHash with exactly one pair.
pub fn first_arg_is_single_pair_hash(call: &ruby_prism::CallNode<'_>) -> bool {
    match first_call_arg(call) {
        Some(node) => {
            if let Some(h) = node.as_hash_node() {
                return h.elements().iter().count() == 1;
            }
            if let Some(k) = node.as_keyword_hash_node() {
                return k.elements().iter().count() == 1;
            }
            false
        }
        None => false,
    }
}

/// Check if a node is an IntegerNode with value 1.
pub fn is_int_one(node: &Node<'_>) -> bool {
    if let Some(i) = node.as_integer_node() {
        let text = i.location().as_slice();
        matches!(
            text,
            b"1" | b"0x1" | b"0X1" | b"0b1" | b"0B1" | b"0o1" | b"0O1"
        )
    } else {
        false
    }
}

/// Get block argument names from a BlockNode's parameters.
/// BlockNode.parameters() returns Option<Node> which is typically a BlockParametersNode.
pub fn block_arg_names(params: &Option<Node<'_>>) -> Vec<String> {
    match params {
        Some(node) => {
            if let Some(block_params) = node.as_block_parameters_node()
                && let Some(inner_params) = block_params.parameters()
            {
                return inner_params
                    .requireds()
                    .iter()
                    .filter_map(|p| {
                        p.as_required_parameter_node()
                            .map(|rp| String::from_utf8_lossy(rp.name().as_slice()).to_string())
                    })
                    .collect();
            }
            // Handle NumberedParametersNode or other cases
            Vec::new()
        }
        None => Vec::new(),
    }
}

/// Check if a DefNode has a block argument (&block), returning its name if so.
pub fn def_block_arg_name(def: &ruby_prism::DefNode<'_>) -> Option<String> {
    let params = def.parameters()?;
    let block_param = params.block()?;
    let name = block_param.name()?;
    Some(String::from_utf8_lossy(name.as_slice()).to_string())
}

/// Count regular (required) arguments in a DefNode.
pub fn def_regular_arg_count(def: &ruby_prism::DefNode<'_>) -> usize {
    match def.parameters() {
        Some(params) => params.requireds().iter().count(),
        None => 0,
    }
}

/// Get the first regular argument name from a DefNode.
pub fn def_first_arg_name(def: &ruby_prism::DefNode<'_>) -> Option<String> {
    let params = def.parameters()?;
    let first = params.requireds().iter().next()?;
    first
        .as_required_parameter_node()
        .map(|rp| String::from_utf8_lossy(rp.name().as_slice()).to_string())
}

/// Check if a string literal contains "def".
pub fn str_contains_def(node: &Node<'_>) -> bool {
    if let Some(s) = node.as_string_node() {
        return String::from_utf8_lossy(s.unescaped()).contains("def");
    }
    if let Some(interp) = node.as_interpolated_string_node() {
        return interp.parts().iter().any(|part| {
            if let Some(s) = part.as_string_node() {
                String::from_utf8_lossy(s.unescaped()).contains("def")
            } else {
                false
            }
        });
    }
    false
}

/// Count the number of top-level expressions in a body node.
pub fn body_expression_count(body: &Option<Node<'_>>) -> usize {
    match body {
        None => 0,
        Some(node) => {
            if let Some(stmts) = node.as_statements_node() {
                stmts.body().iter().count()
            } else {
                1
            }
        }
    }
}

/// Get the single expression from a body node, if the body has exactly one expression.
/// For StatementsNode bodies, returns the first (and only) statement.
/// For single-expression bodies (non-StatementsNode), returns the body node itself.
/// Returns None if body is empty or has multiple expressions.
pub fn body_single_expression(body: Option<Node<'_>>) -> Option<Node<'_>> {
    let node = body?;
    if let Some(stmts) = node.as_statements_node() {
        let mut iter = stmts.body().iter();
        let first = iter.next()?;
        if iter.next().is_some() {
            return None; // multiple expressions
        }
        Some(first)
    } else {
        // Single expression body — the node itself is the expression
        Some(node)
    }
}

/// Test-only helpers for parsing Ruby source with leaked lifetime.
/// `Box::leak` is intentional: test processes reclaim all memory at exit.
#[cfg(test)]
pub mod test_helpers {
    use ruby_prism::{Node, ParseResult};

    /// Parse source and leak the result to get a `'static` lifetime for tests.
    pub fn leak_parse(source: &[u8]) -> &'static ParseResult<'static> {
        let owned: Vec<u8> = source.to_vec();
        let static_source: &'static [u8] = Box::leak(owned.into_boxed_slice());
        Box::leak(Box::new(ruby_prism::parse(static_source)))
    }

    /// Parse source and return the first top-level statement node.
    pub fn parse_first_stmt(source: &[u8]) -> Node<'static> {
        let result = leak_parse(source);
        let program = result.node();
        let prog = program.as_program_node().unwrap();
        prog.statements().body().iter().next().unwrap()
    }
}

/// Compute byte positions of all newline characters in source.
pub fn compute_newline_positions(source: &[u8]) -> Vec<usize> {
    source
        .iter()
        .enumerate()
        .filter(|&(_, &b)| b == b'\n')
        .map(|(i, _)| i)
        .collect()
}

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

    use crate::ast_helpers::test_helpers::parse_first_stmt;

    #[test]
    fn byte_offset_to_line_basic() {
        let positions = vec![5, 11];
        assert_eq!(byte_offset_to_line(&positions, 0), 1);
        assert_eq!(byte_offset_to_line(&positions, 5), 1); // exact match
        assert_eq!(byte_offset_to_line(&positions, 6), 2);
        assert_eq!(byte_offset_to_line(&positions, 12), 3);
    }

    #[test]
    fn byte_offset_to_line_empty() {
        assert_eq!(byte_offset_to_line(&[], 0), 1);
        assert_eq!(byte_offset_to_line(&[], 100), 1);
    }

    #[test]
    fn receiver_is_call_with_name_works() {
        let node = parse_first_stmt(b"a.foo.bar");
        let call = node.as_call_node().unwrap();
        assert!(receiver_is_call_with_name(&call.receiver(), b"foo"));
        assert!(!receiver_is_call_with_name(&call.receiver(), b"baz"));
    }

    #[test]
    fn receiver_is_call_with_name_none() {
        assert!(!receiver_is_call_with_name(&None, b"foo"));
    }

    #[test]
    fn receiver_as_call_works() {
        let node = parse_first_stmt(b"a.foo.bar");
        let call = node.as_call_node().unwrap();
        let recv = call.receiver();
        let inner = receiver_as_call(&recv).unwrap();
        assert_eq!(inner.name().as_slice(), b"foo");
    }

    #[test]
    fn receiver_as_call_not_call() {
        assert!(receiver_as_call(&None).is_none());
    }

    #[test]
    fn has_block_pass_works() {
        let node = parse_first_stmt(b"arr.map(&:to_s)");
        let call = node.as_call_node().unwrap();
        assert!(has_block_pass(&call));
    }

    #[test]
    fn has_block_pass_without() {
        let node = parse_first_stmt(b"arr.map(1)");
        let call = node.as_call_node().unwrap();
        assert!(!has_block_pass(&call));
    }

    #[test]
    fn arg_count_works() {
        let node = parse_first_stmt(b"arr.select(1, 2)");
        let call = node.as_call_node().unwrap();
        assert_eq!(arg_count(&call), 2);
    }

    #[test]
    fn is_single_char_string_works() {
        let node = parse_first_stmt(b"'x'");
        assert!(is_single_char_string(&node));
        let node2 = parse_first_stmt(b"'xy'");
        assert!(!is_single_char_string(&node2));
    }

    #[test]
    fn is_single_char_string_not_string() {
        let node = parse_first_stmt(b"42");
        assert!(!is_single_char_string(&node));
    }

    #[test]
    fn receiver_is_range_inclusive() {
        let node = parse_first_stmt(b"(1..10).include?(5)");
        let call = node.as_call_node().unwrap();
        assert!(receiver_is_range(&call.receiver()));
    }

    #[test]
    fn receiver_is_range_exclusive() {
        let node = parse_first_stmt(b"(1...10).include?(5)");
        let call = node.as_call_node().unwrap();
        assert!(receiver_is_range(&call.receiver()));
    }

    #[test]
    fn receiver_is_range_not_range() {
        let node = parse_first_stmt(b"[1].include?(5)");
        let call = node.as_call_node().unwrap();
        assert!(!receiver_is_range(&call.receiver()));
    }

    #[test]
    fn is_primitive_covers_types() {
        assert!(is_primitive(&parse_first_stmt(b"42")));
        assert!(is_primitive(&parse_first_stmt(b"3.14")));
        assert!(is_primitive(&parse_first_stmt(b"'s'")));
        assert!(is_primitive(&parse_first_stmt(b":sym")));
        assert!(is_primitive(&parse_first_stmt(b"true")));
        assert!(is_primitive(&parse_first_stmt(b"false")));
        assert!(is_primitive(&parse_first_stmt(b"nil")));
        assert!(is_primitive(&parse_first_stmt(b"[]")));
        assert!(is_primitive(&parse_first_stmt(b"{}")));
        assert!(is_primitive(&parse_first_stmt(b"1..5")));
        assert!(is_primitive(&parse_first_stmt(b"1...5")));
        assert!(!is_primitive(&parse_first_stmt(b"x")));
    }

    #[test]
    fn first_arg_is_single_pair_hash_kwargs() {
        let node = parse_first_stmt(b"h.merge!(a: 1)");
        let call = node.as_call_node().unwrap();
        assert!(first_arg_is_single_pair_hash(&call));
    }

    #[test]
    fn first_arg_is_single_pair_hash_explicit() {
        let node = parse_first_stmt(b"h.merge!({a: 1})");
        let call = node.as_call_node().unwrap();
        assert!(first_arg_is_single_pair_hash(&call));
    }

    #[test]
    fn first_arg_is_single_pair_hash_multi() {
        let node = parse_first_stmt(b"h.merge!(a: 1, b: 2)");
        let call = node.as_call_node().unwrap();
        assert!(!first_arg_is_single_pair_hash(&call));
    }

    #[test]
    fn first_arg_is_single_pair_hash_not_hash() {
        let node = parse_first_stmt(b"h.merge!(x)");
        let call = node.as_call_node().unwrap();
        assert!(!first_arg_is_single_pair_hash(&call));
    }

    #[test]
    fn is_int_one_works() {
        assert!(is_int_one(&parse_first_stmt(b"1")));
        assert!(!is_int_one(&parse_first_stmt(b"2")));
        assert!(!is_int_one(&parse_first_stmt(b"'1'")));
    }

    #[test]
    fn block_arg_names_single() {
        let node = parse_first_stmt(b"arr.map { |x| x }");
        let call = node.as_call_node().unwrap();
        if let Some(Node::BlockNode { .. }) = call.block() {
            let block = call.block().unwrap().as_block_node().unwrap();
            let names = block_arg_names(&block.parameters());
            assert_eq!(names, vec!["x".to_string()]);
        } else {
            panic!("Expected BlockNode");
        }
    }

    #[test]
    fn block_arg_names_none() {
        let names = block_arg_names(&None);
        assert!(names.is_empty());
    }

    #[test]
    fn def_block_arg_name_present() {
        let node = parse_first_stmt(b"def foo(&block); end");
        let def = node.as_def_node().unwrap();
        assert_eq!(def_block_arg_name(&def), Some("block".to_string()));
    }

    #[test]
    fn def_block_arg_name_absent() {
        let node = parse_first_stmt(b"def foo(x); end");
        let def = node.as_def_node().unwrap();
        assert_eq!(def_block_arg_name(&def), None);
    }

    #[test]
    fn def_regular_arg_count_works() {
        let node = parse_first_stmt(b"def foo(a, b); end");
        let def = node.as_def_node().unwrap();
        assert_eq!(def_regular_arg_count(&def), 2);
    }

    #[test]
    fn def_regular_arg_count_no_args() {
        let node = parse_first_stmt(b"def foo; end");
        let def = node.as_def_node().unwrap();
        assert_eq!(def_regular_arg_count(&def), 0);
    }

    #[test]
    fn def_first_arg_name_works() {
        let node = parse_first_stmt(b"def foo(bar); end");
        let def = node.as_def_node().unwrap();
        assert_eq!(def_first_arg_name(&def), Some("bar".to_string()));
    }

    #[test]
    fn def_first_arg_name_no_args() {
        let node = parse_first_stmt(b"def foo; end");
        let def = node.as_def_node().unwrap();
        assert_eq!(def_first_arg_name(&def), None);
    }

    #[test]
    fn str_contains_def_in_string() {
        let node = parse_first_stmt(b"\"def foo\"");
        assert!(str_contains_def(&node));
    }

    #[test]
    fn str_contains_def_no_def() {
        let node = parse_first_stmt(b"\"hello\"");
        assert!(!str_contains_def(&node));
    }

    #[test]
    fn str_contains_def_not_string() {
        let node = parse_first_stmt(b"42");
        assert!(!str_contains_def(&node));
    }

    #[test]
    fn str_contains_def_heredoc() {
        let node = parse_first_stmt(b"<<~RUBY\ndef foo\nRUBY\n");
        assert!(str_contains_def(&node));
    }

    #[test]
    fn body_expression_count_none() {
        assert_eq!(body_expression_count(&None), 0);
    }

    #[test]
    fn body_expression_count_single() {
        let node = parse_first_stmt(b"def foo; 42; end");
        let def = node.as_def_node().unwrap();
        assert_eq!(body_expression_count(&def.body()), 1);
    }

    #[test]
    fn body_expression_count_multiple() {
        let node = parse_first_stmt(b"def foo; 1; 2; 3; end");
        let def = node.as_def_node().unwrap();
        assert_eq!(body_expression_count(&def.body()), 3);
    }

    #[test]
    fn body_single_expression_works() {
        let node = parse_first_stmt(b"def foo; 42; end");
        let def = node.as_def_node().unwrap();
        let single = body_single_expression(def.body());
        assert!(single.is_some());
        assert!(single.unwrap().as_integer_node().is_some());
    }

    #[test]
    fn body_single_expression_none_for_multiple() {
        let node = parse_first_stmt(b"def foo; 1; 2; end");
        let def = node.as_def_node().unwrap();
        assert!(body_single_expression(def.body()).is_none());
    }

    #[test]
    fn body_single_expression_none_for_empty() {
        assert!(body_single_expression(None).is_none());
    }

    #[test]
    fn compute_newline_positions_works() {
        let source = b"line1\nline2\nline3";
        let positions = compute_newline_positions(source);
        assert_eq!(positions, vec![5, 11]);
    }

    #[test]
    fn compute_newline_positions_empty() {
        assert!(compute_newline_positions(b"").is_empty());
    }

    #[test]
    fn compute_newline_positions_no_newlines() {
        assert!(compute_newline_positions(b"hello").is_empty());
    }

    #[test]
    fn prism_handles_ascii_encoding() {
        let source = b"# encoding: ASCII\nx = 1\n";
        let result = ruby_prism::parse(source);
        assert!(result.errors().next().is_none());
    }

    #[test]
    fn prism_handles_us_ascii_encoding() {
        let source = b"# encoding: us-ascii\nx = 1\n";
        let result = ruby_prism::parse(source);
        assert!(result.errors().next().is_none());
    }
}