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
//! What an emitted table or column may be called.
//!
//! A name here reaches a `CREATE TABLE`, so the rules about one belong to whatever is emitted rather
//! than to any one derive. Two live here, and between them they are the whole of what a declared
//! name is held to: the framework's own COLUMN namespace, and the ALIAS namespace its rendered
//! statements mint row-source names in. The second is no longer one string — a declaration moves it
//! per database — so what arrives here is [`alias::Fence`], and what stays here is the rule about
//! NAMES that reads it.
//!
//! A third rule joins them and is not about a name at all: which PROJECTION word a field
//! declared. It lives here because it is the same rule for every declaration that has columns — a
//! node's and a value's alike — and one reader is what keeps two grammars from answering it twice.
//!
//! Part of the layer every `ingraph` derive parses on; `Record` is its first consumer.

use ingraph_codegen::prelude::Projection;

use crate::{alias, attribute, errors::Errors};

/// The namespace the framework reserves for its own columns: a name with `__` at BOTH ends.
///
/// Every column the framework adds to a table is named `__something__`, so a user column may not
/// take that shape. A collision would render into a `CREATE TABLE` beside the framework column of
/// the same name, and the DIALECT would refuse it: "duplicate column name" from SQLite, `42701`
/// from Postgres, neither naming the record that caused it.
///
/// Both ends rather than a bare prefix, because it reserves strictly less: `__internal` stays a
/// legal column, `__internal__` does not. What it keeps is the property that matters — a framework
/// column added later can never collide with a schema someone has already written.
///
/// A NAMESPACE rather than a list is what makes this checkable in this crate at all. The list it
/// replaces had to be copied out of `ingraph` — which this crate cannot depend on, since the
/// dependency runs the other way — and two copies of a reserved list is how one of them drifts.
/// Nothing is left to keep in sync: the rule is one shape, and the framework owns everything
/// inside it.
const FRAMEWORK_FENCE: &str = "__";

/// Which reservation a name falls inside, or `None` where it is free to be declared.
///
/// ONE answer rather than two independent checks, because the two namespaces OVERLAP — every alias
/// the framework mints ends `__` as well as beginning its prefix — and a name inside both is one
/// mistake that should be reported once. The framework's own namespace is tested first, so a name in
/// both reports under the older and more specific rule.
///
/// # Why an alias needs a fence of its own, given [`FRAMEWORK_FENCE`]
///
/// A collision in the alias half is not the loud one above describes. An alias 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 table named as an alias is named produces no error at any layer: the statement
/// is well-formed, the planner resolves every reference, and the rows come back from the wrong row
/// source. There is no `CREATE TABLE` to be refused at, because nothing is being created.
///
/// # A bare PREFIX, which is what the other fence deliberately is not
///
/// The reservation is wider than the aliases minted today — every one of those ends `__` and would
/// already be caught above — and the width is the point rather than an oversight: what the fence has
/// to hold is the whole family the mint may grow into, and a rule stated over the members would need
/// restating each time the mint's shape moves. The cost is real and small: `__ignore` stops being a
/// legal name wherever `__ig` is still in play.
///
/// WHICH prefixes are in play is [`alias::Fence`]'s answer rather than a constant here, because a
/// declaration moves them: see that type for why the union is the right one and why the default
/// leaves it when nothing defaults.
fn reserved(fence: &alias::Fence, name: &str) -> Option<String> {
  if name.starts_with(FRAMEWORK_FENCE) && name.ends_with(FRAMEWORK_FENCE) {
    // `__` and `___` are inside it too: both ends are satisfied over an empty or degenerate middle.
    // Nobody names a column that, and letting them through would leave a hole in the fence.
    return Some(
      "a name with `__` at both ends is reserved, because the framework's own columns take that \
       shape and a collision would be refused by the dialect at `CREATE TABLE`"
        .to_owned(),
    );
  }
  fence.caught(name).map(|prefix| {
    format!(
      "names beginning `{prefix}` are its ALIAS half, the row-source names a rendered statement \
       mints, and a real name in that half does not collide loudly: SQL resolves the reference to \
       the inner scope, and the statement answers from the wrong row source"
    )
  })
}

/// Refuse a column whose EFFECTIVE name — the field's own, or whatever renamed it — falls inside
/// either namespace.
///
/// Effective, because a rename walks straight past a check on the field's Rust name, and it is the
/// emitted name that reaches the `CREATE TABLE`.
pub(crate) fn refuse_framework_namespace(
  fence: &alias::Fence,
  name: &syn::Ident,
  errors: &mut Errors,
) {
  refuse_framework_name(fence, &name.to_string(), name, errors);
}

/// The same rule for a column whose name is not a Rust identifier at all.
///
/// A `persist` column's name is a STRING — `bitRate` names a column and no field — so the check takes
/// the name and the token to report at separately. `at` is whatever declared the name: the field, or
/// the string literal that renamed it.
pub(crate) fn refuse_framework_name(
  fence: &alias::Fence,
  name: &str,
  at: impl quote::ToTokens,
  errors: &mut Errors,
) {
  refuse_reserved(fence, "column", name, at, errors);
}

/// The same rule over a declared TABLE name.
///
/// Tables are checked because that is the namespace an ALIAS actually lands in: the column fence
/// predates the mint and reaches the wrong nouns on its own.
pub(crate) fn refuse_reserved_table(
  fence: &alias::Fence,
  name: &str,
  at: impl quote::ToTokens,
  errors: &mut Errors,
) {
  refuse_reserved(fence, "table", name, at, errors);
}

/// One refusal for both subjects, so the two nouns cannot drift into two rules.
fn refuse_reserved(
  fence: &alias::Fence,
  subject: &str,
  name: &str,
  at: impl quote::ToTokens,
  errors: &mut Errors,
) {
  if let Some(why) = reserved(fence, name) {
    errors.push(syn::Error::new_spanned(
      at,
      format!("{subject} `{name}` is inside the framework's namespace — {why}"),
    ));
  }
}

/// The three PROJECTION words, in the order a refusal names a pair.
///
/// Public to the crate because it is a POSITION's vocabulary as well as this walk's table: a field
/// of a kind that elects nothing takes these three and nothing else, and its near-miss line is read
/// off the same list rather than off a copy of it.
pub(crate) const PROJECTIONS: [&str; 3] = ["copy", "repeated", "optional"];

/// What a tier did with a field marker this walk does not own.
///
/// The walk used to be told only how to REFUSE the rest, which was enough while the projection words
/// were the whole of a field's grammar. They are not: an index's field wears its ROLE — `knn`,
/// `searchable` — and the engine blocks that name where that field is written are the next round's,
/// on the same field, in the same attribute. So the seam is a three-state answer rather than an
/// error: a tier may CLAIM an entry, and the walk stays the one place the projection words and the
/// declared-twice rule are read.
pub(crate) enum Claim {
  /// The tier READ it. The entry and whatever it carried are the tier's own, already consumed —
  /// which is why the walk does not swallow it a second time.
  Taken,
  /// The tier refused it, in the sentence its own grammar carries.
  Refused(syn::Error),
}

/// A field's whole marker list read for the projection words, with every OTHER word handed to the
/// caller.
///
/// The two grammars that have columns and no rows — the value tier's and a derived index's — admit
/// exactly these three plus whatever their own tier claims, and what differs between them is the
/// SENTENCE each refusal carries and WHICH words each tier reads. So the walk lives here and both
/// stay with their tiers: `otherwise` is handed the entry and answers with a [`Claim`], and a
/// refusal's entry is swallowed HERE rather than at each caller, which is the step a second copy of
/// this loop would eventually forget.
///
/// The "declared twice" rule is part of the walk for the same reason [`projection`] below is shared:
/// one marker says one thing about one field whichever tier declared it. A CLAIMED word's own
/// duplicate rule is the claiming tier's, because only that tier knows what a second one would mean.
///
/// The accumulator is handed to `otherwise` rather than kept for its return value alone: a claimed
/// word may be a BLOCK — `knn(semantics(fold(sum)))` — and a block reports one refusal per entry in
/// it,
/// which a single returned error cannot carry.
pub(crate) fn projection_markers(
  attrs: &[syn::Attribute],
  field: &syn::Ident,
  errors: &mut Errors,
  mut otherwise: impl FnMut(&syn::meta::ParseNestedMeta<'_>, &mut Errors) -> Claim,
) -> Projection {
  let mut declared: Vec<(&'static str, syn::Path)> = Vec::new();
  attribute::walk(attrs, errors, |meta, errors| {
    if let Some(word) = PROJECTIONS
      .into_iter()
      .find(|word| meta.path.is_ident(word))
    {
      if declared.iter().any(|(seen, _)| *seen == word) {
        errors.push(syn::Error::new_spanned(
          &meta.path,
          format!("`{word}` is declared more than once on `{field}` — one marker, one field"),
        ));
      } else {
        declared.push((word, meta.path.clone()));
      }
      return Ok(());
    }
    if let Claim::Refused(refusal) = otherwise(&meta, errors) {
      errors.push(refusal);
      attribute::skip_entry(&meta);
    }
    Ok(())
  });
  let declared: Vec<(&'static str, &syn::Path)> =
    declared.iter().map(|(word, at)| (*word, at)).collect();
  projection(&declared, field, errors)
}

/// Which of the three PROJECTION words a field declared, and the refusal when it declared two.
///
/// Shared because two grammars ask it — a node's fields and an entity's — and the sentence is the
/// same sentence: the words name three different ways to hand a column out, and a column has one.
/// Two readers of one rule is how the two answers drift.
///
/// `declared` is the words found, IN THE VOCABULARY'S OWN ORDER, so the pair a refusal names is
/// stable rather than dependent on which attribute the author wrote first.
pub(crate) fn projection(
  declared: &[(&'static str, &syn::Path)],
  field: &syn::Ident,
  errors: &mut Errors,
) -> Projection {
  if let [(first, _), (second, at), ..] = declared {
    errors.push(syn::Error::new_spanned(
      at,
      format!(
        "`{first}` and `{second}` are both declared on `{field}`, and each names a different way \
         to hand the column out — a column has one. `repeated` and `optional` are two \
         projections; `copy` hands the column back by value, which is what neither is for."
      ),
    ));
  }
  match declared.first() {
    Some(("copy", _)) => Projection::Copied,
    Some(("repeated", _)) => Projection::Repeated,
    Some(("optional", _)) => Projection::Optional,
    _ => Projection::Borrowed,
  }
}