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