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#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Spanned)]
29#[non_exhaustive]
30pub struct ItemImpl {
31 #[rune(iter)]
33 pub attributes: Vec<ast::Attribute>,
34 pub impl_: T![impl],
36 pub path: ast::Path,
38 pub open: T!['{'],
40 #[rune(iter)]
44 pub items: Vec<(ast::ImplItem, Option<T![;]>)>,
45 pub close: T!['}'],
47}
48
49impl ItemImpl {
50 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#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Spanned)]
91#[non_exhaustive]
92pub enum ImplItem {
93 Fn(ast::ItemFn),
95 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 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}