The basic building block of XPath 4.0 is the expression, which is a string of [Unicode] characters; the version of Unicode to be used is implementation-defined. The language provides several kinds of expressions which may be constructed from keywords, symbols, and operands. In general, the operands of an expression are other expressions. XPath 4.0 allows expressions to be nested with full generality.
Note:
This specification contains no assumptions or requirements regarding the character set encoding of strings of [Unicode] characters.
Like XML, XPath 4.0 is a case-sensitive language. Keywords in XPath 4.0 use lower-case characters and are not reserved—that is, names in XPath 4.0 expressions are allowed to be the same as language keywords, except for certain unprefixed function-names listed in A.3 Reserved Function Names.
[Definition: In the data model, a value is always a sequence.]
[Definition: A sequence is an ordered collection of zero or more items.]
[Definition: An item is either an atomic value, a node, or a function item.]
[Definition: An atomic value is a value in the value space of an atomic type, as defined in [XML Schema 1.0] or [XML Schema 1.1].]
[Definition: A node is an instance of one of the
node kinds defined in Section
6 Nodes
DM31.]
Each node has a unique node identity, a typed value, and a string value. In addition, some nodes have a name. The typed value of a node is a sequence
of zero or more atomic values. The string value of a node is a
value of type xs:string
. The name of a node is a value of type xs:QName
.
[Definition: A function item is an item that can be called using a dynamic function call.]
Note:
This specification uses the term function item where XDM uses functionDM31. There is no distinction in meaning, but function item is preferred here for clarity, because the unqualified term function has additional meanings in relation to function definitions in the static context.
Maps (see 4.14.1 Maps) and arrays (see 4.14.2 Arrays) are specific kinds of function item.
[Definition: A sequence containing exactly one item is called a singleton.] An item is identical to a singleton sequence containing that item. Sequences are never nested—for example, combining the values 1, (2, 3), and ( ) into a single sequence results in the sequence (1, 2, 3). [Definition: A sequence containing zero items is called an empty sequence.]
[Definition: The term XDM instance is used, synonymously with the term value, to denote an unconstrained sequence of items.]
Element nodes have a property called in-scope namespaces. [Definition: The in-scope namespaces property of an element node is a set of namespace bindings, each of which associates a namespace prefix with a URI.] For a given element, one namespace binding may have an empty prefix; the URI of this namespace binding is the default namespace within the scope of the element.
In [XML Path Language (XPath) Version 1.0], the in-scope namespaces of an element node are represented by a collection of namespace nodes arranged on a namespace axis. As of XPath 2.0, the namespace axis is deprecated and need not be supported by a host language. A host language that does not support the namespace axis need not represent namespace bindings in the form of nodes.
[Definition: An expanded QName is a triple: its components are a prefix, a local name, and a namespace URI. In the case of a name in no namespace, the namespace URI and prefix are both absent. In the case of a name in the default namespace, the prefix is absent.] When comparing two expanded QNames, the prefixes are ignored: the local name parts must be equal under the Unicode Codepoint Collation, and the namespace URI parts must either both be absent, or must be equal under the Unicode Codepoint Collation.
In the XPath 4.0 grammar, QNames representing the names of elements, attributes, functions, variables, types, or other such constructs are written as instances of the grammatical production EQName.
[135] | EQName |
::= |
QName | URIQualifiedName
|
|
[145] | QName |
::= |
[http://www.w3.org/TR/REC-xml-names/#NT-QName]Names
|
/* xgc: xml-version */ |
[146] | NCName |
::= |
[http://www.w3.org/TR/REC-xml-names/#NT-NCName]Names
|
/* xgc: xml-version */ |
[140] | URIQualifiedName |
::= |
BracedURILiteral
NCName
|
/* ws: explicit */ |
[141] | BracedURILiteral |
::= | "Q" "{" [^{}]* "}" |
/* ws: explicit */ |
The EQName production allows a QName to be written in one of three ways:
local-name only (for example, invoice
).
A name written in this form has no prefix, and the rules for determining the namespace depend on the context in which the name appears. This form is a lexical QName.
prefix plus local-name (for example, my:invoice
).
In this case the prefix and local name of the QName are as written, and the namespace URI is inferred from the prefix by examining the in-scope namespaces in the static context where the QName appears; the context must include a binding for the prefix. This form is a lexical QName.
URI plus local-name (for example,
Q{http://example.com/ns}invoice)
.
In this case the local name and namespace URI are as
written, and the prefix is absent. This way of writing a QName
is context-free, which makes it particularly suitable for use
in
expressions
that are generated by software. This
form is a URIQualifiedName.
If the
BracedURILiteral has no content (for example, Q{}invoice
)
then the namespace URI of the QName is absent.
[Definition: A lexical QName is a name that conforms to the syntax of the QName production].
The namespace URI value in a URIQualifiedName is whitespace normalized according
to the rules for the xs:anyURI
type in
Section
3.2.17 anyURI
XS1-2 or
Section
3.3.17 anyURI
XS11-2.
It is a static
error
[err:XQST0070] if the
namespace URI for an EQName is
http://www.w3.org/2000/xmlns/
.
Here are some examples of EQNames:
pi
is a lexical QName without a namespace prefix.
math:pi
is a lexical QName with a namespace prefix.
Q{http://www.w3.org/2005/xpath-functions/math}pi
specifies the namespace URI using a BracedURILiteral; it is not a lexical QName.
This document uses the following namespace prefixes to represent the namespace URIs with which they are listed. Although these prefixes are used within this specification to refer to the corresponding namespaces, not all of these bindings will necessarily be present in the static context of every expression, and authors are free to use different prefixes for these namespaces, or to bind these prefixes to different namespaces.
xs = http://www.w3.org/2001/XMLSchema
fn = http://www.w3.org/2005/xpath-functions
map = http://www.w3.org/2005/xpath-functions/map
array = http://www.w3.org/2005/xpath-functions/array
math = http://www.w3.org/2005/xpath-functions/math
err = http://www.w3.org/2005/xqt-errors
(see 2.4.2 Identifying and Reporting Errors).
[Definition: Within this specification, the term URI refers to a Universal Resource Identifier as defined in [RFC3986] and extended in [RFC3987] with the new name IRI.] The term URI has been retained in preference to IRI to avoid introducing new names for concepts such as "Base URI" that are defined or referenced across the whole family of XML specifications.
Note:
In most contexts, processors are not required to raise errors if a URI is not lexically valid according to [RFC3986] and [RFC3987]. See 2.5.5 URI Literals for details.
[Definition: The expression context for a given expression consists of all the information that can affect the result of the expression.]
This information is organized into two categories called the static context and the dynamic context.
[Definition: The static context of an expression is the information that is available during static analysis of the expression, prior to its evaluation.] This information can be used to decide whether the expression contains a static error.
The individual components of the static context are described below. A default initial value for each component must be specified by the host language. The scope of each component is specified in C.1 Static Context Components.
[Definition:
XPath 1.0 compatibility
mode.
This value is true
if rules for backward compatibility with XPath Version 1.0 are in effect; otherwise it is false
.
]
[Definition: Statically known namespaces. This is a mapping from prefix to namespace URI that defines all the namespaces that are known during static processing of a given expression.]
The URI value is whitespace normalized according to the rules for the
xs:anyURI
type in Section
3.2.17 anyURI
XS1-2 or
Section
3.3.17 anyURI
XS11-2.
The statically known namespaces may include a binding for the zero-length prefix; however, this is only used in limited circumstances because the rules for resolving unprefixed QNames depend on the how such a name is used.
Note the difference between in-scope namespaces, which is a dynamic property of an element node, and statically known namespaces, which is a static property of an expression.
[Definition:
Default element namespace. This is a
namespace URI or absentDM31. The namespace URI, if present, is used for any unprefixed QName appearing in a
position where an element name is expected.] The URI value is
whitespace normalized according to the rules for the xs:anyURI
type in Section
3.2.17 anyURI
XS1-2 or Section
3.3.17 anyURI
XS11-2.
[Definition:
Default type namespace. This is a namespace URI or absentDM31. The namespace URI, if present, is used for any unprefixed QName appearing in a
position where a type name is expected.] The URI value is
whitespace normalized according to the rules for the xs:anyURI
type in Section
3.2.17 anyURI
XS1-2 or Section
3.3.17 anyURI
XS11-2.
[Definition:
Default function namespace. This is either a namespace URI, or absentDM31. The namespace URI, if present, is used for any unprefixed QName appearing
in a position where a function name is expected.] The URI value is whitespace normalized according
to the rules for the xs:anyURI
type in Section
3.2.17 anyURI
XS1-2 or Section
3.3.17 anyURI
XS11-2
In its simplest form its value is simply a whitespace-normalized xs:anyURI
value (most commonly, the URI http://www.w3.org/2005/xpath-functions
)
to be used as the default namespace for unprefixed function names. However, the use of a more
complex algorithm is not precluded, for example an algorithm which searches multiple namespaces for
a matching name.
[Definition: In-scope schema definitions. This is a generic term for all the element declarations, attribute declarations, and schema type definitions that are in scope during static analysis of an expression.] It includes the following three parts:
[Definition: In-scope schema types. Each schema type definition is identified either by an expanded QName (for a named type) or by an implementation-dependent type identifier (for an anonymous type). The in-scope schema types include the predefined schema types described in 3.1 Predefined Schema Types. ]
[Definition: In-scope element declarations. Each element declaration is identified either by an expanded QName (for a top-level element declaration) or by an implementation-dependent element identifier (for a local element declaration). ] An element declaration includes information about the element's substitution group affiliation.
[Definition: Substitution groups are defined in Section 2.2.2.2 Element Substitution Group XS1-1 and Section 2.2.2.2 Element Substitution Group XS11-1. Informally, the substitution group headed by a given element (called the head element) consists of the set of elements that can be substituted for the head element without affecting the outcome of schema validation.]
[Definition: In-scope attribute declarations. Each attribute declaration is identified either by an expanded QName (for a top-level attribute declaration) or by an implementation-dependent attribute identifier (for a local attribute declaration). ]
[Definition: In-scope variables. This is a mapping from expanded QName to type. It defines the set of variables that are available for reference within an expression. The expanded QName is the name of the variable, and the type is the static type of the variable.]
An expression that binds a variable extends the in-scope variables, within the scope of the variable, with the variable and its type. Within the body of an inline function expression , the in-scope variables are extended by the names and types of the function parameters.
[Definition: Context item static type. This component defines the static type of the context item within the scope of a given expression.]
[Definition:
Item type aliases. This is a mapping from
expanded QName to ItemTypes
.]
[Definition: A type alias
is an expanded QName that
is mapped to an ItemType
in the item type aliases of
the static context.]
Item type aliases allow frequently used item types, especially complex item types such as record types, to be given simple names, so that the definition of the type is not repeated every time it is used.
Note:
Item type aliases can be defined in XQuery 4.0 and in XSLT 4.0, but not in XPath 4.0 itself.
[Definition: Statically known function definitions. This is a set of function definitions.]
[Definition: A function definition contains information used to evaluate a static function call, including the name, parameters, and return type of the function.]
The properties of a function definition include:
The function name, which is an expanded QName.
A (possibly empty) list of required parameters, each having:
a parameter name (an expanded QName)
a required type (a sequence type)
A (possibly empty) list of optional parameters, each having:
a parameter name (an expanded QName)
a required type (a sequence type)
a default value expression (an expression: see 4 Expressions)
A return type (a sequence type)
A (possibly empty) set of function annotations
An implementation. The function implementation contains the logic that enables the function result to be computed from the supplied parameters and information in the dynamic context.
The names of the parameters must be distinct.
[Definition: A function definition has an arity range, which is a range of consecutive non-negative integers. If the function definition has M required parameters and N optional parameters, then its arity range is from M to M+N inclusive.]
The static context may contain several function definitions with the same name, but the arity ranges of two such function definitions must not overlap. For example, if two function definitions A and B have the same function name, then:
It is acceptable for A to have two required parameters and no optional parameters, while B has three required parameters and one optional parameter.
It is not acceptable for A to have one required parameter while B has three optional parameters.
Note:
Implementations must ensure that no two function definitions have the same expanded QName and overlapping arity ranges (even if the signatures are consistent).
XQuery and XSLT enforce this rule by defining a static error if the rule is violated; but further constraints may be needed if an API allows external functions to be added to the static context.
Function definitions in the static context may originate in a number of ways, for example they may be:
User-written functions, implemented in a host language such as XQuery or XSLT.
Built-in functions, such as those specified in [XQuery and XPath Functions and Operators 4.0], and constructor functions for built-in and user-defined types.
External functions, for example functions implemented in a general-purpose programming language such as Java or Python.
[Definition: Built-in functions are function definitions that are always present in the static context by virtue of rules in the host language; they will typically include the functions specified in [XQuery and XPath Functions and Operators 4.0].]
The function definitions are available for reference from a static function call, or from a named function reference.
[Definition: Statically known collations. This is an implementation-defined mapping from URI to collation. It defines the names of the collations that are available for use in processing expressions.] [Definition: A collation is a specification of the manner in which strings and URIs are compared and, by extension, ordered. For a more complete definition of collation, see Section 5.3 Comparison of strings FO31.]
[Definition:
Default
collation. This identifies one of the collations in statically known collations as the collation to be
used by functions and operators for comparing and ordering values of type xs:string
and xs:anyURI
(and types derived from them) when no
explicit collation is
specified.]
[Definition:
Static Base URI.
This is an absolute URI, used to resolve
relative URI references.
]
If E is a subexpression of F then the Static
Base URI of E is the same as the Static Base URI of F.
There are no constructs in XPath that require resolution of relative URI references
during static analysis.
The Static Base URI is available during dynamic evaluation by use of the
fn:static-base-uri
function, and is used implicitly during dynamic
evaluation by functions such as fn:doc
. Relative URI references are
resolved as described in 2.5.6 Resolving a Relative URI Reference.
[Definition:
Statically known documents. This is a mapping
from strings to types. The string represents the absolute URI of a
resource that is potentially available using the fn:doc
function. The type is the static type of a call to fn:doc
with the given URI as its
literal argument. ]
If the argument to fn:doc
is a
string literal that is not present in statically known documents, then the
static type of
fn:doc
is document-node()?
.
Note:
The purpose of the statically known
documents is to provide static type information, not to determine
which documents are available. A URI need not be found in the
statically known documents to be accessed using
fn:doc
.
[Definition:
Statically known collections. This is a
mapping from strings to types. The string represents the absolute
URI of a resource that is potentially available using the
fn:collection
function. The type is the type of the
sequence of items that would result from calling the
fn:collection
function with this URI as its
argument.] If the argument to
fn:collection
is a string literal that is not present in
statically known collections, then the static type of
fn:collection
is item()*
.
Note:
The purpose of the statically known
collections is to provide static type information, not to determine
which collections are available. A URI need not be found in the
statically known collections to be accessed using
fn:collection
.
[Definition:
Statically known default collection type. This is the type of the sequence of
items that would result from calling the fn:collection
function with no arguments.] Unless initialized to some other value by an implementation, the value of statically known default collection type is item()*
.
[Definition:
Statically known decimal
formats. This is a mapping from QNames to decimal formats, with one default format that has no visible name,
referred to as the unnamed decimal format. Each
format is available for use when formatting numbers using the fn:format-number
function.]
Each decimal format defines a set of properties, which control the interpretation of characters
in the picture string supplied to the fn:format-number
function, and also specify characters to be used in the result
of formatting the number.
The following properties specify characters used both in the picture string, and in the formatted number. In each case the value is a single character:
[Definition: decimal-separator is the character used to separate the integer part of the number from the fractional part, both in the picture string and in the formatted number; the default value is the period character (.)]
[Definition: exponent-separator is the character used to separate the mantissa from the exponent in scientific notation both in the picture string and in the formatted number; the default value is the character (e).]
[Definition: grouping-separator is the character typically used as a thousands separator, both in the picture string and in the formatted number; the default value is the comma character (,)]
[Definition: percent is the character used both in the picture string and in the formatted number to indicate that the number is written as a per-hundred fraction; the default value is the percent character (%)]
[Definition: per-mille is the character used both in the picture string and in the formatted number to indicate that the number is written as a per-thousand fraction; the default value is the Unicode per-mille character (#x2030)]
[Definition: zero-digit is the character used to represent the digit zero; the default value is the Western digit zero (#x30). This character must be a digit (category Nd in the Unicode property database), and it must have the numeric value zero. This property implicitly defines the ten Unicode characters that are used to represent the values 0 to 9: Unicode is organized so that each set of decimal digits forms a contiguous block of characters in numerical sequence. Within the picture string any of these ten character can be used (interchangeably) as a place-holder for a mandatory digit. Within the final result string, these ten characters are used to represent the digits zero to nine.]
The following properties specify
characters to be used in the picture string supplied to the fn:format-number
function, but not in the formatted number. In each case the value must be a single character.
[Definition: digit is a character used in the picture string to represent an optional digit; the default value is the number sign character (#)]
[Definition: pattern-separator is a character used to separate positive and negative sub-pictures in a picture string; the default value is the semi-colon character (;)]
The following properties specify characters or strings that may appear in the result of formatting the number, but not in the picture string:
[Definition:
infinity is the string used to represent the double value infinity (INF
); the
default value is the string "Infinity"]
[Definition: NaN is the string used to represent the double value NaN (not-a-number); the default value is the string "NaN"]
[Definition: minus-sign is the single character used to mark negative numbers; the default value is the hyphen-minus character (#x2D). ]
[Definition: The dynamic context of an expression is defined as information that is needed for the dynamic evaluation of an expression.] If evaluation of an expression relies on some part of the dynamic context that is absentDM31, a dynamic error is raised [err:XPDY0002].
The individual components of the dynamic context are described below. Further rules governing the semantics of these components can be found in C.2 Dynamic Context Components.
The dynamic context consists of all the components of the static context, and the additional components listed below.
[Definition: The first three components of the dynamic context (context item, context position, and context size) are called the focus of the expression. ] The focus enables the processor to keep track of which items are being processed by the expression. If any component in the focus is defined, both the context item and context position are known.
Note:
If any component in the focus is defined, context size is usually defined as well. However, when streaming,
the context size cannot be determined without lookahead, so it may be undefined. If so, expressions like last()
will raise a dynamic error because the context size is undefined.
[Definition: A singleton focus is a focus that refers to a single item; in a singleton focus, context item is set to the item, context position = 1 and context size = 1.]
Certain language constructs, notably the path
operator
E1/E2
, the simple map operator
E1!E2
, and the predicate
E1[E2]
, create a new focus
for the evaluation of a sub-expression. In these constructs, E2
is evaluated once for each item in the
sequence that results from evaluating E1
. Each time E2
is evaluated, it is evaluated with a
different focus. The focus for evaluating E2
is referred to below as the inner
focus, while the focus for evaluating E1
is referred to as the outer
focus. The inner focus is used only for the evaluation of E2
. Evaluation of E1 continues with its original focus unchanged.
[Definition: The context item
is the item currently being processed.]
[Definition: When the context item is a
node, it can also be referred to as the context
node.] The context item is returned by an expression
consisting of a single dot (.
). When an expression E1/E2
or E1[E2]
is evaluated, each item in the
sequence obtained by evaluating E1
becomes the context item in the inner focus for an evaluation of E2
.
[Definition: The context
position is the position of the context item within the
sequence of items currently being processed.] It changes whenever the context item
changes. When the focus is defined, the value of the context position is an integer greater than zero. The context
position is returned by the expression fn:position()
. When an expression E1/E2
or E1[E2]
is evaluated, the context position in
the inner focus for an evaluation of E2
is the position of the context item in the sequence obtained by
evaluating E1
. The position of the
first item in a sequence is always 1 (one). The context position is
always less than or equal to the context size.
[Definition: The context
size is the number of items in the sequence of items currently
being processed.] Its value is always an
integer greater than zero. The context size is returned by the
expression fn:last()
. When an expression
E1/E2
or E1[E2]
is evaluated, the context size in the
inner focus for an evaluation of E2
is
the number of items in the sequence obtained by evaluating E1
.
[Definition: Variable values. This is a mapping from expanded QName to value. It contains the same expanded QNames as the in-scope variables in the static context for the expression. The expanded QName is the name of the variable and the value is the dynamic value of the variable, which includes its dynamic type.]
[Definition: Dynamically known function definitions. This is a set of function definitions. It includes the statically known function definitions as a subset, but may include other function definitions that are not known statically. ]
The function definitions in the dynamic context are used primarily by the fn:function-lookup
function.
If two function definitions in the dynamically known function definitions have the same name, then their arity ranges must not overlap.
Note:
The reason for allowing named functions to be available dynamically beyond those that are
available statically is primarily to allow for cases where the run-time execution
environment is significantly different from the compile-time environment. This could happen, for example,
if a stylesheet or query is compiled within a web server and then executed in the web browser.
The fn:function-lookup
function allows dynamic discovery of resources that were not
available statically.
The dynamically known function definitions may include external functions.
[Definition: External functions are functions that are implemented outside the query environment.] For example, an implementation might provide a set of implementation-defined external functions in addition to the core function library described in [XQuery and XPath Functions and Operators 4.0].
[Definition:
Current dateTime. This information represents
an implementation-dependent point in time during the processing of
an expression, and includes an explicit timezone. It can be retrieved by the fn:current-dateTime
function.
If called multiple times during the execution of
an expression,
this function always returns the same result.]
[Definition:
Implicit timezone. This is the timezone to be used when a date,
time, or dateTime value that does not have a timezone is used in a
comparison or arithmetic operation. The implicit timezone is an implementation-defined value of type
xs:dayTimeDuration
. See Section
3.2.7.3 Timezones
XS1-2 or
Section
3.3.7 dateTime
XS11-2 for the range of valid values of a timezone.]
[Definition:
Default language.
This is the natural language used when creating human-readable output
(for example, by the functions fn:format-date
and fn:format-integer
)
if no other language is requested.
The value is a language code as defined by the type xs:language
.]
[Definition:
Default calendar.
This is the calendar used when formatting dates in human-readable output
(for example, by the functions fn:format-date
and fn:format-dateTime
)
if no other calendar is requested.
The value is a string.]
[Definition:
Default place.
This is a geographical location used to identify the place where events happened (or will happen) when
formatting dates and times using functions such as fn:format-date
and fn:format-dateTime
,
if no other place is specified. It is used when translating timezone offsets to civil timezone names,
and when using calendars where the translation from ISO dates/times to a local representation is dependent
on geographical location. Possible representations of this information are an ISO country code or an
Olson timezone name, but implementations are free to use other representations from which the above
information can be derived.]
[Definition:
Available
documents. This is a mapping of strings to document nodes. Each string
represents the absolute URI of a resource. The document node is the root of a tree that represents that resource
using the data model. The document node is returned by the fn:doc
function when applied to that URI.] The set of available documents is not limited to the set of
statically known documents, and it may be empty.
If there are one or more
URIs in available documents that map to a document
node D
, then the document-uri property of D
must either be absent, or must
be one of these URIs.
Note:
This means that given a document node $N
, the result of
fn:doc(fn:document-uri($N)) is $N
will always be true
, unless
fn:document-uri($N)
is an empty sequence.
[Definition:
Available text resources.
This is a mapping of strings to text resources. Each string
represents the absolute URI of a resource. The resource is returned
by the fn:unparsed-text
function when applied to that
URI.] The set of available text resources is not limited to
the set of statically known
documents, and it may be empty.
[Definition:
Available
collections. This is a mapping of
strings to sequences of items. Each string
represents the absolute URI of a
resource. The sequence of items represents
the result of the fn:collection
function when that URI is supplied as the
argument. ] The set of available
collections is not limited to the set of statically known
collections, and it may be empty.
For every document node D
that is in the target of a mapping in available collections, or that is the root of a tree containing such a node, the document-uri property of D
must either be absent, or must be a
URI U
such that available documents contains a mapping from U
to D
.
Note:
This means that for any document node $N
retrieved using the
fn:collection
function, either directly or by navigating to the root of a
node that was returned, the result of fn:doc(fn:document-uri($N)) is $N
will always be true
, unless fn:document-uri($N)
is an empty sequence. This
implies a requirement for the fn:doc
and fn:collection
functions to be
consistent in their effect. If the implementation uses catalogs or
user-supplied URI resolvers to dereference URIs supplied to the fn:doc
function, the implementation of the fn:collection
function must take these
mechanisms into account. For example, an implementation might achieve this
by mapping the collection URI to a set of document URIs, which are then
resolved using the same catalog or URI resolver that is used by the fn:doc
function.
[Definition:
Default collection.
This is the sequence of items that would result from calling the fn:collection
function
with no arguments.] The value of default collection may be initialized by the
implementation.
[Definition:
Available
URI collections. This is a mapping of
strings to sequences of URIs. The string
represents the absolute URI of a
resource which can be interpreted as an aggregation of a number of individual resources each of which
has its own URI. The sequence of URIs represents
the result of the fn:uri-collection
function when that URI is supplied as the
argument. ] There is no implication that the URIs in this sequence
can be successfully dereferenced, or that the resources they refer to have any particular media type.
Note:
An implementation may maintain some consistent relationship between the available
collections and the available URI collections, for example by ensuring that the result of
fn:uri-collection(X)!fn:doc(.)
is the same as the result of fn:collection(X)
.
However, this is not required. The fn:uri-collection
function is more
general than fn:collection
in that
fn:collection
allows access to
nodes that might lack individual URIs, for example nodes corresponding
to XML fragments stored in the rows of a relational database.
[Definition:
Default URI collection.
This is the sequence of URIs that would result from calling the fn:uri-collection
function
with no arguments.] The value of default URI collection may be initialized by the
implementation.
[Definition: Environment variables. This is a mapping from names to values. Both the names and the values are strings. The names are compared using an implementation-defined collation, and are unique under this collation. The set of environment variables is implementation-defined and may be empty.]
Note:
A possible implementation is to provide the set of POSIX environment variables (or their equivalent on other operating systems) appropriate to the process in which the expression is evaluated.
XPath 4.0 is defined in terms of the data model and the expression context.
Figure 1: Processing Model Overview
Figure 1 provides a schematic overview of the processing steps that are discussed in detail below. Some of these steps are completely outside the domain of XPath 4.0; in Figure 1, these are depicted outside the line that represents the boundaries of the language, an area labeled external processing. The external processing domain includes generation of XDM instances that represent the data to be queried (see 2.3.1 Data Model Generation), schema import processing (see 2.3.2 Schema Import Processing) and serialization. The area inside the boundaries of the language is known as the XPath processing domain , which includes the static analysis and dynamic evaluation phases (see 2.3.3 Expression Processing). Consistency constraints on the XPath processing domain are defined in 2.3.4 Consistency Constraints.
The input data for an expression must be represented as one or more XDM instances. This process occurs outside the domain of XPath 4.0, which is why Figure 1 represents it in the external processing domain. Here are some steps by which an XML document might be converted to an XDM instance:
A document may be parsed using an XML parser that generates an XML Information Set (see [XML Infoset]). The parsed document may then be validated against one or more schemas. This process, which is described in [XML Schema 1.0 Part 1] or [XML Schema 1.1 Part 1], results in an abstract information structure called the Post-Schema Validation Infoset (PSVI). If a document has no associated schema, its Information Set is preserved. (See DM1 in Fig. 1.)
The Information Set or PSVI may be transformed into an XDM instance by a process described in [XQuery and XPath Data Model (XDM) 3.1]. (See DM2 in Fig. 1.)
The above steps provide an example of how an XDM instance might be constructed. An XDM instance might also be synthesized directly from a relational database, or constructed in some other way (see DM3 in Fig. 1.) XPath 4.0 is defined in terms of the data model, but it does not place any constraints on how XDM instances are constructed.
[Definition: Each element node and attribute node in an XDM instance has a type annotation (described in Section
2.7 Schema Information
DM31).
The type annotation of a node is a reference to an XML Schema type.
] The type-name
of a node is the name of the type referenced by its type annotation.
If the XDM instance was derived from a validated XML document as described in Section
3.3 Construction from a PSVI
DM31, the type annotations of the element and attribute nodes are derived from schema
validation. XPath 4.0 does
not provide a way to directly access the type annotation of an element
or attribute node.
The value of an attribute is represented directly within the
attribute node. An attribute node whose type is unknown (such as might
occur in a schemaless document) is given the type annotation
xs:untypedAtomic
.
The value of an element is represented by the children of the
element node, which may include text nodes and other element
nodes. The type annotation of an element node indicates how the values in
its child text nodes are to be interpreted. An element that has not been validated (such as might occur in a schemaless document) is annotated
with the schema type xs:untyped
. An element that has been validated and found to be partially valid is annotated with the schema type xs:anyType
. If an element node is annotated as xs:untyped
, all its descendant element nodes are also annotated as xs:untyped
. However, if an element node is annotated as xs:anyType
, some of its descendant element nodes may have a more specific type annotation.
The in-scope schema definitions in the static context are provided by the host language (see step SI1 in Figure 1) and must satisfy the consistency constraints defined in 2.3.4 Consistency Constraints.
XPath 4.0 defines two phases of processing called the static analysis phase and the dynamic evaluation phase (see Fig. 1). During the static analysis phase, static errors, dynamic errors, or type errors may be raised. During the dynamic evaluation phase, only dynamic errors or type errors may be raised. These kinds of errors are defined in 2.4.1 Kinds of Errors.
Within each phase, an implementation is free to use any strategy or algorithm whose result conforms to the specifications in this document.
[Definition: The static analysis phase depends on the expression itself and on the static context. The static analysis phase does not depend on input data (other than schemas).]
During the static analysis phase, the XPath expression is parsed into an internal representation called the operation tree (step SQ1 in Figure 1). A parse error is raised as a static error [err:XPST0003]. The static context is initialized by the implementation (step SQ2). The static context is used to resolve schema type names, function names, namespace prefixes, and variable names (step SQ4). If a name of one of these kinds in the operation tree is not found in the static context, a static error ([err:XPST0008] or [err:XPST0017]) is raised (however, see exceptions to this rule in 3.6.3.2 Element Test and 3.6.3.4 Attribute Test.)
The operation tree is then normalized by making explicit the implicit operations such as atomization and extraction of Effective Boolean Values (step SQ5).
During the static analysis phase, a processor may perform type analysis. The effect of type analysis is to assign a static type to each expression in the operation tree. [Definition: The static type of an expression is the best inference that the processor is able to make statically about the type of the result of the expression.] This specification does not define the rules for type analysis nor the static types that are assigned to particular expressions: the only constraint is that the inferred type must match all possible values that the expression is capable of returning.
Examples of inferred static types might be:
For the expression concat(a,b)
the inferred static type is xs:string
For the expression $a = $v
the inferred static type is xs:boolean
For the expression $s[exp]
the inferred static
type has the same item type as the static type of $s
,
but a cardinality that allows the empty sequence even if the
static type of $s
does not allow an empty
sequence.
The inferred static type of the expression data($x)
(whether written
explicitly or inserted into the operation tree in places where atomization
is implicit) depends on the inferred static type of $x
: for example, if $x
has type element(*, xs:integer)
then data($x)
has static type xs:integer
.
In XQuery 1.0 and XPath 2.0, rules for static type inferencing were published normatively in [XQuery 1.0 and XPath 2.0 Formal Semantics], but implementations were allowed to refine these rules to infer a more precise type where possible. In XQuery 3.1 and XPath 3.1, the rules for static type inferencing are entirely implementation-dependent.
Every kind of expression also imposes requirements on the type of its
operands. For example, with the expression substring($a, $b, $c)
, $a
must be
of type xs:string
(or something that can be converted to xs:string
by the
function calling rules), while $b
and $c
must be of type xs:double
.
If the
Static Typing Feature is in effect, a processor must raise a
type error during static analysis if the inferred static type of an
expression is not subsumed by the required type of the context where the
expression is used. For example, the call of substring above would cause a
type error if the inferred static type of $a
is xs:integer
; equally, a type
error would be reported during static analysis if the inferred static type
is xs:anyAtomicType
.
If the Static Typing Feature is not in effect, a processor may raise a type error during static analysis only when one of the following conditions is met:
When the inferred static type of an
expression has no overlap (intersection) with the required type, and cannot be converted
to the required type using the coercion rules. For example,
given the call fn:upper-case($s)
, the processor may raise an error if the
declared or inferred type of $s
is xs:integer
,
but not if it is xs:anyAtomicType
.
When the only possible value of an expression that is consistent with the required
type is the empty sequence. Consider for example the expression
fn:codepoints-to-string(fn:tokenize($in))
. Since fn:codepoints-to-string
requires xs:integer*
while fn:tokenize($in)
delivers xs:string*
,
this expression can succeed only in the special case where the value is empty,
so processors may report this as an error. An error
must not be raised under this rule unless both the inferred static type and the required type permit
values other than the empty sequence.
When an ForwardStep or ReverseStep is used, and it is known during static analysis that the step will select no nodes.
One example of this is an expression such as @price/text()
: attribute nodes
never have children, so this expression will never select anything.
Another example arises when schema information is available: if it is known
that the variable $emp
holds a value of type schema-element(employee)
,
and that no element of this type can have an attribute named @sallary
(sic), then
a type error may be reported if the expression $emp/@sallary
is encountered.
Note:
A static error must not be reported simply because a predicate
will always return false: the expression a[name()='b']
will always return
an empty sequence, but it is not an error.
When the KeySpecifier in a
Lookup expression is such that the result of the lookup
will inevitably be empty. For example if the context item is known to be of type
record(longitude, latitude)
then a static type error may be raised
against the expression ?altitude
.
For backwards compatibility, processors should provide
an option to avoid reporting type errors in respect of constructs such as @a/@b
that were executed without error in previous versions. Note in particular that the construct
/..
was sometimes recommended in XPath 1.0 as the preferred way to denote an empty
node-set.
Alternatively, if the Static Typing Feature is not in effect, the processor may defer all type checking until the dynamic evaluation phase.
[Definition: The dynamic evaluation phase is the phase during which the value of an expression is computed.] It is dependent on successful completion of the static analysis phase.
The dynamic evaluation phase can occur only if no errors were detected during the static analysis phase. If the Static Typing Feature is in effect, all type errors are detected during static analysis and serve to inhibit the dynamic evaluation phase.
The dynamic evaluation phase depends on the operation tree of the expression being evaluated (step DQ1), on the input data (step DQ4), and on the dynamic context (step DQ5), which in turn draws information from the external environment (step DQ3) and the static context (step DQ2). The dynamic evaluation phase may create new data-model values (step DQ4) and it may extend the dynamic context (step DQ5)—for example, by binding values to variables.
[Definition: Every value matches one or more sequence types. A value is said to have a dynamic type T if it matches (or is an instance of) the sequence type T.]
In many cases (but not all), one of the dynamic types that a value matches will be a subtype of all the others, in which case it makes sense to speak of "the dynamic type" of the value as meaning this single most specific type. In other cases (examples are empty maps and empty arrays) none of the dynamic types is more specific than all the others.
Note:
An atomic value has a type annotation which will always be a subtype of all the other types that it matches; we can therefore refer to this as the dynamic type of the atomic value without ambiguity.
A value may match a dynamic type that is more specific than the static type
of the expression that computed it (for example, the static type of an expression might be xs:integer*
,
denoting a sequence of zero or more integers, but at evaluation time its value may be an instance of xs:integer
,
denoting exactly one integer).
If an operand of an expression does not have a dynamic type that is a subtype of the static type required for that operand, a type error is raised [err:XPTY0004].
Even though static typing can catch many type errors before an expression is executed, it is possible for an expression to raise an error during evaluation that was not detected by static analysis. For example, an expression may contain a cast of a string into an integer, which is statically valid. However, if the actual value of the string at run time cannot be cast into an integer, a dynamic error will result. Similarly, an expression may apply an arithmetic operator to a value whose static type is xs:untypedAtomic
. This is not a static error, but at run time, if the value cannot be successfully cast to a numeric type, a dynamic error will be raised.
When the Static Typing Feature is in effect, it is also possible for static analysis of an expression to raise a type error, even though execution of the expression on certain inputs would be successful. For example, an expression might contain a function that requires an element as its parameter, and the static analysis phase might infer the static type of the function parameter to be an optional element. This case is treated as a type error and inhibits evaluation, even though the function call would have been successful for input data in which the optional element is present.
In order for XPath 4.0 to be well defined, the input XDM instances, the static context, and the dynamic context must be mutually consistent. The consistency constraints listed below are prerequisites for correct functioning of an XPath 4.0 implementation. Enforcement of these consistency constraints is beyond the scope of this specification. This specification does not define the result of an expression under any condition in which one or more of these constraints is not satisfied.
For every node that has a type annotation, if that type annotation is found in the in-scope schema definitions (ISSD), then its definition in the ISSD must be equivalent to its definition in the type annotation.
Every element name, attribute name, or schema type name referenced in in-scope variables or statically known function definitions must be in the in-scope schema definitions, unless it is an element name referenced as part of an ElementTest or an attribute name referenced as part of an AttributeTest.
Any reference to a global element, attribute, or type name in the in-scope schema definitions must have a corresponding element, attribute or type definition in the in-scope schema definitions.
For each mapping of a string to a document node in available documents, if there exists a mapping of the same string to a document type in statically known documents, the document node must match the document type, using the matching rules in 3.5 Sequence Type Matching.
For each mapping of a string to a sequence of items in available collections, if there exists a mapping of the same string to a type in statically known collections, the sequence of items must match the type, using the matching rules in 3.5 Sequence Type Matching.
The sequence of items in the default collection must match the statically known default collection type, using the matching rules in 3.5 Sequence Type Matching.
The value of the context item must match the context item static type, using the matching rules in 3.5 Sequence Type Matching.
For each (variable, type) pair in in-scope variables and the corresponding (variable, value) pair in variable values such that the variable names are equal, the value must match the type, using the matching rules in 3.5 Sequence Type Matching.
In the statically known namespaces, the prefix xml
must not be bound to any namespace URI other than http://www.w3.org/XML/1998/namespace
, and no prefix other than xml
may be bound to this namespace URI.
The prefix xmlns
must not be bound to any namespace URI, and no prefix may be bound to the namespace URI http://www.w3.org/2000/xmlns/
.
As described in 2.3.3 Expression Processing, XPath 4.0 defines a static analysis phase, which does not depend on input data, and a dynamic evaluation phase, which does depend on input data. Errors may be raised during each phase.
[Definition: An error that can be detected during the static analysis phase, and is not a type error, is a static error.] A syntax error is an example of a static error.
[Definition: A dynamic error is an error that must be detected during the dynamic evaluation phase and may be detected during the static analysis phase. Numeric overflow is an example of a dynamic error.]
[Definition: A type error may be raised during the static analysis phase or the dynamic evaluation phase. During the static analysis phase, a type error occurs when the static type of an expression does not match the expected type of the context in which the expression occurs. During the dynamic evaluation phase, a type error occurs when the dynamic type of a value does not match the expected type of the context in which the value occurs.]
The outcome of the static analysis phase is either success or one or more type errors, static errors, or statically detected dynamic errors. The result of the dynamic evaluation phase is either a result value, a type error, or a dynamic error.
If more than one error is present, or if an error condition comes within the scope of more than one error defined in this specification, then any non-empty subset of these errors may be reported.
During the static
analysis phase, if the
Static Typing Feature is in effect and the static type assigned to an expression other than ()
or data(())
is empty-sequence()
, a static error is raised [err:XPST0005]. This catches cases in which a query refers to an element or attribute that is not present in the in-scope schema definitions, possibly because of a spelling error.
Independently of whether the Static Typing Feature is in effect, if an implementation can determine during the static analysis phase that an XPath expression, if evaluated, would necessarily raise a dynamic error or that an expression, if evaluated, would necessarily raise a type error, the implementation may (but is not required to) report that error during the static analysis phase.
An implementation can raise a dynamic error for an XPath expression statically only if the expression can never execute without raising that error, as in the following example:
error()
The following example contains a type error, which can be reported statically even if the implementation can not prove that the expression will actually be evaluated.
if (empty($arg)) then "cat" * 2 else 0
[Definition: In addition to static errors, dynamic errors, and type errors, an XPath 4.0 implementation may raise warnings, either during the static analysis phase or the dynamic evaluation phase. The circumstances in which warnings are raised, and the ways in which warnings are handled, are implementation-defined.]
In addition to the errors defined in this specification, an implementation may raise a dynamic error for a reason beyond the scope of this specification. For example, limitations may exist on the maximum numbers or sizes of various objects. An error must be raised if such a limitation is exceeded [err:XPDY0130].
The errors defined in this specification are identified by QNames that have the form err:XPYYnnnn
, where:
err
denotes the namespace for XPath and XQuery errors, http://www.w3.org/2005/xqt-errors
. This binding of the namespace prefix err
is used for convenience in this document, and is not normative.
XP
identifies the error as an XPath error (some errors, originally defined by XQuery and later added to XPath, use the code XQ
instead).
YY
denotes the error category, using the following encoding:
ST
denotes a static error.
DY
denotes a dynamic error.
TY
denotes a type error.
nnnn
is a unique numeric code.
Note:
The namespace URI for XPath and XQuery errors is not expected to change from one version of XPath to another. However, the contents of this namespace may be extended to include additional error definitions.
The method by which an XPath 4.0 processor reports error information to the external environment is implementation-defined.
An error can be represented by a URI reference that is derived from the error QName as follows: an error with namespace URI
NS
and local part
LP
can be represented as the URI reference
NS
#
LP
. For example, an error whose QName is err:XPST0017
could be represented as http://www.w3.org/2005/xqt-errors#XPST0017
.
Note:
Along with a code identifying an error, implementations may wish to return additional information, such as the location of the error or the processing phase in which it was detected. If an implementation chooses to do so, then the mechanism that it uses to return this information is implementation-defined.
Except as noted in this document, if any operand of an expression
raises a dynamic error, the expression also raises a dynamic error.
If an expression can validly return a value or raise a dynamic
error, the implementation may choose to return the value or raise
the dynamic error (see 2.4.4 Errors and
Optimization). For example, the logical expression
expr1 and expr2
may return the value false
if either operand returns false
,
or may raise a dynamic error if either operand raises a dynamic
error.
If more than one operand of an expression raises an error, the implementation may choose which error is raised by the expression. For example, in this expression:
($x div $y) + xs:decimal($z)
both the sub-expressions ($x div $y)
and xs:decimal($z)
may
raise an error. The
implementation may choose which error is raised by the "+
"
expression. Once one operand raises an error, the implementation is
not required, but is permitted, to evaluate any other operands.
[Definition: In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called error values.] An implementation may provide a mechanism whereby an application-defined error handler can process error values and produce diagnostic messages. The host language may also provide error handling mechanisms.
A dynamic error may be raised by a built-in
function or operator. For example,
the div
operator raises an error if its operands are xs:decimal
values and its second operand
is equal to zero. Errors raised by built-in functions and operators are defined in [XQuery and XPath Functions and Operators 4.0].
A dynamic error can also be raised explicitly by calling the
fn:error
function, which always raises a dynamic error and never
returns a value. This function is defined in Section
3.1.1 fn:error
FO31. For example, the following
function call raises a dynamic
error, providing a QName that identifies the error, a descriptive string, and a diagnostic value (assuming that the prefix app
is bound to a namespace containing application-defined error codes):
fn:error(xs:QName("app:err057"), "Unexpected value", fn:string($v))
Because different implementations may choose to evaluate or optimize an expression in different ways, certain aspects of raising dynamic errors are implementation-dependent, as described in this section.
An implementation is always free to evaluate the operands of an operator in any order.
In some cases, a processor can determine the result of an expression without accessing all the data that would be implied by the formal expression semantics. For example, the formal description of filter expressions suggests that $s[1]
should be evaluated by examining all the items in sequence $s
, and selecting all those that satisfy the predicate position()=1
. In practice, many implementations will recognize that they can evaluate this expression by taking the first item in the sequence and then exiting. If $s
is defined by an expression such as //book[author eq 'Berners-Lee']
, then this strategy may avoid a complete scan of a large document and may therefore greatly improve performance. However, a consequence of this strategy is that a dynamic error or type error that would be detected if the expression semantics were followed literally might not be detected at all if the evaluation exits early. In this example, such an error might occur if there is a book
element in the input data with more than one author
subelement.
The extent to which a processor may optimize its access to data, at the cost of not raising errors, is defined by the following rules.
Consider an expression Q that has an operand (sub-expression) E. In general the value of E is a sequence. At an intermediate stage during evaluation of the sequence, some of its items will be known and others will be unknown. If, at such an intermediate stage of evaluation, a processor is able to establish that there are only two possible outcomes of evaluating Q, namely the value V or an error, then the processor may deliver the result V without evaluating further items in the operand E. For this purpose, two values are considered to represent the same outcome if their items are pairwise the same, where nodes are the same if they have the same identity, and values are the same if they are equal and have exactly the same type.
There is an exception to this rule: If a processor evaluates an operand E (wholly or in part), then it is required to establish that the actual value of the operand E does not violate any constraints on its cardinality. For example, the expression $e eq 0
results in a type error if the value of $e
contains two or more items. A processor is not allowed to decide, after evaluating the first item in the value of $e
and finding it equal to zero, that the only possible outcomes are the value true
or a type error caused by the cardinality violation. It must establish that the value of $e
contains no more than one item.
These rules apply to all the operands of an expression considered in combination: thus if an expression has two operands E1 and E2, it may be evaluated using any samples of the respective sequences that satisfy the above rules.
The rules cascade: if A is an operand of B and B is an operand of C, then the processor needs to evaluate only a sufficient sample of B to determine the value of C, and needs to evaluate only a sufficient sample of A to determine this sample of B.
The effect of these rules is that the processor is free to stop examining further items in a sequence as soon as it can establish that further items would not affect the result except possibly by causing an error. For example, the processor may return true
as the result of the expression S1 = S2
as soon as it finds a pair of equal values from the two sequences.
Another consequence of these rules is that where none of the items in a sequence contributes to the result of an expression, the processor is not obliged to evaluate any part of the sequence. Again, however, the processor cannot dispense with a required cardinality check: if an empty sequence is not permitted in the relevant context, then the processor must ensure that the operand is not an empty sequence.
Examples:
If an implementation can find (for example, by using an index) that at
least one item returned by $expr1
in the following example has the value 47
, it is allowed to
return true
as the result of the some
expression, without searching for
another item returned by $expr1
that would raise an error if it were evaluated.
some $x in $expr1 satisfies $x = 47
In the following example, if an implementation can find (for example, by using an index) the
product
element-nodes that have an id
child with the value 47
, it is allowed to return these nodes as the
result of the path expression, without searching for another product
node that
would raise an error because it has an id
child whose value is not an integer.
//product[id = 47]
For a variety of reasons, including optimization, implementations may rewrite expressions into a different form. There are a number of rules that limit the extent of this freedom:
Other than the raising or not raising of errors, the result of evaluating a rewritten expression must conform to the semantics defined in this specification for the original expression.
Note:
This allows an implementation to return a result in cases where the original expression would have raised an error, or to raise an error in cases where the original expression would have returned a result. The main cases where this is likely to arise in practice are (a) where a rewrite changes the order of evaluation, such that a subexpression causing an error is evaluated when the expression is written one way and is not evaluated when the expression is written a different way, and (b) where intermediate results of the evaluation cause overflow or other out-of-range conditions.
Note:
This rule does not mean that the result of the expression will always be the same in non-error cases as if it had not been rewritten, because there are many cases where the result of an expression is to some degree implementation-dependent or implementation-defined.
The rules described in 2.4.5 Guarded Expressions ensure that for certain kinds of expression (for example conditional expressions), changing the order of evaluation of subexpressions does not result in dynamic errors that would not otherwise occur.
Expressions must not be rewritten in such a way as to create or remove static errors. The static errors in this specification are defined for the original expression, and must be preserved if the expression is rewritten.
As stated earlier, an expression
must not be rewritten to dispense with a
required cardinality check: for example, string-length(//title)
must raise an
error if the document contains more than one title element.
[Definition: An expression E is said to be guarded by some governing condition C if evaluation of E is not allowed to fail with a dynamic error except when C applies.]
For example, in a conditional expression if (P) then T else F
, the subexpression
T is guarded by P, and the subexpression F is guarded by
not(P)
. One way an implementation can satisfy this rule is by not evaluating T unless P
is true, and likewise not evaluating F unless P is false. Another
way of satisfying the rule is for the implementation to evaluate all the subexpressions, but to catch any errors that occur
in a guarded subexpression so they are not propagated.
The existence of this rule enables errors to be prevented by writing expressions such as
if ($y eq 0) then "N/A" else ($x div $y)
. This example will never fail with a divide-by-zero
error because the else
branch of the conditional is guarded.
Similarly, in the mapping expression E1!E2
, the subexpression E2
is guarded
by the existence of an item from E1. This means, for example, that the expression (1 to $n)!doc('bad.xml')
must not raise a dynamic error if $n
is zero. The rule governing evaluation of guarded expressions
is phrased so as not to disallow “loop-lifting” or “constant-folding” optimizations
whose aim is to avoid repeated evaluation of a common subexpression;
but such optimizations must not result in errors that would not otherwise occur.
The complete list of expressions that have guarded subexpressions is as follows:
In a conditional expression (IfExpr) the then
branch
is guarded by the condition being true, and the else
branch
is guarded by the condition being false.
In an and
expression (AndExpr), the second operand
is guarded by the value of the first operand being true.
In an or
expression (OrExpr), the second operand
is guarded by the value of the first operand being false.
In an otherwise
expression (OtherwiseExpr), the second operand
is guarded by the value of the first operand being an empty sequence.
In a path expression of the form E1/E2
or E1//E2
, and in a mapping
expression of the form E1!E2
, the right-hand operand E2
is guarded by
the existence of the relevant context item in the result of evaluating E1
.
This rule applies even if E2
does not reference the context item.
For example, no dynamic error can be thrown by the expression
(1 to $n)!doc('bad.xml')
in the case where $n
is zero.
In a filter expression of the form E[P]
, the predicate P
is guarded by
the existence of the relevant context item in the result of evaluating E
.
This rule has the consequence that in a filter expression with multiple predicates, such as E[P1][P2]
,
evaluation of P2
must not raise a dynamic error unless P1
returns true. This rule does
not prevent reordering of predicates (for example, to take advantage of indexes), but it does require that any
such reordering must not result in errors that would not otherwise occur.
In a for
expression (ForExpr) such
as for $x in S return E
, the expression E
is guarded by the existence of
an item bound to $x
.
This means that the expression for $x in 1 to $n return doc('bad.xml')
must not raise a dynamic error in the case where $n
is zero.
In a quantified
expression (QuantifiedExpr) such
as some $x in S satisfies P
, the expression P
is guarded by the existence of
an item bound to $x
.
The fact that an expression is guarded does not remove the obligation to report static errors in the expression; nor does it remove the option to report statically detectable type errors.
Note:
These rules do not constrain the order of evaluation of subexpressions. For example, given an expression
such as //person[@first="Winston"][@last="Churchill"]
, or equivalently
//person[@first="Winston" and @last="Churchill"]
, an implementation might use an index on the value of
@last
to select items that satisfy the second condition, and then filter these
items on the value of the first condition. Alternatively, it might evaluate both predicates in parallel.
Or it might interpose an additional redundant condition:
//person[string-length(@first)+string-length(@last)=16][@first="Winston"][@last="Churchill"]
.
But implementations must ensure that
such rewrites do not result in dynamic errors being reported that would not occur if the predicates
were evaluated in order as written.
Note:
Although the rules for guarded expressions prevent optimizations resulting in spurious errors,
they do not prevent optimizations whose effect is to mask errors. For example, the rules guarantee that
("A", 3)[. instance of xs:integer][. eq 3]
will not raise an error caused by the comparison
("A" eq 3)
, but they
do not guarantee the converse: the expression ("A", 3)[. eq 3][. instance of xs:integer]
may or may not raise a dynamic error.
Note:
The rules in this section do not disallow all expression rewrites that might result in dynamic
errors. For example, rewriting ($x - $y + $z)
as ($x + $z - $y)
is permitted
even though it might result in an arithmetic overflow.
Note:
Some implementations allow calls on external functions that have side-effects. The semantics of such function calls are entirely implementation defined. Processors may choose to reference the rules for guarded expressions when defining the behavior of such function calls, but this is outside the scope of the language specification.
This section explains some concepts that are important to the processing of XPath 4.0 expressions.
An ordering called document order is defined among all the nodes accessible during processing of a given expression, which may consist of one or more trees (documents or fragments). Document order is defined in Section 2.4 Document Order DM31, and its definition is repeated here for convenience. Document order is a total ordering, although the relative order of some nodes is implementation-dependent. [Definition: Informally, document order is the order in which nodes appear in the XML serialization of a document.] [Definition: Document order is stable, which means that the relative order of two nodes will not change during the processing of a given expression, even if this order is implementation-dependent.] [Definition: The node ordering that is the reverse of document order is called reverse document order.]
Within a tree, document order satisfies the following constraints:
The root node is the first node.
Every node occurs before all of its children and descendants.
Namespace nodes immediately follow the element node with which they are associated. The relative order of namespace nodes is stable but implementation-dependent.
Attribute nodes immediately follow the namespace nodes of the element node with which they are associated. The relative order of attribute nodes is stable but implementation-dependent.
The relative order of siblings is the order in which they occur
in the children
property of their parent node.
Children and descendants occur before following siblings.
The relative order of nodes in distinct trees is stable but implementation-dependent, subject to the following constraint: If any node in a given tree T1 is before any node in a different tree T2, then all nodes in tree T1 are before all nodes in tree T2.
The semantics of some
XPath 4.0 operators depend on a process called atomization. Atomization is
applied to a value when the value is used in a context in which a
sequence of atomic values is required. The result of atomization is
either a sequence of atomic values or a type error
[err:FOTY0012]FO31. [Definition:
Atomization of a sequence
is defined as the result of invoking the fn:data
function, as defined in Section
2.4 fn:data
FO31.]
The semantics of
fn:data
are repeated here for convenience. The result of
fn:data
is the sequence of atomic values produced by
applying the following rules to each item in the input
sequence:
If the item is an atomic value, it is returned.
If the item is a node, its typed value is returned (a type error [err:FOTY0012]FO31 is raised if the node has no typed value.)
If the item is a function item (other than an array) or map a type error [err:FOTY0013]FO31 is raised.
If the item is an array $a
, atomization is defined as $a?* ! fn:data(.)
, which is equivalent to atomizing the members of the array.
Note:
This definition recursively atomizes members that are arrays. Hence, the result of atomizing the array [ [1, 2, 3], [4, 5, 6] ]
is the sequence (1, 2, 3, 4, 5, 6)
.
Atomization is used in processing the following types of expressions:
Arithmetic expressions
Comparison expressions
Function calls and returns
Cast expressions
Under certain circumstances (listed below), it is necessary to find
the effective boolean value of a
value. [Definition: The
effective boolean value of a value is defined as the result
of applying the fn:boolean
function to the value, as
defined in Section
7.3.1 fn:boolean
FO31.]
The dynamic semantics of fn:boolean
are repeated here for convenience:
If its operand is an empty sequence, fn:boolean
returns false
.
If its operand is a sequence whose first item is a node, fn:boolean
returns true
.
If its operand is a singleton value of type xs:boolean
or derived from xs:boolean
, fn:boolean
returns the value of its operand unchanged.
If its operand is a singleton value of type xs:string
, xs:anyURI
, xs:untypedAtomic
, or a type derived from one of these, fn:boolean
returns false
if the operand value has zero length; otherwise it returns true
.
If its operand is a singleton value of any numeric type or derived from a numeric type, fn:boolean
returns false
if the operand value is NaN
or is numerically equal to zero; otherwise it returns true
.
In all other cases, fn:boolean
raises a type error [err:FORG0006]FO31.
Note:
For instance, fn:boolean
raises a type error if the operand is a function, a map, or an array.
The effective boolean value of a sequence is computed implicitly during processing of the following types of expressions:
Logical expressions (and
, or
)
The fn:not
function
Certain types of predicates, such as a[b]
Conditional expressions (if
)
Quantified expressions (some
, every
)
General comparisons, in XPath 1.0 compatibility mode.
Note:
The definition of effective boolean
value is not used when casting a value to the
type xs:boolean
, for example in a cast
expression or when passing a value to a function whose expected
parameter is of type xs:boolean
.
XPath 4.0 has a set of functions that provide access to XML documents (fn:doc
, fn:doc-available
), collections (fn:collection
, fn:uri-collection
), text files (fn:unparsed-text
, fn:unparsed-text-lines
, fn:unparsed-text-available
), and environment variables (fn:environment-variable
, fn:available-environment-variables
). These functions are defined in Section
14.6 Functions giving access to external information
FO31.
An expression can access input data either by calling one of these input functions or by referencing some part of the dynamic context that is initialized by the external environment, such as a variable or context item.
XPath 4.0 requires a statically known, valid URI in a BracedURILiteral. An implementation may raise a static error [err:XQST0046] if the value of a Braced URI Literal is of nonzero length and is neither an absolute URI nor a relative URI.
Note:
The xs:anyURI
type is designed to anticipate the introduction of
Internationalized Resource Identifiers (IRI's) as defined in
[RFC3987].
Whitespace is normalized using the whitespace normalization rules
of fn:normalize-space
. If the result of whitespace
normalization contains only whitespace, the corresponding URI
consists of the empty string.
A Braced URI Literal or URI Literal is not subjected to percent-encoding or decoding as defined in [RFC3986].
[Definition: To
resolve a relative URI
$rel
against a
base URI $base
is to expand it to an absolute URI,
as if by calling the function fn:resolve-uri($rel,
$base)
.] During static analysis, the base URI is
the Static Base URI. During dynamic evaluation, the base URI
used to resolve a relative URI reference depends on the semantics of the
expression.
Any process that attempts to resolve URI against a base URI, or to dereference the URI, may apply percent-encoding or decoding as defined in the relevant RFCs.