Please check the errata for any errors or issues reported since publication.
See also translations.
This document is also available in these non-normative formats: XML.
Copyright © 2000 W3C® (MIT, ERCIM, Keio, Beihang). W3C liability, trademark and document use rules apply.
XML is a versatile markup language, capable of labeling the information content of diverse data sources, including structured and semi-structured documents, relational databases, and object repositories. A query language that uses the structure of XML intelligently can express queries across all these kinds of data, whether physically stored in XML or viewed as XML via middleware. This specification describes a query language called XQuery, which is designed to be broadly applicable across many types of XML data sources.
A list of changes made since XQuery 3.1 can be found in J Change Log.
This is a draft prepared by the QT4CG (officially registered in W3C as the XSLT Extensions Community Group). Comments are invited.
The publications of this community group are dedicated to our co-chair, Michael Sperberg-McQueen (1954–2024).
This section discusses each of the basic kinds of expression. Each kind of expression has a name such as PathExpr, which is introduced on the left side of the grammar production that defines the expression. Since XQuery 4.0 is a composable language, each kind of expression is defined in terms of other expressions whose operators have a higher precedence. In this way, the precedence of operators is represented explicitly in the grammar.
The order in which expressions are discussed in this document does not reflect the order of operator precedence. In general, this document introduces the simplest kinds of expressions first, followed by more complex expressions. For the complete grammar, see Appendix [A XQuery 4.0 Grammar].
[Definition: A query consists of one or more modules.] If a query is executable, one of its modules has a Query Body containing an expression whose value is the result of the query. An expression is represented in the XQuery grammar by the symbol Expr.
Expr | ::= | (ExprSingle ++ ",") |
ExprSingle | ::= | FLWORExpr |
ExprSingle | ::= | FLWORExpr |
FLWORExpr | ::= | InitialClauseIntermediateClause* ReturnClause |
QuantifiedExpr | ::= | ("some" | "every") (QuantifierBinding ++ ",") "satisfies" ExprSingle |
SwitchExpr | ::= | "switch" SwitchComparand (SwitchCases | BracedSwitchCases) |
TypeswitchExpr | ::= | "typeswitch" "(" Expr ")" (TypeswitchCases | BracedTypeswitchCases) |
IfExpr | ::= | "if" "(" Expr ")" (UnbracedActions | BracedAction) |
TryCatchExpr | ::= | TryClause ((CatchClause+ FinallyClause?) | FinallyClause) |
OrExpr | ::= | AndExpr ("or" AndExpr)* |
The XQuery 4.0 operator that has lowest precedence is the comma operator, which is used to combine two operands to form a sequence. As shown in the grammar, a general expression (Expr) can consist of multiple ExprSingle operands, separated by commas.
The name ExprSingle denotes an expression that does not contain a top-level comma operator (despite its name, an ExprSingle may evaluate to a sequence containing more than one item.)
The symbol ExprSingle is used in various places in the grammar where an expression is not allowed to contain a top-level comma. For example, each of the arguments of a function call must be a ExprSingle, because commas are used to separate the arguments of a function call.
After the comma, the expressions that have next lowest precedence are FLWORExpr,QuantifiedExpr, SwitchExpr, TypeswitchExpr, IfExpr, TryCatchExpr, and OrExpr. Each of these expressions is described in a separate section of this document.
A postfix expression takes one of the following forms:
[Definition: A filter expression is an instance of the construct FilterExpr: that is, it is an expression in the form E1[E2]. Its effect is to return those items from the value of E1 that satisfy the predicate in E2.]
Filter expressions are described in 4.4 Filter Expressions.
An example of a filter expression is (1 to 100)[. mod 2 = 0] which returns all even numbers in the range 1 to 100.
The base expression E1 can itself be a postfix expression, so multiple predicates are allowed, in the form E1[E2][E3][E4].
[Definition: is ]A dynamic function call is an instance of the construct DynamicFunctionCall: that is, it is an expression in the form E1(E2, E3, ...) in which E1 identifies a function item to be called, and the parenthesized argument list (E2, E3, ...)) identifies the arguments supplied to the function. Its effect is to evaluate E1 to obtain a function, and then call that function, with the values of expressions E2, E3, ... as arguments. Dynamic function calls are described in 4.5.3 Dynamic Function Calls.
An example of a dynamic function call is $f("a", 2) where the value of variable $f must be a function item.
[Definition: A lookup expression is an instance of the production LookupExpr: that is, an expression in the form E1?KS, where E1 is an expression returning a sequence of maps or arrays, and KS is a key specifier, which indicates which entries in a map, or members in an array, should be selected.]
Lookup expressions are described in 4.14.3.1 Postfix Lookup Expressions.
An example of a lookup expression is $emp?name, where the value of variable $emp is a map, and the string "name" is the key of one of the entries in the map.
[Definition: A filter expression for maps and arrays is an instance of the construct FilterExprAM: that is, it is an expression in the form E1?[E2]. Its effect is to evaluate E1 to return an array or map, and to select members of the array, or entries from the map, that satisfy the predicate in E2.]
Filter expressions for maps and array are described in 4.14.44.14.5 Filter Expressions for Maps and Arrays.
Postfix expressions are evaluated from left-to-right. For example, the expression $E1[E2]?(E3)(E4) is evaluated by first evaluating the filter expression $E1[E2] to produce a sequence of maps and arrays (say $S), then evaluating the lookup expression $S?(E3) to produce a function item (say $F), then evaluating the dynamic function call $F(E4) to produce the final result.
Note:
The grammar for postfix expressions is defined here in a way designed to link clearly to the semantics of the different kinds of expression. For parsing purposes, the equivalent production rule:
PostfixExpr := PrimaryExpr (Predicate | PositionalArgumentList | Lookup)*
(as used in XPath 3.1) is probably more convenient.
FilterExpr | ::= | PostfixExprPredicate |
PostfixExpr | ::= | PrimaryExpr | FilterExpr | DynamicFunctionCall | LookupExpr | MethodCall | FilterExprAM |
Predicate | ::= | "[" Expr "]" |
Expr | ::= | (ExprSingle ++ ",") |
A filter expression consists of a base expression followed by a predicate, which is an expression written in square brackets. The result of the filter expression consists of the items returned by the base expression, filtered by applying the predicate to each item in turn. The ordering of the items returned by a filter expression is the same as their order in the result of the primary expression.
Note:
Where the expression before the square brackets is an AbbreviatedStep or FullStep, the expression is technically not a filter expression but an AxisStep. There are minor differences in the semantics: see 4.6.5 Predicates within Steps
Here are some examples of filter expressions:
Given a sequence of products in a variable, return only those products whose price is greater than 100.
$products[price gt 100]
List all the integers from 1 to 100 that are divisible by 5. (See 4.7.1 Sequence Concatenation for an explanation of the to operator.)
(1 to 100)[. mod 5 eq 0]
The result of the following expression is the integer 25:
(21 to 29)[5]
The following example returns the fifth through ninth items in the sequence bound to variable $orders.
$orders[5 to 9]
The following example illustrates the use of a filter expression as a step in a path expression. It returns the last chapter or appendix within the book bound to variable $book:
$book/(chapter | appendix)[last()]
For each item in the input sequence, the predicate expression is evaluated using an inner focus, defined as follows: The context value is the item currently being tested against the predicate. The context size is the number of items in the input sequence. The context position is the position of the context value within the input sequence.
For each item in the input sequence, the result of the predicate expression is coerced to an xs:boolean value, called the predicate truth value, as described below. Those items for which the predicate truth value is true are retained, and those for which the predicate truth value is false are discarded.
[Definition: The predicate truth value of a value $V is the result of the expression if ($V instance of xs:numeric+) then ($V = position()) else fn:boolean($V).]
Expanding this definition, the predicate truth value can be obtained by applying the following rules, in order:
If the value V of the predicate expression is a sequence whose first item is an instance of the type xs:numeric, then:
V must be an instance of the type xs:numeric+ (that is, every item in V must be numeric). A type error [err:FORG0006]FO40 is raised if this is not the case.
The predicate truth value is true if V is equal (by the = operator) to the context position, and is false otherwise.
In effect this means that an item in the input sequence is selected if its position in the sequence is equal to one or more of the numeric values in the predicate. For example, the predicate [3 to 5] is true for the third, fourth, and fifth items in the input sequence.
[Definition: A predicate whose predicate expression returns a value of type xs:numeric+ is called a numeric predicate.]
Note:
It is possible, though not generally useful, for the value of a numeric predicate to depend on the focus, and thus to differ for different items in the input sequence. For example, the predicate [xs:integer(@seq)] selects those items in the input sequence whose @seq attribute is numerically equal to their position in the input sequence.
It is also possible, and again not generally useful, for the value of the predicate to be numeric for some items in the input sequence, and boolean for others. For example, the predicate [@special otherwise last()] is true for an item that either has an @special attribute, or is the last item in the input sequence.
Note:
The truth value of a numeric predicate does not depend on the order of the numbers in V. The predicates [ 1, 2, 3 ] and [ 3, 2, 1 ] have exactly the same effect. The items in the result of a filter expression always retain the ordering of the input sequence.
Note:
The truth value of a numeric predicate whose value is non-integral or non-positive is always false.
Note:
Beware that using boolean operators (and, or, not()) with numeric values may not have the intended effect. For example the predicate [1 or last()] selects every item in the sequence, because or operates on the effective boolean value of its operands. The required effect can be achieved with the predicate [1, last()].
Otherwise, the predicate truth value is the effective boolean value of the predicate expression.
Functions in XQuery 4.0 arise in two ways:
A function definition contains information about a family of functions with the same name and a defined arity range. These functions are in most cases known statically (they appear in the statically known function definitions), but there may be further function definitions that are known only dynamically (appearing in the dynamically known function definitions).
Function items are XDM items that can be called using a dynamic function call. They are values that can be bound to variables, passed as arguments, returned as function results, and generally manipulated in the same way as other XDM values.
The functions defined by a statically known function definition can be invoked using a static function call. Function items corresponding to these definitions can also be obtained, as dynamic values, by evaluating a named function reference. Function items can also be obtained using the fn:function-lookup function: in this case the function name and arity do not need to be known statically, and the function definition need not be present in the static context, so long as it is in the dynamic context.
Static and dynamic function calls are described in the following sections.
A dynamic function call consists of a base expression that returns the function and a parenthesized list of zero or more arguments (argument expressions or ArgumentPlaceholders).
A dynamic function call is evaluated as described in 4.5.3.1 Evaluating Dynamic Function Calls.
The following are examples of dynamic function calls:
This example calls the function contained in $f, passing the arguments 2 and 3:
$f(2, 3)
This example fetches the second item from sequence $f, treats it as a function and calls it, passing an xs:string argument:
$f[2]("Hi there")This example calls the function $f passing no arguments, and filters the result with a positional predicate:
$f()[2]
Note:
Arguments in a dynamic function call are always supplied positionally.
A dynamic function call can now be applied to a sequence of functions, and in particular to an empty sequence. This makes it easier to chain a sequence of calls. [Issue 1240 ]
This section applies to dynamic function calls whose arguments do not include an ArgumentPlaceholder. For function calls that include a placeholder, see 4.5.4 Partial Function Application.
A dynamic function call is an expression that is evaluated by calling a function item, which is typically obtained dynamically.
When a dynamic function call FC is evaluated, the result is obtained as follows:
The base expression of the function call is evaluated. If this is not of type function(*)* (a sequence of zero or more function items) then a type error is raised [err:XPTY0004].
The result of the dynamic function call is the sequence concatenation of the results of applying each function item individually, retaining order. That is, the result of F(X, Y, ...) is for $FI in F return $FI(X, Y, ...). The result of a dynamic function call applied to a single function item FI is defined by the rules that follow.
[err:XPTY0004]. If the arity of FI does not match the number of arguments in the ArgumentList, a type error is raised [err:XPTY0004].
Argument expressions are evaluated, producing argument values. The order of argument evaluation is implementation-dependent and an argument need not be evaluated if the function body can be evaluated without evaluating that argument.
Each argument value is converted to the corresponding parameter type in FI’s signature by applying the coercion rules, resulting in a converted argument value
If FI is a map, it is evaluated as described in 4.14.1.2 Maps as Functions.
If FI is an array, it is evaluated as described in 4.14.2.2 Arrays as Functions.
If FI’s body is an XQuery 4.0 expression (for example, if FI is a user-defined function or an anonymous function, or a partial application of such a function):
FI’s body is evaluated. The static context for this evaluation is the static context of the XQuery 4.0 expression. The dynamic context for this evaluation is obtained by taking the dynamic context of the module that contains the FunctionBody, and making the following changes:
The focus (context value, context position, and context size) is absentDM.
In the variable values component of the dynamic context, each converted argument value is bound to the corresponding parameter name.
When this is done, the converted argument values retain their dynamic types, even where these are subtypes of the declared parameter types. For example, a function with a parameter $p of type xs:decimal can be called with an argument of type xs:integer, which is derived from xs:decimal. During the processing of this function call, the value of $p inside the body of the function retains its dynamic type of xs:integer.
FI’s nonlocal variable bindings are also added to the variable values. (Note that the names of the nonlocal variables are by definition disjoint from the parameter names, so there can be no conflict.)
The value returned by evaluating the function body is then converted to the declared return type of FI by applying the coercion rules. The result is then the result of evaluating FC.
As with argument values, the value returned by a function retains its dynamic type, which may be a subtype of the declared return type of FI. For example, a function that has a declared return type of xs:decimal may in fact return a value of dynamic type xs:integer.
If the implementation of FI is not an XQuery 4.0 expression (for example, if FI is a system functionor an external function), the body of the function is evaluated, and the result is converted to the declared return type, in the same way as for a static function call (see 4.5.1.1 Static Function Call Syntax).
Errors may be raised in the same way.
$incr is a nonlocal variable that is available within the function because its variable binding has been added to the variable values of the function. Even though the parameter and return type of this function are both xs:decimal, the more specific type xs:integer is preserved in both cases.
let $incr := 1
let $f := function($i as xs:decimal) as xs:decimal { $i + $incr }
return $f(5)
The following example will raise a type error [err:XPDY0002]:
let $vat := function() { @vat + @price }
return doc('wares.xml')/shop/article/$vat()Instead, the context value can be used as an argument to the anonymous function:
let $vat := function($art) { $art/@vat + $art/@price }
return doc('wares.xml')/shop/article/$vat(.)Alternatively, the value can be referenced as a nonlocal variable binding:
let $ctx := doc('wares.xml')/shop/article
let $vat := function() { for $a in $ctx return $a/@vat + $a/@price }
return $vat()Finally, a focus function can be used. This binds the value of the argument to the context value within the function body:
let $vat := function { @vat + @price }
return $vat(doc('wares.xml')/shop/article)
Methods are described in 4.5.6.1 Methods, and are commonly used in dynamic function calls such as $rectangle?area(). In this example $rectangle is typically a map, and area is the key of one of the entries in the map, the value of the entry being a method. The lookup expression $rectangle?area returns a function item whose captured context includes the containing map, and the dynamic function call then evaluates the body of this method, which is able to access the containing map as the context item.
Such calls can be chained. For example if $rectangle?resize(2) returns a rectangle that is twice the size of the original, then $rectangle?resize(2)?area() returns the area of the enlarged rectangle.
This kind of chaining extends to the case where a method returns zero or more maps. For example, suppose that rectangles are nested, and that $rectangle?contents() delivers a sequence of zero or more rectangles. Then the expression $rectangle?area() - sum($rectangle?contents()?area()) returns the difference between the area of the containing rectangle and the total area of the contained rectangles. This works because the dynamic function call $rectangle?contents()?area() applies the function area to each of the function items in the sequence returned by the expression $rectangle?contents().
Note:
Keyword arguments are not allowed in a dynamic function call.
In inline function expressions, the keyword function may be abbreviated as fn. [Issue 1192 PR 1197 21 May 2024]
New abbreviated syntax is introduced (focus function) for simple inline functions taking a single argument. An example is fn { ../@code } [Issue 503 PR 521 30 May 2023]
An inline function may be annotated as a %method, giving it access to its containing map. [Issues 1800 1845 PRs 1817 1853 4 March 2025]
InlineFunctionExpr | ::= | Annotation* ("function" | "fn") FunctionSignature? FunctionBody |
Annotation | ::= | "%" EQName ("(" (AnnotationValue ++ ",") ")")? |
FunctionSignature | ::= | "(" ParamList ")" TypeDeclaration? |
ParamList | ::= | (VarNameAndType ** ",") |
VarNameAndType | ::= | "$" EQNameTypeDeclaration? |
EQName | ::= | QName | URIQualifiedName |
TypeDeclaration | ::= | "as" SequenceType |
SequenceType | ::= | ("empty-sequence" "(" ")") |
FunctionBody | ::= | EnclosedExpr |
EnclosedExpr | ::= | "{" Expr? "}" |
[Definition: An inline function expression is an instance of the construct InlineFunctionExpr. When evaluated, an inline function expression creates an anonymous function whose properties are defined directly in the inline function expression.] An inline function expression defines the names and types of the parameters to the function, the type of the result, and the body of the function.
An inline function expression whose FunctionSignature is omitted is known as a focus function. Focus functions are described in 4.5.6.24.5.6.1 Focus Functions.
[Definition: An anonymous function is a function item with no name. Anonymous functions may be created, for example, by evaluating an inline function expression or by partial function application.]
The keywords function and fn are synonymous.
The syntax allows the names and types of the function argument to be declared, along with the type of the result:
function($x as xs:integer, $y as xs:integer) as xs:integer { $x + $y }The types can be omitted, and the keyword can be abbreviated:
fn($x, $y) { $x + $y }A zero-arity function can be written as, for example, fn() { current-date() }.
If a function parameter is declared using a name but no type, its default type is item()*. If the result type is omitted, its default result type is item()*.
The parameters of an inline function expression are considered to be variables whose scope is the function body. It is a static error [err:XQST0039] for an inline function expression to have more than one parameter with the same name.
An inline function expression may have annotations. The only annotation; however, no annotations are defined in XQuery 4.0 for inline function expressions is the annotation %method, described in 4.5.6.1 Methods. It is a static error [err:XQST0125] if an inline function expression is annotated as %public or %private. An implementation can define annotations, in its own namespace, to support functionality beyond the scope of this specification.
The static context for the function body is inherited from the location of the inline function expression.
The variables in scope for the function body include all variables representing the function parameters, as well as all variables that are in scope for the inline function expression.
Note:
Function parameter names can mask variables that would otherwise be in scope for the function body.
The result of an inline function expression is a single function item with the following properties (as defined in Section 8.1 Function ItemsDM):
name: Absent.
identity: A new function identity distinct from the identity of any other function item.
Note:
See also 4.5.7 Function Identity.
signature: A FunctionType constructed from the Annotations andSequenceTypes in the InlineFunctionExpr. An implementation which can determine a more specific signature (for example, through use of type analysis of the function’s body) is permitted to do so.
annotations: The annotations explicitly included in the inline function expression. .
body: The FunctionBody of the InlineFunctionExpr.
captured context: the static context is the static context of the inline function expression. The dynamic context has an absent focus, and a set of variable bindings comprising the variable values component of the dynamic context of the InlineFunctionExpr.
The following are examples of some inline function expressions:
This example creates a function that takes no arguments and returns a sequence of the first 6 primes:
function() as xs:integer+ { 2, 3, 5, 7, 11, 13 }This example creates a function that takes two xs:double arguments and returns their product:
fn($a as xs:double, $b as xs:double) as xs:double { $a * $b }This example creates and invokes a function that captures the value of a local variable in its scope:
let $incrementors := (
for $x in 1 to 10
return function($y) as xs:integer { $x + $y }
)
return $incrementors[2](4)The result of this expression is 6
[Definition: A method is a function item that has the annotation %method.]
A method appearing as a value within a map can refer to the containing map as the context value. For example, given the variable:
let $rectangle := {
'height': 3,
'width': 4,
'area': %method fn() { ?height × ?width }
}The dynamic function call $rectangle?area() returns 12.
The detailed rule is as follows: When the lookup operator ? is applied to a map M (see 4.14.3 Lookup Expressions), and both the following conditions apply:
The KeySpecifier in the lookup expression is an NCName or StringLiteral;
The lookup expression selects a singleton value that is a function item F declared as a method
then the function item F′ that is returned by the lookup expression is derived from F as follows:
F′ has a captured context in which the focus is a singleton focus based on the map M.
F′ has no %method annotation and is therefore not a method.
F′ has a separate function identity from F. It is implementation dependent whether repeated evaluations of lookup expressions with the same map and the same key produce functions having the same function identity.
In all other respects F′ has the same properties as F.
Note:
Methods are typically invoked using a dynamic function call such as the call $rectangle?area() in the example above. However, a method selected using a lookup expression such as $rectangle?area can be used in the same way as any other function item. For example, it can be passed as an argument to a higher-order function, or it can be partially applied.
Although methods mimic some of the capability of object-oriented languages, the functionality is more limited:
There is no encapsulation: the entries in a map are all publicly exposed.
There is no class hierarchy, and no inheritance or overriding.
Methods within a map can be removed or replaced in the same way as any other entries in the map.
The context value in the body of a method is bound to the containing map by any lookup expression (using the ? or ?? operators) that selects the method as a singleton item within a key/value pair. It is not bound by other operations that deliver the value, for example a call on map:get or map:for-each. The result of the lookup expression is not itself a method. The means, for example that the expression:
let $rectangle1 := { 'x':3, 'y':4, 'area': %method fn() { ?x × ?y } }
let $rectangle2 := { 'x':5, 'y':5, 'area': $rectangle1?area }
return $rectangle2?area()returns 12, because the function item bound to the key "area" in $rectangle2 is an ordinary function item, not a method.
If the same method is to be used in both variables, this can be written:
let $area := %method fn() { ?x × ?y }
let $rectangle1 := { 'x':3, 'y':4, 'area': $area }
let $rectangle2 := { 'x':5, 'y':5, 'area': $area }
return $rectangle2?area()which returns 25.
An attempt to evaluate a method without binding a context item will typically result in a dynamic error indicating that the context item is not bound. Given the declaration above, the expression $area() raises a type error [err:XPDY0002] because a unary lookup expression (?x or ?y) requires the context value to be bound.
Note:
Methods can be useful when there is a need to write inline recursive functions. For example:
let $lib := {
'product': %method fn($in as xs:double*) {
if (empty( $in ))
then 1
else head($in) × ?product(tail($in))
}
}
return $lib?product((1.2, 1.3, 1.4))In an environment that supports XPath but not XQuery, this mechanism can be used to define all the functions that a particular XPath expression needs to invoke, and these functions can be mutually recursive.
Note:
Methods are often useful in conjunction with named record types: see 5.20.3 Using Methods in Records.
[Definition: A focus function is an inline function expression in which the function signature is implicit: the function takes a single argument of type item()* (that is, any value), and binds this to the context value when evaluating the function body, which returns a result of type item()*.]
Here are some examples of focus functions:
fn { @age } - a function that expects a node as its argument, and returns the @age attribute of that node.
fn { . + 1 } - a function that expects a number as its argument, and returns that number plus one.
function { `${ . }` } - a function that expects a string as its argument, and prepends a "$" character.
function { head(.) + foot(.) } - a function that expects a sequence of numbers as its argument, and returns the sum of the first and last items in the sequence.
Focus functions are often useful as arguments to simple higher-order functions such as fn:sort. For example, to sort employees by salary, write sort(//employee, (), fn { +@salary }). (The unary plus has the effect of converting the attribute’s value to a number, for numeric sorting).
Focus functions can also be useful on the right-hand side of the sequence arrow operator and mapping arrow operator. For example, $s => tokenize() =!> fn { `"{.}"` }() first tokenizes the string $s, then wraps each token in double quotation marks.
The result of calling the function { EXPR } (or fn { EXPR }), with a single argument whose value is $Z arguments, is obtained by evaluating EXPR with a fixed focus in which the context value is $Z, the context position is 1 (one), and the context size is 1 (one).
The expression function { EXPR } is thus formally equivalent to the expression function($Z as item()*) as item()* { $Z -> (EXPR) }, where $Z is some variable name that is otherwise unused. Here -> is the pipeline operator described in 4.22 Pipeline operator.
For example, the expression every(1 to 10, fn { . gt 0 }) returns true.
A focus function cannot be annotated as a method ([err:XPST0107]). (This is because the context value in a method is bound to the containing map, and is therefore not available to be bound to the function’s argument).
Path expressions are extended to handle JNodes (found in trees of maps and arrays) as well as XNodes (found in trees representing parsed XML). [Issue 2054 ]
PathExpr | ::= | AbsolutePathExpr |
| /* xgc: leading-lone-slash */ | ||
AbsolutePathExpr | ::= | ("/" RelativePathExpr?) | ("//" RelativePathExpr) |
RelativePathExpr | ::= | StepExpr (("/" | "//") StepExpr)* |
[Definition: A path expression is either an absolute path expression or a relative path expression ]
[Definition: An absolute path expression is an instance of the production AbsolutePathExpr: it consists of either (a) the operator / followed by zero or more operands separated by / or // operators, or (b) the operator // followed by one or more operands separated by / or // operators.]
[Definition: A relative path expression is a non-trivial instance of the production RelativePathExpr: it consists of two or more operand expressions separated by / or // operators.]
[Definition: The operands of a path expression are conventionally referred to as steps.]
Note:
The term step must not be confused with axis step. A step can be any kind of expression, often but not necessarily an axis step, while an axis step can be used in any expression context, not necessarily as a step in a path expression.
A path expression is typically used to locate GNodes within GTrees.
Note:
Note the terminology:
The following definitions are copied from the data model specification, for convenience:
[Definition: A tree that is rooted at a parentless JNode is referred to as a JTree.]
[Definition: A tree that is rooted at a parentless XNode is referred to as an XTree.]
[Definition: The term generic node or GNode is a collective term for XNodes (more commonly called simply nodes) representing the parts of an XML document, and JNodes, often used to represent the parts of a JSON document.]
[Definition: A JNode is a kind of item used to represent a value within the context of a tree of maps and arrays. A root JNode represents a map or array; a non-root JNode represents a member of an array or an entry in a map.]
[Definition: The term GTree means JTree or XTree.]
Absolute path expressions (those starting with an initial / or //), start their selection from the root GNode of a GTree; relative path expressions (those without a leading / or //) start from the context value.
RelativePathExpr | ::= | StepExpr (("/" | "//") StepExpr)* |
StepExpr | ::= | PostfixExpr | AxisStep |
PostfixExpr | ::= | PrimaryExpr | FilterExpr | DynamicFunctionCall | LookupExpr | MethodCall | FilterExprAM |
AxisStep | ::= | (AbbreviatedStep | FullStep) Predicate* |
A relative path expression is a path expression that selects GNodes within a GTree by following a series of steps starting at the GNodes in the context value (which may be any kind of GNode, not necessarily the root of the tree).
Each non-initial occurrence of // in a path expression is expanded as described in 4.6.7 Abbreviated Syntax, leaving a sequence of steps separated by /. This sequence of steps is then evaluated from left to right. So a path such as E1/E2/E3/E4 is evaluated as ((E1/E2)/E3)/E4. The semantics of a path expression are thus defined by the semantics of the binary / operator, which is defined in 4.6.3 Path operator (/).
Note:
Although the semantics describe the evaluation of a path with more than two steps as proceeding from left to right, the / operator is in most cases associative, so evaluation from right to left usually delivers the same result. The cases where / is not associative arise when the functions fn:position() and fn:last() are used: A/B/position() delivers a sequence of integers from 1 to the size of (A/B), whereas A/(B/position()) restarts the counting at each B element.
The following example illustrates the use of a relative path expressions to select within an XTree. It is assumed that the context value is a single XNode, referred to as the context node.
child::div1/child::para
Selects the para element children of the div1 element children of the context node; that is, the para element grandchildren of the context node that have div1 parents.
Note:
Since each step in a path provides context GNodes for the following step, in effect, only the last step in a path is allowed to return a sequence of non-GNodes.
Most modern programming languages have support for collections of key/value pairs, which may be called maps, dictionaries, associative arrays, hash tables, keyed lists, or objects (these are not the same thing as objects in object-oriented systems). In XQuery 4.0, we call these maps. Most modern programming languages also support ordered lists of values, which may be called arrays, vectors, or sequences. In XQuery 4.0, we have both sequences and arrays. Unlike sequences, an array is an item, and can appear as an item in a sequence.
Note:
The XQuery 4.0 specification focuses on syntax provided for maps and arrays, especially constructors and lookup.
Some of the functionality typically needed for maps and arrays is provided by functions defined in Section 18 Processing mapsFO and Section 19 Processing arraysFO, including functions used to read JSON to create maps and arrays, serialize maps and arrays to JSON, combine maps to create a new map, remove map entries to create a new map, iterate over the keys of a map, convert an array to create a sequence, combine arrays to form a new array, and iterate over arrays in various ways.
The lookup operator ? can now be followed by a string literal, for cases where map keys are strings other than NCNames. It can also be followed by a variable reference.
An inline function may be annotated as a %method, giving it access to its containing map. [Issues 1800 1845 PRs 1817 1853 4 March 2025]
The operator "?", known as the lookup operator, returns values found in the operand map or array.
LookupExpr | ::= | PostfixExprLookup |
PostfixExpr | ::= | PrimaryExpr | FilterExpr | DynamicFunctionCall | LookupExpr | MethodCall | FilterExprAM |
Lookup | ::= | "?" KeySpecifier |
KeySpecifier | ::= | NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard |
IntegerLiteral | ::= | Digits |
| /* ws: explicit */ | ||
Digits | ::= | DecDigit ((DecDigit | "_")* DecDigit)? |
| /* ws: explicit */ | ||
DecDigit | ::= | [0-9] |
| /* ws: explicit */ | ||
StringLiteral | ::= | AposStringLiteral | QuotStringLiteral |
| /* ws: explicit */ | ||
VarRef | ::= | "$" EQName |
ParenthesizedExpr | ::= | "(" Expr? ")" |
LookupWildcard | ::= | "*" |
A postfix Lookup has two parts: the left hand operand selects maps or arrays to be searched, and the KeySelector defines the search criteria.
First a simple example: given an array $A of maps:
[ { "John": 3, "Jill": 5}, {"Peter": 8, "Mary": 6} ]$A ? 1 ? John returns 3
$A ? 2 ? Mary returns 6
$A ? * ? * returns (3, 5, 8, 6)
$A ? * ? Peter returns 8
$A ? 2 ? * returns (8, 6)
The value of the left-hand operand must be a sequence of maps or arrays (but if it includes JNodes, these will be coerced to maps or arrays by extracting the ·content· property of the JNode). The lookup operation is applied independently to each of these maps or arrays, and the final expression result is the sequence concatenation of the individual results.
Examples:
[ 1, 2, 5, 7 ]?* evaluates to (1, 2, 5, 7).
[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]?* evaluates to ([ 1, 2, 3 ], [ 4, 5, 6 ])
[ [ 1, 2, 3 ], 4, 5 ]?*[. instance of array(xs:integer)] evaluates to ([ 1, 2, 3 ])
[ [ 1, 2, 3 ], [ 4, 5, 6 ], 7 ]?*[. instance of array(*)]?2 evaluates to (2, 5)
[ [ 1, 2, 3 ], 4, 5 ]?*[. instance of xs:integer] evaluates to (4, 5).
Lookup expressions are retained in this specification with only minor changes from the previous version 3.1. They remain a convenient solution for simple lookups of entries in maps and arrays.
For more complex queries into trees of maps and arrays, XQuery 4.0 introduces a generalization of path expressions (see 4.6 Path Expressions) which can now handle JTrees as well as XTrees.
For simple expressions, the capabilities of the two constructs overlap. For example, if $m is a map, then the expressions $m?code = 3 and $m/code = 3 have the same effect. Path expressions, however, have more power, and with it, more complexity. The expression $m/code = 3 (unless simplified by an optimizer) effectively expands the expression to (jtree($m)/child::get("code") => jnode-value()) = 3: that is, the supplied map is wrapped in a JNode, the child axis returns a sequence of JNodes, and the ·content· properties of these JNodes are compared with the supplied value 3.
Whereas simple lookups of specific entries in maps and arrays work well, experience has shown that the ?* wildcard lookup can be problematic. This is because of the flattening effect: for example, given the array let $A := [(1,2), (3,4), (), 5] the result of the expression $A?* is the sequence (1, 2, 3, 4, 5) which loses information that might be needed for further processing. By contrast, the path expression $A/* (or $A/child::*) returns a sequence of four JNodes, whose ·content· properties are respectively (1,2), (3,4), (), and 5.
The result of a lookup expression is a simple value (the value of an entry in a map or a member of an array, or the sequence concatenation of several such values). By contrast, the result of a path expression applied to maps or arrays is always a sequence of JNodes. These JNodes can be used for further navigation. If only the ·content· properties of the JNodes are needed, these will usually be extracted automatically by virtue of the coercion rules: for example if the value is used in an arithmetic expression or a value comparison, atomization of the JNode automatically extracts its ·content·. In other cases the value can be extracted explicitly by a call of the jnode-value function.
Method lookup (see 4.5.6.1 Methods4.14.4 Method Calls), as in the expression $rectangle?area() works only with the lookup operator and not with path expressions.
A method call invokes a function held as the value of an entry in a map, supplying the map implicitly as the value of the first argument. [Issue 2143 4 August 2025]
A method call combines looking up an entry in a map whose value is a function item, and calling that function item with that map as the implicit value of the first argument.
For example, given the variable:
let $rectangle := {
'height': 3,
'width': 4,
'area': fn ($rect) { $rect?height × $rect?width }
}The dynamic function call $rectangle ?> area() returns 12.
The function can also be written as a focus function:
let $rectangle := {
'height': 3,
'width': 4,
'area': fn { ?height × ?width }
}The expression M ?> N(X, Y, ...) is by definition equivalent to:
for $map as map(*) in M return ($map?N treat as function(*)) ($map, X, Y, ...)
(where $map is some otherwise unused variable name).
The argument list in a method call must not include an argument placeholder; that is, the call must not be a partial function application.
Note:
Implicit in this definition are the following rules:
The value of M must be a sequence of zero or more maps;
Each of those maps must have an entry with the key N (as an instance of xs:string, xs:untypedAtomic, or xs:anyURI);
The value of that entry must be a single function item;
That function item must have an arity equal to one plus the number of supplied arguments, and the signature of the function must allow a map to be supplied as the first argument.
The error codes raised if these conditions are not satisfied are exactly the same as if the expanded code were used directly.
Note:
Although methods mimic some of the capability of object-oriented languages, the functionality is more limited:
There is no encapsulation: the entries in a map are all publicly exposed.
There is no class hierarchy, and no inheritance or overriding.
Methods within a map can be removed or replaced in the same way as any other entries in the map.
Note:
Methods can be useful when there is a need to write inline recursive functions. For example:
let $lib := {
'product': fn($map as map(*), $in as xs:double*) {
if (empty( $in ))
then 1
else head($in) × $map ?> product(tail($in))
}
}
return $lib ?> product((1.2, 1.3, 1.4))In an environment that supports XPath but not XQuery, this mechanism can be used to define all the functions that a particular XPath expression needs to invoke, and these functions can be mutually recursive.
Note:
Methods are often useful in conjunction with named record types: see 5.20.3 Using Methods in Records.
In the example above, $rectangle ?> area(), $rectangle is typically a single map, and area is the key of one of the entries in the map, the value of the entry being a function item that takes the map as its implicit first argument. The method call $rectangle ?> area() first performs a map lookup ($rectangle?area) to select the function item, and calls the function item, supplying the containing map as the first (and in this case only) argument.
Such calls can be chained. For example if $rectangle ?> resize(2) returns a rectangle that is twice the size of the original, then $rectangle ?> resize(2) ?> area() returns the area of the enlarged rectangle.
This kind of chaining extends to the case where a method returns zero or more maps. For example, suppose that rectangles are nested, and that $rectangle ?> contents() delivers a sequence of zero or more rectangles. Then the expression $rectangle ?> area() - sum($rectangle ?> contents() ?> area()) returns the difference between the area of the containing rectangle and the total area of the contained rectangles. This works because the dynamic function call $rectangle ?> contents() ?> area() applies the area function in each of the maps the sequence returned by the expression $rectangle ?> contents().
FilterExprAM | ::= | PostfixExpr "?[" Expr "]" |
PostfixExpr | ::= | PrimaryExpr | FilterExpr | DynamicFunctionCall | LookupExpr | MethodCall | FilterExprAM |
Expr | ::= | (ExprSingle ++ ",") |
Maps and arrays can be filtered using the construct INPUT?[FILTER]. For example, $array?[count(.)=1] filters an array to retain only those members that are single items.
Note:
The character-pair ?[ forms a single token; no intervening whitespace or comment is allowed.
The required type of the left-hand operand INPUT is (map(*)|array(*))?: that is, it must be either an empty sequence, a single map, or a single array [err:XPTY0004]. However, the coercion rules also allow a JNode whose ·content· is a map or array to be supplied. If the value is an empty sequence, the result of the expression is an empty sequence.
If the value of INPUT is an array, then the FILTER expression is evaluated for each member of the array, with that member as the context value, with its position in the array as the context position, and with the size of the array as the context size. The result of the expression is an array containing those members of the input array for which the predicate truth value of the FILTER expression is true. The order of retained members is preserved.
For example, the following expression:
let $array := [ (), 1, (2, 3), (4, 5, 6) ] return $array?[count(.) ge 2]
returns:
[ (2, 3), (4, 5, 6) ]
Note:
Numeric predicates are handled in the same way as with filter expressions for sequences. However, the result is always an array, even if only one member is selected. For example, given the $array shown above, the result of $array?[3] is the single-member arrayDM[ (2, 3) ]. Contrast this with $array?3 which delivers the sequence 2, 3.
If the value of INPUT is a map, then the FILTER expression is evaluated for each entry in the map, with the context value set to an item of type record(key as xs:anyAtomicType, value as item()*), in which the key and value fields represent the key and value of the map entry. The context position is the position of the entry in the map (in entry orderDM), and the context size is the number of entries in the map. The result of the expression is a map containing those entries of the input map for which the predicate truth value of the FILTER expression is true. The relative order of entries in the result retains the relative order of entries in the input.
For example, the following expression:
let map := { 1: "alpha", 2: "beta", 3: "gamma" }
return $map?[?key ge 2]returns:
{ 2: "beta", 3: "gamma" }Note:
A filter expression such as $map?[last()-1, last()] might be used to return the last two entries of a map in entry orderDM.
A query can be assembled from one or more fragments called modules. [Definition: A module is a fragment of XQuery code that conforms to the Module grammar and can independently undergo the static analysis phase described in 2.3.3 Expression Processing. Each module is either a main module or a library module.]
[Definition: A main module consists of a Prolog followed by a Query Body.] A query has exactly one main module. In a main module, the Query Body is evaluated with respect to the static and dynamic contexts of the main module in which it is found, and its value is the result of the query.
[Definition: A module that does not contain a Query Body is called a library module. A library module consists of a module declaration followed by a Prolog.] A library module cannot be evaluated directly; instead, it provides function and variable declarations that can be imported into other modules.
The XQuery syntax does not allow a module to contain both a module declaration and a Query Body.
[Definition: A Prolog is a series of declarations and imports that define the processing environment for the module that contains the Prolog.] Each declaration or import is followed by a semicolon. A Prolog is organized into two parts.
The first part of the Prolog consists of setters, imports, namespace declarations, and default namespace declarations. [Definition: Setters are declarations that set the value of some property that affects query processing, such as construction mode or default collation.] Namespace declarations and default namespace declarations affect the interpretation of lexical QNames within the query. Imports are used to import definitions from schemas and modules. [Definition: The target namespace of a module is the namespace of the objects (such as elements or functions) that it defines. ]
The second part of the Prolog consists of declarations of variables, functions, and options. These declarations appear at the end of the Prolog because they may be affected by declarations and imports in the first part of the Prolog.
[Definition: The Query Body, if present, consists of an expression that defines the result of the query.] Evaluation of expressions is described in 4 Expressions. A module can be evaluated only if it has a Query Body.
Function definitions in the static context may now have optional parameters, provided this does not cause ambiguity across multiple function definitions with the same name. Optional parameters are given a default value, which can be any expression, including one that depends on the context of the caller (so an argument can default to the context value).
In addition to the system functions, XQuery allows users to declare functions of their own. A function declaration declares a family of functions having the same name and similar parameters. The declaration specifies the name of the function, the names and datatypes of the parameters, and the datatype of the result. All datatypes are specified using the syntax described in 3 Types.
Including a function declaration in the query causes a corresponding function definition to be added to the statically known function definitions of the static context. The associated functions also become available in the dynamically known function definitions of the dynamic context.
FunctionDecl | ::= | "declare" Annotation* "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external") |
| /* xgc: reserved-function-names */ | ||
Annotation | ::= | "%" EQName ("(" (AnnotationValue ++ ",") ")")? |
EQName | ::= | QName | URIQualifiedName |
ParamListWithDefaults | ::= | (ParamWithDefault ++ ",") |
ParamWithDefault | ::= | VarNameAndType (":=" ExprSingle)? |
VarNameAndType | ::= | "$" EQNameTypeDeclaration? |
TypeDeclaration | ::= | "as" SequenceType |
SequenceType | ::= | ("empty-sequence" "(" ")") |
ExprSingle | ::= | FLWORExpr |
FunctionBody | ::= | EnclosedExpr |
EnclosedExpr | ::= | "{" Expr? "}" |
A function declaration specifies whether the implementation of the function is user-defined or external.
In addition to user-defined functions and external functions, XQuery 4.0 allows anonymous functions to be declared in the body of a query using inline function expressions.
The following example illustrates the declaration and use of a local function that accepts a sequence of employee elements, summarizes them by department, and returns a sequence of dept elements.
declare function local:summary($emps as element(employee)*) as element(dept)* {
for $no in distinct-values($emps/deptno)
let $emp := $emps[deptno = $no]
return <dept>
<deptno>{ $no }</deptno>
<headcount>{ count($emp) }</headcount>
<payroll>{ sum($emp/salary) }</payroll>
</dept>
};
local:summary(doc("acme_corp.xml")//employee[location = "Denver"])A function declaration may use the %private or %public annotations to specify that a function is public or private; if neither of these annotations is used, the function is public. [Definition: A private function is a function with a %private annotation. A private function is hidden from module import, which can not import it into the statically known function definitions of another module. ] [Definition: A public function is a function without a %private annotation. A public function is accessible to module import, which can import it into the statically known function definitions of another module. ] Using %public and %private annotations in a main module is not an error, but it does not affect module imports, since a main module cannot be imported. It is a static error [err:XQST0106] if a function declaration contains both a %private and a %public annotation, more than one %private annotation, or more than one %public annotation.
The annotation %method is reserved for use with inline function declarations: see 4.5.6.1 Methods [err:XPST0107].
An implementation can define annotations, in its own namespace, to support functionality beyond the scope of this specification. For instance, an implementation that supports external Java functions might use an annotation to associate a Java function with an XQuery external function:
declare
%java:method("java.lang.StrictMath.copySign")
function smath:copySign($magnitude, $sign) external;Although item type declarations, as described in 5.19 Item Type Declarations, can be used to give names to record types as well as any other item type, named record types as described in this section provide a more concise syntax, plus additional functionality. In particular:
Named record types can be recursive.
Named record types implicitly create a constructor function that can be used to create instances of the record type.
A field in a named record type can be a function that has implicit access to the record on which it is defined, rather like methods in object-oriented languages.
The syntax is as follows:
NamedRecordTypeDecl | ::= | "declare" Annotation* "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")" |
Annotation | ::= | "%" EQName ("(" (AnnotationValue ++ ",") ")")? |
EQName | ::= | QName | URIQualifiedName |
ExtendedFieldDeclaration | ::= | FieldDeclaration (":=" ExprSingle)? |
FieldDeclaration | ::= | FieldName "?"? ("as" SequenceType)? |
FieldName | ::= | NCName | StringLiteral |
StringLiteral | ::= | AposStringLiteral | QuotStringLiteral |
| /* ws: explicit */ | ||
SequenceType | ::= | ("empty-sequence" "(" ")") |
ExprSingle | ::= | FLWORExpr |
ExtensibleFlag | ::= | "," "*" |
A named record declaration serves as both a named item type and as a function definition, and it therefore inherits rules from both these roles. In particular:
Its name must not be the same as the name of any other named item type, or any generalized atomic type, that is present in the same static context [err:XQST0048].
If the declaration is public and is within a library module, then its name must be in the target namespace of the library module [err:XQST0048].
As a function, it must not have an arity range that overlaps the arity range of any other function declaration having the same name in the same static context.
The order of field declarations is significant, because it determines the order of arguments in a call to the constructor function.
The fields must have distinct names. [err:XPST0021]
In order to work as both a record type and a function declaration, the names of the fields must be simple NCNames in no namespace; the names must not be written as string literals [err:XPST0003].
Note:
This is described here as a semantic constraint, but an implementation might choose to impose it at the level of the grammar.
If an initializing expression is present in an ExtendedFieldDeclaration, it must follow the rules for the initializing expression of a parameter in a function declaration, given in 5.18.3 Function Parameters. In particular, if any field has an initializing expression then all following fields must have an initializing expression.
Any annotations that are present, such as %public or %private, apply both to the item type declaration and to the function declaration.
Named record declarations are useful in conjunction with methodsmethod calls, described in 4.5.6.1 Methods4.14.4 Method Calls. For example, given the declaration:
declare record geom:rectangle(
width as xs:double,
height as xs:double,
area as fn() as xs:double := %method fn() {
?width × ?height
},
perimeter as fn() as xs:double := %method fn() {
2 × (?width + ?height)
},
expand as fn($factor as xs:double) as geom:rectangle := %method fn() {
geom:rectangle(?width × $factor, ?height × $factor)
}
);declare record geom:rectangle(
width as xs:double,
height as xs:double,
area as fn($rect as map(*)) as xs:double := fn($rect) {
$rect -> ?width × ?height
},
perimeter as fn($rect as map(*)) as xs:double := fn($rect) {
$rect -> 2 × (?width + ?height)
},
expand as fn($rect as map(*), $factor as xs:double) as geom:rectangle := fn() {
$rect -> geom:rectangle(?width × $factor, ?height × $factor)
}
);The following expression constructs a rectangle and calculates its area:
let $box := geom:rectangle(3, 2)
return $box?area()let $box := geom:rectangle(3, 2)
return $box ?> area()The following expands the dimensions of the rectangle and calculates the perimeter of the result:
let $box := geom:rectangle(3, 2)
return $box?expand(2)?perimeter()let $box := geom:rectangle(3, 2)
return $box ?> expand(2) ?> perimeter()Note:
There is nothing to stop a user constructing an instance of geom:rectangle in which the area fieldentry holds some different function: while the syntax imitates that of object-oriented languages, there is no encapsulation.
This example demonstrates an XQuery library module that provides a new data type to manipulate sets of atomic items.
A query that incorporates this module (by referencing it in an import module declaration) can use constructs such as:
declare variable $empty-set as set:atomic-set
:= set:build(());declare variable $evens as set:atomic-set
:= set:build((1 to 100)[. mod 2 = 0]);declare variable $odds as set:atomic-set
:= set:build((1 to 100)) ? except($evens)declare variable $odds as set:atomic-set
:= set:build((1 to 100)) ?> except($evens)declare function my:is-even ($n as xs:integer) as xs:boolean {
$evens ? contains($n)
};declare function my:is-even ($n as xs:integer) as xs:boolean {
$evens ?> contains($n)
};Here is the implementation of the package. It relies heavily on the use of the function annotation %method, which gives a function item contained in a map access to the containing map: methods are described in 4.5.6.1 Methods4.14.4 Method Calls.
module namespace set = "http://qt4cg.org/atomic-set";
(:
This package defines a type set:atomic-set which represents
a set of distinct atomic items. Atomic items are considered
distinct based on the comparison function fn:atomic-equal.
An instance of an atomic set can be constructed using a function
call such as set:build((1, 3, 5, 7, 9)).
If $A and $B are instances of set:atomic-set, then they
can be manipulated using methods including:
$A?size() - returns the number of items in the set
$A?empty() - returns true if the set is empty
$A?contains($k) - determines whether $k is a member of the set
$A?contains-all($B) - returns true if $B is a subset of $A
$A?values() - returns the items in $A, as a sequence
$A?add($k) - returns a new atomic set containing an additional item
$A?remove($k) - returns a new atomic set in which the given item is absent
$A?union($B) - returns a new atomic set holding the union of $A and $B
$A?intersect($B) - returns a new atomic set holding the intersection of $A and $B
$A?except($B) - returns a new atomic set holding the difference of $A and $B
:)
declare %public record set:atomic-set (
_data as map(xs:anyAtomicType, xs:boolean),
size as %method fn() as xs:integer,
empty as %method fn() as xs:boolean,
contains as %method fn($value as xs:anyAtomicType) as xs:boolean,
contains-all as %method fn($value as set:atomic-set) as xs:boolean,
add as %method fn($item as xs:anyAtomicType) as set:atomic-set,
remove as %method fn($item as xs:anyAtomicType) as set:atomic-set,
union as fn($value as set:atomic-set) as set:atomic-set,
intersect as fn($value as set:atomic-set) as set:atomic-set,
except as fn($value as set:atomic-set) as set:atomic-set,
* );
declare %private variable DATA := "'_data'";
(:
The private function set:replaceData processes the internal map
by applying a supplied function, and returns a new atomic set
with the resulting internal map
:)
declare %private function set:replaceData (
$input as set:atomic-set,
$update as fn(map(*)) as map(*)) as map(xs:anyAtomicType, xs:boolean) {
map:put($input, $DATA, $update($input?$DATA))
}
declare %public function set:build (
$values as xs:anyAtomicType* := ()) {
{
_data:
map:build($values, values:=true#0, {'duplicates': 'use-first'}),
size:
%method fn() as xs:integer
{ map:size(?$DATA) },
empty:
%method fn() as xs:boolean
{ map:empty(?$DATA) },
contains:
%method fn($value as xs:anyAtomicType) as xs:boolean
{ map:contains(?$DATA, $value) },
contains-all:
%method fn($other as set:atomic-set) as xs:boolean
{ every($value, map:contains(?$DATA, ?)) },
values:
"%method fn() as xs:anyAtomicType*
{ keys(?$DATA) }"
add:
%method fn($value as xs:anyAtomicType) as xs:anyAtomicType*
{ set:replaceData(., map:put(?, $value, true())) },
remove:
%method fn($value as xs:anyAtomicType) as xs:anyAtomicType*
{ set:replaceData(., map:remove(?, $value)) },
union:
%method fn($other as set:atomic-set) as set:atomic-set
{ set:replaceData(., fn($this) {map:merge(($this, $other?$DATA),
{'duplicates': 'use-first'})})
},
intersect:
%method fn($other as set:atomic-set) as set:atomic-set
{ set:replaceData(., map:filter(?, $other?contains)) },
except=
%method fn($other as set:atomic-set) as set:atomic-set
{ set:replaceData(., map:remove(?, $other?values())) }
}
};module namespace set = "http://qt4cg.org/atomic-set";
(:
This package defines a type set:atomic-set which represents
a set of distinct atomic items. Atomic items are considered
distinct based on the comparison function fn:atomic-equal.
An instance of an atomic set can be constructed using a function
call such as set:build((1, 3, 5, 7, 9)).
If $A and $B are instances of set:atomic-set, then they
can be manipulated using methods including:
$A?>size() - returns the number of items in the set
$A?>empty() - returns true if the set is empty
$A?>contains($k) - determines whether $k is a member of the set
$A?>contains-all($B) - returns true if $B is a subset of $A
$A?>values() - returns the items in $A, as a sequence
$A?>add($k) - returns a new atomic set containing an additional item
$A?>remove($k) - returns a new atomic set in which the given item is absent
$A?>union($B) - returns a new atomic set holding the union of $A and $B
$A?>intersect($B) - returns a new atomic set holding the intersection of $A and $B
$A?>except($B) - returns a new atomic set holding the difference of $A and $B
:)
declare %public record set:atomic-set (
_data as map(xs:anyAtomicType, xs:boolean),
size as fn($set as set:atomic-set) as xs:integer,
empty as fn($set as set:atomic-set) as xs:boolean,
contains as fn($set as set:atomic-set, $value as xs:anyAtomicType) as xs:boolean,
contains-all as fn($set as set:atomic-set, $value as set:atomic-set) as xs:boolean,
add as fn($set as set:atomic-set, $item as xs:anyAtomicType) as set:atomic-set,
remove as fn($set as set:atomic-set, $item as xs:anyAtomicType) as set:atomic-set,
union as fn($set as set:atomic-set, $value as set:atomic-set) as set:atomic-set,
intersect as fn($set as set:atomic-set, $value as set:atomic-set) as set:atomic-set,
except as fn($set as set:atomic-set, $value as set:atomic-set) as set:atomic-set,
* );
declare %private variable DATA := "'_data'";
(:
The private function set:replaceData processes the internal map
by applying a supplied function, and returns a new atomic set
with the resulting internal map
:)
declare %private function set:replaceData (
$input as set:atomic-set,
$update as fn(map(*)) as map(*)) as map(xs:anyAtomicType, xs:boolean) {
map:put($input, $DATA, $update($input?$DATA))
}
declare %public function set:build (
$values as xs:anyAtomicType* := ()) {
{
_data:
map:build($values, values:=true#0, {'duplicates': 'use-first'}),
size: fn($set as set:atomic-set) as xs:integer
{ map:size($set?$DATA) },
empty: fn($set as set:atomic-set) as xs:boolean
{ map:empty($set?$DATA) },
contains: fn($set as set:atomic-set, $value as xs:anyAtomicType) as xs:boolean
{ map:contains($set?$DATA, $value) },
contains-all: fn($set as set:atomic-set, $other as set:atomic-set) as xs:boolean
{ every($other, map:contains($set?$DATA, ?)) },
values: fn($set as set:atomic-set) as xs:anyAtomicType*
{ keys($set?$DATA) }"
add: fn($set as set:atomic-set, $value as xs:anyAtomicType) as xs:anyAtomicType*
{ set:replaceData($set, map:put(?, $value, true())) },
remove: fn($set as set:atomic-set, $value as xs:anyAtomicType) as xs:anyAtomicType*
{ set:replaceData($set, map:remove(?, $value)) },
union: fn($set as set:atomic-set, $other as set:atomic-set) as set:atomic-set
{ set:replaceData($set, fn($this) {map:merge(($this, $other?$DATA),
{'duplicates': 'use-first'})})
},
intersect: fn($set as set:atomic-set, $other as set:atomic-set) as set:atomic-set
{ set:replaceData($set, map:filter(?, $other?contains)) },
except: fn($set as set:atomic-set, $other as set:atomic-set) as set:atomic-set
{ set:replaceData($set, map:remove(?, $other?values())) }
}
};| Editorial note | |
| The example is not yet tested. It could also be written using the new xsl:record instruction, which might be more concise. | |
The grammar of XQuery 4.0 uses the same simple Extended Backus-Naur Form (EBNF) notation as [XML 1.0] with the following differences.
The notation XYZ ** "," indicates a sequence of zero or more occurrences of XYZ, with a single comma between adjacent occurrences.
The notation XYZ ++ "," indicates a sequence of one or more occurrences of XYZ, with a single comma between adjacent occurrences.
All named symbols have a name that begins with an uppercase letter.
It adds a notation for referring to productions in external specifications.
Comments or extra-grammatical constraints on grammar productions are between '/*' and '*/' symbols.
A 'xgc:' prefix is an extra-grammatical constraint, the details of which are explained in A.1.2 Extra-grammatical Constraints
A 'ws:' prefix explains the whitespace rules for the production, the details of which are explained in A.3.5 Whitespace Rules
A 'gn:' prefix means a 'Grammar Note', and is meant as a clarification for parsing rules, and is explained in A.1.3 Grammar Notes. These notes are not normative.
The terminal symbols for this grammar include the quoted strings used in the production rules below, and the terminal symbols defined in section A.3.1 Terminal Symbols. The grammar is a little unusual in that parsing and tokenization are somewhat intertwined: for more details see A.3 Lexical structure.
The EBNF notation is described in more detail in A.1.1 Notation.
This section describes how an XQuery 4.0 text is tokenized prior to parsing.
All keywords are case sensitive. Keywords are not reserved—that is, any lexical QName may duplicate a keyword except as noted in A.4 Reserved Function Names.
Tokenizing an input string is a process that follows the following rules:
[Definition: An ordinary production rule is a production rule in A.1 EBNF that is not annotated ws:explicit.]
[Definition: A literal terminal is a token appearing as a string in quotation marks on the right-hand side of an ordinary production rule.]
Note:
Strings that appear in other production rules do not qualify. For example, "]]>" is not a literal terminal, because it appears only in the rule CDataSection, which is not an ordinary production rule; similarly BracedURILiteral does not qualify because it appears only in URIQualifiedName, and "0x" does not qualify because it appears only in HexIntegerLiteral.
The literal terminals in XQuery 4.0 are: !!=#$%()*+,...///::::=;<<<<===!>=>>>=>>??>?[@[]{|||}×÷-->allowingancestorancestor-or-selfandarrayasascendingatattributebase-uriboundary-spacebycasecastcastablecatchchildcollationcommentconstructioncontextcopy-namespacescountdecimal-formatdecimal-separatordeclaredefaultdescendantdescendant-or-selfdescendingdigitdivdocumentdocument-nodeelementelseemptyempty-sequenceencodingendenumeqeveryexceptexponent-separatorexternalfalsefinallyfixedfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selffollowsforfunctiongegetgnodegreatestgroupgrouping-separatorgtidivifimportininfinityinheritinstanceintersectisis-notitemjnodekeylaxleleastletltmapmemberminus-signmodmodulenamespacenamespace-nodeNaNnenextno-inheritno-preservenodeofonlyoptionororderorderedorderingotherwiseparentpattern-separatorper-millepercentprecedesprecedingpreceding-or-selfpreceding-siblingpreceding-sibling-or-selfpreservepreviousprocessing-instructionrecordreturnsatisfiesschemaschema-attributeschema-elementselfslidingsomestablestartstrictstripswitchtextthentotreattruetrytumblingtypetypeswitchunionunorderedvalidatevaluevariableversionwhenwherewhilewindowxqueryzero-digit
[Definition: A variable terminal is an instance of a production rule that is not itself an ordinary production rule but that is named (directly) on the right-hand side of an ordinary production rule.]
The variable terminals in XQuery 4.0 are: BinaryIntegerLiteralCDataSectionDecimalLiteralDirCommentConstructorDirElemConstructorDirPIConstructorDoubleLiteralHexIntegerLiteralIntegerLiteralNCNamePragmaQNameStringConstructorStringLiteralStringTemplateURIQualifiedNameWildcard
[Definition: A complex terminal is a variable terminal whose production rule references, directly or indirectly, an ordinary production rule.]
The complex terminals in XQuery 4.0 are: DirElemConstructorPragmaStringConstructorStringTemplate
Note:
The significance of complex terminals is that at one level, a complex terminal is treated as a single token, but internally it may contain arbitrary expressions that must be parsed using the full EBNF grammar.
Tokenization is the process of splitting the supplied input string into a sequence of terminals, where each terminal is either a literal terminal or a variable terminal (which may itself be a complex terminal). Tokenization is done by repeating the following steps:
Starting at the current position, skip any whitespace and comments.
If the current position is not the end of the input, then return the longest literal terminal or variable terminal that can be matched starting at the current position, regardless whether this terminal is valid at this point in the grammar. If no such terminal can be identified starting at the current position, or if the terminal that is identified is not a valid continuation of the grammar rules, then a syntax error is reported.
Note:
Here are some examples showing the effect of the longest token rule:
The expression map{a:b} is a syntax error. Although there is a tokenization of this string that satisfies the grammar (by treating a and b as separate expressions), this tokenization does not satisfy the longest token rule, which requires that a:b is interpreted as a single QName.
The expression 10 div3 is a syntax error. The longest token rule requires that this be interpreted as two tokens ("10" and "div3") even though it would be a valid expression if treated as three tokens ("10", "div", and "3").
The expression $x-$y is a syntax error. This is interpreted as four tokens, ("$", "x-", "$", and "y").
Note:
The lexical production rules for variable terminals have been designed so that there is minimal need for backtracking. For example, if the next terminal starts with "0x", then it can only be either a HexIntegerLiteral or an error; if it starts with "`" (and not with "```") then it can only be a StringTemplate or an error. Direct element constructors and pragmas in XQuery, however, need special treatment, described below.
This convention, together with the rules for whitespace separation of tokens (see A.3.2 Terminal Delimitation) means that the longest-token rule does not normally result in any need for backtracking. For example, suppose that a variable terminal has been identified as a StringTemplate by examining its first few characters. If the construct turns out not to be a valid StringTemplate, an error can be reported without first considering whether there is some shorter token that might be returned instead.
Tokenization requires special care when the current character is U+003C (LESS-THAN SIGN, <) :
If the following character is U+003D (EQUALS SIGN, =) then the token can be identified unambiguously as the operator <=.
If the following character is U+003C (LESS-THAN SIGN, <) then the token can be identified unambiguously as the operator <<.
If the following character is U+0021 (EXCLAMATION MARK, !) then the token can be identified unambiguously as being a DirCommentConstructor (a CDataSection, which also starts with <! can appear only within a direct element constructor, not as a free-standing token).
If the following character is U+003F (QUESTION MARK, ?) , then the token is identified as a DirPIConstructor if and only if a match for the relevant production ("<?" PITarget (S DirPIContents)? "?>") is found. If there is no such match, then the string "<?" is identified as a less-than operator followed by a lookup operator.
If the following character is a NameStartChar then the token is identified as a DirElemConstructor if and only if a match for the leading part of a DirElemConstructor is found: specifically if a substring starting at the U+003C (LESS-THAN SIGN, <) character matches one of the following regular expressions:
^<\i\c*\s*>(as in<element>...)^<\i\c*\s*/>(as in<element/>)^<\i\c*\s+\i\c*\s*=(as in<element att=...)
If the content matches one of these regular expressions but further analysis shows that the subsequent content does not satisfy the DirElemConstructor production, then a static error is reported.
If the content does not match any of these regular expressions then the token is identified as the less-than operator <.
If the following character is any other character then the token can be identified unambiguously as the less-than operator <.
This analysis is done without regard to the syntactic context of the U+003C (LESS-THAN SIGN, <) character. However, a tokenizer may avoid looking for a DirPIConstructor or DirElemConstructor if it knows that such a constructor cannot appear in the current syntactic context.
Note:
The rules here are described much more precisely than in XQuery 3.1, and the results in edge cases might be incompatible with some XQuery 3.1 processors.
Note:
To avoid potential confusion, simply add whitespace after any less-than operator.
In XQuery the initial characters (# followed by whitespace are taken to signal the start of a Pragma. No backtracking takes place if this turns out not to be a valid pragma. The whitespace is necessary to distinguish a pragma from other occurrences of (#, for example a parenthesized QName literal.
Tokenization unambiguously identifies the boundaries of the terminals in the input, and this can be achieved without backtracking or lookahead. However, tokenization does not unambiguously classify each terminal. For example, it might identify the string "div" as a terminal, but it does not resolve whether this is the operator symbol div, or an NCName or QName used as a node test or as a variable or function name. Classification of terminals generally requires information about the grammatical context, and in some cases requires lookahead.
Note:
Operationally, classification of terminals may be done either in the tokenizer or the parser, or in some combination of the two. For example, according to the EBNF, the expression "parent::x" is made up of three tokens, "parent", "::", and "x". The name "parent" can be classified as an axis name as soon as the following token "::" is recognized, and this might be done either in the tokenizer or in the parser. (Note that whitespace and comments are allowed both before and after "::".)
In the case of a complex terminal, identifying the end of the complex terminal typically involves invoking the parser to process any embedded expressions. Tokenization, as described here, is therefore a recursive process. But other implementations are possible.
Note:
Previous versions of this specification included the statement: When tokenizing, the longest possible match that is consistent with the EBNF is used.
Different processors are known to have interpreted this in different ways. One interpretation, for example, was that the expression 10 div-3 should be split into four tokens (10, div, -, 3) on the grounds that any other tokenization would give a result that was inconsistent with the EBNF grammar. Other processors report a syntax error on this example.
This rule has therefore been rewritten in version 4.0. Tokenization is now entirely insensitive to the grammatical context; div-3 is recognized as a single token even though this results in a syntax error. For some implementations this may mean that expressions that were accepted in earlier releases are no longer accepted in 4.0.
A more subtle example is: (. <?b ) cast as xs:integer?> 0) in which <?b ) cast as xs:integer?> is recognized as a single token (a direct processing instruction constructor) even though such a token cannot validly appear in this grammatical context.
An absolute path expression is an instance of the production AbsolutePathExpr: it consists of either (a) the operator / followed by zero or more operands separated by / or // operators, or (b) the operator // followed by one or more operands separated by / or // operators.
An and expression is a non-trivial instance of the production AndExpr.
An anonymous function is a function item with no name. Anonymous functions may be created, for example, by evaluating an inline function expression or by partial function application.
Application functions are function definitions written in a host language such as XQuery or XSLT whose syntax and semantics are defined in this family of specifications. Their behavior (including the rules determining the static and dynamic context) follows the rules for such functions in the relevant host language specification.
An argument to a function call is either an argument expression or an ArgumentPlaceholder (?); in both cases it may either be supplied positionally, or identified by a name (called a keyword).
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.
An array is a function item that associates a set of positions, represented as positive integer keys, with values.
The value associated with a given key is called the associated value of the key.
An atomic item is a value in the value space of an atomic type, as defined in [XML Schema 1.0] or [XML Schema 1.1].
An atomic type is a simple schema type whose {variety}XS11-1 is atomic.
Atomization of a sequence is defined as the result of invoking the fn:data function, as defined in Section 2.1.4 fn:dataFO.
Available binary resources. This is a mapping of strings to binary resources. Each string represents the absolute URI of a resource. The resource is returned by the fn:unparsed-binary function when applied to that URI.
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.
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.
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.
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.
An axis step is an instance of the production AxisStep: it is an expression that returns a sequence of GNodes that are reachable from a starting GNode via a specified axis. An axis step has three parts: an axis, which defines the direction of movement for the step, a node test, which selects GNodes based on their properties, and zero or more predicates which are used to filter the results.
A base URI declaration specifies the Static Base URI property. The Static Base URI property is used when resolving relative URI references.
In a for clause, when an expression is preceded by the keyword in, the value of that expression is called a binding collection.
In a window clause, when an expression is preceded by the keyword in, the value of that expression is called a binding sequence.
A boundary-space declaration sets the boundary-space policy in the static context, overriding any implementation-defined default. Boundary-space policy controls whether boundary whitespace is preserved by element constructors during processing of the query.
Boundary-space policy. This component controls the processing of boundary whitespace by direct element constructors, as described in 4.12.1.4 Boundary Whitespace.
Boundary whitespace is a sequence of consecutive whitespace characters within the content of a direct element constructor, that is delimited at each end either by the start or end of the content, or by a DirectConstructor, or by an EnclosedExpr. For this purpose, characters generated by character references such as   or by CDataSections are not considered to be whitespace characters.
A character reference is an XML-style reference to a [Unicode] character, identified by its decimal or hexadecimal codepoint.
A choice item type defines an item type that is the union of a number of alternatives. For example the type (xs:hexBinary | xs:base64Binary) defines the union of these two primitive atomic types, while the type (map(*) | array(*)) matches any item that is either a map or an array.
The coercion rules are rules used to convert a supplied value to a required type, for example when converting an argument of a function call to the declared type of the function parameter.
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 stringsFO.
A comma operator is a comma used specifically as the operator in a sequence expression.
A complex terminal is a variable terminal whose production rule references, directly or indirectly, an ordinary production rule.
A computed element constructor creates an element node, allowing both the name and the content of the node to be computed.
When an unprefixed lexical QName is expanded using the constructed element namespace rule, then it uses the namespace URI that is bound to the empty (zero-length) prefix in the statically known namespaces of the static context. If there is no such namespace binding then it uses the no-namespace rule.
A construction declaration sets the construction mode in the static context, overriding any implementation-defined default.
Construction mode. The construction mode governs the behavior of element and document node constructors. If construction mode is preserve, the type of a constructed element node is xs:anyType, and all attribute and element nodes copied during node construction retain their original types. If construction mode is strip, the type of a constructed element node is xs:untyped; all element nodes copied during node construction receive the type xs:untyped, and all attribute nodes copied during node construction receive the type xs:untypedAtomic.
The constructor function for a given simple type is used to convert instances of other simple types into the given type. The semantics of the constructor function call T($arg) are defined to be equivalent to the expression $arg cast as T?.
In an enclosed expression, the optional expression enclosed in curly brackets is called the content expression.
A function definition is said to be context dependent if its result depends on the static or dynamic context of its caller. A function definition may be context-dependent for some arities in its arity range, and context-independent for others: for example fn:name#0 is context-dependent while fn:name#1 is context-independent.
When the context value is a single item, it can also be referred to as the context item; when it is a single node, it can also be referred to as the context node.
The context position is the position of the context value within the series of values currently being processed.
The context size is the number of values in the series of values currently being processed.
The context value is the value currently being processed.
A copy-namespaces declaration sets the value of copy-namespaces mode in the static context, overriding any implementation-defined default. Copy-namespaces mode controls the namespace bindings that are assigned when an existing element node is copied by an element constructor or document constructor.
Copy-namespaces mode. This component controls the in-scope namespaces property that is assigned when an existing element node is copied by an element constructor, as described in 4.12.1 Direct Element Constructors. Its value consists of two parts: preserve or no-preserve, and inherit or no-inherit.
Current dateTime. This information represents an implementation-dependent point in time during the processing of a query , and includes an explicit timezone. It can be retrieved by the fn:current-dateTime function. If called multiple times during the execution of a query , this function always returns the same result.
XQuery 4.0 operates on the abstract, logical structure of an XML document or JSON object rather than its surface syntax. This logical structure, known as the data model, is defined in [XQuery and XPath Data Model (XDM) 4.0].
A decimal format declaration adds a decimal format to the statically known decimal formats, which define the properties used to format numbers using the fn:format-number() function
decimal-separator(M, R) is used to separate the integer part of the number from the fractional part. The default value for both the marker and the rendition is U+002E (FULL STOP, PERIOD, .) .
When an unprefixed lexical QName is expanded using the annotation namespace rule, then it uses the namespace URI http://www.w3.org/2012/xquery.
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.
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.
A default collation declaration sets the value of the default collation in the static context, overriding any implementation-defined default.
Default collection. This is the sequence of items that would result from calling the fn:collection function with no arguments.
When an unprefixed lexical QName is expanded using the default element namespace rule, then it uses the default namespace for elements and types. If this is absent, or if it takes the special value ##any, then the no-namespace rule is used.
Default function namespace. This is either a namespace URI, or absentDM. The namespace URI, if present, is used for any unprefixed QName appearing in a position where a function name is expected.
When an unprefixed lexical QName is expanded using the default function namespace rule, it uses the default function namespace from the static context.
The default in-scope namespace of an element node
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.
Default namespace for elements and types. This is either a namespace URI, or the special value "##any", or absentDM. This indicates how unprefixed QNames are interpreted when they appear in a position where an element name or type name is expected.
Default order for empty sequences. This component controls the processing of empty sequences and NaN values as ordering keys in an order by clause in a FLWOR expression, as described in 4.13.9 Order By Clause.
Default place. This is a geographical location used to identify the place where events happened (or will happen) when processing dates and times using functions such as fn:format-date, fn:format-dateTime, and fn:civil-timezone, 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. The only requirement is that it should uniquely identify a civil timezone, which means that country codes for countries with multiple timezones, such as the United States, are inadequate.
When an unprefixed lexical QName is expanded using the default type namespace rule, it uses the default namespace for elements and types. If this is absent, the no-namespace rule is used. If the default namespace for elements and types has the special value ##any, then the lexical QName refers to a name in the namespace http://www.w3.org/2001/XMLSchema.
Default URI collection. This is the sequence of URIs that would result from calling the fn:uri-collection function with no arguments.
The delimiting terminal symbols are: !!=##)$%((#)**:+,--->->...////>::*:::=;<<!--<![CDATA[</<<<=<?==!>=>>>=>>??>?[@[]]]>]```````[`{{{{|||}}`}}×÷AposStringLiteralBracedURILiteralQuotStringLiteralSStringLiteral
A variable value (or the context value) depends on another variable value (or the context value) if, during the evaluation of the initializing expression of the former, the latter is accessed through the module context.
A schema typeS1 is said to derive fromschema typeS2 if any of the following conditions is true:
S1 is the same type as S2.
S2 is the base type of S1.
S2 is a pure union type of which S1 is a member type.
There is a schema typeM such that S1derives fromM and Mderives fromS2.
digit(M) is a character used in the picture string to represent an optional digit; the default value is U+0023 (NUMBER SIGN, #) .
A direct element constructor is a form of element constructor in which the name of the constructed element is a constant.
Informally, document order is the order in which nodes appear in the XML serialization of a document.
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 dynamic context of an expression is defined as information that is needed for the dynamic evaluation of an expression, beyond any information that is needed from the static context.
A dynamic error is an error that must be detected during the dynamic evaluation phase and may be detected during the static analysis phase.
The dynamic evaluation phase is the phase during which the value of an expression is computed.
is
Every value matches one or more sequence types. A value is said to have a dynamic typeT if it matches (or is an instance of) the sequence type T.
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 8.3.1 fn:booleanFO.
The effective case of a switch expression is the first case clause that matches, using the rules given above, or the default clause if no such case clause exists.
The effective case in a typeswitch expression is the first case clause in which the value of the operand expression matches a SequenceType in the SequenceTypeUnion of the case clause, using the rules of SequenceType matching.
When an unprefixed lexical QName is expanded using the element name matching rule rule, then it uses the default namespace for elements and types. If this is absent, then it uses the no-namespace rule. But if it takes the special value ##any, then the name is taken as matching any expanded QName with the corresponding local part, regardless of namespace: that is, the unprefixed name local is interpreted as *:local.
An empty order declaration sets the default order for empty sequences in the static context, overriding any implementation-defined default. This declaration controls the processing of empty sequences and NaN values as ordering keys in an order by clause in a FLWOR expression.
A sequence containing zero items is called an empty sequence.
An enclosed expression is an instance of the EnclosedExpr production, which allows an optional expression within curly brackets.
If present, a version declaration may optionally include an encoding declaration. The value of the string literal following the keyword encoding is an encoding name, and must conform to the definition of EncName specified in [XML 1.0] [err:XQST0087]. The purpose of an encoding declaration is to allow the writer of a query to provide a string that indicates how the query is encoded, such as "UTF-8", "UTF-16", or "US-ASCII".
Each key / value pair in a map is called an entry.
An EnumerationType accepts a fixed set of string values.
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.
Two tuples T1 and T2 have equivalent grouping keys if and only if, for each grouping variable GV, the atomized value of GV in T1 is deep-equal to the atomized value of GV in T2, as defined by applying the function fn:deep-equal using the appropriate collation.
In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called error values.
Executable Base URI. This is an absolute URI used to resolve relative URIs during the evaluation of expressions; it is used, for example, to resolve a relative URI supplied to the fn:doc or fn:unparsed-text functions.
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.
exponent-separator(M, R) is used to separate the mantissa from the exponent in scientific notation. The default value for both the marker and the rendition is U+0065 (LATIN SMALL LETTER E, e) .
The expression context for a given expression consists of all the information that can affect the result of the expression.
An extension expression is an expression whose semantics are implementation-defined.
External functions can be characterized as functions that are neither part of the processor implementation, nor written in a language whose semantics are under the control of this family of specifications. The semantics of external functions, including any context dependencies, are entirely implementation-defined. In XSLT, external functions are called Section 24.1 Extension Functions XT30.
A filter expression is an instance of the construct FilterExpr: that is, it is an expression in the form E1[E2]. Its effect is to return those items from the value of E1 that satisfy the predicate in E2.
A filter expression for maps and arrays is an instance of the construct FilterExprAM: that is, it is an expression in the form E1?[E2]. Its effect is to evaluate E1 to return an array or map, and to select members of the array, or entries from the map, that satisfy the predicate in E2.
A fixed focus is a focus for an expression that is evaluated once, rather than being applied to a series of values; in a fixed focus, the context value is set to one specific value, the context position is 1, and the context size is 1.
The first three components of the dynamic context (context value, context position, and context size) are called the focus of the expression.
A focus function is an inline function expression in which the function signature is implicit: the function takes a single argument of type item()* (that is, any value), and binds this to the context value when evaluating the function body, which returns a result of type item()*.
A function assertion is a predicate that restricts the set of functions matched by a FunctionType. It uses the same syntax as 5.15 Annotations.
Function coercion wraps a function item in a new function whose signature is the same as the expected type. This effectively delays the checking of the argument and return types until the function is called.
A function definition contains information used to evaluate a static function call, including the name, parameters, and return type of the function.
A function item is an item that can be called using a dynamic function call.
A generalized atomic type is an item type whose instances are all atomic items. Generalized atomic types include (a) atomic types, either built-in (for example xs:integer) or imported from a schema, (b) pure union types, either built-in (xs:numeric and xs:error) or imported from a schema, (c) choice item types if their alternatives are all generalized atomic types, and (d) enumeration types.
The term generic node or GNode is a collective term for XNodes (more commonly called simply nodes) representing the parts of an XML document, and JNodes, often used to represent the parts of a JSON document.
The atomized value of a grouping variable is called a grouping key.
grouping-separator(M, R) is used to separate groups of digits (for example as a thousands separator). The default value for both the marker and the rendition is U+002C (COMMA, ,) .
Each grouping specification specifies one grouping variable, which refers to variable bindings in the pre-grouping tuples. The values of the grouping variables are used to assign pre-grouping tuples to groups.
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.
Ignorable whitespace consists of any whitespace characters that may occur between terminals, unless these characters occur in the context of a production marked with a ws:explicit annotation, in which case they can occur only where explicitly specified (see A.3.5.2 Explicit Whitespace Handling).
Certain expressions, while not erroneous, are classified as being implausible, because they achieve no useful effect.
Implementation-defined indicates an aspect that may differ between implementations, but must be specified by the implementer for each particular implementation.
Implementation-dependent indicates an aspect that may differ between implementations, is not specified by this or any W3C specification, and is not required to be specified by the implementer for any particular implementation.
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.
infinity(R) is the string used to represent the double value infinity (INF); the default value is the string "Infinity"
In the dynamic context of every module in a query, the context value component must have the same setting. If this shared setting is not absentDM, it is referred to as the initial context value.
If a variable declaration includes an expression (VarValue or VarDefaultValue), the expression is called an initializing expression. The static context for an initializing expression includes all functions, variables, and namespaces that are declared or imported anywhere in the Prolog.
An inline function expression is an instance of the construct InlineFunctionExpr. When evaluated, an inline function expression creates an anonymous function whose properties are defined directly in the inline function expression.
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). If the Schema Aware Feature is supported, in-scope attribute declarations include all attribute declarations found in imported schemas.
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). If the Schema Aware Feature is supported, in-scope element declarations include all element declarations found in imported schemas.
In-scope named item types. This is a mapping from expanded QNames to named item types.
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.
In-scope schema definitions 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.
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.5 Schema Types. If the Schema Aware Feature is supported, in-scope schema types also include all type definitions found in imported schemas.
In-scope variables. This is a mapping from expanded QNames to sequence types. 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 item is either an atomic item, a node, or a function item.
An item type is a type that can be expressed using the ItemType syntax, which forms part of the SequenceType syntax. Item types match individual items.
An item type designator is a syntactic construct conforming to the grammar rule ItemType. An item type designator is said to designate an item type.
A JNode is a kind of item used to represent a value within the context of a tree of maps and arrays. A root JNode represents a map or array; a non-root JNode represents a member of an array or an entry in a map.
A tree that is rooted at a parentless JNode is referred to as a JTree.
An alternative form of a node test called a type test can select XNodes based on their type, or in the case of JNodes, the type of their contained ·content·
A lexical QName is a name that conforms to the syntax of the QName production
A module that does not contain a Query Body is called a library module. A library module consists of a module declaration followed by a Prolog.
A literal is a direct syntactic representation of an atomic item.
A literal terminal is a token appearing as a string in quotation marks on the right-hand side of an ordinary production rule.
A logical expression is either an and expression or an or expression. If a logical expression does not raise an error, its value is always one of the boolean values true or false.
A lookup expression is an instance of the production LookupExpr: that is, an expression in the form E1?KS, where E1 is an expression returning a sequence of maps or arrays, and KS is a key specifier, which indicates which entries in a map, or members in an array, should be selected.
A main module consists of a Prolog followed by a Query Body.
A map is a function that associates a set of keys with values, resulting in a collection of key / value pairs.
The mapping arrow operator=!> applies a function to each item in a sequence.
MAY means that an item is truly optional.
The values of an array are called its members.
A method is a function item that has the annotation %method.
minus-sign(R) is the string used to mark negative numbers; the default value is U+002D (HYPHEN-MINUS, -) .
A module is a fragment of XQuery code that conforms to the Module grammar and can independently undergo the static analysis phase described in 2.3.3 Expression Processing. Each module is either a main module or a library module.
A module declaration serves to identify a module as a library module. A module declaration begins with the keyword module and contains a namespace prefix and a URILiteral.
A module import imports the public variable declarations, public function declarations, and public item type declarations from one or more library modules into the statically known function definitions, in-scope variables, or in-scope named item types of the importing module.
MUST means that the item is an absolute requirement of the specification.
MUST NOT means that the item is an absolute prohibition of the specification.
A named function reference is an instance of the production NamedFunctionRef: it is an expression (written name#arity) which evaluates to a function item, the details of the function item being based on the properties of a function definition in the static context.
A named item type is an ItemType identified by an expanded QName.
When an expression is used to specify the name of a constructed node, that expression is called the name expression of the constructor.
A namespace binding is a pair comprising a namespace prefix (which is either an xs:NCName or empty), and a namespace URI.
A namespace declaration declares a namespace prefix and associates it with a namespace URI, adding the (prefix, URI) pair to the set of statically known namespaces.
A namespace declaration attribute is used inside a direct element constructor. Its purpose is to bind a namespace prefix (including the zero-length prefix) for the constructed element node, including its attributes.
The namespace-sensitive types are xs:QName, xs:NOTATION, types derived by restriction from xs:QName or xs:NOTATION, list types that have a namespace-sensitive item type, and union types with a namespace-sensitive type in their transitive membership.
A node test that consists only of an EQName or a Wildcard is called a name test.
NaN(R) is the string used to represent the double value NaN (not a number); the default value is the string "NaN"
Except where the context indicates otherwise, the term node is used as a synonym for XNode.
A node test is a condition on the properties of a GNode. A node test determines which GNodes returned by an axis are selected by a step.
When an unprefixed lexical QName is expanded using the no-namespace rule, it is interpreted as having an absent namespace URI.
The non-delimiting terminal symbols are: allowingancestorancestor-or-selfandarrayasascendingatattributebase-uriboundary-spacebycasecastcastablecatchchildcollationcommentconstructioncontextcopy-namespacescountdecimal-formatdecimal-separatordeclaredefaultdescendantdescendant-or-selfdescendingdigitdivdocumentdocument-nodeelementelseemptyempty-sequenceencodingendenumeqeveryexceptexponent-separatorexternalfalsefinallyfixedfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selffollowsforfunctiongegetgnodegreatestgroupgrouping-separatorgtidivifimportininfinityinheritinstanceintersectisis-notitemjnodekeylaxleleastletltmapmemberminus-signmodmodulenamespacenamespace-nodeNaNnenextno-inheritno-preservenodeofonlyoptionororderorderedorderingotherwiseparentpattern-separatorper-millepercentprecedesprecedingpreceding-or-selfpreceding-siblingpreceding-sibling-or-selfpreservepreviousprocessing-instructionrecordreturnsatisfiesschemaschema-attributeschema-elementselfslidingsomestablestartstrictstripswitchtextthentotreattruetrytumblingtypetypeswitchunionunorderedvalidatevaluevariableversionwhenwherewhilewindowxqueryzero-digitBinaryIntegerLiteralDecimalLiteralDoubleLiteralHexIntegerLiteralIntegerLiteralNCNameQNameURIQualifiedName
A construct is said to be a non-trivial instance of a grammatical production if it is not also an instance of one of its sub-productions.
The type xs:numeric is defined as a union type with member types xs:double, xs:float, and xs:decimal. An item that is an instance of any of these types is referred to as a numeric value, and a type that is a subtype of xs:numeric is referred to as a numeric type.
A predicate whose predicate expression returns a value of type xs:numeric+ is called a numeric predicate.
An option declaration declares an option that affects the behavior of a particular implementation. Each option consists of an identifying EQName and a StringLiteral.
An ordinary production rule is a production rule in A.1 EBNF that is not annotated ws:explicit.
An or expression is a non-trivial instance of the production OrExpr.
An output declaration is an option declaration in the namespace http://www.w3.org/2010/xslt-xquery-serialization; it is used to declare serialization parameters.
A static or dynamic function call is a partial function application if one or more arguments is an ArgumentPlaceholder.
A partially applied function is a function created by partial function application.
A path expression is either an absolute path expression or a relative path expression
pattern-separator(M) is a character used to separate positive and negative sub-pictures in a picture string; the default value is U+003B (SEMICOLON, ;) .
percent(M, R) is used to indicate that the number is written as a per-hundred fraction; the default value for both the marker and the rendition is U+0025 (PERCENT SIGN, %) .
per-mille(M, R) is used to indicate that the number is written as a per-thousand fraction; the default value for both the marker and the rendition is U+2030 (PER MILLE SIGN, ‰) .
The pipeline operator-> evaluates an expression and binds the result to the context value before evaluating another expression.
A positional variable is a variable that is preceded by the keyword at.
A pragma is denoted by the delimiters (# and #), and consists of an identifying EQName followed by implementation-defined content.
A predefined entity reference is a short sequence of characters, beginning with an ampersand, that represents a single character that might otherwise have syntactic significance.
The predicate truth value of a value $V is the result of the expression if ($V instance of xs:numeric+) then ($V = position()) else fn:boolean($V).
A primary expression is an instance of the production PrimaryExpr. Primary expressions are the basic primitives of the language. They include literals, variable references, context value references, constructors, and function calls. A primary expression may also be created by enclosing any expression in parentheses, which is sometimes helpful in controlling the precedence of operators.
Every axis has a principal node kind. If an axis can contain elements, then the principal node kind is element; otherwise, it is the kind of nodes that the axis can contain.
A private function is a function with a %private annotation. A private function is hidden from module import, which can not import it into the statically known function definitions of another module.
A private item type is a named item type with a %private annotation. A private item type is hidden from module import, which can not import it into the in-scope named item types of another module.
A private variable is a variable with a %private annotation. A private variable is hidden from module import, which can not import it into the in-scope variables of another module.
A Prolog is a series of declarations and imports that define the processing environment for the module that contains the Prolog.
A public function is a function without a %private annotation. A public function is accessible to module import, which can import it into the statically known function definitions of another module.
A public item type is an item type declaration without a %private annotation. A public item type is accessible to module import, which can import it into the in-scope named item types of another module.
A public variable is a variable without a %private annotation. A public variable is accessible to module import, which can import it into the in-scope variables of another module. Using %public and %private annotations in a main module is not an error, but it does not affect module imports, since a main module cannot be imported. It is a static error [err:XQST0116] if a variable declaration contains both a %private and a %public annotation, more than one %private annotation, or more than one %public annotation.
A pure union type is a simple type that satisfies the following constraints: (a) {variety}XS11-1 is union, (b) the {facets}XS11-1 property is empty, (c) no type in the transitive membership of the union type has {variety}XS11-1list, and (d) no type in the transitive membership of the union type is a type with {variety}XS11-1union having a non-empty {facets}XS11-1 property
A query consists of one or more modules.
The Query Body, if present, consists of an expression that defines the result of the query.
A range expression is a non-trivial instance of the production RangeExpr. A range expression is used to construct a sequence of integers.
A relative path expression is a non-trivial instance of the production RelativePathExpr: it consists of two or more operand expressions separated by / or // operators.
A reserved namespace is a namespace that must not be used in the name of a function declaration.
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).
The node ordering that is the reverse of document order is called reverse document order.
Two atomic items K1 and K2 have the same key value if fn:atomic-equal(K1, K2) returns true, as specified in Section 14.2.1 fn:atomic-equalFO
The Schema Aware Feature permits the query Prolog to contain a schema import, and permits a query to contain a validate expression (see 4.25 Validate Expressions).
A schema import imports the element declarations, attribute declarations, and type definitions from a schema into the in-scope schema definitions. For each named user-defined simple type in the schema, schema import also adds a corresponding constructor function.
A schema type is a complex type or simple type as defined in the [XML Schema 1.0] or [XML Schema 1.1] specifications, including built-in types as well as user-defined types.
A sequence is an ordered collection of zero or more items.
The sequence arrow operator=> applies a function to a supplied sequence.
The sequence concatenation of a number of sequences S1, S2, ... Sn is defined to be the sequence formed from the items of S1, followed by the items from S2, and so on, retaining order.
A sequence expression is a non-trivial instance of the production rule Expr, that is, an expression containing two or more instances of the production ExprSingle separated by the comma operator.
A sequence type is a type that can be expressed using the SequenceType syntax. Sequence types are used whenever it is necessary to refer to a type in an XQuery 4.0 expression. Since all values are sequences, every value matches one or more sequence types.
A sequence type designator is a syntactic construct conforming to the grammar rule SequenceType. A sequence type designator is said to designate a sequence type.
SequenceType matching compares a value with an expected sequence type.
Serialization is the process of converting an XDM instance to a sequence of octets (step DM4 in Figure 1.), as described in [XSLT and XQuery Serialization 4.0].
The Serialization Feature provides means for serializing the result of a query as specified in 2.3.5 Serialization.
Setters are declarations that set the value of some property that affects query processing, such as construction mode or default collation.
SHOULD means that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.
A sequence containing exactly one item is called a singleton.
An enumeration type with a single enumerated value (such as enum("red")) is an anonymous atomic type derived from xs:string by restriction using an enumeration facet that permits only the value "red". This is referred to as a singleton enumeration type.
A singleton focus is a fixed focus in which the context value is a singleton item.
Document order is stable, which means that the relative order of two nodes will not change during the processing of a given query , even if this order is implementation-dependent.
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 queries and expressions.
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.
Statically known function definitions. This is a set of function definitions.
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 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).
Static Base URI. This is an absolute URI, used to resolve relative URIs during static analysis.
The static context of an expression is the information that is available during static analysis of the expression, prior to its evaluation.
An error that can be detected during the static analysis phase, and is not a type error, is a static error.
A static function call is an instance of the production FunctionCall: it consists of an EQName followed by a parenthesized list of zero or more arguments.
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.
The operands of a path expression are conventionally referred to as steps.
A string constructor is an instance of the production StringConstructor: it is an expression that creates a string from literal text and interpolated subexpressions.
The string value of a node is a string and can be extracted by applying the Section 2.1.3 fn:stringFO function to the node.
Two sequence types are deemed to be substantively disjoint if (a) neither is a subtype of the other (see 3.3.1 Subtypes of Sequence Types) and (b) the only values that are instances of both types are one or more of the following:
The empty sequence, ().
The empty mapDM, {}.
The empty arrayDM, [].
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.
Given two sequence types or item types, the rules in this section determine if one is a subtype of the other. If a type A is a subtype of type B, it follows that every value matched by A is also matched by B.
The use of a value that has a dynamic type that is a subtype of the expected type is known as subtype substitution.
Each rule in the grammar defines one symbol, using the following format:
symbol ::= expression
Whitespace and Comments function as symbol separators. For the most part, they are not mentioned in the grammar, and may occur between any two terminal symbols mentioned in the grammar, except where that is forbidden by the /* ws: explicit */ annotation in the EBNF, or by the /* xgc: xml-version */ annotation.
System functions include the functions defined in [XQuery and XPath Functions and Operators 4.0], functions defined by the specifications of a host language, constructor functions for atomic types, and any additional functions provided by the implementation. System functions are sometimes called built-in functions.
The target namespace of a module is the namespace of the objects (such as elements or functions) that it defines.
A terminal is a symbol or string or pattern that can appear in the right-hand side of a rule, but never appears on the left-hand side in the main grammar, although it may appear on the left-hand side of a rule in the grammar for terminals.
A tuple is a set of zero or more named variables, each of which is bound to a value that is an XDM instance.
A tuple stream is an ordered sequence of zero or more tuples.
Each element node and attribute node in an XDM instance has a type annotation (described in Section 4.1 Schema InformationDM). The type annotation of a node is a reference to a schema type.
The Typed Data Feature permits an XDM instance to contain element node types other than xs:untyped and attributes node types other than xs:untypedAtomic.
A variable binding may be accompanied by a type declaration, which consists of the keyword as followed by the static type of the variable, declared using the syntax in 3.1 Sequence Types.
The typed value of a node is a sequence of atomic items and can be extracted by applying the Section 2.1.4 fn:dataFO function to the node.
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.
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.
User defined functions are functions that contain a function body, which provides the implementation of the function as a content expression.
In the data model, a value is always a sequence.
A variable declaration in the XQuery prolog defines the name and static type of a variable, and optionally a value for the variable. It adds to the in-scope variables in the static context, and may also add to the variable values in the dynamic context.
A variable reference is an EQName preceded by a $-sign.
A variable terminal is an instance of a production rule that is not itself an ordinary production rule but that is named (directly) on the right-hand side of an ordinary production rule.
Variable values. This is a mapping from expanded QNames to values. 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.
A version declaration can identify the applicable XQuery syntax and semantics for a module, as well as its encoding.
In addition to static errors, dynamic errors, and type errors, an XQuery 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.
A whitespace character is any of the characters defined by [http://www.w3.org/TR/REC-xml/#NT-S].
In these rules, if MU and NU are NameTestUnions, then MUwildcard-matchesNU is true if every name that matches MU also matches NU.
A window is a sequence of consecutive items drawn from the binding sequence.
The term XDM instance is used, synonymously with the term value, to denote an unconstrained sequence of items.
An XNode is an instance of one of the node kinds defined in Section 7.1 XML NodesDM.
XPath 1.0 compatibility mode.This component must be set by all host languages that include XPath 3.1 as a subset, indicating whether rules for compatibility with XPath 1.0 are in effect. XQuery sets the value of this component to false.
An XQuery 1.0 Processor processes a query according to the XQuery 1.0 specification.
An XQuery 3.0 Processor processes a query according to the XQuery 3.0 specification.
An XQuery 3.1 Processor processes a query according to the XQuery 3.1 specification.
An XQuery 4.0 Processor processes a query according to the XQuery 4.0 specification.
An XQuery version number consists of two integers, referred to as the major version number and the minor version number.
xs:anyAtomicType is an atomic type that includes all atomic items (and no values that are not atomic). Its base type is xs:anySimpleType from which all simple types, including atomic, list, and union types, are derived. All primitive atomic types, such as xs:decimal and xs:string, have xs:anyAtomicType as their base type.
xs:dayTimeDuration is derived by restriction from xs:duration. The lexical representation of xs:dayTimeDuration is restricted to contain only day, hour, minute, and second components.
xs:error is a simple type with no value space. It is defined in Section 3.16.7.3 xs:error XS11-1 and can be used in the 3.1 Sequence Types to raise errors.
xs:untyped is used as the type annotation of an element node that has not been validated, or has been validated in skip mode.
xs:untypedAtomic is an atomic type that is used to denote untyped atomic data, such as text that has not been assigned a more specific type.
xs:yearMonthDuration is derived by restriction from xs:duration. The lexical representation of xs:yearMonthDuration is restricted to contain only year and month components.
A tree that is rooted at a parentless XNode is referred to as an XTree.
zero-digit(M) is the character used in the picture string to represent the digit zero; the default value is U+0030 (DIGIT ZERO, 0) . 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 in the function output: 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.
Use the arrows to browse significant changes since the 3.1 version of this specification.
See 1 Introduction
Sections with significant changes are marked Δ in the table of contents.
See 1 Introduction
Setting the default namespace for elements and types to the special value ##any causes an unprefixed element name to act as a wildcard, matching by local name regardless of namespace.
The terms FunctionType, ArrayType, MapType, and RecordType replace FunctionTest, ArrayTest, MapTest, and RecordTest, with no change in meaning.
Record types are added as a new kind of ItemType, constraining the value space of maps.
Function coercion now allows a function with arity N to be supplied where a function of arity greater than N is expected. For example this allows the function true#0 to be supplied where a predicate function is required.
PR 1817 1853
An inline function may be annotated as a %method, giving it access to its containing map.
See 4.5.6 Inline Function Expressions
See 4.5.6.1 Methods
The symbols × and ÷ can be used for multiplication and division.
The rules for value comparisons when comparing values of different types (for example, decimal and double) have changed to be transitive. A decimal value is no longer converted to double, instead the double is converted to a decimal without loss of precision. This may affect compatibility in edge cases involving comparison of values that are numerically very close.
Operators such as < and > can use the full-width forms < and > to avoid the need for XML escaping.
Operator is-not is introduced, as a complement to the operator is.
Operators precedes and follows are introduced as synonyms for operators << and >>.
PR 1480 1989
When the element name matches a language keyword such as div or value, it must now be written as a QName literal. This is a backwards incompatible change.
See 4.12.3.1 Computed Element Constructors
When the attribute name matches a language keyword such as by or of, it must now be written as a QName literal. This is a backwards incompatible change.
PR 1513 2028
When the processing instruction name matches a language keyword such as try or validate, it must now be written with a preceding # character. This is a backwards incompatible change.
See 4.12.3.5 Computed Processing Instruction Constructors
When the namespace prefix matches a language keyword such as as or at, it must now be written with a preceding # character. This is a backwards incompatible change.
The lookup operator ? can now be followed by a string literal, for cases where map keys are strings other than NCNames. It can also be followed by a variable reference.
PR 1763 1830
The syntax on the right-hand side of an arrow operator has been relaxed; a dynamic function call no longer needs to start with a variable reference or a parenthesized expression, it can also be (for example) an inline function expression or a map or array constructor.
The arrow operator => is now complemented by a “mapping arrow” operator =!> which applies the supplied function to each item in the input sequence independently.
All implementations must now predeclare the namespace prefixes math, map, array, and err. In XQuery 3.1 it was permitted but not required to predeclare these namespaces.
PR 254 2050
The supplied context value is now coerced to the required type specified in the main module using the coercion rules.
Function definitions in the static context may now have optional parameters, provided this does not cause ambiguity across multiple function definitions with the same name. Optional parameters are given a default value, which can be any expression, including one that depends on the context of the caller (so an argument can default to the context value).
PR 682 TODO
The values true() and false() are allowed in function annotations, as well as negated numeric literals and QName literals.
PR 1023 1128
It has been clarified that function coercion applies even when the supplied function item matches the required function type. This is to ensure that arguments supplied when calling the function are checked against the signature of the required function type, which might be stricter than the signature of the supplied function item.
A dynamic function call can now be applied to a sequence of functions, and in particular to an empty sequence. This makes it easier to chain a sequence of calls.
Parts of the static context that were there purely to assist in static typing, such as the statically known documents, were no longer referenced and have therefore been dropped.
The syntax document-node(N), where N is a NameTestUnion, is introduced as an abbreviation for document-node(element(N)). For example, document-node(*) matches any well-formed XML document (as distinct from a document fragment).
See 3.2.7 Node Types
QName literals are new in 4.0.
Path expressions are extended to handle JNodes (found in trees of maps and arrays) as well as XNodes (found in trees representing parsed XML).
A method call invokes a function held as the value of an entry in a map, supplying the map implicitly as the value of the first argument.
PR 159
Keyword arguments are allowed on static function calls, as well as positional arguments.
PR 202
The presentation of the rules for the subtype relationship between sequence types and item types has been substantially rewritten to improve clarity; no change to the semantics is intended.
PR 230
The rules for “errors and optimization” have been tightened up to disallow many cases of optimizations that alter error behavior. In particular there are restrictions on reordering the operands of and and or, and of predicates in filter expressions, in a way that might allow the processor to raise dynamic errors that the author intended to prevent.
PR 254
The term "function conversion rules" used in 3.1 has been replaced by the term "coercion rules".
The coercion rules allow “relabeling” of a supplied atomic item where the required type is a derived atomic type: for example, it is now permitted to supply the value 3 when calling a function that expects an instance of xs:positiveInteger.
The value bound to a variable in a let clause is now converted to the declared type by applying the coercion rules.
The coercion rules are now used when binding values to variables (both global variable declarations and local variable bindings). This aligns XQuery with XSLT, and means that the rules for binding to variables are the same as the rules for binding to function parameters.
PR 284
Alternative syntax for conditional expressions is available: if (condition) { X }.
PR 286
Element and attribute tests can include alternative names: element(chapter|section), attribute(role|class).
See 3.2.7 Node Types
The NodeTest in an AxisStep now allows alternatives: ancestor::(section|appendix)
See 3.2.7 Node Types
Element and attribute tests of the form element(N) and attribute(N) now allow N to be any NameTest, including a wildcard.
PR 324
String templates provide a new way of constructing strings: for example `{$greeting}, {$planet}!` is equivalent to $greeting || ', ' || $planet || '!'
PR 326
Support for higher-order functions is now a mandatory feature (in 3.1 it was optional).
See 6 Conformance
PR 344
A for member clause is added to FLWOR expressions to allow iteration over an array.
PR 364
Switch expressions now allow a case clause to match multiple atomic items.
PR 368
The concept of the context item has been generalized, so it is now a context value. That is, it is no longer constrained to be a single item.
PR 433
Numeric literals can now be written in hexadecimal or binary notation; and underscores can be included for readability.
PR 483
The start clause in window expressions has become optional, as well as the when keyword and its associated expression.
PR 493
A new variable $err:map is available, capturing all error information in one place.
PR 519
The rules for tokenization have been largely rewritten. In some cases the revised specification may affect edge cases that were handled in different ways by different 3.1 processors, which could lead to incompatible behavior.
PR 521
New abbreviated syntax is introduced (focus function) for simple inline functions taking a single argument. An example is fn { ../@code }
PR 587
Switch and typeswitch expressions can now be written with curly brackets, to improve readability.
PR 603
The rules for reporting type errors during static analysis have been changed so that a processor has more freedom to report errors in respect of constructs that are evidently wrong, such as @price/@value, even though dynamic evaluation is defined to return an empty sequence rather than an error.
PR 606
Element and attribute tests of the form element(A|B) and attribute(A|B) are now allowed.
PR 635
The rules for the consistency of schemas imported by different query modules, and for consistency between imported schemas and those used for validating input documents, have been defined with greater precision. It is now recognized that these schemas will not always be identical, and that validation with respect to different schemas may produce different outcomes, even if the components of one are a subset of the components of the other.
PR 659
In previous versions the interpretation of location hints in import schema declarations was entirely at the discretion of the processor. To improve interoperability, XQuery 4.0 recommends (but does not mandate) a specific strategy for interpreting these hints.
PR 678
The comparand expression in a switch expression can be omitted, allowing the switch cases to be provided as arbitrary boolean expressions.
PR 691
Enumeration types are added as a new kind of ItemType, constraining the value space of strings.
PR 728
The syntax record(*) is allowed; it matches any map.
PR 753
The default namespace for elements and types can now be declared to be fixed for a query module, meaning it is unaffected by a namespace declaration appearing on a direct element constructor.
PR 815
The coercion rules now allow conversion in either direction between xs:hexBinary and xs:base64Binary.
PR 820
The value bound to a variable in a for clause is now converted to the declared type by applying the coercion rules.
PR 911
The coercion rules now allow any numeric type to be implicitly converted to any other, for example an xs:double is accepted where the required type is xs:decimal.
PR 943
A FLWOR expression may now include a while clause, which causes early exit from the iteration when a condition is encountered.
PR 996
The value of a predicate in a filter expression can now be a sequence of integers.
PR 1031
An otherwise operator is introduced: A otherwise B returns the value of A, unless it is an empty sequence, in which case it returns the value of B.
PR 1071
In map constructors, the keyword map is now optional, so map { 0: false(), 1: true() } can now be written { 0: false(), 1: true() }, provided it is used in a context where this creates no ambiguity.
PR 1132
Choice item types (an item type allowing a set of alternative item types) are introduced.
PR 1163
Filter expressions for maps and arrays are introduced.
PR 1181
The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.
If the default namespace for elements and types has the special value ##any, then an unprefixed name in a NameTest acts as a wildcard, matching names in any namespace or none.
The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.
PR 1197
The keyword fn is allowed as a synonym for function in function types, to align with changes to inline function declarations.
In inline function expressions, the keyword function may be abbreviated as fn.
PR 1212
XQuery 3.0 included empty-sequence and item as reserved function names, and XQuery 3.1 added map and array. This was unnecessary since these names never appear followed by a left parenthesis at the start of an expression. They have therefore been removed from the list. New keywords introducing item types, such as record and enum, have not been included in the list.
PR 1217
Predicates in filter expressions for maps and arrays can now be numeric.
PR 1249
A for key/value clause is added to FLWOR expressions to allow iteration over a map.
PR 1250
Several decimal format properties, including minus sign, exponent separator, percent, and per-mille, can now be rendered as arbitrary strings rather than being confined to a single character.
PR 1254
The rules concerning the interpretation of xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes have been tightened up.
PR 1265
The rules regarding the document-uri property of nodes returned by the fn:collection function have been relaxed.
PR 1342
The ordered { E } and unordered { E } expressions are retained for backwards compatibility reasons, but in XQuery 4.0 they are deprecated and have no useful effect.
See 4.15 Ordered and Unordered Expressions
The ordering mode declaration is retained for backwards compatibility reasons, but in XQuery 4.0 it is deprecated and has no useful effect.
PR 1344
Parts of the static context that were there purely to assist in static typing, such as the statically known documents, were no longer referenced and have therefore been dropped.
The static typing option has been dropped.
The static typing feature has been dropped.
See 6 Conformance
PR 1361
The term atomic value has been replaced by atomic item.
See 2.1.3 Values
PR 1384
If a type declaration is present, the supplied values in the input sequence are now coerced to the required type. Type declarations are now permitted in XPath as well as XQuery.
PR 1432
In earlier versions, the static context for the initializing expression excluded the variable being declared. This restriction has been lifted.
PR 1470
$err:stack-trace provides information about the current state of execution.
PR 1496
The context value static type, which was there purely to assist in static typing, has been dropped.
PR 1498
The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.
See 2.1 Terminology
The EBNF notation has been extended to allow the constructs (A ++ ",") (one or more occurrences of A, comma-separated, and (A ** ",") (zero or more occurrences of A, comma-separated.
The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.
See A.1 EBNF
See A.1.1 Notation
PR 1501
The coercion rules now apply recursively to the members of an array and the entries in a map.
PR 1532
Four new axes have been defined: preceding-or-self, preceding-sibling-or-self, following-or-self, and following-sibling-or-self.
See 4.6.4.1 Axes
PR 1577
The syntax record() is allowed; the only thing it matches is an empty map.
PR 1686
With the pipeline operator ->, the result of an expression can be bound to the context value before evaluating another expression.
PR 1696
Parameter names may be included in a function signature; they are purely documentary.
PR 1703
Ordered maps are introduced.
See 4.14.1 Maps
The order of key-value pairs in the map constructor is now retained in the constructed map.
PR 1874
The coercion rules now reorder the entries in a map when the required type is a record type.
PR 1898
The rules for subtyping of document node types have been refined.
PR 1914
A finally clause can be supplied, which will always be evaluated after the expressions of the try/catch clauses.
PR 1956
Private variables declared in a library module are no longer required to be in the module namespace.
Private functions declared in a library module are no longer required to be in the module namespace.
PR 1982
Whitespace is now required after the opening (# of a pragma. This is an incompatible change, made to ensure that an expression such as error(#err:XPTY0004) can be parsed as a function call taking a QName literal as its argument value.
PR 1991
Named record types used in the signatures of built-in functions are now available as standard in the static context.
PR 2026
The module feature is no longer an optional feature; processing of library modules is now required.
See 6 Conformance
PR 2030
The technical details of how validation works have been moved to the Functions and Operators specification. The XQuery validate expression is now defined in terms of the new xsd-validator function.
PR 2031
The terms XNode and JNode are introduced; the existing term node remains in use as a synonym for XNode where the context does not specify otherwise.
See 2.1.3 Values
JNodes are introduced
PR 2055
Sequences, arrays, and maps can be destructured in a let clause to extract their components into multiple variables.
PR 2094
A general expression is allowed within a map constructor; this facilitates the creation of maps in which the presence or absence of particular keys is decided dynamically.
PR 2115
This section describes and formalizes a convention that was already in use, but not explicitly stated, in earlier versions of the specification.