Skip to main content

nmbrs_workload/
bindpoints.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Bind point detection and field classification.
5//!
6//! Scans op template fields to detect `{name}` bind point references
7//! and `{{expr}}` inline binding definitions. Classifies fields as
8//! static (no bind points) or dynamic (has bind points).
9
10use polydat::ast::PortType;
11
12use crate::op_text::Piece;
13
14/// Namespace qualifier for a bind point reference.
15///
16/// Each namespace has one qualifier word, written lower-case:
17/// `input`, `bind`, `capture`.
18#[derive(Debug, Clone, PartialEq)]
19pub enum BindQualifier {
20    /// No qualifier — resolved by priority: bind → capture → input.
21    None,
22    /// `{input:name}` — graph input value.
23    Input,
24    /// `{bind:name}` — Polydat binding output.
25    Bind,
26    /// `{capture:name}` — capture context (volatile or sticky port).
27    Capture,
28}
29
30impl BindQualifier {
31    /// The qualifier a word names: `input`, `bind` or `capture`.
32    /// `None` for any other word.
33    fn from_word(word: &str) -> Option<Self> {
34        match word {
35            "input" => Some(Self::Input),
36            "bind" => Some(Self::Bind),
37            "capture" => Some(Self::Capture),
38            _ => None,
39        }
40    }
41
42    /// The qualifier word to write in place of `word`, when `word`
43    /// is a spelling that is not one: `coord` and `coordinate` (now
44    /// `input`), `port` (now `capture`), and any other casing of a
45    /// qualifier word (`Bind`). `None` for any other word,
46    /// qualifier words included.
47    fn retired_word(word: &str) -> Option<&'static str> {
48        if Self::from_word(word).is_some() {
49            return None;
50        }
51        match word.to_ascii_lowercase().as_str() {
52            "input" | "coord" | "coordinate" => Some("input"),
53            "bind" => Some("bind"),
54            "capture" | "port" => Some("capture"),
55            _ => None,
56        }
57    }
58}
59
60/// Workload-author lvalue assertion attached to a [`BindPoint::Reference`].
61///
62/// Spelled as a `:<spec>` suffix inside the brace pair:
63///
64/// - `{meta}` — no marker; strict match. The adapter consults
65///   cluster-side metadata and the binder verifies the wire's
66///   rvalue type matches that.
67/// - `{meta:*}` — wildcard. Polydat is licensed to fuse / coerce;
68///   the binder treats the slot as `Str`-lvalue (which permits any
69///   rvalue per the load-bearing rule).
70/// - `{meta:<type>}` — explicit polydat `PortType` assertion. The
71///   binder uses the asserted type as the lvalue for verification,
72///   overriding what cluster-side metadata would say. The type
73///   name is the type's one polydat keyword (`u64`, `i32`, `f64`,
74///   `vec_f32`, `str`, `bytes`, etc.) — the spelling `PortType`'s
75///   `Display` prints.
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum LvalueSpec {
78    /// `:*` — workload-author opt-in to type fusion.
79    Wildcard,
80    /// `:<typename>` — workload-author asserts a polydat
81    /// `PortType` by its keyword. Resolved here, through
82    /// `PortType::from_workload_name`, so an adapter reads the
83    /// asserted type and never parses a type name itself.
84    Explicit(PortType),
85}
86
87/// A detected bind point in an op template field.
88#[derive(Debug, Clone, PartialEq)]
89pub enum BindPoint {
90    /// `{name}`, `{qualifier:name}`, `{name:*}`, or `{name:<type>}` —
91    /// references a named value with an optional lvalue assertion.
92    ///
93    /// `lvalue_spec` is the workload-author opt-in for the
94    /// construction-time binder check. `None` (the default) means
95    /// strict matching against cluster-side metadata. See
96    /// [`LvalueSpec`] for the two relaxation forms.
97    Reference {
98        name: String,
99        qualifier: BindQualifier,
100        lvalue_spec: Option<LvalueSpec>,
101    },
102    /// `{{expr}}` — inline binding definition.
103    InlineDefinition(String),
104}
105
106/// The classification of an op template field value.
107#[derive(Debug, Clone, PartialEq)]
108pub enum FieldType {
109    /// No bind points — value is constant across cycles.
110    Static,
111    /// Pure binding reference — the entire value is `{name}`.
112    BindRef(String),
113    /// String template with interleaved literals and bind points.
114    Template(Vec<BindPoint>),
115}
116
117/// Scan a string value for bind points and classify it. Fails as
118/// [`extract_bind_points`] does.
119pub fn classify_field(value: &str) -> Result<FieldType, String> {
120    let bind_points = extract_bind_points(value)?;
121    Ok(if bind_points.is_empty() {
122        FieldType::Static
123    } else if bind_points.len() == 1
124        && value.starts_with('{')
125        && !value.starts_with("{{")
126        && value.ends_with('}')
127    {
128        match &bind_points[0] {
129            BindPoint::Reference { name, .. } => FieldType::BindRef(name.clone()),
130            _ => FieldType::Template(bind_points),
131        }
132    } else {
133        FieldType::Template(bind_points)
134    })
135}
136
137/// Extract all bind points from a string.
138///
139/// The text is divided by [`crate::op_text::pieces`]: `\{` and `\}`
140/// are literal braces, and a brace that opens a quoted map is literal.
141/// Each `{{ … }}` is an inline definition and each `{ … }` group is
142/// what [`classify_group`] says it is.
143///
144/// Fails when a group is not a bind point (see [`classify_group`]).
145/// The error quotes the group; a caller that knows the op and field
146/// prefixes them.
147pub fn extract_bind_points(value: &str) -> Result<Vec<BindPoint>, String> {
148    let mut points = Vec::new();
149    for piece in crate::op_text::pieces(value) {
150        match piece {
151            Piece::Text(_) | Piece::Brace(_) => {}
152            Piece::Inline { body, .. } => {
153                points.push(BindPoint::InlineDefinition(body.to_string()));
154            }
155            Piece::Group { body, .. } => points.push(classify_group(body)?),
156        }
157    }
158    Ok(points)
159}
160
161/// What a `{ … }` group in an op field is, from its trimmed body:
162///
163/// - `{:=expr}` or `{:=expr:=}`: an inline definition.
164/// - `{name:*}` or `{name:<type>}`: a reference with an lvalue
165///   assertion.
166/// - a body with a call or an operator (`{mod(cycle, 10)}`,
167///   `{a + b}`): an inline definition.
168/// - `{name}`, `{a.b}`, `{input:name}`, `{k_{k}_limits}`: a
169///   reference.
170///
171/// Anything else is refused: a group that is none of these is text
172/// the workload meant literally (a regex quantifier `{8}`, a set
173/// `{0, 1}`, a format spec `{:5.2}`), and reading it as a bind point
174/// would rewrite the field. The error says how to write it as text
175/// and how to write it as an expression.
176///
177/// Also fails on a `{name:<type>}` assertion whose type is a spelling
178/// polydat retired or a type a workload may not assert (see
179/// [`split_lvalue_spec`]), and on a retired qualifier spelling.
180pub fn classify_group(body: &str) -> Result<BindPoint, String> {
181    if let Some(expr) = body.strip_prefix(":=") {
182        let expr = expr.strip_suffix(":=").unwrap_or(expr).trim();
183        return Ok(BindPoint::InlineDefinition(expr.to_string()));
184    }
185    // An lvalue assertion is detected before `is_expression`, so the
186    // `*` of `{name:*}` is not read as multiplication.
187    if let Some((name_part, spec)) = extract_lvalue_spec(body)? {
188        let (qualifier, name) = parse_qualified_ref(name_part)?;
189        return Ok(BindPoint::Reference {
190            name,
191            qualifier,
192            lvalue_spec: Some(spec),
193        });
194    }
195    if is_expression(body) {
196        return Ok(BindPoint::InlineDefinition(body.to_string()));
197    }
198    let (qualifier, name) = parse_qualified_ref(body)?;
199    if !is_reference_name(&name) {
200        return Err(format!(
201            "`{{{body}}}` is not a bind point: its content is neither a name nor \
202             an expression. Write `\\{{{body}\\}}` for literal braces, or \
203             `{{{{{body}}}}}` for an expression"
204        ));
205    }
206    Ok(BindPoint::Reference {
207        name,
208        qualifier,
209        lvalue_spec: None,
210    })
211}
212
213/// Rewrite each inline definition in an op field's text as a
214/// reference: `{{expr}}`, `{:=expr}`, `{:=expr:=}` and a `{expr}`
215/// group [`classify_group`] reads as an expression each become
216/// `{name}`, where `name` is what `name_for` answers for the
217/// expression. A definition `name_for` has no name for, and
218/// everything else, is kept as written, escaped braces included.
219pub fn rewrite_inline_definitions(
220    text: &str,
221    mut name_for: impl FnMut(&str) -> Option<String>,
222) -> String {
223    let mut out = String::with_capacity(text.len());
224    for piece in crate::op_text::pieces(text) {
225        let expr = match piece {
226            Piece::Inline { body, .. } => Some(body.to_string()),
227            Piece::Group { body, .. } => match classify_group(body) {
228                Ok(BindPoint::InlineDefinition(expr)) => Some(expr),
229                _ => None,
230            },
231            Piece::Text(_) | Piece::Brace(_) => None,
232        };
233        match expr.and_then(|expr| name_for(&expr)) {
234            Some(name) => {
235                out.push('{');
236                out.push_str(&name);
237                out.push('}');
238            }
239            None => piece.as_written(&mut out),
240        }
241    }
242    out
243}
244
245/// True when `s` can name a wire in a `{ … }` reference: an
246/// identifier (`name`), a dotted chain of them (`q.cursor.idx`), or
247/// either with `{name}` groups inside it that are filled in before
248/// the name is looked up (`k_{k}_limits`).
249pub fn is_reference_name(s: &str) -> bool {
250    let bytes = s.as_bytes();
251    if bytes.is_empty() {
252        return false;
253    }
254    let mut at = 0;
255    // True where a segment starts: at the beginning and after a dot.
256    let mut segment_start = true;
257    while at < bytes.len() {
258        match bytes[at] {
259            b'{' => {
260                let Some(close) = s[at..].find('}') else {
261                    return false;
262                };
263                if !is_bare_identifier(&s[at + 1..at + close]) {
264                    return false;
265                }
266                at += close + 1;
267                segment_start = false;
268            }
269            b'.' => {
270                if segment_start {
271                    return false;
272                }
273                at += 1;
274                segment_start = true;
275            }
276            b if b.is_ascii_alphabetic() || b == b'_' => {
277                at += 1;
278                segment_start = false;
279            }
280            b if b.is_ascii_digit() => {
281                if segment_start {
282                    return false;
283                }
284                at += 1;
285            }
286            _ => return false,
287        }
288    }
289    !segment_start
290}
291
292/// Detect whether bind point content is a Polydat expression (not a simple name).
293///
294/// Returns true if the content contains operators, function calls,
295/// or other syntax that can't be a plain identifier.
296pub fn is_expression_public(s: &str) -> bool {
297    is_expression(s)
298}
299
300/// Public form of `extract_lvalue_spec` for adapters that need
301/// to interleave bind-point processing with text generation
302/// (e.g., the cassandra-cpp `resolve_structural_and_mark_remaining`
303/// walker, which scans the statement text char-by-char and must
304/// strip a lvalue-spec suffix from a bind-point body before
305/// deciding whether to inline-resolve or `?`-mark the position).
306///
307/// Returns `(bare_name, Some(spec))` when the body carries a
308/// lvalue-spec suffix; `(body, None)` otherwise. The first half
309/// of the tuple is always the body with any `:*` or `:<type>`
310/// suffix stripped.
311///
312/// Fails when the suffix names a type but not one a workload may
313/// assert: a spelling polydat retired (`{id:String}`: "`String` is
314/// no longer a type keyword; write `str`") or an internal-only type
315/// (`handle`, `ext`).
316pub fn split_lvalue_spec(body: &str) -> Result<(&str, Option<LvalueSpec>), String> {
317    Ok(match extract_lvalue_spec(body)? {
318        Some((name_part, spec)) => (name_part, Some(spec)),
319        None => (body, None),
320    })
321}
322
323/// Detect the `:<spec>` lvalue-assertion suffix on a bind-point
324/// body. Returns `Some((name_part, spec))` when the body is the
325/// shape `<bare-identifier>:<*-or-type-keyword>`; `None` when it is
326/// not an lvalue assertion at all; and an error when the suffix is
327/// a type name that cannot be asserted.
328///
329/// Matched explicitly (not as part of `is_expression` or the
330/// general qualifier-parse path) because:
331///
332/// - `:*` would otherwise trip the `*` arm of `is_expression` and
333///   get treated as multiplication.
334/// - `:<typename>` would otherwise get treated as
335///   `<qualifier>:<name>` and the `name` could collide with a
336///   real workload-named wire if both parts looked like
337///   identifiers (e.g. `{input:cycle}` — qualifier `input`, name
338///   `cycle` — must continue to parse as qualifier+name, not as
339///   `name=input, lvalue=cycle`).
340///
341/// Both parts of the split are required to be bare identifiers
342/// for the suffix detection to fire. That's how `{input:cycle}`
343/// (qualifier path) is distinguished from `{meta:i32}` (lvalue-
344/// spec path): the name part `meta` is a bare identifier, the
345/// spec part `i32` is a bare identifier — but the LEFT side of
346/// `input:cycle` matches a known qualifier word, so the existing
347/// qualifier parser claims it first (in the outer dispatch this
348/// helper runs from). Within this helper we don't even check
349/// qualifier-ness — we just require both halves to be bare
350/// identifier shape.
351fn extract_lvalue_spec(raw: &str) -> Result<Option<(&str, LvalueSpec)>, String> {
352    let Some((name_part, spec_part)) = raw.rsplit_once(':') else {
353        return Ok(None);
354    };
355    let name_part = name_part.trim();
356    let spec_part = spec_part.trim();
357    if !is_bare_identifier(name_part) {
358        return Ok(None);
359    }
360    // If the left side is a qualifier (`input`, `bind`,
361    // `capture`), let the qualifier path claim this binding
362    // instead — don't shadow it here. Composition
363    // (`{capture:meta:type}`) is not currently supported; punt on
364    // it cleanly by declining.
365    if BindQualifier::from_word(name_part).is_some() {
366        return Ok(None);
367    }
368    if spec_part == "*" {
369        Ok(Some((name_part, LvalueSpec::Wildcard)))
370    } else if let Some(port_type) = PortType::from_workload_name(spec_part) {
371        Ok(Some((name_part, LvalueSpec::Explicit(port_type))))
372    } else if let Some(retired) = PortType::retired_keyword_message(spec_part) {
373        Err(format!("bind point `{{{raw}}}`: {retired}"))
374    } else if PortType::from_keyword(spec_part).is_some() {
375        Err(format!(
376            "bind point `{{{raw}}}`: `{spec_part}` is an internal type; \
377             a bind point cannot assert it"
378        ))
379    } else {
380        // Suffix isn't `*` or a type name; this is not a
381        // lvalue-spec binding. Fall through so the outer dispatch
382        // lets the reference path claim the whole body.
383        Ok(None)
384    }
385}
386
387/// Bare-identifier shape: ASCII alpha or underscore start; rest
388/// alphanumeric / underscore. Used by [`extract_lvalue_spec`] to
389/// gate the suffix detection on shapes that look like names /
390/// type-words and nothing else, and by the `set:` classifier
391/// (SRD-18f §6) to decide a bare value is a wire reference.
392pub(crate) fn is_bare_identifier(s: &str) -> bool {
393    let mut chars = s.chars();
394    match chars.next() {
395        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
396        _ => return false,
397    }
398    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
399}
400
401fn is_expression(s: &str) -> bool {
402    // A call or an operator. `-` is not one of them: `a-b` reads as a
403    // hyphenated word, which is neither a name nor an expression, and
404    // a subtraction is written `{{a - b}}`. A bare number is not an
405    // expression either: `{8}` is a regex quantifier far more often
406    // than it is the constant 8.
407    s.contains('(')
408        || s.contains(')')
409        || s.contains('+')
410        || s.contains('*')
411        || s.contains('/')
412        || s.contains('%')
413        || s.contains('^')
414        || s.contains('&')
415        || s.contains('|')
416        || s.contains('!')
417        || s.contains('<')
418        || s.contains('>')
419}
420
421/// Parse a qualified reference like "input:cycle" or just "cycle".
422///
423/// A body whose prefix is not a qualifier word stays one
424/// unqualified name. A prefix that is a retired spelling of a
425/// qualifier, before a plain name, is refused with the bind point
426/// to write: "`port` is not a bind-point qualifier; write
427/// `{capture:auth_token}`".
428fn parse_qualified_ref(raw: &str) -> Result<(BindQualifier, String), String> {
429    let Some((prefix, name)) = raw.split_once(':') else {
430        return Ok((BindQualifier::None, raw.to_string()));
431    };
432    let (prefix, name) = (prefix.trim(), name.trim());
433    if let Some(qualifier) = BindQualifier::from_word(prefix) {
434        return Ok((qualifier, name.to_string()));
435    }
436    if let Some(canonical) = BindQualifier::retired_word(prefix)
437        && is_bare_identifier(name)
438    {
439        return Err(format!(
440            "bind point `{{{raw}}}`: `{prefix}` is not a bind-point qualifier; \
441             write `{{{canonical}:{name}}}`"
442        ));
443    }
444    Ok((BindQualifier::None, raw.to_string()))
445}
446
447/// Extract all referenced binding names from a string (only `{name}`, not `{{expr}}`).
448/// Returns the bare name without qualifier. Fails as
449/// [`extract_bind_points`] does.
450pub fn referenced_bindings(value: &str) -> Result<Vec<String>, String> {
451    Ok(extract_bind_points(value)?
452        .into_iter()
453        .filter_map(|bp| match bp {
454            BindPoint::Reference { name, .. } => Some(name),
455            _ => None,
456        })
457        .collect())
458}
459
460/// Replace `{name}` bind point references with `?` markers for
461/// CQL prepared statements. Returns the parameterized statement.
462///
463/// Also strips quotes that immediately surround a bind point:
464/// `'{id}'` → `?` (not `'?'`), because CQL prepared bind markers
465/// must not be inside string literals. Fails as
466/// [`extract_bind_points`] does.
467pub fn replace_bind_points_with_markers(value: &str) -> Result<String, String> {
468    let names = referenced_bindings(value)?;
469    let mut result = value.to_string();
470    for name in &names {
471        // Try quoted form first: '{name}' → ?
472        let quoted = format!("'{{{name}}}'");
473        if let Some(pos) = result.find(&quoted) {
474            result.replace_range(pos..pos + quoted.len(), "?");
475            continue;
476        }
477        // Bare form: {name} → ?
478        let bare = format!("{{{name}}}");
479        if let Some(pos) = result.find(&bare) {
480            result.replace_range(pos..pos + bare.len(), "?");
481        }
482    }
483    Ok(result)
484}
485
486// =================================================================
487// Capture points: [name] and [name as alias] in op template strings
488// =================================================================
489
490/// Row-set aggregation for a declarative capture: reduce an
491/// array-of-rows body (or addressed sub-array) to one scalar by
492/// folding the named field across rows. Declared with a
493/// `:min(field)` / `:max(field)` / `:sum(field)` suffix on the
494/// capture path. Motivating case: `system_views.sstable_tasks`
495/// carries several concurrent tasks in MIXED units (a
496/// byte-denominated data compaction plus an ordinal-denominated
497/// index build) — a `/0/...` capture pins whichever row sorts
498/// first, so a saturated byte task masks the still-running merge;
499/// `:min(completion_ratio)` reads the least-complete task, which
500/// is the drain's true state.
501#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
502pub enum CaptureAgg {
503    /// Numeric minimum of `field` across rows.
504    Min(String),
505    /// Numeric maximum of `field` across rows.
506    Max(String),
507    /// Numeric sum of `field` across rows.
508    Sum(String),
509}
510
511/// A capture point extracted from an op template.
512///
513/// Capture points mark result fields that should be extracted from
514/// the operation result and stored as named variables for use in
515/// subsequent operations or verification.
516///
517/// Formats:
518/// - `[username]` — capture "username" as "username" (single value)
519/// - `[username as u1]` — capture "username", store as "u1" (single value)
520/// - `[(List) field]` — capture with type assertion
521/// - `[*]` — capture all available fields
522/// - `[@keys]` — **slurp**: collect every row's `keys` column into
523///   a `Value::Json` array. Use when the result has multiple rows
524///   and the consumer needs all per-row column values as a list
525///   (e.g. recall-evaluator's `actual:` reads).
526/// - `[@col as values]` — slurp with alias.
527#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
528pub struct CapturePoint {
529    /// The field name to capture from the result.
530    pub source_name: String,
531    /// The variable name to store the captured value under.
532    /// Same as source_name if no `as` clause.
533    pub as_name: String,
534    /// Optional type assertion (e.g., "List", "int[]").
535    #[serde(default, skip_serializing_if = "Option::is_none")]
536    pub cast_type: Option<String>,
537    /// `true` when the capture-point was declared with the `@`
538    /// slurp prefix (`[@name]`). Slurp captures collect every
539    /// row's column value across the result body into a single
540    /// `Value::Json` array; non-slurp captures take the first
541    /// row's value as a scalar.
542    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
543    pub slurp: bool,
544    /// Optional JSON-Pointer path (RFC 6901, e.g. `/0/value`,
545    /// `/value/inner/0`). When `Some`, the extractor uses
546    /// `serde_json::Value::pointer(path)` against the body's
547    /// `to_json()` projection rather than the first-row /
548    /// top-level field lookup keyed by `source_name`. Lets a
549    /// declarative `capture:` map address Jolokia bulk-POST
550    /// responses (`[{value:N}, {value:[...]}, ...]`) by
551    /// position + nested field.
552    ///
553    /// The bracket-syntax in op text (e.g. `[name]`) leaves
554    /// this `None` and continues to use the original first-row
555    /// extraction path; only the declarative `capture:` block
556    /// populates it.
557    #[serde(default, skip_serializing_if = "Option::is_none")]
558    pub path: Option<String>,
559    /// Reduce the extracted sub-tree to a u64 count instead of
560    /// capturing it as-is. Array → length; object → key count;
561    /// scalar (number / bool / non-empty string) → 1; null /
562    /// missing → 0. Useful for "is the compactions list empty"
563    /// style predicates without binding the array into the
564    /// kernel as a `Value::Json`. Only honoured when `path` is
565    /// also set (declarative capture form).
566    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
567    pub count: bool,
568    /// Row-set aggregation (`:min(f)` / `:max(f)` / `:sum(f)`
569    /// path suffix): fold the named field across the rows of the
570    /// addressed array instead of capturing a single value. Like
571    /// `count`, only honoured on the declarative capture form.
572    #[serde(default, skip_serializing_if = "Option::is_none")]
573    pub agg: Option<CaptureAgg>,
574    /// Row predicate for an aggregate: `(field, value)`, from the
575    /// `where <field>='<value>'` clause of a capture suffix — e.g.
576    /// `":sum(progress where kind='secondary index build')"`. Rows whose
577    /// `field` does not equal `value` are excluded before folding.
578    ///
579    /// Exists because a result set can hold rows that are not commensurable.
580    /// `system_views.sstable_tasks` lists a data compaction reporting
581    /// `unit=bytes` beside a vector index build reporting
582    /// `unit=token range parts`; summing across them adds unlike quantities,
583    /// and the total silently depends on how many tasks were registered at
584    /// sample time. The predicate cannot live in the query — Cassandra allows
585    /// `GROUP BY` only on PRIMARY KEY columns, and narrowing the poll's own
586    /// `WHERE` would change which rows the drain waits for.
587    #[serde(default, skip_serializing_if = "Option::is_none")]
588    pub row_filter: Option<(String, String)>,
589}
590
591/// Result of parsing capture points from a string.
592#[derive(Debug, Clone)]
593pub struct CaptureParseResult {
594    /// The raw template with capture brackets removed.
595    /// `select [username] from t` → `select username from t`
596    pub raw_template: String,
597    /// The capture points found.
598    pub captures: Vec<CapturePoint>,
599}
600
601/// Parse capture points from an op template string.
602///
603/// Detects `[name]`, `[name as alias]`, `[(Type) name]`, and `[*]`
604/// patterns. Returns the cleaned template (brackets removed) and
605/// the list of capture points.
606pub fn parse_capture_points(template: &str) -> CaptureParseResult {
607    let mut captures = Vec::new();
608    let mut raw = String::with_capacity(template.len());
609    let chars: Vec<char> = template.chars().collect();
610    let mut i = 0;
611
612    while i < chars.len() {
613        if chars[i] == '[' {
614            let bracket_start = i;
615            let attempt_start = i + 1;
616            i = attempt_start;
617
618            // Speculatively parse a capture-point spec. If anything
619            // about the grammar fails to match — including the
620            // source name being absent or not starting with an
621            // identifier character — we reset to `bracket_start + 1`
622            // and emit the `[` as a literal. This keeps JSON / CQL
623            // array literals (`[]`, `["foo", 42]`), JNI type
624            // signatures (`[Ljava.lang.String;`), and other uses of
625            // `[...]` from being silently consumed.
626
627            // Skip whitespace
628            while i < chars.len() && chars[i].is_whitespace() {
629                i += 1;
630            }
631
632            // Optional type cast: (Type)
633            let cast_type = if i < chars.len() && chars[i] == '(' {
634                i += 1;
635                let cast_start = i;
636                while i < chars.len() && chars[i] != ')' {
637                    i += 1;
638                }
639                let cast: String = chars[cast_start..i].iter().collect();
640                if i < chars.len() {
641                    i += 1;
642                } // skip ')'
643                while i < chars.len() && chars[i].is_whitespace() {
644                    i += 1;
645                }
646                Some(cast.trim().to_string())
647            } else {
648                None
649            };
650
651            // Optional slurp modifier: `[@name]` collects every
652            // row's column value into a `Value::Json` array. The
653            // `@` is a syntax-only marker — stripped from the
654            // emitted raw_template so the adapter sees clean
655            // column-reference text.
656            let slurp = if i < chars.len() && chars[i] == '@' {
657                i += 1;
658                while i < chars.len() && chars[i].is_whitespace() {
659                    i += 1;
660                }
661                true
662            } else {
663                false
664            };
665
666            // Source name — must look like a real identifier (or
667            // `*` for wildcard). Starts with `_` or an ASCII alpha
668            // character; continues with alphanumerics, `_`, `-`,
669            // `.`, or `*`. The strict-leading-char rule prevents
670            // JSON array literals like `["..."]`, `[42]`, and JNI
671            // signatures like `[Ljava.lang.String;` from being
672            // misread as captures.
673            let name_start = i;
674            if i < chars.len() {
675                let first = chars[i];
676                let is_valid_first = first.is_ascii_alphabetic() || first == '_' || first == '*';
677                if !is_valid_first {
678                    // Not a capture-point opening — emit `[` and
679                    // resume one char in.
680                    raw.push('[');
681                    i = attempt_start;
682                    continue;
683                }
684            }
685            while i < chars.len()
686                && (chars[i].is_alphanumeric()
687                    || chars[i] == '_'
688                    || chars[i] == '-'
689                    || chars[i] == '.'
690                    || chars[i] == '*')
691            {
692                i += 1;
693            }
694            let source_name: String = chars[name_start..i].iter().collect();
695            if source_name.is_empty() {
696                // Defense-in-depth — the leading-char check above
697                // already excludes this path, but keep it explicit.
698                raw.push('[');
699                i = attempt_start;
700                continue;
701            }
702
703            // Optional "as alias"
704            while i < chars.len() && chars[i].is_whitespace() {
705                i += 1;
706            }
707            let as_name = if i + 2 < chars.len()
708                && (chars[i] == 'a' || chars[i] == 'A')
709                && (chars[i + 1] == 's' || chars[i + 1] == 'S')
710                && chars[i + 2].is_whitespace()
711            {
712                i += 2; // skip "as"
713                while i < chars.len() && chars[i].is_whitespace() {
714                    i += 1;
715                }
716                let alias_start = i;
717                while i < chars.len()
718                    && (chars[i].is_alphanumeric()
719                        || chars[i] == '_'
720                        || chars[i] == '-'
721                        || chars[i] == '.')
722                {
723                    i += 1;
724                }
725                let alias: String = chars[alias_start..i].iter().collect();
726                alias
727            } else {
728                source_name.clone()
729            };
730
731            // Skip whitespace and closing bracket
732            while i < chars.len() && chars[i].is_whitespace() {
733                i += 1;
734            }
735            if i < chars.len() && chars[i] == ']' {
736                i += 1;
737                captures.push(CapturePoint {
738                    // Bracket syntax carries no aggregate, so no predicate.
739                    row_filter: None,
740                    source_name: source_name.clone(),
741                    as_name,
742                    cast_type,
743                    slurp,
744                    path: None,
745                    count: false,
746                    agg: None,
747                });
748                // Emit source name without brackets into raw template
749                raw.push_str(&source_name);
750            } else {
751                // No matching `]` for what otherwise looked like a
752                // capture spec — likely a CQL/JSON array containing
753                // an identifier (e.g. `[foo, bar]`). Treat the
754                // opening `[` as a literal and resume one char in.
755                let _ = bracket_start;
756                raw.push('[');
757                i = attempt_start;
758            }
759        } else {
760            raw.push(chars[i]);
761            i += 1;
762        }
763    }
764
765    CaptureParseResult {
766        raw_template: raw,
767        captures,
768    }
769}
770
771#[cfg(test)]
772mod tests {
773    use super::*;
774
775    /// `{name:<type>}` resolves the type through polydat's keyword
776    /// table, so every keyword a workload author may assert is an
777    /// lvalue spec, and the internal-only `handle` and `ext` are not.
778    #[test]
779    fn lvalue_spec_resolves_polydat_type_keywords() {
780        for (body, expected) in [
781            ("meta:i32", PortType::I32),
782            ("id:str", PortType::Str),
783            ("emb:vec_f32", PortType::VecF32),
784            ("ids:vec_i64", PortType::VecI64),
785        ] {
786            let (name, spec) = split_lvalue_spec(body).unwrap();
787            assert_eq!(spec, Some(LvalueSpec::Explicit(expected)), "{body}");
788            assert_eq!(Some(name), body.split(':').next(), "{body}");
789        }
790        assert_eq!(
791            split_lvalue_spec("meta:*").unwrap(),
792            ("meta", Some(LvalueSpec::Wildcard))
793        );
794        assert_eq!(
795            split_lvalue_spec("host:auth_token").unwrap(),
796            ("host:auth_token", None)
797        );
798    }
799
800    /// A suffix that names a type a workload may not assert is
801    /// refused, quoting the bind point: a spelling polydat retired
802    /// with the keyword to write, an internal-only type as such.
803    #[test]
804    fn lvalue_spec_refuses_a_type_that_cannot_be_asserted() {
805        assert_eq!(
806            extract_bind_points("WHERE id = {id:String}"),
807            Err(
808                "bind point `{id:String}`: `String` is no longer a type keyword; write `str`"
809                    .to_string()
810            )
811        );
812        for (body, typ) in [("h:handle", "handle"), ("p:ext", "ext")] {
813            assert_eq!(
814                split_lvalue_spec(body),
815                Err(format!(
816                    "bind point `{{{body}}}`: `{typ}` is an internal type; \
817                     a bind point cannot assert it"
818                )),
819            );
820        }
821        assert!(referenced_bindings("{id:Json}").is_err());
822        assert!(classify_field("{id:Str}").is_err());
823        assert!(replace_bind_points_with_markers("{id:Ext}").is_err());
824    }
825
826    #[test]
827    fn is_expression_detects_function_calls() {
828        assert!(is_expression("hash(cycle)"));
829        assert!(is_expression("mod(x, 100)"));
830    }
831
832    #[test]
833    fn is_expression_detects_operators() {
834        assert!(is_expression("x + 1"));
835        assert!(is_expression("a * b"));
836        assert!(is_expression("x & 0xFF"));
837    }
838
839    #[test]
840    fn is_expression_rejects_simple_names() {
841        assert!(!is_expression("cycle"));
842        assert!(!is_expression("my_var"));
843        assert!(!is_expression("user_id"));
844    }
845
846    /// A bare number is not an expression: `{8}` is a regex
847    /// quantifier, not the constant 8.
848    #[test]
849    fn a_bare_number_is_not_an_expression() {
850        assert!(!is_expression("42"));
851        assert!(!is_expression("3.14"));
852        assert!(!is_expression("-5"));
853        assert!(is_expression("2 * n"));
854    }
855
856    /// A group that is neither a name nor an expression is refused,
857    /// with both ways to write what was meant.
858    #[test]
859    fn a_group_that_is_not_a_bind_point_is_refused() {
860        for body in [
861            "8",
862            "2,3",
863            "0, 1, 2",
864            ":5.2",
865            "my-variable",
866            "a b",
867            "a - b",
868            "host:auth_token",
869        ] {
870            let err = extract_bind_points(&format!("x {{{body}}} y")).unwrap_err();
871            assert_eq!(
872                err,
873                format!(
874                    "`{{{body}}}` is not a bind point: its content is neither a name nor \
875                     an expression. Write `\\{{{body}\\}}` for literal braces, or \
876                     `{{{{{body}}}}}` for an expression"
877                ),
878            );
879        }
880    }
881
882    /// `\{` and `\}` are literal braces: what is between them is not
883    /// a bind point, and a bind point beside them still is.
884    #[test]
885    fn escaped_braces_hold_no_bind_point() {
886        assert_eq!(classify_field(r"^\d\{8\}$").unwrap(), FieldType::Static);
887        assert_eq!(
888            referenced_bindings(r"^\d\{2,3\}-{node}\.log$").unwrap(),
889            vec!["node"]
890        );
891        assert_eq!(classify_field(r"\{name\}").unwrap(), FieldType::Static);
892    }
893
894    #[test]
895    fn reference_names() {
896        for name in ["a", "_a1", "q.cursor.idx", "k_{k}_limits", "{profile}_rows"] {
897            assert!(is_reference_name(name), "{name}");
898        }
899        for name in [
900            "", "8", "a-b", "a b", ".a", "a.", "a..b", "a.1", "k_{k", "k_{1}", ":x",
901        ] {
902            assert!(!is_reference_name(name), "{name}");
903        }
904    }
905
906    #[test]
907    fn static_field() {
908        assert_eq!(classify_field("plain text").unwrap(), FieldType::Static);
909        assert_eq!(classify_field("42").unwrap(), FieldType::Static);
910        assert_eq!(classify_field("").unwrap(), FieldType::Static);
911    }
912
913    #[test]
914    fn pure_bind_ref() {
915        assert_eq!(
916            classify_field("{userid}").unwrap(),
917            FieldType::BindRef("userid".into())
918        );
919    }
920
921    #[test]
922    fn template_with_bind_points() {
923        let ft = classify_field("SELECT * FROM t WHERE id={id} AND name={name}").unwrap();
924        match ft {
925            FieldType::Template(points) => {
926                assert_eq!(points.len(), 2);
927                assert_eq!(
928                    points[0],
929                    BindPoint::Reference {
930                        name: "id".into(),
931                        qualifier: BindQualifier::None,
932                        lvalue_spec: None
933                    }
934                );
935                assert_eq!(
936                    points[1],
937                    BindPoint::Reference {
938                        name: "name".into(),
939                        qualifier: BindQualifier::None,
940                        lvalue_spec: None
941                    }
942                );
943            }
944            _ => panic!("expected Template"),
945        }
946    }
947
948    #[test]
949    fn inline_definition() {
950        let ft = classify_field("value is {{Template('user-{}', ToString())}}").unwrap();
951        match ft {
952            FieldType::Template(points) => {
953                assert_eq!(points.len(), 1);
954                match &points[0] {
955                    BindPoint::InlineDefinition(expr) => {
956                        assert!(expr.contains("Template"));
957                    }
958                    _ => panic!("expected InlineDefinition"),
959                }
960            }
961            _ => panic!("expected Template"),
962        }
963    }
964
965    #[test]
966    fn mixed_references_and_literals() {
967        let refs = referenced_bindings("INSERT INTO t (a, b) VALUES ({col_a}, {col_b})").unwrap();
968        assert_eq!(refs, vec!["col_a", "col_b"]);
969    }
970
971    #[test]
972    fn no_bind_points() {
973        let refs = referenced_bindings("just a plain string").unwrap();
974        assert!(refs.is_empty());
975    }
976
977    // --- Qualified bind point tests ---
978
979    #[test]
980    fn qualified_input() {
981        let points = extract_bind_points("{input:cycle}").unwrap();
982        assert_eq!(points.len(), 1);
983        assert_eq!(
984            points[0],
985            BindPoint::Reference {
986                name: "cycle".into(),
987                qualifier: BindQualifier::Input,
988                lvalue_spec: None,
989            }
990        );
991    }
992
993    #[test]
994    fn qualified_capture() {
995        let points = extract_bind_points("{capture:balance}").unwrap();
996        assert_eq!(points.len(), 1);
997        assert_eq!(
998            points[0],
999            BindPoint::Reference {
1000                name: "balance".into(),
1001                qualifier: BindQualifier::Capture,
1002                lvalue_spec: None,
1003            }
1004        );
1005    }
1006
1007    #[test]
1008    fn qualified_bind() {
1009        let points = extract_bind_points("{bind:user_id}").unwrap();
1010        assert_eq!(points.len(), 1);
1011        assert_eq!(
1012            points[0],
1013            BindPoint::Reference {
1014                name: "user_id".into(),
1015                qualifier: BindQualifier::Bind,
1016                lvalue_spec: None,
1017            }
1018        );
1019    }
1020
1021    #[test]
1022    fn unqualified_still_works() {
1023        let points = extract_bind_points("{user_id}").unwrap();
1024        assert_eq!(
1025            points[0],
1026            BindPoint::Reference {
1027                name: "user_id".into(),
1028                qualifier: BindQualifier::None,
1029                lvalue_spec: None,
1030            }
1031        );
1032    }
1033
1034    #[test]
1035    fn qualified_referenced_bindings_returns_bare_name() {
1036        let refs =
1037            referenced_bindings("VALUES ({input:cycle}, {capture:balance}, {user_id})").unwrap();
1038        assert_eq!(refs, vec!["cycle", "balance", "user_id"]);
1039    }
1040
1041    /// Each namespace has one qualifier word; a retired spelling of
1042    /// one is refused with the bind point to write.
1043    #[test]
1044    fn a_retired_qualifier_spelling_is_refused_naming_the_qualifier() {
1045        for (body, write) in [
1046            ("coord:cycle", "input:cycle"),
1047            ("coordinate:row", "input:row"),
1048            ("port:auth_token", "capture:auth_token"),
1049            ("Bind:user_id", "bind:user_id"),
1050        ] {
1051            let prefix = body.split(':').next().unwrap();
1052            assert_eq!(
1053                extract_bind_points(&format!("VALUES ({{{body}}})")),
1054                Err(format!(
1055                    "bind point `{{{body}}}`: `{prefix}` is not a bind-point qualifier; \
1056                     write `{{{write}}}`"
1057                )),
1058            );
1059        }
1060        // A wire that happens to be named like a retired qualifier
1061        // still takes an lvalue assertion.
1062        assert_eq!(
1063            split_lvalue_spec("port:u64").unwrap(),
1064            ("port", Some(LvalueSpec::Explicit(PortType::U64)))
1065        );
1066    }
1067
1068    // --- Capture point tests ---
1069
1070    #[test]
1071    fn capture_simple() {
1072        let result = parse_capture_points("select [username] from users where id={id}");
1073        assert_eq!(result.captures.len(), 1);
1074        assert_eq!(result.captures[0].source_name, "username");
1075        assert_eq!(result.captures[0].as_name, "username");
1076        assert_eq!(
1077            result.raw_template,
1078            "select username from users where id={id}"
1079        );
1080    }
1081
1082    #[test]
1083    fn capture_with_alias() {
1084        let result = parse_capture_points("select [username as u1] from users");
1085        assert_eq!(result.captures.len(), 1);
1086        assert_eq!(result.captures[0].source_name, "username");
1087        assert_eq!(result.captures[0].as_name, "u1");
1088        assert_eq!(result.raw_template, "select username from users");
1089    }
1090
1091    #[test]
1092    fn capture_with_type_cast() {
1093        let result = parse_capture_points("select [(List) items] from orders");
1094        assert_eq!(result.captures.len(), 1);
1095        assert_eq!(result.captures[0].source_name, "items");
1096        assert_eq!(result.captures[0].cast_type, Some("List".into()));
1097    }
1098
1099    #[test]
1100    fn capture_wildcard() {
1101        let result = parse_capture_points("select [*] from users");
1102        assert_eq!(result.captures.len(), 1);
1103        assert_eq!(result.captures[0].source_name, "*");
1104    }
1105
1106    #[test]
1107    fn capture_empty_brackets_pass_through() {
1108        // `[]` (empty JSON array literal) is NOT a capture point.
1109        // The parser must emit it verbatim — eating the brackets
1110        // would break Jolokia payloads like
1111        // `"arguments":["foo",[]]` which became `"arguments":["foo",]`
1112        // (invalid JSON, JMX op gets 1 arg instead of 2).
1113        let result = parse_capture_points(r#"{"arguments":["foo",[]]}"#);
1114        assert!(
1115            result.captures.is_empty(),
1116            "no capture should be extracted: {:?}",
1117            result.captures
1118        );
1119        assert_eq!(result.raw_template, r#"{"arguments":["foo",[]]}"#);
1120    }
1121
1122    #[test]
1123    fn capture_jni_array_signature_pass_through() {
1124        // JNI array signature `[Ljava.lang.String;` opens with `[`
1125        // but is not a capture point (no closing `]` follows the
1126        // identifier chunk). The parser must not consume anything.
1127        let template = r#""operation":"forceKeyspaceFlush(java.lang.String,[Ljava.lang.String;)""#;
1128        let result = parse_capture_points(template);
1129        assert!(
1130            result.captures.is_empty(),
1131            "JNI signature should not parse as capture: {:?}",
1132            result.captures
1133        );
1134        assert_eq!(result.raw_template, template);
1135    }
1136
1137    #[test]
1138    fn capture_json_array_with_string_pass_through() {
1139        // JSON string-array literal — opens `[`, content begins
1140        // with `"`, no identifier; parser must leave it alone.
1141        let result = parse_capture_points(r#"["alpha","beta"]"#);
1142        assert!(result.captures.is_empty());
1143        assert_eq!(result.raw_template, r#"["alpha","beta"]"#);
1144    }
1145
1146    #[test]
1147    fn capture_json_array_with_number_pass_through() {
1148        // Numeric-literal-only array — leading digit is not a
1149        // valid identifier start, so no capture is extracted.
1150        let result = parse_capture_points("[42]");
1151        assert!(result.captures.is_empty());
1152        assert_eq!(result.raw_template, "[42]");
1153    }
1154
1155    #[test]
1156    fn capture_cql_collection_literal_pass_through() {
1157        // CQL collection literal like `[1, 2, 3]` — content has
1158        // digits + commas, not a valid capture spec. Must
1159        // pass through verbatim.
1160        let template = "INSERT INTO t (vals) VALUES ([1, 2, 3])";
1161        let result = parse_capture_points(template);
1162        assert!(result.captures.is_empty());
1163        assert_eq!(result.raw_template, template);
1164    }
1165
1166    #[test]
1167    fn capture_multiple() {
1168        let result = parse_capture_points("select [a], [b as x] from t where id={id}");
1169        assert_eq!(result.captures.len(), 2);
1170        assert_eq!(result.captures[0].source_name, "a");
1171        assert_eq!(result.captures[0].as_name, "a");
1172        assert_eq!(result.captures[1].source_name, "b");
1173        assert_eq!(result.captures[1].as_name, "x");
1174    }
1175
1176    #[test]
1177    fn capture_no_captures() {
1178        let result = parse_capture_points("select * from users where id={id}");
1179        assert!(result.captures.is_empty());
1180        assert_eq!(result.raw_template, "select * from users where id={id}");
1181    }
1182
1183    #[test]
1184    fn capture_mixed_with_bind_points() {
1185        let result =
1186            parse_capture_points("select [name], [age as user_age] from users where id={userid}");
1187        assert_eq!(result.captures.len(), 2);
1188        // Bind point {userid} should remain in the raw template
1189        assert!(result.raw_template.contains("{userid}"));
1190        // Capture brackets should be removed
1191        assert!(!result.raw_template.contains('['));
1192        assert!(!result.raw_template.contains(']'));
1193    }
1194}