ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! A name with two faces: the one a database sees and the one Rust can spell.
//!
//! A column is declared once and used twice — as the string in a `CREATE TABLE`, a `try_get`, a
//! `#[serde(rename = "…")]` and an error message, and as the IDENT of the field that carries it in
//! an emitted row. Those two are not always the same string: `type` and `bit-rate` are ordinary
//! column names and neither is a legal field name.
//!
//! Keeping them in ONE value is what stops them drifting. A pair of strings passed around
//! separately gets swapped eventually — and the failure is silent, because a mangled name still
//! compiles and a column called `bit_rate` still exists somewhere. Here the choice is made by the
//! trait a use site reaches for: quoting a name into an expansion yields the Rust face, and
//! formatting it yields the external one.
//!
//! Borrowed from `polarsync-codegen`'s `RustSafeName`, which carries the same two faces for the
//! same reason.

use core::fmt;

use heck::ToSnakeCase as _;
use quote::{ToTokens, format_ident};

/// The keywords a field cannot be named. Reserved ones are here too: `become` and `gen` are not
/// usable as identifiers in this edition either, and a list that only tracked what is currently
/// STRICT would let an emission break on an edition bump.
///
/// `union`, `macro_rules`, `raw` and `safe` are deliberately absent — they are contextual, and
/// `let union = 1;` compiles.
const KEYWORDS: &[&str] = &[
  "Self", "abstract", "as", "async", "await", "become", "box", "break", "const", "continue",
  "crate", "do", "dyn", "else", "enum", "extern", "false", "final", "fn", "for", "gen", "if",
  "impl", "in", "let", "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub",
  "ref", "return", "self", "static", "struct", "super", "trait", "true", "try", "type", "typeof",
  "unsafe", "unsized", "use", "virtual", "where", "while", "yield",
];

/// A name as the database spells it, together with the identifier Rust can spell it as.
///
/// The EXTERNAL name is never rewritten: it is what reaches a `CREATE TABLE`, a `SELECT`, and the
/// `rename` attribute an emitted row carries — so a declaration that says `rename = "bit-rate"`
/// gets a column called `bit-rate`, whatever the field holding it has to be called.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RustSafeName {
  /// The identifier an expansion may use — the external name, mangled only as far as it must be.
  safe: syn::Ident,
  /// The name as declared. Verbatim, always.
  external: String,
}

impl RustSafeName {
  /// A name from whatever a declaration wrote, mangled into an identifier as needed.
  ///
  /// `span` is the token the name was declared at, so an emitted field points back at the
  /// declaration and a refusal about it reports there.
  ///
  /// That it is CARRIED is pinned by `ingraph-derive`'s `tests/span_pins.rs`, at the column of a
  /// real compiler's caret. A span is observable nowhere else: proc-macro2 holds every location
  /// behind its `span-locations` feature, and without it `Debug` renders the constant `Span` — so a
  /// unit test comparing two renderings holds for any emitter at all, which is exactly what the
  /// assertion that used to sit in `tests.rs` beside this one did.
  pub fn new(external: impl Into<String>, span: proc_macro2::Span) -> Self {
    let external = external.into();
    let mut safe = mangle(&external);
    safe.set_span(span);
    Self { safe, external }
  }

  /// A name from a record's own FIELD, which is already an identifier.
  ///
  /// The external face drops a raw prefix: `r#type` is how Rust spells a field called `type`, and
  /// `type` is what the column is called.
  pub fn from_ident(ident: &syn::Ident) -> Self {
    let spelled = ident.to_string();
    Self {
      external: spelled
        .strip_prefix("r#")
        .map_or(spelled.clone(), ToOwned::to_owned),
      safe: ident.clone(),
    }
  }

  /// The identifier an expansion uses. Also reachable by quoting the name.
  pub const fn safe(&self) -> &syn::Ident {
    &self.safe
  }

  /// The name the database sees. Also reachable by formatting the name.
  pub fn external(&self) -> &str {
    &self.external
  }
}

/// The external name as an identifier, by the smallest change that makes it one.
///
/// - The name is normalised to SNAKE CASE: `bitRate` becomes `bit_rate`, `HTTPServer` becomes
///   `http_server`. The Rust face is idiomatic Rust, not merely legal Rust.
/// - `-`, and every other character an identifier cannot carry, becomes `_`.
/// - A leading digit gains a `_`.
/// - A KEYWORD gains a trailing `_`.
/// - `_` alone is the wildcard pattern rather than an identifier, so it gains a second one.
///
/// The keyword rule is a trailing underscore rather than a raw identifier because `r#` cannot
/// express four of them: `r#crate`, `r#self`, `r#super` and `r#Self` are all rejected by the
/// compiler. One rule that covers every keyword beats two rules with an exception list.
///
/// The kept set is ASCII, which is narrower than what an identifier may hold. That is on purpose
/// and it is about not PANICKING: `char::is_alphanumeric` accepts `²` — a number by Unicode's
/// reckoning and not an identifier character by the compiler's — so a rule written that way builds
/// a string [`syn::Ident`] rejects, and a proc macro that panics reports nothing a reader can act
/// on. A non-ASCII external name keeps its own spelling; only the field carrying it is folded.
fn mangle(external: &str) -> syn::Ident {
  // Case FIRST, because the Rust face has to be idiomatic Rust and not merely legal Rust. A wire
  // field called `bitRate` is a perfectly valid identifier, so a rule that only asked "does this
  // parse" would emit it and hand every consumer a `non_snake_case` warning about generated code
  // they cannot edit. The lint is telling the truth, and an `#[allow]` would only hide it.
  //
  // `heck` also does the word splitting the character map below would otherwise have to guess at:
  // `HTTPServer` becomes `http_server` rather than `h_t_t_p_server`.
  let mut safe: String = external
    .to_snake_case()
    .chars()
    .map(|c| {
      if c.is_ascii_alphanumeric() || c == '_' {
        c
      } else {
        '_'
      }
    })
    .collect();
  if safe.is_empty() || safe.starts_with(|c: char| c.is_ascii_digit()) {
    safe.insert(0, '_');
  }
  if KEYWORDS.contains(&safe.as_str()) || safe == "_" {
    safe.push('_');
  }
  format_ident!("{safe}")
}

/// The RUST face — quoting a name always yields valid Rust.
impl ToTokens for RustSafeName {
  fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
    self.safe.to_tokens(tokens);
  }
}

/// The EXTERNAL face — string literals, error messages, and the `rename` attributes an emitted row
/// carries.
impl fmt::Display for RustSafeName {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(&self.external)
  }
}

#[cfg(test)]
mod tests;