Skip to main content

solverforge_scoring/stream/
chain_stream.rs

1//! Arbitrary-depth typed join chain, past the named arities.
2//!
3//! `Bi`/`Tri`/`Quad`/`Penta` are ergonomic adapters with hand-written entity
4//! accessors. Beyond Penta there is no per-arity type to write, so this is the
5//! typed row form the arity adapters are built on: a `Chain` owns any
6//! `Operator<S>` tree plus the next binding index, and `.join()` nests another
7//! `JoinNode` whose plan receives the whole borrowed left row. No erasure, no
8//! fixed ceiling — depth is whatever the type nests to.
9//!
10//! Entry is `Penta::join`, which continues the fluent chain at depth six; a
11//! `Chain` then joins indefinitely. Filtering wraps the tree in a `FilterNode`
12//! (identity-preserving, view-transparent); finalizing hands the tree to the
13//! generic `OperatorTerminal`.
14
15use std::marker::PhantomData;
16
17use solverforge_core::score::Score;
18use solverforge_core::{ConstraintRef, ImpactType};
19
20use super::collection_extract::CollectionExtract;
21use super::joiner::plan::{CompileCondition, ExecutablePlan, IndexedPlan};
22use super::relational::operator::{FilterNode, FilterPredicate, JoinNode, Operator};
23use super::relational::Leaf;
24use crate::constraint::relational::OperatorTerminal;
25
26/// A typed join chain of unbounded depth.
27///
28/// `O` is the concrete operator tree (a `JoinNode`, optionally wrapped in a
29/// `FilterNode`); `next_binding` is the binding index the next joined collection
30/// receives, so repeated descriptors stay distinguishable.
31pub struct Chain<S: 'static, O, Sc>
32where
33    O: Operator<S>,
34{
35    tree: O,
36    next_binding: u32,
37    _phantom: PhantomData<fn() -> (S, Sc)>,
38}
39
40impl<S, O, Sc> Chain<S, O, Sc>
41where
42    S: Send + Sync + 'static,
43    O: Operator<S> + Send + Sync,
44    Sc: Score + 'static,
45{
46    /// Wraps an existing operator tree as a chain whose next joined
47    /// collection takes `next_binding`.
48    pub fn new(tree: O, next_binding: u32) -> Self {
49        Self {
50            tree,
51            next_binding,
52            _phantom: PhantomData,
53        }
54    }
55
56    /// Adds a row filter. The filter receives the whole borrowed typed row and
57    /// the solution, and is applied exactly once on every path.
58    pub fn filter<P>(self, predicate: P) -> Chain<S, FilterNode<O, P>, Sc>
59    where
60        P: for<'a> FilterPredicate<S, O::View<'a>> + 'static,
61        FilterNode<O, P>: Operator<S>,
62    {
63        Chain {
64            tree: FilterNode::new(self.tree, predicate),
65            next_binding: self.next_binding,
66            _phantom: PhantomData,
67        }
68    }
69
70    /// Extends the chain with one more source.
71    ///
72    /// The target's condition compiles fresh, so its left key receives the whole
73    /// borrowed row (`O::View<'a>`) and `target`'s key domain is independent of
74    /// every earlier relationship.
75    ///
76    /// # Key shapes
77    ///
78    /// Later joins of a chain take VIEW keys, not entity keys:
79    ///
80    /// - left key — the whole borrowed row so far, spelled here as
81    ///   `|row: &O::View<'_>| ...` (e.g. `row.left.entity.key` on a `Pair`)
82    /// - right key — `|c: &Leaf<'_, B>| c.entity.key`, reading fields via `.entity`
83    ///
84    /// `equal_bi` with entity closures does NOT typecheck here (E0631, expected
85    /// a closure over the row view) — use `equal_on`. The first join of a chain
86    /// keeps `equal_bi` with plain entity keys.
87    pub fn join<B, EB, P>(
88        self,
89        target: (EB, P),
90    ) -> Chain<S, JoinNode<S, O, CollectionNodeAlias<S, EB>, P::Plan>, Sc>
91    where
92        B: Send + Sync + 'static,
93        EB: CollectionExtract<S, Item = B> + 'static,
94        P: CompileCondition + 'static,
95        P::Plan: IndexedPlan,
96        for<'a> CollectionNodeAlias<S, EB>: Operator<S, View<'a> = Leaf<'a, B>>,
97        for<'a> P::Plan: ExecutablePlan<O::View<'a>, Leaf<'a, B>>,
98        JoinNode<S, O, CollectionNodeAlias<S, EB>, P::Plan>: Operator<S>,
99    {
100        let (extractor, condition) = target;
101        let tree = JoinNode::new(
102            self.tree,
103            super::relational::operator::CollectionNode::new(extractor, self.next_binding),
104            condition,
105        );
106        Chain {
107            tree,
108            next_binding: self.next_binding + 1,
109            _phantom: PhantomData,
110        }
111    }
112
113    /// Finalizes into the generic operator terminal, scoring with a weight that
114    /// receives the whole borrowed typed row.
115    pub fn penalize<W>(self, weight: W) -> ChainBuilder<S, O, W, Sc>
116    where
117        W: for<'a> Fn(&S, &O::View<'a>) -> Sc + Send + Sync,
118    {
119        ChainBuilder {
120            tree: self.tree,
121            impact_type: ImpactType::Penalty,
122            weight,
123            is_hard: false,
124            _phantom: PhantomData,
125        }
126    }
127
128    /// Finalizes into the generic operator terminal as a reward.
129    pub fn reward<W>(self, weight: W) -> ChainBuilder<S, O, W, Sc>
130    where
131        W: for<'a> Fn(&S, &O::View<'a>) -> Sc + Send + Sync,
132    {
133        ChainBuilder {
134            tree: self.tree,
135            impact_type: ImpactType::Reward,
136            weight,
137            is_hard: false,
138            _phantom: PhantomData,
139        }
140    }
141}
142
143/// Alias kept short at the use site; the concrete node type.
144type CollectionNodeAlias<S, E> = super::relational::operator::CollectionNode<S, E>;
145
146/// Finalizer for a chain: holds the tree, impact, and row weight until
147/// `named()` attaches a constraint name.
148pub struct ChainBuilder<S: 'static, O, W, Sc>
149where
150    O: Operator<S>,
151{
152    tree: O,
153    impact_type: ImpactType,
154    weight: W,
155    is_hard: bool,
156    _phantom: PhantomData<fn() -> (S, Sc)>,
157}
158
159impl<S, O, W, Sc> ChainBuilder<S, O, W, Sc>
160where
161    S: Send + Sync + 'static,
162    O: Operator<S> + Send + Sync,
163    W: for<'a> Fn(&S, &O::View<'a>) -> Sc + Send + Sync,
164    Sc: Score + 'static,
165    O: super::relational::operator::ExplainOperator<S>,
166{
167    /// Marks the constraint hard.
168    pub fn hard(mut self) -> Self {
169        self.is_hard = true;
170        self
171    }
172
173    /// Names the constraint, producing the terminal.
174    pub fn named(self, name: &str) -> OperatorTerminal<S, O, W, Sc> {
175        OperatorTerminal::new(
176            ConstraintRef::new("", name),
177            self.impact_type,
178            self.tree,
179            self.weight,
180            self.is_hard,
181        )
182    }
183}