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
use crate::Section;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use syn::parse::{self, Parse, ParseStream};
use syn::token::{Brace, Mod};
use syn::{AttrStyle, Attribute, Ident, Item, Visibility};

#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum CatchrModItem {
    Section(Section),
    Item(Item),
}

impl ToTokens for CatchrModItem {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self {
            CatchrModItem::Item(item) => item.to_tokens(tokens),
            CatchrModItem::Section(section) => section.to_tokens(tokens),
        }
    }
}

impl Parse for CatchrModItem {
    fn parse(input: ParseStream) -> parse::Result<Self> {
        let result = if Section::peek(input) {
            CatchrModItem::Section(input.parse::<Section>()?)
        } else {
            CatchrModItem::Item(input.parse::<Item>()?)
        };

        Ok(result)
    }
}

#[derive(Debug, Clone)]
pub struct CatchrMod {
    attrs: Vec<Attribute>,
    vis: Visibility,
    mod_token: Mod,
    ident: Ident,
    content: (Brace, Vec<CatchrModItem>),
}

impl ToTokens for CatchrMod {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let CatchrMod {
            vis,
            content,
            attrs,
            mod_token,
            ident,
        } = &self;

        let content = &content.1;

        let outer_attrs =
            attrs.iter().filter(|attr| attr.style == AttrStyle::Outer);

        let inner_attrs = attrs.iter().filter(|attr| match attr.style {
            AttrStyle::Inner(_) => true,
            _ => false,
        });

        let q = quote! {
            #(#outer_attrs)*
            #[allow(unused)]
            #vis #mod_token #ident {
                #(#inner_attrs)*
                #(#content)*
            }
        };

        tokens.append_all(q);
    }
}

impl Parse for CatchrMod {
    fn parse(input: ParseStream) -> parse::Result<Self> {
        let mut attrs = Attribute::parse_outer(input)?;

        let vis = Visibility::parse(input)?;

        let mod_token = Mod::parse(input)?;

        let ident = Ident::parse(input)?;

        let content;
        let brace = syn::braced!(content in input);

        let inner_attrs = Attribute::parse_inner(&content)?;

        attrs.extend(inner_attrs);

        let mut items = vec![];

        loop {
            if content.is_empty() {
                break;
            }
            let item = content.parse::<CatchrModItem>()?;

            items.push(item);
        }

        Ok(Self {
            attrs,
            vis,
            mod_token,
            ident,
            content: (brace, items),
        })
    }
}

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

    #[test]
    fn parse_quote() {
        let s = r#"
            #[hello]
            mod whatever {
                #![goodbye]
                use super::*;

                when "whatever" {
                    let x = 1;
                    then "hello" {
                        assert_eq!(x, 1);
                    }
                }
            }"#;

        let catchr_mod = syn::parse_str::<CatchrMod>(s).unwrap();

        let act = catchr_mod.to_token_stream();

        let exp = quote!(
            #[hello]
            #[allow(unused)]
            mod whatever {
                #![goodbye]
                use super::*;

                mod when_whatever {
                    use super::*;

                    #[test]
                    fn then_hello() {
                        {
                            let x = 1;
                            {
                                assert_eq!(x, 1);
                            }
                        }
                    }
                }
            }
        );

        assert_eq!(exp.to_string(), act.to_string());
    }
}