clients 0.1.0

Concrete-struct dependency injection for Rust using function pointers instead of trait objects
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//! Concrete dependency injection built from plain structs and function pointers.
//!
//! `clients` models each dependency as a concrete, cloneable value type instead of a
//! trait object. The usual flow is:
//!
//! - declare a dependency client with [`client!`]
//! - resolve dependency methods in free functions with [`deps!`]
//! - override methods in tests with [`test_deps!`]
//! - inject whole dependency values into structs via [`Depends`]
//!
//! The design intentionally favors low ceremony. Live implementations are plain
//! non-capturing closures or function items, and test overrides swap those same
//! function pointers in scoped layers.

extern crate self as clients;

use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::mem::{self, MaybeUninit};
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{OnceLock, RwLock};
use std::thread;

pub use clients_macros::{Depends, client};

mod builtins;

pub use builtins::*;

/// Internal storage for one override layer keyed by concrete dependency type.
type DependencyMap = HashMap<TypeId, Box<dyn Any + Send + Sync>>;

/// A boxed, sendable future used by async dependency methods.
///
/// Async methods declared with [`client!`] are stored as raw function pointers
/// returning this alias so that the generated client structs remain concrete and
/// copyable.
///
/// ```
/// let future: clients::BoxFuture<u64> = clients::boxed(async { 123 });
/// drop(future);
/// ```
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;

/// Common error type used by dependency-based APIs in examples and hand-written
/// live implementations.
///
/// The crate does not force users to return this type, but it is convenient
/// when a dependency wants to surface "missing implementation" or "test-only
/// placeholder" failures without introducing a separate error enum.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DependencyError {
    /// Indicates that a dependency path has no live implementation and no
    /// active override.
    Missing(&'static str),
    /// Carries a borrowed static error message.
    Message(&'static str),
    /// Carries an owned error message.
    Owned(String),
}

impl DependencyError {
    /// Creates an error describing a missing dependency implementation.
    ///
    /// ```
    /// let error = clients::DependencyError::missing("clock.now");
    /// assert_eq!(error.to_string(), "missing dependency implementation for `clock.now`");
    /// ```
    pub const fn missing(path: &'static str) -> Self {
        Self::Missing(path)
    }

    /// Creates an error from a borrowed static message.
    ///
    /// ```
    /// let error = clients::DependencyError::message("boom");
    /// assert_eq!(error.to_string(), "boom");
    /// ```
    pub const fn message(message: &'static str) -> Self {
        Self::Message(message)
    }
}

impl fmt::Display for DependencyError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Missing(path) => {
                write!(formatter, "missing dependency implementation for `{path}`")
            }
            Self::Message(message) => formatter.write_str(message),
            Self::Owned(message) => formatter.write_str(message),
        }
    }
}

impl std::error::Error for DependencyError {}

/// A concrete dependency value that can provide its live implementation.
///
/// This trait is implemented automatically for types generated by [`client!`].
/// The runtime resolves values by type through [`get`], first consulting any
/// active override layers and then falling back to [`Dependency::live`].
pub trait Dependency: Clone + Send + Sync + 'static {
    /// Returns the live value for this dependency type.
    fn live() -> Self;
}

/// Boxes a future into [`BoxFuture`].
///
/// This is mostly useful for hand-written async helpers and for the internal
/// fallback implementations generated by [`client!`].
///
/// ```
/// let future = clients::boxed(async { String::from("hello") });
/// let future: clients::BoxFuture<String> = future;
/// drop(future);
/// ```
pub fn boxed<Fut>(future: Fut) -> BoxFuture<Fut::Output>
where
    Fut: Future + Send + 'static,
{
    Box::pin(future)
}

/// Resolves the current dependency value for `D`.
///
/// Resolution first checks the active override stack, using the most recent
/// matching override if one exists. When no override is present, the runtime
/// falls back to [`Dependency::live`].
///
/// ```
/// mod demo {
///     use clients::client;
///
///     client! {
///         pub struct Clock as clock {
///             pub fn now_millis() -> u64 = || 1234;
///         }
///     }
/// }
///
/// assert_eq!(clients::get::<demo::Clock>().now_millis(), 1234);
/// ```
pub fn get<D>() -> D
where
    D: Dependency,
{
    current_override::<D>().unwrap_or_else(D::live)
}

/// Panics with a consistent message for an unimplemented dependency path.
///
/// Generated clients use this for methods that were declared without a live
/// implementation. It is public so advanced callers can reuse the same panic
/// shape when constructing clients manually.
///
/// ```should_panic(expected = "dependency `demo.missing` has no live implementation and no active test override")
/// clients::unimplemented_dependency("demo.missing");
/// ```
pub fn unimplemented_dependency(path: &'static str) -> ! {
    panic!(
        "dependency `{path}` has no live implementation and no active test override; add `= ...` in `client!` or install a `test_deps!` override"
    )
}

/// Returns the global override stack shared by all dependency lookups.
fn active_overrides() -> &'static RwLock<Vec<DependencyMap>> {
    static ACTIVE_OVERRIDES: OnceLock<RwLock<Vec<DependencyMap>>> = OnceLock::new();
    ACTIVE_OVERRIDES.get_or_init(|| RwLock::new(Vec::new()))
}

/// Looks for the most recent override of dependency type `D`.
fn current_override<D>() -> Option<D>
where
    D: Dependency,
{
    let overrides = active_overrides()
        .read()
        .expect("dependency override lock poisoned");
    for layer in overrides.iter().rev() {
        if let Some(value) = layer.get(&TypeId::of::<D>()) {
            let dependency = value
                .downcast_ref::<D>()
                .expect("dependency override stored with the wrong type");
            return Some(dependency.clone());
        }
    }
    None
}

/// Pushes a new override layer onto the global stack.
fn push_overrides(entries: DependencyMap) {
    active_overrides()
        .write()
        .expect("dependency override lock poisoned")
        .push(entries);
}

/// Pops the most recent override layer from the global stack.
fn pop_overrides() {
    let popped = active_overrides()
        .write()
        .expect("dependency override lock poisoned")
        .pop();

    assert!(popped.is_some(), "dependency override stack underflow");
}

/// Returns the global lock used to serialize `enter_test` scopes.
fn test_scope_lock() -> &'static AtomicBool {
    static TEST_SCOPE_LOCK: AtomicBool = AtomicBool::new(false);
    &TEST_SCOPE_LOCK
}

/// Acquires the process-wide test scope lock.
///
/// `test_deps!` and [`OverrideBuilder::enter_test`] use this to keep tests from
/// trampling shared global override state when they run in parallel.
fn acquire_test_lock() {
    while test_scope_lock()
        .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
        .is_err()
    {
        thread::yield_now();
    }
}

/// Releases the process-wide test scope lock.
fn release_test_lock() {
    test_scope_lock().store(false, Ordering::Release);
}

/// Builds one scoped layer of dependency overrides.
///
/// Most tests should prefer [`test_deps!`] because it is the smallest API, but
/// `OverrideBuilder` is useful when you want to replace a whole client at once
/// or derive a new client from the currently resolved one.
#[derive(Default)]
pub struct OverrideBuilder {
    entries: DependencyMap,
}

impl OverrideBuilder {
    /// Creates an empty override builder.
    ///
    /// ```
    /// let _builder = clients::OverrideBuilder::new();
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Replaces the entire dependency value for type `D`.
    ///
    /// This is the lowest-level override API and is useful when you want to
    /// construct a whole client value manually.
    ///
    /// ```
    /// mod demo {
    ///     use clients::{OverrideBuilder, client, erase_sync_0, get};
    ///
    ///     client! {
    ///         pub struct Clock as clock {
    ///             pub fn now_millis() -> u64 = || 100;
    ///         }
    ///     }
    ///
    ///     pub fn run() {
    ///         let _test_scope = OverrideBuilder::new().enter_test();
    ///         let mut builder = OverrideBuilder::new();
    ///         builder.set(Clock {
    ///             now_millis: erase_sync_0(|| 1234),
    ///         });
    ///         let _guard = builder.enter();
    ///
    ///         assert_eq!(get::<Clock>().now_millis(), 1234);
    ///     }
    /// }
    ///
    /// demo::run();
    /// ```
    pub fn set<D>(&mut self, dependency: D) -> &mut Self
    where
        D: Dependency,
    {
        self.entries.insert(
            TypeId::of::<D>(),
            Box::new(dependency) as Box<dyn Any + Send + Sync>,
        );
        self
    }

    /// Updates dependency type `D` by starting from either the pending override
    /// already in this builder or the currently resolved dependency value.
    ///
    /// This is especially useful for changing only one function pointer on a
    /// larger client while preserving the rest of the existing behavior.
    ///
    /// ```
    /// mod demo {
    ///     use clients::{OverrideBuilder, client, erase_sync_0, get};
    ///
    ///     client! {
    ///         pub struct Clock as clock {
    ///             pub fn now_millis() -> u64 = || 100;
    ///             pub fn timezone() -> String = || "UTC".to_string();
    ///         }
    ///     }
    ///
    ///     pub fn run() {
    ///         let _test_scope = OverrideBuilder::new().enter_test();
    ///         let mut builder = OverrideBuilder::new();
    ///         builder.update::<Clock, _>(|mut clock| {
    ///             clock.now_millis = erase_sync_0(|| 123);
    ///             clock
    ///         });
    ///         let _guard = builder.enter();
    ///
    ///         assert_eq!(get::<Clock>().now_millis(), 123);
    ///         assert_eq!(get::<Clock>().timezone(), "UTC");
    ///     }
    /// }
    ///
    /// demo::run();
    /// ```
    pub fn update<D, F>(&mut self, update: F) -> &mut Self
    where
        D: Dependency,
        F: FnOnce(D) -> D,
    {
        let current = self.take_or_resolve::<D>();
        self.set(update(current))
    }

    /// Enters a scoped override layer without acquiring the process-wide test
    /// lock.
    ///
    /// This is appropriate when you already control access to global override
    /// state or when you are nesting inside an existing [`enter_test`](Self::enter_test)
    /// scope.
    ///
    /// ```
    /// mod demo {
    ///     use clients::{OverrideBuilder, client, erase_sync_0, get};
    ///
    ///     client! {
    ///         pub struct Clock as clock {
    ///             pub fn now_millis() -> u64 = || 100;
    ///         }
    ///     }
    ///
    ///     pub fn run() {
    ///         let _test_scope = OverrideBuilder::new().enter_test();
    ///         let mut builder = OverrideBuilder::new();
    ///         builder.set(Clock {
    ///             now_millis: erase_sync_0(|| 200),
    ///         });
    ///         let _guard = builder.enter();
    ///
    ///         assert_eq!(get::<Clock>().now_millis(), 200);
    ///     }
    /// }
    ///
    /// demo::run();
    /// ```
    pub fn enter(self) -> OverrideGuard {
        push_overrides(self.entries);
        OverrideGuard {
            release_test_lock: false,
        }
    }

    /// Enters a scoped override layer and serializes with other test scopes in
    /// the same process.
    ///
    /// This is the primitive used by [`test_deps!`], and it is the safest API
    /// to reach for in tests.
    ///
    /// ```
    /// mod demo {
    ///     use clients::{OverrideBuilder, client, erase_sync_0, get};
    ///
    ///     client! {
    ///         pub struct Clock as clock {
    ///             pub fn now_millis() -> u64 = || 100;
    ///         }
    ///     }
    ///
    ///     pub fn run() {
    ///         let mut builder = OverrideBuilder::new();
    ///         builder.set(Clock {
    ///             now_millis: erase_sync_0(|| 300),
    ///         });
    ///         let _guard = builder.enter_test();
    ///
    ///         assert_eq!(get::<Clock>().now_millis(), 300);
    ///     }
    /// }
    ///
    /// demo::run();
    /// ```
    pub fn enter_test(self) -> OverrideGuard {
        acquire_test_lock();
        push_overrides(self.entries);
        OverrideGuard {
            release_test_lock: true,
        }
    }

    /// Consumes a pending builder entry for `D` or resolves the current value
    /// from the global dependency system when no entry has been staged yet.
    fn take_or_resolve<D>(&mut self) -> D
    where
        D: Dependency,
    {
        if let Some(entry) = self.entries.remove(&TypeId::of::<D>()) {
            *entry
                .downcast::<D>()
                .expect("dependency override stored with the wrong type")
        } else {
            get::<D>()
        }
    }
}

/// RAII guard that keeps an override scope active until dropped.
///
/// Guards are returned by [`OverrideBuilder::enter`] and
/// [`OverrideBuilder::enter_test`]. Dropping the guard removes that override
/// layer and, for test scopes, releases the serialization lock.
#[must_use = "keep the guard alive for as long as the dependency overrides should remain active"]
pub struct OverrideGuard {
    release_test_lock: bool,
}

impl Drop for OverrideGuard {
    fn drop(&mut self) {
        pop_overrides();
        if self.release_test_lock {
            release_test_lock();
        }
    }
}

/// Verifies that a closure is non-capturing before it is erased to a raw
/// function pointer.
fn assert_non_capturing<F>() {
    assert!(
        mem::size_of::<F>() == 0,
        "dependency implementations must be non-capturing closures or function items"
    );
}

/// Reconstructs a zero-sized closure value after type erasure.
///
/// This is safe for the crate's use because [`assert_non_capturing`] guarantees
/// the closure is zero-sized before we reach this point.
///
/// # Safety
///
/// `F` must be a valid, inhabited zero-sized closure or function-item type.
/// The eraser entry points enforce that by calling [`assert_non_capturing`]
/// before routing execution through this helper.
#[allow(clippy::uninit_assumed_init)]
unsafe fn resurrect_zst<F>() -> F {
    debug_assert_eq!(mem::size_of::<F>(), 0);
    unsafe { MaybeUninit::<F>::uninit().assume_init() }
}

/// Generates the family of closure-to-function-pointer erasers used by the
/// runtime and by code expanded from [`client!`].
///
/// Each generated function:
///
/// 1. rejects capturing closures with [`assert_non_capturing`]
/// 2. emits a monomorphized trampoline for one specific arity
/// 3. reconstructs the zero-sized closure type inside that trampoline
/// 4. returns the trampoline as a plain raw function pointer
///
/// This is the key mechanism that lets generated clients store `fn(...) -> R`
/// fields instead of trait objects while still accepting inline closure syntax.
macro_rules! define_erasers {
    ($( $sync_name:ident, $async_name:ident, ( $( $arg:ident : $arg_ty:ident ),* ) );* $(;)?) => {
        $(
            #[doc = "Internal helper that erases a non-capturing synchronous closure into a raw function pointer."]
            #[doc(hidden)]
            pub fn $sync_name<F, R $(, $arg_ty)*>(_: F) -> fn($( $arg_ty ),*) -> R
            where
                F: Fn($( $arg_ty ),*) -> R + Copy + 'static,
            {
                assert_non_capturing::<F>();

                fn trampoline<F, R $(, $arg_ty)*>($( $arg : $arg_ty ),*) -> R
                where
                    F: Fn($( $arg_ty ),*) -> R + Copy + 'static,
                {
                    let function: F = unsafe { resurrect_zst() };
                    function($( $arg ),*)
                }

                trampoline::<F, R $(, $arg_ty)*>
            }

            #[doc = "Internal helper that erases a non-capturing asynchronous closure into a raw function pointer returning `BoxFuture`."]
            #[doc(hidden)]
            pub fn $async_name<F, Fut, R $(, $arg_ty)*>(_: F) -> fn($( $arg_ty ),*) -> BoxFuture<R>
            where
                F: Fn($( $arg_ty ),*) -> Fut + Copy + 'static,
                Fut: Future<Output = R> + Send + 'static,
            {
                assert_non_capturing::<F>();

                fn trampoline<F, Fut, R $(, $arg_ty)*>($( $arg : $arg_ty ),*) -> BoxFuture<R>
                where
                    F: Fn($( $arg_ty ),*) -> Fut + Copy + 'static,
                    Fut: Future<Output = R> + Send + 'static,
                {
                    let function: F = unsafe { resurrect_zst() };
                    Box::pin(function($( $arg ),*))
                }

                trampoline::<F, Fut, R $(, $arg_ty)*>
            }
        )*
    };
}

define_erasers! {
    erase_sync_0, erase_async_0, ();
    erase_sync_1, erase_async_1, (arg0: A0);
    erase_sync_2, erase_async_2, (arg0: A0, arg1: A1);
    erase_sync_3, erase_async_3, (arg0: A0, arg1: A1, arg2: A2);
    erase_sync_4, erase_async_4, (arg0: A0, arg1: A1, arg2: A2, arg3: A3);
}

/// Internal helper macro that maps an inline synchronous implementation to the
/// correct closure eraser based on arity.
#[doc(hidden)]
#[macro_export]
macro_rules! __dep_to_sync_fn {
    (() => $implementation:expr) => {
        $crate::erase_sync_0($implementation)
    };
    (($arg0:ident : $arg0_ty:ty) => $implementation:expr) => {
        $crate::erase_sync_1($implementation)
    };
    (($arg0:ident : $arg0_ty:ty, $arg1:ident : $arg1_ty:ty) => $implementation:expr) => {
        $crate::erase_sync_2($implementation)
    };
    (($arg0:ident : $arg0_ty:ty, $arg1:ident : $arg1_ty:ty, $arg2:ident : $arg2_ty:ty) => $implementation:expr) => {
        $crate::erase_sync_3($implementation)
    };
    (($arg0:ident : $arg0_ty:ty, $arg1:ident : $arg1_ty:ty, $arg2:ident : $arg2_ty:ty, $arg3:ident : $arg3_ty:ty) => $implementation:expr) => {
        $crate::erase_sync_4($implementation)
    };
}

/// Internal helper macro that maps an inline asynchronous implementation to the
/// correct closure eraser based on arity.
#[doc(hidden)]
#[macro_export]
macro_rules! __dep_to_async_fn {
    (() => $implementation:expr) => {
        $crate::erase_async_0($implementation)
    };
    (($arg0:ident : $arg0_ty:ty) => $implementation:expr) => {
        $crate::erase_async_1($implementation)
    };
    (($arg0:ident : $arg0_ty:ty, $arg1:ident : $arg1_ty:ty) => $implementation:expr) => {
        $crate::erase_async_2($implementation)
    };
    (($arg0:ident : $arg0_ty:ty, $arg1:ident : $arg1_ty:ty, $arg2:ident : $arg2_ty:ty) => $implementation:expr) => {
        $crate::erase_async_3($implementation)
    };
    (($arg0:ident : $arg0_ty:ty, $arg1:ident : $arg1_ty:ty, $arg2:ident : $arg2_ty:ty, $arg3:ident : $arg3_ty:ty) => $implementation:expr) => {
        $crate::erase_async_4($implementation)
    };
}

/// Binds dependency methods from generated helper modules into local variables.
///
/// This macro is designed for free functions and small local scopes where you
/// want direct access to dependency behavior without threading a client value as
/// a parameter.
///
/// ```
/// mod demo {
///     use clients::{DependencyError, client, deps};
///
///     client! {
///         pub struct Clock as clock {
///             pub fn now_millis() -> u64 = || 1234;
///         }
///     }
///
///     pub fn read_now() -> Result<String, DependencyError> {
///         deps! {
///             now = clock.now_millis,
///         }
///
///         Ok(now().to_string())
///     }
/// }
///
/// assert_eq!(demo::read_now().unwrap(), "1234");
/// ```
#[macro_export]
macro_rules! deps {
    () => {};
    ($binding:ident = $client:ident.$method:ident $(, $($rest:tt)*)?) => {
        let $binding = $client::$method::get();
        $crate::deps!($($($rest)*)?);
    };
}

/// Installs one or more dependency overrides for the remainder of the current
/// scope, keeping the test body flat and unindented.
///
/// Each override targets a specific generated method helper module. The macro
/// expands to an [`OverrideGuard`] binding that stays alive until the end of the
/// current scope, so the usual pattern is to place `test_deps!` at the top of a
/// test and then write the test body normally below it.
///
/// ```
/// mod demo {
///     use clients::{client, get};
///
///     client! {
///         pub struct Clock as clock {
///             pub fn now_millis() -> u64 = || 0;
///         }
///     }
///
///     pub fn read_now() -> u64 {
///         get::<Clock>().now_millis()
///     }
/// }
///
/// use demo::*;
/// use clients::test_deps;
///
/// test_deps! {
///     clock.now_millis => || 1234,
/// }
///
/// assert_eq!(read_now(), 1234);
/// ```
#[macro_export]
macro_rules! test_deps {
    () => {
        let __dep_test_scope_guard = $crate::OverrideBuilder::new().enter_test();
        let _ = &__dep_test_scope_guard;
    };
    ($client:ident.$method:ident => $implementation:expr $(, $($rest:tt)*)?) => {
        let mut __dep_builder = $crate::OverrideBuilder::new();
        $client::$method::override_with(&mut __dep_builder, $implementation);
        $(
            $crate::__dep_test_deps_more!(__dep_builder, $($rest)*);
        )?
        let __dep_test_scope_guard = __dep_builder.enter_test();
        let _ = &__dep_test_scope_guard;
    };
}

/// Internal helper used by [`test_deps!`] to recurse across multiple override
/// entries.
#[doc(hidden)]
#[macro_export]
macro_rules! __dep_test_deps_more {
    ($builder:ident, ) => {};
    ($builder:ident, $client:ident.$method:ident => $implementation:expr $(, $($rest:tt)*)?) => {
        $client::$method::override_with(&mut $builder, $implementation);
        $(
            $crate::__dep_test_deps_more!($builder, $($rest)*);
        )?
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::panic::{AssertUnwindSafe, catch_unwind};
    use std::sync::mpsc;
    use std::time::Duration;

    client! {
        struct UnitClock as unit_clock {
            fn now_millis() -> u64 = || 100;
        }
    }

    client! {
        struct UnitMath as unit_math {
            fn add(lhs: u64, rhs: u64) -> u64 = |lhs, rhs| lhs + rhs;
            async fn add_async(lhs: u64, rhs: u64) -> u64 = |lhs, rhs| async move { lhs + rhs };
        }
    }

    client! {
        struct UnitGreeter as unit_greeter {
            fn greeting(id: u64) -> String = |id| {
                deps! {
                    now = unit_clock.now_millis,
                }

                format!("{id}@{}", now())
            };
        }
    }

    /// Polls a future to completion without bringing in an async runtime.
    fn block_on<F>(future: F) -> F::Output
    where
        F: Future,
    {
        use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};

        let mut future = Box::pin(future);

        unsafe fn clone(_: *const ()) -> RawWaker {
            RawWaker::new(std::ptr::null(), &VTABLE)
        }

        unsafe fn wake(_: *const ()) {}
        unsafe fn wake_by_ref(_: *const ()) {}
        unsafe fn drop(_: *const ()) {}

        static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake_by_ref, drop);

        let waker = unsafe { Waker::from_raw(RawWaker::new(std::ptr::null(), &VTABLE)) };
        let mut context = Context::from_waker(&waker);

        loop {
            match Pin::as_mut(&mut future).poll(&mut context) {
                Poll::Ready(value) => return value,
                Poll::Pending => std::thread::yield_now(),
            }
        }
    }

    /// Extracts a readable message from a panic payload for assertion purposes.
    fn panic_message(payload: Box<dyn Any + Send>) -> String {
        match payload.downcast::<String>() {
            Ok(message) => *message,
            Err(payload) => match payload.downcast::<&'static str>() {
                Ok(message) => (*message).to_string(),
                Err(_) => "<non-string panic payload>".into(),
            },
        }
    }

    #[test]
    fn dependency_error_formats_all_variants() {
        assert_eq!(
            DependencyError::missing("clock.now_millis").to_string(),
            "missing dependency implementation for `clock.now_millis`"
        );
        assert_eq!(DependencyError::message("nope").to_string(), "nope");
        assert_eq!(DependencyError::Owned("owned".into()).to_string(), "owned");
    }

    #[test]
    fn get_falls_back_to_live_dependency() {
        let _test_scope = OverrideBuilder::new().enter_test();
        assert_eq!(get::<UnitClock>().now_millis(), 100);
    }

    #[test]
    fn deps_macro_reads_dependency_methods_in_free_functions() {
        let _test_scope = OverrideBuilder::new().enter_test();
        assert_eq!(get::<UnitGreeter>().greeting(7), "7@100");
    }

    #[test]
    fn override_builder_set_replaces_a_whole_client() {
        let _test_scope = OverrideBuilder::new().enter_test();

        let override_clock = UnitClock {
            now_millis: erase_sync_0(|| 777),
        };

        let mut builder = OverrideBuilder::new();
        builder.set(override_clock);
        let _guard = builder.enter();
        assert_eq!(get::<UnitClock>().now_millis(), 777);
    }

    #[test]
    fn override_builder_update_uses_pending_entries_before_live_values() {
        let _test_scope = OverrideBuilder::new().enter_test();

        let mut builder = OverrideBuilder::new();
        builder.set(UnitClock {
            now_millis: erase_sync_0(|| 222),
        });
        builder.update::<UnitClock, _>(|mut dependency| {
            assert_eq!(dependency.now_millis(), 222);
            dependency.now_millis = erase_sync_0(|| 333);
            dependency
        });

        let _guard = builder.enter();
        assert_eq!(get::<UnitClock>().now_millis(), 333);
    }

    #[test]
    fn nested_override_layers_restore_previous_values() {
        let _test_scope = OverrideBuilder::new().enter_test();

        let mut outer_builder = OverrideBuilder::new();
        outer_builder.update::<UnitClock, _>(|mut dependency| {
            dependency.now_millis = erase_sync_0(|| 200);
            dependency
        });
        let outer = outer_builder.enter();
        assert_eq!(get::<UnitClock>().now_millis(), 200);

        {
            let mut inner_builder = OverrideBuilder::new();
            inner_builder.update::<UnitClock, _>(|mut dependency| {
                dependency.now_millis = erase_sync_0(|| 300);
                dependency
            });
            let _inner = inner_builder.enter();
            assert_eq!(get::<UnitClock>().now_millis(), 300);
        }

        assert_eq!(get::<UnitClock>().now_millis(), 200);
        drop(outer);
        assert_eq!(get::<UnitClock>().now_millis(), 100);
    }

    #[test]
    fn boxed_and_async_erasers_work_without_a_runtime() {
        assert_eq!(block_on(boxed(async { 9 })), 9);

        let add_sync: fn(u64, u64) -> u64 = erase_sync_2(|lhs: u64, rhs: u64| lhs + rhs);
        assert_eq!(add_sync(2, 3), 5);

        let add_async: fn(u64, u64) -> BoxFuture<u64> =
            erase_async_2(|lhs: u64, rhs: u64| async move { lhs + rhs });
        assert_eq!(block_on(add_async(2, 3)), 5);
    }

    #[test]
    fn capturing_closures_are_rejected_when_erased() {
        let captured = 9u64;
        let panic = catch_unwind(AssertUnwindSafe(|| {
            let _: fn() -> u64 = erase_sync_0(move || captured);
        }))
        .expect_err("capturing closures should panic");

        assert!(panic_message(panic).contains("non-capturing closures"));
    }

    #[test]
    fn unimplemented_dependency_panics_with_the_requested_path() {
        let panic = catch_unwind(AssertUnwindSafe(|| {
            unimplemented_dependency("unit_clock.now_millis")
        }))
        .expect_err("unimplemented dependency should panic");

        assert!(panic_message(panic).contains("unit_clock.now_millis"));
    }

    #[test]
    fn test_deps_macro_installs_multiple_overrides() {
        test_deps! {
            unit_clock.now_millis => || 444,
            unit_math.add => |lhs, rhs| lhs * rhs,
            unit_math.add_async => |lhs, rhs| async move { lhs * rhs },
        }

        assert_eq!(get::<UnitClock>().now_millis(), 444);
        assert_eq!(get::<UnitMath>().add(2, 3), 6);
        assert_eq!(block_on(get::<UnitMath>().add_async(2, 3)), 6);
    }

    #[test]
    fn enter_test_serializes_parallel_override_scopes() {
        let guard = OverrideBuilder::new().enter_test();
        let (ready_tx, ready_rx) = mpsc::channel();
        let (done_tx, done_rx) = mpsc::channel();

        let handle = std::thread::spawn(move || {
            ready_tx.send(()).expect("thread should signal readiness");
            let _guard = OverrideBuilder::new().enter_test();
            done_tx.send(()).expect("thread should signal acquisition");
        });

        ready_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("thread should start");
        assert!(
            done_rx.recv_timeout(Duration::from_millis(50)).is_err(),
            "second test scope should block while the first is held"
        );

        drop(guard);

        done_rx
            .recv_timeout(Duration::from_secs(1))
            .expect("second test scope should acquire once the first drops");
        handle.join().expect("thread should join cleanly");
    }

    #[test]
    fn pop_overrides_panics_when_the_stack_is_empty() {
        acquire_test_lock();
        let panic =
            catch_unwind(AssertUnwindSafe(pop_overrides)).expect_err("empty stack should panic");
        release_test_lock();

        assert!(panic_message(panic).contains("stack underflow"));
    }
}