ingraph_codegen/name.rs
1//! A name with two faces: the one a database sees and the one Rust can spell.
2//!
3//! A column is declared once and used twice — as the string in a `CREATE TABLE`, a `try_get`, a
4//! `#[serde(rename = "…")]` and an error message, and as the IDENT of the field that carries it in
5//! an emitted row. Those two are not always the same string: `type` and `bit-rate` are ordinary
6//! column names and neither is a legal field name.
7//!
8//! Keeping them in ONE value is what stops them drifting. A pair of strings passed around
9//! separately gets swapped eventually — and the failure is silent, because a mangled name still
10//! compiles and a column called `bit_rate` still exists somewhere. Here the choice is made by the
11//! trait a use site reaches for: quoting a name into an expansion yields the Rust face, and
12//! formatting it yields the external one.
13//!
14//! Borrowed from `polarsync-codegen`'s `RustSafeName`, which carries the same two faces for the
15//! same reason.
16
17use core::fmt;
18
19use heck::ToSnakeCase as _;
20use quote::{ToTokens, format_ident};
21
22/// The keywords a field cannot be named. Reserved ones are here too: `become` and `gen` are not
23/// usable as identifiers in this edition either, and a list that only tracked what is currently
24/// STRICT would let an emission break on an edition bump.
25///
26/// `union`, `macro_rules`, `raw` and `safe` are deliberately absent — they are contextual, and
27/// `let union = 1;` compiles.
28const KEYWORDS: &[&str] = &[
29 "Self", "abstract", "as", "async", "await", "become", "box", "break", "const", "continue",
30 "crate", "do", "dyn", "else", "enum", "extern", "false", "final", "fn", "for", "gen", "if",
31 "impl", "in", "let", "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub",
32 "ref", "return", "self", "static", "struct", "super", "trait", "true", "try", "type", "typeof",
33 "unsafe", "unsized", "use", "virtual", "where", "while", "yield",
34];
35
36/// A name as the database spells it, together with the identifier Rust can spell it as.
37///
38/// The EXTERNAL name is never rewritten: it is what reaches a `CREATE TABLE`, a `SELECT`, and the
39/// `rename` attribute an emitted row carries — so a declaration that says `rename = "bit-rate"`
40/// gets a column called `bit-rate`, whatever the field holding it has to be called.
41#[derive(Debug, Clone, PartialEq, Eq, Hash)]
42pub struct RustSafeName {
43 /// The identifier an expansion may use — the external name, mangled only as far as it must be.
44 safe: syn::Ident,
45 /// The name as declared. Verbatim, always.
46 external: String,
47}
48
49impl RustSafeName {
50 /// A name from whatever a declaration wrote, mangled into an identifier as needed.
51 ///
52 /// `span` is the token the name was declared at, so an emitted field points back at the
53 /// declaration and a refusal about it reports there.
54 ///
55 /// That it is CARRIED is pinned by `ingraph-derive`'s `tests/span_pins.rs`, at the column of a
56 /// real compiler's caret. A span is observable nowhere else: proc-macro2 holds every location
57 /// behind its `span-locations` feature, and without it `Debug` renders the constant `Span` — so a
58 /// unit test comparing two renderings holds for any emitter at all, which is exactly what the
59 /// assertion that used to sit in `tests.rs` beside this one did.
60 pub fn new(external: impl Into<String>, span: proc_macro2::Span) -> Self {
61 let external = external.into();
62 let mut safe = mangle(&external);
63 safe.set_span(span);
64 Self { safe, external }
65 }
66
67 /// A name from a record's own FIELD, which is already an identifier.
68 ///
69 /// The external face drops a raw prefix: `r#type` is how Rust spells a field called `type`, and
70 /// `type` is what the column is called.
71 pub fn from_ident(ident: &syn::Ident) -> Self {
72 let spelled = ident.to_string();
73 Self {
74 external: spelled
75 .strip_prefix("r#")
76 .map_or(spelled.clone(), ToOwned::to_owned),
77 safe: ident.clone(),
78 }
79 }
80
81 /// The identifier an expansion uses. Also reachable by quoting the name.
82 pub const fn safe(&self) -> &syn::Ident {
83 &self.safe
84 }
85
86 /// The name the database sees. Also reachable by formatting the name.
87 pub fn external(&self) -> &str {
88 &self.external
89 }
90}
91
92/// The external name as an identifier, by the smallest change that makes it one.
93///
94/// - The name is normalised to SNAKE CASE: `bitRate` becomes `bit_rate`, `HTTPServer` becomes
95/// `http_server`. The Rust face is idiomatic Rust, not merely legal Rust.
96/// - `-`, and every other character an identifier cannot carry, becomes `_`.
97/// - A leading digit gains a `_`.
98/// - A KEYWORD gains a trailing `_`.
99/// - `_` alone is the wildcard pattern rather than an identifier, so it gains a second one.
100///
101/// The keyword rule is a trailing underscore rather than a raw identifier because `r#` cannot
102/// express four of them: `r#crate`, `r#self`, `r#super` and `r#Self` are all rejected by the
103/// compiler. One rule that covers every keyword beats two rules with an exception list.
104///
105/// The kept set is ASCII, which is narrower than what an identifier may hold. That is on purpose
106/// and it is about not PANICKING: `char::is_alphanumeric` accepts `²` — a number by Unicode's
107/// reckoning and not an identifier character by the compiler's — so a rule written that way builds
108/// a string [`syn::Ident`] rejects, and a proc macro that panics reports nothing a reader can act
109/// on. A non-ASCII external name keeps its own spelling; only the field carrying it is folded.
110fn mangle(external: &str) -> syn::Ident {
111 // Case FIRST, because the Rust face has to be idiomatic Rust and not merely legal Rust. A wire
112 // field called `bitRate` is a perfectly valid identifier, so a rule that only asked "does this
113 // parse" would emit it and hand every consumer a `non_snake_case` warning about generated code
114 // they cannot edit. The lint is telling the truth, and an `#[allow]` would only hide it.
115 //
116 // `heck` also does the word splitting the character map below would otherwise have to guess at:
117 // `HTTPServer` becomes `http_server` rather than `h_t_t_p_server`.
118 let mut safe: String = external
119 .to_snake_case()
120 .chars()
121 .map(|c| {
122 if c.is_ascii_alphanumeric() || c == '_' {
123 c
124 } else {
125 '_'
126 }
127 })
128 .collect();
129 if safe.is_empty() || safe.starts_with(|c: char| c.is_ascii_digit()) {
130 safe.insert(0, '_');
131 }
132 if KEYWORDS.contains(&safe.as_str()) || safe == "_" {
133 safe.push('_');
134 }
135 format_ident!("{safe}")
136}
137
138/// The RUST face — quoting a name always yields valid Rust.
139impl ToTokens for RustSafeName {
140 fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
141 self.safe.to_tokens(tokens);
142 }
143}
144
145/// The EXTERNAL face — string literals, error messages, and the `rename` attributes an emitted row
146/// carries.
147impl fmt::Display for RustSafeName {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 f.write_str(&self.external)
150 }
151}
152
153#[cfg(test)]
154mod tests;