rustqual 1.2.5

Comprehensive Rust code quality analyzer — seven dimensions: IOSP, Complexity, DRY, SRP, Coupling, Test Quality, Architecture
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
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
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
//! Regression harness for call-parity receiver-type inference at the
//! `collect_canonical_calls` level.
//!
//! Each test sets up a workspace type-index with a `Session` type
//! (`open()`/`diff()`/… methods) and a `Ctx` struct carrying a
//! `session` field, then runs a minimal fn body through
//! `collect_canonical_calls`. Positive tests assert the expected
//! `crate::…::Type::method` edge appears in the output; negative
//! tests assert that documented limits correctly fall back to
//! `<method>:name` instead of producing a spurious edge.
//!
//! Coverage targets two pattern families: method-chain constructors
//! (`Type::ctor().chain()?.method()`) and cascading struct-field
//! access (`self.field.method()`), plus the fast-path patterns that
//! must stay green.

use crate::adapters::analyzers::architecture::call_parity_rule::calls::{
    collect_canonical_calls, FnContext,
};
use crate::adapters::analyzers::architecture::call_parity_rule::local_symbols::FileScope;
use crate::adapters::analyzers::architecture::call_parity_rule::type_infer::{
    CanonicalType, WorkspaceTypeIndex,
};
use crate::adapters::analyzers::architecture::call_parity_rule::workspace_graph::collect_local_symbols;
use crate::adapters::shared::use_tree::{
    gather_alias_map, gather_alias_map_scoped, AliasMap, ScopedAliasMap,
};
use std::collections::{HashMap, HashSet};

const SESSION_PATH: &str = "crate::app::session::Session";
const CTX_PATH: &str = "crate::app::Ctx";

/// RegFixture bundling a parsed file plus the resolution inputs
/// (`alias_map`, `local_symbols`, `crate_root_modules`) that
/// `collect_canonical_calls` expects.
struct RegFixture {
    file: syn::File,
    alias_map: AliasMap,
    local_symbols: HashSet<String>,
    crate_roots: HashSet<String>,
}

fn parse(src: &str) -> RegFixture {
    let file: syn::File = syn::parse_str(src).expect("parse fixture");
    let alias_map = gather_alias_map(&file);
    let local_symbols = collect_local_symbols(&file);
    RegFixture {
        file,
        alias_map,
        local_symbols,
        crate_roots: HashSet::new(),
    }
}

/// Pre-populated workspace index modelling a Session + Ctx shape.
fn sample_session_index() -> WorkspaceTypeIndex {
    let session = CanonicalType::path(["crate", "app", "session", "Session"]);
    let response = CanonicalType::path(["crate", "app", "Response"]);
    let error = CanonicalType::path(["crate", "app", "Error"]);
    let mut index = WorkspaceTypeIndex::new();
    // Session::open() -> Result<Session, Error>
    index.insert_method_return(
        SESSION_PATH,
        "open",
        CanonicalType::Result(Box::new(session.clone())),
    );
    // Session::open_cwd() -> Result<Session, Error>
    index.insert_method_return(
        SESSION_PATH,
        "open_cwd",
        CanonicalType::Result(Box::new(session.clone())),
    );
    // Session::diff() -> Response
    index.insert_method_return(SESSION_PATH, "diff", response.clone());
    // Session::files() -> Response
    index.insert_method_return(SESSION_PATH, "files", response.clone());
    // Session::insert() -> Result<Response, Error>
    index.insert_method_return(
        SESSION_PATH,
        "insert",
        CanonicalType::Result(Box::new(response.clone())),
    );
    // Ctx { session: Session }
    index.insert_struct_field(CTX_PATH, "session", session);
    // Free fn make_session() -> Result<Session, Error>
    index.fn_returns.insert(
        "crate::app::make_session".to_string(),
        CanonicalType::Result(Box::new(CanonicalType::path([
            "crate", "app", "session", "Session",
        ]))),
    );
    let _ = error; // keep in scope if extensions need it
    index
}

fn find_fn<'a>(file: &'a syn::File, name: &str) -> &'a syn::ItemFn {
    file.items
        .iter()
        .find_map(|item| match item {
            syn::Item::Fn(f) if f.sig.ident == name => Some(f),
            _ => None,
        })
        .unwrap_or_else(|| panic!("fn {name} not in fixture"))
}

fn sig_params(sig: &syn::Signature) -> Vec<(String, &syn::Type)> {
    sig.inputs
        .iter()
        .filter_map(|arg| match arg {
            syn::FnArg::Typed(pt) => match pt.pat.as_ref() {
                syn::Pat::Ident(pi) => Some((pi.ident.to_string(), pt.ty.as_ref())),
                _ => None,
            },
            _ => None,
        })
        .collect()
}

/// Run the fn body through `collect_canonical_calls` with the given
/// workspace index. Returns the set of canonical call targets.
fn run(fx: &RegFixture, index: &WorkspaceTypeIndex, fn_name: &str) -> HashSet<String> {
    let f = find_fn(&fx.file, fn_name);
    run_with_self(fx, index, &f.sig, &f.block, None)
}

/// Run an `impl Type { fn name(&self, …) { … } }` body through the
/// collector with `self_type` set to crate-rooted segments. The
/// caller passes the canonical path so the test can bind to whichever
/// module the workspace index models for `Type` (e.g. Session lives
/// under `crate::app::session::*` in `sample_session_index()`).
fn run_impl_method(
    fx: &RegFixture,
    index: &WorkspaceTypeIndex,
    type_name: &str,
    fn_name: &str,
    self_segs: Vec<String>,
) -> HashSet<String> {
    let (_, f) = find_impl_method(&fx.file, type_name, fn_name);
    run_with_self(fx, index, &f.sig, &f.block, Some(self_segs))
}

fn run_with_self(
    fx: &RegFixture,
    index: &WorkspaceTypeIndex,
    sig: &syn::Signature,
    body: &syn::Block,
    self_type: Option<Vec<String>>,
) -> HashSet<String> {
    let ctx = FnContext {
        file: &FileScope {
            path: "src/cli/handlers.rs",
            alias_map: &fx.alias_map,
            aliases_per_scope: &ScopedAliasMap::new(),
            local_symbols: &fx.local_symbols,
            local_decl_scopes: &HashMap::new(),
            crate_root_modules: &fx.crate_roots,
            workspace_module_paths: None,
        },
        mod_stack: &[],
        body,
        signature_params: sig_params(sig),
        generic_params: std::collections::HashMap::new(),
        self_type,
        workspace_index: Some(index),
        workspace_files: None,
        reexports: None,
    };
    collect_canonical_calls(&ctx)
}

fn find_impl_method<'a>(
    file: &'a syn::File,
    type_name: &str,
    fn_name: &str,
) -> (Vec<String>, &'a syn::ImplItemFn) {
    file.items
        .iter()
        .filter_map(|item| match item {
            syn::Item::Impl(i) => Some(i),
            _ => None,
        })
        .find_map(|item_impl| {
            let segs = impl_self_segments(item_impl)?;
            if segs.last().map(String::as_str) != Some(type_name) {
                return None;
            }
            item_impl.items.iter().find_map(|it| match it {
                syn::ImplItem::Fn(f) if f.sig.ident == fn_name => Some((segs.clone(), f)),
                _ => None,
            })
        })
        .unwrap_or_else(|| panic!("impl {type_name}::{fn_name} not in fixture"))
}

fn impl_self_segments(item: &syn::ItemImpl) -> Option<Vec<String>> {
    let syn::Type::Path(p) = item.self_ty.as_ref() else {
        return None;
    };
    Some(
        p.path
            .segments
            .iter()
            .map(|s| s.ident.to_string())
            .collect(),
    )
}

// ═══════════════════════════════════════════════════════════════════
// Positive: method-chain constructor patterns
// ═══════════════════════════════════════════════════════════════════

#[test]
fn method_chain_ctor_open_map_err_unwrap_resolves_receiver() {
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            let s = Session::open().map_err(handle).unwrap();
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "expected Session::diff edge, got {calls:?}"
    );
}

#[test]
fn method_chain_ctor_open_cwd_map_err_try_resolves_receiver() {
    // The exact pattern that motivated this inference work:
    // `let session = open_cwd().map_err(f)?` then `session.method()`.
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            let s = Session::open_cwd().map_err(map_err)?;
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "expected Session::diff edge, got {calls:?}"
    );
}

#[test]
fn method_chain_ctor_plain_unwrap_resolves_receiver() {
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            let s = Session::open().unwrap();
            s.files();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(calls.contains("crate::app::session::Session::files"));
}

#[test]
fn method_chain_ctor_expect_message_resolves_receiver() {
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            let s = Session::open().expect("session must open");
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(calls.contains("crate::app::session::Session::diff"));
}

#[test]
fn method_chain_ctor_unwrap_or_else_closure_resolves_receiver() {
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            let s = Session::open().unwrap_or_else(|e| fallback(e));
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(calls.contains("crate::app::session::Session::diff"));
}

#[test]
fn method_chain_ctor_chained_inline_call_resolves_receiver() {
    // No intermediate `let` — the chain resolves inside a single
    // method-call expression.
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            Session::open().unwrap().diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(calls.contains("crate::app::session::Session::diff"));
}

#[test]
fn method_chain_ctor_insert_returning_result_chained_resolves_receiver() {
    // Session::insert returns Result<Response, _> — verify the outer
    // call edge is recorded even on a Result-wrapped receiver chain.
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            Session::open().unwrap().insert();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(calls.contains("crate::app::session::Session::insert"));
}

// ═══════════════════════════════════════════════════════════════════
// Positive: cascading struct-field access patterns
// ═══════════════════════════════════════════════════════════════════

#[test]
fn cascading_struct_field_access_resolves_receiver() {
    let fx = parse(
        r#"
        use crate::app::Ctx;
        pub fn handle(ctx: &Ctx) {
            ctx.session.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "handle");
    assert!(calls.contains("crate::app::session::Session::diff"));
}

#[test]
fn cascading_struct_field_access_via_let_binding_resolves_receiver() {
    let fx = parse(
        r#"
        use crate::app::Ctx;
        pub fn handle(ctx: &Ctx) {
            let s = &ctx.session;
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "handle");
    // `&ctx.session` inferred as Session (Reference is transparent).
    assert!(calls.contains("crate::app::session::Session::diff"));
}

// ═══════════════════════════════════════════════════════════════════
// Positive: self receiver inside impl methods
// ═══════════════════════════════════════════════════════════════════

#[test]
fn self_method_call_resolves_via_impl_type() {
    // `impl Session { fn run(&self) { self.diff() } }` — `self` must
    // bind to the enclosing impl's canonical type so `self.diff()`
    // routes through `method_returns[Session::diff]` instead of
    // collapsing to `<method>:diff`.
    let fx = parse(
        r#"
        impl Session {
            pub fn run(&self) {
                self.diff();
            }
        }
        "#,
    );
    let self_segs = vec![
        "crate".to_string(),
        "app".to_string(),
        "session".to_string(),
        "Session".to_string(),
    ];
    let calls = run_impl_method(&fx, &sample_session_index(), "Session", "run", self_segs);
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "self.diff() must route through workspace_index, got {calls:?}"
    );
}

#[test]
fn self_field_access_resolves_via_impl_type() {
    // `self.session.diff()` — Self::session field, then Session::diff.
    // Needs both the Self → Ctx binding and the field-type lookup
    // chain to fire.
    let fx = parse(
        r#"
        impl Ctx {
            pub fn run(&self) {
                self.session.diff();
            }
        }
        "#,
    );
    let self_segs = vec!["crate".to_string(), "app".to_string(), "Ctx".to_string()];
    let calls = run_impl_method(&fx, &sample_session_index(), "Ctx", "run", self_segs);
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "self.session.diff() must chain through field type, got {calls:?}"
    );
}

#[test]
fn signature_param_typed_self_resolves() {
    // `fn merge(&self, other: Self)` inside `impl Session` — `other`
    // is declared as `Self`, must bind to `Session` so `other.diff()`
    // routes through `method_returns`.
    let fx = parse(
        r#"
        impl Session {
            pub fn merge(&self, other: Self) {
                other.diff();
            }
        }
        "#,
    );
    let self_segs = vec![
        "crate".to_string(),
        "app".to_string(),
        "session".to_string(),
        "Session".to_string(),
    ];
    let calls = run_impl_method(&fx, &sample_session_index(), "Session", "merge", self_segs);
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "param `other: Self` must resolve to Session, got {calls:?}"
    );
}

#[test]
fn let_annotation_self_resolves() {
    // `let other: Self = make();` inside `impl Session` — annotation
    // must substitute Self before resolving.
    let fx = parse(
        r#"
        impl Session {
            pub fn run(&self) {
                let other: Self = make();
                other.diff();
            }
        }
        "#,
    );
    let self_segs = vec![
        "crate".to_string(),
        "app".to_string(),
        "session".to_string(),
        "Session".to_string(),
    ];
    let calls = run_impl_method(&fx, &sample_session_index(), "Session", "run", self_segs);
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "`let other: Self = …` must bind to Session, got {calls:?}"
    );
}

#[test]
fn turbofish_self_inside_impl_resolves() {
    // `let s = get::<Self>(); s.diff();` inside `impl Session`. The
    // turbofish-as-return-type fallback must substitute Self before
    // resolving the type argument so the binding pins to Session.
    let fx = parse(
        r#"
        impl Session {
            pub fn run(&self) {
                let s = get::<Self>();
                s.diff();
            }
        }
        "#,
    );
    let self_segs = vec![
        "crate".to_string(),
        "app".to_string(),
        "session".to_string(),
        "Session".to_string(),
    ];
    let calls = run_impl_method(&fx, &sample_session_index(), "Session", "run", self_segs);
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "`get::<Self>()` turbofish must resolve to Session, got {calls:?}"
    );
}

#[test]
fn annotated_destructuring_self_resolves() {
    // `let Some(other): Option<Self> = maybe() else { return; };` —
    // the annotation goes through `bind_annotated` in the destructure
    // walker, which must substitute Self before resolving.
    let fx = parse(
        r#"
        impl Session {
            pub fn run(&self) {
                let Some(other): Option<Self> = maybe() else { return; };
                other.diff();
            }
        }
        "#,
    );
    let self_segs = vec![
        "crate".to_string(),
        "app".to_string(),
        "session".to_string(),
        "Session".to_string(),
    ];
    let calls = run_impl_method(&fx, &sample_session_index(), "Session", "run", self_segs);
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "annotated destructuring with Self must bind to Session, got {calls:?}"
    );
}

#[test]
fn cast_as_self_resolves() {
    // `(expr as Self).diff()` inside `impl Session` — `infer_cast`
    // resolves the target type, which must substitute Self.
    let fx = parse(
        r#"
        impl Session {
            pub fn run(&self) {
                let s = (raw() as Self);
                s.diff();
            }
        }
        "#,
    );
    let self_segs = vec![
        "crate".to_string(),
        "app".to_string(),
        "session".to_string(),
        "Session".to_string(),
    ];
    let calls = run_impl_method(&fx, &sample_session_index(), "Session", "run", self_segs);
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "`as Self` cast must resolve to Session, got {calls:?}"
    );
}

#[test]
fn qualified_path_does_not_alias_promote_through_leaf() {
    // `use std::sync::Arc as Shared;` is in scope, but the use site
    // is `wrap::Shared<Session>` — a *qualified* path. The leaf
    // `Shared` matches the alias name, but the prefix `wrap::` makes
    // the type unrelated. Receiver inference must NOT peel
    // `wrap::Shared<Session>` to `Session::diff` just because the
    // bare-`Shared` alias resolves to `Arc`. (Session is in scope
    // here so alias-promotion would otherwise produce a real edge.)
    let fx = parse(
        r#"
        use std::sync::Arc as Shared;
        use crate::app::session::Session;
        pub fn handle(s: wrap::Shared<Session>) {
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "handle");
    assert!(
        !calls.contains("crate::app::session::Session::diff"),
        "qualified path must not be alias-promoted, got {calls:?}"
    );
}

#[test]
fn qualified_local_arc_does_not_auto_peel() {
    // `wrap::Arc<Session>` where `wrap::Arc` is a *local* type that
    // happens to be named `Arc`. Direct wrapper dispatch must NOT
    // peel just because the leaf is `Arc`. Only stdlib-rooted
    // qualifications (`std::sync::Arc`) auto-peel.
    let fx = parse(
        r#"
        use crate::app::session::Session;
        mod wrap { pub struct Arc<T>(T); }
        pub fn handle(s: wrap::Arc<Session>) {
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "handle");
    assert!(
        !calls.contains("crate::app::session::Session::diff"),
        "qualified local Arc must not auto-peel as stdlib Arc, got {calls:?}"
    );
}

#[test]
fn bare_local_arc_does_not_auto_peel() {
    // `use crate::wrap::Arc;` then `s: Arc<Session>` — `Arc` is
    // single-segment and matches the stdlib wrapper list, but the
    // active `use` resolves it to a *local* type. The bare-name
    // fast path must canonicalise first and skip auto-peeling for
    // non-stdlib targets.
    let fx = parse(
        r#"
        use crate::wrap::Arc;
        use crate::app::session::Session;
        pub fn handle(s: Arc<Session>) {
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "handle");
    assert!(
        !calls.contains("crate::app::session::Session::diff"),
        "bare Arc shadowed by local must not auto-peel, got {calls:?}"
    );
}

#[test]
fn fully_qualified_user_wrapper_peels_via_leaf_match() {
    // `axum::extract::State<Session>` with
    // `transparent_wrappers = ["State"]`. The canonicaliser can't
    // resolve external `axum::*` paths, so the user-transparent
    // matching must fall back to the leaf segment.
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn handle(s: axum::extract::State<Session>) {
            s.diff();
        }
        "#,
    );
    let mut index = sample_session_index();
    index.transparent_wrappers.insert("State".to_string());
    let calls = run(&fx, &index, "handle");
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "fully-qualified user wrapper must peel via leaf-name, got {calls:?}"
    );
}

#[test]
fn renamed_external_user_wrapper_peels_via_user_config() {
    // `use axum::extract::State as ExtractState;` with
    // `transparent_wrappers = ["State"]`. The alias resolves to
    // `axum::extract::State` (external path), the last segment is
    // "State", which IS in the user-transparent set → peel. Already
    // works through the existing alias-resolution path; this test
    // pins that.
    let fx = parse(
        r#"
        use axum::extract::State as ExtractState;
        use crate::app::session::Session;
        pub fn handle(s: ExtractState<Session>) {
            s.diff();
        }
        "#,
    );
    let mut index = sample_session_index();
    index.transparent_wrappers.insert("State".to_string());
    let calls = run(&fx, &index, "handle");
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "renamed external user wrapper must peel, got {calls:?}"
    );
}

#[test]
fn aliased_local_wrapper_does_not_auto_peel() {
    // `use crate::wrap::Arc as Shared;` aliases a *local* wrapper
    // type to `Shared`. The local `crate::wrap::Arc` may not be
    // Deref-transparent like stdlib Arc, so receiver inference must
    // NOT auto-peel `Shared<Session>` just because the alias's leaf
    // segment is `Arc`. Only when the alias canonical lives in
    // `std`/`core`/`alloc` do we trust the auto-peel.
    let fx = parse(
        r#"
        use crate::wrap::Arc as Shared;
        use crate::app::session::Session;
        pub fn handle(s: Shared<Session>) {
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "handle");
    assert!(
        !calls.contains("crate::app::session::Session::diff"),
        "aliased local wrapper must not auto-peel as stdlib Arc, got {calls:?}"
    );
}

#[test]
fn aliased_stdlib_wrapper_inside_inline_mod_peels_to_inner() {
    // Same renamed-Arc test, but the `use` statement lives inside an
    // inline mod. Top-level `alias_map` doesn't see it; the scoped
    // overlay does. Receiver resolution must consult the scoped
    // overlay for wrapper-name promotion.
    let fx = parse(
        r#"
        mod inner {
            use std::sync::Arc as Shared;
            use crate::app::session::Session;
            pub fn handle(s: Shared<Session>) {
                s.diff();
            }
        }
        "#,
    );
    let f = find_fn_in_mod(&fx.file, "inner", "handle");
    let ctx = FnContext {
        file: &FileScope {
            path: "src/cli/handlers.rs",
            alias_map: &fx.alias_map,
            aliases_per_scope: &gather_alias_map_scoped(&fx.file),
            local_symbols: &fx.local_symbols,
            local_decl_scopes: &HashMap::new(),
            crate_root_modules: &fx.crate_roots,
            workspace_module_paths: None,
        },
        mod_stack: &["inner".to_string()],
        body: &f.block,
        signature_params: sig_params(&f.sig),
        generic_params: std::collections::HashMap::new(),
        self_type: None,
        workspace_index: Some(&sample_session_index()),
        workspace_files: None,
        reexports: None,
    };
    let calls = collect_canonical_calls(&ctx);
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "scoped Arc-alias inside inline mod must peel to Session, got {calls:?}"
    );
}

fn find_fn_in_mod<'a>(file: &'a syn::File, mod_name: &str, fn_name: &str) -> &'a syn::ItemFn {
    file.items
        .iter()
        .find_map(|item| match item {
            syn::Item::Mod(m) if m.ident == mod_name => m.content.as_ref(),
            _ => None,
        })
        .and_then(|(_, items)| {
            items.iter().find_map(|i| match i {
                syn::Item::Fn(f) if f.sig.ident == fn_name => Some(f),
                _ => None,
            })
        })
        .unwrap_or_else(|| panic!("fn {mod_name}::{fn_name} not found"))
}

#[test]
fn aliased_stdlib_wrapper_peels_to_inner() {
    // `use std::sync::Arc as Shared;` then `fn h(s: Shared<Session>)`
    // — the receiver resolver must follow the alias to recognise
    // `Shared` as `Arc`, peel it, and reach `Session::diff`.
    let fx = parse(
        r#"
        use std::sync::Arc as Shared;
        use crate::app::session::Session;
        pub fn handle(s: Shared<Session>) {
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "handle");
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "aliased Arc wrapper must peel to Session, got {calls:?}"
    );
}

// ═══════════════════════════════════════════════════════════════════
// Positive: free-fn return-type chain
// ═══════════════════════════════════════════════════════════════════

#[test]
fn free_fn_result_chain() {
    let fx = parse(
        r#"
        pub fn cmd() {
            let s = crate::app::make_session().unwrap();
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(calls.contains("crate::app::session::Session::diff"));
}

// ═══════════════════════════════════════════════════════════════════
// Positive: fast-path patterns (no workspace_index needed, but still work)
// ═══════════════════════════════════════════════════════════════════

#[test]
fn fast_path_signature_param_resolves() {
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn handle(s: &Session) {
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "handle");
    assert!(calls.contains("crate::app::session::Session::diff"));
}

#[test]
fn fast_path_let_type_annotation() {
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            let s: Session = make_it();
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(calls.contains("crate::app::session::Session::diff"));
}

#[test]
fn fast_path_direct_constructor() {
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            let s = Session::open_cwd();
            // No unwrap — s is Result<Session, _>, not Session.
            // Fast path on the bare-ident fails; inference fallback on
            // `s.diff()` receiver infers Result<Session>, which doesn't
            // have `diff` in the combinator table → <method>:diff.
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    // This pattern is pathological (caller should `?` or `unwrap`), but
    // we verify the resolver doesn't invent a false Session::diff edge.
    assert!(
        calls.contains("<method>:diff") || calls.contains("crate::app::session::Session::diff"),
        "pathological Result<T>.method() must either fall back or correctly unwrap, got {calls:?}"
    );
}

// ═══════════════════════════════════════════════════════════════════
// Negative: documented Stage 1 limits (unresolved stays unresolved)
// ═══════════════════════════════════════════════════════════════════

#[test]
fn negative_external_type_method_is_bare() {
    // `u32` is stdlib — no workspace entry. Calling a made-up method
    // on it must land as `<method>:name` rather than confabulate.
    let fx = parse(
        r#"
        pub fn cmd() {
            let x: u32 = 42;
            x.custom_method();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(
        calls.contains("<method>:custom_method"),
        "expected <method>:custom_method fallback, got {calls:?}"
    );
    assert!(
        !calls.iter().any(|c| c.contains("u32::custom_method")),
        "must not fabricate stdlib method edges, got {calls:?}"
    );
}

#[test]
fn negative_unannotated_generic_stays_unresolved() {
    // `fn get<T>() -> T` yields Opaque; `x.m()` falls back.
    let fx = parse(
        r#"
        pub fn cmd() {
            let x = get();
            x.some_method();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(calls.contains("<method>:some_method"));
}

#[test]
fn negative_stdlib_map_closure_is_unresolved() {
    // `.map(|r| r.diff())` inner call on the closure argument — the
    // closure body is visited, `r` has no binding → <method>:diff. The
    // outer `.map()` itself also yields <method>:map (stdlib
    // closure-dependent combinator).
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            Session::open().map(|r| r.diff());
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    // The inner `r.diff()` is unresolved; assert it stays <method>:diff.
    assert!(
        calls.iter().any(|c| c == "<method>:diff"),
        "closure-body call should stay <method>:diff without binding, got {calls:?}"
    );
}

#[test]
fn negative_tuple_destructuring_is_limit() {
    // Stage 1 doesn't track tuple element types. `let (a, s) = setup();
    // s.m()` leaves `s` unresolved.
    let fx = parse(
        r#"
        pub fn cmd() {
            let (a, s) = setup();
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    // Documented limit: tuple-destructured bindings are Opaque.
    assert!(
        calls.contains("<method>:diff"),
        "tuple destructuring is a Stage 1 limit — expected <method>:diff, got {calls:?}"
    );
}

// ═══════════════════════════════════════════════════════════════════
// Robustness: mixed positive + negative in one fn body
// ═══════════════════════════════════════════════════════════════════

// ═══════════════════════════════════════════════════════════════════
// Stage 2: Trait-Dispatch Over-Approximation
// ═══════════════════════════════════════════════════════════════════

#[test]
fn trait_dispatch_emits_trait_method_anchor() {
    // `dyn Handler.handle()` records ONE edge: the synthetic trait-method
    // anchor `<Trait>::<method>`. Concrete impls (`LoggingHandler::handle`,
    // …) are NOT emitted as separate edges from the dispatch site —
    // fanout would create N-way touchpoint sets that fire Check C
    // false-positives for a single boundary call. The anchor represents
    // the logical capability; impl-level reachability is wired in a
    // separate graph pass via `<Trait>::<method> → <Impl>::<method>`.
    let fx = parse(
        r#"
        use crate::ports::Handler;
        pub fn dispatch(h: &dyn Handler) {
            h.handle();
        }
        "#,
    );
    let mut index = WorkspaceTypeIndex::new();
    index.trait_methods.insert(
        "crate::ports::Handler".to_string(),
        std::iter::once("handle".to_string()).collect(),
    );
    index.trait_impls.insert(
        "crate::ports::Handler".to_string(),
        vec![
            "crate::app::LoggingHandler".to_string(),
            "crate::app::MetricsHandler".to_string(),
            "crate::app::AuditHandler".to_string(),
        ],
    );
    let calls = run(&fx, &index, "dispatch");
    assert!(
        calls.contains("crate::ports::Handler::handle"),
        "expected single trait-method anchor edge, got {calls:?}"
    );
    assert!(
        !calls.contains("crate::app::LoggingHandler::handle"),
        "must not emit per-impl fanout edges from dispatch (Check C false-positive source), got {calls:?}"
    );
    assert!(!calls.contains("crate::app::MetricsHandler::handle"));
    assert!(!calls.contains("crate::app::AuditHandler::handle"));
}

#[test]
fn trait_dispatch_skips_unrelated_methods() {
    // `dyn Handler.unrelated()` — the method isn't on the trait, so no
    // anchor is emitted. Falls back to <method>:name.
    let fx = parse(
        r#"
        use crate::ports::Handler;
        pub fn dispatch(h: &dyn Handler) {
            h.unrelated();
        }
        "#,
    );
    let mut index = WorkspaceTypeIndex::new();
    index.trait_methods.insert(
        "crate::ports::Handler".to_string(),
        std::iter::once("handle".to_string()).collect(),
    );
    index.trait_impls.insert(
        "crate::ports::Handler".to_string(),
        vec!["crate::app::X".to_string()],
    );
    let calls = run(&fx, &index, "dispatch");
    assert!(
        calls.contains("<method>:unrelated"),
        "unrelated method on trait must fall through, got {calls:?}"
    );
    assert!(
        !calls.contains("crate::app::X::unrelated"),
        "must not fabricate edge for non-trait method, got {calls:?}"
    );
}

#[test]
fn trait_dispatch_emits_anchor_regardless_of_default_status() {
    // `trait Handler { fn handle(&self) {} } impl Handler for AppHandler {}`
    // — the impl has no `handle` body and inherits the default. With
    // the trait-method anchor model, the dispatch still emits the
    // synthetic `<Trait>::<method>` anchor; whether the body lives in
    // the impl or the trait is no longer the dispatch site's problem
    // (the boundary walker treats the anchor as the capability the
    // adapter reaches). Concrete impl-edges are NEVER emitted from
    // dispatch — they would fabricate touchpoint fanout that fires
    // Check C false-positives.
    let fx = parse(
        r#"
        use crate::ports::Handler;
        pub fn dispatch(h: &dyn Handler) {
            h.handle();
        }
        "#,
    );
    let mut index = WorkspaceTypeIndex::new();
    index.trait_methods.insert(
        "crate::ports::Handler".to_string(),
        std::iter::once("handle".to_string()).collect(),
    );
    index.trait_impls.insert(
        "crate::ports::Handler".to_string(),
        vec!["crate::app::AppHandler".to_string()],
    );
    let mut by_impl: std::collections::HashMap<String, std::collections::HashSet<String>> =
        std::collections::HashMap::new();
    by_impl.insert(
        "crate::app::AppHandler".to_string(),
        std::collections::HashSet::new(),
    );
    index
        .trait_impl_overrides
        .insert("crate::ports::Handler".to_string(), by_impl);
    let calls = run(&fx, &index, "dispatch");
    assert!(
        calls.contains("crate::ports::Handler::handle"),
        "expected trait-method anchor edge, got {calls:?}"
    );
    assert!(
        !calls.contains("crate::app::AppHandler::handle"),
        "must not fabricate impl-method edge from dispatch, got {calls:?}"
    );
}

#[test]
fn trait_dispatch_with_send_marker_emits_anchor() {
    // `dyn Handler + Send + 'static` — marker traits skipped, Handler wins.
    let fx = parse(
        r#"
        use crate::ports::Handler;
        pub fn dispatch(h: &(dyn Handler + Send)) {
            h.handle();
        }
        "#,
    );
    let mut index = WorkspaceTypeIndex::new();
    index.trait_methods.insert(
        "crate::ports::Handler".to_string(),
        std::iter::once("handle".to_string()).collect(),
    );
    index.trait_impls.insert(
        "crate::ports::Handler".to_string(),
        vec!["crate::app::X".to_string()],
    );
    let calls = run(&fx, &index, "dispatch");
    assert!(
        calls.contains("crate::ports::Handler::handle"),
        "expected anchor edge, got {calls:?}"
    );
    assert!(!calls.contains("crate::app::X::handle"));
}

#[test]
fn trait_dispatch_box_dyn_emits_anchor() {
    // `Box<dyn Handler>` — Box is peeled, then dyn Handler → TraitBound.
    let fx = parse(
        r#"
        use crate::ports::Handler;
        pub fn dispatch(h: Box<dyn Handler>) {
            h.handle();
        }
        "#,
    );
    let mut index = WorkspaceTypeIndex::new();
    index.trait_methods.insert(
        "crate::ports::Handler".to_string(),
        std::iter::once("handle".to_string()).collect(),
    );
    index.trait_impls.insert(
        "crate::ports::Handler".to_string(),
        vec!["crate::app::Y".to_string()],
    );
    let calls = run(&fx, &index, "dispatch");
    assert!(
        calls.contains("crate::ports::Handler::handle"),
        "Box<dyn Trait> must be peeled and emit anchor, got {calls:?}"
    );
    assert!(!calls.contains("crate::app::Y::handle"));
}

// ═══════════════════════════════════════════════════════════════════
// Stage 3: User-Wrapper-Config
// ═══════════════════════════════════════════════════════════════════

#[test]
fn user_wrapper_is_peeled_on_signature_param() {
    // Axum-style `fn h(State(db): State<Db>) { db.query() }`.
    // Stage 3: configure `State` as a transparent wrapper so the
    // inference peels it to reach `Db`, and `db.query()` resolves.
    // Note: our current `extract_pat_ident_name` handles `db: State<Db>`
    // pattern via `Pat::Ident` with type, not `State(db)` tuple-struct
    // destructuring — so we use the plain form here.
    let fx = parse(
        r#"
        use crate::app::Db;
        pub fn handle(db: State<Db>) {
            db.query();
        }
        "#,
    );
    let db = CanonicalType::path(["crate", "app", "Db"]);
    let mut index = WorkspaceTypeIndex::new();
    index.insert_method_return(
        "crate::app::Db",
        "query",
        CanonicalType::path(["crate", "app", "Rows"]),
    );
    // Register `State` as a transparent wrapper.
    index.transparent_wrappers.insert("State".to_string());
    let calls = run(&fx, &index, "handle");
    let _ = db;
    assert!(
        calls.contains("crate::app::Db::query"),
        "user-wrapper State<Db> should peel to Db, got {calls:?}"
    );
}

#[test]
fn user_wrapper_unconfigured_stays_unresolved() {
    // Same fixture but WITHOUT registering State as transparent. Falls
    // through to <method>:query.
    let fx = parse(
        r#"
        use crate::app::Db;
        pub fn handle(db: State<Db>) {
            db.query();
        }
        "#,
    );
    let index = WorkspaceTypeIndex::new();
    let calls = run(&fx, &index, "handle");
    assert!(
        calls.contains("<method>:query"),
        "unconfigured wrapper must not be peeled, got {calls:?}"
    );
}

// ═══════════════════════════════════════════════════════════════════
// Stage 3: Type-Alias-Expansion
// ═══════════════════════════════════════════════════════════════════

#[test]
fn type_alias_expands_to_target_via_signature_param() {
    // `type DbRef = std::sync::Arc<Store>;` — `fn h(db: DbRef) { db.read() }`
    // Inference expands DbRef → Arc<Store> → Store (Arc wrapper peeled).
    // Store has a `read` method in our fixture.
    let fx = parse(
        r#"
        type DbRef = std::sync::Arc<Store>;
        pub fn handle(db: DbRef) {
            db.read();
        }
        "#,
    );
    let store = CanonicalType::path(["crate", "cli", "handlers", "Store"]);
    let mut index = WorkspaceTypeIndex::new();
    // Pre-populate the alias: `crate::cli::handlers::DbRef` → syn::Type
    // for `std::sync::Arc<Store>`.
    let aliased: syn::Type = syn::parse_str("std::sync::Arc<Store>").expect("parse alias target");
    // Non-generic alias — no params to substitute.
    index.type_aliases.insert(
        "crate::cli::handlers::DbRef".to_string(),
        crate::adapters::analyzers::architecture::call_parity_rule::type_infer::workspace_index::AliasDef {
            params: Vec::new(),
            target: aliased,
            decl_file: "src/cli/handlers.rs".to_string(),
            decl_mod_stack: Vec::new(),
        },
    );
    // Store::read() method.
    index.insert_method_return(
        "crate::cli::handlers::Store",
        "read",
        CanonicalType::path(["crate", "cli", "handlers", "Data"]),
    );
    // Include `DbRef` in local symbols so the alias key resolves.
    let mut fx = fx;
    fx.local_symbols.insert("DbRef".to_string());
    fx.local_symbols.insert("Store".to_string());
    let calls = run(&fx, &index, "handle");
    let _ = store;
    assert!(
        calls.contains("crate::cli::handlers::Store::read"),
        "type-alias should expand DbRef → Store, got {calls:?}"
    );
}

// ═══════════════════════════════════════════════════════════════════
// Stage 2: Turbofish-as-Return-Type
// ═══════════════════════════════════════════════════════════════════

#[test]
fn turbofish_gives_concrete_return_type() {
    // `get::<Session>()` — generic fn with single turbofish type arg.
    // No fn_returns entry (generic returns are Opaque), so the
    // turbofish fallback fires and the return type is Session.
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            let s = get::<Session>();
            s.diff();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "turbofish should resolve generic-ctor return type, got {calls:?}"
    );
}

#[test]
fn turbofish_on_type_method_is_not_overridden() {
    // `Vec::<u32>::new()` — turbofish is on the type segment, not the
    // method. Path has 2 segments, so the turbofish fallback doesn't
    // fire. `new` isn't in our index → falls through cleanly.
    let fx = parse(
        r#"
        pub fn cmd() {
            let v = Vec::<u32>::new();
            v.custom_method();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    // Important: we must NOT fabricate a `crate::…::u32::custom_method`
    // edge from the turbofish arg.
    assert!(
        calls.contains("<method>:custom_method"),
        "Vec::<T>::new() turbofish must not override, got {calls:?}"
    );
}

// ═══════════════════════════════════════════════════════════════════

#[test]
fn mixed_resolutions_in_single_body() {
    let fx = parse(
        r#"
        use crate::app::session::Session;
        pub fn cmd() {
            let s = Session::open().unwrap();
            s.diff();
            let x: u32 = 0;
            x.random();
            crate::app::make_session().unwrap().files();
        }
        "#,
    );
    let calls = run(&fx, &sample_session_index(), "cmd");
    assert!(
        calls.contains("crate::app::session::Session::diff"),
        "resolved: Session::diff missing, got {calls:?}"
    );
    assert!(
        calls.contains("crate::app::session::Session::files"),
        "resolved: Session::files missing, got {calls:?}"
    );
    assert!(
        calls.contains("<method>:random"),
        "unresolved: <method>:random expected, got {calls:?}"
    );
}