minfac 0.1.4

Lightweight Inversion Of Control
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
#![doc = include_str!("../README.md")]
#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;

use alloc::{boxed::Box, rc::Rc, string::String, vec::Vec};
use core::{any::type_name, cell::RefCell, fmt::Debug, marker::PhantomData};
use std::sync::OnceLock;

use abi_stable::std_types::{RArc, RVec};

use ffi::{
    FfiResult::{self, FfiErr, FfiOk},
    FfiStr,
};
use service_provider_factory::ServiceProviderFactoryBuilder;
use strategy::{Identifyable, Strategy};
use untyped::{ArcAutoFreePointer, AutoFreePointer, FromArcAutoFreePointer, UntypedFn};

mod binary_search;
mod cycle_detection;
mod ffi;
mod lifetime;
mod registrar;
mod resolvable;
mod service_provider;
mod service_provider_factory;
mod shared;
#[cfg(feature = "stable_abi")]
pub mod stable_abi;
mod strategy;
mod untyped;

pub use lifetime::LifetimeError;
pub use resolvable::Resolvable;
pub use service_provider::ServiceIterator;
pub use service_provider::ServiceProvider;
pub use service_provider::WeakServiceProvider;
pub use service_provider_factory::ServiceProviderFactory;
pub use shared::ShareInner;
pub use strategy::AnyStrategy;

use crate::{
    cycle_detection::{CycleChecker, CycleDetectionInserter},
    ffi::FfiUsizeIterator,
    resolvable::SealedResolvable,
};
pub type ServiceCollection = GenericServiceCollection<AnyStrategy>;

type InternalBuildResult<TS> = FfiResult<UntypedFn<TS>, MissingDependencyWithDependee<TS>>;

type AnyPtr = *const ();

/// Handles lifetime errors, which cannot be enforced using the type system. This is the case when:
/// - WeakServiceProvider outlives the `ServiceProvider` its created from
/// - `ServiceIterator<T>`, which owns a `WeakServiceProvider` internally, outlives its `ServiceProvider`
/// - Any shared service outlives its ServiceProvidevaluer
///
/// Ignoring errors is strongly discouraged, but doesn't cause any undefined behavior or memory leaks by the framework.
/// However, leaking context specific services often lead to memory leaks in user code which are difficult to find:
/// All shared references of a `ServiceProvider` are kept alvalueive if the result of a single `provider::get::<AllRegistered<i32>>()` call
/// is leaking it's provider. This can easily happen, if you forget to collect the results into a vector.
/// To prevent these sneaky errors, `ServiceProvider::drop()` ensures that none of it's internals are kept alive when debug_assertions are enabled.
///
/// The default implementation panics, if the std-feature is enabled (on by default). Otherwise this is a no_op
/// For custom implementations, be aware that this function could be called while panicking already.
/// In std, panic!(), when the thread is panicking already, terminates the entire program immediately.
///
/// This variable only exists, if debug_assertions are enabled
#[cfg(debug_assertions)]
pub static mut MINFAC_ERROR_HANDLER: extern "C-unwind" fn(&LifetimeError) =
    lifetime::default_error_handler;

/// Represents a query for the last registered instance of `T`
#[derive(Debug, PartialEq, Eq)]
pub struct Registered<T>(pub T);

/// Represents a query for all registered instances of Type `T`.
pub struct AllRegistered<T>(pub Box<dyn Iterator<Item = T>>);

/// Collection of constructors for different types of services. Registered constructors are never called in this state.
/// Instances can only be received by a ServiceProvider, which can be created by calling `build`
#[repr(C)]
pub struct GenericServiceCollection<TS: Strategy + 'static> {
    strategy: PhantomData<TS>,
    producer_factories: RVec<ServiceProducer<TS>>,
}

/// Alias builder is used to register services, which depend on the previous service.
/// This is especially useful, if the previous service contains an anonymous type like a lambda
pub struct AliasBuilder<'a, T: ?Sized, TS: Strategy + 'static>(
    Rc<RefCell<&'a mut GenericServiceCollection<TS>>>,
    PhantomData<T>,
);

impl<'a, T: Identifyable<TS::Id>, TS: Strategy + 'static> AliasBuilder<'a, T, TS> {
    fn new(col: &'a mut GenericServiceCollection<TS>) -> Self {
        Self(Rc::new(RefCell::new(col)), PhantomData)
    }

    /// Registers an aliased service. The returned AliasBuilder refers to the new type
    /// ``` rust
    /// let mut col = minfac::ServiceCollection::new();
    /// let mut i8alias = col.register(|| 1i8)
    ///     .alias(|a| a as i16 * 2)
    ///     .alias(|a| a as i32 * 2);
    /// let prov = col.build().unwrap();
    /// assert_eq!(Some(2i16), prov.get());
    /// assert_eq!(Some(4i32), prov.get());
    /// ```
    pub fn alias<TNew: Identifyable<TS::Id>>(
        &mut self,
        creator: fn(T) -> TNew,
    ) -> AliasBuilder<'a, TNew, TS> {
        self.0
            .borrow_mut()
            .with::<Registered<T>>()
            .register(creator);
        AliasBuilder::<_, TS>(self.0.clone(), PhantomData)
    }
}

#[repr(C)]
struct ServiceProducer<TS: Strategy + 'static> {
    identifier: TS::Id,
    factory: UntypedFnFactory<TS>,
}

impl<TS: Strategy + 'static> ServiceProducer<TS> {
    fn new<T: Identifyable<TS::Id>>(factory: UntypedFnFactory<TS>) -> Self {
        Self::new_with_type(factory, T::get_id())
    }
    fn new_with_type(factory: UntypedFnFactory<TS>, type_id: TS::Id) -> Self {
        Self {
            identifier: type_id,
            factory,
        }
    }
}

type UntypedFnFactoryCreator<TS> = extern "C" fn(
    outer_context: AutoFreePointer,
    inner_context: &mut UntypedFnFactoryContext<TS>,
) -> InternalBuildResult<TS>;

#[repr(C)]
struct UntypedFnFactory<TS: Strategy + 'static> {
    creator: UntypedFnFactoryCreator<TS>,
    context: AutoFreePointer,
}

impl<TS: Strategy + 'static> UntypedFnFactory<TS> {
    fn no_alloc(context: AnyPtr, creator: UntypedFnFactoryCreator<TS>) -> Self {
        Self {
            creator,
            context: AutoFreePointer::no_alloc(context),
        }
    }
    fn boxed<T>(input: T, creator: UntypedFnFactoryCreator<TS>) -> Self {
        Self {
            creator,
            context: AutoFreePointer::boxed(input),
        }
    }
    fn call(self, ctx: &mut UntypedFnFactoryContext<TS>) -> InternalBuildResult<TS> {
        (self.creator)(self.context, ctx)
    }
}
#[repr(C)]
struct UntypedFnFactoryContext<'a, TS: Strategy + 'static> {
    state_counter: &'a mut usize,
    final_ordered_types: &'a RVec<TS::Id>,
    cyclic_reference_candidates: CycleDetectionInserter<'a>,
}

impl<TS: Strategy + 'static> UntypedFnFactoryContext<'_, TS> {
    fn reserve_state_space(&mut self) -> usize {
        let result: usize = *self.state_counter;
        *self.state_counter += 1;
        result
    }
}

impl<TS: Strategy + 'static> Default for GenericServiceCollection<TS> {
    fn default() -> Self {
        Self::new()
    }
}

impl<TS: Strategy + 'static> GenericServiceCollection<TS> {
    /// Creates an empty ServiceCollection
    pub fn new() -> Self {
        Self {
            strategy: PhantomData,
            producer_factories: RVec::new(),
        }
    }

    /// Generate a ServiceBuilder with `T` as a dependency.
    /// An instance of T is provided as an argument to the factory fn:
    /// ``` rust
    /// use {minfac::{AllRegistered, Registered, ServiceCollection, ServiceIterator, WeakServiceProvider}};
    ///
    /// let mut collection = ServiceCollection::new();
    ///
    /// // No dependency
    /// collection.register(|| 42u8);
    /// // Single Dependency
    /// collection.with::<Registered<u8>>().register(|i: u8| i as u16);
    /// // All of a type
    /// collection.with::<AllRegistered<u8>>().register(|i: ServiceIterator<u8>| i.map(|i| i as u32).sum::<u32>());
    /// // Multiple (max tupple size == 4)
    /// collection.with::<(Registered<u8>, Registered<u16>)>().register(|(byte, short)| (byte as u64));
    /// // Nested tuples for more than 4 Dependencies
    /// collection.with::<((Registered<u8>, Registered<u16>), (Registered<u32>, Registered<u64>))>()
    ///     .register(|((byte, short), (integer, long))| (byte as u128 + short as u128 + integer as u128 + long as u128));
    /// collection.with::<WeakServiceProvider>().register(|s: WeakServiceProvider| s.get::<u16>().expect("<i16> is available as optional parameter ") as u32);
    ///
    /// let provider = collection.build().expect("Dependencies are ok");
    /// assert_eq!(Some(42 * 4), provider.get::<u128>());
    /// ```
    pub fn with<T: Resolvable<TS>>(&mut self) -> ServiceBuilder<'_, T, TS> {
        ServiceBuilder(self, PhantomData)
    }

    /// Register an instance to be resolvable
    /// If a ServiceProviderFactory is used, all ServicesProviders will clone from the same origin
    pub fn register_instance<T: Identifyable<TS::Id> + Clone + 'static + Send + Sync>(
        &mut self,
        instance: T,
    ) {
        extern "C" fn factory<
            T: Identifyable<TS::Id> + Clone + 'static + Send + Sync,
            TS: Strategy + 'static,
        >(
            outer_ctx: AutoFreePointer,
            _ctx: &mut UntypedFnFactoryContext<TS>,
        ) -> InternalBuildResult<TS> {
            extern "C" fn func<
                T: Identifyable<TS::Id> + Clone + 'static + Send + Sync,
                TS: Strategy + 'static,
            >(
                _: *const ServiceProvider<TS>,
                outer_ctx: *const AutoFreePointer,
            ) -> T {
                let outer_ctx = unsafe { &*outer_ctx as &AutoFreePointer };
                unsafe { &*(outer_ctx.get_pointer() as *const T) }.clone()
            }
            FfiOk(UntypedFn::create(func::<T, TS>, outer_ctx))
        }

        let factory = UntypedFnFactory::boxed(instance, factory::<T, TS>);
        self.producer_factories
            .push(ServiceProducer::<TS>::new::<T>(factory));
    }

    /// Registers a transient service. In contrast to `with::<Registered<T>>().register(|d| {...})`, the lambda
    /// specifies the dependencies, which might be handy if the factory-fn is defined somewhere else.
    ///
    /// ``` rust
    /// use {minfac::{AllRegistered,Registered, ServiceCollection, ServiceIterator, WeakServiceProvider}};
    ///
    /// let mut collection = ServiceCollection::new();
    /// collection.register_with(routine as fn(_) -> _);
    /// collection.register(|| 20u8);
    /// collection.register(|| 22u16);
    /// let provider = collection.build().unwrap();
    /// assert_eq!(Some(42u32), provider.get::<u32>());
    ///
    /// fn routine((Registered(byte), AllRegistered(shorts)): (Registered<u8>, AllRegistered<u16>)) -> u32 {
    ///     byte as u32 + shorts.map(|x| x as u32).sum::<u32>()
    /// }
    /// ```
    pub fn register_with<T: registrar::Registrar<TS>>(
        &mut self,
        registrar: T,
    ) -> AliasBuilder<'_, T::Item, TS> {
        registrar.register(self)
    }

    /// Registers a transient service without dependencies.
    /// To add dependencies, use `with` to generate a ServiceBuilder.
    pub fn register<T: Identifyable<TS::Id>>(
        &mut self,
        creator: fn() -> T,
    ) -> AliasBuilder<'_, T, TS> {
        self.register_with(creator)
    }

    /// Registers a shared service without dependencies.
    /// To add dependencies, use `with` to generate a ServiceBuilder.
    ///
    /// Shared services must have a reference count == 0 after dropping the ServiceProvider. If an Arc is
    /// cloned and thus kept alive, ServiceProvider::drop will panic to prevent service leaking in std.
    pub fn register_shared<T: Send + Sync + Identifyable<TS::Id> + FromArcAutoFreePointer>(
        &mut self,
        creator: fn() -> T,
    ) -> AliasBuilder<'_, T, TS> {
        type InnerContext = (usize, AnyPtr);
        extern "C" fn factory<
            T: Send + Sync + FromArcAutoFreePointer + Identifyable<TS::Id>,
            TS: Strategy + 'static,
        >(
            outer_ctx: AutoFreePointer, // No-Alloc
            ctx: &mut UntypedFnFactoryContext<TS>,
        ) -> InternalBuildResult<TS> {
            extern "C" fn func<
                T: Send + Sync + 'static + FromArcAutoFreePointer + Identifyable<TS::Id>,
                TS: Strategy + 'static,
            >(
                provider: *const ServiceProvider<TS>,
                outer_ctx: *const AutoFreePointer,
            ) -> T {
                let provider = unsafe { &*provider as &ServiceProvider<TS> };
                let outer_ctx = unsafe { &*outer_ctx as &AutoFreePointer };
                let (service_state_idx, fnptr) =
                    unsafe { &*(outer_ctx.get_pointer() as *const InnerContext) };
                let creator: fn() -> T = unsafe { core::mem::transmute(*fnptr) };
                provider.get_or_initialize_pos(*service_state_idx, creator)
            }
            let service_state_idx = ctx.reserve_state_space();
            let inner: InnerContext = (service_state_idx, outer_ctx.get_pointer());
            FfiOk(UntypedFn::create(
                func::<T, TS>,
                AutoFreePointer::boxed(inner),
            ))
        }

        let factory = UntypedFnFactory::no_alloc(creator as AnyPtr, factory::<T, TS>);
        self.producer_factories
            .push(ServiceProducer::<TS>::new::<T>(factory));

        AliasBuilder::new(self)
    }

    /// Checks, if all dependencies of registered services are available.
    /// If no errors occured, Ok(ServiceProvider) is returned.
    pub fn build(self) -> Result<ServiceProvider<TS>, BuildError<TS>> {
        let validation = self.validate_producers(Vec::new())?;
        let shared_services = (0..validation.service_states_count)
            .map(|_| OnceLock::default())
            .collect();
        let immutable_state = service_provider::ServiceProviderImmutableState::new(
            validation.types,
            validation.producers,
            RVec::new(),
        );
        Ok(ServiceProvider::<TS>::new(
            RArc::new(immutable_state),
            shared_services,
            None,
        ))
    }

    ///
    /// Returns a factory which can efficiently create ServiceProviders from
    /// ServiceCollections which are missing one dependent service T (e.g. HttpRequest, StartupConfiguration)
    /// The missing service must implement `Any` + `Clone`.
    ///
    /// Unlike shared services, this service's reference counter isn't checked to equal zero when the provider is dropped
    ///
    pub fn build_factory<T: Clone + Identifyable<TS::Id> + Send + Sync>(
        self,
    ) -> Result<ServiceProviderFactory<T, TS>, BuildError<TS>> {
        ServiceProviderFactory::<_, TS>::create(self, RVec::new())
    }

    pub fn with_parent(
        self,
        provider: impl Into<WeakServiceProvider<TS>>,
    ) -> ServiceProviderFactoryBuilder<TS> {
        ServiceProviderFactoryBuilder::create(self, provider.into())
    }

    fn validate_producers(
        self,
        mut factories: Vec<ServiceProducer<TS>>,
    ) -> Result<ProducerValidationResult<TS>, BuildError<TS>> {
        let mut service_states_count: usize = 0;
        factories.extend(self.producer_factories);

        factories.sort_by_key(|a| a.identifier);

        let types: RVec<_> = factories.iter().map(|f| f.identifier).collect();

        let mut cyclic_reference_candidates = CycleChecker::default();
        let producers = factories
            .into_iter()
            .enumerate()
            .map(|(i, x)| {
                let mut ctx = UntypedFnFactoryContext {
                    state_counter: &mut service_states_count,
                    final_ordered_types: &types,
                    cyclic_reference_candidates: cyclic_reference_candidates.create_inserter(i),
                };

                match x.factory.call(&mut ctx) {
                    FfiOk(producer) => {
                        debug_assert_eq!(&x.identifier, producer.get_result_type_id());
                        Ok(producer)
                    }
                    FfiErr(e) => Err(e.into_build_error()),
                }
            })
            .collect::<Result<_, _>>()?;

        cyclic_reference_candidates
            .ok()
            .map_err(|description| BuildError::CyclicDependency { description })?;

        Ok(ProducerValidationResult {
            producers,
            types,
            service_states_count,
        })
    }
}

pub(crate) struct ProducerValidationResult<TS: Strategy + 'static> {
    producers: RVec<UntypedFn<TS>>,
    types: RVec<TS::Id>,
    service_states_count: usize,
}

/// Possible errors when calling ServiceCollection::build() or ServiceCollection::build_factory().
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum BuildError<TS: Strategy> {
    /// `name`-format is subject of change and should only be used for debugging purpose
    #[non_exhaustive]
    MissingDependency {
        id: TS::Id,
        name: &'static str,
        dependee_name: &'static str,
    },
    /// `description`-format is subject of change and should only be used for debugging purpose
    #[non_exhaustive]
    CyclicDependency { description: String },
}

impl<TS: Strategy + Debug> core::fmt::Display for BuildError<TS> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            BuildError::MissingDependency {
                id,
                name,
                dependee_name,
            } => f.write_fmt(format_args!(
                "{dependee_name} is missing dependency {name} ({id:?})"
            )),
            BuildError::CyclicDependency { description } => {
                f.write_fmt(format_args!("detected cyclic dependency: {description}"))
            }
        }
    }
}

impl<TS: Strategy + Debug> core::error::Error for BuildError<TS> {}

#[derive(Debug)]
#[repr(C)]
pub struct MissingDependencyWithDependee<TS: Strategy> {
    id: <TS as Strategy>::Id,
    name: FfiStr<'static>,
    dependee_name: FfiStr<'static>,
}

impl<TS: Strategy + 'static> MissingDependencyWithDependee<TS> {
    fn into_build_error(self) -> BuildError<TS> {
        BuildError::MissingDependency {
            id: self.id,
            name: self.name.into(),
            dependee_name: self.dependee_name.into(),
        }
    }
}

#[derive(Debug)]
#[repr(C)]
pub struct MissingDependency<TS: Strategy> {
    id: <TS as Strategy>::Id,
    name: FfiStr<'static>,
}

impl<TS: Strategy + 'static> MissingDependency<TS> {
    fn new_missing_dependency<T: Identifyable<TS::Id>>() -> Self {
        MissingDependency {
            name: FfiStr::from(type_name::<T>()),
            id: T::get_id(),
        }
    }

    fn with_dependee<TDependee: core::any::Any>(self) -> MissingDependencyWithDependee<TS> {
        MissingDependencyWithDependee {
            id: self.id,
            name: self.name.into(),
            dependee_name: core::any::type_name::<TDependee>().into(),
        }
    }
}

#[doc(hidden)]
pub struct ServiceBuilder<'col, T: Resolvable<TS>, TS: Strategy + 'static = AnyStrategy>(
    pub &'col mut GenericServiceCollection<TS>,
    PhantomData<T>,
);

impl<TDep: Resolvable<TS> + 'static, TS: Strategy + 'static> ServiceBuilder<'_, TDep, TS> {
    pub fn register<T: Identifyable<TS::Id>>(
        &mut self,
        creator: fn(TDep::ItemPreChecked) -> T,
    ) -> AliasBuilder<'_, T, TS> {
        type InnerContext<TDep, TS> = (<TDep as SealedResolvable<TS>>::PrecheckResult, AnyPtr);
        extern "C" fn factory<
            T: Identifyable<TS::Id>,
            TDep: Resolvable<TS> + 'static,
            TS: Strategy + 'static,
        >(
            outer_ctx: AutoFreePointer, // No-Alloc
            ctx: &mut UntypedFnFactoryContext<TS>,
        ) -> InternalBuildResult<TS> {
            let key = match TDep::precheck(ctx.final_ordered_types) {
                Ok(x) => x,
                Err(x) => return FfiErr(x.with_dependee::<T>()),
            };
            let data = TDep::iter_positions(ctx.final_ordered_types);
            ctx.cyclic_reference_candidates.insert(
                type_name::<TDep::ItemPreChecked>().into(),
                FfiUsizeIterator::from_iter(data),
            );
            extern "C" fn func<
                T: Identifyable<TS::Id>,
                TDep: Resolvable<TS> + 'static,
                TS: Strategy + 'static,
            >(
                provider: *const ServiceProvider<TS>,
                outer_ctx: *const AutoFreePointer,
            ) -> T {
                let provider = unsafe { &*provider as &ServiceProvider<TS> };
                let outer_ctx = unsafe { &*outer_ctx as &AutoFreePointer };
                let (key, c): &InnerContext<TDep, TS> =
                    unsafe { &*(outer_ctx.get_pointer() as *const InnerContext<TDep, TS>) };
                let creator: fn(TDep::ItemPreChecked) -> T = unsafe { core::mem::transmute(*c) };
                let arg = TDep::resolve_prechecked(provider, key);
                creator(arg)
            }
            let inner: InnerContext<TDep, TS> = (key, outer_ctx.get_pointer());
            FfiOk(UntypedFn::create(
                func::<T, TDep, TS>,
                AutoFreePointer::boxed(inner),
            ))
        }
        let factory = UntypedFnFactory::no_alloc(creator as AnyPtr, factory::<T, TDep, TS>);
        self.0
            .producer_factories
            .push(ServiceProducer::<TS>::new::<T>(factory));

        AliasBuilder::new(self.0)
    }
    pub fn register_shared<T: Send + Sync + Identifyable<TS::Id> + FromArcAutoFreePointer>(
        &mut self,
        creator: fn(TDep::ItemPreChecked) -> T,
    ) -> AliasBuilder<'_, T, TS> {
        type InnerContext<TDep, TS> = (
            <TDep as SealedResolvable<TS>>::PrecheckResult,
            AnyPtr,
            usize,
        );
        extern "C" fn factory<
            T: Send + Sync + FromArcAutoFreePointer + Identifyable<TS::Id>,
            TDep: Resolvable<TS> + 'static,
            TS: Strategy + 'static,
        >(
            outer_ctx: AutoFreePointer,
            ctx: &mut UntypedFnFactoryContext<TS>,
        ) -> InternalBuildResult<TS> {
            let service_state_idx = ctx.reserve_state_space();
            let key = match TDep::precheck(ctx.final_ordered_types) {
                Ok(x) => x,
                Err(x) => return FfiErr(x.with_dependee::<T>()),
            };
            let data = TDep::iter_positions(ctx.final_ordered_types);
            ctx.cyclic_reference_candidates.insert(
                type_name::<TDep::ItemPreChecked>().into(),
                FfiUsizeIterator::from_iter(data),
            );
            extern "C" fn func<
                T: Send + Sync + 'static + FromArcAutoFreePointer + Identifyable<TS::Id>,
                TDep: Resolvable<TS> + 'static,
                TS: Strategy + 'static,
            >(
                provider: *const ServiceProvider<TS>,
                outer_ctx: *const AutoFreePointer,
            ) -> T {
                let provider = unsafe { &*provider as &ServiceProvider<TS> };
                let outer_ctx = unsafe { &*outer_ctx as &AutoFreePointer };
                let (key, c, service_state_idx): &InnerContext<TDep, TS> =
                    unsafe { &*(outer_ctx.get_pointer() as *const InnerContext<TDep, TS>) };
                provider.get_or_initialize_pos(*service_state_idx, || {
                    let creator: fn(TDep::ItemPreChecked) -> T =
                        unsafe { core::mem::transmute(*c) };
                    creator(TDep::resolve_prechecked(provider, key))
                })
            }
            let inner: InnerContext<TDep, TS> = (key, outer_ctx.get_pointer(), service_state_idx);
            FfiOk(UntypedFn::create(
                func::<T, TDep, TS>,
                AutoFreePointer::boxed(inner),
            ))
        }
        let factory = UntypedFnFactory::no_alloc(creator as AnyPtr, factory::<T, TDep, TS>);
        self.0
            .producer_factories
            .push(ServiceProducer::<TS>::new::<T>(factory));

        AliasBuilder::new(self.0)
    }
}

// At the time of writing, core::any::type_name_of_val was behind a nightly feature flag
#[repr(C)]
struct TypeNamed<T> {
    inner: T,
    type_name: FfiStr<'static>,
}