marcellus 0.1.0

Fail-closed source-capability inventory gate over a Rust module tree
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
//! Fail-closed source-capability gating over a Rust module tree.
//!
//! `rustc` grants access to a private field to the defining module tree
//! alone. This crate makes that privacy cone auditable. It loads a module
//! directory, refuses every construction that could route source into or
//! out of it, exposes the declared struct shape, and reports identifier
//! occurrences at token level, so comments and string literals can neither
//! hide nor fabricate a capability site.
//!
//! The crate is generic machinery. It knows nothing about any particular
//! library; a caller names the module directory, the struct, and the
//! representation identifier, and holds its own classified manifest.
//!
//! The checks cover source text as parsed, not macro expansion or `cfg`
//! resolution. Item-position macro invocations and `include`-family
//! identifiers are therefore refused outright rather than resolved.

use std::collections::BTreeMap;
use std::fs;
use std::path::Path;

use proc_macro2::{TokenStream, TokenTree};

pub use syn;

/// One parsed file of a module tree.
pub struct ModuleFile {
    /// File name inside the module directory, for example `lattice.rs`.
    pub name: String,
    /// Complete source text.
    pub source: String,
    /// Parsed syntax tree.
    pub ast: syn::File,
}

/// A loaded module tree: `mod.rs` first, then every declared file
/// submodule in declaration order.
pub struct ModuleTree {
    /// Every file of the tree.
    pub files: Vec<ModuleFile>,
}

/// The module-shape findings for one file's items.
pub struct ModuleAudit {
    /// File submodules the items declare.
    pub declared: Vec<String>,
    /// Every refused construction, with its reason.
    pub violations: Vec<String>,
}

/// Attributes a module declaration may carry. `#[path]` moves source
/// outside the directory and `cfg_attr` can smuggle it, so neither is
/// admitted; every unknown attribute is refused rather than ignored.
fn module_attribute_violation(attribute: &syn::Attribute) -> Option<String> {
    let path = attribute.path();
    if path.is_ident("cfg") || path.is_ident("doc") || path.is_ident("allow") {
        return None;
    }
    Some(format!(
        "module declaration carries a refused attribute: {}",
        path.segments
            .iter()
            .map(|segment| segment.ident.to_string())
            .collect::<Vec<_>>()
            .join("::")
    ))
}

fn audit_items(items: &[syn::Item], root: bool, audit: &mut ModuleAudit) {
    for item in items {
        match item {
            syn::Item::Mod(module) => {
                for attribute in &module.attrs {
                    if let Some(violation) = module_attribute_violation(attribute) {
                        audit
                            .violations
                            .push(format!("mod {}: {violation}", module.ident));
                    }
                }
                match &module.content {
                    None if root => audit.declared.push(module.ident.to_string()),
                    None => audit.violations.push(format!(
                        "mod {}: file submodule below the root widens the tree",
                        module.ident
                    )),
                    Some((_, inner)) => audit_items(inner, false, audit),
                }
            }
            syn::Item::Macro(invocation) => audit.violations.push(format!(
                "item-position macro invocation is refused: {}",
                invocation
                    .mac
                    .path
                    .segments
                    .iter()
                    .map(|segment| segment.ident.to_string())
                    .collect::<Vec<_>>()
                    .join("::")
            )),
            syn::Item::Impl(implementation) => {
                for member in &implementation.items {
                    if matches!(member, syn::ImplItem::Macro(_)) {
                        audit
                            .violations
                            .push("impl-position macro invocation is refused".to_string());
                    }
                }
            }
            syn::Item::Trait(definition) => {
                for member in &definition.items {
                    if matches!(member, syn::TraitItem::Macro(_)) {
                        audit
                            .violations
                            .push("trait-position macro invocation is refused".to_string());
                    }
                }
            }
            _ => {}
        }
    }
}

/// Audits one file's items: declared file submodules and refused
/// constructions. Only the root file may declare file submodules.
#[must_use]
pub fn audit_module_items(ast: &syn::File, root: bool) -> ModuleAudit {
    let mut audit = ModuleAudit {
        declared: Vec::new(),
        violations: Vec::new(),
    };
    audit_items(&ast.items, root, &mut audit);
    audit
}

/// A path the gate reads must be a plain file or directory; a symlink can
/// route source outside the audited tree.
fn refuse_symlink(path: &Path, violations: &mut Vec<String>) -> bool {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_symlink() => {
            violations.push(format!("{}: symlink escapes the tree", path.display()));
            false
        }
        Ok(_) => true,
        Err(error) => {
            violations.push(format!("{}: {error}", path.display()));
            false
        }
    }
}

fn load_file(dir: &Path, name: &str, violations: &mut Vec<String>) -> Option<ModuleFile> {
    let path = dir.join(name);
    if !refuse_symlink(&path, violations) {
        return None;
    }
    let source = match fs::read_to_string(&path) {
        Ok(source) => source,
        Err(error) => {
            violations.push(format!("{name}: read failed: {error}"));
            return None;
        }
    };
    match syn::parse_file(&source) {
        Ok(ast) => Some(ModuleFile {
            name: name.to_string(),
            source,
            ast,
        }),
        Err(error) => {
            violations.push(format!("{name}: parse failed: {error}"));
            None
        }
    }
}

/// Loads `mod.rs` and every file submodule it declares, closing the tree.
///
/// Every declared file must exist, every `.rs` file must be declared, and
/// subdirectories are refused. Every violation is reported; an empty
/// violation list is the only success.
///
/// # Errors
///
/// Returns every violation found instead of a tree.
pub fn load_module_tree(dir: &Path) -> Result<ModuleTree, Vec<String>> {
    let mut violations = Vec::new();
    let mut files = Vec::new();
    let mut declared = Vec::new();

    if !refuse_symlink(dir, &mut violations) {
        return Err(violations);
    }

    if let Some(root) = load_file(dir, "mod.rs", &mut violations) {
        let audit = audit_module_items(&root.ast, true);
        declared = audit.declared;
        violations.extend(audit.violations.into_iter().map(|v| format!("mod.rs: {v}")));
        files.push(root);
    }

    for module in &declared {
        let name = format!("{module}.rs");
        if let Some(file) = load_file(dir, &name, &mut violations) {
            let audit = audit_module_items(&file.ast, false);
            violations.extend(audit.violations.into_iter().map(|v| format!("{name}: {v}")));
            files.push(file);
        }
    }

    match fs::read_dir(dir) {
        Ok(entries) => {
            for entry in entries {
                let entry = match entry {
                    Ok(entry) => entry,
                    Err(error) => {
                        violations.push(format!("module directory entry: {error}"));
                        continue;
                    }
                };
                let name = entry.file_name().to_string_lossy().into_owned();
                if !refuse_symlink(&entry.path(), &mut violations) {
                    continue;
                }
                if entry.path().is_dir() {
                    violations.push(format!("{name}/: subdirectory widens the tree"));
                } else if !files.iter().any(|file| file.name == name) {
                    violations.push(format!("{name}: undeclared file in the module directory"));
                }
            }
        }
        Err(error) => violations.push(format!("module directory: {error}")),
    }

    if violations.is_empty() {
        Ok(ModuleTree { files })
    } else {
        Err(violations)
    }
}

/// Requires the parent file to bind `name` as one plain file module.
///
/// The compiler's route into the audited directory is then the directory
/// itself: no inline body, no `#[path]`, no `cfg_attr`, no second
/// declaration.
///
/// # Errors
///
/// Returns every violation of that shape.
pub fn file_module_binding(parent: &syn::File, name: &str) -> Result<(), Vec<String>> {
    let mut violations = Vec::new();
    let mut bindings = 0usize;
    for item in &parent.items {
        let syn::Item::Mod(module) = item else {
            continue;
        };
        if module.ident != name {
            continue;
        }
        bindings += 1;
        for attribute in &module.attrs {
            if let Some(violation) = module_attribute_violation(attribute) {
                violations.push(format!("mod {name}: {violation}"));
            }
        }
        if module.content.is_some() {
            violations.push(format!(
                "mod {name}: inline body bypasses the audited directory"
            ));
        }
    }
    if bindings != 1 {
        violations.push(format!(
            "mod {name}: expected exactly one declaration, found {bindings}"
        ));
    }
    if violations.is_empty() {
        Ok(())
    } else {
        Err(violations)
    }
}

/// The named struct's fields. Requires exactly one declaration of that
/// name anywhere in the file, including inline modules.
///
/// # Errors
///
/// Returns a description when the struct is absent or declared twice.
pub fn struct_fields<'ast>(ast: &'ast syn::File, name: &str) -> Result<&'ast syn::Fields, String> {
    fn find<'ast>(items: &'ast [syn::Item], name: &str, found: &mut Vec<&'ast syn::Fields>) {
        for item in items {
            match item {
                syn::Item::Struct(declaration) if declaration.ident == name => {
                    found.push(&declaration.fields);
                }
                syn::Item::Mod(module) => {
                    if let Some((_, inner)) = &module.content {
                        find(inner, name, found);
                    }
                }
                _ => {}
            }
        }
    }
    let mut found = Vec::new();
    find(&ast.items, name, &mut found);
    match found.as_slice() {
        [fields] => Ok(fields),
        [] => Err(format!("struct {name} is not declared")),
        _ => Err(format!("struct {name} is declared more than once")),
    }
}

/// Every macro reachable from a source file, at token level, each entry
/// carrying its complete path spelling and line. Qualified spellings stay
/// qualified, so `evil::assert` can never collapse onto `assert`.
pub struct MacroSurface {
    /// `path!(...)` invocations anywhere, including expression position.
    pub invocations: Vec<(String, usize)>,
    /// `#[path ...]` and `#![path ...]` attributes anywhere.
    pub attributes: Vec<(String, usize)>,
    /// Complete trait paths inside `#[derive(...)]` lists.
    pub derives: Vec<(String, usize)>,
}

fn spelled(ident: &proc_macro2::Ident) -> String {
    let raw = ident.to_string();
    raw.strip_prefix("r#")
        .map_or_else(|| raw.clone(), ToString::to_string)
}

/// Reads `Ident (:: Ident)*` starting at `start`; returns the joined
/// spelling, the first line, and the index past the path.
fn read_path(trees: &[TokenTree], start: usize) -> Option<(String, usize, usize)> {
    let Some(TokenTree::Ident(first)) = trees.get(start) else {
        return None;
    };
    let mut segments = vec![spelled(first)];
    let line = first.span().start().line;
    let mut index = start + 1;
    while let (
        Some(TokenTree::Punct(left)),
        Some(TokenTree::Punct(right)),
        Some(TokenTree::Ident(next)),
    ) = (trees.get(index), trees.get(index + 1), trees.get(index + 2))
    {
        if left.as_char() == ':'
            && right.as_char() == ':'
            && left.spacing() == proc_macro2::Spacing::Joint
        {
            segments.push(spelled(next));
            index += 3;
        } else {
            break;
        }
    }
    Some((segments.join("::"), line, index))
}

fn record_attribute(group: &proc_macro2::Group, surface: &mut MacroSurface) {
    let trees: Vec<TokenTree> = group.stream().into_iter().collect();
    let Some((name, line, next)) = read_path(&trees, 0) else {
        return;
    };
    surface.attributes.push((name.clone(), line));
    if name == "derive"
        && let Some(TokenTree::Group(traits)) = trees.get(next)
    {
        let inner: Vec<TokenTree> = traits.stream().into_iter().collect();
        let mut cursor = 0;
        while cursor < inner.len() {
            if let Some((path, path_line, after)) = read_path(&inner, cursor) {
                surface.derives.push((path, path_line));
                cursor = after;
            } else {
                cursor += 1;
            }
        }
    }
    // Attribute arguments can carry nested invocations; scan them too.
    scan_macro_surface(&trees, surface);
}

fn scan_macro_surface(trees: &[TokenTree], surface: &mut MacroSurface) {
    let mut index = 0;
    while index < trees.len() {
        match &trees[index] {
            TokenTree::Punct(punct) if punct.as_char() == '#' => {
                let mut next = index + 1;
                if let Some(TokenTree::Punct(bang)) = trees.get(next)
                    && bang.as_char() == '!'
                {
                    next += 1;
                }
                if let Some(TokenTree::Group(group)) = trees.get(next)
                    && group.delimiter() == proc_macro2::Delimiter::Bracket
                {
                    record_attribute(group, surface);
                    index = next + 1;
                    continue;
                }
                index += 1;
            }
            TokenTree::Ident(_) => {
                let (path, line, next) =
                    read_path(trees, index).expect("read_path accepts an identifier");
                if let (Some(TokenTree::Punct(bang)), Some(TokenTree::Group(_))) =
                    (trees.get(next), trees.get(next + 1))
                    && bang.as_char() == '!'
                {
                    surface.invocations.push((path, line));
                }
                index = next;
            }
            TokenTree::Group(group) => {
                let inner: Vec<TokenTree> = group.stream().into_iter().collect();
                scan_macro_surface(&inner, surface);
                index += 1;
            }
            TokenTree::Punct(_) | TokenTree::Literal(_) => index += 1,
        }
    }
}

/// Every name a `use` item binds into the file's scope.
///
/// Each entry carries the complete imported path and line; a glob import
/// binds the unknowable and is reported as `*`. Inline modules are
/// traversed. A caller refuses bindings that could shadow an allowlisted
/// macro or derive name.
#[must_use]
pub fn use_bindings(ast: &syn::File) -> Vec<(String, String, usize)> {
    use syn::spanned::Spanned as _;

    fn walk_tree(
        tree: &syn::UseTree,
        prefix: &mut Vec<String>,
        bindings: &mut Vec<(String, String, usize)>,
    ) {
        match tree {
            syn::UseTree::Path(path) => {
                prefix.push(spelled(&path.ident));
                walk_tree(&path.tree, prefix, bindings);
                let _ = prefix.pop();
            }
            syn::UseTree::Name(name) => {
                let mut full = prefix.clone();
                full.push(spelled(&name.ident));
                bindings.push((
                    spelled(&name.ident),
                    full.join("::"),
                    name.ident.span().start().line,
                ));
            }
            syn::UseTree::Rename(rename) => {
                let mut full = prefix.clone();
                full.push(spelled(&rename.ident));
                bindings.push((
                    spelled(&rename.rename),
                    full.join("::"),
                    rename.rename.span().start().line,
                ));
            }
            syn::UseTree::Glob(glob) => {
                let mut full = prefix.clone();
                full.push("*".to_string());
                bindings.push(("*".to_string(), full.join("::"), glob.span().start().line));
            }
            syn::UseTree::Group(group) => {
                for item in &group.items {
                    walk_tree(item, prefix, bindings);
                }
            }
        }
    }

    fn walk_items(items: &[syn::Item], bindings: &mut Vec<(String, String, usize)>) {
        for item in items {
            match item {
                syn::Item::Use(import) => {
                    walk_tree(&import.tree, &mut Vec::new(), bindings);
                }
                syn::Item::ExternCrate(external) => {
                    let bound = external
                        .rename
                        .as_ref()
                        .map_or(&external.ident, |(_, rename)| rename);
                    bindings.push((
                        spelled(bound),
                        spelled(&external.ident),
                        bound.span().start().line,
                    ));
                }
                syn::Item::Mod(module) => {
                    if let Some((_, inner)) = &module.content {
                        walk_items(inner, bindings);
                    }
                }
                _ => {}
            }
        }
    }

    let mut bindings = Vec::new();
    walk_items(&ast.items, &mut bindings);
    bindings
}

/// The number of `use` declarations the item-level walk can see.
///
/// Inline modules are included. A caller compares this against the
/// file's `use`-token count: a surplus token is a block-local import or
/// a precise-capture `use<..>`, both outside the audited binding walk,
/// so both are refused until classified.
#[must_use]
pub fn use_statement_count(ast: &syn::File) -> usize {
    fn walk(items: &[syn::Item]) -> usize {
        items
            .iter()
            .map(|item| match item {
                syn::Item::Use(_) => 1,
                syn::Item::Mod(module) => {
                    module.content.as_ref().map_or(0, |(_, inner)| walk(inner))
                }
                _ => 0,
            })
            .sum()
    }
    walk(&ast.items)
}

/// The complete macro surface of a source file. Every entry is a site
/// where expansion could manufacture source the gate never scans, so a
/// caller admits each name against an explicit allowlist or fails.
///
/// # Errors
///
/// Returns a description when the source does not lex.
pub fn macro_surface(source: &str) -> Result<MacroSurface, String> {
    let stream: TokenStream = source
        .parse()
        .map_err(|error| format!("lex failed: {error}"))?;
    let trees: Vec<TokenTree> = stream.into_iter().collect();
    let mut surface = MacroSurface {
        invocations: Vec::new(),
        attributes: Vec::new(),
        derives: Vec::new(),
    };
    scan_macro_surface(&trees, &mut surface);
    Ok(surface)
}

fn collect_identifier(stream: TokenStream, identifier: &str, lines: &mut Vec<usize>) {
    for tree in stream {
        match tree {
            TokenTree::Ident(ident) => {
                // `r#counters` resolves to the same field as `counters`;
                // normalize the raw spelling before comparing.
                let spelled = ident.to_string();
                if spelled.strip_prefix("r#").unwrap_or(&spelled) == identifier {
                    lines.push(ident.span().start().line);
                }
            }
            TokenTree::Group(group) => {
                collect_identifier(group.stream(), identifier, lines);
            }
            TokenTree::Punct(_) | TokenTree::Literal(_) => {}
        }
    }
}

/// Every source line on which `identifier` occurs as a token, one entry
/// per occurrence, in source order. Comments and literals cannot produce
/// or hide an occurrence: the scan walks lexed tokens.
///
/// # Errors
///
/// Returns a description when the source does not lex.
pub fn identifier_lines(source: &str, identifier: &str) -> Result<Vec<usize>, String> {
    let stream: TokenStream = source
        .parse()
        .map_err(|error| format!("lex failed: {error}"))?;
    let mut lines = Vec::new();
    collect_identifier(stream, identifier, &mut lines);
    Ok(lines)
}

/// Per-line occurrence presence for `identifier`: the set of source lines
/// naming it, mapped to the line's trimmed text, counted per distinct
/// text. The shape a classified manifest compares against.
///
/// # Errors
///
/// Returns a description when the source does not lex.
pub fn identifier_line_census(
    source: &str,
    identifier: &str,
) -> Result<BTreeMap<String, usize>, String> {
    let mut lines = identifier_lines(source, identifier)?;
    lines.sort_unstable();
    lines.dedup();
    let text: Vec<&str> = source.lines().collect();
    let mut census = BTreeMap::new();
    for line in lines {
        let content = text
            .get(line - 1)
            .map_or_else(String::new, |content| content.trim().to_string());
        *census.entry(content).or_insert(0) += 1;
    }
    Ok(census)
}

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

    #[test]
    fn raw_strings_cannot_mask_an_occurrence() {
        let source = "fn f(&mut self) { let _ = r#\"\" // \"#; self.counters.clear(); }\n";
        assert_eq!(
            identifier_lines(source, "counters").expect("lexes"),
            vec![1]
        );
    }

    #[test]
    fn raw_identifiers_resolve_to_the_same_site() {
        let source = "fn f(&mut self) { self.r#counters.clear(); }\n";
        assert_eq!(
            identifier_lines(source, "counters").expect("lexes"),
            vec![1]
        );
        let banned = "fn f() { r#include!(\"../elsewhere.rs\"); }\n";
        assert_eq!(identifier_lines(banned, "include").expect("lexes"), vec![1]);
    }

    #[test]
    fn comments_and_strings_produce_no_occurrence() {
        let source = "// counters\n/* counters */\nfn f() { let _ = \"counters\"; }\n";
        assert_eq!(
            identifier_lines(source, "counters").expect("lexes"),
            Vec::<usize>::new()
        );
    }

    #[test]
    fn path_attributes_are_refused() {
        let ast = syn::parse_file("#[path = \"../elsewhere.rs\"]\nmod extra;\n").expect("parses");
        let audit = audit_module_items(&ast, true);
        assert_eq!(audit.violations.len(), 1);
        assert!(audit.violations[0].contains("path"));
    }

    #[test]
    fn cfg_attr_on_modules_is_refused() {
        let ast = syn::parse_file("#[cfg_attr(unix, path = \"../elsewhere.rs\")]\nmod extra;\n")
            .expect("parses");
        let audit = audit_module_items(&ast, true);
        assert_eq!(audit.violations.len(), 1);
    }

    #[test]
    fn item_position_macros_are_refused() {
        let ast = syn::parse_file("include!(\"../elsewhere.rs\");\n").expect("parses");
        let audit = audit_module_items(&ast, true);
        assert_eq!(audit.violations.len(), 1);
        assert!(audit.violations[0].contains("include"));
    }

    #[test]
    fn macro_surface_sees_every_position() {
        let source = "#[evil_attr]\nfn f() { evil!(self); let _ = also_evil![1]; }\n\
             #[derive(Clone, Evil)]\nstruct S;\n";
        let surface = macro_surface(source).expect("lexes");
        let invocations: Vec<&str> = surface
            .invocations
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        assert_eq!(invocations, ["evil", "also_evil"]);
        let attributes: Vec<&str> = surface
            .attributes
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        assert_eq!(attributes, ["evil_attr", "derive"]);
        let derives: Vec<&str> = surface
            .derives
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        assert_eq!(derives, ["Clone", "Evil"]);
    }

    #[test]
    fn qualified_spellings_stay_qualified() {
        let source = "#[kani::proof]\n#[derive(evil::Error)]\n\
             fn f() { evil::assert!(true); #[attr(nested!(1))] struct T; }\n";
        let surface = macro_surface(source).expect("lexes");
        let invocations: Vec<&str> = surface
            .invocations
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        assert_eq!(invocations, ["evil::assert", "nested"]);
        let attributes: Vec<&str> = surface
            .attributes
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        assert_eq!(attributes, ["kani::proof", "derive", "attr"]);
        let derives: Vec<&str> = surface
            .derives
            .iter()
            .map(|(name, _)| name.as_str())
            .collect();
        assert_eq!(derives, ["evil::Error"]);
    }

    #[test]
    fn use_bindings_report_renames_and_globs() {
        let ast = syn::parse_file(
            "use evil::assert;\nuse evil::{prelude::*, Error as Failure};\n\
             mod inner { use evil::assert_eq; }\n",
        )
        .expect("parses");
        let bindings: Vec<(String, String)> = use_bindings(&ast)
            .into_iter()
            .map(|(name, path, _)| (name, path))
            .collect();
        assert_eq!(
            bindings,
            [
                ("assert".to_string(), "evil::assert".to_string()),
                ("*".to_string(), "evil::prelude::*".to_string()),
                ("Failure".to_string(), "evil::Error".to_string()),
                ("assert_eq".to_string(), "evil::assert_eq".to_string()),
            ]
        );
    }

    #[test]
    fn raw_aliases_normalize_in_use_bindings() {
        let ast = syn::parse_file("use evil::assert as r#assert;\n").expect("parses");
        let bindings: Vec<(String, String)> = use_bindings(&ast)
            .into_iter()
            .map(|(name, path, _)| (name, path))
            .collect();
        assert_eq!(
            bindings,
            [("assert".to_string(), "evil::assert".to_string())]
        );
    }

    #[test]
    fn parent_binding_refuses_redirection_and_inline_bodies() {
        let redirected =
            syn::parse_file("#[path = \"../elsewhere/mod.rs\"]\nmod guarded;\n").expect("parses");
        assert!(file_module_binding(&redirected, "guarded").is_err());
        let inline = syn::parse_file("mod guarded { pub struct S;\n}\n").expect("parses");
        assert!(file_module_binding(&inline, "guarded").is_err());
        let doubled =
            syn::parse_file("mod guarded;\n#[cfg(test)]\nmod guarded;\n").expect("parses");
        assert!(file_module_binding(&doubled, "guarded").is_err());
        let plain = syn::parse_file("mod guarded;\n").expect("parses");
        assert!(file_module_binding(&plain, "guarded").is_ok());
    }

    #[test]
    fn multiline_visibility_is_structural_not_textual() {
        let ast = syn::parse_file("pub struct S {\n    pub(crate)\n    field: u32,\n}\n")
            .expect("parses");
        let fields = struct_fields(&ast, "S").expect("declared once");
        let field = fields.iter().next().expect("one field");
        assert!(!matches!(field.vis, syn::Visibility::Inherited));
    }
}