luauperf 0.1.6

A static performance linter for Luau
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
use crate::lint::{Hit, Rule, Severity};
use crate::visit;

pub struct ForeachDeprecated;
pub struct GetnDeprecated;
pub struct MaxnDeprecated;
pub struct FreezeInLoop;
pub struct InsertWithPosition;
pub struct RemoveInIpairs;
pub struct PackOverLiteral;
pub struct ManualCopyLoop;
pub struct DeferredFieldAssignment;
pub struct IpairsOverNumericFor;
pub struct PolymorphicConstructor;
pub struct SortComparisonAllocation;
pub struct ClearVsNew;
pub struct TableMoveOverLoop;
pub struct ConcatWithSeparatorLoop;
pub struct PairsOverGeneralized;
pub struct NilFieldInConstructor;
pub struct RawsetInLoop;
pub struct NextTNilOverPairs;

impl Rule for ForeachDeprecated {
    fn id(&self) -> &'static str { "table::foreach_deprecated" }
    fn severity(&self) -> Severity { Severity::Error }

    fn check(&self, _source: &str, ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        visit::each_call(ast, |call, _ctx| {
            if visit::is_dot_call(call, "table", "foreach") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "table.foreach() is deprecated - use for k, v in pairs(t)".into(),
                });
            }
            if visit::is_dot_call(call, "table", "foreachi") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "table.foreachi() is deprecated - use for i, v in ipairs(t)".into(),
                });
            }
        });
        hits
    }
}

impl Rule for GetnDeprecated {
    fn id(&self) -> &'static str { "table::getn_deprecated" }
    fn severity(&self) -> Severity { Severity::Error }

    fn check(&self, _source: &str, ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        visit::each_call(ast, |call, _ctx| {
            if visit::is_dot_call(call, "table", "getn") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "table.getn() is deprecated - use #t".into(),
                });
            }
        });
        hits
    }
}

impl Rule for MaxnDeprecated {
    fn id(&self) -> &'static str { "table::maxn_deprecated" }
    fn severity(&self) -> Severity { Severity::Error }

    fn check(&self, _source: &str, ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        visit::each_call(ast, |call, _ctx| {
            if visit::is_dot_call(call, "table", "maxn") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "table.maxn() is deprecated - use #t or track max index manually".into(),
                });
            }
        });
        hits
    }
}

impl Rule for FreezeInLoop {
    fn id(&self) -> &'static str { "table::freeze_in_loop" }
    fn severity(&self) -> Severity { Severity::Warn }

    fn check(&self, _source: &str, ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        visit::each_call(ast, |call, ctx| {
            if ctx.in_loop && visit::is_dot_call(call, "table", "freeze") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "table.freeze() in loop - freeze tables once at creation, not per-iteration".into(),
                });
            }
        });
        hits
    }
}

impl Rule for InsertWithPosition {
    fn id(&self) -> &'static str { "table::insert_with_position" }
    fn severity(&self) -> Severity { Severity::Warn }

    fn check(&self, _source: &str, ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        visit::each_call(ast, |call, _ctx| {
            if visit::is_dot_call(call, "table", "insert") && visit::call_arg_count(call) == 3 {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "table.insert(t, pos, v) is O(n) shift + no FASTCALL - use 2-arg append or restructure".into(),
                });
            }
        });
        hits
    }
}

impl Rule for RemoveInIpairs {
    fn id(&self) -> &'static str { "table::remove_in_ipairs" }
    fn severity(&self) -> Severity { Severity::Error }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let remove_positions = visit::find_pattern_positions(source, "table.remove(");
        if remove_positions.is_empty() {
            return vec![];
        }

        let mut hits = Vec::new();
        for pos in remove_positions {
            let context_start = visit::floor_char(source, pos.saturating_sub(300));
            let context = &source[context_start..pos];
            if context.contains("ipairs(") || context.contains("in pairs(") {
                let has_loop_keyword = context.contains("\nfor ") || context.starts_with("for ");
                if has_loop_keyword {
                    hits.push(Hit {
                        pos,
                        msg: "table.remove() during ipairs/pairs iteration - corrupts iteration order, iterate backwards or collect removals".into(),
                    });
                }
            }
        }
        hits
    }
}

impl Rule for PackOverLiteral {
    fn id(&self) -> &'static str { "table::pack_over_literal" }
    fn severity(&self) -> Severity { Severity::Warn }

    fn check(&self, _source: &str, ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        visit::each_call(ast, |call, _ctx| {
            if visit::is_dot_call(call, "table", "pack") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "table.pack(...) - use {...} instead (table constructor is significantly faster)".into(),
                });
            }
        });
        hits
    }
}

impl Rule for ManualCopyLoop {
    fn id(&self) -> &'static str { "table::manual_copy_loop" }
    fn severity(&self) -> Severity { Severity::Warn }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        for pos in visit::find_pattern_positions(source, "in pairs(") {
            let context_start = visit::floor_char(source, pos.saturating_sub(30));
            let before = &source[context_start..pos];
            if !before.contains("for ") {
                continue;
            }
            let after_end = visit::ceil_char(source, (pos + 200).min(source.len()));
            let after = &source[pos..after_end];
            if after.contains("] = ") && after.contains("end") {
                hits.push(Hit {
                    pos,
                    msg: "manual table copy loop - use table.clone() instead (single C call, no iteration overhead)".into(),
                });
            }
        }
        hits
    }
}

impl Rule for DeferredFieldAssignment {
    fn id(&self) -> &'static str { "table::deferred_field_assignment" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let empty_positions = visit::find_pattern_positions(source, "= {}");
        if empty_positions.is_empty() {
            return vec![];
        }

        let mut hits = Vec::new();
        for &pos in &empty_positions {
            let line_start = source[..pos].rfind('\n').map(|i| i + 1).unwrap_or(0);
            let line_prefix = source[line_start..pos].trim();
            let var_name = if let Some(rest) = line_prefix.strip_prefix("local ") {
                rest.trim()
            } else {
                line_prefix
            };
            if var_name.is_empty() || var_name.contains(' ') || var_name.contains('.') {
                continue;
            }

            let after_start = pos + "= {}".len();
            let after_end = visit::ceil_char(source, (after_start + 300).min(source.len()));
            let after = &source[after_start..after_end];

            let field_pattern = format!("{var_name}.");
            let mut field_count = 0;
            for line in after.lines().take(10) {
                let trimmed = line.trim();
                if trimmed.is_empty() || trimmed.starts_with("--") {
                    continue;
                }
                if trimmed.starts_with(&field_pattern) && trimmed.contains(" = ") {
                    field_count += 1;
                } else if field_count > 0 {
                    break;
                }
            }

            if field_count >= 3 {
                hits.push(Hit {
                    pos,
                    msg: "empty {} then field assignments - use table literal {x = ..., y = ...} for table template optimization".into(),
                });
            }
        }
        hits
    }
}

impl Rule for IpairsOverNumericFor {
    fn id(&self) -> &'static str { "table::ipairs_over_numeric_for" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();

        for pos in visit::find_pattern_positions(source, "for ") {
            let after_end = visit::ceil_char(source, (pos + 300).min(source.len()));
            let after = &source[pos..after_end];

            let trimmed = after.trim();
            if !trimmed.starts_with("for ") {
                continue;
            }
            let rest = &trimmed[4..];

            let eq_idx = match rest.find(" = ") {
                Some(i) => i,
                None => continue,
            };
            let iter_var = rest[..eq_idx].trim();
            if iter_var.is_empty() || !iter_var.chars().all(|c| c.is_alphanumeric() || c == '_') {
                continue;
            }

            let after_eq = &rest[eq_idx + 3..];
            if !after_eq.starts_with("1, #") && !after_eq.starts_with("1,#") {
                continue;
            }

            let hash_idx = after_eq.find('#').unwrap();
            let after_hash = &after_eq[hash_idx + 1..];
            let table_name_end = after_hash.find(|c: char| !c.is_alphanumeric() && c != '_').unwrap_or(after_hash.len());
            let table_name = &after_hash[..table_name_end];
            if table_name.is_empty() {
                continue;
            }

            let bracket_access = format!("{table_name}[{iter_var}]");
            if after.contains(&bracket_access) {
                hits.push(Hit {
                    pos,
                    msg: format!("for {iter_var} = 1, #{table_name} with {bracket_access} - use ipairs() for FORGPREP_INEXT fast-path (~2x faster)"),
                });
            }
        }
        hits
    }
}

impl Rule for PolymorphicConstructor {
    fn id(&self) -> &'static str { "table::polymorphic_constructor" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        use std::collections::HashSet;

        let mut hits = Vec::new();
        let constructor_positions = visit::find_pattern_positions(source, "= {");
        if constructor_positions.len() < 2 {
            return hits;
        }

        let mut constructors: Vec<(usize, HashSet<String>)> = Vec::new();
        for &pos in &constructor_positions {
            let after_start = pos + "= {".len();
            let after_end = visit::ceil_char(source, (after_start + 500).min(source.len()));
            let after = &source[after_start..after_end];

            let trimmed = after.trim_start();
            if trimmed.starts_with('}') {
                continue;
            }

            let mut keys = HashSet::new();
            let mut depth = 1i32;
            let mut end_idx = after.len();
            for (i, ch) in after.char_indices() {
                if ch == '{' { depth += 1; }
                if ch == '}' {
                    depth -= 1;
                    if depth <= 0 {
                        end_idx = i;
                        break;
                    }
                }
            }
            let content = &after[..end_idx];
            for segment in content.split(',') {
                let segment = segment.trim();
                if let Some(eq_pos) = segment.find(" = ") {
                    let key = segment[..eq_pos].trim();
                    if !key.is_empty()
                        && !key.starts_with('[')
                        && key.chars().all(|c| c.is_alphanumeric() || c == '_')
                    {
                        keys.insert(key.to_string());
                    }
                }
            }

            if keys.len() >= 2 {
                constructors.push((pos, keys));
            }
        }

        for i in 0..constructors.len() {
            for j in (i + 1)..constructors.len() {
                let (pos_a, keys_a) = &constructors[i];
                let (pos_b, keys_b) = &constructors[j];
                if pos_b - pos_a > 2000 {
                    break;
                }
                if keys_a != keys_b && !keys_a.is_disjoint(keys_b) && keys_a.len() >= 2 && keys_b.len() >= 2 {
                    hits.push(Hit {
                        pos: *pos_b,
                        msg: "table constructors with different key sets in same scope - defeats inline caching (~27% overhead), use consistent shapes".into(),
                    });
                    break; // Only flag once per pair
                }
            }
        }
        hits
    }
}

impl Rule for SortComparisonAllocation {
    fn id(&self) -> &'static str { "table::sort_comparison_allocation" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        let loop_depth = build_loop_depth_map(source);
        let line_starts = line_start_offsets(source);

        for pos in visit::find_pattern_positions(source, "table.sort(") {
            let after = &source[pos + "table.sort(".len()..];
            if after.contains("function(") {
                let paren_end = after.find("function(").unwrap_or(0);
                let between = &after[..paren_end];
                if between.contains(',') {
                    let line = line_starts.partition_point(|&s| s <= pos).saturating_sub(1);
                    if line < loop_depth.len() && loop_depth[line] > 0 {
                        hits.push(Hit {
                            pos,
                            msg: "table.sort with inline function in loop - allocates comparator each iteration, hoist the function".into(),
                        });
                    }
                }
            }
        }
        hits
    }
}

impl Rule for ClearVsNew {
    fn id(&self) -> &'static str { "table::clear_vs_new" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        let loop_depth = build_loop_depth_map(source);
        let line_starts = line_start_offsets(source);

        for pos in visit::find_pattern_positions(source, "= {}") {
            let line = line_starts.partition_point(|&s| s <= pos).saturating_sub(1);
            if line < loop_depth.len() && loop_depth[line] > 0 {
                let before = &source[source[..pos].rfind('\n').map(|i| i + 1).unwrap_or(0)..pos];
                let trimmed = before.trim();
                if !trimmed.starts_with("local ") && !trimmed.is_empty() {
                    hits.push(Hit {
                        pos,
                        msg: "reassigning to {} in loop - use table.clear() to reuse the table allocation".into(),
                    });
                }
            }
        }
        hits
    }
}

impl Rule for TableMoveOverLoop {
    fn id(&self) -> &'static str { "table::move_over_loop" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        for pos in visit::find_pattern_positions(source, "for ") {
            let after_end = visit::ceil_char(source, (pos + 200).min(source.len()));
            let after = &source[pos..after_end];
            let trimmed = after.trim();
            if !trimmed.starts_with("for ") {
                continue;
            }
            if let Some(eq_pos) = trimmed.find(" = ") {
                let rest = &trimmed[eq_pos + 3..];
                if rest.starts_with("1,") || rest.starts_with("1 ,") {
                    if after.contains("] = ") && after.contains("[") {
                        let assigns: Vec<&str> = after.lines()
                            .filter(|l| l.contains("] = ") && l.contains("["))
                            .collect();
                        if assigns.len() == 1 {
                            hits.push(Hit {
                                pos,
                                msg: "element-by-element array copy - use table.move(src, 1, #src, 1, dst) instead".into(),
                            });
                        }
                    }
                }
            }
        }
        hits
    }
}

impl Rule for ConcatWithSeparatorLoop {
    fn id(&self) -> &'static str { "table::concat_with_separator_loop" }
    fn severity(&self) -> Severity { Severity::Warn }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        let loop_depth = build_loop_depth_map(source);
        let line_starts = line_start_offsets(source);

        for pos in visit::find_pattern_positions(source, " = ") {
            let line_idx = line_starts.partition_point(|&s| s <= pos).saturating_sub(1);
            if line_idx >= loop_depth.len() || loop_depth[line_idx] == 0 {
                continue;
            }
            let line_start = line_starts[line_idx];
            let line_end = source[pos..].find('\n').map(|p| pos + p).unwrap_or(source.len());
            let line = &source[line_start..line_end];
            let trimmed = line.trim();
            if trimmed.contains(" .. ") && trimmed.split(" .. ").count() >= 3 {
                let lhs = trimmed.split(" = ").next().unwrap_or("");
                let rhs = trimmed.split(" = ").nth(1).unwrap_or("");
                if rhs.contains(lhs.trim()) && rhs.contains(" .. ") {
                    hits.push(Hit {
                        pos: line_start,
                        msg: "string accumulation with .. in loop - use table.insert + table.concat for O(n) instead of O(n^2)".into(),
                    });
                }
            }
        }
        hits
    }
}

fn line_start_offsets(source: &str) -> Vec<usize> {
    let mut starts = vec![0];
    for (i, b) in source.bytes().enumerate() {
        if b == b'\n' { starts.push(i + 1); }
    }
    starts
}

fn build_loop_depth_map(source: &str) -> Vec<u32> {
    let mut depth: u32 = 0;
    let mut depths = Vec::new();
    for line in source.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with("for ") || trimmed.starts_with("while ") || trimmed.starts_with("repeat") {
            depth += 1;
        }
        depths.push(depth);
        if trimmed == "end" || trimmed.starts_with("end ") || trimmed.starts_with("until ") || trimmed == "until" {
            depth = depth.saturating_sub(1);
        }
    }
    depths
}

impl Rule for PairsOverGeneralized {
    fn id(&self) -> &'static str { "table::pairs_over_generalized" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        for pos in visit::find_pattern_positions(source, "in pairs(") {
            hits.push(Hit {
                pos,
                msg: "pairs() is unnecessary - use generalized iteration: for k, v in t do (same bytecode, no function call)".into(),
            });
        }
        for pos in visit::find_pattern_positions(source, "in ipairs(") {
            hits.push(Hit {
                pos,
                msg: "ipairs() is unnecessary - use generalized iteration: for i, v in t do (same bytecode, no function call)".into(),
            });
        }
        hits
    }
}

impl Rule for NilFieldInConstructor {
    fn id(&self) -> &'static str { "table::nil_field_in_constructor" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        for (i, line) in source.lines().enumerate() {
            let trimmed = line.trim();
            if trimmed.contains("= nil") && (trimmed.contains("= nil,") || trimmed.contains("= nil;") || trimmed.ends_with("= nil")) {
                let before = &source[..source.lines().take(i).map(|l| l.len() + 1).sum::<usize>()];
                let open_braces = before.matches('{').count();
                let close_braces = before.matches('}').count();
                if open_braces > close_braces {
                    let byte_pos: usize = source.lines().take(i).map(|l| l.len() + 1).sum();
                    hits.push(Hit {
                        pos: byte_pos,
                        msg: "nil field in table constructor defeats Luau's table template optimization - omit nil fields (they default to nil)".into(),
                    });
                }
            }
        }
        hits
    }
}

impl Rule for RawsetInLoop {
    fn id(&self) -> &'static str { "table::rawset_in_loop" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, _source: &str, ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        visit::each_call(ast, |call, ctx| {
            if ctx.in_loop && visit::is_bare_call(call, "rawset") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "rawset() in loop bypasses __newindex metamethod but is not a FASTCALL builtin - regular t[k] = v is faster when no metatable is set".into(),
                });
            }
        });
        hits
    }
}

impl Rule for NextTNilOverPairs {
    fn id(&self) -> &'static str { "table::next_t_nil_over_pairs" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        for pos in visit::find_pattern_positions(source, "next(") {
            let after = &source[pos + 5..];
            if let Some(close) = after.find(')') {
                let args = &after[..close];
                if args.contains(", nil") || args.ends_with(",nil") || args.trim() == args.split(',').next().unwrap_or("").trim() {
                    if source[pos..].starts_with("next(") {
                        let before = source[..pos].trim_end();
                        if before.ends_with("==") || before.ends_with("~=") {
                            continue;
                        }
                        if args.contains(',') && (args.contains("nil") || args.trim().split(',').nth(1).map(|s| s.trim()) == Some("nil")) {
                            hits.push(Hit {
                                pos,
                                msg: "next(t, nil) == next(t) - omit the nil second argument for cleaner empty-table check".into(),
                            });
                        }
                    }
                }
            }
        }
        hits
    }
}

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

    fn parse(src: &str) -> full_moon::ast::Ast {
        full_moon::parse(src).unwrap()
    }

    #[test]
    fn pack_detected() {
        let src = "local t = table.pack(a, b, c)";
        let ast = parse(src);
        let hits = PackOverLiteral.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn manual_copy_detected() {
        let src = "for k, v in pairs(src) do dst[k] = v end";
        let ast = parse(src);
        let hits = ManualCopyLoop.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn non_copy_pairs_not_flagged() {
        let src = "for k, v in pairs(src) do print(v) end";
        let ast = parse(src);
        let hits = ManualCopyLoop.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn deferred_field_assignment_detected() {
        let src = "local t = {}\nt.x = 1\nt.y = 2\nt.z = 3";
        let ast = parse(src);
        let hits = DeferredFieldAssignment.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn inline_constructor_not_flagged() {
        let src = "local t = {x = 1, y = 2, z = 3}";
        let ast = parse(src);
        let hits = DeferredFieldAssignment.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn ipairs_over_numeric_for_detected() {
        let src = "for i = 1, #items do\n  local item = items[i]\nend";
        let ast = parse(src);
        let hits = IpairsOverNumericFor.check(src, &ast);
        assert_eq!(hits.len(), 1);
        assert!(hits[0].msg.contains("FORGPREP_INEXT"));
    }

    #[test]
    fn ipairs_already_used_not_flagged() {
        let src = "for i, v in ipairs(items) do\n  print(v)\nend";
        let ast = parse(src);
        let hits = IpairsOverNumericFor.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn polymorphic_constructor_detected() {
        let src = "local a = {\n  name = \"x\",\n  health = 100,\n}\nlocal b = {\n  name = \"y\",\n  damage = 50,\n}";
        let ast = parse(src);
        let hits = PolymorphicConstructor.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn uniform_constructor_not_flagged() {
        let src = "local a = {\n  name = \"x\",\n  health = 100,\n}\nlocal b = {\n  name = \"y\",\n  health = 50,\n}";
        let ast = parse(src);
        let hits = PolymorphicConstructor.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn foreach_detected() {
        let src = "table.foreach(t, fn)";
        let ast = parse(src);
        let hits = ForeachDeprecated.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn pairs_loop_not_flagged_as_foreach() {
        let src = "for k, v in pairs(t) do fn(k, v) end";
        let ast = parse(src);
        let hits = ForeachDeprecated.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn insert_with_position_detected() {
        let src = "table.insert(t, 1, value)";
        let ast = parse(src);
        let hits = InsertWithPosition.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn insert_append_ok() {
        let src = "table.insert(t, value)";
        let ast = parse(src);
        let hits = InsertWithPosition.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn freeze_in_loop_detected() {
        let src = "for i = 1, 10 do\n  table.freeze(t)\nend";
        let ast = parse(src);
        let hits = FreezeInLoop.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn freeze_outside_loop_ok() {
        let src = "table.freeze(config)";
        let ast = parse(src);
        let hits = FreezeInLoop.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn sort_comparison_in_loop_detected() {
        let src = "for i = 1, 10 do\n  table.sort(t, function(a, b) return a < b end)\nend";
        let ast = parse(src);
        let hits = SortComparisonAllocation.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn sort_outside_loop_ok() {
        let src = "table.sort(t, function(a, b) return a < b end)";
        let ast = parse(src);
        let hits = SortComparisonAllocation.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn clear_vs_new_detected() {
        let src = "for i = 1, 10 do\n  results = {}\nend";
        let ast = parse(src);
        let hits = ClearVsNew.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn local_new_table_in_loop_ok() {
        let src = "for i = 1, 10 do\n  local t = {}\nend";
        let ast = parse(src);
        let hits = ClearVsNew.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn concat_with_separator_loop_detected() {
        let src = "for _, v in items do\n  result = result .. \", \" .. v\nend";
        let ast = parse(src);
        let hits = ConcatWithSeparatorLoop.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn concat_outside_loop_ok() {
        let src = "local s = a .. \", \" .. b";
        let ast = parse(src);
        let hits = ConcatWithSeparatorLoop.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn pairs_over_generalized_detected() {
        let src = "for k, v in pairs(t) do end";
        let ast = parse(src);
        let hits = PairsOverGeneralized.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn generalized_iteration_ok() {
        let src = "for k, v in t do end";
        let ast = parse(src);
        let hits = PairsOverGeneralized.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn ipairs_detected() {
        let src = "for i, v in ipairs(t) do end";
        let ast = parse(src);
        let hits = PairsOverGeneralized.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn nil_field_in_constructor_detected() {
        let src = "local t = {\n  name = \"test\",\n  value = nil,\n}";
        let ast = parse(src);
        let hits = NilFieldInConstructor.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn no_nil_field_ok() {
        let src = "local t = {\n  name = \"test\",\n  value = 42,\n}";
        let ast = parse(src);
        let hits = NilFieldInConstructor.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn rawset_in_loop_detected() {
        let src = "for i = 1, 10 do\n  rawset(t, i, val)\nend";
        let ast = parse(src);
        let hits = RawsetInLoop.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn rawset_outside_loop_ok() {
        let src = "rawset(t, \"key\", val)";
        let ast = parse(src);
        let hits = RawsetInLoop.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }
}