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
//! Reading an entry's `= "…"` value as the thing it names.
//!
//! Every typed option in this grammar is written as a STRING and re-parsed: `crate = "a::b"` into a
//! [`syn::Path`], `rename = "Name"` into a [`syn::Ident`]. Going through a literal is what keeps a
//! raw identifier spellable, and re-parsing is what makes a value that cannot BE the thing a
//! refusal here rather than a failure somewhere downstream in an expansion.
//!
//! The two were separate functions before this layer existed. They differ only in the type asked
//! for and the sentence used when the answer is no.
//!
//! Part of the layer every `ingraph` derive parses on; `Record` is its first consumer.

/// An entry's `= "…"` value, as the string literal itself.
///
/// For the values that are NOT Rust: a column name, a table name, a schema. Those reach a
/// `CREATE TABLE` verbatim rather than through an ident, so there is nothing here to re-parse —
/// whether a store can HOLD the name is a separate question, answered by `column` once the value has
/// been read. The LITERAL rather than its contents, because it carries the span a refusal about the
/// name reports at.
///
/// # Errors
/// `refusal`, spanned at whatever could not be read — a missing value, or a non-string.
pub(crate) fn literal(
  meta: &syn::meta::ParseNestedMeta<'_>,
  refusal: &str,
) -> syn::Result<syn::LitStr> {
  meta
    .value()
    .and_then(|value| value.parse::<syn::LitStr>())
    .map_err(|e| syn::Error::new(e.span(), refusal))
}

/// An entry's `= "…"` value, taken as a string literal and re-parsed as `T`.
///
/// # Errors
/// `refusal`, spanned at whatever could not be read — a missing value, a non-string, or a string
/// that is not a `T`.
pub(crate) fn parse_literal<T: syn::parse::Parse>(
  meta: &syn::meta::ParseNestedMeta<'_>,
  refusal: &str,
) -> syn::Result<T> {
  literal(meta, refusal)?
    .parse::<T>()
    .map_err(|e| syn::Error::new(e.span(), refusal))
}

/// A string literal read as the RUST FIELD NAME it holds, tolerating a name rustc reserves.
///
/// # A field legally called `r#type` has to be nameable
///
/// The string-kind schema-words law says a Rust KEYWORD is an ordinary schema name — that is why a
/// column's `rename` is carried as a literal and never parsed. This is the other side of the same
/// law: the positions that name a field of somebody's struct must be able to name a field that IS
/// a keyword, and [`parse_literal`] cannot, because `syn`'s `Ident` parser refuses `type` exactly
/// as rustc's grammar does.
///
/// So BOTH spellings are the field. `"type"` is the word an author reaches for, because it is what
/// the schema and the database call the column; `"r#type"` is what the declaring struct had to
/// write to name it in Rust. Neither is a different field from the other, and both are read as the
/// RAW identifier — which is what the emission has to spell, `type` being unwritable bare.
///
/// The FENCE is unchanged: what is not an identifier under either spelling is still refused, with
/// the caller's own sentence and at the literal's own span.
///
/// It takes the LITERAL rather than the entry, unlike [`parse_literal`]: the positions that read a
/// field name read the string first, because a value that is not a string at all earns the
/// position's own shape sentence before this reader is asked anything.
///
/// # Errors
/// `refusal`, spanned at the literal, when it names no field under either spelling.
pub(crate) fn named_field(written: &syn::LitStr, refusal: &str) -> syn::Result<syn::Ident> {
  if let Ok(plain) = written.parse::<syn::Ident>() {
    return Ok(plain);
  }
  // The escaped form, and it is built rather than accepted: `Ident::parse_any` over `r#<word>` is
  // what tells a keyword from a word no identifier could be, and it PANICS for the handful rustc
  // forbids an escape for (`crate`, `self`, `Self`, `super`, `_`) — so the parse is the check, and
  // its answer is the ident.
  let value = written.value();
  let bare = value.strip_prefix("r#").unwrap_or(&value);
  let mut escaped = syn::parse::Parser::parse_str(
    <syn::Ident as syn::ext::IdentExt>::parse_any,
    &format!("r#{bare}"),
  )
  .map_err(|_| syn::Error::new(written.span(), refusal))?;
  escaped.set_span(written.span());
  Ok(escaped)
}

/// An entry's `= "…"` value, or the `= ["…", "…"]` list of them, as the string literals themselves.
///
/// The ONE-OR-SEVERAL shape, for a word whose subject is a list that is usually one long: `emits =
/// "…"` and `emits = ["…", "…"]` are the same declaration at two arities, and a grammar that made
/// the singular spell a one-element list would be asking most declarations to write punctuation for
/// a plural they do not have.
///
/// The literals rather than their contents, for [`literal`]'s reason — and per ELEMENT, so a list
/// whose third entry is unreadable refuses at the third entry.
///
/// # Errors
/// `refusal`, spanned at whatever could not be read — a missing value, a non-string, or a list
/// element that is not a string.
pub(crate) fn literals(
  meta: &syn::meta::ParseNestedMeta<'_>,
  refusal: &str,
) -> syn::Result<Vec<syn::LitStr>> {
  let value = meta
    .value()
    .map_err(|e| syn::Error::new(e.span(), refusal))?;
  if !value.peek(syn::token::Bracket) {
    return value
      .parse::<syn::LitStr>()
      .map(|one| vec![one])
      .map_err(|e| syn::Error::new(e.span(), refusal));
  }
  let array = value
    .parse::<syn::ExprArray>()
    .map_err(|e| syn::Error::new(e.span(), refusal))?;
  array
    .elems
    .into_iter()
    .map(|element| match element {
      syn::Expr::Lit(syn::ExprLit {
        lit: syn::Lit::Str(text),
        ..
      }) => Ok(text),
      other => Err(syn::Error::new_spanned(other, refusal)),
    })
    .collect()
}

/// An entry's `= N` value, as the integer literal itself.
///
/// The one value in this grammar written BARE, and the rule above is why rather than an exception to
/// it: what the strings buy is a raw identifier and a re-parse into Rust, and a COUNT is neither —
/// `depth = "16"` would be a number spelled as text so that it could be turned back into a number.
/// The literal rather than its value, because it carries the span a refusal about the count reports
/// at and because how wide a count may be is the caller's question.
///
/// # Errors
/// `refusal`, spanned at whatever could not be read — a missing value, or a non-integer.
pub(crate) fn integer(
  meta: &syn::meta::ParseNestedMeta<'_>,
  refusal: &str,
) -> syn::Result<syn::LitInt> {
  meta
    .value()
    .and_then(|value| value.parse::<syn::LitInt>())
    .map_err(|e| syn::Error::new(e.span(), refusal))
}

/// An entry's `= 1.0` value, as the decimal literal itself.
///
/// BARE for [`integer`]'s reason, and a DECIMAL rather than a count because what it reads is a
/// RATIO — a coefficient in a fold, not a number of rows. `1` is refused with the position's own
/// sentence rather than widened into `1.0`: two spellings of one value would be two shapes every
/// later reader has to remember, and the correction is one keystroke.
///
/// A NEGATIVE one IS read, and that is measured rather than assumed: syn parses a leading minus as
/// part of the literal in value position, so `-1.0` arrives here as a `LitFloat` whose
/// `base10_parse` answers `-1.0`. Whether a negative is legal is therefore the caller's rule and
/// never this reader's silence.
///
/// The literal rather than its value, because it carries the span a refusal about the ratio reports
/// at, and because WHICH ratios are legal is the caller's question.
///
/// # Errors
/// `refusal`, spanned at whatever could not be read — a missing value, or one that is not a decimal
/// literal.
pub(crate) fn float(
  meta: &syn::meta::ParseNestedMeta<'_>,
  refusal: &str,
) -> syn::Result<syn::LitFloat> {
  meta
    .value()
    .and_then(|value| value.parse::<syn::LitFloat>())
    .map_err(|e| syn::Error::new(e.span(), refusal))
}

/// An entry's `= true` / `= false` value, as the boolean literal itself.
///
/// BARE for [`integer`]'s reason, one type over: what a string literal buys is a raw identifier and
/// a re-parse into Rust, and a FLAG is neither — `rrf = "false"` would be a boolean spelled as text
/// so that it could be turned back into a boolean, and a typo in it would be a string nobody checks.
///
/// The literal rather than its value, because it carries the span a refusal about the flag reports
/// at.
///
/// # Errors
/// `refusal`, spanned at whatever could not be read — a missing value, or a non-boolean.
pub(crate) fn boolean(
  meta: &syn::meta::ParseNestedMeta<'_>,
  refusal: &str,
) -> syn::Result<syn::LitBool> {
  meta
    .value()
    .and_then(|value| value.parse::<syn::LitBool>())
    .map_err(|e| syn::Error::new(e.span(), refusal))
}