ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The SQL table aliases a record's rows are addressed by inside a nested statement, minted HERE
//! rather than at the moment one is rendered.
//!
//! # Why an expansion computes them and the engine only indexes
//!
//! An alias is a pure function of two compile-time facts — the table's name, and the nesting DEPTH
//! of the scope wearing it — so there is nothing about it a running statement knows that a macro
//! does not. Minting at render time therefore bought nothing and cost a `Utf8BytesMut` per
//! occurrence per statement, on the one path this family is arranged to keep allocation off.
//!
//! What the engine gets instead is `&'static [&'static str]` beside the row's address: an index, a
//! slice bound, and no string built at all.
//!
//! # Both halves are a DECLARATION's to move, and the defaults are what most of them keep
//!
//! [`ALIAS_PREFIX`] and [`DEPTH_CEILING`] are the answers a record that names nothing gets.
//! `<db>(alias(prefix = "__mine", depth = 16))` is the record that names one, and the knob
//! is per DATABASE because the emitted table is: `ALIASES` rides one `SqlQuery<Db>` impl, so two
//! databases of one record already carry two of them and nothing had to be widened to let them
//! differ.
//!
//! # The DEPTH is the axis, and it is the only one that separates anything
//!
//! An alias is scoped to the subquery that states it, so two SIBLING subqueries may each call their
//! row source the same thing and neither can see the other's. What has to differ is a name and the
//! name it NESTS inside — and nesting depth is exactly that, which is why the array is indexed by it
//! and why a per-occurrence counter would have been both unobtainable and unnecessary.
//!
//! # No parity, and no alternating pair
//!
//! Two alternating names — one for even depths, one for odd — would be enough for a reference that
//! never reaches two levels, and that is the whole objection: it is correct until a declaration
//! nests a relation inside a relation over the same table, at which point the third level silently
//! takes the first level's name, SQL resolves every reference to the inner scope, and the statement
//! answers from the wrong row source with no error anywhere. A scheme that fails silently at a
//! reachable depth is not a smaller version of this one. The ceiling is a REFUSAL for the same
//! reason: past it the engine says so.

use crate::prefix::FRAMEWORK_LEAD;

/// The framework's DEFAULT identifier namespace — the four characters a minted alias begins with
/// where the declaration named no other, and the prefix `ingraph-derive` refuses a declared table or
/// column name for taking wherever any database still defaults.
///
/// It is deliberately SHORT. An alias competes for the same sixty-three bytes an engine keeps of an
/// identifier as the table name inside it does, so every character the prefix spends is a character
/// the name it stands for loses before the clamp starts cutting — which is also the whole cost of
/// spending a longer one through `alias(prefix = "…")`.
///
/// Pinned against `ingraph`'s own `ALIAS_PREFIX` and against `ingraph-derive`'s fence — three
/// crates hold this string because the dependency edges do not let one of them hold it for the
/// others, and each pair that CAN see both is a test.
///
/// It is also the mark [`EmissionPrefix::INGRAPH`](crate::prefix::EmissionPrefix::INGRAPH) is
/// built from, so a platform's own namespace and this default are one type with one string behind
/// the framework arm rather than two spellings that have to be kept level.
pub const ALIAS_PREFIX: &str = "__ig";

/// The ORDER-PRESERVING COMPANION COLUMN one `sortable` collection is mirrored into.
///
/// ```text
/// tags  →  __ig_tags_sort__
/// ```
///
/// **The ONE mint**, and three parties spell it from here: the order-by term that renders it, the
/// write plan that fills it, and the descriptor that creates it. A companion is unlike an edge
/// table, whose name every party DERIVES — it is a real column of a real table, so it is minted once
/// and carried, which is the arrangement a provenance table's name already has.
///
/// # It is inside the SYNTHESIZED-COLUMN fence, and that is what makes it collision-proof
///
/// `__ig_` in front and `__` behind — the shape `ingraph`'s own `interface::KIND` states the law
/// for, and one `ingraph-derive` refuses a DECLARED column for taking. So no record can spell this
/// name, including one whose field is actually called `tags_sort`: that field's own companion is
/// `__ig_tags_sort_sort__`, and neither is a name a declaration could have written.
///
/// The join is INJECTIVE for the same reason: the field is everything between a fixed prefix and a
/// fixed suffix, so two fields cannot reach one companion.
///
/// It takes the column's EXTERNAL name — what `<db>(rename)` left it called in the database
/// being emitted for — because the companion is a column of THAT table beside it.
///
/// # It takes the RESOLVED namespace, and that is a fix rather than a widening
///
/// `prefix` is the mark this DATABASE mints in — `<db>(alias(prefix = …))` where the declaration
/// named one, the model's own [`EmissionPrefix`](crate::prefix::EmissionPrefix) where it did not.
/// It is the caller's to resolve, exactly as [`alias`] takes it. Spelling the framework's own constant
/// here instead was a real collision: a record that overrode the prefix on every database it names
/// has had `__ig*` HANDED BACK by `ingraph-derive`'s fence and may declare a column called
/// `__ig_tags_sort__`, which is precisely the name the companion for `tags` used to take.
#[must_use]
pub fn sort_column(prefix: &str, external: &str) -> String {
  format!("{prefix}_{external}_sort__")
}

/// How deep a record's aliases are minted where its declaration names no number, and therefore how
/// deep a relation over such a record may nest before the engine refuses.
///
/// # A DEFAULT rather than a wall, and the array is what the refusal reads
///
/// The aliases are emitted as a SLICE beside the row's address, so the length is a fact about one
/// (record, database) pair rather than part of a trait item's type — and `ingraph`'s
/// `RelationDepthError` carries that slice's own length. So a declaration whose filters nest deeper
/// writes `<db>(alias(depth = 16))` and gets sixteen, refusing at sixteen and saying so,
/// with no engine holding a second copy of the number.
///
/// Eight is chosen against what a relation predicate actually nests: each level is a subquery inside
/// a subquery over the same statement, and a filter written by hand or generated from a wire query
/// reaches two or three. The cost of the unused tail is eight `&'static str` per record per
/// database, which is a pointer pair each in the binary's read-only data and nothing at all at
/// runtime.
///
/// Past whatever was minted the lowering REFUSES, naming the table and both numbers — see
/// `ingraph`'s `SqlLoweringError::RelationDepth`. Refusing is the whole point of having a number at
/// all: the alternative to a depth is not "no limit" but a name reused at some depth nobody chose,
/// which SQL resolves to the inner scope without complaining.
pub const DEPTH_CEILING: usize = 8;

/// The shallowest alias table this mint will write: one depth.
///
/// `depth = 0` is refused rather than accepted as the empty table, because an alias array with no
/// depths aliases nothing — [`aliases`] would answer `[]`, and the emitted `ALIASES` would be a
/// slice no index can be inside. Every value from one up is a real answer, `1` included: it mints
/// the depth-zero entry the outermost `FROM` never wears and refuses every nested relation, which is
/// *this row is never nested* stated in the one place that can hold it. Zero states nothing at all.
const MINIMUM_DEPTH: usize = 1;

/// The longest alias every shipped engine keeps WHOLE: PostgreSQL's sixty-three bytes, which is one
/// below MySQL's sixty-four and unbounded on SQLite.
///
/// The LOWER of the two, because what an engine past its limit does is TRUNCATE rather than refuse.
/// Two aliases differing only past the cut arrive at the server as one name, and the statement is
/// then well-formed over a row source that is not the one it was built for — the same silent class
/// [`ALIAS_PREFIX`] exists to close, reached by a different road.
const ALIAS_CEILING: usize = 63;

/// The hexadecimal digits a clamped name's digest is rendered in.
const DIGEST_WIDTH: usize = 8;

/// Every alias one table wears in one database, indexed by the depth of the scope wearing it.
///
/// `depth` is how many the declaration asked for — [`DEPTH_CEILING`] where it asked for nothing —
/// and `prefix` the namespace they are minted in, [`ALIAS_PREFIX`] by the same rule. Both are the
/// caller's to resolve, so this function has no defaulting of its own to disagree with anybody
/// else's; [`refused`] is where the pair is held to what the mint can actually spend.
///
/// `ALIASES[0]` is minted like the rest and is never WORN: the outermost `FROM` names the real
/// table, so depth zero has no alias to take. It is present because the array is indexed by depth
/// and an array that started at depth one would need every use site to subtract, which is an
/// arithmetic step each of them could get wrong and none of them could get caught at.
pub fn aliases(prefix: &str, table: &str, depth: usize) -> Vec<String> {
  (0..depth).map(|at| alias(prefix, table, at)).collect()
}

/// `<prefix>_<table>_<depth>__`, clamped to what every shipped engine stores whole.
///
/// # A long name is CLAMPED, and the clamp cannot re-collide two names
///
/// Past [`ALIAS_CEILING`] the prefix and the depth are the parts that must survive, so the TABLE is
/// what gives way — and a plain truncation is exactly the silent re-collision the ceiling exists to
/// avoid, since two tables sharing a long leading run would cut to one string. So a clamped name
/// keeps what fits and ends in a digest of the WHOLE name, which differs wherever the names do.
///
/// # The budget is the PREFIX's to spend, which is why a declared one is bounded
///
/// Every byte the prefix takes is a byte the table loses before the clamp starts cutting, so a long
/// enough prefix would leave nothing for the name to be recognisable by — and, further out, nothing
/// for the digest either, which is subtraction below zero rather than a bad name. [`refused`] is
/// what holds a declared prefix above that line, and it is checked where the declaration is read
/// rather than here: this function is the mint, and a mint that answered a refusal would have two
/// jobs.
pub fn alias(prefix: &str, table: &str, depth: usize) -> String {
  let digits = depth.to_string();
  let budget = budget(prefix, digits.len());
  let mut alias = String::with_capacity(ALIAS_CEILING);
  alias.push_str(prefix);
  alias.push('_');
  if table.len() <= budget {
    alias.push_str(table);
  } else {
    // Saturating rather than checked, and the floor is unreachable through a declaration: `refused`
    // admits no pair leaving fewer than `DIGEST_WIDTH + 2` bytes here. What it buys is that this
    // function stays TOTAL for a caller that reached it another way — a mint that panicked would do
    // so inside an expansion, where the report is a compiler crash rather than a refusal.
    let keep = budget.saturating_sub(DIGEST_WIDTH + 1);
    alias.push_str(&table[..floor_char_boundary(table, keep)]);
    alias.push('_');
    alias.push_str(&digest(table));
  }
  alias.push('_');
  alias.push_str(&digits);
  alias.push_str("__");
  alias
}

/// How many bytes of TABLE fit inside one alias: the ceiling, less the prefix, the depth's digits
/// and the three separators plus the closing pair.
///
/// Saturating, because the caller that has not been through [`refused`] is the one asking whether a
/// prefix fits at all — and the honest answer there is zero rather than a panic in a macro
/// expansion, which is a compiler crash where a refusal was wanted.
const fn budget(prefix: &str, digits: usize) -> usize {
  ALIAS_CEILING.saturating_sub(prefix.len() + digits + 4)
}

/// Why this (prefix, depth) pair cannot be minted, or [`None`] where it can.
///
/// The RULE lives here rather than in `ingraph-derive` because the mint is here: the shapes a prefix
/// must have are the shapes [`alias`] spends it in, and a second copy of them one crate over is the
/// copy that drifts the day the mint's own shape moves. What the derive adds is the span — this
/// answers in prose and knows nothing about tokens.
///
/// Both halves are already resolved: a caller passes what it will actually mint with, so a
/// declaration that named only `depth` asks about [`ALIAS_PREFIX`] beside it and gets the same
/// answer the emission will.
#[must_use]
pub fn refused(prefix: &str, depth: usize) -> Option<String> {
  if depth < MINIMUM_DEPTH {
    return Some(format!(
      "`depth = {depth}` mints an alias array with no depths, which aliases nothing — every \
       relation predicate over this row would refuse at depth one. `depth = 1` is the shallowest \
       table that says something: it is *this row is never nested*"
    ));
  }
  if prefix.is_empty() {
    return Some(
      "`prefix` names the namespace every alias over this row is minted in, and an empty one names \
       none — the minted names would begin with the table's own, where a real table of that name \
       resolves to the inner scope and the statement answers from the wrong row source"
        .to_owned(),
    );
  }
  if !prefix.starts_with(FRAMEWORK_LEAD) {
    return Some(format!(
      "`prefix = \"{prefix}\"` does not begin `{FRAMEWORK_LEAD}` — a prefix is FENCED as well as \
       minted in, so every column and table name starting with it stops being declarable, and a \
       bare word would confiscate a namespace this schema's own author is using. Lead with \
       `{FRAMEWORK_LEAD}`, which is the shape a reader already reads as the framework's"
    ));
  }
  if let Some(stray) = prefix.chars().find(|char| !legal_in_prefix(*char)) {
    return Some(format!(
      "`prefix = \"{prefix}\"` holds `{stray}`, which an alias cannot carry — a minted name is \
       joined with `_` and read back by eye at a `FROM`, so the namespace is ASCII letters, digits \
       and `_`. A dialect would quote anything, and what it cannot do is make it recognisable"
    ));
  }
  // The DEEPEST entry is the one whose digits are widest, so a pair that fits there fits at every
  // shallower depth — and a table clamped to nothing is a name that stands for no table.
  let deepest = (depth - 1).to_string().len();
  let budget = budget(prefix, deepest);
  if budget < DIGEST_WIDTH + 2 {
    return Some(format!(
      "`prefix = \"{prefix}\"` with `depth = {depth}` leaves {budget} bytes for the table's own \
       name, where a clamped one needs {needed} — the prefix, the depth and the digest that keeps \
       two long tables apart all have to survive inside the {ALIAS_CEILING} bytes every shipped \
       engine stores whole. Shorten the prefix",
      needed = DIGEST_WIDTH + 2,
    ));
  }
  None
}

/// Whether a character may appear in a declared prefix.
///
/// Shared with [`EmissionPrefix::refused`](crate::prefix::EmissionPrefix::refused), which holds a
/// PLATFORM to the same alphabet a declaration is held to: both spend a mark as one identifier
/// joined with `_`, so a rule either of them relaxed alone would admit a name the other could not
/// spell.
pub(crate) const fn legal_in_prefix(char: char) -> bool {
  char.is_ascii_alphanumeric() || char == '_'
}

/// The largest index at or below `at` that does not split a character.
///
/// A ceiling is counted in BYTES — it is the engine's, and every one of them counts storage — while
/// a cut inside a multi-byte character produces no string at all. `str::floor_char_boundary` says
/// exactly this and is unstable, so it is written here rather than waited for.
fn floor_char_boundary(name: &str, at: usize) -> usize {
  let mut at = at.min(name.len());
  while at > 0 && !name.is_char_boundary(at) {
    at -= 1;
  }
  at
}

/// FNV-1a over the whole name, low thirty-two bits, lowercase hex — the tail that keeps two clamped
/// names apart.
///
/// A hash rather than a counter, because the clamp has to be a pure function of the name it cuts:
/// a table's alias is minted in one expansion and read by a statement built somewhere else, and the
/// two share no state to count in.
///
/// FNV-1a rather than the standard hasher, which is seeded per process — an expansion is a build
/// artefact, so a name that varied per compilation would spell one table two ways across two builds
/// of the same source.
fn digest(name: &str) -> String {
  let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
  for byte in name.as_bytes() {
    hash ^= u64::from(*byte);
    hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
  }
  #[expect(
    clippy::cast_possible_truncation,
    reason = "the low half is the digest"
  )]
  let folded = hash as u32;
  format!("{folded:0>width$x}", width = DIGEST_WIDTH)
}

#[cfg(test)]
mod tests;