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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
//#![cfg_attr(not(feature = "std"), no_std)] // Enable `no_std` if `std` feature is disabled
//#![allow(dead_code, unused)]
extern crate proc_macro;
//#[cfg(feature = "std")]
//extern crate std;
extern crate alloc;
use TokenStream as ProcMacroTokenStream;
use ;
use crateTuples;
use Ident;
/// `Component` macro for defining Flecs ECS components.
///
/// When a type is decorated with `#[derive(Component)]`, several trait implementations are automatically added based on its structure:
///
/// - Depending on whether the type is a struct or Rust enum or `repr(C)` enum.
/// when it's a struct or Rust Enum it implements`ComponentType<Struct>` and in a C compatible enum the `ComponentType<Enum>` trait is also implemented.
/// - Based on the presence of fields or variants, the type will implement either `TagComponent` or `DataComponent`.
/// - The `ComponentId` trait is implemented, providing storage mechanisms for the component.
///
/// # Generic types
/// - Generic types are supported, but they don't have first-class support for the `ComponentId` trait where it automatically registers the
/// ctor and copy hooks (Default & Clone) which are used for either `EntityView::add` or `EntityView::duplicate` and some other operations.
/// In that case, the user has to manually register the hooks for each variant of T of the generic component
/// by using `T::register_ctor_hook` and `T::register_clone_hook`.
///
/// # Enums:
///
/// Ensure that enums annotated with `Component` have at least one variant; otherwise, a compile-time error will be triggered.
///
/// ## Example:
///
/// ```ignore
/// #[derive(Component)]
/// struct Position {
/// x: f32,
/// y: f32,
/// }
///
/// #[derive(Component)]
/// struct Generic<T>
/// {
/// value: T,
/// }
///
/// #[derive(Component, Default)]
/// #[repr(C)]
/// enum State {
/// #[default]
/// Idle,
/// Running,
/// Jumping,
/// }
/// ```
/// Function-like macro for defining a query with `QueryBuilder`.
///
/// Usage: `query!("query_name", world, ... terms ...)`.
///
/// Returns `&mut QueryBuilder`.
///
/// Diverges from the [flecs query manual](https://github.com/SanderMertens/flecs/blob/master/docs/FlecsQueryLanguage.md) in the following respects:
///
/// 1. If the first argument is a string literal it will be used as a name.
/// 2. The next argument is a value implementing `WorldProvider`
/// 3. Terms prefixed with `&mut` or `&` will appear in the closure and must appear first:
/// ```ignore
/// // Like this:
/// query!(world, &mut MyComponent);
/// // Not like this:
/// query!(world, MyFilter, &mut MyComponent);
/// ```
/// 4. String literal terms will be matched by name:
/// ```ignore
/// query!(world, "MyComponent");
/// ```
/// 5. String literals prefixed by `$` are variables:
/// ```ignore
/// query!(world, &mut Location($"my_var"), (LocatedIn, $"my_var"));
/// ```
/// 6. Values that implement `Into<Entity>` prefixed by `$` will be used as ids:
/// ```ignore
/// query!(world, $my_entity);
/// ```
///
/// Other operators all function according to the manual.
///
/// Advanced operations are currently unsupported.
///
/// # Examples
/// ```
/// use flecs_ecs::prelude::*;
///
/// #[derive(Component)]
/// struct Foo(u8);
///
/// #[derive(Component)]
/// struct Bar(u8);
///
/// #[derive(Component)]
/// struct Bazz;
///
/// let mut world = World::new();
///
/// // Basic
/// let builder = world.query::<(&Foo, &mut Bar)>().with(Bazz::id()).build();
/// let dsl = query!(&mut world, &Foo, &mut Bar, Bazz).build();
/// assert_eq!(builder.to_string(), dsl.to_string());
///
/// // Logical modifiers
/// let builder = world
/// .query::<()>()
/// .with(Foo::id())
/// .or()
/// .with(Bar::id())
/// .without(Bazz::id())
/// .build();
///
/// let dsl = query!(&mut world, Foo || Bar, !Bazz).build();
/// assert_eq!(builder.to_string(), dsl.to_string());
/// ```
/// Function-like macro for defining a system with `SystemBuilder`.
///
/// Usage: `system!("system_name", world, ... terms ...)`.
///
/// Returns `&mut SystemBuilder`.
///
/// See [`query`] for examples & DSL divergences from the flecs spec.
///
/// [`query`]: macro@query
/// Function-like macro for defining an observer with `ObserverBuilder`.
///
/// Usage: `observer!("observer_name", world, EventType, ... terms ...)`.
///
/// Returns `&mut ObserverBuilder`.
///
/// See [`query`] for examples & DSL divergences from the flecs spec.
///
/// [`query`]: macro@query
/// Rust trait support for Flecs ECS.
///
/// This module provides macro support for registering Rust traits as Flecs components,
/// enabling dynamic dispatch through the ECS system. This is particularly useful when you
/// want to query components by trait implementation rather than concrete types.
///
/// # Overview
///
/// The `ecs_rust_trait!` macro generates a component wrapper around a Rust trait, allowing:
/// - Registration of vtables for each trait implementor
/// - Dynamic casting from entities to trait objects
/// - Querying entities that implement a specific trait
///
/// # How it works
///
/// 1. The macro generates a `<TraitName>Trait` component struct that stores vtable information
/// 2. Each concrete type implementing the trait registers its vtable with `register_vtable::<T>()`
/// 3. Components can be queried using the generated trait component
/// 4. Retrieved components can be cast to trait objects using `cast()` or `cast_mut()`
///
/// # Usage Pattern
///
/// 1. Define your trait
/// 2. Call `ecs_rust_trait!` with the trait name
/// 3. Implement the trait for your component types
/// 4. Register vtables for each implementor type
/// 5. Query components that implement the trait using the generated trait component
/// 6. Cast components to trait objects as needed
///
/// # Example
///
/// ```ignore
/// use flecs_ecs::prelude::*;
///
/// // 1. Define a trait
/// pub trait Shapes {
/// fn calculate(&self) -> u64;
/// }
///
/// // 2. Generate the trait component
/// ecs_rust_trait!(Shapes);
///
/// // 3. Implement the trait for component types
/// #[derive(Component)]
/// pub struct Circle {
/// radius: f32,
/// }
///
/// impl Shapes for Circle {
/// fn calculate(&self) -> u64 {
/// 1
/// }
/// }
///
/// #[derive(Component)]
/// pub struct Square {
/// side: f32,
/// }
///
/// impl Shapes for Square {
/// fn calculate(&self) -> u64 {
/// 2
/// }
/// }
///
/// #[derive(Component)]
/// pub struct Triangle {
/// side: f32,
/// }
///
/// impl Shapes for Triangle {
/// fn calculate(&self) -> u64 {
/// 3
/// }
/// }
///
/// let world = World::new();
///
/// // 4. Register the vtable per type that implements the trait
/// ShapesTrait::register_vtable::<Circle>(&world);
/// ShapesTrait::register_vtable::<Square>(&world);
/// ShapesTrait::register_vtable::<Triangle>(&world);
///
/// // Create entities with the components
/// world.entity_named("circle").set(Circle { radius: 5.0 });
/// world.entity_named("square").set(Square { side: 5.0 });
/// world.entity_named("triangle").set(Triangle { side: 5.0 });
///
/// // 5. Query entities that implement the trait
/// let query = world.query::<()>().with(ShapesTrait::id()).build();
///
/// query.run(|mut it| {
/// while it.next() {
/// let world = it.world();
/// for i in it.iter() {
/// let e = it.get_entity(i).unwrap();
/// let id = it.id(0);
/// // 6. Cast to trait object and use it
/// let shape = ShapesTrait::cast(e, id);
/// let calc = shape.calculate();
/// println!("{} - calc: {}", e.name(), calc);
/// }
/// }
/// });
///
/// // Output:
/// // circle - calc: 1
/// // square - calc: 2
/// // triangle - calc: 3
/// ```
///
/// # Feature flag
///
/// This module is only available when the `flecs_query_rust_traits` feature is enabled.
/// Attribute macro that conditionally applies the appropriate extern ABI based on target platform.
///
/// For WASM targets (which don't support unwinding), it uses `extern "C"`.
/// For other targets, it uses `extern "C-unwind"`.
///
/// # Usage
///
/// ```ignore
/// use flecs_ecs_derive::extern_abi;
///
/// #[extern_abi]
/// fn my_function() {
/// // Function implementation
/// }
/// ```
///
/// This will expand to:
/// - `extern "C" fn my_function() { ... }` on WASM targets
/// - `extern "C-unwind" fn my_function() { ... }` on other targets
/// Internal macro for generating tuple implementations.
///
/// This macro is used internally by the library and is not part of the public API.