trait-kit 0.4.2

Module Standard Interface and Capability Management Center — A lightweight Rust library that provides a standard interface for module definition and Kit capability management.
Documentation
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! Declarative macros for reducing boilerplate in module declarations.
//!
//! These `macro_rules!` macros generate `ModuleMeta` (and optionally
//! `AsyncAutoBuilder`) implementations, replacing repetitive hand-written
//! impl blocks with a single-line invocation.

/// Implements `ModuleMeta` for a module type (no dependencies).
///
/// # Syntax
///
/// ```text
/// impl_module_meta!(Type, "name");
/// impl_module_meta!(Type, "name", deps = [DepA, DepB]);
/// ```
///
/// # Example
///
/// ```
/// use trait_kit::impl_module_meta;
/// use trait_kit::core::ModuleMeta;
///
/// struct MyModule;
/// impl_module_meta!(MyModule, "my-module");
///
/// assert_eq!(MyModule::NAME, "my-module");
/// assert!(MyModule::dependencies().is_empty());
/// ```
#[macro_export]
macro_rules! impl_module_meta {
    ($ty:ty, $name:literal) => {
        impl $crate::core::ModuleMeta for $ty {
            const NAME: &'static str = $name;

            fn dependencies() -> &'static [(&'static str, std::any::TypeId)] {
                &[]
            }
        }
    };
    ($ty:ty, $name:literal, deps = [$($dep:ty),* $(,)?]) => {
        impl $crate::core::ModuleMeta for $ty {
            const NAME: &'static str = $name;

            fn dependencies() -> &'static [(&'static str, std::any::TypeId)] {
                static DEPS: &[(&str, std::any::TypeId)] = &[
                    $( (<$dep as $crate::core::ModuleMeta>::NAME, std::any::TypeId::of::<$dep>()), )*
                ];
                DEPS
            }
        }
    };
}

/// Implements `AutoBuilder` for a module type (sync counterpart to
/// `impl_async_auto_builder!`).
///
/// # Syntax
///
/// ```text
/// impl_auto_builder!(Type, Capability, Error, |kit| <expr>);
/// ```
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use trait_kit::impl_module_meta;
/// use trait_kit::impl_auto_builder;
/// use trait_kit::core::{AutoBuilder, ModuleMeta};
/// use trait_kit::kit::Kit;
///
/// # #[derive(Debug, thiserror::Error)]
/// # #[error("mock")]
/// # struct MockErr;
/// # #[derive(Clone)]
/// # struct Cap { v: u32 }
/// struct MyModule;
/// impl_module_meta!(MyModule, "my-module");
/// impl_auto_builder!(
///     MyModule,
///     Arc<Cap>,
///     MockErr,
///     |_kit| Ok(Arc::new(Cap { v: 42 }))
/// );
/// ```
#[macro_export]
macro_rules! impl_auto_builder {
    ($ty:ty, $cap:ty, $err:ty, |$kit:ident| $body:expr) => {
        impl $crate::core::AutoBuilder for $ty {
            type Capability = $cap;
            type Error = $err;

            #[track_caller]
            fn build(
                $kit: &$crate::kit::Kit,
            ) -> ::std::result::Result<Self::Capability, Self::Error> {
                $body
            }
        }
    };
}

/// Implements `AsyncAutoBuilder` for a module type.
///
/// The body expression must evaluate to
/// `Pin<Box<dyn Future<Output = Result<Capability, Error>> + Send + 'a>>`.
/// The closure parameter `|kit|` binds the `&AsyncKit` argument, matching
/// the hand-written impl pattern.
///
/// # Syntax
///
/// ```text
/// impl_async_auto_builder!(Type, Capability, Error, |kit| <expr>);
/// ```
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use trait_kit::impl_module_meta;
/// use trait_kit::impl_async_auto_builder;
/// use trait_kit::core::{AsyncAutoBuilder, ModuleMeta};
/// use trait_kit::kit::AsyncKit;
///
/// # #[derive(Debug, thiserror::Error)]
/// # #[error("mock")]
/// # struct MockErr;
/// # #[derive(Clone)]
/// # struct Cap { v: u32 }
/// struct MyAsyncModule;
/// impl_module_meta!(MyAsyncModule, "my-async");
/// impl_async_auto_builder!(
///     MyAsyncModule,
///     Arc<Cap>,
///     MockErr,
///     |kit| Box::pin(async move {
///         let _ = kit;
///         Ok(Arc::new(Cap { v: 42 }))
///     })
/// );
/// ```
#[cfg(feature = "async")]
#[macro_export]
macro_rules! impl_async_auto_builder {
    ($ty:ty, $cap:ty, $err:ty, |$kit:ident| $body:expr) => {
        impl $crate::core::AsyncAutoBuilder for $ty {
            type Capability = $cap;
            type Error = $err;

            #[track_caller]
            fn build<'a>(
                $kit: &'a $crate::kit::AsyncKit,
            ) -> ::std::pin::Pin<
                ::std::boxed::Box<
                    dyn ::std::future::Future<
                            Output = ::std::result::Result<Self::Capability, Self::Error>,
                        > + Send
                        + 'a,
                >,
            > {
                $body
            }
        }
    };
}

#[cfg(test)]
mod tests {
    use crate::core::ModuleMeta;

    // === Fixtures ===

    struct MacroModuleNoDeps;
    impl_module_meta!(MacroModuleNoDeps, "macro-no-deps");

    struct Dep1;
    impl_module_meta!(Dep1, "dep1");

    struct Dep2;
    impl_module_meta!(Dep2, "dep2");

    struct MacroModuleWithDeps;
    impl_module_meta!(MacroModuleWithDeps, "macro-with-deps", deps = [Dep1, Dep2]);

    // Hand-written equivalents for comparison

    struct HandWrittenNoDeps;
    impl ModuleMeta for HandWrittenNoDeps {
        const NAME: &'static str = "macro-no-deps";
        fn dependencies() -> &'static [(&'static str, std::any::TypeId)] {
            &[]
        }
    }

    struct HandWrittenWithDeps;
    impl ModuleMeta for HandWrittenWithDeps {
        const NAME: &'static str = "macro-with-deps";
        fn dependencies() -> &'static [(&'static str, std::any::TypeId)] {
            static DEPS: &[(&str, std::any::TypeId)] = &[
                (<Dep1 as ModuleMeta>::NAME, std::any::TypeId::of::<Dep1>()),
                (<Dep2 as ModuleMeta>::NAME, std::any::TypeId::of::<Dep2>()),
            ];
            DEPS
        }
    }

    // === Tests ===

    #[test]
    fn macro_generates_correct_name_no_deps() {
        assert_eq!(MacroModuleNoDeps::NAME, "macro-no-deps");
    }

    #[test]
    fn macro_generates_empty_dependencies_when_no_deps() {
        assert!(MacroModuleNoDeps::dependencies().is_empty());
    }

    #[test]
    fn macro_generates_correct_name_with_deps() {
        assert_eq!(MacroModuleWithDeps::NAME, "macro-with-deps");
    }

    #[test]
    fn macro_generates_correct_dependency_count() {
        assert_eq!(MacroModuleWithDeps::dependencies().len(), 2);
    }

    #[test]
    fn macro_dependency_names_match_module_meta_names() {
        let deps = MacroModuleWithDeps::dependencies();
        assert_eq!(deps[0].0, "dep1");
        assert_eq!(deps[1].0, "dep2");
    }

    #[test]
    fn macro_dependency_type_ids_match_hand_written() {
        let macro_deps = MacroModuleWithDeps::dependencies();
        let hand_deps = HandWrittenWithDeps::dependencies();
        assert_eq!(macro_deps.len(), hand_deps.len());
        for (i, (m, h)) in macro_deps.iter().zip(hand_deps.iter()).enumerate() {
            assert_eq!(m.0, h.0, "dep {i}: name mismatch");
            assert_eq!(m.1, h.1, "dep {i}: TypeId mismatch");
        }
    }

    #[test]
    fn macro_name_equals_hand_written_name() {
        assert_eq!(MacroModuleNoDeps::NAME, HandWrittenNoDeps::NAME);
        assert_eq!(MacroModuleWithDeps::NAME, HandWrittenWithDeps::NAME);
    }

    #[test]
    fn macro_dependencies_equal_hand_written_no_deps() {
        let m = MacroModuleNoDeps::dependencies();
        let h = HandWrittenNoDeps::dependencies();
        assert_eq!(m.len(), h.len());
    }
}

#[cfg(all(test, feature = "async"))]
mod async_macro_tests {
    use crate::core::{AsyncAutoBuilder, ModuleMeta};
    use crate::kit::AsyncKit;
    use crate::test_helpers::block_on;
    use std::future::Future;
    use std::pin::Pin;
    use std::sync::Arc;
    use thiserror::Error;

    // === Fixtures ===

    #[derive(Debug, Error)]
    #[allow(dead_code, reason = "mock error type verifies trait signature only")]
    enum MockErr {
        #[error("mock async build failed: {0}")]
        Failed(String),
    }

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct AsyncCap {
        value: u32,
    }

    // Macro-generated impl
    struct MacroAsyncModule;
    impl_module_meta!(MacroAsyncModule, "macro-async");
    impl_async_auto_builder!(MacroAsyncModule, Arc<AsyncCap>, MockErr, |kit| Box::pin(
        async move {
            let _ = kit;
            Ok(Arc::new(AsyncCap { value: 42 }))
        }
    ));

    // Hand-written impl for comparison
    struct HandAsyncModule;
    impl ModuleMeta for HandAsyncModule {
        const NAME: &'static str = "macro-async";
        fn dependencies() -> &'static [(&'static str, std::any::TypeId)] {
            &[]
        }
    }
    impl AsyncAutoBuilder for HandAsyncModule {
        type Capability = Arc<AsyncCap>;
        type Error = MockErr;
        fn build<'a>(
            kit: &'a AsyncKit,
        ) -> Pin<Box<dyn Future<Output = Result<Self::Capability, Self::Error>> + Send + 'a>>
        {
            let _ = kit;
            Box::pin(async move { Ok(Arc::new(AsyncCap { value: 42 })) })
        }
    }

    // Error-propagation fixture
    struct ErrAsyncModule;
    impl_module_meta!(ErrAsyncModule, "err-async");
    impl_async_auto_builder!(ErrAsyncModule, Arc<AsyncCap>, MockErr, |kit| Box::pin(
        async move {
            let _ = kit;
            Err(MockErr::Failed("intentional".to_string()))
        }
    ));

    // === Tests ===

    #[test]
    fn macro_async_generates_correct_name() {
        assert_eq!(MacroAsyncModule::NAME, "macro-async");
    }

    #[test]
    fn macro_async_generates_empty_dependencies() {
        assert!(MacroAsyncModule::dependencies().is_empty());
    }

    #[test]
    fn macro_async_capability_type_matches_hand_written() {
        assert_eq!(
            std::any::TypeId::of::<<MacroAsyncModule as AsyncAutoBuilder>::Capability>(),
            std::any::TypeId::of::<<HandAsyncModule as AsyncAutoBuilder>::Capability>(),
        );
    }

    #[test]
    fn macro_async_error_type_matches_hand_written() {
        assert_eq!(
            std::any::TypeId::of::<<MacroAsyncModule as AsyncAutoBuilder>::Error>(),
            std::any::TypeId::of::<<HandAsyncModule as AsyncAutoBuilder>::Error>(),
        );
    }

    #[test]
    fn macro_async_build_returns_expected_capability() {
        let kit = AsyncKit::new();
        let cap = block_on(MacroAsyncModule::build(&kit)).unwrap();
        assert_eq!(cap.value, 42);
    }

    #[test]
    fn macro_async_build_result_matches_hand_written() {
        let kit = AsyncKit::new();
        let macro_cap = block_on(MacroAsyncModule::build(&kit)).unwrap();
        let hand_cap = block_on(HandAsyncModule::build(&kit)).unwrap();
        assert_eq!(macro_cap, hand_cap);
    }

    #[test]
    fn macro_async_build_propagates_errors() {
        let kit = AsyncKit::new();
        let result = block_on(ErrAsyncModule::build(&kit));
        assert!(result.is_err());
    }

    #[test]
    fn macro_async_name_equals_hand_written_name() {
        assert_eq!(MacroAsyncModule::NAME, HandAsyncModule::NAME);
    }

    #[test]
    fn hand_written_async_module_dependencies_empty() {
        assert!(HandAsyncModule::dependencies().is_empty());
    }
}

#[cfg(test)]
mod sync_auto_builder_tests {
    use crate::core::{AutoBuilder, ModuleMeta};
    use crate::kit::Kit;
    use std::sync::Arc;
    use thiserror::Error;

    // === Fixtures ===

    #[derive(Debug, Error)]
    #[allow(dead_code, reason = "mock error type verifies trait signature only")]
    enum MockErr {
        #[error("mock build failed: {0}")]
        Failed(String),
    }

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct SyncCap {
        value: u32,
    }

    // Macro-generated impl
    struct MacroSyncModule;
    impl_module_meta!(MacroSyncModule, "macro-sync");
    impl_auto_builder!(MacroSyncModule, Arc<SyncCap>, MockErr, |_kit| Ok(Arc::new(
        SyncCap { value: 42 }
    )));

    // Hand-written impl for comparison
    struct HandSyncModule;
    impl ModuleMeta for HandSyncModule {
        const NAME: &'static str = "macro-sync";
        fn dependencies() -> &'static [(&'static str, std::any::TypeId)] {
            &[]
        }
    }
    impl AutoBuilder for HandSyncModule {
        type Capability = Arc<SyncCap>;
        type Error = MockErr;
        fn build(_kit: &Kit) -> Result<Self::Capability, Self::Error> {
            Ok(Arc::new(SyncCap { value: 42 }))
        }
    }

    // Error-propagation fixture
    struct ErrSyncModule;
    impl_module_meta!(ErrSyncModule, "err-sync");
    impl_auto_builder!(ErrSyncModule, Arc<SyncCap>, MockErr, |_kit| Err(
        MockErr::Failed("intentional".to_string())
    ));

    // === Tests ===

    #[test]
    fn macro_sync_generates_correct_name() {
        assert_eq!(MacroSyncModule::NAME, "macro-sync");
    }

    #[test]
    fn macro_sync_generates_empty_dependencies() {
        assert!(MacroSyncModule::dependencies().is_empty());
    }

    #[test]
    fn macro_sync_capability_type_matches_hand_written() {
        assert_eq!(
            std::any::TypeId::of::<<MacroSyncModule as AutoBuilder>::Capability>(),
            std::any::TypeId::of::<<HandSyncModule as AutoBuilder>::Capability>(),
        );
    }

    #[test]
    fn macro_sync_error_type_matches_hand_written() {
        assert_eq!(
            std::any::TypeId::of::<<MacroSyncModule as AutoBuilder>::Error>(),
            std::any::TypeId::of::<<HandSyncModule as AutoBuilder>::Error>(),
        );
    }

    #[test]
    fn macro_sync_build_returns_expected_capability() {
        let kit = Kit::new();
        let cap = MacroSyncModule::build(&kit).unwrap();
        assert_eq!(cap.value, 42);
    }

    #[test]
    fn macro_sync_build_result_matches_hand_written() {
        let kit = Kit::new();
        let macro_cap = MacroSyncModule::build(&kit).unwrap();
        let hand_cap = HandSyncModule::build(&kit).unwrap();
        assert_eq!(macro_cap, hand_cap);
    }

    #[test]
    fn macro_sync_build_propagates_errors() {
        let kit = Kit::new();
        let result = ErrSyncModule::build(&kit);
        assert!(result.is_err());
    }

    #[test]
    fn macro_sync_name_equals_hand_written_name() {
        assert_eq!(MacroSyncModule::NAME, HandSyncModule::NAME);
    }

    #[test]
    fn hand_written_sync_module_dependencies_empty() {
        assert!(HandSyncModule::dependencies().is_empty());
    }
}