chassis 0.2.0

Compile-time dependency injection framework
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
#![doc(html_root_url = "https://docs.rs/chassis/0.2.0")]

//! Compile-time dependency injector.
//!
//! *Let the compiler generate your dependency injection code.*
//!
//! ## Goals
//! * No need to annotate your classes (support for third-party classes)
//! * No required usage of [`Arc`]
//! * Zero overhead: Fast as handwritten code
//!     * No use of runtime type information (provided by [`Any`] references) -
//!       At the moment relying on compiler optimization until [`min_specialization`]
//!      is stabilized.
//! * (Detect errors at compile time like missing dependencies or cyclic dependencies)
//!   * Waiting for compile time reflection or at least stabilization of
//!     [`min_specialization`], [`const_type_id`] and [`const_cmp_type_id`]
//!
//! ## Use
//!
//! Add `chassis` to your crate dependencies
//! ```toml
//! [dependencies]
//! chassis = "^0.2.0"
//! ```
//!
//! Structs will be modules that can provide dependencies with functions
//! and that itself can have dependencies.
//! *Note: Currently only associated functions are supported!*
//! ```rust,no_run
//! # pub struct Dependency1;
//! # pub struct Dependency2;
//! # pub struct Dependency3;
//! # impl Dependency3 { fn new(dep1: Dependency1, dep2: Dependency2) -> Self { Self } }
//! #[derive(Default)]
//! pub struct Module;
//!
//! #[chassis::module]
//! impl Module {
//!     pub fn provide_something(dep1: Dependency1, dep2: Dependency2) -> Dependency3 {
//!         Dependency3::new(dep1, dep2)
//!     }
//!     // ...
//! }
//! ```
//!
//! Traits will be components. For each trait an implemented component will be created.
//! The generated implementation will have a `Impl` suffix, for example `ComponentImpl`. Also a
//! `Component::new` function is created.
//! ```rust,no_run
//! # pub struct MainClass;
//! # #[derive(Default)] pub struct Module;
//! # #[chassis::module] impl Module { }
//! #[chassis::injector(modules = [Module])]
//! pub trait Component {
//!     fn resolve_main_class(&self) -> MainClass;
//! }
//! ```
//!
//! ## Example
//! ```rust,no_run
//! use std::rc::Rc;
//!
//! // define your business logic
//!
//! /// printer trait
//! pub trait Printer {
//!     fn print(&self, input: &str);
//! }
//!
//! /// a printer implementation
//! pub struct StdoutPrinter;
//! impl Printer for StdoutPrinter {
//!     fn print(&self, input: &str) {
//!         println!("{}", input);
//!     }
//! }
//!
//! /// greeter for messages
//! pub struct Greeter {
//!     message: String,
//!     printer: Rc<dyn Printer>,
//! }
//! impl Greeter {
//!     /// constructor with dependencies
//!     pub fn new(message: String, printer: Rc<dyn Printer>) -> Self {
//!         Self { message, printer }
//!     }
//!
//!     /// your business logic
//!     pub fn say_hello(&self) {
//!         self.printer.print(&self.message);
//!     }
//! }
//!
//! /// module that is parsed to create the dependency injection code
//! #[derive(Default)]
//! pub struct DemoModule;
//!
//! // use strong types when in need to distinguish
//! pub struct Message(String);
//!
//! /// Define how to create your dependencies
//! #[chassis::module]
//! impl DemoModule {
//!     pub fn provide_printer() -> Rc<dyn Printer> {
//!         Rc::new(StdoutPrinter)
//!     }
//!
//!     pub fn provide_message() -> Message {
//!         Message("Hello World".to_string())
//!     }
//!
//!     pub fn provide_greeter(
//!         message: Message,
//!         printer: Rc<dyn Printer>
//!     ) -> Greeter {
//!         Greeter::new(message.0, printer)
//!     }
//! }
//!
//! /// Define which dependencies you need.
//! ///
//! /// A struct `DemoComponentImpl` will be created for
//! /// you which implements `DemoComponent`.
//! #[chassis::injector(modules = [DemoModule])]
//! pub trait DemoComponent {
//!     /// request the to create injection code for our main class `Greeter`
//!     fn resolve_greeter(&self) -> Greeter;
//! }
//!
//! fn main() {
//!     // use generated component implementation
//!     let injector = <dyn DemoComponent>::new()
//!         .expect("DI container should be consistent");
//!
//!     // Resolve main dependency
//!     // Note: it can not fail at runtime!
//!     let greeter = injector.resolve_greeter();
//!
//!     // enjoy!
//!     greeter.say_hello();
//! }
//! ```
//!
//! ## Singletons
//!
//! Normally for every needed dependency the provider function on the module is called. This results
//! in types created multiple times. This is maybe not intended. The solution is to use a
//! `singleton` attribute. The provide method will than only called once at build time of the
//! component (call to `ComponentImpl::new`). The requirement is that the type implements the
//! [`Clone`] trait. It is recommendable to use a shared reference type like [`Rc`] or [`Arc`] for
//! singletons so that really only one instance is created.
//!
//! ### Example
//! ```rust,no_run
//! # use std::rc::Rc;
//! # trait Printer {}
//! # struct StdoutPrinter;
//! # impl Printer for StdoutPrinter {}
//! # #[derive(Default)]
//! # struct Module;
//! #[chassis::module]
//! impl Module {
//!     #[chassis(singleton)]
//!     pub fn provide_printer() -> Rc<dyn Printer> {
//!         Rc::new(StdoutPrinter)
//!     }
//! }
//! ```
//!
//! ## Limitations
//! * Lifetimes in the types are not supported (except `'static`)
//! * Generics are not handled correctly
//! * Request a reference to a registered non-reference type in a module
//!   (`&MyType` when `MyType` is provided by a module)
//! * Lazy requests (request a provider instead of concrete type)
//! * Optional requests (only get it when it exists)
//! * Multiple provider (useful for plugins)
//! * Failable module functions (return `Result` in module)
//!
//! [`Clone`]: Clone
//! [`Copy`]: Copy
//! [`Rc`]: std::rc::Rc
//! [`Arc`]: std::sync::Arc
//! [`Any`]: std::any::Any
//! [`min_specialization`]: https://github.com/rust-lang/rust/issues/68970
//! [`const_type_id`]: https://github.com/rust-lang/rust/issues/77125
//! [`const_cmp_type_id`]: https://github.com/rust-lang/rust/issues/101871

extern crate core;

use core::fmt;
use std::any::{Any, TypeId};
use std::error::Error;

pub use chassis_proc_macros::{injector, module};

mod check;

/// Internal interface between modules and injector
#[doc(hidden)]
pub mod injector {
    use std::any::Any;

    /// Interface implemented by [crate::module]
    pub trait ProvideModule {
        /// Return type of [ProvideModule::into_provider]
        type Provider: Provider;

        /// Allow introspection of this module
        fn introspect<T: Any>(visitor: &mut impl IntrospectVisitor);
        /// Turn module in a real provider
        ///
        /// This provider holds for example singleton values.
        fn into_provider(self) -> Self::Provider;
    }

    /// Provider for values.
    ///
    /// This provider holds singleton values and calls module methods.
    ///
    /// Implemented by [crate::module]
    pub trait Provider {
        fn provide<T: Any, V: Injector>(&self, v: &V) -> Option<T>;
    }

    /// Injector interface.
    ///
    /// Implemented by [crate::injector]
    pub trait Injector {
        fn provide<T: Any>(&self) -> T;
        fn introspect<T: Any>(visitor: &mut impl IntrospectVisitor);
    }

    /// Interface for introspection of injector.
    ///
    /// Implemented by a user of [Injector::introspect]
    pub trait IntrospectVisitor {
        /// Visit provider for `T` provided by module `M`.
        ///
        /// `dependencies` provides ability to iterate over dependencies of the provider.
        fn item<M: Any, T: Any, A: DependenciesAccess>(&mut self, dependencies: A);
    }

    /// Iterator over dependencies of a provider.
    ///
    /// Implemented by [crate::module]
    pub trait DependenciesAccess {
        /// Called for every dependency of provider
        fn next<V: DependenciesVisitor>(&self, visitor: &mut V);
    }

    /// Interface for introspection of a dependency.
    ///
    /// Implemented by a user of [Injector::introspect]
    pub trait DependenciesVisitor {
        /// Visit dependency on type `T`.
        fn dependency<T: Any>(&mut self);
    }
}

/// Information about a type
///
/// Useful for error messages.
pub struct TypeInfo {
    id: TypeId,
    name: &'static str,
}

impl TypeInfo {
    /// Create for type
    pub fn of<T: Any>() -> Self {
        Self {
            id: TypeId::of::<T>(),
            name: std::any::type_name::<T>(),
        }
    }

    /// Type identifier
    pub fn id(&self) -> TypeId {
        self.id
    }

    /// Type name from [std::any::type_name]
    pub fn name(&self) -> &'static str {
        self.name
    }
}

impl PartialEq for TypeInfo {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
    }
}

impl fmt::Debug for TypeInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("TypeInfo").field(&self.name).finish()
    }
}

/// Errors detected when assembling inject modules.
#[derive(Debug, PartialEq)]
pub struct AssembleErrors(Box<[AssembleError]>);

impl AssembleErrors {
    /// Create from a list of errors
    pub fn new(errors: impl Into<Box<[AssembleError]>>) -> Self {
        Self(errors.into())
    }

    /// Provide iterator to errors
    pub fn iter(&self) -> std::slice::Iter<AssembleError> {
        self.0.iter()
    }

    /// Provide errors slice
    pub fn as_slice(&self) -> &[AssembleError] {
        &self.0
    }
}

/// Error detected when assembling inject modules.
#[derive(Debug, PartialEq)]
#[allow(unused)]
pub enum AssembleError {
    /// Cyclic dependency detected
    ///
    /// An injection point requests an value that requires transitive this value.
    CyclicDependency { ty: TypeInfo },
    /// Implementation is missing
    ///
    /// It is impossible to provide value because no module provides it.
    MissingImplementation {
        /// Type for which a implementation is missing
        ty: TypeInfo,
    },
    /// Multiple implementations found for a type
    ///
    /// Multiple modules provide implementations to provide a type
    DuplicateImplementation {
        /// Type for which multiple implementations exist
        ty: TypeInfo,
    },
    /// Internal error happened
    ///
    /// Should not occur. It is possibly a bug of this library.
    InternalError(String),
}

impl fmt::Display for AssembleError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AssembleError::InternalError(message) => {
                f.write_fmt(format_args!("Internal error: {}", message))
            }
            AssembleError::CyclicDependency { ty } => f.write_fmt(format_args!(
                "Cyclic dependency when providing '{}'",
                ty.name()
            )),
            AssembleError::MissingImplementation { ty } => {
                f.write_fmt(format_args!("No provider for '{}'", ty.name()))
            }
            AssembleError::DuplicateImplementation { ty } => {
                f.write_fmt(format_args!("Multiple providers for '{}'", ty.name()))
            }
        }
    }
}

impl fmt::Display for AssembleErrors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, error) in self.0.iter().enumerate() {
            if i != 0 {
                f.write_str("\n")?;
            }
            fmt::Display::fmt(error, f)?;
        }
        Ok(())
    }
}

impl Error for AssembleErrors {}

/// Result type of factory builder
pub type AssembleResult<T> = Result<T, AssembleErrors>;

/// Internal helper functions
#[doc(hidden)]
pub mod __priv {
    use std::any::Any;

    pub use crate::check::check_factory;

    #[inline]
    #[allow(clippy::mem_replace_option_with_none)]
    pub fn safe_transmute<U: Any, T: Any>(x: U) -> T {
        let mut tmp: Option<U> = Some(x);
        std::mem::replace(
            (&mut tmp as &mut dyn Any)
                .downcast_mut::<Option<T>>()
                .unwrap(),
            None,
        )
        .unwrap()
    }
}