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