Skip to main content

rune/ast/
item_impl.rs

1use crate::ast::prelude::*;
2
3#[test]
4#[cfg(not(miri))]
5fn ast_parse() {
6    rt::<ast::ItemImpl>("impl Foo {}");
7    rt::<ast::ItemImpl>("impl Foo { fn test(self) { } }");
8    rt::<ast::ItemImpl>(
9        "#[variant(enum_= \"SuperHero\", x = \"1\")] impl Foo { fn test(self) { } }",
10    );
11    rt::<ast::ItemImpl>("#[xyz] impl Foo { #[jit] fn test(self) { } }");
12    rt::<ast::ItemImpl>("impl Foo { const X = 1; }");
13    rt::<ast::ItemImpl>("impl Foo { pub const X = 1; fn x() { Self::X } const Y = 2; }");
14    rt::<ast::ItemImpl>("impl Foo { /// Docs.\n #[doc = \"y\"] pub const X = Self(1); }");
15    rt::<ast::ItemImpl>("impl Foo { pub const fn x() { 1 } }");
16
17    let item = rt::<ast::ItemImpl>("impl Foo { const X = 1; fn x() {} }");
18    assert!(matches!(
19        item.items.as_slice(),
20        [
21            (ast::ImplItem::Const(..), Some(..)),
22            (ast::ImplItem::Fn(..), None)
23        ]
24    ));
25}
26
27/// An impl item.
28#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Spanned)]
29#[non_exhaustive]
30pub struct ItemImpl {
31    /// The attributes of the `impl` block
32    #[rune(iter)]
33    pub attributes: Vec<ast::Attribute>,
34    /// The `impl` keyword.
35    pub impl_: T![impl],
36    /// Path of the implementation.
37    pub path: ast::Path,
38    /// The open brace.
39    pub open: T!['{'],
40    /// The functions and constants of the impl, in the order they were
41    /// written, each with the semicolon which followed it if any. A constant
42    /// is always followed by one.
43    #[rune(iter)]
44    pub items: Vec<(ast::ImplItem, Option<T![;]>)>,
45    /// The close brace.
46    pub close: T!['}'],
47}
48
49impl ItemImpl {
50    /// Parse an `impl` item with the given attributes.
51    pub(crate) fn parse_with_attributes(
52        parser: &mut Parser<'_>,
53        attributes: Vec<ast::Attribute>,
54    ) -> Result<Self> {
55        let impl_ = parser.parse()?;
56        let path = parser.parse()?;
57        let open = parser.parse()?;
58
59        let mut items = Vec::new();
60
61        while !parser.peek::<ast::CloseBrace>()? {
62            let item = ast::ImplItem::parse(parser)?;
63
64            let semi_colon =
65                if matches!(item, ast::ImplItem::Const(..)) || parser.peek::<T![;]>()? {
66                    Some(parser.parse::<T![;]>()?)
67                } else {
68                    None
69                };
70
71            items.try_push((item, semi_colon))?;
72        }
73
74        let close = parser.parse()?;
75
76        Ok(Self {
77            attributes,
78            impl_,
79            path,
80            open,
81            items,
82            close,
83        })
84    }
85}
86
87item_parse!(Impl, ItemImpl, "impl item");
88
89/// An item inside of an `impl` block.
90#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Spanned)]
91#[non_exhaustive]
92pub enum ImplItem {
93    /// An associated function.
94    Fn(ast::ItemFn),
95    /// An associated constant.
96    Const(ast::ItemConst),
97}
98
99impl Parse for ImplItem {
100    fn parse(p: &mut Parser<'_>) -> Result<Self> {
101        let attributes = p.parse()?;
102        let visibility = p.parse()?;
103        let const_token = p.parse::<Option<T![const]>>()?;
104
105        // `const` is both what starts a constant and a modifier on a function,
106        // so which one this is is only known from what follows it.
107        if let (Some(const_token), K![ident]) = (&const_token, p.nth(0)?) {
108            return Ok(Self::Const(ast::ItemConst::parse_with_meta(
109                p,
110                attributes,
111                visibility,
112                *const_token,
113            )?));
114        }
115
116        let async_token = p.parse()?;
117
118        Ok(Self::Fn(ast::ItemFn::parse_with_meta(
119            p,
120            attributes,
121            visibility,
122            const_token,
123            async_token,
124        )?))
125    }
126}