rustqual 0.4.2

Comprehensive Rust code quality analyzer — six dimensions: Complexity, Coupling, DRY, IOSP, SRP, Test Quality
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
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
use std::collections::{HashMap, HashSet};

use syn::visit::Visit;
use syn::{File, ImplItem, TraitItem};

/// Collects all declared function/method/type names across a project.
///
/// Used in a two-pass analysis: first pass builds the scope, second pass
/// uses it to distinguish own calls from external ones.
#[derive(Debug, Clone, Default)]
pub struct ProjectScope {
    /// Free functions: `classify_function`, `collect_rust_files`, …
    pub functions: HashSet<String>,
    /// Methods from impl/trait blocks: `analyze_file`, `load`, …
    pub methods: HashSet<String>,
    /// Struct/enum/trait names: `Analyzer`, `Config`, `Summary`, …
    pub types: HashSet<String>,
    /// Trivial getters: single-receiver, single-statement methods (equivalent to field access).
    pub trivial_methods: HashSet<String>,
    /// Methods that only appear in trait contexts (trait defs or trait impls), never in inherent impls.
    /// Dot-syntax calls to these are polymorphic dispatch, not own calls.
    pub trait_only_methods: HashSet<String>,
    /// Methods grouped by parent type name: `"Config" → {"load", "save"}`.
    pub methods_by_type: HashMap<String, HashSet<String>>,
}

impl ProjectScope {
    /// Build a ProjectScope from a set of already-parsed files.
    pub fn from_files(files: &[(&str, &File)]) -> Self {
        let mut collector = ScopeCollector {
            functions: HashSet::new(),
            methods: HashSet::new(),
            types: HashSet::new(),
            trivial_candidates: HashSet::new(),
            non_trivial_methods: HashSet::new(),
            trait_method_names: HashSet::new(),
            concrete_method_names: HashSet::new(),
            methods_by_type: HashMap::new(),
        };
        files
            .iter()
            .for_each(|(_, file)| collector.visit_file(file));
        ProjectScope {
            functions: collector.functions,
            methods: collector.methods,
            types: collector.types,
            trivial_methods: collector
                .trivial_candidates
                .difference(&collector.non_trivial_methods)
                .cloned()
                .collect(),
            trait_only_methods: collector
                .trait_method_names
                .difference(&collector.concrete_method_names)
                .cloned()
                .collect(),
            methods_by_type: collector.methods_by_type,
        }
    }

    /// Is `name` an own *function* call (path-style: `func()` or `Type::func()`)?
    ///
    /// - Single segment (`classify_function`): checks `functions`
    /// - Multi-segment (`Config::load`): checks if first segment is in `types`
    /// - `Self::method`: checks `methods` excluding trait-only
    /// - PascalCase final segment: enum variant constructor, not a call
    ///
    /// Operation: if-let + comparison logic, no own calls.
    pub fn is_own_function(&self, name: &str) -> bool {
        if let Some((prefix, method)) = name.split_once("::") {
            if prefix == "Self" {
                return self.methods.contains(method) && !self.trait_only_methods.contains(method);
            }
            self.types.contains(prefix)
                && !method.starts_with(char::is_uppercase)
                && !self.trait_only_methods.contains(method)
        } else {
            self.functions.contains(name)
        }
    }

    /// Is `name` an own *method* call (dot-style: `.method()`)?
    /// Fallback for receivers with unknown type.
    /// Operation: boolean logic, no own calls.
    pub fn is_own_method(&self, name: &str) -> bool {
        self.methods.contains(name)
            && !self.trivial_methods.contains(name)
            && !self.trait_only_methods.contains(name)
    }

    /// Is `.method()` an own call when called on `self` inside an impl of `parent_type`?
    /// Layer 1: checks if this specific type defines the method.
    /// Operation: lookup logic, no own calls.
    pub fn is_own_self_method(&self, method: &str, parent_type: &str) -> bool {
        self.methods_by_type
            .get(parent_type)
            .map(|m| m.contains(method))
            .unwrap_or(false)
            && !self.trivial_methods.contains(method)
            && !self.trait_only_methods.contains(method)
    }
}

/// Check if a method signature has only `self`/`&self`/`&mut self` with no other parameters.
/// Operation: iteration + pattern matching logic, no own calls.
fn has_trivial_self_signature(sig: &syn::Signature) -> bool {
    let has_receiver = sig
        .inputs
        .iter()
        .any(|arg| matches!(arg, syn::FnArg::Receiver(_)));
    let typed_count = sig
        .inputs
        .iter()
        .filter(|arg| matches!(arg, syn::FnArg::Typed(_)))
        .count();
    has_receiver && typed_count == 0
}

/// Check if a method call is a trivial accessor call (no-arg stdlib accessor or `.get()` with
/// a trivial argument like a literal or self field access).
/// Operation: if/match logic with inlined arg check, no own calls.
fn is_trivial_method_call(mc: &syn::ExprMethodCall) -> bool {
    let method_name = mc.method.to_string();
    if mc.args.is_empty() {
        return matches!(
            method_name.as_str(),
            "len"
                | "is_empty"
                | "clone"
                | "as_ref"
                | "as_mut"
                | "as_str"
                | "to_owned"
                | "to_string"
                | "borrow"
                | "borrow_mut"
        );
    }
    if mc.args.len() != 1 || !matches!(method_name.as_str(), "get") {
        return false;
    }
    // Inline trivial-arg check: self field access, literal, or reference thereof
    let mut current = &mc.args[0];
    loop {
        match current {
            syn::Expr::Lit(_) => return true,
            syn::Expr::Field(f) => current = &f.base,
            syn::Expr::Path(p) if p.path.is_ident("self") => return true,
            syn::Expr::Reference(r) => current = &r.expr,
            _ => return false,
        }
    }
}

/// Check if a method body is a trivial accessor (single expression accessing self fields).
/// Handles: `self.x`, `&self.x`, `self.x.clone()`, `self.x.len()`, `self.x as f64`,
/// `self.items.get(self.index)`, etc.
/// Operation: iterative loop with pattern matching, no own calls (closure hides helper).
fn is_trivial_accessor_body(block: &syn::Block) -> bool {
    if block.stmts.len() != 1 {
        return false;
    }
    let expr = match &block.stmts[0] {
        syn::Stmt::Expr(e, _) => e,
        _ => return false,
    };
    let check_call = |mc: &syn::ExprMethodCall| is_trivial_method_call(mc);
    let mut current = expr;
    loop {
        match current {
            syn::Expr::Field(_) => return true,
            syn::Expr::Reference(r) => current = &r.expr,
            syn::Expr::Cast(c) => current = &c.expr,
            syn::Expr::Unary(u) => current = &u.expr,
            syn::Expr::Paren(p) => current = &p.expr,
            syn::Expr::MethodCall(mc) if check_call(mc) => {
                current = &mc.receiver;
            }
            _ => return false,
        }
    }
}

/// AST visitor that collects declarations (functions, methods, types).
struct ScopeCollector {
    functions: HashSet<String>,
    methods: HashSet<String>,
    types: HashSet<String>,
    trivial_candidates: HashSet<String>,
    non_trivial_methods: HashSet<String>,
    /// Methods from trait definitions and `impl Trait for Struct` blocks.
    trait_method_names: HashSet<String>,
    /// Methods from inherent (non-trait) impl blocks only.
    concrete_method_names: HashSet<String>,
    /// Methods grouped by parent type.
    methods_by_type: HashMap<String, HashSet<String>>,
}

impl<'ast> Visit<'ast> for ScopeCollector {
    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        self.functions.insert(node.sig.ident.to_string());
        syn::visit::visit_item_fn(self, node);
    }

    fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
        let type_name = if let syn::Type::Path(tp) = &*node.self_ty {
            tp.path.segments.last().map(|seg| {
                self.types.insert(seg.ident.to_string());
                seg.ident.to_string()
            })
        } else {
            None
        };
        let is_trait_impl = node.trait_.is_some();
        for item in &node.items {
            if let ImplItem::Fn(method) = item {
                let name = method.sig.ident.to_string();
                self.methods.insert(name.clone());
                if let Some(ref tn) = type_name {
                    self.methods_by_type
                        .entry(tn.clone())
                        .or_default()
                        .insert(name.clone());
                }
                if is_trait_impl {
                    self.trait_method_names.insert(name.clone());
                } else {
                    self.concrete_method_names.insert(name.clone());
                }
                if has_trivial_self_signature(&method.sig)
                    && is_trivial_accessor_body(&method.block)
                {
                    self.trivial_candidates.insert(name);
                } else {
                    self.non_trivial_methods.insert(name);
                }
            }
        }
        syn::visit::visit_item_impl(self, node);
    }

    fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
        self.types.insert(node.ident.to_string());
        for item in &node.items {
            if let TraitItem::Fn(method) = item {
                let name = method.sig.ident.to_string();
                self.methods.insert(name.clone());
                self.trait_method_names.insert(name);
            }
        }
        syn::visit::visit_item_trait(self, node);
    }

    fn visit_item_struct(&mut self, node: &'ast syn::ItemStruct) {
        self.types.insert(node.ident.to_string());
        syn::visit::visit_item_struct(self, node);
    }

    fn visit_item_enum(&mut self, node: &'ast syn::ItemEnum) {
        self.types.insert(node.ident.to_string());
        syn::visit::visit_item_enum(self, node);
    }

    fn visit_item_mod(&mut self, node: &'ast syn::ItemMod) {
        // Recurse into inline modules to collect their declarations too
        syn::visit::visit_item_mod(self, node);
    }
}

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

    fn build_scope(code: &str) -> ProjectScope {
        let syntax = syn::parse_file(code).expect("Failed to parse test code");
        let files = vec![("test.rs", &syntax)];
        ProjectScope::from_files(&files)
    }

    // ── ScopeCollector Tests ──────────────────────────────────────────

    #[test]
    fn test_collect_free_functions() {
        let scope = build_scope("fn foo() {} fn bar() {}");
        assert!(scope.functions.contains("foo"));
        assert!(scope.functions.contains("bar"));
    }

    #[test]
    fn test_collect_impl_methods() {
        let scope = build_scope("struct Foo; impl Foo { fn bar(&self) {} }");
        assert!(scope.methods.contains("bar"));
        assert!(scope.types.contains("Foo"));
    }

    #[test]
    fn test_collect_trait_methods() {
        let scope = build_scope("trait T { fn baz(&self); }");
        assert!(scope.methods.contains("baz"));
        assert!(scope.types.contains("T"));
    }

    #[test]
    fn test_collect_struct_names() {
        let scope = build_scope("struct S;");
        assert!(scope.types.contains("S"));
    }

    #[test]
    fn test_collect_enum_names() {
        let scope = build_scope("enum E { A }");
        assert!(scope.types.contains("E"));
    }

    #[test]
    fn test_collect_nested_module() {
        let scope = build_scope("mod inner { fn f() {} }");
        assert!(scope.functions.contains("f"));
    }

    // ── is_own_function Tests ─────────────────────────────────────────

    #[test]
    fn test_own_function_single_segment() {
        let scope = build_scope("fn foo() {}");
        assert!(scope.is_own_function("foo"));
    }

    #[test]
    fn test_own_function_not_in_scope() {
        let scope = build_scope("fn foo() {}");
        assert!(!scope.is_own_function("unknown"));
    }

    #[test]
    fn test_own_function_type_prefix() {
        let scope = build_scope("struct Config; impl Config { fn load() {} }");
        assert!(scope.is_own_function("Config::load"));
    }

    #[test]
    fn test_own_function_external_type() {
        let scope = build_scope("fn foo() {}");
        assert!(!scope.is_own_function("String::new"));
    }

    #[test]
    fn test_own_function_self_inherent_is_own() {
        // Inherent impl method IS an own call (no longer blocked by UNIVERSAL_METHODS)
        let scope = build_scope("struct X; impl X { fn default(&self) {} }");
        assert!(scope.is_own_function("Self::default"));
    }

    #[test]
    fn test_own_function_self_own_method() {
        let scope = build_scope("struct X; impl X { fn analyze(&self) {} }");
        assert!(scope.is_own_function("Self::analyze"));
    }

    // ── is_own_method Tests ───────────────────────────────────────────

    #[test]
    fn test_own_method_in_scope() {
        let scope = build_scope("struct A; impl A { fn analyze_file(&self) {} }");
        assert!(scope.is_own_method("analyze_file"));
    }

    #[test]
    fn test_own_method_not_in_scope() {
        let scope = build_scope("struct A; impl A { fn analyze_file(&self) {} }");
        assert!(!scope.is_own_method("push"));
    }

    #[test]
    fn test_own_method_inherent_is_own() {
        // Inherent impl constructor IS an own method (type-resolution handles disambiguation)
        let scope = build_scope("struct A; impl A { fn new() -> Self { A } }");
        assert!(scope.is_own_method("new"));
    }

    #[test]
    fn test_own_method_not_universal() {
        let scope = build_scope("struct A; impl A { fn record_logic(&mut self) {} }");
        assert!(scope.is_own_method("record_logic"));
    }

    // ── Trivial Accessor Tests ───────────────────────────────────────

    #[test]
    fn test_trivial_method_field_access() {
        let scope = build_scope("struct S { x: i32 } impl S { fn x(&self) -> i32 { self.x } }");
        assert!(scope.trivial_methods.contains("x"));
    }

    #[test]
    fn test_trivial_method_len_chain() {
        let scope = build_scope(
            "struct S { items: Vec<i32> } impl S { fn count(&self) -> usize { self.items.len() } }",
        );
        assert!(scope.trivial_methods.contains("count"));
    }

    #[test]
    fn test_trivial_method_clone() {
        let scope = build_scope(
            "struct S { name: String } impl S { fn name(&self) -> String { self.name.clone() } }",
        );
        assert!(scope.trivial_methods.contains("name"));
    }

    #[test]
    fn test_trivial_method_reference() {
        let scope = build_scope(
            "struct S { data: Vec<u8> } impl S { fn data(&self) -> &Vec<u8> { &self.data } }",
        );
        assert!(scope.trivial_methods.contains("data"));
    }

    #[test]
    fn test_nontrivial_method_with_params() {
        let scope = build_scope(
            "struct S { v: Vec<i32> } impl S { fn get(&self, i: usize) -> i32 { self.v[i] } }",
        );
        assert!(!scope.trivial_methods.contains("get"));
    }

    #[test]
    fn test_nontrivial_method_with_logic() {
        let scope = build_scope(
            "struct S { x: i32 } impl S { fn check(&self) -> bool { if self.x > 0 { true } else { false } } }",
        );
        assert!(!scope.trivial_methods.contains("check"));
    }

    #[test]
    fn test_nontrivial_method_multi_stmt() {
        let scope = build_scope(
            "struct S { x: i32 } impl S { fn compute(&self) -> i32 { let y = self.x; y } }",
        );
        assert!(!scope.trivial_methods.contains("compute"));
    }

    #[test]
    fn test_trivial_method_not_own_call() {
        let scope = build_scope(
            "struct S { items: Vec<i32> } impl S { fn count(&self) -> usize { self.items.len() } }",
        );
        assert!(
            !scope.is_own_method("count"),
            "Trivial getter should not be counted as own call"
        );
    }

    // ── Bug 4: Type::new() / Type::default() Not Own Call ──────────

    #[test]
    fn test_own_function_type_inherent_is_own() {
        // Inherent impl constructors ARE own calls (type-resolution handles disambiguation)
        let scope = build_scope("struct MyType; impl MyType { fn new() -> Self { MyType } }");
        assert!(
            scope.is_own_function("MyType::new"),
            "MyType::new() IS an own function (inherent impl)"
        );
    }

    #[test]
    fn test_own_function_trait_impl_blocked() {
        // Trait impl methods are NOT own calls (polymorphic dispatch)
        let scope = build_scope(
            "struct MyType; trait Foo { fn foo(&self); } impl Foo for MyType { fn foo(&self) {} }",
        );
        assert!(
            !scope.is_own_function("MyType::foo"),
            "Trait impl method should NOT be own function"
        );
    }

    #[test]
    fn test_own_function_type_custom_still_counted() {
        let scope = build_scope("struct MyType; impl MyType { fn load() -> Self { MyType } }");
        assert!(
            scope.is_own_function("MyType::load"),
            "MyType::load() SHOULD be own function (load is not universal)"
        );
    }

    // ── Bug 5: Trivial .get() Accessor Tests ────────────────────────

    #[test]
    fn test_trivial_method_get_self_field() {
        let scope = build_scope(
            "struct S { items: Vec<i32>, index: usize }
             impl S { fn current(&self) -> Option<&i32> { self.items.get(self.index) } }",
        );
        assert!(
            scope.trivial_methods.contains("current"),
            ".get(self.field) should be trivial"
        );
    }

    #[test]
    fn test_trivial_method_get_literal() {
        let scope = build_scope(
            "struct S { items: Vec<i32> }
             impl S { fn first(&self) -> Option<&i32> { self.items.get(0) } }",
        );
        assert!(
            scope.trivial_methods.contains("first"),
            ".get(0) should be trivial"
        );
    }

    #[test]
    fn test_trivial_method_get_ref_field() {
        let scope = build_scope(
            "struct S { map: std::collections::HashMap<String, i32>, key: String }
             impl S { fn entry(&self) -> Option<&i32> { self.map.get(&self.key) } }",
        );
        assert!(
            scope.trivial_methods.contains("entry"),
            ".get(&self.key) should be trivial"
        );
    }

    #[test]
    fn test_trivial_method_get_deep_field() {
        let scope = build_scope(
            "struct Config { idx: usize }
             struct S { data: Vec<i32>, config: Config }
             impl S { fn item(&self) -> Option<&i32> { self.data.get(self.config.idx) } }",
        );
        assert!(
            scope.trivial_methods.contains("item"),
            ".get(self.config.idx) should be trivial"
        );
    }

    // ── Trait-Only Method Tests ──────────────────────────────────

    #[test]
    fn test_trait_only_method_not_own_call() {
        let scope = build_scope(
            "trait Provider { fn fetch(&self) -> i32; }
             struct S;
             impl Provider for S { fn fetch(&self) -> i32 { 42 } }",
        );
        assert!(
            scope.trait_only_methods.contains("fetch"),
            "fetch only appears in trait + trait impl, should be trait-only"
        );
        assert!(
            !scope.is_own_method("fetch"),
            "trait-only method should NOT be counted as own call"
        );
    }

    #[test]
    fn test_trait_and_inherent_collision_not_trait_only() {
        let scope = build_scope(
            "trait T { fn process(&self); }
             struct A;
             impl T for A { fn process(&self) {} }
             struct B;
             impl B { fn process(&self) {} }",
        );
        assert!(
            !scope.trait_only_methods.contains("process"),
            "process appears in both trait impl and inherent impl — not trait-only"
        );
        assert!(
            scope.is_own_method("process"),
            "collision should be counted as own call"
        );
    }

    #[test]
    fn test_external_trait_impl_trait_only() {
        // Simulates implementing an external trait locally
        let scope = build_scope(
            "struct S;
             impl std::fmt::Display for S {
                 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { Ok(()) }
             }",
        );
        // fmt is a UNIVERSAL_METHOD so would be excluded anyway, but the trait_only
        // tracking should still work. Let's test with a non-universal name:
        let scope2 = build_scope(
            "trait ExternalTrait { fn do_work(&self); }
             struct S;
             impl ExternalTrait for S { fn do_work(&self) {} }",
        );
        assert!(
            scope2.trait_only_methods.contains("do_work"),
            "Method only in trait impl should be trait-only"
        );
        assert!(
            !scope2.is_own_method("do_work"),
            "trait-only method should not be own call"
        );
        // Verify fmt is still in the set (even though UNIVERSAL_METHODS would block it)
        assert!(scope.trait_only_methods.contains("fmt"));
    }

    #[test]
    fn test_self_path_trait_only_not_own_function() {
        let scope = build_scope(
            "trait Provider { fn fetch(&self) -> i32; }
             struct S;
             impl Provider for S { fn fetch(&self) -> i32 { 42 } }",
        );
        assert!(
            !scope.is_own_function("Self::fetch"),
            "Self::fetch for trait-only method should NOT be own function"
        );
    }

    #[test]
    fn test_trait_def_only_no_impl() {
        let scope = build_scope("trait Provider { fn fetch_data(&self) -> Vec<u8>; }");
        assert!(
            scope.trait_only_methods.contains("fetch_data"),
            "Method only in trait definition should be trait-only"
        );
        assert!(
            !scope.is_own_method("fetch_data"),
            "trait-only method should not be own call"
        );
    }

    #[test]
    fn test_nontrivial_method_get_computed_arg() {
        let scope = build_scope(
            "struct S { items: Vec<i32>, index: usize }
             impl S { fn item(&self) -> Option<&i32> { self.items.get(self.index + 1) } }",
        );
        assert!(
            !scope.trivial_methods.contains("item"),
            ".get(self.index + 1) should NOT be trivial (arithmetic)"
        );
    }

    // ── Name Collision Tests ─────────────────────────────────────────

    #[test]
    fn test_name_collision_conservative() {
        let scope = build_scope(
            "struct A { x: i32 }
             impl A { fn value(&self) -> i32 { self.x } }
             struct B { items: Vec<i32> }
             impl B { fn value(&self, idx: usize) -> i32 { self.items[idx] } }",
        );
        assert!(
            !scope.trivial_methods.contains("value"),
            "Name collision should be conservative — non-trivial wins"
        );
        assert!(
            scope.is_own_method("value"),
            "Collided method should be counted as own call"
        );
    }

    #[test]
    fn test_enum_variant_constructor_not_own_call() {
        let code = r#"
            enum ChunkKind {
                Function,
                Method,
                Other(String),
            }
            impl ChunkKind {
                fn as_str(&self) -> &str { "" }
            }
            fn determine_kind(key: &str) -> ChunkKind {
                match key {
                    "fn" => ChunkKind::Function,
                    "method" => ChunkKind::Method,
                    _ => ChunkKind::Other(key.to_string()),
                }
            }
        "#;
        let syntax = syn::parse_file(code).unwrap();
        let scope = ProjectScope::from_files(&[("test.rs", &syntax)]);

        // PascalCase variants should NOT be own calls
        assert!(
            !scope.is_own_function("ChunkKind::Function"),
            "Enum variant ChunkKind::Function should not be an own call"
        );
        assert!(
            !scope.is_own_function("ChunkKind::Other"),
            "Enum variant ChunkKind::Other should not be an own call"
        );
        // snake_case methods SHOULD be own calls
        assert!(
            scope.is_own_function("ChunkKind::as_str"),
            "Method ChunkKind::as_str should be an own call"
        );
    }
}