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