summaryrefslogtreecommitdiff
path: root/ecs-macros/src/lib.rs
blob: 73709e4d79059f1de18710f6df1eade5bce02545 (plain)
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
use std::path::PathBuf as FsPathBuf;

use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::spanned::Spanned;
use syn::{parse, Attribute, Ident, Item, ItemEnum, ItemStruct, ItemUnion, Path};
use toml::value::{Table as TomlTable, Value as TomlValue};

macro_rules! syn_path {
    ($first_segment: ident $(::$segment: ident)*) => {
        ::syn::Path {
            leading_colon: None,
            segments: ::syn::punctuated::Punctuated::from_iter([
                syn_path_segment!($first_segment),
                $(syn_path_segment!($segment),)*
            ])
        }
    };
}

macro_rules! syn_path_segment {
    ($segment: ident) => {
        ::syn::PathSegment {
            ident: ::proc_macro2::Ident::new(
                stringify!($segment),
                ::proc_macro2::Span::call_site(),
            ),
            arguments: ::syn::PathArguments::None,
        }
    };
}

#[proc_macro_derive(Component, attributes(component))]
pub fn component_derive(input: TokenStream) -> TokenStream
{
    let item: TypeItem = parse::<Item>(input).unwrap().try_into().unwrap();

    let item_ident = item.ident();

    let component_attr = item.component_attribute().unwrap_or_default();

    let drop_last = component_attr.drop_last;

    let ecs_path = find_engine_ecs_crate_path().unwrap_or_else(|| syn_path!(ecs));

    quote! {
        impl #ecs_path::component::Component for #item_ident
        {
            fn drop_last(&self) -> bool {
                #drop_last
            }

            fn as_any_mut(&mut self) -> &mut dyn std::any::Any
            {
                self
            }

            fn as_any(&self) -> &dyn std::any::Any
            {
                self
            }
        }

        impl #ecs_path::system::Input for #item_ident {}

        impl #ecs_path::type_name::TypeName for #item_ident
        {
            fn type_name(&self) -> &'static str
            {
                std::any::type_name::<Self>()
            }
        }
    }
    .into()
}

#[proc_macro_derive(Sole)]
pub fn sole_derive(input: TokenStream) -> TokenStream
{
    let item: TypeItem = parse::<Item>(input).unwrap().try_into().unwrap();

    let item_ident = item.ident();

    let ecs_path = find_engine_ecs_crate_path().unwrap_or_else(|| syn_path!(ecs));

    quote! {
        impl #ecs_path::sole::Sole for #item_ident
        {
            fn as_any_mut(&mut self) -> &mut dyn std::any::Any
            {
                self
            }

            fn as_any(&self) -> &dyn std::any::Any
            {
                self
            }
        }

        impl #ecs_path::type_name::TypeName for #item_ident
        {
            fn type_name(&self) -> &'static str
            {
                std::any::type_name::<Self>()
            }
        }
    }
    .into()
}

enum TypeItem
{
    Struct(ItemStruct),
    Enum(ItemEnum),
    Union(ItemUnion),
}

impl TypeItem
{
    fn ident(&self) -> &Ident
    {
        match self {
            Self::Struct(struct_item) => &struct_item.ident,
            Self::Enum(enum_item) => &enum_item.ident,
            Self::Union(union_item) => &union_item.ident,
        }
    }

    fn component_attribute(&self) -> Option<ComponentAttribute>
    {
        let item_attrs = match &self {
            Self::Struct(struct_item) => &struct_item.attrs,
            &Self::Enum(enum_item) => &enum_item.attrs,
            &Self::Union(union_item) => &union_item.attrs,
        };

        let mut component_attr: Option<&Attribute> = None;

        for item_attr in item_attrs {
            if component_attr.is_some() {
                panic!("Expected only one component attribute");
            }

            if item_attr.path().get_ident()? == "component" {
                component_attr = Some(item_attr);
            }
        }

        Some(ComponentAttribute::from_attribute(component_attr?).unwrap())
    }
}

impl TryFrom<Item> for TypeItem
{
    type Error = syn::Error;

    fn try_from(item: Item) -> Result<Self, Self::Error>
    {
        match item {
            Item::Struct(struct_item) => Ok(Self::Struct(struct_item)),
            Item::Enum(enum_item) => Ok(Self::Enum(enum_item)),
            Item::Union(union_item) => Ok(Self::Union(union_item)),
            _ => Err(syn::Error::new(
                item.span(),
                "Expected a struct, a enum or a union",
            )),
        }
    }
}

impl ToTokens for TypeItem
{
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream)
    {
        match self {
            Self::Struct(struct_item) => struct_item.to_tokens(tokens),
            Self::Enum(enum_item) => enum_item.to_tokens(tokens),
            Self::Union(union_item) => union_item.to_tokens(tokens),
        }
    }
}

#[derive(Debug, Default)]
struct ComponentAttribute
{
    drop_last: bool,
}

impl ComponentAttribute
{
    fn from_attribute(attribute: &Attribute) -> Result<Self, syn::Error>
    {
        let mut drop_last = false;

        attribute.parse_nested_meta(|meta| {
            if meta
                .path
                .get_ident()
                .is_some_and(|flag| flag == "drop_last")
            {
                drop_last = true;

                return Ok(());
            }

            Err(meta.error("Unrecognized token"))
        })?;

        Ok(Self { drop_last })
    }
}

fn find_engine_ecs_crate_path() -> Option<Path>
{
    let cargo_manifest_dir = FsPathBuf::from(std::env::var("CARGO_MANIFEST_DIR").ok()?);

    let crate_manifest = std::fs::read_to_string(cargo_manifest_dir.join("Cargo.toml"))
        .ok()?
        .parse::<TomlTable>()
        .expect("Failed to parse crate manifest file");

    let crate_dependencies = match crate_manifest.get("dependencies")? {
        TomlValue::Table(dependencies) => Some(dependencies),
        _ => None,
    }?;

    crate_dependencies.iter().find_map(|(crate_dep_name, _)| {
        if crate_dep_name == "engine" {
            return Some(syn_path!(engine::ecs));
        }

        None
    })
}