Skip to main content

relate_parser/
normalize.rs

1//! The statement normalizer (ADR-0503): one pass over the lexer's own
2//! token stream that derives a plan-cache template key, the rewritten
3//! statement text, and the extracted literal values — the enabler for
4//! template-keyed plan caching on workloads that emit literals instead of
5//! parameters.
6//!
7//! The three outputs of one walk, so they cannot drift:
8//!
9//! - **template** — the canonical key. Value-bearing literal tokens
10//!   (`Integer`, `Float`, `String`) become typed placeholders
11//!   `$__AUTO_INT_0__`/`$__AUTO_FLOAT_1__`/`$__AUTO_STR_2__` (the type is
12//!   part of the key, so `42` and `'42'` never share a template); a
13//!   bracket group of only such literals (recursively) collapses to one
14//!   `$__AUTO_LIST_n__` placeholder; identifiers render through the
15//!   canonical quoting policy ([`quote_identifier`]), parameters through
16//!   [`parameter_reference`] (the shaped `$name` render — a
17//!   non-identifier-shaped name renders backtick-quoted, so two different
18//!   names never share a template and the two spellings of one name
19//!   share one), and every other token — keywords included — as written.
20//!   Two statements share a template only if they parse identically.
21//!   Keyword case is deliberately NOT folded: the dialect keeps keyword
22//!   spellings as case-sensitive names (`(o:Order)`, `-[:ORDER]->`,
23//!   `n.match`, `{match: 1}`), and the token stream cannot prove a
24//!   keyword sits in a clause position rather than a name position — so
25//!   `match …` and `MATCH …` keep distinct templates (a miss, never a
26//!   wrong plan).
27//! - **rewritten** — the source with each normalized literal's byte span
28//!   replaced by its placeholder: a real Cypher statement whose literals
29//!   are parameters. Parsing it (with the extracted values bound as
30//!   `$__AUTO_*__` parameters, through the ordinary front-end entry) is
31//!   what a cache entry is built from, so any literal position whose
32//!   parameter form is ungrammatical fails that parse and the statement
33//!   simply stays uncached — an over-eager normalization costs a miss,
34//!   never a wrong plan.
35//! - **values** — the placeholder/value pairs in token order.
36//!
37//! Grammar guards skip normalization where a parameter is not grammatical
38//! or would change meaning (each costs only a cache miss): a `String`
39//! followed by `:` is a map-literal key; a `String` preceded by the
40//! contextual `FIELDTERMINATOR` identifier is a LOAD CSV field terminator;
41//! an `Integer`/`Float` preceded by `*` or `..` is a var-length quantifier
42//! bound; a `String` that is a function call's first argument feeds the
43//! front-end's constant folding (a temporal constructor's literal folds
44//! to a constant at lowering — a parameter there stays a per-row call).
45//! `CYPHER <version>` integers need no guard — the rewritten parse fails
46//! closed.
47//!
48//! Deliberately NOT done (the 2026-10-31 session's constraints, §7): no
49//! variable renaming (variable names are structural), no size threshold,
50//! no folding of non-clause keywords (`n.true` and `n.TRUE` are different
51//! property keys).
52
53use std::cell::Cell;
54
55use crate::lexer::{tokenize_with_options, ParseOptions};
56use crate::parser::{parse_int_literal, MAX_NESTING_DEPTH, MAX_QUERY_BYTES};
57use crate::token::{
58    is_field_terminator_word, line_starts_of, quote_identifier, token_start_byte, Token, TokenType,
59};
60use relate_model::identifier::parameter_reference;
61
62/// The reserved prefix of every auto-parameter name. A statement whose
63/// token stream references a parameter with this prefix, or a caller whose
64/// parameter map carries a key with it, is [`NormalizeOutcome::NotCacheable`]
65/// — the caller can never collide with the engine's own names. Private
66/// behind the two named predicates that spell the policy
67/// ([`name_is_auto_parameter`] on names, [`column_carries_auto_parameter`]
68/// on rendered column text): the prefix itself is not surface.
69const AUTO_PARAM_PREFIX: &str = "__AUTO_";
70
71/// Whether a caller's parameter map carries any [`AUTO_PARAM_PREFIX`]-named
72/// key — the one spelling of the reserved-prefix collision policy, consulted
73/// at the one boundary that decides cache participation — the facade's
74/// `Connection::cache_lookup`, before the raw stage — where such a caller
75/// disables the cache for the statement entirely. Generic over the value
76/// type — the policy is about the names only.
77pub fn params_carry_reserved_prefix<V>(params: &std::collections::BTreeMap<String, V>) -> bool {
78    params.keys().any(|name| name_is_auto_parameter(name))
79}
80
81/// Whether `name` is an auto-parameter name ([`AUTO_PARAM_PREFIX`]) —
82/// the one spelling of the prefix test, shared by the caller-map
83/// boundary above and the planner's auto-parameter plan predicate (the
84/// dispatch epilogue's authored-name restore is keyed on the same
85/// prefix, ADR-0663).
86pub fn name_is_auto_parameter(name: &str) -> bool {
87    name.starts_with(AUTO_PARAM_PREFIX)
88}
89
90/// Whether a rendered result column carries the auto-parameter prefix
91/// (the compiled plan spells an unaliased auto-extracted item as the
92/// placeholder) — the text-level half of the epilogue's re-parse
93/// trigger, beside the name-level [`name_is_auto_parameter`]: the two
94/// consult one prefix, one on names the plan holds typed, one on the
95/// column text the plan rendered.
96pub fn column_carries_auto_parameter(column: &str) -> bool {
97    column.contains(AUTO_PARAM_PREFIX)
98}
99
100/// One extracted literal value: the normalizer's own small vocabulary (the
101/// parser crate does not depend on the engine's value type). The facade
102/// converts these into parameter values at the one boundary where both
103/// exist.
104#[derive(Debug, Clone, PartialEq)]
105pub enum NormalizedValue {
106    Int(i64),
107    Float(f64),
108    Str(String),
109    List(Vec<NormalizedValue>),
110}
111
112/// What [`normalize_statement`] produced.
113#[derive(Debug, Clone, PartialEq)]
114pub enum NormalizeOutcome {
115    /// The template key, the rewritten statement, and the values, all of
116    /// one walk.
117    Normalized(Normalized),
118    /// The statement must not participate in the plan cache. Oversized
119    /// input, a lexer error token, an unparseable literal, a `$__AUTO_*`
120    /// name in the stream, or a list scan past its total step budget (an
121    /// adversarially nested payload — the parser's own guards are then
122    /// the statement's verdict). Never an error: the statement itself
123    /// parses and runs exactly as before.
124    NotCacheable,
125}
126
127/// The normalizer's outputs. See the [module documentation](self).
128#[derive(Debug, Clone, PartialEq)]
129pub struct Normalized {
130    /// The canonical template: two statements share it only if they parse
131    /// identically.
132    pub template: String,
133    /// The statement with normalized literals as `$__AUTO_*__`
134    /// parameters.
135    pub rewritten: String,
136    /// The `(placeholder, value)` pairs, in token order.
137    pub values: Vec<(String, NormalizedValue)>,
138    /// The original source spelling of each [`Self::values`] entry, in the
139    /// same order: the text the result column keeps (`RETURN 1` stays `1`).
140    pub spellings: Vec<String>,
141}
142
143/// Normalize `src` under the same [`ParseOptions`] the real parse would
144/// use (the preview gates change what the lexer produces, so the template
145/// must be derived from the identical token stream).
146pub fn normalize_statement(src: &str, options: ParseOptions) -> NormalizeOutcome {
147    // The same cap the parse enforces (ADR-0257), checked for the same
148    // reason: no adversarial amplification into unbounded token
149    // allocation. An oversized statement fails the parse anyway.
150    if src.len() > MAX_QUERY_BYTES {
151        return NormalizeOutcome::NotCacheable;
152    }
153    let tokens = tokenize_with_options(src, options);
154    let line_starts = line_starts_of(src);
155    let scan_budget = tokens.len() as u64 * 2 + SCAN_STEP_HEADROOM;
156    let mut pass = Pass {
157        src,
158        tokens: &tokens,
159        line_starts: &line_starts,
160        template: String::new(),
161        spans: Vec::new(),
162        values: Vec::new(),
163        spellings: Vec::new(),
164        next_index: 0,
165        call_argument: call_argument_context(&tokens),
166        scan_steps: Cell::new(0),
167        scan_budget,
168    };
169    match pass.run() {
170        Some(normalized) => NormalizeOutcome::Normalized(normalized),
171        None => NormalizeOutcome::NotCacheable,
172    }
173}
174
175/// The list scan's step-budget headroom over `2 × token count` — slack
176/// for the empty-group and single-element shapes whose scans touch a few
177/// tokens more than once.
178const SCAN_STEP_HEADROOM: u64 = 64;
179
180/// The one-pass state. `Option` returns are the not-cacheable bailouts,
181/// never errors: every guard's failure mode is a statement that stays
182/// uncached. The two lifetimes are the source's and the tokens' own
183/// (ADR-0505 borrowed them from it).
184struct Pass<'a, 't> {
185    src: &'a str,
186    tokens: &'t [Token<'a>],
187    line_starts: &'a [usize],
188    /// The template under construction: the rendered tokens joined with
189    /// single spaces.
190    template: String,
191    /// The rewritten text's replacements, in source order:
192    /// `(byte start, byte end, placeholder)` — the span runs from the
193    /// normalized token's (or group's) first byte to the next token's
194    /// first byte, so the inter-token whitespace rides out with the
195    /// literal.
196    spans: Vec<(usize, usize, String)>,
197    /// The extracted values in placeholder order.
198    values: Vec<(String, NormalizedValue)>,
199    /// Original source spellings, parallel to `values`.
200    spellings: Vec<String>,
201    /// The one counter every placeholder name derives from.
202    next_index: usize,
203    /// Whether each token sits inside a function call's argument list —
204    /// the innermost unmatched opener enclosing it is a `(` whose callee
205    /// identifier stands before it (a map or list nested in the argument
206    /// list is still argument territory). One linear precompute pass
207    /// (before the run loop), so the literal guards are a lookup, never a
208    /// per-literal rescan of the token prefix.
209    call_argument: Vec<bool>,
210    /// The list scan's consumed steps against `scan_budget` (see the
211    /// scan's doc) — a `Cell` so the scan stays `&self`, matching the
212    /// run loop's borrows.
213    scan_steps: Cell<u64>,
214    /// The total step budget: a healthy statement's scans visit each
215    /// token a bounded number of times, so `2 × tokens + headroom` is
216    /// never reached; the pathological re-descending shape trips it
217    /// early.
218    scan_budget: u64,
219}
220
221impl<'a, 't> Pass<'a, 't> {
222    /// Whether the list scan's step budget tripped — derived from the
223    /// counter and the budget, the same comparison the scan itself
224    /// declines on, never a stored copy of it: the whole statement
225    /// declines to not-cacheable (the parser's own guards are then its
226    /// verdict).
227    fn scan_exhausted(&self) -> bool {
228        self.scan_steps.get() > self.scan_budget
229    }
230
231    fn run(&mut self) -> Option<Normalized> {
232        let mut i = 0;
233        while i < self.tokens.len() {
234            if self.scan_exhausted() {
235                return None;
236            }
237            let tok = &self.tokens[i];
238            match tok.ty {
239                // A lexer error token fails the real parse; there is
240                // nothing to cache.
241                TokenType::Error => return None,
242                TokenType::Parameter => {
243                    if name_is_auto_parameter(&tok.literal) {
244                        return None;
245                    }
246                    if tok.is_dynamic_opener_sentinel() {
247                        // The empty literal is the `$(expr)` encoding,
248                        // never a name — `parameter_reference` cannot
249                        // render it, so the template declines. (The
250                        // dynamic-operand uncacheability rule is a
251                        // separate fact, enforced where it lives,
252                        // `cache_insert_eligible`.) The sentinel's
253                        // encoding is the token layer's one fact
254                        // (`Token::is_dynamic_opener_sentinel`), never
255                        // re-tested as a raw literal here.
256                        return None;
257                    }
258                    self.push_rendered(&parameter_reference(&tok.literal));
259                }
260                // A CIP-261 interpolated string embeds expressions, and an
261                // embedded parameter reference is invisible to the
262                // reserved-name check above — the payload is one token.
263                // The whole statement bails: an embedded `$__AUTO_*__`
264                // could otherwise collide with the rewritten text's own
265                // placeholders (found in review), and the payload's
266                // embedded literals are as unnormalizable as the
267                // interpolation itself.
268                TokenType::InterpString => return None,
269                TokenType::Identifier => {
270                    self.push_rendered(&quote_identifier(&tok.literal));
271                }
272                TokenType::Integer | TokenType::Float
273                    if !self.after_quantifier_bound(i) && !self.call_argument[i] =>
274                {
275                    let value = literal_value(tok)?;
276                    self.replace_token(i, value)?;
277                }
278                TokenType::String => {
279                    if self.is_map_key(i) || self.is_field_terminator(i) || self.call_argument[i] {
280                        // A guarded string (map key, LOAD CSV field
281                        // terminator, or a function-call argument) stays
282                        // in the template, quoted — the quotes keep it
283                        // from aliasing an identifier's render, and the
284                        // escaping keeps the render injective.
285                        self.push_rendered(&format!("'{}'", escape_single_quoted(&tok.literal)));
286                    } else {
287                        self.replace_token(i, literal_value(tok)?)?;
288                    }
289                }
290                TokenType::LeftBracket if !self.call_argument[i] => {
291                    if let Some((close, elements)) = self.scan_literal_group(i + 1) {
292                        // The whole bracket group is one parameter whose
293                        // value is the list (lists-as-one-param, the
294                        // `$__AUTO_INT_3__` positional-typed-key precedent).
295                        self.replace_group(i, close, NormalizedValue::List(elements))?;
296                        i = close;
297                    } else if self.scan_exhausted() {
298                        // The scan's step budget tripped: the statement
299                        // declines whole, not bracket by bracket.
300                        return None;
301                    } else {
302                        self.push_rendered(&tok.literal);
303                    }
304                }
305                // Every remaining token renders as written — keywords
306                // included. Case folding a keyword token is unsound at
307                // token level: the dialect keeps keyword spellings as
308                // case-sensitive NAMES (`(o:Order)` and `-[:ORDER]->`
309                // parse with the name as written, `n.match` and
310                // `{match: 1}` bind by spelling), and the token stream
311                // cannot prove a keyword sits in a clause position
312                // rather than a name position — so `match …` and
313                // `MATCH …` keep distinct templates, the safe direction.
314                _ => {
315                    self.push_rendered(&tok.literal);
316                }
317            }
318            i += 1;
319        }
320        Some(Normalized {
321            template: std::mem::take(&mut self.template),
322            rewritten: self.splice(),
323            values: std::mem::take(&mut self.values),
324            spellings: std::mem::take(&mut self.spellings),
325        })
326    }
327
328    /// Append one rendered token to the template, space-separated.
329    fn push_rendered(&mut self, text: &str) {
330        if !self.template.is_empty() {
331            self.template.push(' ');
332        }
333        self.template.push_str(text);
334    }
335
336    /// The byte offset of token `i`'s first byte.
337    fn start_byte(&self, i: usize) -> Option<usize> {
338        token_start_byte(&self.tokens[i], self.line_starts, self.src.len())
339    }
340
341    /// The byte offset the token after `i` starts at — the end of token
342    /// `i`'s replacement span (the inter-token whitespace rides out with
343    /// the literal); the source end for the final token.
344    fn end_byte(&self, i: usize) -> Option<usize> {
345        match self.tokens.get(i + 1) {
346            Some(next) => token_start_byte(next, self.line_starts, self.src.len()),
347            None => Some(self.src.len()),
348        }
349    }
350
351    /// Whether token `i` sits directly after `*` or `..`: the var-length
352    /// quantifier bounds (`[:TYPE*1..3]`), which take literal integers
353    /// only. The same shape after an arithmetic `*` (`2 * 3`) is a false
354    /// positive that costs a miss, never a wrong key.
355    fn after_quantifier_bound(&self, i: usize) -> bool {
356        i > 0 && matches!(self.tokens[i - 1].ty, TokenType::Star | TokenType::DotDot)
357    }
358
359    /// Whether token `i` is a `String` followed by `:` — a map-literal
360    /// key (`{'name': 1}`). Parameters are not map keys, and the key is
361    /// structural: it stays in the template.
362    fn is_map_key(&self, i: usize) -> bool {
363        self.tokens
364            .get(i + 1)
365            .is_some_and(|next| next.ty == TokenType::Colon)
366    }
367
368    /// Whether token `i` is the `String` after the contextual
369    /// `FIELDTERMINATOR` identifier of LOAD CSV, which requires a literal
370    /// there — decided through the crate's one spelling of that word.
371    fn is_field_terminator(&self, i: usize) -> bool {
372        i > 0
373            && self.tokens[i - 1].ty == TokenType::Identifier
374            && is_field_terminator_word(&self.tokens[i - 1].literal)
375    }
376
377    /// Replace token `i` with a fresh typed placeholder: the whole-group
378    /// emitter over a one-token span. `None` only when the token's byte
379    /// offset cannot derive — a real token stream from this source always
380    /// carries real positions.
381    fn replace_token(&mut self, i: usize, value: NormalizedValue) -> Option<()> {
382        self.replace_group(i, i, value)
383    }
384
385    /// Replace the token span `open..=close` (inclusive) with one
386    /// placeholder — the one emitter of the template text, the rewritten
387    /// span, and the value, from the one counter, so the three outputs
388    /// cannot drift. `None` only when a span endpoint's byte offset
389    /// cannot derive.
390    fn replace_group(&mut self, open: usize, close: usize, value: NormalizedValue) -> Option<()> {
391        let name = self.fresh_name(&value);
392        // One placeholder value feeds both outputs, so the template's
393        // rendering and the rewritten span are the same text by
394        // construction — the one parameter render, shaped names included
395        // (fresh names are always plain, but the spelling stays canonical).
396        let placeholder = parameter_reference(&name);
397        self.push_rendered(&placeholder);
398        let start = self.start_byte(open)?;
399        let end = self.end_byte(close)?;
400        self.spans.push((start, end, placeholder));
401        self.values.push((name, value));
402        self.spellings
403            .push(self.src[start..end].trim_end().to_string());
404        Some(())
405    }
406
407    fn fresh_name(&mut self, value: &NormalizedValue) -> String {
408        // The type tag derives from the value it names — the two cannot
409        // disagree.
410        let kind = match value {
411            NormalizedValue::Int(_) => "INT",
412            NormalizedValue::Float(_) => "FLOAT",
413            NormalizedValue::Str(_) => "STR",
414            NormalizedValue::List(_) => "LIST",
415        };
416        let name = format!("{AUTO_PARAM_PREFIX}{kind}_{}__", self.next_index);
417        self.next_index += 1;
418        name
419    }
420
421    /// Scan a bracket group's interior starting at `j` (just past the
422    /// `[`): `Some((index of the closing `]`, element values))` when every
423    /// element is a normalizable literal or such a group, comma-separated
424    /// (an empty group scans clean); `None` when anything else appears —
425    /// the caller then renders the `[` and lets the element tokens take
426    /// their own arms. The recursion is depth-capped at
427    /// [`MAX_NESTING_DEPTH`], the parser's own ADR-0257 limit: this scan
428    /// runs BEFORE the parse, so an adversarially nested payload must not
429    /// recurse past what the parser would reject anyway — a group past the
430    /// cap declines (no collapse), and the parse's depth guard is the
431    /// statement's verdict.
432    fn scan_literal_group(&self, j: usize) -> Option<(usize, Vec<NormalizedValue>)> {
433        self.scan_literal_group_at_depth(j, 0)
434    }
435
436    /// [`Pass::scan_literal_group`] with the recursion depth counted and
437    /// the total step budget charged: every visited token costs one step,
438    /// and a budget exhausted mid-scan flags the whole statement
439    /// not-cacheable — without it, a declined deep group re-descends from
440    /// the very next bracket (each restart at depth 0), turning an
441    /// adversarial payload into quadratic token visits.
442    fn scan_literal_group_at_depth(
443        &self,
444        mut j: usize,
445        depth: u32,
446    ) -> Option<(usize, Vec<NormalizedValue>)> {
447        if depth >= MAX_NESTING_DEPTH {
448            // Past the parser's depth cap the whole statement declines.
449            // A bare `None` would restart a depth-0 scan at the next `[`.
450            self.scan_steps.set(self.scan_budget.saturating_add(1));
451            return None;
452        }
453        let mut elements = Vec::new();
454        loop {
455            let steps = self.scan_steps.get() + 1;
456            self.scan_steps.set(steps);
457            if self.scan_exhausted() {
458                return None;
459            }
460            let tok = self.tokens.get(j)?;
461            let element = match tok.ty {
462                TokenType::LeftBracket => {
463                    let (close, inner) = self.scan_literal_group_at_depth(j + 1, depth + 1)?;
464                    j = close;
465                    NormalizedValue::List(inner)
466                }
467                TokenType::RightBracket if elements.is_empty() => return Some((j, elements)),
468                // `literal_value` is the scan's only token vocabulary: a
469                // non-literal is `None`, which declines the group.
470                _ => literal_value(tok)?,
471            };
472            elements.push(element);
473            j += 1;
474            match self.tokens.get(j)?.ty {
475                TokenType::Comma => j += 1,
476                TokenType::RightBracket => return Some((j, elements)),
477                _ => return None,
478            }
479        }
480    }
481
482    /// Build the rewritten statement: the source with every replacement
483    /// span spliced out for its placeholder. The span swallows the
484    /// inter-token whitespace with the literal, so a separator is put back
485    /// only when the next character would glue onto the placeholder
486    /// (`$__AUTO_INT_0__LIMIT` would lex as one name). An operator stays
487    /// where the source put it (`1+2`), which is what a projection's
488    /// column name round-trips from. The spans are in source order by
489    /// construction (the walk appends them in token order and
490    /// `replace_group` covers its whole interior).
491    fn splice(&self) -> String {
492        let mut out = String::with_capacity(self.src.len());
493        let mut cursor = 0;
494        for (start, end, placeholder) in &self.spans {
495            if *start > cursor {
496                out.push_str(&self.src[cursor..*start]);
497            }
498            out.push_str(placeholder);
499            // The span swallowed the original separator. Put one back only
500            // when the next character would otherwise glue to the
501            // placeholder (`$__AUTO_INT_0__LIMIT`). `1+2` keeps its `+`.
502            let glue = self.src[*end..]
503                .chars()
504                .next()
505                .is_some_and(|ch| ch == '$' || ch == '_' || ch.is_ascii_alphanumeric());
506            if glue {
507                out.push(' ');
508            }
509            cursor = *end;
510        }
511        out.push_str(&self.src[cursor..]);
512        out
513    }
514}
515
516/// The per-token function-call-argument context, in one linear pass: a
517/// token is argument territory when the innermost unmatched **paren**
518/// enclosing it is a call's (its callee identifier standing before it).
519/// A paren-only stack answers that in O(1) per token — brackets and
520/// braces are transparent (a map or list nested in an argument list is
521/// still argument territory, its literals feeding the same constant
522/// fold; one outside any call sees an empty or non-call paren stack) —
523/// and closers of a different kind never pop a paren, so the stack stays
524/// exact for parseable input. The precompute replaces a per-literal
525/// rescan of the token prefix (quadratic on the pre-parse lookup path,
526/// found in review) and itself never rescans the stack.
527fn call_argument_context(tokens: &[Token<'_>]) -> Vec<bool> {
528    #[derive(Clone, Copy, PartialEq)]
529    enum Paren {
530        Call,
531        Other,
532    }
533    let mut parens: Vec<Paren> = Vec::new();
534    let mut context = Vec::with_capacity(tokens.len());
535    for (i, tok) in tokens.iter().enumerate() {
536        context.push(parens.last() == Some(&Paren::Call));
537        match tok.ty {
538            TokenType::LeftParen => {
539                let is_call = i > 0 && tokens[i - 1].ty == TokenType::Identifier;
540                parens.push(if is_call { Paren::Call } else { Paren::Other });
541            }
542            TokenType::RightParen => {
543                parens.pop();
544            }
545            // Brackets and braces: transparent — no push, no pop, so a
546            // paren opened inside them still matches its own closer and
547            // the territory answer passes through unchanged.
548            _ => {}
549        }
550    }
551    context
552}
553
554/// The literal value one literal token carries — the one token-to-value
555/// mapping both the run loop's literal arms and the list scan read, with
556/// the same bail policy (`None`, nothing to cache) for anything that does
557/// not decode.
558fn literal_value(tok: &Token) -> Option<NormalizedValue> {
559    match tok.ty {
560        TokenType::Integer => Some(NormalizedValue::Int(parse_int_literal(&tok.literal).ok()?)),
561        TokenType::Float => Some(NormalizedValue::Float(parse_finite_float(&tok.literal)?)),
562        TokenType::String => Some(NormalizedValue::Str(tok.literal.to_string())),
563        _ => None,
564    }
565}
566
567/// Parse a float literal the way the parser's own expression arm does
568/// (CIP-52): a numeric literal that overflows to ±infinity is a
569/// compile-time error, so the statement never parses — `None`, nothing to
570/// cache.
571fn parse_finite_float(literal: &str) -> Option<f64> {
572    let value: f64 = literal.parse().ok()?;
573    value.is_finite().then_some(value)
574}
575
576/// Escape a skipped string's value for its single-quoted template render:
577/// backslash and quote doubled, everything else as-is. The render is
578/// injective on the value (a key string is data, not a spelling), which
579/// is all the template needs from it. The parser crate does not depend
580/// on `relate-core` (which spells this same two-character policy as
581/// its `escape_cypher_string`), so the policy is owned here, at this
582/// boundary, rather than imported.
583fn escape_single_quoted(value: &str) -> String {
584    let mut out = String::with_capacity(value.len());
585    for ch in value.chars() {
586        match ch {
587            '\\' | '\'' => {
588                out.push('\\');
589                out.push(ch);
590            }
591            _ => out.push(ch),
592        }
593    }
594    out
595}
596
597#[cfg(test)]
598#[path = "normalize_tests.rs"]
599mod tests;