rune/ast/
item_struct.rs

1use crate::ast::prelude::*;
2
3#[test]
4#[cfg(not(miri))]
5fn ast_parse() {
6    rt::<ast::ItemStruct>("struct Foo");
7    rt::<ast::ItemStruct>("struct Foo ( a, b, c )");
8    rt::<ast::ItemStruct>("struct Foo { a, b, c }");
9    rt::<ast::ItemStruct>("struct Foo { #[default_value = 1] a, b, c }");
10    rt::<ast::ItemStruct>("#[alpha] struct Foo ( #[default_value = \"x\" ] a, b, c )");
11
12    rt::<ast::Fields>("");
13
14    rt::<ast::Fields>("{ a, b, c }");
15    rt::<ast::Fields>("{ #[x] a, #[y] b, #[z] #[w] #[f32] c }");
16    rt::<ast::Fields>("{ a, #[attribute] b, c }");
17
18    rt::<ast::Fields>("( a, b, c )");
19    rt::<ast::Fields>("( #[x] a, b, c )");
20    rt::<ast::Fields>("( #[x] pub a, b, c )");
21    rt::<ast::Fields>("( a, b, c )");
22    rt::<ast::Fields>("()");
23
24    rt::<ast::Field>("a");
25    rt::<ast::Field>("#[x] a");
26
27    rt::<ast::ItemStruct>(
28        r"
29        struct Foo { 
30            a: i32, 
31            b: f64, 
32            c: CustomType, 
33        }",
34    );
35}
36
37/// A struct item.
38#[derive(Debug, TryClone, PartialEq, Eq, Parse, ToTokens, Spanned)]
39#[rune(parse = "meta_only")]
40#[non_exhaustive]
41pub struct ItemStruct {
42    /// The attributes for the struct
43    #[rune(iter, meta)]
44    pub attributes: Vec<ast::Attribute>,
45    /// The visibility of the `struct` item
46    #[rune(option, meta)]
47    pub visibility: ast::Visibility,
48    /// The `struct` keyword.
49    pub struct_token: T![struct],
50    /// The identifier of the struct declaration.
51    pub ident: ast::Ident,
52    /// The body of the struct.
53    #[rune(iter)]
54    pub body: ast::Fields,
55    /// Opaque identifier of the struct.
56    #[rune(skip)]
57    pub(crate) id: ItemId,
58}
59
60impl ItemStruct {
61    /// If the struct declaration needs to be terminated with a semicolon.
62    pub(crate) fn needs_semi_colon(&self) -> bool {
63        self.body.needs_semi_colon()
64    }
65}
66
67item_parse!(Struct, ItemStruct, "struct item");
68
69/// A field as part of a struct or a tuple body.
70#[derive(Debug, TryClone, PartialEq, Eq, ToTokens, Parse, Spanned)]
71#[non_exhaustive]
72pub struct Field {
73    /// Attributes associated with field.
74    #[rune(iter)]
75    pub attributes: Vec<ast::Attribute>,
76    /// The visibility of the field
77    #[rune(option)]
78    pub visibility: ast::Visibility,
79    /// Name of the field.
80    pub name: ast::Ident,
81    /// The type.
82    #[rune(option)]
83    pub ty: Option<(T![:], ast::Type)>,
84}