Skip to main content

rune/ast/
item_mod.rs

1use crate::ast::prelude::*;
2
3#[test]
4#[cfg(not(miri))]
5fn ast_parse() {
6    rt::<ast::ItemMod>("mod ruins {}");
7
8    let item = rt::<ast::ItemMod>("#[cfg(test)] mod tests {}");
9    assert_eq!(item.attributes.len(), 1);
10
11    let item = rt::<ast::ItemMod>("mod whiskey_bravo { #![allow(dead_code)] fn x() {} }");
12    assert_eq!(item.attributes.len(), 0);
13    assert!(matches!(item.body, ast::ItemModBody::InlineBody(..)));
14}
15
16/// A module item.
17#[derive(Debug, TryClone, PartialEq, Eq, Parse, ToTokens, Spanned)]
18#[rune(parse = "meta_only")]
19#[non_exhaustive]
20pub struct ItemMod {
21    /// The *inner* attributes are applied to the module  `#[cfg(test)] mod tests {  }`
22    #[rune(iter, meta)]
23    pub attributes: Vec<ast::Attribute>,
24    /// The visibility of the `mod` item
25    #[rune(option, meta)]
26    pub visibility: ast::Visibility,
27    /// The `mod` keyword.
28    pub mod_token: T![mod],
29    /// The name of the mod.
30    pub name: ast::Ident,
31    /// The optional body of the module declaration.
32    pub body: ItemModBody,
33    /// The id of the module item.
34    #[rune(skip)]
35    pub(crate) id: ItemId,
36}
37
38impl ItemMod {}
39
40item_parse!(Mod, ItemMod, "mod item");
41
42/// An item body.
43#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Spanned)]
44#[non_exhaustive]
45pub enum ItemModBody {
46    /// An empty body terminated by a semicolon.
47    EmptyBody(T![;]),
48    /// An inline body.
49    InlineBody(ItemInlineBody),
50}
51
52impl Parse for ItemModBody {
53    fn parse(p: &mut Parser<'_>) -> Result<Self> {
54        Ok(match p.nth(0)? {
55            K!['{'] => Self::InlineBody(p.parse()?),
56            _ => Self::EmptyBody(p.parse()?),
57        })
58    }
59}
60
61/// A module declaration.
62#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Parse, Spanned)]
63#[non_exhaustive]
64pub struct ItemInlineBody {
65    /// The open brace.
66    pub open: T!['{'],
67    /// A nested "file" declaration.
68    #[rune(option)]
69    pub file: Box<ast::File>,
70    /// The close brace.
71    pub close: T!['}'],
72}
73
74impl Peek for ItemInlineBody {
75    fn peek(p: &mut Peeker<'_>) -> bool {
76        <T!['{']>::peek(p)
77    }
78}