hunyi 0.1.5

渾儀 (Hunyi) — Tianheng's semantic (AST/syn) observation dimension, the complement of the static import boundary. Declare in Rust how a module's public surface must behave: what its API must not expose (types — including named public re-exports and, opt-in, a trait impl's impl-site positions — and no dyn / impl Trait or async fn seam), where a trait may be implemented, that it declares no bare pub, and which markers a type must not acquire — observed via syn, reacted in CI. The heavy syn dependency is quarantined here, never in the core.
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
//! The AST-collector cluster — the pure syntax-tree walkers that turn one parsed `syn::Item`
//! into the exposure findings each semantic rule reacts to. Every collector observes only the
//! public surface (via [`crate::syn_util::is_public`]), stamps each finding with its seam, and returns; the
//! reaction/decision lives in `lib.rs`. This module holds no state and makes no I/O.

use syn::visit::Visit;

use crate::finding::{
    PathExposure, SemanticFinding, field_seam, fn_seam, inherent_assoc_seam, inherent_method_seam,
    item_seam, member_label, render_sig_tail, tag_paths, trait_assoc_seam, trait_method_seam,
};
use crate::resolve::{
    DynCollector, ImplTraitCollector, PathCollector, ShapeExposure, UseMap, canonical_self_owner,
    path_to_string, stamp_seam, strip_raw, type_to_string,
};
use crate::syn_util::is_public;

/// Collect the returned-`impl Trait` [`ShapeExposure`]s in the **return type** of a public item's
/// functions/methods only (the existential positions). Never visits argument positions (APIT is
/// universal, not a leak) nor trait-*impl* methods (their return shape is dictated by the trait).
pub(crate) fn collect_item_return_impl_traits(
    item: &syn::Item,
    module: &str,
    uses: &UseMap,
    ordinal: usize,
    out: &mut Vec<ShapeExposure>,
) {
    match item {
        syn::Item::Fn(item) if is_public(&item.vis) => {
            let seam = fn_seam(module, &item.sig.ident);
            out.extend(stamp_seam(impl_traits_in_return(&item.sig), &seam));
        }
        syn::Item::Trait(item) if is_public(&item.vis) => {
            // A trait method's return is part of the public trait API (trait items carry no
            // individual visibility); the trait DECLARES any RPIT here.
            let trait_name = strip_raw(&item.ident.to_string());
            for trait_item in &item.items {
                if let syn::TraitItem::Fn(method) = trait_item {
                    let seam = trait_method_seam(module, &trait_name, &method.sig.ident);
                    out.extend(stamp_seam(impl_traits_in_return(&method.sig), &seam));
                }
            }
        }
        syn::Item::Impl(item) if item.trait_.is_none() => {
            let owner = canonical_self_owner(&item.self_ty, uses, module, ordinal);
            for impl_item in &item.items {
                if let syn::ImplItem::Fn(method) = impl_item {
                    if is_public(&method.vis) {
                        let seam = inherent_method_seam(&owner, &method.sig.ident);
                        out.extend(stamp_seam(impl_traits_in_return(&method.sig), &seam));
                    }
                }
            }
        }
        _ => {}
    }
}

/// The returned-`impl Trait` [`ShapeExposure`]s in a signature's **return type** (at any depth).
/// Visits `sig.output` ONLY — never `sig.inputs`, so argument-position `impl Trait` (APIT) is
/// excluded.
fn impl_traits_in_return(sig: &syn::Signature) -> Vec<ShapeExposure> {
    let mut collector = ImplTraitCollector::default();
    if let syn::ReturnType::Type(_, ty) = &sig.output {
        collector.visit_type(ty);
    }
    collector.exposures
}

pub(crate) fn collect_item_async_exposures(
    item: &syn::Item,
    module: &str,
    uses: &UseMap,
    ordinal: usize,
    out: &mut Vec<String>,
) {
    match item {
        syn::Item::Fn(item) if is_public(&item.vis) => {
            if item.sig.asyncness.is_some() {
                out.push(
                    SemanticFinding::AsyncFreeFn {
                        module: module.to_string(),
                        name: strip_raw(&item.sig.ident.to_string()),
                        tail: render_sig_tail(&item.sig),
                    }
                    .to_string(),
                );
            }
        }
        syn::Item::Trait(item) if is_public(&item.vis) => {
            let trait_name = strip_raw(&item.ident.to_string());
            for trait_item in &item.items {
                if let syn::TraitItem::Fn(method) = trait_item {
                    if method.sig.asyncness.is_some() {
                        out.push(
                            SemanticFinding::AsyncTraitMethod {
                                module: module.to_string(),
                                trait_name: trait_name.clone(),
                                name: strip_raw(&method.sig.ident.to_string()),
                                tail: render_sig_tail(&method.sig),
                            }
                            .to_string(),
                        );
                    }
                }
            }
        }
        syn::Item::Impl(item) if item.trait_.is_none() => {
            // Owner-qualify by the impl's canonical self type (via the shared `canonical_self_owner`,
            // as the other three collectors do) so `impl A`/`impl B` async methods of the same name
            // never collide under the (target, rule, finding) baseline (a false negative). Generics
            // stay distinct (`Foo<u8>` vs `Foo<u16>`); a self type with an unrenderable const-generic
            // expression is disambiguated by the impl's position, never collapsed.
            let owner = canonical_self_owner(&item.self_ty, uses, module, ordinal);
            for impl_item in &item.items {
                if let syn::ImplItem::Fn(method) = impl_item {
                    if is_public(&method.vis) && method.sig.asyncness.is_some() {
                        out.push(
                            SemanticFinding::AsyncInherentMethod {
                                owner: owner.clone(),
                                name: strip_raw(&method.sig.ident.to_string()),
                                tail: render_sig_tail(&method.sig),
                            }
                            .to_string(),
                        );
                    }
                }
            }
        }
        _ => {}
    }
}

fn paths_in_signature(sig: &syn::Signature) -> Vec<syn::Path> {
    let mut c = PathCollector::default();
    c.visit_signature(sig);
    c.paths
}

fn paths_in_type(ty: &syn::Type) -> Vec<syn::Path> {
    let mut c = PathCollector::default();
    c.visit_type(ty);
    c.paths
}

fn paths_in_generics(generics: &syn::Generics) -> Vec<syn::Path> {
    let mut c = PathCollector::default();
    c.visit_generics(generics);
    c.paths
}

fn dyns_in_signature(sig: &syn::Signature) -> Vec<ShapeExposure> {
    let mut c = DynCollector::default();
    c.visit_signature(sig);
    c.exposures
}

fn dyns_in_type(ty: &syn::Type) -> Vec<ShapeExposure> {
    let mut c = DynCollector::default();
    c.visit_type(ty);
    c.exposures
}

fn dyns_in_generics(generics: &syn::Generics) -> Vec<ShapeExposure> {
    let mut c = DynCollector::default();
    c.visit_generics(generics);
    c.exposures
}

/// Collect the type paths exposed by one item's public surface. Only `pub` items
/// contribute; `pub(crate)`/`pub(in …)`/private are internal, not exposed. Trait `impl`
/// blocks are skipped (out of scope — their shape is the trait's, not the impl site's).
pub(crate) fn collect_item_exposures(
    item: &syn::Item,
    module: &str,
    uses: &UseMap,
    ordinal: usize,
    out: &mut Vec<PathExposure>,
) {
    match item {
        syn::Item::Fn(item) if is_public(&item.vis) => {
            let seam = fn_seam(module, &item.sig.ident);
            out.extend(tag_paths(paths_in_signature(&item.sig), &seam));
        }
        syn::Item::Struct(item) if is_public(&item.vis) => {
            let name = strip_raw(&item.ident.to_string());
            out.extend(tag_paths(
                paths_in_generics(&item.generics),
                &item_seam("struct", module, &item.ident),
            ));
            for (index, field) in item.fields.iter().enumerate() {
                if is_public(&field.vis) {
                    let seam = field_seam("field", module, &name, &member_label(index, field));
                    out.extend(tag_paths(paths_in_type(&field.ty), &seam));
                }
            }
        }
        syn::Item::Enum(item) if is_public(&item.vis) => {
            let name = strip_raw(&item.ident.to_string());
            out.extend(tag_paths(
                paths_in_generics(&item.generics),
                &item_seam("enum", module, &item.ident),
            ));
            // Enum variants and their fields are as public as the enum itself. Each field
            // carries a per-member seam (`variant {Enum}::{Variant}::{index|name}`), mirroring
            // struct/union fields, so two forbidden fields of one variant stay distinct findings
            // — never collapsing to one `(target, rule, finding)` and masking a new leak.
            for variant in &item.variants {
                let owner = format!("{name}::{}", strip_raw(&variant.ident.to_string()));
                for (index, field) in variant.fields.iter().enumerate() {
                    let seam = field_seam("variant", module, &owner, &member_label(index, field));
                    out.extend(tag_paths(paths_in_type(&field.ty), &seam));
                }
            }
        }
        syn::Item::Union(item) if is_public(&item.vis) => {
            let name = strip_raw(&item.ident.to_string());
            out.extend(tag_paths(
                paths_in_generics(&item.generics),
                &item_seam("union", module, &item.ident),
            ));
            for (index, field) in item.fields.named.iter().enumerate() {
                if is_public(&field.vis) {
                    let seam = field_seam("field", module, &name, &member_label(index, field));
                    out.extend(tag_paths(paths_in_type(&field.ty), &seam));
                }
            }
        }
        syn::Item::Type(item) if is_public(&item.vis) => {
            let seam = item_seam("type", module, &item.ident);
            out.extend(tag_paths(paths_in_generics(&item.generics), &seam));
            out.extend(tag_paths(paths_in_type(&item.ty), &seam));
        }
        syn::Item::Const(item) if is_public(&item.vis) => {
            out.extend(tag_paths(
                paths_in_type(&item.ty),
                &item_seam("const", module, &item.ident),
            ));
        }
        syn::Item::Static(item) if is_public(&item.vis) => {
            out.extend(tag_paths(
                paths_in_type(&item.ty),
                &item_seam("static", module, &item.ident),
            ));
        }
        syn::Item::Trait(item) if is_public(&item.vis) => {
            let trait_name = strip_raw(&item.ident.to_string());
            let trait_seam = item_seam("trait", module, &item.ident);
            out.extend(tag_paths(paths_in_generics(&item.generics), &trait_seam));
            // Supertraits are part of the trait's public contract; walk them with the same
            // full recursion (paths_in_bounds → PathCollector) every other position uses, so a
            // forbidden type in a bound's generic argument (`Facade: AsRef<crate::infra::Secret>`)
            // is observed too — not only the bound's head trait (which paths_in_bounds still pushes,
            // preserving forbidden-supertrait-head detection).
            out.extend(tag_paths(paths_in_bounds(&item.supertraits), &trait_seam));
            for trait_item in &item.items {
                match trait_item {
                    syn::TraitItem::Fn(method) => {
                        let seam = trait_method_seam(module, &trait_name, &method.sig.ident);
                        out.extend(tag_paths(paths_in_signature(&method.sig), &seam));
                    }
                    syn::TraitItem::Type(assoc) => {
                        let seam = trait_assoc_seam("type", module, &trait_name, &assoc.ident);
                        // Full-recursion coverage for every bound position of a public associated
                        // type: its own bounds (`: Into<crate::infra::Secret>`), its generic
                        // parameters (GAT `<T: crate::infra::Marker>` + where-clause), and its
                        // default target (`= crate::infra::Secret`, an observed type position the
                        // `dyn` collector already walks) — so a forbidden generic argument here is
                        // not silently dropped as the raw-path push once did.
                        out.extend(tag_paths(paths_in_bounds(&assoc.bounds), &seam));
                        out.extend(tag_paths(paths_in_generics(&assoc.generics), &seam));
                        if let Some((_, ty)) = &assoc.default {
                            out.extend(tag_paths(paths_in_type(ty), &seam));
                        }
                    }
                    syn::TraitItem::Const(assoc) => {
                        let seam = trait_assoc_seam("const", module, &trait_name, &assoc.ident);
                        out.extend(tag_paths(paths_in_type(&assoc.ty), &seam));
                    }
                    _ => {}
                }
            }
        }
        // Inherent `impl Type { … }` (no trait): its `pub` methods are public API the module
        // authored. Trait impls (`impl Trait for Type`) carry `trait_` and are out of scope.
        syn::Item::Impl(item) if item.trait_.is_none() => {
            let owner = canonical_self_owner(&item.self_ty, uses, module, ordinal);
            for impl_item in &item.items {
                match impl_item {
                    // A public method's signature (unchanged).
                    syn::ImplItem::Fn(method) if is_public(&method.vis) => {
                        let seam = inherent_method_seam(&owner, &method.sig.ident);
                        out.extend(tag_paths(paths_in_signature(&method.sig), &seam));
                    }
                    // A public associated `const`'s declared type is public API (`Foo::K`).
                    syn::ImplItem::Const(assoc) if is_public(&assoc.vis) => {
                        let seam = inherent_assoc_seam("const", &owner, &assoc.ident);
                        out.extend(tag_paths(paths_in_type(&assoc.ty), &seam));
                    }
                    // A public associated `type`'s target is public API (`Foo::T`).
                    syn::ImplItem::Type(assoc) if is_public(&assoc.vis) => {
                        let seam = inherent_assoc_seam("type", &owner, &assoc.ident);
                        out.extend(tag_paths(paths_in_type(&assoc.ty), &seam));
                    }
                    _ => {}
                }
            }
        }
        // A bare `pub use` republishes what it names on the module's public surface — the most
        // direct exposure (`semantic-reexport-exposure`). Restricted-visibility re-exports are
        // internal, like a private field. The walked path flows through the same resolve →
        // canonicalize → match pipeline as any exposed type.
        syn::Item::Use(item) if is_public(&item.vis) => {
            walk_reexport_tree(
                &item.tree,
                Vec::new(),
                module,
                item.leading_colon.is_some(),
                out,
            );
        }
        // A `pub extern crate X [as Y];` republishes the external crate root `X` on the module's
        // public surface — like `pub use ::X;`. The exposure names the **real** crate `X` (not the
        // `as`-rename), a bare extern head (raw external set, `is_reexport`). `extern crate self`
        // renames the current crate, not an external exposure.
        syn::Item::ExternCrate(item) if is_public(&item.vis) && item.ident != "self" => {
            let name = strip_raw(&item.ident.to_string());
            out.push(PathExposure {
                seam: format!("pub extern crate {name}"),
                path: syn::Path::from(item.ident.clone()),
                is_reexport: true,
            });
        }
        _ => {}
    }
}

/// Walk a `pub use` tree, pushing one [`PathExposure`] per re-exported leaf (and the root of a
/// glob), seam-qualified by the **exported** path so two aliases of the same forbidden type stay
/// distinct findings. Handles: named/renamed leaves; grouped re-exports (per leaf); a whole-module
/// re-export (`pub use crate::infra as fs` — the leaf path is a module, matched like any path); a
/// `self` group member (`{self, X}` — re-exports the prefix module, keyed by the prefix's final
/// segment, never the literal `self`); a glob (the root prefix, which reacts iff it resolves
/// in/under the forbidden set). `as _` binds no nameable path — a stated non-observed bound.
/// `self` group member and a renamed `self` both mean "the prefix module itself" — collapse to
/// the prefix, keyed by the prefix's final segment (or the alias). Recognised on the raw `Ident`
/// (`self` is a keyword and never a raw identifier, so a string compare is exact).
fn is_self_segment(ident: &syn::Ident) -> bool {
    ident == "self"
}
fn walk_reexport_tree(
    tree: &syn::UseTree,
    prefix: Vec<syn::Ident>,
    module: &str,
    leading_colon: bool,
    out: &mut Vec<PathExposure>,
) {
    match tree {
        syn::UseTree::Path(path) => {
            let mut segs = prefix;
            segs.push(path.ident.clone());
            walk_reexport_tree(&path.tree, segs, module, leading_colon, out);
        }
        syn::UseTree::Name(name) => {
            if is_self_segment(&name.ident) {
                // `pub use crate::infra::{self, …}` re-exports the prefix module, bound under the
                // prefix's final segment (never the literal `self`).
                let exported = prefix.last().map(seg_name);
                push_reexport(&prefix, exported.as_deref(), module, leading_colon, out);
            } else {
                let exported = seg_name(&name.ident);
                let mut segs = prefix;
                segs.push(name.ident.clone());
                push_reexport(&segs, Some(&exported), module, leading_colon, out);
            }
        }
        syn::UseTree::Rename(rename) => {
            let alias = seg_name(&rename.rename);
            if alias == "_" {
                return; // `as _` binds no nameable path — a stated non-observed bound
            }
            if is_self_segment(&rename.ident) {
                // `pub use crate::infra::{self as fs}` — the prefix module, renamed.
                push_reexport(&prefix, Some(&alias), module, leading_colon, out);
            } else {
                let mut segs = prefix;
                segs.push(rename.ident.clone());
                push_reexport(&segs, Some(&alias), module, leading_colon, out);
            }
        }
        syn::UseTree::Glob(_) => {
            // The glob root: reacts iff it resolves in/under the forbidden set (the pipeline
            // decides). A sibling/ancestor root simply does not match — a stated glob bound.
            push_reexport(&prefix, Some("*"), module, leading_colon, out);
        }
        syn::UseTree::Group(group) => {
            for item in &group.items {
                walk_reexport_tree(item, prefix.clone(), module, leading_colon, out);
            }
        }
    }
}

/// A path segment's display name, raw-identifier prefix stripped (`r#type` → `type`), for the
/// human-facing exported name in the seam.
fn seg_name(ident: &syn::Ident) -> String {
    strip_raw(&ident.to_string())
}

/// Push a re-export exposure. The `syn::Path` is built **directly from the segment idents** (never
/// re-parsed from a string), so a raw-identifier segment (`pub use crate::r#type::X;`) is preserved
/// and matches correctly — `resolve_path`/`matches_forbidden` normalize raw idents downstream. The
/// seam is `pub use {module}::{exported}`. An empty segment list is skipped (a `self` under no
/// prefix cannot arise from a legal re-export).
fn push_reexport(
    segs: &[syn::Ident],
    exported: Option<&str>,
    module: &str,
    leading_colon: bool,
    out: &mut Vec<PathExposure>,
) {
    let (Some(exported), false) = (exported, segs.is_empty()) else {
        return;
    };
    let segments = segs
        .iter()
        .map(|ident| syn::PathSegment {
            ident: ident.clone(),
            arguments: syn::PathArguments::None,
        })
        .collect();
    out.push(PathExposure {
        // Preserve the `use` item's leading `::`: `pub use ::dep::X;` is an unambiguous extern
        // (resolved against the raw extern set by the query's leading-`::` branch), so it must stay
        // distinguishable from a bare `pub use dep::X;` — the latter is shadowed by a same-named
        // child `mod dep`, the former is not.
        path: syn::Path {
            leading_colon: leading_colon.then(<syn::Token![::]>::default),
            segments,
        },
        seam: format!("pub use {module}::{exported}"),
        is_reexport: true,
    });
}

/// The type paths in a signature's **return type** only (`sig.output`) — never `sig.inputs`.
/// A trait impl method's parameters/receiver are invariant with the trait declaration (not
/// refinable at the impl site), but its return MAY be refined (return-position `impl Trait` in
/// traits / async fn in traits), so a concretely-written return can expose an impl-site-authored
/// type. Observed without classifying refined-vs-dictated (that would need the possibly-foreign
/// trait definition — an essential gap), so a concrete return is observed either way.
fn paths_in_return(sig: &syn::Signature) -> Vec<syn::Path> {
    let mut c = PathCollector::default();
    if let syn::ReturnType::Type(_, ty) = &sig.output {
        c.visit_type(ty);
    }
    c.paths
}

/// The paths named across a set of trait-bounds — each bound's trait path *and* any type nested
/// in its generic arguments (`T: From<crate::infra::Secret>` yields both `From` and
/// `crate::infra::Secret`). Used for the impl-site `where` position.
fn paths_in_bounds(
    bounds: &syn::punctuated::Punctuated<syn::TypeParamBound, syn::token::Plus>,
) -> Vec<syn::Path> {
    let mut c = PathCollector::default();
    for bound in bounds {
        c.visit_type_param_bound(bound);
    }
    c.paths
}

/// Collect the type paths exposed by one **trait `impl` block**'s impl-site-authored positions
/// (`semantic-trait-impl-exposure`, opt-in). Only fires for `impl Trait for Type` (inherent impls
/// are `collect_item_exposures`'s job). The observed positions — each seam-qualified so two of them
/// exposing the same forbidden type stay distinct findings (the one forbidden bug) — are:
/// `trait-arg` (the trait ref's generic arguments, NOT the trait path itself: implementing a
/// forbidden *trait* is `must_not_acquire`/locality's concern), `self` (the Self type, bare and
/// nested), `assoc {name}` (associated type/value bindings), `where {bounded-type}` (the impl's own
/// generics + `where`-clause, keyed by the bounded type so two bounds never collapse), and
/// `method {name} return` (the written return type only — params/receiver are trait-dictated). The
/// pushed [`PathExposure`]s flow through the same resolve → canonicalize → match → `{type} exposed
/// by {seam}` pipeline as signature-coupling, with `BareFallback::Ignore` parity.
pub(crate) fn collect_trait_impl_exposures(
    item: &syn::Item,
    module: &str,
    uses: &UseMap,
    ordinal: usize,
    out: &mut Vec<PathExposure>,
) {
    let syn::Item::Impl(item) = item else { return };
    let Some((_, trait_path, _)) = &item.trait_ else {
        return; // inherent impl — governed by `collect_item_exposures`
    };
    // Seam prefix `impl {Trait} for {SelfTy}`. The Self label is canonicalized (parity with the
    // inherent-impl / locality seam owner); the trait label is the written path (a rendering-
    // granularity choice — its generic args distinguish `From<Vec<X>>` from `From<Box<X>>`).
    let trait_label = path_to_string(trait_path).unwrap_or_else(|| format!("trait_#{ordinal}"));
    let self_label = canonical_self_owner(&item.self_ty, uses, module, ordinal);
    let prefix = format!("impl {trait_label} for {self_label}");

    // 1. trait-arg — the trait ref's generic arguments (not the trait base path).
    if let Some(syn::PathArguments::AngleBracketed(args)) =
        trait_path.segments.last().map(|s| &s.arguments)
    {
        let seam = format!("{prefix} (trait-arg)");
        for arg in &args.args {
            match arg {
                syn::GenericArgument::Type(ty) => out.extend(tag_paths(paths_in_type(ty), &seam)),
                syn::GenericArgument::AssocType(at) => {
                    out.extend(tag_paths(paths_in_type(&at.ty), &seam))
                }
                _ => {}
            }
        }
    }

    // 2. self — the Self type, bare (`impl T for infra::Forbidden`) and nested
    //    (`impl T for Vec<infra::Forbidden>`). A bare `Self`/`Self::X` in a return (position 5)
    //    does not resolve and cannot double-fire here.
    out.extend(tag_paths(
        paths_in_type(&item.self_ty),
        &format!("{prefix} (self)"),
    ));

    // 4. where — impl generic-param bounds and the `where`-clause, keyed by the bounded type so
    //    two distinct bounds exposing the same type never collapse under the baseline.
    for param in &item.generics.params {
        match param {
            syn::GenericParam::Type(tp) => {
                let key = strip_raw(&tp.ident.to_string());
                let seam = format!("{prefix} (where {key})");
                out.extend(tag_paths(paths_in_bounds(&tp.bounds), &seam));
            }
            // A const-param's *type* annotation (`impl<const N: crate::infra::X>`) is impl-site-
            // authored — v1's `paths_in_generics` observes it, so the hand-rolled walk must too.
            syn::GenericParam::Const(cp) => {
                let key = strip_raw(&cp.ident.to_string());
                let seam = format!("{prefix} (where {key})");
                out.extend(tag_paths(paths_in_type(&cp.ty), &seam));
            }
            syn::GenericParam::Lifetime(_) => {}
        }
    }
    if let Some(where_clause) = &item.generics.where_clause {
        for predicate in &where_clause.predicates {
            if let syn::WherePredicate::Type(pt) = predicate {
                let key = type_to_string(&pt.bounded_ty).unwrap_or_else(|| "_".to_string());
                let seam = format!("{prefix} (where {key})");
                // Both sides are impl-site-authored: a forbidden type in the bounded (LHS) type
                // (`where crate::infra::X: Clone`) leaks as surely as one in the bound (RHS). v1's
                // `paths_in_generics` observes both; the hand-rolled walk must not lose that.
                out.extend(tag_paths(paths_in_type(&pt.bounded_ty), &seam));
                out.extend(tag_paths(paths_in_bounds(&pt.bounds), &seam));
            }
        }
    }

    for impl_item in &item.items {
        match impl_item {
            // 3. assoc {name} — associated type/value bindings authored in the impl. Both an
            //    associated `type X = …` and an associated `const X: … ` carry an impl-site type
            //    (parity with v1's trait-def walk, which observes both).
            syn::ImplItem::Type(assoc) => {
                let seam = format!("{prefix} (assoc {})", strip_raw(&assoc.ident.to_string()));
                out.extend(tag_paths(paths_in_type(&assoc.ty), &seam));
            }
            syn::ImplItem::Const(assoc) => {
                let seam = format!("{prefix} (assoc {})", strip_raw(&assoc.ident.to_string()));
                out.extend(tag_paths(paths_in_type(&assoc.ty), &seam));
            }
            // 5. method {name} return — the written return type only (never params/receiver).
            syn::ImplItem::Fn(method) => {
                let seam = format!(
                    "{prefix} (method {} return)",
                    strip_raw(&method.sig.ident.to_string())
                );
                out.extend(tag_paths(paths_in_return(&method.sig), &seam));
            }
            _ => {}
        }
    }
}

/// Collect the `dyn` trait-object shapes exposed by one item's public surface — the
/// dyn-shape complement of [`collect_item_exposures`], over the same governed positions.
/// Kept **deliberately parallel, not merged**: signature-coupling pushes bare supertrait /
/// associated-bound *paths* (whose collected paths a shared visitor would change), and this
/// walk additionally observes associated-type **defaults** (`type T = Box<dyn …>;`), a
/// position exposure-governance does not cover. A `dyn` cannot appear in a supertrait or a
/// `: Bound` (those are trait, not type, positions), so they are skipped here.
pub(crate) fn collect_item_dyn_exposures(
    item: &syn::Item,
    module: &str,
    uses: &UseMap,
    ordinal: usize,
    out: &mut Vec<ShapeExposure>,
) {
    match item {
        syn::Item::Fn(item) if is_public(&item.vis) => {
            let seam = fn_seam(module, &item.sig.ident);
            out.extend(stamp_seam(dyns_in_signature(&item.sig), &seam));
        }
        syn::Item::Struct(item) if is_public(&item.vis) => {
            let name = strip_raw(&item.ident.to_string());
            out.extend(stamp_seam(
                dyns_in_generics(&item.generics),
                &item_seam("struct", module, &item.ident),
            ));
            for (index, field) in item.fields.iter().enumerate() {
                if is_public(&field.vis) {
                    let seam = field_seam("field", module, &name, &member_label(index, field));
                    out.extend(stamp_seam(dyns_in_type(&field.ty), &seam));
                }
            }
        }
        syn::Item::Enum(item) if is_public(&item.vis) => {
            let name = strip_raw(&item.ident.to_string());
            out.extend(stamp_seam(
                dyns_in_generics(&item.generics),
                &item_seam("enum", module, &item.ident),
            ));
            // Enum variants and their fields are as public as the enum itself; per-member seam
            // for the same injectivity guarantee as the type-exposure collector above.
            for variant in &item.variants {
                let owner = format!("{name}::{}", strip_raw(&variant.ident.to_string()));
                for (index, field) in variant.fields.iter().enumerate() {
                    let seam = field_seam("variant", module, &owner, &member_label(index, field));
                    out.extend(stamp_seam(dyns_in_type(&field.ty), &seam));
                }
            }
        }
        syn::Item::Union(item) if is_public(&item.vis) => {
            let name = strip_raw(&item.ident.to_string());
            out.extend(stamp_seam(
                dyns_in_generics(&item.generics),
                &item_seam("union", module, &item.ident),
            ));
            for (index, field) in item.fields.named.iter().enumerate() {
                if is_public(&field.vis) {
                    let seam = field_seam("field", module, &name, &member_label(index, field));
                    out.extend(stamp_seam(dyns_in_type(&field.ty), &seam));
                }
            }
        }
        syn::Item::Type(item) if is_public(&item.vis) => {
            let seam = item_seam("type", module, &item.ident);
            out.extend(stamp_seam(dyns_in_generics(&item.generics), &seam));
            // A public type-alias target writing `dyn` is exposed at the alias item itself; a
            // public item that merely *names* this alias is not expanded (the resolver does
            // not expand `type` aliases — a stated bound).
            out.extend(stamp_seam(dyns_in_type(&item.ty), &seam));
        }
        syn::Item::Const(item) if is_public(&item.vis) => {
            out.extend(stamp_seam(
                dyns_in_type(&item.ty),
                &item_seam("const", module, &item.ident),
            ));
        }
        syn::Item::Static(item) if is_public(&item.vis) => {
            out.extend(stamp_seam(
                dyns_in_type(&item.ty),
                &item_seam("static", module, &item.ident),
            ));
        }
        syn::Item::Trait(item) if is_public(&item.vis) => {
            let trait_name = strip_raw(&item.ident.to_string());
            out.extend(stamp_seam(
                dyns_in_generics(&item.generics),
                &item_seam("trait", module, &item.ident),
            ));
            for trait_item in &item.items {
                match trait_item {
                    syn::TraitItem::Fn(method) => {
                        let seam = trait_method_seam(module, &trait_name, &method.sig.ident);
                        out.extend(stamp_seam(dyns_in_signature(&method.sig), &seam));
                    }
                    // The associated-type **default** (`type T = Box<dyn …>;`) is an exposed
                    // type position; the `: Bound`s are trait positions and cannot be `dyn`.
                    syn::TraitItem::Type(assoc) => {
                        if let Some((_, default)) = &assoc.default {
                            let seam = trait_assoc_seam("type", module, &trait_name, &assoc.ident);
                            out.extend(stamp_seam(dyns_in_type(default), &seam));
                        }
                    }
                    syn::TraitItem::Const(assoc) => {
                        let seam = trait_assoc_seam("const", module, &trait_name, &assoc.ident);
                        out.extend(stamp_seam(dyns_in_type(&assoc.ty), &seam));
                    }
                    _ => {}
                }
            }
        }
        syn::Item::Impl(item) if item.trait_.is_none() => {
            let owner = canonical_self_owner(&item.self_ty, uses, module, ordinal);
            for impl_item in &item.items {
                match impl_item {
                    syn::ImplItem::Fn(method) if is_public(&method.vis) => {
                        let seam = inherent_method_seam(&owner, &method.sig.ident);
                        out.extend(stamp_seam(dyns_in_signature(&method.sig), &seam));
                    }
                    // A public associated `const`/`type` declares a public-API type position, so a
                    // `dyn` written there is exposed — the same positions the signature-coupling
                    // collector observes (`collect_item_exposures`); the dyn rule must not lag it.
                    syn::ImplItem::Const(assoc) if is_public(&assoc.vis) => {
                        let seam = inherent_assoc_seam("const", &owner, &assoc.ident);
                        out.extend(stamp_seam(dyns_in_type(&assoc.ty), &seam));
                    }
                    syn::ImplItem::Type(assoc) if is_public(&assoc.vis) => {
                        let seam = inherent_assoc_seam("type", &owner, &assoc.ident);
                        out.extend(stamp_seam(dyns_in_type(&assoc.ty), &seam));
                    }
                    _ => {}
                }
            }
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::resolve::{BareFallback, resolve_path};

    // Resolve every exposure path a public item produces, via the same segment-ident resolver the
    // query uses (`BareFallback::Ignore`), so a test can assert whether a forbidden `crate::…` type
    // is observed by the collector.
    fn resolved(item_src: &str, module: &str) -> Vec<String> {
        let item: syn::Item = syn::parse_str(item_src).unwrap();
        let uses = UseMap::new();
        let mut out = Vec::new();
        collect_item_exposures(&item, module, &uses, 0, &mut out);
        out.iter()
            .filter_map(|e| resolve_path(&e.path, &uses, module, BareFallback::Ignore))
            .collect()
    }

    fn exposes(item_src: &str, needle: &str) -> bool {
        resolved(item_src, "crate::domain")
            .iter()
            .any(|p| p == needle)
    }

    #[test]
    fn an_inherent_impl_public_assoc_const_and_type_are_observed() {
        // FN closed: a forbidden type in a public inherent-impl associated `const`'s type or
        // `type` alias's target is now observed (was skipped — only methods were).
        assert!(
            exposes(
                "impl Foo { pub const K: crate::infra::Secret = todo!(); }",
                "crate::infra::Secret"
            ),
            "an inherent-impl pub const's type must expose crate::infra::Secret"
        );
        assert!(
            exposes(
                "impl Foo { pub type T = crate::infra::Secret; }",
                "crate::infra::Secret"
            ),
            "an inherent-impl pub type's target must expose crate::infra::Secret"
        );
    }

    #[test]
    fn a_non_public_inherent_assoc_item_is_not_exposed_but_a_pub_method_still_is() {
        // Only `pub` inherent assoc items are exposed; a private const/type is internal.
        assert!(
            !resolved(
                "impl Foo { const K: crate::infra::Secret = todo!(); type T = crate::infra::Secret; }",
                "crate::domain"
            )
            .iter()
            .any(|p| p.contains("crate::infra")),
            "a non-pub inherent assoc const/type must not be exposed"
        );
        // A public method's signature is still observed (the arm is unchanged).
        assert!(
            exposes(
                "impl Foo { pub fn make() -> crate::infra::Secret { todo!() } }",
                "crate::infra::Secret"
            ),
            "a pub inherent method signature is still observed"
        );
    }

    #[test]
    fn a_supertrait_generic_argument_is_observed() {
        // Control: a struct field's generic arg was already observed.
        assert!(
            exposes(
                "pub struct S { pub f: Vec<crate::infra::Secret> }",
                "crate::infra::Secret"
            ),
            "control: a field generic arg must expose crate::infra::Secret"
        );
        // The fix: a supertrait bound's generic arg is now observed too (was silently dropped).
        assert!(
            exposes(
                "pub trait Facade: AsRef<crate::infra::Secret> {}",
                "crate::infra::Secret"
            ),
            "a supertrait bound's generic arg must expose crate::infra::Secret"
        );
    }

    #[test]
    fn an_assoc_type_bound_gat_param_and_default_are_observed() {
        assert!(
            exposes(
                "pub trait F { type Bar: Into<crate::infra::Secret>; }",
                "crate::infra::Secret"
            ),
            "an associated-type bound's generic arg must be observed"
        );
        assert!(
            exposes(
                "pub trait F { type Gat<T: crate::infra::Marker>; }",
                "crate::infra::Marker"
            ),
            "a GAT generic-parameter bound must be observed"
        );
        assert!(
            exposes(
                "pub trait F { type Bar = crate::infra::Secret; }",
                "crate::infra::Secret"
            ),
            "an associated-type default target must be observed"
        );
    }

    #[test]
    fn a_forbidden_supertrait_head_still_reacts_and_a_std_bound_does_not() {
        // No regression: a forbidden supertrait *head itself* is still observed.
        assert!(
            exposes(
                "pub trait Facade: crate::infra::SecretTrait {}",
                "crate::infra::SecretTrait"
            ),
            "a forbidden supertrait head must still react"
        );
        // An escape-free / std bound exposes no crate::infra.
        assert!(
            !resolved("pub trait Facade: Send + Sync {}", "crate::domain")
                .iter()
                .any(|p| p.contains("crate::infra")),
            "a std supertrait must not expose crate::infra"
        );
    }
}