ingraph-codegen 0.1.0

The emission engine behind ingraph-derive: a plain declaration model in, the ingraph framework faces out.
Documentation
//! Both faces of every name, asserted together.
//!
//! A test that checked only one face would pass while the other silently rewrote a column: the
//! whole point of the type is that the Rust face is always spellable and the external face is
//! never touched.

use quote::quote;

use crate::name::RustSafeName;

/// The Rust face — what `quote!(#name)` puts in an expansion.
fn rust(name: &RustSafeName) -> String {
  quote!(#name).to_string()
}

/// The external face — what `Display` hands a string literal, an error, a `try_get` or a
/// `#[serde(rename)]`.
fn external(name: &RustSafeName) -> String {
  format!("{name}")
}

fn name(external: &str) -> RustSafeName {
  RustSafeName::new(external, proc_macro2::Span::call_site())
}

/// The ordinary case: a name that is already an identifier reaches both faces untouched.
#[test]
fn an_identifier_is_its_own_rust_face() {
  let name = name("bit_rate");
  assert_eq!(rust(&name), "bit_rate");
  assert_eq!(external(&name), "bit_rate");
}

/// A keyword gains a TRAILING UNDERSCORE rather than an `r#` prefix — see the mangling's own doc
/// for the four keywords a raw identifier cannot express.
#[test]
fn a_keyword_gains_a_trailing_underscore_and_keeps_its_external_name() {
  for (declared, safe) in [
    ("type", "type_"),
    ("crate", "crate_"),
    ("self", "self_"),
    // `Self` lowercases to the keyword `self` first, so it takes the same underscore. The two
    // spellings therefore COLLIDE on one type, which the parser refuses by name.
    ("Self", "self_"),
    ("super", "super_"),
    ("match", "match_"),
    ("gen", "gen_"),
  ] {
    let name = name(declared);
    assert_eq!(rust(&name), safe, "`{declared}`");
    assert_eq!(
      external(&name),
      declared,
      "`{declared}` reaches SQL unchanged"
    );
  }
}

/// The Rust face is IDIOMATIC Rust, not merely legal Rust: a camelCase wire name reaches an
/// emitted field as snake_case.
///
/// `bitRate` is a valid identifier, so a rule that only asked "does this parse" would let it
/// through and hand every consumer a `non_snake_case` warning about generated code they cannot
/// edit. The lint tells the truth; the fix belongs in the mangling rather than in an `#[allow]`.
#[test]
fn the_rust_face_is_snake_case_and_the_external_face_is_not() {
  for (declared, safe) in [
    ("bitRate", "bit_rate"),
    ("HTTPServer", "http_server"),
    ("VideoTrackID", "video_track_id"),
    ("streamIndex", "stream_index"),
    ("SELECT", "select"),
    ("XMLHttpRequest", "xml_http_request"),
    ("already_snake", "already_snake"),
  ] {
    let name = name(declared);
    assert_eq!(rust(&name), safe, "`{declared}`");
    assert_eq!(
      external(&name),
      declared,
      "`{declared}` is what a client sees, and it is never rewritten"
    );
  }
}

/// Normalising is IDEMPOTENT — a name that is already snake_case is left exactly as it is, so
/// nothing drifts by being run through the mangling twice.
#[test]
fn normalising_an_already_idiomatic_name_changes_nothing() {
  for declared in ["bit_rate", "id", "media_id", "a", "x2"] {
    let name = name(declared);
    assert_eq!(rust(&name), declared, "`{declared}`");
    assert_eq!(external(&name), declared);
  }
}

/// Anything an identifier cannot contain becomes an underscore, and the external name keeps it.
#[test]
fn a_non_identifier_character_becomes_an_underscore() {
  for (declared, safe) in [
    ("my column", "my_column"),
    ("a-b", "a_b"),
    ("bit.rate", "bit_rate"),
    ("a\"b", "a_b"),
  ] {
    let name = name(declared);
    assert_eq!(rust(&name), safe, "`{declared}`");
    assert_eq!(external(&name), declared, "`{declared}`");
  }
}

/// A leading digit gains a prefix. The Rust face is asserted as a PARSABLE identifier rather than
/// as one spelling, because what matters is that quoting it always yields valid Rust.
#[test]
fn a_leading_digit_gains_a_prefix() {
  let name = name("2fast");
  assert_eq!(rust(&name), "_2fast");
  assert_eq!(external(&name), "2fast");
  syn::parse_str::<syn::Ident>(&rust(&name)).expect("the Rust face is an identifier");
}

/// The degenerate names, which have to land somewhere: `_` is the wildcard pattern rather than an
/// identifier, so neither an empty name nor a bare underscore may produce it.
#[test]
fn the_degenerate_names_still_produce_an_identifier() {
  for declared in ["", "_", "-", "  "] {
    let name = name(declared);
    syn::parse_str::<syn::Ident>(&rust(&name))
      .unwrap_or_else(|e| panic!("`{declared}` produced `{}`: {e}", rust(&name)));
    assert_eq!(external(&name), declared, "`{declared}`");
  }
}

/// Every mangling, run over the whole roster: whatever the external name, the Rust face parses as
/// an identifier and the external face is returned verbatim.
#[test]
fn every_name_has_a_spellable_rust_face_and_an_untouched_external_one() {
  for declared in [
    "bit_rate",
    "type",
    "crate",
    "my column",
    "2fast",
    "a-b",
    "",
    "_",
    "SELECT",
    "r#type",
    "__seq__",
    "9",
  ] {
    let name = name(declared);
    syn::parse_str::<syn::Ident>(&rust(&name))
      .unwrap_or_else(|e| panic!("`{declared}` produced `{}`: {e}", rust(&name)));
    assert_eq!(external(&name), declared, "`{declared}` is never rewritten");
  }
}

/// A name built from a FIELD is already safe, and its external face drops the raw prefix: `r#type`
/// is the Rust spelling of a column called `type`.
#[test]
fn a_field_ident_keeps_its_spelling_and_unraws_its_external_face() {
  let plain =
    RustSafeName::from_ident(&syn::Ident::new("bit_rate", proc_macro2::Span::call_site()));
  assert_eq!(rust(&plain), "bit_rate");
  assert_eq!(external(&plain), "bit_rate");

  let raw = RustSafeName::from_ident(&syn::Ident::new_raw("type", proc_macro2::Span::call_site()));
  assert_eq!(
    rust(&raw),
    "r#type",
    "the field keeps the spelling it was declared with"
  );
  assert_eq!(external(&raw), "type", "and the column is called `type`");
}

/// The Rust face is what an emitted field name is, so it has to survive being quoted into a struct.
#[test]
fn the_rust_face_can_be_quoted_into_a_struct_field() {
  let names: Vec<RustSafeName> = ["type", "my column", "2fast"]
    .iter()
    .map(|n| name(n))
    .collect();
  let item: syn::ItemStruct = syn::parse2(quote! {
    struct Row { #(#names: u64,)* }
  })
  .expect("every mangled name is a legal field name");
  let fields: Vec<String> = match &item.fields {
    syn::Fields::Named(named) => named
      .named
      .iter()
      .map(|f| f.ident.as_ref().expect("named").to_string())
      .collect(),
    _ => panic!("named fields"),
  };
  assert_eq!(fields, ["type_", "my_column", "_2fast"]);
}