View Old View New View Both View Only Previous Next

This draft contains only sections that have differences from the version that it modified.

W3C

XQuery 4.0: An XML Query Language

W3C Editor's Draft 218 February 2026

This version:
https://qt4cg.org/specifications/xquery-40/
Most recent version of XQuery:
https://qt4cg.org/specifications/xquery-40/
Most recent Recommendation of XQuery:
https://www.w3.org/TR/2017/REC-xquery-31-20170321/
Editor:
Michael Kay, Saxonica <mike@saxonica.com>

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.


Abstract

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.

Status of this Document

This is a draft prepared by the QT4CG (officially registered in W3C as the XSLT Extensions Community Group). Comments are invited.

Dedication

The publications of this community group are dedicated to our co-chair, Michael Sperberg-McQueen (1954–2024).


4 Expressions

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
| QuantifiedExpr
| SwitchExpr
| TypeswitchExpr
| IfExpr
| TryCatchExpr
| OrExpr
ExprSingle::=FLWORExpr
| QuantifiedExpr
| SwitchExpr
| TypeswitchExpr
| IfExpr
| TryCatchExpr
| OrExpr
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.

4.14 Maps and Arrays

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.

4.14.1 Maps

Changes in 4.0  

  1. Ordered maps are introduced.  [Issue 1651 PR 1703 14 January 2025]

[Definition: A map is a function that associates a set of keys with values, resulting in a collection of key / value pairs.] [Definition: Each key / value pair in a map is called an entry.] [Definition: The value associated with a given key is called the associated value of the key.]

Maps and their properties are defined in the data model: see Section 8.2 Map ItemsDM. For an overview of the functions available for processing maps, see Section 18 Processing mapsFO.

Note:

Maps in XQuery 4.0 are ordered. The effect of this property is explained in Section 8.2 Map ItemsDM. In an ordered map, the order of entries is predictable and depends on the order in which they were added to the map.

4.14.1.1 Map Constructors

Changes in 4.0  

  1. 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.   [Issue 1070 PR 1071 26 March 2024]

  2. The order of key-value pairs in the map constructor is now retained in the constructed map.  [Issue 1651 PR 1703 14 January 2025]

  3. 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.  [Issue 2003 PR 2094 13 July 2025]

A map can be created using a MapConstructor.

Examples are:

{ "a": 1, "b": 2 }

which constructs a map with two entries, and

{ "a": 1, if ($condition) { map{ "b": 2 } } }

which constructs a map having either one or two entries depending on the value of $condition.

Both the keys and the values in a map constructor can be supplied as expressions rather than as constants.

MapConstructor::="map"? "{" (MapConstructorEntry ** ",") "}"
MapConstructorEntry::=ExprSingle (":" ExprSingle)?
ExprSingle::=FLWORExpr
| QuantifiedExpr
| SwitchExpr
| TypeswitchExpr
| IfExpr
| TryCatchExpr
| OrExpr

Note:

The keyword map was required in earlier versions of the language; in XQuery 4.0 it becomes optional. There may be cases where using the keyword improves readability.

In order to allow the map keyword to be omitted, an incompatible change has been made to XQuery computed element and attribute constructors: if the name of the constructed element or attribute is a language keyword, it must now be written using the QNameLiteral syntax, for example element #div {}.

Although the grammar allows a MapConstructor to appear within an EnclosedExpr (that is, between curly brackets), this may be confusing to readers, and using the map keyword in such cases may improve clarity. The keyword map is used in the second example above to avoid any confusion between the braces required for the then part of the conditional expression, and the braces required for the inner map constructor.

If the EnclosedExpr appears in a context such as a StringTemplate, the two adjacent left opening braces must at least be separated by whitespace.

When a MapConstructorEntry is written as two instances of ExprSingle separated by a colon, the first expression is evaluated and atomized to form a key, and the second expression is evaluated to form the corresponding value. The result is a single-entry mapDM which will be merged into the constructed map, as described below. A type error [err:XPTY0004] occurs if the result of the first expression (after atomization) is not a single atomic item. The result of the second expression is used as is.

When the MapConstructorEntry is written as a single instance of ExprSingle with no colon, it must evaluate to a sequence of zero or more map items ([err:XPTY0004]). These map items will be merged into the constructed map, as described below.

Each contained MapConstructorEntry thus delivers zero or more maps, and the result of the map constructor is a new map obtained by merging these component maps, in order, as if by the map:merge function.

[Definition: 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 ] If two or more entries have the same key value then a dynamic error is raised [err:XQDY0137]. The error may be raised statically if two or more entries can be determined statically to have the same key value.

The entry orderDM of the entries in the constructed map retains the order of the MapConstructorEntry entries in the input.

Example: Constructing a fixed map

The following expression constructs a map with seven entries:

{
  "Su" : "Sunday",
  "Mo" : "Monday",
  "Tu" : "Tuesday",
  "We" : "Wednesday",
  "Th" : "Thursday",
  "Fr" : "Friday",
  "Sa" : "Saturday"
}

 

Example: Constructing a map with conditional entries

The following expression constructs a map with either five or seven entries, depending on a supplied condition:

{
  "Mo" : "Monday",
  "Tu" : "Tuesday",
  "We" : "Wednesday",
  "Th" : "Thursday",
  "Fr" : "Friday",
  if ($include-weekends) {
    { "Sa" : "Saturday",
      "Su" : "Sunday"
    }
  }
}

This could also be written:

{
  "Mo" : "Monday",
  "Tu" : "Tuesday",
  "We" : "Wednesday",
  "Th" : "Thursday",
  "Fr" : "Friday",
  { "Sa" : "Saturday",
    "Su" : "Sunday"
  } [$include-weekends]
}

 

Example: Constructing a map to index nodes

The following expression (which uses two nested map constructors) constructs a map that indexes employees by the value of their @id attribute:

{ //employee ! {@id, .} }
{ //employee ! {@id : .} }

 

Example: Constructing nested maps

Maps can nest, and can contain any XDM value. Here is an example of a nested map with values that can be string values, numeric values, or arrays:

{
  "book": {
    "title": "Data on the Web",
    "year": 2000,
    "author": [
      {
        "last": "Abiteboul",
        "first": "Serge"
      },
      {
        "last": "Buneman",
        "first": "Peter"
      },
      {
        "last": "Suciu",
        "first": "Dan"
      }
    ],
    "publisher": "Morgan Kaufmann Publishers",
    "price": 39.95
  }
}

Note:

The syntax deliberately mimics JSON, but there are a few differences. JSON constructs that are not accepted in XQuery 4.0 map constructors include the keywords true, false, and null, and backslash-escaped characters such as "\n" in string literals. In an XQuery 4.0 map constructor, of course, any literal value can be replaced with an expression.

Note:

In some circumstances, it is necessary to include whitespace before or after the colon of a MapConstructorEntry to ensure that it is parsed as intended.

For instance, consider the expression {a:b}. Although it matches the EBNF for MapConstructor (with a matching MapKeyExpr and b matching MapValueExpr)MapConstructor, the "longest possible match" rule“longest terminal” rule (see A.3 Lexical structure) requires that a:b be parsed as a QName, which results inis likely to result in an error indicating that the prefix a syntax errorhas not been declared. Changing the expression to {a :b} or {a: b} will prevent this, resulting in the intended parse.

Similarly, consider these three expressions:

{a:b:c}
{a:*:c}
{*:b:c}

In each case, the expression matches the EBNF in two different ways, but the “longest possible match” rule forces the parse in which the MapKeyExprfirst subexpression is a:b, a:*, or *:b (respectively) and the MapValueExprsecond subexpression is c. To achieve the alternative parse (in which the MapKeyExprfirst expression is merely a or *), insert whitespace before and/or after the first colon.

See A.3 Lexical structure.

Note:

There are also several functions that can be used to construct maps with a variable number of entries:

  • map:build takes any sequence as input, and for each item in the sequence, it computes a key and a value, by calling user-supplied functions.

  • map:merge takes a sequence of maps (often but not necessarily single-entry mapDM) and merges them into a single map.

  • map:of-pairs takes a sequence of key-value pair mapsFO and merges them into a single map.

Any of these functions can be used to build an index of employee elements using the value of the @id attribute as a key:

  • map:build(//employee, fn { @id })

  • map:merge(//employee ! { @id, . })

  • map:of-pairs(//employee ! { 'key': @id, 'value': . })

All three functions also provide control over:

  • The way in which duplicate keys are handled, and

  • The ordering of entries in the resulting map.

A XQuery 4.0 Grammar

A.1 EBNF

Changes in 4.0  

  1. 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.  [Issue 1366 PR 1498]

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.

AbbreviatedStep::=".." | ("@" NodeTest) | SimpleNodeTest
AdditiveExpr::=MultiplicativeExpr (("+" | "-") MultiplicativeExpr)*
AllowingEmpty::="allowing" "empty"
AndExpr::=ComparisonExpr ("and" ComparisonExpr)*
Annotation::="%" EQName ("(" (AnnotationValue ++ ",") ")")?
AnnotationValue::=StringLiteral | ("-"? NumericLiteral) | QNameLiteral | ("true" "(" ")") | ("false" "(" ")")
AnyArrayType::="array" "(" "*" ")"
AnyFunctionType::=("function" | "fn") "(" "*" ")"
AnyItemTest::="item" "(" ")"
AnyMapType::="map" "(" "*" ")"
AnyNodeKindTest::="node" "(" ")"
AnyRecordType::="record" "(" "*" ")"
AposAttrValueContent::=AposAttrContentChar
| CommonContent
Argument::=ExprSingle | ArgumentPlaceholder
ArgumentList::="(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
ArgumentPlaceholder::="?"
ArrayConstructor::=SquareArrayConstructor | CurlyArrayConstructor
ArrayType::=AnyArrayType | TypedArrayType
ArrowExpr::=UnaryExpr (SequenceArrowTarget | MappingArrowTarget)*
ArrowTarget::=FunctionCall | RestrictedDynamicCall
AttributeName::=EQName
AttributeTest::="attribute" "(" (NameTestUnion ("," TypeName)?)? ")"
Axis::=("ancestor" | "ancestor-or-self" | "attribute" | "child" | "descendant" | "descendant-or-self" | "following" | "following-or-self" | "following-sibling" | "following-sibling-or-self" | "parent" | "preceding" | "preceding-or-self" | "preceding-sibling" | "preceding-sibling-or-self" | "self") "::"
AxisStep::=(AbbreviatedStep | FullStep) Predicate*
BaseURIDecl::="declare" "base-uri" URILiteral
BoundarySpaceDecl::="declare" "boundary-space" ("preserve" | "strip")
BracedAction::=EnclosedExpr
BracedSwitchCases::="{" SwitchCases "}"
BracedTypeswitchCases::="{" TypeswitchCases "}"
CaseClause::="case" (VarName "as")? SequenceTypeUnion "return" ExprSingle
CastableExpr::=CastExpr ("castable" "as" CastTarget "?"?)?
CastExpr::=PipelineExpr ("cast" "as" CastTarget "?"?)?
CastTarget::=TypeName | ChoiceItemType | EnumerationType
CatchClause::="catch" NameTestUnionEnclosedExpr
CDataSection::="<![CDATA[" CDataSectionContents "]]>"
/* ws: explicit */
CDataSectionContents::=(Char* - (Char* ']]>' Char*))
/* ws: explicit */
ChoiceItemType::="(" (ItemType ++ "|") ")"
CommentTest::="comment" "(" ")"
CommonContent::=PredefinedEntityRef | CharRef | "{{" | "}}" | EnclosedExpr
ComparisonExpr::=OtherwiseExpr ((ValueComp | GeneralComp | NodeComp) OtherwiseExpr)?
CompAttrConstructor::="attribute" CompNodeNameEnclosedExpr
CompCommentConstructor::="comment" EnclosedExpr
CompDocConstructor::="document" EnclosedExpr
CompElemConstructor::="element" CompNodeNameEnclosedContentExpr
CompNamespaceConstructor::="namespace" CompNodeNCNameEnclosedExpr
CompNodeName::=QNameLiteral | UnreservedName | ("{" Expr "}")
CompNodeNCName::=MarkedNCName | UnreservedNCName | ("{" Expr "}")
CompPIConstructor::="processing-instruction" CompNodeNCNameEnclosedExpr
CompTextConstructor::="text" EnclosedExpr
ComputedConstructor::=CompDocConstructor
| CompElemConstructor
| CompAttrConstructor
| CompNamespaceConstructor
| CompTextConstructor
| CompCommentConstructor
| CompPIConstructor
ConstructionDecl::="declare" "construction" ("strip" | "preserve")
ContextValueDecl::="declare" "context" (("value" ("as" SequenceType)?) | ("item" ("as" ItemType)?)) ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
ContextValueRef::="."
CopyNamespacesDecl::="declare" "copy-namespaces" PreserveMode "," InheritMode
CountClause::="count" VarName
CurlyArrayConstructor::="array" EnclosedExpr
CurrentVar::=VarName
DecimalFormatDecl::="declare" (("decimal-format" EQName) | ("default" "decimal-format")) (DFPropertyName "=" StringLiteral)*
DefaultCollationDecl::="declare" "default" "collation" URILiteral
DefaultNamespaceDecl::="declare" "fixed"? "default" ("element" | "function") "namespace" URILiteral
DFPropertyName::="decimal-separator" | "grouping-separator" | "infinity" | "minus-sign" | "NaN" | "percent" | "per-mille" | "zero-digit" | "digit" | "pattern-separator" | "exponent-separator"
DirAttributeList::=(S (QNameS? "=" S? DirAttributeValue)?)*
/* ws: explicit */
DirAttributeValue::=('"' (EscapeQuot | QuotAttrValueContent)* '"')
| ("'" (EscapeApos | AposAttrValueContent)* "'")
/* ws: explicit */
DirCommentConstructor::="<!--" DirCommentContents "-->"
/* ws: explicit */
DirCommentContents::=((Char - '-') | ("-" (Char - '-')))*
/* ws: explicit */
DirectConstructor::=DirElemConstructor
| DirCommentConstructor
| DirPIConstructor
DirElemConstructor::="<" QNameDirAttributeList ("/>" | (">" DirElemContent* "</" QNameS? ">"))
/* ws: explicit */
DirElemContent::=DirectConstructor
| CDataSection
| CommonContent
| ElementContentChar
DirPIConstructor::="<?" PITarget (SDirPIContents)? "?>"
/* ws: explicit */
DirPIContents::=(Char* - (Char* '?>' Char*))
/* ws: explicit */
DocumentTest::="document-node" "(" (ElementTest | SchemaElementTest | NameTestUnion)? ")"
DynamicFunctionCall::=PostfixExprPositionalArgumentList
ElementName::=EQName
ElementTest::="element" "(" (NameTestUnion ("," TypeName "?"?)?)? ")"
EmptyOrderDecl::="declare" "default" "order" "empty" ("greatest" | "least")
EnclosedContentExpr::=EnclosedExpr
EnclosedExpr::="{" Expr? "}"
EnumerationType::="enum" "(" (StringLiteral ++ ",") ")"
EQName::=QName | URIQualifiedName
Expr::=(ExprSingle ++ ",")
ExprSingle::=FLWORExpr
| QuantifiedExpr
| SwitchExpr
| TypeswitchExpr
| IfExpr
| TryCatchExpr
| OrExpr
ExtendedFieldDeclaration::=FieldDeclaration (":=" ExprSingle)?
ExtensibleFlag::="," "*"
ExtensionExpr::=Pragma+ "{" Expr? "}"
FieldDeclaration::=FieldName "?"? ("as" SequenceType)?
FieldName::=NCName | StringLiteral
FilterExpr::=PostfixExprPredicate
FilterExprAM::=PostfixExpr "?[" Expr "]"
FinallyClause::="finally" EnclosedExpr
FLWORExpr::=InitialClauseIntermediateClause* ReturnClause
ForBinding::=ForItemBinding | ForMemberBinding | ForEntryBinding
ForClause::="for" (ForBinding ++ ",")
ForEntryBinding::=((ForEntryKeyBindingForEntryValueBinding?) | ForEntryValueBinding) PositionalVar? "in" ExprSingle
ForEntryKeyBinding::="key" VarNameAndType
ForEntryValueBinding::="value" VarNameAndType
ForItemBinding::=VarNameAndTypeAllowingEmpty? PositionalVar? "in" ExprSingle
ForMemberBinding::="member" VarNameAndTypePositionalVar? "in" ExprSingle
FullStep::=AxisNodeTest
FunctionBody::=EnclosedExpr
FunctionCall::=EQNameArgumentList
/* xgc: reserved-function-names */
/* gn: parens */
FunctionDecl::="declare" Annotation* "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")
/* xgc: reserved-function-names */
FunctionItemExpr::=NamedFunctionRef | InlineFunctionExpr
FunctionSignature::="(" ParamList ")" TypeDeclaration?
FunctionType::=Annotation* (AnyFunctionType
| TypedFunctionType)
GeneralComp::="=" | "!=" | "<" | "<=" | ">" | ">="
GNodeType::="gnode" "(" ")"
GroupByClause::="group" "by" (GroupingSpec ++ ",")
GroupingSpec::=VarName (TypeDeclaration? ":=" ExprSingle)? ("collation" URILiteral)?
IfExpr::="if" "(" Expr ")" (UnbracedActions | BracedAction)
Import::=SchemaImport | ModuleImport
InheritMode::="inherit" | "no-inherit"
InitialClause::=ForClause | LetClause | WindowClause
InlineFunctionExpr::=Annotation* ("function" | "fn") FunctionSignature? FunctionBody
InstanceofExpr::=TreatExpr ("instance" "of" SequenceType)?
IntermediateClause::=InitialClause | WhereClause | WhileClause | GroupByClause | OrderByClause | CountClause
IntersectExceptExpr::=InstanceofExpr (("intersect" | "except") InstanceofExpr)*
ItemType::=RegularItemType | FunctionType | TypeName | ChoiceItemType
ItemTypeDecl::="declare" Annotation* "type" EQName "as" ItemType
JNodeType::="jnode-type" "(" SequenceType? ")"
KeySpecifier::=NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard
KeywordArgument::=EQName ":=" Argument
KeywordArguments::=(KeywordArgument ++ ",")
LetArrayBinding::="$" "[" (VarNameAndType ++ ",") "]" TypeDeclaration? ":=" ExprSingle
LetBinding::=LetValueBinding | LetSequenceBinding | LetArrayBinding | LetMapBinding
LetClause::="let" (LetBinding ++ ",")
LetMapBinding::="$" "{" (VarNameAndType ++ ",") "}" TypeDeclaration? ":=" ExprSingle
LetSequenceBinding::="$" "(" (VarNameAndType ++ ",") ")" TypeDeclaration? ":=" ExprSingle
LetValueBinding::=VarNameAndType ":=" ExprSingle
LibraryModule::=ModuleDeclProlog
Literal::=NumericLiteral | StringLiteral | QNameLiteral
Lookup::="?" KeySpecifier
LookupExpr::=PostfixExprLookup
LookupWildcard::="*"
MainModule::=PrologQueryBody
MapConstructor::="map"? "{" (MapConstructorEntry ** ",") "}"
MapConstructorEntry::=ExprSingle (":" ExprSingle)?
MapKeyExpr::=ExprSingle
MappingArrowTarget::="=!>" ArrowTarget
MapType::=AnyMapType | TypedMapType
MapValueExpr::=ExprSingle
MarkedNCName::="#" NCName
Module::=VersionDecl? (LibraryModule | MainModule)
ModuleDecl::="module" "namespace" NCName "=" URILiteralSeparator
ModuleImport::="import" "module" ("namespace" NCName "=")? URILiteral ("at" (URILiteral ++ ","))?
MultiplicativeExpr::=UnionExpr (("*" | "×" | "div" | "÷" | "idiv" | "mod") UnionExpr)*
NamedFunctionRef::=EQName "#" IntegerLiteral
/* xgc: reserved-function-names */
NamedRecordTypeDecl::="declare" Annotation* "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
NamespaceDecl::="declare" "namespace" NCName "=" URILiteral
NamespaceNodeTest::="namespace-node" "(" ")"
NameTest::=EQName | Wildcard
NameTestUnion::=(NameTest ++ "|")
NextVar::="next" VarName
NodeComp::="is" | "<<" | ">>"
NodeConstructor::=DirectConstructor
| ComputedConstructor
NodeKindTest::=DocumentTest
| ElementTest
| AttributeTest
| SchemaElementTest
| SchemaAttributeTest
| PITest
| CommentTest
| TextTest
| NamespaceNodeTest
| AnyNodeKindTest
NodeTest::=UnionNodeTest | SimpleNodeTest
NumericLiteral::=IntegerLiteral | HexIntegerLiteral | BinaryIntegerLiteral | DecimalLiteral | DoubleLiteral
OccurrenceIndicator::="?" | "*" | "+"
/* xgc: occurrence-indicators */
OptionDecl::="declare" "option" EQNameStringLiteral
OrderByClause::="stable"? "order" "by" (OrderSpec ++ ",")
OrderedExpr::="ordered" EnclosedExpr
OrderingModeDecl::="declare" "ordering" ("ordered" | "unordered")
OrderModifier::=("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral)?
OrderSpec::=ExprSingleOrderModifier
OrExpr::=AndExpr ("or" AndExpr)*
OtherwiseExpr::=StringConcatExpr ("otherwise" StringConcatExpr)*
ParamList::=(VarNameAndType ** ",")
ParamListWithDefaults::=(ParamWithDefault ++ ",")
ParamWithDefault::=VarNameAndType (":=" ExprSingle)?
ParenthesizedExpr::="(" Expr? ")"
PathExpr::=("/" RelativePathExpr?)
| ("//" RelativePathExpr)
| RelativePathExpr
/* xgc: leading-lone-slash */
PipelineExpr::=ArrowExpr ("->" ArrowExpr)*
PITest::="processing-instruction" "(" (NCName | StringLiteral)? ")"
PositionalArgumentList::="(" PositionalArguments? ")"
PositionalArguments::=(Argument ++ ",")
PositionalVar::="at" VarName
PostfixExpr::=PrimaryExpr | FilterExpr | DynamicFunctionCall | LookupExpr | FilterExprAM
Pragma::="(#" SEQName (SPragmaContents)? "#)"
/* ws: explicit */
PragmaContents::=(Char* - (Char* '#)' Char*))
Predicate::="[" Expr "]"
PreserveMode::="preserve" | "no-preserve"
PreviousVar::="previous" VarName
PrimaryExpr::=Literal
| VarRef
| ParenthesizedExpr
| ContextValueRef
| FunctionCall
| OrderedExpr
| UnorderedExpr
| NodeConstructor
| FunctionItemExpr
| MapConstructor
| ArrayConstructor
| StringTemplate
| StringConstructor
| UnaryLookup
Prolog::=((DefaultNamespaceDecl | Setter | NamespaceDecl | Import) Separator)* ((ContextValueDecl | VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl | OptionDecl) Separator)*
QNameLiteral::="#" EQName
QuantifiedExpr::=("some" | "every") (QuantifierBinding ++ ",") "satisfies" ExprSingle
QuantifierBinding::=VarNameAndType "in" ExprSingle
QueryBody::=Expr
QuotAttrValueContent::=QuotAttrContentChar
| CommonContent
RangeExpr::=AdditiveExpr ("to" AdditiveExpr)?
RecordType::=AnyRecordType | TypedRecordType
RegularItemType::=AnyItemTest | NodeKindTest | GNodeType | JNodeType | MapType | ArrayType | RecordType | EnumerationType
RelativePathExpr::=StepExpr (("/" | "//") StepExpr)*
RestrictedDynamicCall::=(VarRef | ParenthesizedExpr | FunctionItemExpr | MapConstructor | ArrayConstructor) PositionalArgumentList
ReturnClause::="return" ExprSingle
SchemaAttributeTest::="schema-attribute" "(" AttributeName ")"
SchemaElementTest::="schema-element" "(" ElementName ")"
SchemaImport::="import" "schema" SchemaPrefix? URILiteral ("at" (URILiteral ++ ","))?
SchemaPrefix::=("namespace" NCName "=") | ("fixed"? "default" "element" "namespace")
Selector::=EQName | Wildcard | ("get" "(" Expr ")")
Separator::=";"
SequenceArrowTarget::="=>" ArrowTarget
SequenceType::=("empty-sequence" "(" ")")
| (ItemTypeOccurrenceIndicator?)
SequenceTypeUnion::=SequenceType ("|" SequenceType)*
Setter::=BoundarySpaceDecl | DefaultCollationDecl | BaseURIDecl | ConstructionDecl | OrderingModeDecl | EmptyOrderDecl | CopyNamespacesDecl | DecimalFormatDecl
SimpleMapExpr::=PathExpr ("!" PathExpr)*
SimpleNodeTest::=TypeTest | Selector
SlidingWindowClause::="sliding" "window" VarNameAndType "in" ExprSingleWindowStartCondition? WindowEndCondition
SquareArrayConstructor::="[" (ExprSingle ** ",") "]"
StepExpr::=PostfixExpr | AxisStep
StringConcatExpr::=RangeExpr ("||" RangeExpr)*
StringConstructor::="``[" StringConstructorContent "]``"
/* ws: explicit */
StringConstructorChars::=(Char* - (Char* ('`{' | ']``') Char*))
/* ws: explicit */
StringConstructorContent::=StringConstructorChars (StringInterpolationStringConstructorChars)*
/* ws: explicit */
StringInterpolation::="`{" Expr? "}`"
/* ws: explicit */
StringTemplate::="`" (StringTemplateFixedPart | StringTemplateVariablePart)* "`"
/* ws: explicit */
StringTemplateFixedPart::=((Char - ('{' | '}' | '`')) | "{{" | "}}" | "``")*
/* ws: explicit */
StringTemplateVariablePart::=EnclosedExpr
/* ws: explicit */
SwitchCaseClause::=("case" SwitchCaseOperand)+ "return" ExprSingle
SwitchCaseOperand::=Expr
SwitchCases::=SwitchCaseClause+ "default" "return" ExprSingle
SwitchComparand::="(" Expr? ")"
SwitchExpr::="switch" SwitchComparand (SwitchCases | BracedSwitchCases)
TextTest::="text" "(" ")"
TreatExpr::=CastableExpr ("treat" "as" SequenceType)?
TryCatchExpr::=TryClause ((CatchClause+ FinallyClause?) | FinallyClause)
TryClause::="try" EnclosedExpr
TumblingWindowClause::="tumbling" "window" VarNameAndType "in" ExprSingleWindowStartCondition? WindowEndCondition?
TypedArrayType::="array" "(" SequenceType ")"
TypeDeclaration::="as" SequenceType
TypedFunctionParam::=("$" EQName "as")? SequenceType
TypedFunctionType::=("function" | "fn") "(" (TypedFunctionParam ** ",") ")" "as" SequenceType
TypedMapType::="map" "(" ItemType "," SequenceType ")"
TypedRecordType::="record" "(" (FieldDeclaration ** ",") ExtensibleFlag? ")"
TypeName::=EQName
TypeswitchCases::=CaseClause+ "default" VarName? "return" ExprSingle
TypeswitchExpr::="typeswitch" "(" Expr ")" (TypeswitchCases | BracedTypeswitchCases)
TypeTest::=RegularItemType | ("type" "(" SequenceType ")")
UnaryExpr::=("-" | "+")* ValueExpr
UnaryLookup::=Lookup
UnbracedActions::="then" ExprSingle "else" ExprSingle
UnionExpr::=IntersectExceptExpr (("union" | "|") IntersectExceptExpr)*
UnionNodeTest::="(" (SimpleNodeTest ++ "|") ")"
UnorderedExpr::="unordered" EnclosedExpr
UnreservedName::=EQName
/* xgc: unreserved-name */
UnreservedNCName::=NCName
/* xgc: unreserved-name */
URILiteral::=StringLiteral
ValidateExpr::="validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
ValidationMode::="lax" | "strict"
ValueComp::="eq" | "ne" | "lt" | "le" | "gt" | "ge"
ValueExpr::=ValidateExpr | ExtensionExpr | SimpleMapExpr
VarDecl::="declare" Annotation* "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
VarDefaultValue::=ExprSingle
VarName::="$" EQName
VarNameAndType::="$" EQNameTypeDeclaration?
VarRef::="$" EQName
VarValue::=ExprSingle
VersionDecl::="xquery" (("encoding" StringLiteral) | ("version" StringLiteral ("encoding" StringLiteral)?)) Separator
WhereClause::="where" ExprSingle
WhileClause::="while" ExprSingle
Wildcard::="*"
| (NCName ":*")
| ("*:" NCName)
| (BracedURILiteral "*")
/* ws: explicit */
WindowClause::="for" (TumblingWindowClause | SlidingWindowClause)
WindowEndCondition::="only"? "end" WindowVars ("when" ExprSingle)?
WindowStartCondition::="start" WindowVars ("when" ExprSingle)?
WindowVars::=CurrentVar? PositionalVar? PreviousVar? NextVar?