Skip to main content

vibe/stdlib_v2/text_and_collections/
mod.rs

1//! VibeScript v0.02 (`vibe-0.2`) Text Processing, Linear-Time Thompson NFA Regex,
2//! Immutable Collections & Core Data Structures (`str.*`, `regex.*`, `list.*`, `deque.*`,
3//! `pqueue.*`, `set.*`).
4//!
5//! Directory-backed library structure (`AGENTS.md` ยง0-B):
6//! - `grapheme_str`: UAX #29 extended grapheme cluster strings (`str.*`)
7//! - `linear_regex`: Stateless $O(n)$ non-backtracking Thompson NFA regex (`regex.*`)
8//! - `collections`: Immutable collections, natural sort, seeded shuffle, deque, priority queue,
9//!   and structural-value sets (`list.*`, `deque.*`, `pqueue.*`, `set.*`)
10
11pub mod collections;
12pub mod grapheme_str;
13pub mod linear_regex;
14
15pub use grapheme_str::split_graphemes;
16
17use crate::error::{DiagCode, Diagnostic};
18use crate::span::Span;
19use crate::value::Value;
20
21/// All stdlib v2 binding paths handled by `text_and_collections`.
22pub const TEXT_AND_COLLECTIONS_BINDINGS: &[&str] = &[
23    "str.graphemes",
24    "str.grapheme_len",
25    "str.grapheme_at",
26    "str.grapheme_slice",
27    "str.code_points",
28    "str.bytes",
29    "str.trim",
30    "str.trim_start",
31    "str.trim_end",
32    "str.pad_start",
33    "str.pad_end",
34    "str.split",
35    "str.join",
36    "str.replace_literal",
37    "str.starts_with",
38    "str.ends_with",
39    "str.contains",
40    "str.to_upper",
41    "str.to_lower",
42    "regex.compile",
43    "regex.is_match",
44    "regex.find",
45    "regex.find_all",
46    "regex.replace_all",
47    "list.range",
48    "list.at",
49    "list.slice",
50    "list.sort_natural",
51    "list.chunk",
52    "list.windows",
53    "list.zip",
54    "list.unzip",
55    "list.enumerate",
56    "list.partition",
57    "list.uniq",
58    "list.uniq_by",
59    "list.intersperse",
60    "list.flatten",
61    "list.shuffle_seeded",
62    "deque.new",
63    "deque.push_front",
64    "deque.push_back",
65    "deque.pop_front",
66    "deque.pop_back",
67    "pqueue.new",
68    "pqueue.push",
69    "pqueue.pop_min",
70    "pqueue.pop_max",
71    "set.from_list",
72    "set.union",
73    "set.intersection",
74    "set.difference",
75    "set.symmetric_difference",
76    "set.is_subset",
77    "set.is_disjoint",
78];
79
80/// Route a `str.*`, `regex.*`, `list.*`, `deque.*`, `pqueue.*`, or `set.*` call.
81pub fn call_text_and_collections(
82    path: &str,
83    args: &[Value],
84    span: Span,
85) -> Result<Option<Value>, Diagnostic> {
86    if path.starts_with("str.") {
87        return grapheme_str::call_grapheme_str(path, args, span);
88    }
89    if path.starts_with("regex.") {
90        return linear_regex::call_linear_regex(path, args, span);
91    }
92    if path.starts_with("list.")
93        || path.starts_with("deque.")
94        || path.starts_with("pqueue.")
95        || path.starts_with("set.")
96    {
97        return collections::call_collections(path, args, span);
98    }
99    Ok(None)
100}
101
102pub(crate) fn extract_str(
103    args: &[Value],
104    idx: usize,
105    ctx: &str,
106    span: Span,
107) -> Result<String, Diagnostic> {
108    match args.get(idx) {
109        Some(Value::String(s)) | Some(Value::Iri(s)) => Ok(s.clone()),
110        _ => Err(Diagnostic::new(
111            DiagCode::E100,
112            span,
113            format!("{ctx}: argument #{idx} must be a string"),
114        )),
115    }
116}
117
118pub(crate) fn extract_i64(
119    args: &[Value],
120    idx: usize,
121    ctx: &str,
122    span: Span,
123) -> Result<i64, Diagnostic> {
124    args.get(idx).and_then(Value::as_i64).ok_or_else(|| {
125        Diagnostic::new(
126            DiagCode::E100,
127            span,
128            format!("{ctx}: argument #{idx} must be an integer"),
129        )
130    })
131}
132
133pub(crate) fn extract_opt_i64(args: &[Value], idx: usize) -> Option<i64> {
134    match args.get(idx) {
135        Some(Value::Null) | None => None,
136        Some(v) => v.as_i64(),
137    }
138}
139
140pub(crate) fn extract_list(
141    args: &[Value],
142    idx: usize,
143    ctx: &str,
144    span: Span,
145) -> Result<Vec<Value>, Diagnostic> {
146    match args.get(idx) {
147        Some(Value::List(xs)) => Ok(xs.clone()),
148        _ => Err(Diagnostic::new(
149            DiagCode::E100,
150            span,
151            format!("{ctx}: argument #{idx} must be a list"),
152        )),
153    }
154}
155
156/// Resolve a signed index (supporting `-1` = last element) to an in-bounds `usize`.
157pub(crate) fn resolve_element_index(idx: i64, len: usize) -> Option<usize> {
158    let n = len as i64;
159    let resolved = if idx < 0 { n + idx } else { idx };
160    if resolved >= 0 && resolved < n {
161        Some(resolved as usize)
162    } else {
163        None
164    }
165}
166
167/// Clamp and resolve a slice bound (supporting negative indices) into `0..=len`.
168pub(crate) fn resolve_slice_bound(bound: i64, len: usize) -> usize {
169    let n = len as i64;
170    let resolved = if bound < 0 { n + bound } else { bound };
171    resolved.clamp(0, n) as usize
172}