Skip to main content

Crate shacl_structural_model

Crate shacl_structural_model 

Source
Expand description

§shacl-structural-model

crates.io Documentation CI License

Typed structural values for SHACL shapes in Rust.

shacl-structural-model represents SHACL shapes, property paths, targets, constraint components, severities, RDF messages, SPARQL declarations, and SHACL Advanced Features functions, expressions and rules. It is intended for parsers, editors, validators, serializers, and storage adapters that need typed shape values without taking a dependency on an RDF graph implementation.

The default value type is rdf_structural_model::Term. The structural types are also generic over the value type, so an application can use its own RDF term model without copying or converting RDF-valued fields. Shape IDs and references retain blank nodes; target nodes can also be literals. Messages keep language tags and datatypes. Numeric ordering literals retain their lexical precision.

This crate models structural values only. It does not parse RDF, read or write files, access a graph store, execute validation, run SPARQL, or collect an entire shapes graph. Callers should stream shapes from their input and retain only the structural values needed by their operation.

§W3C specifications

The stable baseline is the SHACL Recommendation. SPARQL and AF declarations follow that recommendation and SHACL Advanced Features. Representing these declarations does not establish validator conformance or pySHACL compatibility. The Component::SingleLine(bool) declaration follows SHACL 1.2 Core, Working Draft 14 October 2026, section 7.4.4. It preserves both true and explicit false through nested JSON and binary serialization. The draft marks this constraint at risk; this crate represents the declaration without executing it. SHACL 1.2 is the target specification, tracked at its newest drafts: each draft feature is added as a model-only declaration as it is modelled, and the declarations listed in this README are the ones modelled so far. SHACL-JS is outside the scope.

The same draft’s list constraint declarations (section 7.5) are represented by MemberShape(Value), MinListLength(Count), MaxListLength(Count) and UniqueMembers(bool). Member-shape references retain caller-owned RDF identity; length bounds retain exact RDF values or independent compiled counts without a machine-integer limit. Explicit UniqueMembers(false) relaxes uniqueness while still requiring a valid SHACL list in the draft. Consumers own integer validation, list traversal, member validation, equality and report construction. These declarations do not traverse or collect lists.

§Example

use iri_rfc3987::Iri;
use rdf_structural_model::{BlankNodeId, Literal};
use shacl_structural_model::{Component, DefaultTerm, NodeShape, PropertyShape, ShaclPath, Target};

let person: Iri<String> = "https://example.org/Person".parse().expect("valid IRI");
let name: Iri<String> = "https://example.org/name".parse().expect("valid IRI");

let name_shape = PropertyShape::<DefaultTerm>::new(
    DefaultTerm::BlankNode(BlankNodeId::try_new("urn:shapes:source".parse().unwrap(), "nameShape".to_owned()).unwrap()),
    ShaclPath::Predicate(name),
)
.with_component(Component::MinCount(DefaultTerm::literal(
    Literal::typed("1", "http://www.w3.org/2001/XMLSchema#integer".parse().unwrap()).unwrap(),
)));

let person_shape = NodeShape::<DefaultTerm>::new(
    DefaultTerm::iri("https://example.org/PersonShape".parse().expect("valid IRI")),
)
.with_target(Target::Class(person))
.with_property_shape(name_shape.id.clone());

assert_eq!(person_shape.property_count(), 1);
assert_eq!(name_shape.components[0].kind_name(), "minCount");

§Value types

RDF-valued fields default to rdf_structural_model::Term. Applications can instead use oxrdf::Term, references to their existing terms, or opaque term handles. Construction has no Clone, Debug, or Serde bounds; those traits are required only when calling the corresponding operations. IRIs in IRI-only roles, such as predicates and datatypes, default to iri_rfc3987::Iri<String>. The independent Named parameter accepts a caller-owned named-node type when programmatic RDF terms preserve relative or otherwise non-RFC lexical values. This does not relax the default IRI parser or accept arbitrary RDF values in named roles.

use shacl_structural_model::Component;

let constraint: Component<String> = Component::Pattern {
    pattern: "^[A-Z]".to_owned(),
    flags: Some("i".to_owned()),
};

assert_eq!(constraint.kind_name(), "pattern");

Count and length parameters preserve the caller’s RDF value type, including signed and arbitrary-size integers. Component<Value, Count>, NodeShape<Value, Count>, PropertyShape<Value, Count>, and parameterized declarations also accept a separate compiled count type; Count defaults to Value. The model does not parse lexical forms, impose a u64 limit, or read literal payloads. Order values stay as RDF terms, independently of Count.

Regex flag parameters likewise retain Value by default. The independent third generic Flags is available on components, shapes, parameters, custom components, target types and functions. An engine can retain an opaque RDF reference beside its bounded compiled flags without materializing the original string. Pattern parameters also retain Value by default, with an independent fourth generic Pattern for compiled representations. For example, Component<Value, Count, Flags, Pattern> allows four different types. Both representations propagate through all declarations containing constraints. The model does not parse regex syntax, compile patterns, or read payloads. Consumers own compilation, resource accounting, and validation of RDF metadata.

Named roles use the fifth generic on components, shapes, parameters, custom components, target types and functions. Paths use ShaclPath<Named>, and targets, expressions, rules and parameter values propagate the same named type separately from Value. Construction does not require conversion, cloning, display or Serde traits. Display alone requires Named: AsRef<str>. Serialization and checked loading use the selected named type’s Serde contract; the strict Iri<String> default continues to reject relative and invalid IRI strings. Severity retains its independent checked IRI contract.

§Checked values, errors and ordering

sh:languageIn members are LanguageTag values. LanguageTag::try_new checks BCP 47 well-formedness (without consulting the IANA registry), and Serde decoding applies the same check, so a malformed tag cannot be loaded from JSON or Postcard. Spelling is preserved; equality, hashing and ordering ignore ASCII case.

use shacl_structural_model::{Component, LanguageTag, LexicalRole, StructuralModelError};

let languages = ["en", "nl-BE"].map(|tag| LanguageTag::try_new(tag).unwrap());
let constraint: Component<String> = Component::LanguageIn(languages.to_vec());
assert_eq!(constraint.display_value(), "en, nl-BE");
assert_eq!(
    LanguageTag::try_new("en_US"),
    Err(StructuralModelError::InvalidSyntax {
        lexical: "en_US".to_owned(),
        expected: LexicalRole::LanguageTag,
    })
);

StructuralModelError reports the offending lexical value with the LexicalRole it was supplied for: UnknownTerm for a well-formed value outside a closed vocabulary (an unknown sh:nodeKind IRI) and InvalidSyntax for a malformed value (a severity that is not an absolute IRI, a malformed tag).

The structural value types implement PartialOrd and Ord whenever their generic parameters do, so consumers can sort shapes, components, paths, targets, expressions and rules canonically. The default rdf_structural_model::Term has no order, so canonical sorting needs an ordered caller term type. Severity orders from most to least severe: Violation < Warning < Info, followed by application-defined severities in IRI order. The inference declarations retain RDF literals and subjects, which are unordered, and so remain unordered.

Every sh: IRI the model decodes or encodes is a documented constant in the vocabulary module, such as vocabulary::VIOLATION and vocabulary::IRI.

§Serialization and RDF identity

The default terms use the shared rdf-structural-model foundation. Their serialization supports JSON and non-self-describing binary formats such as Postcard, including nested shapes, numeric lexical forms and directional language messages. Blank nodes carry an explicit caller-assigned scope IRI; use the same scope for intentionally shared identities and distinct scopes for independent imports. This changes the default term API and serialized shape.

Applications still supply their own Value, Count and Flags without a conversion layer. Their Serde support is conditional on those types. Model support for RDF 1.2 triple terms and typed extensions does not establish SHACL validator execution support for those features.

§Restricted SHACL 1.2 inference declarations

The inference module describes a model-only subset pinned to the 28 October 2026 Inference Rules draft and Node Expressions draft. It is distinct from the AF declarations below. It does not execute rules or certify inference-engine support.

APIRepresentation
RuleSet, RuleSetMembership, RuleSetInclusionIndependent checked IRI declaration and edge records, suitable for streaming
ResourceRef, ShapeRuleLinkShared RDF Subject<Text> identities, including scoped blank nodes
RuleNumber, RuleScheduleChecked exact integer/decimal metadata; absent layer/order/runOnce retained
TripleRuleDeclarationIndependent rule identity, schedule, and three optional expression slots
DirectExpressionChecked direct IRI/literal/triple-term constants or shnex:pathValues with shared paths

The new types accept shared RDF owned or borrowed text. Numeric Eq/hash retain literal identity; cmp_value compares arbitrary-width exact values without floating-point conversion, digit-buffer allocation or a general datatype engine. Constructors and nested JSON/Postcard decoding apply the same semantic checks.

Rule-set includes remain edges; the consumer resolves references, cycles and membership without hydrating the relation. A rule’s global status requires the relevant shapes graph’s associations, not merely the selected rule set.

Bare blank nodes are rejected as direct constants. Explicit shnex:focusNode expressions are rejected in this subset, including during decoding. Paths retain ordered structure and require at least two sequence/alternative members. Expression construction caps structural depth at 64 and term/path nodes at 4096; already allocated caller inputs remain the caller’s responsibility. Default expression decoding additionally caps wire depth at 128, deserializer calls at 32768 and total visited text at 1 MiB. deserialize_with_limits accepts tighter caller budgets. Cap source bytes as well: a format decoder may allocate text before delivering a Serde visitor. Bounds apply per expression, not per dataset.

Other 1.2 expression forms, explicit focus expressions, rule-type catalogs, conditions, deactivation, expected-derived predicates, processors, entailment selection, SPARQL/template declarations and temporary/provenance triple policies are not yet modelled; they belong to the SHACL 1.2 target and are added as model-only declarations. Existing AF declarations retain their own contract. Reference resolution, default application, scheduling, target/condition validation, graph traversal, SPARQL execution and inference remain consumer-owned.

§SPARQL and Advanced Features

DeclarationStructural types
SELECT constraints, ASK/SELECT validators, result annotationsSparqlConstraint, SparqlValidator, ResultAnnotation
Query literals, prefix resources and importsSparqlQuery, PrefixDeclaration, PrefixDeclarations
Custom components and parameter valuesCustomConstraintComponent, CustomConstraint, Parameter, ParameterValues
Direct SPARQL targets and reusable target typesSparqlTarget, SparqlTargetType, CustomTarget
ASK/SELECT functionsShaclFunction, SparqlSelectOrAsk
All seven AF node-expression forms, including nested path inputsNodeExpression, ExpressionKind, ExpressionConstraint
Triple and SPARQL rules, conditions, order and deactivationShaclRule, RuleKind, TripleRule

Declarations retain source nodes and RDF-valued messages. Parameter values are kept in full before an engine constructs query bindings. Prefix resources and imports are references, so shared declarations need not be copied into every query. Property shapes support targets as well as node shapes. Implicit class targets and custom target-type identifiers use the caller’s RDF value type, preserving blank-node identity as well as named resources.

use shacl_structural_model::{Component, DefaultTerm, NodeShape, SparqlConstraint, SparqlQuery};

use rdf_structural_model::{BlankNodeId, Literal};

let blank = |label: &str| DefaultTerm::BlankNode(
    BlankNodeId::try_new("urn:shapes:source".parse().unwrap(), label.to_owned()).unwrap()
);
let query = SparqlQuery::new(DefaultTerm::literal(Literal::string(
    "SELECT $this WHERE { $this ex:status ex:Invalid }",
)))
.with_prefixes(blank("prefixes"));
let shape = NodeShape::<DefaultTerm>::new(blank("shape"))
    .with_component(Component::Sparql(Box::new(
        SparqlConstraint::new(blank("constraint"), query),
    )));
assert_eq!(shape.components[0].kind_name(), "sparql");

§Scope and memory

The crate exposes individual shapes and nested structural values. It does not provide a document-sized Schema collection, so a parser can emit shapes one at a time and let the caller decide whether to validate, serialize, persist, or retain them. Collections inside a single shape represent that shape’s direct structural values; they are not a replacement for streaming an entire input document.

This is a parsed structural model, not an RDF graph archive. Paths retain their structure but not all RDF-list cell identities. Boolean parameters and sh:languageIn members are checked language tags. Regex patterns and flags retain their RDF values or caller-defined compiled representations. Callers that need exact source triples or graph context must retain those separately. path_node can retain a path’s source root for result reporting. Display helpers are human-readable labels, not RDF or SPARQL serialization.

The parser/consumer checks RDF node kinds, cardinality, query syntax, shape references and expression cycles. This crate does not inspect opaque Value payloads or certify a declaration as well-formed. Serde rejects unrecognized fields on shapes and the new declarations, rather than discarding them.

§Migrating from 6.4

This is a breaking API and Serde-validation change:

  • Component::LanguageIn holds Vec<LanguageTag> instead of Vec<String>. Construct members with LanguageTag::try_new. The JSON and Postcard encodings are unchanged, but stored malformed tags no longer decode.
  • StructuralModelError::UnknownNodeKind { value } becomes UnknownTerm { lexical, expected: LexicalRole::NodeKindIri }, and InvalidSeverityIri { value } becomes InvalidSyntax { lexical, expected: LexicalRole::SeverityIri }.
  • Component, the shapes and the declarations that contain them now also implement Eq and Hash when their generic parameters do.

§Migrating from 2.x

Target::ImplicitClass, SparqlTargetType::id and CustomTarget::target_type now hold Value rather than Iri<String>. Pass the corresponding RDF term, including for named resources. Target::iri() and NodeShape::target_class_iris() cover explicit IRI-valued targets; they do not inspect opaque implicit-class terms. This is a breaking API and serialized-shape change for callers whose RDF value representation differs from an IRI string.

§Migrating from 1.x

This is a breaking API and Serde format change:

  • Shape IDs, shape references, Target::Node, and message builders now take Value. Construct an RDF IRI/blank-node/literal term for those fields.
  • PropertyShape::name and description become names and descriptions: vectors of RDF literals. Their builders append values, retaining languages.
  • Shape and rule order values use Option<Value>, replacing floating-point ordering on property shapes. Node shapes now also have order.
  • ShaclRule::Sparql becomes ShaclRule::new(id, RuleKind::Sparql(query)). Query text is an RDF literal in SparqlQuery, with explicit prefix references.
  • Severity supports custom IRIs and is no longer Copy. Its accessors borrow the value. Invalid text returns an error.
  • Shape local_name() methods are removed because IDs need not be IRIs. Inspect the caller’s term type and use local_name for actual IRIs. Target::iri() now returns Option for Core class/predicate targets.
  • Exhaustive matches on Component, Target, and Severity need the new variants. Migrate stored Serde values explicitly; no legacy fields are ignored.

§License

Licensed under either of:

  • Apache License, Version 2.0
  • MIT License

at your option. Typed structural values for SHACL shapes without an RDF-store dependency.

Modules§

inference
Restricted, checked declarations for the SHACL 1.2 Inference Rules draft.
vocabulary
The SHACL vocabulary IRIs this crate decodes and encodes.

Structs§

CustomConstraint
An application of a custom component to a shape.
CustomConstraintComponent
A custom sh:ConstraintComponent declaration.
CustomTarget
One use of a custom target type, with its supplied RDF parameter values.
ExpressionConstraint
A sh:expression constraint with expression-specific messages.
LanguageTag
A well-formed BCP 47 language tag, as listed by sh:languageIn.
NodeExpression
A node expression paired with its original RDF node.
NodeShape
A SHACL node shape.
Parameter
One sh:parameter declaration, retaining constraints and RDF annotations.
ParameterValues
All values supplied for one parameter predicate at a component or target use.
PrefixDeclaration
One sh:declare resource, retaining the original RDF literals.
PrefixDeclarations
The prefix declarations and import edges attached to one resource.
PropertyShape
A SHACL property shape.
ResultAnnotation
An AF sh:resultAnnotation declaration on a constraint or validator.
ShaclFunction
A sh:SPARQLFunction declaration without registration or execution.
ShaclRule
A SHACL-AF rule with its identity, execution metadata, and declared bodies.
SparqlConstraint
A sh:sparql constraint, including its source identity and messages.
SparqlQuery
A query literal and its sh:prefixes references.
SparqlTarget
A direct sh:SPARQLTarget declaration.
SparqlTargetType
A reusable, parameterized sh:SPARQLTargetType declaration.
SparqlValidator
A SPARQL validator attached to a custom constraint component.
TripleRule
The three expressions of a sh:TripleRule.

Enums§

Component
A Core, SPARQL, or AF constraint declaration applied to a shape.
DefaultTerm
An RDF term with owned or borrowed text and an explicit extension parameter.
ExpressionKind
The seven node expression forms defined by SHACL-AF.
LexicalRole
The role a rejected lexical value was supplied for.
NodeKind
The type of RDF node a value must be.
RuleKind
A declarative rule body; no query or node expression is executed here.
Severity
The severity of a SHACL validation result.
ShaclPath
A SHACL property path represented as an AST.
SparqlSelectOrAsk
The query forms supported by SPARQL validators and functions.
StructuralModelError
Errors raised by structural constructors and standard-value decoding.
Target
A target declaration on a node or property shape.

Functions§

local_name
Return the local name after the final # or / in an IRI.