Skip to main content

shacl_structural_model/
component.rs

1//! SHACL Core constraint components.
2
3use std::fmt;
4
5use iri_rfc3987::Iri;
6
7use crate::{
8    CustomConstraint, ExpressionConstraint, LanguageTag, NodeKind, ShaclPath, SparqlConstraint,
9};
10
11/// The default value type used by [`Component`].
12pub type DefaultValue = crate::DefaultTerm;
13
14/// A Core, SPARQL, or AF constraint declaration applied to a shape.
15///
16/// Integer count and length parameters use `Count`, which defaults to the
17/// caller's RDF value type. Consumers may instead supply a compiled comparison
18/// type without imposing a machine-integer limit on the structural model.
19/// Regex flags and patterns use independent `Flags` and `Pattern` types,
20/// also defaulting to `Value`. Consumers may retain an RDF reference beside
21/// a compiled representation without requiring an owned lexical string.
22#[derive(
23    Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Serialize, serde::Deserialize,
24)]
25#[serde(
26    deny_unknown_fields,
27    bound(
28        serialize = "Value: serde::Serialize, Count: serde::Serialize, Flags: serde::Serialize, Pattern: serde::Serialize, Named: serde::Serialize",
29        deserialize = "Value: serde::Deserialize<'de>, Count: serde::Deserialize<'de>, Flags: serde::Deserialize<'de>, Pattern: serde::Deserialize<'de>, Named: serde::Deserialize<'de>"
30    )
31)]
32pub enum Component<
33    Value = DefaultValue,
34    Count = Value,
35    Flags = Value,
36    Pattern = Value,
37    Named = Iri<String>,
38> {
39    /// `sh:class` — the value must be an instance of the class.
40    Class(Named),
41    /// `sh:datatype` — the value must have the given datatype.
42    Datatype(Named),
43    /// `sh:nodeKind` — the value must have the given RDF node kind.
44    NodeKind(NodeKind),
45    /// `sh:minCount`.
46    MinCount(Count),
47    /// `sh:maxCount`.
48    MaxCount(Count),
49    /// `sh:minExclusive`.
50    MinExclusive(Value),
51    /// `sh:minInclusive`.
52    MinInclusive(Value),
53    /// `sh:maxExclusive`.
54    MaxExclusive(Value),
55    /// `sh:maxInclusive`.
56    MaxInclusive(Value),
57    /// `sh:minLength`.
58    MinLength(Count),
59    /// `sh:maxLength`.
60    MaxLength(Count),
61    /// `sh:pattern` with optional `sh:flags`.
62    Pattern {
63        /// Original RDF pattern value, or a caller-defined compiled representation.
64        pattern: Pattern,
65        /// Original RDF flags value, or a caller-defined compiled representation.
66        flags: Option<Flags>,
67    },
68    /// `sh:languageIn`, with each member checked as a BCP 47 language tag.
69    LanguageIn(Vec<LanguageTag>),
70    /// `sh:uniqueLang`.
71    UniqueLang(bool),
72    /// `sh:equals`.
73    Equals(ShaclPath<Named>),
74    /// `sh:disjoint`.
75    Disjoint(ShaclPath<Named>),
76    /// `sh:lessThan`.
77    LessThan(ShaclPath<Named>),
78    /// `sh:lessThanOrEquals`.
79    LessThanOrEquals(ShaclPath<Named>),
80    /// `sh:and`.
81    And(Vec<Value>),
82    /// `sh:or`.
83    Or(Vec<Value>),
84    /// `sh:not`.
85    Not(Value),
86    /// `sh:xone`.
87    Xone(Vec<Value>),
88    /// `sh:node`.
89    Node(Value),
90    /// `sh:qualifiedValueShape` with optional min/max counts.
91    QualifiedValueShape {
92        /// The shape to count conforming values against.
93        shape: Value,
94        /// Minimum number of conforming values.
95        min_count: Option<Count>,
96        /// Maximum number of conforming values.
97        max_count: Option<Count>,
98        /// Whether sibling qualified shapes use disjoint value sets.
99        disjoint: bool,
100    },
101    /// `sh:hasValue`.
102    HasValue(Value),
103    /// `sh:in`.
104    In(Vec<Value>),
105    /// `sh:closed` with `sh:ignoredProperties`.
106    Closed {
107        /// Whether the shape is closed.
108        is_closed: bool,
109        /// Properties exempt from the closure check.
110        ignored_properties: Vec<Named>,
111    },
112    /// A `sh:sparql` constraint declaration.
113    Sparql(Box<SparqlConstraint<Value>>),
114    /// A `sh:expression` constraint declaration.
115    Expression(Box<ExpressionConstraint<Value, Named>>),
116    /// A use of a separately declared custom component.
117    Custom(CustomConstraint<Value, Named>),
118    /// `sh:singleLine` from the SHACL 1.2 Core 2026-10-14 Working Draft.
119    ///
120    /// When true, literal values must not contain U+000A through U+000D.
121    /// False explicitly permits multiline values. This declaration is at risk
122    /// in the draft; representing it does not implement constraint evaluation.
123    SingleLine(bool),
124    /// `sh:memberShape` from the SHACL 1.2 Core 2026-10-14 Working Draft.
125    ///
126    /// Each value must be a well-formed SHACL list whose members conform to
127    /// this caller-owned shape reference. The consumer checks and evaluates it.
128    MemberShape(Value),
129    /// Draft `sh:minListLength`, using the independent caller-owned count type.
130    ///
131    /// The consumer checks the non-negative integer parameter and list structure.
132    MinListLength(Count),
133    /// Draft `sh:maxListLength`, using the independent caller-owned count type.
134    ///
135    /// The consumer checks the non-negative integer parameter and list structure.
136    MaxListLength(Count),
137    /// Draft `sh:uniqueMembers` — require distinct members when true.
138    ///
139    /// Both true and false require a well-formed SHACL list. False relaxes only
140    /// the uniqueness check, not list well-formedness. Evaluation is consumer-owned.
141    UniqueMembers(bool),
142}
143
144impl<Value, Count, Flags, Pattern, Named> Component<Value, Count, Flags, Pattern, Named> {
145    /// Return the SHACL constraint kind name.
146    #[must_use]
147    pub const fn kind_name(&self) -> &'static str {
148        match self {
149            Self::Class(_) => "class",
150            Self::Datatype(_) => "datatype",
151            Self::NodeKind(_) => "nodeKind",
152            Self::MinCount(_) => "minCount",
153            Self::MaxCount(_) => "maxCount",
154            Self::MinExclusive(_) => "minExclusive",
155            Self::MinInclusive(_) => "minInclusive",
156            Self::MaxExclusive(_) => "maxExclusive",
157            Self::MaxInclusive(_) => "maxInclusive",
158            Self::MinLength(_) => "minLength",
159            Self::MaxLength(_) => "maxLength",
160            Self::Pattern { .. } => "pattern",
161            Self::LanguageIn(_) => "languageIn",
162            Self::UniqueLang(_) => "uniqueLang",
163            Self::Equals(_) => "equals",
164            Self::Disjoint(_) => "disjoint",
165            Self::LessThan(_) => "lessThan",
166            Self::LessThanOrEquals(_) => "lessThanOrEquals",
167            Self::And(_) => "and",
168            Self::Or(_) => "or",
169            Self::Not(_) => "not",
170            Self::Xone(_) => "xone",
171            Self::Node(_) => "node",
172            Self::QualifiedValueShape { .. } => "qualifiedValueShape",
173            Self::HasValue(_) => "hasValue",
174            Self::In(_) => "in",
175            Self::Closed { .. } => "closed",
176            Self::Sparql(_) => "sparql",
177            Self::Expression(_) => "expression",
178            Self::Custom(_) => "custom",
179            Self::SingleLine(_) => "singleLine",
180            Self::MemberShape(_) => "memberShape",
181            Self::MinListLength(_) => "minListLength",
182            Self::MaxListLength(_) => "maxListLength",
183            Self::UniqueMembers(_) => "uniqueMembers",
184        }
185    }
186}
187
188impl<
189    Value: fmt::Debug,
190    Count: fmt::Debug,
191    Flags: fmt::Debug,
192    Pattern: fmt::Debug,
193    Named: AsRef<str>,
194> Component<Value, Count, Flags, Pattern, Named>
195{
196    /// Return a human-readable display value for this component.
197    #[must_use]
198    pub fn display_value(&self) -> String {
199        match self {
200            Self::Class(iri) | Self::Datatype(iri) => crate::local_name(iri),
201            Self::NodeKind(kind) => format!("{kind:?}"),
202            Self::MinCount(count)
203            | Self::MaxCount(count)
204            | Self::MinLength(count)
205            | Self::MaxLength(count)
206            | Self::MinListLength(count)
207            | Self::MaxListLength(count) => format!("{count:?}"),
208            Self::MinExclusive(value)
209            | Self::MinInclusive(value)
210            | Self::MaxExclusive(value)
211            | Self::MaxInclusive(value)
212            | Self::HasValue(value)
213            | Self::Not(value)
214            | Self::Node(value)
215            | Self::MemberShape(value) => format!("{value:?}"),
216            Self::Pattern { pattern, flags } => match flags {
217                Some(flags) => format!("/{pattern:?}/{flags:?}"),
218                None => format!("/{pattern:?}/"),
219            },
220            Self::LanguageIn(languages) => languages
221                .iter()
222                .map(LanguageTag::as_str)
223                .collect::<Vec<_>>()
224                .join(", "),
225            Self::UniqueLang(value) | Self::SingleLine(value) | Self::UniqueMembers(value) => {
226                value.to_string()
227            }
228            Self::Equals(path)
229            | Self::Disjoint(path)
230            | Self::LessThan(path)
231            | Self::LessThanOrEquals(path) => path.to_string(),
232            Self::And(iris) | Self::Or(iris) | Self::Xone(iris) => iris
233                .iter()
234                .map(|value| format!("{value:?}"))
235                .collect::<Vec<_>>()
236                .join(", "),
237            Self::QualifiedValueShape {
238                shape,
239                min_count,
240                max_count,
241                ..
242            } => {
243                let mut parts = vec![format!("{shape:?}")];
244                if let Some(min) = min_count {
245                    parts.push(format!("min={min:?}"));
246                }
247                if let Some(max) = max_count {
248                    parts.push(format!("max={max:?}"));
249                }
250                parts.join(", ")
251            }
252            Self::In(values) => values
253                .iter()
254                .map(|value| format!("{value:?}"))
255                .collect::<Vec<_>>()
256                .join(", "),
257            Self::Closed {
258                is_closed,
259                ignored_properties,
260            } => {
261                if *is_closed {
262                    if ignored_properties.is_empty() {
263                        "true".to_owned()
264                    } else {
265                        let ignored = ignored_properties
266                            .iter()
267                            .map(crate::local_name)
268                            .collect::<Vec<_>>();
269                        format!("true (ignore: {})", ignored.join(", "))
270                    }
271                } else {
272                    "false".to_owned()
273                }
274            }
275            Self::Sparql(constraint) => format!("{:?}", constraint.select.text),
276            Self::Expression(constraint) => format!("{:?}", constraint.expression.node),
277            Self::Custom(constraint) => crate::local_name(&constraint.component),
278        }
279    }
280}