hunyi 0.1.9

渾儀 (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
//! The crate-wide scan — one fresh whole-crate traversal from the root, descending every
//! file-based and inline module, that collects the `pub use` re-export closure, the resolvable
//! type-alias map, crate-root `extern crate … as` renames, the locally-defined trait paths,
//! every trait-impl site, and every type definition (with its `#[derive]`s). The reaction hearts
//! read the resulting [`CrateScan`]; this is distinct from the single-path descent in
//! `module_resolve` (which does not fit a "nowhere except here" property), reusing only the leaf
//! primitives and the shared resolver.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use syn::parse::Parser;
use syn::visit::{self, Visit};

use crate::crate_scope::{child_module_names, local_type_namespace_names};
use crate::errors::missing_module_file_error;
use crate::module_resolve::{locate_module_file, read_parse, resolve_module_root};
use crate::resolve::{
    AliasMap, BareFallback, ExternRenameMap, ReexportMap, UseMap, alias_nominal_target,
    bare_single_segment_ident, collect_reexports, collect_uses, extern_verbatim_renamed,
    resolve_path, strip_raw, type_to_string,
};
use crate::syn_util::has_path_attr;

/// One impl site observed in the crate: its enclosing module path, the written trait
/// path, the implemented-for type, and that module's `use`-map (for resolution).
pub(crate) struct ImplSite {
    pub(crate) module: String,
    pub(crate) trait_path: syn::Path,
    pub(crate) self_ty: syn::Type,
    pub(crate) uses: UseMap,
}

/// One type definition observed in the crate: its canonical path (`module::Name`), the module
/// it is defined in (for a forbidden-`derive` finding's source file), the paths in its
/// `#[derive(...)]`/`#[cfg_attr(_, derive(...))]`, and that module's `use`-map (so a renamed
/// derive macro, `use serde::Serialize as Ser; #[derive(Ser)]`, resolves to its true leaf).
pub(crate) struct TypeDef {
    pub(crate) canonical: String,
    pub(crate) module: String,
    pub(crate) derives: Vec<syn::Path>,
    pub(crate) uses: UseMap,
}

/// One crate-wide scan: the `pub use` re-export closure, the set of locally-defined trait
/// paths (for anchor verification), every trait-impl site, and every type definition.
pub(crate) struct CrateScan {
    pub(crate) reexports: ReexportMap,
    pub(crate) aliases: AliasMap,
    pub(crate) extern_renames: ExternRenameMap,
    pub(crate) trait_defs: HashSet<String>,
    pub(crate) impls: Vec<ImplSite>,
    pub(crate) type_defs: Vec<TypeDef>,
    /// For each non-generic `type X = <path>;` whose target is a nominal path, the alias's canonical
    /// key (`{module}::X`) mapped to the **landing type** its target resolves to under the same
    /// bare-head `CurrentModule` fallback the impl-self check uses (`type Bar = Real` in `crate::dom`
    /// → `crate::dom::Real`; `type Baz = Vec<u8>` / `= String` → `crate::dom::Vec` / `crate::dom::String`,
    /// neither crate-defined). A `type` alias defines no new type — coherence sees through it — so a
    /// marker impl'd on `Bar` governs a subtree type IFF this landing type is itself a crate-defined
    /// subtree type. The forbidden-marker check consults this to react on `type Bar = Real` while NOT
    /// firing on an alias to a foreign/prelude type (whose marker lands off the governed subtree).
    /// (This is distinct from `aliases`, the exposure closure's resolvable-target map, which does not
    /// record a bare-local-struct target.)
    pub(crate) alias_targets: HashMap<String, String>,
}

/// Collect crate-root `extern crate X as Y;` renames (`Y → X`) into `out`. Crate-root only: such a
/// rename binds `Y` crate-wide via the extern prelude, whereas a module-scoped `extern crate … as`
/// binds only locally (collecting it crate-wide would false-positive on a same-named head elsewhere
/// — a stated bound). `as _` / `X == Y` / `extern crate self as …` are no-ops.
fn collect_crate_root_extern_renames(items: &[syn::Item], out: &mut ExternRenameMap) {
    for item in items {
        if let syn::Item::ExternCrate(ec) = item {
            if let Some((_, rename)) = &ec.rename {
                let alias = strip_raw(&rename.to_string());
                let real = strip_raw(&ec.ident.to_string());
                if alias != "_" && alias != real && real != "self" {
                    out.insert(alias, real);
                }
            }
        }
    }
}

/// A bare single-segment alias target (`type X = Inner`) whose ident names a non-generic type
/// alias in the *current* module resolves to that alias's canonical key `{module}::{ident}`, so the
/// query fixpoint can follow a bare alias-of-an-alias chain (order-independent). `None` for a
/// leading-`::` / multi-segment / generic-argument-bearing path, or a name that is not a local
/// alias — leaving a bare non-alias target (a local struct, a std prelude type like `String`)
/// unresolved, matching the exposure query's `Ignore` policy for a bare non-alias head (no
/// mis-record, so no false positive even under a boundary forbidding the module's own path).
fn bare_local_alias_target(
    target: &syn::Path,
    module: &str,
    local_alias_names: &HashSet<String>,
) -> Option<String> {
    bare_single_segment_ident(target)
        .filter(|name| local_alias_names.contains(name))
        .map(|name| format!("{module}::{name}"))
}

/// Walk the whole crate from its root, descending every file-based and inline module,
/// collecting re-exports, trait definitions, and trait-impl sites. This is a fresh
/// whole-crate traversal (the single-path `descend` does not fit a "nowhere except
/// here" property); it reuses only the leaf primitives and the shared resolver.
pub(crate) fn scan_crate(
    src_dir: &Path,
    root_file: &Path,
    crate_package: &str,
    externs: &HashSet<String>,
) -> Result<CrateScan, String> {
    let root = read_parse(root_file)?;
    let mut scan = CrateScan {
        reexports: ReexportMap::new(),
        aliases: AliasMap::new(),
        extern_renames: ExternRenameMap::new(),
        trait_defs: HashSet::new(),
        impls: Vec::new(),
        type_defs: Vec::new(),
        alias_targets: HashMap::new(),
    };
    // Pre-collect crate-root `extern crate X as Y;` renames BEFORE the walk, so the rename map is
    // complete before any alias-target or re-export-closure resolution — every source-order
    // (forward-reference) hazard is eliminated (an alias or re-export preceding the `extern crate`
    // in root source order still resolves). Renames are crate-root-only (they bind crate-wide via
    // the extern prelude; a module-scoped one is a stated bound), so one root scan suffices.
    collect_crate_root_extern_renames(&root.items, &mut scan.extern_renames);
    // Every source file read during the walk, by its canonicalized (symlink-resolved) path. A
    // file-backed `mod x;` is located through the live filesystem, which follows symlinks, so a
    // cyclic symlinked module directory (`src/foo/foo -> src/foo`) would otherwise recurse forever
    // and stack-overflow (SIGABRT) — neither exit 0/1 nor the contract's exit 2. Re-reaching an
    // already-visited canonical file is that cycle: "cannot judge" (exit 2), never a crash. The
    // louke probe scanner guards the same hazard; the two dimensions keep parallel copies (三儀 ⊥
    // 三儀). Seeded with the crate root so a submodule symlinking back to it is caught too.
    let mut visited: HashSet<PathBuf> = HashSet::new();
    visited.insert(canonicalize_source(root_file)?);
    walk_module(
        root.items,
        "crate".to_string(),
        src_dir.to_path_buf(),
        crate_package,
        externs,
        &mut visited,
        &mut scan,
    )?;
    Ok(scan)
}

/// Canonicalize a source file path (resolving symlinks) for the visited-set cycle guard; an
/// unresolvable path is a scan error ("cannot judge"), never a silent skip.
fn canonicalize_source(file: &Path) -> Result<PathBuf, String> {
    std::fs::canonicalize(file).map_err(|err| {
        format!(
            "cannot canonicalize source file '{}': {err}",
            file.display()
        )
    })
}

/// Resolve a module's direct child `mod` declarations to the `(items, module path, child dir)` each
/// subtree walk recurses into — the single copy of the descent skeleton and its false-negative-
/// critical guards, shared by [`walk_module`], [`collect_subtree`] (`walk_subtree_modules`), and
/// [`walk_unsafe`] (`scan_unsafe_sites`) so a fix to one guard cannot silently diverge across the
/// three (the twin-drift bug class). Owns: the `#[path]` remap skip (a stated coverage bound, incl.
/// the `cfg_attr`-wrapped spelling), the inline-vs-file dispatch, the symlink module-cycle guard (a
/// re-reached canonical file is exit 2, never a stack overflow), and the `#[cfg]`-tolerance /
/// non-cfg-missing-file guard (exit 2).
///
/// Children are returned in source order; each caller does its own per-module work, then recurses
/// over them. All direct children are resolved before the caller recurses; since `visited` is
/// monotonic over the module tree, the same files are reached in the same order and a re-reach is
/// exit 2 regardless. An inline module's body is cloned (callers borrow their items).
fn resolve_child_modules(
    items: &[syn::Item],
    module: &str,
    child_dir: &Path,
    crate_package: &str,
    visited: &mut HashSet<PathBuf>,
) -> Result<Vec<(Vec<syn::Item>, String, PathBuf)>, String> {
    let mut children = Vec::new();
    for item in items {
        let syn::Item::Mod(module_item) = item else {
            continue;
        };
        // A `#[path]`-remapped module is located off the conventional path; not observed (a stated
        // coverage bound, incl. the `cfg_attr`-wrapped spelling), never a silent claim of cleanliness.
        if has_path_attr(&module_item.attrs) {
            continue;
        }
        let name = strip_raw(&module_item.ident.to_string());
        let child_module = format!("{module}::{name}");
        let sub_dir = child_dir.join(&name);
        match &module_item.content {
            // Inline `mod x { … }`: descend its lexical items; file-children under `x/`.
            Some((_, inner)) => children.push((inner.clone(), child_module, sub_dir)),
            // File `mod x;`: `<dir>/x.rs` or `<dir>/x/mod.rs`; children under `x/`.
            None => match locate_module_file(child_dir, &name) {
                Some(file) => {
                    // A file already visited (by canonical, symlink-resolved path) is a module cycle
                    // — a symlinked directory looping the `mod` graph back on itself. Stop with a
                    // scan error (exit 2 "cannot judge") rather than recursing into a stack overflow.
                    if !visited.insert(canonicalize_source(&file)?) {
                        return Err(format!(
                            "cannot judge module '{child_module}' in package '{crate_package}': \
                             its source file '{}' forms a module cycle (a symlink loop)",
                            file.display()
                        ));
                    }
                    let parsed = read_parse(&file)?;
                    children.push((parsed.items, child_module, sub_dir));
                }
                // A `#[cfg]`-gated module may legitimately have no source file when the feature is
                // off (a standard optional-feature pattern) — a stated coverage bound, not a scan
                // error. A non-cfg missing file is a real scan error: fail loud (exit 2).
                None => {
                    if !has_cfg_attr(&module_item.attrs) {
                        return Err(missing_module_file_error(&child_module, crate_package));
                    }
                }
            },
        }
    }
    Ok(children)
}

fn walk_module(
    items: Vec<syn::Item>,
    module: String,
    child_dir: PathBuf,
    crate_package: &str,
    externs: &HashSet<String>,
    visited: &mut HashSet<PathBuf>,
    scan: &mut CrateScan,
) -> Result<(), String> {
    let uses = collect_uses(&items);
    // The re-export closure applies the same per-defining-module child-module shadow the direct
    // head oracle does: a bare `pub use dep::X;` / `pub use wc::X;` head named by this module's own
    // child `mod dep` / `mod wc` is not recorded as the dependency / renamed crate, so a
    // cross-module facade reaching it through this crate-wide map does not mis-canonicalize (the
    // facade-closure FP). `collect_reexports` keeps a leading-`::` head on the raw sets.
    let child_mods = child_module_names(&items);
    collect_reexports(
        &items,
        &module,
        externs,
        &child_mods,
        &scan.extern_renames,
        &mut scan.reexports,
    );
    // Alias targets resolve in the same per-module shadow as type positions: a bare head naming
    // a local child module (`mod serde` + `type X = serde::Foo`) is local, not the dependency.
    let externs_type: HashSet<String> = externs
        .difference(&local_type_namespace_names(&items))
        .cloned()
        .collect();
    // This module's own non-generic type-alias names — the only bare single-segment targets the
    // alias-collection ladder resolves against the current module (a bare intermediate in an
    // alias-of-an-alias chain, always same-module). Gating to these names keeps a bare non-alias
    // target (a local struct, or a std prelude type like `String`) from being mis-recorded as
    // `{module}::{name}` — which would false-positive under a boundary forbidding the module's own
    // path. Computed once here so the check is order-independent within the module.
    let local_alias_names: HashSet<String> = items
        .iter()
        .filter_map(|it| match it {
            syn::Item::Type(t) if t.generics.params.is_empty() => {
                Some(strip_raw(&t.ident.to_string()))
            }
            _ => None,
        })
        .collect();

    for item in &items {
        match item {
            syn::Item::Trait(trait_item) => {
                scan.trait_defs.insert(format!(
                    "{module}::{}",
                    strip_raw(&trait_item.ident.to_string())
                ));
            }
            // Trait impls only (`impl Trait for Type`); inherent impls carry no `trait_`.
            syn::Item::Impl(impl_item) if impl_item.trait_.is_some() => {
                let (_, trait_path, _) = impl_item.trait_.as_ref().expect("trait_ is Some");
                scan.impls.push(ImplSite {
                    module: module.clone(),
                    trait_path: trait_path.clone(),
                    self_ty: (*impl_item.self_ty).clone(),
                    uses: uses.clone(),
                });
            }
            syn::Item::Struct(i) => {
                push_type_def(&i.attrs, &i.ident, &module, &uses, scan)?;
            }
            syn::Item::Enum(i) => {
                push_type_def(&i.attrs, &i.ident, &module, &uses, scan)?;
            }
            syn::Item::Union(i) => {
                push_type_def(&i.attrs, &i.ident, &module, &uses, scan)?;
            }
            // A non-generic `type X = <nominal path>;` alias: record `{module}::X → target`
            // so the exposure pipeline can follow it to the defining path. The target-resolution
            // ladder is byte-identical to the query site's, so no resolvable target is dropped and
            // no local shadow is misread:
            //   0. a leading-`::` target — an unambiguous extern (raw set, with the crate-root
            //      rename applied), a HARD short-circuit, so `type X = ::serde::Value;` records the
            //      extern even under a local `mod serde`, and `type X = ::<rename>::Foo;` too;
            //   1. `resolve_path(Ignore)` — use-map / `crate`·`self`·`super`;
            //   2. `bare_local_alias_target` — a bare single-segment target naming one of THIS
            //      module's own type aliases recorded as `{module}::{name}` (its canonical alias-map
            //      key), tried BEFORE the extern oracle so a local alias shadows a same-named
            //      dependency (rustc's own resolution); the query-time `canonicalize_through_aliases`
            //      fixpoint then closes a *bare* alias-of-an-alias chain regardless of source order.
            //      Gated to local alias names, so a bare non-alias target (a local struct, a std
            //      prelude type like `String`) is never mis-recorded — no false positive;
            //   3. `extern_verbatim_renamed` — an extern head, incl. a crate-root `extern crate as`
            //      rename (the rename map is pre-collected, so this is order-independent).
            // A generic alias (`type X<T> = …`) or a complex target (`Vec<T>`, `&T`, a
            // tuple/`dyn`/`impl`) is skipped — a stated coverage bound, never a silent claim.
            syn::Item::Type(type_item) if type_item.generics.params.is_empty() => {
                // Record the alias's LANDING type — where its target resolves under the same bare-head
                // `CurrentModule` fallback the impl-self check uses — so the forbidden-marker check can
                // react on an alias to a crate-defined subtree type (`type Bar = Real`) yet stay silent
                // on one to a foreign/prelude type (`type Baz = Vec<u8>` / `= String`), whose marker
                // lands off the governed subtree. Only a nominal `Type::Path` target has a single
                // landing type; a tuple/ref/`dyn` target has none and is skipped (never governed here).
                if let syn::Type::Path(tp) = &*type_item.ty {
                    if let Some(landing) =
                        resolve_path(&tp.path, &uses, &module, BareFallback::CurrentModule)
                    {
                        let alias =
                            format!("{module}::{}", strip_raw(&type_item.ident.to_string()));
                        scan.alias_targets.insert(alias, landing);
                    }
                }
                if let Some(target) = alias_nominal_target(&type_item.ty) {
                    let alias = format!("{module}::{}", strip_raw(&type_item.ident.to_string()));
                    let resolved = if target.leading_colon.is_some() {
                        extern_verbatim_renamed(target, externs, &scan.extern_renames)
                    } else {
                        resolve_path(target, &uses, &module, BareFallback::Ignore)
                            .or_else(|| {
                                bare_local_alias_target(target, &module, &local_alias_names)
                            })
                            .or_else(|| {
                                extern_verbatim_renamed(target, &externs_type, &scan.extern_renames)
                            })
                    };
                    if let Some(resolved) = resolved {
                        if resolved != alias {
                            scan.aliases.insert(alias, resolved);
                        }
                    }
                }
            }
            _ => {}
        }
    }

    for (child_items, child_module, sub_dir) in
        resolve_child_modules(&items, &module, &child_dir, crate_package, visited)?
    {
        walk_module(
            child_items,
            child_module,
            sub_dir,
            crate_package,
            externs,
            visited,
            scan,
        )?;
    }
    Ok(())
}

/// Walk the anchored module's whole subtree — the module itself and every descendant (file-based
/// `mod x;` and inline `mod x { … }` alike) — returning each module's path and the items it owns.
/// The subtree analogue of [`crate::module_resolve::resolve_module_items`]: where that returns one
/// module's items, this returns every module at or below the anchor, so a reaction can observe a
/// "nowhere under here" property (e.g. no public `async fn` anywhere beneath a sans-I/O kernel).
///
/// Inherits the crate walk's guards, so a subtree reaction never silently under-reacts: a
/// `#[path]`-remapped module is skipped (a stated coverage bound), a `#[cfg]`-gated fileless module
/// is tolerated, a non-`#[cfg]` missing module file is a scan error (exit 2), and a symlink module
/// cycle is a scan error (exit 2), never a stack overflow.
pub(crate) fn walk_subtree_modules(
    src_dir: &Path,
    root_file: &Path,
    module: &str,
    crate_package: &str,
) -> Result<Vec<(String, Vec<syn::Item>)>, String> {
    let (items, file, child_dir) = resolve_module_root(src_dir, root_file, module, crate_package)?;
    // Seed the cycle guard with the anchor module's own file, so a descendant symlinking back to it
    // is caught — the same discipline `scan_crate` applies from the crate root.
    let mut visited: HashSet<PathBuf> = HashSet::new();
    visited.insert(canonicalize_source(&file)?);
    let mut out: Vec<(String, Vec<syn::Item>)> = Vec::new();
    collect_subtree(
        items,
        module.to_string(),
        child_dir,
        crate_package,
        &mut visited,
        &mut out,
    )?;
    Ok(out)
}

/// Recurse the subtree from one module: descend each child `mod` (mirroring [`walk_module`]'s
/// descent and its guards), then record this module's own `(path, items)`. The order of `out` is
/// unspecified — a subtree reaction sorts its findings — so recording after descent is fine.
fn collect_subtree(
    items: Vec<syn::Item>,
    module: String,
    child_dir: PathBuf,
    crate_package: &str,
    visited: &mut HashSet<PathBuf>,
    out: &mut Vec<(String, Vec<syn::Item>)>,
) -> Result<(), String> {
    for (child_items, child_module, sub_dir) in
        resolve_child_modules(&items, &module, &child_dir, crate_package, visited)?
    {
        collect_subtree(
            child_items,
            child_module,
            sub_dir,
            crate_package,
            visited,
            out,
        )?;
    }
    out.push((module, items));
    Ok(())
}

/// Record a type definition with its derive paths into the scan.
fn push_type_def(
    attrs: &[syn::Attribute],
    ident: &syn::Ident,
    module: &str,
    uses: &UseMap,
    scan: &mut CrateScan,
) -> Result<(), String> {
    let name = strip_raw(&ident.to_string());
    let derives = extract_derives(attrs)?;
    scan.type_defs.push(TypeDef {
        canonical: format!("{module}::{name}"),
        module: module.to_string(),
        derives,
        uses: uses.clone(),
    });
    Ok(())
}

/// Extract the derive paths from a type's `#[derive(...)]` and `#[cfg_attr(_, derive(...))]`
/// attributes (the latter read cfg-agnostically). A `derive` whose arguments fail to parse is
/// a scan error (exit 2) — "cannot judge" is never a silent skip.
fn extract_derives(attrs: &[syn::Attribute]) -> Result<Vec<syn::Path>, String> {
    let mut out = Vec::new();
    for attr in attrs {
        if attr.path().is_ident("derive") {
            out.extend(parse_derive_paths(&attr.meta)?);
        } else if attr.path().is_ident("cfg_attr") {
            let metas = attr
                .parse_args_with(meta_list_parser())
                .map_err(|e| format!("cannot parse #[cfg_attr(...)]: {e}"))?;
            extract_derives_from_cfg_metas(&metas, &mut out)?;
        }
    }
    Ok(out)
}

fn meta_list_parser() -> impl Parser<Output = syn::punctuated::Punctuated<syn::Meta, syn::Token![,]>>
{
    syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated
}

/// Parse the comma-separated paths of a `derive(...)` meta-list (empty `#[derive]`/non-list
/// yields none).
fn parse_derive_paths(meta: &syn::Meta) -> Result<Vec<syn::Path>, String> {
    let parser = syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated;
    match meta {
        syn::Meta::List(list) => Ok(list
            .parse_args_with(parser)
            .map_err(|e| format!("cannot parse derive(...): {e}"))?
            .into_iter()
            .collect()),
        _ => Ok(Vec::new()),
    }
}

/// Extract derives from a `cfg_attr`'s metas: the first is the cfg predicate (skipped); the
/// rest are conditionally-applied attributes — a `derive(...)`, or a **nested** `cfg_attr(...)`
/// recursed into (so `#[cfg_attr(a, cfg_attr(b, derive(X)))]` still yields `X`).
fn extract_derives_from_cfg_metas(
    metas: &syn::punctuated::Punctuated<syn::Meta, syn::Token![,]>,
    out: &mut Vec<syn::Path>,
) -> Result<(), String> {
    for meta in metas.iter().skip(1) {
        if let syn::Meta::List(list) = meta {
            if list.path.is_ident("derive") {
                out.extend(parse_derive_paths(meta)?);
            } else if list.path.is_ident("cfg_attr") {
                let inner = list
                    .parse_args_with(meta_list_parser())
                    .map_err(|e| format!("cannot parse nested #[cfg_attr(...)]: {e}"))?;
                extract_derives_from_cfg_metas(&inner, out)?;
            }
        }
    }
    Ok(())
}

fn has_cfg_attr(attrs: &[syn::Attribute]) -> bool {
    attrs.iter().any(|attr| attr.path().is_ident("cfg"))
}

// --- Unsafe-site scan (`semantic-unsafe-confinement`) -------------------------

/// One `unsafe` site observed in the crate: its enclosing (file) module and a stable label
/// (`unsafe block`, `unsafe fn decode`, `unsafe impl Send`, `unsafe trait Zeroable`,
/// `unsafe extern block`). The label is module-qualified at the finding layer for injectivity.
pub(crate) struct UnsafeSite {
    pub(crate) module: String,
    pub(crate) label: String,
}

/// A `syn::visit::Visit` collector recording every executable-`unsafe` **code site** within the
/// items it is fed: `unsafe fn` (free / inherent / trait-decl / trait-impl method), `unsafe impl`,
/// `unsafe trait`, `unsafe extern` block, and `unsafe {}` expression block (deep in bodies). It is
/// fed a module's items **minus top-level `mod`s** (the walk owns their descent); `visit_item_mod`
/// is left at its **default (recursing)** so a `mod` declared *inside a fn/block body* — which the
/// top-level walk never reaches — is still observed, attributed to the enclosing file module.
#[derive(Default)]
struct UnsafeSiteCollector {
    labels: Vec<String>,
    // Positional discriminator for a self type `type_to_string` cannot render (`_#n`), so two such
    // `unsafe impl`s in one module stay distinct findings rather than masking each other.
    unsafe_impl_ordinal: usize,
}

/// Render a trait path for an `unsafe impl` label — segment idents joined by `::` (raw-stripped),
/// enough to keep two `unsafe impl`s of different traits distinct. No `quote`.
fn render_trait_path(path: &syn::Path) -> String {
    let lead = if path.leading_colon.is_some() {
        "::"
    } else {
        ""
    };
    let segs: Vec<String> = path
        .segments
        .iter()
        .map(|s| strip_raw(&s.ident.to_string()))
        .collect();
    format!("{lead}{}", segs.join("::"))
}

impl<'ast> Visit<'ast> for UnsafeSiteCollector {
    fn visit_expr_unsafe(&mut self, node: &'ast syn::ExprUnsafe) {
        self.labels.push("unsafe block".to_string());
        visit::visit_expr_unsafe(self, node);
    }

    fn visit_item_fn(&mut self, node: &'ast syn::ItemFn) {
        if node.sig.unsafety.is_some() {
            self.labels.push(format!(
                "unsafe fn {}",
                strip_raw(&node.sig.ident.to_string())
            ));
        }
        visit::visit_item_fn(self, node);
    }

    fn visit_impl_item_fn(&mut self, node: &'ast syn::ImplItemFn) {
        if node.sig.unsafety.is_some() {
            self.labels.push(format!(
                "unsafe fn {}",
                strip_raw(&node.sig.ident.to_string())
            ));
        }
        visit::visit_impl_item_fn(self, node);
    }

    fn visit_trait_item_fn(&mut self, node: &'ast syn::TraitItemFn) {
        if node.sig.unsafety.is_some() {
            self.labels.push(format!(
                "unsafe fn {}",
                strip_raw(&node.sig.ident.to_string())
            ));
        }
        visit::visit_trait_item_fn(self, node);
    }

    fn visit_item_impl(&mut self, node: &'ast syn::ItemImpl) {
        if node.unsafety.is_some() {
            // Owner-qualify by the implemented-for type so `unsafe impl Send for Foo` and
            // `unsafe impl Send for Bar` in one module stay distinct findings — else a baseline of
            // the first silently masks the second (a false negative). Lexical (`type_to_string`, no
            // resolution — this is the light walk), mirroring the trait-path rendering above.
            let owner = type_to_string(&node.self_ty)
                .unwrap_or_else(|| format!("_#{}", self.unsafe_impl_ordinal));
            self.unsafe_impl_ordinal += 1;
            let label = match &node.trait_ {
                Some((_, path, _)) => {
                    format!("unsafe impl {} for {}", render_trait_path(path), owner)
                }
                None => format!("unsafe impl {owner}"),
            };
            self.labels.push(label);
        }
        visit::visit_item_impl(self, node);
    }

    fn visit_item_trait(&mut self, node: &'ast syn::ItemTrait) {
        if node.unsafety.is_some() {
            self.labels.push(format!(
                "unsafe trait {}",
                strip_raw(&node.ident.to_string())
            ));
        }
        visit::visit_item_trait(self, node);
    }

    fn visit_item_foreign_mod(&mut self, node: &'ast syn::ItemForeignMod) {
        if node.unsafety.is_some() {
            self.labels.push("unsafe extern block".to_string());
        }
        visit::visit_item_foreign_mod(self, node);
    }
}

/// Walk the whole crate from its root and collect every `unsafe` site with its enclosing module.
/// Mirrors [`scan_crate`]'s descent (file + inline modules, symlink-cycle guard → exit 2, `#[path]`
/// skipped as a stated bound, a non-`#[cfg]` missing module file → exit 2, a cfg-gated missing file
/// tolerated). A separate, lighter walk than `scan_crate` (no re-export/alias/type-def resolution).
pub(crate) fn scan_unsafe_sites(
    src_dir: &Path,
    root_file: &Path,
    crate_package: &str,
) -> Result<Vec<UnsafeSite>, String> {
    let root = read_parse(root_file)?;
    let mut sites = Vec::new();
    let mut visited: HashSet<PathBuf> = HashSet::new();
    visited.insert(canonicalize_source(root_file)?);
    walk_unsafe(
        root.items,
        "crate".to_string(),
        src_dir.to_path_buf(),
        crate_package,
        &mut visited,
        &mut sites,
    )?;
    Ok(sites)
}

fn walk_unsafe(
    items: Vec<syn::Item>,
    module: String,
    child_dir: PathBuf,
    crate_package: &str,
    visited: &mut HashSet<PathBuf>,
    sites: &mut Vec<UnsafeSite>,
) -> Result<(), String> {
    // Feed the collector this module's items minus top-level `mod`s (walk-owned); body-nested
    // `mod`s stay in and are caught by the collector's default `visit_item_mod` recursion.
    let mut collector = UnsafeSiteCollector::default();
    for item in &items {
        if matches!(item, syn::Item::Mod(_)) {
            continue;
        }
        collector.visit_item(item);
    }
    for label in collector.labels {
        sites.push(UnsafeSite {
            module: module.clone(),
            label,
        });
    }

    for (child_items, child_module, sub_dir) in
        resolve_child_modules(&items, &module, &child_dir, crate_package, visited)?
    {
        walk_unsafe(
            child_items,
            child_module,
            sub_dir,
            crate_package,
            visited,
            sites,
        )?;
    }
    Ok(())
}