aboutsummaryrefslogtreecommitdiff
path: root/mingling_pathf/src/patterns/pack.rs
blob: f025f7dea743b7001ce2103745a897afde79e377 (plain) (blame)
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
use syn::Item;

use crate::pattern_analyzer::{AnalyzeItem, AnalyzePattern};

/// Matches types defined by `pack!`, `pack_err!`, `pack_structural!`, `pack_err_structural!` macros.
///
/// Covered forms:
/// - `pack!(TypeName = InnerType)`
/// - `pack! { TypeName = InnerType }`
/// - `pack_err!(TypeName)`
/// - `pack_err!(TypeName = InnerType)`
/// - `pack_structural!` series same as above
pub struct PackPattern;

impl AnalyzePattern for PackPattern {
    fn contains(&self, content: &str) -> bool {
        content.contains("pack!") || content.contains("pack_err!")
    }

    fn analyze(&self, content: &str) -> Vec<AnalyzeItem> {
        let Ok(syntax) = syn::parse_file(content) else {
            return Vec::new();
        };

        let mut items = Vec::new();

        for item in &syntax.items {
            match item {
                // Top-level macro calls
                Item::Macro(m) => {
                    if let Some(name) = try_extract_pack_name(m) {
                        items.push(AnalyzeItem {
                            module: String::new(),
                            item_name: name,
                        });
                    }
                }
                // Macro calls inside inline modules
                Item::Mod(item_mod) => {
                    if let Some((_, nested)) = &item_mod.content {
                        for n in nested {
                            if let Item::Macro(m) = n
                                && let Some(name) = try_extract_pack_name(m) {
                                    items.push(AnalyzeItem {
                                        module: item_mod.ident.to_string(),
                                        item_name: name,
                                    });
                                }
                        }
                    }
                }
                _ => {}
            }
        }

        items
    }
}

/// If the macro call is `pack!` / `pack_err!` / etc., extract the registered type name.
fn try_extract_pack_name(m: &syn::ItemMacro) -> Option<String> {
    let macro_name = m.mac.path.segments.last()?.ident.to_string();

    match macro_name.as_str() {
        "pack" | "pack_err" | "pack_structural" | "pack_err_structural" => {}
        _ => return None,
    }

    let tokens = &m.mac.tokens;

    // `pack!(T)` or `pack!(T = U)` — the first ident is the type name
    // Parse simply with syn
    if let Ok(ident) = syn::parse2::<syn::Ident>(tokens.clone()) {
        // pack!(TypeName) — just a single ident
        return Some(ident.to_string());
    }

    // Try to parse `Ident = Type`
    // Clone tokens first to avoid partial consumption
    let stream = tokens.clone();
    let mut iter = stream.into_iter();

    // Skip leading attributes/doc comments
    loop {
        match iter.next()? {
            proc_macro2::TokenTree::Ident(ident) => {
                // Found the first ident, this is the type name
                let type_name = ident.to_string();

                // Check if `=` follows
                if let Some(proc_macro2::TokenTree::Punct(p)) = iter.next()
                    && p.as_char() == '=' {
                        // pack!(TypeName = InnerType)
                        return Some(type_name);
                    }

                // pack_err!(TypeName) — only a single ident
                return Some(type_name);
            }
            _ => continue,
        }
    }
}