relate-ir 1.5.0

Planner IR (lowered Cypher AST)
Documentation
//! The one shared body-descent skeleton (ADR-0740): the FINAL-stage
//! cursor, the any-arm fold over a stage's `UNION` arms, and the
//! concluding-clause hand-off into which each layer injects its own
//! verdict — the naming layer's ([`Query::projects_columns`]) here in
//! the IR, the executor's (the planner's full clause table with
//! any-branch breadth and the batched-call ruling) in relate-executor.
//! The model this walk runs over stays in this module's parent
//! ([`Query`](super::Query), [`Clause`](super::Clause),
//! [`final_stage`](Query::final_stage)); this module owns the
//! classification fold, its injected-verdict seam, and the structural
//! invariants it surfaces. The skeleton's tests live beside it
//! (`body_descent_tests`); the AST fixtures both that suite and the
//! executor verdict's suite build their subjects from live in
//! `body_descent_fixtures`, gated behind this crate's `test-hooks`.

use super::{Clause, Query, SingleQuery};

impl Query {
    /// Whether this query's FINAL stage projects a statement result of
    /// its own under a layer's [`ConcludingVerdict`] — the one shared
    /// body-descent skeleton (ADR-0740): the FINAL-stage cursor (a
    /// `NEXT`-chained body is judged by its final stage, never its
    /// first), the any-arm fold over the stage's `UNION` arms, and the
    /// hand-off of each arm's concluding clause to the verdict, which
    /// receives this same descent back for the clause's nested bodies.
    /// The structural invariants are surfaced here, never defaulted
    /// over: a `Query` invariantly carries at least one part, and a part
    /// at least one clause (validation refuses an empty part before any
    /// fold runs).
    ///
    /// Two verdicts ride this one skeleton, and their agreement is the
    /// skeleton's contract: the naming layer's
    /// ([`Query::projects_columns`]: `RETURN`-only vocabulary with a
    /// first-branch stand-in) and the executor's (the planner's full
    /// clause table with any-branch breadth and its batched-call
    /// ruling). The two answer alike on every valid body — validation
    /// holds every `WHEN` branch and `UNION` arm to the same export
    /// shape, so the representative and the any-branch folds cannot
    /// disagree — and a new nested-body arm added to one verdict needs
    /// its twin arm in the other; the agreement test beside the
    /// executor's verdict pins it.
    pub fn final_stage_projects_rows(&self, verdict: &ConcludingVerdict) -> bool {
        stage_projects_rows(&self.final_stage().parts, verdict)
    }

    /// Whether this query projects columns: its true final stage (the end of
    /// its `NEXT` chain, not merely its own part list) ends in a `RETURN`,
    /// or in a `CONDITIONAL` / nested `CALL { … }` that projects. A body
    /// that does not — an update clause, a bare procedure call — leaves a
    /// `CALL { … }` a *unit* subquery.
    ///
    /// The one IR spelling of the fact: the planner's subquery-scope fold
    /// and the redundant-`OPTIONAL` notification detector both read it.
    /// The body-descent structure under it — the FINAL-stage cursor, the
    /// any-arm fold, the concluding-clause hand-off — is the one shared
    /// body-descent skeleton ([`Query::final_stage_projects_rows`],
    /// ADR-0740); this method is the naming layer's verdict over that
    /// skeleton ([`projects_columns_concluding`]), where the executor
    /// injects its own (the planner's full clause table with any-branch
    /// breadth and the batched-call ruling) — the two agree on every
    /// nested-body shape under the validated branch/arm representative
    /// agreement.
    pub fn projects_columns(&self) -> bool {
        self.final_stage_projects_rows(&projects_columns_concluding)
    }
}

/// A layer's concluding-clause verdict for the shared body-descent
/// skeleton ([`Query::final_stage_projects_rows`] /
/// [`stage_projects_rows`], ADR-0740): whether the clause concluding an
/// arm projects a statement result of its own. `descend` — the
/// skeleton's own body descent handed back — answers the clause's
/// nested bodies (a `WHEN` branch body, a nested `CALL { … }` body)
/// under the same verdict, so a layer folds them by its own breadth
/// without re-spelling the query structure the skeleton owns. The
/// descent's own type stays inline (`&dyn Fn(&Query) -> bool`): a named
/// alias for it would be a bare `dyn` defaulting to `'static`, which
/// the closures the skeleton hands back cannot satisfy.
pub type ConcludingVerdict = dyn Fn(&Clause, &dyn Fn(&Query) -> bool) -> bool;

/// The clause concluding a part — its last clause, with the part
/// invariant stated once, here: a part invariantly carries at least one
/// clause (validation refuses an empty part as `empty query part`
/// before any fold runs), so reaching an empty part is a broken
/// invariant to surface, never a verdict to fabricate. The skeleton's
/// arm fold and the executor's NEXT-seeding fold read this one
/// spelling.
pub fn part_concluding_clause(part: &[Clause]) -> &Clause {
    part.last()
        .expect("a part invariantly carries at least one clause")
}

/// The concluding clauses of a stage's parts — the skeleton's all-form
/// half, for the consumers that judge every arm instead of any arm
/// ([`stage_projects_rows`] is the any-form fold). The stage invariant
/// is surfaced once, here: a stage invariantly carries at least one
/// part, so an empty parts iterator is a broken invariant to surface,
/// never a fold that answers vacuously. The executor's NEXT-seeding
/// fold reads this one enumeration instead of re-spelling the walk and
/// its invariants.
pub fn stage_concluding_clauses<'p>(
    mut parts: impl Iterator<Item = &'p [Clause]>,
) -> impl Iterator<Item = &'p Clause> {
    let first = parts
        .next()
        .expect("a stage invariantly carries at least one part");
    std::iter::once(first)
        .chain(parts)
        .map(part_concluding_clause)
}

/// The stage-level entry of the one shared body-descent skeleton
/// (ADR-0740): whether any of one stage's `UNION` arms projects a
/// statement result of its own under a layer's [`ConcludingVerdict`].
/// [`Query::final_stage_projects_rows`] is the body-level form — the
/// same fold over a whole body's FINAL stage; this entry serves the one
/// caller that judges the stage it is about to run rather than a body
/// (the executor's stage driver, which holds the stage's own parts).
///
/// The skeleton owns the structure walk and surfaces its invariants: a
/// `Query` invariantly carries at least one part, a part at least one
/// clause (validation refuses an empty part as `empty query part`
/// before any fold runs) — both stated once, in
/// [`stage_concluding_clauses`], the one enumeration this any-form fold
/// and the executor's all-form fold read. A layer owns only its
/// clause-level verdict; the two current verdicts — the naming layer's
/// `RETURN`-only base with a first-branch stand-in, the executor's
/// planner-table base with any-branch breadth and the batched-call
/// ruling — agree on every valid body, and a new nested-body arm in one
/// needs its twin in the other.
pub fn stage_projects_rows(parts: &[SingleQuery], verdict: &ConcludingVerdict) -> bool {
    stage_concluding_clauses(parts.iter().map(|part| part.clauses.as_slice()))
        .any(|concluding| verdict(concluding, &|body| body.final_stage_projects_rows(verdict)))
}

/// The naming layer's [`ConcludingVerdict`]: a `RETURN` concludes a
/// projecting body; a `WHEN` clause's first branch stands in for the
/// whole clause (the grammar pushes one before its loop can break, and
/// validation holds every branch and arm to the same export shape, so
/// the stand-in and the executor's any-branch fold answer alike); a
/// nested `CALL { … }` is its body's answer. Everything else leaves the
/// body unit — no export columns, no statement result: the update
/// clauses, the read pipeline's interior and procedure-read clauses
/// (`MATCH`/`WITH`/`UNWIND`/`CALL` — a bare procedure call, unlike the
/// row-producing `CALL { … }`), the DDL/admin family, `LOAD CSV`,
/// `FINISH`, and the routing `USE`. [`Query::projects_columns`] is this
/// verdict's one spelling over the shared body-descent skeleton
/// (ADR-0740).
pub(super) fn projects_columns_concluding(
    clause: &Clause,
    descend: &dyn Fn(&Query) -> bool,
) -> bool {
    // Exhaustive on purpose — no `_ =>` — the discipline every clause
    // table over `Clause` carries (the planner's `clause_kind` tables
    // spell it in their own docs): a new IR variant is a compile error
    // here, forcing the naming ruling the same round its executor twin
    // is forced through the planner table — never a silent "no columns"
    // the verdict-agreement test cannot see.
    match clause {
        Clause::Return { .. } => true,
        Clause::Conditional { branches, .. } => descend(
            &branches
                .first()
                .expect("a WHEN clause has at least one branch")
                .1,
        ),
        Clause::CallSubquery { query, .. } => descend(query),
        Clause::Catalog(_)
        | Clause::Match { .. }
        | Clause::Create { .. }
        | Clause::Merge { .. }
        | Clause::Call { .. }
        | Clause::Delete { .. }
        | Clause::Set { .. }
        | Clause::Remove { .. }
        | Clause::With { .. }
        | Clause::Unwind { .. }
        | Clause::ShowIndexes
        | Clause::Finish
        | Clause::LoadCsv { .. }
        | Clause::Foreach { .. }
        | Clause::Use { .. }
        | Clause::CreateIndex { .. }
        | Clause::DropIndex { .. } => false,
    }
}