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
use quote::{quote, ToTokens};
use syn::{parse::Parse, parse::ParseStream};

#[cfg(no_std)]
use core::mem;
#[cfg(not(no_std))]
use std::mem;

use std::borrow::Cow;

use crate::attrs::{AttrItem, ExportInfo, ExportScope, ExportedParams};
use crate::function::ExportedFn;
use crate::rhai_module::{ExportedConst, ExportedType};

#[derive(Debug, Clone, Eq, PartialEq, Hash, Default)]
pub struct ExportedModParams {
    pub name: String,
    skip: bool,
    pub scope: ExportScope,
}

impl Parse for ExportedModParams {
    fn parse(args: ParseStream) -> syn::Result<Self> {
        if args.is_empty() {
            return Ok(ExportedModParams::default());
        }

        Self::from_info(crate::attrs::parse_attr_items(args)?)
    }
}

impl ExportedParams for ExportedModParams {
    fn parse_stream(args: ParseStream) -> syn::Result<Self> {
        Self::parse(args)
    }

    fn no_attrs() -> Self {
        Default::default()
    }

    fn from_info(info: ExportInfo) -> syn::Result<Self> {
        let ExportInfo { items: attrs, .. } = info;
        let mut name = String::new();
        let mut skip = false;
        let mut scope = None;
        for attr in attrs {
            let AttrItem { key, value, .. } = attr;
            match (key.to_string().as_ref(), value) {
                ("name", Some(s)) => {
                    let new_name = s.value();
                    if name == new_name {
                        return Err(syn::Error::new(key.span(), "conflicting name"));
                    }
                    name = new_name;
                }
                ("name", None) => return Err(syn::Error::new(key.span(), "requires value")),

                ("skip", None) => skip = true,
                ("skip", Some(s)) => return Err(syn::Error::new(s.span(), "extraneous value")),

                ("export_prefix", Some(_)) | ("export_all", None) if scope.is_some() => {
                    return Err(syn::Error::new(key.span(), "duplicate export scope"));
                }
                ("export_prefix", Some(s)) => scope = Some(ExportScope::Prefix(s.value())),
                ("export_prefix", None) => {
                    return Err(syn::Error::new(key.span(), "requires value"))
                }
                ("export_all", None) => scope = Some(ExportScope::All),
                ("export_all", Some(s)) => {
                    return Err(syn::Error::new(s.span(), "extraneous value"))
                }
                (attr, ..) => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!("unknown attribute '{attr}'"),
                    ))
                }
            }
        }

        Ok(ExportedModParams {
            name,
            skip,
            scope: scope.unwrap_or_default(),
        })
    }
}

#[derive(Debug)]
pub struct Module {
    mod_all: syn::ItemMod,
    consts: Vec<ExportedConst>,
    custom_types: Vec<ExportedType>,
    fns: Vec<ExportedFn>,
    sub_modules: Vec<Module>,
    params: ExportedModParams,
}

impl Module {
    pub fn set_params(&mut self, params: ExportedModParams) -> syn::Result<()> {
        self.params = params;
        Ok(())
    }
}

impl Parse for Module {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut mod_all: syn::ItemMod = input.parse()?;

        let fns: Vec<_>;
        let mut consts = Vec::new();
        let mut custom_types = Vec::new();
        let mut sub_modules = Vec::new();

        if let Some((.., ref mut content)) = mod_all.content {
            // Gather and parse functions.
            fns = content
                .iter_mut()
                .filter_map(|item| match item {
                    syn::Item::Fn(f) => Some(f),
                    _ => None,
                })
                .try_fold(Vec::new(), |mut vec, item_fn| -> syn::Result<_> {
                    let params =
                        crate::attrs::inner_item_attributes(&mut item_fn.attrs, "rhai_fn")?;

                    let f =
                        syn::parse2(item_fn.to_token_stream()).and_then(|mut f: ExportedFn| {
                            f.set_params(params)?;
                            f.set_cfg_attrs(crate::attrs::collect_cfg_attr(&item_fn.attrs));

                            #[cfg(feature = "metadata")]
                            f.set_comments(crate::attrs::doc_attributes(&item_fn.attrs)?);
                            Ok(f)
                        })?;

                    vec.push(f);
                    Ok(vec)
                })?;
            // Gather and parse constants definitions.
            for item in &*content {
                if let syn::Item::Const(syn::ItemConst {
                    vis: syn::Visibility::Public(..),
                    ref expr,
                    ident,
                    attrs,
                    ty,
                    ..
                }) = item
                {
                    consts.push(ExportedConst {
                        name: ident.to_string(),
                        typ: ty.clone(),
                        expr: expr.as_ref().clone(),
                        cfg_attrs: crate::attrs::collect_cfg_attr(attrs),
                    })
                }
            }
            // Gather and parse type definitions.
            for item in &*content {
                if let syn::Item::Type(syn::ItemType {
                    vis: syn::Visibility::Public(..),
                    ident,
                    attrs,
                    ty,
                    ..
                }) = item
                {
                    custom_types.push(ExportedType {
                        name: ident.to_string(),
                        typ: ty.clone(),
                        cfg_attrs: crate::attrs::collect_cfg_attr(attrs),
                    })
                }
            }
            // Gather and parse sub-module definitions.
            //
            // They are actually removed from the module's body, because they will need
            // re-generating later when generated code is added.
            sub_modules.reserve(content.len() - fns.len() - consts.len());
            let mut i = 0;
            while i < content.len() {
                match content[i] {
                    syn::Item::Mod(..) => {
                        let mut item_mod = match content.remove(i) {
                            syn::Item::Mod(m) => m,
                            _ => unreachable!(),
                        };
                        let params: ExportedModParams =
                            crate::attrs::inner_item_attributes(&mut item_mod.attrs, "rhai_mod")?;
                        let module = syn::parse2::<Module>(item_mod.to_token_stream()).and_then(
                            |mut m| {
                                m.set_params(params)?;
                                Ok(m)
                            },
                        )?;
                        sub_modules.push(module);
                    }
                    _ => i += 1,
                }
            }
        } else {
            fns = Vec::new();
        }
        Ok(Module {
            mod_all,
            fns,
            consts,
            custom_types,
            sub_modules,
            params: ExportedModParams::default(),
        })
    }
}

impl Module {
    pub fn attrs(&self) -> &[syn::Attribute] {
        &self.mod_all.attrs
    }

    pub fn module_name(&self) -> &syn::Ident {
        &self.mod_all.ident
    }

    pub fn exported_name(&self) -> Cow<str> {
        if !self.params.name.is_empty() {
            (&self.params.name).into()
        } else {
            self.module_name().to_string().into()
        }
    }

    pub fn update_scope(&mut self, parent_scope: &ExportScope) {
        let keep = match (self.params.skip, parent_scope) {
            (true, ..) => false,
            (.., ExportScope::PubOnly) => matches!(self.mod_all.vis, syn::Visibility::Public(..)),
            (.., ExportScope::Prefix(s)) => self.mod_all.ident.to_string().starts_with(s),
            (.., ExportScope::All) => true,
        };
        self.params.skip = !keep;
    }

    pub fn skipped(&self) -> bool {
        self.params.skip
    }

    pub fn generate(self) -> proc_macro2::TokenStream {
        match self.generate_inner() {
            Ok(tokens) => tokens,
            Err(e) => e.to_compile_error(),
        }
    }

    fn generate_inner(self) -> Result<proc_macro2::TokenStream, syn::Error> {
        // Check for collisions if the "name" attribute was used on inner functions.
        crate::rhai_module::check_rename_collisions(&self.fns)?;

        // Extract the current structure of the module.
        let Module {
            mut mod_all,
            mut fns,
            consts,
            custom_types,
            mut sub_modules,
            params,
            ..
        } = self;
        let mod_vis = mod_all.vis;
        let mod_name = mod_all.ident.clone();
        let (.., orig_content) = mod_all.content.take().unwrap();
        let mod_attrs = mem::take(&mut mod_all.attrs);

        #[cfg(feature = "metadata")]
        let mod_doc = crate::attrs::doc_attributes(&mod_attrs)?.join("\n");
        #[cfg(not(feature = "metadata"))]
        let mod_doc = String::new();

        if !params.skip {
            // Generate new module items.
            //
            // This is done before inner module recursive generation, because that is destructive.
            let mod_gen = crate::rhai_module::generate_body(
                &mod_doc,
                &mut fns,
                &consts,
                &custom_types,
                &mut sub_modules,
                &params.scope,
            );

            // NB: sub-modules must have their new items for exporting generated in depth-first order
            // to avoid issues caused by re-parsing them
            let inner_modules = sub_modules
                .into_iter()
                .try_fold::<_, _, Result<_, syn::Error>>(Vec::new(), |mut acc, m| {
                    acc.push(m.generate_inner()?);
                    Ok(acc)
                })?;

            // Regenerate the module with the new content added.
            Ok(quote! {
                #(#mod_attrs)*
                #[allow(clippy::needless_pass_by_value)]
                #mod_vis mod #mod_name {
                    #(#orig_content)*
                    #(#inner_modules)*
                    #mod_gen
                }
            })
        } else {
            // Regenerate the original module as-is.
            Ok(quote! {
                #(#mod_attrs)*
                #[allow(clippy::needless_pass_by_value)]
                #mod_vis mod #mod_name {
                    #(#orig_content)*
                }
            })
        }
    }

    #[allow(dead_code)]
    pub fn name(&self) -> &syn::Ident {
        &self.mod_all.ident
    }

    #[allow(dead_code)]
    pub fn consts(&self) -> &[ExportedConst] {
        &self.consts
    }

    #[allow(dead_code)]
    pub fn custom_types(&self) -> &[ExportedType] {
        &self.custom_types
    }

    #[allow(dead_code)]
    pub fn fns(&self) -> &[ExportedFn] {
        &self.fns
    }

    #[allow(dead_code)]
    pub fn sub_modules(&self) -> &[Module] {
        &self.sub_modules
    }

    #[allow(dead_code)]
    pub fn content(&self) -> Option<&[syn::Item]> {
        match self.mod_all {
            syn::ItemMod {
                content: Some((.., ref vec)),
                ..
            } => Some(vec),
            _ => None,
        }
    }
}