Abstract

ShEx is a schema language for RDF graphs. It provides structural constraint on graph structures and lexical forms of literals. ShExPath addresses elements in a ShEx schema. This can be used to anchor validation results, identify regions of RDF graphs, or tie external annotations to elements in a schema.

Scope

ShExPath addresses any element of a schema that ShExJ writes down: Shape Expressions and Triple Expressions, the Node Constraint facets and value sets within them, and the semantic actions and annotations hung on any of these.

It addresses a schema, not a graph. What a path selects is a set of schema elements; an application decides what to do with them — report a validation result against one, hang an annotation on one, or ask a validator what data matched one.

Document Conventions

This specification describes the structure of ShEx schemas in terms of ShExJ. A ShExJ document is a tree of JSON objects, arrays and atomic values; ShExPath steps are named for ShExJ's own property names, so /shapes/*[0]/shapeExpr/expression reads as the JavaScript S.shapes[0].shapeExpr.expression does.

The reference implementation is ShapePath.js (npm shape-path-core), where the language is called ShapePath. The two names are used interchangeably; the grammar in this document is that implementation's grammar, and the nonterminal names below are its nonterminal names.

Examples in this document are written against the example schema and select the elements the tables say they do.

Data Model

A ShExPath is a Unicode string which defines a traversal of a Shape Expressions schema.

An item is any node of the ShExJ document: an object (a Schema, a ShapeDecl, a shape expression, a triple expression, a SemAct, an Annotation, an ObjectLiteral, …), an array (shapes, expressions, extends, …), or an atomic value (an IRI, a string, a number, a boolean).

An array is an item in its own right, not a shorthand for its members: extends selects the array and extends/* selects the shape expressions in it. A shape or triple expression reference is an IRI, so it is an atomic item; the referent is elsewhere in the schema and a path reaches it by starting again from @ or $.

A value is a sequence of items. A value may hold the same item more than once (see Junctions). The position of an item is its 0-based offset in the value that holds it; index() reports it and [0] selects the first item.

A singleton is a sequence of exactly one item. A path says it expects one with [assert count() = 1], which is what the @ and $ shortcuts do.

evaluateShExPath takes a ShExPath P, a schema S and an initial value V, and produces a value. Unless the application says otherwise, V is the singleton holding S (see Relative ShExPaths).

This specification uses XPath's notion of item, value, step and singleton to leverage shared understanding. Would other terms be more useful?

Positions are 0-based, where XPath's are 1-based. XPath's aggregate is position() and ShExPath's is index(): the different name is the signal that it counts differently. [N] is shorthand for [index() = N], so the two have to agree.

Path Expressions

A ShExPath is a series of steps separated by /, evaluated left to right: each step is applied to every item in the value the previous step produced, and their results are concatenated. The first step is applied to the value the application supplied, which is by default the singleton holding the schema. A / is permitted before that first step and has no effect on where the path begins.

XPath's leading / means "from the root of the document", and this one does not: /shapes/* looks for a shapes property on whatever value it was handed, so it selects nothing when that value is not the schema. Either / should reset the context to the schema — which is what makes a path absolute, and what the shortcuts would want — or it should be dropped from the grammar.

// is accepted wherever / is and currently means the same thing. In XPath it abbreviates descendant-or-self::; either it should mean that here or it should be removed from the grammar.

Junctions

Two paths may be combined into one. The operators, loosest first:

operator value
,every item each operand selected, in order, keeping duplicates: a sequence of n paths that each select one item selects n items.
unionevery item either operand selected, with duplicates removed.
intersectionthe items every operand selected.

union and intersection are matched without regard to case.

union and intersection compare items by value — two structurally identical triple constraints in different shapes are one item to them — where the rest of this language compares by identity. Two constraints that say the same thing are not the same element of the schema, so this should probably be identity.

Steps

A step selects, for each item it is applied to, some set of items reachable from it, and then applies its filters. It has three parts, all but the first optional: an axis, a term type test, and filters.

Axes

The axis says which items are reachable. child:: is the default and may be omitted.

axis selects
child::attributethe value of that ShExJ property, if the item has it.
child::*every property value of an object item, or every member of an array item.
self::the item itself.
parent::the item that has this one as a property value or array member. The schema has no parent.
ancestor::that parent, its parent, and so on up to the schema.
thisShapeExpr::the item, and — if it is a ShapeAnd, ShapeOr or ShapeNot — the shape expressions it combines, transitively. This is how a path reaches the Shape in IRI /re/ {…} without knowing that a conjunction is in the way.
thisTripleExpr::the item, and — if it is an EachOf or OneOf — the triple expressions it groups, transitively, an inclusion among them.

Neither thisShapeExpr:: nor thisTripleExpr:: crosses into the other kind of expression: thisTripleExpr:: does not enter a constraint's valueExpr, and thisShapeExpr:: does not enter a shape's expression. thisShapeExpr:: stops at a shape reference, which is an IRI rather than an expression.

thisShapeExpr:: yields nothing for a ShapeExternal or a ShapeDecl, though ShapeExternal is a term type and a declaration is what shapes holds.

Inclusions

A triple expression may be a label rather than an expression — ShExC writes it &<#label> — and it means the expression that label names is part of this one. thisTripleExpr:: reads it that way: the axis goes on into the expression the label names, so a shape's body is what a validator matches against and not merely what is written between its braces. The ~ shortcut is built on that axis, so it reaches an included constraint too.

An expression the walk has already reported is not reported again, so an expression that includes itself, and one included twice, are each that expression once. A label nothing in the schema declares selects nothing.

An included expression is one expression, however many bodies take it in: two shapes that include the same group reach the same items, and something hung on one of those items — an annotation, a semantic action — is hung on it for every shape that includes it. Addressing it through a shape reads as though it were that shape's own; it isn't.

A descendant:: axis — every item below this one, at any depth — is used by the $ shortcut but has no spelling of its own in the grammar.

Attributes

A child step names a ShExJ property. The names are ShExJ's, and the grammar admits only these:

on attributes
any itemtype id semActs annotations predicate
Schema@context startActs start imports shapes
shape expressionsshapeExprs shapeExpr
NodeConstraintnodeKind datatype values length minlength maxlength pattern flags mininclusive minexclusive maxinclusive maxexclusive totaldigits fractiondigits
value set valuesvalue language stem exclusions languageTag
Shapeclosed extra extends expression
triple expressionsexpressions min max inverse valueExpr
SemActname code
Annotationobject

An attribute the item does not have selects nothing, so a step is a filter as much as a traversal.

shapeExpr is in the list because a ShapeDecl has one, but the declaration's other property, abstract, is not; nor is ShapeDecl a term type. ShapeDecl postdates this grammar.

Term Types

A term type after the axis keeps only the items whose ShExJ type is that one. It is exactly the filter [type = T], written where it reads best.

kind term types
shape expressionsShapeAnd ShapeOr ShapeNot NodeConstraint Shape ShapeExternal
triple expressionsEachOf OneOf TripleConstraint
value set valuesIriStem IriStemRange LiteralStem LiteralStemRange Language LanguageStem LanguageStemRange Wildcard
otherSchema SemAct Annotation

A term type is a keyword, not an IRI: [type = <TripleConstraint>] is an IRI comparison and selects nothing.

Filters

A filter is a bracketed expression that keeps some of the items a step selected. Filters apply left to right, each to what the one before it left, so [0][0] is [0].

A filter is evaluated once per item, and knows three things: the item, the value the filter is trimming, and the item's position in it.

filter keeps
[path]the items for which path, evaluated from that item, has a true effective boolean value. [valueExpr] keeps the constraints that have one.
[path = rvalue]the items where the first item path selects equals rvalue, an INTEGER or an IRI. [predicate = :name], [id = <#IssueShape>].
[index()], [count()]index() is the item's position and count() the size of the value being trimmed; each is used through a comparison or an effective boolean value.
[N]shorthand for [index() = N] — the item at position N, counting from 0.
[assert expr]every item, if expr holds; otherwise the path is in error. [assert count() = 1] says "there should be exactly one of these".

The effective boolean value of a value is: false for an empty value; true for a value of more than one item; and for a single item, the boolean itself, false for the number 0, false for the empty string, and true otherwise.

< and > are in the grammar beside =, and this document does not say what they compare — numbers, IRIs by string order, or both. shape-path-core parses them and selects nothing.

A step may be a parenthesized path — (path)filter* — which the grammar admits and shape-path-core does not yet evaluate.

Shortcuts

Three sigils address the elements that have names. Each is a step and needs no / before it.

shortcut is
@label the shape expression declared with that label:
/shapes/*[id = label][assert count() = 1]/shapeExpr
~iri the triple constraint on that predicate, in this shape's own body:
/thisShapeExpr::Shape/expression/thisTripleExpr::TripleConstraint[predicate = iri]
$label the triple expression declared with that label, wherever it was declared:
/descendant::[id = label][assert count() = 1]

@ lands on the shape expression, not on the ShapeDecl that names it, since that is where a schema says what the label means. ~ begins with thisShapeExpr::Shape, so it looks through the conjunction in IRI /re/ {…} for the shape that has a body.

$ looks through the whole schema because ShExJ has no top-level list of triple expressions the way it has shapes: a triple expression label may sit on an EachOf, a OneOf or a TripleConstraint at any depth, including inside the inline shape of some constraint's value expression.

The three sigils address three different things and do not collide: @ a shape expression label, $ a triple expression label, and ~ the predicate of a triple constraint. A label naming both a shape expression and a triple expression is a structural error in ShEx.

A label may be a blank node in ShExJ, and the grammar takes only an iri after a sigil, so a shape declared with a blank node label cannot be addressed.

A shortcut is a step like any other and starts where the step before it left off. @ begins with a shapes step, so it addresses a schema and selects nothing anywhere else. $ searches downward from the value it is given: from the schema, all of it; from one shape expression, that expression. ~ reads the shape expression it is given.

A shortcut takes no filters: ~:component[2] is not a path. @ and $ carry [assert count() = 1] of their own, but ~ may select several constraints, and narrowing them needs a further step to hang the filter on — ~:component/self::[2].

Examples

The example schema

This schema excerpt describes an issue that might appear in an issue tracking system. Every example in this document is evaluated against it.

PREFIX : <http://ex.example/ns#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
BASE <http://ex.example/schema>

<#IssueShape> {
  :name xsd:string MINLENGTH 4 ;
  :category ["bug" "feature request"] ;
  $<#reportedBy> :postedBy @<#UserShape> ;
  :processing {
    :reproduced [true false] ;
    :priority xsd:integer
  } ?
}

<#UserShape> IRI /User\?id=[0-9]+/ {
  (  foaf:name xsd:string
   |  foaf:givenName xsd:string + ;
      foaf:familyName xsd:string
  ) ;
  foaf:mbox IRI
}

<#AgentShape> { foaf:mbox IRI }

<#EmployeeShape> EXTENDS @<#UserShape> EXTENDS @<#AgentShape> {
  :employeeId xsd:integer
}
        

Simple Access

ShExPath value
@<#IssueShape>the Shape declared as #IssueShape.
@<#IssueShape>~:categorythe :category constraint in it.
$<#reportedBy>the :postedBy constraint, addressed by the name given to it.
$<#reportedBy>/valueExprthe reference to #UserShape in that constraint — an IRI, not the shape.
@<#UserShape>~foaf:mboxthe foaf:mbox constraint, reached through the ShapeAnd that IRI /re/ {…} compiles to.
@<#IssueShape>~:processing/valueExpr/expression/expressions/*the two constraints of the nested inline shape.

Each shortcut is an abbreviation, and the long way round selects the same thing:

ShExPath value
/shapes/*[id = <#IssueShape>][assert count() = 1]/shapeExpras @<#IssueShape>.
@<#IssueShape>/thisShapeExpr::Shape/expression
  /thisTripleExpr::TripleConstraint[predicate = :category]
as @<#IssueShape>~:category.
/shapes/*the four shape declarations, where @ gives the expression each declares.
/shapes/*[0]the first of them, #IssueShape's declaration.

Filters and term types

ShExPath value
@<#IssueShape>/expression/expressions/*the four constraints in #IssueShape.
@<#IssueShape>/expression/expressions/*[1]the second of them, :category.
@<#IssueShape>/expression/expressions/*[index() = 1]the same, written out.
@<#IssueShape>/expression/expressions/*[predicate = :name]the :name constraint.
@<#IssueShape>/expression/expressions/TripleConstraintthe four again — all of them are triple constraints.
@<#IssueShape>/expression/expressions/*[assert count() = 4]the four, and an error if a fifth is ever added.
@<#UserShape>/shapeExprs/*/thisShapeExpr::NodeConstraintthe IRI /User\?id=[0-9]+/ half of #UserShape.
@<#IssueShape>~:category/ancestor::Shapethe shape that constraint is in.

Junctions

ShExPath value
@<#IssueShape>~:name , @<#IssueShape>~:categorytwo constraints.
@<#IssueShape>~:name union @<#IssueShape>~:nameone constraint: union drops the repeat.
@<#IssueShape>~:name , @<#IssueShape>~:namethe same constraint twice: , keeps it.

Extended Shape Expressions

A shape's EXTENDS list is addressed with the extends step. The step selects the list; /* selects what is in it, and a filter picks one out.

ShExPath value
@<#EmployeeShape>/extendsthe list of shape expressions extended by #EmployeeShape.
@<#EmployeeShape>/extends/*the two references in it.
@<#EmployeeShape>/extends/*[0]the first extended shape expression, the reference to #UserShape.

Validators may use such paths to name partial validation results, for instance <http://a.example/s>@<#EmployeeShape>/extends/*[0] for the result of testing node <http://a.example/s> against the extension of #EmployeeShape by #UserShape.

Disambiguation

More than one triple constraint may have the same predicate. ~ selects all of them; a self:: step carrying a filter picks one out by the order they appear in the shape.

<#BPObs> {
  :component { :code ["systolic"] ; :value xsd:double } ;
  :component { :code ["diastolic"] ; :value xsd:double } ;
  :component { :code ["posture"] ; :value @<#Postures> } ?
}
        
ShExPath value
@<#BPObs>~:componentall three :component constraints.
@<#BPObs>~:component/self::[2]the third of them, the one expecting a code of "posture".
@<#BPObs>~:component/self::[assert count() = 1]an error: there are three.

Relative ShExPaths

Invocation of evaluateShExPath includes a value, and every ShExPath is relative to it. An application that supplies the schema can use any path in this document; one that supplies something else can use the paths that read downward from there, which is every path but those beginning with @ or with a Schema attribute. A context path is a ShExPath which, when evaluated against the schema, produces an equivalent value. For instance validation results MAY be reported using relative ShExPaths.

Context ShExPath value
@<#IssueShape>~:categorythe :category constraint in the #IssueShape shape.
@<#IssueShape>expression/expressions/*[1]the same constraint.

A relative ShExPath can be concatenated to its context path with a / separator, except before a shortcut, which needs none.

Grammar

The nonterminal names are those of the reference implementation's parser, ShapePathParser.jison, so that the grammar and the parser can be read side by side. union, intersection and assert are matched case-insensitively. Whitespace and COMMENT are skipped between tokens.

shapePath             ::= sequenceStep ("," sequenceStep)*
sequenceStep          ::= unionStep ("union" unionStep)*
unionStep             ::= intersectionStep ("intersection" intersectionStep)*
intersectionStep      ::= startStep nextStep*
startStep             ::= ("/" | "//")? step | shortcut
nextStep              ::= ("/" | "//") step | shortcut
shortcut              ::= ("@" | "~" | "$") iri
step                  ::= "child::"? termType filter*
                        | "child::"? attributeOrAny termType? filter*
                        | nonChildAxis termType? filter*
                        | "(" shapePath ")" termType? filter*
nonChildAxis          ::= "thisShapeExpr::" | "thisTripleExpr::"
                        | "self::" | "parent::" | "ancestor::"
attributeOrAny        ::= "*" | attribute
filter                ::= "[" filterExpr "]"
filterExpr            ::= "assert"? shapePath comparison?
                        | "assert"? function comparison?
                        | numericExpr
function              ::= "index" "(" ")" | "count" "(" ")"
comparison            ::= comparitor rvalue
comparitor            ::= "=" | "<" | ">"
rvalue                ::= INTEGER | iri
numericExpr           ::= INTEGER

termType              ::= shapeExprType | tripleExprType | valueType
                        | "Schema" | "SemAct" | "Annotation"
shapeExprType         ::= "ShapeAnd" | "ShapeOr" | "ShapeNot"
                        | "NodeConstraint" | "Shape" | "ShapeExternal"
tripleExprType        ::= "EachOf" | "OneOf" | "TripleConstraint"
valueType             ::= "IriStem" | "IriStemRange"
                        | "LiteralStem" | "LiteralStemRange"
                        | "Language" | "LanguageStem" | "LanguageStemRange"
                        | "Wildcard"

attribute             ::= "type" | "id" | "semActs" | "annotations" | "predicate"
                        | schemaAttr | shapeExprAttr | tripleExprAttr
                        | valueSetValueAttr | semActAttr | annotationAttr
schemaAttr            ::= "@context" | "startActs" | "start" | "imports" | "shapes"
shapeExprAttr         ::= "shapeExprs" | "shapeExpr" | nodeConstraintAttr | shapeAttr
nodeConstraintAttr    ::= "nodeKind" | "datatype" | xsFacetAttr | "values"
xsFacetAttr           ::= stringFacetAttr | numericFacetAttr
stringFacetAttr       ::= "length" | "minlength" | "maxlength" | "pattern" | "flags"
numericFacetAttr      ::= "mininclusive" | "minexclusive"
                        | "maxinclusive" | "maxexclusive"
                        | "totaldigits" | "fractiondigits"
valueSetValueAttr     ::= "value" | "language" | "stem" | "exclusions" | "languageTag"
shapeAttr             ::= "closed" | "extra" | "extends" | "expression"
tripleExprAttr        ::= "expressions" | "min" | "max" | tripleConstraintAttr
tripleConstraintAttr  ::= "inverse" | "valueExpr"
semActAttr            ::= "name" | "code"
annotationAttr        ::= "object"

[136s]  iri           ::= IRIREF | prefixedName
[137s]  prefixedName  ::= PNAME_LN | PNAME_NS

@terminals
        COMMENT          ::= '#' [^#x0a#x0d]* | '<!--' ([^-] | '-' [^-] | '--' [^>])* '-->'
[18t]   IRIREF           ::= '<' ([^#x00-#x20<>\"{}|^`\\] | UCHAR)* '>'
[140s]  PNAME_NS         ::= PN_PREFIX? ':'
[141s]  PNAME_LN         ::= PNAME_NS PN_LOCAL
[19t]   INTEGER          ::= [+-]? [0-9]+
[26t]   UCHAR            ::= '\\u' HEX HEX HEX HEX
                           | '\\U' HEX HEX HEX HEX HEX HEX HEX HEX
[160s]  ECHAR            ::= '\\' [tbnrf\\\"\']
[164s]  PN_CHARS_BASE    ::= [A-Z] | [a-z]
                           | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x02FF]
                           | [#x0370-#x037D] | [#x037F-#x1FFF]
                           | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF]
                           | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD]
                           | [#x10000-#xEFFFF]
[165s]  PN_CHARS_U       ::= PN_CHARS_BASE | '_'
[167s]  PN_CHARS         ::= PN_CHARS_U | '-' | [0-9]
                           | [#x00B7] | [#x0300-#x036F] | [#x203F-#x2040]
[168s]  PN_PREFIX        ::= PN_CHARS_BASE ((PN_CHARS | '.')* PN_CHARS)?
[169s]  PN_LOCAL         ::= (PN_CHARS_U | ':' | [0-9] | PLX)
                             (PN_CHARS | '.' | ':' | PLX)*
[170s]  PLX              ::= PERCENT | PN_LOCAL_ESC
[171s]  PERCENT          ::= '%' HEX HEX
[172s]  HEX              ::= [0-9] | [A-F] | [a-f]
[173s]  PN_LOCAL_ESC     ::= '\\' ('_' | '~' | '.' | '-' | '!' | '$' | '&' | "'"
                           | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?'
                           | '#' | '@' | '%')
      

ShExPath's PN_LOCAL, unlike ShExC's, may end in a .: no ShExPath operator is spelled ., so nothing needs the character back. The predicate shortcut was spelled . before it was spelled ~, for this reason.

This grammar does not ensure that an absolute path starts with a shape expression, nor that a path stripes between shape expressions, triple expressions and the shape expressions nested in triple expressions' value expressions. Such a path is well-formed and selects nothing.