Skip to main content

vibe/web_runtime/
validation.rs

1//! Constraint Validation API (`ValidityState`), form-level validation, cross-field relational
2//! invariants, and Belnap 4-valued paraconsistent ($E_\tau$) conflict evaluation
3//! (`validate.*` stdlib bindings for VibeScript v0.02 Zero-JS UI).
4
5use std::collections::BTreeMap;
6
7use crate::error::{DiagCode, Diagnostic};
8use crate::quantity::UnitId;
9use crate::span::Span;
10use crate::value::Value;
11
12/// Dispatch a `validate.*` call in the VibeScript engine.
13pub fn call_validation(
14    path: &str,
15    args: &[Value],
16    span: Span,
17) -> Result<Option<Value>, Diagnostic> {
18    match path {
19        "validate.check_field" => eval_check_field(args, span).map(Some),
20        "validate.check_form" => eval_check_form(args, span).map(Some),
21        "validate.cross_field" => eval_cross_field(args, span).map(Some),
22        "validate.paraconsistent" => eval_paraconsistent(args, span).map(Some),
23        _ => Ok(None),
24    }
25}
26
27/// `validate.check_field(value: Value, rules: Record)`
28pub fn eval_check_field(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
29    let value = args.first().unwrap_or(&Value::Null);
30    let Some(Value::Record(rules)) = args.get(1) else {
31        return Err(Diagnostic::new(
32            DiagCode::E100,
33            span,
34            "validate.check_field: argument #1 (rules) must be a Record",
35        ));
36    };
37    Ok(Value::Record(check_field_against_rules(value, rules)))
38}
39
40pub(crate) fn check_field_against_rules(
41    value: &Value,
42    rules: &BTreeMap<String, Value>,
43) -> BTreeMap<String, Value> {
44    let required = matches!(rules.get("required"), Some(Value::Bool(true)));
45    let is_empty = match value {
46        Value::Null | Value::Bool(false) => true,
47        Value::String(s) | Value::Iri(s) => s.trim().is_empty(),
48        Value::List(xs) => xs.is_empty(),
49        _ => false,
50    };
51
52    let value_missing = required && is_empty;
53    let (mut type_mismatch, mut pattern_mismatch, mut too_short, mut too_long) =
54        (false, false, false, false);
55    let (mut range_underflow, mut range_overflow, mut step_mismatch, mut unit_mismatch) =
56        (false, false, false, false);
57    let mut bad_input = matches!(rules.get("bad_input"), Some(Value::Bool(true)));
58    let custom_err_msg = match rules.get("custom_error") {
59        Some(Value::String(s)) if !s.is_empty() => Some(s.clone()),
60        Some(Value::Bool(true)) => Some("Custom validation error".to_string()),
61        _ => None,
62    };
63    let custom_error = custom_err_msg.is_some();
64
65    if !is_empty {
66        if let Some(Value::String(t)) = rules
67            .get("type")
68            .or_else(|| rules.get("kind"))
69            .or_else(|| rules.get("data_type"))
70        {
71            let s_opt = match value {
72                Value::String(s) | Value::Iri(s) => Some(s.as_str()),
73                _ => None,
74            };
75            match t.as_str() {
76                "email" => type_mismatch = !s_opt.is_some_and(is_valid_email),
77                "url" | "iri" => type_mismatch = !s_opt.is_some_and(is_valid_iri),
78                "did" => type_mismatch = !s_opt.is_some_and(is_valid_did),
79                "tel" => type_mismatch = !s_opt.is_some_and(is_valid_tel),
80                "number" => {
81                    let ok = matches!(value, Value::I64(_) | Value::U64(_) | Value::Quantity(_))
82                        || matches!(value, Value::F64(n) if !n.is_nan())
83                        || s_opt.is_some_and(|s| s.trim().parse::<f64>().is_ok());
84                    if !ok {
85                        bad_input = true;
86                        type_mismatch = true;
87                    }
88                }
89                _ => {}
90            }
91        }
92        if let Value::String(s) | Value::Iri(s) = value {
93            let n = s.chars().count() as i64;
94            too_short = rules.get("min_length").and_then(Value::as_i64).is_some_and(|lo| n < lo);
95            too_long = rules.get("max_length").and_then(Value::as_i64).is_some_and(|hi| n > hi);
96            if let Some(Value::String(pat)) = rules.get("pattern") {
97                pattern_mismatch = !pat.is_empty() && !matches_simple_pattern(s, pat);
98            }
99        }
100        let num_val = value.as_f64().or_else(|| match value {
101            Value::String(s) => s.trim().parse::<f64>().ok(),
102            Value::Instant(i) => Some(i.secs as f64),
103            _ => None,
104        });
105        if let Some(num) = num_val {
106            let min_b = rules.get("min").and_then(Value::as_f64);
107            let max_b = rules.get("max").and_then(Value::as_f64);
108            range_underflow = min_b.is_some_and(|lo| num < lo);
109            range_overflow = max_b.is_some_and(|hi| num > hi);
110            if let Some(step) = rules.get("step").and_then(Value::as_f64).filter(|&s| s > 0.0) {
111                let rem = ((num - min_b.unwrap_or(0.0)) / step).fract().abs();
112                step_mismatch = rem > 1e-6 && (1.0 - rem).abs() > 1e-6;
113            }
114        }
115        if let Some(Value::String(exp) | Value::Iri(exp)) = rules.get("expected_unit") {
116            if !exp.is_empty() {
117                let unit_ok = |u: &str| u == exp || UnitId::new(u).compatible(&UnitId::new(exp));
118                unit_mismatch = match value {
119                    Value::Quantity(q) => !unit_ok(&q.unit),
120                    Value::Record(r) => !matches!(r.get("unit"), Some(Value::String(u) | Value::Iri(u)) if unit_ok(u)),
121                    _ => true,
122                };
123            }
124        }
125    }
126
127    let flags = [
128        ("value_missing", value_missing, "Value is required"),
129        ("bad_input", bad_input, "Bad numeric or structured input"),
130        ("type_mismatch", type_mismatch, "Value does not match expected type"),
131        ("pattern_mismatch", pattern_mismatch, "Value does not match required pattern"),
132        ("too_short", too_short, "Value is shorter than minimum length"),
133        ("too_long", too_long, "Value exceeds maximum length"),
134        ("range_underflow", range_underflow, "Value is below minimum bound"),
135        ("range_overflow", range_overflow, "Value exceeds maximum bound"),
136        ("step_mismatch", step_mismatch, "Value does not align with step increment"),
137        ("unit_mismatch", unit_mismatch, "Unit mismatch with expected physical dimension"),
138        ("custom_error", custom_error, "Custom validation error"),
139    ];
140    let valid = flags.iter().all(|(_, failed, _)| !*failed);
141    let msg = if valid {
142        String::new()
143    } else {
144        custom_err_msg.unwrap_or_else(|| {
145            flags.iter().find(|(_, f, _)| *f).map(|(_, _, m)| (*m).to_string()).unwrap_or_default()
146        })
147    };
148
149    let mut rec = BTreeMap::new();
150    for (k, v, _) in flags {
151        rec.insert(k.to_string(), Value::Bool(v));
152    }
153    rec.insert("valid".to_string(), Value::Bool(valid));
154    rec.insert("validation_message".to_string(), Value::String(msg));
155    rec
156}
157
158/// `validate.check_form(values: Record, rules_by_field: Record)`
159pub fn eval_check_form(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
160    let (Some(Value::Record(values)), Some(Value::Record(rules_by_field))) = (args.first(), args.get(1)) else {
161        return Err(Diagnostic::new(DiagCode::E100, span, "validate.check_form: expected (values, rules_by_field) Records"));
162    };
163    let (mut invalid_fields, mut reports) = (Vec::new(), BTreeMap::new());
164    for (field_id, rule_val) in rules_by_field {
165        let Value::Record(rules) = rule_val else { continue };
166        let field_val = values
167            .get(field_id)
168            .or_else(|| match values.get("values") { Some(Value::Record(inner)) => inner.get(field_id), _ => None })
169            .unwrap_or(&Value::Null);
170        let report = check_field_against_rules(field_val, rules);
171        if report.get("valid") != Some(&Value::Bool(true)) {
172            invalid_fields.push(Value::String(field_id.clone()));
173        }
174        reports.insert(field_id.clone(), Value::Record(report));
175    }
176    let first_invalid = invalid_fields.first().cloned().unwrap_or(Value::Null);
177    Ok(Value::Record(BTreeMap::from([
178        ("valid".to_string(), Value::Bool(invalid_fields.is_empty())),
179        ("invalid_fields".to_string(), Value::List(invalid_fields)),
180        ("first_invalid_field".to_string(), first_invalid),
181        ("reports".to_string(), Value::Record(reports)),
182    ])))
183}
184
185/// `validate.cross_field(rule_name: String, condition: Bool, fields: List<Value>, message: String)`
186pub fn eval_cross_field(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
187    let args = if args.len() == 5 && matches!(args.first(), Some(Value::Record(_))) { &args[1..] } else { args };
188    let (Some(Value::String(rule_name)), Some(Value::Bool(cond)), Some(Value::List(fields)), Some(Value::String(msg))) =
189        (args.first(), args.get(1), args.get(2), args.get(3))
190    else {
191        return Err(Diagnostic::new(DiagCode::E100, span, "validate.cross_field: expected (rule_name, condition, fields, message)"));
192    };
193    Ok(Value::Record(BTreeMap::from([
194        ("rule_name".to_string(), Value::String(rule_name.clone())),
195        ("valid".to_string(), Value::Bool(*cond)),
196        ("fields".to_string(), Value::List(fields.clone())),
197        ("validation_message".to_string(), Value::String(if *cond { String::new() } else { msg.clone() })),
198    ])))
199}
200
201/// `validate.paraconsistent(field_id: String, claims: List<Record>)`
202pub fn eval_paraconsistent(args: &[Value], span: Span) -> Result<Value, Diagnostic> {
203    let (Some(Value::String(field_id) | Value::Iri(field_id)), Some(Value::List(claims))) = (args.first(), args.get(1)) else {
204        return Err(Diagnostic::new(DiagCode::E100, span, "validate.paraconsistent: expected (field_id, claims)"));
205    };
206    let mut distinct_values: Vec<Value> = Vec::new();
207    let (mut pooled_mu, mut pooled_lambda) = (0.0_f64, 0.0_f64);
208    for item in claims {
209        if let Value::Record(c) = item {
210            if let Some(v) = c.get("value").filter(|v| !matches!(v, Value::Null)) {
211                if !distinct_values.contains(v) {
212                    distinct_values.push(v.clone());
213                }
214            }
215            let mu = c.get("support_mu").or_else(|| c.get("mu")).and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 1.0);
216            let lam = c.get("refutation_lambda").or_else(|| c.get("lambda")).and_then(Value::as_f64).unwrap_or(0.0).clamp(0.0, 1.0);
217            pooled_mu = pooled_mu.max(mu);
218            pooled_lambda = pooled_lambda.max(lam);
219        }
220    }
221    let distinct_count = distinct_values.len() as i64;
222    let belnap = if distinct_count > 1 || (pooled_mu >= 0.5 && pooled_lambda >= 0.5) {
223        "Both"
224    } else if pooled_mu >= 0.5 {
225        "True"
226    } else if pooled_lambda >= 0.5 {
227        "False"
228    } else {
229        "Neither"
230    };
231    Ok(Value::Record(BTreeMap::from([
232        ("field_id".to_string(), Value::String(field_id.clone())),
233        ("belnap_state".to_string(), Value::String(belnap.to_string())),
234        ("mu".to_string(), Value::F64(pooled_mu)),
235        ("lambda".to_string(), Value::F64(pooled_lambda)),
236        ("quarantine_routed".to_string(), Value::Bool(belnap == "Both")),
237        ("distinct_values_count".to_string(), Value::I64(distinct_count)),
238    ])))
239}
240
241fn is_valid_email(s: &str) -> bool {
242    let mut p = s.split('@');
243    matches!((p.next(), p.next(), p.next()), (Some(l), Some(d), None) if !l.is_empty() && !d.is_empty() && !s.chars().any(char::is_whitespace) && d.contains('.') && !d.starts_with('.') && !d.ends_with('.'))
244}
245
246fn is_valid_iri(s: &str) -> bool {
247    !s.is_empty() && !s.chars().any(char::is_whitespace) && (s.contains("://") || s.starts_with("urn:") || s.starts_with("did:"))
248}
249
250fn is_valid_did(s: &str) -> bool {
251    let segs: Vec<&str> = s.split(':').collect();
252    segs.len() >= 3 && segs[0] == "did" && segs.iter().all(|p| !p.is_empty()) && !s.chars().any(char::is_whitespace)
253}
254
255fn is_valid_tel(s: &str) -> bool {
256    s.chars().filter(char::is_ascii_digit).count() >= 3
257        && s.chars().all(|c| c.is_ascii_digit() || matches!(c, '+' | '-' | ' ' | '(' | ')' | '.' | 'x'))
258}
259
260fn matches_simple_pattern(text: &str, pattern: &str) -> bool {
261    let pat = pattern.strip_prefix('^').unwrap_or(pattern).strip_suffix('$').unwrap_or(pattern);
262    if pat.contains('|') {
263        return pat.split('|').any(|alt| matches_simple_pattern(text, alt));
264    }
265    let chars: Vec<char> = text.chars().collect();
266    let mut positions = vec![0usize];
267    for (atom, min_rep, max_rep) in parse_pattern_atoms(pat) {
268        let mut next = Vec::new();
269        for &pos in &positions {
270            if min_rep == 0 && !next.contains(&pos) {
271                next.push(pos);
272            }
273            let mut m = 0usize;
274            while pos + m < chars.len() && m < max_rep && atom_matches(&atom, chars[pos + m]) {
275                m += 1;
276                if m >= min_rep && !next.contains(&(pos + m)) {
277                    next.push(pos + m);
278                }
279            }
280        }
281        if next.is_empty() {
282            return false;
283        }
284        positions = next;
285    }
286    positions.contains(&chars.len())
287}
288
289fn atom_matches(atom: &str, c: char) -> bool {
290    match atom {
291        "." => true,
292        "\\d" => c.is_ascii_digit(),
293        "\\w" => c.is_ascii_alphanumeric() || c == '_',
294        "\\s" => c.is_whitespace(),
295        s if s.starts_with('[') => {
296            let b: Vec<char> = s[1..s.len() - 1].chars().collect();
297            (0..b.len()).any(|i| {
298                (i + 2 < b.len() && b[i + 1] == '-' && c >= b[i] && c <= b[i + 2])
299                    || (b[i] != '-' && b[i] == c)
300            })
301        }
302        s => s.starts_with(c),
303    }
304}
305
306fn parse_pattern_atoms(pat: &str) -> Vec<(String, usize, usize)> {
307    let (c, mut i, mut out): (Vec<char>, usize, Vec<_>) = (pat.chars().collect(), 0, Vec::new());
308    while i < c.len() {
309        let atom = if c[i] == '\\' && i + 1 < c.len() {
310            i += 2;
311            if matches!(c[i - 1], 'd' | 'w' | 's') { format!("\\{}", c[i - 1]) } else { c[i - 1].to_string() }
312        } else if c[i] == '[' {
313            let end = c[i..].iter().position(|&x| x == ']').map_or(c.len(), |p| i + p + 1);
314            let s: String = c[i..end].iter().collect();
315            i = end;
316            s
317        } else {
318            i += 1;
319            c[i - 1].to_string()
320        };
321        let (lo, hi) = match c.get(i) {
322            Some('*') => { i += 1; (0, usize::MAX) }
323            Some('+') => { i += 1; (1, usize::MAX) }
324            Some('?') => { i += 1; (0, 1) }
325            Some('{') => {
326                let end = c[i..].iter().position(|&x| x == '}').map_or(c.len(), |p| i + p);
327                let spec: String = c[i + 1..end].iter().collect();
328                i = (end + 1).min(c.len());
329                match spec.split_once(',') {
330                    Some((a, b)) => {
331                        let lo = a.trim().parse().unwrap_or(0);
332                        (lo, if b.trim().is_empty() { usize::MAX } else { b.trim().parse().unwrap_or(lo) })
333                    }
334                    None => {
335                        let n = spec.trim().parse().unwrap_or(1);
336                        (n, n)
337                    }
338                }
339            }
340            _ => (1, 1),
341        };
342        out.push((atom, lo, hi));
343    }
344    out
345}