ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! The EMISSION NAMESPACE: the mark every name this crate mints into somebody else's scope wears,
//! held as ONE value a front end sets rather than as a constant each mint re-spells.
//!
//! # What the seat is FOR, and who the second occupant is
//!
//! This crate is *model in, tokens out* — the derive builds a model today, and `ingraph-compiler`
//! will build one from a manifest. Both of those are `ingraph`'s own front ends and both want
//! `__ig`. The occupant this seat exists for is the third: a DOMAIN FRAMEWORK that depends on
//! `ingraph-codegen` directly, builds the same models, and emits them under its own name —
//! `mediagraph-codegen` is the first, and it passes `__mg`.
//!
//! Without the seat that framework's expansions would carry `ingraph`'s mark on every name they put
//! in an author's scope, which is wrong twice over: the names read as another crate's, and the
//! FENCE that makes them safe is a fence the other framework's derive is not holding. A namespace
//! is minted in and refused in by the same party or it is not a namespace at all — see
//! [`EmissionPrefix::refused`], which is the half a front end spends before it ever reaches a mint.
//!
//! # MIXED GRAPHS ARE LEGAL, which is why this is a value and not a feature flag
//!
//! One deployment may hold raw-`ingraph` records beside a platform's, and their names are per
//! DECLARATION rather than per build: a `__ig_key__` field on one record and a `__mg_key__` field
//! on the next are two expansions of two models, and nothing downstream is entitled to assume a
//! single mark. A `cfg` or a crate-wide constant would have made that arrangement unrepresentable;
//! a field on the model makes it the ordinary case.
//!
//! # WHAT IS AND IS NOT INSIDE THE SEAT
//!
//! The seat covers every name that lands in a SHARED namespace — the declaring module's scope, a
//! database catalog, a wire face, or an emitted public API. Those are the names a second framework
//! could stand beside, so those are the names a second framework must be able to move.
//!
//! It does NOT cover a name minted inside an anonymous `const _: () = { … }` block or bound by a
//! `let` in a generated function body. Two expansions cannot see one another's anonymous const, so
//! there is nothing there for a mark to separate — `__ig_says_goodbye` in
//! [`crate::emit`] and `__ig_row` in [`crate::aggregate`] are spelled once, collide with nothing,
//! and stay as they are. The tell is the FRAME: a name in the shared namespace wears `__` at both
//! ends, and every one of those is threaded here.

use std::borrow::Cow;

use quote::format_ident;

/// The mark a framework's emitted names are minted under — `__ig` for `ingraph` itself.
///
/// # It holds the mark WITHOUT the joining underscore
///
/// `__ig`, not `__ig_`: the separator belongs to the join rather than to the namespace, because the
/// two shapes this mints — [`framed`](Self::framed) and [`prefixed`](Self::prefixed) — place it
/// identically and a mark carrying its own would make one of them spell a double. It is also the
/// shape the FENCE reads: a declared name is refused for *starting with the mark*, and a fence
/// holding `__ig_` would let a column called `__ig` itself through.
///
/// # `Cow`, because both occupants are real
///
/// The framework's own mark is a `&'static str` and costs nothing to carry; a front end computing
/// one — from a manifest, or from a domain crate's own configuration — owns a `String`. A `Cow`
/// serves both without making the common case allocate, and [`INGRAPH`](Self::INGRAPH) is `const`
/// for the same reason.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EmissionPrefix(Cow<'static, str>);

impl Default for EmissionPrefix {
  /// The framework's own, which is what every `ingraph` front end passes and what a model built
  /// without a thought about namespaces has to be.
  fn default() -> Self {
    Self::INGRAPH
  }
}

impl EmissionPrefix {
  /// `ingraph`'s own namespace — the answer every model this repository's derive builds carries.
  ///
  /// It reads [`crate::alias::ALIAS_PREFIX`] rather than re-spelling it, so the string lives in one
  /// place and the alias mint, the companion column and the injected fields cannot drift apart.
  pub const INGRAPH: Self = Self(Cow::Borrowed(crate::alias::ALIAS_PREFIX));

  /// A domain framework's own mark.
  ///
  /// Nothing is checked here: [`refused`](Self::refused) is where the rules are, and it is spent by
  /// the front end that has a span to report at. A mint that validated would be answering a
  /// question its caller has already had to answer — the arrangement
  /// [`crate::alias::alias`] already keeps one module over.
  pub fn new(mark: impl Into<Cow<'static, str>>) -> Self {
    Self(mark.into())
  }

  /// The mark itself, for the two places that need the bare string: the FENCE a front end holds
  /// declared names to, and the alias mint that spends it as a byte budget.
  #[must_use]
  pub fn mark(&self) -> &str {
    &self.0
  }

  /// Whether this is the framework's own — the question a front end asks about the SEAT.
  ///
  /// It is what says *this model moved nothing*, and it is why a declaration under the default mark
  /// expands byte for byte as it did before this seat existed.
  ///
  /// # It is NOT the question an emission asks before staying silent
  ///
  /// That one is
  /// [`InterfaceModel::mints_the_default_words`](crate::interface::InterfaceModel::mints_the_default_words),
  /// and it compares against `ingraph`'s own constant rather than against this — because what an
  /// emission may leave unsaid is decided by what the ENGINE already believes, and the engine holds
  /// one default whoever built the model. The two coincide for `ingraph`'s front ends and part
  /// company for a platform's, which is exactly where the distinction earns its keep.
  #[must_use]
  pub fn is_default(&self) -> bool {
    self.0 == Self::INGRAPH.0
  }

  /// `__ig_<word>__` — a name in the SYNTHESIZED-COLUMN frame.
  ///
  /// The shape a framework-invented FIELD or COLUMN wears: the mark in front and `__` behind. Both
  /// ends are load-bearing. The front is what a fence refuses a declared name for; the back is what
  /// makes the join INJECTIVE, since the word is then everything between two fixed strings and two
  /// words cannot reach one name.
  ///
  /// A word whose tail looks like `_<digits>__` is the one shape this cannot carry — that is the
  /// alias mint's own tail, and a framed word ending in one would be reachable by a join as well.
  /// Where a mint is indexed the digits FUSE into the word (`__ig_ord0__`, never `__ig_ord_0__`).
  #[must_use]
  pub fn framed(&self, word: &str) -> String {
    format!("{}_{word}__", self.0)
  }

  /// [`framed`](Self::framed) as an identifier, for the fields and items an expansion writes.
  ///
  /// # It cannot be spanned here
  ///
  /// The call site sets the span, because a framework-minted name has no source to point at and the
  /// span a diagnostic wants is the DECLARATION's. Every caller today takes `Span::call_site`,
  /// which is what `format_ident!` gives.
  #[must_use]
  pub fn framed_ident(&self, word: &str) -> syn::Ident {
    format_ident!("{}", self.framed(word))
  }

  /// `__ig_<word>` — a name in the namespace but OUTSIDE the frame.
  ///
  /// The shape for a minted ITEM rather than a column: a marker const, a DDL object, an audit
  /// function. It wears no tail because there is nothing to keep injective — such a name already
  /// ends in a word this crate chose, and the frame is the COLUMN law rather than the namespace's.
  #[must_use]
  pub fn prefixed(&self, word: &str) -> String {
    format!("{}_{word}", self.0)
  }

  /// [`prefixed`](Self::prefixed) as an identifier, spanned at the call site for
  /// [`framed_ident`](Self::framed_ident)'s reason.
  #[must_use]
  pub fn prefixed_ident(&self, word: &str) -> syn::Ident {
    format_ident!("{}", self.prefixed(word))
  }

  /// Why this mark cannot be a namespace, or [`None`] where it can.
  ///
  /// # The rules are the MINT's, which is why they live beside it rather than in a front end
  ///
  /// A mark is spent in three shapes — a framed column, a prefixed item, and a clamped SQL
  /// alias — and what it must be is decided by what those spend it as. A second copy of these
  /// rules in whichever crate happens to read the configuration is the copy that drifts the day a
  /// mint's shape moves. What a front end adds is the SPAN: this answers in prose and knows
  /// nothing about tokens.
  ///
  /// The byte BUDGET is deliberately not here. It is a fact about the alias mint alone — how much
  /// of a table's own name survives PostgreSQL's sixty-three — and it depends on a depth this seat
  /// has never heard of; [`crate::alias::refused`] is where the pair is held together.
  #[must_use]
  pub fn refused(mark: &str) -> Option<String> {
    if mark.is_empty() {
      return Some(
        "an emission namespace names the mark every framework-minted name wears, and an empty one \
         names none — the minted names would begin with the declaration's own words, where a \
         column or an item the author declared collides with one the expansion invented and \
         neither party is holding a fence"
          .to_owned(),
      );
    }
    if !mark.starts_with(FRAMEWORK_LEAD) {
      return Some(format!(
        "`{mark}` does not begin `{FRAMEWORK_LEAD}` — a namespace is FENCED as well as minted in, \
         so every column and item 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 a framework's"
      ));
    }
    if let Some(stray) = mark
      .chars()
      .find(|char| !crate::alias::legal_in_prefix(*char))
    {
      return Some(format!(
        "`{mark}` holds `{stray}`, which a minted name cannot carry — the name is joined with `_`, \
         spelled as a Rust identifier 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 \
         an identifier"
      ));
    }
    None
  }
}

/// What every namespace leads with, framework's or platform's — and what a DECLARED
/// `<db>(alias(prefix = …))` is held to by [`crate::alias::refused`], which reads it from here.
///
/// The shape a reader already reads as *not the author's*, and the one rule that keeps two
/// frameworks' marks inside one reserved region instead of each confiscating a word of the
/// declaration's own vocabulary. ONE spelling, because the two seats fence the same region: a lead
/// the platform seat admitted and the alias word refused would be a namespace a model could hold
/// and no database could mint in.
pub(crate) const FRAMEWORK_LEAD: &str = "__";

#[cfg(test)]
mod tests;