Skip to main content

relate_parser/
auto_parameter.rs

1//! The auto-parameter vocabulary in both directions (ADR-0503's
2//! extraction, ADR-0718's substitution): the reserved placeholder prefix
3//! and its two named predicates, the name grammar's one writer and its
4//! reader, and the authored-spelling pairs the naming path substitutes
5//! with. A sibling of `normalize.rs` — the one-pass normalizer produces
6//! the spellings, this module owns the vocabulary around them — so the
7//! normalizer's own header stays true and the placeholder grammar has
8//! one home whichever direction a consumer reads it.
9
10/// The reserved prefix of every auto-parameter name. A statement whose
11/// token stream references a parameter with this prefix, or a caller whose
12/// parameter map carries a key with it, is [`NormalizeOutcome::NotCacheable`]
13/// — the caller can never collide with the engine's own names. Private
14/// behind the two named predicates that spell the policy
15/// ([`name_is_auto_parameter`] on names, [`column_carries_auto_parameter`]
16/// on rendered column text): the prefix itself is not surface.
17const AUTO_PARAM_PREFIX: &str = "__AUTO_";
18
19/// Whether a caller's parameter map carries any [`AUTO_PARAM_PREFIX`]-named
20/// key — the one spelling of the reserved-prefix collision policy, consulted
21/// at the one boundary that decides cache participation — the facade's
22/// `Connection::cache_lookup`, before the raw stage — where such a caller
23/// disables the cache for the statement entirely. Generic over the value
24/// type — the policy is about the names only.
25pub fn params_carry_reserved_prefix<V>(params: &std::collections::BTreeMap<String, V>) -> bool {
26    params.keys().any(|name| name_is_auto_parameter(name))
27}
28
29/// Whether `name` is an auto-parameter name ([`AUTO_PARAM_PREFIX`]) —
30/// the one spelling of the prefix test, shared by the caller-map
31/// boundary above and the planner's auto-parameter plan predicate (the
32/// dispatch epilogue's authored-name restore is keyed on the same
33/// prefix, ADR-0663).
34pub fn name_is_auto_parameter(name: &str) -> bool {
35    name.starts_with(AUTO_PARAM_PREFIX)
36}
37
38/// Whether a rendered result column carries the auto-parameter prefix
39/// (the compiled plan spells an unaliased auto-extracted item as the
40/// placeholder) — the text-level half of the epilogue's re-parse
41/// trigger, beside the name-level [`name_is_auto_parameter`]: the two
42/// consult one prefix, one on names the plan holds typed, one on the
43/// column text the plan rendered.
44pub fn column_carries_auto_parameter(column: &str) -> bool {
45    column.contains(AUTO_PARAM_PREFIX)
46}
47
48/// One extracted literal's authored spelling (ADR-0718): the placeholder
49/// name the compiled plan carries, and the authored source text the
50/// naming path substitutes it with. Named fields, never a positional
51/// pair — which side is the placeholder is a compile-time fact, not a
52/// destructuring convention.
53#[derive(Clone, Debug, PartialEq)]
54pub struct AuthoredSpelling {
55    /// The placeholder name (`__AUTO_INT_0__`), the plan's spelling.
56    pub placeholder: String,
57    /// The authored source text (`1`), what the result column keeps.
58    pub authored: String,
59}
60
61/// The extracted literals' authored spellings, one per literal, in
62/// creation order — the pairs the naming path substitutes with,
63/// [`Normalized::values`] zipped with [`Normalized::spellings`], carried
64/// beside the values on every cache channel that already carries them.
65/// The placeholder's authored text is data, never re-derived by a parse
66/// at result time.
67pub type AuthoredSpellings = Vec<AuthoredSpelling>;
68
69/// Zip a normalization's [`AuthoredSpellings`] — the one construction,
70/// from the two parallel vectors the normalizer produced (generic over
71/// the value type: the normalizer's own `NormalizedValue`, the engine's
72/// `Value`, whatever channel carries the pairs).
73pub fn authored_spellings<V>(values: &[(String, V)], spellings: &[String]) -> AuthoredSpellings {
74    // The two parallel vectors are the normalizer's own output shape
75    // (one Pass walk pushes both sides together); this is the one
76    // boundary where they meet, and a length disagreement is a normalizer
77    // bug, stated as the invariant rather than a silent truncation.
78    assert_eq!(
79        values.len(),
80        spellings.len(),
81        "the normalizer pushes one spelling per value"
82    );
83    values
84        .iter()
85        .zip(spellings)
86        .map(|((name, _), spelling)| AuthoredSpelling {
87            placeholder: name.clone(),
88            authored: spelling.clone(),
89        })
90        .collect()
91}
92
93/// Replace every auto-parameter placeholder in `text` with its authored
94/// spelling (ADR-0718) — the one substitution, in the crate that owns the
95/// placeholder grammar. Three rules make it safe on rendered column text,
96/// which is a verbatim substring of the rewritten statement:
97///
98/// - **Exact-name match**: a `$__AUTO_…` occurrence substitutes only when
99///   the whole parsed name is one of `spellings`' carried names. A
100///   non-extracted string literal's content can look like a placeholder
101///   (`startsWith(n.x, '$__AUTO_INT_0__')` — the call-argument guard kept
102///   the string out of extraction); a lookalike that is not a carried
103///   name stays verbatim, exactly what a re-parse of the source would
104///   have kept.
105/// - **Quote awareness**: the scan tracks string spans by the lexer's own
106///   rules (a `'`/`"` opens, the same byte closes, a backslash escapes
107///   the next byte), so a string literal that happens to contain a
108///   *carried* name verbatim is never touched from inside its quotes —
109///   the one case an exact-name match alone cannot refuse.
110/// - **Single pass**: the output is never re-scanned, so an authored
111///   spelling that itself contains placeholder-lookalike text (an
112///   extracted string literal) lands once, verbatim.
113///
114/// Inter-token spacing inside a substituted name follows the plan the
115/// column text came from (ADR-0718 decision 4): a first execution's
116/// splice preserves the literal span's trailing separator verbatim, so
117/// the name reproduces the source's spacing exactly (`RETURN 1  +  2`
118/// answers `1  +  2`); a template hit's plan was compiled from the
119/// FIRST statement's rewritten text, so the name inherits that
120/// statement's spacing — the one recorded divergence.
121pub fn substitute_auto_parameters(text: &str, spellings: &[AuthoredSpelling]) -> String {
122    // The fast path: nothing carried, nothing to substitute (the common
123    // statement — no literals extracted, no placeholders in any column).
124    if spellings.is_empty() {
125        return text.to_string();
126    }
127    // Byte-wise accumulation over valid UTF-8 copied in order and valid
128    // UTF-8 spellings spliced in — the result is valid UTF-8 by
129    // construction, converted once at the end (a byte-level `String`
130    // push would re-encode every multi-byte body byte as mojibake).
131    let bytes = text.as_bytes();
132    let mut out: Vec<u8> = Vec::with_capacity(text.len());
133    let mut index = 0;
134    // The string span the lexer's grammar would open at this byte: the
135    // opening quote while inside, `None` between tokens.
136    let mut in_string: Option<u8> = None;
137    while index < bytes.len() {
138        let byte = bytes[index];
139        match in_string {
140            Some(quote) => {
141                out.push(byte);
142                if byte == b'\\' {
143                    // The escape consumes the next byte (read_string's
144                    // own rule); copy both verbatim.
145                    if let Some(&escaped) = bytes.get(index + 1) {
146                        out.push(escaped);
147                        index += 1;
148                    }
149                } else if byte == quote {
150                    in_string = None;
151                }
152                index += 1;
153            }
154            None => {
155                if byte == b'\'' || byte == b'"' {
156                    in_string = Some(byte);
157                    out.push(byte);
158                    index += 1;
159                } else if byte == b'$' {
160                    // A placeholder reference renders as `$` + the name;
161                    // try to read one whole name and match it exactly.
162                    match read_auto_parameter_name(&bytes[index + 1..]) {
163                        Some(name) => {
164                            match spellings.iter().find(|carried| carried.placeholder == name) {
165                                Some(carried) => {
166                                    out.extend_from_slice(carried.authored.as_bytes());
167                                }
168                                // Not a carried name: a lookalike in
169                                // ordinary text or a non-extracted
170                                // literal's content — verbatim.
171                                None => {
172                                    out.push(b'$');
173                                    out.extend_from_slice(name.as_bytes());
174                                }
175                            }
176                            index += 1 + name.len();
177                        }
178                        // Not a name at all: an explicit parameter or
179                        // ordinary text — copy the `$` and continue.
180                        None => {
181                            out.push(b'$');
182                            index += 1;
183                        }
184                    }
185                } else {
186                    out.push(byte);
187                    index += 1;
188                }
189            }
190        }
191    }
192    String::from_utf8(out).expect("copied UTF-8 in order stays valid UTF-8")
193}
194
195/// Write one whole auto-parameter name — the grammar
196/// [`crate::normalize::Pass::fresh_name`] assigns with (the tag derives
197/// from the value it names there, the index from the one creation
198/// counter), stated once here so the writer and the reader below can
199/// never drift. The reader stays deliberately tolerant of unknown tags
200/// (any uppercase run): a stored pair list may outlive a dialect that
201/// grew a new value kind.
202pub(crate) fn auto_parameter_name(kind: &str, index: usize) -> String {
203    format!("{AUTO_PARAM_PREFIX}{kind}_{index}__")
204}
205
206/// Read one whole auto-parameter name from the bytes after a `$` —
207/// [`AUTO_PARAM_PREFIX`], a kind tag, `_`, digits, and the closing `__`
208/// (the grammar [`auto_parameter_name`] writes) — `None` when the bytes
209/// do not spell one. Every consumed byte is echoed into the returned
210/// name, so the caller advances by `name.len()`: the name IS the
211/// consumption record.
212fn read_auto_parameter_name(bytes: &[u8]) -> Option<String> {
213    let mut rest = bytes.strip_prefix(AUTO_PARAM_PREFIX.as_bytes())?;
214    let mut name = AUTO_PARAM_PREFIX.to_string();
215    // The kind tag: ASCII uppercase only (`INT`, `FLOAT`, `STR`, `LIST`).
216    let tag = rest.iter().take_while(|b| b.is_ascii_uppercase()).count();
217    if tag == 0 {
218        return None;
219    }
220    name.push_str(std::str::from_utf8(&rest[..tag]).expect("ASCII uppercase is UTF-8"));
221    rest = &rest[tag..];
222    // The index separator, then the digits, then the closing `__`. The
223    // name's own length is the one advance — the caller moves by what it
224    // matched, never by a second counter that could drift from it.
225    if rest.first() != Some(&b'_') {
226        return None;
227    }
228    name.push('_');
229    rest = &rest[1..];
230    let digits = rest.iter().take_while(|b| b.is_ascii_digit()).count();
231    if digits == 0 {
232        return None;
233    }
234    name.push_str(std::str::from_utf8(&rest[..digits]).expect("ASCII digits are UTF-8"));
235    rest = &rest[digits..];
236    if rest.first() != Some(&b'_') || rest.get(1) != Some(&b'_') {
237        return None;
238    }
239    name.push_str("__");
240    Some(name)
241}