ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! HOW an artifact family's addresses END — the `extension` word's six forms, as a model.
//!
//! A blob's address is `<slot>/<seg1>/…/<segN>[.<ext>]`, and the suffix is the one part of it that
//! does not come from the key. It exists for browsability — a human opening the store's directory
//! sees `12.png` rather than `12` — and for the hosts that read a type off a name.
//!
//! # Six forms, four keys, and why the count is what it is
//!
//! ```text
//! extension = "png"                                          static
//! (omitted)                                                  extensionless
//! extension(from = "format", any_of = ["png", "jpg"])        a String column, output-fenced
//! extension(from(field = "format", type = "app::Format"))    an enum column, full set
//! extension(from(…), variants = ["app::Format::Png", …])     an enum column, a subset
//! extension(from(…), with = "app::suffix_of")                the author's own render
//! ```
//!
//! Two spellings were REFUSED in the design and are refused by the parser: a bare array
//! (`extension = ["png", "jpg"]`) cannot answer *which one is entry 42*, so a family with several
//! suffixes has to say what decides; and the parenthesized single value (`extension("png")`) is a
//! single fact, which this grammar writes as a key-value everywhere else.
//!
//! # The two fences point in opposite directions, which is why there are two words
//!
//! [`variants`](ColumnExtension::variants) is an INPUT fence — WHICH values of the column are
//! admitted — and only the enum road has one, a subset of a type's variants being the only input set
//! this grammar can name. [`any_of`](ColumnExtension::any_of) is an OUTPUT fence — which SUFFIXES may
//! be produced — and it is REQUIRED on the string road, where nothing else bounds what a column
//! holds. On the enum road the full variant set already fences the input by construction, so
//! `any_of` there is an extra promise about the rendering rather than the only one there is.
//!
//! Both compose with [`with`](ColumnExtension::with), which is the whole reason they are separate
//! words: a hook takes the column value (fenced by `variants`) and returns a suffix (fenced by
//! `any_of`).
//!
//! # The column is the ENTITY's, and it is a PURE INPUT
//!
//! `from` names a column the locate-field resolver already holds hydrated — `self` — so a dynamic
//! suffix costs no round trip and the zero-I/O pin on `locate` survives intact. What it does NOT
//! survive on its own is the WRITE side: the lane renders the stored name from
//! `upstream(…, extension = "<upstream field>")`, and the framework cannot prove at read time that the
//! two are the same source. That seam is documented law with three mitigations, one of which — a
//! framework-written materialization that is same-source by construction — is reserved and not built.

use crate::model::NodeKind;

/// WHICH column an artifact family reads its suffix out of, and how the column's type is known.
///
/// The type is EXPLICIT on the enum road and absent on the string road, and that asymmetry is the
/// key-即-意图 rule rather than an inference the emitter declined to write: `from = "…"` MEANS a
/// string column, `from(…)` means a column whose type is named. Reading a label tree to guess which
/// one an author meant would make the same two spellings mean different things in different
/// declarations.
#[derive(Debug, Clone)]
pub enum ExtensionSource {
  /// `from = "format"` — the entity's own STRING column, rendered as the suffix directly.
  Text {
    /// The column, as a Rust field name.
    field: syn::Ident,
  },
  /// `from(field = "format", type = "app::media::ImageFormat")` — an ENUM column, its type named.
  ///
  /// The suffix is the variant's storage textual form, so the full variant set fences the output by
  /// construction and the type path is what a `variants` list is prefix-checked against.
  Enumerated {
    /// The column, as a Rust field name.
    field: syn::Ident,
    /// The column's type, VERBATIM — resolved nowhere in this crate, emitted and resolved by rustc
    /// at the span its author wrote.
    ty: syn::Path,
  },
}

impl ExtensionSource {
  /// The column both roads name.
  #[must_use]
  pub const fn field(&self) -> &syn::Ident {
    match self {
      Self::Text { field } | Self::Enumerated { field, .. } => field,
    }
  }

  /// The enum type, where the road has one.
  #[must_use]
  pub const fn enumerated(&self) -> Option<&syn::Path> {
    match self {
      Self::Text { .. } => None,
      Self::Enumerated { ty, .. } => Some(ty),
    }
  }
}

/// A suffix decided PER ENTRY — the block form, in all four of its shapes.
#[derive(Debug, Clone)]
pub struct ColumnExtension {
  /// The column the suffix is decided by, and which road it is on.
  pub source: ExtensionSource,
  /// `variants = ["app::Format::Png", …]` — the INPUT fence, as FULL PATHS in string literals.
  ///
  /// Full paths for the campaign's standing refer-quoting convention, and they buy a check nothing
  /// else could make: the expansion prefix-checks each against `from`'s type, and rustc then verifies
  /// the variant EXISTS by resolving an emitted reference to it — so a misspelled variant is a
  /// compile error at the string that named it rather than a value silently outside the fence.
  ///
  /// EMPTY where the word was not written, which on the enum road means the FULL set.
  pub variants: Vec<syn::LitStr>,
  /// `any_of = ["png", "jpg"]` — the OUTPUT fence, as suffix strings.
  ///
  /// REQUIRED on the string road and optional on the enum road, for the reason the module note
  /// gives. Empty means the word was not written.
  pub any_of: Vec<syn::LitStr>,
  /// `with = "app::suffix_of"` — the author's own render, `fn(&ColType) -> suffix`.
  ///
  /// The COLUMN VALUE and not the row, which is what makes ONE function serve both sides: the write
  /// lane has the upstream field and the read resolver has the entity's column, and a hook over the
  /// value is spendable from either. A hook over the row would need two different rows and would be
  /// two functions pretending to be one.
  pub with: Option<syn::Path>,
}

/// HOW this artifact family's addresses end.
///
/// [`Option<Extension>`] is the whole vocabulary: `None` is the omitted form — extensionless
/// storage, the zero-tax road a heterogeneous family takes, where a per-entry type travels as
/// metadata or as the host channel's `Content-Type` instead.
#[derive(Debug, Clone)]
pub enum Extension {
  /// `extension = "png"` — ONE suffix for the whole family, known at the type.
  ///
  /// The only form a by-key `get` can resolve on its own, which is why it is also the only one the
  /// shipped `BlobRecord::extension()` seat can carry: that seat is TYPE-LEVEL, deliberately, because
  /// a read by key has no record instance to ask.
  Static(syn::LitStr),
  /// The block form — a suffix decided per entry, off a column.
  Column(ColumnExtension),
}

impl Extension {
  /// The static suffix, where this family has one.
  #[must_use]
  pub const fn statik(&self) -> Option<&syn::LitStr> {
    match self {
      Self::Static(suffix) => Some(suffix),
      Self::Column(_) => None,
    }
  }

  /// The column form, where this family takes one.
  #[must_use]
  pub const fn column(&self) -> Option<&ColumnExtension> {
    match self {
      Self::Static(_) => None,
      Self::Column(column) => Some(column),
    }
  }
}

/// Whether `suffix` can be the tail of an address at all.
///
/// # A FLOOR rather than a charset, and the difference is deliberate
///
/// What this refuses is what no host can hold: the empty string, a path separator of either family,
/// a NUL, and the two directory names `.` and `..`. Each of those makes the ADDRESS malformed rather
/// than merely ugly — a separator invents a directory level the key never declared, and `..` invents
/// one above the store's own root.
///
/// It does NOT impose the filesystem backend's verbatim charset. That charset decides which
/// rendering a KEY SEGMENT gets — verbatim or escaped — and a segment is never refused for failing
/// it. A suffix has no escape hatch, so a charset here would be a refusal rather than a routing, and
/// which characters an artifact family may end its names with is a question every backend answers
/// differently (an object store's key alphabet is not a filesystem's). The narrow question is
/// settled; the wide one waits for a ruling.
#[must_use]
pub fn admissible_suffix(suffix: &str) -> bool {
  !suffix.is_empty() && suffix != "." && suffix != ".." && !suffix.contains(['/', '\\', '\0'])
}

/// The word itself, spelled once.
pub const EXTENSION: &str = "extension";

/// What an author who wrote `extension` on the wrong kind is told.
#[must_use]
pub fn wrong_kind(kind: NodeKind) -> String {
  format!(
    "`extension` is an ARTIFACT FAMILY's word and {article} {noun} has no addresses to end — a \
     suffix is the tail of a stored object's name, and this declaration's documents are held by an \
     engine that names its own entries",
    article = kind.article(),
    noun = kind.noun(),
  )
}