Skip to main content

solverforge_scoring/stream/
collection_extract.rs

1//! `CollectionExtract`: the source of a stream's rows.
2//!
3//! A stream source is a planning-model collection: the accessor that
4//! `#[planning_solution]` generates for each entity, fact and list-element
5//! collection (`Plan::shifts()`). Each accessor reports which descriptor owns its
6//! rows, so incremental scoring can map an entity notification to the rows it
7//! changes. A raw closure or `fn` item carries no such identity and is not a
8//! source.
9
10use std::marker::PhantomData;
11
12mod planning_id;
13
14#[doc(hidden)]
15pub use planning_id::{
16    AnalysisPlanningId, ModelPlanningIds, NoPlanningIds, RenderPlanningId, RenderPlanningIdDebug,
17    RenderPlanningIdDisplay, RenderPlanningIdNone, SourcePlanningIds,
18};
19
20/// Extracts a slice of entities from the solution.
21///
22/// The associated type `Item` names the entity type, allowing callers to
23/// write `E: CollectionExtract<S, Item = A>` when `A` must be inferred from `E`
24/// rather than stated as a separate generic parameter.
25#[diagnostic::on_unimplemented(
26    message = "`{Self}` is not a stream source",
27    label = "stream sources must come from the planning model",
28    note = "pass the generated accessor, e.g. `Plan::shifts()`"
29)]
30pub trait CollectionExtract<S>: Send + Sync {
31    /// The entity type yielded by this extractor.
32    type Item;
33
34    /// Extracts the entity slice from the solution.
35    fn extract<'s>(&self, s: &'s S) -> &'s [Self::Item];
36
37    /// Reports whether this extractor's own source-level predicate accepts an item.
38    fn contains(&self, _s: &S, _item: &Self::Item) -> bool {
39        true
40    }
41
42    /// The descriptor that owns this source's rows, or `Static` when no
43    /// planning-variable change can alter them. Macro-generated solution source
44    /// methods attach it through hidden internal support.
45    fn change_source(&self) -> ChangeSource;
46
47    /// The planning id constraint analysis reports for `item`, rendered as
48    /// described on [`EntityRef::planning_id`](crate::api::analysis::EntityRef::planning_id).
49    /// Read only while explaining a match, never while scoring. Planning-model
50    /// entity and fact collections report their `#[planning_id]`; the default
51    /// reports none.
52    fn planning_id(&self, _item: &Self::Item) -> Option<String> {
53        None
54    }
55}
56
57/// Preserves a unary stream's membership at the source boundary, before
58/// indexed joins build keys or materialize pairs. The original slice and index
59/// mapping remain unchanged so descriptor-local mutations keep their identity.
60#[doc(hidden)]
61pub struct FilteredExtract<E, F> {
62    extractor: E,
63    filter: F,
64}
65
66impl<E, F> FilteredExtract<E, F> {
67    pub fn new(extractor: E, filter: F) -> Self {
68        Self { extractor, filter }
69    }
70}
71
72impl<S, E, F> CollectionExtract<S> for FilteredExtract<E, F>
73where
74    E: CollectionExtract<S>,
75    F: super::filter::UniFilter<S, E::Item>,
76{
77    type Item = E::Item;
78
79    fn extract<'s>(&self, s: &'s S) -> &'s [Self::Item] {
80        self.extractor.extract(s)
81    }
82
83    fn contains(&self, s: &S, item: &Self::Item) -> bool {
84        self.extractor.contains(s, item) && self.filter.test(s, item)
85    }
86
87    fn change_source(&self) -> ChangeSource {
88        self.extractor.change_source()
89    }
90
91    fn planning_id(&self, item: &Self::Item) -> Option<String> {
92        self.extractor.planning_id(item)
93    }
94}
95
96#[doc(hidden)]
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
98pub enum ChangeSource {
99    Static,
100    Descriptor(usize),
101}
102
103impl ChangeSource {
104    #[inline]
105    pub fn owns_descriptor(self, descriptor_index: usize) -> bool {
106        matches!(self, Self::Descriptor(index) if index == descriptor_index)
107    }
108
109    #[inline]
110    pub fn same_index_domain(self, other: Self) -> bool {
111        matches!((self, other), (Self::Descriptor(left), Self::Descriptor(right)) if left == right)
112    }
113}
114
115/// Borrows the child items of one parent entity, for flattened streams.
116pub trait FlattenExtract<P>: Send + Sync {
117    /// The child item type.
118    type Item;
119
120    /// Returns `parent`'s children.
121    fn extract<'s>(&self, parent: &'s P) -> &'s [Self::Item];
122}
123
124impl<P, B, F> FlattenExtract<P> for F
125where
126    F: for<'a> Fn(&'a P) -> &'a [B] + Send + Sync,
127{
128    type Item = B;
129
130    #[inline]
131    fn extract<'s>(&self, parent: &'s P) -> &'s [B] {
132        self(parent)
133    }
134}
135
136/// Adapts a closure returning `&Vec<B>` to [`FlattenExtract`].
137#[derive(Clone, Copy)]
138pub struct FlattenVecExtract<F>(pub F);
139
140impl<P, B, F> FlattenExtract<P> for FlattenVecExtract<F>
141where
142    F: for<'a> Fn(&'a P) -> &'a Vec<B> + Send + Sync,
143{
144    type Item = B;
145
146    #[inline]
147    fn extract<'s>(&self, parent: &'s P) -> &'s [B] {
148        (self.0)(parent).as_slice()
149    }
150}
151
152/// A collection source: the slice accessor, the descriptor that owns its
153/// rows, and, in `I`, how analysis renders its items' planning ids (a
154/// zero-sized [`SourcePlanningIds`] choice, so it adds nothing to the source).
155#[doc(hidden)]
156pub struct SourceExtract<E, I = NoPlanningIds> {
157    extractor: E,
158    change_source: ChangeSource,
159    planning_ids: PhantomData<fn() -> I>,
160}
161
162impl<E: Clone, I> Clone for SourceExtract<E, I> {
163    fn clone(&self) -> Self {
164        Self {
165            extractor: self.extractor.clone(),
166            change_source: self.change_source,
167            planning_ids: PhantomData,
168        }
169    }
170}
171
172impl<E: Copy, I> Copy for SourceExtract<E, I> {}
173
174impl<E, I> SourceExtract<E, I> {
175    pub fn new(extractor: E, change_source: ChangeSource) -> Self {
176        Self {
177            extractor,
178            change_source,
179            planning_ids: PhantomData,
180        }
181    }
182
183    pub fn extractor(&self) -> &E {
184        &self.extractor
185    }
186}
187
188impl<S, A, E, I> CollectionExtract<S> for SourceExtract<E, I>
189where
190    E: for<'a> Fn(&'a S) -> &'a [A] + Send + Sync,
191    I: SourcePlanningIds<A>,
192{
193    type Item = A;
194
195    #[inline]
196    fn extract<'s>(&self, s: &'s S) -> &'s [A] {
197        (self.extractor)(s)
198    }
199
200    fn change_source(&self) -> ChangeSource {
201        self.change_source
202    }
203
204    fn planning_id(&self, item: &A) -> Option<String> {
205        I::planning_id(item)
206    }
207}
208
209#[doc(hidden)]
210pub fn source<E>(extractor: E, change_source: ChangeSource) -> SourceExtract<E> {
211    SourceExtract::new(extractor, change_source)
212}
213
214/// A planning-model entity or fact collection source: like [`source`], and
215/// its items report their `#[planning_id]` in constraint analysis.
216#[doc(hidden)]
217pub fn model_source<E>(
218    extractor: E,
219    change_source: ChangeSource,
220) -> SourceExtract<E, ModelPlanningIds> {
221    SourceExtract::new(extractor, change_source)
222}