Skip to main content

qualia_core_db/modalities/logic/shacl/
text_input.rs

1//! Text-driven SHACL validation — the entry point the docs playground / any
2//! "paste shapes + data, get a report" caller uses.
3//!
4//! * **Data** is N3/N-Triples text (parsed by the engine's own [`N3Parser`]).
5//!   Numeric object literals are inline-encoded (so range constraints work);
6//!   IRIs/strings are `q_hash`ed and retained in a resolver (so string
7//!   constraints — pattern/length/language — work).
8//! * **Shapes** are a compact JSON list ([`ShapeSpec`]) mapping 1:1 onto the
9//!   [`ShaclConstraint`] vocabulary.
10//!
11//! [`validate_json`] runs the comprehensive [`ShaclEngine`] and returns the
12//! [`ValidationReport`] as JSON.
13
14use std::collections::HashMap;
15
16use super::shacl_types::{CompiledShape, ShaclConstraint, ShaclSeverity, ValidationReport};
17use super::validate::ShaclEngine;
18use crate::frame_layout::{pack_float_object, INLINE_TAG_INTEGER, INLINE_VALUE_MASK};
19use crate::modalities::logic::n3_parser::{N3Event, N3Parser, Term};
20use crate::{q_hash, NQuin};
21
22/// One shape in the playground/JSON input.
23#[derive(Debug, Clone, serde::Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct ShapeSpec {
26    /// `sh:targetClass` IRI (instances of this class are the focus nodes).
27    pub target_class: String,
28    /// Property path the value constraints apply to (`""` = a node shape on the
29    /// focus node itself, for `class`/`nodeKind`/`closed`/logical constraints).
30    #[serde(default)]
31    pub path: String,
32    /// `Violation` (default) | `Warning` | `Info`.
33    #[serde(default)]
34    pub severity: Option<String>,
35    pub constraints: Vec<ConstraintSpec>,
36}
37
38/// One constraint in a [`ShapeSpec`]. Exactly the field for the `kind` is read.
39#[derive(Debug, Clone, serde::Deserialize)]
40pub struct ConstraintSpec {
41    /// e.g. `minInclusive`, `minCount`, `class`, `datatype`, `nodeKind`,
42    /// `pattern`, `in`, `hasValue`, `equals`, `lessThan`, `node`, `not`, `and`,
43    /// `or`, `xone`, `languageIn`, `uniqueLang`, `closed`, `minLength`…
44    pub kind: String,
45    #[serde(default)]
46    pub num: Option<f64>,
47    #[serde(default)]
48    pub text: Option<String>,
49    #[serde(default)]
50    pub list: Option<Vec<String>>,
51}
52
53/// Unwrap any `Term` variant to its string payload (Uri, Variable,
54/// Literal and Formula all carry their surface form).
55fn term_str<'a>(t: &Term<'a>) -> &'a str {
56    match t {
57        Term::Uri(s) | Term::Variable(s) | Term::Literal(s) | Term::Formula(s) => s,
58    }
59}
60
61/// `q_hash` `s` and record its lexical form in resolver `r` for later
62/// string constraints; returns the hash. First occurrence wins.
63fn intern(s: &str, r: &mut HashMap<u64, String>) -> u64 {
64    let h = q_hash(s);
65    r.entry(h).or_insert_with(|| s.to_string());
66    h
67}
68
69/// Encode a triple object: numeric literals → inline-typed value; everything
70/// else → `q_hash` (retained in the resolver for string constraints).
71fn encode_object(t: &Term, r: &mut HashMap<u64, String>) -> u64 {
72    let s = term_str(t);
73    if let Term::Literal(_) = t {
74        if let Ok(i) = s.parse::<i64>() {
75            return INLINE_TAG_INTEGER | ((i as u64) & INLINE_VALUE_MASK);
76        }
77        if let Ok(f) = s.parse::<f64>() {
78            return pack_float_object(f as f32);
79        }
80    }
81    intern(s, r)
82}
83
84/// Parse N3/N-Triples text into a quin graph plus a hash→lexical resolver.
85pub fn build_graph(data: &str) -> (Vec<NQuin>, HashMap<u64, String>) {
86    let mut quins = Vec::new();
87    let mut resolver = HashMap::new();
88    let mut parser = N3Parser::new(data);
89    let _ = parser.parse_all(|ev| {
90        if let N3Event::StaticTriple(t) = ev {
91            let subject = intern(term_str(&t.subject), &mut resolver);
92            let predicate = intern(term_str(&t.predicate), &mut resolver);
93            let object = encode_object(&t.object, &mut resolver);
94            quins.push(NQuin {
95                subject,
96                predicate,
97                object,
98                context: 0,
99                metadata: 0,
100                parity: 0,
101            });
102        }
103        Ok(())
104    });
105    (quins, resolver)
106}
107
108/// Map a severity string to `ShaclSeverity`; anything absent or
109/// unrecognized defaults to `Violation` (fail closed).
110fn severity_of(s: &Option<String>) -> ShaclSeverity {
111    match s.as_deref() {
112        Some("Warning") | Some("warning") => ShaclSeverity::Warning,
113        Some("Info") | Some("info") => ShaclSeverity::Info,
114        _ => ShaclSeverity::Violation,
115    }
116}
117
118/// Convert a JSON `ConstraintSpec` to a typed `ShaclConstraint` by
119/// `kind` name — numeric kinds read `num` (default 0.0), text kinds
120/// read `text`, list kinds read `list`. `None` for unknown kinds.
121fn constraint_of(c: &ConstraintSpec) -> Option<ShaclConstraint> {
122    let num = c.num.unwrap_or(0.0);
123    let u = num as u32;
124    let text = || c.text.clone().unwrap_or_default();
125    let list = || c.list.clone().unwrap_or_default();
126    Some(match c.kind.as_str() {
127        "minInclusive" => ShaclConstraint::MinInclusive(num),
128        "maxInclusive" => ShaclConstraint::MaxInclusive(num),
129        "minExclusive" => ShaclConstraint::MinExclusive(num),
130        "maxExclusive" => ShaclConstraint::MaxExclusive(num),
131        "minCount" => ShaclConstraint::MinCount(u),
132        "maxCount" => ShaclConstraint::MaxCount(u),
133        "minLength" => ShaclConstraint::MinLength(u),
134        "maxLength" => ShaclConstraint::MaxLength(u),
135        "pattern" => ShaclConstraint::Pattern(text()),
136        "class" => ShaclConstraint::Class(text()),
137        "datatype" => ShaclConstraint::DataType(text()),
138        "nodeKind" => ShaclConstraint::NodeKind(text()),
139        "hasValue" => ShaclConstraint::HasValue(text()),
140        "in" => ShaclConstraint::In(list()),
141        "equals" => ShaclConstraint::Equals(text()),
142        "lessThan" => ShaclConstraint::LessThan(text()),
143        "lessThanOrEquals" => ShaclConstraint::LessThanOrEquals(text()),
144        "greaterThan" => ShaclConstraint::GreaterThan(text()),
145        "greaterThanOrEquals" => ShaclConstraint::GreaterThanOrEquals(text()),
146        "node" => ShaclConstraint::Node(text()),
147        "not" => ShaclConstraint::Not(text()),
148        "and" => ShaclConstraint::And(list()),
149        "or" => ShaclConstraint::Or(list()),
150        "xone" => ShaclConstraint::Xone(list()),
151        "languageIn" => ShaclConstraint::LanguageIn(list()),
152        "uniqueLang" => ShaclConstraint::UniqueLang,
153        "closed" => ShaclConstraint::Closed {
154            ignored_properties: list(),
155        },
156        "econVaRPositive" => ShaclConstraint::EconVaRPositive,
157        "econPositivePrice" => ShaclConstraint::EconPositivePrice,
158        "econConvergedModel" => ShaclConstraint::EconConvergedModel,
159        "econWelfareAboveFloor" => ShaclConstraint::EconWelfareAboveFloor { min_welfare: num },
160        "econRiskBelowThreshold" => ShaclConstraint::EconRiskBelowThreshold { max_risk: num },
161        "valuesConsentNonCoerced" => ShaclConstraint::ValuesConsentNonCoerced {
162            max_imbalance: if num.is_finite() && num > 0.0 {
163                num
164            } else {
165                0.5
166            },
167        },
168        "valuesHarmBelowCeiling" => ShaclConstraint::ValuesHarmBelowCeiling { max_harm: num },
169        "fuzzyMinDegree" => ShaclConstraint::FuzzyMinDegree {
170            min_degree: if num.is_finite() {
171                num.clamp(0.0, 1.0)
172            } else {
173                0.0
174            },
175        },
176        "deonticObligate" => ShaclConstraint::DeonticObligate,
177        "deonticPermit" => ShaclConstraint::DeonticPermit,
178        "deonticForbid" => ShaclConstraint::DeonticForbid,
179        "epistemicKnowledge" => ShaclConstraint::EpistemicKnowledge {
180            min_certainty: u as u8,
181        },
182        "epistemicBelief" => ShaclConstraint::EpistemicBelief {
183            min_certainty: u as u8,
184        },
185        "commonKnowledge" => ShaclConstraint::CommonKnowledge,
186        "ltlGlobally" | "ltlFinally" | "ltlNext" | "ltlUntil" | "ltlRelease" | "ltlConstraint" => {
187            ShaclConstraint::LtlConstraint { formula: text() }
188        }
189        "paraconsistentMaxContradiction" | "paraconsistentConstraint" => {
190            ShaclConstraint::ParaconsistentConstraint {
191                isolation_context: text(),
192            }
193        }
194        _ => return None,
195    })
196}
197
198/// Build a [`CompiledShape`] from a [`ShapeSpec`].
199pub fn shape_from_spec(spec: &ShapeSpec) -> CompiledShape {
200    let constraints: Vec<ShaclConstraint> =
201        spec.constraints.iter().filter_map(constraint_of).collect();
202    let mut shape = CompiledShape::new(
203        spec.target_class.clone(),
204        constraints,
205        severity_of(&spec.severity),
206    );
207    shape.property_path = spec.path.clone();
208    shape
209}
210
211/// Validate N3/N-Triples `data` against `specs` and return the report.
212pub fn validate_text(data: &str, specs: &[ShapeSpec]) -> ValidationReport {
213    let (quins, resolver) = build_graph(data);
214    let shapes: Vec<CompiledShape> = specs.iter().map(shape_from_spec).collect();
215    let engine = ShaclEngine::new(&quins, &shapes);
216    engine.validate(&|h| resolver.get(&h).cloned())
217}
218
219/// JSON-in / JSON-out convenience for the playground & WASM boundary.
220pub fn validate_json(data: &str, shapes_json: &str) -> Result<String, String> {
221    let specs: Vec<ShapeSpec> =
222        serde_json::from_str(shapes_json).map_err(|e| format!("invalid shapes JSON: {e}"))?;
223    let report = validate_text(data, &specs);
224    serde_json::to_string(&report).map_err(|e| format!("serialize report: {e}"))
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    #[test]
232    fn end_to_end_age_mininclusive() {
233        let data = ":alice a :Person .\n:alice :age 15 .\n:bob a :Person .\n:bob :age 40 .";
234        let shapes = r#"[
235            {"targetClass":":Person","path":":age","severity":"Violation",
236             "constraints":[{"kind":"minInclusive","num":18}]}
237        ]"#;
238        let out = validate_json(data, shapes).unwrap();
239        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
240        assert_eq!(
241            v["conforms"], false,
242            "alice (15) must violate minInclusive 18"
243        );
244        let results = v["results"].as_array().unwrap();
245        assert_eq!(results.len(), 1);
246        assert_eq!(
247            results[0]["source_constraint_component"],
248            "sh:MinInclusiveConstraintComponent"
249        );
250    }
251
252    #[test]
253    fn end_to_end_pattern_with_resolver() {
254        let data = r#":u a :User . :u :email "alice@example.org" ."#;
255        let shapes = r#"[
256            {"targetClass":":User","path":":email",
257             "constraints":[{"kind":"pattern","text":"^[^@]+@[^@]+\\.[a-z]+$"}]}
258        ]"#;
259        let out = validate_json(data, shapes).unwrap();
260        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
261        assert_eq!(
262            v["conforms"], true,
263            "a well-formed email matches the pattern"
264        );
265    }
266
267    #[test]
268    fn end_to_end_class_and_node_kind() {
269        // pet must be an instance of :Dog; here it's a :Cat → violation.
270        let data = ":o a :Owner . :o :pet :rex . :rex a :Cat .";
271        let shapes = r#"[
272            {"targetClass":":Owner","path":":pet",
273             "constraints":[{"kind":"class","text":":Dog"}]}
274        ]"#;
275        let v: serde_json::Value =
276            serde_json::from_str(&validate_json(data, shapes).unwrap()).unwrap();
277        assert_eq!(v["conforms"], false);
278    }
279
280    #[test]
281    fn invalid_json_is_reported() {
282        assert!(validate_json(":a :b :c .", "{not json").is_err());
283    }
284
285    #[test]
286    fn values_consent_non_coerced_and_harm_ceiling() {
287        let ok = ":a a :Act . :a :imbalance 0.2 . :a :harm 3.0 .";
288        let bad = ":a a :Act . :a :imbalance 0.9 . :a :harm 12.0 .";
289        let shapes = r#"[
290            {"targetClass":":Act","path":":imbalance",
291             "constraints":[{"kind":"valuesConsentNonCoerced","num":0.5}]},
292            {"targetClass":":Act","path":":harm",
293             "constraints":[{"kind":"valuesHarmBelowCeiling","num":10.0}]}
294        ]"#;
295        let v_ok: serde_json::Value =
296            serde_json::from_str(&validate_json(ok, shapes).unwrap()).unwrap();
297        assert_eq!(v_ok["conforms"], true, "{v_ok}");
298        let v_bad: serde_json::Value =
299            serde_json::from_str(&validate_json(bad, shapes).unwrap()).unwrap();
300        assert_eq!(v_bad["conforms"], false, "{v_bad}");
301    }
302
303    #[test]
304    fn end_to_end_econ_welfare_and_var_constraints() {
305        let passing_data = ":p a :PolicyEvaluation .\n:p :welfare 0.85 .\n:p :var 1250000.0 .";
306        let failing_data = ":p a :PolicyEvaluation .\n:p :welfare 0.35 .\n:p :var -50000.0 .";
307        let shapes = r#"[
308            {"targetClass":":PolicyEvaluation","path":":welfare",
309             "constraints":[{"kind":"econWelfareAboveFloor","num":0.50}]},
310            {"targetClass":":PolicyEvaluation","path":":var",
311             "constraints":[{"kind":"econVaRPositive"}]}
312        ]"#;
313
314        let pass_out = validate_json(passing_data, shapes).unwrap();
315        let pass_val: serde_json::Value = serde_json::from_str(&pass_out).unwrap();
316        assert_eq!(
317            pass_val["conforms"], true,
318            "passing data failed with report: {pass_out}"
319        );
320
321        let fail_out = validate_json(failing_data, shapes).unwrap();
322        let fail_val: serde_json::Value = serde_json::from_str(&fail_out).unwrap();
323        assert_eq!(
324            fail_val["conforms"], false,
325            "failing data must violate welfare floor and positive var"
326        );
327        let results = fail_val["results"].as_array().unwrap();
328        assert_eq!(results.len(), 2, "must have 2 violations");
329    }
330}