Skip to main content

id_effect/capability/
hlist.rs

1//! Typed environments: `HNil`/`HCons`/`Here`/`There`, `HList` and the
2//! `Selector`/`Plucker`/`Sculptor`/`Embed`/`Concat` traits with their diagnostics.
3//!
4//! The environment `R` of an `Effect` is an HList of `Arc`ed capabilities. Lookups, provision,
5//! subset projection and concatenation are traits whose index parameters the compiler infers
6//! (design A ยง2.1). A missing capability is a compile error with a custom diagnostic.
7//!
8//! # Diagnostics
9//!
10//! `Selector`, `Plucker`, `Sculptor` and `Embed` carry `#[diagnostic::on_unimplemented]`, so a
11//! missing, superfluous or non-embeddable capability is reported in capability terms. Every
12//! recursive impl (`There<I>` for the single-element traits, `HCons<I, Is>` for the list traits)
13//! is `#[diagnostic::do_not_recommend]`: rustc then reports the failed obligation at the trait the
14//! user's code named, with one `help` line, instead of a `required for ..` chain that grows with
15//! the length of `R`. The `.stderr` shapes are pinned by `k-ui-suite`.
16//!
17//! A capability that appears twice in `R` is ambiguous (E0283, "type annotations needed"):
18//! `on_unimplemented` does not fire on ambiguity. `caps!` rejects duplicates at the
19//! declaration, and `Layer::merge` deduplicates shared inputs (`k-layer-base`).
20
21use std::marker::PhantomData;
22use std::sync::Arc;
23
24/// The empty environment.
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
26pub struct HNil;
27
28/// One capability (shared, `Arc`) in front of the rest of the environment.
29#[derive(Debug)]
30pub struct HCons<H, T>(pub Arc<H>, pub T);
31
32impl<H, T: Clone> Clone for HCons<H, T> {
33  fn clone(&self) -> Self {
34    Self(Arc::clone(&self.0), self.1.clone())
35  }
36}
37
38impl<H, T> HCons<H, T> {
39  /// `head` (wrapped in an `Arc`) in front of `tail`.
40  pub fn new(head: H, tail: T) -> Self {
41    Self(Arc::new(head), tail)
42  }
43}
44
45/// Index witness: the capability is the head.
46#[derive(Debug)]
47pub struct Here;
48
49/// Index witness: the capability is somewhere in the tail.
50#[derive(Debug)]
51pub struct There<I>(PhantomData<I>);
52
53/// An environment value: cheap to clone (one `Arc` bump per capability), shareable across fibers.
54pub trait HList: Clone + Send + Sync + 'static {
55  /// Number of capabilities.
56  const LEN: usize;
57}
58
59impl HList for HNil {
60  const LEN: usize = 0;
61}
62
63impl<H: Send + Sync + 'static, T: HList> HList for HCons<H, T> {
64  const LEN: usize = 1 + T::LEN;
65}
66
67/// Read capability `T` at the inferred index `I`. A missing `T` is a compile error.
68#[diagnostic::on_unimplemented(
69  message = "capability `{T}` is not in this effect's environment",
70  label = "`{T}` is required here",
71  note = "add `{T}` to the effect's `caps!(..)`, or remove it with `.provide(..)` / `.provide_env(..)` before running"
72)]
73pub trait Selector<T, I> {
74  /// The capability.
75  fn get(&self) -> &Arc<T>;
76}
77
78impl<T, Tl> Selector<T, Here> for HCons<T, Tl> {
79  fn get(&self) -> &Arc<T> {
80    &self.0
81  }
82}
83
84#[diagnostic::do_not_recommend]
85impl<T, H, Tl: Selector<T, I>, I> Selector<T, There<I>> for HCons<H, Tl> {
86  fn get(&self) -> &Arc<T> {
87    self.1.get()
88  }
89}
90
91/// Remove capability `T` (at `I`) from the environment type: what `provide` eliminates.
92#[diagnostic::on_unimplemented(
93  message = "`{T}` is not required by this effect, so it cannot be provided",
94  label = "this effect's environment `{Self}` has no `{T}`",
95  note = "only capabilities in the effect's `R` can be provided; drop this `.provide(..)`"
96)]
97pub trait Plucker<T, I>: Sized {
98  /// The environment without `T`.
99  type Rest: HList;
100  /// Put `t` back at its index in `rest`.
101  fn plant(t: Arc<T>, rest: Self::Rest) -> Self;
102  /// Take `T` out, returning it and the rest.
103  fn pluck(self) -> (Arc<T>, Self::Rest);
104}
105
106impl<T: Send + Sync + 'static, Tl: HList> Plucker<T, Here> for HCons<T, Tl> {
107  type Rest = Tl;
108  fn plant(t: Arc<T>, rest: Tl) -> Self {
109    Self(t, rest)
110  }
111  fn pluck(self) -> (Arc<T>, Tl) {
112    (self.0, self.1)
113  }
114}
115
116#[diagnostic::do_not_recommend]
117impl<T, H: Send + Sync + 'static, Tl: Plucker<T, I>, I> Plucker<T, There<I>> for HCons<H, Tl> {
118  type Rest = HCons<H, Tl::Rest>;
119  fn plant(t: Arc<T>, rest: Self::Rest) -> Self {
120    Self(rest.0, Tl::plant(t, rest.1))
121  }
122  fn pluck(self) -> (Arc<T>, Self::Rest) {
123    let (t, rest) = self.1.pluck();
124    (t, HCons(self.0, rest))
125  }
126}
127
128/// Remove a whole sub-environment `Sub` (at indices `Is`): what `provide_some` eliminates.
129#[diagnostic::on_unimplemented(
130  message = "`{Sub}` is not a part of this effect's environment `{Self}`",
131  label = "cannot provide `{Sub}` here",
132  note = "every capability given to `.provide_some(..)` must be in the effect's `R`; provide the others separately or drop them"
133)]
134pub trait Sculptor<Sub, Is>: Sized {
135  /// The environment without `Sub`.
136  type Rest: HList;
137  /// Put every capability of `sub` back at its index in `rest`.
138  fn plant(sub: Sub, rest: Self::Rest) -> Self;
139}
140
141impl<S: HList> Sculptor<HNil, HNil> for S {
142  type Rest = S;
143  fn plant(_: HNil, rest: S) -> S {
144    rest
145  }
146}
147
148#[diagnostic::do_not_recommend]
149impl<S, H, T, I, Is> Sculptor<HCons<H, T>, HCons<I, Is>> for S
150where
151  S: Plucker<H, I>,
152  S::Rest: Sculptor<T, Is>,
153{
154  type Rest = <S::Rest as Sculptor<T, Is>>::Rest;
155  fn plant(sub: HCons<H, T>, rest: Self::Rest) -> Self {
156    S::plant(sub.0, <S::Rest as Sculptor<T, Is>>::plant(sub.1, rest))
157  }
158}
159
160/// Read-only projection of a sub-environment `Sub` out of `Self` (any subset, any order): what
161/// narrowing (`~sub_effect`, `.narrow()`, `.provide_env(..)`) uses. Costs one `Arc` clone per
162/// capability in `Sub`.
163#[diagnostic::on_unimplemented(
164  message = "the environment `{Self}` does not contain every capability of `{Sub}`",
165  label = "cannot narrow `{Self}` to `{Sub}`",
166  note = "every capability of `{Sub}` must be in `{Self}`; add the missing ones to the caller's `caps!(..)` (for a `~` bind, a `~(..)` branch or `.narrow()`), to the `hlist![..]` (for `.provide_env(..)`) or to the layer's output (for `.provide_layer(..)` / `.provide_to(..)`)"
167)]
168pub trait Embed<Sub, Is> {
169  /// The sub-environment.
170  fn project(&self) -> Sub;
171}
172
173impl<S> Embed<HNil, HNil> for S {
174  fn project(&self) -> HNil {
175    HNil
176  }
177}
178
179#[diagnostic::do_not_recommend]
180impl<S, H, T, I, Is> Embed<HCons<H, T>, HCons<I, Is>> for S
181where
182  S: Selector<H, I> + Embed<T, Is>,
183{
184  fn project(&self) -> HCons<H, T> {
185    HCons(
186      Arc::clone(Selector::<H, I>::get(self)),
187      Embed::<T, Is>::project(self),
188    )
189  }
190}
191
192/// Type-level and value-level append (layer merge).
193pub trait Concat<Rhs> {
194  /// `Self` followed by `Rhs`.
195  type Out: HList;
196  /// Append `rhs`.
197  fn concat(self, rhs: Rhs) -> Self::Out;
198}
199
200impl<Rhs: HList> Concat<Rhs> for HNil {
201  type Out = Rhs;
202  fn concat(self, rhs: Rhs) -> Rhs {
203    rhs
204  }
205}
206
207impl<H: Send + Sync + 'static, T: Concat<Rhs>, Rhs> Concat<Rhs> for HCons<H, T> {
208  type Out = HCons<H, T::Out>;
209  fn concat(self, rhs: Rhs) -> Self::Out {
210    HCons(self.0, self.1.concat(rhs))
211  }
212}
213
214/// Builds an environment value: `hlist![Db::new(), Logger::default()]`.
215#[doc(hidden)]
216#[macro_export]
217macro_rules! __hlist {
218  () => { $crate::HNil };
219  ($head:expr $(, $rest:expr)* $(,)?) => {
220    $crate::HCons::new($head, $crate::__hlist!($($rest),*))
221  };
222}
223
224#[doc(inline)]
225pub use crate::__hlist as hlist;
226
227#[cfg(test)]
228mod tests {
229  use super::*;
230
231  struct A(u8);
232  struct B(&'static str);
233  struct C;
234
235  fn get<T, I, L: Selector<T, I>>(l: &L) -> &Arc<T> {
236    l.get()
237  }
238
239  #[test]
240  fn select_pluck_sculpt_embed_concat() {
241    let env = hlist![A(1), B("b"), C];
242    assert_eq!(<HCons<A, HCons<B, HCons<C, HNil>>> as HList>::LEN, 3);
243    assert_eq!(get::<A, _, _>(&env).0, 1);
244    assert_eq!(get::<B, _, _>(&env).0, "b");
245
246    let (b, rest): (Arc<B>, HCons<A, HCons<C, HNil>>) = Plucker::<B, _>::pluck(env.clone());
247    assert_eq!(b.0, "b");
248    let back: HCons<A, HCons<B, HCons<C, HNil>>> = Plucker::<B, _>::plant(b, rest);
249    assert_eq!(get::<A, _, _>(&back).0, 1);
250
251    let sub: HCons<C, HCons<A, HNil>> = Embed::<_, _>::project(&env);
252    assert_eq!(get::<A, _, _>(&sub).0, 1);
253
254    let rest = HCons::new(B("x"), HNil);
255    let whole: HCons<A, HCons<B, HCons<C, HNil>>> =
256      Sculptor::<HCons<A, HCons<C, HNil>>, _>::plant(hlist![A(3), C], rest);
257    assert_eq!(get::<B, _, _>(&whole).0, "x");
258    assert_eq!(get::<A, _, _>(&whole).0, 3);
259
260    let cat = hlist![A(2)].concat(hlist![C]);
261    let _: &HCons<A, HCons<C, HNil>> = &cat;
262  }
263}