Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-gql/src/lower.rs

//! A parsed query lowered onto a [`Plan`].

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt;
use std::sync::Arc;

use kleene_graph::GraphBackend;
use kleene_plan::{
    Aggregate, Atom, BinOp, Cmp, Compute, Cond, Constant, Datum, EdgeTest, Engine, Func, Hops,
    IdRanges, Inputs, Literal, Marked, NullMark, Order, OrderKey, Plan, ProcArg, Procedure, Reduce,
    RelId, Rows, Shortest, Source, Stratum, Term, TextOp, Type, UnOp, Value, Var, Way, plan,
};

use crate::ast::{
    AggFn, CallArg, CallClause, CmpOp, Condition, Dir, EdgePattern, ListQuant, NodePattern,
    Operand, Quantifier, Query, ReturnItem, ReturnValue, Selector, Unwind, UnwindList, WholeFn,
};
use crate::error::{GqlError, Result};
use crate::whole::{EdgeAt, EdgeInfo, Entity, LabelInfo, NodeHow, Part, Want, Wholes};
use kleene_plan::Catalog;

/// A query lowered onto a plan: the plan, the sources of its inputs, and how its result
/// relation becomes the returned table.
#[derive(Clone, Debug)]
pub struct Lowered {
    /// The plan.
    pub plan: Plan,
    /// The sources of its input relations (labels, edges, properties the query names).
    pub inputs: Inputs,
    /// The relation of the matches (or of the returned rows, under `DISTINCT`).
    pub result: RelId,
    /// The path relations, one per quantified edge that needed one.
    pub paths: Vec<RelId>,
    columns: Vec<String>,
    pick: Vec<usize>,
    /// The `ORDER BY` keys: a column of the match relation, falling or not.
    order: Vec<(usize, bool)>,
    /// Counts with no groups: a row of zeros when nothing matches.
    zero_row: bool,
    /// The returned items that are lists (`nodes(p)`): the item and how to build it.
    lists: Vec<(usize, List)>,
    /// The returned items that hold float codes (a procedure's scores).
    floats: Vec<usize>,
    /// How each node is found and which quantified edges an index answers.
    notes: Vec<String>,
    /// With OPTIONAL MATCH: per clause (and per aggregate of its values), the found flag's
    /// column and the columns null where it is 0.
    found: Vec<Found>,
    /// The queries after `UNION [ALL]`, lowered.
    union: Vec<Lowered>,
    /// `UNION ALL`.
    union_all: bool,
    offset: Option<u64>,
    limit: Option<u64>,
    /// The part before a `WITH`, run first; its rows fill input relation `prior_rel`.
    prior: Option<Box<Lowered>>,
    prior_rel: Option<RelId>,
    /// What each returned column binds when this part is the one before a `WITH`.
    carry: Vec<Carry>,
    /// The returned items that are whole nodes, edges or parts of them.
    wholes: Wholes,
    /// The matches counted (one row per distinct binding with its number of matches):
    /// the output takes its rows each its count's times ([`Rows::Bag`]).
    mult: Option<RelId>,
}

/// What a column of the rows before a `WITH` binds after it.
#[derive(Clone, Debug)]
enum Carry {
    /// A node, with the label sets it had, and whether it was any node of any vertex table
    /// (its value its `id(n)`, not a row).
    Node(Vec<Vec<String>>, bool),
    /// A path's length (`I64` when it may be null, else `U64`).
    PathLen(Type),
    /// A value of this type (an unsigned value that may be null as `I64`).
    Value(Type),
}

impl Carry {
    fn ty(&self) -> Type {
        match self {
            Carry::Node(..) => Type::U64,
            Carry::PathLen(t) | Carry::Value(t) => *t,
        }
    }
}

/// The rows [`Lowered::shape`] gives and their null cells.
struct Shaped {
    rows: Vec<Vec<Value>>,
    nulls: Vec<(usize, usize)>,
}

/// The found flag of an OPTIONAL MATCH clause in the match relation (or of an aggregate of
/// its values in the grouped one).
#[derive(Clone, Debug)]
struct Found {
    /// Its column: 1 where the OPTIONAL MATCH extends the row, 0 where not.
    flag: usize,
    /// The match columns of the OPTIONAL MATCH's values (null where the flag is 0).
    nulls: Vec<usize>,
}

/// A shortest-paths relation's rows by (start, end, path): (position, vertex) pairs.
pub(crate) type PathsByEnds = HashMap<[Value; 3], Vec<(Value, Value)>>;

/// How a list item (`nodes(p)`) is built from a row of the match relation.
#[derive(Clone, Debug)]
enum List {
    /// A path of fixed edges: its nodes' columns and the base of each one's `id(n)`.
    Nodes(Vec<(usize, u64)>),
    /// A shortest path: its (start, end, path) columns, its vertices read from `rel`'s
    /// (start, end, path, position, vertex) rows.
    Shortest {
        /// The shortest-paths relation.
        rel: RelId,
        /// The columns of the start, the end and the path number.
        cols: [usize; 3],
    },
}

/// The rows a query returns.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Table {
    /// The column names.
    pub columns: Vec<String>,
    /// The rows, in order (`ORDER BY`, else by their values) and cut by `OFFSET` and `LIMIT`.
    /// A list column (`nodes(p)`) holds an index into [`Table::lists`].
    pub rows: Vec<Vec<Value>>,
    /// The columns that hold lists.
    pub list_columns: Vec<usize>,
    /// The lists the list columns point at.
    pub lists: Vec<Vec<Value>>,
    /// The columns that hold floats as order-keeping codes ([`kleene_plan::Type::F64`]'s;
    /// [`Table::float`] reads one).
    pub float_columns: Vec<usize>,
    /// The null cells, (row, column) rising: the values of an OPTIONAL MATCH that does not
    /// extend the row (their codes are 0).
    pub nulls: Vec<(usize, usize)>,
    /// The whole values, (row, column, value) rising: a returned node (its cell holds its
    /// value, the whole node is here), edge, `labels(n)`, `type(r)`, `properties(x)` or
    /// `relationships(p)` ([`Table::entity`]).
    pub entities: Vec<(usize, usize, Entity)>,
}

impl Table {
    /// The float in row `r`, column `c`, if `c` is a float column.
    pub fn float(&self, r: usize, c: usize) -> Option<f64> {
        if !self.float_columns.contains(&c) {
            return None;
        }
        match Type::F64.decode(*self.rows.get(r)?.get(c)?, None) {
            Datum::F64(x) => Some(x),
            _ => None,
        }
    }

    /// Whether row `r`'s value in column `c` is null.
    pub fn is_null(&self, r: usize, c: usize) -> bool {
        self.nulls.binary_search(&(r, c)).is_ok()
    }

    /// The whole value in row `r`, column `c` (a node, an edge, or a part of one).
    pub fn entity(&self, r: usize, c: usize) -> Option<&Entity> {
        entity_at(&self.entities, r, c)
    }

    /// The list in row `r`, column `c`, if `c` is a list column.
    pub fn list(&self, r: usize, c: usize) -> Option<&[Value]> {
        if !self.list_columns.contains(&c) {
            return None;
        }
        let i = usize::try_from(*self.rows.get(r)?.get(c)?).ok()?;
        self.lists.get(i).map(Vec::as_slice)
    }
}

impl Lowered {
    /// The plan's strata (each path relation in a reach or closure stratum).
    pub fn strata(&self) -> Result<Vec<Stratum>> {
        Ok(plan(&self.plan)?)
    }

    /// The counted relation of the matches ([`kleene_plan::Plan::derived_counted`]: one
    /// row per distinct binding, then its number of matches), when the rows are a bag
    /// ([`Rows::Bag`]) and not grouped: what a row's proof is asked of
    /// ([`kleene_plan::Output::why`] on a run of [`Lowered::plan`] by an explaining engine).
    pub fn matches(&self) -> Option<RelId> {
        self.mult
    }

    /// What the plan reads and runs: per node, an index lookup (`index lookup T.k in
    /// lo..=hi`), a label scan or its edges; per quantified edge an index answers, `reach
    /// index`; then each stratum's kind and the relations it derives.
    pub fn explain(&self) -> Result<String> {
        use std::fmt::Write;
        let mut s = String::new();
        if let Some(p) = &self.prior {
            let _ = writeln!(s, "{}WITH:", p.explain()?);
        }
        for n in &self.notes {
            let _ = writeln!(s, "{n}");
        }
        for st in self.strata()? {
            let names: Vec<String> = st
                .relations()
                .iter()
                .map(|&r| self.plan.relation_info(r).name.to_string())
                .collect();
            let _ = writeln!(s, "stratum: {} [{}]", st.kind(), names.join(", "));
        }
        for (k, part) in self.union.iter().enumerate() {
            let all = if self.union_all { " ALL" } else { "" };
            let _ = write!(s, "UNION{all} part {}:\n{}", k + 2, part.explain()?);
        }
        Ok(s)
    }

    /// The inputs of the run: with a `WITH`, the rows of the part before it (run first) as
    /// the input relation its names bind. A null node or unsigned value there is refused.
    async fn inputs_now<B: GraphBackend>(&self, engine: &Engine<B>) -> Result<Inputs> {
        let (Some(p), Some(rel)) = (&self.prior, self.prior_rel) else {
            return Ok(self.inputs.clone());
        };
        let t = Box::pin(p.run_typed(engine)).await?;
        // the rows as an input of their types (a counted input: each distinct row once with
        // its number of rows)
        let types: Vec<Type> = p.carry.iter().map(|c| c.ty()).collect();
        let mut inputs = self.inputs.clone();
        inputs
            .datums(rel, &types, &t.rows, self.plan.is_counted(rel))
            .map_err(|e| {
                GqlError::Semantic(format!(
                    "WITH {}: {e} (a null node or unsigned value is not passed on, in this \
                     version)",
                    p.columns.join(", ")
                ))
            })?;
        Ok(inputs)
    }

    /// Whether a returned column holds values [`Lowered::run`] does not return (a signed
    /// integer, a boolean, a string): run the query with [`Lowered::run_typed`].
    pub fn returns_typed(&self) -> bool {
        let typed = |l: &Lowered| {
            l.pick
                .iter()
                .any(|&c| !matches!(l.plan.col_type(l.result, c), Type::U64 | Type::F64))
        };
        typed(self) || self.union.iter().any(typed)
    }

    /// Run the plan on `engine` and shape the returned table: with `UNION`, each part's rows
    /// after the first's (`UNION ALL`), or the distinct rows sorted (`UNION`).
    pub async fn run<B: GraphBackend>(&self, engine: &Engine<B>) -> Result<Table> {
        let mut t = self.run_one(engine).await?;
        if self.union.is_empty() {
            return Ok(t);
        }
        for part in &self.union {
            let u = part.run_one(engine).await?;
            if u.float_columns != t.float_columns {
                return Err(GqlError::Semantic(
                    "UNION parts with a float column in one and not the other".into(),
                ));
            }
            let n = t.rows.len();
            t.entities
                .extend(u.entities.into_iter().map(|(r, c, e)| (r + n, c, e)));
            let mut m = Marked {
                rows: std::mem::take(&mut t.rows),
                nulls: std::mem::take(&mut t.nulls),
            };
            m.append(Marked {
                rows: u.rows,
                nulls: u.nulls,
            });
            (t.rows, t.nulls) = (m.rows, m.nulls);
        }
        if !self.union_all {
            // A null and a 0 are not one value: each cell with its null mark (nulls last).
            // A whole value is one by all of it (two edges from one node are two rows).
            // (each row with the row it was, for its whole values)
            let mut whole: Vec<Vec<String>> = vec![Vec::new(); t.rows.len()];
            for (r, c, e) in &t.entities {
                whole[*r].push(format!("{c} {e}"));
            }
            let mut m = Marked {
                rows: std::mem::take(&mut t.rows),
                nulls: std::mem::take(&mut t.nulls),
            };
            let was: HashMap<usize, usize> = m
                .distinct(&whole)
                .into_iter()
                .enumerate()
                .map(|(i, at)| (at, i))
                .collect();
            (t.rows, t.nulls) = (m.rows, m.nulls);
            let mut entities: Vec<(usize, usize, Entity)> = std::mem::take(&mut t.entities)
                .into_iter()
                .filter_map(|(r, c, e)| was.get(&r).map(|&i| (i, c, e)))
                .collect();
            entities.sort_by_key(|e| (e.0, e.1));
            t.entities = entities;
        }
        Ok(t)
    }

    /// The shortest paths that lists and whole values read: per relation, each path's
    /// (position, vertex) rising by its (start, end, number).
    fn shortest_paths(&self, out: &kleene_plan::Output) -> Result<HashMap<RelId, PathsByEnds>> {
        let mut paths: HashMap<RelId, PathsByEnds> = HashMap::new();
        let rels = self
            .lists
            .iter()
            .filter_map(|(_, l)| match l {
                List::Shortest { rel, .. } => Some(*rel),
                List::Nodes(_) => None,
            })
            .chain(self.wholes.shortest_rels());
        for rel in rels {
            if paths.contains_key(&rel) {
                continue;
            }
            let f = out
                .get(rel)
                .ok_or_else(|| GqlError::Semantic("the shortest paths were not derived".into()))?;
            let mut by: PathsByEnds = HashMap::new();
            for r in f.rows() {
                by.entry([r[0], r[1], r[2]]).or_default().push((r[3], r[4]));
            }
            for v in by.values_mut() {
                v.sort_unstable();
            }
            paths.insert(rel, by);
        }
        Ok(paths)
    }

    async fn run_one<B: GraphBackend>(&self, engine: &Engine<B>) -> Result<Table> {
        if let Some(c) = self
            .pick
            .iter()
            .position(|&c| !matches!(self.plan.col_type(self.result, c), Type::U64 | Type::F64))
        {
            return Err(GqlError::Unsupported(format!(
                "`{}` is not an unsigned integer: run the query with run_typed",
                self.columns[c]
            )));
        }
        let inputs = self.inputs_now(engine).await?;
        let out = engine.run(&self.plan, &inputs).await?;
        let Shaped { mut rows, nulls } = self.shape(&out)?;
        let paths = self.shortest_paths(&out)?;
        let entities = self
            .wholes
            .build(engine, &rows, self.pick.len(), &nulls, &paths)
            .await?;
        // List items: each row's list built from the match row kept after the picks.
        let mut lists: Vec<Vec<Value>> = Vec::new();
        if !self.lists.is_empty() {
            let n = self.pick.len();
            for row in &mut rows {
                for (item, l) in &self.lists {
                    let full = &row[n..];
                    let list: Vec<Value> = match l {
                        List::Nodes(cols) => cols.iter().map(|&(c, base)| full[c] + base).collect(),
                        List::Shortest { rel, cols } => paths[rel]
                            .get(&[full[cols[0]], full[cols[1]], full[cols[2]]])
                            .map(|v| v.iter().map(|x| x.1).collect())
                            .unwrap_or_default(),
                    };
                    row[*item] = lists.len() as Value;
                    lists.push(list);
                }
                row.truncate(n);
            }
        }
        for row in &mut rows {
            row.truncate(self.pick.len());
        }
        Ok(Table {
            columns: self.columns.clone(),
            rows,
            list_columns: self.lists.iter().map(|l| l.0).collect(),
            lists,
            float_columns: (0..self.pick.len())
                .filter(|&i| {
                    self.floats.contains(&i)
                        || self.plan.col_type(self.result, self.pick[i]) == Type::F64
                })
                .collect(),
            nulls,
            entities,
        })
    }

    /// [`Lowered::run`] with every returned value by its type (strings as strings, a
    /// missing or null property as null). A query that returns a list is refused here.
    pub async fn run_typed<B: GraphBackend>(&self, engine: &Engine<B>) -> Result<TypedTable> {
        if !self.union.is_empty() && !self.union_all {
            return Err(GqlError::Unsupported(
                "UNION with typed values: UNION ALL, or run".into(),
            ));
        }
        let mut t = self.run_typed_one(engine).await?;
        for part in &self.union {
            let u = part.run_typed_one(engine).await?;
            let n = t.rows.len();
            t.entities
                .extend(u.entities.into_iter().map(|(r, c, e)| (r + n, c, e)));
            t.rows.extend(u.rows);
        }
        Ok(t)
    }

    async fn run_typed_one<B: GraphBackend>(&self, engine: &Engine<B>) -> Result<TypedTable> {
        if !self.lists.is_empty() {
            return Err(GqlError::Unsupported(
                "a returned list with typed values: use run".into(),
            ));
        }
        let inputs = self.inputs_now(engine).await?;
        let out = engine.run(&self.plan, &inputs).await?;
        let types: Vec<Type> = self
            .pick
            .iter()
            .map(|&c| self.plan.col_type(self.result, c))
            .collect();
        let shaped = self.shape(&out)?;
        let paths = self.shortest_paths(&out)?;
        let entities = self
            .wholes
            .build(engine, &shaped.rows, self.pick.len(), &shaped.nulls, &paths)
            .await?;
        let rows = shaped
            .rows
            .into_iter()
            .enumerate()
            .map(|(i, r)| {
                r.into_iter()
                    .zip(&types)
                    .enumerate()
                    .map(|(c, (v, t))| {
                        if shaped.nulls.binary_search(&(i, c)).is_ok() {
                            Datum::Null
                        } else {
                            t.decode(v, out.dict())
                        }
                    })
                    .collect()
            })
            .collect();
        Ok(TypedTable {
            columns: self.columns.clone(),
            rows,
            entities,
        })
    }

    /// The match rows as codes: ordered, cut by `OFFSET` and `LIMIT` (the core's output
    /// operator, [`kleene_plan::Order`]: the `ORDER BY` keys, null where their clause's
    /// found flag is 0, then the picks, the whole row when lists or whole values read it,
    /// the flags), the picks first (and the whole match row after them when lists are
    /// returned).
    fn shape(&self, out: &kleene_plan::Output) -> Result<Shaped> {
        let facts = out
            .get(self.result)
            .ok_or_else(|| GqlError::Semantic("the match relation was not derived".into()))?;
        let marks: Vec<NullMark> = self
            .found
            .iter()
            .map(|f| NullMark {
                flag: f.flag,
                cols: f.nulls.clone(),
            })
            .collect();
        let mut order = Order::new();
        for &(c, desc) in &self.order {
            let key = if desc {
                OrderKey::desc(c)
            } else {
                OrderKey::asc(c)
            };
            order = order.by(key.null_by(&marks));
        }
        let whole = !self.lists.is_empty() || self.wholes.needs_row();
        let cols: Vec<usize> = self
            .pick
            .iter()
            .copied()
            .chain((0..facts.arity()).filter(|_| whole))
            .chain(self.found.iter().map(|f| f.flag))
            .collect();
        for c in cols {
            order = order.by(OrderKey::asc(c));
        }
        order.offset = self.offset.unwrap_or(0);
        order.limit = self.limit;
        // Counts with no groups over no matches: one row of zeros.
        // One row per match: the counted matches, each its count's times.
        let rows: Vec<Vec<Value>> = if self.zero_row && facts.is_empty() {
            order.apply(&self.plan.types(self.result), vec![vec![0; facts.arity()]])
        } else {
            match self.mult {
                Some(m) => out.ordered(&self.plan, m, Rows::Bag, &order)?,
                None => out.ordered(&self.plan, self.result, Rows::Distinct, &order)?,
            }
        };
        // each flag 0 makes its columns null
        let Marked { rows, nulls } = Marked::pick(rows, &self.pick, whole, &marks);
        Ok(Shaped { rows, nulls })
    }
}

/// The rows a query returns, each value by its type ([`Lowered::run_typed`]).
#[derive(Clone, Debug, PartialEq)]
pub struct TypedTable {
    /// The column names.
    pub columns: Vec<String>,
    /// The rows, in the order of [`Table::rows`].
    pub rows: Vec<Vec<Datum>>,
    /// The whole values, as in [`Table::entities`].
    pub entities: Vec<(usize, usize, Entity)>,
}

impl TypedTable {
    /// The whole value in row `r`, column `c`, as [`Table::entity`].
    pub fn entity(&self, r: usize, c: usize) -> Option<&Entity> {
        entity_at(&self.entities, r, c)
    }
}

fn entity_at(es: &[(usize, usize, Entity)], r: usize, c: usize) -> Option<&Entity> {
    es.binary_search_by(|e| (e.0, e.1).cmp(&(r, c)))
        .ok()
        .map(|i| &es[i].2)
}

impl fmt::Display for TypedTable {
    /// The table as [`Table`] prints it, strings quoted.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let cells: Vec<Vec<String>> = self
            .rows
            .iter()
            .enumerate()
            .map(|(i, r)| {
                r.iter()
                    .enumerate()
                    .map(|(c, v)| match self.entity(i, c) {
                        Some(e) => e.to_string(),
                        None => v.to_string(),
                    })
                    .collect()
            })
            .collect();
        text_table(f, &self.columns, &cells)
    }
}

impl fmt::Display for Table {
    /// The table as text: a header, a rule, one line per row (values right-aligned in
    /// columns `|`-separated), and the row count.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let cells: Vec<Vec<String>> = self
            .rows
            .iter()
            .enumerate()
            .map(|(i, r)| {
                r.iter()
                    .enumerate()
                    .map(|(c, v)| match (self.list(i, c), self.float(i, c)) {
                        _ if self.is_null(i, c) => "null".to_string(),
                        _ if self.entity(i, c).is_some() => {
                            self.entity(i, c).expect("checked").to_string()
                        }
                        (Some(l), _) => format!(
                            "[{}]",
                            l.iter()
                                .map(|x| x.to_string())
                                .collect::<Vec<_>>()
                                .join(", ")
                        ),
                        (_, Some(x)) => format!("{x:.6}"),
                        _ => v.to_string(),
                    })
                    .collect()
            })
            .collect();
        text_table(f, &self.columns, &cells)
    }
}

fn text_table(
    f: &mut fmt::Formatter<'_>,
    columns: &[String],
    cells: &[Vec<String>],
) -> fmt::Result {
    let width: Vec<usize> = (0..columns.len())
        .map(|c| {
            cells
                .iter()
                .map(|r| r[c].len())
                .chain([columns[c].chars().count()])
                .max()
                .unwrap_or(0)
        })
        .collect();
    let line = |f: &mut fmt::Formatter<'_>, items: &[String], right: bool| -> fmt::Result {
        for (c, it) in items.iter().enumerate() {
            let sep = if c == 0 { " " } else { " | " };
            if right {
                write!(f, "{sep}{it:>w$}", w = width[c])?;
            } else if c + 1 == items.len() {
                write!(f, "{sep}{it}")?;
            } else {
                write!(f, "{sep}{it:<w$}", w = width[c])?;
            }
        }
        writeln!(f)
    };
    line(f, columns, false)?;
    let rule: Vec<String> = width.iter().map(|&w| "-".repeat(w + 2)).collect();
    writeln!(f, "{}", rule.join("+"))?;
    for r in cells {
        line(f, r, true)?;
    }
    let n = cells.len();
    writeln!(f, "({n} row{})", if n == 1 { "" } else { "s" })
}

/// Values of a query's parameters (`$name`), by name (without the `$`).
pub type Params = BTreeMap<String, Param>;

/// A parameter's value.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Param {
    /// An unsigned integer: a value where one goes.
    Int(Value),
    /// A list of unsigned integers: for `UNWIND $name AS x`.
    List(Vec<Value>),
}

impl From<Value> for Param {
    fn from(v: Value) -> Self {
        Param::Int(v)
    }
}

/// Parse `text`, lower it with `catalog` and run it on `engine`.
pub async fn query<B: GraphBackend>(
    engine: &Engine<B>,
    catalog: &Catalog,
    text: &str,
) -> Result<Table> {
    query_with(engine, catalog, text, &Params::new()).await
}

/// [`query`] with values for the query's parameters.
pub async fn query_with<B: GraphBackend>(
    engine: &Engine<B>,
    catalog: &Catalog,
    text: &str,
    params: &Params,
) -> Result<Table> {
    lower_with(&crate::parse(text)?, catalog, params)?
        .run(engine)
        .await
}

/// A value a comparison or `RETURN` reads, resolved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Val {
    /// A node (its id).
    Node(usize),
    /// A property of a node: (node, property slot).
    Prop(usize, usize),
    /// A property of an edge: its two nodes and the slot.
    EdgeProp {
        /// The node before (its first column).
        from: usize,
        /// The node after.
        to: usize,
        /// The slot in the edge properties.
        slot: usize,
    },
    /// A value a procedure yields (its slot).
    Yield(usize),
    /// The number of edges of a shortest path (its path variable's slot).
    PathLen(usize),
    /// The number of a shortest path among those of its pair of ends.
    PathId(usize),
    /// A constant.
    Const(Value),
    /// An arithmetic value (its slot) and the nodes it reads (a bit each, below 64).
    Calc {
        /// The slot in the arithmetic values.
        slot: usize,
        /// The nodes it reads.
        nodes: u64,
    },
}

/// One side of an arithmetic value: the value it reads (none for a constant), its term
/// and type.
#[derive(Clone, Copy, Debug)]
struct CalcSide {
    val: Option<Val>,
    term: Term,
    ty: Type,
}

impl CalcSide {
    /// The side in an expression: a value's term, or a constant as a number (a float code
    /// where the expression is a float's, `float`); a null constant is `0 / 0`, which is
    /// null.
    fn expr(&self, float: bool) -> kleene_plan::Expr {
        use kleene_plan::Expr;
        if self.val.is_some() {
            return Expr::from(self.term);
        }
        let Term::Const(code) = self.term else {
            return Expr::from(self.term);
        };
        let zero = || {
            if float {
                Expr::from(Term::float(0.0))
            } else {
                Expr::from(0u64)
            }
        };
        let null = || Expr::op(BinOp::Div, zero(), zero());
        match self.ty.decode(code, None) {
            Datum::U64(u) if float => Expr::from(Term::float(u as f64)),
            Datum::U64(u) => Expr::from(u),
            Datum::I64(i) if float => Expr::from(Term::float(i as f64)),
            Datum::I64(i) if i >= 0 => Expr::from(i as u64),
            Datum::I64(i) => Expr::unary(UnOp::Neg, Expr::from(i.unsigned_abs())),
            Datum::Null => null(),
            _ => Expr::from(self.term),
        }
    }
}

/// An arithmetic value: `var = expr` (a [`Compute`] of the rule, of type `ty`) over the
/// values `vals` reads.
#[derive(Clone, Debug)]
struct Calc {
    vals: Vec<Val>,
    expr: kleene_plan::Expr,
    var: Var,
    ty: Type,
}

/// The operator of an arithmetic value.
#[derive(Clone, Copy, Debug)]
enum CalcOp {
    Bin(BinOp),
    Un(UnOp),
}

/// One node variable of the query.
struct Node {
    name: String,
    /// Label sets: the node has a label of each set (a set of one: that label).
    labels: Vec<Vec<String>>,
    /// Step ends and lone patterns it stands in.
    touches: usize,
    /// Step ends it stands in.
    steps: usize,
    /// A procedure yields it, or the part before a `WITH` binds it.
    called: bool,
    /// With no label and no edge in a catalog of one id space: any node, its labels every
    /// label of no other label's nodes.
    anything: bool,
    /// With no label and no edge in a catalog of vertex tables: any row of any table,
    /// its value its `id(n)` ([`Catalog::vertex_table`]).
    global: bool,
    /// With no label: the vertex table its edges' ends name ([`Catalog::edge_ends`]).
    table: Option<String>,
    var: Var,
}

/// A property of a node the query reads.
struct Prop {
    node: usize,
    key: String,
    rel: RelId,
    var: Var,
}

/// A literal of a comparison, before it is coded for the value it meets.
#[derive(Clone, Debug)]
enum Lit {
    Uint(u64),
    Int(i64),
    Float(f64),
    Str(String),
    Bool(bool),
    Null,
}

/// The mark of an edge label's rows in a catalog name (`E@row`, `E@row.p`).
const EDGE_ROW: &str = "@row";

/// A property of an edge the query reads: (from, to, value) along `rel`, or, for an edge
/// read by its rows ([`EdgeVar::rows`]), (row terms, value); the value in column `col`.
struct EdgeProp {
    edge: usize,
    rel: RelId,
    var: Var,
    col: usize,
}

/// An edge variable: the edge between two nodes of one step, its labels (all edge labels
/// when it has none) and whether it goes either way or is quantified.
struct EdgeVar {
    name: String,
    from: usize,
    to: usize,
    labels: Vec<String>,
    any: bool,
    quantified: bool,
    /// Read by its rows (the catalog's `E@row`): the relation of its edges, its columns the
    /// row terms then (from, to), and the row terms' variables (the row; for several labels
    /// or either way the label's number first). Two edges between the same nodes are then
    /// two matches, each with its own values.
    rows: Option<(RelId, Vec<Var>)>,
}

/// A value column a `CALL` yields (or a `WITH` passes on).
struct YieldVar {
    name: String,
    var: Var,
    /// Its type.
    ty: Type,
    /// A path's length (through a `WITH`).
    path: bool,
}

/// A path variable (or a selector's path with no variable).
struct PathVar {
    name: String,
    kind: PathKind,
}

enum PathKind {
    /// Fixed edges: the nodes in order.
    Fixed(Vec<usize>),
    /// A shortest path from `start` to `end`: its length and number.
    Shortest {
        start: usize,
        end: usize,
        len: Var,
        id: Var,
    },
}

/// One edge between two nodes, direction resolved: along `rel` from `from` to `to`.
struct Step {
    from: usize,
    to: usize,
    rel: RelId,
    label: String,
    /// `None`: one edge; `Some(m)`: `m` (0 or 1) or more, a reach or closure.
    min: Option<u64>,
    /// Any other length range: a walk ([`kleene_plan::Plan::walk`]).
    walk: Option<Hops>,
    /// Under a selector: the path variable, which paths, the lengths, and whether the
    /// path's start is `from` (else it goes against `rel` from `to`).
    shortest: Option<(usize, Shortest, Hops, bool)>,
    /// Its edge labels, either way, of a variable length (for [`two_tables`]).
    edge: (Vec<String>, bool, bool),
    /// Its edge variable.
    var: Option<usize>,
}

struct Lowering<'a> {
    catalog: &'a Catalog,
    params: &'a Params,
    plan: Plan,
    inputs: Inputs,
    rels: HashMap<(u8, String), RelId>,
    nodes: Vec<Node>,
    by_name: HashMap<String, usize>,
    edge_vars: Vec<EdgeVar>,
    props: Vec<Prop>,
    eprops: Vec<EdgeProp>,
    path_vars: Vec<PathVar>,
    /// Per property relation, the relation of the nodes that have a row in it.
    has: HashMap<RelId, RelId>,
    yields: Vec<YieldVar>,
    /// The names a `CALL` binds, in its columns' order.
    yield_names: Vec<String>,
    /// Per node found by an index lookup, the relation of the nodes it finds.
    hits: HashMap<usize, RelId>,
    /// For [`Lowered::explain`].
    notes: Vec<String>,
    /// The arithmetic values.
    calcs: Vec<Calc>,
    /// One row per match (the standard) or per distinct row.
    rows: Rows,
    /// The edge relations of several labels or either way ([`Lowering::edge_rel`]): their
    /// labels and whether either way, for their counts.
    edge_unions: HashMap<RelId, (Vec<String>, bool)>,
}

impl Lowering<'_> {
    /// A derived counted relation over `vals` (then the count), typed by them.
    fn derived_counted(&mut self, name: &str, vals: &[Val]) -> RelId {
        let types: Vec<Type> = vals
            .iter()
            .map(|&v| self.ty(v).unwrap_or_default())
            .collect();
        self.plan.derived_counted(name, &types)
    }

    /// The counted relation of edge label `label`'s parallel edges ([`Catalog::edge_counts`])
    /// when `rel` is that label's edges as they are (not a union, not filtered).
    fn edge_counts_rel(&mut self, label: &str, rel: RelId) -> Option<RelId> {
        if self.rels.get(&(1, label.to_string())) != Some(&rel) {
            return None;
        }
        let source = self.catalog.edge_count_source(label)?.clone();
        let key = (9, label.to_string());
        if let Some(&r) = self.rels.get(&key) {
            return Some(r);
        }
        let r = self
            .plan
            .input_counted(&format!("{label} counts"), &[Type::U64, Type::U64]);
        self.inputs.set(r, source);
        self.rels.insert(key, r);
        Some(r)
    }

    /// An atom of `rel` over `vars`, and a fresh variable for its count when it is counted.
    fn atom_n(&mut self, rel: RelId, vars: &[Var]) -> Literal {
        let mut vs = vars.to_vec();
        if self.plan.is_counted(rel) {
            vs.push(self.plan.var("n"));
        }
        atom(rel, &vs)
    }

    /// `rel(head) :- body`: a counting rule (the count a fresh variable after `head`) when
    /// `rel` is counted.
    fn rule_n(&mut self, rel: RelId, mut head: Vec<Term>, body: Vec<Literal>) -> Result<()> {
        if self.plan.is_counted(rel) {
            head.push(Term::Var(self.plan.var("N")));
            self.plan.count_rule(Atom { rel, terms: head }, body)?;
        } else {
            self.plan.rule(Atom { rel, terms: head }, body)?;
        }
        Ok(())
    }

    /// The plan relation of a catalog name (`kind` 0 node label, 1 edge label, 2 property),
    /// declared and given its source the first time.
    fn input(&mut self, kind: u8, name: &str, arity: usize, source: &Source) -> RelId {
        if let Some(&r) = self.rels.get(&(kind, name.to_string())) {
            return r;
        }
        let r = self.plan.input(name, arity);
        self.inputs.set(r, source.clone());
        self.rels.insert((kind, name.to_string()), r);
        r
    }

    /// The source and value type of property `key` of label `lab` (an edge label with
    /// `edge`), read by `form` when given (the catalog's relation `lab.key@form`).
    fn prop_source(
        &self,
        lab: &str,
        key: &str,
        form: Option<&str>,
        edge: bool,
    ) -> Result<(Source, Type)> {
        if let Some(form) = form {
            let (source, types) = self
                .catalog
                .relation(&format!("{lab}.{key}@{form}"))
                .map_err(|e| GqlError::Unsupported(e.to_string()))?;
            let ty = *types.last().expect("a property has a value column");
            return Ok((source, ty));
        }
        Ok(if edge {
            let source = self.catalog.edge_prop(lab, key).expect("checked").clone();
            (source, self.catalog.edge_property_type(lab, key))
        } else {
            let source = self.catalog.label_prop(lab, key).expect("checked").clone();
            (source, self.catalog.prop_type(lab, key))
        })
    }

    /// The (from, to, value) relation of property `key` of the `label` edges, of the type the
    /// catalog gives it ([`Catalog::edge_property_type`]): a procedure's weights or
    /// capacities, mapped as they are. Which types a procedure takes is the plan's
    /// [`Plan::procedure`] to check.
    fn edge_values(&mut self, label: &str, key: &str) -> Result<RelId> {
        if let Some(why) = self.catalog.refused_prop(Some(label), key, true) {
            return Err(GqlError::Unsupported(why));
        }
        if self.catalog.edge_prop(label, key).is_none() {
            return Err(GqlError::Semantic(format!(
                "no property `{key}` for edge `{label}`"
            )));
        }
        let name = format!("{label}.{key}");
        if let Some(&r) = self.rels.get(&(3, name.clone())) {
            return Ok(r);
        }
        // the relation by name: its source and column types from the core's catalog
        let r = self.plan.input_from(self.catalog, &name)?;
        self.inputs.set(r, self.catalog.relation(&name)?.0);
        self.rels.insert((3, name), r);
        Ok(r)
    }

    fn node(&mut self, var: &Option<String>, labels: &[String]) -> Result<usize> {
        if let Some(v) = var
            && self.yields.iter().any(|y| y.name == *v)
        {
            return Err(GqlError::Semantic(format!(
                "`{v}` is a value the procedure yields, not a node"
            )));
        }
        let i = match var {
            Some(v) if self.by_name.contains_key(v) => self.by_name[v],
            _ => {
                let name = var
                    .clone()
                    .unwrap_or_else(|| format!("_{}", self.nodes.len() + 1));
                let pv = self.plan.var(&name);
                self.nodes.push(Node {
                    name: name.clone(),
                    labels: Vec::new(),
                    touches: 0,
                    steps: 0,
                    called: false,
                    anything: false,
                    global: false,
                    table: None,
                    var: pv,
                });
                if var.is_some() {
                    self.by_name.insert(name, self.nodes.len() - 1);
                }
                self.nodes.len() - 1
            }
        };
        if !labels.is_empty() {
            for l in labels {
                if self.catalog.node_label(l).is_none() {
                    return Err(GqlError::Semantic(format!("no node label `{l}`")));
                }
            }
            let mut set = labels.to_vec();
            set.sort_unstable();
            set.dedup();
            if !self.nodes[i].labels.contains(&set) {
                self.nodes[i].labels.push(set);
            }
        }
        Ok(i)
    }

    /// The relation of a union of `names` (one rule each), or the one relation of a single
    /// name; `one` gives each name's relation. Made once per kind and names.
    fn union(
        &mut self,
        kind: u8,
        names: &[String],
        arity: usize,
        one: &dyn Fn(&mut Self, &str) -> RelId,
    ) -> Result<RelId> {
        if let [n] = names {
            return Ok(one(self, n));
        }
        let key = (kind, names.join("|"));
        if let Some(&r) = self.rels.get(&key) {
            return Ok(r);
        }
        let r = self.plan.derived(&key.1, arity);
        let vars: Vec<Var> = (0..arity)
            .map(|i| self.plan.var(&format!("U{i}")))
            .collect();
        for n in names {
            let x = one(self, n);
            self.plan.rule(at(r, &vars), [at(x, &vars)])?;
        }
        self.rels.insert(key, r);
        Ok(r)
    }

    /// `r` read either way: `r(X, Y)` or `r(Y, X)` (the rest of the columns kept).
    fn either_way(&mut self, r: RelId) -> Result<RelId> {
        let name = format!("{}~", self.plan.relation_info(r).name);
        let key = (5, name.clone());
        if let Some(&e) = self.rels.get(&key) {
            return Ok(e);
        }
        let arity = self.plan.relation_info(r).arity;
        let e = if self.plan.is_typed(r) {
            let types = self.plan.types(r);
            self.plan.derived_typed(&name, &types)
        } else {
            self.plan.derived(&name, arity)
        };
        let vars: Vec<Var> = (0..arity)
            .map(|i| self.plan.var(&format!("W{i}")))
            .collect();
        let mut back = vars.clone();
        back.swap(0, 1);
        self.plan.rule(at(e, &vars), [at(r, &vars)])?;
        self.plan.rule(at(e, &back), [at(r, &vars)])?;
        self.rels.insert(key, e);
        Ok(e)
    }

    /// The edge relation of `labels` (all edge labels when empty), either way when `any`.
    fn edge_rel(&mut self, labels: &[String], any: bool) -> Result<(RelId, String)> {
        let all: Vec<String>;
        let names = if labels.is_empty() {
            all = self.catalog.edge_labels().map(String::from).collect();
            if all.is_empty() {
                return Err(GqlError::Semantic("no edge labels".into()));
            }
            &all
        } else {
            labels
        };
        for n in names {
            if self.catalog.edge_label(n).is_none() {
                return Err(GqlError::Semantic(format!("no edge label `{n}`")));
            }
        }
        let mut names = names.to_vec();
        names.sort_unstable();
        names.dedup();
        // (a label with another name in the list: once, under that name)
        let aliased: Vec<String> = names
            .iter()
            .filter_map(|n| self.catalog.alias_of(n))
            .filter(|of| names.iter().any(|x| x == of))
            .map(String::from)
            .collect();
        names.retain(|n| !aliased.contains(n));
        let one = |l: &mut Self, n: &str| {
            let source = l.catalog.edge_label(n).expect("checked").clone();
            l.input(1, n, 2, &source)
        };
        let mut r = self.union(1, &names, 2, &one)?;
        if any {
            r = self.either_way(r)?;
        }
        if any || names.len() > 1 {
            self.edge_unions.insert(r, (names.clone(), any));
        }
        Ok((r, names.join("|")))
    }

    /// The matches of an edge of `names` (either way when `any`) between each pair: a
    /// counted relation adding up each label's edges (its parallel ones too) each way it
    /// is read (a self loop once).
    fn union_counts(&mut self, names: &[String], any: bool) -> Result<RelId> {
        let key = (
            10,
            format!("{} counts{}", names.join("|"), if any { "~" } else { "" }),
        );
        if let Some(&r) = self.rels.get(&key) {
            return Ok(r);
        }
        let c = self.plan.derived_counted(&key.1, &[Type::U64, Type::U64]);
        let (x, y) = (self.plan.var("CX"), self.plan.var("CY"));
        for n in names {
            let source = self.catalog.edge_label(n).expect("checked").clone();
            let base = self.input(1, n, 2, &source);
            let src = self.edge_counts_rel(n, base).unwrap_or(base);
            let lit = self.atom_n(src, &[x, y]);
            self.rule_n(c, vec![Term::Var(x), Term::Var(y)], vec![lit])?;
            if any {
                let lit = self.atom_n(src, &[y, x]);
                let ne = Literal::Cond(Cond::Cmp {
                    left: Term::Var(x),
                    op: Cmp::Ne,
                    right: Term::Var(y),
                });
                self.rule_n(c, vec![Term::Var(x), Term::Var(y)], vec![lit, ne])?;
            }
        }
        self.rels.insert(key, c);
        Ok(c)
    }

    /// The relation of property `key` of node `n`: of a label the node must have, else of
    /// the labels of one of its label sets that have it (a union), else, for a node with no
    /// label, of the only label that has such a property.
    fn node_prop(&mut self, n: usize, key: &str) -> Result<Option<RelId>> {
        // (`k@form`, such as `hex(n.k)`: property `k` read by that form, the catalog's
        // relation `L.k@form`)
        let (key, form) = split_form(key);
        if self.nodes[n].global {
            if form.is_some() {
                return Err(GqlError::Unsupported(format!(
                    "a form of property `{key}` of a node of any vertex table"
                )));
            }
            return self.global_prop(key);
        }
        let sets = self.nodes[n].labels.clone();
        let mut labels: Vec<Option<&str>> =
            sets.iter().flatten().map(|l| Some(l.as_str())).collect();
        if sets.is_empty() {
            labels.push(None);
        }
        if let Some(why) = labels
            .into_iter()
            .find_map(|l| self.catalog.refused_prop(l, key, false))
        {
            return Err(GqlError::Unsupported(why));
        }
        let one = |l: &mut Self, lab: &str| l.label_prop_rel(lab, key, form);
        for set in sets.iter().filter(|s| s.len() == 1) {
            if self.catalog.label_prop(&set[0], key).is_some() {
                return Ok(Some(one(self, &set[0])?));
            }
        }
        // A node with no label: of every label holding the key (one alone as above).
        let holders = [self.catalog.holders(key)];
        let sets_or = if sets.is_empty() {
            &holders[..]
        } else {
            &sets[..]
        };
        if let [only] = sets_or
            && only.len() == 1
            && sets.is_empty()
        {
            return Ok(Some(one(self, &only[0])?));
        }
        for set in sets_or {
            let with: Vec<String> = set
                .iter()
                .filter(|lab| self.catalog.label_prop(lab, key).is_some())
                .cloned()
                .collect();
            if !with.is_empty() {
                let names: Vec<String> = with
                    .iter()
                    .map(|lab| with_form(&format!("{lab}.{key}"), form))
                    .collect();
                let key2 = (6, names.join("|"));
                if let Some(&r) = self.rels.get(&key2) {
                    return Ok(Some(r));
                }
                let tys: Vec<Type> = with
                    .iter()
                    .map(|lab| {
                        let lab = self.catalog.prop_owner(lab, key).unwrap_or(lab);
                        Ok(self.prop_source(lab, key, form, false)?.1)
                    })
                    .collect::<Result<_>>()?;
                if tys.iter().any(|&t| t != tys[0]) {
                    return Err(GqlError::Semantic(format!(
                        "property `{key}` has another type on each of {}",
                        with.join(", ")
                    )));
                }
                let r = if tys[0] == Type::U64 {
                    self.plan.derived(&key2.1, 2)
                } else {
                    self.plan.derived_typed(&key2.1, &[Type::U64, tys[0]])
                };
                let (x, v) = (self.plan.var("U0"), self.plan.var("U1"));
                for lab in &with {
                    let i = one(self, lab)?;
                    self.plan.rule(at(r, &[x, v]), [at(i, &[x, v])])?;
                }
                self.rels.insert(key2, r);
                return Ok(Some(r));
            }
        }
        Ok(None)
    }

    /// The (node, value) input of property `key` of label `lab`'s nodes, read by `form` when
    /// given: of the label holding the property (a kind label's: its label's, one relation
    /// for both), of the catalog's type. The label must have the property.
    fn label_prop_rel(&mut self, lab: &str, key: &str, form: Option<&str>) -> Result<RelId> {
        let lab = self
            .catalog
            .prop_owner(lab, key)
            .expect("checked")
            .to_string();
        let (source, ty) = self.prop_source(&lab, key, form, false)?;
        let name = with_form(&format!("{lab}.{key}"), form);
        Ok(match self.rels.get(&(2, name.clone())) {
            Some(&r) => r,
            None if ty == Type::U64 => self.input(2, &name, 2, &source),
            None => {
                let r = self.plan.input_typed(&name, &[Type::U64, ty]);
                self.inputs.set(r, source);
                self.rels.insert((2, name), r);
                r
            }
        })
    }

    /// Property `key` of a node of any vertex table, by its id: of each table that has it
    /// (`any.key(id, v) :- T.key(row, v), id T(row, id)`, a rule each); a node of a table
    /// without it has no value.
    fn global_prop(&mut self, key: &str) -> Result<Option<RelId>> {
        let tables: Vec<(String, u64, u64)> = self
            .catalog
            .tables()
            .map(|(l, b, c)| (l.to_string(), b, c))
            .collect();
        for (t, ..) in &tables {
            if let Some(why) = self.catalog.refused_prop(Some(t), key, false) {
                return Err(GqlError::Unsupported(why));
            }
        }
        let with: Vec<&(String, u64, u64)> = tables
            .iter()
            .filter(|t| self.catalog.label_prop(&t.0, key).is_some())
            .collect();
        let Some(first) = with.first() else {
            return Ok(None);
        };
        let rkey = (9, format!("any.{key}"));
        if let Some(&r) = self.rels.get(&rkey) {
            return Ok(Some(r));
        }
        let ty = self.catalog.prop_type(&first.0, key);
        if let Some(t) = with
            .iter()
            .find(|t| self.catalog.prop_type(&t.0, key) != ty)
        {
            return Err(GqlError::Semantic(format!(
                "property `{key}` is a {} on `{}` and a {} on `{}`",
                ty.name(),
                first.0,
                self.catalog.prop_type(&t.0, key).name(),
                t.0
            )));
        }
        let r = if ty == Type::U64 {
            self.plan.derived(&rkey.1, 2)
        } else {
            self.plan.derived_typed(&rkey.1, &[Type::U64, ty])
        };
        let (row, id, v) = (self.plan.var("R"), self.plan.var("G"), self.plan.var("V"));
        for (t, ..) in with {
            let name = format!("{t}.{key}");
            let source = self.catalog.label_prop(t, key).expect("checked").clone();
            let p = match self.rels.get(&(2, name.clone())) {
                Some(&p) => p,
                None if ty == Type::U64 => self.input(2, &name, 2, &source),
                None => {
                    let p = self.plan.input_typed(&name, &[Type::U64, ty]);
                    self.inputs.set(p, source);
                    self.rels.insert((2, name), p);
                    p
                }
            };
            let sname = format!("id {t}");
            let shift = match self.rels.get(&(3, sname.clone())) {
                Some(&s) => s,
                None => {
                    let s = self.plan.external(&sname, 2);
                    self.inputs
                        .external(s, Arc::new(self.catalog.row_ids(t).expect("a table")));
                    self.rels.insert((3, sname), s);
                    s
                }
            };
            self.plan
                .rule(at(r, &[id, v]), [at(p, &[row, v]), at(shift, &[row, id])])?;
        }
        self.rels.insert(rkey, r);
        Ok(Some(r))
    }

    /// The relation of property `key` of edge variable `e`: (from, to, value) of its labels
    /// that have it, either way for an edge that goes either way.
    fn edge_prop(&mut self, e: usize, key: &str) -> Result<Option<RelId>> {
        let (key, form) = split_form(key);
        let (labels, any) = (self.edge_vars[e].labels.clone(), self.edge_vars[e].any);
        let mut named: Vec<Option<&str>> = labels.iter().map(|l| Some(l.as_str())).collect();
        if labels.is_empty() {
            named.push(None);
        }
        if let Some(why) = named
            .into_iter()
            .find_map(|l| self.catalog.refused_prop(l, key, true))
        {
            return Err(GqlError::Unsupported(why));
        }
        let with: Vec<String> = labels
            .iter()
            .filter(|lab| self.catalog.edge_prop(lab, key).is_some())
            .cloned()
            .collect();
        if with.is_empty() {
            return Ok(None);
        }
        let one = |l: &mut Self, lab: &str| -> Result<RelId> {
            let (source, ty) = l.prop_source(lab, key, form, true)?;
            let name = with_form(&format!("{lab}.{key}"), form);
            Ok(match l.rels.get(&(3, name.clone())) {
                Some(&r) => r,
                None if ty == Type::U64 => l.input(3, &name, 3, &source),
                None => {
                    let r = l.plan.input_typed(&name, &[Type::U64, Type::U64, ty]);
                    l.inputs.set(r, source);
                    l.rels.insert((3, name), r);
                    r
                }
            })
        };
        let tys: Vec<Type> = with
            .iter()
            .map(|lab| Ok(self.prop_source(lab, key, form, true)?.1))
            .collect::<Result<_>>()?;
        if tys.iter().any(|&t| t != tys[0]) {
            return Err(GqlError::Semantic(format!(
                "edge property `{key}` has another type on each of {}",
                with.join(", ")
            )));
        }
        let names: Vec<String> = with
            .iter()
            .map(|lab| with_form(&format!("{lab}.{key}"), form))
            .collect();
        let mut r = if with.len() == 1 {
            one(self, &with[0])?
        } else {
            let key2 = (7, names.join("|"));
            match self.rels.get(&key2) {
                Some(&r) => r,
                None => {
                    let r = if tys[0] == Type::U64 {
                        self.plan.derived(&key2.1, 3)
                    } else {
                        self.plan
                            .derived_typed(&key2.1, &[Type::U64, Type::U64, tys[0]])
                    };
                    let vs: Vec<Var> = (0..3).map(|i| self.plan.var(&format!("U{i}"))).collect();
                    for lab in &with {
                        let i = one(self, lab)?;
                        self.plan.rule(at(r, &vs), [at(i, &vs)])?;
                    }
                    self.rels.insert(key2, r);
                    r
                }
            }
        };
        if any {
            r = self.either_way(r)?;
        }
        Ok(Some(r))
    }

    /// Edge variable `e` read by its rows ([`EdgeVar::rows`]) when the catalog has the rows
    /// of each of its labels (`E@row`) and it is one edge (not quantified): one label one
    /// way is `E@row` (row, from, to) itself; several labels, or either way, a relation of
    /// (label number, row, from, to), each edge each way it is read (a self loop once).
    /// Whether it is.
    fn edge_by_rows(&mut self, e: usize) -> Result<bool> {
        if self.edge_vars[e].rows.is_some() {
            return Ok(true);
        }
        let ev = &self.edge_vars[e];
        if ev.quantified
            || ev.labels.is_empty()
            || ev
                .labels
                .iter()
                .any(|lab| self.catalog.edge_row_source(lab).is_none())
        {
            return Ok(false);
        }
        let (labels, any, name) = (ev.labels.clone(), ev.any, ev.name.clone());
        let row = self.plan.var(&format!("row({name})"));
        let rows = if let ([lab], false) = (labels.as_slice(), any) {
            let rel = self.row_input(&format!("{lab}{EDGE_ROW}"))?;
            (rel, vec![row])
        } else {
            let key = (
                20,
                format!(
                    "{}{EDGE_ROW}{}",
                    labels.join("|"),
                    if any { "~" } else { "" }
                ),
            );
            let rel = match self.rels.get(&key) {
                Some(&r) => r,
                None => {
                    let r = self.plan.derived(&key.1, 4);
                    let [x, y, k] = ["RX", "RY", "RK"].map(|n| self.plan.var(n));
                    for (i, lab) in labels.iter().enumerate() {
                        let input = self.row_input(&format!("{lab}{EDGE_ROW}"))?;
                        let i = Term::Const(i as u64);
                        let head = |a: Var, b: Var| Atom {
                            rel: r,
                            terms: vec![i, Term::Var(k), Term::Var(a), Term::Var(b)],
                        };
                        self.plan.rule(head(x, y), [at(input, &[k, x, y])])?;
                        if any {
                            self.plan.rule(head(y, x), [at(input, &[k, x, y])])?;
                        }
                    }
                    self.rels.insert(key, r);
                    r
                }
            };
            (rel, vec![self.plan.var(&format!("label({name})")), row])
        };
        self.edge_vars[e].rows = Some(rows);
        Ok(true)
    }

    /// Edge variable `v`'s row as a value ([`Operand::EdgeRow`]): its row variable when it
    /// has one label, one way, and the catalog has that label's rows (it is then read by its
    /// rows, [`Lowering::edge_by_rows`]); else 0 (its list is then read by its two nodes).
    fn edge_row_value(&mut self, v: &str) -> Result<Val> {
        let e = self
            .edge_vars
            .iter()
            .position(|e| e.name == v)
            .ok_or_else(|| GqlError::Semantic(format!("no edge `{v}`")))?;
        let ev = &self.edge_vars[e];
        let one = matches!(ev.labels.as_slice(), [lab] if self.catalog.edge_row_source(lab).is_some())
            && !ev.any;
        if !one || !self.edge_by_rows(e)? {
            return Ok(Val::Const(0));
        }
        let row = self.edge_vars[e].rows.as_ref().expect("read by rows").1[0];
        let name = format!("#row({v})");
        let y = match self.yields.iter().position(|y| y.name == name) {
            Some(y) => y,
            None => {
                self.yields.push(YieldVar {
                    name,
                    var: row,
                    ty: Type::U64,
                    path: false,
                });
                self.yields.len() - 1
            }
        };
        Ok(Val::Yield(y))
    }

    /// The input relation of catalog name `name` (an edge label's rows or a property of
    /// them), of the catalog's column types.
    fn row_input(&mut self, name: &str) -> Result<RelId> {
        let key = (21, name.to_string());
        if let Some(&r) = self.rels.get(&key) {
            return Ok(r);
        }
        let r = self.plan.input_from(self.catalog, name)?;
        self.inputs.set(r, self.catalog.relation(name)?.0);
        self.rels.insert(key, r);
        Ok(r)
    }

    /// The relation of property `key` of edge variable `e` by the edges' rows, and its
    /// value column, when `e` is read by its rows ([`Lowering::edge_by_rows`]): one label
    /// one way `E@row.key` (row, value); else (label number, row, value) of its labels that
    /// have it. `None` when `e` is not read by rows (its labels' properties are then read
    /// as (from, to, value), [`Lowering::edge_prop`]).
    fn edge_row_prop(&mut self, e: usize, key: &str) -> Result<Option<(RelId, usize)>> {
        let (labels, any) = (self.edge_vars[e].labels.clone(), self.edge_vars[e].any);
        if let Some(why) = labels
            .iter()
            .find_map(|l| self.catalog.refused_prop(Some(l), key, true))
        {
            return Err(GqlError::Unsupported(why));
        }
        let with: Vec<String> = labels
            .iter()
            .filter(|lab| self.catalog.edge_row_prop(lab, key).is_some())
            .cloned()
            .collect();
        if with.is_empty() || !self.edge_by_rows(e)? {
            return Ok(None);
        }
        let tys: Vec<Type> = with
            .iter()
            .map(|lab| self.catalog.edge_row_prop(lab, key).expect("checked").1)
            .collect();
        if tys.iter().any(|&t| t != tys[0]) {
            return Err(GqlError::Semantic(format!(
                "edge property `{key}` has another type on each of {}",
                with.join(", ")
            )));
        }
        if let ([lab], false) = (labels.as_slice(), any) {
            return Ok(Some((
                self.row_input(&format!("{lab}{EDGE_ROW}.{key}"))?,
                1,
            )));
        }
        let key2 = (22, format!("{}{EDGE_ROW}.{key}", labels.join("|")));
        if let Some(&r) = self.rels.get(&key2) {
            return Ok(Some((r, 2)));
        }
        let r = self
            .plan
            .derived_typed(&key2.1, &[Type::U64, Type::U64, tys[0]]);
        let (k, v) = (self.plan.var("RK"), self.plan.var("RV"));
        for (i, lab) in labels.iter().enumerate() {
            if !with.contains(lab) {
                continue;
            }
            let input = self.row_input(&format!("{lab}{EDGE_ROW}.{key}"))?;
            let head = Atom {
                rel: r,
                terms: vec![Term::Const(i as u64), Term::Var(k), Term::Var(v)],
            };
            self.plan.rule(head, [at(input, &[k, v])])?;
        }
        self.rels.insert(key2, r);
        Ok(Some((r, 2)))
    }

    /// The vertex table of node `n` and its base: its one label's, or for a node with no
    /// label the one its edges name; `None` in a catalog of one id space.
    fn table_of(&self, n: usize) -> Result<Option<(String, u64)>> {
        let node = &self.nodes[n];
        if !self.catalog.numbered() || node.global {
            return Ok(None);
        }
        let label = match &node.labels[..] {
            [] => node.table.clone().ok_or_else(|| {
                GqlError::Unsupported(format!(
                    "id({0}) of a node with no label whose edges do not name its vertex \
                     table: give `{0}` its label",
                    node.name
                ))
            })?,
            [set] if set.len() == 1 => set[0].clone(),
            _ => {
                return Err(GqlError::Unsupported(format!(
                    "id({}) of a node of label alternatives or several labels: row numbers of \
                     two vertex tables collide, give it one label",
                    node.name
                )));
            }
        };
        let base = self.catalog.base(&label).ok_or_else(|| {
            GqlError::Unsupported(format!(
                "id({}): label `{label}` is no vertex table and has no id base",
                node.name
            ))
        })?;
        Ok(Some((label, base)))
    }

    /// `id(n)`: the node itself in a catalog of one id space, of no label and no edge, or of
    /// a table at base 0; else its row plus its table's base (a value read through a
    /// shift relation, as a property `id()` of the node).
    fn id_of(&mut self, n: usize) -> Result<Val> {
        let Some((label, base)) = self.table_of(n)? else {
            return Ok(Val::Node(n));
        };
        if base == 0 {
            return Ok(Val::Node(n));
        }
        let name = format!("id {label}");
        let rel = match self.rels.get(&(3, name.clone())) {
            Some(&r) => r,
            None => {
                let r = self.plan.external(&name, 2);
                self.inputs.external(
                    r,
                    Arc::new(self.catalog.row_ids(&label).expect("a label with a base")),
                );
                self.rels.insert((3, name), r);
                r
            }
        };
        if let Some(s) = self.props.iter().position(|p| p.node == n && p.rel == rel) {
            return Ok(Val::Prop(n, s));
        }
        let var = self.plan.var(&format!("id({})", self.nodes[n].name));
        self.props.push(Prop {
            node: n,
            key: ID_KEY.into(),
            rel,
            var,
        });
        Ok(Val::Prop(n, self.props.len() - 1))
    }

    /// The relation of every node of every vertex table by its id: listed from the tables'
    /// numbers, nothing read.
    fn all_nodes(&mut self) -> RelId {
        let name = "every node".to_string();
        if let Some(&r) = self.rels.get(&(3, name.clone())) {
            return r;
        }
        let r = self.plan.external(&name, 1);
        let ranges: Vec<(u64, u64)> = self.catalog.tables().map(|t| (t.1, t.2)).collect();
        self.inputs
            .external(r, Arc::new(IdRanges::new(ranges, [(0, Value::MAX)])));
        self.rels.insert((3, name), r);
        r
    }

    fn value(&mut self, o: &Operand) -> Result<Val> {
        let node = |s: &Self, v: &str| -> Result<usize> {
            if s.edge_vars.iter().any(|e| e.name == v) {
                return Err(GqlError::Unsupported(format!(
                    "edge variable `{v}` as a value (its properties are values: `{v}.key`)"
                )));
            }
            s.by_name
                .get(v)
                .copied()
                .ok_or_else(|| GqlError::Semantic(format!("unknown variable `{v}`")))
        };
        match o {
            Operand::Int(i) => Ok(Val::Const(*i)),
            Operand::Param(p) => match self.params.get(p) {
                Some(Param::Int(c)) => Ok(Val::Const(*c)),
                Some(Param::List(_)) => Err(GqlError::Semantic(format!(
                    "parameter `${p}` is a list: UNWIND ${p} AS x"
                ))),
                None => Err(GqlError::Semantic(format!("parameter `${p}` has no value"))),
            },
            Operand::Arith(a, op, b) => self.calc(CalcOp::Bin(*op), a, Some(b)),
            Operand::Unary(op, a) => self.calc(CalcOp::Un(*op), a, None),
            Operand::Call(f, args) => self.string_calc(*f, args),
            Operand::Var(v) if self.yields.iter().any(|y| y.name == *v && y.path) => {
                Err(GqlError::Unsupported(format!(
                    "path `{v}` through a WITH is its length only: length({v})"
                )))
            }
            Operand::Length(v) if self.yields.iter().any(|y| y.name == *v && y.path) => {
                Ok(Val::Yield(
                    self.yields
                        .iter()
                        .position(|y| y.name == *v)
                        .expect("checked"),
                ))
            }
            Operand::Length(v) => match self.path_vars.iter().position(|p| p.name == *v) {
                Some(k) => Ok(match &self.path_vars[k].kind {
                    PathKind::Fixed(ns) => Val::Const(ns.len() as Value - 1),
                    PathKind::Shortest { .. } => Val::PathLen(k),
                }),
                None => Err(GqlError::Semantic(format!("unknown path variable `{v}`"))),
            },
            Operand::Var(v) if self.yields.iter().any(|y| y.name == *v) => Ok(Val::Yield(
                self.yields
                    .iter()
                    .position(|y| y.name == *v)
                    .expect("checked"),
            )),
            Operand::Prop(v, _) if self.yields.iter().any(|y| y.name == *v) => Err(
                GqlError::Semantic(format!("`{v}` is a value: it has no properties")),
            ),
            Operand::Var(v) if self.path_vars.iter().any(|p| p.name == *v) => {
                Err(GqlError::Unsupported(format!(
                    "path `{v}` as a value: return it, nodes({v}) or length({v})"
                )))
            }
            Operand::Var(v) => Ok(Val::Node(node(self, v)?)),
            Operand::Id(v) if self.edge_vars.iter().any(|e| e.name == *v) => {
                Err(GqlError::Unsupported(format!(
                    "id({v}) of an edge: an edge is a pair of nodes here, with no id of its own"
                )))
            }
            Operand::Id(v) if self.path_vars.iter().any(|p| p.name == *v) => Err(
                GqlError::Semantic(format!("id({v}) of a path: id takes a node")),
            ),
            Operand::Id(v) if self.yields.iter().any(|y| y.name == *v) => Err(GqlError::Semantic(
                format!("id({v}) of a value: id takes a node"),
            )),
            Operand::Id(v) => {
                let n = node(self, v)?;
                self.id_of(n)
            }
            Operand::Str(_)
            | Operand::Signed(_)
            | Operand::Float(_)
            | Operand::Bool(_)
            | Operand::Null => Err(GqlError::Unsupported(
                "a literal other than an unsigned integer is only compared".into(),
            )),
            Operand::EdgeRow(v) => self.edge_row_value(v),
            Operand::Prop(v, k) => {
                if let Some(e) = self.edge_vars.iter().position(|e| e.name == *v) {
                    if self.edge_vars[e].quantified {
                        return Err(GqlError::Unsupported(format!(
                            "a property of the quantified edge `{v}` (one value per edge of a path)"
                        )));
                    }
                    let (rel, col) = match self.edge_row_prop(e, k)? {
                        Some(r) => r,
                        None => (
                            self.edge_prop(e, k)?.ok_or_else(|| {
                                GqlError::Semantic(format!("no property `{k}` for edge `{v}` here"))
                            })?,
                            2,
                        ),
                    };
                    let (from, to) = (self.edge_vars[e].from, self.edge_vars[e].to);
                    if let Some(slot) = self.eprops.iter().position(|p| p.edge == e && p.rel == rel)
                    {
                        return Ok(Val::EdgeProp { from, to, slot });
                    }
                    let var = self.plan.var(&format!("{v}.{k}"));
                    self.eprops.push(EdgeProp {
                        edge: e,
                        rel,
                        var,
                        col,
                    });
                    return Ok(Val::EdgeProp {
                        from,
                        to,
                        slot: self.eprops.len() - 1,
                    });
                }
                let n = node(self, v)?;
                let rel = self.node_prop(n, k)?.ok_or_else(|| {
                    GqlError::Semantic(format!("no property `{k}` for `{v}` here"))
                })?;
                if let Some(s) = self.props.iter().position(|p| p.node == n && p.rel == rel) {
                    return Ok(Val::Prop(n, s));
                }
                let var = self.plan.var(&format!("{v}.{k}"));
                self.props.push(Prop {
                    node: n,
                    key: k.clone(),
                    rel,
                    var,
                });
                Ok(Val::Prop(n, self.props.len() - 1))
            }
        }
    }

    /// A condition with its values resolved.
    fn cx(&mut self, c: &Condition) -> Result<Cx> {
        Ok(match c {
            Condition::Cmp(c) => self.compare(&c.left, cmp(c.op), &c.right)?,
            // IN () is false (a null's too): the empty OR
            Condition::In { value, list } => match self.one_of(value, list)? {
                Some(c) => c,
                None => self.in_as_or(value, list)?,
            },
            Condition::IsNull { value, null } => match self.lit(value)? {
                Some(Lit::Null) => Cx::Known(*null),
                Some(_) => Cx::Known(!*null),
                None => match self.value(value)? {
                    v @ (Val::Prop(..) | Val::EdgeProp { .. }) => Cx::Null(v, *null),
                    // a node is never null
                    _ => Cx::Known(!*null),
                },
            },
            Condition::Text { value, op, pattern } => {
                let Some(Lit::Str(pat)) = self.lit(pattern)? else {
                    return Err(GqlError::Unsupported(format!(
                        "the pattern of {} is a string literal",
                        op.words().to_uppercase()
                    )));
                };
                if let Some(Lit::Str(s)) = self.lit(value)? {
                    return Ok(Cx::Known(op.holds(&s, &pat)));
                }
                let v = self.value(value)?;
                if self.ty(v) != Some(Type::Str) {
                    return Err(GqlError::Semantic(format!(
                        "{} tests a string property",
                        op.words().to_uppercase()
                    )));
                }
                let Term::Const(k) = self.plan.str(&pat) else {
                    unreachable!("a string constant")
                };
                Cx::Text(v, *op, k)
            }

            Condition::Not(x) => Cx::Not(Box::new(self.cx(x)?)),
            Condition::And(cs) => Cx::And(cs.iter().map(|c| self.cx(c)).collect::<Result<_>>()?),
            Condition::Or(cs) => Cx::Or(cs.iter().map(|c| self.cx(c)).collect::<Result<_>>()?),
            Condition::Xor(a, b) => Cx::Xor(Box::new(self.cx(a)?), Box::new(self.cx(b)?)),
            Condition::EdgeList { quant, list, .. } => {
                return Err(GqlError::Unsupported(format!(
                    "{}(... IN {list} WHERE ...) inside OR / NOT, or over `{list}`, which is not \
                     a quantified edge of its MATCH: put it at the top of the MATCH's WHERE \
                     (an AND)",
                    quant.name()
                )));
            }
        })
    }

    /// `value IN (list)` as an OR of equalities: for a constant on the left, or a list with
    /// a member that is not a constant.
    fn in_as_or(&mut self, value: &Operand, list: &[Operand]) -> Result<Cx> {
        let mut parts = Vec::with_capacity(list.len());
        for x in list {
            parts.push(self.compare(value, Cmp::Eq, x)?);
        }
        Ok(Cx::Or(parts))
    }

    /// `value IN (list)` as the core's list test, for a node or a node's property tested
    /// against constants and parameters (a NULL among them dropped and noted); `None` for
    /// an empty list, a constant or any other value, or a member that is not a constant.
    fn one_of(&mut self, value: &Operand, list: &[Operand]) -> Result<Option<Cx>> {
        if list.is_empty() || self.lit(value)?.is_some() {
            return Ok(None);
        }
        let mut lits = Vec::with_capacity(list.len());
        for x in list {
            match self.lit(x)? {
                Some(x) => lits.push(x),
                None => return Ok(None),
            }
        }
        let v = self.value(value)?;
        if !matches!(v, Val::Prop(..) | Val::Node(_)) {
            return Ok(None);
        }
        let ty = self.ty(v).unwrap_or_default();
        let null = lits.iter().any(|x| matches!(x, Lit::Null));
        let members: Vec<kleene_plan::ListMember> = lits
            .into_iter()
            .filter_map(|x| {
                Some(kleene_plan::ListMember::Const(match x {
                    Lit::Uint(u) => Constant::Uint(u),
                    Lit::Int(i) => Constant::Int(i),
                    Lit::Float(f) => Constant::Float(f),
                    Lit::Str(s) => Constant::Str(s),
                    Lit::Bool(b) => Constant::Bool(b),
                    Lit::Null => return None,
                }))
            })
            .collect();
        let list = match self.plan.list(ty, members) {
            Ok(l) => l,
            Err(kleene_plan::PlanError::Program(m)) => return Err(GqlError::Semantic(m)),
            Err(e) => return Err(e.into()),
        };
        Ok(Some(Cx::In(v, list, null)))
    }

    /// A literal operand (an unsigned integer and a parameter included), else `None`.
    fn lit(&mut self, o: &Operand) -> Result<Option<Lit>> {
        Ok(Some(match o {
            Operand::Int(i) => Lit::Uint(*i),
            Operand::Param(_) => match self.value(o)? {
                Val::Const(c) => Lit::Uint(c),
                _ => unreachable!("a parameter is a constant"),
            },
            Operand::Signed(i) => Lit::Int(*i),
            Operand::Float(x) => Lit::Float(x.0),
            Operand::Str(s) => Lit::Str(s.clone()),
            Operand::Bool(b) => Lit::Bool(*b),
            Operand::Null => Lit::Null,
            Operand::Var(_)
            | Operand::Prop(..)
            | Operand::Length(_)
            | Operand::Id(_)
            | Operand::EdgeRow(_)
            | Operand::Arith(..)
            | Operand::Unary(..)
            | Operand::Call(..) => {
                return Ok(None);
            }
        }))
    }

    /// The type of a value read from the graph (`None` for a constant).
    fn ty(&self, v: Val) -> Option<Type> {
        match v {
            Val::Prop(_, s) => Some(self.plan.col_type(self.props[s].rel, 1)),
            Val::EdgeProp { slot, .. } => {
                let p = &self.eprops[slot];
                Some(self.plan.col_type(p.rel, p.col))
            }
            Val::Node(_) | Val::PathLen(_) | Val::PathId(_) => Some(Type::U64),
            Val::Yield(y) => Some(self.yields[y].ty),
            Val::Calc { slot, .. } => Some(self.calcs[slot].ty),
            Val::Const(_) => None,
        }
    }

    /// `a op b` with each literal coded for the type of the value it meets: an unsigned
    /// or negative integer for a signed property, any number for a float one, a string for
    /// a string one, `TRUE` / `FALSE` for a boolean one. Two literals are compared here.
    fn compare(&mut self, a: &Operand, op: Cmp, b: &Operand) -> Result<Cx> {
        let (la, lb) = (self.lit(a)?, self.lit(b)?);
        if matches!(la, Some(Lit::Null)) || matches!(lb, Some(Lit::Null)) {
            return Err(GqlError::Semantic(
                "a comparison with NULL is never true: write IS NULL or IS NOT NULL".into(),
            ));
        }
        match (la, lb) {
            (Some(x), Some(y)) => Ok(Cx::Known(known(&x, op, &y)?)),
            (None, None) => {
                let (x, y) = (self.value(a)?, self.value(b)?);
                if let (Val::Node(m), Val::Node(n)) = (x, y)
                    && self.catalog.numbered()
                    && tables_of(self, m) != tables_of(self, n)
                {
                    return Err(meet(&format!(
                        "`{}` compared with `{}`",
                        self.nodes[m].name, self.nodes[n].name
                    )));
                }
                Ok(Cx::Cmp(x, op, y))
            }
            (Some(x), None) => {
                let v = self.value(b)?;
                Ok(Cx::Cmp(Val::Const(self.code(&x, self.ty(v))?), op, v))
            }
            (None, Some(y)) => {
                let v = self.value(a)?;
                Ok(Cx::Cmp(v, op, Val::Const(self.code(&y, self.ty(v))?)))
            }
        }
    }

    /// `x` coded as a value of type `ty` ([`Plan::constant`], the core's coding of a
    /// constant for the place it meets).
    fn code(&mut self, x: &Lit, ty: Option<Type>) -> Result<Value> {
        let ty = ty.unwrap_or_default();
        let c = match x {
            Lit::Uint(u) => Constant::Uint(*u),
            Lit::Int(i) => Constant::Int(*i),
            Lit::Float(f) => Constant::Float(*f),
            Lit::Str(s) => Constant::Str(s.clone()),
            Lit::Bool(b) => Constant::Bool(*b),
            Lit::Null => {
                return Err(GqlError::Semantic(format!(
                    "NULL compared with a {} value",
                    ty.name()
                )));
            }
        };
        match self.plan.constant(&c, ty) {
            Ok(Term::Const(c)) => Ok(c),
            Ok(Term::Var(_)) => unreachable!("a constant"),
            Err(kleene_plan::PlanError::Program(m)) => Err(GqlError::Semantic(m)),
            Err(e) => Err(e.into()),
        }
    }

    /// The relation of the nodes with a row in property relation `rel`.
    fn has(&mut self, rel: RelId) -> Result<RelId> {
        if let Some(&r) = self.has.get(&rel) {
            return Ok(r);
        }
        let name = format!("has_{}", self.plan.relation_info(rel).name);
        let r = self.plan.derived(&name, 1);
        let (n, v) = (self.plan.var("N"), self.plan.var("V"));
        self.plan.rule(at(r, &[n]), [at(rel, &[n, v])])?;
        self.has.insert(rel, r);
        Ok(r)
    }

    /// A derived relation over `vals`, typed when one of them is.
    fn derived(&mut self, name: &str, vals: &[Val]) -> RelId {
        let types: Vec<Type> = vals
            .iter()
            .map(|&v| self.ty(v).unwrap_or_default())
            .collect();
        if types.iter().all(|&t| t == Type::U64) {
            self.plan.derived(name, types.len())
        } else {
            self.plan.derived_typed(name, &types)
        }
    }

    /// Whether `v` holds float codes (a procedure's score).
    fn is_float(&self, v: Val) -> bool {
        matches!(v, Val::Yield(y) if self.yields[y].ty == Type::F64)
    }

    fn term(&self, v: Val) -> Term {
        match v {
            Val::Node(n) => Term::Var(self.nodes[n].var),
            Val::Prop(_, s) => Term::Var(self.props[s].var),
            Val::EdgeProp { slot, .. } => Term::Var(self.eprops[slot].var),
            Val::Yield(y) => Term::Var(self.yields[y].var),
            Val::PathLen(p) | Val::PathId(p) => match self.path_vars[p].kind {
                PathKind::Shortest { len, id, .. } => Term::Var(if matches!(v, Val::PathLen(_)) {
                    len
                } else {
                    id
                }),
                PathKind::Fixed(_) => unreachable!("a fixed path has no length variable"),
            },
            Val::Const(c) => Term::Const(c),
            Val::Calc { slot, .. } => Term::Var(self.calcs[slot].var),
        }
    }

    /// One side of an arithmetic value.
    fn side(&mut self, o: &Operand) -> Result<CalcSide> {
        let konst = |term: Term, ty: Type| CalcSide {
            val: None,
            term,
            ty,
        };
        Ok(match self.lit(o)? {
            Some(Lit::Uint(u)) => konst(Term::Const(u), Type::U64),
            Some(Lit::Int(i)) => konst(Term::int(i), Type::I64),
            Some(Lit::Float(x)) => konst(Term::float(x), Type::F64),
            Some(Lit::Null) => konst(Term::Const(kleene_plan::NULL), Type::I64),
            Some(x) => {
                return Err(GqlError::Semantic(format!(
                    "{} in arithmetic: numbers only",
                    lit_name(&x)
                )));
            }
            None => {
                let v = self.value(o)?;
                CalcSide {
                    val: Some(v),
                    term: self.term(v),
                    ty: self.ty(v).unwrap_or_default(),
                }
            }
        })
    }

    /// A string function of `args` as a value ([`Func`]: `||`, `char_length`, `substring`):
    /// a [`Compute`] of the rule, a string or (`char_length`) an `i64`; null where an
    /// argument is null.
    fn string_calc(&mut self, f: Func, args: &[Operand]) -> Result<Val> {
        let name = match f {
            Func::Concat => "||",
            Func::Len => "char_length",
            _ => "substring",
        };
        let mut sides = Vec::with_capacity(args.len());
        for (i, a) in args.iter().enumerate() {
            let text = f.string_arg(i);
            let side = match self.lit(a)? {
                Some(Lit::Str(s)) if text => CalcSide {
                    val: None,
                    term: self.plan.str(&s),
                    ty: Type::Str,
                },
                Some(x) if text => {
                    return Err(GqlError::Semantic(format!(
                        "{} in {name}: strings only",
                        lit_name(&x)
                    )));
                }
                _ => self.side(a)?,
            };
            let ok = if text {
                side.ty == Type::Str
            } else {
                matches!(side.ty, Type::U64 | Type::I64)
            };
            if !ok {
                return Err(GqlError::Semantic(format!(
                    "{name} of a {} value where {} goes",
                    side.ty.name(),
                    if text { "a string" } else { "an integer" }
                )));
            }
            sides.push(side);
        }
        let expr = kleene_plan::Expr::call(f, sides.iter().map(|x| x.expr(false)));
        let ty = if f.makes_string() {
            Type::Str
        } else {
            Type::I64
        };
        self.calc_of(expr, sides, ty)
    }

    /// An unsigned value `v` (term `t`, type `ty`) as a signed one.
    fn calc_vals(&mut self, v: Val, t: Term, ty: Type) -> Result<Val> {
        let a = CalcSide {
            val: Some(v),
            term: t,
            ty,
        };
        self.calc_of(a.expr(false), vec![a], Type::I64)
    }

    /// `a op b` (or `op a`) as a value: a [`Compute`] of the rule, integers as `i64` (a
    /// float side: `f64`), null for a null side, a division by zero or an overflow.
    fn calc(&mut self, op: CalcOp, a: &Operand, b: Option<&Operand>) -> Result<Val> {
        let mut sides = vec![self.side(a)?];
        if let Some(b) = b {
            sides.push(self.side(b)?);
        }
        let num = |t: Type| matches!(t, Type::U64 | Type::I64 | Type::F64);
        if let Some(x) = sides.iter().find(|x| !num(x.ty)) {
            return Err(GqlError::Semantic(format!(
                "arithmetic on {} values: numbers only",
                x.ty.name()
            )));
        }
        let float = sides.iter().any(|x| x.ty == Type::F64);
        let bits = match op {
            CalcOp::Bin(o) => o.is_bits(),
            CalcOp::Un(o) => o == UnOp::Not,
        };
        if float && bits {
            return Err(GqlError::Semantic(format!(
                "{} of a float: integers only",
                match op {
                    CalcOp::Bin(o) => o.symbol(),
                    CalcOp::Un(_) => "bitnot",
                }
            )));
        }
        let e: Vec<kleene_plan::Expr> = sides.iter().map(|x| x.expr(float)).collect();
        let expr = match op {
            CalcOp::Bin(o) => kleene_plan::Expr::op(o, e[0].clone(), e[1].clone()),
            CalcOp::Un(o) => kleene_plan::Expr::unary(o, e[0].clone()),
        };
        let ty = if float { Type::F64 } else { Type::I64 };
        self.calc_of(expr, sides, ty)
    }

    fn calc_of(&mut self, expr: kleene_plan::Expr, sides: Vec<CalcSide>, ty: Type) -> Result<Val> {
        let vals: Vec<Val> = sides.iter().filter_map(|x| x.val).collect();
        let var = self.plan.var(&format!("calc{}", self.calcs.len()));
        let mut nodes = 0u64;
        for n in nodes_of(&vals) {
            if n >= 64 {
                return Err(GqlError::Unsupported(
                    "arithmetic over a node past the 64th of a query".into(),
                ));
            }
            nodes |= 1 << n;
        }
        self.calcs.push(Calc {
            vals,
            expr,
            var,
            ty,
        });
        Ok(Val::Calc {
            slot: self.calcs.len() - 1,
            nodes,
        })
    }

    /// The label atoms of node `n`: one per label set (a union for alternatives).
    fn label_atoms(&mut self, n: usize) -> Vec<Literal> {
        let var = self.nodes[n].var;
        if let Some(&h) = self.hits.get(&n) {
            // The index holds nodes of the label only: the lookup is the label's domain.
            return vec![atom(h, &[var])];
        }
        if self.nodes[n].global {
            let r = self.all_nodes();
            return vec![atom(r, &[var])];
        }
        let sets = self.nodes[n].labels.clone();
        let one = |l: &mut Self, name: &str| {
            let source = l.catalog.node_label(name).expect("checked").clone();
            l.input(0, name, 1, &source)
        };
        sets.iter()
            .map(|set| {
                let rel = match self.kinds_rel(set) {
                    Some(r) => r,
                    None => self.union(0, set, 1, &one).expect("a union of labels"),
                };
                atom(rel, &[var])
            })
            .collect()
    }

    /// A label set whose labels are all kinds of one kinds index: the relation of their
    /// nodes, one lookup of the index per kind (a union of the bitmaps).
    fn kinds_rel(&mut self, set: &[String]) -> Option<RelId> {
        let kinds: Vec<(String, u64)> = set
            .iter()
            .map(|lab| self.catalog.kind_of(lab).cloned())
            .collect::<Option<_>>()?;
        let index = kinds[0].0.clone();
        if kinds.iter().any(|k| k.0 != index) {
            return None;
        }
        let key = (4, format!("kinds {}", set.join("|")));
        if let Some(&r) = self.rels.get(&key) {
            return Some(r);
        }
        let source = self.catalog.kinds_idx(&index)?.clone();
        let name = format!("kinds index {index}");
        let idx = match self.rels.get(&(3, name.clone())) {
            Some(&r) => r,
            None => {
                let r = self.plan.external(&name, 2);
                self.inputs.set(r, source);
                self.rels.insert((3, name), r);
                r
            }
        };
        let r = self.plan.derived(&key.1, 1);
        let v = self.plan.var("K");
        for (_, k) in &kinds {
            self.plan
                .rule(
                    at(r, &[v]),
                    [Literal::Pos(Atom {
                        rel: idx,
                        terms: vec![Term::Const(*k), Term::Var(v)],
                    })],
                )
                .expect("a kinds rule");
        }
        self.rels.insert(key, r);
        Some(r)
    }

    /// The atoms that read the properties `vals` mention (each once).
    fn prop_atoms(&self, vals: &[Val], out: &mut Vec<Literal>) {
        for v in vals {
            if let Val::Calc { slot, .. } = *v {
                let c = &self.calcs[slot];
                self.prop_atoms(&c.vals, out);
                let a = Literal::Compute(Compute::typed(c.var, c.expr.clone(), c.ty));
                if !out.contains(&a) {
                    out.push(a);
                }
            }
            if let Val::EdgeProp { from, to, slot } = *v {
                let p = &self.eprops[slot];
                let a = match &self.edge_vars[p.edge].rows {
                    Some((_, row)) => atom(p.rel, &[row.as_slice(), &[p.var]].concat()),
                    None => atom(p.rel, &[self.nodes[from].var, self.nodes[to].var, p.var]),
                };
                if !out.contains(&a) {
                    out.push(a);
                }
            }
            if let Val::Prop(n, s) = *v {
                let a = Literal::Pos(Atom {
                    rel: self.props[s].rel,
                    terms: vec![Term::Var(self.nodes[n].var), Term::Var(self.props[s].var)],
                });
                if !out.contains(&a) {
                    out.push(a);
                }
            }
        }
    }
}

/// A WHERE condition with its values resolved, before it is lowered.
#[derive(Clone, Debug)]
enum Cx {
    Cmp(Val, Cmp, Val),
    Not(Box<Cx>),
    And(Vec<Cx>),
    Or(Vec<Cx>),
    Xor(Box<Cx>, Box<Cx>),
    /// `IS NULL` (true) or `IS NOT NULL` of a property.
    Null(Val, bool),
    /// A text test of a string property against a string constant (its code).
    Text(Val, TextOp, Value),
    /// `IN` a list of constants: the core's list test ([`Cond::OneOf`]) of a node's id or
    /// property; `true`: the list held a NULL (dropped from it: `IN` is then never false,
    /// `NOT IN` never true).
    In(Val, kleene_plan::ListId, bool),
    /// Known when the query is lowered (constants only).
    Known(bool),
}

impl Cx {
    /// The nodes it reads, rising.
    fn nodes(&self) -> Vec<usize> {
        fn walk(c: &Cx, out: &mut Vec<usize>) {
            match c {
                Cx::Cmp(a, _, b) => out.extend(nodes_of(&[*a, *b])),
                Cx::Null(a, _) | Cx::Text(a, ..) | Cx::In(a, ..) => out.extend(nodes_of(&[*a])),
                Cx::Not(x) => walk(x, out),
                Cx::And(cs) | Cx::Or(cs) => cs.iter().for_each(|c| walk(c, out)),
                Cx::Xor(a, b) => {
                    walk(a, out);
                    walk(b, out);
                }
                Cx::Known(_) => {}
            }
        }
        let mut out = Vec::new();
        walk(self, &mut out);
        out.sort_unstable();
        out.dedup();
        out
    }
}

/// `c` with its constant parts worked out (constants are never unknown).
fn fold(c: Cx) -> Cx {
    match c {
        Cx::Cmp(Val::Const(a), op, Val::Const(b)) => Cx::Known(op.holds(a, b)),
        Cx::Not(x) => match fold(*x) {
            Cx::Known(b) => Cx::Known(!b),
            x => Cx::Not(Box::new(x)),
        },
        Cx::And(cs) => {
            let mut keep = Vec::new();
            for c in cs.into_iter().map(fold) {
                match c {
                    Cx::Known(true) => {}
                    Cx::Known(false) => return Cx::Known(false),
                    c => keep.push(c),
                }
            }
            match keep.len() {
                0 => Cx::Known(true),
                1 => keep.pop().expect("one"),
                _ => Cx::And(keep),
            }
        }
        Cx::Or(cs) => {
            let mut keep = Vec::new();
            for c in cs.into_iter().map(fold) {
                match c {
                    Cx::Known(false) => {}
                    Cx::Known(true) => return Cx::Known(true),
                    c => keep.push(c),
                }
            }
            match keep.len() {
                0 => Cx::Known(false),
                1 => keep.pop().expect("one"),
                _ => Cx::Or(keep),
            }
        }
        Cx::Xor(a, b) => match (fold(*a), fold(*b)) {
            (Cx::Known(x), Cx::Known(y)) => Cx::Known(x != y),
            (Cx::Known(false), c) | (c, Cx::Known(false)) => c,
            (Cx::Known(true), c) | (c, Cx::Known(true)) => fold(Cx::Not(Box::new(c))),
            (a, b) => Cx::Xor(Box::new(a), Box::new(b)),
        },
        c => c,
    }
}

/// `UNWIND list AS x` over the rows `before` (none: one row): a relation of each row with
/// each item (`unwind(V..., x) :- before(V...), [the item's reads]`, a rule per item),
/// `x` a value of the items' type (unsigned and signed integers together as signed).
fn lower_unwind(l: &mut Lowering<'_>, u: &Unwind, before: Option<Literal>) -> Result<Literal> {
    if l.by_name.contains_key(&u.alias) || l.yields.iter().any(|y| y.name == u.alias) {
        return Err(GqlError::Semantic(format!(
            "UNWIND binds `{}` twice",
            u.alias
        )));
    }
    // (value read, or None; term; type)
    let mut items: Vec<(Option<Val>, Term, Type)> = Vec::new();
    // a list property's: the atom of its list relation, in each rule's body
    let mut list_atom: Option<Literal> = None;
    match &u.list {
        UnwindList::Prop(..) | UnwindList::EdgeProp { .. } => {
            let (atom, x, ty) = unwind_list(l, &u.list, &u.alias)?;
            items.push((None, x, ty));
            list_atom = Some(atom);
        }
        UnwindList::Param(p) => match l.params.get(p) {
            Some(Param::List(xs)) => {
                items.extend(xs.iter().map(|&x| (None, Term::Const(x), Type::U64)));
            }
            Some(Param::Int(_)) => {
                return Err(GqlError::Semantic(format!(
                    "UNWIND ${p}: the parameter is not a list"
                )));
            }
            None => {
                return Err(GqlError::Semantic(format!("parameter `${p}` has no value")));
            }
        },
        UnwindList::Items(ops) => {
            for o in ops {
                let t = match l.lit(o)? {
                    Some(Lit::Uint(x)) => (None, Term::Const(x), Type::U64),
                    Some(Lit::Int(i)) => (None, Term::int(i), Type::I64),
                    Some(Lit::Float(x)) => (None, Term::float(x), Type::F64),
                    Some(Lit::Bool(b)) => (None, Term::bool(b), Type::Bool),
                    Some(Lit::Str(s)) => (None, l.plan.str(&s), Type::Str),
                    Some(Lit::Null) => {
                        return Err(GqlError::Unsupported(
                            "NULL as an UNWIND item, in this version".into(),
                        ));
                    }
                    None => {
                        let v = l.value(o)?;
                        if matches!(v, Val::Node(_)) {
                            return Err(GqlError::Unsupported(
                                "a node as an UNWIND item: unwind its id(n) or a property".into(),
                            ));
                        }
                        (Some(v), l.term(v), l.ty(v).unwrap_or_default())
                    }
                };
                items.push(t);
            }
        }
    }
    // One type: unsigned and signed integers together as signed.
    let mut ty = items.first().map_or(Type::U64, |i| i.2);
    if items.iter().any(|i| i.2 != ty) {
        if items.iter().all(|i| matches!(i.2, Type::U64 | Type::I64)) {
            ty = Type::I64;
            for it in &mut items {
                if it.2 == Type::U64 {
                    *it = match it.0 {
                        None => match it.1 {
                            Term::Const(c) => match i64::try_from(c) {
                                Ok(i) if i < i64::MAX => (None, Term::int(i), Type::I64),
                                _ => {
                                    return Err(GqlError::Semantic(format!(
                                        "{c} is out of a signed range"
                                    )));
                                }
                            },
                            t => (None, t, Type::I64),
                        },
                        // a value + 0: the signed value
                        Some(_) => {
                            let v = l.calc_vals(it.0.expect("a value"), it.1, Type::U64)?;
                            (Some(v), l.term(v), Type::I64)
                        }
                    };
                }
            }
        } else {
            let names: BTreeSet<&str> = items.iter().map(|i| i.2.name()).collect();
            return Err(GqlError::Semantic(format!(
                "UNWIND items of types {}: one type",
                names.into_iter().collect::<Vec<_>>().join(", ")
            )));
        }
    }
    let (vars, mut types): (Vec<Var>, Vec<Type>) = match &before {
        Some(Literal::Pos(a)) => (
            a.terms
                .iter()
                .filter_map(|t| match t {
                    Term::Var(v) => Some(*v),
                    _ => None,
                })
                .collect(),
            (0..a.terms.len())
                .map(|c| l.plan.col_type(a.rel, c))
                .collect(),
        ),
        _ => (Vec::new(), Vec::new()),
    };
    // Rows before that are counted: the items counted too (each item a row per row before).
    let counted = matches!(&before, Some(Literal::Pos(a)) if l.plan.is_counted(a.rel));
    let mut vars = vars;
    if counted {
        vars.pop();
        types.pop();
    }
    types.push(ty);
    let rel = if counted || l.rows == Rows::Bag {
        l.plan.derived_counted("unwind", &types)
    } else {
        typed_rel(&mut l.plan, "unwind", &types)
    };
    // No rows before: one row.
    let one = l.plan.input("one row", 1);
    l.inputs.set(
        one,
        Source::Facts(kleene_plan::Facts::from_rows(1, [[0u64]])?),
    );
    for (v, t, _) in &items {
        let mut body: Vec<Literal> = before.iter().cloned().collect();
        if body.is_empty() {
            body.push(Literal::Pos(Atom {
                rel: one,
                terms: vec![Term::Const(0)],
            }));
        }
        if let Some(v) = v {
            l.prop_atoms(&[*v], &mut body);
        }
        body.extend(list_atom.clone());
        let mut head: Vec<Term> = vars.iter().map(|&v| Term::Var(v)).collect();
        head.push(*t);
        l.rule_n(rel, head, body)?;
    }
    let x = l.plan.var(&u.alias);
    l.yields.push(YieldVar {
        name: u.alias.clone(),
        var: x,
        ty,
        path: false,
    });
    let mut all = vars;
    all.push(x);
    Ok(l.atom_n(rel, &all))
}

/// `UNWIND n.key` or `UNWIND e.key`: the atom of the list relation of the node's (or the
/// edge's) list property (`L.key(n, P, x)`, `E.key(from, to, P, x)`: the catalog's
/// [`Catalog::list_property`] / [`Catalog::list_edge_property`], one row per element, `P`
/// its position, so equal elements are rows of their own), the element's term `x` and type.
fn unwind_list(
    l: &mut Lowering<'_>,
    list: &UnwindList,
    alias: &str,
) -> Result<(Literal, Term, Type)> {
    // (the node terms; the label and its list relation's name; source; type)
    let (ends, name, source, ty) = match list {
        UnwindList::Prop(v, key) => {
            let n = match l.by_name.get(v) {
                Some(&n) => n,
                None => {
                    return Err(GqlError::Semantic(format!(
                        "UNWIND {v}.{key}: `{v}` is no node bound before"
                    )));
                }
            };
            let labels: BTreeSet<String> = l.nodes[n].labels.iter().flatten().cloned().collect();
            let with: Vec<&String> = labels
                .iter()
                .filter(|lab| l.catalog.list_prop(lab, key).is_some())
                .collect();
            let [lab] = with[..] else {
                return Err(one_list(v, key, &with));
            };
            let (source, ty) = l.catalog.list_prop(lab, key).expect("checked");
            (
                vec![Term::Var(l.nodes[n].var)],
                format!("{lab}.{key}"),
                source.clone(),
                ty,
            )
        }
        UnwindList::EdgeProp {
            edge,
            labels,
            row,
            key,
            ..
        } if matches!(labels.as_slice(), [lab]
            if l.catalog.list_edge_row_prop(lab, key).is_some()
                && l.catalog.edge_row_source(lab).is_some()) =>
        {
            let lab = &labels[0];
            let r = l.yields.iter().find(|y| y.name == *row).ok_or_else(|| {
                GqlError::Semantic(format!(
                    "UNWIND {edge}.{key}: the edge's row is not passed on"
                ))
            })?;
            let (source, ty) = l.catalog.list_edge_row_prop(lab, key).expect("checked");
            (
                vec![Term::Var(r.var)],
                format!("{lab}@row.{key}"),
                source.clone(),
                ty,
            )
        }
        UnwindList::EdgeProp {
            edge,
            from,
            to,
            labels,
            key,
            ..
        } => {
            let mut terms = Vec::with_capacity(2);
            for end in [from, to] {
                let n = *l.by_name.get(end).ok_or_else(|| {
                    GqlError::Semantic(format!("UNWIND {edge}.{key}: no node at its end"))
                })?;
                terms.push(Term::Var(l.nodes[n].var));
            }
            let labels: Vec<String> = if labels.is_empty() {
                l.catalog.edge_labels().map(String::from).collect()
            } else {
                labels.clone()
            };
            let with: Vec<&String> = labels
                .iter()
                .filter(|lab| l.catalog.list_edge_prop(lab, key).is_some())
                .collect();
            let [lab] = with[..] else {
                return Err(one_list(edge, key, &with));
            };
            let (source, ty) = l.catalog.list_edge_prop(lab, key).expect("checked");
            (terms, format!("{lab}.{key}"), source.clone(), ty)
        }
        _ => unreachable!("a list property"),
    };
    let mut types = vec![Type::U64; ends.len() + 1];
    types.push(ty);
    let rel = match l.rels.get(&(8, name.clone())) {
        Some(&r) => r,
        None => {
            let r = if ty == Type::U64 {
                l.plan.input(&name, types.len())
            } else {
                l.plan.input_typed(&name, &types)
            };
            l.inputs.set(r, source);
            l.rels.insert((8, name.clone()), r);
            r
        }
    };
    let k = l.plan.var(&format!("#{alias}#{name}#position"));
    let x = Term::Var(l.plan.var(&format!("#{alias}#{name}#element")));
    let mut terms = ends;
    terms.push(Term::Var(k));
    terms.push(x);
    Ok((Literal::Pos(Atom { rel, terms }), x, ty))
}

/// Why `UNWIND v.key` finds no one list relation: no label of `v`'s has such a list
/// property, or more than one has.
fn one_list(v: &str, key: &str, with: &[&String]) -> GqlError {
    if with.is_empty() {
        GqlError::Semantic(format!(
            "UNWIND {v}.{key}: no label of `{v}` has a list property `{key}`"
        ))
    } else {
        let names: Vec<&str> = with.iter().map(|s| s.as_str()).collect();
        GqlError::Unsupported(format!(
            "UNWIND {v}.{key}: labels {} each have a list `{key}`: name one",
            names.join(", ")
        ))
    }
}

/// A predicate over each edge of a quantified edge: the edges kept are those where
/// `pred` (of the edge, named `var`) is true (`keep`), else those where it is false.
#[derive(Clone, Debug)]
struct EdgePred {
    keep: bool,
    var: String,
    pred: Condition,
    /// The function, for messages.
    func: &'static str,
}

/// The top-level `all` / `none` / `any` / `single` predicates and the short form
/// (`r.w >= $min` on a quantified `r`) of each MATCH taken out of its WHERE, by edge
/// variable; `any` and `single` over `-[r*]->` rewrite the pattern as
/// `-[r~0*0..]->()-[r~p]->()-[r~1*0..]->` (the edge that passes in the middle; for
/// `single`, the others failing it).
fn edge_predicates(query: &Query) -> Result<(Query, HashMap<String, Vec<EdgePred>>)> {
    let mut q = query.clone();
    let mut preds: HashMap<String, Vec<EdgePred>> = HashMap::new();
    for m in &mut q.matches {
        let quantified: BTreeMap<String, (usize, usize)> = m
            .paths
            .iter()
            .enumerate()
            .flat_map(|(pi, p)| {
                p.steps.iter().enumerate().filter_map(move |(si, (e, _))| {
                    e.quant.and(e.var.clone()).map(|v| (v, (pi, si)))
                })
            })
            .collect();
        let mut rewrites: Vec<(String, ListQuant, String, Condition)> = Vec::new();
        let mut kept = Vec::new();
        for c in std::mem::take(&mut m.filter) {
            match c {
                Condition::EdgeList {
                    quant,
                    var,
                    list,
                    pred,
                } if quantified.contains_key(&list) => match quant {
                    ListQuant::All | ListQuant::None => {
                        preds.entry(list).or_default().push(EdgePred {
                            keep: quant == ListQuant::All,
                            var,
                            pred: *pred,
                            func: quant.name(),
                        });
                    }
                    ListQuant::Any | ListQuant::Single => {
                        let (pi, si) = quantified[&list];
                        let qn = m.paths[pi].steps[si].0.quant.expect("quantified");
                        if qn.max.is_some() {
                            return Err(GqlError::Unsupported(format!(
                                "{}(x IN {list} WHERE ...) over a bounded length: any and \
                                 single are read over `*` or `+` only, in this version",
                                quant.name()
                            )));
                        }
                        rewrites.push((list, quant, var, *pred));
                    }
                },
                Condition::Cmp(cmp)
                    if [&cmp.left, &cmp.right].iter().any(
                        |o| matches!(o, Operand::Prop(v, _) if quantified.contains_key(v)),
                    ) =>
                {
                    let v = [&cmp.left, &cmp.right]
                        .iter()
                        .find_map(|o| match o {
                            Operand::Prop(v, _) if quantified.contains_key(v) => Some(v.clone()),
                            _ => None,
                        })
                        .expect("found");
                    preds.entry(v.clone()).or_default().push(EdgePred {
                        keep: true,
                        var: v,
                        pred: Condition::Cmp(cmp),
                        func: "all",
                    });
                }
                c => kept.push(c),
            }
        }
        m.filter = kept;
        // Rewrites from the last step back, so the places of the earlier ones hold.
        let mut at: Vec<(String, ListQuant, String, Condition, usize, usize)> = rewrites
            .into_iter()
            .map(|(l, q, v, p)| {
                let (pi, si) = quantified[&l];
                (l, q, v, p, pi, si)
            })
            .collect();
        at.sort_by_key(|x| std::cmp::Reverse((x.4, x.5)));
        for (list, quant, var, pred, pi, si) in at {
            let (e, n) = m.paths[pi].steps[si].clone();
            let seg = |name: String, quant: Option<Quantifier>| EdgePattern {
                var: Some(name),
                labels: e.labels.clone(),
                dir: e.dir,
                quant,
            };
            // (named with a `~`: not a column of the match, so a pair of ends is one row)
            let any_node = |k: &str| NodePattern {
                var: Some(format!("{list}~{k}")),
                labels: Vec::new(),
            };
            let zero = Some(Quantifier { min: 0, max: None });
            let (s0, sp, s1) = (
                format!("{list}~0"),
                format!("{list}~p"),
                format!("{list}~1"),
            );
            let (first, last) = if e.dir == Dir::In {
                (s1.clone(), s0.clone())
            } else {
                (s0.clone(), s1.clone())
            };
            m.paths[pi].steps.splice(
                si..=si,
                [
                    (seg(first, zero), any_node("x")),
                    (seg(sp.clone(), None), any_node("y")),
                    (seg(last, zero), n),
                ],
            );
            let outer = preds.remove(&list).unwrap_or_default();
            preds.entry(sp).or_default().push(EdgePred {
                keep: true,
                var: var.clone(),
                pred: pred.clone(),
                func: quant.name(),
            });
            for s in [s0, s1] {
                let mine = preds.entry(s).or_default();
                mine.extend(outer.iter().cloned());
                if quant == ListQuant::Single {
                    mine.push(EdgePred {
                        keep: false,
                        var: var.clone(),
                        pred: pred.clone(),
                        func: quant.name(),
                    });
                }
            }
            preds.entry(format!("{list}~p")).or_default().extend(outer);
        }
    }
    Ok((q, preds))
}

/// The edges of `rel` (edge variable `e`'s) that `preds` keep: a relation of a rule per
/// way the predicates hold (each an AND of comparisons of the edge's properties with
/// constants; a null value keeps no edge), so the walk over it never steps on another.
fn edge_filter(l: &mut Lowering<'_>, e: usize, rel: RelId, preds: &[EdgePred]) -> Result<RelId> {
    let mut tests: Vec<EdgeTest> = Vec::new();
    let mut texts: Vec<String> = Vec::new();
    let name = l.edge_vars[e].name.clone();
    for p in preds {
        let refuse = || {
            GqlError::Unsupported(format!(
                "{}({} IN {name} WHERE ...): a comparison (or an AND of them) of the edge's \
                 properties with constants, in this version",
                p.func, p.var
            ))
        };
        let mut parts: Vec<&Condition> = Vec::new();
        let mut stack = vec![&p.pred];
        while let Some(c) = stack.pop() {
            match c {
                Condition::And(cs) => stack.extend(cs.iter().rev()),
                c => parts.push(c),
            }
        }
        // (property relation, op, code)
        let mut cmps: Vec<(RelId, Cmp, Value)> = Vec::new();
        let mut text: Vec<String> = Vec::new();
        for c in parts {
            let Condition::Cmp(c) = c else {
                return Err(refuse());
            };
            let (key, op, other) = match (&c.left, &c.right) {
                (Operand::Prop(v, k), o) if *v == p.var => (k, cmp(c.op), o),
                (o, Operand::Prop(v, k)) if *v == p.var => (k, flipped(cmp(c.op)), o),
                _ => return Err(refuse()),
            };
            let lit = match l.lit(other)? {
                Some(Lit::Null) | None => return Err(refuse()),
                Some(x) => x,
            };
            let prel = l.edge_prop(e, key)?.ok_or_else(|| {
                GqlError::Semantic(format!("no property `{key}` for the edges of `{name}`"))
            })?;
            let code = l.code(&lit, Some(l.plan.col_type(prel, 2)))?;
            cmps.push((prel, op, code));
            text.push(format!(
                "{}.{key} {} {}",
                p.var,
                cmp_symbol(op),
                other.text()
            ));
        }
        tests.push(EdgeTest { cmps, keep: p.keep });
        let joined = text.join(" AND ");
        texts.push(if p.keep {
            joined
        } else {
            format!("NOT ({joined})")
        });
    }
    // the edges that pass, as the core's rules give them
    let f = l
        .plan
        .edge_filter(&format!("edges of {name}"), rel, &tests)?;
    l.notes.push(format!(
        "({name}): the walk keeps the edges where {}",
        texts.join(" AND ")
    ));
    Ok(f)
}

fn cmp_symbol(op: Cmp) -> &'static str {
    match op {
        Cmp::Eq => "=",
        Cmp::Ne => "<>",
        Cmp::Lt => "<",
        Cmp::Le => "<=",
        Cmp::Gt => ">",
        Cmp::Ge => ">=",
    }
}

/// The variables as terms.
fn terms_of(vars: &[Var]) -> Vec<Term> {
    vars.iter().map(|&v| Term::Var(v)).collect()
}

/// The comparison that holds exactly where `op` does not (for values both present).
/// A query with `UNION [ALL]` parts: each part lowered alone; the same column names in
/// each. Refused: `ORDER BY`, `OFFSET` or `LIMIT` in a part (they would order or cut only
/// that part) and returned lists.
fn lower_union(query: &Query, catalog: &Catalog, params: &Params, rows: Rows) -> Result<Lowered> {
    let first = Query {
        union: Vec::new(),
        union_all: false,
        ..query.clone()
    };
    let parts: Vec<&Query> = std::iter::once(&first).chain(&query.union).collect();
    let mut lowered: Vec<Lowered> = Vec::with_capacity(parts.len());
    for q in parts {
        let r = &q.ret;
        if !r.order.is_empty() || r.offset.is_some() || r.limit.is_some() {
            return Err(GqlError::Unsupported(
                "ORDER BY, OFFSET or LIMIT in a part of a UNION (it would order or cut that part \
                 alone)"
                    .into(),
            ));
        }
        let l = lower_rows(q, catalog, params, rows)?;
        if let Some(f) = lowered.first()
            && catalog.numbered()
            && f.carry.iter().zip(&l.carry).any(|(a, b)| match (a, b) {
                (Carry::Node(x, _), Carry::Node(y, _)) => {
                    let t = |sets: &Vec<Vec<String>>| -> BTreeSet<Option<String>> {
                        sets.iter()
                            .flatten()
                            .map(|s| catalog.table_named(s))
                            .collect()
                    };
                    t(x) != t(y) || t(x).len() > 1 || t(x).contains(&None)
                }
                _ => false,
            })
        {
            return Err(meet("a node column of a UNION"));
        }
        if !l.lists.is_empty() {
            return Err(GqlError::Unsupported("a returned list in a UNION".into()));
        }
        if let Some(f) = lowered.first()
            && f.columns != l.columns
        {
            return Err(GqlError::Semantic(format!(
                "UNION parts return different columns: {} and {}",
                f.columns.join(", "),
                l.columns.join(", ")
            )));
        }
        lowered.push(l);
    }
    let mut head = lowered.remove(0);
    head.union = lowered;
    head.union_all = query.union_all;
    Ok(head)
}

/// `op` with its sides swapped (`a < b` is `b > a`).
fn flipped(op: Cmp) -> Cmp {
    match op {
        Cmp::Lt => Cmp::Gt,
        Cmp::Gt => Cmp::Lt,
        Cmp::Le => Cmp::Ge,
        Cmp::Ge => Cmp::Le,
        o => o,
    }
}

/// The vertex tables node `n`'s labels name (for a node with no label: the one its edges
/// name); `None` when a label has none, or the node has no label and no table.
fn tables_of(l: &Lowering<'_>, n: usize) -> Option<BTreeSet<String>> {
    let node = &l.nodes[n];
    if node.labels.is_empty() {
        return node.table.clone().map(|t| BTreeSet::from([t]));
    }
    node.labels
        .iter()
        .flatten()
        .map(|lab| l.catalog.table_named(lab))
        .collect()
}

/// The refusal of a match where nodes of two vertex tables meet.
fn meet(what: &str) -> GqlError {
    GqlError::Unsupported(format!(
        "{what}: nodes of two vertex tables meet there, and their rows share their numbers; a \
         catalog of one id space has none of this (a set's, kleene-gar's `IdSpace`, as `kleene \
         gql` reads it)"
    ))
}

/// In a catalog of vertex tables ([`Catalog::vertex_table`]), where a node is its row,
/// refuse a match where nodes of two tables meet by row: a node of labels of two tables, a
/// node of any table at an edge, an edge whose (label, way) pairs join two pairs of tables
/// or a table its end does not have, a variable-length edge through two tables.
fn two_tables(l: &Lowering<'_>, steps: &[Step]) -> Result<()> {
    if !l.catalog.numbered() {
        return Ok(());
    }
    for n in 0..l.nodes.len() {
        if tables_of(l, n).is_some_and(|t| t.len() > 1) {
            return Err(meet(&format!(
                "`{}` of labels of two vertex tables",
                l.nodes[n].name
            )));
        }
    }
    for s in steps {
        let (labels, any, quantified) = &s.edge;
        let shown = || labels.join("|");
        if l.nodes[s.from].global || l.nodes[s.to].global {
            return Err(meet(&format!(
                "a node of any vertex table at edge `{}`",
                shown()
            )));
        }
        // (an edge label whose ends are not known: not told)
        let Some(pairs) = labels
            .iter()
            .map(|lab| {
                let (a, b) = l.catalog.ends(lab)?;
                Some((l.catalog.table_named(a)?, l.catalog.table_named(b)?))
            })
            .collect::<Option<Vec<(String, String)>>>()
        else {
            continue;
        };
        let pairs: BTreeSet<(String, String)> = pairs
            .into_iter()
            .flat_map(|(a, b)| {
                let back = any.then(|| (b.clone(), a.clone()));
                std::iter::once((a, b)).chain(back)
            })
            .collect();
        let one = |n: usize| tables_of(l, n).and_then(|t| t.into_iter().next());
        let tables: BTreeSet<&String> = pairs.iter().flat_map(|p| [&p.0, &p.1]).collect();
        let fits = pairs
            .iter()
            .all(|p| one(s.from).is_none_or(|t| t == p.0) && one(s.to).is_none_or(|t| t == p.1));
        if pairs.len() > 1 || (*quantified && tables.len() > 1) || !fits {
            return Err(meet(&format!("edge `{}`", shown())));
        }
    }
    Ok(())
}

/// Whether node `n` is pinned: found by an index lookup, or of a label and equal to a
/// constant.
fn pinned(l: &Lowering<'_>, conds: &[(Val, Cmp, Val)], n: usize) -> bool {
    l.hits.contains_key(&n)
        || (!l.nodes[n].labels.is_empty() || l.nodes[n].global)
            && conds.iter().any(|&(a, op, b)| {
                op == Cmp::Eq
                    && match (a, b) {
                        (Val::Node(m), Val::Const(_)) | (Val::Const(_), Val::Node(m)) => m == n,
                        _ => false,
                    }
            })
}

/// Index lookups: per node, what bounds it (its labels' id blocks in a catalog of one id
/// space, its properties with each holding label's range or name index, the comparisons
/// with constants and the ORs of equalities in the WHERE's top conjunction) as a core
/// [`kleene_plan::Lookup`]; the core's choice ([`kleene_plan::Lookup::choose`]) finds the
/// node by an index, not a scan of its label. In a catalog of vertex tables `id(n)` bounds
/// list rows ([`id_lookup`]). The comparisons stay in the match rule.
fn index_lookups(l: &mut Lowering<'_>, conds: &[(Val, Cmp, Val)], ors: &[Cx]) -> Result<()> {
    for n in 0..l.nodes.len() {
        if l.catalog.numbered() && id_lookup(l, n, conds)? {
            continue;
        }
        // The labels whose indexes find `n` by a key: its one label; or, for a node with no
        // label in a catalog of one id space (any node, or at an edge), every label holding
        // the key (it has a value only as a node of one of them), each with an index.
        let one: Option<String> = match &l.nodes[n].labels[..] {
            [set] if set.len() == 1 => Some(set[0].clone()),
            _ => None,
        };
        let node = &l.nodes[n];
        let unlabelled = !l.catalog.numbered()
            && !node.global
            && !node.called
            && (node.anything || node.labels.is_empty());
        let one = one.as_deref();
        let mut lk = kleene_plan::Lookup::default();
        // id blocks: of its labels (no label: of every label of no other's)
        if !l.catalog.numbered() && !node.global && !node.called {
            let labels: Vec<String> = match &node.labels[..] {
                [] => l.catalog.top_labels().map(String::from).collect(),
                [set] => set.clone(),
                _ => Vec::new(),
            };
            let blocks: Option<Vec<(u64, u64)>> =
                labels.iter().map(|x| l.catalog.block(x)).collect();
            lk.blocks = blocks.filter(|b| !b.is_empty());
        }
        // its properties, each with the index of every label holding it
        let mut holders: Vec<Vec<String>> = Vec::with_capacity(l.props.len());
        for p in &l.props {
            let ty = l.plan.col_type(p.rel, 1);
            let ls = if p.node == n && (one.is_some() || unlabelled) {
                holding(l, one, &p.key)
            } else {
                Vec::new()
            };
            let indexes = ls
                .iter()
                .map(|x| {
                    if ty == Type::Str {
                        l.catalog
                            .name_idx(x, &p.key)
                            .map(|index| kleene_plan::Index::Names {
                                index: index.clone(),
                                within: None,
                            })
                    } else {
                        l.catalog
                            .prop_idx(x, &p.key)
                            .map(|s| kleene_plan::Index::Range {
                                lookup: s.clone(),
                                within: None,
                            })
                    }
                })
                .collect();
            lk.props.push(kleene_plan::Key { ty, indexes });
            holders.push(ls);
        }
        let bound = |a: Val, op: Cmp, b: Val| -> Option<kleene_plan::Bound> {
            let (x, op, c) = match (a, b) {
                (x, Val::Const(c)) => (x, op, c),
                (Val::Const(c), x) => (x, flipped(op), c),
                _ => return None,
            };
            let on = match x {
                Val::Prop(m, s) if m == n => kleene_plan::On::Prop(s),
                Val::Node(m) if m == n => kleene_plan::On::Id,
                _ => return None,
            };
            Some(kleene_plan::Bound { on, op, value: c })
        };
        lk.bounds = conds
            .iter()
            .filter_map(|&(a, op, b)| bound(a, op, b))
            .collect();
        // ORs of comparisons all on `n`
        lk.ors = ors
            .iter()
            .filter_map(|c| match c {
                Cx::Or(parts) => parts
                    .iter()
                    .map(|p| match p {
                        Cx::Cmp(a, op, b) => bound(*a, *op, *b),
                        _ => None,
                    })
                    .collect::<Option<Vec<_>>>(),
                // one lookup per member, as an OR of equalities
                Cx::In(a, list, _) => {
                    let mut members = l.plan.list_of(*list).members.clone();
                    members.sort_unstable();
                    members.dedup();
                    (!members.is_empty())
                        .then(|| {
                            members
                                .iter()
                                .map(|&k| bound(*a, Cmp::Eq, Val::Const(k)))
                                .collect::<Option<Vec<_>>>()
                        })
                        .flatten()
                }
                _ => None,
            })
            .collect();
        let Some(choice) = lk.choose(l.plan.strings()) else {
            continue;
        };
        let name = l.nodes[n].name.clone();
        let hit = choice.build(&lk, &mut l.plan, &mut l.inputs, &format!("hit_{name}"))?;
        l.hits.insert(n, hit);
        let key = |l: &Lowering<'_>, s: usize| -> (String, String) {
            (holders[s].join("|"), l.props[s].key.clone())
        };
        let note = match &choice {
            kleene_plan::Choice::Ids { wanted } => {
                let shown: Vec<String> = wanted
                    .iter()
                    .map(|(a, b)| {
                        if a == b {
                            a.to_string()
                        } else {
                            format!("{a}..={b}")
                        }
                    })
                    .collect();
                format!("({name}): id range {}, ids listed", shown.join(", "))
            }
            kleene_plan::Choice::Names { prop, names } => {
                let (labels, key) = key(l, *prop);
                let shown: Vec<String> = names.iter().map(|x| format!("{x:?}")).collect();
                format!(
                    "({name}): name index {labels}.{key} for {}",
                    shown.join(", ")
                )
            }
            kleene_plan::Choice::Range { prop, lo, hi, .. } => {
                let (labels, key) = key(l, *prop);
                format!("({name}): index lookup {labels}.{key} in {lo}..={hi}")
            }
            kleene_plan::Choice::At { prop, values } => {
                let (labels, key) = key(l, *prop);
                let shown: Vec<String> = values.iter().map(|x| x.to_string()).collect();
                format!(
                    "({name}): index lookup {labels}.{key} at {}",
                    shown.join(", ")
                )
            }
            _ => format!("({name}): an index lookup"),
        };
        l.notes.push(note);
    }
    Ok(())
}

/// The labels whose nodes a lookup by property `key` of a node of label `one` (or, with
/// none, of no label) finds: `one`, or every label holding the key.
fn holding(l: &Lowering<'_>, one: Option<&str>, key: &str) -> Vec<String> {
    match one {
        Some(x) => vec![x.to_string()],
        None => l.catalog.holders(key),
    }
}

/// A node of a vertex table (or of any, with no label and no edge) with constant bounds on
/// its `id(n)` in the WHERE's top conjunction: its rows in the range, listed from the
/// tables' numbers (no scan, no index). The comparisons stay in the match rule.
fn id_lookup(l: &mut Lowering<'_>, n: usize, conds: &[(Val, Cmp, Val)]) -> Result<bool> {
    let (ranges, rows, target) = if l.nodes[n].global {
        let ranges: Vec<(u64, u64)> = l.catalog.tables().map(|t| (t.1, t.2)).collect();
        (ranges, false, Val::Node(n))
    } else {
        let Ok(Some((label, base))) = l.table_of(n) else {
            return Ok(false);
        };
        let Some((_, count)) = l.catalog.table(&label) else {
            return Ok(false);
        };
        let target = if base == 0 {
            Val::Node(n)
        } else {
            match l.props.iter().position(|p| p.node == n && p.key == ID_KEY) {
                Some(s) => Val::Prop(n, s),
                None => return Ok(false),
            }
        };
        (vec![(base, count)], true, target)
    };
    let Some((lo, hi)) = bounds_of(target, conds) else {
        return Ok(false);
    };
    let name = format!("ids of {} in {lo}..={hi}", l.nodes[n].name);
    let ext = l.plan.external(&name, 1);
    l.inputs.external(
        ext,
        Arc::new(if rows {
            IdRanges::new(ranges, [(lo, hi)]).rows()
        } else {
            IdRanges::new(ranges, [(lo, hi)])
        }),
    );
    let v = l.plan.var("I");
    let hit = l.plan.derived(&format!("hit_{}", l.nodes[n].name), 1);
    l.plan.rule(at(hit, &[v]), [atom(ext, &[v])])?;
    l.hits.insert(n, hit);
    l.notes.push(format!(
        "({}): id range {lo}..={hi}, rows listed",
        l.nodes[n].name
    ));
    Ok(true)
}

/// The bounds `(lo, hi)` (both in) the WHERE's top conjunction puts on value `target` by
/// comparisons with constants, if any does.
fn bounds_of(target: Val, conds: &[(Val, Cmp, Val)]) -> Option<(Value, Value)> {
    let (mut lo, mut hi, mut any) = (0, Value::MAX, false);
    for &(a, op, b) in conds {
        let (op, c) = match (a, b) {
            (x, Val::Const(c)) if x == target => (op, c),
            (Val::Const(c), x) if x == target => (flipped(op), c),
            _ => continue,
        };
        any |= op != Cmp::Ne;
        match op {
            Cmp::Eq => {
                lo = lo.max(c);
                hi = hi.min(c);
            }
            Cmp::Lt => match c.checked_sub(1) {
                Some(x) => hi = hi.min(x),
                None => (lo, hi) = (1, 0),
            },
            Cmp::Le => hi = hi.min(c),
            Cmp::Gt => match c.checked_add(1) {
                Some(x) => lo = lo.max(x),
                None => (lo, hi) = (1, 0),
            },
            Cmp::Ge => lo = lo.max(c),
            Cmp::Ne => {}
        }
    }
    any.then_some((lo, hi))
}

/// The property name of `id(n)` read through a shift relation (no property has it: it
/// has parentheses).
const ID_KEY: &str = "id()";

/// Lowers one filter over `nodes` with three-valued logic, as relations over those nodes:
/// for each part, the bindings (of the domain) where it is true, and where it is false
/// (neither where it is unknown: a property missing). `NOT` swaps the two, `AND` is true
/// where all parts are (one rule joining them) and false where any is (a rule each), `OR`
/// the other way round, `XOR` two rules each way. A comparison inside a rule is written
/// there; any other part is its own relation, made once (true and false each at most
/// once), so the rules grow with the condition's length, never exponentially.
struct Emit {
    nodes: Vec<usize>,
    dom: Vec<Literal>,
    made: HashMap<(*const Cx, bool), RelId>,
}

impl Emit {
    fn new(nodes: Vec<usize>, dom: Vec<Literal>) -> Self {
        Emit {
            nodes,
            dom,
            made: HashMap::new(),
        }
    }

    /// The relation of the domain's bindings where `c` is `want`.
    fn rel(&mut self, l: &mut Lowering<'_>, c: &Cx, want: bool) -> Result<RelId> {
        if let Some(&r) = self.made.get(&(c as *const Cx, want)) {
            return Ok(r);
        }
        let vars: Vec<Var> = self.nodes.iter().map(|&n| l.nodes[n].var).collect();
        let name = format!(
            "where{}_{}",
            l.plan.relations().len(),
            if want { "t" } else { "f" }
        );
        let r = l.plan.derived(&name, vars.len());
        let bodies = self.alts(l, c, want)?;
        if bodies.is_empty() {
            // Never: the domain under a condition that does not hold.
            let mut b = self.dom.clone();
            b.push(Literal::Cond(Cond::Cmp {
                left: Term::Const(0),
                op: Cmp::Ne,
                right: Term::Const(0),
            }));
            l.plan.rule(at(r, &vars), b)?;
        }
        for mut b in bodies {
            let binds = |v: &Var| {
                b.iter()
                    .any(|lit| matches!(lit, Literal::Pos(a) if a.terms.contains(&Term::Var(*v))))
            };
            if !vars.iter().all(binds) {
                let mut d = self.dom.clone();
                d.append(&mut b);
                b = d;
            }
            l.plan.rule(at(r, &vars), b)?;
        }
        self.made.insert((c as *const Cx, want), r);
        Ok(r)
    }

    /// `c` being `want` as one conjunction: a comparison written out, else its relation.
    fn part(&mut self, l: &mut Lowering<'_>, c: &Cx, want: bool) -> Result<Vec<Literal>> {
        if let Cx::Cmp(..) = c {
            let mut alts = self.alts(l, c, want)?;
            return Ok(alts.pop().unwrap_or_default());
        }
        if let Cx::In(..) = c {
            let mut alts = self.alts(l, c, want)?;
            if alts.len() == 1 {
                return Ok(alts.pop().expect("one body"));
            }
        }
        let r = self.rel(l, c, want)?;
        let vars: Vec<Var> = self.nodes.iter().map(|&n| l.nodes[n].var).collect();
        Ok(vec![atom(r, &vars)])
    }

    /// The bodies (a union) where `c` is `want`; none: never; one empty body: always.
    fn alts(&mut self, l: &mut Lowering<'_>, c: &Cx, want: bool) -> Result<Vec<Vec<Literal>>> {
        Ok(match c {
            Cx::Known(b) => {
                if *b == want {
                    vec![Vec::new()]
                } else {
                    Vec::new()
                }
            }
            Cx::Cmp(a, op, b) => {
                let mut body = Vec::new();
                l.prop_atoms(&[*a, *b], &mut body);
                body.push(Literal::Cond(Cond::Cmp {
                    left: l.term(*a),
                    op: if want { *op } else { op.negated() },
                    right: l.term(*b),
                }));
                vec![body]
            }
            // Null where the value is, or where the node has no row.
            Cx::Null(a, null) if *null == want => {
                let Val::Prop(n, s) = *a else {
                    // an edge property: a null value (an edge with no row has none)
                    let mut body = Vec::new();
                    l.prop_atoms(&[*a], &mut body);
                    body.push(Literal::Cond(Cond::IsNull {
                        x: l.term(*a),
                        null: true,
                    }));
                    return Ok(vec![body]);
                };
                let mut body = Vec::new();
                l.prop_atoms(&[*a], &mut body);
                body.push(Literal::Cond(Cond::IsNull {
                    x: l.term(*a),
                    null: true,
                }));
                let has = l.has(l.props[s].rel)?;
                vec![body, vec![Literal::Neg(at(has, &[l.nodes[n].var]))]]
            }
            Cx::Null(a, _) => {
                let mut body = Vec::new();
                l.prop_atoms(&[*a], &mut body);
                body.push(Literal::Cond(Cond::IsNull {
                    x: l.term(*a),
                    null: false,
                }));
                vec![body]
            }
            // a list with a NULL: IN is never false, NOT IN never true
            Cx::In(_, _, true) if !want => Vec::new(),
            Cx::In(a, list, _) => {
                let mut body = Vec::new();
                l.prop_atoms(&[*a], &mut body);
                body.push(Literal::Cond(Cond::OneOf {
                    x: l.term(*a),
                    list: *list,
                    not: !want,
                }));
                vec![body]
            }
            Cx::Text(a, op, k) => {
                let mut body = Vec::new();
                l.prop_atoms(&[*a], &mut body);
                if want {
                    body.push(Literal::Cond(Cond::Text {
                        x: l.term(*a),
                        op: *op,
                        pat: Term::Const(*k),
                    }));
                } else {
                    // false: a value that is there and fails the test
                    body.push(Literal::Cond(Cond::IsNull {
                        x: l.term(*a),
                        null: false,
                    }));
                    let r = self.rel(l, c, true)?;
                    let vars: Vec<Var> = self.nodes.iter().map(|&n| l.nodes[n].var).collect();
                    body.push(Literal::Neg(at(r, &vars)));
                }
                vec![body]
            }
            Cx::Not(x) => self.alts(l, x, !want)?,
            // All parts must be `want`: one body.
            Cx::And(cs) if want => vec![self.all(l, cs, true)?],
            Cx::Or(cs) if !want => vec![self.all(l, cs, false)?],
            // Any part: a body each.
            Cx::And(cs) | Cx::Or(cs) => {
                let mut out = Vec::new();
                for c in cs {
                    out.push(self.part(l, c, want)?);
                }
                out
            }
            // True: exactly one is true; false: both are, or neither.
            Cx::Xor(a, b) => {
                let mut one = self.part(l, a, true)?;
                one.extend(self.part(l, b, !want)?);
                let mut two = self.part(l, a, false)?;
                two.extend(self.part(l, b, want)?);
                vec![one, two]
            }
        })
    }

    fn all(&mut self, l: &mut Lowering<'_>, cs: &[Cx], want: bool) -> Result<Vec<Literal>> {
        let mut body = Vec::new();
        for c in cs {
            for lit in self.part(l, c, want)? {
                if !body.contains(&lit) {
                    body.push(lit);
                }
            }
        }
        Ok(body)
    }
}

/// A `RETURN` item resolved: a value, an aggregate of one (none: `count(*)`), or the
/// `rank(..)` of this number among the query's ranks.
enum Item {
    Plain(Val),
    Agg(AggFn, bool, Option<Val>),
    Rank(usize),
}

/// Two literals compared: numbers as numbers, strings by their bytes, booleans false first.
fn known(x: &Lit, op: Cmp, y: &Lit) -> Result<bool> {
    use std::cmp::Ordering;
    let num = |l: &Lit| match *l {
        Lit::Uint(u) => Some(u as f64),
        Lit::Int(i) => Some(i as f64),
        Lit::Float(f) => Some(f),
        _ => None,
    };
    let ord = match (x, y) {
        (Lit::Uint(a), Lit::Uint(b)) => a.cmp(b),
        (Lit::Int(a), Lit::Int(b)) => a.cmp(b),
        // a negative integer is below every unsigned one
        (Lit::Int(_), Lit::Uint(_)) => Ordering::Less,
        (Lit::Uint(_), Lit::Int(_)) => Ordering::Greater,
        (Lit::Str(a), Lit::Str(b)) => a.as_bytes().cmp(b.as_bytes()),
        (Lit::Bool(a), Lit::Bool(b)) => a.cmp(b),
        _ => match (num(x), num(y)) {
            (Some(a), Some(b)) => a.total_cmp(&b),
            _ => {
                return Err(GqlError::Semantic(format!(
                    "{} compared with {}",
                    lit_name(x),
                    lit_name(y)
                )));
            }
        },
    };
    Ok(match op {
        Cmp::Eq => ord.is_eq(),
        Cmp::Ne => ord.is_ne(),
        Cmp::Lt => ord.is_lt(),
        Cmp::Le => ord.is_le(),
        Cmp::Gt => ord.is_gt(),
        Cmp::Ge => ord.is_ge(),
    })
}

fn lit_name(x: &Lit) -> &'static str {
    match x {
        Lit::Uint(_) => "an unsigned integer",
        Lit::Int(_) => "a negative integer",
        Lit::Float(_) => "a float",
        Lit::Str(_) => "a string",
        Lit::Bool(_) => "a boolean",
        Lit::Null => "NULL",
    }
}

fn cmp(op: CmpOp) -> Cmp {
    match op {
        CmpOp::Eq => Cmp::Eq,
        CmpOp::Ne => Cmp::Ne,
        CmpOp::Lt => Cmp::Lt,
        CmpOp::Le => Cmp::Le,
        CmpOp::Gt => Cmp::Gt,
        CmpOp::Ge => Cmp::Ge,
    }
}

fn nodes_of(vals: &[Val]) -> impl Iterator<Item = usize> + '_ {
    vals.iter().flat_map(|v| match *v {
        Val::Node(n) | Val::Prop(n, _) => vec![n],
        Val::EdgeProp { from, to, .. } => vec![from, to],
        Val::Yield(_) | Val::PathLen(_) | Val::PathId(_) | Val::Const(_) => Vec::new(),
        Val::Calc { nodes, .. } => (0..64).filter(|&n| nodes >> n & 1 == 1).collect(),
    })
}

/// The values a path's list is built from: a fixed path's nodes, a shortest path's ends
/// and number.
fn list_vals(l: &Lowering<'_>, k: usize) -> Vec<Val> {
    match &l.path_vars[k].kind {
        PathKind::Fixed(ns) => ns.iter().map(|&n| Val::Node(n)).collect(),
        PathKind::Shortest { start, end, .. } => {
            vec![Val::Node(*start), Val::Node(*end), Val::PathId(k)]
        }
    }
}

fn has_atom(body: &[Literal]) -> bool {
    body.iter().any(|l| matches!(l, Literal::Pos(_)))
}

fn zero_length(label: &str, node: &str) -> GqlError {
    GqlError::Unsupported(format!(
        "a path of length 0 over `{label}` from `{node}`, which has no label: give one end a label"
    ))
}

/// A quantified edge with a length range other than 0 or 1 to no bound: a walk from a
/// start relation. Its ends alone when the start node is dropped (or, backward, the end
/// node), else (start, end) pairs from the start's seeds (or, backward, the end's), else
/// pairs from every source of an edge. Gives the match rule's atom and the walk relation.
#[allow(clippy::too_many_arguments)]
fn lower_walk(
    l: &mut Lowering<'_>,
    s: &Step,
    hops: Hops,
    name: &str,
    drop: &[bool],
    gone: &mut [bool],
    (from_seeds, to_seeds): (Vec<Literal>, Vec<Literal>),
    counted: Option<RelId>,
) -> Result<(Literal, RelId)> {
    let (fv, tv) = (l.nodes[s.from].var, l.nodes[s.to].var);
    let forward_end = s.from != s.to && drop[s.from];
    let backward_end = !forward_end && s.from != s.to && drop[s.to];
    // Which node the walk starts at, and whether it runs along the edges.
    let forward = if forward_end {
        true
    } else if backward_end {
        false
    } else {
        !from_seeds.is_empty() || to_seeds.is_empty()
    };
    let (start, seeds) = if forward {
        (s.from, from_seeds)
    } else {
        (s.to, to_seeds)
    };
    let sv = l.nodes[start].var;
    let other = l.plan.var("O");
    // A start needs an atom: its label, else the edges it leaves (or, backward, enters).
    let body: Vec<Literal> = if has_atom(&seeds) {
        seeds
    } else if hops.min == 0 {
        return Err(zero_length(&s.label, &l.nodes[start].name));
    } else {
        let e = if forward {
            atom(s.rel, &[sv, other])
        } else {
            atom(s.rel, &[other, sv])
        };
        [vec![e], seeds].concat()
    };
    let starts = l.plan.derived(&format!("{name}_start"), 1);
    l.plan.rule(at(starts, &[sv]), body)?;
    let way = if forward { Way::Forward } else { Way::Backward };
    // Counted (one row per walk): the number of walks per end or pair, by plus-times
    // steps over `counted` (the edges, or their counts of parallel edges).
    let ends = |l: &mut Lowering<'_>, k: usize| -> Result<RelId> {
        Ok(match counted {
            Some(e) => {
                let p = l.plan.derived_counted(name, &vec![Type::U64; k]);
                l.plan.walk_counted(p, starts, e, way, hops)?;
                p
            }
            None => {
                let p = l.plan.derived(name, k);
                l.plan.walk(p, starts, s.rel, way, hops)?;
                p
            }
        })
    };
    if forward_end || backward_end {
        gone[start] = true;
        let p = ends(l, 1)?;
        let keep = if forward { tv } else { fv };
        return Ok((l.atom_n(p, &[keep]), p));
    }
    let p = ends(l, 2)?;
    let terms = if forward { [fv, tv] } else { [tv, fv] };
    Ok((l.atom_n(p, &terms), p))
}

/// The procedures a `CALL` may name (lower case, a prefix `algo.`, `gds.` or `kleene.` and
/// a suffix `.stream` left out): the procedure's kind and its columns.
fn procedure_named(name: &str) -> Option<(&'static str, &'static [&'static str])> {
    let mut n = name.to_ascii_lowercase();
    for pre in ["algo.", "gds.", "kleene."] {
        if let Some(r) = n.strip_prefix(pre) {
            n = r.to_string();
        }
    }
    if let Some(r) = n.strip_suffix(".stream") {
        n = r.to_string();
    }
    Some(match n.as_str() {
        "pagerank" | "page_rank" => ("pagerank", &["node", "score"]),
        "wcc" | "weaklyconnectedcomponents" | "connectedcomponents" | "components" => {
            ("wcc", &["node", "component"])
        }
        "scc" | "stronglyconnectedcomponents" => ("scc", &["node", "component"]),
        "sssp" | "dijkstra" | "deltastepping" | "bfs" => ("sssp", &["node", "distance"]),
        "betweenness" | "betweennesscentrality" | "bc" => ("betweenness", &["node", "score"]),
        "trianglecount" | "triangles" | "tc" => ("triangles", &["count"]),
        "harmonic" | "harmoniccentrality" | "closeness.harmonic" => {
            ("harmonic", &["node", "score"])
        }
        "ktruss" | "k_truss" | "truss" => ("ktruss", &["source", "target", "support"]),
        "mis" | "maximalindependentset" | "independentset" => ("mis", &["node"]),
        "trussnumbers" | "trussnumber" | "truss_numbers" | "trussdecomposition" => {
            ("trussnumbers", &["source", "target", "truss"])
        }
        "msf"
        | "mst"
        | "spanningforest"
        | "minimumspanningforest"
        | "spanningtree"
        | "minimumspanningtree" => ("msf", &["source", "target", "weight"]),
        "maxflow" | "max_flow" | "maximumflow" => ("maxflow", &["flow"]),
        _ => return None,
    })
}

/// The columns of a procedure that hold nodes: bound to node variables, which later
/// patterns share.
const NODE_COLUMNS: [&str; 3] = ["node", "source", "target"];

/// A `CALL`: the procedure's relation from its arguments, its yielded node column bound
/// to a node variable and its value columns to yielded values. Gives the relation's atom.
fn lower_call(l: &mut Lowering<'_>, c: &CallClause) -> Result<Literal> {
    if let Some(columns) = schema_named(&c.procedure) {
        return lower_schema_call(l, c, columns);
    }
    if let Some(what) = machine_named(&c.procedure) {
        return lower_machine_call(l, c, what);
    }
    let (kind, columns) = procedure_named(&c.procedure).ok_or_else(|| {
        GqlError::Semantic(format!(
            "no procedure `{}` (pagerank, wcc, scc, sssp, bfs, betweenness, triangleCount, \
             harmonic, ktruss, trussNumbers, mis, msf, maxflow; schema.labels, schema.edges, \
             schema.columns, schema.refused; machine.steps, machine.states, machine.starts)",
            c.procedure
        ))
    })?;
    let usage = || match Procedure::usage(kind) {
        Some(args) => format!("{}(EdgeLabel{args})", c.procedure),
        None => format!("{}(EdgeLabel, source [, weightKey])", c.procedure),
    };
    let label = match c.args.first() {
        Some(CallArg::Name(n)) => n.clone(),
        _ => {
            return Err(GqlError::Semantic(format!(
                "{}: an edge label first",
                usage()
            )));
        }
    };
    // the arguments after the label, read; their meaning and checks are kleene-plan's
    let mut args = Vec::with_capacity(c.args.len().saturating_sub(1));
    for (i, a) in c.args[1..]
        .iter()
        .enumerate()
        .filter(|_| Procedure::usage(kind).is_some())
    {
        args.push(match a {
            // an edge property's key: its relation, mapped as it is
            CallArg::Name(key) if Procedure::property_arg(kind, i) => {
                ProcArg::Values(l.edge_values(&label, key)?)
            }
            CallArg::Name(w) => ProcArg::Word(w),
            CallArg::Value(o) => match l.value(o)? {
                Val::Const(v) => ProcArg::Number(v),
                _ => unreachable!("an argument value is a constant"),
            },
        });
    }
    // a refused argument is the query's fault: a semantic error
    let made = Procedure::from_args(kind, &args).map_err(|e| match e {
        kleene_plan::PlanError::Program(why) => GqlError::Semantic(why),
        e => GqlError::Plan(e),
    })?;
    if made.is_none() && c.args.len() > 3 {
        return Err(GqlError::Semantic(format!(
            "{}: too many arguments",
            usage()
        )));
    }
    let (edge, _) = l.edge_rel(std::slice::from_ref(&label), false)?;
    let bfs = c.procedure.to_ascii_lowercase().ends_with("bfs");
    let procedure = match made {
        Some(p) => p,
        None => {
            let source = match c.args.get(1) {
                Some(CallArg::Value(o)) => match l.value(o)? {
                    Val::Const(v) => v,
                    _ => unreachable!("an argument value is a constant"),
                },
                _ => {
                    return Err(GqlError::Semantic(format!(
                        "{}: a source vertex second",
                        usage()
                    )));
                }
            };
            let weights = match c.args.get(2) {
                None => None,
                // the weight key's relation, as the core's catalog gives it
                Some(CallArg::Name(key)) if !bfs => Some(l.edge_values(&label, key)?),
                Some(_) => {
                    return Err(GqlError::Semantic(format!(
                        "{}: the third argument is a weight key{}",
                        usage(),
                        if bfs {
                            " (not for bfs: every edge weighs 1)"
                        } else {
                            ""
                        }
                    )));
                }
            };
            Procedure::Sssp { source, weights }
        }
    };
    // Scores and float weights are float columns (Type::F64 codes): a typed relation.
    let types = l.plan.procedure_types(&procedure);
    let rel = typed_rel(&mut l.plan, &format!("call_{kind}"), &types);
    l.plan.procedure(rel, edge, procedure)?;
    yield_columns(l, c, columns, &types, rel)
}

/// What a `machine.*` call yields: its steps, its states' nodes or its starts.
#[derive(Clone, Copy, PartialEq, Eq)]
enum MachineCall {
    Steps,
    States,
    Starts,
}

/// The state machine calls (lower case): `machine.steps`, `machine.states`,
/// `machine.starts`.
fn machine_named(name: &str) -> Option<MachineCall> {
    Some(match name.to_ascii_lowercase().as_str() {
        "machine.steps" => MachineCall::Steps,
        "machine.states" => MachineCall::States,
        "machine.starts" => MachineCall::Starts,
        _ => return None,
    })
}

/// A `CALL machine.steps / states / starts (Edge, labelKey, Eps | NULL, Start [, startKey]
/// [, limit])`: the core's state machine ([`Plan::state_machine`], the subset construction)
/// of the `Edge` edges, each named by its `labelKey` property, with the closure through the
/// `Eps` edges, from the nodes of label `Start` (each its own key, or keyed by its
/// `startKey` property: equal values make one start set). All three calls lower onto the
/// same helper's relations: the steps (state, label, next), the table of sets (state,
/// node), the starts (node or key, state). First version: `Edge` and `Eps` within one node
/// label, `Start` a label of its nodes.
fn lower_machine_call(l: &mut Lowering<'_>, c: &CallClause, what: MachineCall) -> Result<Literal> {
    let usage = format!(
        "{}(Edge, labelKey, Eps | NULL, Start [, startKey] [, limit])",
        c.procedure
    );
    let bad = |m: &str| GqlError::Semantic(format!("{usage}: {m}"));
    let name = |i: usize, m: &str| match c.args.get(i) {
        Some(CallArg::Name(n)) => Ok(n.clone()),
        _ => Err(bad(m)),
    };
    let edge = name(0, "an edge label first")?;
    let label_key = name(1, "the edges' property that names the step second")?;
    let eps = match c.args.get(2) {
        Some(CallArg::Name(n)) => Some(n.clone()),
        Some(CallArg::Value(Operand::Null)) => None,
        _ => return Err(bad("an edge label without a label third, or NULL")),
    };
    let start = name(3, "a node label of the starts fourth")?;
    let (mut key, mut limit) = (None, None);
    for a in c.args.iter().skip(4) {
        match a {
            CallArg::Name(k) if key.is_none() && limit.is_none() => key = Some(k.clone()),
            CallArg::Value(o) if limit.is_none() && !matches!(o, Operand::Null) => {
                match l.value(o)? {
                    Val::Const(0) => return Err(bad("the limit of sets is 1 or more")),
                    Val::Const(v) => limit = Some(v),
                    _ => return Err(bad("the limit is an integer")),
                }
            }
            _ => return Err(bad("one start key and one limit at most")),
        }
    }
    for n in std::iter::once(&edge).chain(&eps) {
        if l.catalog.edge_label(n).is_none() {
            return Err(GqlError::Semantic(format!("no edge label `{n}`")));
        }
    }
    if l.catalog.node_label(&start).is_none() {
        return Err(GqlError::Semantic(format!("no node label `{start}`")));
    }
    if let Some(k) = &key {
        if let Some(why) = l.catalog.refused_prop(Some(&start), k, false) {
            return Err(GqlError::Unsupported(why));
        }
        if l.catalog.label_prop(&start, k).is_none() {
            return Err(GqlError::Semantic(format!(
                "no property `{k}` for node label `{start}`"
            )));
        }
    }
    // One node label: the ends of both edge labels, where the catalog names them, are one
    // label, and (with vertex tables, where ids are rows of a table) `Start` is of its table.
    let within = |l: &Lowering<'_>, e: &str| -> Result<Option<String>> {
        match l.catalog.ends(e) {
            Some((a, b)) if a != b => Err(GqlError::Semantic(format!(
                "{}: the edges `{e}` go from `{a}` to `{b}`; a state machine takes edges \
                 within one node label",
                c.procedure
            ))),
            Some((a, _)) => Ok(Some(a.clone())),

The file goes on; the console shows all of it.