1use std::marker::PhantomData;
4
5use crate::builder::PassedModule;
6use crate::{BoxFuture, KernelError, ModuleBuilder, ModuleId, ProviderKey, Resolver, Scope};
7
8pub trait Module: Send + Sync + 'static {
15 fn id(&self) -> ModuleId {
18 ModuleId::of::<Self>()
19 }
20
21 fn name(&self) -> &'static str {
23 self.id().name()
24 }
25
26 fn is_configured(&self) -> bool {
28 false
29 }
30
31 fn register(&self, m: &mut ModuleBuilder);
33
34 #[doc(hidden)]
38 #[allow(private_interfaces)]
39 fn __module_type(&self, _: sealed::Witness<'_>) -> sealed::ModuleType {
40 sealed::ModuleType {
41 type_name: std::any::type_name::<Self>(),
42 }
43 }
44}
45
46mod sealed {
47 use std::marker::PhantomData;
48
49 #[derive(Clone, Copy)]
50 pub struct Witness<'a>(PhantomData<fn(&'a ()) -> &'a ()>);
51
52 impl Witness<'_> {
53 pub(super) fn new() -> Self {
54 Self(PhantomData)
55 }
56 }
57
58 #[derive(Clone, Copy)]
59 pub struct ModuleType {
60 pub(super) type_name: &'static str,
61 }
62}
63
64impl Module for Box<dyn Module> {
65 fn id(&self) -> ModuleId {
66 (**self).id()
67 }
68
69 fn name(&self) -> &'static str {
70 (**self).name()
71 }
72
73 fn is_configured(&self) -> bool {
74 (**self).is_configured()
75 }
76
77 fn register(&self, m: &mut ModuleBuilder) {
78 (**self).register(m);
79 }
80
81 #[allow(private_interfaces)]
82 fn __module_type(&self, witness: sealed::Witness<'_>) -> sealed::ModuleType {
83 (**self).__module_type(witness)
84 }
85}
86
87impl Module for std::pin::Pin<Box<dyn Module>> {
88 fn id(&self) -> ModuleId {
89 self.as_ref().get_ref().id()
90 }
91
92 fn name(&self) -> &'static str {
93 self.as_ref().get_ref().name()
94 }
95
96 fn is_configured(&self) -> bool {
97 self.as_ref().get_ref().is_configured()
98 }
99
100 fn register(&self, m: &mut ModuleBuilder) {
101 self.as_ref().get_ref().register(m);
102 }
103
104 #[allow(private_interfaces)]
105 fn __module_type(&self, witness: sealed::Witness<'_>) -> sealed::ModuleType {
106 self.as_ref().get_ref().__module_type(witness)
107 }
108}
109
110pub(crate) fn resolved_type_name(module: &dyn Module) -> &'static str {
113 module.__module_type(sealed::Witness::new()).type_name
114}
115
116pub struct ConfiguredModule<M, O> {
164 options: Option<O>,
165 register: fn(&mut ModuleBuilder, Option<O>),
166 module: PhantomData<fn() -> M>,
167}
168
169impl<M, O> ConfiguredModule<M, O> {
170 pub fn for_root(options: O, register: fn(&mut ModuleBuilder, Option<O>)) -> Self {
173 Self {
174 options: Some(options),
175 register,
176 module: PhantomData,
177 }
178 }
179
180 pub fn from_config(register: fn(&mut ModuleBuilder, Option<O>)) -> Self {
182 Self {
183 options: None,
184 register,
185 module: PhantomData,
186 }
187 }
188}
189
190impl<M: 'static, O: Clone + Send + Sync + 'static> Module for ConfiguredModule<M, O> {
191 fn id(&self) -> ModuleId {
192 ModuleId::of::<M>()
193 }
194
195 fn is_configured(&self) -> bool {
196 true
197 }
198
199 fn register(&self, m: &mut ModuleBuilder) {
200 if self.options.is_some() {
201 m.contribute(CodeConfigured {
202 module: ModuleId::of::<M>().name(),
203 });
204 }
205 (self.register)(m, self.options.clone());
206 }
207}
208
209#[doc(hidden)]
273#[macro_export]
274macro_rules! configured_module {
275 (
276 $(#[$meta:meta])*
277 $vis:vis $name:ident,
278 $module:ty,
279 $options:ty,
280 $register:expr $(,)?
281 ) => {
282 #[allow(missing_docs)]
283 $(#[$meta])*
284 $vis struct $name($crate::ConfiguredModule<$module, $options>);
285
286 impl $name {
287 #[allow(dead_code)]
288 pub(crate) fn for_root(options: $options) -> Self {
289 Self($crate::ConfiguredModule::for_root(options, $register))
290 }
291
292 #[allow(dead_code)]
293 pub(crate) fn from_config() -> Self {
294 Self($crate::ConfiguredModule::from_config($register))
295 }
296 }
297
298 impl $crate::Module for $name {
299 fn id(&self) -> $crate::ModuleId {
300 $crate::Module::id(&self.0)
301 }
302
303 fn is_configured(&self) -> bool {
304 $crate::Module::is_configured(&self.0)
305 }
306
307 fn register(&self, m: &mut $crate::ModuleBuilder) {
308 $crate::Module::register(&self.0, m);
309 }
310 }
311 };
312}
313
314mod sample {
315 pub struct PlainModule;
335
336 impl PlainModule {
337 pub fn from_config() -> ConfiguredPlainModule {
339 ConfiguredPlainModule::from_config()
340 }
341 }
342
343 impl crate::Module for PlainModule {
344 fn register(&self, _: &mut crate::ModuleBuilder) {}
345 }
346
347 fn register(_: &mut crate::ModuleBuilder, _: Option<()>) {}
348
349 crate::configured_module!(pub ConfiguredPlainModule, PlainModule, (), register);
350}
351
352pub use sample::{ConfiguredPlainModule, PlainModule};
353
354#[derive(Clone, Copy, Debug, PartialEq, Eq)]
359pub struct CodeConfigured {
360 module: &'static str,
361}
362
363impl CodeConfigured {
364 pub fn module(&self) -> &'static str {
366 self.module
367 }
368}
369
370pub trait Injectable: Sized + Send + Sync + 'static {
372 fn scope() -> Scope {
374 Scope::Singleton
375 }
376
377 fn dependencies() -> Vec<ProviderKey> {
380 Vec::new()
381 }
382
383 fn construct(r: Resolver) -> BoxFuture<'static, Result<Self, KernelError>>;
385}
386
387pub trait IntoModules {
390 fn into_modules(self) -> Vec<Box<dyn Module>>;
392
393 #[doc(hidden)]
398 fn into_passed_modules(self) -> Vec<PassedModule>
399 where
400 Self: Sized,
401 {
402 self.into_modules()
403 .into_iter()
404 .map(PassedModule::boxed)
405 .collect()
406 }
407}
408
409impl<M: Module> IntoModules for M {
410 fn into_modules(self) -> Vec<Box<dyn Module>> {
411 vec![Box::new(self)]
412 }
413
414 fn into_passed_modules(self) -> Vec<PassedModule> {
415 vec![PassedModule::of(self)]
416 }
417}
418
419impl IntoModules for Vec<Box<dyn Module>> {
420 fn into_modules(self) -> Vec<Box<dyn Module>> {
421 self
422 }
423}
424
425macro_rules! tuple_into_modules {
426 ($($name:ident),+) => {
427 impl<$($name: Module),+> IntoModules for ($($name,)+) {
428 #[allow(non_snake_case)]
429 fn into_modules(self) -> Vec<Box<dyn Module>> {
430 let ($($name,)+) = self;
431 vec![$(Box::new($name) as Box<dyn Module>),+]
432 }
433
434 #[allow(non_snake_case)]
435 fn into_passed_modules(self) -> Vec<PassedModule> {
436 let ($($name,)+) = self;
437 vec![$(PassedModule::of($name)),+]
438 }
439 }
440 };
441}
442
443tuple_into_modules!(A);
444tuple_into_modules!(A, B);
445tuple_into_modules!(A, B, C);
446tuple_into_modules!(A, B, C, D);
447tuple_into_modules!(A, B, C, D, E);
448tuple_into_modules!(A, B, C, D, E, F);
449tuple_into_modules!(A, B, C, D, E, F, G);
450tuple_into_modules!(A, B, C, D, E, F, G, H);
451tuple_into_modules!(A, B, C, D, E, F, G, H, I);
452tuple_into_modules!(A, B, C, D, E, F, G, H, I, J);
453tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K);
454tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L);
455tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M);
456tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
457tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
458tuple_into_modules!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
459
460#[cfg(test)]
461mod tests {
462 use super::*;
463 use crate::Navree;
464 use crate::graph::Graph;
465 use crate::plugin::{FIRST_PARTY, PluginInfo, is_first_party};
466
467 mod navree_flags_probe {
469 use crate::{Module, ModuleBuilder};
470
471 #[derive(Clone)]
472 pub struct FlagsOptions(pub &'static str);
473
474 pub struct FlagsModule;
475
476 impl FlagsModule {
477 pub fn for_root(options: FlagsOptions) -> impl Module {
478 ConfiguredFlagsModule::for_root(options)
479 }
480
481 pub fn from_config() -> impl Module {
482 ConfiguredFlagsModule::from_config()
483 }
484 }
485
486 impl Module for FlagsModule {
487 fn register(&self, m: &mut ModuleBuilder) {
488 register(m, None);
489 }
490 }
491
492 crate::configured_module!(ConfiguredFlagsModule, FlagsModule, FlagsOptions, register);
493
494 fn register(m: &mut ModuleBuilder, options: Option<FlagsOptions>) {
495 let city = options.map_or("from_config", |options| options.0);
496 m.contribute(city);
497 }
498 }
499
500 #[test]
501 fn a_configured_form_written_in_a_crate_is_a_type_of_that_crate_with_the_modules_id() {
502 use navree_flags_probe::{FlagsModule, FlagsOptions};
503
504 let plain_id = ModuleId::of::<FlagsModule>();
505 let krate = concat!(module_path!(), "::navree_flags_probe");
506 let prefix = format!("{krate}::");
507
508 let for_root = FlagsModule::for_root(FlagsOptions("Ludhiana"));
509 assert_eq!(for_root.id(), plain_id);
510 assert_eq!(for_root.name(), "FlagsModule");
511 assert!(for_root.is_configured());
512 let passed_root = PassedModule::of(for_root);
513 assert!(
514 passed_root.type_name.starts_with(prefix.as_str()),
515 "{}",
516 passed_root.type_name
517 );
518 assert!(
519 !passed_root.type_name.contains('<'),
520 "{}",
521 passed_root.type_name
522 );
523
524 let graph = Graph::build_passed(&[passed_root], &[]).expect("valid");
525 let m = graph.module_of(plain_id).expect("in the graph");
526 let code_configured: Vec<&str> = graph.modules[m]
527 .contributions
528 .iter()
529 .filter_map(|c| c.value.downcast_ref::<CodeConfigured>())
530 .map(|c| c.module())
531 .collect();
532 assert_eq!(code_configured, ["FlagsModule"]);
533 let cities: Vec<&str> = graph.modules[m]
534 .contributions
535 .iter()
536 .filter_map(|c| c.value.downcast_ref::<&'static str>().copied())
537 .collect();
538 assert_eq!(cities, ["Ludhiana"]);
539
540 let from_config = FlagsModule::from_config();
541 assert_eq!(from_config.id(), plain_id);
542 assert!(from_config.is_configured());
543 let passed_config = PassedModule::of(from_config);
544 assert!(
545 passed_config.type_name.starts_with(prefix.as_str()),
546 "{}",
547 passed_config.type_name
548 );
549 let listed = [("navree-flags", krate)];
550 let info = PluginInfo::new("navree-flags", krate, "flags", "1.4.0");
551 assert!(is_first_party(
552 &info,
553 &[passed_config.type_name],
554 &listed,
555 "1.4.0"
556 ));
557
558 let graph = Graph::build_passed(&[passed_config], &[]).expect("valid");
559 let m = graph.module_of(plain_id).expect("in the graph");
560 let has_code_configured = graph.modules[m]
561 .contributions
562 .iter()
563 .any(|c| c.value.downcast_ref::<CodeConfigured>().is_some());
564 assert!(!has_code_configured);
565 let cities: Vec<&str> = graph.modules[m]
566 .contributions
567 .iter()
568 .filter_map(|c| c.value.downcast_ref::<&'static str>().copied())
569 .collect();
570 assert_eq!(cities, ["from_config"]);
571 }
572
573 #[test]
574 fn the_kernels_own_configured_wrapper_never_makes_a_plugin_first_party() {
575 use navree_flags_probe::{FlagsModule, FlagsOptions};
576
577 let version = env!("CARGO_PKG_VERSION");
578 let krate = concat!(module_path!(), "::navree_flags_probe");
579 let listed = [("navree-flags", krate)];
580 let info = PluginInfo::new("navree-flags", krate, "flags", version);
581
582 let for_root = PassedModule::of(ConfiguredModule::<FlagsModule, FlagsOptions>::for_root(
583 FlagsOptions("Ludhiana"),
584 |_, _| {},
585 ));
586 let from_config = PassedModule::of(
587 ConfiguredModule::<FlagsModule, FlagsOptions>::from_config(|_, _| {}),
588 );
589 for wrapped in [&for_root, &from_config] {
590 assert!(
591 !is_first_party(&info, &[wrapped.type_name], &listed, version),
592 "{}",
593 wrapped.type_name
594 );
595 }
596
597 let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", version);
601 let kernel_wrapped = "navree_kernel::module::ConfiguredModule<navree_flags::module::FlagsModule, navree_flags::options::FlagsOptions>";
602 assert!(!is_first_party(
603 &flags,
604 &[kernel_wrapped],
605 FIRST_PARTY,
606 version
607 ));
608
609 let mut graph =
610 Graph::build_passed(&[PassedModule::of(PlainModule)], &[]).expect("a plain module");
611 let m = graph
612 .module_of(ModuleId::of::<PlainModule>())
613 .expect("in the graph");
614 graph.modules[m].type_name = kernel_wrapped;
615 graph.modules[m].plugin = Some(flags);
616 let mut errors = Vec::new();
617 graph.check_plugins(&mut errors);
618 assert!(
619 matches!(
620 errors.as_slice(),
621 [KernelError::NamespaceReserved {
622 plugin: "navree-flags",
623 namespace: "flags",
624 }]
625 ),
626 "{errors:?}"
627 );
628 assert!(!graph.first_party.contains("navree-flags"));
629
630 let claimed = ConfiguredModule::<FlagsModule, ()>::from_config(|m, _| {
631 m.plugin(PluginInfo::new(
632 "navree-flags",
633 "navree_kernel",
634 "flags",
635 env!("CARGO_PKG_VERSION"),
636 ));
637 });
638 let refused = Navree::app()
639 .module(claimed)
640 .validate()
641 .expect_err("the kernel's own wrapper is never first-party");
642 assert!(
643 matches!(
644 refused.0.as_slice(),
645 [KernelError::NamespaceReserved {
646 plugin: "navree-flags",
647 namespace: "flags",
648 }]
649 ),
650 "{refused:?}"
651 );
652 }
653}