ingraph-derive 0.1.0

The attribute and derive macros for ingraph: the words a record, node, key, filter and vocabulary declaration is written in.
Documentation
//! `alias(prefix = "__mine", depth = 16)` — the namespace a declaration's minted row-source names
//! live in, and how many of them there are.
//!
//! # It rides a DATABASE block, because that is where the emitted table lives
//!
//! `SqlQuery::ALIASES` is emitted once per `SqlQuery<Db>` impl, so a record stored in two databases
//! already carries two alias tables. Letting the two differ cost nothing that was not already there
//! — and the user story is per database as well: one deployment's schema holds legacy tables inside
//! the default namespace and the others do not, so the override belongs on that database alone.
//!
//! # The two knobs are independent, and neither is a rename of the other
//!
//! `prefix` is about COLLISION — a minted name and a real table share one namespace inside a
//! statement, and SQL resolves a reference to the innermost scope that has a match, so a real table
//! called `__ig_shot_1__` answers a nested query from the wrong row source and nothing refuses.
//! `depth` is about REACH: how far a relation predicate may nest before the lowering runs out of
//! names. A declaration may write either, both, or the block itself and neither — the last being a
//! refusal, since a block naming no knob has stated nothing and cannot have meant to.
//!
//! # The rules are `ingraph-codegen`'s, and the SPANS are this crate's
//!
//! What a prefix may be is a fact about what the mint spends it on, so `alias::refused` answers it
//! where the mint is. This module reports that answer at the token that wrote it, which is the one
//! thing the other crate has no access to.
//!
//! Part of the layer every `ingraph` derive parses on; `Record` and `Interface` are its consumers.

use ingraph_codegen::{prefix::EmissionPrefix, prelude::AliasOptions};
use quote::ToTokens as _;

use crate::{
  attribute::{self, set_once},
  errors::Errors,
  value,
};

/// Whether the block being read SIZES an alias table.
///
/// A record's does — `ALIASES` is emitted beside its row's address, and `depth` is that array's
/// length. An interface's does not: an interface owns no table, so its `alias(…)` moves the
/// SYNTHETIC WORDS a union statement projects and there is no array for a depth to be the length of.
/// Accepting the word there and reading nothing would be the accept-and-ignore this grammar refuses
/// everywhere else, so the word is refused BY THAT REASON.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Depth {
  /// `depth = N` is read, and is this declaration's alias table's length.
  Sized,
  /// `depth = N` has nothing here to be the length of. The string names the subject that owns no
  /// table, completing *… and `<subject>` owns no table to mint one for*.
  Unsized(&'static str),
}

impl Depth {
  /// What the block takes, which is one word shorter where it sizes nothing.
  const fn knobs(self) -> &'static str {
    match self {
      Self::Sized => "`prefix = \"…\"` and `depth = N`",
      Self::Unsized(_) => "`prefix = \"…\"`",
    }
  }

  /// The same two knobs as a near-miss reader compares against — the words [`Depth::knobs`] names
  /// and no others, so a suggestion here can never offer the word this block sizes nothing for.
  const fn words(self) -> &'static [&'static str] {
    match self {
      Self::Sized => &["prefix", "depth"],
      Self::Unsized(_) => &["prefix"],
    }
  }
}

/// Read one `alias(…)` block into `settled`, refusing a second and everything the block cannot hold.
///
/// `scope` is what a message calls the block's home — `` `sqlite(…)` `` — so a refusal reads as
/// being about the database it was written in rather than about aliases in the abstract.
pub(crate) fn block(
  option: &syn::meta::ParseNestedMeta<'_>,
  settled: &mut AliasOptions,
  seen: &mut Option<syn::Path>,
  scope: &str,
  sizes: Depth,
  errors: &mut Errors,
) -> syn::Result<()> {
  set_once(
    seen,
    option.path.clone(),
    &option.path,
    &format!("`alias(…)` is declared more than once in {scope} — one block, one namespace"),
    errors,
  );
  let mut prefix: Option<syn::LitStr> = None;
  let mut depth: Option<syn::LitInt> = None;
  let walked = attribute::options(option, |entry| {
    if entry.path.is_ident("prefix") {
      match value::literal(&entry, PREFIX_VALUE) {
        Ok(written) => set_once(
          &mut prefix,
          written,
          &entry.path,
          &format!("`prefix` is declared more than once in `alias(…)` in {scope} — one namespace"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    if entry.path.is_ident("depth") {
      if let Depth::Unsized(subject) = sizes {
        errors.push(attribute::unknown(
          &entry,
          &format!(
            "`depth` is the LENGTH of an alias table, and {subject} owns no table to mint one \
             for — what `alias(prefix = \"…\")` moves here are the words the statement INVENTS, \
             which are one name each rather than one per nesting level"
          ),
          // `depth` is a word this block KNOWS and refuses here for a reason, so it is spelled
          // correctly by definition.
          &[],
        ));
        return Ok(());
      }
      match value::integer(&entry, DEPTH_VALUE) {
        Ok(written) => set_once(
          &mut depth,
          written,
          &entry.path,
          &format!("`depth` is declared more than once in `alias(…)` in {scope} — one length"),
          errors,
        ),
        Err(e) => errors.push(e),
      }
      return Ok(());
    }
    errors.push(attribute::unknown(
      &entry,
      &format!(
        "unknown entry in `alias(…)` in {scope} — it takes {knobs} and nothing else",
        knobs = sizes.knobs(),
      ),
      sizes.words(),
    ));
    Ok(())
  });
  *settled = settle(&prefix, depth.as_ref(), option, scope, sizes, errors);
  walked
}

/// The refusal the namespace gets when it is not a string.
const PREFIX_VALUE: &str = "`prefix` must be the namespace every alias over this row is minted in, \
                            in a string literal";

/// The refusal the depth gets when it is not a number.
///
/// A bare integer rather than a string, unlike every other value in this grammar: the values written
/// as strings are the ones that are RUST — a path, a type, an identifier — and are re-parsed on the
/// way in. A length is a number in both languages and has nothing to be re-parsed from.
const DEPTH_VALUE: &str =
  "`depth` must be how many nesting depths this row's aliases are minted for, as a plain integer";

/// The refusal a depth past what a `usize` holds gets.
const TOO_DEEP: &str = "`depth` is past what any alias table could hold — the deepest entry's own \
                        digits have to fit inside the sixty-three bytes every shipped engine keeps \
                        of an identifier, beside the prefix and the table's own name";

/// The block's two knobs, checked against what the mint can actually spend.
///
/// A refused value is DROPPED rather than carried, which is the posture [`set_once`] already takes
/// for a repeat: the declaration is refused either way, and what the rest of the pass reads should
/// be one it can finish walking.
fn settle(
  prefix: &Option<syn::LitStr>,
  depth: Option<&syn::LitInt>,
  at: &syn::meta::ParseNestedMeta<'_>,
  scope: &str,
  sizes: Depth,
  errors: &mut Errors,
) -> AliasOptions {
  if prefix.is_none() && depth.is_none() {
    errors.push(syn::Error::new_spanned(
      at.path.to_token_stream(),
      format!(
        "`alias(…)` in {scope} names neither knob — it takes {knobs}, and a block that states \
         nothing leaves both at the framework's own answers, which is what omitting it already says",
        knobs = sizes.knobs(),
      ),
    ));
    return AliasOptions::default();
  }
  let minted = depth.and_then(|written| match written.base10_parse::<usize>() {
    Ok(depth) => Some(depth),
    // Whatever a `usize` cannot hold is past every ceiling this rule has, so the budget rule's own
    // sentence is the honest one — reached here rather than through the arithmetic on the way to it.
    Err(_) => {
      errors.push(syn::Error::new_spanned(written, TOO_DEEP));
      None
    }
  });
  let settled = AliasOptions {
    prefix: prefix.as_ref().map(syn::LitStr::value),
    depth: minted,
  };
  let Some(why) = ingraph_codegen::alias::refused(
    settled.prefix_in(&EmissionPrefix::default()),
    settled.depth(),
  ) else {
    return settled;
  };
  // Spanned at the PREFIX wherever one was written, because it is the half a declaration can
  // shorten: every rule here that crosses both knobs is one the prefix spends the budget of.
  match (prefix, depth) {
    (Some(written), _) => errors.push(syn::Error::new_spanned(written, why)),
    (None, Some(written)) => errors.push(syn::Error::new_spanned(written, why)),
    (None, None) => errors.push(syn::Error::new_spanned(at.path.to_token_stream(), why)),
  }
  AliasOptions::default()
}

/// The alias namespaces a declaration's own table and column names are held out of.
///
/// # A UNION, because a field is the domain's and a prefix is one database's
///
/// A record's fields are declared once and stored in every database it names, so a column name has
/// to stay clear of every namespace ANY of those databases mints in — a record with
/// `sqlite(alias(prefix = "__mine"))` beside a defaulting `postgres` refuses a field starting
/// `__mine` and one starting `__ig` alike, because one of its two tables would collide either way.
///
/// # The DEFAULT joins the union only where something still defaults
///
/// A declaration that overrode the prefix on every database it names has handed `__ig*` back to its
/// author: no statement over it mints a name there any more, so refusing one would be reserving a
/// namespace nobody is using. That is the whole reason [`AliasOptions::prefix`] is an `Option` in
/// the model — a shape that had already collapsed *absent* into *the default* could not tell the two
/// apart.
pub(crate) struct Fence {
  /// Every namespace held, in the order a message would name them: the declared ones as written,
  /// then the default where it is still in play.
  prefixes: Vec<String>,
}

impl Default for Fence {
  /// The framework's own namespace and nothing else — what a declaration with no database blocks at
  /// all is held to, an entity's fields included. An entity does not know which record flattens it,
  /// so the conservative answer is the only available one and it is also the right one.
  ///
  /// It reads the SEAT rather than the constant, and that is the law rather than a preference: a
  /// namespace is minted in and refused in by the same party, so a fence spelling `__ig` while its
  /// front end minted `__mg` would hand the minted namespace back to the author it was reserved
  /// against. `ingraph-derive` is `ingraph`'s front end, so the seat it reads is the default —
  /// a domain framework's own derive holds its own, through the same accessor.
  fn default() -> Self {
    Self {
      prefixes: vec![EmissionPrefix::default().mark().to_owned()],
    }
  }
}

impl Fence {
  /// The union over one declaration's databases, each contributing its own prefix or nothing.
  pub(crate) fn over<'a>(declared: impl IntoIterator<Item = Option<&'a str>>) -> Self {
    let mut prefixes: Vec<String> = Vec::new();
    let mut defaults = false;
    for prefix in declared {
      match prefix {
        Some(prefix) if !prefixes.iter().any(|held| held == prefix) => {
          prefixes.push(prefix.to_owned());
        }
        Some(_) => {}
        None => defaults = true,
      }
    }
    // A declaration with no databases at all defaults too — it stores nothing, and a name it could
    // not have collided with is still a name the next database it names would.
    if defaults || prefixes.is_empty() {
      prefixes.push(EmissionPrefix::default().mark().to_owned());
    }
    Self { prefixes }
  }

  /// The namespace `name` falls inside, or [`None`] where it falls inside none of them.
  pub(crate) fn caught(&self, name: &str) -> Option<&str> {
    self
      .prefixes
      .iter()
      .find(|prefix| name.starts_with(prefix.as_str()))
      .map(String::as_str)
  }
}