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
use crate::lint::{Hit, Rule, Severity};
use crate::visit;

pub struct MagnitudeOverSquared;
pub struct UncachedGetService;
pub struct TweenInfoInFunction;
pub struct RaycastParamsInFunction;
pub struct InstanceNewInLoop;
pub struct CFrameNewInLoop;
pub struct Vector3NewInLoop;
pub struct OverlapParamsInFunction;
pub struct NumberRangeInFunction;
pub struct NumberSequenceInFunction;
pub struct ColorSequenceInFunction;
pub struct TweenCreateInLoop;
pub struct GetAttributeInLoop;
pub struct Color3NewInLoop;
pub struct UDim2NewInLoop;
pub struct RepeatedMethodCall;
pub struct CurrentCameraUncached;
pub struct LocalPlayerUncached;
pub struct WorkspaceLookupInLoop;
pub struct RepeatedColor3;
pub struct EnumLookupInLoop;
pub struct BrickColorNewInLoop;
pub struct RegionNewInLoop;

impl Rule for MagnitudeOverSquared {
    fn id(&self) -> &'static str { "cache::magnitude_over_squared" }
    fn severity(&self) -> Severity { Severity::Warn }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        visit::find_pattern_positions(source, ".Magnitude")
            .into_iter()
            .filter(|&pos| {
                // Only flag when used in comparison context (< > <= >= == ~=)
                let after_start = pos + ".Magnitude".len();
                let after_end = visit::ceil_char(source, (after_start + 30).min(source.len()));
                let after = source[after_start..after_end].trim_start();
                after.starts_with('<') || after.starts_with('>')
                    || after.starts_with("==") || after.starts_with("~=")
                    || after.starts_with("then")
            })
            .map(|pos| Hit {
                pos,
                msg: ".Magnitude in comparison uses sqrt - compare squared distances with .Magnitude^2 or dot product".into(),
            })
            .collect()
    }
}

impl Rule for UncachedGetService {
    fn id(&self) -> &'static str { "cache::uncached_get_service" }
    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_func && visit::is_method_call(call, "GetService") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: ":GetService() inside function body - cache at module level".into(),
                });
            }
        });
        hits
    }
}

impl Rule for TweenInfoInFunction {
    fn id(&self) -> &'static str { "cache::tween_info_in_function" }
    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_func && visit::is_dot_call(call, "TweenInfo", "new") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "TweenInfo.new() in function - cache as module-level constant".into(),
                });
            }
        });
        hits
    }
}

impl Rule for RaycastParamsInFunction {
    fn id(&self) -> &'static str { "cache::raycast_params_in_function" }
    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_func && visit::is_dot_call(call, "RaycastParams", "new") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "RaycastParams.new() in function - cache and reuse".into(),
                });
            }
        });
        hits
    }
}

impl Rule for InstanceNewInLoop {
    fn id(&self) -> &'static str { "cache::instance_new_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, "Instance", "new") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "Instance.new() in loop - consider Clone() or pre-allocation".into(),
                });
            }
        });
        hits
    }
}

impl Rule for CFrameNewInLoop {
    fn id(&self) -> &'static str { "cache::cframe_new_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 {
                return;
            }
            let is_cframe = visit::is_dot_call(call, "CFrame", "new")
                || visit::is_dot_call(call, "CFrame", "lookAt")
                || visit::is_dot_call(call, "CFrame", "Angles")
                || visit::is_dot_call(call, "CFrame", "fromEulerAnglesXYZ")
                || visit::is_dot_call(call, "CFrame", "fromOrientation");
            if is_cframe {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "CFrame constructor in loop - cache if arguments are loop-invariant".into(),
                });
            }
        });
        hits
    }
}

impl Rule for Vector3NewInLoop {
    fn id(&self) -> &'static str { "cache::vector3_new_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, "Vector3", "new") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "Vector3.new() in loop - cache if arguments are loop-invariant".into(),
                });
            }
        });
        hits
    }
}

impl Rule for OverlapParamsInFunction {
    fn id(&self) -> &'static str { "cache::overlap_params_in_function" }
    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_func && visit::is_dot_call(call, "OverlapParams", "new") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "OverlapParams.new() in function - cache at module level and reuse".into(),
                });
            }
        });
        hits
    }
}

impl Rule for NumberRangeInFunction {
    fn id(&self) -> &'static str { "cache::number_range_in_function" }
    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_func && visit::is_dot_call(call, "NumberRange", "new") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "NumberRange.new() in function - cache as module-level constant".into(),
                });
            }
        });
        hits
    }
}

impl Rule for NumberSequenceInFunction {
    fn id(&self) -> &'static str { "cache::number_sequence_in_function" }
    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_func && visit::is_dot_call(call, "NumberSequence", "new") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "NumberSequence.new() in function - cache as module-level constant".into(),
                });
            }
        });
        hits
    }
}

impl Rule for ColorSequenceInFunction {
    fn id(&self) -> &'static str { "cache::color_sequence_in_function" }
    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_func && visit::is_dot_call(call, "ColorSequence", "new") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "ColorSequence.new() in function - cache as module-level constant".into(),
                });
            }
        });
        hits
    }
}

impl Rule for TweenCreateInLoop {
    fn id(&self) -> &'static str { "cache::tween_create_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_method_call(call, "Create") {
                let src = format!("{call}");
                if src.contains("TweenService") || src.contains("tweenService") || src.contains("Tween") {
                    hits.push(Hit {
                        pos: visit::call_pos(call),
                        msg: "TweenService:Create() in loop - creates new tween object per iteration".into(),
                    });
                }
            }
        });
        hits
    }
}

impl Rule for GetAttributeInLoop {
    fn id(&self) -> &'static str { "cache::get_attribute_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_method_call(call, "GetAttribute") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: ":GetAttribute() in loop - ~247ns bridge cost per call, cache outside loop".into(),
                });
            }
        });
        hits
    }
}

impl Rule for Color3NewInLoop {
    fn id(&self) -> &'static str { "cache::color3_new_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 {
                return;
            }
            let is_color3 = visit::is_dot_call(call, "Color3", "new")
                || visit::is_dot_call(call, "Color3", "fromRGB")
                || visit::is_dot_call(call, "Color3", "fromHSV")
                || visit::is_dot_call(call, "Color3", "fromHex");
            if is_color3 {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "Color3 constructor in loop - cache if arguments are loop-invariant".into(),
                });
            }
        });
        hits
    }
}

impl Rule for UDim2NewInLoop {
    fn id(&self) -> &'static str { "cache::udim2_new_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 {
                return;
            }
            let is_udim2 = visit::is_dot_call(call, "UDim2", "new")
                || visit::is_dot_call(call, "UDim2", "fromScale")
                || visit::is_dot_call(call, "UDim2", "fromOffset");
            if is_udim2 {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "UDim2 constructor in loop - cache if arguments are loop-invariant".into(),
                });
            }
        });
        hits
    }
}

impl Rule for RepeatedMethodCall {
    fn id(&self) -> &'static str { "cache::repeated_method_call" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let expensive_methods = [
            ":GetChildren()", ":GetDescendants()", ":GetAttributes()",
            ":GetTags()", ":GetBoundingBox()", ":GetPivot()",
        ];
        let mut hits = Vec::new();
        for method in &expensive_methods {
            let positions = visit::find_pattern_positions(source, method);
            if positions.len() < 2 {
                continue;
            }
            let mut calls: Vec<(usize, String)> = Vec::new();
            for &pos in &positions {
                let before = &source[..pos];
                let obj_end = before.len();
                let obj_start = before.rfind(|c: char| !c.is_alphanumeric() && c != '_' && c != '.')
                    .map(|i| i + 1)
                    .unwrap_or(0);
                let obj = &source[obj_start..obj_end];
                if !obj.is_empty() && obj.chars().next().map(|c| c.is_alphabetic()).unwrap_or(false) {
                    calls.push((pos, obj.to_string()));
                }
            }

            let mut seen: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
            for (pos, obj) in &calls {
                if let Some(&first_pos) = seen.get(obj.as_str()) {
                    if pos - first_pos < 1000 {
                        let method_name = method.trim_start_matches(':').trim_end_matches("()");
                        hits.push(Hit {
                            pos: *pos,
                            msg: format!("duplicate {obj}:{method_name}() - cache in a local, each call creates a new table"),
                        });
                    }
                } else {
                    seen.insert(obj, *pos);
                }
            }
        }
        hits
    }
}

impl Rule for CurrentCameraUncached {
    fn id(&self) -> &'static str { "cache::current_camera_uncached" }
    fn severity(&self) -> Severity { Severity::Warn }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let positions = visit::find_pattern_positions(source, "workspace.CurrentCamera");
        if positions.len() < 2 {
            return vec![];
        }
        positions[1..]
            .iter()
            .map(|&pos| Hit {
                pos,
                msg: "workspace.CurrentCamera accessed multiple times - cache in a local".into(),
            })
            .collect()
    }
}

impl Rule for LocalPlayerUncached {
    fn id(&self) -> &'static str { "cache::local_player_uncached" }
    fn severity(&self) -> Severity { Severity::Warn }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let positions = visit::find_pattern_positions(source, ".LocalPlayer");
        let positions: Vec<_> = positions.into_iter().filter(|&p| {
            let after = &source[p + ".LocalPlayer".len()..];
            !after.starts_with("Uncached") && !after.starts_with("_")
        }).collect();
        if positions.len() < 2 {
            return vec![];
        }
        positions[1..]
            .iter()
            .map(|&pos| Hit {
                pos,
                msg: "Players.LocalPlayer accessed multiple times - cache in a module-level local".into(),
            })
            .collect()
    }
}

impl Rule for WorkspaceLookupInLoop {
    fn id(&self) -> &'static str { "cache::workspace_lookup_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 {
                return;
            }
            let tok = match visit::prefix_token(call) {
                Some(t) => t,
                None => return,
            };
            if visit::tok_text(tok) == "workspace" {
                if visit::is_method_call(call, "FindFirstChild")
                    || visit::is_method_call(call, "WaitForChild")
                    || visit::is_method_call(call, "FindFirstChildOfClass")
                    || visit::is_method_call(call, "FindFirstChildWhichIsA")
                {
                    hits.push(Hit {
                        pos: visit::call_pos(call),
                        msg: "workspace lookup in loop - cache the result outside the loop".into(),
                    });
                }
            }
        });
        hits
    }
}

impl Rule for RepeatedColor3 {
    fn id(&self) -> &'static str { "cache::repeated_color3" }
    fn severity(&self) -> Severity { Severity::Allow }

    fn check(&self, source: &str, _ast: &full_moon::ast::Ast) -> Vec<Hit> {
        let mut hits = Vec::new();
        let mut counts: std::collections::HashMap<String, (usize, usize)> = std::collections::HashMap::new();
        let mut start = 0;
        while let Some(idx) = source[start..].find("Color3.fromRGB(") {
            let abs = start + idx;
            let after = &source[abs + "Color3.fromRGB(".len()..];
            if let Some(close) = after.find(')') {
                let args = after[..close].to_string();
                let entry = counts.entry(format!("Color3.fromRGB({})", args)).or_insert((0, abs));
                entry.0 += 1;
            }
            start = abs + 1;
        }
        start = 0;
        while let Some(idx) = source[start..].find("Color3.new(") {
            let abs = start + idx;
            let after = &source[abs + "Color3.new(".len()..];
            if let Some(close) = after.find(')') {
                let args = after[..close].to_string();
                let entry = counts.entry(format!("Color3.new({})", args)).or_insert((0, abs));
                entry.0 += 1;
            }
            start = abs + 1;
        }
        for (call, (count, pos)) in &counts {
            if *count >= 4 {
                hits.push(Hit {
                    pos: *pos,
                    msg: format!("{} repeated {} times - extract to a module-level constant", call, count),
                });
            }
        }
        hits
    }
}

impl Rule for EnumLookupInLoop {
    fn id(&self) -> &'static str { "cache::enum_lookup_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();
        let loop_depth = build_loop_depth_map(source);
        let line_starts = line_start_offsets(source);
        let mut start = 0;
        while let Some(idx) = source[start..].find("Enum.") {
            let abs = start + idx;
            let rest = &source[abs + 5..];
            if rest.starts_with(|c: char| c.is_ascii_uppercase()) {
                if let Some(dot2) = rest.find('.') {
                    let after_dot2 = &rest[dot2 + 1..];
                    if after_dot2.starts_with(|c: char| c.is_ascii_uppercase()) {
                        let line = line_starts.partition_point(|&s| s <= abs).saturating_sub(1);
                        if line < loop_depth.len() && loop_depth[line] > 0 {
                            let end = abs + 5 + dot2 + 1 + after_dot2.find(|c: char| !c.is_alphanumeric() && c != '_').unwrap_or(after_dot2.len());
                            let enum_val = &source[abs..end];
                            hits.push(Hit {
                                pos: abs,
                                msg: format!("{} in loop - cache enum value outside the loop", enum_val),
                            });
                        }
                    }
                }
            }
            start = abs + 1;
        }
        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 BrickColorNewInLoop {
    fn id(&self) -> &'static str { "cache::brick_color_new_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_dot_call(call, "BrickColor", "new") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "BrickColor.new() in loop allocates each iteration - cache outside if arguments are loop-invariant".into(),
                });
            }
        });
        hits
    }
}

impl Rule for RegionNewInLoop {
    fn id(&self) -> &'static str { "cache::region_new_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, "Region3", "new") {
                hits.push(Hit {
                    pos: visit::call_pos(call),
                    msg: "Region3.new() in loop allocates a Region3 each iteration - cache outside if bounds are loop-invariant".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 repeated_get_children_detected() {
        let src = "local a = obj:GetChildren()\nfor _, v in obj:GetChildren() do end";
        let ast = parse(src);
        let hits = RepeatedMethodCall.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn single_get_children_ok() {
        let src = "local children = obj:GetChildren()";
        let ast = parse(src);
        let hits = RepeatedMethodCall.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn different_objects_not_flagged() {
        let src = "local a = obj1:GetChildren()\nlocal b = obj2:GetChildren()";
        let ast = parse(src);
        let hits = RepeatedMethodCall.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn current_camera_uncached_detected() {
        let src = "local c1 = workspace.CurrentCamera\nlocal c2 = workspace.CurrentCamera";
        let ast = parse(src);
        let hits = CurrentCameraUncached.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn current_camera_single_ok() {
        let src = "local cam = workspace.CurrentCamera";
        let ast = parse(src);
        let hits = CurrentCameraUncached.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn local_player_uncached_detected() {
        let src = "local p = Players.LocalPlayer\nlocal n = Players.LocalPlayer.Name";
        let ast = parse(src);
        let hits = LocalPlayerUncached.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn local_player_single_ok() {
        let src = "local player = Players.LocalPlayer";
        let ast = parse(src);
        let hits = LocalPlayerUncached.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn workspace_lookup_in_loop_detected() {
        let src = "for i = 1, 10 do\n  workspace:FindFirstChild(\"Part\")\nend";
        let ast = parse(src);
        let hits = WorkspaceLookupInLoop.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn workspace_lookup_outside_loop_ok() {
        let src = "local p = workspace:FindFirstChild(\"Part\")";
        let ast = parse(src);
        let hits = WorkspaceLookupInLoop.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn repeated_color3_detected() {
        let src = "local a = Color3.fromRGB(255, 0, 0)\nlocal b = Color3.fromRGB(255, 0, 0)\nlocal c = Color3.fromRGB(255, 0, 0)\nlocal d = Color3.fromRGB(255, 0, 0)";
        let ast = parse(src);
        let hits = RepeatedColor3.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn unique_color3_ok() {
        let src = "local a = Color3.fromRGB(255, 0, 0)\nlocal b = Color3.fromRGB(0, 255, 0)";
        let ast = parse(src);
        let hits = RepeatedColor3.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn enum_lookup_in_loop_detected() {
        let src = "for _, part in parts do\n  part.Material = Enum.Material.SmoothPlastic\nend";
        let ast = parse(src);
        let hits = EnumLookupInLoop.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn enum_lookup_outside_loop_ok() {
        let src = "part.Material = Enum.Material.SmoothPlastic";
        let ast = parse(src);
        let hits = EnumLookupInLoop.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn brick_color_in_loop_detected() {
        let src = "for i = 1, 10 do\n  local bc = BrickColor.new(\"Really red\")\nend";
        let ast = parse(src);
        let hits = BrickColorNewInLoop.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn brick_color_outside_loop_ok() {
        let src = "local bc = BrickColor.new(\"Really red\")";
        let ast = parse(src);
        let hits = BrickColorNewInLoop.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }

    #[test]
    fn region_new_in_loop_detected() {
        let src = "for i = 1, 10 do\n  local r = Region3.new(min, max)\nend";
        let ast = parse(src);
        let hits = RegionNewInLoop.check(src, &ast);
        assert_eq!(hits.len(), 1);
    }

    #[test]
    fn region_new_outside_loop_ok() {
        let src = "local r = Region3.new(min, max)";
        let ast = parse(src);
        let hits = RegionNewInLoop.check(src, &ast);
        assert_eq!(hits.len(), 0);
    }
}