Skip to main content

relate_ir/ast/
body_descent.rs

1//! The one shared body-descent skeleton (ADR-0740): the FINAL-stage
2//! cursor, the any-arm fold over a stage's `UNION` arms, and the
3//! concluding-clause hand-off into which each layer injects its own
4//! verdict — the naming layer's ([`Query::projects_columns`]) here in
5//! the IR, the executor's (the planner's full clause table with
6//! any-branch breadth and the batched-call ruling) in relate-executor.
7//! The model this walk runs over stays in this module's parent
8//! ([`Query`](super::Query), [`Clause`](super::Clause),
9//! [`final_stage`](Query::final_stage)); this module owns the
10//! classification fold, its injected-verdict seam, and the structural
11//! invariants it surfaces. The skeleton's tests live beside it
12//! (`body_descent_tests`); the AST fixtures both that suite and the
13//! executor verdict's suite build their subjects from live in
14//! `body_descent_fixtures`, gated behind this crate's `test-hooks`.
15
16use super::{Clause, Query, SingleQuery};
17
18impl Query {
19    /// Whether this query's FINAL stage projects a statement result of
20    /// its own under a layer's [`ConcludingVerdict`] — the one shared
21    /// body-descent skeleton (ADR-0740): the FINAL-stage cursor (a
22    /// `NEXT`-chained body is judged by its final stage, never its
23    /// first), the any-arm fold over the stage's `UNION` arms, and the
24    /// hand-off of each arm's concluding clause to the verdict, which
25    /// receives this same descent back for the clause's nested bodies.
26    /// The structural invariants are surfaced here, never defaulted
27    /// over: a `Query` invariantly carries at least one part, and a part
28    /// at least one clause (validation refuses an empty part before any
29    /// fold runs).
30    ///
31    /// Two verdicts ride this one skeleton, and their agreement is the
32    /// skeleton's contract: the naming layer's
33    /// ([`Query::projects_columns`]: `RETURN`-only vocabulary with a
34    /// first-branch stand-in) and the executor's (the planner's full
35    /// clause table with any-branch breadth and its batched-call
36    /// ruling). The two answer alike on every valid body — validation
37    /// holds every `WHEN` branch and `UNION` arm to the same export
38    /// shape, so the representative and the any-branch folds cannot
39    /// disagree — and a new nested-body arm added to one verdict needs
40    /// its twin arm in the other; the agreement test beside the
41    /// executor's verdict pins it.
42    pub fn final_stage_projects_rows(&self, verdict: &ConcludingVerdict) -> bool {
43        stage_projects_rows(&self.final_stage().parts, verdict)
44    }
45
46    /// Whether this query projects columns: its true final stage (the end of
47    /// its `NEXT` chain, not merely its own part list) ends in a `RETURN`,
48    /// or in a `CONDITIONAL` / nested `CALL { … }` that projects. A body
49    /// that does not — an update clause, a bare procedure call — leaves a
50    /// `CALL { … }` a *unit* subquery.
51    ///
52    /// The one IR spelling of the fact: the planner's subquery-scope fold
53    /// and the redundant-`OPTIONAL` notification detector both read it.
54    /// The body-descent structure under it — the FINAL-stage cursor, the
55    /// any-arm fold, the concluding-clause hand-off — is the one shared
56    /// body-descent skeleton ([`Query::final_stage_projects_rows`],
57    /// ADR-0740); this method is the naming layer's verdict over that
58    /// skeleton ([`projects_columns_concluding`]), where the executor
59    /// injects its own (the planner's full clause table with any-branch
60    /// breadth and the batched-call ruling) — the two agree on every
61    /// nested-body shape under the validated branch/arm representative
62    /// agreement.
63    pub fn projects_columns(&self) -> bool {
64        self.final_stage_projects_rows(&projects_columns_concluding)
65    }
66}
67
68/// A layer's concluding-clause verdict for the shared body-descent
69/// skeleton ([`Query::final_stage_projects_rows`] /
70/// [`stage_projects_rows`], ADR-0740): whether the clause concluding an
71/// arm projects a statement result of its own. `descend` — the
72/// skeleton's own body descent handed back — answers the clause's
73/// nested bodies (a `WHEN` branch body, a nested `CALL { … }` body)
74/// under the same verdict, so a layer folds them by its own breadth
75/// without re-spelling the query structure the skeleton owns. The
76/// descent's own type stays inline (`&dyn Fn(&Query) -> bool`): a named
77/// alias for it would be a bare `dyn` defaulting to `'static`, which
78/// the closures the skeleton hands back cannot satisfy.
79pub type ConcludingVerdict = dyn Fn(&Clause, &dyn Fn(&Query) -> bool) -> bool;
80
81/// The clause concluding a part — its last clause, with the part
82/// invariant stated once, here: a part invariantly carries at least one
83/// clause (validation refuses an empty part as `empty query part`
84/// before any fold runs), so reaching an empty part is a broken
85/// invariant to surface, never a verdict to fabricate. The skeleton's
86/// arm fold and the executor's NEXT-seeding fold read this one
87/// spelling.
88pub fn part_concluding_clause(part: &[Clause]) -> &Clause {
89    part.last()
90        .expect("a part invariantly carries at least one clause")
91}
92
93/// The concluding clauses of a stage's parts — the skeleton's all-form
94/// half, for the consumers that judge every arm instead of any arm
95/// ([`stage_projects_rows`] is the any-form fold). The stage invariant
96/// is surfaced once, here: a stage invariantly carries at least one
97/// part, so an empty parts iterator is a broken invariant to surface,
98/// never a fold that answers vacuously. The executor's NEXT-seeding
99/// fold reads this one enumeration instead of re-spelling the walk and
100/// its invariants.
101pub fn stage_concluding_clauses<'p>(
102    mut parts: impl Iterator<Item = &'p [Clause]>,
103) -> impl Iterator<Item = &'p Clause> {
104    let first = parts
105        .next()
106        .expect("a stage invariantly carries at least one part");
107    std::iter::once(first)
108        .chain(parts)
109        .map(part_concluding_clause)
110}
111
112/// The stage-level entry of the one shared body-descent skeleton
113/// (ADR-0740): whether any of one stage's `UNION` arms projects a
114/// statement result of its own under a layer's [`ConcludingVerdict`].
115/// [`Query::final_stage_projects_rows`] is the body-level form — the
116/// same fold over a whole body's FINAL stage; this entry serves the one
117/// caller that judges the stage it is about to run rather than a body
118/// (the executor's stage driver, which holds the stage's own parts).
119///
120/// The skeleton owns the structure walk and surfaces its invariants: a
121/// `Query` invariantly carries at least one part, a part at least one
122/// clause (validation refuses an empty part as `empty query part`
123/// before any fold runs) — both stated once, in
124/// [`stage_concluding_clauses`], the one enumeration this any-form fold
125/// and the executor's all-form fold read. A layer owns only its
126/// clause-level verdict; the two current verdicts — the naming layer's
127/// `RETURN`-only base with a first-branch stand-in, the executor's
128/// planner-table base with any-branch breadth and the batched-call
129/// ruling — agree on every valid body, and a new nested-body arm in one
130/// needs its twin in the other.
131pub fn stage_projects_rows(parts: &[SingleQuery], verdict: &ConcludingVerdict) -> bool {
132    stage_concluding_clauses(parts.iter().map(|part| part.clauses.as_slice()))
133        .any(|concluding| verdict(concluding, &|body| body.final_stage_projects_rows(verdict)))
134}
135
136/// The naming layer's [`ConcludingVerdict`]: a `RETURN` concludes a
137/// projecting body; a `WHEN` clause's first branch stands in for the
138/// whole clause (the grammar pushes one before its loop can break, and
139/// validation holds every branch and arm to the same export shape, so
140/// the stand-in and the executor's any-branch fold answer alike); a
141/// nested `CALL { … }` is its body's answer. Everything else leaves the
142/// body unit — no export columns, no statement result: the update
143/// clauses, the read pipeline's interior and procedure-read clauses
144/// (`MATCH`/`WITH`/`UNWIND`/`CALL` — a bare procedure call, unlike the
145/// row-producing `CALL { … }`), the DDL/admin family, `LOAD CSV`,
146/// `FINISH`, and the routing `USE`. [`Query::projects_columns`] is this
147/// verdict's one spelling over the shared body-descent skeleton
148/// (ADR-0740).
149pub(super) fn projects_columns_concluding(
150    clause: &Clause,
151    descend: &dyn Fn(&Query) -> bool,
152) -> bool {
153    // Exhaustive on purpose — no `_ =>` — the discipline every clause
154    // table over `Clause` carries (the planner's `clause_kind` tables
155    // spell it in their own docs): a new IR variant is a compile error
156    // here, forcing the naming ruling the same round its executor twin
157    // is forced through the planner table — never a silent "no columns"
158    // the verdict-agreement test cannot see.
159    match clause {
160        Clause::Return { .. } => true,
161        Clause::Conditional { branches, .. } => descend(
162            &branches
163                .first()
164                .expect("a WHEN clause has at least one branch")
165                .1,
166        ),
167        Clause::CallSubquery { query, .. } => descend(query),
168        Clause::Catalog(_)
169        | Clause::Match { .. }
170        | Clause::Create { .. }
171        | Clause::Merge { .. }
172        | Clause::Call { .. }
173        | Clause::Delete { .. }
174        | Clause::Set { .. }
175        | Clause::Remove { .. }
176        | Clause::With { .. }
177        | Clause::Unwind { .. }
178        | Clause::ShowIndexes
179        | Clause::Finish
180        | Clause::LoadCsv { .. }
181        | Clause::Foreach { .. }
182        | Clause::Use { .. }
183        | Clause::CreateIndex { .. }
184        | Clause::DropIndex { .. } => false,
185    }
186}