<?xml version="1.0" encoding="utf-8"?><html xmlns="http://www.w3.org/1999/xhtml" lang="EN"><head><title>XQuery 4.0: An XML Query Language </title><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/><link rel="stylesheet" type="text/css" href="css/w3c-base.css"/><link rel="stylesheet" href="css/qtspecs.css"/><link rel="stylesheet" href="css/xquery-40.css"/></head><body><div class="head"><p><a href="https://www.w3.org/"><img src="https://www.w3.org/StyleSheets/TR/2016/logos/W3C" alt="W3C" height="48" width="72"/></a></p>
<h1><a id="title"/>XQuery 4.0: An XML Query Language </h1>
<h2><a id="w3c-doctype"/>W3C Editor's Draft 29 October 2025</h2><dl><dt>This version:</dt><dd><a href="https://qt4cg.org/pr/2271/xquery-40//">https://qt4cg.org/pr/2271/xquery-40/</a></dd><dt>Most recent version of XQuery:</dt><dd>
         <a href="https://qt4cg.org/specifications/xquery-40/">https://qt4cg.org/specifications/xquery-40/</a>
      </dd><dt>Most recent Recommendation of XQuery:</dt><dd>
         <a href="https://www.w3.org/TR/2017/REC-xquery-31-20170321/">https://www.w3.org/TR/2017/REC-xquery-31-20170321/</a>
      </dd><dt>Editor:</dt><dd>Michael Kay, Saxonica <a href="http://www.saxonica.com/">&lt;http://www.saxonica.com/&gt;</a></dd></dl><p>This document is also available in these non-normative formats: <a href="xquery-40.xml">XML</a>.</p><p class="copyright"><a href="https://www.w3.org/Consortium/Legal/ipr-notice#Copyright">Copyright</a> © 2000 <a href="https://www.w3.org/"><abbr title="World Wide Web Consortium">W3C</abbr></a><sup>®</sup> (<a href="https://www.csail.mit.edu/"><abbr title="Massachusetts Institute of Technology">MIT</abbr></a>, <a href="https://www.ercim.eu/"><abbr title="European Research Consortium for Informatics and Mathematics">ERCIM</abbr></a>, <a href="https://www.keio.ac.jp/">Keio</a>, <a href="http://ev.buaa.edu.cn/">Beihang</a>). W3C <a href="https://www.w3.org/Consortium/Legal/ipr-notice#Legal_Disclaimer">liability</a>, <a href="https://www.w3.org/Consortium/Legal/ipr-notice#W3C_Trademarks">trademark</a> and <a href="https://www.w3.org/Consortium/Legal/copyright-documents">document use</a> rules apply.</p><hr/></div><div>
<h2><a id="abstract"/>Abstract</h2><p>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.</p><p>A list of changes made since XQuery 3.1 can be found in <a href="#id-revision-log"><b>J Change Log</b></a>. 
</p></div><div>
<h2><a id="status"/>Status of this Document</h2><p>
            <em>This section describes the status of this document at the time of its publication.
               Other documents may supersede this document.</em>
         </p><p>This document is a working draft developed and maintained by a W3C Community Group,
            the <a href="https://www.w3.org/community/xslt-40/">XQuery and XSLT Extensions Community Group</a>
            unofficially known as QT4CG (where "QT" denotes Query and Transformation). This draft
            is work in progress and should not be considered either stable or complete.
            Standard W3C copyright and patent conditions apply.</p><p>The community group welcomes comments on the specification. Comments are best submitted
         as issues on the group's <a href="https://github.com/qt4cg/qtspecs/issues">GitHub repository</a>.</p><p>The community group maintains two extensive test suites, 
            one oriented to XQuery and XPath, the other to XSLT.
         These can be found at <a href="https://github.com/qt4cg/qt4tests">qt4tests</a> and
         <a href="https://github.com/qt4cg/xslt40-test">xslt40-test</a> respectively. New tests,
         or suggestions for correcting existing tests, are welcome. The test suites include extensive metadata
         describing the conditions for applicability of each test case as well as the expected results. They
         do not include any test drivers for executing the tests: each implementation is expected to provide
         its own test driver.</p><div class="dedication" id="dedication"><h3>Dedication</h3><p>The publications of this community group 
<a href="xpath-40.html#dedication">are dedicated</a> to our co-chair,
Michael Sperberg-McQueen (1954–2024).</p></div></div><nav id="toc">
<h2><a id="contents"/>Table of Contents<span class="expalltoc collapsed"> ▶</span></h2><ol class="toc"><li><details><summary><a href="#id-introduction"><span class="secno">1 </span><span class="content toc-chg">Introduction</span></a></summary></details></li><li><details><summary><a href="#id-basics"><span class="secno">2 </span><span class="content">Basics</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-terminology"><span class="secno">2.1 </span><span class="content toc-chg">Terminology</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-ebnf-introduction"><span class="secno">2.1.1 </span><span class="content toc-chg">Grammar Notation</span></a></summary></details></li><li><details><summary><a href="#id-expression-names"><span class="secno">2.1.2 </span><span class="content toc-chg">Expression Names</span></a></summary></details></li><li><details><summary><a href="#id-values"><span class="secno">2.1.3 </span><span class="content toc-chg">Values</span></a></summary></details></li><li><details><summary><a href="#id-namespaces-and-qnames"><span class="secno">2.1.4 </span><span class="content toc-chg">Namespaces and QNames</span></a></summary></details></li><li><details><summary><a href="#id-expanding-unprefixed-qnames"><span class="secno">2.1.5 </span><span class="content">Expanding Lexical QNames</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#context"><span class="secno">2.2 </span><span class="content">Expression Context</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#static_context"><span class="secno">2.2.1 </span><span class="content toc-chg">Static Context</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-function-definitions"><span class="secno">2.2.1.1 </span><span class="content">Function Definitions</span></a></summary></details></li><li><details><summary><a href="#id-decimal-formats"><span class="secno">2.2.1.2 </span><span class="content toc-chg">Decimal Formats</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#eval_context"><span class="secno">2.2.2 </span><span class="content toc-chg">Dynamic Context</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-processing-model"><span class="secno">2.3 </span><span class="content toc-chg">Processing Model</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-data-model-generation"><span class="secno">2.3.1 </span><span class="content">Data Model Generation</span></a></summary></details></li><li><details><summary><a href="#id-schema-import-processing"><span class="secno">2.3.2 </span><span class="content">Schema Import Processing</span></a></summary></details></li><li><details><summary><a href="#id-expression-processing"><span class="secno">2.3.3 </span><span class="content">Expression
Processing</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-static-analysis"><span class="secno">2.3.3.1 </span><span class="content">Static Analysis Phase</span></a></summary></details></li><li><details><summary><a href="#id-dynamic-evaluation"><span class="secno">2.3.3.2 </span><span class="content">Dynamic Evaluation Phase</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-input-sources"><span class="secno">2.3.4 </span><span class="content">Input Sources</span></a></summary></details></li><li><details><summary><a href="#id-serialization"><span class="secno">2.3.5 </span><span class="content">Serialization</span></a></summary></details></li><li><details><summary><a href="#id-consistency-constraints"><span class="secno">2.3.6 </span><span class="content">Consistency Constraints</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#errors"><span class="secno">2.4 </span><span class="content">Error Handling</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-kinds-of-errors"><span class="secno">2.4.1 </span><span class="content">Kinds of Errors</span></a></summary></details></li><li><details><summary><a href="#id-identifying-errors"><span class="secno">2.4.2 </span><span class="content">Identifying and Reporting Errors</span></a></summary></details></li><li><details><summary><a href="#id-handling-dynamic"><span class="secno">2.4.3 </span><span class="content">Handling Dynamic Errors</span></a></summary></details></li><li><details><summary><a href="#id-errors-and-opt"><span class="secno">2.4.4 </span><span class="content">Errors and
      Optimization</span></a></summary></details></li><li><details><summary><a href="#id-guarded-expressions"><span class="secno">2.4.5 </span><span class="content toc-chg">Guarded Expressions</span></a></summary></details></li><li><details><summary><a href="#id-implausible-expressions"><span class="secno">2.4.6 </span><span class="content toc-chg">Implausible Expressions</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-important-concepts"><span class="secno">2.5 </span><span class="content">Concepts</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-document-order"><span class="secno">2.5.1 </span><span class="content">Document Order</span></a></summary></details></li><li><details><summary><a href="#id-typed-value"><span class="secno">2.5.2 </span><span class="content">Typed Value and String Value</span></a></summary></details></li><li><details><summary><a href="#id-atomization"><span class="secno">2.5.3 </span><span class="content">Atomization</span></a></summary></details></li><li><details><summary><a href="#id-ebv"><span class="secno">2.5.4 </span><span class="content">Effective Boolean Value</span></a></summary></details></li><li><details><summary><a href="#id-uri-literals"><span class="secno">2.5.5 </span><span class="content">URI Literals</span></a></summary></details></li><li><details><summary><a href="#id-resolve-relative-uri"><span class="secno">2.5.6 </span><span class="content">Resolving a Relative URI Reference</span></a></summary></details></li></ol></details></li></ol></details></li><li><details><summary><a href="#id-types"><span class="secno">3 </span><span class="content">Types</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-sequencetype-syntax"><span class="secno">3.1 </span><span class="content">Sequence Types</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-sequence-type-examples"><span class="secno">3.1.1 </span><span class="content">Examples of Sequence Types</span></a></summary></details></li><li><details><summary><a href="#id-sequencetype-matching"><span class="secno">3.1.2 </span><span class="content">Sequence Type Matching</span></a></summary></details></li><li><details><summary><a href="#id-schema-type-derivation"><span class="secno">3.1.3 </span><span class="content">Schema Type Relationships</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-matching-item"><span class="secno">3.2 </span><span class="content">Item Types</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#general-item-types"><span class="secno">3.2.1 </span><span class="content">General item types</span></a></summary></details></li><li><details><summary><a href="#id-atomic-types"><span class="secno">3.2.2 </span><span class="content">Atomic Types</span></a></summary></details></li><li><details><summary><a href="#id-union-types"><span class="secno">3.2.3 </span><span class="content">Union Types</span></a></summary></details></li><li><details><summary><a href="#id-namespace-sensitive"><span class="secno">3.2.4 </span><span class="content">Namespace-sensitive Types</span></a></summary></details></li><li><details><summary><a href="#id-choice-item-types"><span class="secno">3.2.5 </span><span class="content toc-chg">Choice Item Types</span></a></summary></details></li><li><details><summary><a href="#id-enumeration-types"><span class="secno">3.2.6 </span><span class="content toc-chg">Enumeration Types</span></a></summary></details></li><li><details><summary><a href="#node-types"><span class="secno">3.2.7 </span><span class="content toc-chg">Node Types</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-simple-node-tests"><span class="secno">3.2.7.1 </span><span class="content">Simple Node Types</span></a></summary></details></li><li><details><summary><a href="#id-element-test"><span class="secno">3.2.7.2 </span><span class="content toc-chg">Element Types</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-schema-element-test"><span class="secno">3.2.7.2.1 </span><span class="content">Schema Element Types</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-attribute-test"><span class="secno">3.2.7.3 </span><span class="content toc-chg">Attribute Types</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-schema-attribute-test"><span class="secno">3.2.7.3.1 </span><span class="content">Schema Attribute Types</span></a></summary></details></li></ol></details></li></ol></details></li><li><details><summary><a href="#id-function-map-array-tests"><span class="secno">3.2.8 </span><span class="content">Function, Map, and Array Types</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-function-test"><span class="secno">3.2.8.1 </span><span class="content toc-chg">Function Types</span></a></summary></details></li><li><details><summary><a href="#id-map-test"><span class="secno">3.2.8.2 </span><span class="content">Map Types</span></a></summary></details></li><li><details><summary><a href="#id-record-test"><span class="secno">3.2.8.3 </span><span class="content toc-chg">Record Types</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-recursive-record-tests"><span class="secno">3.2.8.3.1 </span><span class="content">Recursive Record Types</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-array-test"><span class="secno">3.2.8.4 </span><span class="content">Array Types</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-generalized-node-types"><span class="secno">3.2.9 </span><span class="content toc-chg">Generalized Node Types</span></a></summary></details></li><li><details><summary><a href="#id-xs-error"><span class="secno">3.2.10 </span><span class="content">The type xs:error</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-sequencetype-subtype"><span class="secno">3.3 </span><span class="content toc-chg">Subtype Relationships</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-seqtype-subtype"><span class="secno">3.3.1 </span><span class="content">Subtypes of Sequence Types</span></a></summary></details></li><li><details><summary><a href="#id-itemtype-subtype"><span class="secno">3.3.2 </span><span class="content">Subtypes of Item Types</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-item-subtype-general"><span class="secno">3.3.2.1 </span><span class="content">General Subtyping Rules</span></a></summary></details></li><li><details><summary><a href="#id-item-subtype-choice"><span class="secno">3.3.2.2 </span><span class="content">Subtyping of Choice Item Types</span></a></summary></details></li><li><details><summary><a href="#id-item-subtype-atomic"><span class="secno">3.3.2.3 </span><span class="content">Subtyping of Atomic and Union Types</span></a></summary></details></li><li><details><summary><a href="#id-item-subtype-enum"><span class="secno">3.3.2.4 </span><span class="content">Subtyping of Enumeration Types</span></a></summary></details></li><li><details><summary><a href="#id-item-subtype-nodes"><span class="secno">3.3.2.5 </span><span class="content">Subtyping of Node Types</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-item-subtype-nodes-general"><span class="secno">3.3.2.5.1 </span><span class="content">Subtyping Nodes: General Rules</span></a></summary></details></li><li><details><summary><a href="#id-item-subtype-documents"><span class="secno">3.3.2.5.2 </span><span class="content toc-chg">Subtyping Nodes: Document Nodes</span></a></summary></details></li><li><details><summary><a href="#id-item-subtype-elements"><span class="secno">3.3.2.5.3 </span><span class="content toc-chg">Subtyping Nodes: Elements</span></a></summary></details></li><li><details><summary><a href="#id-item-subtype-attributes"><span class="secno">3.3.2.5.4 </span><span class="content toc-chg">Subtyping Nodes: Attributes</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-item-subtype-functions"><span class="secno">3.3.2.6 </span><span class="content">Subtyping Functions</span></a></summary></details></li><li><details><summary><a href="#id-item-subtype-maps"><span class="secno">3.3.2.7 </span><span class="content">Subtyping Maps</span></a></summary></details></li><li><details><summary><a href="#id-item-subtype-arrays"><span class="secno">3.3.2.8 </span><span class="content">Subtyping Arrays</span></a></summary></details></li><li><details><summary><a href="#id-item-subtype-records"><span class="secno">3.3.2.9 </span><span class="content">Subtyping Records</span></a></summary></details></li><li><details><summary><a href="#id-itemtype-subtype-aliases"><span class="secno">3.3.2.10 </span><span class="content">Subtyping of Named Item Types</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-assertions-subtype"><span class="secno">3.3.3 </span><span class="content xquery">The judgement subtype-assertions(AnnotationsA, AnnotationsB)</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-coercion-rules"><span class="secno">3.4 </span><span class="content toc-chg">Coercion Rules</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-item-coercion-rules"><span class="secno">3.4.1 </span><span class="content">Item Coercion Rules</span></a></summary></details></li><li><details><summary><a href="#id-implausible-coercions"><span class="secno">3.4.2 </span><span class="content">Implausible Coercions</span></a></summary></details></li><li><details><summary><a href="#id-function-coercion"><span class="secno">3.4.3 </span><span class="content toc-chg">Function Coercion</span></a></summary></details></li><li><details><summary><a href="#id-coercion-examples"><span class="secno">3.4.4 </span><span class="content">Examples of Coercions</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-predefined-types"><span class="secno">3.5 </span><span class="content">Schema Types</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-expressions"><span class="secno">4 </span><span class="content">Expressions</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#comments"><span class="secno">4.1 </span><span class="content">Comments</span></a></summary></details></li><li><details><summary><a href="#id-primary-expressions"><span class="secno">4.2 </span><span class="content">Primary Expressions</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-literals"><span class="secno">4.2.1 </span><span class="content">Literals</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-numeric-literals"><span class="secno">4.2.1.1 </span><span class="content toc-chg">Numeric Literals</span></a></summary></details></li><li><details><summary><a href="#id-string-literal"><span class="secno">4.2.1.2 </span><span class="content">String Literals</span></a></summary></details></li><li><details><summary><a href="#id-qname-literals"><span class="secno">4.2.1.3 </span><span class="content toc-chg">QName Literals</span></a></summary></details></li><li><details><summary><a href="#id-constants-other-types"><span class="secno">4.2.1.4 </span><span class="content">Constants of Other Types</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-variables"><span class="secno">4.2.2 </span><span class="content">Variable References</span></a></summary></details></li><li><details><summary><a href="#id-context-value-references"><span class="secno">4.2.3 </span><span class="content">Context Value References</span></a></summary></details></li><li><details><summary><a href="#id-paren-expressions"><span class="secno">4.2.4 </span><span class="content">Parenthesized Expressions</span></a></summary></details></li><li><details><summary><a href="#id-enclosed-expr"><span class="secno">4.2.5 </span><span class="content">Enclosed Expressions</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-postfix-expression"><span class="secno">4.3 </span><span class="content">Postfix Expressions</span></a></summary></details></li><li><details><summary><a href="#id-filter-expression"><span class="secno">4.4 </span><span class="content toc-chg">Filter Expressions</span></a></summary></details></li><li><details><summary><a href="#id-functions"><span class="secno">4.5 </span><span class="content">Functions</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-static-functions"><span class="secno">4.5.1 </span><span class="content">Static Function Calls</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-function-calls"><span class="secno">4.5.1.1 </span><span class="content toc-chg">Static Function Call Syntax</span></a></summary></details></li><li><details><summary><a href="#id-eval-static-function-call"><span class="secno">4.5.1.2 </span><span class="content">Evaluating Static Function Calls</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-dynamic-functions"><span class="secno">4.5.2 </span><span class="content">Function Items</span></a></summary></details></li><li><details><summary><a href="#id-dynamic-function-invocation"><span class="secno">4.5.3 </span><span class="content">Dynamic Function Calls</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-eval-dynamic-function-call"><span class="secno">4.5.3.1 </span><span class="content toc-chg">Evaluating Dynamic Function Calls</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-partial-function-application"><span class="secno">4.5.4 </span><span class="content">Partial Function Application</span></a></summary></details></li><li><details><summary><a href="#id-named-function-ref"><span class="secno">4.5.5 </span><span class="content">Named Function References</span></a></summary></details></li><li><details><summary><a href="#id-inline-func"><span class="secno">4.5.6 </span><span class="content toc-chg">Inline Function Expressions</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-focus-functions"><span class="secno">4.5.6.1 </span><span class="content">Focus Functions</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-function-identity"><span class="secno">4.5.7 </span><span class="content">Function Identity</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-path-expressions"><span class="secno">4.6 </span><span class="content toc-chg">Path Expressions</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-absolute-path-expressions"><span class="secno">4.6.1 </span><span class="content">Absolute Path Expressions</span></a></summary></details></li><li><details><summary><a href="#id-relative-path-expressions"><span class="secno">4.6.2 </span><span class="content">Relative Path Expressions</span></a></summary></details></li><li><details><summary><a href="#id-path-operator"><span class="secno">4.6.3 </span><span class="content">Path operator (/)</span></a></summary></details></li><li><details><summary><a href="#id-axis-steps"><span class="secno">4.6.4 </span><span class="content">Axis Steps</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#axes"><span class="secno">4.6.4.1 </span><span class="content toc-chg">Axes</span></a></summary></details></li><li><details><summary><a href="#node-tests"><span class="secno">4.6.4.2 </span><span class="content toc-chg">Node Tests</span></a></summary></details></li><li><details><summary><a href="#id-selectors-for-xnodes"><span class="secno">4.6.4.3 </span><span class="content">Selectors for XNodes</span></a></summary></details></li><li><details><summary><a href="#id-selectors-for-JNodes"><span class="secno">4.6.4.4 </span><span class="content">Selectors for JNodes</span></a></summary></details></li><li><details><summary><a href="#id-type-tests"><span class="secno">4.6.4.5 </span><span class="content">Type Tests</span></a></summary></details></li><li><details><summary><a href="#implausible-axis-steps"><span class="secno">4.6.4.6 </span><span class="content toc-chg">Implausible Axis Steps</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-predicate"><span class="secno">4.6.5 </span><span class="content">Predicates within Steps</span></a></summary></details></li><li><details><summary><a href="#unabbrev"><span class="secno">4.6.6 </span><span class="content">Unabbreviated Syntax</span></a></summary></details></li><li><details><summary><a href="#abbrev"><span class="secno">4.6.7 </span><span class="content">Abbreviated Syntax</span></a></summary></details></li><li><details><summary><a href="#comparison-with-JSONPath"><span class="secno">4.6.8 </span><span class="content">Comparison with JSONPath</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-sequence-expressions"><span class="secno">4.7 </span><span class="content">Sequence Expressions</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#construct_seq"><span class="secno">4.7.1 </span><span class="content">Sequence Concatenation</span></a></summary></details></li><li><details><summary><a href="#id-range-expressions"><span class="secno">4.7.2 </span><span class="content">Range Expressions</span></a></summary></details></li><li><details><summary><a href="#combining_seq"><span class="secno">4.7.3 </span><span class="content">Combining GNode Sequences</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-arithmetic"><span class="secno">4.8 </span><span class="content toc-chg">Arithmetic Expressions</span></a></summary></details></li><li><details><summary><a href="#id-string-expr"><span class="secno">4.9 </span><span class="content">String Expressions</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-string-concat-expr"><span class="secno">4.9.1 </span><span class="content">String Concatenation Expressions</span></a></summary></details></li><li><details><summary><a href="#id-string-templates"><span class="secno">4.9.2 </span><span class="content toc-chg">String Templates</span></a></summary></details></li><li><details><summary><a href="#id-string-constructors"><span class="secno">4.9.3 </span><span class="content xquery">String Constructors</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-comparisons"><span class="secno">4.10 </span><span class="content">Comparison Expressions</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-value-comparisons"><span class="secno">4.10.1 </span><span class="content toc-chg">Value Comparisons</span></a></summary></details></li><li><details><summary><a href="#id-general-comparisons"><span class="secno">4.10.2 </span><span class="content toc-chg">General Comparisons</span></a></summary></details></li><li><details><summary><a href="#id-node-comparisons"><span class="secno">4.10.3 </span><span class="content toc-chg">GNode Comparisons</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-logical-expressions"><span class="secno">4.11 </span><span class="content toc-chg">Logical Expressions</span></a></summary></details></li><li><details><summary><a href="#id-constructors"><span class="secno">4.12 </span><span class="content xquery">Node Constructors</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-element-constructor"><span class="secno">4.12.1 </span><span class="content">Direct Element Constructors</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-attributes"><span class="secno">4.12.1.1 </span><span class="content">Attributes</span></a></summary></details></li><li><details><summary><a href="#id-namespaces"><span class="secno">4.12.1.2 </span><span class="content toc-chg">Namespace Declaration Attributes</span></a></summary></details></li><li><details><summary><a href="#id-content"><span class="secno">4.12.1.3 </span><span class="content">Content</span></a></summary></details></li><li><details><summary><a href="#id-whitespace"><span class="secno">4.12.1.4 </span><span class="content">Boundary Whitespace</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-otherConstructors"><span class="secno">4.12.2 </span><span class="content">Other Direct Constructors</span></a></summary></details></li><li><details><summary><a href="#id-computedConstructors"><span class="secno">4.12.3 </span><span class="content">Computed Constructors</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-computedElements"><span class="secno">4.12.3.1 </span><span class="content toc-chg">Computed Element Constructors</span></a></summary></details></li><li><details><summary><a href="#id-computedAttributes"><span class="secno">4.12.3.2 </span><span class="content toc-chg">Computed Attribute Constructors</span></a></summary></details></li><li><details><summary><a href="#id-documentConstructors"><span class="secno">4.12.3.3 </span><span class="content">Document Node Constructors</span></a></summary></details></li><li><details><summary><a href="#id-textConstructors"><span class="secno">4.12.3.4 </span><span class="content">Text Node Constructors</span></a></summary></details></li><li><details><summary><a href="#id-computed-pis"><span class="secno">4.12.3.5 </span><span class="content toc-chg">Computed Processing Instruction Constructors</span></a></summary></details></li><li><details><summary><a href="#id-computed-comments"><span class="secno">4.12.3.6 </span><span class="content">Computed Comment Constructors</span></a></summary></details></li><li><details><summary><a href="#id-computed-namespaces"><span class="secno">4.12.3.7 </span><span class="content toc-chg">Computed Namespace Constructors</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-ns-nodes-on-elements"><span class="secno">4.12.4 </span><span class="content">In-scope Namespaces of a Constructed Element</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-flwor-expressions"><span class="secno">4.13 </span><span class="content">FLWOR Expressions</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-binding-rules"><span class="secno">4.13.1 </span><span class="content xquery">Variable Bindings</span></a></summary></details></li><li><details><summary><a href="#id-xquery-for-clause"><span class="secno">4.13.2 </span><span class="content xquery toc-chg">For Clause</span></a></summary></details></li><li><details><summary><a href="#id-xquery-let-clause"><span class="secno">4.13.3 </span><span class="content xquery toc-chg">Let Clause</span></a></summary></details></li><li><details><summary><a href="#id-windows"><span class="secno">4.13.4 </span><span class="content xquery toc-chg">Window Clause</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-tumbling-windows"><span class="secno">4.13.4.1 </span><span class="content">Tumbling Windows</span></a></summary></details></li><li><details><summary><a href="#id-sliding-windows"><span class="secno">4.13.4.2 </span><span class="content">Sliding Windows</span></a></summary></details></li><li><details><summary><a href="#id-effects-of-window-clauses"><span class="secno">4.13.4.3 </span><span class="content">Effects of Window Clauses on the Tuple Stream</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-where"><span class="secno">4.13.5 </span><span class="content xquery">Where Clause</span></a></summary></details></li><li><details><summary><a href="#id-while"><span class="secno">4.13.6 </span><span class="content xquery toc-chg">While Clause</span></a></summary></details></li><li><details><summary><a href="#id-count"><span class="secno">4.13.7 </span><span class="content xquery">Count Clause</span></a></summary></details></li><li><details><summary><a href="#id-group-by"><span class="secno">4.13.8 </span><span class="content xquery">Group By Clause</span></a></summary></details></li><li><details><summary><a href="#id-order-by-clause"><span class="secno">4.13.9 </span><span class="content xquery">Order By Clause</span></a></summary></details></li><li><details><summary><a href="#id-return-clause"><span class="secno">4.13.10 </span><span class="content xquery">Return Clause</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-maps-and-arrays"><span class="secno">4.14 </span><span class="content">Maps and Arrays</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-maps"><span class="secno">4.14.1 </span><span class="content toc-chg">Maps</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-map-constructors"><span class="secno">4.14.1.1 </span><span class="content toc-chg">Map Constructors</span></a></summary></details></li><li><details><summary><a href="#id-map-lookup"><span class="secno">4.14.1.2 </span><span class="content">Maps as Functions</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-arrays"><span class="secno">4.14.2 </span><span class="content">Arrays</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-array-constructors"><span class="secno">4.14.2.1 </span><span class="content">Array Constructors</span></a></summary></details></li><li><details><summary><a href="#id-array-lookup"><span class="secno">4.14.2.2 </span><span class="content">Arrays as Functions</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-lookup"><span class="secno">4.14.3 </span><span class="content toc-chg">Lookup Expressions</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-postfix-lookup"><span class="secno">4.14.3.1 </span><span class="content">Postfix Lookup Expressions</span></a></summary></details></li><li><details><summary><a href="#id-unary-lookup"><span class="secno">4.14.3.2 </span><span class="content">Unary Lookup</span></a></summary></details></li><li><details><summary><a href="#id-lookup-vs-path-expressions"><span class="secno">4.14.3.3 </span><span class="content">Comparing Lookup and Path Expressions</span></a></summary></details></li><li><details><summary><a href="#id-implausible-lookup-expressions"><span class="secno">4.14.3.4 </span><span class="content">Implausible Lookup Expressions</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-methods"><span class="secno">4.14.4 </span><span class="content toc-chg">Method Calls</span></a></summary></details></li><li><details><summary><a href="#id-filter-maps-and-arrays"><span class="secno">4.14.5 </span><span class="content toc-chg">Filter Expressions for Maps and Arrays</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-unordered-expressions"><span class="secno">4.15 </span><span class="content xquery toc-chg">Ordered and Unordered Expressions</span></a></summary></details></li><li><details><summary><a href="#id-conditionals"><span class="secno">4.16 </span><span class="content toc-chg">Conditional Expressions</span></a></summary></details></li><li><details><summary><a href="#id-otherwise"><span class="secno">4.17 </span><span class="content toc-chg">Otherwise Expressions</span></a></summary></details></li><li><details><summary><a href="#id-switch"><span class="secno">4.18 </span><span class="content xquery toc-chg">Switch Expressions</span></a></summary></details></li><li><details><summary><a href="#id-quantified-expressions"><span class="secno">4.19 </span><span class="content toc-chg">Quantified Expressions</span></a></summary></details></li><li><details><summary><a href="#id-try-catch"><span class="secno">4.20 </span><span class="content xquery toc-chg">Try/Catch Expressions</span></a></summary></details></li><li><details><summary><a href="#id-expressions-on-datatypes"><span class="secno">4.21 </span><span class="content">Expressions on SequenceTypes</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-instance-of"><span class="secno">4.21.1 </span><span class="content">Instance Of</span></a></summary></details></li><li><details><summary><a href="#id-typeswitch"><span class="secno">4.21.2 </span><span class="content xquery toc-chg">Typeswitch</span></a></summary></details></li><li><details><summary><a href="#id-cast"><span class="secno">4.21.3 </span><span class="content">Cast</span></a></summary></details></li><li><details><summary><a href="#id-castable"><span class="secno">4.21.4 </span><span class="content">Castable</span></a></summary></details></li><li><details><summary><a href="#id-constructor-functions"><span class="secno">4.21.5 </span><span class="content">Constructor Functions</span></a></summary></details></li><li><details><summary><a href="#id-treat"><span class="secno">4.21.6 </span><span class="content toc-chg">Treat</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-pipeline-operator"><span class="secno">4.22 </span><span class="content toc-chg">Pipeline operator</span></a></summary></details></li><li><details><summary><a href="#id-map-operator"><span class="secno">4.23 </span><span class="content">Simple map operator (!)</span></a></summary></details></li><li><details><summary><a href="#id-arrow-operator"><span class="secno">4.24 </span><span class="content toc-chg">Arrow Expressions</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-sequence-arrow-expression"><span class="secno">4.24.1 </span><span class="content">Sequence Arrow Expressions</span></a></summary></details></li><li><details><summary><a href="#id-mapping-arrow-expression"><span class="secno">4.24.2 </span><span class="content toc-chg">Mapping Arrow Expressions</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-validate"><span class="secno">4.25 </span><span class="content xquery toc-chg">Validate Expressions</span></a></summary></details></li><li><details><summary><a href="#id-extension-expressions"><span class="secno">4.26 </span><span class="content xquery toc-chg">Extension Expressions</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-query-prolog"><span class="secno">5 </span><span class="content xquery">Modules and Prologs</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-version-declaration"><span class="secno">5.1 </span><span class="content">Version Declaration</span></a></summary></details></li><li><details><summary><a href="#id-module-declaration"><span class="secno">5.2 </span><span class="content">Module Declaration</span></a></summary></details></li><li><details><summary><a href="#id-boundary-space-decls"><span class="secno">5.3 </span><span class="content">Boundary-space Declaration</span></a></summary></details></li><li><details><summary><a href="#id-default-collation-declaration"><span class="secno">5.4 </span><span class="content">Default Collation Declaration</span></a></summary></details></li><li><details><summary><a href="#id-base-uri-decl"><span class="secno">5.5 </span><span class="content">Base URI Declaration</span></a></summary></details></li><li><details><summary><a href="#id-construction-declaration"><span class="secno">5.6 </span><span class="content">Construction Declaration</span></a></summary></details></li><li><details><summary><a href="#id-default-ordering-decl"><span class="secno">5.7 </span><span class="content toc-chg">Ordering Mode Declaration</span></a></summary></details></li><li><details><summary><a href="#id-empty-order-decl"><span class="secno">5.8 </span><span class="content">Empty Order Declaration</span></a></summary></details></li><li><details><summary><a href="#id-copy-namespaces-decl"><span class="secno">5.9 </span><span class="content">Copy-Namespaces Declaration</span></a></summary></details></li><li><details><summary><a href="#id-decimal-format-decl"><span class="secno">5.10 </span><span class="content toc-chg">Decimal Format Declaration</span></a></summary></details></li><li><details><summary><a href="#id-schema-import"><span class="secno">5.11 </span><span class="content toc-chg">Schema Import</span></a></summary></details></li><li><details><summary><a href="#id-module-import"><span class="secno">5.12 </span><span class="content">Module Import</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-module-handling-module-uris"><span class="secno">5.12.1 </span><span class="content">The Target Namespace of a Module</span></a></summary></details></li><li><details><summary><a href="#id-module-handling-multiple-same"><span class="secno">5.12.2 </span><span class="content">Multiple Modules with the same Namespace</span></a></summary></details></li><li><details><summary><a href="#id-module-handling-location-uris"><span class="secno">5.12.3 </span><span class="content">Location URIs</span></a></summary></details></li><li><details><summary><a href="#id-module-handling-cycles"><span class="secno">5.12.4 </span><span class="content">Cycles</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-namespace-declaration"><span class="secno">5.13 </span><span class="content toc-chg">Namespace Declaration</span></a></summary></details></li><li><details><summary><a href="#id-default-namespace"><span class="secno">5.14 </span><span class="content toc-chg">Default Namespace Declaration</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-default-element-namespace-declaration"><span class="secno">5.14.1 </span><span class="content">Default Element Namespace Declaration</span></a></summary></details></li><li><details><summary><a href="#id-default-function-namespace-declaration"><span class="secno">5.14.2 </span><span class="content">Default Function Namespace Declaration</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-annotations"><span class="secno">5.15 </span><span class="content">Annotations</span></a></summary></details></li><li><details><summary><a href="#id-variable-declarations"><span class="secno">5.16 </span><span class="content toc-chg">Variable Declaration</span></a></summary></details></li><li><details><summary><a href="#id-context-value-declarations"><span class="secno">5.17 </span><span class="content toc-chg">Context Value Declaration</span></a></summary></details></li><li><details><summary><a href="#FunctionDeclns"><span class="secno">5.18 </span><span class="content toc-chg">Function Declarations</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-user-defined-functions"><span class="secno">5.18.1 </span><span class="content">User-Defined Functions</span></a></summary></details></li><li><details><summary><a href="#id-function-names"><span class="secno">5.18.2 </span><span class="content toc-chg">Function Names</span></a></summary></details></li><li><details><summary><a href="#id-function-parameters"><span class="secno">5.18.3 </span><span class="content">Function Parameters</span></a></summary></details></li><li><details><summary><a href="#id-function-annotations"><span class="secno">5.18.4 </span><span class="content toc-chg">Function Annotations</span></a></summary></details></li><li><details><summary><a href="#id-external-functions"><span class="secno">5.18.5 </span><span class="content">External Functions</span></a></summary></details></li><li><details><summary><a href="#id-recursion"><span class="secno">5.18.6 </span><span class="content">Recursion</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-item-type-declaration"><span class="secno">5.19 </span><span class="content">Item Type Declarations</span></a></summary></details></li><li><details><summary><a href="#id-named-record-types"><span class="secno">5.20 </span><span class="content">Named Record Types</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#named-records-as-item-types"><span class="secno">5.20.1 </span><span class="content">Named Records as Item Types</span></a></summary></details></li><li><details><summary><a href="#named-records-as-functions"><span class="secno">5.20.2 </span><span class="content">Constructor Functions for Named Record Types</span></a></summary></details></li><li><details><summary><a href="#id-functions-as-fields"><span class="secno">5.20.3 </span><span class="content">Using Methods in Records</span></a></summary></details></li><li><details><summary><a href="#id-atomic-set-example"><span class="secno">5.20.4 </span><span class="content">Example: Defining an Atomic Set</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-option-declaration"><span class="secno">5.21 </span><span class="content">Option Declarations</span></a></summary></details></li><li><details><summary><a href="#id-output-declarations"><span class="secno">5.22 </span><span class="content">Output Declarations</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-serialization-parameters"><span class="secno">5.22.1 </span><span class="content">Serialization Parameters</span></a></summary></details></li></ol></details></li></ol></details></li><li><details><summary><a href="#id-conformance"><span class="secno">6 </span><span class="content toc-chg">Conformance</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-minimal-conformance"><span class="secno">6.1 </span><span class="content xquery">Minimal Conformance</span></a></summary></details></li><li><details><summary><a href="#id-conform-optional-features"><span class="secno">6.2 </span><span class="content xquery">Optional Features</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-schema-aware-feature"><span class="secno">6.2.1 </span><span class="content">Schema Aware Feature</span></a></summary></details></li><li><details><summary><a href="#id-typed-data-feature"><span class="secno">6.2.2 </span><span class="content">Typed Data Feature</span></a></summary></details></li><li><details><summary><a href="#id-serialization-feature"><span class="secno">6.2.3 </span><span class="content">Serialization Feature</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-data-model-conformance"><span class="secno">6.3 </span><span class="content xquery">Data Model Conformance</span></a></summary></details></li><li><details><summary><a href="#id-syntax-extensions"><span class="secno">6.4 </span><span class="content xquery">Syntax Extensions</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#nt-bnf"><span class="secno">A </span><span class="content">XQuery 4.0 Grammar</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-grammar"><span class="secno">A.1 </span><span class="content toc-chg">EBNF</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#EBNFNotation"><span class="secno">A.1.1 </span><span class="content toc-chg">Notation</span></a></summary></details></li><li><details><summary><a href="#extra-grammatical-constraints"><span class="secno">A.1.2 </span><span class="content">Extra-grammatical Constraints</span></a></summary></details></li><li><details><summary><a href="#notes-on-parsing"><span class="secno">A.1.3 </span><span class="content">Grammar Notes</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#productions-derived-from-XML"><span class="secno">A.2 </span><span class="content">Productions Derived from XML</span></a></summary></details></li><li><details><summary><a href="#lexical-structure"><span class="secno">A.3 </span><span class="content toc-chg">Lexical structure</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#terminal-symbols"><span class="secno">A.3.1 </span><span class="content">Terminal Symbols</span></a></summary></details></li><li><details><summary><a href="#id-terminal-delimitation"><span class="secno">A.3.2 </span><span class="content">Terminal Delimitation</span></a></summary></details></li><li><details><summary><a href="#id-eol-handling"><span class="secno">A.3.3 </span><span class="content">End-of-Line Handling</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-xml10-eol-handling"><span class="secno">A.3.3.1 </span><span class="content">XML 1.0 End-of-Line Handling</span></a></summary></details></li><li><details><summary><a href="#id-xml11-eol-handling"><span class="secno">A.3.3.2 </span><span class="content">XML 1.1 End-of-Line Handling</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#whitespace-rules"><span class="secno">A.3.4 </span><span class="content">Whitespace Rules</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#DefaultWhitespaceHandling"><span class="secno">A.3.4.1 </span><span class="content">Default Whitespace Handling</span></a></summary></details></li><li><details><summary><a href="#ExplicitWhitespaceHandling"><span class="secno">A.3.4.2 </span><span class="content">Explicit Whitespace Handling</span></a></summary></details></li></ol></details></li></ol></details></li><li><details><summary><a href="#id-reserved-fn-names"><span class="secno">A.4 </span><span class="content toc-chg">Reserved Function Names</span></a></summary></details></li><li><details><summary><a href="#id-precedence-order"><span class="secno">A.5 </span><span class="content">Precedence Order (Non-Normative)</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-xq-context-components"><span class="secno">B </span><span class="content xquery">Context Components</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-xq-static-context-components"><span class="secno">B.1 </span><span class="content toc-chg">Static Context Components</span></a></summary></details></li><li><details><summary><a href="#id-xq-evaluation-context-components"><span class="secno">B.2 </span><span class="content">Dynamic Context Components</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-impl-defined-items"><span class="secno">C </span><span class="content">Implementation-Defined Items</span></a></summary></details></li><li><details><summary><a href="#id-references"><span class="secno">D </span><span class="content">References</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-normative-references"><span class="secno">D.1 </span><span class="content">Normative References</span></a></summary></details></li><li><details><summary><a href="#id-non-normative-references"><span class="secno">D.2 </span><span class="content">Non-normative References</span></a></summary></details></li><li><details><summary><a href="#id-background-material"><span class="secno">D.3 </span><span class="content">Background Material</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-errors"><span class="secno">E </span><span class="content">Error Conditions</span></a></summary></details></li><li><details><summary><a href="#id-mime-type"><span class="secno">F </span><span class="content xquery">The application/xquery Media Type</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-mime-type-intro"><span class="secno">F.1 </span><span class="content">Introduction</span></a></summary></details></li><li><details><summary><a href="#id-registration-of-mime-type"><span class="secno">F.2 </span><span class="content">Registration of MIME Media Type application/xquery</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-interoperability-considerations"><span class="secno">F.2.1 </span><span class="content">Interoperability Considerations</span></a></summary></details></li><li><details><summary><a href="#id-applications-of-media-type"><span class="secno">F.2.2 </span><span class="content">Applications Using this Media Type</span></a></summary></details></li><li><details><summary><a href="#id-file-extensions"><span class="secno">F.2.3 </span><span class="content">File Extensions</span></a></summary></details></li><li><details><summary><a href="#id-intended-usage"><span class="secno">F.2.4 </span><span class="content">Intended Usage</span></a></summary></details></li><li><details><summary><a href="#id-author-change-controller"><span class="secno">F.2.5 </span><span class="content">Author/Change Controller</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#xquery-mime-encoding"><span class="secno">F.3 </span><span class="content">Encoding Considerations</span></a></summary></details></li><li><details><summary><a href="#xquery-mime-recognizing"><span class="secno">F.4 </span><span class="content">Recognizing XQuery Files</span></a></summary></details></li><li><details><summary><a href="#id-charset-default-rules"><span class="secno">F.5 </span><span class="content">Charset Default Rules</span></a></summary></details></li><li><details><summary><a href="#id-security-considerations"><span class="secno">F.6 </span><span class="content">Security Considerations</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-glossary"><span class="secno">G </span><span class="content">Glossary</span></a></summary></details></li><li><details><summary><a href="#id-atomic-comparisons"><span class="secno">H </span><span class="content">Atomic Comparisons: An Overview</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#value-comparisons-summary"><span class="secno">H.1 </span><span class="content">Value Comparisons</span></a></summary></details></li><li><details><summary><a href="#general-comparisons-summary"><span class="secno">H.2 </span><span class="content">General Comparisons</span></a></summary></details></li><li><details><summary><a href="#deep-equal-summary"><span class="secno">H.3 </span><span class="content">fn:deep-equal</span></a></summary></details></li><li><details><summary><a href="#atomic-equal-summary"><span class="secno">H.4 </span><span class="content">fn:atomic-equal</span></a></summary></details></li><li><details><summary><a href="#fn-compare-summary"><span class="secno">H.5 </span><span class="content">fn:compare</span></a></summary></details></li><li><details><summary><a href="#comparison-methods-summary"><span class="secno">H.6 </span><span class="content">Summary of Atomic Comparison Methods</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-incompatibilities"><span class="secno">I </span><span class="content">Backwards Compatibility</span></a><span class="exptoc collapsed"/></summary><ol class="toc"><li><details><summary><a href="#id-incompatibilities-31"><span class="secno">I.1 </span><span class="content">Incompatibilities relative to XQuery 3.1</span></a></summary></details></li><li><details><summary><a href="#id-incompatibilities-30"><span class="secno">I.2 </span><span class="content">Incompatibilities relative to XQuery 3.0</span></a></summary></details></li><li><details><summary><a href="#id-incompatibilities-10"><span class="secno">I.3 </span><span class="content">Incompatibilities relative to XQuery 1.0</span></a></summary></details></li></ol></details></li><li><details><summary><a href="#id-revision-log"><span class="secno">J </span><span class="content">Change Log</span></a></summary></details></li></ol></nav><hr/><div class="body"><div class="div1">
<h2><a id="id-introduction"/>1 <a href="#id-introduction" style="text-decoration: none">Introduction</a></h2><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-terminology">⬇</a></p><ol><li><p>Use the arrows to browse significant changes since the 3.1 version of this specification.</p></li><li><p>Sections with significant changes are marked Δ in the table of contents.</p></li></ol></div><p>As increasing amounts of information are stored, exchanged, and presented using
		XML, the ability to intelligently query XML data sources becomes increasingly important. One
		of the great strengths of XML is its flexibility in representing many different kinds of
		information from diverse sources. To exploit this flexibility, an XML query language must
	provide features for retrieving and interpreting information from these diverse sources.</p><p>As increasing amounts of JSON are used for lightweight data-exchange, an XML query language
	for Web data needs to handle JSON as well as XML and HTML.</p><p>XQuery is designed to be a language in which queries are concise and
		easily understood. It is also flexible enough to query a broad spectrum of information
		sources, both XML and non-XML, including both databases and documents. XQuery was originally derived from an XML query
		language called Quilt <a href="#Quilt">[Quilt]</a>, which in turn borrowed features from several
		other languages, including XPath 1.0 <a href="#xpath">[XPath 1.0]</a>, XQL <a href="#XQL">[XQL]</a>, XML-QL
			<a href="#XML-QL">[XML-QL]</a>, SQL <a href="#SQL">[SQL]</a>, and OQL <a href="#ODMG">[ODMG]</a>. </p><p>
            [<a id="dt-datamodel" title="data model">Definition</a>: 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 <b>data model</b>, is defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a>.]
         </p><p>
            <span class="xquery">XQuery 4.0 is an extension of XPath 4.0.</span>
          

 In general, any expression that is
		syntactically valid and executes successfully in both XPath 4.0 and XQuery 4.0 will return
		the same result in both languages. There are a few exceptions to this rule: </p><ul><li><p>Because XQuery expands <span class="xquery">
                        <a title="predefined entity reference" class="termref" href="#dt-predefined-entity-reference">predefined entity
							references</a> and <a title="character reference" class="termref" href="#dt-character-reference">character
							references</a>
                     </span>
					 and XPath does not, expressions containing these produce different
					results in the two languages. For instance, the value of the string literal
						<code>"&amp;amp;"</code> is <code>&amp;</code> in XQuery,
					and <code>&amp;amp;</code> in XPath. (A host language may expand predefined entity references or character references
					before the XPath expression is evaluated.)</p></li><li><p>If XPath 1.0 compatibility mode is enabled, XPath behaves differently from
					XQuery in a number of ways, 
					<span class="xquery">which are discussed in <a href="#xpath-40">[XPath 4.0]</a>.</span>
                  </p></li></ul><p>Because these languages are so closely related, their grammars and language descriptions are
		generated from a common source to ensure consistency.</p><p>XQuery 4.0 also depends on and is closely related to the following specifications:</p><ul><li><p>
                  <a href="#xpath-datamodel-40">[XDM 4.0]</a> defines the data model that underlies all
				XQuery 4.0 expressions.</p></li><li><p>The type system of XQuery 4.0 is based on XML Schema. It is implementation-defined
				whether the type system is based on <a href="#XMLSchema10">[XML Schema 1.0]</a> or <a href="#XMLSchema11">[XML Schema 1.1]</a>.</p></li><li><p>The system function library and the operators supported by XQuery 4.0 are defined
				in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>The XML-based syntax for XQuery known as XQueryX
		is no longer maintained.</p></div><p>
            [<a id="dt-xquery-40-processor" title="XQuery 4.0 Processor">Definition</a>:  An <b>XQuery 4.0
			Processor</b> processes a query according to the XQuery 4.0 specification. ]
            [<a id="dt-xquery-31-processor" title="XQuery 3.1 Processor">Definition</a>:  An <b>XQuery 3.1
				Processor</b> processes a query according to the XQuery 3.1 specification. ]
            [<a id="dt-xquery-30-processor" title="XQuery 3.0 Processor">Definition</a>:  An <b>XQuery 3.0
				Processor</b> processes a query according to the XQuery 3.0 specification. ]
            [<a id="dt-xquery-10-processor" title="XQuery 1.0 Processor">Definition</a>:  An <b>XQuery 1.0
				Processor</b> processes a query according to the XQuery 1.0 specification.
		]
         </p><p>This document specifies a grammar for XQuery 4.0, using the same basic EBNF notation used in
			<a href="#XML">[XML 1.0]</a>. Unless otherwise noted (see <a href="#lexical-structure"><b>A.3 Lexical structure</b></a>),
		whitespace is not significant in <span class="xquery">queries</span>. Grammar productions are introduced together with the features
		that they describe, and a complete grammar is also presented in the appendix [<a href="#nt-bnf"><b>A XQuery 4.0 Grammar</b></a>]. The appendix is the normative version.</p><p>In the grammar productions in this document, named symbols are underlined and literal text is
		enclosed in double quotes. For example, the following productions describe the syntax of a
		static function call:</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-FunctionCall"/><code>FunctionCall</code></td><td>::=</td><td><code>
                  <a href="#example-example-doc-xquery40-FunctionCall-EQName">EQName</a>
                  <a href="#example-example-doc-xquery40-FunctionCall-ArgumentList">ArgumentList</a>
               </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                  <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                */</td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                  <a href="#parse-note-parens">gn: parens</a>
                */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-FunctionCall-EQName"/><code>EQName</code></td><td>::=</td><td><code>
                  <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-FunctionCall-ArgumentList"/><code>ArgumentList</code></td><td>::=</td><td><code>"("  ((<a href="#example-example-doc-xquery40-FunctionCall-PositionalArguments">PositionalArguments</a>  (","  <a href="#example-example-doc-xquery40-FunctionCall-KeywordArguments">KeywordArguments</a>)?)  |  <a href="#example-example-doc-xquery40-FunctionCall-KeywordArguments">KeywordArguments</a>)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-FunctionCall-PositionalArguments"/><code>PositionalArguments</code></td><td>::=</td><td><code>(<a href="#example-example-doc-xquery40-FunctionCall-Argument">Argument</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-FunctionCall-Argument"/><code>Argument</code></td><td>::=</td><td><code>
                  <a href="#example-example-doc-xquery40-FunctionCall-ExprSingle">ExprSingle</a>  |  <a href="#example-example-doc-xquery40-FunctionCall-ArgumentPlaceholder">ArgumentPlaceholder</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-FunctionCall-ExprSingle"/><code>ExprSingle</code></td><td>::=</td><td><code>
                  <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                  <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                  <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                  <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                  <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                  <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                  <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-FunctionCall-ArgumentPlaceholder"/><code>ArgumentPlaceholder</code></td><td>::=</td><td><code>"?"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-FunctionCall-KeywordArguments"/><code>KeywordArguments</code></td><td>::=</td><td><code>(<a href="#example-example-doc-xquery40-FunctionCall-KeywordArgument">KeywordArgument</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-FunctionCall-KeywordArgument"/><code>KeywordArgument</code></td><td>::=</td><td><code>
                  <a href="#example-example-doc-xquery40-FunctionCall-EQName">EQName</a>  ":="  <a href="#example-example-doc-xquery40-FunctionCall-Argument">Argument</a>
               </code></td></tr></tbody></table><p>The productions should be read as follows: A function call consists of an <a href="#doc-xquery40-EQName">EQName</a> followed by an <a href="#prod-xquery40-ArgumentList">ArgumentList</a>. The
		argument list consists of an opening parenthesis, an optional list of one or more arguments
		(separated by commas), and a closing parenthesis.</p><p>This document normatively defines the static and dynamic semantics of XQuery 4.0. In this
		document, examples and material labeled as “Note” are provided for explanatory purposes and
		are not normative.</p></div><div class="div1">
<h2><a id="id-basics"/>2 <a href="#id-basics" style="text-decoration: none">Basics</a></h2><div class="div2">
<h3><a id="id-terminology"/>2.1 <a href="#id-terminology" style="text-decoration: none">Terminology</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-ebnf-introduction">⬇</a> <a href="#id-introduction">⬆</a></p><ol><li><p>The EBNF operators <code>++</code> and <code>**</code>
      have been introduced, for more concise representation of sequences using a character
      such as <code>","</code> as a separator. The notation is borrowed from Invisible XML.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1366">1366</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1498">1498</a>]</i></p></li></ol></div><p>The basic building block of XQuery 4.0 is the
	 <b>expression</b>, which is a string of <a href="#Unicode">[Unicode]</a> characters; the version of Unicode to be used is <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>.
	 The language provides several kinds of expressions which may be constructed
	 from keywords, symbols, and operands. In general, the operands of an expression
	 are other expressions. XQuery 4.0 allows expressions to be nested with full
generality. <span class="xquery">(However, unlike a pure functional
language, it does not allow variable substitution if the variable
declaration contains construction of new nodes.)</span>
            </p><div class="note"><p class="prefix"><b>Note:</b></p><p>This specification contains no
assumptions or requirements regarding the character set encoding of strings
of <a href="#Unicode">[Unicode]</a> characters.</p></div><p>Like XML, XQuery 4.0 is a case-sensitive language. Keywords in
	 XQuery 4.0 use lower-case characters and are not reserved—that is, names in XQuery 4.0 expressions are allowed to be the same as language keywords, except for certain unprefixed function-names listed in <a href="#id-reserved-fn-names"><b>A.4 Reserved Function Names</b></a>.</p><p>In this specification the phrases <span class="verb">must</span>, <span class="verb">must
                  not</span>, <span class="verb">should</span>, <span class="verb">should not</span>,
                  <span class="verb">may</span>, <span class="verb">required</span>, and
                  <span class="verb">recommended</span>, when used in normative
                  text and rendered in small capitals, are to be interpreted as described in
                  <a href="#RFC2119">[RFC2119]</a>.</p><p>Certain aspects of language processing are described in this specification as
			<b>implementation-defined</b> or <b>implementation-dependent</b>.</p><ul><li><p>
                     [<a id="dt-implementation-defined" title="implementation defined">Definition</a>: 
                        <b>Implementation-defined</b> indicates an aspect that may differ
					between implementations, but must be specified by the implementer for each
					particular implementation.]
                  </p></li><li><p>
                     [<a id="dt-implementation-dependent" title="implementation   dependent">Definition</a>: 
                        <b>Implementation-dependent</b> 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.]
                  </p></li></ul><div class="div3">
<h4><a id="id-ebnf-introduction"/>2.1.1 <a href="#id-ebnf-introduction" style="text-decoration: none">Grammar Notation</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-expression-names">⬇</a> <a href="#id-terminology">⬆</a></p><ol><li><p>
                  The EBNF notation has been extended to allow the constructs <code>(A ++ ",")</code>
                  (one or more occurrences of <code>A</code>, comma-separated, and <code>(A ** ",")</code>
                  (zero or more occurrences of <code>A</code>, comma-separated.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1366">1366</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1498">1498</a> 30 October 2024]</i></p></li></ol></div><p>The grammar of XQuery 4.0 is defined using a version of EBNF defined
            in <a href="#EBNFNotation"><b>A.1.1 Notation</b></a>. The notation is based on the EBNF dialect used in the
            XML specification, with two notable additions derived from the Invisible XML grammar:</p><p>
                  <code>(A ++ ",")</code> represents a sequence of one or more comma-separated
               occurrences of <code>A</code>.</p><p>
                  <code>(A ** ",")</code> represents a sequence of zero or more comma-separated
               occurrences of <code>A</code>.</p><p>For example the following production rule indicates that an <code>Expr</code>
            consists of one or more occurrences of <code>ExprSingle</code>, separated by commas:</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-Expr"/><code>Expr</code></td><td>::=</td><td><code>(<a href="#example-example-doc-xquery40-Expr-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-Expr-ExprSingle"/><code>ExprSingle</code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody></table><p>In principle any production can be used for the separator, but in practice this notation
            is only used in cases where the separator is a simple constant string.</p><p>EBNF grammar rules appear throughout the specification for ease of reference, and the
            entire grammar is summarized in <a href="#id-grammar"><b>A.1 EBNF</b></a>.
            
            <span class="xquery">For XQuery 4.0, the top-level production rule is 
            <a href="#doc-xquery40-Module">Module</a>, representing an XQuery module.</span>
               </p></div><div class="div3">
<h4><a id="id-expression-names"/>2.1.2 <a href="#id-expression-names" style="text-decoration: none">Expression Names</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-values">⬇</a> <a href="#id-ebnf-introduction">⬆</a></p><ol><li><p>
                  This section describes and formalizes a convention that was already in use,
                  but not explicitly stated, in earlier versions of the specification.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2084">2084</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2115">2115</a> 23 July 2025]</i></p></li></ol></div><p>Many grammatical production rules for expressions 
               take a form similar to:</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-RangeExpr"/><code>RangeExpr</code></td><td>::=</td><td><code>
                        <a href="#example-example-doc-xquery40-RangeExpr-AdditiveExpr">AdditiveExpr</a>  ("to"  <a href="#example-example-doc-xquery40-RangeExpr-AdditiveExpr">AdditiveExpr</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="example-example-doc-xquery40-RangeExpr-AdditiveExpr"/><code>AdditiveExpr</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-MultiplicativeExpr">MultiplicativeExpr</a>  (("+"  |  "-")  <a href="#prod-xquery40-MultiplicativeExpr">MultiplicativeExpr</a>)*</code></td></tr></tbody></table><p>In describing the semantics of the language, we adopt the convention that a
               term such as <b>range expression</b> (written in bold, or hyperlinked to its definition)
               refers to a non-trivial instance of the production named <a href="#doc-xquery40-RangeExpr">RangeExpr</a>. More
               specifically, it refers to an instance of the production in which the optional part
               (<code>to AdditiveExpr</code>) is actually present. The construct <code>$n + 1</code>,
               being an <a href="#doc-xquery40-AdditiveExpr">AdditiveExpr</a>, is technically an instance of <a href="#doc-xquery40-RangeExpr">RangeExpr</a>,
               but it is not a <b>range expression</b> under this definition.</p><p>
                  [<a id="dt-non-trivial" title="non-trivial">Definition</a>: A construct is said to be a
            <b>non-trivial</b> instance of a grammatical production if it is not also
            an instance of one of its sub-productions.]
               </p></div><div class="div3">
<h4><a id="id-values"/>2.1.3 <a href="#id-values" style="text-decoration: none">Values</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-namespaces-and-qnames">⬇</a> <a href="#id-expression-names">⬆</a></p><ol><li><p>
               The term <b>atomic value</b> has been replaced by <a title="atomic item" class="termref" href="#dt-atomic-item">atomic item</a>.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1337">1337</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1361">1361</a> 2 August 2024]</i></p></li><li><p>
               The terms <b>XNode</b> and <code>JNode</code> are introduced; the existing
               term <b>node</b> remains in use as a synonym for <b>XNode</b> where
               the context does not specify otherwise.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2025">2025</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2031">2031</a> 13 June 2025]</i></p></li></ol></div><p>
                  [<a id="dt-value" title="value">Definition</a>: In the <a title="data model" class="termref" href="#dt-datamodel">data model</a>, a <b>value</b> is always a <a title="sequence" class="termref" href="#dt-sequence">sequence</a>.]
               </p><p>
                  [<a id="dt-sequence" title="sequence">Definition</a>: A
<b>sequence</b> is an ordered collection of zero or more
<a title="item" class="termref" href="#dt-item">items</a>.]
               </p><p>
                  [<a id="dt-item" title="item">Definition</a>: 
  An <b>item</b> is either an <a title="atomic item" class="termref" href="#dt-atomic-item">atomic item</a>, a <a title="node" class="termref" href="#dt-node">node</a>,
or a <a title="function item" class="termref" href="#dt-function-item">function item</a>.]
               </p><p>
                  [<a id="dt-atomic-item" title="atomic item">Definition</a>: An <b>atomic
	 item</b> is a value in the value space of an <b>atomic
	 type</b>, as defined in <a href="#XMLSchema10">[XML Schema 1.0]</a>  or <a href="#XMLSchema11">[XML Schema 1.1]</a>.]
               </p><p>
                  [<a id="dt-XNode" title="XNode">Definition</a>: An <b>XNode</b> is an instance of one of the
	  <b>node kinds</b> defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#nodes">7.1 XML Nodes</a>.]
Each XNode has a unique <b>node identity</b>, a <b>typed value</b>, and a <b>string value</b>. 
            In addition, some XNodes have a <b>name</b>. The <b>typed value</b> of an XNode is a sequence
	 of zero or more atomic items. The <b>string value</b> of an XNode is a
	 value of type <code>xs:string</code>. The <b>name</b> of an XNode is a value of type <code>xs:QName</code>.</p><p>
                  [<a id="dt-node" title="node">Definition</a>: Except where the context indicates otherwise, the term
         <b>node</b> is used as a synonym for <a title="XNode" class="termref" href="#dt-XNode">XNode</a>.]
               </p><p>
                  [<a id="dt-function-item" title="function item">Definition</a>: A <b>function item</b> is an item that can
         be called using a <a title="dynamic function call" class="termref" href="#dt-dynamic-function-call">dynamic function call</a>.]
               </p><p>Maps (see <a href="#id-maps"><b>4.14.1 Maps</b></a>) and arrays (see <a href="#id-arrays"><b>4.14.2 Arrays</b></a>) are
         specific kinds of <a title="function item" class="termref" href="#dt-function-item">function item</a>s.</p><p>
                  [<a id="dt-singleton" title="singleton">Definition</a>: A sequence containing exactly one item is called a
	 <b>singleton</b>.] An item is identical to a singleton sequence
	 containing that item. Sequences are never nested—for example, combining the
	 values 1, (2, 3), and ( ) into a single sequence results in the sequence (1, 2,
	 3). [<a id="dt-empty-sequence" title="empty sequence">Definition</a>: A sequence containing zero items is called an <b>empty sequence</b>.]
               </p><p>
                  [<a id="dt-data-model-instance" title="XDM instance">Definition</a>: The term <b>XDM instance</b> is used,
    synonymously with the term <a title="value" class="termref" href="#dt-value">value</a>, to denote an unconstrained
    <a title="sequence" class="termref" href="#dt-sequence">sequence</a> of <a title="item" class="termref" href="#dt-item">items</a>.]
               </p></div><div class="div3">
<h4><a id="id-namespaces-and-qnames"/>2.1.4 <a href="#id-namespaces-and-qnames" style="text-decoration: none">Namespaces and QNames</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#static_context">⬇</a> <a href="#id-values">⬆</a></p><ol><li><p>In XQuery 4.0, an initial set of
            namespace bindings is prescribed for the static context.<i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/485">485</a> <a href="https://github.com/qt4cg/qtspecs/issues/2178">2178</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/487">487</a>]</i></p></li><li><p>A <code>URIQualifiedName</code> may now supply a prefix
            as well as a URI and local name.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2079">2079</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2227">2227</a> 3 October 2025]</i></p></li></ol></div><p>
                  [<a id="dt-namespace-binding" title="namespace binding">Definition</a>: A <b>namespace binding</b>
         is a pair comprising a namespace prefix (which is either an <code>xs:NCName</code> or empty),
         and a namespace URI.]
               </p><p>Element nodes have a property called <b>in-scope namespaces</b>. [<a id="dt-in-scope-namespaces" title="in-scope namespaces">Definition</a>: The <b>in-scope namespaces</b> property of an element node is a set of 
         <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace bindings</a>, each of which associates a namespace prefix with a URI.]
For a given element, one namespace binding may have an empty prefix; the URI of this namespace binding is 
referred to as the <a title="default in-scope namespace" class="termref" href="#dt-default-in-scope-namespace">default in-scope namespace</a> for the element.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In <a href="#xpath">[XPath 1.0]</a>, the in-scope namespaces of an element node are represented by a collection of <b>namespace nodes</b> arranged on a <b>namespace axis</b>, which is optional and deprecated in <a href="#xpath-40">[XPath 4.0]</a>. XQuery does not support the namespace axis and does not represent namespace bindings in the form of nodes.</p><p>However, where other specifications such as <a href="#xslt-xquery-serialization-40">[Serialization 4.0]</a> refer to namespace nodes, these nodes may be synthesized from the in-scope namespaces of 
            an element node by interpreting each <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> as a namespace node. An application that 
            needs to create a set of namespace nodes to represent these bindings for an element bound to 
            <code>$e</code> can do so using the following code.


</p><div class="exampleInner"><pre>
for key $k value $v in in-scope-namespaces($e)
return namespace {$k}{$v}</pre></div></div><p>
                  [<a id="dt-default-in-scope-namespace" title="default in-scope namespace">Definition</a>: The <b>default in-scope namespace</b>
         of an element node] is the namespace URI to which the empty prefix is bound in the element’s 
         <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a>. In the absence of an explicit binding for the empty prefix, the
         default in-scope namespace is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>.</p><p>
                  [<a id="dt-expanded-qname" title="expanded QName">Definition</a>: An <b>expanded QName</b> is a
      triple: its components are a prefix, a local name, and a
      namespace URI. In the case of a name in no namespace, the
      namespace URI and prefix are both absent. In the case of a name
      in the default namespace, the prefix is absent.] When
      comparing two expanded QNames, the prefixes are ignored: the
      local name parts must be equal under the Unicode codepoint
      collation (<a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#collations">5.3.1 Collations</a>), 
      and the namespace URI parts must either both be
      absent, or must be equal under the Unicode codepoint
      collation.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-datum">datum</a><sup><small>DM</small></sup> of 
            an <a title="atomic item" class="termref" href="#dt-atomic-item">atomic item</a> of type <code>xs:QName</code>
            is an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>. However, the
            term <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> is also used for
            the names of constructs such as functions, variables, and types
            that are not themselves atomic items.</p></div><p>In the XQuery 4.0
      grammar, QNames representing the names of
      elements, attributes, functions, variables, types, or other such
      constructs are written as instances of the grammatical
      production <a href="#doc-xquery40-EQName">EQName</a>.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#doc-xquery40-EQName-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-EQName-URIQualifiedName"/><code><a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-EQName-BracedURILiteral">BracedURILiteral</a>  (<a href="#prod-xquery40-NCName">NCName</a>  ":")?  <a href="#prod-xquery40-NCName">NCName</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-EQName-BracedURILiteral"/><code><a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a></code></td><td>::=</td><td><code>"Q"  "{"  (<a href="#prod-xquery40-PredefinedEntityRef">PredefinedEntityRef</a>  |  <a href="#prod-xquery40-CharRef">CharRef</a>  |  [^&amp;{}])*  "}"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody></table><p>The <a href="#doc-xquery40-EQName">EQName</a> production allows a QName to
      be written in one of four ways:
      </p><ul><li><p>local-name only (for example, <code>invoice</code>).</p><p>A name written in this form has no prefix, and the rules
        for determining the namespace depend on the context in which
        the name appears: the various rules used are summarized
        in <a href="#id-expanding-unprefixed-qnames"><b>2.1.5 Expanding Lexical QNames</b></a>.
                  This form is a <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>.</p></li><li><p>prefix plus local-name (for example, <code>my:invoice</code>).</p><p>In this case the prefix and local name of the QName are as
        written, and the namespace URI is inferred from the prefix by
        examining the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a> in the static context where
        the QName appears; the context must include a binding for the
        prefix. This form is a <a title="lexical QName" class="termref" href="#dt-qname">lexical
        QName</a>.</p></li><li><p>URI plus local-name (for example,
        <code>Q{http://example.com/ns}invoice</code>).</p><p>In this case the local name and namespace URI are as
        written, and the prefix is absent. This way of writing a QName
        is context-free, which makes it particularly suitable for use
        in  <span class="xquery">queries</span>
            
        that are generated by software. This
        form is a <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>.  
        If the <a href="#prod-xquery40-BracedURILiteral">
        BracedURILiteral</a> has no content (for example, <code>Q{}invoice</code>) 
        then the namespace URI of the QName is absent.</p></li><li><p>URI plus prefix plus local-name (for example,
        <code>Q{http://example.com/ns}xmp:invoice</code>).</p><p>In this case all three components of the expanded QName are
                  present. Although in most contexts the prefix will be ignored,
                  there may be cases where it is useful, for example if the QName
                  is cast to a string.</p><p>It is a static error [<a href="#ERRXPST0154" title="err:XPST0154">err:XPST0154</a>] 
                  if the prefix is present and the namespace URI
               is absent (for example <code>Q{}xmp:invoice</code>).</p></li></ul><p>
                  [<a id="dt-qname" title="lexical QName">Definition</a>: A
          <b>lexical QName</b> is a name that conforms to the syntax of the
          <a href="#prod-xquery40-QName">QName</a> production].
          </p><p>
	  The namespace URI value in a <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a> is whitespace normalized according
	  to the rules for the <code>xs:anyURI</code> type in
          <a href="https://www.w3.org/TR/xmlschema-2/#anyURI">
               
                  3.2.17 anyURI
            </a><sup><small>XS1-2</small></sup> or 
          <a href="https://www.w3.org/TR/xmlschema11-2/#anyURI">
               
                  3.3.17 anyURI
            </a><sup><small>XS11-2</small></sup>. 

          It is a <a title="static error" class="termref" href="#dt-static-error">static
          error</a>
                  [<a href="#ERRXQST0070" title="err:XQST0070">err:XQST0070</a>] if the
          namespace URI for an EQName is
          <code>http://www.w3.org/2000/xmlns/</code>.
          </p><p>Here are some examples of <a href="#doc-xquery40-EQName">EQName</a>s:</p><ul><li><p>
                        <code>pi</code> is a <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> without a namespace prefix.</p></li><li><p>
                        <code>math:pi</code> is a <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> with a namespace prefix.</p></li><li><p>
                        <code>Q{http://www.w3.org/2005/xpath-functions/math}pi</code> specifies the namespace URI using a  <a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>; it is not a  <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>.</p></li></ul><p>This document uses the following namespace prefixes to represent the namespace URIs 
         with which they are listed.</p><ul><li class="xquery"><p>
                        <code>xml</code>: <code>http://www.w3.org/XML/1998/namespace</code>
                     </p></li><li><p>
                        <code>xs</code>: <code>http://www.w3.org/2001/XMLSchema</code>
                     </p></li><li class="xquery"><p>
                        <code>xsi</code>: <code>http://www.w3.org/2001/XMLSchema-instance</code>
                     </p></li><li><p>
                        <code>fn</code>: <code>http://www.w3.org/2005/xpath-functions</code>
                     </p></li><li><p>
                        <code>array</code>: <code>http://www.w3.org/2005/xpath-functions/array</code>
                     </p></li><li><p>
                        <code>map</code>: <code>http://www.w3.org/2005/xpath-functions/map</code>
                     </p></li><li><p>
                        <code>math</code>: <code>http://www.w3.org/2005/xpath-functions/math</code>
                     </p></li><li><p>
                        <code>err</code>: <code>http://www.w3.org/2005/xqt-errors</code>
                  (see <a href="#id-identifying-errors"><b>2.4.2 Identifying and Reporting Errors</b></a>).</p></li><li class="xquery"><p>
                        <code>local</code>: <code>http://www.w3.org/2005/xquery-local-functions</code>
                  (see <a href="#FunctionDeclns"><b>5.18 Function Declarations</b></a>.)
            </p></li><li><p>
                        <code>output</code>: <code>http://www.w3.org/2010/xslt-xquery-serialization</code>
                     </p></li><li class="xquery"><p>
                        <code>xq</code>: <code>http://www.w3.org/2012/xquery</code>
                     </p></li></ul><p>In XQuery 4.0, the above namespace bindings are by default included
      in the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a> of the <a title="static context" class="termref" href="#dt-static-context">static context</a> 
      of every query module; however, these bindings can be overridden in the query prolog.</p><p>
                  [<a id="dt-URI" title="URI">Definition</a>: Within this specification, the term <b>URI</b> refers to a Universal Resource Identifier as defined in <a href="#RFC3986">[RFC3986]</a> and extended in <a href="#RFC3987">[RFC3987]</a> with the new name <b>IRI</b>.]
The term URI has been retained in preference to IRI to avoid introducing new names for concepts such as “Base URI” that are defined or referenced across the whole family of XML specifications.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In most contexts, processors are not required to raise errors if a URI is not lexically valid according to  <a href="#RFC3986">[RFC3986]</a> and  <a href="#RFC3987">[RFC3987]</a>. See <a href="#id-uri-literals"><b>2.5.5 URI Literals</b></a>
                     <span class="xquery">and <a href="#id-namespaces"><b>4.12.1.2 Namespace Declaration Attributes</b></a>
                     </span> for details.</p></div></div><div class="div3">
<h4><a id="id-expanding-unprefixed-qnames"/>2.1.5 <a href="#id-expanding-unprefixed-qnames" style="text-decoration: none">Expanding Lexical QNames</a></h4><p>When a <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> appearing in an XQuery 4.0 expression is expanded, the rules are as follows.</p><p>If the name contains a colon, then the prefix (the substring before the colon) is used to establish the 
               corresponding URI by reference to the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>
            in the <a title="static context" class="termref" href="#dt-static-context">static context</a>. If there
                  is no binding for the prefix in the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a> then
                  a static error is raised [<a href="#ERRXPST0081" title="err:XPST0081">err:XPST0081</a>].
            </p><p>If the <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> contains no colon (and therefore no prefix),
            the namespace URI part of the QName is inferred in one of a number of ways, depending on the syntactic context
            in which the name appears. The various rules are defined below, and are referred to throughout the specification.</p><ul><li><p>
                        [<a id="dt-no-namespace-rule" title="no-namespace rule">Definition</a>: When an unprefixed lexical QName
               is expanded using the <b>no-namespace rule</b>, it is interpreted as having an absent namespace URI.]
                     </p></li><li><p>
                        [<a id="dt-default-function-namespace-rule" title="default function namespace rule">Definition</a>: When 
                     an unprefixed lexical QName
                     is expanded using the <b>default function namespace rule</b>, 
                     the processor searches for a matching function definition as follows: 
                     first, if the static context includes a no-namespace function definition 
                     with the required local name and arity, then that function definition is used; 
                     otherwise, the name is expanded using the <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a> from 
                     the <a title="static context" class="termref" href="#dt-static-context">static context</a>.]
                     </p><div class="note"><p class="prefix"><b>Note:</b></p><p>The implication of this rule is that if there is a user-defined function in no namespace
                  with the same local name as a system-defined function in the <code>fn</code>
                     namespace, then a function call using the unprefixed function name invokes the user-defined
                     function in preference to the system-defined function.</p><p>It is generally advisable to avoid any danger of user confusion by keeping the names
                        of user-defined functions noticably distinct from the names of system-defined functions,
                        for example by using different naming conventions (for example, leading upper-case letters
                        leading underscores, or <code>camelCase</code>).</p><p>There may however be cases where a user-defined function deliberately has the same local name
                        as a system-defined function, but with modified semantics. For example a user might choose
                        to define a function <code>Q{}current-date()</code> that returns a date with no timezone:
                        this might be defined in XQuery as:</p><div class="exampleInner"><pre>declare function current-date() as xs:date {
   fn:current-date() =&gt; fn:adjust-date-to-timezone(())
}</pre></div></div></li><li><p>
                        [<a id="dt-default-type-namespace-rule" title="default type namespace rule">Definition</a>: When 
                  an unprefixed lexical QName
               is expanded using the <b>default type namespace rule</b>, it uses the 
                  <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>. If this is absent, the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>
                  is used. If the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> has the special value <code>##any</code>,
                  then the lexical QName refers to a name in the namespace <code>http://www.w3.org/2001/XMLSchema</code>.]
                     </p></li><li><p>
                        [<a id="dt-default-element-namespace-rule" title="default element namespace rule">Definition</a>: When 
                  an unprefixed lexical QName
               is expanded using the <b>default element namespace rule</b>, then it uses the 
                  <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>. If this is absent, or if it takes
                  the special value <code>##any</code>, then the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>
                  is used.]
                     </p></li><li class="xquery"><p>
                        [<a id="dt-constructed-element-namespace-rule" title="constructed element namespace rule">Definition</a>: 
                  When  an unprefixed lexical QName
               is expanded using the <b>constructed element namespace rule</b>, then it uses the namespace URI
                     that is bound to the empty (zero-length) prefix in the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a> of the
                     <a title="static context" class="termref" href="#dt-static-context">static context</a>. If there is no such <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a>
                  then it uses the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.]
                     </p></li><li class="xquery"><p>
                        [<a id="dt-default-annotation-namespace-rule" title="default annotation namespace rule">Definition</a>: 
                  When  an unprefixed lexical QName
               is expanded using the <b>annotation namespace rule</b>, then it uses the namespace URI
                     <code>http://www.w3.org/2012/xquery</code>.]
                     </p></li><li><p>
                        [<a id="dt-element-name-matching-rule" title="element name matching rule">Definition</a>: When 
                  an unprefixed lexical QName
               is expanded using the <b>element name matching rule</b> rule, then it uses the 
                  <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>. If this is absent, then 
                  it uses the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>. But if it takes the special value <code>##any</code>,
                  then the name is taken as matching any <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> with the corresponding local part,
                  regardless of namespace: that is, the  unprefixed name <code>local</code> is interpreted
                  as <code>*:local</code>.]
                     </p></li></ul></div></div><div class="div2">
<h3><a id="context"/>2.2 <a href="#context" style="text-decoration: none">Expression Context</a></h3><p>
               [<a id="dt-expression-context" title="expression context">Definition</a>: The <b>expression
		context</b> for a given expression consists of all
		the information that can affect the result of the
		expression.]
            </p><p>This information is organized into two categories
		called the <a title="static context" class="termref" href="#dt-static-context">static
		context</a> and the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic
		context</a>.</p><div class="div3">
<h4><a id="static_context"/>2.2.1 <a href="#static_context" style="text-decoration: none">Static Context</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-decimal-formats">⬇</a> <a href="#id-namespaces-and-qnames">⬆</a></p><ol><li><p>
                  The <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> can be set to the value <code>##any</code>,
                  allowing unprefixed names in axis steps to match elements with a given local name in any namespace.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/296">296</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1181">1181</a> 30 April 2024]</i></p></li><li><p>

                  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.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1343">1343</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1344">1344</a> 23 September 2024]</i></p></li><li><p>
                  The context value static type, which was there purely to assist in static typing, has been dropped.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1495">1495</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1496">1496</a> 29 October 2024]</i></p></li><li><p>
                  Named record types used in the signatures of built-in functions are now available as standard
                  in the static context.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/835">835</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1991">1991</a> 11 May 2025]</i></p></li></ol></div><p>
                  [<a id="dt-static-context" title="static context">Definition</a>: The <b>static context</b> of an expression is
		  the information that is available during static analysis of the expression, prior
		  to its evaluation.] This information can be used to decide whether the
		  expression contains a <a title="static error" class="termref" href="#dt-static-error">static error</a>. </p><p>The individual components of the <a title="static context" class="termref" href="#dt-static-context">static context</a> are described below.</p><p>In XQuery 4.0, the static context for an expression is largely defined
               in the query prolog of a module: see <a href="#id-query-prolog"><b>5 Modules and Prologs</b></a>. Declarations in the 
               prolog, such as variable declarations, function declarations, and decimal format declarations
               populate the static context for expressions appearing within the module. In some cases (but
               not all) these declarations may affect the static context for expressions that precede
               the relevant declaration. The static context can also be affected by declarations in other
               modules that are referenced using an <code>import module</code> declaration: see
               <a href="#id-module-import"><b>5.12 Module Import</b></a>.</p><p>In addition, some expressions modify the static context for their subexpressions.
               The most obvious example is <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a>
               (a <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a> declares bindings of local variables that are available
               for reference within subsequent clauses of the expression). A further example is the
               <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>: an element constructor may contain namespace declarations
               such as <code>xmlns:p="some_uri"</code> which cause additional namespace prefixes to be available
               within the content of the element constructor.</p><p>Appendix <a href="#id-xq-static-context-components"><b>B.1 Static Context Components</b></a> gives an overview
               of the components in the static context and the way they are initialized.</p><p>Some components of the static context, but not all, also affect the dynamic semantics
            of expressions. For example, casting of a string such as <code>"xbrl:xbrl"</code> to
            an <code>xs:QName</code> might expand the prefix <code>xbrl</code> to the namespace
            URI <code>http://www.xbrl.org/2003/instance</code> using the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>
               from the static context;
            since the input string <code>"xbrl:xbrl"</code> is in general not known until execution time (it
            might be read from a source document), this means that the values of the 
            <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a> must be available at execution time.</p><ul><li><p>
                        [<a id="dt-xpath-compat-mode" title="XPath 1.0 compatibility     mode">Definition</a>: 
                           <b>XPath 1.0 compatibility
			 mode.</b>
                           <span class="xquery">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
			 <code>false</code>.
                         </span>
                        ]
                     </p></li><li><p>
                        [<a id="dt-static-namespaces" title="statically known namespaces">Definition</a>: 
                           <b>Statically known namespaces.</b> 
        This is a mapping from prefix to namespace URI that defines all the namespaces 
        that are known during static processing of a given expression.]
                     </p><p>The URI value is whitespace normalized according to the rules for the
                     <code>xs:anyURI</code> type in <a href="https://www.w3.org/TR/xmlschema-2/#anyURI">
               
                  3.2.17 anyURI
            </a><sup><small>XS1-2</small></sup> or 
                     <a href="https://www.w3.org/TR/xmlschema11-2/#anyURI">
               
                  3.3.17 anyURI
            </a><sup><small>XS11-2</small></sup>.</p><p>The statically known namespaces may include a binding for the zero-length prefix:
                  however, this is used only by the <a title="constructed element namespace rule" class="termref" href="#dt-constructed-element-namespace-rule">constructed element namespace rule</a>.</p><p>Note the difference between <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a>, which is a dynamic property of an element node, and <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>, which is a static property of an expression.</p><p>Some namespaces are predeclared (see <a href="#id-namespaces-and-qnames"><b>2.1.4 Namespaces and QNames</b></a>); 
                     additional  namespaces can be added to the statically known namespaces by <a title="namespace declaration" class="termref" href="#dt-namespace-declaration">namespace declarations</a>,
<a title="schema import" class="termref" href="#dt-schema-import">schema imports</a>, or  <a title="module import" class="termref" href="#dt-module-import">module imports</a> in a <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a>, by  a <a title="module declaration" class="termref" href="#dt-module-declaration">module declaration</a>, 
and by <a title="namespace declaration attribute" class="termref" href="#dt-namespace-decl-attr">namespace declaration attributes</a> in <a title="direct element constructor" class="termref" href="#dt-direct-elem-const">direct element constructors</a>.</p></li><li><p>
                        [<a id="dt-default-namespace-elements-and-types" title="default namespace for elements and types">Definition</a>: 
                           <b>Default namespace for elements and types.</b> This is either a
				namespace URI, or the special value <code>"##any"</code>, or <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>. This indicates how unprefixed QNames are interpreted when
                        they appear in a position  where an element name or type name is expected.]
                     </p><ul><li><p>If the value is set to a namespace URI, 
                        this namespace is used for any such unprefixed QName. The URI value is
               whitespace-normalized according to the rules for the <code>xs:anyURI</code> type in <a href="https://www.w3.org/TR/xmlschema-2/#anyURI">
               
                  3.2.17 anyURI
            </a><sup><small>XS1-2</small></sup> or <a href="https://www.w3.org/TR/xmlschema11-2/#anyURI">
               
                  3.3.17 anyURI
            </a><sup><small>XS11-2</small></sup>.</p></li><li><p>The special value <code>"##any"</code> indicates that:</p><ul><li><p>When an unprefixed QName is used as a <a title="name test" class="termref" href="#dt-name-test">name test</a> for selecting
                              named elements in an <a title="axis step" class="termref" href="#dt-axis-step">axis step</a>, the <a title="name test" class="termref" href="#dt-name-test">name test</a>
                           will match an element having the specified local name, in any namespace or none.</p></li><li><p>When an unprefixed QName is used in a context where a type name is expected
                           (but not as a function name), the default namespace is the <code>xs</code>
                           namespace, <code>http://www.w3.org/2001/XMLSchema</code>.</p></li><li><p>In any other context, an unprefixed QName represents a name in no namespace.</p></li></ul></li><li><p>If the value is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>,
                        an unprefixed QName representing an element or type
                        name is interpreted as being in no namespace.</p></li></ul></li><li><p>
                        [<a id="dt-default-function-namespace" title="default function namespace">Definition</a>: 
                           <b>Default function namespace.</b> This determines how unprefixed lexical QNames
                        appearing in a <a title="static function call" class="termref" href="#dt-static-function-call">static function call</a> or a
                        <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a> are interpreted.]
                     </p><p>There are three possible settings:</p><ol class="enumar"><li><p>The property may be <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>. In this case
                     an unprefixed <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> appearing in a <a title="static function call" class="termref" href="#dt-static-function-call">static function call</a> 
                      or in a <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a>
                     is resolved first by searching the static context for a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> in no namespace,
                     having a matching local name and <a title="arity range" class="termref" href="#dt-arity-range">arity range</a>; if that fails to find a matching function
                     definition, a second search is conducted looking for a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
                     in the namespace <code>http://www.w3.org/2005/xpath-functions</code>, again
                     having a matching local name and <a title="arity range" class="termref" href="#dt-arity-range">arity range</a>.</p></li><li><p>The property may be set to the empty URI, <code>""</code>. In this case
                     an unprefixed <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> appearing in a 
                        <a title="static function call" class="termref" href="#dt-static-function-call">static function call</a> or a <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a>
                     is resolved by searching the static context for a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> in no namespace,
                     having a matching local name and <a title="arity range" class="termref" href="#dt-arity-range">arity range</a>.</p></li><li><p>The property may be set to an explicit URI, say <var>NS</var>. In this case
                     an unprefixed <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> appearing in a 
                        <a title="static function call" class="termref" href="#dt-static-function-call">static function call</a> or a <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a>
                     is resolved by searching the static context for a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> in namespace <var>NS</var>,
                     having a matching local name and <a title="arity range" class="termref" href="#dt-arity-range">arity range</a>.</p></li></ol><p>The URI value is whitespace-normalized according
                     to the rules for the <code>xs:anyURI</code> type in <a href="https://www.w3.org/TR/xmlschema-2/#anyURI">
               
                  3.2.17 anyURI
            </a><sup><small>XS1-2</small></sup> or <a href="https://www.w3.org/TR/xmlschema11-2/#anyURI">
               
                  3.3.17 anyURI
            </a><sup><small>XS11-2</small></sup>
                     </p><p>Host languages may use a more complex algorithm for resolving function names. For
                     example XSLT resolves ambiguities using the concept of import precedence.
                  </p><p>
                     In XQuery, a default function namespace can be
                     declared in the prolog in a <b>default function namespace declaration</b>
                     (see <a href="#id-default-namespace"><b>5.14 Default Namespace Declaration</b></a>); in the absence of such a declaration, the namespace
                     <code>http://www.w3.org/2005/xpath-functions</code> is used.</p></li><li><p>
                        [<a id="dt-issd" title="in-scope schema definitions">Definition</a>: 
                           <b>In-scope schema
			 definitions</b> is a generic term
			 for all the element declarations, attribute declarations, and schema type
			 definitions that are in scope during
			 static analysis of an expression.] It includes the
			 following three
			 parts:</p><ul><li><p>
                              [<a id="dt-is-types" title="in-scope schema type">Definition</a>: 
                                 <b>In-scope schema types.</b> Each schema type
			        definition is identified either by an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded
			        QName</a> (for a <b>named type</b>)
			        or by an <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> type
			        identifier (for an <b>anonymous
			        type</b>). The in-scope schema types include the predefined schema types described in <a href="#id-predefined-types"><b>3.5 Schema Types</b></a>.

                                <span class="xquery">If the
                                <a title="schema aware feature" class="termref" href="#dt-schema-aware-feature">Schema Aware Feature</a>
                                is supported, in-scope schema types
                                also include all type definitions
                                found in imported schemas.</span>
                              ]
                           </p></li><li><p>
                              [<a id="dt-is-elems" title="in-scope element declarations">Definition</a>: 
                                 <b>In-scope element declarations.</b> Each element
declaration is identified either by an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> (for a top-level element
declaration) or by an <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> element identifier (for a
local element declaration). <span class="xquery"> If the
<a title="schema aware feature" class="termref" href="#dt-schema-aware-feature">Schema Aware Feature</a>
is supported, in-scope element declarations include all element
declarations found in imported schemas. </span>
                              ] An element
declaration includes information about the element’s <a title="substitution group" class="termref" href="#dt-substitution-group">substitution group</a> affiliation.</p><p>
                              [<a id="dt-substitution-group" title="substitution group">Definition</a>: 
                                 <b>Substitution groups</b> are defined in <a href="https://www.w3.org/TR/xmlschema-1/#Element_Equivalence_Class">
                  
                     2.2.2.2 Element Substitution Group
               </a><sup><small>XS1-1</small></sup> and 
<a href="https://www.w3.org/TR/xmlschema11-1/#Element_Equivalence_Class">
                  
                     2.2.2.2 Element Substitution Group
               </a><sup><small>XS11-1</small></sup>. Informally, the substitution group headed by a given element (called the <b>head element</b>) consists of  the set of elements that can be substituted for the head element without affecting the outcome of schema validation.]
                           </p></li><li><p>
                              [<a id="dt-is-attrs" title="in-scope attribute declarations">Definition</a>: 
                                 <b>In-scope attribute
declarations.</b> Each attribute declaration is identified either
by an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> (for a top-level attribute declaration) or by an
<a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> attribute identifier (for a local attribute
declaration).  <span class="xquery">If the
<a title="schema aware feature" class="termref" href="#dt-schema-aware-feature">Schema Aware Feature</a>
is supported, in-scope attribute declarations include all attribute
declarations found in imported
schemas.</span>
                              ]
                           </p></li></ul></li><li><p>
                        [<a id="dt-in-scope-variables" title="in-scope variables">Definition</a>: 
                           <b>In-scope variables.</b> 
                           This is a mapping from <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a> to sequence types. It defines the
                           set of variables that are available for reference within an
                           expression. The <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> is the name of the variable, and the type is the
                           <a title="static type" class="termref" href="#dt-static-type">static type</a> of the
                           variable.]
                     </p><p>
                        <span class="xquery">Variable declarations in a <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a> are added to <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a>.</span>
An expression that binds a variable extends the <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a>, within the scope of the variable, with the variable and its type. 
Within the body of an
<a title="inline function expression" class="termref" href="#dt-inline-func">inline function expression</a>
                        <span class="xquery"> or <a title="user-defined function" class="termref" href="#dt-udf">user-defined function</a>
                        </span>, the
<a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a> are extended
by the names and types of the <b>function
parameters</b>.</p><p>The static type of a variable may either be declared in a query or
inferred by static type inference as discussed in  <a href="#id-static-analysis"><b>2.3.3.1 Static Analysis Phase</b></a>.</p></li><li><p>
                        [<a id="dt-in-scope-named-item-types" title="in-scope named item types">Definition</a>: 
                           <b>In-scope named item types.</b> This is a mapping from 
                        <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a> to 
                        <a title="named item type" class="termref" href="#dt-named-item-type">named item types</a>.]
                     </p><p>
                        [<a id="dt-named-item-type" title="named item type">Definition</a>: A <b>named item type</b>
                      is an <code>ItemType</code> identified by an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>.]
                     </p><p>Named item types serve two purposes:</p><ul><li><p>They allow frequently used item types, especially complex item types such as
                        record types, to be given simple names, to avoid repeating the definition 
                        every time it is used.</p></li><li><p>They allow the definition of recursive types, which are useful for
                     describing recursive data structures such as lists and trees. For details see
                     <a href="#id-recursive-record-tests"><b>3.2.8.3.1 Recursive Record Types</b></a>. </p></li></ul><p>Certain named item types (typically item types used in the signatures of built-in functions)
                  are always available in the static context. These are defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#id-built-in-named-record-types">C Built-in named record types</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In XQuery, named item types can be declared in the Query Prolog.</p></div></li><li><p>
                        [<a id="dt-statically-known-function-definitions" title="statically known function definitions">Definition</a>: 
                           <b>Statically known function definitions.</b> This is a set of 
                           <a title="function definition" class="termref" href="#dt-function-definition">function definitions</a>.]
                     </p><p>Function definitions are described in <a href="#id-function-definitions"><b>2.2.1.1 Function Definitions</b></a>.</p></li><li><p>
                        [<a id="dt-static-collations" title="statically known collations">Definition</a>: 
                           <b>Statically known collations.</b> This is an <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>
        mapping from URI to collation. It defines the names of the collations that are available for
				use in processing <span class="xquery">queries and</span> expressions.]
                        [<a id="dt-collation" title="collation">Definition</a>: A <b>collation</b> 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 <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#string-compare">5.3 Comparison of strings</a>.]
                     </p></li><li class="xquery"><p>
                        [<a id="dt-construction-mode" title="construction mode">Definition</a>: 
                           <b>Construction mode.</b> The
			 construction mode governs the behavior of element and document node constructors. If construction mode is <code>preserve</code>, the type of a constructed element node is <code>xs:anyType</code>, and all attribute and element nodes copied during node construction    retain their original types. If construction mode is <code>strip</code>, the type of a constructed element node is <code>xs:untyped</code>; all element nodes copied during node construction receive the type <code>xs:untyped</code>, and all attribute nodes copied during node construction receive the type <code>xs:untypedAtomic</code>.]
                     </p></li><li class="xquery"><p>
                        [<a id="dt-default-empty-order" title="default order for empty sequences">Definition</a>: 
                           <b>Default order for empty sequences.</b> This component controls the processing of empty sequences and <code>NaN</code> values as ordering keys in an <code>order by</code> clause in a FLWOR expression, as described in <a href="#id-order-by-clause"><b>4.13.9 Order By Clause</b></a>.]  Its value may be <code>greatest</code> or <code>least</code>.</p></li><li class="xquery"><p>
                        [<a id="dt-boundary-space-policy" title="boundary-space policy">Definition</a>: 
                           <b>Boundary-space
			 policy.</b> This component controls the processing of <a title="boundary whitespace" class="termref" href="#dt-boundary-whitespace">boundary whitespace</a>
			 by <a title="direct element constructor" class="termref" href="#dt-direct-elem-const">direct element constructors</a>, as described in <a href="#id-whitespace"><b>4.12.1.4 Boundary Whitespace</b></a>.] Its value may be <code>preserve</code> or <code>strip</code>.</p></li><li class="xquery"><p>
                        [<a id="dt-copy-namespaces-mode" title="copy-namespaces mode">Definition</a>: 
                           <b>Copy-namespaces mode.</b> This component controls the <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a>
                        property that
is assigned when an existing element node is copied by an element
constructor, as described in <a href="#id-element-constructor"><b>4.12.1 Direct Element Constructors</b></a>. Its value consists of two parts: <code>preserve</code> or <code>no-preserve</code>, and <code>inherit</code> or <code>no-inherit</code>.]
                     </p></li><li><p>
                        [<a id="dt-static-base-uri" title="Static Base URI">Definition</a>: 
                           <b>Static Base URI.</b>
        This is an absolute URI, used to resolve relative URIs during static analysis.
                     ]
                     For example, it is used to resolve module location URIs in XQuery, and 
                     the URIs in <code>xsl:import</code> and <code>xsl:include</code> in XSLT.
                     <span class="xquery">
        All expressions within a module have the same static base URI.
        The Static Base URI can be set using a <a title="base URI declaration" class="termref" href="#dt-base-uri-decl">base URI declaration</a>.
      </span>
                     </p><p>
                        Relative URI references are 
      resolved as described in <a href="#id-resolve-relative-uri"><b>2.5.6 Resolving a Relative URI Reference</b></a>.</p><p>At execution time,
                  relative URIs supplied to functions such as <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-doc"><code>fn:doc</code></a>
                  are resolved against the <a title="Executable Base URI" class="termref" href="#dt-executable-base-uri">Executable Base URI</a>,
                  which may or may not be the same as the Static Base URI.</p></li><li><p>
                        [<a id="dt-static-decimal-formats" title="statically known decimal formats">Definition</a>: 
                           <b>Statically known decimal
		      formats.</b> 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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-number"><code>fn:format-number</code></a> function.]
                     </p><p>Decimal formats are described in <a href="#id-decimal-formats"><b>2.2.1.2 Decimal Formats</b></a>.</p></li></ul><div class="div4">
<h5><a id="id-function-definitions"/>2.2.1.1 <a href="#id-function-definitions" style="text-decoration: none">Function Definitions</a></h5><p>
                     [<a id="dt-function-definition" title="function definition">Definition</a>: A <b>function definition</b>
                  contains information used to evaluate a static function call, including the name, parameters,
                  and return type of the function.]
                  </p><p>The properties of a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> include:</p><ul><li><p>The function name, which is an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>.</p></li><li><p>Parameter definitions, specifically:</p><ul><li><p>A (possibly empty) list of required parameters, each having:</p><ul><li><p>a parameter name (an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>)</p></li><li><p>a required type (a <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>)</p></li></ul></li><li><p>A (possibly empty) list of optional parameters, each having:</p><ul><li><p>a parameter name (an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>)</p></li><li><p>a required type (a <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>)</p></li><li><p>a default value expression (an <b>expression</b>: see <a href="#id-expressions"><b>4 Expressions</b></a>)</p></li></ul></li></ul><p>The names of the parameters must be distinct.</p><p>
                           [<a id="dt-arity-range" title="arity range">Definition</a>: A <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> has an <b>arity range</b>,
                        which is a range of consecutive non-negative integers. If the function definition has <var>M</var> required parameters
                        and <var>N</var> optional parameters, then its arity range is from <var>M</var> to <var>M</var>+<var>N</var>
                        inclusive.]
                        </p><p>The static context may contain several <a title="function definition" class="termref" href="#dt-function-definition">function definitions</a> with the
                        same name, but the <a title="arity range" class="termref" href="#dt-arity-range">arity ranges</a> of two such function definitions must not 
                        overlap. For example, if two function definitions <var>A</var> and <var>B</var> have the same function name, then:</p><ul><li><p>It is acceptable for <var>A</var> to have two required parameters and no optional
                           parameters, while <var>B</var> has three required parameters and one optional
                           parameter.</p></li><li><p>It is not acceptable for <var>A</var> to have one required parameter while <var>B</var>
                           has three optional parameters.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>Implementations must ensure that no two <a title="function definition" class="termref" href="#dt-function-definition">function definitions</a> 
                        have the same <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> and overlapping
                        arity ranges (even if the signatures are consistent).</p><p>XQuery and XSLT enforce this rule by defining a static error if the rule is violated; but further constraints
                           may be needed if an API allows external functions to be added to the static context.</p></div></li><li><p>A return type (a <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>)</p></li><li><p>The function category, which is one of application, system, or external:</p><ul><li><p>
                                 [<a id="dt-application-function" title="application function">Definition</a>: 
                                    <b>Application functions</b> 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.]
                           The most common application functions are functions written by users in XQuery or XSLT.
                        </p></li><li><p>
                                 [<a id="dt-system-function" title="system function">Definition</a>: 
                                    <b>System functions</b> include the functions defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>, functions defined by the specifications 
                           of a host language, <a title="constructor function" class="termref" href="#dt-constructor-function">constructor functions</a> 
                           for atomic types, and any additional functions provided
                           by the implementation. System functions are sometimes called built-in
                           functions.]
                              </p><p>The behavior of system functions follows the rules given for the individual
                              function in this family of specifications, or in the specification of the
                              particular processor implementation. A system function may have behavior that depends on the
                              static or dynamic context of the caller (for example, comparing strings
                              using the default collation from the <span>dynamic</span> context of the caller). Such
                              functions are said to be <a title="context dependent" class="termref" href="#dt-context-dependent">context dependent</a>.</p></li><li><p>
                                 [<a id="dt-external-function" title="external function">Definition</a>: 
                                    <b>External functions</b> 
                           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 
                           <a href="https://www.w3.org/TR/xslt-30/#extension-functions">
            
               24.1 Extension Functions
         </a><sup><small>XT30</small></sup>. ]
                              </p><p>For example, an implementation might provide a mechanism allowing
                              external functions to be written in a language such as Java or Python.
                              The way in which argument and return values are converted between
                              the XDM type system and the type system of the external language is
                              implementation-defined.
                           </p></li></ul><p>
                           [<a id="dt-context-dependent" title="context dependent">Definition</a>: A 
                        <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> is said to be <b>context dependent</b>
                        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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-name"><code>fn:name#0</code></a> is context-dependent
                        while <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-name"><code>fn:name#1</code></a> is context-independent.]
                        </p><div class="note"><p class="prefix"><b>Note:</b></p><p>Some system functions, such as <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-position"><code>fn:position</code></a>, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-last"><code>fn:last</code></a>,
                        and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-static-base-uri"><code>fn:static-base-uri</code></a>, exist for the sole purpose of providing information
                        about the static or dynamic context of their caller.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>
                              <a title="application function" class="termref" href="#dt-application-function">Application functions</a> 
                        are context dependent only to the extent that they define optional parameters with default
                        values that are context dependent.</p></div></li><li><p>A (possibly empty) set of <b>function annotations</b>
                        </p><p>In XQuery, function annotations are described in <a href="#id-annotations"><b>5.15 Annotations</b></a>.</p></li><li><p>A body. The function 
                     body contains the logic that enables the function
                     result to be computed from the supplied arguments and information in the static and dynamic context.</p></li></ul><p>The <a title="function definition" class="termref" href="#dt-function-definition">function definitions</a> 
                  present in the static context are available for reference from a 
                  <a title="static function call" class="termref" href="#dt-static-function-call">static function call</a>,
                  or from a 
                  <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a>.
                  
               </p></div><div class="div4">
<h5><a id="id-decimal-formats"/>2.2.1.2 <a href="#id-decimal-formats" style="text-decoration: none">Decimal Formats</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#eval_context">⬇</a> <a href="#static_context">⬆</a></p><ol><li><p>
                           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.
                        <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1048">1048</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1250">1250</a> 3 June 2024]</i></p></li></ol></div><p>Each decimal format defines a set of properties, which control the interpretation of characters
                        in the picture string supplied to the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-number"><code>fn:format-number</code></a>
                        function, and also specify characters to be used in the result
                        of formatting the number.</p><p>Each property potentially has two parts: a marker character <var>M</var> used
                     in the picture string to mark an insertion position, and a rendition string <var>R</var>
                     to indicate how the relevant property is to be rendered in the output of the 
                     <code>fn:format-number</code> function. In the list below properties are annotated
                     with <em>(<var>M</var>)</em>, <em>(<var>R</var>)</em>, or 
                     <em>(<var>M</var>, <var>R</var>)</em> to indicate whether the property includes a
                     marker character, a rendition string, or both.</p><p>In XQuery and XSLT declarations
                     defining the values of properties, a property where the marker character and the
                     rendition differ is indicated using the syntax <code>
                        <var>M</var>:<var>R</var>
                     </code>. For
                     example the <code>percent</code> property may be expressed as <code>%:pc</code>
                     to indicate that the character <code>%</code> will be used in the picture string,
                     and the string <code>pc</code> will be used in the function output.
                     In this example, the value <code>0.10</code>, formatted with the picture string 
                      <code>#0%</code>, results in the output <code>10pc</code>
                  </p><ul><li><p>
                           [<a id="id-static-decimal-format-decimal-separator" title="decimal-separator">Definition</a>: 
                              <b>decimal-separator</b>
                              <em>(<var>M</var>, <var>R</var>)</em> 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 <span class="unicode-codepoint">U+002E</span> (<span class="unicode-name">FULL STOP, PERIOD</span>, <code>.</code>) .]
                        </p></li><li><p>
                           [<a id="id-static-decimal-format-exponent-separator" title="exponent-separator">Definition</a>: 
                              <b>exponent-separator</b>
                              <em>(<var>M</var>, <var>R</var>)</em> is
                                 used to separate the mantissa from the exponent in
                                 scientific notation. The default value 
                                 for both the marker and the rendition is <span class="unicode-codepoint">U+0065</span> (<span class="unicode-name">LATIN SMALL LETTER E</span>, <code>e</code>) .]
                        </p></li><li><p>
                           [<a id="id-static-decimal-format-grouping-separator" title="grouping-separator">Definition</a>: 
                              <b>grouping-separator</b>
                              <em>(<var>M</var>, <var>R</var>)</em> is used to 
                                 separate groups of digits (for example as a thousands separator).
                                 The default value for both the marker and the rendition is <span class="unicode-codepoint">U+002C</span> (<span class="unicode-name">COMMA</span>, <code>,</code>) .]
                        </p></li><li><p>
                           [<a id="id-static-decimal-format-percent" title="percent">Definition</a>: 
                              <b>percent</b>
                              <em>(<var>M</var>, <var>R</var>)</em> 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 <span class="unicode-codepoint">U+0025</span> (<span class="unicode-name">PERCENT SIGN</span>, <code>%</code>) .]
                        </p></li><li><p>
                           [<a id="id-static-decimal-format-per-mille" title="per-mille">Definition</a>: 
                              <b>per-mille</b>
                              <em>(<var>M</var>, <var>R</var>)</em> 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 <span class="unicode-codepoint">U+2030</span> (<span class="unicode-name">PER MILLE SIGN</span>, <code>‰</code>) .]
                        </p></li><li><p>
                           [<a id="id-static-decimal-format-zero-digit" title="zero-digit">Definition</a>: 
                              <b>zero-digit</b>
                              <em>(<var>M</var>)</em>
                                 is the character used in the picture string to represent the digit zero; the default
                                 value is <span class="unicode-codepoint">U+0030</span> (<span class="unicode-name">DIGIT ZERO</span>, <code>0</code>) . 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.]
                        </p></li><li><p>
                           [<a id="id-static-decimal-format-digit" title="digit">Definition</a>: 
                              <b>digit</b>
                              <em>(<var>M</var>)</em>
                                 is a character used in the picture string to represent an optional digit; 
                                 the default value is <span class="unicode-codepoint">U+0023</span> (<span class="unicode-name">NUMBER SIGN</span>, <code>#</code>) .]
                        </p></li><li><p>
                           [<a id="id-static-decimal-format-pattern-separator" title="pattern-separator">Definition</a>: 
                              <b>pattern-separator</b>
                              <em>(<var>M</var>)</em> is a character used
                                 to separate positive and negative sub-pictures
                                 in a picture string; the default value is <span class="unicode-codepoint">U+003B</span> (<span class="unicode-name">SEMICOLON</span>, <code>;</code>) .]
                        </p></li><li><p>
                           [<a id="id-static-decimal-format-infinity" title="infinity">Definition</a>: 
                              <b>infinity</b>
                              <em>(<var>R</var>)</em>
                                 is the string used to represent the double value infinity (<code>INF</code>); the
                                 default value is the string <code>"Infinity"</code>
                           ]
                        </p></li><li><p>
                           [<a id="id-static-decimal-format-NaN" title="NaN">Definition</a>: 
                              <b>NaN</b>
                              <em>(<var>R</var>)</em>
                                 is the string used to
                                 represent the double value <code>NaN</code> (not a number); the default value is the string <code>"NaN"</code>
                           ]
                        </p></li><li><p>
                           [<a id="id-static-decimal-format-minus-sign" title="minus-sign">Definition</a>: 
                              <b>minus-sign</b>
                              <em>(<var>R</var>)</em> is the string used to mark negative numbers; the
                                 default value is <span class="unicode-codepoint">U+002D</span> (<span class="unicode-name">HYPHEN-MINUS</span>, <code>-</code>) .]
                        </p></li></ul></div></div><div class="div3">
<h4><a id="eval_context"/>2.2.2 <a href="#eval_context" style="text-decoration: none">Dynamic Context</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-processing-model">⬇</a> <a href="#id-decimal-formats">⬆</a></p><ol><li><p>
                  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.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/129">129</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/368">368</a> 14 September 2023]</i></p></li><li><p>
                  The rules regarding the <code>document-uri</code> property of nodes returned by the
                  <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collection"><code>fn:collection</code></a> function have been relaxed.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1161">1161</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1265">1265</a> 11 June 2024]</i></p></li></ol></div><p>
                  [<a id="dt-dynamic-context" title="dynamic context">Definition</a>: The <b>dynamic
context</b> 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 <a title="static context" class="termref" href="#dt-static-context">static context</a>.] If
evaluation of an expression relies on some part of the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> that 
is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>, a <a title="type error" class="termref" href="#dt-type-error">type error</a> 
               is raised [<a href="#ERRXPDY0002" title="err:XPDY0002">err:XPDY0002</a>].</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In previous versions of the specification, this was classified as a
            <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>. The change allows the error to be raised during
            static analysis when possible; for example a function written as
            <code>fn($x) { @code }</code> can now be reported as an error whether or not
            the function is actually evaluated. The actual error code remains unchanged
            for backwards compatibility reasons.</p><p>There are other cases where static detection of the error is not possible.</p></div><p>The individual
components of the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> are described below.</p><p>In general, the dynamic context for the outermost expression is supplied externally,
               often by some kind of application programming interface (API) allowing XQuery 4.0
               expressions to be invoked from a host language. Application Programming Interfaces
               are outside the scope of this specification. <span class="xquery">In XQuery 4.0,
               some aspects of the dynamic context (for example, initial values of variables)
               are defined within the query prolog.</span> The dynamic context for inner subexpressions
               may be set by their containing expressions: for example in a mapping expression 
               <code>
                     <var>E<sub>1</sub></var>!<var>E<sub>2</sub></var>
                  </code>,
               the value of the <a title="focus" class="termref" href="#dt-focus">focus</a> (part of the dynamic context) for evaluation
               of <var>E<sub>2</sub></var> is defined by the evaluation of <var>E<sub>1</sub></var>.</p><p>Some aspects of the dynamic context are outside the direct control of the query author;
               they are defined by the implementation, which may or may not allow them to be configured by users.
               An example is <a title="available documents" class="termref" href="#dt-available-docs">available documents</a>, which is an abstraction for the set of XML
               documents that can be retrieved by URI from within an expression. In some environments this may be
               the entire contents of the web; in others it may be constrained to documents that satisfy
               particular security constraints; and in some environments the set of available documents
               might even be empty. These components of the dynamic context are generally treated as being constant for
               the duration of the execution.</p><p>
                  <span class="xquery">Rules governing the initialization and alteration of  these components can be found in  <a href="#id-xq-evaluation-context-components"><b>B.2 Dynamic Context Components</b></a>.</span>
               </p><p>The components of the 
           <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> are listed below.</p><p>
                  [<a id="dt-focus" title="focus">Definition</a>: The first three components of
the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a>
(context value, context position, and context size) are called the
<b>focus</b> of the expression. ] The focus enables the
processor to keep track of which items are being processed by the
expression.

<span class="xquery">If any component in the focus is defined, all components of the focus are defined.</span>
               </p><p>
                  [<a id="dt-fixed-focus" title="fixed focus">Definition</a>: A <b>fixed focus</b> 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.]
               </p><p>
                  [<a id="dt-singleton-focus" title="singleton focus">Definition</a>: A <b>singleton focus</b> is a <a title="fixed focus" class="termref" href="#dt-fixed-focus">fixed focus</a> in which the
                  <a title="context value" class="termref" href="#dt-context-value">context value</a> is a <a title="singleton" class="termref" href="#dt-singleton">singleton</a> item.].
               With a singleton focus, the context value is a single item, the context position is 1, and the context size is 1.
               </p><p>Certain language constructs, notably the <a title="path expression" class="termref" href="#dt-path-expression">path operator</a>
                  <code>
                     <var>E<sub>1</sub></var>/<var>E<sub>2</sub></var>
                  </code>, the <a href="#doc-xquery40-SimpleMapExpr">simple map operator</a>
                  <code>
                     <var>E<sub>1</sub></var>!<var>E<sub>2</sub></var>
                  </code>, and the <a title="" class="termref" href="#dt-predicate">predicate</a>
                  <code>
                     <var>E<sub>1</sub></var>[<var>E<sub>2</sub></var>]</code>, create a new focus
for the evaluation of a sub-expression. In these constructs, <var>E<sub>2</sub></var> is evaluated once for each item in the
sequence that results from evaluating <var>E<sub>1</sub></var>. Each time <var>E<sub>2</sub></var> is evaluated, it is evaluated with a
different focus. The focus for evaluating <var>E<sub>2</sub></var> is referred to below as the <b>inner
focus</b>, while the focus for evaluating <var>E<sub>1</sub></var> is referred to as the <b>outer
focus</b>. The inner focus is used only for the evaluation of <var>E<sub>2</sub></var>. Evaluation of <var>E<sub>1</sub></var> continues with its original focus unchanged.</p><ul><li><p>
                        [<a id="dt-context-value" title="context value">Definition</a>: The <b>context value</b>
is the <a title="value" class="termref" href="#dt-value">value</a> currently being processed.]
                     In many cases (but not always), the context value will be a single item.
                     [<a id="dt-context-node" title="context node">Definition</a>: When the context value is a single item, it can also be referred
                        to as the <b>context item</b>; when it is a single node,
it can also be referred to as the <b>context
node</b>.] The context value is returned by an expression
consisting of a single dot (<code>.</code>). When an expression <code>
                           <var>E<sub>1</sub></var>/<var>E<sub>2</sub></var>
                        </code> or <code>
                           <var>E<sub>1</sub></var>[<var>E<sub>2</sub></var>]</code> is evaluated, each item in the
sequence obtained by evaluating <code>
                           <var>E<sub>1</sub></var>
                        </code>
becomes the context value in the inner focus for an evaluation of <var>E<sub>2</sub></var>. </p><p>
                        [<a id="dt-initial-context-value" title="initial context value">Definition</a>: 
    
    
      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 <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>,
      it is referred to as the <b>initial context value</b>.
    
  ]
                     </p></li><li><p>
                        [<a id="dt-context-position" title="context position">Definition</a>: The <b>context
position</b> is the position of the context value within the
series of values currently being processed.] It changes whenever the context value
changes. When the focus is defined, the value of the context position is an integer greater than zero. The context
position is returned by the expression <code>fn:position()</code>. When an expression <code>
                           <var>E<sub>1</sub></var>/<var>E<sub>2</sub></var>
                        </code> or <code>
                           <var>E<sub>1</sub></var>[<var>E<sub>2</sub></var>]</code> is evaluated, the context position in
the inner focus for an evaluation of <code>E2</code>
is the position of the context value in the sequence obtained by
evaluating <var>E<sub>1</sub></var>. The position of the
first item in a sequence is always 1 (one). The context position is
always less than or equal to the context size.</p></li><li><p>
                        [<a id="dt-context-size" title="context size">Definition</a>: The <b>context
size</b> is the number of values in the series of values currently
being processed.] Its value is always an
integer greater than zero. The context size is returned by the
expression <code>fn:last()</code>. When an expression
<code>
                           <var>E<sub>1</sub></var>/<var>E<sub>2</sub></var>
                        </code> or <code>
                           <var>E<sub>1</sub></var>[<var>E<sub>2</sub></var>]</code> is evaluated, the context size in the
inner focus for an evaluation of <var>E<sub>2</sub></var> is
the number of items in the sequence obtained by evaluating <var>E<sub>1</sub></var>. </p></li><li><p>
                        [<a id="dt-variable-values" title="variable values">Definition</a>: 
                           <b>Variable values</b>. 
        This is a mapping from <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a> to values. 
        It contains the
				same <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a> as the <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a> in the
				<a title="static context" class="termref" href="#dt-static-context">static context</a> for the expression. The <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> is the name of the variable and the value is the dynamic value of the variable, which includes its <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a>.]
                     </p></li><li><p>
                        [<a id="dt-dynamically-known-function-definitions" title="dynamically known function definitions">Definition</a>: 
                           <b>Dynamically known function definitions</b>.
        This is a set of <a title="function definition" class="termref" href="#dt-function-definition">function definitions</a>. It includes the
                        <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a> as a subset, but may include
                        other function definitions that are not known statically.
      ]
                     </p><p>The function definitions in the dynamic context are used primarily by the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-function-lookup"><code>fn:function-lookup</code></a>
                  function.</p><p>If two function definitions in the <a title="dynamically known function definitions" class="termref" href="#dt-dynamically-known-function-definitions">dynamically known function definitions</a> have the same
                     name, then their <a title="arity range" class="termref" href="#dt-arity-range">arity ranges</a> must not overlap.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The reason for allowing named functions to be available dynamically beyond those that are
                  available statically is primarily to allow for cases where the run-time execution
                  environment is significantly different from the compile-time environment. This could happen, for example,
                  if a stylesheet or query is compiled within a web server and then executed in the web browser.
                  The <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-function-lookup"><code>fn:function-lookup</code></a> function allows dynamic discovery of resources that were not
                  available statically.</p></div></li><li><p>
                        [<a id="dt-date-time" title="current dateTime">Definition</a>: 
                           <b>Current dateTime.</b> This information represents
				an <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> point in time during the processing of <span class="xquery">a query</span>
                        , and includes an explicit timezone. It can be retrieved by the  <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-current-dateTime"><code>fn:current-dateTime</code></a> function. 
                        If called multiple times during the execution of <span class="xquery">a query</span>
                        ,
				this function always returns the same result.]
                     </p></li><li><p>
                        [<a id="dt-timezone" title="implicit timezone">Definition</a>: 
                           <b>Implicit timezone.</b> 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  <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> value of type
<code>xs:dayTimeDuration</code>. See <a href="https://www.w3.org/TR/xmlschema-2/#dateTime-timezones">
                  
                     3.2.7.3 Timezones
               </a><sup><small>XS1-2</small></sup> or
<a href="https://www.w3.org/TR/xmlschema11-2/#dateTime">
               
                  3.3.7 dateTime
            </a><sup><small>XS11-2</small></sup> for the range of valid values of a timezone.]
                     </p></li><li><p>
                        [<a id="dt-executable-base-uri" title="Executable Base URI">Definition</a>: 
                           <b>Executable Base URI.</b> 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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-doc"><code>fn:doc</code></a> or <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-unparsed-text"><code>fn:unparsed-text</code></a>
                     functions.
                  ]
                     </p><p>URIs are resolved as described in <a href="#id-resolve-relative-uri"><b>2.5.6 Resolving a Relative URI Reference</b></a>.</p><p>The function <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-static-base-uri"><code>fn:static-base-uri</code></a>, despite its name, returns the
                     value of the <a title="Executable Base URI" class="termref" href="#dt-executable-base-uri">Executable Base URI</a>.</p><p>In many straightforward processing scenarios, the <a title="Executable Base URI" class="termref" href="#dt-executable-base-uri">Executable Base URI</a>
                  in the dynamic context will be the same as the <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a> for the
                     corresponding expression in the static context. There are situations, however, where they may differ:</p><ul><li><p>Some processors may allow the static analysis of a query or stylesheet
                     to take place on a development machine, while execution of the query or stylesheet
                     happens on a test or production server. In this situation, resources needed during
                     static analysis (such as other modules of the query or stylesheet) will be located
                     on the development machine, by reference to the <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a>,
                     while resources needed during execution (such as reference data files) will be located
                     on the production machine, accessed via the <a title="Executable Base URI" class="termref" href="#dt-executable-base-uri">Executable Base URI</a>.</p></li><li><p>When the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-static-base-uri"><code>fn:static-base-uri</code></a> function is called within
                     the initializing expression of an optional parameter in a function declaration,
                     it returns the executable base URI of the relevant function call. This allows a user-written
                     function to accept two parameters: a required parameter containing a relative URI, and an
                     optional parameter containing a base URI. The optional parameter can be given a default
                     value of <code>fn:static-base-uri()</code>, allowing the code in the function body
                     to resolve the relative URI against the executable base URI of the caller.</p></li></ul></li><li><p>
                        [<a id="dt-def-collation" title="default collation">Definition</a>: 
                           <b>Default
                           collation.</b> This identifies one of the collations in <a title="statically known collations" class="termref" href="#dt-static-collations">statically known collations</a> as the  collation to be
                        used by functions and operators for comparing and ordering values of type <code>xs:string</code> and <code>xs:anyURI</code> (and types derived from them) when no
                        explicit collation is
                        specified.]
                     </p><div class="note"><p class="prefix"><b>Note:</b></p><p>Although the default collation is defined (in 4.0) as a property of the
                     dynamic context, its value will in nearly all cases be known statically. The reason it is defined in the
                     dynamic context is to allow a call on the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-default-collation"><code>fn:default-collation</code></a> function to be used when defining
                     the default value of an optional parameter to a user-defined function. In this situation,
                     the actual value supplied for the parameter is taken from the dynamic context of the relevant function call.</p></div></li><li><p>
                        [<a id="dt-default-language" title="default language">Definition</a>: 
                           <b>Default language.</b>
  This is the natural language used when creating human-readable output
  (for example, by the functions <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-date"><code>fn:format-date</code></a> and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-integer"><code>fn:format-integer</code></a>)
  if no other language is requested. 
  The value is a language code as defined by the type <code>xs:language</code>.]
                     </p></li><li><p>
                        [<a id="dt-default-calendar" title="default calendar">Definition</a>: 
                           <b>Default calendar.</b>
    This is the calendar used when formatting dates in human-readable output
    (for example, by the functions <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-date"><code>fn:format-date</code></a> and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-dateTime"><code>fn:format-dateTime</code></a>)
    if no other calendar is requested. 
    The value is a string.]
                     </p></li><li><p>
                        [<a id="dt-default-place" title="default place">Definition</a>: 
                           <b>Default place.</b>
    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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-date"><code>fn:format-date</code></a>, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-dateTime"><code>fn:format-dateTime</code></a>,
     and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-civil-timezone"><code>fn:civil-timezone</code></a>,
    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.]
                     </p></li><li><p>
                        [<a id="dt-available-docs" title="available documents">Definition</a>: 
                           <b>Available
    documents.</b> 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 <a title="data model" class="termref" href="#dt-datamodel">data model</a>. The document node is returned by the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-doc"><code>fn:doc</code></a> 
    function when applied to that URI.] The set of available documents may be empty.</p></li><li><p>
                        [<a id="dt-available-text-resources" title="available text resources">Definition</a>: 
                           <b>Available text resources</b>. 
  This is a mapping of strings to text resources. Each string
  represents the absolute URI of a resource. The resource is returned
  by the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-unparsed-text"><code>fn:unparsed-text</code></a> function when applied to that
  URI.] The set of available text resources may be empty.</p></li><li><p>
                        [<a id="dt-available-binary-resources" title="available binary resources">Definition</a>: 
                           <b>Available binary resources</b>. 
  This is a mapping of strings to binary resources. Each string
  represents the absolute URI of a resource. The resource is returned
  by the <code>fn:unparsed-binary</code> function when applied to that
  URI.] The set of available binary resources may be empty.</p></li><li><p>
                        [<a id="dt-available-collections" title="available item collections">Definition</a>: 
                           <b>Available
                           collections.</b> 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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collection"><code>fn:collection</code></a>
                         function when that URI is supplied as the
                         argument. ] The set of available
                            collections may be empty.</p><p>Ideally, for every document node <code>D</code> that is in the target of a 
                     mapping in <a title="available item collections" class="termref" href="#dt-available-collections">available item collections</a>, or that is the root of a tree containing 
                     such a node, the document-uri property of <code>D</code> should either be absent, 
                     or should be a URI <code>U</code> such that <a title="available documents" class="termref" href="#dt-available-docs">available documents</a> contains a mapping from <code>U</code> to <code>D</code>.

</p><div class="note"><p class="prefix"><b>Note:</b></p><p>That is to say, the <code>document-uri</code> property of nodes returned
                        by the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collection"><code>fn:collection</code></a> function should be such that
                        calling <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-doc"><code>fn:doc</code></a> with that URI returns the relevant node.</p><p>It is not always possible to ensure this, especially in cases where 
                        dereferencing of document or collection URIs is configurable using
                        configuration files or user-supplied resolver code.</p></div></li><li><p>
                        [<a id="dt-default-collection" title="default collection">Definition</a>: 
                           <b>Default  collection.</b>
    This is the sequence of items  that would result from calling the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collection"><code>fn:collection</code></a> function
    with no arguments.] The value of <b>default   collection</b> may be initialized by the
    implementation.</p></li><li><p>
                        [<a id="dt-available-uri-collections" title="available uri collections">Definition</a>: 
                           <b>Available
    URI collections.</b> 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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-uri-collection"><code>fn:uri-collection</code></a>
    function when that URI is supplied as the
    argument. ] There is no implication that the URIs in this sequence
    can be successfully dereferenced, or that the resources they refer to have any particular media type.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>An implementation <span class="verb">may</span> maintain some consistent relationship between the available
    collections and the available URI collections, for example by ensuring that the result of
  <code>fn:uri-collection(X)!fn:doc(.)</code> is the same as the result of <code>fn:collection(X)</code>.
    However, this is not required. The <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-uri-collection"><code>fn:uri-collection</code></a> function is more 
    general than <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collection"><code>fn:collection</code></a> in that 
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collection"><code>fn:collection</code></a> allows access to 
    nodes that might lack individual URIs, for example nodes corresponding 
    to XML fragments stored in the rows of a relational database.</p></div></li><li><p>
                        [<a id="dt-default-uri-collection" title="default URI collection">Definition</a>: 
                           <b>Default URI collection.</b>
    This is the sequence of URIs that would result from calling the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-uri-collection"><code>fn:uri-collection</code></a> function
    with no arguments.] The value of <b>default URI collection</b> may be initialized by the
    implementation.</p></li><li><p>
                        [<a id="dt-environment-variables" title="environment variables">Definition</a>: 
                           <b>Environment variables.</b>
  This is a mapping from names to values. 
    Both the names and the values are strings. The names are compared using an
    <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> collation, and are unique under this collation. The set of environment variables is
  <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> and <span class="verb">may</span> be empty.]
                     </p><div class="note"><p class="prefix"><b>Note:</b></p><p>A possible implementation is to provide the set of POSIX environment variables (or their equivalent on other
      operating systems) appropriate to the process in which the <span class="xquery">query is initiated</span>
                        .</p></div></li></ul></div></div><div class="div2">
<h3><a id="id-processing-model"/>2.3 <a href="#id-processing-model" style="text-decoration: none">Processing Model</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-guarded-expressions">⬇</a> <a href="#eval_context">⬆</a></p><ol><li><p>
             The static typing option has been dropped.
           <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1343">1343</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1344">1344</a> 3 September 2024]</i></p></li></ol></div><p>The semantics of XQuery 4.0 are defined in terms
                         of the <a title="data model" class="termref" href="#dt-datamodel">data
                         model</a> and the <a title="expression context" class="termref" href="#dt-expression-context">expression
                         context</a>.</p><div class="svg-image"><!-- Generated by graphviz version 12.2.1 (20241206.2353)
 --><!-- Title: Processing_Model Pages: 1 --><svg width="630pt" height="667pt" viewBox="0.00 0.00 629.62 666.50" preserveAspectRatio="xMidYMid meet" zoomAndPan="magnify" version="1.1" contentScriptType="text/ecmascript" contentStyleType="text/css"><g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 662.5)"><title>Processing_Model</title><g id="a_graph0"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="XQuery Processing Model" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<polygon fill="white" stroke="none" points="-4,4 -4,-662.5 625.62,-662.5 625.62,4 -4,4"/>
</a></g><g id="clust1" class="cluster"><title>clusterQT4</title><g id="a_clust1"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="Query Processing" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<polygon fill="none" stroke="black" points="260,-80.5 260,-575 526,-575 526,-80.5 260,-80.5"/>
<text text-anchor="middle" x="393" y="-557.7" font-family="Times,serif" font-size="14.00">Query Processing</text>
</a></g></g><g id="clust2" class="cluster"><title>clusterEP</title><g id="a_clust2"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="XQuery Processing Model" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<polygon fill="none" stroke="black" points="8,-174 8,-349 252,-349 252,-174 8,-174"/>
<text text-anchor="middle" x="130" y="-331.7" font-family="Times,serif" font-size="14.00">External processing</text>
</a></g></g><!-- Exec --><g id="node1" class="node"><title>Exec</title><g id="a_node1"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="Execution Engine" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M351.38,-223C351.38,-223 304.62,-223 304.62,-223 298.62,-223 292.62,-217 292.62,-211 292.62,-211 292.62,-194 292.62,-194 292.62,-188 298.62,-182 304.62,-182 304.62,-182 351.38,-182 351.38,-182 357.38,-182 363.38,-188 363.38,-194 363.38,-194 363.38,-211 363.38,-211 363.38,-217 357.38,-223 351.38,-223"/>
<text text-anchor="middle" x="328" y="-205.7" font-family="Times,serif" font-size="14.00">Execution</text>
<text text-anchor="middle" x="328" y="-189.2" font-family="Times,serif" font-size="14.00">Engine</text>
</a></g></g><!-- XDM --><g id="node2" class="node"><title>XDM</title><g id="a_node2"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#dt-data-model-instance" xlink:title="XPath Data Model" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<polygon fill="none" stroke="black" points="347.5,-129.5 268.5,-129.5 268.5,-88.5 347.5,-88.5 347.5,-129.5"/>
<text text-anchor="middle" x="308" y="-112.2" font-family="Times,serif" font-size="14.00" fill="blue">XPath Data</text>
<text text-anchor="middle" x="308" y="-95.7" font-family="Times,serif" font-size="14.00" fill="blue">Model</text>
</a></g></g><!-- Exec&#45;&gt;XDM --><g id="edge9" class="edge"><title>Exec-&gt;XDM</title><g id="a_edge9"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DQ12345" xlink:title=" DQ4" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M321.21,-170.46C319.13,-160.9 316.83,-150.39 314.74,-140.84"/>
<polygon fill="black" stroke="black" points="317.78,-171.15 323.34,-180.17 324.62,-169.65 317.78,-171.15"/>
<polygon fill="black" stroke="black" points="318.21,-140.32 312.65,-131.29 311.37,-141.81 318.21,-140.32"/>
</a></g><g id="a_edge9-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DQ12345" xlink:title="Access and create" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="334.79" y="-150.7" font-family="Times,serif" font-size="14.00" fill="blue"> DQ4</text>
</a></g></g><!-- Serialize --><g id="node16" class="node"><title>Serialize</title><polygon fill="none" stroke="black" points="333.62,-36 276.38,-36 276.38,0 339.62,0 339.62,-30 333.62,-36"/><polyline fill="none" stroke="black" points="333.62,-36 333.62,-30"/><polyline fill="none" stroke="black" points="339.62,-30 333.62,-30"/><text text-anchor="middle" x="308" y="-12.95" font-family="Times,serif" font-size="14.00">Serialize</text></g><!-- XDM&#45;&gt;Serialize --><g id="edge18" class="edge"><title>XDM-&gt;Serialize</title><g id="a_edge18"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#id-serialization" xlink:title=" DM4" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M308,-88.25C308,-76.33 308,-60.94 308,-47.69"/>
<polygon fill="black" stroke="black" points="311.5,-47.81 308,-37.81 304.5,-47.81 311.5,-47.81"/>
</a></g><g id="a_edge18-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#id-serialization" xlink:title="Serialize" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="324.5" y="-57.2" font-family="Times,serif" font-size="14.00" fill="blue"> DM4</text>
</a></g></g><!-- AST --><g id="node3" class="node"><title>AST</title><g id="a_node3"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SQ5" xlink:title="Abstract Syntax Tree (AST)" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M375.75,-316.5C375.75,-316.5 280.25,-316.5 280.25,-316.5 274.25,-316.5 268.25,-310.5 268.25,-304.5 268.25,-304.5 268.25,-287.5 268.25,-287.5 268.25,-281.5 274.25,-275.5 280.25,-275.5 280.25,-275.5 375.75,-275.5 375.75,-275.5 381.75,-275.5 387.75,-281.5 387.75,-287.5 387.75,-287.5 387.75,-304.5 387.75,-304.5 387.75,-310.5 381.75,-316.5 375.75,-316.5"/>
<text text-anchor="middle" x="328" y="-299.2" font-family="Times,serif" font-size="14.00" fill="blue">Abstract</text>
<text text-anchor="middle" x="328" y="-282.7" font-family="Times,serif" font-size="14.00" fill="blue">Syntax Tree (AST)</text>
</a></g></g><!-- AST&#45;&gt;Exec --><g id="edge3" class="edge"><title>AST-&gt;Exec</title><g id="a_edge3"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DQ12345" xlink:title=" DQ1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M328,-275.15C328,-263.28 328,-247.94 328,-234.5"/>
<polygon fill="black" stroke="black" points="331.5,-234.83 328,-224.83 324.5,-234.83 331.5,-234.83"/>
</a></g><g id="a_edge3-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DQ12345" xlink:title="Access AST" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="343" y="-244.2" font-family="Times,serif" font-size="14.00" fill="blue"> DQ1</text>
</a></g></g><!-- AST&#45;&gt;AST --><g id="edge2" class="edge"><title>AST-&gt;AST</title><g id="a_edge2"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SQ5" xlink:title=" SQ5" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M387.98,-304.22C398.46,-303.12 405.75,-300.38 405.75,-296 405.75,-293.47 403.31,-291.48 399.23,-290.05"/>
<polygon fill="black" stroke="black" points="399.96,-286.62 389.47,-288.08 398.58,-293.49 399.96,-286.62"/>
</a></g><g id="a_edge2-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SQ5" xlink:title="Normalize" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="419.62" y="-290.95" font-family="Times,serif" font-size="14.00" fill="blue"> SQ5</text>
</a></g></g><!-- Static --><g id="node4" class="node"><title>Static</title><g id="a_node4"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#dt-static-context" xlink:title="Static Context" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<polygon fill="none" stroke="black" points="513.38,-432.5 458.62,-432.5 454.62,-428.5 454.62,-391.5 509.38,-391.5 513.38,-395.5 513.38,-432.5"/>
<polyline fill="none" stroke="black" points="509.38,-428.5 454.62,-428.5"/>
<polyline fill="none" stroke="black" points="509.38,-428.5 509.38,-391.5"/>
<polyline fill="none" stroke="black" points="509.38,-428.5 513.38,-432.5"/>
<text text-anchor="middle" x="484" y="-415.2" font-family="Times,serif" font-size="14.00" fill="blue">Static</text>
<text text-anchor="middle" x="484" y="-398.7" font-family="Times,serif" font-size="14.00" fill="blue">Context</text>
</a></g></g><!-- Static&#45;&gt;AST --><g id="edge6" class="edge"><title>Static-&gt;AST</title><g id="a_edge6"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SQ1234" xlink:title=" SQ4" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M456.83,-391.14C431.18,-372.4 392.55,-344.17 364.28,-323.51"/>
<polygon fill="black" stroke="black" points="366.48,-320.79 356.35,-317.71 362.35,-326.44 366.48,-320.79"/>
</a></g><g id="a_edge6-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SQ1234" xlink:title="Resolve names" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="442.96" y="-360.2" font-family="Times,serif" font-size="14.00" fill="blue"> SQ4</text>
</a></g></g><!-- Dynamic --><g id="node5" class="node"><title>Dynamic</title><g id="a_node5"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#dt-dynamic-context" xlink:title="Dynamic Context" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<polygon fill="none" stroke="black" points="518.12,-316.5 455.88,-316.5 451.88,-312.5 451.88,-275.5 514.12,-275.5 518.12,-279.5 518.12,-316.5"/>
<polyline fill="none" stroke="black" points="514.12,-312.5 451.88,-312.5"/>
<polyline fill="none" stroke="black" points="514.12,-312.5 514.12,-275.5"/>
<polyline fill="none" stroke="black" points="514.12,-312.5 518.12,-316.5"/>
<text text-anchor="middle" x="485" y="-299.2" font-family="Times,serif" font-size="14.00" fill="blue">Dynamic</text>
<text text-anchor="middle" x="485" y="-282.7" font-family="Times,serif" font-size="14.00" fill="blue">Context</text>
</a></g></g><!-- Static&#45;&gt;Dynamic --><g id="edge7" class="edge"><title>Static-&gt;Dynamic</title><g id="a_edge7"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DQ12345" xlink:title=" DQ2" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M484.17,-391.14C484.33,-373.73 484.55,-348.14 484.73,-328.03"/>
<polygon fill="black" stroke="black" points="488.23,-328.17 484.81,-318.14 481.23,-328.11 488.23,-328.17"/>
</a></g><g id="a_edge7-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DQ12345" xlink:title="Provide access" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="499.47" y="-360.2" font-family="Times,serif" font-size="14.00" fill="blue"> DQ2</text>
</a></g></g><!-- Dynamic&#45;&gt;Exec --><g id="edge8" class="edge"><title>Dynamic-&gt;Exec</title><g id="a_edge8"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DQ12345" xlink:title=" DQ5" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M442.04,-269.96C420.21,-257.24 393.74,-241.81 371.79,-229.02"/>
<polygon fill="black" stroke="black" points="439.99,-272.82 450.4,-274.83 443.52,-266.77 439.99,-272.82"/>
<polygon fill="black" stroke="black" points="373.77,-226.12 363.37,-224.11 370.25,-232.17 373.77,-226.12"/>
</a></g><g id="a_edge8-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DQ12345" xlink:title="Access and change" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="435.56" y="-244.2" font-family="Times,serif" font-size="14.00" fill="blue"> DQ5</text>
</a></g></g><!-- Schema --><g id="node6" class="node"><title>Schema</title><g id="a_node6"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#dt-issd" xlink:title="In-Scope Schema Definitions" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<polygon fill="none" stroke="black" points="434.38,-542.5 357.62,-542.5 357.62,-485 434.38,-485 434.38,-542.5"/>
<text text-anchor="middle" x="396" y="-525.2" font-family="Times,serif" font-size="14.00" fill="blue">In-Scope</text>
<text text-anchor="middle" x="396" y="-508.7" font-family="Times,serif" font-size="14.00" fill="blue">Schema</text>
<text text-anchor="middle" x="396" y="-492.2" font-family="Times,serif" font-size="14.00" fill="blue">Definitions</text>
</a></g></g><!-- Schema&#45;&gt;Static --><g id="edge4" class="edge"><title>Schema-&gt;Static</title><path fill="none" stroke="black" d="M420.75,-484.7C432.67,-471.18 446.95,-455 458.92,-441.43"/><polygon fill="black" stroke="black" points="461.41,-443.89 465.4,-434.08 456.16,-439.26 461.41,-443.89"/></g><!-- XQuery --><g id="node7" class="node"><title>XQuery</title><g id="a_node7"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="XQuery/XQueryX" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M350.62,-432.5C350.62,-432.5 305.38,-432.5 305.38,-432.5 299.38,-432.5 293.38,-426.5 293.38,-420.5 293.38,-420.5 293.38,-403.5 293.38,-403.5 293.38,-397.5 299.38,-391.5 305.38,-391.5 305.38,-391.5 350.62,-391.5 350.62,-391.5 356.62,-391.5 362.62,-397.5 362.62,-403.5 362.62,-403.5 362.62,-420.5 362.62,-420.5 362.62,-426.5 356.62,-432.5 350.62,-432.5"/>
<text text-anchor="middle" x="328" y="-415.2" font-family="Times,serif" font-size="14.00">XQuery/</text>
<text text-anchor="middle" x="328" y="-398.7" font-family="Times,serif" font-size="14.00">XQueryX</text>
</a></g></g><!-- XQuery&#45;&gt;AST --><g id="edge1" class="edge"><title>XQuery-&gt;AST</title><g id="a_edge1"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SQ1234" xlink:title=" SQ1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M328,-391.14C328,-373.73 328,-348.14 328,-328.03"/>
<polygon fill="black" stroke="black" points="331.5,-328.14 328,-318.14 324.5,-328.14 331.5,-328.14"/>
</a></g><g id="a_edge1-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SQ1234" xlink:title="Parse query" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="341.88" y="-360.2" font-family="Times,serif" font-size="14.00" fill="blue"> SQ1</text>
</a></g></g><!-- Modules --><g id="node8" class="node"><title>Modules</title><g id="a_node8"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#id-module-declaration" xlink:title="Modules" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M504,-531.75C504,-531.75 464,-531.75 464,-531.75 458,-531.75 452,-525.75 452,-519.75 452,-519.75 452,-507.75 452,-507.75 452,-501.75 458,-495.75 464,-495.75 464,-495.75 504,-495.75 504,-495.75 510,-495.75 516,-501.75 516,-507.75 516,-507.75 516,-519.75 516,-519.75 516,-525.75 510,-531.75 504,-531.75"/>
<text text-anchor="middle" x="484" y="-508.7" font-family="Times,serif" font-size="14.00" fill="blue">Modules</text>
</a></g></g><!-- Modules&#45;&gt;Static --><g id="edge5" class="edge"><title>Modules-&gt;Static</title><g id="a_edge5"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SQ1234" xlink:title=" SQ3" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M484,-495.37C484,-481.22 484,-460.89 484,-443.97"/>
<polygon fill="black" stroke="black" points="487.5,-444.43 484,-434.43 480.5,-444.43 487.5,-444.43"/>
</a></g><g id="a_edge5-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SQ1234" xlink:title="Augment with module prolog" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="497.88" y="-453.7" font-family="Times,serif" font-size="14.00" fill="blue"> SQ3</text>
</a></g></g><!-- XML --><g id="node9" class="node"><title>XML</title><polygon fill="none" stroke="black" points="64,-314 16,-314 16,-278 70,-278 70,-308 64,-314"/><polyline fill="none" stroke="black" points="64,-314 64,-308"/><polyline fill="none" stroke="black" points="70,-308 64,-308"/><text text-anchor="middle" x="43" y="-290.95" font-family="Times,serif" font-size="14.00">XML</text></g><!-- PSVI --><g id="node11" class="node"><title>PSVI</title><g id="a_node11"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#id-data-model-generation" xlink:title="Infoset/PSVI" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<polygon fill="none" stroke="black" points="89.62,-223 38.38,-223 38.38,-182 95.62,-182 95.62,-217 89.62,-223"/>
<polyline fill="none" stroke="black" points="89.62,-223 89.62,-217"/>
<polyline fill="none" stroke="black" points="95.62,-217 89.62,-217"/>
<text text-anchor="middle" x="67" y="-205.7" font-family="Times,serif" font-size="14.00" fill="blue">Infoset/</text>
<text text-anchor="middle" x="67" y="-189.2" font-family="Times,serif" font-size="14.00" fill="blue">PSVI</text>
</a></g></g><!-- XML&#45;&gt;PSVI --><g id="edge10" class="edge"><title>XML-&gt;PSVI</title><g id="a_edge10"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DM1" xlink:title=" DM1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M47.51,-277.79C50.73,-265.54 55.14,-248.73 58.95,-234.21"/>
<polygon fill="black" stroke="black" points="62.3,-235.2 61.46,-224.64 55.53,-233.42 62.3,-235.2"/>
</a></g><g id="a_edge10-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DM1" xlink:title="Parse and optionally validate" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="73.65" y="-244.2" font-family="Times,serif" font-size="14.00" fill="blue"> DM1</text>
</a></g></g><!-- JSON --><g id="node10" class="node"><title>JSON</title><polygon fill="none" stroke="black" points="136,-314 88,-314 88,-278 142,-278 142,-308 136,-314"/><polyline fill="none" stroke="black" points="136,-314 136,-308"/><polyline fill="none" stroke="black" points="142,-308 136,-308"/><text text-anchor="middle" x="115" y="-290.95" font-family="Times,serif" font-size="14.00">JSON</text></g><!-- JSON&#45;&gt;XDM --><g id="edge11" class="edge"><title>JSON-&gt;XDM</title><g id="a_edge11"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DM2" xlink:title=" DM2" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M122.16,-277.83C133.44,-252.48 157.47,-204.7 190,-174 209.46,-155.63 235.2,-140.87 257.67,-130.17"/>
<polygon fill="black" stroke="black" points="259.07,-133.38 266.69,-126.02 256.14,-127.02 259.07,-133.38"/>
</a></g><g id="a_edge11-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DM2" xlink:title="Generate Data Model" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="206.5" y="-197.45" font-family="Times,serif" font-size="14.00" fill="blue"> DM2</text>
</a></g></g><!-- PSVI&#45;&gt;XDM --><g id="edge12" class="edge"><title>PSVI-&gt;XDM</title><g id="a_edge12"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DM2" xlink:title=" DM2" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M69.38,-181.69C71.84,-170.02 76.84,-155.92 87,-147.5 112.23,-126.59 199.89,-116.96 256.94,-112.82"/>
<polygon fill="black" stroke="black" points="257.02,-116.33 266.75,-112.15 256.53,-109.34 257.02,-116.33"/>
</a></g><g id="a_edge12-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DM2" xlink:title="Generate Data Model" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="103.5" y="-150.7" font-family="Times,serif" font-size="14.00" fill="blue"> DM2</text>
</a></g></g><!-- Direct --><g id="node12" class="node"><title>Direct</title><g id="a_node12"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="Other/Direct Generation" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M232.12,-316.5C232.12,-316.5 171.88,-316.5 171.88,-316.5 165.88,-316.5 159.88,-310.5 159.88,-304.5 159.88,-304.5 159.88,-287.5 159.88,-287.5 159.88,-281.5 165.88,-275.5 171.88,-275.5 171.88,-275.5 232.12,-275.5 232.12,-275.5 238.12,-275.5 244.12,-281.5 244.12,-287.5 244.12,-287.5 244.12,-304.5 244.12,-304.5 244.12,-310.5 238.12,-316.5 232.12,-316.5"/>
<text text-anchor="middle" x="202" y="-299.2" font-family="Times,serif" font-size="14.00">Other/Direct</text>
<text text-anchor="middle" x="202" y="-282.7" font-family="Times,serif" font-size="14.00">Generation</text>
</a></g></g><!-- Direct&#45;&gt;XDM --><g id="edge13" class="edge"><title>Direct-&gt;XDM</title><g id="a_edge13"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DM3" xlink:title=" DM3" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M207.72,-275.16C215.37,-250.35 230.42,-207.11 251,-174 258.93,-161.24 269.48,-148.58 279.34,-137.94"/>
<polygon fill="black" stroke="black" points="281.63,-140.62 286,-130.96 276.56,-135.78 281.63,-140.62"/>
</a></g><g id="a_edge13-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DM3" xlink:title="Other/Direct Generation" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="267.5" y="-197.45" font-family="Times,serif" font-size="14.00" fill="blue"> DM3</text>
</a></g></g><!-- XSD --><g id="node13" class="node"><title>XSD</title><g id="a_node13"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="XML Schema" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<polygon fill="none" stroke="black" points="374.75,-658.5 321.25,-658.5 321.25,-617.5 380.75,-617.5 380.75,-652.5 374.75,-658.5"/>
<polyline fill="none" stroke="black" points="374.75,-658.5 374.75,-652.5"/>
<polyline fill="none" stroke="black" points="380.75,-652.5 374.75,-652.5"/>
<text text-anchor="middle" x="351" y="-641.2" font-family="Times,serif" font-size="14.00">XML</text>
<text text-anchor="middle" x="351" y="-624.7" font-family="Times,serif" font-size="14.00">Schema</text>
</a></g></g><!-- XSD&#45;&gt;Schema --><g id="edge14" class="edge"><title>XSD-&gt;Schema</title><g id="a_edge14"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#id-schema-import-processing" xlink:title=" SI1" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M358.33,-617.09C364.65,-599.92 373.96,-574.63 381.74,-553.49"/>
<polygon fill="black" stroke="black" points="384.96,-554.89 385.13,-544.29 378.39,-552.47 384.96,-554.89"/>
</a></g><g id="a_edge14-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#id-schema-import-processing" xlink:title="XML Schema Import" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="382.06" y="-586.2" font-family="Times,serif" font-size="14.00" fill="blue"> SI1</text>
</a></g></g><!-- DirectXSD --><g id="node14" class="node"><title>DirectXSD</title><g id="a_node14"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="Other/Direct Generation" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M471.12,-658.5C471.12,-658.5 410.88,-658.5 410.88,-658.5 404.88,-658.5 398.88,-652.5 398.88,-646.5 398.88,-646.5 398.88,-629.5 398.88,-629.5 398.88,-623.5 404.88,-617.5 410.88,-617.5 410.88,-617.5 471.12,-617.5 471.12,-617.5 477.12,-617.5 483.12,-623.5 483.12,-629.5 483.12,-629.5 483.12,-646.5 483.12,-646.5 483.12,-652.5 477.12,-658.5 471.12,-658.5"/>
<text text-anchor="middle" x="441" y="-641.2" font-family="Times,serif" font-size="14.00">Other/Direct</text>
<text text-anchor="middle" x="441" y="-624.7" font-family="Times,serif" font-size="14.00">Generation</text>
</a></g></g><!-- DirectXSD&#45;&gt;Schema --><g id="edge15" class="edge"><title>DirectXSD-&gt;Schema</title><g id="a_edge15"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SI2" xlink:title=" SI2" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M433.67,-617.09C427.35,-599.92 418.04,-574.63 410.26,-553.49"/>
<polygon fill="black" stroke="black" points="413.61,-552.47 406.87,-544.29 407.04,-554.89 413.61,-552.47"/>
</a></g><g id="a_edge15-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SI2" xlink:title="Other/Direct Generation" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="437.69" y="-586.2" font-family="Times,serif" font-size="14.00" fill="blue"> SI2</text>
</a></g></g><!-- Host --><g id="node15" class="node"><title>Host</title><g id="a_node15"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:title="Host Environment" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M609.62,-534.25C609.62,-534.25 546.38,-534.25 546.38,-534.25 540.38,-534.25 534.38,-528.25 534.38,-522.25 534.38,-522.25 534.38,-505.25 534.38,-505.25 534.38,-499.25 540.38,-493.25 546.38,-493.25 546.38,-493.25 609.62,-493.25 609.62,-493.25 615.62,-493.25 621.62,-499.25 621.62,-505.25 621.62,-505.25 621.62,-522.25 621.62,-522.25 621.62,-528.25 615.62,-534.25 609.62,-534.25"/>
<text text-anchor="middle" x="578" y="-516.95" font-family="Times,serif" font-size="14.00">Host</text>
<text text-anchor="middle" x="578" y="-500.45" font-family="Times,serif" font-size="14.00">Environment</text>
</a></g></g><!-- Host&#45;&gt;Static --><g id="edge16" class="edge"><title>Host-&gt;Static</title><g id="a_edge16"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SQ1234" xlink:title=" SQ2" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M559.43,-493.04C545.4,-478.15 525.95,-457.51 510.31,-440.92"/>
<polygon fill="black" stroke="black" points="512.98,-438.65 503.57,-433.77 507.88,-443.45 512.98,-438.65"/>
</a></g><g id="a_edge16-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#SQ1234" xlink:title="Initialize from host environment" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="547.69" y="-453.7" font-family="Times,serif" font-size="14.00" fill="blue"> SQ2</text>
</a></g></g><!-- Host&#45;&gt;Dynamic --><g id="edge17" class="edge"><title>Host-&gt;Dynamic</title><g id="a_edge17"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DQ12345" xlink:title=" DQ3" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<path fill="none" stroke="black" d="M574.75,-492.79C572.44,-480.41 568.87,-464.29 564,-450.5 548.03,-405.24 521.13,-356.55 503.22,-326.42"/>
<polygon fill="black" stroke="black" points="506.23,-324.64 498.08,-317.87 500.24,-328.25 506.23,-324.64"/>
</a></g><g id="a_edge17-label"><a xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#DQ12345" xlink:title="Initialize from host environment" xlink:type="simple" xlink:show="replace" xlink:actuate="onRequest">
<text text-anchor="middle" x="571.59" y="-406.95" font-family="Times,serif" font-size="14.00" fill="blue"> DQ3</text>
</a></g></g></g></svg></div><p>Figure 1:
                         Processing Model Overview</p><p>Figure 1 provides a schematic overview of the processing steps that
are discussed in detail below. Some of these steps are completely
outside the domain of XQuery 4.0; in Figure 1, these are depicted
outside the line that represents the boundaries of the language, an
area labeled <b>external processing</b>. The external processing
domain includes generation of <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instances</a> that represent the data to be queried (see <a href="#id-data-model-generation"><b>2.3.1 Data Model Generation</b></a>), schema import processing (see
<a href="#id-schema-import-processing"><b>2.3.2 Schema Import Processing</b></a>), and serialization<span class="xquery"> (see
<a href="#id-serialization"><b>2.3.5 Serialization</b></a>)</span>. The area inside the boundaries of
the language is known as the <span class="xquery">
                  <b>query processing domain</b>
               </span>, which includes the static
analysis and dynamic evaluation phases (see <a href="#id-expression-processing"><b>2.3.3 Expression
Processing</b></a>).  Consistency constraints on the
<span class="xquery">query</span>
             processing domain are defined in <a href="#id-consistency-constraints"><b>2.3.6 Consistency Constraints</b></a>.</p><div class="div3">
<h4><a id="id-data-model-generation"/>2.3.1 <a href="#id-data-model-generation" style="text-decoration: none">Data Model Generation</a></h4><p>The input data for <span class="xquery">a query</span>
                must be represented as one or more <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instances</a>. This process occurs outside
the domain of XQuery 4.0, which is why Figure 1 represents it in the
external processing domain.</p><p>In many cases the input data might originate as XML.
               Here are some steps by which an XML
document might be converted to an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a>:</p><ol class="enumar"><li><p>A document may be parsed using an XML parser that
generates an <b>XML Information Set</b> (see <a href="#XINFO">[XML Infoset]</a>). The parsed document may then be validated against one
or more schemas. This process, which is described in <a href="http://www.w3.org/TR/xmlschema-1/">[XML Schema 1.0 Part 1]</a> or
<a href="http://www.w3.org/TR/xmlschema11-1/">[XML Schema 1.1 Part 1]</a>, results in an abstract information structure called
the <b>Post-Schema Validation Infoset</b> (PSVI). If a document
has no associated schema, its Information Set is preserved. (See DM1
in Figure 1)</p></li><li><p>The Information Set or PSVI may be
transformed into an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a>
by a process described in <a href="#xpath-datamodel-40">[XDM 4.0]</a>. (See DM2 in
Figure 1)</p></li></ol><p>The above steps provide an example of how an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a> might be constructed. An XDM instance might
also be constructed in some other way (see DM3 in Figure 1), for example it might be 
synthesized directly from a relational database, or
derived by parsing a JSON text or a CSV file. Whatever the origin, XQuery 4.0 is defined in terms
of the <a title="data model" class="termref" href="#dt-datamodel">data model</a>,
but it does not place any constraints on how XDM instances are constructed.</p><p>The remainder of this section is concerned with the common case where XML data is being processed.</p><p>
                  [<a id="dt-type-annotation" title="type annotation">Definition</a>: Each element node and attribute node in an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a> has a <b>type annotation</b> (described in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#types">4.1 Schema Information</a>). 
The type annotation of a node is a reference to a <a title="schema type" class="termref" href="#dt-schema-type">schema type</a>. 
]  The <code>type-name</code> of a node is the name of the type referenced by its <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> (but note that the
               type annotation can be a reference to an anonymous type). 
If the <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a> was derived from a validated XML document as described in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#const-psvi">7.4.3 Construction from a PSVI</a>, the type annotations of the element and attribute nodes are derived from schema
validation. XQuery 4.0 does
not provide a way to directly access the type annotation of an element
or attribute node.</p><p>The value of an attribute is represented directly within the
attribute node. An attribute node whose type is unknown (such as might
occur in a schemaless document) is given the <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a>
                  <code>xs:untypedAtomic</code>.</p><p>The value of an element is represented by the children of the
element node, which may include text nodes and other element
nodes. The <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> of an element node indicates how the values in
its child text nodes are to be interpreted. An element that has not been validated (such as might occur in a schemaless document) is annotated
with the <a title="schema type" class="termref" href="#dt-schema-type">schema type</a>
                  <code>xs:untyped</code>. An element that has been validated and found to be partially valid is annotated with the schema type <code>xs:anyType</code>. If an element node is annotated as <code>xs:untyped</code>, all its descendant element nodes are also annotated as <code>xs:untyped</code>. However, if an element node is annotated as <code>xs:anyType</code>, some of its descendant element nodes may have a more specific <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a>.</p></div><div class="div3">
<h4><a id="id-schema-import-processing"/>2.3.2 <a href="#id-schema-import-processing" style="text-decoration: none">Schema Import Processing</a></h4><p>The <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope
schema definitions</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a> may be extracted from
actual XML schemas (see step SI1 in Figure 1) or may be
generated by some other mechanism (see step SI2 in Figure 1). In
either case, the result must satisfy the consistency constraints
defined in <a href="#id-consistency-constraints"><b>2.3.6 Consistency Constraints</b></a>.</p></div><div class="div3">
<h4><a id="id-expression-processing"/>2.3.3 <a href="#id-expression-processing" style="text-decoration: none">Expression
Processing</a></h4><p>XQuery 4.0 defines two phases of processing called
the <a title="static analysis phase" class="termref" href="#dt-static-analysis">static analysis phase</a>
and the <a title="dynamic evaluation phase" class="termref" href="#dt-dynamic-evaluation">dynamic evaluation
phase</a> (see Figure 1).  During the static analysis phase, <a title="static error" class="termref" href="#dt-static-error">static errors</a>,  <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic errors</a>, or <a title="type error" class="termref" href="#dt-type-error">type errors</a> may be raised. During the dynamic evaluation phase, only <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic errors</a> or <a title="type error" class="termref" href="#dt-type-error">type errors</a> may be raised. These kinds of errors are defined in <a href="#id-kinds-of-errors"><b>2.4.1 Kinds of Errors</b></a>.  </p><p>Within each phase, an implementation is free to use any
strategy or algorithm whose result conforms to the
specifications in this document.</p><div class="div4">
<h5><a id="id-static-analysis"/>2.3.3.1 <a href="#id-static-analysis" style="text-decoration: none">Static Analysis Phase</a></h5><p>
                     [<a id="dt-static-analysis" title="static analysis phase">Definition</a>: The
<b>static analysis phase</b> depends on the expression itself
and on the <a title="static context" class="termref" href="#dt-static-context">static context</a>. The <b>static analysis phase</b> does
not depend on input data (other than schemas).]
                  </p><p>During the static analysis phase, the <span class="xquery">query</span>
                   is typically parsed into an
internal representation called the <b>operation tree</b> (step
SQ1 in Figure 1).  A parse error is raised as a <a title="static error" class="termref" href="#dt-static-error">static error</a>
                     [<a href="#ERRXPST0003" title="err:XPST0003">err:XPST0003</a>]. The <a title="static context" class="termref" href="#dt-static-context">static context</a> is initialized by the implementation (step SQ2). <span class="xquery">The <a title="static context" class="termref" href="#dt-static-context">static context</a> is then changed and augmented based on information in the
                        <b>prolog</b> (step SQ3). 
                        The static context is extended with function
                        declarations and variable declarations from imported modules.
                        If the <a title="schema aware feature" class="termref" href="#dt-schema-aware-feature">Schema Aware Feature</a>
                        is supported, the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a> are populated with information from imported schemas. 
                        </span> The <a title="static context" class="termref" href="#dt-static-context">static context</a> is used to resolve schema type names, function names, namespace prefixes, and variable names (step
SQ4).
If a name of one of these kinds in the <b>operation tree</b> is
not found in the <a title="static context" class="termref" href="#dt-static-context">static context</a>, a <a title="static error" class="termref" href="#dt-static-error">static error</a> ([<a href="#ERRXPST0008" title="err:XPST0008">err:XPST0008</a>] or [<a href="#ERRXPST0017" title="err:XPST0017">err:XPST0017</a>]) is raised (however, see exceptions to this rule in <a href="#id-element-test"><b>3.2.7.2 Element Types</b></a> and <a href="#id-attribute-test"><b>3.2.7.3 Attribute Types</b></a>.)</p><p>The <b>operation tree</b> is then typically
normalized by making explicit the implicit operations
such as <a title="atomization" class="termref" href="#dt-atomization">atomization</a> and extraction of <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean values</a> (step SQ5).</p><p>During the <a title="static analysis phase" class="termref" href="#dt-static-analysis">static analysis
phase</a>, a processor may perform type analysis. The
effect of type analysis is to assign a <a title="static type" class="termref" href="#dt-static-type">static type</a> to each expression in the
operation tree. [<a id="dt-static-type" title="static type">Definition</a>: The
<b>static type</b> of an expression is the best inference that
the processor is able to make statically about the type of the result
of the expression.] This specification does not define the
rules for type analysis nor the static types that are assigned to
particular expressions: the only constraint is that the inferred type
must match all possible values that the expression is capable of
returning.</p><p>Examples of inferred static types might be:</p><ul><li><p>For the expression <code>concat(a,b)</code> the inferred static type is <code>xs:string</code>
                        </p></li><li><p>For the expression <code>$a = $v</code> the inferred static type is <code>xs:boolean</code>
                        </p></li><li><p>For the expression <code>$s[exp]</code> the inferred static
    type has the same item type as the static type of <code>$s</code>,
    but a cardinality that allows the empty sequence even if the
    static type of <code>$s</code> does not allow an empty
    sequence.</p></li><li><p>The inferred static type of the expression <code>data($x)</code> (whether written
    explicitly or inserted into the operation tree in places where atomization
    is implicit) depends on the inferred static type of <code>$x</code>: for example, if <code>$x</code>
    has type <code>element(*, xs:integer)</code> then <code>data($x)</code> has static type <code>xs:integer</code>.</p></li></ul><p>In XQuery 1.0 and XPath 2.0, rules for static type inferencing were published
normatively in <a href="#xquery-semantics">[XQuery 1.0 and XPath 2.0 Formal Semantics]</a>, but implementations were allowed to
refine these rules to infer a more precise type where possible. In
subsequent versions, the rules for static type inferencing are entirely implementation-dependent.</p><p>Every kind of expression also imposes requirements on the type of its
operands. For example, with the expression <code>substring($a, $b, $c)</code>, <code>$a</code> must be
of type <code>xs:string</code> (or something that can be converted to <code>xs:string</code> by the
function calling rules), while <code>$b</code> and <code>$c</code> must be numeric.</p><p>A processor <span class="verb">may</span> raise a type
                  error during static analysis if the inferred static type of an
                     expression has no overlap (intersection) with the required type, and cannot be converted
                     to the required type using the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>. For example,
                     given the call <code>fn:upper-case($s)</code>, the processor <span class="verb">may</span> raise an error if the
                     declared or inferred type of <code>$s</code> is <code>xs:integer</code>, 
                     but not if it is <code>xs:anyAtomicType</code>.
                  </p><p>In addition, type analysis <span class="verb">may</span> conclude that an expression is <a title="implausible" class="termref" href="#dt-implausible">implausible</a>.
               Implausible expressions may be considered erroneous unless such checks have been disabled.
               For example, the expression <code>round(tokenize($input))</code> is implausible because 
                  the required type for <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-round"><code>fn:round</code></a> is <code>xs:numeric?</code>,
                  while the static type of <code>tokenize($input)</code> is <code>xs:string*</code>,
                  and these two sequence types are <a title="substantively disjoint" class="termref" href="#dt-substantively-disjoint">substantively disjoint</a>.
               This topic is described further in <a href="#id-implausible-expressions"><b>2.4.6 Implausible Expressions</b></a>.</p><p>Alternatively, the processor
                  <span class="verb">may</span> defer all type checking until the dynamic evaluation phase.</p></div><div class="div4">
<h5><a id="id-dynamic-evaluation"/>2.3.3.2 <a href="#id-dynamic-evaluation" style="text-decoration: none">Dynamic Evaluation Phase</a></h5><p>
                     [<a id="dt-dynamic-evaluation" title="dynamic evaluation phase">Definition</a>: The <b>dynamic evaluation phase</b> is the phase during which the value of an expression is computed.] It is dependent on successful completion of the <a title="static analysis phase" class="termref" href="#dt-static-analysis">static analysis phase</a>.</p><p>The dynamic evaluation phase can occur only if no errors were detected during the <a title="static analysis phase" class="termref" href="#dt-static-analysis">static analysis phase</a>.</p><p>The dynamic evaluation phase depends on the <b>operation
tree</b> of the expression being evaluated (step DQ1), on the input
data (step DQ4), and on the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> (step DQ5), which in turn draws information from  the external environment (step DQ3) and the <a title="static context" class="termref" href="#dt-static-context">static context</a> (step DQ2). The dynamic evaluation phase may create new data-model values (step DQ4) and it may extend the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> (step DQ5)—for example, by binding values to variables.</p><p>
                     [<a id="dt-dynamic-type" title="dynamic type">Definition</a>: 
                  Every value matches one or more <a title="sequence type" class="termref" href="#dt-sequence-type">sequence types</a>. 
                     A value is said to have a <b>dynamic type</b>
                        <var>T</var> if it matches (or <b>is an instance of</b>) 
                     the sequence type <var>T</var>.]
                  </p><p>In many cases (but not all), one of the dynamic types that a value matches will 
                     be a subtype of all the others, in which case it makes sense to speak of “the dynamic type” of the value as 
                     meaning this single most specific type. In other cases (examples are 
                     <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-empty-map">empty maps</a><sup><small>DM</small></sup> and 
                     <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-empty-array">empty arrays</a><sup><small>DM</small></sup>) none of the 
                     dynamic types is more specific than all the others.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>An atomic item has a <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> which will always be
                  a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of all the other types that it matches; we can therefore refer to 
                  this as the <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a> of the atomic item without ambiguity.</p></div><p>A value may match a dynamic type that is more specific than the <a title="static type" class="termref" href="#dt-static-type">static type</a> 
                  of the expression that computed it (for example, the static type of an expression might be <code>xs:integer*</code>, 
                  denoting a sequence of zero or more integers, but at evaluation time its value may be an instance of <code>xs:integer</code>, 
                  denoting exactly one integer).
               </p><p>If an operand of an expression does not have a <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a> that is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of the <a title="static type" class="termref" href="#dt-static-type">static type</a>
                  required for that operand, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is
                  raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p><p>Even though static typing can catch many <a title="type error" class="termref" href="#dt-type-error">type errors</a> before an expression is executed, it is possible for an expression to raise an error during evaluation that was not detected by static  analysis. For example, an expression may contain a cast of a string into an integer, which is statically valid. However, if the actual value of the string at run time cannot be cast into an integer, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> will result. Similarly, an expression may apply an arithmetic operator to a value whose <a title="static type" class="termref" href="#dt-static-type">static type</a> is <code>xs:untypedAtomic</code>. This is not a <a title="static error" class="termref" href="#dt-static-error">static error</a>, but at run time, if the value cannot be successfully cast to a <a title="numeric" class="termref" href="#dt-numeric">numeric</a> type, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> will be raised.</p></div></div><div class="div3">
<h4><a id="id-input-sources"/>2.3.4 <a href="#id-input-sources" style="text-decoration: none">Input Sources</a></h4><p>XQuery 4.0 has a set of functions that provide access to XML documents (<a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-doc"><code>fn:doc</code></a>, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-doc-available"><code>fn:doc-available</code></a>), collections (<a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collection"><code>fn:collection</code></a>, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-uri-collection"><code>fn:uri-collection</code></a>), text files (<a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-unparsed-text"><code>fn:unparsed-text</code></a>, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-unparsed-text-lines"><code>fn:unparsed-text-lines</code></a>, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-unparsed-text-available"><code>fn:unparsed-text-available</code></a>), and environment variables (<a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-environment-variable"><code>fn:environment-variable</code></a>, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-available-environment-variables"><code>fn:available-environment-variables</code></a>).  These functions are defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#fns-on-docs">17.1 Accessing external information</a>.</p><p>An expression can access input data either by calling one
               of these input functions or by referencing some part of the
               <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> that is initialized by the external
               environment, such as a <a title="variable values" class="termref" href="#dt-variable-values">variable</a> or
               <a title="context value" class="termref" href="#dt-context-value">context value</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The <a href="http://expath.org">EXPath Community Group</a> has developed a <a href="http://expath.org/spec/file">File Module</a>, which some implementations use to perform file system related operations 
                  such as reading or writing files and directories. Multiple files can be read or written 
                  from a single query.</p></div></div><div class="div3">
<h4><a id="id-serialization"/>2.3.5 <a href="#id-serialization" style="text-decoration: none">Serialization</a></h4><p>
                  [<a id="dt-serialization" title="serialization">Definition</a>: 
                     <b>Serialization</b> is the process of
converting an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM
instance</a> to a sequence of octets (step DM4 in Figure 1.),
as described in <a href="#xslt-xquery-serialization-40">[Serialization 4.0]</a>.]
               </p><p>Although serialization of XQuery results is outside
            the scope of this specification, syntax is provided in the query
            prolog to enable default serialization options to be defined.
            See <a href="#id-output-declarations"><b>5.22 Output Declarations</b></a>.</p><p>Serialization can also be invoked from within a query
               by calling the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-serialize"><code>fn:serialize</code></a> function.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>This definition of serialization is the definition
used in this specification. Any form of serialization that is
not based on <a href="#xslt-xquery-serialization-40">[Serialization 4.0]</a> is outside
the scope of the XQuery 4.0 specification.</p></div><p>An XQuery implementation is not required to provide a
serialization interface. For example, an implementation may 
provide only a DOM interface (see <a href="#DOM">[Document Object Model]</a>) or an interface
based on an event stream. </p></div><div class="div3">
<h4><a id="id-consistency-constraints"/>2.3.6 <a href="#id-consistency-constraints" style="text-decoration: none">Consistency Constraints</a></h4><p>In order for XQuery 4.0 to
be well defined, the input <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instances</a>, the <a title="static context" class="termref" href="#dt-static-context">static context</a>, and the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> must be mutually
consistent. The consistency constraints listed below are prerequisites
for correct functioning of an XQuery 4.0 implementation. Enforcement
of these consistency constraints is beyond the scope of this
specification. This specification does not
define the result of  <span class="xquery">a query</span>
                under any condition in which one
or more of these constraints is not satisfied.</p><ul><li><p>For every  node that has a type annotation, if that type annotation is found in the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a> (ISSD), then its definition in the ISSD must be 
                     <span>
                           <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-schema-compatible">compatible</a><sup><small>DM</small></sup>
                        </span> with its definition 
                     in the <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-schema">schema</a><sup><small>DM</small></sup> that was used to validate the node. 
                  </p></li><li><p>Every element name, attribute name, or schema type name referenced in <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a> or <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a>
                         must be in the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a>, unless it is an element name referenced as part of an <a href="#doc-xquery40-ElementTest">ElementTest</a> or an attribute name referenced as part of an <a href="#doc-xquery40-AttributeTest">AttributeTest</a>.</p></li><li><p>Any reference to a global element, attribute, or type name in
the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a> must have a corresponding element, attribute or type
definition in the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a>.</p></li><li><p>For each (variable, type) pair in <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a> and the corresponding (variable, value) pair in <a title="variable values" class="termref" href="#dt-variable-values">variable values</a> such that the variable names are equal, the value must match the type, using the matching rules in  <a href="#id-sequencetype-matching"><b>3.1.2 Sequence Type Matching</b></a>.</p></li><li class="xquery"><p>For each variable declared as external, if the variable declaration does
not include a <a href="#prod-xquery40-VarDefaultValue">VarDefaultValue</a>, the external environment must provide a value
for the variable.</p><p>For each variable declared as external for which the external environment
provides a value: If the variable declaration includes a declared type,
the value provided by the external environment must match the
declared type, using the matching rules in  <a href="#id-sequencetype-matching"><b>3.1.2 Sequence Type Matching</b></a>. If the variable declaration does not include a declared type, the
external environment must provide a type to accompany the value provided, using the same matching rules.</p></li><li class="xquery"><p>For each function declared as external: the function’s <a title="function item" class="termref" href="#dt-function-item">implementation</a> must either return a value that matches the declared result type,
using the matching rules in <a href="#id-sequencetype-matching"><b>3.1.2 Sequence Type Matching</b></a>, or raise an
<a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> error.</p></li><li class="xquery"><p>For a given query, define a <b>participating ISSD</b> as the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a> of a module that is used in evaluating the query.
                     All participating ISSDs must be <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-schema-compatible">compatible</a><sup><small>DM</small></sup>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>This rule ensures that when one module <var>M</var> imports schema <var>X</var>, and another
                     module <var>N</var> imports schema <var>Y</var>, then an element node validated
                        against type <var>T</var> in <var>M</var> can be safely passed to a function
                        in <var>N</var> that expects an argument of type <code>element(*, T)</code>.
                     The requirement for compatibility does not guarantee that in all cases, validation
                     of an element against the two different schemas will produce exactly the same outcome
                     (there may be differences, for example, in the definition of substitution groups
                     or wildcards), and the processor must allow for such differences.</p></div></li><li><p>In the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>, the prefix <code>xml</code> must not be bound to any namespace URI other than <code>http://www.w3.org/XML/1998/namespace</code>, and no prefix other than <code>xml</code> may be bound to this namespace URI.
The prefix <code>xmlns</code> must not be bound to any namespace URI, and no prefix may be bound to the namespace URI <code>http://www.w3.org/2000/xmlns/</code>.</p></li></ul></div></div><div class="div2">
<h3><a id="errors"/>2.4 <a href="#errors" style="text-decoration: none">Error Handling</a></h3><div class="div3">
<h4><a id="id-kinds-of-errors"/>2.4.1 <a href="#id-kinds-of-errors" style="text-decoration: none">Kinds of Errors</a></h4><p>
As described in <a href="#id-expression-processing"><b>2.3.3 Expression
Processing</b></a>, XQuery 4.0
defines a <a title="static analysis phase" class="termref" href="#dt-static-analysis">static analysis phase</a>, which does not depend on input
data, and a <a title="dynamic evaluation phase" class="termref" href="#dt-dynamic-evaluation">dynamic evaluation
phase</a>, which does depend on input
data.  Errors may be raised during each phase.</p><p>
                  [<a id="dt-static-error" title="static error">Definition</a>: 
An error that can be detected during the static analysis phase, and is not a type error, is a <b>static error</b>.] A syntax error is an example of a <a title="static error" class="termref" href="#dt-static-error">static error</a>.</p><p>
                  [<a id="dt-dynamic-error" title="dynamic error">Definition</a>: A <b>dynamic
error</b> is an error that
must be detected during the dynamic evaluation phase and may be detected
during the static analysis phase.]
Numeric overflow is an example of a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>.
            </p><p>
                  [<a id="dt-type-error" title="type error">Definition</a>: A <b>type
error</b> may be raised during the static analysis phase or the dynamic evaluation phase.
During the static analysis phase, a <a title="type error" class="termref" href="#dt-type-error">type error</a> occurs
when the <a title="static type" class="termref" href="#dt-static-type">static type</a> of an expression does not match the expected type
of the context in which the expression occurs.
During the dynamic evaluation phase, a <a title="type error" class="termref" href="#dt-type-error">type error</a> occurs
when the <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a> of a value does not match the expected type of
the context in which the value occurs.]
               </p><p>The outcome of the <a title="static analysis phase" class="termref" href="#dt-static-analysis">static analysis
phase</a> is either success or one or more <a title="type error" class="termref" href="#dt-type-error">type errors</a>, <a title="static error" class="termref" href="#dt-static-error">static errors</a>, or statically detected <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic errors</a>. The result of the <a title="dynamic evaluation phase" class="termref" href="#dt-dynamic-evaluation">dynamic evaluation
phase</a> is either a result value, a <a title="type error" class="termref" href="#dt-type-error">type
error</a>, or a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>.</p><p>If more than one error is present, or if an error condition comes within the
scope of more than one error defined in this specification, then any non-empty
subset of these errors may be reported.</p><p>If an implementation can determine during the
<a title="static analysis phase" class="termref" href="#dt-static-analysis">static
analysis phase</a> that <span class="xquery">a <a href="#prod-xquery40-QueryBody">QueryBody</a>
                  </span>
               , if evaluated, would necessarily
raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> or that an expression, if evaluated, would necessarily raise a <a title="type error" class="termref" href="#dt-type-error">type error</a>, the implementation may (but is not required to) report that
error during the <a title="static analysis phase" class="termref" href="#dt-static-analysis">static
analysis phase</a>.</p><p>An implementation can raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> for <span class="xquery">a <a href="#prod-xquery40-QueryBody">QueryBody</a>
                  </span>
                statically only if the <span class="xquery">query</span>
                can never execute without raising that error, as in the following example:</p><div class="exampleInner"><pre>
error()</pre></div><p>The following example contains a type error, which can be reported statically even if the implementation can not prove that the expression will actually be evaluated.</p><div class="exampleInner"><pre>
if (empty($arg))
then "cat" * 2
else 0</pre></div><p>
                  [<a id="dt-warning" title="warning">Definition</a>: In addition to <a title="static error" class="termref" href="#dt-static-error">static errors</a>, <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic errors</a>, and <a title="type error" class="termref" href="#dt-type-error">type
errors</a>, an XQuery 4.0
implementation may raise <b>warnings</b>, either during the <a title="static analysis phase" class="termref" href="#dt-static-analysis">static analysis
phase</a> or the
<a title="dynamic evaluation phase" class="termref" href="#dt-dynamic-evaluation">dynamic evaluation
phase</a>. The circumstances in which warnings are raised, and
the ways in which warnings are handled, are <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>.]
               </p><p>In addition to the errors defined in this
specification, an implementation may raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> for a reason beyond the scope of this specification. For
example, limitations may exist on the maximum
numbers or sizes of various objects. 
<span>An error must be raised if such a limitation is exceeded  [<a href="#ERRXPDY0130" title="err:XPDY0130">err:XPDY0130</a>].</span>
               </p></div><div class="div3">
<h4><a id="id-identifying-errors"/>2.4.2 <a href="#id-identifying-errors" style="text-decoration: none">Identifying and Reporting Errors</a></h4><p>The errors defined in this specification are identified by QNames that have the form 
               <code>err:XXYYnnnn</code>, where:</p><ul><li><p>
                        <code>err</code> denotes the namespace for XPath and XQuery errors, <code>http://www.w3.org/2005/xqt-errors</code>. This binding of the namespace prefix <code>err</code> is used for convenience in this document, and is not normative.</p></li><li class="xquery"><p>
                        <code>XX</code> denotes the language in which the error is defined, using the following encoding:</p><ul class="xquery"><li><p>
                              <code>XP</code> denotes an error defined by XPath. Such an error may also occur XQuery since XQuery  includes XPath as a subset.</p></li><li><p>
                              <code>XQ</code> denotes an error defined by XQuery (or an error originally defined by XQuery and later added to XPath).</p></li></ul></li><li><p>
                        <code>YY</code> denotes the error category, using the following encoding:</p><ul><li><p>
                              <code>ST</code> denotes a static error.</p></li><li><p>
                              <code>DY</code> denotes a dynamic error.</p></li><li><p>
                              <code>TY</code> denotes a type error.</p></li></ul></li><li><p>
                        <code>nnnn</code> is a unique numeric code.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>The namespace URI for  XPath and XQuery errors is not expected to
change from one version of <span class="xquery">XQuery</span>
                   to another. However, the contents of this
namespace may be extended to include additional error definitions.</p></div></div><div class="div3">
<h4><a id="id-handling-dynamic"/>2.4.3 <a href="#id-handling-dynamic" style="text-decoration: none">Handling Dynamic Errors</a></h4><p>Except as noted in this document, if any operand of an expression
raises a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>, the expression also raises a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>.
If an expression can validly return a value or raise a dynamic
error, the implementation may choose to return the value or raise
the dynamic error (see <a href="#id-errors-and-opt"><b>2.4.4 Errors and
      Optimization</b></a>).  For example, the logical expression
<code>expr1 and expr2</code> may return the value <code>false</code>
if either operand returns <code>false</code>,
or may raise a dynamic error if either operand raises a dynamic
error.</p><p> If more than one operand of an expression raises
an error, the
implementation may choose which error is raised by the expression.
For example, in this expression:

</p><div class="exampleInner"><pre>($x div $y) + xs:decimal($z)</pre></div><p>

both the sub-expressions <code>($x div $y)</code> and <code>xs:decimal($z)</code> may
raise an error.  The
implementation may choose which error is raised by the <code>+</code>
expression.  Once one operand raises an error, the implementation is
not required, but is permitted, to evaluate any other operands.</p><p>
                  [<a id="dt-error-value" title="error value">Definition</a>: In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called <b>error values</b>.] An implementation may provide a mechanism whereby an application-defined error handler can process error values and produce diagnostic messages. 
  <span class="xquery">XQuery 3.1 provides standard error handling via  section <a href="../xquery-40/xquery-40.html#id-try-catch">4.20 Try/Catch Expressions</a>.</span>
               </p><p>A dynamic error may be raised by a <a title="system function" class="termref" href="#dt-system-function">system
function</a> or operator.  For example,
the <code>div</code> operator raises an error if its operands are <code>xs:decimal</code> values and its second operand
is equal to zero. Errors raised by system functions and operators are defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> or the host language.</p><p>A dynamic error can also be raised explicitly by calling the
<a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-error"><code>fn:error</code></a> function, which always raises a dynamic error and never
returns a value.  This function is defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#func-error">21.1.1 fn:error</a>. For example, the following
function call raises a dynamic
error, providing a QName that identifies the error, a descriptive string, and a diagnostic value (assuming that the prefix <code>app</code> is bound to a namespace containing application-defined error codes):</p><div class="exampleInner"><pre>error( #app:err057, "Unexpected value", string($v) )</pre></div></div><div class="div3">
<h4><a id="id-errors-and-opt"/>2.4.4 <a href="#id-errors-and-opt" style="text-decoration: none">Errors and
      Optimization</a></h4><p>Because different implementations may
      choose to evaluate or optimize an expression in different ways,
      certain aspects of raising <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic errors</a> are <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>, as described in this section.</p><p>An implementation is always free to evaluate the operands of an operator in any order.</p><p>In some cases,  a processor can determine the result of an expression without accessing all the data that would be implied by the formal expression semantics. For example, the formal description of <a title="filter expression" class="termref" href="#dt-filter-expression">filter expressions</a> suggests that <code>$s[1]</code> should be evaluated by examining all the items in sequence <code>$s</code>, and selecting all those that satisfy the predicate <code>position()=1</code>. In practice, many implementations will recognize that they can evaluate this expression by taking the first item in the sequence and then exiting. If <code>$s</code> is defined by an expression such as <code>//book[author eq 'Berners-Lee']</code>, then this strategy may avoid a complete scan of a large document and may therefore greatly improve performance. However, a consequence of this strategy is that a dynamic error or type error that would be detected if the expression semantics were followed literally might not be detected at all if the evaluation exits early. In this example, such an error might occur if there is a <code>book</code> element in the input data with more than one <code>author</code> subelement.</p><p>The extent to which a processor may optimize its access to data, at the cost of not raising errors, is defined by the following rules.</p><p>Consider an expression <em>Q</em> that has an operand (sub-expression) <em>E</em>. In general the value of <em>E</em> is a sequence. At an intermediate stage during evaluation of the sequence, some of its items will be known and others will be unknown. If, at such an intermediate stage of evaluation, a processor is able to establish that there are only two possible outcomes of evaluating <em>Q</em>, namely the value <em>V</em> or an error, then the processor may deliver the result <em>V</em> without evaluating further items in the operand <em>E</em>. For this purpose, two values are considered to represent the same outcome if their items are pairwise the same, where nodes are the same if they have the same identity, and values are the same if they are equal and have exactly the same type.</p><p>There is an exception to this rule: If a processor evaluates an operand <em>E</em> (wholly or in part), then it  is required to establish that the actual value of the operand <em>E</em> does not violate any constraints on its cardinality. For example, the expression <code>$e eq 0</code> results in a type error if the value of <code>$e</code> contains two or more items. A processor is not allowed to decide, after evaluating the first item in the value of <code>$e</code> and finding it equal to zero, that the only possible outcomes are the value <code>true</code> or a type error caused by the cardinality violation. It must establish that the value of <code>$e</code> contains no more than one item.</p><p>These rules apply to all the operands of an expression considered in combination: thus if an expression has two operands <em>E1</em> and <em>E2</em>, it may be evaluated using any samples of the respective sequences that satisfy the above rules.</p><p>The rules cascade: if <em>A</em> is an operand of <em>B</em> and <em>B</em> is an operand of <em>C</em>, then the processor needs to evaluate only a sufficient sample of <em>B</em> to determine the value of <em>C</em>, and needs to evaluate only a sufficient sample of <em>A</em> to determine this sample of <em>B</em>.</p><p>The effect of these rules is that the processor is free to stop examining further items in a sequence as soon as it can establish that further items would not affect the result except possibly by causing an error. For example, the processor may return <code>true</code> as the result of the expression <code>S1 = S2</code> as soon as it finds a pair of equal values from the two sequences.</p><p>Another consequence of these rules is that where none of the items in a sequence contributes to the result of an expression, the processor is not obliged to evaluate any part of the sequence. Again, however, the processor cannot dispense with a required cardinality check: if an empty sequence is not permitted in the relevant context, then the processor must ensure that the operand is not an empty sequence.</p><p>Examples:</p><ul><li><p>If an implementation can find (for example, by using an index) that at
least one item returned by <code>$expr1</code> in the following example has the value <code>47</code>, it is allowed to
return <code>true</code> as the result of the <code>some</code> expression, without searching for
another item returned by <code>$expr1</code> that would raise an error if it were evaluated.
</p><div class="exampleInner"><pre>some $x in $expr1 satisfies $x = 47</pre></div></li><li><p>In the following example, if an implementation can find (for example, by using an index) the
<code>product</code> element-nodes that have an <code>id</code> child with the value <code>47</code>, it is allowed to return these nodes as the
result of the <a title="path expression" class="termref" href="#dt-path-expression">path expression</a>, without searching for another <code>product</code> node that
would raise an error because it has an <code>id</code> child whose value is not an integer.</p><div class="exampleInner"><pre>//product[id = 47]</pre></div></li></ul><p>For a variety of reasons, including optimization, implementations
          may rewrite expressions into a different
          form. There are a number of rules that limit the extent of this freedom:
          </p><ul><li><p>
                Other than the raising or not raising of errors, the result
                of evaluating a rewritten expression must
                conform to the semantics
                defined in this specification for the original expression.
             </p><div class="note"><p class="prefix"><b>Note:</b></p><p>
                This allows an implementation to return a result in cases where the
                original expression would have raised an error, or to raise an error in cases
                where the original expression would have returned a result. The main cases
                where this is likely to arise in practice are (a) where a rewrite changes the
                order of evaluation, such that a subexpression causing an error is evaluated
                when the expression is written one way and is not evaluated when the expression
                is written a different way, and (b) where intermediate results of the
                evaluation cause overflow or other out-of-range conditions.
             </p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>
                This rule does not mean that the result of the expression will always
                be the same in non-error cases as if it had not been rewritten, because there
                are many cases where the result of an expression is to some degree
                <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>
                or <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>.
             </p></div></li><li><p>
                     The rules described in <a href="#id-guarded-expressions"><b>2.4.5 Guarded Expressions</b></a> ensure that for
                     certain kinds of expression (for example conditional expressions), changing the
                     order of evaluation of subexpressions does not result in dynamic errors that
                     would not otherwise occur.</p></li><li><p>
                Expressions must not be rewritten in such a way
                as to create or remove static errors.

                The static errors in this specification are defined
                for the original expression, and must be preserved if
                the expression is rewritten.</p></li><li><p>
                     As stated earlier, an expression
                     must not be rewritten to dispense with a
                     required cardinality check: for example, <code>string-length(//title)</code>
                     must raise an
                     error if the document contains more than one title element.
                  </p></li></ul></div><div class="div3">
<h4><a id="id-guarded-expressions"/>2.4.5 <a href="#id-guarded-expressions" style="text-decoration: none">Guarded Expressions</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-implausible-expressions">⬇</a> <a href="#id-processing-model">⬆</a></p><ol><li><p>
                  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 <code>and</code> and <code>or</code>,
                  and of predicates in filter expressions, in a way that might allow the processor to raise dynamic
                  errors that the author intended to prevent.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/71">71</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/230">230</a> 15 November 2022]</i></p></li></ol></div><p>
                  [<a id="dt-guarded" title="guarded">Definition</a>: An expression <var>E</var> is said to be <b>guarded</b>
               by some governing condition <var>C</var> if evaluation of <var>E</var> is not allowed to fail
               with a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> except when <var>C</var> applies.]
               </p><p>For example, in a conditional expression <code>if (P) then T else F</code>, the subexpression
               <var>T</var> is guarded by <var>P</var>, and the subexpression <var>F</var> is guarded by
               <code>not(P)</code>. One way an implementation can satisfy this rule is by not evaluating <var>T</var> unless <var>P</var>
               is true, and likewise not evaluating <var>F</var> unless <var>P</var> is false. Another
               way of satisfying the rule is for the implementation to evaluate all the subexpressions, but to catch any errors that occur 
               in a guarded subexpression so they are not propagated.
            </p><p>The existence of this rule enables errors to be prevented by writing expressions such as
            <code>if ($y eq 0) then "N/A" else ($x div $y)</code>. This example will never fail with a divide-by-zero
            error because the <code>else</code> branch of the conditional is <a title="guarded" class="termref" href="#dt-guarded">guarded</a>.</p><p>Similarly, in the mapping expression <code>
                     <var>E<sub>1</sub></var>!<var>E<sub>2</sub></var>
                  </code>, the subexpression <var>E<sub>2</sub></var> is guarded
            by the existence of an item from <var>E<sub>1</sub></var>. This means, for example, that the expression <code>(1 to $n)!doc('bad.xml')</code>
            must not raise a dynamic error if <code>$n</code> is zero. The rule governing evaluation of guarded expressions
               is phrased so as not to disallow “loop-lifting” or “constant-folding” optimizations 
               whose aim is to avoid repeated evaluation of a common subexpression;
            but such optimizations must not result in errors that would not otherwise occur.</p><p>The complete list of expressions that have guarded subexpressions is as follows:</p><ul><li><p>In a conditional expression (<a href="#doc-xquery40-IfExpr">IfExpr</a>) the <code>then</code> branch
                  is guarded by the condition being true, and the <code>else</code> branch
                  is guarded by the condition being false.</p></li><li class="xquery"><p>In a <code>switch</code> expression (<a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>), 
               the <code>return</code> expression of a particular <code>case</code> is guarded by the condition for that case
               matching, and no earlier case matching.</p></li><li class="xquery"><p>In a <code>typeswitch</code> expression (<a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>), 
                  the <code>return</code> expression of a particular <code>case</code> is guarded by the condition for that case
                  matching, and no earlier case matching.</p></li><li><p>In an <a title="and expression" class="termref" href="#dt-and-expression">and expression</a>, the second operand
               is guarded by the value of the first operand being true.</p></li><li><p>In an <a title="or expression" class="termref" href="#dt-or-expression">or expression</a>, the second operand
                  is guarded by the value of the first operand being false.</p></li><li><p>In an <code>otherwise</code> expression (<a href="#doc-xquery40-OtherwiseExpr">OtherwiseExpr</a>), the second operand
                  is guarded by the value of the first operand being an empty sequence.</p></li><li><p>In a path expression of the form <code>
                           <var>E<sub>1</sub></var>/<var>E<sub>2</sub></var>
                        </code> 
                  or <code>
                           <var>E<sub>1</sub></var>//<var>E<sub>2</sub></var>
                        </code>, and in a mapping
               expression of the form <code>
                           <var>E<sub>1</sub></var>!<var>E<sub>2</sub></var>
                        </code>, the right-hand operand <var>E<sub>2</sub></var> is guarded by
               the existence of at least one item in the result of evaluating <var>E<sub>1</sub></var>.</p><p>This rule applies even if <var>E<sub>2</sub></var> does not reference the context value.
                     For example, no dynamic error can be thrown by the expression 
               <code>(1 to $n)!doc('bad.xml')</code> in the case where <code>$n</code> is zero.</p></li><li><p>In a filter expression of the form <code>
                           <var>E</var>[<var>P</var>]</code>, 
                  the predicate <var>P</var> is guarded by
                  the existence of at least one item in the result of evaluating <var>E</var>.</p><p>This rule has the consequence that in a filter expression with multiple predicates, 
                  such as <code>
                           <var>E</var>[<var>P<sub>1</sub></var>][<var>P<sub>2</sub></var>]</code>,
               evaluation of <var>P<sub>2</sub></var> must not raise a dynamic error unless <var>P<sub>1</sub></var> returns <code>true</code>. This rule does
               not prevent reordering of predicates (for example, to take advantage of indexes), but it does require that any
               such reordering must not result in errors that would not otherwise occur.</p></li><li><p>In a <code>FLWOR</code> expression (<a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>), an expression
                     that is logically dependent on the tuples in the tuple stream is guarded by the existence
                     of a relevant tuple. This applies even where the expression does not actually reference
                     any of the variable bindings in the tuple stream. For example, in the expression
                     <code>for $x in <var>S</var> return <var>E</var>
                        </code>, the expression 
                     <var>E</var> is guarded by the existence of
                        an item bound to <code>$x</code>.</p><p>This means that the expression <code>for $x in 1 to $n return doc('bad.xml')</code>
               must not raise a dynamic error in the case where <code>$n</code> is zero.</p></li><li><p>In a <code>quantified</code> expression (<a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>) such
                  as <code>some $x in <var>S</var> satisfies <var>P</var>
                        </code>, the expression 
                  <var>P</var> is guarded by the existence of
                     an item bound to <code>$x</code>.</p></li></ul><p>The fact that an expression is <a title="guarded" class="termref" href="#dt-guarded">guarded</a> does not remove the obligation to report
            <a title="static error" class="termref" href="#dt-static-error">static errors</a> in the expression; nor does it remove the option
            to report statically detectable <a title="type error" class="termref" href="#dt-type-error">type errors</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>These rules do not constrain the order of evaluation of subexpressions. For example, given an expression
                  such as <code>//person[@first = "Winston"][@last = "Churchill"]</code>, or equivalently
                  <code>//person[@first = "Winston" and @last = "Churchill"]</code>, an implementation might use an index on the value of
                  <code>@last</code> to select items that satisfy the second condition, and then filter these
                  items on the value of the first condition. Alternatively, it might evaluate both predicates in parallel.
                  Or it might interpose an additional redundant condition: 
                  <code>//person[string-length(@first) + string-length(@last) = 16][@first = "Winston"][@last = "Churchill"]</code>.
                  But implementations must ensure that
                  such rewrites do not result in dynamic errors being reported that would not occur if the predicates
                  were evaluated in order as written.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Although the rules for guarded expressions prevent optimizations resulting in spurious errors, 
                  they do not prevent optimizations whose effect is to mask errors. For example, the rules guarantee that
                  <code>("A", 3)[. instance of xs:integer][. eq 3]</code> will not raise an error caused by the comparison
                  <code>("A" eq 3)</code>, but they
                  do not guarantee the converse: the expression <code>("A", 3)[. eq 3][. instance of xs:integer]</code>
                  may or may not raise a dynamic error.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The rules in this section do not disallow all expression rewrites that might result in dynamic
                  errors. For example, rewriting <code>($x - $y + $z)</code> as <code>($x + $z - $y)</code> is permitted
               even though it might result in an arithmetic overflow.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Some implementations allow calls on external functions that have side-effects. The semantics of
               such function calls are entirely <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation defined</a>. Processors <span class="verb">may</span>
               choose to reference the rules for <a title="guarded" class="termref" href="#dt-guarded">guarded</a> expressions when defining the behavior
               of such function calls, but this is outside the scope of the language specification.</p></div></div><div class="div3">
<h4><a id="id-implausible-expressions"/>2.4.6 <a href="#id-implausible-expressions" style="text-decoration: none">Implausible Expressions</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-choice-item-types">⬇</a> <a href="#id-guarded-expressions">⬆</a></p><ol><li><p>
                  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 <code>@price/@value</code>, even though dynamic evaluation
                  is defined to return an empty sequence rather than an error.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/602">602</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/603">603</a> 25 July 2023]</i></p></li></ol></div><p>
                  [<a id="dt-implausible" title="implausible">Definition</a>: Certain expressions, while not
            erroneous, are classified as being <b>implausible</b>,
            because they achieve no useful effect.]
               </p><p>An example of an implausible expression is <code>@code/text()</code>. This expression
            will always evaluate to an empty sequence, because attribute nodes cannot have text
            node children. The semantics of the expression are well defined, but it is likely
            that the user writing this expression intended something different: if they wanted to write an 
            expression that evaluated to an empty sequence, there would be easier ways to write it.</p><p>Where an expression is classified (by rules in this specification) as being
            <a title="implausible" class="termref" href="#dt-implausible">implausible</a>, a processor <span class="verb">may</span> (but is
            not <span class="verb">required</span> to) raise a static error.</p><p>For reasons of backwards compatibility and interoperability, and to facilitate
            automatic generation of XQuery 4.0 code, a processor <span class="verb">must</span> 
            provide a mode of operation in which <a title="implausible" class="termref" href="#dt-implausible">implausible</a>
            expressions are not treated as static errors, but are evaluated
            with the defined semantics for the expression.</p><p>Some other examples of implausible expressions include:</p><ul><li><p>
                        <code>round(tokenize($input))</code>. The result of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-tokenize"><code>fn:tokenize</code></a>
               is a sequence of strings (<code>xs:string*</code>), while the required type for the
               first argument of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-round"><code>fn:round</code></a> is optional numeric (<code>xs:numeric?</code>).
               The expression can succeed only in the exceptional case where the result of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-tokenize"><code>fn:tokenize</code></a>
               is an empty sequence, in which case the result of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-round"><code>fn:round</code></a> will also be
               an empty sequence; it is therefore highly likely that the expression was written in error.</p></li><li><p>
                        <code>parse-csv($input)?column-names</code>. The signature of the <code>parse-csv</code>
               function declares its return type as <code>record(columns, rows)</code>. There is no field in this
               record named <code>column-names</code>, and therefore the lookup expression will always
               return an empty sequence. Again, there is no good reason that a user would write this,
               so it is likely that it was written in error.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>The specification is deliberately conservative in the choice of constructs that have
            been classified as implausible. Constructs have not been classified as implausible merely because there
            are better ways of writing the same thing, but only in cases where it is considered that no user in full understanding
            of the specification would intentionally write such a construct. All these cases correspond to situations
            that would be classed as errors in a language with stricter static typing rules.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>In many cases the classification of constructs as implausible is designed to protect users
            from usability problems that have been found with earlier versions of the language. without
            introducing backwards incompatibilities.</p></div></div></div><div class="div2">
<h3><a id="id-important-concepts"/>2.5 <a href="#id-important-concepts" style="text-decoration: none">Concepts</a></h3><p>This section explains some concepts that are important to the processing of XQuery 4.0 expressions.</p><div class="div3">
<h4><a id="id-document-order"/>2.5.1 <a href="#id-document-order" style="text-decoration: none">Document Order</a></h4><p>An ordering called <b>document order</b> is defined among all the 
               nodes accessible during processing of a given <span class="xquery">query</span>
               , which may consist of one or more <b>trees</b> (documents or fragments).</p><p>Document order applies both to <a title="XNode" class="termref" href="#dt-XNode">XNodes</a> (typically
               corresponding to nodes in an XML document, and generally referred to simply as <b>nodes</b>),
               and also to <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-JNode">JNodes</a><sup><small>DM</small></sup>, often corresponding to the contents
               of a JSON source text. These are known collectively as 
               <a title="GNode" class="termref" href="#dt-GNode">GNodes</a> (for "generalized node").</p><p>Document order is defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#document-order">6.2 Document Order</a>, and its definition is repeated here for convenience. 

Document order is a total ordering, although the relative order of some nodes is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>.  

[<a id="dt-document-order" title="document order">Definition</a>: Informally, <b>document order</b> is the order in which nodes appear in the XML serialization of a document.]
                  [<a id="stable" title="stable">Definition</a>: Document order is <b>stable</b>, which means that the relative order of two nodes will not change during the processing of a given <span class="xquery">query</span>
                  , even if this order is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>.]
                  [<a id="dt-reverse-document-order" title="reverse document order">Definition</a>: The node ordering that is the reverse of document order is called <b>reverse document order</b>.]
               </p><p>Within an <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-XTree">XTree</a><sup><small>DM</small></sup>,
               (that is, a tree consisting of XNodes), document order satisfies the following constraints:</p><ol class="enumar"><li><p>The root node precedes all other nodes.</p></li><li><p>A parent node precedes its children (and therefore its descendants).</p></li><li><p>The children of a node <var>N</var> precede the following siblings of <var>N</var>.</p></li><li><p>Attribute nodes immediately follow the namespace nodes of the
element node with which they are associated. The relative order of
attribute nodes is stable but <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>.</p></li><li><p>The relative order of siblings is the order in which they occur
in the <code>children</code> property of their parent node.</p></li></ol><p>Similarly, within an <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-JTree">JTree</a><sup><small>DM</small></sup>,
               (that is, a tree consisting of JNodes), document order satisfies the following constraints:</p><ol class="enumar"><li><p>The root JNode precedes all other JNodes.</p></li><li><p>A parent JNode precedes its children (and therefore its descendants).</p></li><li><p>The children of a JNode <var>N</var> precede the following siblings of <var>N</var>.</p></li><li><p>The children of a JNode that wraps an array follow the ordering of the members of the array.</p></li><li><p>The children of a JNode that wraps a map follow the ordering of the entries in the map.</p></li></ol><p>The relative order of nodes in distinct trees is stable but
<a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>,
subject to the following constraint: If any node in a given tree T1 is before
any node in a different tree T2, then all nodes in tree T1 are before all nodes in
tree T2.</p></div><div class="div3">
<h4><a id="id-typed-value"/>2.5.2 <a href="#id-typed-value" style="text-decoration: none">Typed Value and String Value</a></h4><p>Every node (that is, every <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-XNode">XNode</a><sup><small>DM</small></sup>)
               has a <b>typed value</b> and a <b>string value</b>, except for nodes whose value is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>.
               
               [<a id="dt-typed-value" title="typed value">Definition</a>: The <b>typed
                     value</b> of a node is a sequence of atomic items and can be
                  extracted by applying the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-data"><code>data</code></a> function to the
                  node.]
                  [<a id="dt-string-value" title="string value">Definition</a>: The
                  <b>string value</b> of a node is a string and can be extracted
                  by applying the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-string"><code>string</code></a>
                  function to the node.]
               </p><p>An implementation may store both the <a title="typed value" class="termref" href="#dt-typed-value">typed value</a> and the <a title="string value" class="termref" href="#dt-string-value">string value</a> of a node, or it may store only one of these and derive the other as needed.
               The string value of a node must be a valid lexical representation of the typed value of the node,
               but the node is not required to preserve the string representation from the original source document.
               For example, if the typed value of a node is the <code>xs:integer</code> value <code>30</code>,
               its string value might be <code>"30"</code> or <code>"0030"</code>.</p><p>The <a title="typed value" class="termref" href="#dt-typed-value">typed value</a>, <a title="string value" class="termref" href="#dt-string-value">string value</a>, and <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> of a node are closely related, and are defined by rules found in the following locations:</p><ul class="xquery"><li><p>If the node was created by mapping from an Infoset or PSVI, see rules in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#types">4.1 Schema Information</a>.</p></li><li><p>If the node was created by an XQuery node constructor, see rules in <a href="#id-element-constructor"><b>4.12.1 Direct Element Constructors</b></a>, <a href="#id-computedElements"><b>4.12.3.1 Computed Element Constructors</b></a>, or <a href="#id-computedAttributes"><b>4.12.3.2 Computed Attribute Constructors</b></a>.</p></li><li><p>If the node was created by a <code>validate</code> expression, see rules in <a href="#id-validate"><b>4.25 Validate Expressions</b></a>.</p></li></ul><p>The relationship between <a title="typed value" class="termref" href="#dt-typed-value">typed value</a> and
               <a title="string value" class="termref" href="#dt-string-value">string value</a> for various kinds of nodes is summarized and illustrated
               by examples below.</p><ol class="enumar"><li><p>For text and document nodes, the typed value of the node is the same as its
                     string value, as an instance of  the type <code>xs:untypedAtomic</code>. The
                     string value of a document node is formed by concatenating the string
                     values of all its descendant text nodes, in <a title="document order" class="termref" href="#dt-document-order">document
                        order</a>.</p></li><li><p>The typed value of a comment or processing instruction node is the same as its string value. It is an instance of the type <code>xs:string</code>.</p></li><li><p>The typed value of an attribute node with
                     the <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a>
                        <code>xs:anySimpleType</code> or <code>xs:untypedAtomic</code> is the same as its
                     string value, as an instance of <code>xs:untypedAtomic</code>. The
                     typed value of an attribute node with any other type annotation is
                     derived from its string value and type annotation using the lexical-to-value-space mapping defined in <a href="#XMLSchema10">[XML Schema 1.0]</a> or <a href="#XMLSchema11">[XML Schema 1.1]</a> Part 2 for
                     the relevant type.</p><p>Example: A1 is an attribute
                     having string value <code>"3.14E-2"</code> and type annotation
                     <code>xs:double</code>.  The typed value of A1 is the
                     <code>xs:double</code> value whose lexical representation is
                     <code>3.14E-2</code>. </p><p>Example: A2 is an attribute with type
                     annotation <code>xs:IDREFS</code>, which is a list datatype whose item type is the atomic datatype <code>xs:IDREF</code>. Its string value is
                     <code>"bar baz faz"</code>. The typed value of A2 is a sequence of
                     three atomic items (<code>"bar"</code>, <code>"baz"</code>",
                     <code>"faz"</code>"), each of type <code>xs:IDREF</code>. The typed
                     value of a node is never treated as an instance of a named list
                     type. Instead, if the type annotation of a node is a list type (such
                     as <code>xs:IDREFS</code>), its typed value is treated as a sequence
                     of the <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a> from which it is derived (such as
                     <code>xs:IDREF</code>).</p></li><li><p>For an element node, the
                     relationship between typed value and string value depends on the
                     node’s <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a>, as follows:</p><ol class="enumla"><li><p>If the type annotation is <code>xs:untyped</code> or <code>xs:anySimpleType</code> or
                           denotes a complex type with mixed content (including <code>xs:anyType</code>), then the typed value of the
                           node is equal to its string value, as an instance of
                           <code>xs:untypedAtomic</code>.  However, if the <code>nilled</code>
                           property of the node is <code>true</code>, then its typed value is the empty sequence.</p><p>Example: E1 is an element node
                           having type annotation <code>xs:untyped</code> and string value
                           <code>"1999-05-31"</code>. The typed value of E1 is
                           <code>"1999-05-31"</code>, as an instance of
                           <code>xs:untypedAtomic</code>.</p><p>Example: E2 is an element node
                           with the type annotation <code>formula</code>, which is a complex type
                           with mixed content. The content of E2 consists of the character
                           <code>H</code>, a child element named <code>subscript</code> with
                           string value <code>"2"</code>, and the character <code>O</code>. The
                           typed value of E2 is <code>"H2O"</code> as an instance of
                           <code>xs:untypedAtomic</code>.</p></li><li><p>If the type
                           annotation denotes a simple type or a complex type with simple
                           content, then the typed value of the node is derived from its string
                           value and its type annotation in a way that is consistent with schema
                           validation. However, if the <code>nilled</code>
                           property of the node is <code>true</code>, then its typed value is the empty sequence.</p><p>Example: E3 is an element node with the type
                           annotation <code>cost</code>, which is a complex type that has several
                           attributes and a simple content type of <code>xs:decimal</code>. The
                           string value of E3 is <code>"74.95"</code>. The typed value of E3 is
                           <code>74.95</code>, as an instance of
                           <code>xs:decimal</code>.</p><p>Example: E4 is an element node with the
                           type annotation <code>hatsizelist</code>, which is a simple type
                           derived from the <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a>
                              <code>hatsize</code>, which in turn is
                           derived from <code>xs:integer</code>. The string value of E4 is
                           <code>"7 8 9"</code>. The typed value of E4 is a sequence of three
                           values (<code>7</code>, <code>8</code>, <code>9</code>), each of type
                           <code>hatsize</code>.</p><p>Example: E5 is an element node with the type annotation <code>my:integer-or-string</code>
                           which is a union type with member types <code>xs:integer</code> and <code>xs:string</code>.
                           The string value of E5 is <code>"47"</code>. The typed value of E5 is <code>47</code> as a
                           <code>xs:integer</code>, since <code>xs:integer</code> is the member type that validated the
                           content of E5. In general, when the type annotation of a node is a union type,
                           the typed value of the node will be an instance of one of the member types of the union.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>If an implementation stores only the string value of a node, and the type annotation of the node is a union type, the implementation must be able to deliver the typed value of the node as an instance of the appropriate member type.</p></div></li><li><p>If the type annotation
                           denotes a complex type with empty content, then the typed value of the
                           node is the empty sequence and its string value is the zero-length string.</p></li><li><p>If the type annotation
                           denotes a complex type with element-only content, then the typed value
                           of the node is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>. The <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-data"><code>fn:data</code></a> function raises a
                           <a title="type error" class="termref" href="#dt-type-error">type error</a>
                              [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFOTY0012" title="err:FOTY0012">err:FOTY0012</a>]<sup><small>FO40</small></sup> when applied to such a node. The string value of such a node is equal to the concatenated string values of all its text node descendants, in document order.</p><p>Example: E6 is an
                           element node with the type annotation <code>weather</code>, which is a
                           complex type whose content type specifies
                           <code>element-only</code>. E6 has two child elements named
                           <code>temperature</code> and <code>precipitation</code>. The typed
                           value of E6 is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>, and the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-data"><code>fn:data</code></a> function
                           applied to E6 raises an error.
                        </p></li></ol></li></ol></div><div class="div3">
<h4><a id="id-atomization"/>2.5.3 <a href="#id-atomization" style="text-decoration: none">Atomization</a></h4><p>The semantics of some
XQuery 4.0 operators depend on a process called <a title="atomization" class="termref" href="#dt-atomization">atomization</a>. Atomization is
applied to a value when the value is used in a context in which a
sequence of atomic items is required. The result of atomization is
either a sequence of atomic items or a <a title="type error" class="termref" href="#dt-type-error">type error</a>
                  [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFOTY0012" title="err:FOTY0012">err:FOTY0012</a>]<sup><small>FO40</small></sup>.  [<a id="dt-atomization" title="atomization">Definition</a>: 
                     <b>Atomization</b> of a sequence
is defined as the result of invoking the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-data"><code>fn:data</code></a> function, as defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#func-data">12.1.6 fn:data</a>.]
               </p><p> The semantics of
<a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-data"><code>fn:data</code></a> are repeated here for convenience. The result of
<a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-data"><code>fn:data</code></a> is the sequence of atomic items produced by
applying the following rules to each item in the input
sequence:</p><ul><li><p>If the item is an atomic item, it is
returned.</p></li><li><p>If the item is a node (specifically, an <a title="XNode" class="termref" href="#dt-XNode">XNode</a>),
its <a title="typed value" class="termref" href="#dt-typed-value">typed value</a> is returned (a <a title="type error" class="termref" href="#dt-type-error">type error</a>
                        [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFOTY0012" title="err:FOTY0012">err:FOTY0012</a>]<sup><small>FO40</small></sup> is raised if the node has no typed value.)</p></li><li><p>If the item is a <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-JNode">JNode</a><sup><small>DM</small></sup>,
                  its <b>·content·</b> property is atomized and the result is returned.</p></li><li><p>If the item is a <a title="function item" class="termref" href="#dt-function-item">function item</a> (other than an array) or map a <a title="type error" class="termref" href="#dt-type-error">type error</a>
                        [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFOTY0013" title="err:FOTY0013">err:FOTY0013</a>]<sup><small>FO40</small></sup> is raised.</p></li><li><p>If the item is an array <code>$a</code>, atomization is defined as <code>$a?* ! fn:data(.)</code>, which is equivalent to atomizing the members of the array.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>This definition recursively atomizes members that are arrays. Hence, the result of atomizing the array <code>[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]</code> is the sequence <code>(1, 2, 3, 4, 5, 6)</code>.</p></div></li></ul><p>Atomization is used in
processing many expressions that are designed to operate on atomic items, including: </p><ul><li><p>Arithmetic expressions</p></li><li><p>Comparison expressions</p></li><li><p>Function calls and returns</p></li><li><p>Cast expressions</p></li><li class="xquery"><p>Constructor expressions for various kinds of nodes</p></li><li class="xquery"><p>
                        <code>order by</code> clauses in FLWOR expressions</p></li><li class="xquery"><p>
                        <code>group by</code> clauses in FLWOR expressions</p></li><li class="xquery"><p>Switch expressions</p></li></ul><p>Atomization plays an important role in the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a> used
            when converting a supplied argument in a function call to the type declared
            in the function signature.</p></div><div class="div3">
<h4><a id="id-ebv"/>2.5.4 <a href="#id-ebv" style="text-decoration: none">Effective Boolean Value</a></h4><p>Under certain circumstances (some of which are listed below), it is necessary to find
the <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> of a
value. [<a id="dt-ebv" title="effective boolean value">Definition</a>: The
<b>effective boolean value</b> of a value is defined as the result
of applying the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean"><code>fn:boolean</code></a> function to the value.]
               </p><p>The dynamic semantics of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean"><code>fn:boolean</code></a> are repeated here for convenience:</p><ol class="enumar"><li><p>If its operand is an empty sequence, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean"><code>fn:boolean</code></a> returns <code>false</code>.</p></li><li><p>If its operand is a sequence whose first item is a 
                     <a title="GNode" class="termref" href="#dt-GNode">GNode</a>, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean"><code>fn:boolean</code></a> returns 
                     <code>true</code>.</p></li><li><p>If its operand is a <a title="singleton" class="termref" href="#dt-singleton">singleton</a> value of 
                     type <code>xs:boolean</code> or derived from <code>xs:boolean</code>, 
                     <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean"><code>fn:boolean</code></a> returns the value of its operand unchanged.</p></li><li><p>If its operand is a <a title="singleton" class="termref" href="#dt-singleton">singleton</a> value of 
                     type <code>xs:string</code>, <code>xs:anyURI</code>, 
                     <code>xs:untypedAtomic</code>, or a type derived from one of these,
                     <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean"><code>fn:boolean</code></a> returns <code>false</code> 
                     if the operand value has zero length; otherwise it returns <code>true</code>.</p></li><li><p>If its operand is a <a title="singleton" class="termref" href="#dt-singleton">singleton</a> value of 
                     any <a title="numeric" class="termref" href="#dt-numeric">numeric</a> type or derived from a numeric
                     type, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean"><code>fn:boolean</code></a> returns <code>false</code> 
                     if the operand value is <code>NaN</code> or is numerically 
                     equal to zero; otherwise it returns <code>true</code>.</p></li><li><p>In all other cases, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean"><code>fn:boolean</code></a> raises a type error [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFORG0006" title="err:FORG0006">err:FORG0006</a>]<sup><small>FO40</small></sup>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>For instance, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean"><code>fn:boolean</code></a> raises a type error if the operand is a function, a map, or an array.</p></div></li></ol><p>The <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> of a sequence is computed implicitly during  processing of the following types of expressions: </p><ul><li><p>Logical expressions (<code>and</code>, <code>or</code>)</p></li><li><p>The <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-not"><code>fn:not</code></a> function</p></li><li class="xquery"><p>The <code>where</code> clause of a FLWOR expression</p></li><li><p>Certain types of <a title="" class="termref" href="#dt-predicate">predicates</a>, such as <code>a[b]</code>
                     </p></li><li><p>Conditional expressions (<code>if</code>)</p></li><li><p>Quantified expressions (<code>some</code>, <code>every</code>)</p></li><li class="xquery"><p>
                        <a href="#prod-xquery40-WindowStartCondition">WindowStartCondition</a> and <a href="#prod-xquery40-WindowEndCondition">WindowEndCondition</a> in <code>window</code> clauses.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>The definition of <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean
  value</a> is <em>not</em> used when casting a value to the
  type <code>xs:boolean</code>, for example in a <code>cast</code>
  expression. It also plays no role in the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>
  used when passing a value to a function whose signature declares a
  parameter of type <code>xs:boolean</code>.</p></div></div><div class="div3">
<h4><a id="id-uri-literals"/>2.5.5 <a href="#id-uri-literals" style="text-decoration: none">URI Literals</a></h4><p>XQuery 4.0 requires a statically known, valid URI in <span class="xquery">a <a href="#prod-xquery40-URILiteral">URILiteral</a> or
      </span>a <a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>. 

      An implementation may raise a <a title="static error" class="termref" href="#dt-static-error">static error</a>
                  [<a href="#ERRXQST0046" title="err:XQST0046">err:XQST0046</a>] if the value of <span class="xquery">a
      URI Literal or</span> a Braced URI Literal is of nonzero length
      and is neither an
      absolute URI nor a relative URI.</p><p>As in a string literal, any <a title="predefined entity reference" class="termref" href="#dt-predefined-entity-reference">predefined entity
      reference</a> (such as <code>&amp;amp;</code>), <a title="character reference" class="termref" href="#dt-character-reference">character reference</a> (such
      as <code>&amp;#x2022;</code>), or <a href="#prod-xquery40-EscapeQuot">EscapeQuot</a> or <a href="#prod-xquery40-EscapeApos">EscapeApos</a> (for example, <code>""</code>)
      is replaced by its appropriate expansion. Certain characters,
      notably the ampersand, can only be represented using a <a title="predefined entity reference" class="termref" href="#dt-predefined-entity-reference">predefined entity
      reference</a> or a <a title="character reference" class="termref" href="#dt-character-reference">character reference</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The <code>xs:anyURI</code>
      type is designed to anticipate the introduction of
      Internationalized Resource Identifiers (IRIs) as defined in
      <a href="#RFC3987">[RFC3987]</a>.</p></div><p>Whitespace is normalized using the whitespace normalization rules
      of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-normalize-space"><code>fn:normalize-space</code></a>. If the result of whitespace
      normalization contains only whitespace, the corresponding URI
      consists of the empty string.  <span class="xquery">Whitespace
      normalization is done after the expansion of <a title="character reference" class="termref" href="#dt-character-reference">character references</a>, so
      writing a newline (for example) as <code>&amp;#xA;</code> does
      not prevent its being normalized to a space
      character.</span>
               </p><p>A Braced URI Literal or URI Literal is not
      subjected to percent-encoding
      or decoding as defined in <a href="#RFC3986">[RFC3986]</a>.</p></div><div class="div3">
<h4><a id="id-resolve-relative-uri"/>2.5.6 <a href="#id-resolve-relative-uri" style="text-decoration: none">Resolving a Relative URI Reference</a></h4><p>
                  [<a id="dt-resolve-relative-uri" title="resolve">Definition</a>: To
      <b>resolve a relative URI</b>
                     <code>$rel</code> against a
      base URI <code>$base</code> is to expand it to an absolute URI,
      as if by calling the function <code>fn:resolve-uri($rel,
      $base)</code>.] During static analysis, the base URI is
      the Static Base URI. During dynamic evaluation, the base URI
      used to resolve a relative URI reference depends on the semantics of the
      expression.</p><p>Any process that attempts to <a title="resolve" class="termref" href="#dt-resolve-relative-uri">resolve a URI</a> against a
      base URI, or to dereference the URI, may apply percent-encoding
      or decoding as defined in the relevant RFCs.</p></div></div></div><div class="div1">
<h2><a id="id-types"/>3 <a href="#id-types" style="text-decoration: none">Types</a></h2><p>As noted in <a href="#id-values"><b>2.1.3 Values</b></a>, every value in XQuery 4.0 is regarded
      as a <a title="sequence" class="termref" href="#dt-sequence">sequence</a> of zero, one, or more <a title="item" class="termref" href="#dt-item">items</a>.
      The type system of XQuery 4.0, described in this section, classifies the
      kinds of value that the language can handle, and the operations permitted
      on different kinds of value.</p><p>The type system of XQuery 4.0 is related to the type system of
		<a href="#XMLSchema10">[XML Schema 1.0]</a> or <a href="#XMLSchema11">[XML Schema 1.1]</a> in two ways:</p><ul><li><p>atomic items in XQuery 4.0 (which are one kind of <a title="item" class="termref" href="#dt-item">item</a>)
               have <a title="atomic type" class="termref" href="#dt-atomic-type">atomic types</a> such as <code>xs:string</code>,
               <code>xs:boolean</code>, and <code>xs:integer</code>. These types are taken directly
               from their definitions in <a href="#XMLSchema10">[XML Schema 1.0]</a> or <a href="#XMLSchema11">[XML Schema 1.1]</a>.</p></li><li><p>
                  <a title="XNode" class="termref" href="#dt-XNode">XNodes</a> 
               (which are another kind of <a title="item" class="termref" href="#dt-item">item</a>) have a property
            called a <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> which determines the type of their content.
            The type annotation is a <a title="schema type" class="termref" href="#dt-schema-type">schema type</a>. The type annotation of a node
            must not be confused with the item type of the node. For example, an element 
            <code>&lt;age&gt;23&lt;/age&gt;</code> might have been validated against a schema
               that defines this element as having <code>xs:integer</code> content. If this
               is the case, the <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> of the node will be
               <code>xs:integer</code>, and in the XQuery 4.0 type system, the node will
               match the <a title="item type" class="termref" href="#dt-item-type">item type</a>
                  <code>element(age, xs:integer)</code>.
            </p></li></ul><p>This chapter of the specification starts by defining 
            <a title="sequence type" class="termref" href="#dt-sequence-type">sequence types</a> and 
         <a title="item type" class="termref" href="#dt-item-type">item types</a>, which describe the range of
            <a title="value" class="termref" href="#dt-value">values</a> that can be bound to variables, used in 
            expressions, or passed to functions. It then describes how these
            relate to <a title="schema type" class="termref" href="#dt-schema-type">schema types</a>,
            that is, the simple and complex types defined in an XSD schema.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In many situations the terms <b>item type</b> and 
         <b>sequence type</b> are used interchangeably to refer either to the type itself,
         or to the syntactic construct that designates the type: so in the expression
         <code>$x instance of xs:string*</code>, the construct <code>xs:string*</code>
         uses the <a href="#doc-xquery40-SequenceType">SequenceType</a> syntax to designate a
         <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a> whose instances are sequences of strings.
         When more precision is required, the specification is careful to use the terms
         <a title="item type" class="termref" href="#dt-item-type">item type</a> and <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a> to
         refer to the actual types, while using the production names <a href="#doc-xquery40-ItemType">ItemType</a>
         and <a href="#doc-xquery40-SequenceType">SequenceType</a> to refer to the syntactic
         designators of these types.</p></div><div class="div2">
<h3><a id="id-sequencetype-syntax"/>3.1 <a href="#id-sequencetype-syntax" style="text-decoration: none">Sequence Types</a></h3><p>
               [<a id="dt-sequence-type" title="sequence type">Definition</a>: A <b>sequence type</b> is a type that can be expressed using the <a href="#doc-xquery40-SequenceType">SequenceType</a>
                  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 <b>sequence types</b>.]
            </p><p>Whenever it is necessary to refer to a <b>sequence type</b> 
            in an XQuery 4.0 expression, the <a href="#doc-xquery40-SequenceType">SequenceType</a> syntax is used.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-SequenceType-ItemType">ItemType</a>
                     <a href="#doc-xquery40-SequenceType-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SequenceType-ItemType"/><code><a href="#prod-xquery40-ItemType">ItemType</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-RegularItemType">RegularItemType</a>  |  <a href="#doc-xquery40-FunctionType">FunctionType</a>  |  <a href="#prod-xquery40-TypeName">TypeName</a>  |  <a href="#prod-xquery40-ChoiceItemType">ChoiceItemType</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SequenceType-OccurrenceIndicator"/><code><a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a></code></td><td>::=</td><td><code>"?"  |  "*"  |  "+"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-occurrence-indicators">xgc: occurrence-indicators</a>
                   */</td></tr></tbody></table><p>
               [<a id="dt-sequence-type-designator" title="sequence type designator">Definition</a>: A
      <b>sequence type designator</b> is a syntactic construct conforming to the grammar rule
         <a href="#doc-xquery40-SequenceType">SequenceType</a>. A sequence type designator is said
      to <b>designate</b> a <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>.]
            </p><p>With the exception of the special type
<code>empty-sequence()</code>, a <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a> consists of an
<a title="item type" class="termref" href="#dt-item-type">item type</a> that constrains the type of each item in the
sequence, and a <b>cardinality</b> that constrains the number of
items in the sequence. Apart from the item type <code>item()</code>,
which permits any kind of item, item types divide into <b>node
types</b> (such as <code>element()</code>), <b>generalized atomic
types</b> (such as <code>xs:integer</code>) and function types
(such as <code>function() as item()*</code>).</p><p>The cardinality of a <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a> is represented
               in the <a title="sequence type designator" class="termref" href="#dt-sequence-type-designator">sequence type designator</a> syntax by
               an <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>. 
               The occurrence indicators <code>+</code>, <code>*</code>, and <code>?</code> 
               bind to the last <a href="#doc-xquery40-ItemType">ItemType</a> in the <a href="#doc-xquery40-SequenceType">SequenceType</a>, as described in the <a href="#parse-note-occurrence-indicators">occurrence-indicators</a> constraint.</p><div class="div3">
<h4><a id="id-sequence-type-examples"/>3.1.1 <a href="#id-sequence-type-examples" style="text-decoration: none">Examples of Sequence Types</a></h4><p>Here are some examples of <a title="sequence type" class="termref" href="#dt-sequence-type">sequence types</a> that
		  might be used in XQuery 4.0:</p><ul><li><p>
                        <code>xs:date</code> refers to the built-in atomic schema type named <code>xs:date</code>
                     </p></li><li><p>
                        <code>attribute()?</code> refers to an optional attribute node</p></li><li><p>
                        <code>element()</code> refers to any element node</p></li><li><p>
                        <code>element(po:shipto, po:address)</code> refers to an element node that has the name <code>po:shipto</code> and has the type annotation <code>po:address</code> (or a schema type derived from <code>po:address</code>)</p></li><li><p>
                        <code>element(*, po:address)</code> refers to an element node of any name that has the type annotation <code>po:address</code> (or a type derived from <code>po:address</code>)</p></li><li><p>
                        <code>element(customer)</code> refers to an element node named <code>customer</code> with any type annotation</p></li><li><p>
                        <code>schema-element(customer)</code> refers to an element node whose name is <code>customer</code> (or is in the substitution group headed by <code>customer</code>) and whose type annotation matches the schema type declared for a <code>customer</code> element in the <a title="in-scope element declarations" class="termref" href="#dt-is-elems">in-scope element declarations</a>
                     </p></li><li><p>
                        <code>node()*</code> refers to a sequence of zero or more nodes of any kind</p></li><li><p>
                        <code>item()+</code> refers to a sequence of one or more <a title="item" class="termref" href="#dt-item">items</a>
                     </p></li><li><p>
                        <code>function(*)</code> refers to any <a title="function item" class="termref" href="#dt-function-item">function item</a>, regardless of arity or type</p></li><li><p>
                        <code>function(node()) as xs:string*</code> refers to a <a title="function item" class="termref" href="#dt-function-item">function item</a> that takes a single argument whose value is a single node,
        and returns a sequence of zero or more <code>xs:string</code> values</p></li><li><p>
                        <code>(fn(node()) as xs:string)*</code> refers to a sequence of zero or more <a title="function item" class="termref" href="#dt-function-item">function items</a>, each of which takes a single
        argument whose value is a single node, and returns as its result a single <code>xs:string</code> value</p></li></ul></div><div class="div3">
<h4><a id="id-sequencetype-matching"/>3.1.2 <a href="#id-sequencetype-matching" style="text-decoration: none">Sequence Type Matching</a></h4><p>
                  [<a id="dt-sequencetype-matching" title="SequenceType matching">Definition</a>: 
                     <b>SequenceType matching</b> compares a value with an expected <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>. ] For example, an <code>instance of</code> expression 
               returns <code>true</code> if a given value matches a given <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>, and <code>false</code> if it does not.</p><p>An XQuery 4.0 implementation must be able to determine relationships among the types in type annotations in an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a> and the types in the  <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a> (ISSD). <span class="xquery">An XQuery 4.0 implementation must be able to determine relationships among the types in ISSDs used in different modules of the same query.</span>
               </p><p>
                  [<a id="dt-subtype-substitution" title="subtype substitution">Definition</a>: The use of a value that has a <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a>
                      that is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of the
		  expected type is known as <b>subtype substitution</b>.]
		  Subtype substitution does not change the actual type of a value. For
		  example, if an <code>xs:integer</code> value is used where an
		  <code>xs:decimal</code> value is expected, the value retains its type
		  as <code>xs:integer</code>.</p><p>The rules for <a title="SequenceType matching" class="termref" href="#dt-sequencetype-matching">SequenceType
		  matching</a> are given below, with examples (the examples are
		  for purposes of illustration, and do not cover all possible
		  cases).</p><ul><li><p>The <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>
                        <code>empty-sequence()</code> matches a value that is the empty sequence.</p></li><li><p>An <a href="#doc-xquery40-ItemType">ItemType</a> with no <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a> matches any value that contains exactly one item if the <a href="#doc-xquery40-ItemType">ItemType</a> matches that item (see <a href="#id-matching-item"><b>3.2 Item Types</b></a>).</p></li><li><p>An <a href="#doc-xquery40-ItemType">ItemType</a> with an <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a> matches a value if the number of items in the value matches the <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a> and the <a href="#doc-xquery40-ItemType">ItemType</a> matches each of the items in the value.</p></li></ul><p>An <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a> specifies the number of items in
		    a sequence, as follows:</p><ul><li><p>
                        <code>?</code> matches zero or one items</p></li><li><p>
                        <code>*</code> matches zero or more items</p></li><li><p>
                        <code>+</code> matches one or more items</p></li></ul><p>As a consequence of these rules, any <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a> whose
		    <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a> is <code>*</code> or <code>?</code> matches a
		    value that is an empty sequence.</p></div><div class="div3">
<h4><a id="id-schema-type-derivation"/>3.1.3 <a href="#id-schema-type-derivation" style="text-decoration: none">Schema Type Relationships</a></h4><p>Some <a title="item type" class="termref" href="#dt-item-type">item types</a> are defined in terms
            of <a title="schema type" class="termref" href="#dt-schema-type">schema types</a>, and the matching
            rules for such item types depend on the rules defining relationships between
            schema types in the XSD specification.</p><p>
                  [<a id="dt-derives-from" title="derives from">Definition</a>: A 
               <a title="schema type" class="termref" href="#dt-schema-type">schema type</a>
                     <var>S<sub>1</sub></var> is said to <b>derive from</b>
                     <a title="schema type" class="termref" href="#dt-schema-type">schema type</a>
                     <var>S<sub>2</sub></var> if any of the following
               conditions is true:
               </p><ul><li><p>
                        <var>S<sub>1</sub></var> is the same type as <var>S<sub>2</sub></var>.</p></li><li><p>
                        <var>S<sub>2</sub></var> is the base type of <var>S<sub>1</sub></var>.</p></li><li><p>
                        <var>S<sub>2</sub></var> is a <a title="pure union type" class="termref" href="#dt-pure-union-type">pure union type</a>
                     of which <var>S<sub>1</sub></var> is a member type.</p></li><li><p>There is a <a title="schema type" class="termref" href="#dt-schema-type">schema type</a>
                        <var>M</var> such that 
                     <var>S<sub>1</sub></var>
                        <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                        <var>M</var>
                     and <var>M</var>
                        <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                        <var>S<sub>2</sub></var>.</p></li></ul><p>]</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The XML Schema specification does not completely specify the circumstances
               under which <var>S<sub>1</sub></var> and <var>S<sub>2</sub></var> are considered to be the same
               type. For example, if both are anonymous union types with the same member types,
               but defined in different places in the schema, then schema processors have
               discretion whether to treat them as the same type.</p></div></div></div><div class="div2">
<h3><a id="id-matching-item"/>3.2 <a href="#id-matching-item" style="text-decoration: none">Item Types</a></h3><p>
               [<a id="dt-item-type" title="item type">Definition</a>: An <b>item type</b> is a type that can be expressed using the <a href="#doc-xquery40-ItemType">ItemType</a> syntax, which forms part of the <a href="#doc-xquery40-SequenceType">SequenceType</a>
            syntax. Item types match individual <a title="item" class="termref" href="#dt-item">items</a>.]
            </p><div class="note"><p class="prefix"><b>Note:</b></p><p>While this definition is adequate for the purpose of defining the syntax
            of XQuery 4.0, it ignores the fact that there are also item types that cannot be
            expressed using XQuery 4.0 syntax: specifically, item types that reference
            an anonymous simple type or complex type defined in a schema. Such types 
            can appear as type annotations on nodes following schema validation.</p></div><p>In most cases, the set of items matched by an item type consists either
         exclusively of <a title="atomic item" class="termref" href="#dt-atomic-item">atomic items</a>,
         exclusively of <a title="node" class="termref" href="#dt-node">nodes</a>, 
         or exclusively of <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-function-item">function items</a><sup><small>DM</small></sup>.
         Exceptions include the generic types <code>item()</code>, which matches all items, <code>xs:error</code>,
         which matches no items, and <a title="choice item type" class="termref" href="#dt-choice-item-type">choice item types</a>,
         which can match any combination of types.
      </p><p>
               [<a id="dt-item-type-designator" title="item type designator">Definition</a>: An
         <b>item type designator</b> is a syntactic construct conforming to the grammar rule
         <a href="#doc-xquery40-ItemType">ItemType</a>. An item type designator is said
         to <b>designate</b> an <a title="item type" class="termref" href="#dt-item-type">item type</a>.]
            </p><div class="note"><p class="prefix"><b>Note:</b></p><p>Two <a title="item type designator" class="termref" href="#dt-item-type-designator">item type designators</a> may designate the
      same item type. For example, <code>element()</code> and <code>element(*)</code> are equivalent,
      as are <code>attribute(A)</code> and <code>attribute(A, xs:anySimpleType)</code>.</p></div><p>
               <a title="lexical QName" class="termref" href="#dt-qname">Lexical QNames</a> appearing in an <a title="item type designator" class="termref" href="#dt-item-type-designator">item type designator</a>
               <span class="xquery">(other than within
                  a <a title="function assertion" class="termref" href="#dt-function-assertion">function assertion</a>)</span> are expanded using the 
                  <a title="default type namespace rule" class="termref" href="#dt-default-type-namespace-rule">default type namespace rule</a>.
      Equality of QNames is defined by the <code>eq</code> operator.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType"/><code><a href="#prod-xquery40-ItemType">ItemType</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ItemType-RegularItemType">RegularItemType</a>  |  <a href="#doc-xquery40-ItemType-FunctionType">FunctionType</a>  |  <a href="#doc-xquery40-ItemType-TypeName">TypeName</a>  |  <a href="#doc-xquery40-ItemType-ChoiceItemType">ChoiceItemType</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-RegularItemType"/><code><a href="#prod-xquery40-RegularItemType">RegularItemType</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ItemType-AnyItemTest">AnyItemTest</a>  |  <a href="#doc-xquery40-ItemType-NodeKindTest">NodeKindTest</a>  |  <a href="#doc-xquery40-ItemType-GNodeType">GNodeType</a>  |  <a href="#doc-xquery40-ItemType-JNodeType">JNodeType</a>  |  <a href="#doc-xquery40-ItemType-MapType">MapType</a>  |  <a href="#doc-xquery40-ItemType-ArrayType">ArrayType</a>  |  <a href="#doc-xquery40-ItemType-RecordType">RecordType</a>  |  <a href="#doc-xquery40-ItemType-EnumerationType">EnumerationType</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-AnyItemTest"/><code><a href="#prod-xquery40-AnyItemTest">AnyItemTest</a></code></td><td>::=</td><td><code>"item"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-NodeKindTest"/><code><a href="#prod-xquery40-NodeKindTest">NodeKindTest</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ItemType-DocumentTest">DocumentTest</a>
                     <br/>|  <a href="#doc-xquery40-ItemType-ElementTest">ElementTest</a>
                     <br/>|  <a href="#doc-xquery40-ItemType-AttributeTest">AttributeTest</a>
                     <br/>|  <a href="#doc-xquery40-ItemType-SchemaElementTest">SchemaElementTest</a>
                     <br/>|  <a href="#doc-xquery40-ItemType-SchemaAttributeTest">SchemaAttributeTest</a>
                     <br/>|  <a href="#doc-xquery40-ItemType-PITest">PITest</a>
                     <br/>|  <a href="#doc-xquery40-ItemType-CommentTest">CommentTest</a>
                     <br/>|  <a href="#doc-xquery40-ItemType-TextTest">TextTest</a>
                     <br/>|  <a href="#doc-xquery40-ItemType-NamespaceNodeTest">NamespaceNodeTest</a>
                     <br/>|  <a href="#doc-xquery40-ItemType-AnyNodeKindTest">AnyNodeKindTest</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-DocumentTest"/><code><a href="#prod-xquery40-DocumentTest">DocumentTest</a></code></td><td>::=</td><td><code>"document-node"  "("  (<a href="#doc-xquery40-ItemType-ElementTest">ElementTest</a>  |  <a href="#doc-xquery40-ItemType-SchemaElementTest">SchemaElementTest</a>  |  <a href="#doc-xquery40-ItemType-NameTestUnion">NameTestUnion</a>)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-ElementTest"/><code><a href="#prod-xquery40-ElementTest">ElementTest</a></code></td><td>::=</td><td><code>"element"  "("  (<a href="#doc-xquery40-ItemType-NameTestUnion">NameTestUnion</a>  (","  <a href="#doc-xquery40-ItemType-TypeName">TypeName</a>  "?"?)?)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-SchemaElementTest"/><code><a href="#prod-xquery40-SchemaElementTest">SchemaElementTest</a></code></td><td>::=</td><td><code>"schema-element"  "("  <a href="#prod-xquery40-ElementName">ElementName</a>  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-NameTestUnion"/><code><a href="#prod-xquery40-NameTestUnion">NameTestUnion</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ItemType-NameTest">NameTest</a> ++ "|")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-NameTest"/><code><a href="#prod-xquery40-NameTest">NameTest</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ItemType-EQName">EQName</a>  |  <a href="#prod-xquery40-Wildcard">Wildcard</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-AttributeTest"/><code><a href="#prod-xquery40-AttributeTest">AttributeTest</a></code></td><td>::=</td><td><code>"attribute"  "("  (<a href="#doc-xquery40-ItemType-NameTestUnion">NameTestUnion</a>  (","  <a href="#doc-xquery40-ItemType-TypeName">TypeName</a>)?)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-SchemaAttributeTest"/><code><a href="#prod-xquery40-SchemaAttributeTest">SchemaAttributeTest</a></code></td><td>::=</td><td><code>"schema-attribute"  "("  <a href="#prod-xquery40-AttributeName">AttributeName</a>  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-PITest"/><code><a href="#prod-xquery40-PITest">PITest</a></code></td><td>::=</td><td><code>"processing-instruction"  "("  (<a href="#prod-xquery40-NCName">NCName</a>  |  <a href="#doc-xquery40-ItemType-StringLiteral">StringLiteral</a>)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-CommentTest"/><code><a href="#prod-xquery40-CommentTest">CommentTest</a></code></td><td>::=</td><td><code>"comment"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-TextTest"/><code><a href="#prod-xquery40-TextTest">TextTest</a></code></td><td>::=</td><td><code>"text"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-NamespaceNodeTest"/><code><a href="#prod-xquery40-NamespaceNodeTest">NamespaceNodeTest</a></code></td><td>::=</td><td><code>"namespace-node"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-AnyNodeKindTest"/><code><a href="#prod-xquery40-AnyNodeKindTest">AnyNodeKindTest</a></code></td><td>::=</td><td><code>"node"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-GNodeType"/><code><a href="#prod-xquery40-GNodeType">GNodeType</a></code></td><td>::=</td><td><code>"gnode"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-JNodeType"/><code><a href="#prod-xquery40-JNodeType">JNodeType</a></code></td><td>::=</td><td><code>"jnode"  "("  <a href="#doc-xquery40-SequenceType">SequenceType</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-MapType"/><code><a href="#prod-xquery40-MapType">MapType</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AnyMapType">AnyMapType</a>  |  <a href="#prod-xquery40-TypedMapType">TypedMapType</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-ArrayType"/><code><a href="#prod-xquery40-ArrayType">ArrayType</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AnyArrayType">AnyArrayType</a>  |  <a href="#prod-xquery40-TypedArrayType">TypedArrayType</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-RecordType"/><code><a href="#prod-xquery40-RecordType">RecordType</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AnyRecordType">AnyRecordType</a>  |  <a href="#prod-xquery40-TypedRecordType">TypedRecordType</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-EnumerationType"/><code><a href="#prod-xquery40-EnumerationType">EnumerationType</a></code></td><td>::=</td><td><code>"enum"  "("  (<a href="#doc-xquery40-ItemType-StringLiteral">StringLiteral</a> ++ ",")  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-FunctionType"/><code><a href="#prod-xquery40-FunctionType">FunctionType</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-Annotation">Annotation</a>*  (<a href="#prod-xquery40-AnyFunctionType">AnyFunctionType</a>
                     <br/>|  <a href="#prod-xquery40-TypedFunctionType">TypedFunctionType</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-TypeName"/><code><a href="#prod-xquery40-TypeName">TypeName</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ItemType-EQName">EQName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemType-ChoiceItemType"/><code><a href="#prod-xquery40-ChoiceItemType">ChoiceItemType</a></code></td><td>::=</td><td><code>"("  (<a href="#doc-xquery40-ItemType">ItemType</a> ++ "|")  ")"</code></td></tr></tbody></table><p>This section defines the syntax and semantics of different <code>ItemTypes</code>
               in terms of the values that they match.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>For an explanation of the EBNF grammar notation (and in particular, the operators
               <code>++</code> and <code>**</code>), see <a href="#id-grammar"><b>A.1 EBNF</b></a>.</p></div><p>An <a title="item type designator" class="termref" href="#dt-item-type-designator">item type designator</a> written simply 
               as an <code>EQName</code>
               (that is, a <code>TypeName</code>) is interpreted as follows:</p><ol class="enumar"><li><p>If the name is written as a lexical QName, then it is expanded using the
               <a title="default type namespace rule" class="termref" href="#dt-default-type-namespace-rule">default type namespace rule</a>.</p></li><li><p>If the expanded name matches a <a title="named item type" class="termref" href="#dt-named-item-type">named item type</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>,
                  then it is taken as a reference to the corresponding item type. The rules that
               apply are the rules for the expanded item type definition.</p></li><li><p>Otherwise, it must match the name of a type in the <a title="in-scope schema type" class="termref" href="#dt-is-types">in-scope schema types</a>
                  in the <a title="static context" class="termref" href="#dt-static-context">static context</a>: specifically, an <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a>
                  or a <a title="pure union type" class="termref" href="#dt-pure-union-type">pure union type</a>.
                  See <a href="#id-predefined-types"><b>3.5 Schema Types</b></a> for details.
                  </p><div class="note"><p class="prefix"><b>Note:</b></p><p>A name in the <code>xs</code> namespace will always fall into this category, since the namespace
               is reserved. See <a href="#id-namespaces-and-qnames"><b>2.1.4 Namespaces and QNames</b></a>.</p></div></li><li><p>If the name cannot be resolved to a type, a <a title="static error" class="termref" href="#dt-static-error">static error</a> 
                  is raised [<a href="#ERRXPST0051" title="err:XPST0051">err:XPST0051</a>].</p></li></ol><div class="div3">
<h4><a id="general-item-types"/>3.2.1 <a href="#general-item-types" style="text-decoration: none">General item types</a></h4><ul><li><p>
                        <code>item()</code> matches
                        any single <a title="item" class="termref" href="#dt-item">item</a>.</p><p>For example, <code>item()</code> matches the atomic
                        item <code>1</code>, the element <code>&lt;a/&gt;</code>, or the function <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-concat"><code>fn:concat#3</code></a>.</p></li><li><p>A <a href="#prod-xquery40-ChoiceItemType">ChoiceItemType</a> lists a number of alternative item types in parentheses,
                        separated by <code>"|"</code>. An item matches a <code>ChoiceItemType</code>
                        it if matches any of the alternatives.</p><p>For example, <code>(map(*) | array(*))</code> matches any item that
                     is a map or an array.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>If there is only one alternative, the <code>ChoiceItemType</code>
                         designates the same <a title="item type" class="termref" href="#dt-item-type">item type</a>
                         as the <a href="#doc-xquery40-ItemType">ItemType</a> that is in parentheses.
                         A singleton choice (that is, a parenthesized item type) is used primarily 
                         when defining nested item types in a function
                      signature. For example, a sequence of functions that each return a single boolean might be denoted
                      <code>(fn() as xs:boolean)*</code>. In this example the parentheses
                      are needed to indicate where the occurrence indicator belongs.</p></div></li></ul></div><div class="div3">
<h4><a id="id-atomic-types"/>3.2.2 <a href="#id-atomic-types" style="text-decoration: none">Atomic Types</a></h4><p>Atomic types in the XQuery 4.0 type system correspond directly to atomic types
                  as defined in the <a href="#XMLSchema10">[XML Schema 1.0]</a> or <a href="#XMLSchema11">[XML Schema 1.1]</a>
                 type system.</p><p>Atomic types are either built-in atomic types such as <code>xs:integer</code>,
               or user-defined atomic types imported from a schema. Atomic types are identified
               by a QName: see <a href="#id-namespaces-and-qnames"><b>2.1.4 Namespaces and QNames</b></a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>A schema may also include anonymous atomic types. Such types are
               not usable directly in XQuery 4.0, though they may appear as the values
               of <a title="type annotation" class="termref" href="#dt-type-annotation">type annotations</a> on nodes.</p></div><p>
                  [<a id="dt-generalized-atomic-type" title="generalized atomic type">Definition</a>: A <b>generalized atomic type</b> is an 
                        <a title="item type" class="termref" href="#dt-item-type">item type</a> whose instances are all
                        atomic items. Generalized atomic types include (a) 
                        <a title="atomic type" class="termref" href="#dt-atomic-type">atomic types</a>, either built-in
                        (for example <code>xs:integer</code>) or imported from a schema, 
                        (b) <a title="pure union type" class="termref" href="#dt-pure-union-type">pure union types</a>, either built-in
                        (<code>xs:numeric</code> and <code>xs:error</code>) or imported from a schema,
                        (c) <a title="choice item type" class="termref" href="#dt-choice-item-type">choice item types</a> if their alternatives
                        are all generalized atomic types, and 
                        (d) <a title="enumeration type" class="termref" href="#dt-enumeration-type">enumeration types</a>.
                     ].</p><p>A <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a> may be designated by 
                     an <a href="#doc-xquery40-ItemType">ItemType</a> in any of the following ways:</p><ul><li><p>Using the QName of a type in the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a> that is an 
                        <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a>
                     or a <a title="pure union type" class="termref" href="#dt-pure-union-type">pure union type</a>.</p></li><li><p>Using a QName that identifies a <a title="named item type" class="termref" href="#dt-named-item-type">named item type</a> that resolves
                        to a <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a>.</p></li><li><p>Using a <a href="#prod-xquery40-ChoiceItemType">ChoiceItemType</a> where every alternative
                        is itself a <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a>.</p></li><li><p>Using an <a href="#doc-xquery40-EnumerationType">EnumerationType</a> as described below.</p></li></ul><p>An atomic item <var>A</var> matches the 
                     <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a>
                  <var>GAT</var> 
                     if the <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> of <var>A</var>
                  <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                  <var>GAT</var>.</p><p>Example: The <a href="#doc-xquery40-ItemType">ItemType</a>
                  <code>xs:decimal</code> matches any value of type
    <code>xs:decimal</code>.  It also matches any value of type
                        <code>shoesize</code>, if <code>shoesize</code> is an <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a>
    derived by restriction from <code>xs:decimal</code>.</p><p>Example: Suppose <a href="#doc-xquery40-ItemType">ItemType</a>
                  <code>dress-size</code> is a union type that allows
    either <code>xs:decimal</code> values for numeric sizes (for example: 4, 6, 10, 12),
    or one of an enumerated set of <code>xs:strings</code>
    (for example: <code>small</code>, <code>medium</code>, <code>large</code>). The <a href="#doc-xquery40-ItemType">ItemType</a>
                  <code>dress-size</code> matches any of these values.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The names of <span>list</span>
    types such as <code>xs:IDREFS</code> are not accepted in this context,
    but can often be replaced by a <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a> with an occurrence indicator, such as
    <code>xs:IDREF+</code>.</p></div></div><div class="div3">
<h4><a id="id-union-types"/>3.2.3 <a href="#id-union-types" style="text-decoration: none">Union Types</a></h4><p>Union types, as defined in XSD, are a variety of simple types. The membership of
                  a union type in XSD may include list types as well as atomic types and other union types.</p><p>
                  [<a id="dt-pure-union-type" title="pure union type">Definition</a>: A <b>pure union type</b> is a <span>
                        <b>simple type</b>
                     </span> 
                     that satisfies the following constraints:
                     (a) <a href="https://www.w3.org/TR/xmlschema11-1/#std-variety">{variety}<sup><small>XS11-1</small></sup></a> is <code>union</code>, 
                     (b) the <a href="https://www.w3.org/TR/xmlschema11-1/#std-facets">{facets}<sup><small>XS11-1</small></sup></a> property is empty, 
                     (c) no type in the transitive membership of the union type has 
                     <a href="https://www.w3.org/TR/xmlschema11-1/#std-variety">{variety}<sup><small>XS11-1</small></sup></a>
                     <code>list</code>, and 
                     (d) no type in the transitive membership of the union type is a type with 
                     <a href="https://www.w3.org/TR/xmlschema11-1/#std-variety">{variety}<sup><small>XS11-1</small></sup></a>
                     <code>union</code> having a non-empty <a href="https://www.w3.org/TR/xmlschema11-1/#std-facets">{facets}<sup><small>XS11-1</small></sup></a> property].</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The definition of <a title="pure union type" class="termref" href="#dt-pure-union-type">pure union type</a>
                     excludes union types derived by non-trivial restriction from other
                     union types, as well as union types that include list types in their
                     membership. Pure union types have the property that every
                     instance of an <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a> defined as one of the member types of the
                     union is also a valid instance of the union type.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The current (second) edition of XML Schema 1.0 contains an
                     error in respect of the substitutability of a union type by one of its
                     members: it fails to recognize that this is unsafe if the union is
                     derived by restriction from another union.</p><p>This problem is fixed in XSD 1.1, but the effect of the resolution
                     is that an atomic item labeled with an atomic type cannot be treated
                     as being substitutable for a union type without explicit validation.
                     This specification therefore allows union types to be used as item
                     types only if they are defined directly as the union of a number of
                     atomic types.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Local union types (see <a href="#id-choice-item-types"><b>3.2.5 Choice Item Types</b></a>) and 
                  <a title="enumeration type" class="termref" href="#dt-enumeration-type">enumeration types</a> cannot be
                  used as the target for schema validation.</p></div><p>
                  [<a id="dt-numeric" title="numeric">Definition</a>: The type <code>xs:numeric</code>
               is defined as a union type with member types <code>xs:double</code>, 
               <code>xs:float</code>, and <code>xs:decimal</code>. An item that
               is an instance of any of these types is referred to as a <b>numeric value</b>,
               and a type that is a subtype of <code>xs:numeric</code> is referred to
               as a <b>numeric type</b>.]
               </p></div><div class="div3">
<h4><a id="id-namespace-sensitive"/>3.2.4 <a href="#id-namespace-sensitive" style="text-decoration: none">Namespace-sensitive Types</a></h4><p>
                  [<a id="dt-namespace-sensitive" title="namespace-sensitive">Definition</a>: The <b>namespace-sensitive</b>
                     types are <code>xs:QName</code>, <code>xs:NOTATION</code>, types
                     derived by restriction from <code>xs:QName</code> or
                     <code>xs:NOTATION</code>, list types that have a namespace-sensitive
                     item type, and union types with a namespace-sensitive type in their
                     transitive membership.]
               </p><p>It is not possible to preserve the type of a <a title="namespace-sensitive" class="termref" href="#dt-namespace-sensitive">namespace-sensitive</a> value without also preserving the <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> 
                  that defines the meaning of each namespace prefix used in the value. Therefore, XQuery 4.0 defines 
                  some error conditions that occur only with <a title="namespace-sensitive" class="termref" href="#dt-namespace-sensitive">namespace-sensitive</a> values. For instance, casting to a <a title="namespace-sensitive" class="termref" href="#dt-namespace-sensitive">namespace-sensitive</a> type raises 
                  a <a title="type error" class="termref" href="#dt-type-error">type error</a>
                  [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFONS0004" title="err:FONS0004">err:FONS0004</a>]<sup><small>FO40</small></sup> if the namespace bindings for the result cannot be determined. </p></div><div class="div3">
<h4><a id="id-choice-item-types"/>3.2.5 <a href="#id-choice-item-types" style="text-decoration: none">Choice Item Types</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-enumeration-types">⬇</a> <a href="#id-implausible-expressions">⬆</a></p><ol><li><p>
                     Choice item types (an item type allowing a set of alternative item types)
                     are introduced.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/122">122</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1132">1132</a> 9 April 2024]</i></p></li></ol></div><p>
                  [<a id="dt-choice-item-type" title="choice item type">Definition</a>: A 
                  <b>choice item type</b> defines an item type that is the union
               of a number of alternatives. For example the type 
               <code>(xs:hexBinary | xs:base64Binary)</code> defines the union of 
                  these two primitive <a title="atomic type" class="termref" href="#dt-atomic-type">atomic types</a>, 
                  while the type <code>(map(*) | array(*))</code>
               matches any item that is either a map or an array.]
               </p><p>An item matches a <code>ChoiceItemType</code> if it matches any of the 
                  alternatives listed within the parentheses.</p><p>For example, the type <code>(xs:NCName | enum(""))</code> matches any value that is either
                  an instance of <code>xs:NCName</code>, or a zero-length string. This might be a suitable type for
                  a variable that holds a namespace prefix.</p><p>If all the alternatives are <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic types</a>
                  then the <a title="choice item type" class="termref" href="#dt-choice-item-type">choice item type</a> is itself a generalized atomic type,
               which means, for example, that it can be used as the target of a cast expression.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>A <a title="choice item type" class="termref" href="#dt-choice-item-type">choice item type</a> in which all the alternatives are atomic
                  behaves in most respects like a schema-defined <a title="pure union type" class="termref" href="#dt-pure-union-type">pure union type</a>.
                     However, because it can be defined at the point of use (for example,
                     within a function signature), it may be more convenient than defining the type in an
                     imported schema.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Choice item types are particularly useful in function signatures, 
                     allowing a function to take arguments
                  of a variety of types. If the choice item type is a local union type, 
                  then the semantics are identical to using a named union type, but a local union type is more
                  convenient because it does not need to be defined in a schema, and does not require a schema-aware processor.</p><p>A local union type can also be used in a cast expression: <code>cast @when as (xs:date | xs:dateTime)</code>
                  allows the attribute <code>@when</code> to be either an <code>xs:date</code>, or an <code>xs:dateTime</code>.</p><p>An <code>instance of</code> expression can be used to test whether a value belongs to one
                  of a number of specified types: <code>$x instance of (xs:string | xs:anyURI | xs:untypedAtomic)</code>
                  returns <code>true</code> if <code>$x</code> is an instance of any of these three atomic types,
                  while <code>$x instance of (map(*) | array(*))</code> tests whether <code>$x</code> is
                  a map or array.</p></div></div><div class="div3">
<h4><a id="id-enumeration-types"/>3.2.6 <a href="#id-enumeration-types" style="text-decoration: none">Enumeration Types</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#node-types">⬇</a> <a href="#id-choice-item-types">⬆</a></p><ol><li><p>Enumeration types are added as a new kind of <code>ItemType</code>, constraining
                     the value space of strings.<i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/688">688</a> <a href="https://github.com/qt4cg/qtspecs/issues/2152">2152</a> PRs <a href="https://github.com/qt4cg/qtspecs/pull/691">691</a> <a href="https://github.com/qt4cg/qtspecs/pull/2154">2154</a> 10 October 2023]</i></p></li></ol></div><p>
                  [<a id="dt-enumeration-type" title="enumeration type">Definition</a>: An <b>EnumerationType</b>
                  accepts a fixed set of string values.]
               </p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-EnumerationType"/><code><a href="#prod-xquery40-EnumerationType">EnumerationType</a></code></td><td>::=</td><td><code>"enum"  "("  (<a href="#doc-xquery40-EnumerationType-StringLiteral">StringLiteral</a> ++ ",")  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-EnumerationType-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody></table><p>An <a title="enumeration type" class="termref" href="#dt-enumeration-type">enumeration type</a> has a value space consisting of a set of <code>xs:string</code>
                  values. When matching strings against an enumeration type, strings are always compared
               using the Unicode codepoint collation.</p><p>For example, if an argument of a function declares the required type 
                  as <code>enum("red", "green", "blue")</code>, then the string <code>"green"</code> is accepted,
                  while <code>"yellow"</code> is rejected with a type error.</p><p>Technically, enumeration types are defined as follows:</p><ul><li><p>
                        [<a id="dt-singleton-enumeration-type" title="singleton enumeration type">Definition</a>: An 
                     enumeration type with a single enumerated value <var>E</var> (such as
                     <code>enum("red")</code>) matches an item <var>S</var> if and only if (a) <var>S</var>
                     is an instance of <code>xs:string</code>, and (b) <var>S</var> is equal
                     to <var>E</var> when compared using Unicode codepoint collation. This is referred to
                     as a <b>singleton enumeration type</b>.]
                     </p><div class="note"><p class="prefix"><b>Note:</b></p><p>When matching a string <var>S</var> against an enumeration type,
                     then apart from the requirement that <var>S</var> is an instance of
                     <code>xs:string</code>, the type annotation of <var>S</var> is immaterial.</p></div></li><li><p>A <a title="singleton enumeration type" class="termref" href="#dt-singleton-enumeration-type">singleton enumeration type</a> whose enumerated value
                  is <var>E</var> is a subtype of <code>xs:string</code>.</p></li><li><p>Two <a title="singleton enumeration type" class="termref" href="#dt-singleton-enumeration-type">singleton enumeration types</a> 
                     are the same type if and only
                  if they have the same (single) enumerated value, as determined using the Unicode
                  codepoint collation.</p></li><li><p>An enumeration type with multiple
                     enumerated values is a union of <a title="singleton enumeration type" class="termref" href="#dt-singleton-enumeration-type">singleton enumeration types</a>, 
                     so <code>enum("red", "green", "blue")</code>
                     is equivalent to <code>(enum("red") | enum("green") | enum("blue"))</code>.</p></li><li><p>In consequence, an enumeration type <var>T</var> is a subtype
                  of an enumeration type <var>U</var> if the enumerated values of <var>T</var>
                  are a subset of the enumerated values of <var>U</var>: 
                     see <a href="#id-itemtype-subtype"><b>3.3.2 Subtypes of Item Types</b></a>.</p></li></ul><p>An enumeration type is a <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a>.</p><p>It follows from these rules that the expression <code>"red" instance of enum("red", "green", "blue")</code>
               returns <code>true</code>. By contrast, <code>xs:untypedAtomic("red") 
                  instance of enum("red", "green", "blue")</code> returns false; but the
                  <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a> ensure that where a variable
               or function declaration specifies an enumeration type as the required type, 
               an <code>xs:untypedAtomic</code> or <code>xs:anyURI</code> value equal
               to one of the enumerated values will be accepted.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Some consequences of these rules may not be immediately apparent.</p><p>Suppose that an XQuery query contains the declarations:</p><div class="exampleInner"><pre>
declare type my:color := enum("red", "green", "orange");
declare type my:fruit := enum("apple", "orange", "banana");
declare variable $orange-color as my:color := "orange";
declare variable $orange-fruit as my:fruit := "orange";</pre></div><p>The same applies with the equivalent XSLT syntax:</p><div class="exampleInner"><pre>
&lt;xsl:item-type name="my:color" as="enum('red', 'green', 'orange')"/&gt;
&lt;xsl:item-type name="my:fruit" as="enum('apple', 'orange', 'banana')"/&gt;
&lt;xsl:variable name="orange-color" as="my:color" select="'orange'"/&gt;
&lt;xsl:variable name="orange-fruit" as="my:fruit" select="'orange'"/&gt;</pre></div><p>Now, the value of <code>$orange-color</code> is an atomic item whose datum
                  is the string <code>"orange"</code>, and whose type annotation is <code>xs:string</code>. 
                     Similarly, the value of 
                     <code>$orange-fruit</code> is an atomic item whose datum
                  is the string <code>"orange"</code>, and whose type annotation is <code>xs:string</code>. That is, the values of the two
                     variables are indistinguishable and interchangeable in every way. In particular,
                  both values are instances of <code>my:color</code>,
                  and both are instances of <code>my:fruit</code>.</p><p>This way of handling enumeration values has advantages and disadvantages.
                  On the positive side, it means that enumeration subsets and supersets work
                  cleanly: a value that is an instance of <code>enum("red", "green", "orange")</code>
                  can be used where an instance of <code>enum("red", "orange", "yellow", "green", "blue", "indigo",
                     "violet")</code> is expected. The downside is that labeling a string as an instance
                  of an enumeration type does not provide type safety: a function that expects an instance
                  of <code>my:color</code> can be called with any string that matches one of the required
                  colors, whether or not it has an appropriate type annotation. A function that expects a color
                  can be successfully called passing a fruit, if they happen to have the same name.</p><p>In the terminology of computer science, XDM atomic types derived by restriction
                  are <em>nominative</em> types, allowing two types with identical properties
                  but different names to be treated as different types with different instances. By
                  contrast, enumeration types are <em>structural</em> types, where membership
                  of the type is determined purely by a predicate applied to the value.</p><p>In consequence, instances of an enumeration type are not annotated as such.
                  The type annotation of such an instance may be <code>xs:string</code> or any type
                  derived by restriction from <code>xs:string</code>, but it will not be the
                  enumeration type itself, which is anonymous.</p></div></div><div class="div3">
<h4><a id="node-types"/>3.2.7 <a href="#node-types" style="text-decoration: none">Node Types</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-element-test">⬇</a> <a href="#id-enumeration-types">⬆</a></p><ol><li><p>
                     Element and attribute tests can include alternative names: <code>element(chapter|section)</code>,
                     <code>attribute(role|class)</code>.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/107">107</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/286">286</a> 17 January 2023]</i></p></li><li><p>
                     The <code>NodeTest</code> in an <code>AxisStep</code> now allows alternatives: 
                     <code>ancestor::(section|appendix)</code>
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/107">107</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/286">286</a> 17 January 2023]</i></p></li><li><p>
                     The syntax <code>document-node(<var>N</var>)</code>, where <var>N</var> is a <code>NameTestUnion</code>,
                     is introduced as an abbreviation for <code>document-node(element(<var>N</var>))</code>. For example,
                     <code>document-node(*)</code> matches any well-formed XML document (as distinct from a document fragment).
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1593">1593</a>  24 November 2024]</i></p></li></ol></div><p>Node types are <a title="item type" class="termref" href="#dt-item-type">item types</a> whose 
                  instances are all <a title="node" class="termref" href="#dt-node">nodes</a>.</p><p>The syntax for node types is also used for <a title="node test" class="termref" href="#dt-node-test">node tests</a>
               within path expressions. This explains why the production rules have names such as
               <code>NodeTest</code> rather than <code>NodeType</code>.</p><p>Some of the constructs described in this section include a <a href="#prod-xquery40-TypeName">TypeName</a>. This appears 
                  as <var>T</var> in:</p><ul><li><p>
                        <code>element(N, T)</code>
                     </p></li><li><p>
                        <code>attribute(N, T)</code>
                     </p></li><li><p>
                        <code>document-node(element(N, T))</code>
                     </p></li></ul><p>The type name <var>T</var> is expanded using the <a title="default type namespace rule" class="termref" href="#dt-default-type-namespace-rule">default type namespace rule</a>. The resulting
               <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> must identify a type in the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a>. This can be any <a title="schema type" class="termref" href="#dt-schema-type">schema type</a>: either a simple type,
               or (except in the case of attributes) a complex type. If it is a simple type then it can be an atomic, union, or
               list type. It can be a built-in type (such as <code>xs:integer</code>) or a user-defined type. It must however
               be the name of a type defined in a schema; it cannot be a <a title="named item type" class="termref" href="#dt-named-item-type">named item type</a>.</p><div class="div4">
<h5><a id="id-simple-node-tests"/>3.2.7.1 <a href="#id-simple-node-tests" style="text-decoration: none">Simple Node Types</a></h5><ul><li><p>
                           <code>node()</code>
    matches any node.</p></li><li><p>
                           <code>text()</code> matches any
    text node.</p></li><li><p>
                           <code>processing-instruction()</code>
    matches any processing-instruction
    node.</p></li><li><p>
                           <code>processing-instruction(</code>
                           <em>N</em>
                           <code>)</code>
    matches any processing-instruction node whose PITarget is equal to <code>fn:normalize-space(N)</code>. If the result of <code>fn:normalize-space(N)</code> is not in the lexical space of NCName, a type error is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>]
                        </p><p>Example:
    <code>processing-instruction(xml-stylesheet)</code> matches any
    processing instruction whose PITarget is
    <code>xml-stylesheet</code>.</p><p>For backward compatibility with
    XPath 1.0, the PITarget of a
    processing instruction may also be expressed as a
    string literal, as in this example:
    <code>processing-instruction("xml-stylesheet")</code>.</p><p>If the specified PITarget is not a syntactically valid NCName, a type error is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>
                           <code>comment()</code> matches any comment node.</p></li><li><p>
                           <code>namespace-node()</code> matches any
    namespace node.</p></li><li><p>
                           <code>document-node()</code> matches any document
    node.</p></li><li><p>
                           <code>document-node(</code>
                           <em>E</em>
                           <code>)</code>, where <var>E</var> is an <a href="#doc-xquery40-ElementTest">ElementTest</a> or <a href="#doc-xquery40-SchemaElementTest">SchemaElementTest</a> (see <a href="#id-element-test"><b>3.2.7.2 Element Types</b></a> and <a href="#id-schema-element-test"><b>3.2.7.2.1 Schema Element Types</b></a>)
    matches any document node whose children comprise (in any order) zero or more
    comment and processing instruction nodes, zero text nodes, and exactly one element node,
    which itself must match <var>E</var>.</p><p>Example:
    <code>document-node(element(book))</code> matches a document node
    containing
    exactly one element node that is matched by the ElementTest
    <code>element(book)</code>.</p></li><li><p>The construct <code>document-node(<var>NTU</var>)</code>, where
                  <var>NTU</var> is a <a href="#prod-xquery40-NameTestUnion">NameTestUnion</a>, is
                  an abbreviation for <code>document-node(element(<var>NTU</var>))</code>.
                  For example, <code>document-node(*)</code> is an abbreviation for
                  <code>document-node(element(*))</code>, which matches any document node
                  corresponding to a well-formed XML document, that is, one that has
                  one element child, zero or more comment and processing-instruction children,
                  and no text node children.</p></li><li><p>An <a href="#doc-xquery40-ItemType">ItemType</a> that is an
    <a href="#doc-xquery40-ElementTest">ElementTest</a>, <a href="#doc-xquery40-SchemaElementTest">SchemaElementTest</a>, <a href="#doc-xquery40-AttributeTest">AttributeTest</a>,
    <a href="#doc-xquery40-SchemaAttributeTest">SchemaAttributeTest</a>, or <a href="#doc-xquery40-FunctionType">FunctionType</a> matches an item as described in the following sections.
    </p></li></ul></div><div class="div4">
<h5><a id="id-element-test"/>3.2.7.2 <a href="#id-element-test" style="text-decoration: none">Element Types</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-attribute-test">⬇</a> <a href="#node-types">⬆</a></p><ol><li><p>
                     Element and attribute tests of the form <code>element(N)</code>
                     and <code>attribute(N)</code> now allow <code>N</code> to be any <code>NameTest</code>,
                     including a wildcard.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/107">107</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/286">286</a> 17 January 2023]</i></p></li><li><p>
                     Element and attribute tests of the form <code>element(A|B)</code>
                     and <code>attribute(A|B)</code> are now allowed.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/23">23</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/606">606</a> 17 January 2023]</i></p></li><li><p>
                     Setting the default namespace for elements and types to the special value
                     <code>##any</code> causes an unprefixed element name to act as a wildcard,
                     matching by local name regardless of namespace.
                  </p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ElementTest"/><code><a href="#prod-xquery40-ElementTest">ElementTest</a></code></td><td>::=</td><td><code>"element"  "("  (<a href="#doc-xquery40-ElementTest-NameTestUnion">NameTestUnion</a>  (","  <a href="#doc-xquery40-ElementTest-TypeName">TypeName</a>  "?"?)?)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ElementTest-NameTestUnion"/><code><a href="#prod-xquery40-NameTestUnion">NameTestUnion</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ElementTest-NameTest">NameTest</a> ++ "|")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ElementTest-NameTest"/><code><a href="#prod-xquery40-NameTest">NameTest</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-ElementTest-EQName">EQName</a>  |  <a href="#doc-xquery40-ElementTest-Wildcard">Wildcard</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ElementTest-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ElementTest-Wildcard"/><code><a href="#prod-xquery40-Wildcard">Wildcard</a></code></td><td>::=</td><td><code>"*"<br/>|  (<a href="#prod-xquery40-NCName">NCName</a>  ":*")<br/>|  ("*:"  <a href="#prod-xquery40-NCName">NCName</a>)<br/>|  (<a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>  "*")</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ElementTest-TypeName"/><code><a href="#prod-xquery40-TypeName">TypeName</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-ElementTest-EQName">EQName</a>
                        </code></td></tr></tbody></table><p>
    An <a href="#doc-xquery40-ElementTest">ElementTest</a> is used to match an
    element node by its name and/or <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a>.
  </p><p>An unprefixed <a href="#doc-xquery40-EQName">EQName</a>
                  within the <code>NameTestUnion</code> is expanded using the
                  <a title="element name matching rule" class="termref" href="#dt-element-name-matching-rule">element name matching rule</a>.
                  The name need not be present in the <a title="in-scope attribute declarations" class="termref" href="#dt-is-attrs">in-scope element declarations</a>.
               </p><div class="note"><p class="prefix"><b>Note:</b></p><p>This means that when the 
                  <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>
               has the special value <code>##any</code>, an unprefixed name
               <var>N</var> is interpreted as a wildcard <code>*:<var>N</var>
                        </code>.</p><p>It is always possible to match no-namespace names explicitly
               by using the form <code>Q{}<var>N</var>
                        </code>
                     </p></div><p>An unprefixed <a href="#prod-xquery40-TypeName">TypeName</a> is expanded using the
                  <a title="default type namespace rule" class="termref" href="#dt-default-type-namespace-rule">default type namespace rule</a>.
                  The <a href="#prod-xquery40-TypeName">TypeName</a> must be present in the <a title="in-scope schema type" class="termref" href="#dt-is-types">in-scope schema types</a>
                     [<a href="#ERRXPST0008" title="err:XPST0008">err:XPST0008</a>]
                  </p><div class="note"><p class="prefix"><b>Note:</b></p><p>If the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>
                  has the special value <code>##any</code>, then an unprefixed type name
                  <var>T</var> is interpreted as <code>Q{http://www.w3.org/2001/XMLSchema}<var>T</var>
                        </code>.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>
                        <a title="substitution group" class="termref" href="#dt-substitution-group">Substitution groups</a> do not affect the semantics of <a href="#doc-xquery40-ElementTest">ElementTest</a>.</p></div><p>An <a href="#doc-xquery40-ElementTest">ElementTest</a>
                     <var>ET</var> matches an item <var>E</var> if the following conditions
                  are satisfied:</p><ol class="enumar"><li><p>
                           <var>E</var> is an element node.</p></li><li><p>If <var>ET</var> includes a <a href="#prod-xquery40-NameTestUnion">NameTestUnion</a>,
                           then the name of the element node <var>E</var> matches one or more of
                           the <a href="#prod-xquery40-NameTest">NameTests</a> in the <a href="#prod-xquery40-NameTestUnion">NameTestUnion</a>.
                           A name <var>N</var> matches a <a href="#prod-xquery40-NameTest">NameTest</a>
                           <var>NT</var> if one of the following
                           conditions is true:</p><ol class="enumla"><li><p>
                                 <var>NT</var> is <code>*</code>
                              </p></li><li><p>
                                 <var>NT</var> is <code>*:<em>local</em>
                                 </code> and the local part
                                 of <var>N</var> is <var>local</var>.</p></li><li><p>
                                 <var>NT</var> is <code>
                                    <em>prefix</em>:*</code> and the namespace URI
                                 of <var>N</var> matches the namespace URI bound to <var>prefix</var> in the static
                                 context.</p></li><li><p>
                                 <var>NT</var> is <code>
                                    <em>BracedURILiteral</em>*</code> and the namespace URI
                                 of <var>N</var> matches the namespace URI found in the <code>BracedURILiteral</code>.</p></li><li><p>
                                 <var>NT</var> is an <code>EQName</code> equal to <var>N</var>.</p></li></ol></li><li><p>If <var>ET</var> includes a <a href="#prod-xquery40-TypeName">TypeName</a>
                           <var>T</var>,
                           then the <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> of the element node <var>E</var>
                           <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                           <var>T</var>.</p></li><li><p>If <var>E</var> has the <code>nilled</code> property, then <var>ET</var>
                           either includes no <a href="#prod-xquery40-TypeName">TypeName</a>, 
                           or includes a <a href="#prod-xquery40-TypeName">TypeName</a> followed by the symbol <code>?</code>.</p></li></ol><p>Here are some examples of <a href="#doc-xquery40-ElementTest">ElementTests</a>:</p><ol class="enumar"><li><p>
                           <code>element()</code> and

<code>element(*)</code>  match any
single element node, regardless of its name or
type annotation.</p></li><li><p>
                           <code>element(person)</code> matches any element node whose name is <code>person</code>,
                        in the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>.</p></li><li><p>
                           <code>element(doctor|nurse)</code> matches any element node whose name is 
                        <code>doctor</code> or <code>nurse</code>,
                        in the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>.</p></li><li><p>
                           <code>element(xhtml:*)</code> matches any element node whose name is in the namespace
                        bound to the prefix <code>xhtml</code>.</p></li><li><p>
                           <code>element(xhtml:*|svg:*|mathml:*)</code> matches any element node whose name is one of the
                        three namespaces identified, specifically the namespaces bound to the prefixes
                        <code>xhtml</code>, <code>svg</code>, and <code>mathml</code>.</p></li><li><p>
                           <code>element(Q{http://www.w3.org/2000/svg}*)</code> matches any element node whose name is in the SVG namespace.</p></li><li><p>
                           <code>element(*:html)</code> matches any element node whose local name is <code>"html"</code>,
                     in any namespace.</p></li><li><p>
                           <code>element(person, surgeon)</code> matches a
non-nilled element node whose name is <code>person</code> and whose
type annotation is <code>surgeon</code> (or is derived from <code>surgeon</code>). </p></li><li><p>
                           <code>element(person, surgeon?)</code> matches a nilled or non-nilled element node whose name is <code>person</code> and whose type
annotation is <code>surgeon</code> (or is derived from <code>surgeon</code>).</p></li><li><p>
                           <code>element(*, surgeon)</code>
matches any non-nilled element node whose type annotation is
<code>surgeon</code> (or is derived from <code>surgeon</code>), regardless of its name.</p></li><li><p>
                           <code>element(*, surgeon?)</code>
matches any nilled or non-nilled element node whose type annotation is
<code>surgeon</code> (or is derived from <code>surgeon</code>), regardless of its name.</p></li></ol><p>
                  Where a <a href="#prod-xquery40-TypeName">TypeName</a> is included in an 
                  <a href="#doc-xquery40-ElementTest">ElementTest</a>
                     <var>T</var>, an element node will only
                  match the test if it has been validated against a schema that 
                  defines type <var>T</var>; furthermore, <var>T</var> must be
                  present in the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a> of the static context of the
                  <a href="#doc-xquery40-ElementTest">ElementTest</a>. Although it is guaranteed that
                  type <var>T</var> will have 
                  <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-schema-compatible">compatible</a><sup><small>DM</small></sup>
                  definitions in the schema that was used for validation and in the
                  <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a>, it is not guaranteed that revalidation
                  using the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a> would succeed. For example, if
                  substitution group membership varies between the two schemas, the element
                  node may contain children or descendants that the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a>
                  would not allow.
               </p><div class="note"><p class="prefix"><b>Note:</b></p><p>Technically, <code>element(p|q)</code> is not the same type as
               the choice item type <code>(element(p)|element(q))</code>. However, (a)
               they match exactly the same set of element nodes, and (b) each is a subtype
               of the other, so in practice they are indistinguishable.</p></div><div class="div5">
<h6><a id="id-schema-element-test"/>3.2.7.2.1 <a href="#id-schema-element-test" style="text-decoration: none">Schema Element Types</a></h6><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SchemaElementTest"/><code><a href="#prod-xquery40-SchemaElementTest">SchemaElementTest</a></code></td><td>::=</td><td><code>"schema-element"  "("  <a href="#doc-xquery40-SchemaElementTest-ElementName">ElementName</a>  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SchemaElementTest-ElementName"/><code><a href="#prod-xquery40-ElementName">ElementName</a></code></td><td>::=</td><td><code>
                              <a href="#doc-xquery40-SchemaElementTest-EQName">EQName</a>
                           </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SchemaElementTest-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                              <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                           </code></td></tr></tbody></table><p>
    A <a href="#doc-xquery40-SchemaElementTest">SchemaElementTest</a> matches an element node against a corresponding
    element declaration found in the <a title="in-scope element declarations" class="termref" href="#dt-is-elems">in-scope element declarations</a>.
  </p><p>
    The <a href="#prod-xquery40-ElementName">ElementName</a> of a <a href="#doc-xquery40-SchemaElementTest">SchemaElementTest</a>
    has its prefixes expanded to a namespace URI by means of the
    <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>, or if unprefixed, the
                  is interpreted according to the
                  <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>. If this has the special
                  value <code>"##any"</code>, an unprefixed name represents a name in no namespace.

    If the <a href="#prod-xquery40-ElementName">ElementName</a> specified in the <a href="#doc-xquery40-SchemaElementTest">SchemaElementTest</a>
    is not found in the <a title="in-scope element declarations" class="termref" href="#dt-is-elems">in-scope element declarations</a>, a
    <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXPST0008" title="err:XPST0008">err:XPST0008</a>].
  </p><p>
    A <a href="#doc-xquery40-SchemaElementTest">SchemaElementTest</a> matches a candidate element node if all of the following conditions are satisfied:
  </p><ol class="enumar"><li><p>Either:</p><ol class="enumla"><li><p>The name <var>N</var> of the candidate node matches the specified <a href="#prod-xquery40-ElementName">ElementName</a>, or</p></li><li><p>The name <var>N</var> of the candidate node matches the name of an element declaration 
                              that is a member of the actual substitution group headed by the declaration of element <a href="#prod-xquery40-ElementName">ElementName</a>.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>The term “actual substitution group” is defined in <a href="#XMLSchema11">[XML Schema 1.1]</a>. The actual substitution group of an element declaration 
                           <var>H</var> includes those element declarations 
                           <var>P</var> that are declared to have <var>H</var> as their 
                           direct or indirect substitution group head, provided that 
                           <var>P</var> is not declared as abstract, and that <var>P</var> 
                           is validly substitutable for <var>H</var>, which means that 
                           there must be no blocking constraints that prevent substitution.</p></div></li><li><p>The schema element declaration named <var>N</var> is not abstract.</p></li><li><p>
                              <var>AT</var>
                              <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                              <var>ET</var>,
                        where <var>AT</var> is the type annotation of the candidate node 
                        and <var>ET</var> is the schema type referenced by the <code>{type definition}</code> 
                        property of the global schema element declaration named <var>N</var>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>If the element declaration has no explicit <code>type</code> attribute
                        or <code>xs:simpleType</code> or <code>xs:complexType</code> child, but
                        is a member of a substitution group, then the <code>{type definition}</code> 
                        property defaults to the <code>{type definition}</code> of the first
                        element named in the <code>substitutionGroup</code> attribute.</p></div></li><li><p>If the schema element declaration named <var>N</var> 
                        is not nillable, then the <code>nilled</code> property of the candidate node 
                        is <code>false</code>.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>The broad intent of the <code>schema-element(<var>N</var>)</code> 
                  type is to select nodes that have been
                  validated (using strict or lax validation) against the global element declaration 
                  named <var>N</var>. An element that has been validated in this way will always match
                  the <code>schema-element</code> test. However, it is possible for an element node
                  to match the <code>schema-element(<var>N</var>)</code> test and yet be invalid against the element
                  declaration <var>N</var>. This can happen, for example, when 
                  (a) the element node has been validated against an
                  unrelated (local) element declaration having the same name and the same type, 
                  and (b) the global element
                  declaration imposes constraints beyond those implied by its 
                  <code>{type definition}</code> property. For example, the global element declaration
                  might define uniqueness constraints that are not present in the local element declaration
                  that was used for validation.</p></div><p>Example: The <a href="#doc-xquery40-SchemaElementTest">SchemaElementTest</a>
                        <code>schema-element(customer)</code> matches a candidate element node 
                  in the following two situations (among others):
</p><ol class="enumar"><li><p>
                                 <code>customer</code> is a top-level element declaration in the in-scope element declarations; 
                           the name of the candidate node is <code>customer</code>; the element declaration of <code>customer</code> 
                           is not abstract; the type annotation of the candidate node is the same as or 
                           derived from the schema type declared in the <code>customer</code> element declaration; 
                           and either the candidate node is not nilled, or <code>customer</code> is declared to be nillable.</p></li><li><p>
                                 <code>customer</code> is a top-level element declaration in the in-scope element declarations; 
                           the name of the candidate node is <code>client</code>; <code>client</code> is an actual 
                           (non-abstract and non-blocked) member of the substitution group of 
                           <code>customer</code>; the type annotation of the candidate node is the same as or 
                           derived from the schema type declared for the <code>client</code> element; 
                           and either the candidate node is not nilled, or <code>client</code> is 
                           declared to be nillable.</p></li></ol><p>
                  In the case where the schema <var>X</var> used to validate an element node 
                  <var>E</var> (whose name is <var>N</var>)
                  differs from the schema <var>Y</var> represented by the
                  <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a> in the static context of the 
                  <a href="#doc-xquery40-SchemaElementTest">SchemaElementTest</a>, the following
                  considerations apply:</p><ul><li><p>In applying the test <code>
                                 <var>AT</var> derives-from <var>ET</var>
                              </code>,
                  note that <var>AT</var> will necessarily be present in <var>X</var>,
                  but not necessarily in <var>Y</var>. However, <var>ET</var> will 
                  necessarily be present in both; and because the two schemas
                  must be <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-schema-compatible">compatible</a><sup><small>DM</small></sup>,
                  <var>ET</var> will be the present in both schemas, will have the same
                  definition in both, and will be the declared type of <var>N</var> in both.
                  The test can therefore be applied from knowledge of type <var>AT</var>
                  as defined in schema <var>X</var>.</p></li><li><p>The test as to whether the element name <var>N</var> is a member
                  of the actual substitution group is performed entirely by reference
                  to schema <var>Y</var>. Although the two schemas are compatible,
                  substitution group membership can vary.</p></li></ul></div></div><div class="div4">
<h5><a id="id-attribute-test"/>3.2.7.3 <a href="#id-attribute-test" style="text-decoration: none">Attribute Types</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-function-test">⬇</a> <a href="#id-element-test">⬆</a></p><ol><li><p>
                     Element and attribute tests of the form <code>element(N)</code>
                     and <code>attribute(N)</code> now allow <code>N</code> to be any <code>NameTest</code>,
                     including a wildcard.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/107">107</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/286">286</a> 17 January 2023]</i></p></li><li><p>
                     Element and attribute tests of the form <code>element(A|B)</code>
                     and <code>attribute(A|B)</code> are now allowed.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/23">23</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/606">606</a> 17 January 2023]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AttributeTest"/><code><a href="#prod-xquery40-AttributeTest">AttributeTest</a></code></td><td>::=</td><td><code>"attribute"  "("  (<a href="#doc-xquery40-AttributeTest-NameTestUnion">NameTestUnion</a>  (","  <a href="#doc-xquery40-AttributeTest-TypeName">TypeName</a>)?)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AttributeTest-NameTestUnion"/><code><a href="#prod-xquery40-NameTestUnion">NameTestUnion</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-AttributeTest-NameTest">NameTest</a> ++ "|")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AttributeTest-NameTest"/><code><a href="#prod-xquery40-NameTest">NameTest</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-AttributeTest-EQName">EQName</a>  |  <a href="#doc-xquery40-AttributeTest-Wildcard">Wildcard</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AttributeTest-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AttributeTest-Wildcard"/><code><a href="#prod-xquery40-Wildcard">Wildcard</a></code></td><td>::=</td><td><code>"*"<br/>|  (<a href="#prod-xquery40-NCName">NCName</a>  ":*")<br/>|  ("*:"  <a href="#prod-xquery40-NCName">NCName</a>)<br/>|  (<a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>  "*")</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AttributeTest-TypeName"/><code><a href="#prod-xquery40-TypeName">TypeName</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-AttributeTest-EQName">EQName</a>
                        </code></td></tr></tbody></table><p>
    An <a href="#doc-xquery40-AttributeTest">AttributeTest</a> is used to match an
    attribute node by its name and/or <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a>.
  </p><p>An unprefixed <a href="#doc-xquery40-EQName">EQName</a>
               within the <code>NameTestUnion</code> is expanded using the
                  <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.
                  The name need not be present in the <a title="in-scope attribute declarations" class="termref" href="#dt-is-attrs">in-scope attribute declarations</a>.</p><p>An unprefixed <a href="#prod-xquery40-TypeName">TypeName</a> is expanded using the <a title="default type namespace rule" class="termref" href="#dt-default-type-namespace-rule">default type namespace rule</a>.
                  The <a href="#prod-xquery40-TypeName">TypeName</a> must be present in the <a title="in-scope schema type" class="termref" href="#dt-is-types">in-scope schema types</a>
                     [<a href="#ERRXPST0008" title="err:XPST0008">err:XPST0008</a>]
                  </p><p>An <a href="#doc-xquery40-AttributeTest">AttributeTest</a>
                     <var>AT</var> matches an item <var>A</var> if the following conditions
                     are satisfied:</p><ol class="enumar"><li><p>
                           <var>A</var> is an attribute node.</p></li><li><p>If <var>AT</var> includes a <a href="#prod-xquery40-NameTestUnion">NameTestUnion</a>,
                        then the name of the attribute node <var>A</var> matches one or more of
                        the <a href="#prod-xquery40-NameTest">NameTests</a> in the <a href="#prod-xquery40-NameTestUnion">NameTestUnion</a>.
                        A name <var>N</var> matches a <a href="#prod-xquery40-NameTest">NameTest</a>
                           <var>NT</var> if one of the following
                        conditions is true:</p><ol class="enumla"><li><p>
                                 <var>NT</var> is <code>*</code>
                              </p></li><li><p>
                                 <var>NT</var> is <code>*:<em>local</em>
                                 </code> and the local part
                           of <var>N</var> matches <var>local</var>.</p></li><li><p>
                                 <var>NT</var> is <code>
                                    <em>prefix</em>:*</code> and the namespace URI
                           of <var>N</var> matches the namespace URI bound to <var>prefix</var> in the static
                           context.</p></li><li><p>
                                 <var>NT</var> is <code>
                                    <em>BracedURILiteral</em>*</code> and the namespace URI
                              of <var>N</var> matches the namespace URI found in the <code>BracedURILiteral</code>.</p></li><li><p>
                                 <var>NT</var> is an <code>EQName</code> equal to <var>N</var>.</p></li></ol></li><li><p>If <var>AT</var> includes a <a href="#prod-xquery40-TypeName">TypeName</a>
                           <var>T</var>,
                        then the <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> of the attribute node <var>A</var>
                           <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                           <var>T</var>.</p></li></ol><p>Here are some examples of <a href="#doc-xquery40-AttributeTest">AttributeTests</a>:
  </p><ul><li><p>
                           <code>attribute()</code> and <code>attribute(*)</code> match any single attribute node,
regardless of its name or type annotation.</p></li><li><p>
                           <code>attribute(price)</code>
                        matches any attribute node whose name is <code>price</code>
                        (in no namespace), regardless of its type annotation.</p></li><li><p>
                           <code>attribute(price|discount)</code>
                        matches any attribute node whose name is <code>price</code> or <code>discount</code>
                        (in no namespace).</p></li><li><p>
                           <code>attribute(xlink:*)</code> matches any attribute node whose name is in the namespace
                        bound to the prefix <code>xlink</code>.</p></li><li><p>
                           <code>element(Q{http://www.w3.org/2000/svg}*)</code> matches any attribute node whose name is in the SVG namespace.</p></li><li><p>
                           <code>attribute(*:default-collation)</code> matches any attribute node
                        whose local name is <code>default-collation</code>,
                        regardless of namespace, and regardless of type annotation.</p></li><li><p>
                           <code>attribute(*:price|*:discount)</code> matches any attribute node
                        whose local name is <code>price</code> or <code>discount</code>,
                        regardless of namespace, and regardless of type annotation.</p></li><li><p>
                           <code>attribute(price, currency)</code> matches an
attribute node whose name is <code>price</code> (in no namespace) and whose type
annotation is
<code>currency</code> (or is derived from <code>currency</code>).</p></li><li><p>
                           <code>attribute(xlink:*, xs:string)</code> matches any attribute node whose name is in the namespace
                        bound to the prefix <code>xlink</code>, and whose type annotation is <code>xs:string</code>
                     or a type derived from <code>xs:string</code>.</p></li><li><p>
                           <code>attribute(*, currency)</code> matches any attribute node whose
type annotation is <code>currency</code> (or is derived from <code>currency</code>), regardless of its
name.</p></li></ul><p>
                  Unlike the situation with an <a href="#doc-xquery40-ElementTest">ElementTest</a>,
                  few problems arise if the attribute was validated using a different
                  schema. This is because simple types can never be derived by extension,
                  and attributes do not have substitution groups.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Technically, <code>attribute(p|q)</code> is not the same type as
               the choice item type <code>(attribute(p)|attribute(q))</code>. However, (a)
               they match exactly the same set of attribute nodes, and (b) each is a subtype
               of the other, so in practice they are indistinguishable.</p></div><div class="div5">
<h6><a id="id-schema-attribute-test"/>3.2.7.3.1 <a href="#id-schema-attribute-test" style="text-decoration: none">Schema Attribute Types</a></h6><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SchemaAttributeTest"/><code><a href="#prod-xquery40-SchemaAttributeTest">SchemaAttributeTest</a></code></td><td>::=</td><td><code>"schema-attribute"  "("  <a href="#doc-xquery40-SchemaAttributeTest-AttributeName">AttributeName</a>  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SchemaAttributeTest-AttributeName"/><code><a href="#prod-xquery40-AttributeName">AttributeName</a></code></td><td>::=</td><td><code>
                              <a href="#doc-xquery40-SchemaAttributeTest-EQName">EQName</a>
                           </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SchemaAttributeTest-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                              <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                           </code></td></tr></tbody></table><p>
    A <a href="#doc-xquery40-SchemaAttributeTest">SchemaAttributeTest</a> matches an attribute node against a corresponding
    attribute declaration found in the <a title="in-scope attribute declarations" class="termref" href="#dt-is-attrs">in-scope attribute declarations</a>.
  </p><p>
    The <a href="#prod-xquery40-AttributeName">AttributeName</a> of a <a href="#doc-xquery40-SchemaAttributeTest">SchemaAttributeTest</a>
    has its prefixes expanded to a namespace URI by means of the
    <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>. If unprefixed, an
    <a href="#prod-xquery40-AttributeName">AttributeName</a> is in no namespace.

    If the <a href="#prod-xquery40-AttributeName">AttributeName</a> specified in the <a href="#doc-xquery40-SchemaAttributeTest">SchemaAttributeTest</a>
    is not found in the <a title="in-scope attribute declarations" class="termref" href="#dt-is-attrs">in-scope attribute declarations</a>, a
    <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXPST0008" title="err:XPST0008">err:XPST0008</a>].
  </p><p>
    A <a href="#doc-xquery40-SchemaAttributeTest">SchemaAttributeTest</a> matches a candidate attribute node if both of the
  following conditions are satisfied:
  </p><ol class="enumar"><li><p>The name of the candidate node matches the specified <a href="#prod-xquery40-AttributeName">AttributeName</a>.</p></li><li><p>
                              <var>AT</var>
                              <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                              <var>ET</var>,
                        where <var>AT</var> is the type annotation of the candidate node and 
                        <var>ET</var> is the schema type (always a simple type) referenced
                        by the <code>{type definition}</code> property of the attribute
                        declaration for attribute <a href="#prod-xquery40-AttributeName">AttributeName</a> in the <a title="in-scope attribute declarations" class="termref" href="#dt-is-attrs">in-scope attribute declarations</a>.</p></li></ol><p>Example: The <a href="#doc-xquery40-SchemaAttributeTest">SchemaAttributeTest</a>
                        <code>schema-attribute(color)</code> matches a candidate attribute node if <code>color</code> is a top-level attribute declaration in the <a title="in-scope attribute declarations" class="termref" href="#dt-is-attrs">in-scope attribute declarations</a>, the name of the candidate node is <code>color</code>, and the type annotation of the candidate node  is the same as or derived from the schema type declared for the <code>color</code> attribute.</p><p>
                  Unlike the situation with a <a href="#doc-xquery40-SchemaElementTest">SchemaElementTest</a>,
                  few problems arise if the attribute was validated using a different
                  schema. This is because attributes do not have substitution groups.</p></div></div></div><div class="div3">
<h4><a id="id-function-map-array-tests"/>3.2.8 <a href="#id-function-map-array-tests" style="text-decoration: none">Function, Map, and Array Types</a></h4><p>The following sections describe the syntax for <a title="item type" class="termref" href="#dt-item-type">item types</a>
            for functions, including arrays and maps.</p><p>The <a title="subtype" class="termref" href="#dt-subtype">subtype</a> relation among these types is described in the various subsections
            of <a href="#id-itemtype-subtype"><b>3.3.2 Subtypes of Item Types</b></a>.</p><div class="div4">
<h5><a id="id-function-test"/>3.2.8.1 <a href="#id-function-test" style="text-decoration: none">Function Types</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-record-test">⬇</a> <a href="#id-attribute-test">⬆</a></p><ol><li><p>The keyword <code>fn</code> is allowed as a synonym for <code>function</code>
                  in function types, to align with changes to inline function declarations.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1192">1192</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1197">1197</a> 21 May 2024]</i></p></li><li><p>The terms <b>FunctionType</b>, <b>ArrayType</b>,
                     <b>MapType</b>, and <b>RecordType</b> replace 
                     <b>FunctionTest</b>, <b>ArrayTest</b>,
                     <b>MapTest</b>, and <b>RecordTest</b>, with no
                  change in meaning.</p></li><li><p>
                     Parameter names may be included in a function signature; they are purely
                     documentary.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1136">1136</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1696">1696</a> 12 January 2025]</i></p></li></ol></div><p>A <a href="#doc-xquery40-FunctionType">FunctionType</a> matches selected <a title="function item" class="termref" href="#dt-function-item">function items</a>,
                  potentially checking their <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-signature">signature</a><sup><small>DM</small></sup>
                  (which includes the types of the arguments and results).</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionType"/><code><a href="#prod-xquery40-FunctionType">FunctionType</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-FunctionType-Annotation">Annotation</a>*  (<a href="#doc-xquery40-FunctionType-AnyFunctionType">AnyFunctionType</a>
                           <br/>|  <a href="#doc-xquery40-FunctionType-TypedFunctionType">TypedFunctionType</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionType-Annotation"/><code><a href="#prod-xquery40-Annotation">Annotation</a></code></td><td>::=</td><td><code>"%"  <a href="#doc-xquery40-FunctionType-EQName">EQName</a>  ("("  (<a href="#prod-xquery40-Constant">Constant</a> ++ ",")  ")")?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionType-AnyFunctionType"/><code><a href="#prod-xquery40-AnyFunctionType">AnyFunctionType</a></code></td><td>::=</td><td><code>("function"  |  "fn")  "("  "*"  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionType-TypedFunctionType"/><code><a href="#prod-xquery40-TypedFunctionType">TypedFunctionType</a></code></td><td>::=</td><td><code>("function"  |  "fn")  "("  (<a href="#doc-xquery40-FunctionType-TypedFunctionParam">TypedFunctionParam</a> ** ",")  ")"  "as"  <a href="#doc-xquery40-FunctionType-SequenceType">SequenceType</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionType-TypedFunctionParam"/><code><a href="#prod-xquery40-TypedFunctionParam">TypedFunctionParam</a></code></td><td>::=</td><td><code>("$"  <a href="#doc-xquery40-FunctionType-EQName">EQName</a>  "as")?  <a href="#doc-xquery40-FunctionType-SequenceType">SequenceType</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionType-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionType-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                           <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody></table><p>The keywords <code>function</code> and <code>fn</code> are synonyms.</p><p>If the <a href="#doc-xquery40-FunctionType"/> contains an 
               <a href="#doc-xquery40-Annotation"/>, then this is interpreted as a
               <a title="function assertion" class="termref" href="#dt-function-assertion">function assertion</a>, as described below.</p><p>An <a href="#prod-xquery40-AnyFunctionType">AnyFunctionType</a>
    matches any <a title="function item" class="termref" href="#dt-function-item">function item</a>, including a map or an array. For example,
    the following expressions all return true:</p><ul><li><p>
                           <code>fn:name#1 instance of function(*)</code>
                        </p></li><li><p>
                           <code>fn { @id } instance of function(*)</code>
                        </p></li><li><p>
                           <code>fn:random-number-generator() instance of function(*)</code>
                        </p></li><li><p>
                           <code>[ 1, 2, 3 ] instance of fn(*)</code>
                        </p></li><li><p>
                           <code>{} instance of fn(*)</code>
                        </p></li></ul><p>A <a href="#prod-xquery40-TypedFunctionType">TypedFunctionType</a> matches
    a <a title="function item" class="termref" href="#dt-function-item">function item</a> if the function’s type signature (as defined in
    <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#function-items">8.1 Function Items</a>) is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of the <a href="#prod-xquery40-TypedFunctionType">TypedFunctionType</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The keywords <code>function</code> and <code>fn</code> are synonymous.</p></div><p>If parameter names are included in a <a href="#prod-xquery40-TypedFunctionType">TypedFunctionType</a>,
               they are purely documentary and have no semantic effect. In particular, they
               play no part in deciding whether a particular function item matches the
               function type, and they never appear as keywords in function calls. 
               For example the construct
               <code>function($x as node()) as xs:string</code> designates exactly the same type
               as <code>function(node()) as xs:string</code>.</p><p>Any parameter names that are supplied must be distinct 
                  [<a href="#ERRXQST0039" title="err:XQST0039">err:XQST0039</a>].</p><p>A <a href="#prod-xquery40-TypedFunctionType">TypedFunctionType</a>
               may also match certain maps and arrays, as described in <a href="#id-map-test"><b>3.2.8.2 Map Types</b></a> and
               <a href="#id-array-test"><b>3.2.8.4 Array Types</b></a>
                  </p><p>
    Here are some examples of expressions that 
    use a <a href="#prod-xquery40-TypedFunctionType">TypedFunctionType</a>:
  </p><ul><li><p>
                           <code>fn:count#1 instance of function(item()*) as xs:integer</code> returns true,
                        because the signature of the function item <code>fn:count#1</code>
                        is <code>function(item()*) as xs:integer</code>.
                     </p></li><li><p>
                           <code>fn:count#1 instance of function(xs:string*) as item()</code> returns true,
                        because the signature of the function item <code>fn:count#1</code>
                        is a subtype of <code>function(xs:string*) as item()</code>.
                     </p><div class="note"><p class="prefix"><b>Note:</b></p><p>The same type might also be written 
                        <code>fn($x as xs:int, $y as xs:int) as xs:int</code>.</p></div></li><li class="xquery"><p>
                           <code>$F instance of %my:assertion function(*)</code> is true if
                        <code>$F</code> is a <a title="function item" class="termref" href="#dt-function-item">function</a> that satisfies the implementation-defined 
                        function assertion <code>%my:assertion</code>.
    </p></li><li class="xquery"><p>
                           <code>$F instance of %my:assertion function(xs:int, xs:int) as xs:int</code> 
                        is true if <code>$F</code> is a <a title="function item" class="termref" href="#dt-function-item">function item</a> with the function signature <code>function(xs:int, xs:int) as xs:int</code> 
                        that satisfies the implementation-defined function assertion <code>%my:assertion</code>.
    </p></li><li><p>
                           <code>function(xs:anyAtomicType) as item()*</code> matches any map, 
                        or any other function item with the required signature.</p></li><li><p>
                           <code>function(xs:integer) as item()*</code> matches any array, 
                        or any other function item with the required signature.</p></li></ul><p>
                     [<a id="dt-function-assertion" title="function assertion">Definition</a>:  A
    <b>function assertion</b> is a predicate that restricts the
    set of functions matched by a FunctionType. It uses the same
    syntax as <a href="#id-annotations"><b>5.15 Annotations</b></a>.] XQuery 4.0 does not currently
    define any function assertions, but future versions may. Other
    specifications in the XQuery family may also use function
    assertions in the future.</p><p>If the name of a function assertion is written as a <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>,
                  then it is expanded using the <a title="default annotation namespace rule" class="termref" href="#dt-default-annotation-namespace-rule">default annotation namespace rule</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>An unprefixed QName used 
                  within a <a title="function assertion" class="termref" href="#dt-function-assertion">function assertion</a> is taken to refer to the namespace
                  <code>http://www.w3.org/2012/xquery</code>. Since this is a 
                  <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespace</a>,
                  and no assertions are currently defined in this namespace, this means that
                  in practice, use of an unprefixed QName is always an error.
               </p></div><p>Implementations are free to define their own function
    assertions, whose behavior is completely implementation-defined. Implementations may also provide a way for
    users to define their own function assertions.</p><p>An implementation may raise implementation-defined
    errors or warnings for function assertions, for example if the parameters
    are not correct for a given assertion. If the namespace URI of a function 
    assertion’s <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> 
    is not recognized by an implementation, it is ignored, and has no
    effect on the semantics of the function type.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>An implementation is free to raise warnings for function
    assertions that it does not recognize.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Although function assertions use the same syntax as
    annotations, they are not directly related to annotations. If an
    implementation defines the annotation <code>blue</code> and uses it in
    function declarations, there is no guarantee that it will also
    define a function assertion <code>blue</code>, or that a function
    assertion named <code>blue</code> matches a function declared with
    the annotation <code>blue</code>. Of course, an implementation
    that does so may be more intuitive to users.</p></div><p>
    Implementations must not define function assertions in <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespaces</a>; it is is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
                     [<a href="#ERRXQST0045" title="err:XQST0045">err:XQST0045</a>] for a user to define a function assertion  in a <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespace</a>.

  
  </p></div><div class="div4">
<h5><a id="id-map-test"/>3.2.8.2 <a href="#id-map-test" style="text-decoration: none">Map Types</a></h5><p>A <a href="#doc-xquery40-MapType">MapType</a> designates an item type that
               either matches any map, or that matches maps whose keys and values
               are constrained to specific types.</p>
<a id="d2e9568"/><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MapType"/><code><a href="#prod-xquery40-MapType">MapType</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-MapType-AnyMapType">AnyMapType</a>  |  <a href="#doc-xquery40-MapType-TypedMapType">TypedMapType</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MapType-AnyMapType"/><code><a href="#prod-xquery40-AnyMapType">AnyMapType</a></code></td><td>::=</td><td><code>"map"  "("  "*"  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MapType-TypedMapType"/><code><a href="#prod-xquery40-TypedMapType">TypedMapType</a></code></td><td>::=</td><td><code>"map"  "("  <a href="#doc-xquery40-MapType-ItemType">ItemType</a>  ","  <a href="#doc-xquery40-MapType-SequenceType">SequenceType</a>  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MapType-ItemType"/><code><a href="#prod-xquery40-ItemType">ItemType</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-RegularItemType">RegularItemType</a>  |  <a href="#doc-xquery40-FunctionType">FunctionType</a>  |  <a href="#prod-xquery40-TypeName">TypeName</a>  |  <a href="#prod-xquery40-ChoiceItemType">ChoiceItemType</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MapType-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-MapType-ItemType">ItemType</a>
                           <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody></table><p>An <a href="#prod-xquery40-AnyMapType">AnyMapType</a>
                     <code>map(*)</code> matches any map.</p><p>The <a href="#doc-xquery40-MapType">MapType</a>
                     <code>map(K, V)</code> matches any map where every key
                  is an instance of <code>K</code> and every value is an
                  instance of <code>V</code>.</p><p>The <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-entry-order">entry-order</a><sup><small>DM</small></sup>
               of a map has no effect on whether the map matches a particular
               map type.</p><p>Although the grammar for <code>TypedMapType</code>
               allows the key to be described using the full <code>ItemType</code> syntax, the item type used must be
               a <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a>
                     [<a href="#ERRXPST0152" title="err:XPST0152">err:XPST0152</a>].</p><p>For example, given a map <code>$M</code> whose keys are integers and whose
  results are strings, such as <code>{ 0: "no", 1: "yes" }</code>,
  the following following expressions deliver the result shown:
  </p><ul><li><p>
                           <code>$M instance of map(*)</code>  returns <code>true()</code>
                        </p></li><li><p>
                           <code>$M instance of map(xs:integer, xs:string)</code>  returns <code>true()</code>
                        </p></li><li><p>
                           <code>$M instance of map(xs:decimal, xs:anyAtomicType)</code>  returns <code>true()</code>
                        </p></li><li><p>
                           <code>$M instance of map(xs:int, xs:string)</code>  returns <code>false()</code>
                        </p></li><li><p>
                           <code>$M instance of map(xs:integer, xs:token))</code>  returns <code>false()</code>
                        </p></li></ul><p>A map is also a function item, and therefore matches certain
               function types. Specifically, a map that matches <code>map(K, V)</code> also matches a function
               type of the form <code>function(xs:anyAtomicType) as R</code> provided that both the following
                  conditions are satisfied:</p><ul><li><p>
                           <var>V</var> is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of <var>R</var>
                        </p></li><li><p>
                           <code>empty-sequence()</code> is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of <var>R</var>
                        </p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>To understand this rule, consider the use of a map <code>$M</code> in a function 
                  call <code>$M($K)</code>, which is equivalent to the function call <code>map:get($M, $K)</code>.

                  This function accepts any atomic item for the argument <code>$K</code>, and hence matches
                  a function type that requires an argument type of <code>xs:anyAtomicType</code>. If the

                  key <code>$K</code> is present in the map, the result of the function will be a value of
                  type <var>V</var>; if not, it will be an empty sequence. The map is therefore substitutable
                  for the function type provided that the function type allows both a value of type <var>V</var>
                  and the empty sequence as possible results.</p><p>The key type <var>K</var> does not enter into this rule. That is because in the function call
                     <code>$M($K)</code>, the sought key <code>$K</code> does not have to be of the same
                  type as the keys actually present in the map.</p><p>The transitivity rules for item type matching mean that if an item <var>M</var>
                     matches a type <var>T</var>, and <var>T</var> is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> 
                     of <var>U</var>, then <var>M</var> also matches type <var>U</var>. So the fact
                  that a map from integers to strings (<code>map(xs:integer, xs:string)</code>)
                  matches <code>function(xs:anyAtomicType) as xs:string?</code>
                  means that it will also match other function types such as 
                     <code>function(xs:integer) as xs:string?</code> and 
                     <code>function(xs:decimal) as xs:anyAtomicType?</code>
                     </p><p>Furthermore, the rules for
                     <a title="function coercion" class="termref" href="#dt-function-coercion">function coercion</a> mean that any map can be supplied as a value in a
                     context where it does not actually match the required function type, but
                     can be coerced to a function that does. For example a map of type 
                     <code>map(xs:integer, xs:string)</code> can be coerced to a function of
                     type <code>function(xs:integer) as xs:string</code>; in this situation a type
                     error will occur only if a call on the function actually returns an empty sequence. </p></div><p>Examples:</p><ul><li><p>
                           <code>$M instance of fn(*)</code>  returns <code>true()</code>
                        </p></li><li><p>
                           <code>$M instance of fn(xs:anyAtomicType) as item()*</code> returns <code>true()</code>
                        </p></li><li><p>
                           <code>$M instance of fn(xs:integer) as item()*</code>  returns <code>true()</code>
                        </p></li><li><p>
                           <code>$M instance of fn(xs:int) as item()*</code>  returns <code>true()</code>
                        </p></li><li><p>
                           <code>$M instance of fn(xs:string) as item()*</code>  returns <code>true()</code>
                        </p></li><li><p>
                           <code>not($M instance of fn(xs:integer) as xs:string)</code>  returns <code>true()</code>
                        </p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>The last case might seem surprising; 
                     however, <a title="function coercion" class="termref" href="#dt-function-coercion">function coercion</a> ensures that <code>$M</code> can be used successfully 
  anywhere that the required type is <code>fn(xs:integer) as xs:string</code>.</p></div><p>Rules defining whether one map type is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of another
               are given in <a href="#id-item-subtype-maps"><b>3.3.2.7 Subtyping Maps</b></a>.</p></div><div class="div4">
<h5><a id="id-record-test"/>3.2.8.3 <a href="#id-record-test" style="text-decoration: none">Record Types</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-generalized-node-types">⬇</a> <a href="#id-function-test">⬆</a></p><ol><li><p>
                     Record types are added as a new kind of <code>ItemType</code>, constraining
                     the value space of maps.
                  </p></li><li><p>
                     The syntax <code>record(*)</code> is allowed; it matches any map.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/52">52</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/728">728</a> 10 October 2023]</i></p></li><li><p>
                     The syntax <code>record()</code> is allowed; the only thing it matches is an empty map.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1491">1491</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1577">1577</a> 17 October 2024]</i></p></li></ol></div><p>A <a href="#doc-xquery40-RecordType">RecordType</a> matches maps that meet specific criteria.</p><p>For example, the <code>RecordType</code>
                     <code>record(r as xs:double, i as xs:double)</code>
		             matches a map if the map has exactly two entries: an entry with key <code>"r"</code>
		                whose value is a <a title="singleton" class="termref" href="#dt-singleton">singleton</a>
                     <code>xs:double</code> value, and an entry with key <code>"i"</code>
		                whose value is also a <a title="singleton" class="termref" href="#dt-singleton">singleton</a>
                     <code>xs:double</code> value.</p><p>Record types describe a subset of the value space of maps. They do not define any new kinds of
		             values, or any additional operations. They are useful in many cases to describe more accurately the
		             type of a variable, function parameter, or function result, giving benefits both in the readability
		             of the code, and in the ability of the processor to detect and diagnose type errors and to optimize
		             execution.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RecordType"/><code><a href="#prod-xquery40-RecordType">RecordType</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-RecordType-AnyRecordType">AnyRecordType</a>  |  <a href="#doc-xquery40-RecordType-TypedRecordType">TypedRecordType</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RecordType-AnyRecordType"/><code><a href="#prod-xquery40-AnyRecordType">AnyRecordType</a></code></td><td>::=</td><td><code>"record"  "("  "*"  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RecordType-TypedRecordType"/><code><a href="#prod-xquery40-TypedRecordType">TypedRecordType</a></code></td><td>::=</td><td><code>"record"  "("  (<a href="#doc-xquery40-RecordType-FieldDeclaration">FieldDeclaration</a> ** ",")  <a href="#doc-xquery40-RecordType-ExtensibleFlag">ExtensibleFlag</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RecordType-FieldDeclaration"/><code><a href="#prod-xquery40-FieldDeclaration">FieldDeclaration</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-RecordType-FieldName">FieldName</a>  "?"?  ("as"  <a href="#doc-xquery40-RecordType-SequenceType">SequenceType</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RecordType-FieldName"/><code><a href="#prod-xquery40-FieldName">FieldName</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-NCName">NCName</a>  |  <a href="#doc-xquery40-RecordType-StringLiteral">StringLiteral</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RecordType-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RecordType-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                           <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RecordType-ExtensibleFlag"/><code><a href="#prod-xquery40-ExtensibleFlag">ExtensibleFlag</a></code></td><td>::=</td><td><code>","  "*"</code></td></tr></tbody></table><p>If the list of fields ends with <code>",*"</code> then the record type is said to be
		                <b>extensible</b>. For example, the <code>RecordType</code>
                     <code>record(e as element(Employee), *)</code>
		             matches a map if it has an entry with key <code>"e"</code> whose value matches <code>element(Employee)</code>,
		             regardless what other entries the map might contain.</p><p>For generality:</p><ul><li><p>The syntax <code>record()</code> defines a record type that has no explicit fields and that
                  is not extensible. The only thing it matches is an <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-empty-map">empty map</a><sup><small>DM</small></sup>.</p></li><li><p>The syntax <code>record(*)</code> defines an extensible record type that has no explicit
                  field declarations. It is equivalent to the item type
                  <code>map(*)</code>: that is, it matches any map.</p></li></ul><p>A record type can constrain only those entries whose keys are strings, but when the record
		             type is marked as extensible, then other entries may be present in the map with either string or non-string keys.
		             Entries whose key is a string can be expressed using an (unquoted) NCName if the key conforms to
		             NCName syntax, or using a (quoted) string literal otherwise.</p><p>Although constructors for named record types produce a map in which the
                  <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-entry-order">entry order</a><sup><small>DM</small></sup> reflects
                  the order of field definitions in the record type definition,
                  the <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-entry-order">entry order</a><sup><small>DM</small></sup>
                  of a map has no effect on whether the map matches a particular
                  record type: the entries in a map do not have to be in any particular order.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Lookup expressions have been extended in 4.0 so that non-NCName keys can be used without
		             parentheses: <code>employee?"middle name"</code>
                     </p></div><p>If the type declaration for a field is omitted, then <code>item()*</code> is assumed: that is,
		             the map entry may have any type.</p><p>If the field name is followed by a question mark,
		             then the value must have the specified type if it is present, but it may also be absent. For example,
		             the <code>RecordType</code>
                     <code>record(first as xs:string, middle? as xs:string, last as xs:string, *)</code>
		                requires the map to have string-valued entries with keys <code>"first"</code> and <code>"last"</code>;
		                it also declares that if the map has an entry with key <code>"middle"</code>, the value of that
		                entry must be a single <code>xs:string</code>. Declaring the type as 
		                <code>record(first as xs:string, middle? as xs:string?, last as xs:string, *)</code> also allows
		             the entry with key <code>"middle"</code> to be present but empty.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Within an extensible record type, a <code>FieldDeclaration</code> that is marked optional 
                     and has no declared type does not constrain the
                     map in any way, so it serves no practical purpose, but it is permitted because it may have
                     documentary value.</p></div><p>The names of the fields in a record type must be distinct [<a href="#ERRXPST0021" title="err:XPST0021">err:XPST0021</a>].</p><p>If a variable <code>$rec</code> is known to conform to a particular
		             record type, then when a lookup expression <code>$rec?field</code> is used, (a) the processor
		             can report a type error if <code>$rec</code> cannot contain an entry with name <code>field</code>
                   (see <a href="#id-implausible-lookup-expressions"><b>4.14.3.4 Implausible Lookup Expressions</b></a>),
		             and (b) the processor can make static type inferences about the type of value returned by 
		             <code>$rec?field</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>(TODO: change function signatures as suggested here!) A number of functions in the standard 
                     function library use maps as function arguments;
		                this is a useful technique where the information to be supplied across the interface is highly
		                variable. However, the type signature for such functions typically declares the argument type
		                as <code>map(*)</code>, which gives very little information (and places very few constraints)
		                on the values that are actually passed across. Using record types offers the possibility of
		                improving this: for example, the options argument of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-parse-json"><code>fn:parse-json</code></a>, previously
		                given as <code>map(*)</code>, can now be expressed as <code>record(liberal? as xs:boolean, 
		                   duplicates? as xs:string, escape? as xs:boolean, fallback as fn(xs:string) as xs:string, *)</code>.
		                In principle the <code>xs:string</code> type used to describe the <code>duplicates</code>
		                   option could also be replaced by a schema-defined subtype
		                of <code>xs:string</code> that enumerates the permitted values (<code>"reject"</code>,
		                   <code>"use-first"</code>, <code>"use-last"</code>). 
		                </p><p>The use of a record type in the signature of such a function causes the 
		                   <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>
		                to be invoked. So, for example, if the function expects an entry in the map to be an <code>xs:double</code>
		                value, it becomes possible to supply a map in which the corresponding entry has type <code>xs:integer</code>.</p><p>Greater precision in defining the types of such arguments also enables better type checking,
		                better diagnostics, better optimization, better documentation, and better syntax-directed
		                editing tools.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>One of the motivations for introducing record types is to enable better pattern matching
		             in XSLT when processing JSON input. With XML input, patterns are often based
		             around XML element names. JSON has no direct equivalent of XML’s element names; matching a JSON object
		             such as <code>{longitude: 130.2, latitude: 53.4}</code> relies instead on recognizing the property
		             names appearing in the object. XSLT 4.0, by integrating record types into pattern matching syntax,
		             allows such an object to be matched with a pattern of the form 
		                <code>match="record(longitude, latitude)"</code>
                     </p></div><p>Rules defining whether one record type is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of another
                  are given in <a href="#id-item-subtype-records"><b>3.3.2.9 Subtyping Records</b></a>.</p><div class="div5">
<h6><a id="id-recursive-record-tests"/>3.2.8.3.1 <a href="#id-recursive-record-tests" style="text-decoration: none">Recursive Record Types</a></h6><p>A named record type <var>N</var> is said to be recursive if its 
                  definition includes a direct or indirect reference to <var>N</var>. 
               </p><p>For example, the following XQuery declaration defines a linked list:</p><div class="exampleInner"><pre>declare record my:list (value as item()*, next? as my:list);</pre></div><p>The equivalent in XSLT is:</p><div class="exampleInner"><pre>&lt;xsl:record-type name="my:list"&gt;
   &lt;xsl:field name="value" as="item()*"/&gt;
   &lt;xsl:field name="next" as="my:list" required="no"/&gt;
&lt;/xsl:record-type&gt;</pre></div><p>Instances of recursive record types can be constructed and interrogated in the normal way.
               For example a list of length 3 can be constructed as:</p><div class="exampleInner"><pre>{ "value": 1, "next": { "value": 2, "next": { "value": 3 } } }</pre></div><p>and the third value in the map can be retrieved as <code>$list?next?next?value</code>.
               In practice, recursive data structures are usually manipulated using recursive functions.</p><p>It is possible to define a recursive record type that cannot be instantiated, because it
               has no finite instances: for example (in XQuery) <code>declare record X (next as X);</code>.
               Such a record declaration is <a title="implausible" class="termref" href="#dt-implausible">implausible</a>, so the processor may
               treat it as an error [<a href="#ERRXPST0023" title="err:XPST0023">err:XPST0023</a>], but it is not obliged to do so.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>For an example of a practical use of recursive record types, see the
               specification of the function <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-random-number-generator"><code>fn:random-number-generator</code></a>.</p></div><p>Recursive type definitions need to be handled specially by the subtyping rules; 
                  a naïve approach of simply replacing each reference to a named item type 
               with its definition would make the assessment of the subtype relationship non-terminating.
               For details see <a href="#id-itemtype-subtype"><b>3.3.2 Subtypes of Item Types</b></a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>While record types may be recursive, it is not possible to construct
               instances containing cyclic references. Specifically, if an instance <var>A</var> contains a reference
               to <var>B</var> then it is not possible for <var>B</var> to contain a reference to <var>A</var>.
               This is because <var>A</var> cannot contain a reference to <var>B</var>
               unless <var>B</var> exists at the time <var>A</var> is created, and since all values
               are immutable, <var>B</var> cannot subsequently be updated to refer to <code>A</code>.</p><p>The simplest workaround for this is to make the references indirect, via some kind of index
               based on application-allocated unique identifiers.</p><p>The data model does not forbid cycles among instances, and indeed, there are functions
               such as <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-schema-type"><code>fn:schema-type</code></a> that may return cyclic instances. However, such
               cycles can only be constructed using mechanisms beyond the capabilities of XQuery 4.0.
               (The structure returned by <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-schema-type"><code>fn:schema-type</code></a> carefully uses functions
               to represent references from one value to another, rather than making the 
               references direct. This reduces the danger that
               operations such as serialization will be non-terminating. However, it does not remove
               the difficulty that the structure cannot be built using XQuery 4.0 alone.)</p></div><div class="example">
<div class="exampleHeader"><a id="e-binary-tree"/>Example: A Binary Tree</div><p>A record used to represent a node in a binary tree might be represented (using XQuery syntax) as:</p><div class="exampleInner"><pre>declare record t:binary-tree 
   ( left? as t:binary-tree, 
     value as item()*, 
     right? as t:binary-tree
   )</pre></div><p>A recursive function to walk this tree and enumerate all the values in depth-first order might be written 
                     (again using XQuery syntax) as:</p><div class="exampleInner"><pre>declare function t:values($tree as t:binary-tree?) as item()* {
  $tree ! (t:values(?left), ?value, t:values(?right))   
}</pre></div></div><p> </p><div class="example">
<div class="exampleHeader"><a id="e-arbitrary-tree"/>Example: An Arbitrary Tree</div><p>A record used to represent a node in a tree where each node has an arbitrary number
                     of children might be represented (using XQuery syntax) as:</p><div class="exampleInner"><pre>declare record t:tree as (value, children as t:tree*);</pre></div><p>A function to walk this tree and enumerate all the values in order might be written 
                     as:</p><div class="exampleInner"><pre>declare function t:flatten($tree as t:tree) as item()* {
  $tree?value, $tree?children ! t:flatten(.))   
}</pre></div></div></div></div><div class="div4">
<h5><a id="id-array-test"/>3.2.8.4 <a href="#id-array-test" style="text-decoration: none">Array Types</a></h5><p>An <a href="#doc-xquery40-ArrayType">ArrayType</a> designates an item type that
               either matches all arrays, or that matches arrays whose members
               are constrained to a specific type.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrayType"/><code><a href="#prod-xquery40-ArrayType">ArrayType</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-ArrayType-AnyArrayType">AnyArrayType</a>  |  <a href="#doc-xquery40-ArrayType-TypedArrayType">TypedArrayType</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrayType-AnyArrayType"/><code><a href="#prod-xquery40-AnyArrayType">AnyArrayType</a></code></td><td>::=</td><td><code>"array"  "("  "*"  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrayType-TypedArrayType"/><code><a href="#prod-xquery40-TypedArrayType">TypedArrayType</a></code></td><td>::=</td><td><code>"array"  "("  <a href="#doc-xquery40-ArrayType-SequenceType">SequenceType</a>  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrayType-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                           <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody></table><p>An <a href="#prod-xquery40-AnyArrayType">AnyArrayType</a>
                     <code>array(*)</code> matches any array.</p><p>The <a href="#prod-xquery40-TypedArrayType">TypedArrayType</a>
                     <code>array(X)</code> matches any array
  in which every array member matches the <a href="#doc-xquery40-SequenceType">SequenceType</a>
                     <code>X</code>.</p><p>Examples:</p><ul><li><p>
                           <code>[ 1, 2 ] instance of array(*)</code> returns <code>true()</code>
                        </p></li><li><p>
                           <code>[] instance of array(xs:string)</code> returns <code>true()</code>
                        </p></li><li><p>
                           <code>[ "foo" ] instance of array(xs:string)</code> returns <code>true()</code>
                        </p></li><li><p>
                           <code>[ "foo" ] instance of array(xs:integer)</code> returns <code>false()</code>
                        </p></li><li><p>
                           <code>[ (1, 2), (3, 4) ] instance of array(xs:integer)</code> returns <code>false()</code>
                        </p></li><li><p>
                           <code>[ (1, 2), (3, 4) ] instance of array(xs:integer+)</code> returns <code>true()</code>
                        </p></li><li><p>
                           <code>[ [ 1, 2 ], [ 3, 4 ] ] instance of array(array(xs:integer+))</code> returns <code>true()</code>
                        </p></li></ul><p>An array also matches certain other <a title="item type" class="termref" href="#dt-item-type">item types</a>, 
                  including:</p><ul><li><p>
                           <code>item()</code>
                        </p></li><li><p>
                           <code>function(*)</code>
                        </p></li><li><p>
                           <code>function(xs:integer) as item()*</code>
                        </p></li></ul><p>An array that matches <code>array(T)</code>
                  also matches the function type <code>function(xs:integer) as T</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>To understand this rule, consider the use of an array <code>$A</code> in a function 
                     call <code>$A($I)</code>, which is equivalent to the function call <code>array:get($A, $I)</code>.
                     This function accepts any integer for the argument <code>$I</code>, and the result
                     will either be an instance of <var>T</var>, or an error.</p><p>The transitivity rules for item type matching mean that if an item <var>A</var>
                     matches a type <var>T</var>, and <var>T</var> is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> 
                     of <var>U</var>, then <var>A</var> also matches type <var>U</var>. So the fact
                     that an array of strings (<code>array(xs:string)</code>)
                     matches <code>function(xs:integer) as xs:string</code>
                     means that it will also match other function types such as 
                     <code>function(xs:long) as item()*</code>.</p><p>Furthermore, the rules for
                     <a title="function coercion" class="termref" href="#dt-function-coercion">function coercion</a> mean that any array can be supplied as a value in a
                        context where it does not actually match the required function type, but
                        can be coerced to a function that does. For example an array of type 
                        <code>array(node())</code> can be coerced to a function of
                        type <code>function(xs:integer) as element()</code>; in this situation a type
                        error will occur only if a call on the function actually returns a node
                        that is not an element node.</p></div><p>Rules defining whether one array type is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of another
                  are given in <a href="#id-item-subtype-arrays"><b>3.3.2.8 Subtyping Arrays</b></a>.</p></div></div><div class="div3">
<h4><a id="id-generalized-node-types"/>3.2.9 <a href="#id-generalized-node-types" style="text-decoration: none">Generalized Node Types</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-sequencetype-subtype">⬇</a> <a href="#id-record-test">⬆</a></p><ol><li><p>
                     JNodes are introduced
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2025">2025</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2031">2031</a> 13 June 2025]</i></p></li></ol></div><p>A <a href="#doc-xquery40-GNodeType">GNodeType</a> matches a generalized node (<a title="GNode" class="termref" href="#dt-GNode">GNode</a>):
                  that is, it matches any <a title="XNode" class="termref" href="#dt-XNode">XNode</a>
                  or <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-JNode">JNode</a><sup><small>DM</small></sup>.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-GNodeType"/><code><a href="#prod-xquery40-GNodeType">GNodeType</a></code></td><td>::=</td><td><code>"gnode"  "("  ")"</code></td></tr></tbody></table><p>A <a href="#doc-xquery40-JNodeType">JNodeType</a> matches a <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-JNode">JNode</a><sup><small>DM</small></sup>.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-JNodeType"/><code><a href="#prod-xquery40-JNodeType">JNodeType</a></code></td><td>::=</td><td><code>"jnode"  "("  <a href="#doc-xquery40-JNodeType-SequenceType">SequenceType</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-JNodeType-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                        <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody></table><p>The form <code>jnode()</code> matches any JNode. The form
               <code>jnode(<var>T</var>)</code> matches a JNode whose <b>·content·</b> is an instance
               of the sequence type <var>T</var>.</p></div><div class="div3">
<h4><a id="id-xs-error"/>3.2.10 <a href="#id-xs-error" style="text-decoration: none">The type <code>xs:error</code>
               </a></h4><p>The item type <code>xs:error</code> has an empty value space; 
                  it never appears as a dynamic type or as the content type of a dynamic element or attribute type. 
                  
                  
                  It was defined in XML Schema in the interests of making the type system complete and closed, 
                  and it is also available in XQuery 4.0 for similar reasons.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Even though it cannot occur in an instance, <code>xs:error</code> is a valid type name in a sequence type. The
                     practical uses of <code>xs:error</code> as a sequence type are limited, but they do exist. For instance, an error-handling function that always raises a dynamic error 
                     never returns a value, so <code>xs:error</code> is a good choice for the return type of the function.</p><p>The semantics of <code>xs:error</code> are well defined as a consequence of the fact that <code>xs:error</code> is defined as a union type with
                     no member types. For example:</p><ul><li><p>
                           <code>$x instance of xs:error</code> always returns <code>false</code>, regardless of the value of <code>$x</code>.</p></li><li><p>
                           <code>$x cast as xs:error</code> fails dynamically with error [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFORG0001" title="err:FORG0001">err:FORG0001</a>]<sup><small>FO40</small></sup>,  regardless of the value of <code>$x</code>.</p></li><li><p>
                           <code>$x cast as xs:error?</code> raises a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>
                           [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFORG0001" title="err:FORG0001">err:FORG0001</a>]<sup><small>FO40</small></sup> if <code>exists($x)</code> returns <code>true</code>, and evaluates to the empty sequence if <code>empty($x)</code> returns <code>true</code>.</p></li><li><p>
                           <code>xs:error($x)</code> has the same semantics as <code>$x cast as xs:error?</code> (see the previous bullet point)</p></li><li><p>
                           <code>$x castable as xs:error</code> evaluates to <code>false</code>, regardless of the value of <code>$x</code>.</p></li><li><p>
                           <code>$x treat as xs:error</code>  raises a <a title="type error" class="termref" href="#dt-type-error">type error</a>
                           [<a href="#ERRXPDY0050" title="err:XPDY0050">err:XPDY0050</a>], regardless of the value of <code>$x</code>.</p></li><li class="xquery"><p>
                           <code>let $x as xs:error := 1 return 2</code>  raises a <a title="type error" class="termref" href="#dt-type-error">type error</a>
                           [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>], which can be raised statically or dynamically, and need not be raised if the variable <code>$x</code> is never evaluated by the query processor.</p></li><li class="xquery"><p>
                           <code>declare function ns:f($arg as xs:error) {...};</code> is a valid function declaration, but it always  raises a <a title="type error" class="termref" href="#dt-type-error">type error</a>
                           [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>] if the function is called.</p></li></ul><p>All of the above examples assume that <code>$x</code> is actually evaluated. The rules specified in <a href="#id-errors-and-opt"><b>2.4.4 Errors and
      Optimization</b></a> permit an implementation to avoid evaluating <code>$x</code> if the result of the query does not depend upon the value of <code>$x</code> and thus to avoid raising an error.</p></div></div></div><div class="div2">
<h3><a id="id-sequencetype-subtype"/>3.3 <a href="#id-sequencetype-subtype" style="text-decoration: none">Subtype Relationships</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-item-subtype-documents">⬇</a> <a href="#id-generalized-node-types">⬆</a></p><ol><li><p>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.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/196">196</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/202">202</a> 25 October 2022]</i></p></li></ol></div><p>
               [<a id="dt-subtype" title="subtype">Definition</a>: Given two 
               <a title="sequence type" class="termref" href="#dt-sequence-type">sequence types</a>
               or <a title="item type" class="termref" href="#dt-item-type">item types</a>, the rules in this section determine if one 
               is a <b>subtype</b> of the other. If a type <var>A</var> is a subtype of type <var>B</var>,
               it follows that every value matched by <var>A</var> is also matched by <var>B</var>.]
            </p><div class="note"><p class="prefix"><b>Note:</b></p><p>The relationship <code>subtype(A, A)</code> is always true:
               every type is a subtype of itself.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The converse is not necessarily true: we cannot infer that 
               if every value matched by <var>A</var> is also matched by <var>B</var>, then 
               <var>A</var> is a subtype of type <var>B</var>. For example, <var>A</var> might be
            defined as the set of strings matching the regular expression <code>[A-Z]*</code>, while <var>B</var>
            is the set of strings matching the regular expression <code>[A-Za-z]*</code>; no subtype
            relationship holds between these types.</p></div><p>The rules for deciding whether one <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a> is a subtype
               of another are given in <a href="#id-seqtype-subtype"><b>3.3.1 Subtypes of Sequence Types</b></a>. The rules for deciding whether
               one <a title="item type" class="termref" href="#dt-item-type">item type</a> is a subtype of another are given in <a href="#id-itemtype-subtype"><b>3.3.2 Subtypes of Item Types</b></a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The subtype relationship is not acyclic. There are cases where <code>subtype(A, B)</code> and
               <code>subtype(B, A)</code> are both true. This implies that <var>A</var> and <var>B</var>
               have the same value space, but they can still be different types. For example this applies when <var>A</var>
               is a union type with member types <code>xs:string</code> and <code>xs:integer</code>, while 
               <var>B</var> is a union type with member types <code>xs:integer</code> and <code>xs:string</code>.
               These are different types (<code>"23" cast as A</code> produces a string, while <code>"23" cast as B</code>
               produces an integer, because casting is attempted to each member type in order) but both types have the same value space.
            </p></div><div class="div3">
<h4><a id="id-seqtype-subtype"/>3.3.1 <a href="#id-seqtype-subtype" style="text-decoration: none">Subtypes of Sequence Types</a></h4><p>We use the notation <code>A ⊑ B</code>, or <code>subtype(A, B)</code> to indicate that
                  a <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>
                  <code>A</code> is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of a sequence type <code>B</code>.
               This section defines the rules for deciding whether any two sequence types have this relationship.</p><p>To define the rules, we divide sequence types into six categories:</p><ul><li><p>The category <code>empty</code> includes the sequence types <code>empty-sequence()</code>,
                   <code>xs:error*</code> and <code>xs:error?</code>. All these sequence types
                  match the empty sequence as their only instance.</p></li><li><p>The category <code>void</code> includes the sequence types <code>xs:error</code> and <code>xs:error+</code>,
                  which have no instances (not even the empty sequence).</p></li><li><p>The categories <code>X?</code>, <code>X*</code>, <code>X</code> and <code>X+</code> includes all sequence types 
                     having an item type <code>X</code> other than <code>xs:error</code>, together with an occurrence indicator of 
                     <code>?</code> (zero or more), <code>*</code> (one or more), absent (exactly one), or <code>+</code> (one or more)
                     respectively. We use the notation <var>X<sub>i</sub></var> to indicate the item type of such a sequence type.</p></li></ul><p>The judgement <code>A ⊑ B</code> is then determined by the categories of the two sequence types, as defined
               in the table below. In many cases this depends on the relationship between the item types of <code>A</code>
                  and <code>B</code>. This is denoted using the notation <code>
                     <var>A<sub>i</sub></var> ⊆ <var>B<sub>i</sub></var>
                  </code>, 
                  as defined in <a href="#id-itemtype-subtype"><b>3.3.2 Subtypes of Item Types</b></a>.</p><table class="medium"><tbody><tr><th rowspan="2" colspan="2"/><th colspan="6">
                           <a title="sequence type" class="termref" href="#dt-sequence-type">Sequence type</a>
                           <var>B</var>
                        </th></tr><tr><th>
                           <code>empty</code>
                        </th><th>
                           <code>
                              <var>B<sub>i</sub></var>?</code>
                        </th><th>
                           <code>
                              <var>B<sub>i</sub></var>*</code>
                        </th><th>
                           <code>
                              <var>B<sub>i</sub></var>
                           </code>
                        </th><th>
                           <code>
                              <var>B<sub>i</sub></var>+</code>
                        </th><th>
                           <code>void</code>
                        </th></tr><tr><th rowspan="6">
                           <a title="sequence type" class="termref" href="#dt-sequence-type">Sequence type</a>
                           <var>A</var>
                        </th><th>
                           <code>empty</code>
                        </th><td>true</td><td>true</td><td>true</td><td>false</td><td>false</td><td>false</td></tr><tr><th>
                           <code>
                              <var>A<sub>i</sub></var>?</code>
                        </th><td>false</td><td>
                           <code>
                              <var>A<sub>i</sub></var> ⊆ <var>B<sub>i</sub></var>
                           </code>
                        </td><td>
                           <code>
                              <var>A<sub>i</sub></var> ⊆ <var>B<sub>i</sub></var>
                           </code>
                        </td><td>false</td><td>false</td><td>false</td></tr><tr><th>
                           <code>
                              <var>A<sub>i</sub></var>*</code>
                        </th><td>false</td><td>false</td><td>
                           <code>
                              <var>A<sub>i</sub></var> ⊆ <var>B<sub>i</sub></var>
                           </code>
                        </td><td>false</td><td>false</td><td>false</td></tr><tr><th>
                           <code>
                              <var>A<sub>i</sub></var>
                           </code>
                        </th><td>false</td><td>
                           <code>
                              <var>A<sub>i</sub></var> ⊆ <var>B<sub>i</sub></var>
                           </code>
                        </td><td>
                           <code>
                              <var>A<sub>i</sub></var> ⊆ <var>B<sub>i</sub></var>
                           </code>
                        </td><td>
                           <code>
                              <var>A<sub>i</sub></var> ⊆ <var>B<sub>i</sub></var>
                           </code>
                        </td><td>
                           <code>
                              <var>A<sub>i</sub></var> ⊆ <var>B<sub>i</sub></var>
                           </code>
                        </td><td>false</td></tr><tr><th>
                           <code>
                              <var>A<sub>i</sub></var>+</code>
                        </th><td>false</td><td>false</td><td>
                           <code>
                              <var>A<sub>i</sub></var> ⊆ <var>B<sub>i</sub></var>
                           </code>
                        </td><td>false</td><td>
                           <code>
                              <var>A<sub>i</sub></var> ⊆ <var>B<sub>i</sub></var>
                           </code>
                        </td><td>false</td></tr><tr><th>
                           <code>void</code>
                        </th><td>true</td><td>true</td><td>true</td><td>true</td><td>true</td><td>true</td></tr></tbody></table></div><div class="div3">
<h4><a id="id-itemtype-subtype"/>3.3.2 <a href="#id-itemtype-subtype" style="text-decoration: none">Subtypes of Item Types</a></h4><p>We use the notation <code>A ⊆ B</code>, or <code>itemtype-subtype(A, B)</code> to indicate that
                  an <a title="item type" class="termref" href="#dt-item-type">item type</a>
                  <code>A</code> is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of an item type <code>B</code>.
                  This section defines the rules for deciding whether any two item types have this relationship.</p><p>The rules in this section apply to 
                  <a title="item type" class="termref" href="#dt-item-type">item types</a>, not to 
                  <a title="item type designator" class="termref" href="#dt-item-type-designator">item type designators</a>.
                  For example, if the name <code>STR</code> has been defined in the
                  static context as a <a title="named item type" class="termref" href="#dt-named-item-type">named item type</a> referring to the type <code>xs:string</code>,
                  then anything said here about the type <code>xs:string</code> applies equally
                  whether it is designated as <code>xs:string</code> or as <code>STR</code>,
                  or indeed as the parenthesized forms <code>(xs:string)</code> or
                 <code>(STR)</code>.</p><p>References to <a title="named item type" class="termref" href="#dt-named-item-type">named item types</a> 
                  are handled as described in <a href="#id-itemtype-subtype-aliases"><b>3.3.2.10 Subtyping of Named Item Types</b></a>.</p><p>The relationship <code>A ⊆ B</code> is true
               if and only if at least one of the conditions listed in the following subsections applies:</p><div class="div4">
<h5><a id="id-item-subtype-general"/>3.3.2.1 <a href="#id-item-subtype-general" style="text-decoration: none">General Subtyping Rules</a></h5><p>Given <a title="item type" class="termref" href="#dt-item-type">item types</a>
                     <var>A</var> and <var>B</var>, 
                     <code>
                        <var>A</var> ⊆ <var>B</var>
                     </code> is true if any of the following apply:</p><ol class="enumar"><li><p>
                           <var>A</var> is <code>xs:error</code>.</p></li><li><p>
                           <var>B</var> is <code>item()</code>.</p></li><li><p>
                           <var>A</var> and <var>B</var> are the same <a title="item type" class="termref" href="#dt-item-type">item type</a>.</p></li><li><p>There is an <a title="item type" class="termref" href="#dt-item-type">item type</a>
                           <var>X</var> such that <code>
                              <var>A</var> ⊆ <var>X</var>
                           </code>
                              and <code>
                              <var>X</var> ⊆ <var>B</var>
                           </code>. (This is referred to below as the <b>transitivity rule</b>).</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>The first rule is technically redundant: it is implied by the second rule in <a href="#id-item-subtype-atomic"><b>3.3.2.3 Subtyping of Atomic and Union Types</b></a>.
                     The type <code>xs:error</code> is defined as a union type with no member types; therefore it is automatically true that
                        every member type <var>T</var> satisfies <code>
                           <var>T</var> ⊆ <var>B</var>
                        </code>.</p></div></div><div class="div4">
<h5><a id="id-item-subtype-choice"/>3.3.2.2 <a href="#id-item-subtype-choice" style="text-decoration: none">Subtyping of Choice Item Types</a></h5><p>The following rules determine whether <code>
                        <var>A</var> ⊆ <var>B</var>
                     </code> is true in the
                  case where either <var>A</var> or <var>B</var> or both is a <a title="choice item type" class="termref" href="#dt-choice-item-type">choice item type</a>.</p><p>Firstly, if one of the operands is <em>not</em> a choice item type, then it is treated
                  as a choice item type with a single member type. The rule is then:</p><p>
                     <code>
                        <var>A</var> ⊆ <var>B</var>
                     </code> is true if for every member type <var>a</var> in 
                  <var>A</var>, there is a member type <var>b</var> in <var>B</var> such that <code>
                        <var>a</var> ⊆ <var>b</var>
                     </code>.</p><p>For example, <code>(xs:int | xs:long)</code> is a subtype of <code>(xs:decimal | xs:date)</code>
                  because both <code>xs:int</code> and <code>xs:long</code> are subtypes of <code>xs:decimal</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Because an <a title="enumeration type" class="termref" href="#dt-enumeration-type">enumeration type</a> is defined as a choice type
                        of singleton enumerations, these
                     rules have the consequence, for example, that <code>enum("A", "B")</code> is a subtype
                     of <code>enum("A", "B", "C")</code>.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The type <code>xs:int</code> is not a subtype of <code>(xs:negativeInteger | xs:nonNegativeInteger)</code>,
                     because it does not satisfy this rule. This is despite the fact that the value space of <code>xs:int</code>
                     is a subset of the value space of <code>(xs:negativeInteger | xs:nonNegativeInteger)</code>.</p></div></div><div class="div4">
<h5><a id="id-item-subtype-atomic"/>3.3.2.3 <a href="#id-item-subtype-atomic" style="text-decoration: none">Subtyping of Atomic and Union Types</a></h5><p>Given item types <var>A</var> and <var>B</var>, <code>
                        <var>A</var> ⊆ <var>B</var>
                     </code> is true if any of the following apply:</p><ol class="enumar"><li><p>
                           <var>A</var> and <var>B</var> are <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic types</a>, 
                              and <var>A</var>
                           <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                           <var>B</var>.</p><div class="example">
<div class="exampleHeader"><a id="d2e11500"/>Examples:</div><ul><li><p>
                                    <code>xs:integer ⊆ xs:decimal</code> because <code>xs:integer</code> is derived
                                 by restriction from <code>xs:decimal</code>.</p></li><li><p>
                                    <code>xs:decimal ⊆ xs:numeric</code> because <code>xs:numeric</code> is a pure union
                                    type that includes <code>xs:decimal</code> as a member type.</p></li></ul></div></li><li><p>
                           <var>A</var> is a <a title="pure union type" class="termref" href="#dt-pure-union-type">pure union type</a>, 
                              and every type <var>T</var> in the transitive membership of <var>A</var>
                              satisfies <code>
                              <var>T</var> ⊆ <var>B</var>
                           </code>.</p><div class="example">
<div class="exampleHeader"><a id="d2e11545"/>Examples:</div><ul><li><p>
                                    <code>(xs:short | xs:long) ⊆ xs:integer</code>
                                    because <code>xs:short ⊆ xs:integer</code> and <code>xs:long ⊆ xs:integer</code>.</p></li><li><p>
                                    <code>(P | Q) ⊆ (P | Q | R)</code>
                                 because <code>P ⊆ (P | Q | R)</code> and <code>Q ⊆ (P | Q | R)</code>.</p></li><li><p>
                                    <code>enum("red", "green") ⊆ xs:string</code> because the 
                                    enumeration type <code>enum("red") ⊆ xs:string</code> 
                                    and <code>enum("green") ⊆ xs:string</code>.</p></li><li><p>
                                    <code>enum("red", "green") ⊆ enum("red", "green", "blue")</code> because 
                                    <code>enum("red") ⊆ enum("red", "green", "blue")</code> and 
                                    <code>enum("green") ⊆ enum("red", "green", "blue")</code>.</p></li><li><p>
                                    <code>enum("red", "green", "blue") ⊆ (enum("red", "green") | enum("blue"))</code> because 
                                    each of the types <code>enum("red")</code>, <code>enum("green")</code>, and <code>enum("blue")</code>
                                    is a subtype of one of the two members of the union type.</p></li></ul></div></li></ol></div><div class="div4">
<h5><a id="id-item-subtype-enum"/>3.3.2.4 <a href="#id-item-subtype-enum" style="text-decoration: none">Subtyping of Enumeration Types</a></h5><p>If <var>A</var> is a <a title="singleton enumeration type" class="termref" href="#dt-singleton-enumeration-type">singleton enumeration type</a>
                     permitting the string value <var>V</var>, then <code>
                        <var>A</var> ⊆ <var>B</var>
                     </code> 
                     is true if <var>B</var> is <code>xs:string</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Because a non-singleton enumeration type is defined as a choice type,
                  <code>
                           <var>A</var> ⊆ <var>B</var>
                        </code> also holds if <var>A</var> is
                  <code>enum("red")</code> and <var>B</var> is <code>enum("red", "green")</code>.
                  See <a href="#id-item-subtype-choice"><b>3.3.2.2 Subtyping of Choice Item Types</b></a>.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The type <code>enum("red", "green")</code> is not a subtype
                  of <code>xs:NCName</code>, despite the fact that all the enumerated values
                  are valid <code>NCName</code>s. This is because instances of <code>xs:NCName</code>
                  must have a type annotation of <code>xs:NCName</code> or a subtype thereof,
                  whereas instances of <code>enum("red", "green")</code> are not subject to this
                  constraint.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>A type <var>T</var> derived by restriction from <code>xs:string</code>,
                  for example a type with the facet <code>length="0"</code> (which permits
                  only the zero-length string), is not a subtype of any enumeration type,
                  even if every string in the value space of <var>T</var> is an instance of
                  the enumeration type.</p></div></div><div class="div4">
<h5><a id="id-item-subtype-nodes"/>3.3.2.5 <a href="#id-item-subtype-nodes" style="text-decoration: none">Subtyping of Node Types</a></h5><p>The following subsections describe the subtype relationships
                  among node types.</p><div class="div5">
<h6><a id="id-item-subtype-nodes-general"/>3.3.2.5.1 <a href="#id-item-subtype-nodes-general" style="text-decoration: none">Subtyping Nodes: General Rules</a></h6><p>Given item types <var>A</var> and <var>B</var>, <code>
                           <var>A</var> ⊆ <var>B</var>
                        </code> is true if any of the following apply:</p><ol class="enumar"><li><p>
                              <var>A</var> is a <a href="#prod-xquery40-NodeKindTest">NodeKindTest</a> and <var>B</var> is <code>node()</code>.</p><div class="example">
<div class="exampleHeader"><a id="d2e11726"/>Example:</div><p>
                                 <code>comment() ⊆ node()</code>
                              </p></div></li><li><p>
                              <var>A</var> is <code>processing-instruction(<var>N</var>)</code> for any name <var>N</var>,
                              and <var>B</var> is <code>processing-instruction()</code>.</p><div class="example">
<div class="exampleHeader"><a id="d2e11750"/>Example:</div><p>
                                 <code>processing-instruction('pi') ⊆ processing-instruction()</code>
                              </p></div></li><li><p>
                              <var>A</var> is a <a href="#doc-xquery40-JNodeType">JNodeType</a> and <var>B</var> is a <a href="#doc-xquery40-GNodeType">GNodeType</a>.</p></li><li><p>
                              <var>A</var> is <code>jnode(<var>T</var>)</code> and <var>B</var> is <code>jnode()</code>, for any sequence type 
                              <var>T</var>.</p></li><li><p>
                              <var>A</var> is <code>jnode(<var>T</var>)</code>, <var>B</var> is <code>jnode(<var>U</var>)</code>, 
                              and <code>T ⊑ U</code>.</p></li><li><p>
                              <var>A</var> is a <a href="#doc-xquery40-NodeTest">NodeTest</a> and <var>B</var> is a <a href="#doc-xquery40-GNodeType">GNodeType</a>
                           </p></li></ol></div><div class="div5">
<h6><a id="id-item-subtype-documents"/>3.3.2.5.2 <a href="#id-item-subtype-documents" style="text-decoration: none">Subtyping Nodes: Document Nodes</a></h6><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-item-subtype-elements">⬇</a> <a href="#id-sequencetype-subtype">⬆</a></p><ol><li><p>The rules for subtyping of document node types have been refined.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1624">1624</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1898">1898</a> 7 April 2025]</i></p></li></ol></div><p>Given item types <var>A</var> and <var>B</var>, <code>
                           <var>A</var> ⊆ <var>B</var>
                        </code> 
                     is true if any of the following rules apply.</p><p>These rules apply after expanding <code>document-node(<var>N</var>)</code>, where <var>N</var>
                  is a <a href="#prod-xquery40-NameTestUnion">NameTestUnion</a>, to the equivalent 
                     <code>document-node(element(<var>N</var>))</code>.</p><ol class="enumar"><li><p>
                              <var>A</var> is <code>document-node(<var>E</var>)</code> for any <var>E</var>,
                              and <var>B</var> is <code>document-node()</code>.</p><div class="example">
<div class="exampleHeader"><a id="d2e11880"/>Examples:</div><p>
                                 <code>document-node(element(chap)) ⊆ document-node()</code>
                              </p><p>
                                 <code>document-node(*) ⊆ document-node()</code>
                              </p></div></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is <code>document-node(<var>A<sub>e</sub></var>)</code>
                                 </p></li><li><p>
                                    <var>B</var> is <code>document-node(<var>B<sub>e</sub></var>)</code>
                                 </p></li><li><p>
                                    <code>
                                       <var>A<sub>e</sub></var> ⊆ <var>B<sub>e</sub></var>
                                    </code>
                                 </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e11925"/>Examples:</div><p>
                                 <code>document-node(element(title)) ⊆ document-node(element(*))</code>.</p><p>
                                 <code>document-node(title) ⊆ document-node(*)</code>.</p></div></li><li><p>
                              <var>A</var> is <code>document-node(element(<var>A<sub>1</sub></var>|<var>A<sub>2</sub></var>|..., <var>T</var>))</code> 
                              (where <var>T</var> may be absent),
                           and for each <var>A<sub>n</sub></var>, <code>document-node(element(<var>A<sub>n</sub></var>, <var>T</var>)) ⊆ <var>B</var>
                              </code>.</p><div class="example">
<div class="exampleHeader"><a id="d2e11964"/>Examples:</div><ul><li><p>
                                       <code>document-node(a|b) ⊆ document-node(a) | document-node(b)</code>
                                    </p></li><li><p>
                                       <code>document-node(a|b) ⊆ document-node(a|b|c)</code>
                                    </p></li></ul></div></li></ol></div><div class="div5">
<h6><a id="id-item-subtype-elements"/>3.3.2.5.3 <a href="#id-item-subtype-elements" style="text-decoration: none">Subtyping Nodes: Elements</a></h6><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-item-subtype-attributes">⬇</a> <a href="#id-item-subtype-documents">⬆</a></p><ol><li><p>The type <code>schema-element(N)</code> is now defined
                     to be a subtype of <code>element()</code> and of various other element tests.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2201">2201</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2202">2202</a> 23 September 2025]</i></p></li></ol></div><p>
                        [<a id="dt-wildcard-matches" title="wildcard-matches">Definition</a>: In these rules, if <var>MU</var> and <var>NU</var> 
                     are <a href="#prod-xquery40-NameTestUnion">NameTestUnions</a>, 
                     then <var>MU</var>
                           <b>wildcard-matches</b>
                           <var>NU</var> is true if every name that matches <var>MU</var>
                     also matches <var>NU</var>.]
                     </p><p>More specifically, this is the case if for every <a href="#prod-xquery40-NameTest">NameTest</a>
                        <var>M</var>
                     in <var>MU</var> there is a <a href="#prod-xquery40-NameTest">NameTest</a>
                        <var>N</var> in <var>NU</var>
                     where at least one of the following applies:</p><ol class="enumar"><li><p>
                              <var>M</var> and <var>N</var> are the same <code>NameTest</code>.</p></li><li><p>
                              <var>M</var> is an <code>EQName</code> and <var>N</var> is a 
                        <a href="#prod-xquery40-Wildcard">Wildcard</a> that matches <var>M</var>.</p></li><li><p>
                              <var>N</var> is the <a href="#prod-xquery40-Wildcard">Wildcard</a>
                              <code>*</code>.</p></li></ol><p>Given item types <var>A</var> and <var>B</var>, <code>
                           <var>A</var> ⊆ <var>B</var>
                        </code> 
                     is true if any of the following apply.</p><ol class="enumar"><li><p>
                              <var>A</var> is an <a href="#doc-xquery40-ElementTest">ElementTest</a> 
                           or <a href="#doc-xquery40-SchemaElementTest">SchemaElementTest</a> and
                           <var>B</var> is either <code>element()</code> or <code>element(*)</code>
                           </p></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is either <code>element(<var>A<sub>n</sub></var>)</code> or <code>element(<var>A<sub>n</sub></var>, <var>T</var>)</code>  
                                 or <code>element(<var>A<sub>n</sub></var>, <var>T</var>?)</code> for any type <var>T</var>
                                 </p></li><li><p>
                                    <var>B</var> is either <code>element(<var>B<sub>n</sub></var>)</code> or <code>element(<var>B<sub>n</sub></var>, xs:anyType?)</code>
                                 </p></li><li><p>
                                    <var>A<sub>n</sub></var>
                                    <a title="wildcard-matches" class="termref" href="#dt-wildcard-matches">wildcard-matches</a>
                                    <var>B<sub>n</sub></var>
                                 </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e12163"/>Examples:</div><ul><li><p>
                                       <code>element(title) ⊆ element(*)</code>
                                    </p></li><li><p>
                                       <code>element(title, xs:string) ⊆ element(*)</code>
                                    </p></li><li><p>
                                       <code>element(title|heading, xs:string) ⊆ element(*)</code>
                                    </p></li><li><p>
                                       <code>element(title, xs:string) ⊆ element(title|heading)</code>
                                    </p></li><li><p>
                                       <code>element(title, xs:string?) ⊆ element(*)</code>
                                    </p></li><li><p>
                                       <code>element(title|heading, xs:string) ⊆ element(*)</code>
                                    </p></li><li><p>
                                       <code>element(title) ⊆ element(title, xs:anyType?)</code>
                                    </p></li><li><p>
                                       <code>element(title, xs:integer) ⊆ element(title|heading, xs:anyType?)</code>
                                    </p></li><li><p>
                                       <code>element(title, xs:string?) ⊆ element(title, xs:anyType?)</code>
                                    </p></li><li><p>
                                       <code>element(my:title|your:title) ⊆ element(*:title)</code>
                                    </p></li><li><p>
                                       <code>element(my:title|my:heading) ⊆ element(my:*)</code>
                                    </p></li></ul></div></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is <code>element(<var>A<sub>n</sub></var>, <var>A<sub>t</sub></var>)</code>.</p></li><li><p>
                                    <var>B</var> is <code>element(<var>B<sub>n</sub></var>, <var>B<sub>t</sub></var>)</code>.</p></li><li><p>
                                    <var>A<sub>n</sub></var>
                                    <a title="wildcard-matches" class="termref" href="#dt-wildcard-matches">wildcard-matches</a>
                                    <var>B<sub>n</sub></var>.</p></li><li><p>
                                    <var>A<sub>t</sub></var>
                                    <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                                    <var>B<sub>t</sub></var>.</p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e12277"/>Examples:</div><ul><li><p>
                                       <code>element(size, xs:integer) ⊆ element(size, xs:decimal)</code>
                                    </p></li><li><p>
                                       <code>element(size, xs:integer) ⊆ element(size|größe, xs:decimal)</code>
                                    </p></li><li><p>
                                       <code>element(size, xs:integer) ⊆ element(*, xs:decimal)</code>
                                    </p></li><li><p>
                                       <code>element(*, xs:integer) ⊆ element(*, xs:decimal)</code>
                                    </p></li><li><p>
                                       <code>element(my:*, xs:integer) ⊆ element(*, xs:decimal)</code>
                                    </p></li></ul></div></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is either <code>element(<var>A<sub>n</sub></var>, <var>A<sub>t</sub></var>)</code> or 
                                 <code>element(<var>A<sub>n</sub></var>, <var>A<sub>t</sub></var>?)</code>
                                 </p></li><li><p>
                                    <var>B</var> is <code>element(<var>B<sub>n</sub></var>, <var>B<sub>t</sub></var>?)</code>
                                 </p></li><li><p>
                                    <var>A<sub>n</sub></var>
                                    <a title="wildcard-matches" class="termref" href="#dt-wildcard-matches">wildcard-matches</a>
                                    <var>B<sub>n</sub></var>
                                 </p></li><li><p>
                                    <var>A<sub>t</sub></var>
                                    <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                                    <var>B<sub>t</sub></var>.</p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e12362"/>Examples:</div><ul><li><p>
                                       <code>element(size, xs:integer) ⊆ element(size, xs:decimal?)</code>
                                    </p></li><li><p>
                                       <code>element(size, xs:integer?) ⊆ element(*, xs:decimal?)</code>
                                    </p></li><li><p>
                                       <code>element(*, xs:integer) ⊆ element(*, xs:decimal?)</code>
                                    </p></li><li><p>
                                       <code>element(my:*, xs:integer?) ⊆ element(*, xs:decimal?)</code>
                                    </p></li></ul></div></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is <code>schema-element(<var>A<sub>n</sub></var>)</code>
                                 </p></li><li><p>
                                    <var>B</var> is <code>schema-element(<var>B<sub>n</sub></var>)</code>
                                 </p></li><li><p>Every element declaration that is an actual member of the substitution group of <var>A<sub>n</sub></var> 
                                 is also an actual member of the substitution group of <var>B<sub>n</sub></var>.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>The fact that <var>P</var> is a member of the substitution group of <var>Q</var> 
                                   does not mean that every element declaration in the substitution group of <var>P</var> 
                                   is also in the substitution group of <var>Q</var>. For example, <var>Q</var> might 
                                   block substitution of elements whose type is derived by extension, while <var>P</var> does not.</p></div></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is <code>schema-element(<var>A<sub>n</sub></var>)</code>
                                 </p></li><li><p>
                                    <var>B</var> is <code>element(*, <var>B<sub>t</sub></var>)</code>
                                 </p></li><li><p>the schema type identified by the <code>{type definition}</code> 
                                 property of the element declaration of 
                              <var>A<sub>n</sub></var> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>
                                    <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                                    <var>B<sub>t</sub></var>.</p></li><li><p>the element declaration of 
                              <var>A<sub>n</sub></var> in the <a title="static context" class="termref" href="#dt-static-context">static context</a> is not nillable.</p></li></ol></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is <code>schema-element(<var>A<sub>n</sub></var>)</code>
                                 </p></li><li><p>
                                    <var>B</var> is <code>element(*, <var>B<sub>t</sub></var>?)</code>
                                 </p></li><li><p>the schema type identified by the <code>{type definition}</code> 
                                 property of the element declaration of 
                              <var>A<sub>n</sub></var> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>
                                    <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                                    <var>B<sub>t</sub></var>.</p></li></ol></li><li><p>
                              <var>A</var> is <code>element(<var>A<sub>1</sub></var>|<var>A<sub>2</sub></var>|..., <var>T</var>)</code> 
                              (where <var>T</var> may be absent),
                           and for each <var>A<sub>n</sub></var>, <code>element(<var>A<sub>n</sub></var>, <var>T</var>) ⊆ <var>B</var>
                              </code>.</p><div class="example">
<div class="exampleHeader"><a id="d2e12543"/>Examples:</div><ul><li><p>
                                       <code>element(a|b) ⊆ (element(a)|element(b)|element(c))</code>
                                    </p></li><li><p>
                                       <code>element(a|b, xs:integer) ⊆ (element(a, xs:decimal) | element(b, xs:integer))</code>
                                    </p></li></ul></div></li></ol></div><div class="div5">
<h6><a id="id-item-subtype-attributes"/>3.3.2.5.4 <a href="#id-item-subtype-attributes" style="text-decoration: none">Subtyping Nodes: Attributes</a></h6><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-coercion-rules">⬇</a> <a href="#id-item-subtype-elements">⬆</a></p><ol><li><p>The type <code>schema-attribute(N)</code> is now defined
                     to be a subtype of <code>attribute()</code> and of various other attribute tests.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2201">2201</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2202">2202</a> 23 September 2025]</i></p></li></ol></div><p>Given item types <var>A</var> and <var>B</var>, <code>
                           <var>A</var> ⊆ <var>B</var>
                        </code> is true if any of the following apply:</p><ol class="enumar"><li><p>
                              <var>A</var> is an <a href="#doc-xquery40-AttributeTest">AttributeTest</a> 
                              and
                              <var>B</var> is either <code>attribute()</code> or <code>attribute(*)</code>
                           </p></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is either <code>attribute(<var>A<sub>n</sub></var>)</code> or 
                                 <code>attribute(<var>A<sub>n</sub></var>, <var>T</var>)</code> 
                                 for any type <var>T</var>.</p></li><li><p>
                                    <var>B</var> is either <code>attribute(Bn)</code> or 
                                 <code>attribute(<var>B<sub>n</sub></var>, xs:anyAtomicType)</code>
                                 </p></li><li><p>
                                    <var>A<sub>n</sub></var>
                                    <a title="wildcard-matches" class="termref" href="#dt-wildcard-matches">wildcard-matches</a>
                                    <var>B<sub>n</sub></var>
                                 </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e12646"/>Examples:</div><ul><li><p>
                                       <code>attribute(code) ⊆ attribute(*)</code>
                                    </p></li><li><p>
                                       <code>attribute(code|status) ⊆ attribute(*)</code>
                                    </p></li><li><p>
                                       <code>attribute(code, xs:untypedAtomic) ⊆ attribute(*)</code>
                                    </p></li><li><p>
                                       <code>attribute(code|status, xs:string) ⊆ attribute(code, xs:anyAtomicType)</code>
                                    </p></li><li><p>
                                       <code>attribute(my:code|your:code) ⊆ attribute(*:code)</code>
                                    </p></li><li><p>
                                       <code>attribute(my:code|my:status) ⊆ attribute(my:*)</code>
                                    </p></li></ul></div></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is <code>attribute(<var>A<sub>n</sub></var>, <var>A<sub>t</sub></var>)</code>
                                 </p></li><li><p>
                                    <var>B</var> is <code>attribute(<var>B<sub>n</sub></var>, <var>B<sub>t</sub></var>)</code>
                                 </p></li><li><p>
                                    <var>A<sub>n</sub></var>
                                    <a title="wildcard-matches" class="termref" href="#dt-wildcard-matches">wildcard-matches</a>
                                    <var>B<sub>n</sub></var>
                                 </p></li><li><p>
                                    <var>A<sub>t</sub></var>
                                    <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                                    <var>B<sub>t</sub></var>.</p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e12730"/>Examples:</div><ul><li><p>
                                       <code>attribute(*, xs:ID) ⊆ attribute(*, xs:string)</code>
                                    </p></li><li><p>
                                       <code>attribute(my:*, xs:ID) ⊆ attribute(*, xs:string)</code>
                                    </p></li><li><p>
                                       <code>attribute(code, xs:ID) ⊆ attribute(code|status, xs:string)</code>
                                    </p></li><li><p>
                                       <code>attribute(code, xs:ID) ⊆ attribute(*, xs:string)</code>
                                    </p></li><li><p>
                                       <code>attribute(code, xs:ID) ⊆ attribute(*:code, xs:ID)</code>
                                    </p></li><li><p>
                                       <code>attribute(my:code|my:status, xs:ID) ⊆ attribute(my:*, xs:string)</code>
                                    </p></li></ul></div></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is <code>schema-attribute(<var>A<sub>n</sub></var>)</code>
                                 </p></li><li><p>
                                    <var>B</var> is <code>schema-attribute(<var>B<sub>n</sub></var>)</code>
                              or <code>attribute(<var>B<sub>n</sub></var>)</code>
                                 </p></li><li><p>the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> of <var>A<sub>n</sub></var> equals the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> of <var>B<sub>n</sub></var>
                                 </p></li></ol></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is <code>schema-attribute(<var>A<sub>n</sub></var>)</code>
                                 </p></li><li><p>
                                    <var>B</var> is <code>attribute(<var>B<sub>n</sub></var>, <var>B<sub>t</sub></var>)</code>
                                 </p></li><li><p>the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> of <var>A<sub>n</sub></var> equals the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> of <var>B<sub>n</sub></var>
                                 </p></li><li><p>the schema type (always a simple type) referenced
                                  by the <code>{type definition}</code> property of the attribute
                                  declaration of 
                              <var>A<sub>n</sub></var> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>
                                    <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                                    <var>B<sub>t</sub></var>.</p></li></ol></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                    <var>A</var> is <code>schema-attribute(<var>A<sub>n</sub></var>)</code>
                                 </p></li><li><p>
                                    <var>B</var> is <code>attribute(<var>N</var>, <var>B<sub>t</sub></var>)</code>
                                 </p></li><li><p>
                                    <var>N</var> is a <a href="#prod-xquery40-NameTestUnion">NameTestUnion</a> that matches
                              <var>A<sub>n</sub></var> (for example, <code>*</code>).</p></li><li><p>the schema type (always a simple type) referenced
                                  by the <code>{type definition}</code> property of the attribute
                                  declaration of 
                              <var>A<sub>n</sub></var> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>
                                    <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                                    <var>B<sub>t</sub></var>.</p></li></ol></li><li><p>
                              <var>A</var> is <code>attribute(<var>A<sub>1</sub></var>|<var>A<sub>2</sub></var>|..., <var>T</var>)</code> (where <var>T</var> may be absent),
                           and for each <var>A<sub>n</sub></var>, <code>attribute(<var>A<sub>n</sub></var>, <var>T</var>) ⊆ <var>B</var>
                              </code>.</p><div class="example">
<div class="exampleHeader"><a id="d2e12942"/>Examples:</div><ul><li><p>
                                       <code>attribute(a|b) ⊆ (attribute(a)|attribute(b)|attribute(c))</code>
                                    </p></li><li><p>
                                       <code>attribute(a|b, xs:integer) ⊆ (attribute(a, xs:decimal) | attribute(b))</code>
                                    </p></li></ul></div></li></ol></div></div><div class="div4">
<h5><a id="id-item-subtype-functions"/>3.3.2.6 <a href="#id-item-subtype-functions" style="text-decoration: none">Subtyping Functions</a></h5><p>Given item types <var>A</var> and <var>B</var>, <code>
                        <var>A</var> ⊆ <var>B</var>
                     </code> is true if any of the following apply:</p><ol class="enumar"><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is a <a href="#doc-xquery40-FunctionType">FunctionType</a>
                                 <span class="xquery"> with annotations <code>[AnnotationsA]</code>
                                 </span>
                              </p></li><li><p>
                                 <var>B</var> is <code>
                                    <span class="xquery">[AnnotationsB]</span> function(*)</code>
                              </p></li><li class="xquery"><p>
                                 <code>subtype-assertions(AnnotationsA, AnnotationsB)</code>, 
                              where <code>[AnnotationsB]</code> and <code>[AnnotationsA]</code> 
                              are optional lists of one or more annotations.</p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13014"/>Example:</div><p>
                              <code>function(xs:integer) as xs:string ⊆ function(*)</code>
                           </p></div></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is <code>
                                    <span class="xquery">AnnotationsA </span>function(<var>a<sub>1</sub></var>, <var>a<sub>2</sub></var>, ... <var>a<sub>M</sub></var>) as <var>R<sub>A</sub></var>
                                 </code>
                              </p></li><li><p>
                                 <var>B</var> is <code>
                                    <span class="xquery">AnnotationsB </span>function(<var>b<sub>1</sub></var>, <var>b<sub>2</sub></var>, ... <var>b<sub>N</sub></var>) as <var>R<sub>B</sub></var>
                                 </code>
                              </p></li><li class="xquery"><p>
                                 <code>[AnnotationsB]</code> and <code>[AnnotationsA]</code> are optional lists of one or more annotations;</p></li><li><p>
                                 <var>N</var> (the arity of <var>B</var>) equals <var>M</var> (the arity of <var>A</var>)
                                    </p></li><li><p>
                                 <code>
                                    <var>R<sub>A</sub></var> ⊑ <var>R<sub>B</sub></var>
                                 </code>
                              </p></li><li><p>For all values of <var>p</var> between 1 and <var>N</var>, <code>
                                    <var>b<sub>p</sub></var> ⊑ <var>a<sub>p</sub></var>
                                 </code>
                                 <span class="xquery">, and <code>subtype-assertions(AnnotationsA, AnnotationsB)</code>
                                 </span>
                              </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13112"/>Examples:</div><ul><li><p>
                                    <code>function(xs:integer) as xs:string ⊆ function(xs:long) as xs:string</code>
                                 </p></li><li><p>
                                    <code>function(xs:integer) as xs:ID ⊆ function(xs:integer) as xs:string</code>
                                 </p></li><li><p>
                                    <code>function(xs:integer) as xs:ID ⊆ function(xs:long) as xs:string</code>
                                 </p></li></ul></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Function return types are covariant because this rule requires <code>
                                 <var>R<sub>A</sub></var> ⊑ <var>R<sub>B</sub></var>
                              </code> for return types. 
                                 Function parameter types are contravariant because this rule requires <code>
                                 <var>b<sub>p</sub></var> ⊑ <var>a<sub>p</sub></var>
                              </code> for parameter types.</p></div></li></ol></div><div class="div4">
<h5><a id="id-item-subtype-maps"/>3.3.2.7 <a href="#id-item-subtype-maps" style="text-decoration: none">Subtyping Maps</a></h5><p>Given item types <var>A</var> and <var>B</var>, <code>
                        <var>A</var> ⊆ <var>B</var>
                     </code> is true if any of the following apply:</p><ol class="enumar"><li><p>Both of the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is <code>map(<var>K</var>, <var>V</var>)</code>,
                                 for any <var>K</var> and <var>V</var>
                              </p></li><li><p>
                                 <var>B</var> is <code>map(*)</code>
                              </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13194"/>Example:</div><p>
                              <code>map(xs:integer, item()*) ⊆ map(*)</code>
                           </p></div></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is <code>map(<var>K<sub>a</sub></var>, <var>V<sub>a</sub></var>)</code>
                              </p></li><li><p>
                                 <var>B</var> is <code>map(<var>K<sub>b</sub></var>, <var>V<sub>b</sub></var>)</code>
                              </p></li><li><p>
                                 <code>
                                    <var>K<sub>a</sub></var> ⊆ <var>K<sub>b</sub></var>
                                 </code>
                              </p></li><li><p>
                                 <code>
                                    <var>V<sub>a</sub></var> ⊑ <var>V<sub>b</sub></var>
                                 </code>
                              </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13248"/>Example:</div><p>
                              <code>map(xs:long, item()) ⊆ map(xs:integer, item()+)</code>
                           </p></div></li><li><p>Both the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is <code>map(*)</code>
                                 (or, because of the transitivity rules, any other map type)</p></li><li><p>
                                 <var>B</var> is <code>function(*)</code>
                              </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13274"/>Example:</div><p>
                              <code>map(xs:long, xs:string?) ⊆ function(*)</code>
                           </p></div></li><li><p>Both the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is <code>map(*)</code>
                                 (or, because of the transitivity rules, any other map type)</p></li><li><p>
                                 <var>B</var> is 
                                 <code>function(xs:anyAtomicType) as item()*</code>
                              </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13300"/>Example:</div><p>
                              <code>map(xs:long, xs:string?) ⊆ function(xs:anyAtomicType) as item()*</code>
                           </p></div></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is <code>map(<var>K</var>, <var>V</var>)</code>
                              </p></li><li><p>
                                 <var>B</var> is <code>function(xs:anyAtomicType) as <var>R</var>
                                 </code>
                              </p></li><li><p>
                                 <var>V</var> ⊆ <var>R</var>
                              </p></li><li><p>
                                 <code>empty-sequence()</code> ⊆ <var>R</var>
                              </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13347"/>Examples:</div><ul><li><p>
                                    <code>map(xs:int, node()) ⊆ function(xs:anyAtomicType) as node()?</code>
                                 </p></li><li><p>
                                    <code>map(xs:int, node()+) ⊆ function(xs:anyAtomicType) as node()*</code>
                                 </p></li></ul><p>The function accepts type <code>xs:anyAtomicType</code> rather than <code>xs:int</code>,
                              because <code>$M("xyz")</code> is a valid call on a map (treated as a function) even
                              when all the keys in the map are integers.</p><p>The return type of the function is extended from <code>node()</code> or <code>node()+</code> to allow an empty sequence
                                 because <code>$M("xyz")</code> can return an empty sequence even if none of the entries
                              in the map contains an empty sequence.</p></div></li></ol></div><div class="div4">
<h5><a id="id-item-subtype-arrays"/>3.3.2.8 <a href="#id-item-subtype-arrays" style="text-decoration: none">Subtyping Arrays</a></h5><p>Given item types <var>A</var> and <var>B</var>, <code>
                        <var>A</var> ⊆ <var>B</var>
                     </code> is true if any of the following apply:</p><ol class="enumar"><li><p>Both the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is <code>array(<var>X</var>)</code>
                              </p></li><li><p>
                                 <var>B</var> is <code>array(*)</code>
                              </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13421"/>Example:</div><p>
                              <code>array(xs:integer) ⊆ array(*)</code>
                           </p></div></li><li><p>All the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is <code>array(<var>X</var>)</code>
                              </p></li><li><p>
                                 <var>B</var> is <code>array(<var>Y</var>)</code>
                              </p></li><li><p>
                                 <code>
                                    <var>X</var> ⊑ <var>Y</var>
                                 </code>
                              </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13461"/>Example:</div><p>
                              <code>array(xs:integer) ⊆ array(xs:decimal+)</code>
                           </p></div></li><li><p>Both the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is <code>array(*)</code>
                                 (or, because of the transitivity rules, any other array type)</p></li><li><p>
                                 <var>B</var> is <code>function(*)</code>
                              </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13487"/>Example:</div><p>
                              <code>array(xs:integer) ⊆ function(*)</code>
                           </p></div></li><li><p>Both the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is <code>array(*)</code>
                                 (or, because of the transitivity rules, any other array type)</p></li><li><p>
                                 <var>B</var> is <code>function(xs:integer) as item()*</code>
                              </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13513"/>Example:</div><p>
                              <code>array(*) ⊆ function(xs:integer) as item()*</code>
                           </p></div></li><li><p>Both the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is <code>array(<var>X</var>)</code>
                              </p></li><li><p>
                                 <var>B</var> is <code>function(xs:integer) as <var>X</var>
                                 </code>
                              </p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13543"/>Example:</div><p>
                              <code>array(xs:string) ⊆ function(xs:integer) as xs:string</code>
                           </p></div></li></ol></div><div class="div4">
<h5><a id="id-item-subtype-records"/>3.3.2.9 <a href="#id-item-subtype-records" style="text-decoration: none">Subtyping Records</a></h5><p>Given item types <var>A</var> and <var>B</var>, <var>A</var>
                     <code>⊆</code>
                     <var>B</var> is true if any of the following apply:</p><ol class="enumar"><li><p>
                           <var>A</var> is <code>map(*)</code> and <var>B</var> is <code>record(*)</code>.</p></li><li><p>All of the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is a record type.</p></li><li><p>
                                 <var>B</var> is <code>map(*)</code> or <code>record(*)</code>.</p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13598"/>Examples:</div><p>
                              <code>record(longitude, latitude)</code> ⊆ <code>map(*)</code>
                           </p><p>
                              <code>record(longitude, latitude, *)</code> ⊆ <code>record(*)</code>
                           </p><p>
                              <code>record(*)</code> ⊆ <code>map(*)</code>
                           </p></div></li><li><p>All of the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is a non-extensible record type</p></li><li><p>
                                 <var>B</var> is <code>map(<var>K</var>, <var>V</var>)</code>
                              </p></li><li><p>
                                 <var>K</var> is either <code>xs:string</code> or <code>xs:anyAtomicType</code>
                              </p></li><li><p>For every field <var>F</var> in <var>A</var>,
                              where <var>T</var> is the declared type of <var>F</var> (or its default, <code>item()*</code>),
                              <code>
                                    <var>T</var> ⊑ <var>V</var>
                                 </code>.</p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13677"/>Examples:</div><ul><li><p>
                                    <code>record(x, y)</code> ⊆ <code>map(xs:string, item()*)</code>
                                 </p></li><li><p>
                                    <code>record(x as xs:double, y as xs:double)</code> ⊆ <code>map(xs:string, xs:double)</code>
                                 </p></li></ul></div></li><li><p>All of the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is a non-extensible record type.</p></li><li><p>
                                 <var>B</var> is a non-extensible record type.</p></li><li><p>Every field in <var>A</var> is also declared in <var>B</var>.</p></li><li><p>Every mandatory field in <var>B</var> is also declared  as mandatory in <var>A</var>.</p></li><li><p>For every field that is declared in both <var>A</var> and <var>B</var>,
                              where the declared type in <var>A</var> is <var>T</var> 
                              and the declared type in <var>B</var> is <var>U</var>, <code>
                                    <var>T</var> ⊑ <var>U</var>
                                 </code>.</p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13748"/>Examples:</div><ul><li><p>
                                    <code>record(x, y as xs:integer) ⊆ record(x, y as xs:decimal)</code>
                                 </p></li><li><p>
                                    <code>record(x, y) ⊆ record(x, y, z?)</code>
                                 </p></li></ul></div></li><li><p>All of the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is an extensible record type</p></li><li><p>
                                 <var>B</var> is an extensible record type</p></li><li><p>Every mandatory field in <var>B</var> is also declared  as mandatory in <var>A</var>.</p></li><li><p>For every field that is declared in both <var>A</var> and <var>B</var>,
                                 where the declared type in <var>A</var> is <var>T</var> 
                                 and the declared type in <var>B</var> is <var>U</var>, <code>
                                    <var>T</var> ⊑ <var>U</var>
                                 </code>.</p></li><li><p>For every field that is declared in <var>B</var>
                                 but not in <var>A</var>, the declared type in <var>B</var> is <code>item()*</code>.</p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13818"/>Examples:</div><ul><li><p>
                                    <code>record(x, y, z, *) ⊆ record(x, y, *)</code>
                                 </p></li><li><p>
                                    <code>record(x?, y?, z?, *) ⊆ record(x, y, *)</code>
                                 </p></li><li><p>
                                    <code>record(x as xs:integer, y as xs:integer, *) ⊆ record(x as xs:decimal, y as xs:integer*, *)</code>
                                 </p></li><li><p>
                                    <code>record(x as xs:integer, *) ⊆ record(x as xs:decimal, y as item(), *)</code>
                                 </p></li></ul></div></li><li><p>All of the following are true:</p><ol class="enumla"><li><p>
                                 <var>A</var> is a non-extensible record type.</p></li><li><p>
                                 <var>B</var> is an extensible record type.</p></li><li><p>Every mandatory field in <var>B</var> is also declared as mandatory in <var>A</var>.</p></li><li><p>For every field that is declared in both <var>A</var> and <var>B</var>,
                              where the declared type in <var>A</var> is <var>T</var> 
                              and the declared type in <var>B</var> is <var>U</var>, <code>
                                    <var>T</var> ⊑ <var>U</var>
                                 </code>.</p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e13889"/>Examples:</div><ul><li><p>
                                    <code>record(x, y as xs:integer) ⊆ record(x, y as xs:decimal, *)</code>
                                 </p></li><li><p>
                                    <code>record(y as xs:integer) ⊆ record(x?, y as xs:decimal, *)</code>
                                 </p></li></ul></div></li></ol></div><div class="div4">
<h5><a id="id-itemtype-subtype-aliases"/>3.3.2.10 <a href="#id-itemtype-subtype-aliases" style="text-decoration: none">Subtyping of Named Item Types</a></h5><p>This section describes how references to <a title="named item type" class="termref" href="#dt-named-item-type">named item types</a>
                  are handled when evaluating the subtype relationship.</p><p>Named item types can be classified as recursive or non-recursive. 
                     A recursive type is one that references itself, directly or indirectly. Only named record
                  types are allowed to be recursive.</p><p>In the case of references to non-recursive named item types, the reference
                  is fully expanded as the first step in evaluating the subtype relationship. For example
                  this means that if <var>U</var> is a named item type with the expansion 
                     <code>(xs:integer | xs:double)</code>,
                     then <code>xs:integer ⊆ U</code> is true, because 
                     <code>xs:integer ⊆ (xs:integer | xs:double)</code> is true.</p><p>Recursive record types are considered to be, in the terminology of the computer science
                  literature, <b>iso-recursive</b> (rather than <b>equi-recursive</b>). 
                     This means that a recursive type name is not
                  treated as being equivalent to its expansion (at any depth). 
                  For example, if the named item type <var>T</var>
                  has the expansion <code>record(A as item()*, B as T?)</code>, then the type 
                     <code>array(T)</code> is not considered to be equivalent to 
                     <code>array(record(A as item()*, B as T?))</code>, despite the fact
                  that the two types have exactly the same instances.</p><p>The rules are therefore defined as follows:</p><ul><li><p>If <var>B</var> is a reference to a recursive record type, then
                        <var>A</var> ⊆ <var>B</var> is true if and only if 
                        <var>A</var> and <var>B</var>
                        are references to the same named record type.</p></li><li><p>If <var>A</var> is a reference to a recursive named item type, then
                        <var>A</var> ⊆ <var>B</var> is true if either:</p><ul><li><p>
                                 <var>A</var> and <var>B</var>
                              are references to the same named record type.</p></li><li><p>
                                 <code>record(*) ⊆ B</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>This is because only record types are allowed to be recursive.</p></div></li></ul></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>The decision to make recursive types iso-recursive rather than equi-recursive
                  was made largely because it saves a great deal of implementation complexity without any serious
                  adverse effects for users. In practice, problems can be avoided by using named record types
                  consistently (for example, avoiding having two named record types with
                  different names but identical definitions).</p></div></div></div><div class="div3 xquery">
<h4><a id="id-assertions-subtype"/>3.3.3 <a href="#id-assertions-subtype" style="text-decoration: none">The judgement <code>subtype-assertions(AnnotationsA, AnnotationsB)</code>
               </a></h4><p>
      The judgement <code>subtype-assertions(AnnotationsA, AnnotationsB)</code> determines if <code>AnnotationsA</code> is a subtype of <code>AnnotationsB</code>,
      where <code>AnnotationsA</code> and <code>AnnotationsB</code> are annotation lists from two FunctionTypes.
      It is defined to ignore function assertions in namespaces not understood by the XQuery
      implementation. For assertions that are understood, their effect on the result
      of <code>subtype-assertions()</code> is implementation defined.
    </p><p>
      The following examples are some possible ways to define <code>subtype-assertions()</code> for some
      implementation defined assertions in the <code>local</code> namespace. These examples 
                  assume that some implementation uses annotations to label functions as 
                  deterministic or nondeterministic, and treats deterministic functions 
                  as a subset of nondeterministic functions. In this implementation, 
                  nondeterministic functions are not a subset of deterministic functions.
    </p><ul><li><p>
        AnnotationsA is
        </p><div class="exampleInner"><pre>%local:inline</pre></div><p>
        It has no influence on the outcome of <code>subtype-assertions()</code>.
      </p></li><li><p>
        AnnotationsA is
        </p><div class="exampleInner"><pre>%local:deterministic</pre></div><p>
        AnnotationsB is
        </p><div class="exampleInner"><pre>%local:nondeterministic</pre></div><p>
        Since deterministic functions are a subset of nondeterministic functions, <code>subtype-assertions()</code> is true.
      </p></li><li><p>
        AnnotationsA contains
        </p><div class="exampleInner"><pre>%local:nondeterministic</pre></div><p>
        AnnotationsB is empty.
        If FunctionTypes without the <code>%local:nondeterministic</code> annotation only match deterministic functions,
        <code>subtype-assertions()</code> must be false.
      </p></li></ul></div></div><div class="div2">
<h3><a id="id-coercion-rules"/>3.4 <a href="#id-coercion-rules" style="text-decoration: none">Coercion Rules</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-function-coercion">⬇</a> <a href="#id-item-subtype-attributes">⬆</a></p><ol><li><p>
                  The term "function conversion rules" used in 3.1 has been replaced by the term "coercion rules".
               <i>  [ PR <a href="https://github.com/qt4cg/qtspecs/pull/254">254</a> 29 November 2022]</i></p></li><li><p>
                  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 <code>xs:positiveInteger</code>.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/117">117</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/254">254</a> 29 November 2022]</i></p></li><li><p>
                  The coercion rules now allow any numeric type to be implicitly converted to any other, for example
                  an <code>xs:double</code> is accepted where the required type is <code>xs:decimal</code>.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/980">980</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/911">911</a> 30 January 2024]</i></p></li><li><p>
                  The coercion rules now allow conversion in either direction between <code>xs:hexBinary</code>
                  and <code>xs:base64Binary</code>.
               <i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/130">130</a> <a href="https://github.com/qt4cg/qtspecs/issues/480">480</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/815">815</a> 7 November 2023]</i></p></li><li><p>
                  The coercion rules now apply recursively to the members of an array and the entries in a map.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1318">1318</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1501">1501</a> 29 October 2024]</i></p></li><li><p>
                  The coercion rules now reorder the entries in a map when the required type is a record type.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1862">1862</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1874">1874</a> 25 March 2025]</i></p></li></ol></div><p>
               [<a id="dt-coercion-rules" title="coercion rules">Definition</a>: The <b>coercion rules</b> 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.
                  ] The required type is expressed as a <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>. The effect of the coercion rules may be to accept the value as supplied,
                  to convert it to a value that matches the required type, or to reject it with a type error.</p><p>This section defines how the coercion rules operate; the situations in which the rules apply
                  are defined elsewhere, by reference to this section.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In previous versions of this specification, the coercion rules were referred to as the
                              <em>function conversion</em> rules. The terminology has changed because the rules are not exclusively
                              associated with functions or function calling.</p></div><p>If the required type is <code>empty-sequence()</code>, 
                  no coercion takes place (the supplied
               value must be an empty sequence, or a type error occurs).</p><p>In all other cases, the required 
                  <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>
               <var>T</var> comprises a required <a title="item type" class="termref" href="#dt-item-type">item type</a>
               <var>R</var> 
                  and an optional occurrence indicator. The coercion rules are then 
                  applied to a supplied value <var>V</var> 
               and the required type <var>T</var> as follows:</p><ol class="enumar"><li><p>Each item in <var>V</var> is processed against the required item type <var>R</var>
                     using the item coercion rules defined
                  in <a href="#id-item-coercion-rules"><b>3.4.1 Item Coercion Rules</b></a>, and the results are sequence-concatenated
                  into a single sequence <var>V′</var>.</p></li><li><p>A type error is raised if the cardinality of <var>V′</var> does not match the
                  required cardinality of <var>T</var>
                     [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li></ol><div class="div3">
<h4><a id="id-item-coercion-rules"/>3.4.1 <a href="#id-item-coercion-rules" style="text-decoration: none">Item Coercion Rules</a></h4><p>The rules in this section are used to process each item <var>J</var> in a supplied
               sequence, given a required <a title="item type" class="termref" href="#dt-item-type">item type</a>
                  <var>R</var>.</p><ol class="enumar"><li><p>If <var>R</var> is a <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a>
                     (for example, if it is an <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a>,
                     a <a title="pure union type" class="termref" href="#dt-pure-union-type">pure union type</a>, or
                     an <a title="enumeration type" class="termref" href="#dt-enumeration-type">enumeration type</a>), and <var>J</var>
                     is not an atomic item, then:
                     </p><ol class="enumla"><li><p>
                                 <var>J</var> is <a title="atomization" class="termref" href="#dt-atomization">atomized</a> 
                           to produce a sequence of atomic items <var>JJ</var>.</p></li><li><p>Each atomic item in <var>JJ</var> is coerced to the required
                        type <var>R</var> by recursive application of the item coercion rules (the 
                        rules in this section) to produce a value <var>V</var>.</p></li><li><p>The result is the <a title="sequence concatenation" class="termref" href="#dt-sequence-concatenation">sequence concatenation</a> 
                           of the <var>V</var> values.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>For example, if <code>J</code> is an element with type annotation
                  <code>xs:integer</code>, and <code>R</code> is the union type <code>xs:numeric</code>,
                  then the effect is to atomize the element to an <code>xs:integer</code>, and then
                  to coerce the resulting <code>xs:integer</code> to <code>xs:numeric</code>
                  (which leaves the integer unchanged). This is not the same as attempting to
                  coerce the element to each of the alternatives of the union type in turn, which
                  would deliver an instance of <code>xs:double</code>.</p></div></li><li><p>Otherwise, if <var>R</var> is a <a title="choice item type" class="termref" href="#dt-choice-item-type">choice item type</a> or
                     a <a title="pure union type" class="termref" href="#dt-pure-union-type">pure union type</a> (which includes the case where
                     it is an <a title="enumeration type" class="termref" href="#dt-enumeration-type">enumeration type</a>), then:</p><ol class="enumla"><li><p>If <var>J</var> matches (is an instance of) one of the alternatives
                           in <var>R</var>, then <var>J</var> is coerced to the first alternative in 
                           <var>R</var> that <var>J</var> matches.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>There are two situations where coercing an item to a type that
                              it already matches does not simply return the item unchanged:</p><ul><li><p>When the required type is a typed function type
                                      (see <a href="#id-function-test"><b>3.2.8.1 Function Types</b></a>),
                                    then function coercion is applied to coerce <var>J</var> to that
                                    function type, as described in <a href="#id-function-coercion"><b>3.4.3 Function Coercion</b></a>.</p></li><li><p>When the required type is a record type and the supplied
                                 value is a map, then coercion may change the <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-entry-order">entry order</a><sup><small>DM</small></sup>
                                 of the entries in the map.</p></li></ul></div></li><li><p>Otherwise, the item coercion rules (the rules in this section)
                              are applied to <var>J</var> recursively
                              with <var>R</var> set to each of the alternatives in the
                              choice or union item type, in order, until an alternative is found that
                              does not result in a type error; a type error is raised
                              only if all alternatives fail.</p><p>The error code used in the event of failure 
                              should be the error code arising from the
                              first unsuccessful matching attempt. (The diagnostic information
                              associated with the error may also describe how further attempts
                              failed.)</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>Suppose the required type is <code>(xs:integer | element(e))*</code>
                           and the supplied value is the sequence 
                           <code>(&lt;e&gt;22&lt;/e&gt;, 23, &lt;f&gt;24&lt;/f&gt;)</code>. 
                        Item coercion is applied independently to each of the three items in this
                        sequence. The first item matches one of the alternatives, namely <code>element(e)</code>,
                        so it is returned unchanged as an element node. The second item (the integer 23) also matches one of the
                        alternatives, and is returned unchanged as an integer. The third item does not match any of
                        the alternatives, so coercion is attempted to each one in turn. Coercion
                        to type <code>xs:integer</code> succeeds (by virtue of atomization and untyped
                           atomic conversion), so the final result is the sequence <code>(&lt;e&gt;22&lt;/e&gt;, 23, 24)</code>
                        </p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Suppose the required type is <code>enum("red", "green", "blue")</code>
                           and the supplied value is <code>"green"</code>. The enumeration type is defined
                           as a choice item type whose alternatives are singleton enumerations, so the rules
                           are applied first to the type <code>enum("red")</code> (which fails), and
                           then to the type <code>enum("green")</code> (which succeeds). The strings in an
                           enumeration type are required to be distinct so the order
                           of checking is in this case immaterial. The supplied value will be accepted, and
                           will be relabeled if necessary as an instance of <code>xs:string</code>.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Schema-defined union types behave in exactly the same way as
                        <a title="choice item type" class="termref" href="#dt-choice-item-type">choice item types.</a>
                        </p></div></li><li><p>If <var>R</var> is an <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a>
                     and <var>J</var> is an <a title="atomic item" class="termref" href="#dt-atomic-item">atomic item</a>, then:</p><ol class="enumla"><li><p>If <var>J</var> is an instance of 
                           <var>R</var> then it is used unchanged.</p></li><li><p>If <var>J</var> is an instance of type <code>xs:untypedAtomic</code>
                        then:</p><ol class="enumlr"><li><p>If <var>R</var> is <a title="namespace-sensitive" class="termref" href="#dt-namespace-sensitive">namespace-sensitive</a> then 
                                    a <a title="type error" class="termref" href="#dt-type-error">type error</a>
                                    [<a href="#ERRXPTY0117" title="err:XPTY0117">err:XPTY0117</a>] is raised.</p></li><li><p>Otherwise,  <var>J</var> is cast to type <var>R</var>.</p></li></ol></li></ol></li><li><p>If there is an entry (<var>from</var>, <var>to</var>)
                     in the following table such that <var>J</var> is an instance of <var>from</var>,
                     and <var>to</var> is <var>R</var>, then <var>J</var> is cast to type <var>R</var>.</p><table style="border:1px solid" class="medium"><caption>Implicit Casting</caption><thead><tr><th>from</th><th>to</th></tr></thead><tbody><tr><td>
                                 <code>xs:decimal</code>
                              </td><td>
                                 <code>xs:double</code>
                              </td></tr><tr><td>
                                 <code>xs:double</code>
                              </td><td>
                                 <code>xs:decimal</code>
                              </td></tr><tr><td>
                                 <code>xs:decimal</code>
                              </td><td>
                                 <code>xs:float</code>
                              </td></tr><tr><td>
                                 <code>xs:float</code>
                              </td><td>
                                 <code>xs:decimal</code>
                              </td></tr><tr><td>
                                 <code>xs:float</code>
                              </td><td>
                                 <code>xs:double</code>
                              </td></tr><tr><td>
                                 <code>xs:double</code>
                              </td><td>
                                 <code>xs:float</code>
                              </td></tr><tr><td>
                                 <code>xs:string</code>
                              </td><td>
                                 <code>xs:anyURI</code>
                              </td></tr><tr><td>
                                 <code>xs:anyURI</code>
                              </td><td>
                                 <code>xs:string</code>
                              </td></tr><tr><td>
                                 <code>xs:hexBinary</code>
                              </td><td>
                                 <code>xs:base64Binary</code>
                              </td></tr><tr><td>
                                 <code>xs:base64Binary</code>
                              </td><td>
                                 <code>xs:hexBinary</code>
                              </td></tr></tbody></table><div class="note"><p class="prefix"><b>Note:</b></p><p>The item type in the <var>to</var> column must match <var>R</var>
                        exactly; however, <var>J</var> may belong to a subtype of the type in the <var>from</var>
                        column.</p><p>For example, an <code>xs:NCName</code> will be cast to type <code>xs:anyURI</code>,
                        but an <code>xs:anyURI</code> will not be cast to type <code>xs:NCName</code>.</p><p>Similarly, an <code>xs:integer</code> will be cast to type <code>xs:double</code>,
                        but an <code>xs:double</code> will not be cast to type <code>xs:integer</code>.</p></div></li><li><p>If <var>R</var> is an <a title="singleton enumeration type" class="termref" href="#dt-singleton-enumeration-type">singleton enumeration type</a>
                     and <var>J</var> is an instance of <code>xs:untypedAtomic</code>
                        or <code>xs:anyURI</code>, then <var>J</var> is cast to
                        type <code>xs:string</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The effect of this rule, when taken in conjunction with the 
                        rules above regarding atomization and choice item types, is that 
                        when the required type is based on an <a title="enumeration type" class="termref" href="#dt-enumeration-type">enumeration type</a>,
                        for example <code>enum("red", "green", "blue")*</code>, the supplied value can be, 
                        in this example:</p><ul><li><p>An empty sequence.</p></li><li><p>The string <code>"red"</code>.</p></li><li><p>An untyped node whose string value is <code>"red"</code>.</p></li><li><p>A list-valued node whose typed value contains zero or more
                              strings (or <code>xs:anyURI</code> values), each of which is 
                              codepoint-equal to one of <code>"red"</code>, <code>"green"</code>,
                              or <code>"blue"</code>.</p></li><li><p>The <code>xs:anyURI</code> value <code>"red"</code>.</p></li><li><p>An array with zero or more members each of which 
                              is codepoint-equal to one of <code>"red"</code>, <code>"green"</code>,
                              or <code>"blue"</code>.</p></li><li><p>A JNode whose <b>·content·</b> property is any of the above.</p></li></ul></div></li><li><p>If <var>R</var> is derived from some primitive atomic type <var>P</var>, 
                     then <var>J</var> is <b>relabeled</b> as an instance of <var>R</var> if it satisfies
                     all the following conditions:</p><ul><li><p>
                              <var>J</var> is an instance of <var>P</var>.</p></li><li><p>
                              <var>J</var> is not an instance of <var>R</var>.</p></li><li><p>The <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-datum">datum</a><sup><small>DM</small></sup> of <var>J</var> is 
                           within the value space of <var>R</var>.</p></li></ul><p>Relabeling an atomic item changes the <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> but not the 
                        <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-datum">datum</a><sup><small>DM</small></sup>. For example, the
                        <code>xs:integer</code> value 3 can be relabeled as an instance of <code>xs:unsignedByte</code>, because
                        the datum is within the value space of <code>xs:unsignedByte</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Relabeling is not the same as casting. For example, the <code>xs:decimal</code> value 10.1
                        can be cast to <code>xs:integer</code>, but it cannot be relabeled as <code>xs:integer</code>,
                        because its datum not within the value space of <code>xs:integer</code>.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The effect of this rule is that if, for example, a function parameter is declared
                        with an expected type of <code>xs:positiveInteger</code>, then a call that supplies the literal
                        value 3 will succeed, whereas a call that supplies -3 will fail.</p><p>This differs from previous versions of this specification, where both these calls would fail.</p><p>This change allows the arguments of existing functions to be defined with a
                           
                           more precise type. For example, the <code>$position</code> argument of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-array-get"><code>array:get</code></a>
                           
                           could be defined as <code>xs:positiveInteger</code> 
                           rather than <code>xs:integer</code>.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>If <var>T</var>
                           is a union type with members <code>xs:negativeInteger</code> and 
                           <code>xs:positiveInteger</code> and the supplied value is the
                           sequence <code>(20, -20)</code>, then the effect of these rules 
                           is that the first item <code>20</code> is relabeled as type
                           <code>xs:positiveInteger</code> and the second item <code>-20</code>is relabeled as type 
                           <code>xs:negativeInteger</code>.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Promotion (for example of <code>xs:float</code> to <code>xs:double</code>)
                        occurs only when <var>T</var> is a primitive type.
                        Relabeling occurs only when <var>T</var> is a derived type. Promotion and relabeling are therefore
                        never combined.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>A <a title="singleton enumeration type" class="termref" href="#dt-singleton-enumeration-type">singleton enumeration type</a> such as <code>enum("green")</code> is treated
                     as an atomic type derived by restriction from <code>xs:string</code>; so if the
                     <code>xs:string</code> value <code>"green"</code> is supplied in a context where
                     the required type is <code>enum("red", "green", "blue")</code>, the value will be
                        accepted.</p></div></li><li><p>If <var>J</var> is a <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-JNode">JNode</a><sup><small>DM</small></sup> and does not
                        match <var>R</var>,
                     then each item in the <b>·content·</b> of <var>J</var> is coerced to type <var>R</var>
                     by applying the coercion rules recursively.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>For example, if <code>$A</code> is an array and the members
                     of the array are maps, then <code>$A/child::*</code> returns a sequence
                     of JNodes that encapsulate maps, and the average size of these maps can be obtained 
                     using the expression <code>avg($A/child::* ! map:size(.))</code>. The first
                     argument of <code>map:size</code> does not accept a JNode directly, but
                     it does (in effect) accept a JNode that encapsulates a map.</p></div></li><li><p>If <var>R</var> is an <a href="#doc-xquery40-ArrayType">ArrayType</a> other than <code>array(*)</code> and <var>J</var>
                        is an array, then <var>J</var> is converted to a new array by converting
                        each member to the required member type by applying the coercion rules
                        recursively.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>For example, if the required type is
                     <code>array(xs:double)</code> and the supplied value is
                        <code>[ 1, 2 ]</code>, the array is converted to
                        <code>[ 1e0, 2e0 ]</code>.</p></div></li><li><p>If <var>R</var> is a <a href="#doc-xquery40-MapType">MapType</a> other than <code>map(*)</code> and <var>J</var>
                        is a map, then <var>J</var> is converted to a new map as follows:</p><ol class="enumla"><li><p>Each key in the supplied map is converted to the required
                           map key type by applying the coercion rules. If the resulting map would
                           contain duplicate keys, a type error is raised
                           [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>The corresponding value is converted to the required
                           map value type by applying the coercion rules recursively.</p></li><li><p>The order of entries in the map remains unchanged.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>For example, if the required type is
                     <code>map(xs:string, xs:double)</code> and the supplied value is
                        <code>{ "x": 1, "y": 2 }</code>, the map is converted to
                        <code>{ "x": 1e0, "y": 2e0 }</code>.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Duplicate keys can occur if the value space of the target type
                        is more restrictive than the original type. For example, an error is raised
                        if the map <code>{ 1.2: 0, 1.2000001: 0 }</code>, which contains two keys
                        of type <code>xs:decimal</code>, is coerced to the type
                        <code>map(xs:float, xs:integer)</code>.</p></div></li><li><p>If <var>R</var> is a <a href="#doc-xquery40-RecordType">RecordType</a> and <var>J</var> is a map, then <var>J</var> is converted
                        to a new map as follows:</p><ol class="enumla"><li><p>The keys in the supplied map are unchanged.</p></li><li><p>In any map entry whose key is equal to the
                        name of one of the field declarations in <var>R</var> (under the rules
                           of the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-atomic-equal"><code>atomic-equal</code></a> function), the corresponding
                           value is converted to the required type defined by that field declaration, 
                           by applying the coercion rules recursively 
                           (but with XPath 1.0 compatibility mode treated as false).</p></li><li><p>The order of entries in the map is changed: entries whose keys correspond
                        to the names of field declarations in <var>R</var> appear first, in the order
                        of the corresponding field declarations, and (if the record type is extensible)
                        other entries then follow retaining their relative order in <var>J</var>.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>For example, if the required type is
                     <code>record(longitude as xs:double, latitude as xs:double)</code> and the supplied value is 
                        <code>{ "latitude": 53.2, "longitude": 0 }</code>,
                        then the map is converted to <code>{ "longitude": 0.0e0, "latitude": 53.2e0 }</code>.</p></div></li><li><p>If <var>R</var> is a <a href="#prod-xquery40-TypedFunctionType">TypedFunctionType</a> and <var>J</var> is a function item, then <a title="function coercion" class="termref" href="#dt-function-coercion">function coercion</a> is applied to <var>J</var>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Function coercion applies even if <var>J</var> is already an instance
                        of <var>R</var>.</p><p>Maps and arrays are functions, so function coercion applies to them as well.</p></div></li><li><p> If, after the
		above conversions, the resulting item does not match
		the expected item type <var>R</var> according to the rules for <a title="SequenceType matching" class="termref" href="#dt-sequencetype-matching">SequenceType
		Matching</a>, a type error is
		raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Under the general rules for type errors 
                           (see <a href="#id-kinds-of-errors"><b>2.4.1 Kinds of Errors</b></a>), a processor
                        <span class="verb">may</span> report a type error during static
                        analysis if it will necessarily occur when the expression is evaluated.
                        For example, the function call <code>fn:abs("beer")</code>
                        will necessarily fail when evaluated, because the function requires
                        a numeric value as its argument; this <span class="verb">may</span> be detected and reported
                        as a static error.</p></div></li></ol></div><div class="div3">
<h4><a id="id-implausible-coercions"/>3.4.2 <a href="#id-implausible-coercions" style="text-decoration: none">Implausible Coercions</a></h4><p>An expression is deemed to be
                     <a title="implausible" class="termref" href="#dt-implausible">implausible</a>
                  [<a href="#ERRXPTY0006" title="err:XPTY0006">err:XPTY0006</a>] if the static type of the expression, after applying
                     all necessary coercions, is <b>substantively disjoint</b>
                     with the required type <var>T</var>.</p><p>
                  [<a id="dt-substantively-disjoint" title="substantively disjoint">Definition</a>: Two 
               <a title="sequence type" class="termref" href="#dt-sequence-type">sequence types</a> are
                     deemed to be <b>substantively disjoint</b> if (a) neither is a subtype
                     of the other (see <a href="#id-seqtype-subtype"><b>3.3.1 Subtypes of Sequence Types</b></a>) and 
                     (b) the only values that
                     are instances of both types are one or more of the following:
               </p><ul><li><p>The empty sequence, <code>()</code>.</p></li><li><p>The <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-empty-map">empty map</a><sup><small>DM</small></sup>, <code>{}</code>.</p></li><li><p>The <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-empty-array">empty array</a><sup><small>DM</small></sup>, <code>[]</code>.</p></li></ul><p>]</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Examples of pairs of sequence types that are substantively disjoint
                        include:</p><ul><li><p>
                           <code>xs:integer*</code> and <code>xs:string*</code>
                        </p></li><li><p>
                           <code>map(xs:integer, node())</code> and <code>map(xs:string, node())</code>
                        </p></li><li><p>
                           <code>array(xs:integer)</code> and <code>array(xs:string)</code>
                        </p></li></ul></div><p>For example, supplying a value whose static type is <code>xs:integer*</code>
                     when the required type is <code>xs:string*</code> is <a title="implausible" class="termref" href="#dt-implausible">implausible</a>,
                     because it can succeed only in the special case where the actual value supplied
                     is an empty sequence.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The case where the supplied type and the required type are completely
                  disjoint (for example <code>map(*)</code> and <code>array(*)</code>) is covered
                  by the general rules for type errors: that case can always be reported as a static
                  error.</p></div><p>Examples of implausible coercions include the following:</p><ul><li><p>
                        <code>round(timezone-from-time($now))</code>. The result of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-timezone-from-time"><code>fn:timezone-from-time</code></a>
                  is of type <code>xs:dayTimeDuration?</code>, which is substantively disjoint with the required type
                  of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-round"><code>fn:round</code></a>, namely <code>xs:numeric?</code>.</p></li><li><p>
                        <code>function($x as xs:integer) as array(xs:string) { array { 1 to $x } }</code>. The type
                  of the function body is <code>array(xs:integer)</code>, which is substantively disjoint with the
                  required type <code>array(xs:string)</code>: the function can succeed only in the exceptional case
                  where the function body delivers an <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-empty-array">empty array</a><sup><small>DM</small></sup>.</p></li></ul></div><div class="div3">
<h4><a id="id-function-coercion"/>3.4.3 <a href="#id-function-coercion" style="text-decoration: none">Function Coercion</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-numeric-literals">⬇</a> <a href="#id-coercion-rules">⬆</a></p><ol><li><p>
                     Function coercion now allows a function with arity <var>N</var> to be supplied where a function of arity 
                     greater than <var>N</var> is expected. For example this allows the function <code>true#0</code> 
                     to be supplied where a predicate function is required.
                  </p></li><li><p>
                     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.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1020">1020</a> PRs <a href="https://github.com/qt4cg/qtspecs/pull/1023">1023</a> <a href="https://github.com/qt4cg/qtspecs/pull/1128">1128</a> 9 April 2024]</i></p></li></ol></div><p>
        Function coercion is a transformation applied to <a title="function item" class="termref" href="#dt-function-item">function items</a> during application of the
        <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>.
        [<a id="dt-function-coercion" title="function coercion">Definition</a>: 
                     <b>Function coercion</b> wraps a <a title="function item" class="termref" href="#dt-function-item">function item</a>
        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.]
               </p><p>Given a function <var>F</var>, and an expected function type <var>T</var>,
                  <a title="function coercion" class="termref" href="#dt-function-coercion">function coercion</a>
	proceeds as follows:</p><ol class="enumar"><li><p>If <var>F</var> has higher arity than <var>T</var>,
                     a type error is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>]
                     </p></li><li><p>If <var>F</var> has lower arity than <var>T</var>,
                     then <var>F</var> is wrapped in a new function that declares and ignores the
                  additional argument; the following steps are then applied to this new function.</p><p>For example, if <var>T</var> is <code>function(node(), xs:boolean) as xs:string</code>,
                  and the supplied function is <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-name"><code>fn:name#1</code></a>, then the supplied function is effectively
                  replaced by <code>function($n as node(), $b as xs:boolean) as xs:string { fn:name($n) }</code>
                     </p><div class="note"><p class="prefix"><b>Note:</b></p><p>This mechanism makes it easier to design versatile and extensible higher-order functions. 
                     For example, in previous versions of this specification, the second argument of
                     the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-filter"><code>fn:filter</code></a> function expected an argument of type 
                     <code>function(item()) as xs:boolean</code>. This has now been extended to
                     <code>function(item(), xs:integer) as xs:boolean</code>, but existing code continues
                     to work, because callback functions that are not interested in the value of the second
                     argument simply ignore it.                    
                  </p></div></li><li><p>A type error is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>] 
                        if, for any parameter type, or for the result type, the 
                        relevant type in the signature of the supplied function and the relevant type
                        in the expected function type are <a title="substantively disjoint" class="termref" href="#dt-substantively-disjoint">substantively disjoint</a>.
                     </p><p>For example, the types <code>xs:integer</code> and <code>xs:string</code>
                     are substantively disjoint, so a function with signature <code>function(xs:integer) as xs:boolean</code>
                        cannot be supplied where the expected type is <code>function(xs:string) as xs:boolean</code>.</p></li><li><p>Function coercion then
        returns a new <a title="function item" class="termref" href="#dt-function-item">function item</a>
        with the following properties
        (as defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#function-items">8.1 Function Items</a>):

        </p><ul><li><p>
                                 <b>name</b>:
            The name of <var>F</var>
                                 <span>(if not absent)</span>.
          </p></li><li><p>
                                 <b>identity</b>: A new function
              identity distinct from the identity of any other function item.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>See also <a href="#id-function-identity"><b>4.5.7 Function Identity</b></a>.</p></div></li><li><p>
                                 <b>signature</b>:
            <code>Annotations</code> is set to the annotations of <var>F</var>. <code>TypedFunctionType</code> is set to the expected type.
          </p></li><li><p>
                                 <b>implementation</b>:
            In effect,
            a <code>FunctionBody</code> that calls <var>F</var>,
            passing it the parameters of this new function,
            in order.
          </p></li><li><p>
                                 <b>nonlocal variable bindings</b>:
            An empty mapping.
          </p></li></ul></li></ol><p>
        These rules have the following consequences:

        </p><ul><li><p>SequenceType matching of the function’s arguments and result are delayed until that function is called.
          </p></li><li><p>When the coerced function is called, the supplied arguments must match the parameter
              typed defined in <var>T</var>; it is not sufficient to match the parameter types defined
              in <var>F</var>.</p></li><li><p>
                           The <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a> rules applied to the function’s arguments and result are defined by the SequenceType
            it has most recently been coerced to. Additional coercion rules could apply when the wrapped function
            is called.
          </p></li><li><p>
            If an implementation has static type information about a function, that can be used to type check the
            function’s argument and return types during static analysis.
          </p></li><li><p>When function coercion is applied to a map or an array, the resulting function is not
           a map or array, and cannot be used as such. For example, the expression </p><div class="exampleInner"><pre>let $f as function(xs:integer) as xs:boolean := { 0: false(), 1: true() }
return $f?0</pre></div><p>raises a type error, because a lookup expression requires the left hand
           operand to be a map or array, and <code>$f</code> is neither.</p></li><li><p>When function types are used as alternatives in a <a title="choice item type" class="termref" href="#dt-choice-item-type">choice item type</a>,
                 the supplied function is coerced to the first alternative for which coercion does
                 not raise a type error. In this situation it is important to write the alternatives
                 in order, with the most specific first. </p></li></ul><p>
      For instance, consider the following query:
      </p><div class="exampleInner"><pre>
declare function local:filter(
  $s as item()*, 
  $p as function(xs:string) as xs:boolean
) as item()* {
  $s[$p(.)]
};
let $f := function($a) { starts-with($a, "E") }
return local:filter(("Ethel", "Enid", "Gertrude"), $f)</pre></div><p>
        The function <code>$f</code> has a static type of <code>function(item()*) as item()*</code>. When the <code>local:filter()</code> function
        is called, the following occurs to the function:

        </p><ol class="enumar"><li><p>
                           The <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a> result in applying 
                           <a title="function coercion" class="termref" href="#dt-function-coercion">function coercion</a> to 
            <code>$f</code>,
            wrapping $f in a new function (<code>$p</code>)
            with the signature <code>function(xs:string) as xs:boolean</code>.
          </p></li><li><p>
                           <code>$p</code> is matched against the SequenceType of <code>function(xs:string) as xs:boolean</code>, and succeeds.
          </p></li><li><p>
                           When <code>$p</code> is called inside the predicate, <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion</a> 
                           and SequenceType matching rules are applied to the context value argument,
            resulting in an <code>xs:string</code> value or a type error.
          </p></li><li><p>
                           <code>$f</code> is called with the <code>xs:string</code>, which returns an <code>xs:boolean</code>.
          </p></li><li><p>
                           <code>$p</code> applies <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a> to the result sequence from <code>$f</code>, 
                           which already matches its declared return type of <code>xs:boolean</code>.
          </p></li><li><p>
            The <code>xs:boolean</code> is returned as the result of <code>$p</code>.
          </p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>
                     The semantics of <a title="function coercion" class="termref" href="#dt-function-coercion">function coercion</a> are specified in terms of wrapping the functions.
        Static typing may be able to reduce the number of places where this is actually necessary.
        However, it cannot be assumed that because a supplied function is an instance of the required
        function type, no function coercion is necessary: the supplied function might not perform
        all required checks on the types of its arguments.
      </p></div><p>Since maps and arrays are also functions in XQuery 4.0, 
                  <a title="function coercion" class="termref" href="#dt-function-coercion">function coercion</a> applies to them as well.

        For instance, consider the following expression:
      </p><div class="exampleInner"><pre>
let $m := {
  "Monday" : true(),
  "Wednesday" : false(),
  "Friday" : true()
}
let $days := ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
return filter($days, $m)</pre></div><p>
        The map <code>$m</code> is an instance of 
                  <code>function(xs:anyAtomicType?) as item()*</code>. 
                  When the <code>fn:filter()</code> function is called, the following 
                  occurs to the map:

</p><ol class="enumar"><li><p>The map <code>$m</code> is treated as a function equivalent to <code>map:get($m, ?)</code>.</p></li><li><p>The <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a> result in applying 
                           <a title="function coercion" class="termref" href="#dt-function-coercion">function coercion</a> 
                           to this function, wrapping it in a new function (<var>M′</var>) with the 
                           signature <code>function(item(), xs:integer) as xs:boolean</code>.</p></li><li><p>When <var>M′</var> is called by <code>fn:filter()</code>, <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion</a> 
                           and SequenceType matching rules are applied to the argument, 
                           resulting in an <code>item()</code> value 
                           (<code>$a</code>) or a type error.</p></li><li><p>
                           The function <code>map:get($m, ?)</code> is called with <code>$a</code>
                           as the argument; this returns either an <code>xs:boolean</code> or the empty sequence
                           (call the result <var>R</var>).</p></li><li><p>
                           The wrapper function <code>$p</code> applies the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>
                              to <var>R</var>. If <var>R</var> is an <code>xs:boolean</code> the matching succeeds. 
                              When it is an empty sequence (in particular, <code>$m</code> does not contain a 
                           key for <code>"Tuesday"</code>), a type error is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>], since the expected type is <code>xs:boolean</code> 
                           and the actual type is an empty sequence.</p></li></ol><p>Consider the following expression:
      </p><div class="exampleInner"><pre>

let $m := {
   "Monday" : true(),
   "Wednesday" : false(),
   "Friday" : true(),
}
let $days := ("Monday", "Wednesday", "Friday")
return filter($days, $m)</pre></div><p>In this case the result of the expression is the sequence <code>("Monday", "Friday")</code>.
                  But if the input sequence included the string <code>"Tuesday"</code>, the filter operation
                  would fail with a type error.
               </p><div class="note"><p class="prefix"><b>Note:</b></p><p>Function coercion applies even if the supplied function matches the required type.</p><p>For example, consider this case:</p><div class="exampleInner"><pre>
declare function local:filter(
  $s as item()*, 
  $p as function(xs:string) as xs:boolean
) as item()* {
  $s[$p(.)]
};

let $f := function($a) { $a mod 2 = 0 }
return local:filter(1 to 10, $f)</pre></div><p>Here the supplied function <code>$f</code> is an instance of the required type,
                  because its signature defaults the argument type to <code>item()*</code>, which
                  is a supertype of <code>xs:string</code>. The expression <code>$s[$p(.)]</code>
                  could in principle succeed. However, function coercion ensures that the supplied function 
                  is wrapped in a function that requires the argument to be of type <code>xs:string</code>,
                  so the call fails with a type error when the wrapping function is invoked supplying an
                  <code>xs:integer</code> as the argument.</p><p>This has the consequence that in XQuery 4.0, there is a backwards
                     incompatibility introduced because coercion rules
                  now apply to global variable declarations (<code>declare variable</code>) and
                  local variable bindings (for example <code>let</code> clauses). Previously
                  the following would execute without error:</p><div class="exampleInner"><pre>let $f as function(xs:integer) as item()* := function($x) { $x + 1 }
return $f(12.3)</pre></div><p>With XQuery 4.0, as a consequence of function coercion,
                     this fails with a type error because the
                  argument supplied in the function call is not of type <code>xs:integer</code>.</p></div></div><div class="div3">
<h4><a id="id-coercion-examples"/>3.4.4 <a href="#id-coercion-examples" style="text-decoration: none">Examples of Coercions</a></h4><p>This section illustrates the effect of the coercion rules with examples.</p><div class="example">
<div class="exampleHeader"><a id="eg-coercion-to-string"/>Example: Coercion to <code>xs:string</code>
                  </div><p>Consider the case where the required type (of a variable, or a function argument)
                  is <code>xs:string</code>. For example, the second argument of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-matches"><code>fn:matches</code></a>,
                  which expects a regular expression. The table below illustrates the values that might be supplied, and
                  the coercions that are applied.</p><table class="medium"><thead><tr><th style="text-align:left">Supplied Value</th><th style="text-align:left">Coercion</th></tr></thead><tbody><tr><td style="vertical-align:top">
                              <code>"[0-9]"</code>
                           </td><td style="vertical-align:top">
                              <p>None; the supplied value is an instance of the required type.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>default-language()</code>
                           </td><td style="vertical-align:top">
                              <p>None; the supplied value is an instance of <code>xs:language</code>, which
                              is a subtype of the required type <code>xs:string</code>.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>&lt;a&gt;[0-9]&lt;/a&gt;</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied element node is atomized. Unless it has been schema-validated,
                           the typed value will be an instance of <code>xs:untypedAtomic</code>, which
                           is accepted when the required type is <code>xs:string</code>.</p>
                              <p>Supplying an element whose type annotation is (say) <code>xs:date</code> 
                                 will fail with a type error.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>xs:anyURI("urn:dummy")</code>
                           </td><td style="vertical-align:top">
                              <p>Supplying an instance of <code>xs:anyURI</code> where the expected type
                              is <code>xs:string</code> is permitted; this is one of the pairs of types
                           where implicit casting is allowed.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>["a|b"]</code>
                           </td><td style="vertical-align:top">
                              <p>Supplying an array holding a single string succeeds, because the rules cause the
                              array to be atomized, and the value after atomization is a single string.</p>
                              <p>Supplying an array holding multiple strings would fail.</p>
                           </td></tr></tbody></table></div><p> </p><div class="example">
<div class="exampleHeader"><a id="eg-coercion-to-decimal"/>Example: Coercion to <code>xs:decimal?</code>
                  </div><p>Consider the case where the required type (of a variable, or a function argument)
                     is <code>xs:decimal?</code>. For example, the first argument of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-seconds"><code>fn:seconds</code></a>,
                     which expects a decimal number of seconds. The table below illustrates the values that might be supplied, and
                     the coercions that are applied.</p><table class="medium"><thead><tr><th style="text-align:left">Supplied Value</th><th style="text-align:left">Coercion</th></tr></thead><tbody><tr><td style="vertical-align:top">
                              <code>12.4</code>
                           </td><td style="vertical-align:top">
                              <p>None; the supplied value is an instance of the required type.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>()</code>
                           </td><td style="vertical-align:top">
                              <p>None; an empty sequence is an instance of the required type.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>42</code>
                           </td><td style="vertical-align:top">
                              <p>None; the supplied value is an instance of <code>xs:integer</code>,
                              which is a subtype of the required type.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>math:pi()</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied value is an instance of <code>xs:double</code>,
                              which can be converted to <code>xs:decimal</code> under the coercion rules.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>("a", "b")[.="c"]</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied value is an empty sequence, which is a valid
                              instance of the required type <code>xs:decimal?</code>. However,
                           the processor may (optionally) reject this as an implausible coercion,
                           on the grounds that it can only succeed in one special case, namely
                           where the filter expression selects no values. </p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>(1.5, 2.5, 3.5)</code>
                           </td><td style="vertical-align:top">
                              <p>A type error is raised.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>&lt;a&gt;3.14159&lt;/a&gt;</code>
                           </td><td style="vertical-align:top">
                              <p>The element node is atomized; unless it has been schema-validated, the
                              result will be <code>"3.14159"</code> as an instance of <code>xs:untypedAtomic</code>.
                             This is converted to an instance of <code>xs:decimal</code> following the rules
                           of the <code>cast as</code> operator.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>[1.5]</code>
                           </td><td style="vertical-align:top">
                              <p>The array is atomized, and the result is a valid instance of the required
                           type <code>xs:decimal?</code>
                              </p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>[]</code>
                           </td><td style="vertical-align:top">
                              <p>The array is atomized, and the result is an empty sequence, which is a valid instance of the required
                              type <code>xs:decimal?</code>
                              </p>
                           </td></tr></tbody></table></div><p> </p><div class="example">
<div class="exampleHeader"><a id="eg-coercion-to-positive-integer"/>Example: Coercion to <code>xs:positive-integer</code>
                  </div><p>Consider the case where the required type (of a variable, or a function argument)
                     is <code>xs:positive-integer</code>. The table below illustrates the values that might be supplied, and
                     the coercions that are applied.</p><table class="medium"><thead><tr><th style="text-align:left">Supplied Value</th><th style="text-align:left">Coercion</th></tr></thead><tbody><tr><td style="vertical-align:top">
                              <code>12</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied value is of type <code>xs:integer</code>. Because the supplied value and
                              the required type, <code>xs:positiveInteger</code>, both come under the primitive
                           type <code>xs:decimal</code>, and the value <code>12</code> is within the value space
                           of <code>xs:positiveInteger</code>, the value is relabeled as an <code>xs:positiveInteger</code>
                           and the call succeeds.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>12.1</code>
                           </td><td style="vertical-align:top">
                              <p>This fails with a type error, because the <code>xs:decimal</code> value <code>12.1</code>
                              is not a value in the value space of <code>xs:positiveInteger</code>. This is so even though
                           casting to <code>xs:positiveInteger</code> would succeed.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>math:pi()</code>
                           </td><td style="vertical-align:top">
                              <p>This fails with a type error. A value of type <code>xs:double</code> is accepted
                           where the required type is <code>xs:decimal</code> or <code>xs:float</code>,
                           but not where it is <code>xs:positiveInteger</code>.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>&lt;a&gt;1200&lt;/a&gt;</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied element node is atomized. If the element has not been schema-validated,
                           the result will be an <code>xs:untypedAtomic</code> item, which is successfully cast to the
                           required type <code>xs:positiveInteger</code>. If the element has been validated against a schema,
                           then coercion succeeds if the typed value would itself be acceptable, for example if it
                           is an <code>xs:positiveInteger</code>, or some other <code>xs:decimal</code> within the value space
                           of <code>xs:positiveInteger</code>.</p>
                           </td></tr></tbody></table></div><p> </p><div class="example">
<div class="exampleHeader"><a id="eg-coercion-to-union"/>Example: Coercion to a union type</div><p>Consider the first parameter of the function <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-char"><code>fn:char</code></a>, whose declared
                  type is <code>(xs:string | xs:positiveInteger)</code>. The rules are the same
                  as if it were a union typed declared in an imported schema.</p><table class="medium"><thead><tr><th style="text-align:left">Supplied Value</th><th style="text-align:left">Coercion</th></tr></thead><tbody><tr><td style="vertical-align:top">
                              <code>"amp"</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied value is of type <code>xs:string</code>, which is one of the allowed
                           types. The call therefore succeeds.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>"#"</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied value is of type <code>xs:string</code>, which is one of the allowed
                              types. As far as the coercion rules are concerned, the call therefore succeeds. Under the
                              semantic rules for the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-char"><code>fn:char</code></a> function, however, this value is not accepted;
                              a dynamic error (as distinct from a type error) is therefore raised.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>0x25</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied value is of type <code>xs:integer</code>. Although this is not one of the allowed
                              types, it is acceptable because coercion of the value to type <code>xs:positiveInteger</code>
                              succeeds. The value is relabeled as an instance of <code>xs:positiveInteger</code>.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>&lt;a&gt;0x25&lt;/a&gt;</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied element node is atomized. Assuming that the node has not been schema-validated,
                              the result is an instance of <code>xs:untypedAtomic</code>. The member types of the choice
                              are tested in order. Conversion to <code>xs:string</code> with the value "0x25" succeeds, so 
                              the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-char"><code>fn:char</code></a> function is called supplying this string; but the function rejects this
                              string as semantically invalid. The same would happen if the value were, say, &lt;a&gt;37&lt;/a&gt;.
                              Supplying such a value requires an explicit cast, for example <code>fn:char( xs:positiveInteger( ./a ))</code>.</p>
                           </td></tr></tbody></table></div><p> </p><div class="example">
<div class="exampleHeader"><a id="eg-coercion-to-choice"/>Example: Coercion to a choice type</div><p>Suppose the required type is <code>(record(x as xs:decimal, y as xs:decimal, *) | record(size as enum("S", "M", "L", "XL"), *))</code>.</p><table class="medium"><col style="width:40%" span="1"/><col style="width:60%" span="1"/><thead><tr><th style="text-align:left">Supplied Value</th><th style="text-align:left">Coercion</th></tr></thead><tbody><tr><td style="vertical-align:top">
                              <code>{ "x": 1, "y": 2, "z": 3 }</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied value is an instance of the first record type: no coercion is necessary.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>{ "size": "M" }</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied value is an instance of the second record type: no coercion is necessary.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>{ "x": 1, "y": 2, "size": "XL" }</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied value is an instance of both record types: no coercion is necessary.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>{ "x": 1e0, "y": 2e0, "size": "XL" }</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied value is not an instance of the first record type because the fields are of
                              type <code>xs:double</code> rather than <code>xs:decimal</code>. It is however an instance
                              of the second record type. It is therefore accepted <em>as is</em>; the fields
                           <code>x</code> and <code>y</code> are not converted from <code>xs:double</code> to
                           <code>xs:decimal</code>.</p>
                           </td></tr><tr><td style="vertical-align:top">
                              <code>{ "x": 1e0, "y": 2e0, "size": "XXL" }</code>
                           </td><td style="vertical-align:top">
                              <p>The supplied value is not an instance of the first record type because the fields are of
                              type <code>xs:double</code> rather than <code>xs:decimal</code>, and it is not an instance
                              of the second record type because the <code>size</code> value does not match the enumeration
                              type. Coercion is therefore attempted to the first record type, and succeeds. The <code>x</code>
                           and <code>y</code> fields are coerced to <code>xs:decimal</code>, and the <code>size</code> field
                           is accepted <em>as is</em>.</p>
                           </td></tr></tbody></table></div></div></div><div class="div2">
<h3><a id="id-predefined-types"/>3.5 <a href="#id-predefined-types" style="text-decoration: none">Schema Types</a></h3><p>
               [<a id="dt-schema-type" title="schema type">Definition</a>: A <b>schema type</b>
            is a complex type or simple type as defined in the <a href="#XMLSchema10">[XML Schema 1.0]</a> or <a href="#XMLSchema11">[XML Schema 1.1]</a> specifications, including built-in types as well as user-defined types.]
            </p><p>Every schema type is either a <b>complex type</b> or a
            <b>simple type</b>; simple types are further subdivided into <b>list types</b>, <b>union
               types</b>, and <b>atomic types</b> (see <a href="#XMLSchema10">[XML Schema 1.0]</a> or <a href="#XMLSchema11">[XML Schema 1.1]</a> for definitions and explanations of these terms.)</p><p>A schema type can appear as a type annotation on an
            element or attribute node. The type annotation on an element node can be
            a complex type or a simple type; the type annotation on an attribute node
            is always a simple type. Non-instantiable types such as <code>xs:NOTATION</code> or
            <code>xs:anyAtomicType</code> never appear as type annotations, but their derived
            types can be so used. Union types never appear as type annotations; when
            an element or attribute is validated against a union type, the resulting
            type annotation will be one of the types in the transitive membership of 
            the union type.</p><p>
               [<a id="dt-atomic-type" title="atomic type">Definition</a>: An <b>atomic type</b>
            is a simple <a title="schema type" class="termref" href="#dt-schema-type">schema type</a> whose 
            <a href="https://www.w3.org/TR/xmlschema11-1/#std-variety">{variety}<sup><small>XS11-1</small></sup></a>
            is <code>atomic</code>.]
            </p><p>An <b>atomic type</b> is either a built-in atomic
            type (defined either in the XSD specification or in this specification), or
            it is a user-defined atomic type included in an imported schema.</p><p>The schema types defined in  <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#types-predefined">4.1.4 Predefined Types</a> are summarized below.</p><p>The <a title="in-scope schema type" class="termref" href="#dt-is-types">in-scope schema types</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>
            are initialized with certain predefined schema types,
            including the built-in schema types in the namespace
            <code>http://www.w3.org/2001/XMLSchema</code>,
            which has the predefined namespace prefix
            <code>xs</code>.  The schema types in this namespace are defined in <a href="#XMLSchema10">[XML Schema 1.0]</a> or  <a href="#XMLSchema11">[XML Schema 1.1]</a>
            and augmented by additional types defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a>.  Element and attribute
            declarations in the <code>xs</code> namespace are
            not implicitly included in the static context. The schema types defined in  <a href="#xpath-datamodel-40">[XDM 4.0]</a> are summarized below.</p><ol class="enumar"><li><p>
                     [<a id="dt-untyped" title="xs:untyped">Definition</a>: 
                        <code>xs:untyped</code> is  used as the <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> of an element node that has not been validated, or has been validated in <code>skip</code> mode.] 
                  No predefined schema types are derived from <code>xs:untyped</code>.</p></li><li><p>
                     [<a id="dt-untypedAtomic" title="xs:untypedAtomic">Definition</a>: 
                        <code>xs:untypedAtomic</code>
                     is an <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a> that is used to denote untyped atomic data, 
                     such as text that has not been assigned a more specific type.] 
                  An attribute that has been validated in <code>skip</code> mode is represented in the <a title="data model" class="termref" href="#dt-datamodel">data model</a> by an attribute node with the <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a>
                     <code>xs:untypedAtomic</code>. No predefined schema types are derived from <code>xs:untypedAtomic</code>.</p></li><li><p>
                     [<a id="dt-dayTimeDuration" title="xs:dayTimeDuration">Definition</a>: 
                        <code>xs:dayTimeDuration</code> is derived by restriction from <code>xs:duration</code>. The  lexical representation of <code>xs:dayTimeDuration</code>
                     is restricted to contain only day, hour, minute, and second
                     components.]
                  </p></li><li><p>
                     [<a id="dt-yearMonthDuration" title="xs:yearMonthDuration">Definition</a>: 
                        <code>xs:yearMonthDuration</code> is derived by restriction from <code>xs:duration</code>. The lexical representation of <code>xs:yearMonthDuration</code> is
                     restricted to contain only year and month
                     components.]
                  </p></li><li><p>
                     [<a id="dt-anyAtomicType" title="xs:anyAtomicType">Definition</a>: 
                        <code>xs:anyAtomicType</code> is an <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a> 
                     that includes all atomic items (and no values that
                     are not atomic). Its base type is
                     <code>xs:anySimpleType</code> from which all simple types, including atomic,
                     list, and union types, are derived. All primitive atomic types, such as
                     <code>xs:decimal</code> and <code>xs:string</code>, have <code>xs:anyAtomicType</code> as their base type.]
                  </p><div class="note"><p class="prefix"><b>Note:</b></p><p>
                        <code>xs:anyAtomicType</code>  will not appear as the type of an actual value in an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a>.</p></div></li><li><p>
                     [<a id="dt-xs-error" title="xs:error">Definition</a>: 
                        <code>xs:error</code> is a simple type with no value space.  It is defined in <a href="https://www.w3.org/TR/xmlschema11-1/#xsd-error">
                  
                     3.16.7.3 xs:error
                  
               </a><sup><small>XS11-1</small></sup> and  can be used in the <a href="#id-sequencetype-syntax"><b>3.1 Sequence Types</b></a> to raise errors.]
                  </p></li></ol><p>The relationships among the schema types in the <code>xs</code> namespace are illustrated in Figure 2. A more complete description of the XQuery 4.0 type hierarchy can be found in 
            <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#datatypes">1.8 Type System</a>.</p><img src="types.jpg" alt="Type Hierarchy Diagram"/><p>Figure 2: Hierarchy of Schema Types used in XQuery 4.0.</p></div></div><div class="div1">
<h2><a id="id-expressions"/>4 <a href="#id-expressions" style="text-decoration: none">Expressions</a></h2><p>This section discusses each of the basic kinds of expression. Each kind of expression has a name such as <code>PathExpr</code>, 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.</p><p>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 href="#nt-bnf"><b>A XQuery 4.0 Grammar</b></a>].</p><p>
            <span class="xquery">
               [<a id="dt-query" title="query">Definition</a>: A <b>query</b> consists of one or more <a title="module" class="termref" href="#dt-module">modules</a>.]  If a query is executable, one of its modules has a <a title="query body" class="termref" href="#dt-queryBody">Query Body</a>  containing an expression whose value is the result of the query. An expression is represented in the XQuery grammar by the symbol <a href="#doc-xquery40-Expr">Expr</a>.</span>
         </p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-Expr-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Expr-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                  <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                  <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                  <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                  <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                  <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                  <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                  <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
               </code></td></tr></tbody></table><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                  <a href="#doc-xquery40-ExprSingle-FLWORExpr">FLWORExpr</a>
                  <br/>|  <a href="#doc-xquery40-ExprSingle-QuantifiedExpr">QuantifiedExpr</a>
                  <br/>|  <a href="#doc-xquery40-ExprSingle-SwitchExpr">SwitchExpr</a>
                  <br/>|  <a href="#doc-xquery40-ExprSingle-TypeswitchExpr">TypeswitchExpr</a>
                  <br/>|  <a href="#doc-xquery40-ExprSingle-IfExpr">IfExpr</a>
                  <br/>|  <a href="#doc-xquery40-ExprSingle-TryCatchExpr">TryCatchExpr</a>
                  <br/>|  <a href="#doc-xquery40-ExprSingle-OrExpr">OrExpr</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExprSingle-FLWORExpr"/><code><a href="#prod-xquery40-FLWORExpr">FLWORExpr</a></code></td><td>::=</td><td><code>
                  <a href="#prod-xquery40-InitialClause">InitialClause</a>
                  <a href="#prod-xquery40-IntermediateClause">IntermediateClause</a>*  <a href="#doc-xquery40-ReturnClause">ReturnClause</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExprSingle-QuantifiedExpr"/><code><a href="#prod-xquery40-QuantifiedExpr">QuantifiedExpr</a></code></td><td>::=</td><td><code>("some"  |  "every")  (<a href="#prod-xquery40-QuantifierBinding">QuantifierBinding</a> ++ ",")  "satisfies"  <a href="#doc-xquery40-ExprSingle">ExprSingle</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExprSingle-SwitchExpr"/><code><a href="#prod-xquery40-SwitchExpr">SwitchExpr</a></code></td><td>::=</td><td><code>"switch"  <a href="#prod-xquery40-SwitchComparand">SwitchComparand</a>  (<a href="#prod-xquery40-SwitchCases">SwitchCases</a>  |  <a href="#prod-xquery40-BracedSwitchCases">BracedSwitchCases</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExprSingle-TypeswitchExpr"/><code><a href="#prod-xquery40-TypeswitchExpr">TypeswitchExpr</a></code></td><td>::=</td><td><code>"typeswitch"  "("  <a href="#doc-xquery40-Expr">Expr</a>  ")"  (<a href="#prod-xquery40-TypeswitchCases">TypeswitchCases</a>  |  <a href="#prod-xquery40-BracedTypeswitchCases">BracedTypeswitchCases</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExprSingle-IfExpr"/><code><a href="#prod-xquery40-IfExpr">IfExpr</a></code></td><td>::=</td><td><code>"if"  "("  <a href="#doc-xquery40-Expr">Expr</a>  ")"  (<a href="#prod-xquery40-UnbracedActions">UnbracedActions</a>  |  <a href="#prod-xquery40-BracedAction">BracedAction</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExprSingle-TryCatchExpr"/><code><a href="#prod-xquery40-TryCatchExpr">TryCatchExpr</a></code></td><td>::=</td><td><code>
                  <a href="#prod-xquery40-TryClause">TryClause</a>  ((<a href="#prod-xquery40-CatchClause">CatchClause</a>+  <a href="#prod-xquery40-FinallyClause">FinallyClause</a>?)  |  <a href="#prod-xquery40-FinallyClause">FinallyClause</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExprSingle-OrExpr"/><code><a href="#prod-xquery40-OrExpr">OrExpr</a></code></td><td>::=</td><td><code>
                  <a href="#prod-xquery40-AndExpr">AndExpr</a>  ("or"  <a href="#prod-xquery40-AndExpr">AndExpr</a>)*</code></td></tr></tbody></table><p>The XQuery 4.0 operator that has lowest precedence is the <a title="comma operator" class="termref" href="#dt-comma-operator">comma operator</a>, which is used to combine two operands to form a sequence. 
         As shown in the grammar, a general expression (<a href="#doc-xquery40-Expr">Expr</a>) can consist of multiple <a href="#doc-xquery40-ExprSingle">ExprSingle</a> operands, separated by commas.</p><p>The name <a href="#doc-xquery40-ExprSingle">ExprSingle</a> denotes an expression that does not contain a top-level <a title="comma operator" class="termref" href="#dt-comma-operator">comma operator</a> (despite its name, an <a href="#doc-xquery40-ExprSingle">ExprSingle</a> may evaluate to a sequence containing more than one item.)</p><p>The symbol <a href="#doc-xquery40-ExprSingle">ExprSingle</a> 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 <a href="#doc-xquery40-ExprSingle">ExprSingle</a>, because commas are 
         used to separate the arguments of a function call.</p><p>After the comma, the expressions that have next lowest precedence are
<span class="xquery">
               <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>,</span>
            <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>,
<span class="xquery">
               <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>, <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>, </span>
            <a href="#doc-xquery40-IfExpr">IfExpr</a>,
<span class="xquery">
               <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>, </span>
and <a href="#doc-xquery40-OrExpr">OrExpr</a>. Each of these expressions is described in a separate section of this document.</p><div class="div2">
<h3><a id="comments"/>4.1 <a href="#comments" style="text-decoration: none">Comments</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Comment"/><code><a href="#prod-xquery40-Comment">Comment</a></code></td><td>::=</td><td><code>"(:"  (<a href="#doc-xquery40-Comment-CommentContents">CommentContents</a>  |  <a href="#doc-xquery40-Comment">Comment</a>)*  ":)"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-comments">gn: comments</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Comment-CommentContents"/><code><a href="#prod-xquery40-CommentContents">CommentContents</a></code></td><td>::=</td><td><code>(<a href="#prod-xquery40-Char">Char</a>+ - (Char* ('(:' | ':)') Char*))</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody></table><p>Comments may be used to provide information relevant to programmers who read <span class="xquery">a query, either in the <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a> or in the <a title="query body" class="termref" href="#dt-queryBody">Query Body</a>
               </span>
            . Comments are lexical constructs only, and do not affect  <span class="xquery">query</span>
             processing.</p><p>Comments are strings, delimited by the symbols <code>(:</code> and <code>:)</code>. Comments may be nested.</p><p>A comment may be used anywhere <a title="ignorable whitespace" class="termref" href="#IgnorableWhitespace">ignorable whitespace</a> is allowed (see <a href="#DefaultWhitespaceHandling"><b>A.3.4.1 Default Whitespace Handling</b></a>).</p><p>The following is an example of a comment:</p><div class="exampleInner"><pre>(: Houston, we have a problem :)</pre></div></div><div class="div2">
<h3><a id="id-primary-expressions"/>4.2 <a href="#id-primary-expressions" style="text-decoration: none">Primary Expressions</a></h3><p>
               [<a id="dt-primary-expression" title="primary expression">Definition</a>: 
               A <b>primary expression</b> is an instance of the production
               <a href="#doc-xquery40-PrimaryExpr">PrimaryExpr</a>. Primary expressions are the basic primitives of the
	 language. They include literals, variable references, context value references, <span class="xquery">constructors, </span> 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.]
               <span class="xquery">Node Constructors are described in <a href="#id-constructors"><b>4.12 Node Constructors</b></a>.</span>Map and Array Constructors are described in <a href="#id-maps"><b>4.14.1 Maps</b></a> and <a href="#id-arrays"><b>4.14.2 Arrays</b></a>.
<span class="xquery">String Constructors are described in <a href="#id-string-constructors"><b>4.9.3 String Constructors</b></a>.</span>
            </p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr"/><code><a href="#prod-xquery40-PrimaryExpr">PrimaryExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PrimaryExpr-Literal">Literal</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-VarRef">VarRef</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-ParenthesizedExpr">ParenthesizedExpr</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-ContextValueRef">ContextValueRef</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-FunctionCall">FunctionCall</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-OrderedExpr">OrderedExpr</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-UnorderedExpr">UnorderedExpr</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-NodeConstructor">NodeConstructor</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-FunctionItemExpr">FunctionItemExpr</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-MapConstructor">MapConstructor</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-ArrayConstructor">ArrayConstructor</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-StringTemplate">StringTemplate</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-StringConstructor">StringConstructor</a>
                     <br/>|  <a href="#doc-xquery40-PrimaryExpr-UnaryLookup">UnaryLookup</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-Literal"/><code><a href="#prod-xquery40-Literal">Literal</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-NumericLiteral">NumericLiteral</a>  |  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>  |  <a href="#doc-xquery40-QNameLiteral">QNameLiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-VarRef"/><code><a href="#prod-xquery40-VarRef">VarRef</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-EQName">EQName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-ParenthesizedExpr"/><code><a href="#prod-xquery40-ParenthesizedExpr">ParenthesizedExpr</a></code></td><td>::=</td><td><code>"("  <a href="#doc-xquery40-Expr">Expr</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-ContextValueRef"/><code><a href="#prod-xquery40-ContextValueRef">ContextValueRef</a></code></td><td>::=</td><td><code>"."</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-FunctionCall"/><code><a href="#prod-xquery40-FunctionCall">FunctionCall</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-EQName">EQName</a>
                     <a href="#prod-xquery40-ArgumentList">ArgumentList</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                   */</td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-parens">gn: parens</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-OrderedExpr"/><code><a href="#prod-xquery40-OrderedExpr">OrderedExpr</a></code></td><td>::=</td><td><code>"ordered"  <a href="#doc-xquery40-PrimaryExpr-EnclosedExpr">EnclosedExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-UnorderedExpr"/><code><a href="#prod-xquery40-UnorderedExpr">UnorderedExpr</a></code></td><td>::=</td><td><code>"unordered"  <a href="#doc-xquery40-PrimaryExpr-EnclosedExpr">EnclosedExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-NodeConstructor"/><code><a href="#prod-xquery40-NodeConstructor">NodeConstructor</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-DirectConstructor">DirectConstructor</a>
                     <br/>|  <a href="#doc-xquery40-ComputedConstructor">ComputedConstructor</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-FunctionItemExpr"/><code><a href="#prod-xquery40-FunctionItemExpr">FunctionItemExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PrimaryExpr-NamedFunctionRef">NamedFunctionRef</a>  |  <a href="#doc-xquery40-PrimaryExpr-InlineFunctionExpr">InlineFunctionExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-NamedFunctionRef"/><code><a href="#prod-xquery40-NamedFunctionRef">NamedFunctionRef</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-EQName">EQName</a>  "#"  <a href="#prod-xquery40-IntegerLiteral">IntegerLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-InlineFunctionExpr"/><code><a href="#prod-xquery40-InlineFunctionExpr">InlineFunctionExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-Annotation">Annotation</a>*  ("function"  |  "fn")  <a href="#prod-xquery40-FunctionSignature">FunctionSignature</a>?  <a href="#prod-xquery40-FunctionBody">FunctionBody</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-MapConstructor"/><code><a href="#prod-xquery40-MapConstructor">MapConstructor</a></code></td><td>::=</td><td><code>"map"?  "{"  (<a href="#prod-xquery40-MapConstructorEntry">MapConstructorEntry</a> ** ",")  "}"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-ArrayConstructor"/><code><a href="#prod-xquery40-ArrayConstructor">ArrayConstructor</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-SquareArrayConstructor">SquareArrayConstructor</a>  |  <a href="#prod-xquery40-CurlyArrayConstructor">CurlyArrayConstructor</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-StringTemplate"/><code><a href="#prod-xquery40-StringTemplate">StringTemplate</a></code></td><td>::=</td><td><code>"`"  (<a href="#prod-xquery40-StringTemplateFixedPart">StringTemplateFixedPart</a>  |  <a href="#prod-xquery40-StringTemplateVariablePart">StringTemplateVariablePart</a>)*  "`"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-StringConstructor"/><code><a href="#prod-xquery40-StringConstructor">StringConstructor</a></code></td><td>::=</td><td><code>"``["  <a href="#prod-xquery40-StringConstructorContent">StringConstructorContent</a>  "]``"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PrimaryExpr-UnaryLookup"/><code><a href="#prod-xquery40-UnaryLookup">UnaryLookup</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-Lookup">Lookup</a>
                  </code></td></tr></tbody></table><div class="div3">
<h4><a id="id-literals"/>4.2.1 <a href="#id-literals" style="text-decoration: none">Literals</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Literal"/><code><a href="#prod-xquery40-Literal">Literal</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-Literal-NumericLiteral">NumericLiteral</a>  |  <a href="#doc-xquery40-Literal-StringLiteral">StringLiteral</a>  |  <a href="#doc-xquery40-Literal-QNameLiteral">QNameLiteral</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Literal-NumericLiteral"/><code><a href="#prod-xquery40-NumericLiteral">NumericLiteral</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-IntegerLiteral">IntegerLiteral</a>  |  <a href="#prod-xquery40-HexIntegerLiteral">HexIntegerLiteral</a>  |  <a href="#prod-xquery40-BinaryIntegerLiteral">BinaryIntegerLiteral</a>  |  <a href="#prod-xquery40-DecimalLiteral">DecimalLiteral</a>  |  <a href="#prod-xquery40-DoubleLiteral">DoubleLiteral</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Literal-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Literal-QNameLiteral"/><code><a href="#prod-xquery40-QNameLiteral">QNameLiteral</a></code></td><td>::=</td><td><code>"#"  <a href="#doc-xquery40-EQName">EQName</a>
                     </code></td></tr></tbody></table><p>
                  [<a id="dt-literal" title="literal">Definition</a>: A <b>literal</b> is a direct syntactic representation of an
		atomic item.] XQuery 4.0 supports three kinds of literals: numeric literals,
		string literals, and QName literals.</p><div class="div4">
<h5><a id="id-numeric-literals"/>4.2.1.1 <a href="#id-numeric-literals" style="text-decoration: none">Numeric Literals</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-qname-literals">⬇</a> <a href="#id-function-coercion">⬆</a></p><ol><li><p>
                     Numeric literals can now be written in hexadecimal or binary notation; 
                     and underscores can be included for readability.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/429">429</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/433">433</a> 25 April 2023]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral"/><code><a href="#prod-xquery40-NumericLiteral">NumericLiteral</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-NumericLiteral-IntegerLiteral">IntegerLiteral</a>  |  <a href="#doc-xquery40-NumericLiteral-HexIntegerLiteral">HexIntegerLiteral</a>  |  <a href="#doc-xquery40-NumericLiteral-BinaryIntegerLiteral">BinaryIntegerLiteral</a>  |  <a href="#doc-xquery40-NumericLiteral-DecimalLiteral">DecimalLiteral</a>  |  <a href="#doc-xquery40-NumericLiteral-DoubleLiteral">DoubleLiteral</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral-IntegerLiteral"/><code><a href="#prod-xquery40-IntegerLiteral">IntegerLiteral</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-NumericLiteral-Digits">Digits</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral-Digits"/><code><a href="#prod-xquery40-Digits">Digits</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-NumericLiteral-DecDigit">DecDigit</a>  ((<a href="#doc-xquery40-NumericLiteral-DecDigit">DecDigit</a>  |  "_")*  <a href="#doc-xquery40-NumericLiteral-DecDigit">DecDigit</a>)?</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral-DecDigit"/><code><a href="#prod-xquery40-DecDigit">DecDigit</a></code></td><td>::=</td><td><code>[0-9]</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral-HexIntegerLiteral"/><code><a href="#prod-xquery40-HexIntegerLiteral">HexIntegerLiteral</a></code></td><td>::=</td><td><code>"0x"  <a href="#doc-xquery40-NumericLiteral-HexDigits">HexDigits</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral-HexDigits"/><code><a href="#prod-xquery40-HexDigits">HexDigits</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-NumericLiteral-HexDigit">HexDigit</a>  ((<a href="#doc-xquery40-NumericLiteral-HexDigit">HexDigit</a>  |  "_")*  <a href="#doc-xquery40-NumericLiteral-HexDigit">HexDigit</a>)?</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral-HexDigit"/><code><a href="#prod-xquery40-HexDigit">HexDigit</a></code></td><td>::=</td><td><code>[0-9a-fA-F]</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral-BinaryIntegerLiteral"/><code><a href="#prod-xquery40-BinaryIntegerLiteral">BinaryIntegerLiteral</a></code></td><td>::=</td><td><code>"0b"  <a href="#doc-xquery40-NumericLiteral-BinaryDigits">BinaryDigits</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral-BinaryDigits"/><code><a href="#prod-xquery40-BinaryDigits">BinaryDigits</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-NumericLiteral-BinaryDigit">BinaryDigit</a>  ((<a href="#doc-xquery40-NumericLiteral-BinaryDigit">BinaryDigit</a>  |  "_")*  <a href="#doc-xquery40-NumericLiteral-BinaryDigit">BinaryDigit</a>)?</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral-BinaryDigit"/><code><a href="#prod-xquery40-BinaryDigit">BinaryDigit</a></code></td><td>::=</td><td><code>[01]</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral-DecimalLiteral"/><code><a href="#prod-xquery40-DecimalLiteral">DecimalLiteral</a></code></td><td>::=</td><td><code>("."  <a href="#doc-xquery40-NumericLiteral-Digits">Digits</a>)  |  (<a href="#doc-xquery40-NumericLiteral-Digits">Digits</a>  "."  <a href="#doc-xquery40-NumericLiteral-Digits">Digits</a>?)</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NumericLiteral-DoubleLiteral"/><code><a href="#prod-xquery40-DoubleLiteral">DoubleLiteral</a></code></td><td>::=</td><td><code>(("."  <a href="#doc-xquery40-NumericLiteral-Digits">Digits</a>)  |  (<a href="#doc-xquery40-NumericLiteral-Digits">Digits</a>  ("."  <a href="#doc-xquery40-NumericLiteral-Digits">Digits</a>?)?))  [eE]  [+-]?  <a href="#doc-xquery40-NumericLiteral-Digits">Digits</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody></table><p>The value of a numeric literal is determined as follows (taking the rules in order):</p><ol class="enumar"><li><p>Underscore characters are stripped out. Underscores may be included in a numeric
                  literal to aid readability, but have no effect on the value. For example, <code>1_000_000</code>
                  is equivalent to <code>1000000</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Underscores must not appear at the beginning or end of a sequence of digits, only
                  in intermediate positions. Multiple adjacent underscores are allowed.</p></div></li><li><p>A <code>HexIntegerLiteral</code> represents a non-negative integer
                      expressed in hexadecimal: for example <code>0xffff</code> represents the integer 65535, and
                     <code>0xFFFF_FFFF</code> represents the integer 4294967295.</p></li><li><p>A <code>BinaryIntegerLiteral</code> represents a non-negative integer
                     expressed in binary: for example <code>0b101</code> represents the integer 5, and
                     <code>0b1111_1111</code> represents the integer 255.</p></li><li><p>The value of a <b>numeric literal</b> containing no <code>.</code> and 
                     no <code>e</code> or <code>E</code> character is an atomic item of type <code>xs:integer</code>;
                     the value is obtained by casting from <code>xs:string</code> to <code>xs:integer</code> as specified in
                     <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#casting-from-strings">23.2 Casting from xs:string and xs:untypedAtomic</a>.</p></li><li><p>The value of a numeric literal containing <code>.</code> but no <code>e</code> or <code>E</code> 
                     character is an atomic item of type <code>xs:decimal</code>;
                     the value is obtained by casting from <code>xs:string</code> to <code>xs:decimal</code> as specified in
                     <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#casting-from-strings">23.2 Casting from xs:string and xs:untypedAtomic</a>.</p></li><li><p>The value of a numeric literal 
                     containing an <code>e</code> or <code>E</code> character is an atomic item of type 
                     <code>xs:double</code>;
                     the value is obtained by casting from <code>xs:string</code> to <code>xs:double</code> as specified in
                     <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#casting-from-strings">23.2 Casting from xs:string and xs:untypedAtomic</a>.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>The value of a numeric literal is always non-negative. An expression may
                  appear to include a negative number such as <code>-1</code>, but this is technically
                  an arithmetic expression comprising a unary minus operator followed by a numeric literal.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The effect of the above rules is that in the case of an integer or decimal literal, a dynamic error [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFOAR0002" title="err:FOAR0002">err:FOAR0002</a>]<sup><small>FO40</small></sup> will generally be raised if the literal is outside the range of values supported by the implementation (other options are available: see <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#op.numeric">4.2 Arithmetic operators on numeric values</a> for details.)</p><p>The limits of numeric datatypes are specified in <a href="#id-data-model-conformance"><b>6.3 Data Model Conformance</b></a>.</p></div><p>Here are some examples of numeric literals:</p><ul><li><p>
                           <code>12</code> denotes the <code>xs:integer</code> value twelve.</p></li><li><p>
                           <code>1_000_000</code> denotes the <code>xs:integer</code> value one million.</p></li><li><p>
                           <code>12.5</code> denotes the <code>xs:decimal</code> value twelve and one half.</p></li><li><p>
                           <code>3.14159_26535_89793e0</code>
                  is an <code>xs:double</code> value representing the mathematical constant
                  <var>π</var> to 15 decimal places. </p></li><li><p>
                           <code>125E2</code> denotes the <code>xs:double</code> value twelve thousand, five hundred.</p></li><li><p>
                           <code>0xffff</code> denotes the <code>xs:integer</code> value 65535.</p></li><li><p>
                           <code>0b1000_0001</code> denotes the <code>xs:integer</code> value 129.</p></li></ul></div><div class="div4">
<h5><a id="id-string-literal"/>4.2.1.2 <a href="#id-string-literal" style="text-decoration: none">String Literals</a></h5><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-StringLiteral-AposStringLiteral">AposStringLiteral</a>  |  <a href="#doc-xquery40-StringLiteral-QuotStringLiteral">QuotStringLiteral</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringLiteral-AposStringLiteral"/><code><a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a></code></td><td>::=</td><td><code>"'"  (<a href="#doc-xquery40-StringLiteral-PredefinedEntityRef">PredefinedEntityRef</a>  |  <a href="#doc-xquery40-StringLiteral-CharRef">CharRef</a>  |  <a href="#doc-xquery40-StringLiteral-EscapeApos">EscapeApos</a>  |  [^'&amp;])*  "'"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringLiteral-PredefinedEntityRef"/><code><a href="#prod-xquery40-PredefinedEntityRef">PredefinedEntityRef</a></code></td><td>::=</td><td><code>"&amp;"  ("lt"  |  "gt"  |  "amp"  |  "quot"  |  "apos")  ";"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringLiteral-CharRef"/><code><a href="#prod-xquery40-CharRef">CharRef</a></code></td><td>::=</td><td><code>
                           <a href="https://www.w3.org/TR/REC-xml/#NT-CharRef">[http://www.w3.org/TR/REC-xml#NT-CharRef]</a><sup><small>XML</small></sup>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#parse-note-xml-version">xgc: xml-version</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringLiteral-EscapeApos"/><code><a href="#prod-xquery40-EscapeApos">EscapeApos</a></code></td><td>::=</td><td><code>"''"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringLiteral-QuotStringLiteral"/><code><a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a></code></td><td>::=</td><td><code>'"'  (<a href="#doc-xquery40-StringLiteral-PredefinedEntityRef">PredefinedEntityRef</a>  |  <a href="#doc-xquery40-StringLiteral-CharRef">CharRef</a>  |  <a href="#doc-xquery40-StringLiteral-EscapeQuot">EscapeQuot</a>  |  [^"&amp;])*  '"'</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringLiteral-EscapeQuot"/><code><a href="#prod-xquery40-EscapeQuot">EscapeQuot</a></code></td><td>::=</td><td><code>'""'</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody></table><p>The value of a <b>string literal</b> is an atomic item whose type is
               <code>xs:string</code> and whose value is the string denoted by the characters between the
		delimiting apostrophes or quotation marks. If the literal is delimited by apostrophes, two adjacent 
		apostrophes within the literal are interpreted as a single apostrophe. Similarly, if the literal 
		is delimited by quotation marks, two adjacent quotation marks within the literal are interpreted 
		as one quotation mark.</p><p>
                     [<a id="dt-predefined-entity-reference" title="predefined entity reference">Definition</a>: A <b>predefined entity reference</b> is a short sequence of characters, 
                  beginning with an ampersand, that represents a single character that might otherwise 
                  have syntactic significance.] Each predefined entity reference is replaced 
                  by the character it represents when the string literal is processed. The predefined 
                  entity references recognized by XPath and XQuery are as follows:</p><table style="width:60%; border:1px solid" class="medium"><tbody><tr><th style="text-align:center">Entity Reference</th><th style="text-align:center">Character Represented</th></tr><tr><td style="text-align:center">
                                 <code>&amp;lt;</code>
                              </td><td style="text-align:center">
                                 <code>&lt;</code>
                              </td></tr><tr><td style="text-align:center">
                                 <code>&amp;gt;</code>
                              </td><td style="text-align:center">
                                 <code>&gt;</code>
                              </td></tr><tr><td style="text-align:center">
                                 <code>&amp;amp;</code>
                              </td><td style="text-align:center">
                                 <code>&amp;</code>
                              </td></tr><tr><td style="text-align:center">
                                 <code>&amp;quot;</code>
                              </td><td style="text-align:center">
                                 <code>"</code>
                              </td></tr><tr><td style="text-align:center">
                                 <code>&amp;apos;</code>
                              </td><td style="text-align:center">
                                 <code>'</code>
                              </td></tr></tbody></table><p>
                     [<a id="dt-character-reference" title="character reference">Definition</a>: A <b>character reference</b> is an XML-style reference to a <a href="#Unicode">[Unicode]</a> character, identified by its decimal or hexadecimal codepoint.] For example, 
                  the character <span class="unicode-codepoint">U+20AC</span> (<span class="unicode-name">EURO SIGN</span>, <code>€</code>)  
               can be represented by the character reference <code>&amp;#8364;</code> or <code>&amp;#x20ac;</code>. Character references are 
               normatively defined in Section 4.1 of the XML specification (it is <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> whether the rules in <a href="#XML">[XML 1.0]</a> or <a href="#XML1.1">[XML 1.1]</a> apply.) A <a title="static error" class="termref" href="#dt-static-error">static error</a>
                     [<a href="#ERRXQST0090" title="err:XQST0090">err:XQST0090</a>] is raised if a character reference does not identify a valid character in the version of XML that is in use.</p><p>Here are some examples of string literals:</p><ul><li><p>
                           <code>"He said, ""I don't like it."""</code> denotes a string containing two quotation marks and one apostrophe.</p></li><li class="xquery"><p>
                           <code>"Ben &amp;amp; Jerry&amp;apos;s"</code> denotes the <code>xs:string</code> value  <code>"Ben &amp; Jerry's"</code>.</p></li><li class="xquery"><p>
                           <code>"&amp;#8364;99.50"</code> denotes the <code>xs:string</code>  value <code>"€99.50"</code>.</p></li><li><p>In XQuery, the string literal <code>"&amp;lt;"</code> denotes a string of length 1 containing the single character
                     <code>"&lt;"</code>. In XPath, the string literal <code>"&amp;lt;"</code> denotes a string of length 4 containing the four 
                     characters <code>"&amp;"</code>, <code>"l"</code>, <code>"t"</code>, <code>";"</code>. (However, when the XPath
                     expression is embedded in an XML document, the sequence <code>"&amp;lt;"</code> will typically have already been converted
                     to <code>"&lt;"</code> by the XML parser.)</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>When XPath or XQuery expressions are embedded in contexts where quotation
                     marks have special significance, such as inside XML attributes, or in string literals in a host language such
                     as Java or C#, then additional
                     escaping may be needed.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Fixed string values can also be written as string templates: 
                  see <a href="#id-string-templates"><b>4.9.2 String Templates</b></a>. A string template with no enclosed
               expressions, such as <code>`Jamaica`</code> evaluates to the same value as
               the string literals <code>"Jamaica"</code> or <code>'Jamaica'</code>. 
               A string template can contain both single and double quotation marks:
               <code>`He said: "I don't like it"`</code>. However, there there are
               some subtle differences:</p><ul><li><p>In string literals, the treatment of character and entity references
                  such as <code>&amp;amp;</code> varies between XQuery and XPath; in string templates,
                  such references are not expanded in either language.</p></li><li><p>String templates can only be used where an expression is expected. String
                  literals are also used in some non-expression contexts, for example in
                  defining an enumeration type: see <a href="#id-enumeration-types"><b>3.2.6 Enumeration Types</b></a>.</p></li><li><p>Curly brackets (<span class="unicode-codepoint">U+007B</span> (<span class="unicode-name">LEFT CURLY BRACKET</span>, <code>{</code>)  and <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>) ) and backticks 
                  (<span class="unicode-codepoint">U+0060</span> (<span class="unicode-name">GRAVE ACCENT, BACKTICK</span>, <code>`</code>) ) have a reserved meaning in string templates.</p></li></ul></div></div><div class="div4">
<h5><a id="id-qname-literals"/>4.2.1.3 <a href="#id-qname-literals" style="text-decoration: none">QName Literals</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-filter-expression">⬇</a> <a href="#id-numeric-literals">⬆</a></p><ol><li><p>QName literals are new in 4.0.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1661">1661</a> ]</i></p></li></ol></div><p>A QName literal represents a value of type <code>xs:QName</code>.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-QNameLiteral"/><code><a href="#prod-xquery40-QNameLiteral">QNameLiteral</a></code></td><td>::=</td><td><code>"#"  <a href="#doc-xquery40-QNameLiteral-EQName">EQName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-QNameLiteral-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                        </code></td></tr></tbody></table><p>For example, the expression <code>node-name($node) = #xml:space</code>
               returns true if the name of the node <code>$node</code> is the QName with local part <code>space</code>
                  and namespace URI <code>http://www.w3.org/XML/1998/namespace</code>.</p><p>If the <code>EQName</code> is an unprefixed <code>NCName</code>, then it is expanded using
                  the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>. If there
                  is no binding for the prefix in the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a> then
                  a static error is raised [<a href="#ERRXPST0081" title="err:XPST0081">err:XPST0081</a>].
               </p><div class="note"><p class="prefix"><b>Note:</b></p><p>No whitespace or comment is permitted between the <code>#</code> character
                  and the <code>EQName</code>.</p><p>In XQuery, the character pair <code>(#</code> is recognized as the start of
                     a pragma. In order to ensure that an expression such as <code>error(#err:XPTY0004)</code>
                     is correctly parsed, the rules for pragmas have changed to require whitespace
                     after the opening <code>(#</code> and before the <code>EQName</code>.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>A <code>QNameLiteral</code> is an expression that evaluates to a single
                  item of type <code>xs:QName</code>; it is thus an alternative to calling the
                  <code>xs:QName</code> constructor function with a literal string argument.
                  This should not be confused with QNames that are used directly in XQuery 4.0 to refer to constructs such as
               functions, variables, and elements.</p><p>A <code>QName</code> appearing on its own as an expression,
               for example <code>my:invoice</code>, is an abbreviation for the axis step <code>child::my:step</code>,
               which selects a child element of the context node having this particular element name. A different
               construct is therefore needed to represent an atomic value of type <code>xs:QName</code>.
               For example, the function <code>fn:error</code> expects an <code>xs:QName</code> value
               as its first argument, so (provided that the prefix <code>err</code> is defined in the static
               context) it is possible to use a call such as <code>error( #err:XPTY0004 )</code> to raise an
               error with this error code.</p></div></div><div class="div4">
<h5><a id="id-constants-other-types"/>4.2.1.4 <a href="#id-constants-other-types" style="text-decoration: none">Constants of Other Types</a></h5><p>
               
      The <code>xs:boolean</code> values <code>true</code> and <code>false</code> can be constructed by calls to the
      <a title="system function" class="termref" href="#dt-system-function">system functions</a>
                     <code>fn:true()</code> and <code>fn:false()</code>, respectively.
    </p><p>Values of other simple types can be constructed by calling the <a title="constructor function" class="termref" href="#dt-constructor-function">constructor function</a> for the given type. The constructor functions for XML Schema
		built-in types are defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#constructor-functions-for-xsd-types">22.1 Constructor functions for XML Schema built-in atomic types</a>. In general, the name of a constructor function for a given type is the same as the name of the type (including its namespace). For
		example:</p><ul><li><p>
                           <code>xs:integer("12")</code> returns the integer value twelve.</p></li><li><p>
                           <code>xs:date("2001-08-25")</code> returns an item whose type is <code>xs:date</code> and whose value represents the date 25th August 2001.</p></li><li><p>
                           <code>xs:dayTimeDuration("PT5H")</code> returns an item whose type is <code>xs:dayTimeDuration</code> and whose value represents a duration of five hours.</p></li></ul><p>Constructor functions can also be used to create special values that have no literal representation, as in the following examples:
</p><ul><li><p>
                              <code>xs:float("NaN")</code> returns the special floating-point value, "Not a Number."</p></li><li><p>
                              <code>xs:double("INF")</code> returns the special double-precision value, "positive infinity."</p></li></ul><p>Constructor functions are available for all simple types,
including union types. For example, if <code>my:dt</code> is a user-defined union
type whose member types are <code>xs:date</code>, <code>xs:time</code>, and <code>xs:dateTime</code>, then
the expression <code>my:dt("2011-01-10")</code> creates an atomic item of type
<code>xs:date</code>. The rules follow XML Schema validation rules for union types:
the effect is to choose the first member type that accepts the given
string in its lexical space.</p><p>It is also possible to construct values of various types by using a <code>cast</code> expression. For example:</p><ul><li><p>
                           <code>9 cast as
                        hatsize</code> returns the atomic item <code>9</code>
			 whose type is  <code>hatsize</code>.</p></li></ul></div></div><div class="div3">
<h4><a id="id-variables"/>4.2.2 <a href="#id-variables" style="text-decoration: none">Variable References</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VarRef"/><code><a href="#prod-xquery40-VarRef">VarRef</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-VarRef-EQName">EQName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VarRef-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody></table><p>
                  [<a id="dt-variable-reference" title="variable reference">Definition</a>: A <b>variable reference</b> is an EQName preceded by a $-sign.]
                The variable name is expanded using the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.
                Two variable references are equivalent if their  <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a>  are equal (as defined by the <code>eq</code> operator). The scope of a variable binding is defined separately for each kind of
expression that can bind variables.</p><p>Every variable reference must match a name in the <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a>. </p><p>Every variable binding has a static scope. The scope defines where
references to the variable can validly occur.

It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
                  [<a href="#ERRXPST0008" title="err:XPST0008">err:XPST0008</a>] to reference a variable that is not in scope. If a variable is bound in the <a title="static context" class="termref" href="#dt-static-context">static context</a> for an expression, that variable is in scope for the entire expression except where it is occluded by another binding that uses the same name within that scope.</p><p>A reference to a variable that was declared <code>external</code>, but was not bound to a value by the external environment, raises a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>
                  [<a href="#ERRXPDY0002" title="err:XPDY0002">err:XPDY0002</a>].</p><p>
At evaluation time, the value of a variable reference is the value to which the relevant variable is bound.</p></div><div class="div3">
<h4><a id="id-context-value-references"/>4.2.3 <a href="#id-context-value-references" style="text-decoration: none">Context Value References</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ContextValueRef"/><code><a href="#prod-xquery40-ContextValueRef">ContextValueRef</a></code></td><td>::=</td><td><code>"."</code></td></tr></tbody></table><p>A <b>context value reference</b> evaluates to
              the <a title="context value" class="termref" href="#dt-context-value">context value</a>.</p><p>In many syntactic contexts, the context value will be a single item.
               For example this applies on the right-hand side of the <code>/</code> 
               or <code>!</code> operators, or within a <a href="#doc-xquery40-Predicate">Predicate</a>.</p><p>If the <a title="context value" class="termref" href="#dt-context-value">context value</a> is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>, a context value reference raises a <a title="type error" class="termref" href="#dt-type-error">type error</a>
                  [<a href="#ERRXPDY0002" title="err:XPDY0002">err:XPDY0002</a>].</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Being absent is not the same thing as being empty.</p></div></div><div class="div3">
<h4><a id="id-paren-expressions"/>4.2.4 <a href="#id-paren-expressions" style="text-decoration: none">Parenthesized Expressions</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ParenthesizedExpr"/><code><a href="#prod-xquery40-ParenthesizedExpr">ParenthesizedExpr</a></code></td><td>::=</td><td><code>"("  <a href="#doc-xquery40-ParenthesizedExpr-Expr">Expr</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ParenthesizedExpr-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody></table><p>Parentheses may be used to override the precedence rules.
        For example, the expression <code>(2 + 4)
		    * 5</code> evaluates to thirty, since the parenthesized expression <code>(2 + 4)</code> is evaluated first and its result is multiplied by five. Without
			 parentheses, the expression <code>2 + 4 * 5</code> evaluates to twenty-two, because the multiplication operator has higher
			 precedence than the addition operator.</p><p>Empty parentheses are used to denote an empty sequence, as
		described in <a href="#construct_seq"><b>4.7.1 Sequence Concatenation</b></a>.</p></div><div class="div3">
<h4><a id="id-enclosed-expr"/>4.2.5 <a href="#id-enclosed-expr" style="text-decoration: none">Enclosed Expressions</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-EnclosedExpr-Expr">Expr</a>?  "}"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-EnclosedExpr-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody></table><p>
                  [<a id="dt-enclosed-expression" title="enclosed expression">Definition</a>: An <b>enclosed expression</b> is an instance of the <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a> production, which allows an optional expression within curly brackets.]
                  [<a id="dt-content-expression" title="content expression">Definition</a>: In an  <a title="enclosed expression" class="termref" href="#dt-enclosed-expression">enclosed expression</a>, the optional expression enclosed in curly brackets is called the <b>content expression</b>.] If the <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> is not provided explicitly,  the content expression is <code>()</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Despite the name, an enclosed expression is not actually an expression
                  in its own right; rather it is a construct that is used in the grammar of many other expressions.</p></div></div></div><div class="div2">
<h3><a id="id-postfix-expression"/>4.3 <a href="#id-postfix-expression" style="text-decoration: none">Postfix Expressions</a></h3>
<a id="d2e18264"/><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PostfixExpr"/><code><a href="#prod-xquery40-PostfixExpr">PostfixExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PostfixExpr-PrimaryExpr">PrimaryExpr</a>  |  <a href="#doc-xquery40-PostfixExpr-FilterExpr">FilterExpr</a>  |  <a href="#doc-xquery40-PostfixExpr-DynamicFunctionCall">DynamicFunctionCall</a>  |  <a href="#doc-xquery40-PostfixExpr-LookupExpr">LookupExpr</a>  |  <a href="#doc-xquery40-PostfixExpr-MethodCall">MethodCall</a>  |  <a href="#doc-xquery40-PostfixExpr-FilterExprAM">FilterExprAM</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PostfixExpr-PrimaryExpr"/><code><a href="#prod-xquery40-PrimaryExpr">PrimaryExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-Literal">Literal</a>
                     <br/>|  <a href="#doc-xquery40-VarRef">VarRef</a>
                     <br/>|  <a href="#doc-xquery40-ParenthesizedExpr">ParenthesizedExpr</a>
                     <br/>|  <a href="#doc-xquery40-ContextValueRef">ContextValueRef</a>
                     <br/>|  <a href="#doc-xquery40-FunctionCall">FunctionCall</a>
                     <br/>|  <a href="#doc-xquery40-OrderedExpr">OrderedExpr</a>
                     <br/>|  <a href="#prod-xquery40-UnorderedExpr">UnorderedExpr</a>
                     <br/>|  <a href="#doc-xquery40-NodeConstructor">NodeConstructor</a>
                     <br/>|  <a href="#prod-xquery40-FunctionItemExpr">FunctionItemExpr</a>
                     <br/>|  <a href="#doc-xquery40-MapConstructor">MapConstructor</a>
                     <br/>|  <a href="#doc-xquery40-ArrayConstructor">ArrayConstructor</a>
                     <br/>|  <a href="#doc-xquery40-StringTemplate">StringTemplate</a>
                     <br/>|  <a href="#doc-xquery40-StringConstructor">StringConstructor</a>
                     <br/>|  <a href="#doc-xquery40-UnaryLookup">UnaryLookup</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PostfixExpr-FilterExpr"/><code><a href="#prod-xquery40-FilterExpr">FilterExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PostfixExpr">PostfixExpr</a>
                     <a href="#doc-xquery40-Predicate">Predicate</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PostfixExpr-DynamicFunctionCall"/><code><a href="#prod-xquery40-DynamicFunctionCall">DynamicFunctionCall</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PostfixExpr">PostfixExpr</a>
                     <a href="#prod-xquery40-PositionalArgumentList">PositionalArgumentList</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PostfixExpr-LookupExpr"/><code><a href="#prod-xquery40-LookupExpr">LookupExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PostfixExpr">PostfixExpr</a>
                     <a href="#prod-xquery40-Lookup">Lookup</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PostfixExpr-MethodCall"/><code><a href="#prod-xquery40-MethodCall">MethodCall</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PostfixExpr">PostfixExpr</a>  "=?&gt;"  <a href="#prod-xquery40-NCName">NCName</a>
                     <a href="#prod-xquery40-PositionalArgumentList">PositionalArgumentList</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PostfixExpr-FilterExprAM"/><code><a href="#prod-xquery40-FilterExprAM">FilterExprAM</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PostfixExpr">PostfixExpr</a>  "?["  <a href="#doc-xquery40-Expr">Expr</a>  "]"</code></td></tr></tbody></table><p>A postfix expression takes one of the following forms:</p><ul><li><p>
                     [<a id="dt-filter-expression" title="filter expression">Definition</a>: 
               A <b>filter expression</b> is an
               instance of the construct <a href="#doc-xquery40-FilterExpr">FilterExpr</a>:
               that is, it is an expression in the form <code>
                           <var>E<sub>1</sub></var>[<var>E<sub>2</sub></var>]</code>. 
               Its effect is to return those items from the value of <var>E<sub>1</sub></var> that
               satisfy the predicate in <var>E<sub>2</sub></var>.]
                  </p><p>Filter expressions are described in <a href="#id-filter-expression"><b>4.4 Filter Expressions</b></a>.</p><p>An example of a filter expression is <code>(1 to 100)[. mod 2 = 0]</code>
            which returns all even numbers in the range 1 to 100.</p><p>The base expression <var>E<sub>1</sub></var> can itself be a postfix expression,
            so multiple predicates are allowed, in the form <code>
                        <var>E<sub>1</sub></var>[<var>E<sub>2</sub></var>][<var>E<sub>3</sub></var>][<var>E<sub>4</sub></var>]</code>.</p></li><li><p>
                     [<a id="dt-dynamic-function-call" title="dynamic function call">Definition</a>: 
               is 
            ]A <a title="dynamic function call" class="termref" href="#dt-dynamic-function-call">dynamic function call</a>
               is an instance of the construct <a href="#doc-xquery40-DynamicFunctionCall">DynamicFunctionCall</a>:
               that is, it is an expression in the form <code>
                        <var>E<sub>1</sub></var>(<var>E<sub>2</sub></var>, <var>E<sub>3</sub></var>, ...)</code>
               in which <var>E<sub>1</sub></var> identifies a <a title="function item" class="termref" href="#dt-function-item">function item</a>
               to be called, and the parenthesized argument list
                <code>(<var>E<sub>2</sub></var>, <var>E<sub>3</sub></var>, ...)</code>) identifies the arguments supplied to the function. Its
               effect is to evaluate <var>E<sub>1</sub></var> to obtain a function,
               and then call that function, with the values of expressions
               <var>E<sub>2</sub></var>, <var>E<sub>3</sub></var>, <code>...</code> as
               arguments. Dynamic function calls are described in <a href="#id-dynamic-function-invocation"><b>4.5.3 Dynamic Function Calls</b></a>.</p><p>An example of a dynamic function call is <code>$f("a", 2)</code> where
            the value of variable <code>$f</code> must be a function item.</p></li><li><p>
                     [<a id="dt-lookup-expression" title="lookup expression">Definition</a>: 
               A <b>lookup expression</b> is an instance of the production
                  <a href="#doc-xquery40-LookupExpr">LookupExpr</a>: that is, an expression in the form
                  <code>
                           <var>E<sub>1</sub></var>?<var>KS</var>
                        </code>, where <var>E<sub>1</sub></var> is an expression returning a sequence
            of maps or arrays, and <var>KS</var> is a key specifier, which indicates which
            entries in a map, or members in an array, should be selected.]
                  </p><p>Lookup expressions are described in <a href="#id-postfix-lookup"><b>4.14.3.1 Postfix Lookup Expressions</b></a>.</p><p>An example of a lookup expression is <code>$emp?name</code>, where
            the value of variable <code>$emp</code> is a map, and the string <code>"name"</code>
            is the key of one of the entries in the map.</p></li><li><p>
                     [<a id="dt-filter-expression-ma" title="filter expression for maps and arrays">Definition</a>: 
               A <b>filter expression for maps and arrays</b> is an
               instance of the construct <a href="#doc-xquery40-FilterExprAM">FilterExprAM</a>:
               that is, it is an expression in the form <code>
                           <var>E<sub>1</sub></var>?[<var>E<sub>2</sub></var>]</code>. 
               Its effect is to evaluate <var>E<sub>1</sub></var> to return an array or map, and to select
               members of the array, or entries from the map, that satisfy the predicate in <var>E<sub>2</sub></var>.]
                  </p><p>Filter expressions for maps and array are described in <a href="#id-filter-maps-and-arrays"><b>4.14.5 Filter Expressions for Maps and Arrays</b></a>.</p></li></ul><p>Postfix expressions are evaluated from left-to-right. For example, the 
         expression <code>$E1[E2]?(E3)(E4)</code> is evaluated by first evaluating
            the filter expression <code>$E1[E2]</code> to produce a sequence of maps and arrays 
            (say <code>$S</code>), then evaluating the lookup expression <code>$S?(E3)</code>
            to produce a function item (say <code>$F</code>), then evaluating the dynamic
            function call <code>$F(E4)</code> to produce the final result.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>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:</p><div class="exampleInner"><pre>PostfixExpr := PrimaryExpr (Predicate | PositionalArgumentList | Lookup)*</pre></div><p>(as used in XPath 3.1) is probably more convenient.</p></div></div><div class="div2">
<h3><a id="id-filter-expression"/>4.4 <a href="#id-filter-expression" style="text-decoration: none">Filter Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-function-calls">⬇</a> <a href="#id-qname-literals">⬆</a></p><ol><li><p>
                  The value of a predicate in a filter expression can now be a sequence of integers.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/816">816</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/996">996</a> 6 February 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FilterExpr"/><code><a href="#prod-xquery40-FilterExpr">FilterExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FilterExpr-PostfixExpr">PostfixExpr</a>
                     <a href="#doc-xquery40-FilterExpr-Predicate">Predicate</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FilterExpr-PostfixExpr"/><code><a href="#prod-xquery40-PostfixExpr">PostfixExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PrimaryExpr">PrimaryExpr</a>  |  <a href="#doc-xquery40-FilterExpr">FilterExpr</a>  |  <a href="#doc-xquery40-DynamicFunctionCall">DynamicFunctionCall</a>  |  <a href="#doc-xquery40-LookupExpr">LookupExpr</a>  |  <a href="#doc-xquery40-MethodCall">MethodCall</a>  |  <a href="#doc-xquery40-FilterExprAM">FilterExprAM</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FilterExpr-Predicate"/><code><a href="#prod-xquery40-Predicate">Predicate</a></code></td><td>::=</td><td><code>"["  <a href="#doc-xquery40-Expr">Expr</a>  "]"</code></td></tr></tbody></table><p>A <a title="filter expression" class="termref" href="#dt-filter-expression">filter expression</a> 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.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Where the expression before the square brackets is an
                  <a href="#doc-xquery40-AbbreviatedStep">AbbreviatedStep</a> or <a href="#prod-xquery40-FullStep">FullStep</a>, the expression is technically not a
                  filter expression but an <a href="#doc-xquery40-AxisStep">AxisStep</a>. There are minor differences
                  in the semantics: see <a href="#id-predicate"><b>4.6.5 Predicates within Steps</b></a>
               </p></div><p>Here are some examples of filter expressions:</p><ul><li><p>Given a sequence of products in a variable, return only those products whose price is greater than 100.</p><div class="exampleInner"><pre>$products[price gt 100]</pre></div></li><li><p>List all the integers from 1 to 100 that are divisible by 5. (See <a href="#construct_seq"><b>4.7.1 Sequence Concatenation</b></a> for an explanation of the <code>to</code> operator.)</p><div class="exampleInner"><pre>(1 to 100)[. mod 5 eq 0]</pre></div></li><li><p>The result of the following expression is the integer 25:</p><div class="exampleInner"><pre>(21 to 29)[5]</pre></div></li><li><p>The following example returns the fifth through ninth items in the sequence bound to variable <code>$orders</code>.</p><div class="exampleInner"><pre>$orders[5 to 9]</pre></div></li><li><p>The following example illustrates the use of a filter expression as a <a title="step" class="termref" href="#dt-step">step</a> in a <a title="path expression" class="termref" href="#dt-path-expression">path expression</a>. It returns the last chapter or appendix within the book bound to variable <code>$book</code>:</p><div class="exampleInner"><pre>$book/(chapter | appendix)[last()]</pre></div></li></ul><p>For each item in the input sequence, the predicate expression
               is evaluated using an <b>inner focus</b>, 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. </p><p>For each item in the input sequence, the result of the
               predicate expression is coerced to an <code>xs:boolean</code>
               value, called the <a title="predicate truth value" class="termref" href="#dt-predicate-truth-value">predicate truth value</a>, as
               described below. Those items for which the predicate truth value
               is <code>true</code> are retained, and those for which the
               predicate truth value is <code>false</code> are discarded.</p><p>
               [<a id="dt-predicate-truth-value" title="predicate truth value">Definition</a>: The
            <b>predicate truth value</b> of a value <code>$V</code>
            is the result of the expression <code>if ($V instance of xs:numeric+)
            then ($V = position()) else fn:boolean($V)</code>.]
            </p><p>Expanding this definition, the predicate truth value can be obtained 
               by applying the following rules, in order:</p><ol class="enumar"><li><p>If the value <var>V</var> of the predicate expression 
                     is a sequence whose first item is an instance of the type <code>xs:numeric</code>,
                     then:</p><ol class="enumla"><li><p>
                           <var>V</var> must be an instance of the type
                        <code>xs:numeric+</code> (that is, every item in <var>V</var>
                           must be numeric). A type error [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFORG0006" title="err:FORG0006">err:FORG0006</a>]<sup><small>FO40</small></sup> is
                        raised if this is not the case.</p></li><li><p>The predicate truth value is <code>true</code> if 
                           <var>V</var> is equal (by the
                           <code>=</code> operator) to the <b>context
                              position</b>, and is <code>false</code>
                           otherwise.</p></li></ol><p>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 <code>[3 to 5]</code>
                  is true for the third, fourth, and fifth items in the input sequence.</p><p>
                     [<a id="dt-numeric-predicate" title="numeric predicate">Definition</a>: A predicate whose predicate
                     expression returns a value of type <code>xs:numeric+</code> is called a <b>numeric
                        predicate</b>.]
                  </p><div class="note"><p class="prefix"><b>Note:</b></p><p>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 <code>[xs:integer(@seq)]</code>
                  selects those items in the input sequence whose <code>@seq</code> attribute
                  is numerically equal to their position in the input sequence.</p><p>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 <code>[@special otherwise last()]</code>
                  is true for an item that either has an <code>@special</code> attribute,
                     or is the last item in the input sequence.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The truth value of a numeric predicate does not depend on the order
                  of the numbers in <var>V</var>. The predicates <code>[ 1, 2, 3 ]</code>
                  and <code>[ 3, 2, 1 ]</code> have exactly the same effect. The items in 
                  the result of a filter expression always retain the ordering of the input
                  sequence.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The truth value of a numeric predicate whose value is non-integral
                  or non-positive is always false.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Beware that using boolean operators (<code>and</code>, <code>or</code>,
                  <code>not()</code>) with numeric values may not have the intended effect.
                  For example the predicate <code>[1 or last()]</code> selects every item
                  in the sequence, because <code>or</code> operates on the <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a>
                  of its operands. The required effect can be achieved with the predicate
                  <code>[1, last()]</code>.</p></div></li><li><p>Otherwise, the predicate truth value is the <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> of the
                     predicate expression.</p></li></ol></div><div class="div2">
<h3><a id="id-functions"/>4.5 <a href="#id-functions" style="text-decoration: none">Functions</a></h3><p>Functions in XQuery 4.0 arise in two ways:</p><ul><li><p>A <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> 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 <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a>), 
               but there may be further function definitions
               that are known only dynamically (appearing in the <a title="dynamically known function definitions" class="termref" href="#dt-dynamically-known-function-definitions">dynamically known function definitions</a>).</p></li><li><p>
                     <a title="function item" class="termref" href="#dt-function-item">Function items</a> are XDM items that can be called
               using a <a title="dynamic function call" class="termref" href="#dt-dynamic-function-call">dynamic function call</a>. 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.</p></li></ul><p>The functions defined by a statically known <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> can be invoked using a
            <a title="static function call" class="termref" href="#dt-static-function-call">static function call</a>. <a title="function item" class="termref" href="#dt-function-item">Function items</a> corresponding
            to these definitions can also be obtained, as dynamic values, by evaluating a <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a>. 
            <a title="function item" class="termref" href="#dt-function-item">Function items</a> can also be obtained using the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-function-lookup"><code>fn:function-lookup</code></a>
            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 <a title="static context" class="termref" href="#dt-static-context">static context</a>, so long as it is in the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a>.</p><p>Static and dynamic function calls are described in the following sections.</p><div class="div3">
<h4><a id="id-static-functions"/>4.5.1 <a href="#id-static-functions" style="text-decoration: none">Static Function Calls</a></h4><p>The <a title="static context" class="termref" href="#dt-static-context">static context</a> for an expression includes a set 
                  of <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a>. Every <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
               in the static context has a name (which is an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>) and 
                  an <a title="arity range" class="termref" href="#dt-arity-range">arity range</a>, which is a range of permitted arities for
               calls on that function. Two <a title="function definition" class="termref" href="#dt-function-definition">function definitions</a> 
                  having the same name must not have overlapping arity ranges.
               This means that for a given static function call, it is possible to identify the target function definition
               in the static context unambiguously from knowledge of the function name and the number of supplied arguments.</p><p>A <a title="static function call" class="termref" href="#dt-static-function-call">static function call</a> is bound to a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> 
                  in the static context by matching the name
               and arity. If the function call has <var>P</var> positional arguments followed by
                  <var>K</var> keyword arguments, then the required arity is <var>P+K</var>, and the static context 
                  must include a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> whose name matches the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> 
                  in the function call, and whose <a title="arity range" class="termref" href="#dt-arity-range">arity range</a> 
               includes this required arity. This is the function chosen to be called.
               The result of the function is obtained by evaluating the expression that forms its implementation, with
               a dynamic context that provides values for all the declared parameters, initialized
               as described in <a href="#id-eval-static-function-call"><b>4.5.1.2 Evaluating Static Function Calls</b></a> below.</p><p>Similarly, a <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a> of the form <code>f#N</code> binds to a 
                  <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> in the
                  static context whose name matches <var>f</var> where <code>MinP ≤ N and MaxP ≥ N</code>.
               The result of evaluating a function reference is a <a title="function item" class="termref" href="#dt-function-item">function item</a> which can be called
               using a dynamic function call. Function items are never variadic and their arguments
               are always supplied positionally. For example, the function reference <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-concat"><code>fn:concat#3</code></a>
               returns a function item with arity 3, which is always called by supplying three positional
               arguments, and whose effect is the same as a static call on <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-concat"><code>fn:concat</code></a> with
               three positional arguments. </p><p>The detailed rules for evaluating static function calls and function references are defined
               in subsequent sections.</p><div class="div4">
<h5><a id="id-function-calls"/>4.5.1.1 <a href="#id-function-calls" style="text-decoration: none">Static Function Call Syntax</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-eval-dynamic-function-call">⬇</a> <a href="#id-filter-expression">⬆</a></p><ol><li><p>
                  Keyword arguments are allowed on static function calls, as well as positional arguments.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/155">155</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/159">159</a> 30 September 2020]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionCall"/><code><a href="#prod-xquery40-FunctionCall">FunctionCall</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-FunctionCall-EQName">EQName</a>
                           <a href="#doc-xquery40-FunctionCall-ArgumentList">ArgumentList</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                         */</td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#parse-note-parens">gn: parens</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionCall-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionCall-ArgumentList"/><code><a href="#prod-xquery40-ArgumentList">ArgumentList</a></code></td><td>::=</td><td><code>"("  ((<a href="#doc-xquery40-FunctionCall-PositionalArguments">PositionalArguments</a>  (","  <a href="#doc-xquery40-FunctionCall-KeywordArguments">KeywordArguments</a>)?)  |  <a href="#doc-xquery40-FunctionCall-KeywordArguments">KeywordArguments</a>)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionCall-PositionalArguments"/><code><a href="#prod-xquery40-PositionalArguments">PositionalArguments</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-FunctionCall-Argument">Argument</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionCall-Argument"/><code><a href="#prod-xquery40-Argument">Argument</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-FunctionCall-ExprSingle">ExprSingle</a>  |  <a href="#doc-xquery40-FunctionCall-ArgumentPlaceholder">ArgumentPlaceholder</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionCall-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                           <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                           <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                           <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                           <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                           <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                           <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionCall-ArgumentPlaceholder"/><code><a href="#prod-xquery40-ArgumentPlaceholder">ArgumentPlaceholder</a></code></td><td>::=</td><td><code>"?"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionCall-KeywordArguments"/><code><a href="#prod-xquery40-KeywordArguments">KeywordArguments</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-FunctionCall-KeywordArgument">KeywordArgument</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionCall-KeywordArgument"/><code><a href="#prod-xquery40-KeywordArgument">KeywordArgument</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-FunctionCall-EQName">EQName</a>  ":="  <a href="#doc-xquery40-FunctionCall-Argument">Argument</a>
                        </code></td></tr></tbody></table><p>
                     [<a id="dt-static-function-call" title="static function call">Definition</a>: A <b>static function call</b>
               is an instance of the production <a href="#doc-xquery40-FunctionCall">FunctionCall</a>: it
               consists of an EQName followed by a parenthesized list of zero or more arguments.].</p><p>The EQName is expanded using the <a title="default function namespace rule" class="termref" href="#dt-default-function-namespace-rule">default function namespace rule</a>.</p><p>The argument list consists of zero or more positional arguments,
               followed by zero or more keyword arguments.</p><p>
                     [<a id="dt-arg-expr" title="argument expression">Definition</a>: An argument to a function call is either an
               <b>argument expression</b> or an <a href="#prod-xquery40-ArgumentPlaceholder">ArgumentPlaceholder</a> 
               (<code>?</code>); in both cases it may
            either be supplied positionally, or identified by a name (called a keyword).]
                  </p><p>This section is concerned with static function calls in which none of the arguments are
               <a href="#prod-xquery40-ArgumentPlaceholder">ArgumentPlaceholders</a>. 
               Calls using one or more <a href="#prod-xquery40-ArgumentPlaceholder">ArgumentPlaceholders</a> are covered in the 
               section <a href="#id-partial-function-application"><b>4.5.4 Partial Function Application</b></a>.</p><p>The <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> used as the function name and the number of arguments used in the static function call 
               (the required arity) must match the name and arity range of a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> 
               in the <a title="static context" class="termref" href="#dt-static-context">static context</a>
                     <span> using the rules defined in the previous section</span>; if there is no match, a
               <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXPST0017" title="err:XPST0017">err:XPST0017</a>].
               </p><p>Evaluation of static function calls is described in <a href="#id-eval-static-function-call"><b>4.5.1.2 Evaluating Static Function Calls</b></a>
                     .</p><p>Since the arguments of a function call are separated by commas, any <a title="argument expression" class="termref" href="#dt-arg-expr">argument expression</a> that contains a top-level <a title="comma operator" class="termref" href="#dt-comma-operator">comma operator</a> must be
               enclosed in parentheses. Here are some illustrative examples of
               static function calls:</p><ul><li><p>
                           <code>my:three-argument-function(1, 2, 3)</code> denotes a static function call with three 
                     <span>positional</span> arguments. <span>The 
                  corresponding function declaration must define at least three parameters, and may define
                  more, provided they are optional.</span>
                        </p></li><li><p>
                           <code>my:two-argument-function((1, 2), 3)</code> denotes a static function call with two arguments, the first of which is a
                     sequence of two values. <span>The 
                        corresponding function declaration must define at least two parameters, and may define
                        more, provided they are optional.</span>
                        </p></li><li><p>
                           <code>my:two-argument-function(1, ())</code> denotes a static function call with two arguments, 
                     the second of which is an empty sequence.</p></li><li><p>
                           <code>my:one-argument-function((1, 2,
                        3))</code> denotes a static function call with one argument that is a sequence of three
                     values. </p></li><li><p>
                           <code>my:one-argument-function(( ))</code> denotes a static function call with one argument that is an empty sequence.</p></li><li><p>
                           <code>my:zero-argument-function( )</code> denotes a static function call with zero arguments.</p></li><li><p>
                           <code>lang(node := $n, language := 'de')</code> is a static function 
                     call with two keyword arguments. The corresponding function declaration defines two parameters,
                     a required parameter <code>language</code> and an optional parameter <code>node</code>.
                     This call supplies values for both parameters. It is equivalent to the call 
                     <code>fn:lang('de', $n)</code>. Note that the keyword arguments are in a different
                     order from the parameter declarations.
                  </p></li><li><p>
                           <code>sort(//employee, key := fn($e) { xs:decimal($e/salary) })</code> is a static function 
                     call with one positional argument and one keyword argument. 
                     The corresponding function declaration defines three parameters,
                     a required parameter <code>$input</code>, an optional parameter <code>$collation</code>,
                     and an optional parameter <code>$key</code>
                     This call supplies values for the first and third parameters, leaving the second parameter (<code>$collation</code>)
                     to take its default value. The default value of the <code>$collation</code> parameter
                     is given as <code>fn:default-collation()</code>, so the value supplied to the function is the
                     default collation from the dynamic context of the caller. It is equivalent to the call 
                     <code>fn:sort(//employee, fn:default-collation(), fn($e) { xs:decimal($e/salary) })</code>.
                  </p></li></ul><p>An <code>EQName</code> in a <code>KeywordArgument</code> is expanded 
               using the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.
            The keywords used in a function call (after expansion) must be distinct 
               [<a href="#ERRXPST0017" title="err:XPST0017">err:XPST0017</a>]; [<a href="#ERRXPST0017" title="err:XPST0017">err:XPST0017</a>].</p></div><div class="div4">
<h5><a id="id-eval-static-function-call"/>4.5.1.2 <a href="#id-eval-static-function-call" style="text-decoration: none">Evaluating Static Function Calls</a></h5><p>This section applies to static function calls where none of the
            arguments is an <code>ArgumentPlaceholder</code>. For function calls involving
            placeholders, see <a href="#id-partial-function-application"><b>4.5.4 Partial Function Application</b></a>.</p><p>
                      When a static function call <var>FC</var> is evaluated
                      with respect to a static context <var>SC</var> and
                      a dynamic context <var>DC</var>,
                      the result is obtained as follows:
                    </p><ol class="enumar"><li><p>
                          The <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
                           <var>FD</var> to be used is found in 
                        the <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a> of <var>SC</var>.
                        </p><p>The <b>required arity</b> is the total number of arguments in the
                        function call, including both positional and keyword arguments.</p><p>
                              There can be at most one <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
                           <var>FD</var> in the 
                              <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a> component of <var>SC</var> whose function name
                              matches the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> in <var>FC</var> and whose <a title="arity range" class="termref" href="#dt-arity-range">arity range</a>
                              includes the arity of <var>FC</var>’s <code>ArgumentList</code>.
                           </p><p>If there is no such <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>, a static error [<a href="#ERRXPST0017" title="err:XPST0017">err:XPST0017</a>] is raised.</p></li><li><p>Each parameter in the <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
                           <var>FD</var> is matched to an argument
                     expression as follows:</p><ol class="enumla"><li><p>If there are <var>N</var> positional arguments in the function call <var>FC</var>,
                           then
                           the corresponding argument expressions are matched pairwise to the first <var>N</var>
                           parameters in the declaration. For this purpose the required parameters and optional parameters
                           in <var>FD</var> are concatenated into a single list, in order.</p></li><li><p>Any keyword arguments in <var>FC</var> are then matched to
                           parameters (whether required or optional) in <var>FD</var> by comparing the keyword
                           used in <var>FC</var> with the paramater name declared in <var>FD</var>.
                           Each keyword must match the name of a declared parameter [<a href="#ERRXPST0017" title="err:XPST0017">err:XPST0017</a>], 
                           and this must be one that has not already
                           been matched to a positional argument. [<a href="#ERRXPST0017" title="err:XPST0017">err:XPST0017</a>].</p></li><li><p>If any required parameter has not been matched to any argument in <var>FC</var>
                           by applying the above rules, a static error is reported [<a href="#ERRXPST0017" title="err:XPST0017">err:XPST0017</a>]
                              </p></li><li><p>If any optional parameter has not been matched to any argument in <var>FC</var>
                           by applying the above rules, then the parameter is matched to the 
                           default value expression for that parameter in <var>FD</var>.</p></li></ol></li><li><p>
                          Each argument expression established by the above rules is evaluated with respect to DC.
                          The order of argument evaluation is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation   dependent</a> and it is not
                        required that an argument be evaluated if the function body can be evaluated without evaluating
                        that argument.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>All argument expressions, including default value expressions, are evaluated in the dynamic
                     context of the function call. It is therefore possible to use a default value expression such as 
                     <code>.</code>, or <code>/</code>, or <code>fn:current-dateTime()</code>, whose value depends on the
                     dynamic context of the function call.</p></div><p>If the expression used for the default value of a parameter has no dependencies on the dynamic
                     context, then an implementation <span class="verb">may</span> choose to reuse the same value on repeated
                     function calls rather than re-evaluating it on each function call.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>This is relevant, for example, if the expression constructs new nodes.</p></div></li><li><p>The result of evaluating the argument expression is converted to the required type (the
                     declared type associated with the corresponding parameter in the function declaration, defaulting
                     to <code>item()*</code>) by applying the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>.</p><p>
                           <span>This applies both to explicitly supplied arguments, and
                        to values obtained by evaluating default value expressions. In both cases a type
                        error will be raised if the value (after coercion) does not match the required type.</span>
                        </p></li><li><p>The result of the function call is obtained as follows:</p><ul><li><p>
                                 <var>FD</var>’s <span>body</span> is invoked
                                      in an implementation-dependent way.
                                      The processor makes the following information
                                      available to that invocation:
                                      
                                    </p><ul><li><p>The converted argument values;</p></li><li><p>If the function is <a title="context dependent" class="termref" href="#dt-context-dependent">context dependent</a>,
                                          the static context <var>SC</var> and dynamic context <var>DC</var> of the function call.
                                           </p></li></ul></li><li><p>The result is converted to the required type (the
                                             declared return type in the function declaration, defaulting
                                             to <code>item()*</code>) by applying the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>.</p><p>The result of applying the coercion rules is either an instance of <var>FD</var>’s return type
                                      or a dynamic error.
                                      This result is then the result of evaluating <var>FC</var>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>A host language may define alternative rules for processing the result, especially
                                      in the case of external functions implemented using a non-XDM type system.</p></div></li><li><p>
                                      Errors raised by system functions are defined in
                                      <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>.
                                    </p></li><li class="xquery"><p>
                                      Errors raised by external functions are
                                      <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>
                                      (see <a href="#id-consistency-constraints"><b>2.3.6 Consistency Constraints</b></a>).
                                    </p></li></ul><div class="example">
<div class="exampleHeader"><a id="d2e19552"/>Example: A System Function</div><p>The following function call uses the function 
                                  <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#func-base-uri">12.1.1 fn:base-uri</a>.  Use of <code>SC</code> and <code>DC</code> and errors raised by this function are all defined in 
                                  <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>.</p><div class="exampleInner"><pre>base-uri()</pre></div></div></li></ol></div></div><div class="div3">
<h4><a id="id-dynamic-functions"/>4.5.2 <a href="#id-dynamic-functions" style="text-decoration: none">Function Items</a></h4><p>A <a title="function item" class="termref" href="#dt-function-item">function item</a> is an XDM
            value that can be bound to a variable, or manipulated in various ways by XQuery 4.0 expressions.
            The most significant such expression is a <a title="dynamic function call" class="termref" href="#dt-dynamic-function-call">dynamic function call</a>, which supplies
            values of arguments and evaluates the function to produce a result.</p><p>The syntax of dynamic function calls is defined in <a href="#id-dynamic-function-invocation"><b>4.5.3 Dynamic Function Calls</b></a>.</p><p>A number of constructs can be used to produce a <a title="function item" class="termref" href="#dt-function-item">function item</a>, notably:</p><ul><li><p>A <b>named function reference</b> (see <a href="#id-named-function-ref"><b>4.5.5 Named Function References</b></a>)
               constructs a function item by reference to <a title="function definition" class="termref" href="#dt-function-definition">function definitions</a>
                  in the static context. For example, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-node-name"><code>fn:node-name#1</code></a>
               returns a function item whose effect is to call the static <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-node-name"><code>fn:node-name</code></a> function
               with one argument.</p></li><li><p>An <b>inline function</b> (see <a href="#id-inline-func"><b>4.5.6 Inline Function Expressions</b></a>
                        )
                  constructs a function item whose <span>body</span> is defined locally. For example, the
               construct <code>fn($x) { $x + 1 }</code> returns a function item whose effect is to increment
               the value of the supplied argument.</p></li><li><p>A <b>partial function application</b> (see 
                  <a href="#id-partial-function-application"><b>4.5.4 Partial Function Application</b></a>) derives one function item from another by supplying
               the values of some of its arguments. For example, <code>fn:ends-with(?, ".txt")</code> returns
               a function item with one argument that tests whether the supplied string ends with the substring
                  <code>".txt"</code>.</p></li><li><p>Maps and arrays are also function items. See <a href="#id-map-constructors"><b>4.14.1.1 Map Constructors</b></a>
               and <a href="#id-array-constructors"><b>4.14.2.1 Array Constructors</b></a>.</p></li><li><p>The <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-function-lookup"><code>fn:function-lookup</code></a> function can be called to discover functions
               that are present in the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a>.</p></li><li><p>The <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-load-xquery-module"><code>fn:load-xquery-module</code></a> function can be called to load functions
                  dynamically from an external XQuery library module.</p></li><li><p>Some system functions such as <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-random-number-generator"><code>fn:random-number-generator</code></a> 
                  and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-op"><code>fn:op</code></a> return a <a title="function item" class="termref" href="#dt-function-item">function item</a> as their result.</p></li></ul><p>These constructs are described in detail in the following sections, or in
               <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>.</p></div><div class="div3">
<h4><a id="id-dynamic-function-invocation"/>4.5.3 <a href="#id-dynamic-function-invocation" style="text-decoration: none">Dynamic Function Calls</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DynamicFunctionCall"/><code><a href="#prod-xquery40-DynamicFunctionCall">DynamicFunctionCall</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-DynamicFunctionCall-PostfixExpr">PostfixExpr</a>
                        <a href="#doc-xquery40-DynamicFunctionCall-PositionalArgumentList">PositionalArgumentList</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DynamicFunctionCall-PostfixExpr"/><code><a href="#prod-xquery40-PostfixExpr">PostfixExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-PrimaryExpr">PrimaryExpr</a>  |  <a href="#doc-xquery40-FilterExpr">FilterExpr</a>  |  <a href="#doc-xquery40-DynamicFunctionCall">DynamicFunctionCall</a>  |  <a href="#doc-xquery40-LookupExpr">LookupExpr</a>  |  <a href="#doc-xquery40-MethodCall">MethodCall</a>  |  <a href="#doc-xquery40-FilterExprAM">FilterExprAM</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DynamicFunctionCall-PositionalArgumentList"/><code><a href="#prod-xquery40-PositionalArgumentList">PositionalArgumentList</a></code></td><td>::=</td><td><code>"("  <a href="#doc-xquery40-DynamicFunctionCall-PositionalArguments">PositionalArguments</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DynamicFunctionCall-PositionalArguments"/><code><a href="#prod-xquery40-PositionalArguments">PositionalArguments</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-DynamicFunctionCall-Argument">Argument</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DynamicFunctionCall-Argument"/><code><a href="#prod-xquery40-Argument">Argument</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-DynamicFunctionCall-ExprSingle">ExprSingle</a>  |  <a href="#doc-xquery40-DynamicFunctionCall-ArgumentPlaceholder">ArgumentPlaceholder</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DynamicFunctionCall-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DynamicFunctionCall-ArgumentPlaceholder"/><code><a href="#prod-xquery40-ArgumentPlaceholder">ArgumentPlaceholder</a></code></td><td>::=</td><td><code>"?"</code></td></tr></tbody></table><p>
                  A <a title="dynamic function call" class="termref" href="#dt-dynamic-function-call">dynamic function call</a>
                     consists of a base expression that returns the function and a
                     parenthesized list of zero or more arguments (<a title="argument expression" class="termref" href="#dt-arg-expr">argument expressions</a> or
                     ArgumentPlaceholders).
               </p><p>
                  A dynamic function call is evaluated as described in
                  <a href="#id-eval-dynamic-function-call"><b>4.5.3.1 Evaluating Dynamic Function Calls</b></a>.
               </p><p>The following are examples of dynamic function calls:</p><ul><li><p>This example calls the function contained in <code>$f</code>, passing the arguments 2 and 3:
                        </p><div class="exampleInner"><pre>$f(2, 3)</pre></div></li><li><p>This example fetches the second item from sequence <code>$f</code>, treats it as a function and calls it, passing an <code>xs:string</code> argument:
                        </p><div class="exampleInner"><pre>$f[2]("Hi there")</pre></div></li><li><p>This example calls the function <code>$f</code> passing no arguments, and filters the result with a positional predicate:
                        </p><div class="exampleInner"><pre>$f()[2]</pre></div></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>Arguments in a dynamic function call are always supplied positionally.</p></div><div class="div4">
<h5><a id="id-eval-dynamic-function-call"/>4.5.3.1 <a href="#id-eval-dynamic-function-call" style="text-decoration: none">Evaluating Dynamic Function Calls</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-inline-func">⬇</a> <a href="#id-function-calls">⬆</a></p><ol><li><p>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.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1240">1240</a> ]</i></p></li></ol></div><p>This section applies to dynamic function calls whose arguments do not include
            an <code>ArgumentPlaceholder</code>. For function calls that include a placeholder,
            see <a href="#id-partial-function-application"><b>4.5.4 Partial Function Application</b></a>.</p><p>A <a title="dynamic function call" class="termref" href="#dt-dynamic-function-call">dynamic function call</a>
            is an expression that is evaluated by calling a <a title="function item" class="termref" href="#dt-function-item">function item</a>, which is
            typically obtained dynamically.</p><p>
                      When a dynamic function call <var>FC</var> is evaluated,
                      the result is obtained as follows:
                    </p><ol class="enumar"><li><p>
                          The base expression of the function call is evaluated.
                          If this is not of type <code>function(*)*</code> (a sequence
                        of zero or more function items) then a type error is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].
                     </p></li><li><p>The result of the dynamic function call is the <a title="sequence concatenation" class="termref" href="#dt-sequence-concatenation">sequence concatenation</a>
                        of the results of applying each function item individually, retaining order. That is, the
                        result of <code>
                              <var>F</var>(<var>X</var>, <var>Y</var>, ...)</code> is 
                        <code>for $FI in <var>F</var> return <var>$FI</var>(<var>X</var>, <var>Y</var>, ...)</code>.
                        The result of a dynamic function call applied to a single function item <var>FI</var> is defined
                        by the rules that follow.
                     </p></li><li><p>
                           [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].
                              If the arity of <var>FI</var> does not match the number of arguments in the <code>ArgumentList</code>,
                              a type error is raised
                              [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].
                            </p></li><li><p>
                           <a title="argument expression" class="termref" href="#dt-arg-expr">Argument expressions</a> are evaluated, 
                        producing <b>argument values</b>. The order of argument evaluation is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> and an argument need not be evaluated 
                        if the function body can be evaluated without evaluating that argument.</p></li><li><p>
                          Each argument value is converted
                          to the corresponding parameter type in <var>FI</var>’s signature
                          by applying the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>, resulting in a
                        <b>converted argument value</b>
                        </p></li><li><p>If <var>FI</var> is a map, it is evaluated as described in <a href="#id-map-lookup"><b>4.14.1.2 Maps as Functions</b></a>.</p></li><li><p>If <var>FI</var> is an array, it is evaluated as described in <a href="#id-array-lookup"><b>4.14.2.2 Arrays as Functions</b></a>.</p></li><li><p>
                                  If <var>FI</var>’s <span>body</span> is 
                                  
                                  an XQuery 4.0 expression
                                  
                                    (for example, if <var>FI</var> is
                                    <span class="xquery">a <a title="user-defined function" class="termref" href="#dt-udf">user-defined function</a> or</span>
                                    an <a title="anonymous function" class="termref" href="#dt-anonymous-function">anonymous function</a>,
                                    or a
                                    <a title="partially applied function" class="termref" href="#dt-partially-applied-function">partial application</a>
                                    of such a function):
                                  
                                </p><ol class="enumla"><li><p>
                                 <var>FI</var>’s <span>body</span> 
                                      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
                                      <span class="xquery">module</span>
                                          
                                      that contains the <code>FunctionBody</code>, and
                                      making the following changes:
                                    </p><ul><li><p>
                                          The <a title="focus" class="termref" href="#dt-focus">focus</a>
                                          (context value, context position, and context size)
                                          is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>.
                                        </p></li><li><p>
                                          In the <a title="variable values" class="termref" href="#dt-variable-values">variable values</a> component of the dynamic context,
                                          each converted argument value is bound to the
                                          corresponding parameter name.
                                        </p><p>
                                       <span>When this is done,
                                          the converted argument values retain
                                          their <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic types</a>,
                                          even where these are <a title="subtype" class="termref" href="#dt-subtype">subtypes</a> 
                                          of the declared parameter types.</span>
                                          For example, a function with
                                          a parameter <code>$p</code> of type <code>xs:decimal</code>
                                          can be called with an argument of type <code>xs:integer</code>,
                                          which is derived from <code>xs:decimal</code>.
                                          During the processing of this function
                                          call, the value of <code>$p</code> inside the body of the function 
                                          retains its <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a> of <code>xs:integer</code>.
                                        </p></li><li><p>
                                       <var>FI</var>’s nonlocal variable bindings
                                          are also added to the <a title="variable values" class="termref" href="#dt-variable-values">variable values</a>.
                                          (Note that the names of the nonlocal variables
                                          are by definition disjoint from the parameter names,
                                          so there can be no conflict.)
                                        </p></li></ul></li><li><p>
                                      The value returned by evaluating the function body
                                      is then converted to the declared return type of <var>FI</var>
                                      by applying the
                                      <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>.
                                      The result is then the result of evaluating <var>FC</var>.
                                    </p><p>
                                      As with argument values,
                                      the value returned by a function
                                      retains its <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a>,
                                      which may be a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of the declared return type of <var>FI</var>.
                                      For example, a function that has
                                      a declared return type of <code>xs:decimal</code>
                                      may in fact return a value of dynamic type <code>xs:integer</code>.
                                    </p></li></ol></li><li><p>                                  
                                  If the implementation of <var>FI</var> is
                                  not an XQuery 4.0 expression
                                  (for example, if <var>FI</var> is
                                  a <a title="system function" class="termref" href="#dt-system-function">system function</a>
                           <span class="xquery">or an <a title="external function" class="termref" href="#dt-external-function">external function</a>
                           </span>), 
                                    the <span>body</span> 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 <a href="#id-function-calls"><b>4.5.1.1 Static Function Call Syntax</b></a>).</p><p>Errors may be raised in the same way.</p></li></ol><div class="example">
<div class="exampleHeader"><a id="d2e20072"/>Example: Derived Types and Nonlocal Variable Bindings</div><p>
                        <code>$incr</code> 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 <code>xs:decimal</code>,
                                  the more specific type <code>xs:integer</code> is preserved in both cases.</p><div class="exampleInner"><pre>
let $incr := 1
let $f := function($i as xs:decimal) as xs:decimal { $i + $incr }
return $f(5)</pre></div></div><p> </p><div class="example">
<div class="exampleHeader"><a id="d2e20087"/>Example: Using the Context Value in an Anonymous Function</div><p>The following example will raise a <a title="type error" class="termref" href="#dt-type-error">type error</a>
                        [<a href="#ERRXPDY0002" title="err:XPDY0002">err:XPDY0002</a>]:</p><div class="exampleInner"><pre>
let $vat := function() { @vat + @price }
return doc('wares.xml')/shop/article/$vat()</pre></div><p>Instead, the context value can be used as an argument to the anonymous function:</p><div class="exampleInner"><pre>
let $vat := function($art) { $art/@vat + $art/@price }
return doc('wares.xml')/shop/article/$vat(.)</pre></div><p>Alternatively, the value can be referenced as a nonlocal variable binding:</p><div class="exampleInner"><pre>
let $ctx := doc('wares.xml')/shop/article
let $vat := function() { for $a in $ctx return $a/@vat + $a/@price }
return $vat()</pre></div><p>Finally, a <a title="focus function" class="termref" href="#dt-focus-function">focus function</a> can be used.
                                       This binds the value of the argument to the context value within the function body:</p><div class="exampleInner"><pre>
let $vat := function { @vat + @price }
return $vat(doc('wares.xml')/shop/article)</pre></div></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Keyword arguments are not allowed in a dynamic function call.</p></div></div></div><div class="div3">
<h4><a id="id-partial-function-application"/>4.5.4 <a href="#id-partial-function-application" style="text-decoration: none">Partial Function Application</a></h4><p>
                  [<a id="dt-partial-function-application" title="partial function application">Definition</a>: 
                     A <a title="static function call" class="termref" href="#dt-static-function-call">static</a> or 
                     <a title="dynamic function call" class="termref" href="#dt-dynamic-function-call">dynamic</a>
                     function call is a <b>partial function application</b>
                     if one or more arguments is an <a href="#prod-xquery40-ArgumentPlaceholder">ArgumentPlaceholder</a>.]
               </p><p>The rules for partial function application in static function calls and dynamic function
               calls have a great deal in common, but they are stated separately below for clarity.</p><p>Partial function application delivers
                  <a title="function item" class="termref" href="#dt-function-item">function items</a>, whose
                  arity is equal to the number of placeholders in the call.</p><p>A static partial function application always delivers one <a title="function item" class="termref" href="#dt-function-item">function item</a>.
               A dynamic partial function application delivers one <a title="function item" class="termref" href="#dt-function-item">function item</a> for each
               <a title="function item" class="termref" href="#dt-function-item">function item</a> in the input.</p><p>More specifically, each function item in the result of the partial function application is 
                  a <a title="partially applied function" class="termref" href="#dt-partially-applied-function">partially applied function</a>.
                  [<a id="dt-partially-applied-function" title="partially applied function">Definition</a>: A <b>partially applied function</b>
                  is a function created by  <a title="partial function application" class="termref" href="#dt-partial-function-application">partial function application</a>.]
               </p><p>For static function calls, the result is obtained as follows:</p><ol class="enumar"><li><p>The <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
                        <var>FD</var> to be partially applied
                        is determined in the same way as for a static function call without placeholders, 
                        as described in <a href="#id-function-calls"><b>4.5.1.1 Static Function Call Syntax</b></a>.
                        For this purpose an <code>ArgumentPlaceholder</code> contributes to the count of
                        arguments.</p></li><li><p>The parameters of <var>FD</var> are classified into three categories:</p><ul><li><p>Parameters that map to a placeholder, referred to as <b>placeholder parameters</b>.</p></li><li><p>Parameters for which an explicit value is given in the function call (either
                        positionally or by keyword), referred to as <b>explicitly supplied parameters</b>.</p></li><li><p>Parameters (which are necessarily optional parameters) for which no corresponding
                        argument is supplied, either as a placeholder or with an explicit value. These are referred to
                        as <b>defaulted parameters</b>.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>A partial function application need not have any explicitly supplied parameters.
                        For example, the partial function application <code>fn:string(?)</code>
                        is allowed; it has exactly the same effect as the <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-string"><code>fn:string#1</code></a>. </p></div></li><li><p>Explicitly supplied parameters and defaulted parameters are evaluated and 
                        converted to the required type using the rules for a static function call.
                        This may result in an error being raised.</p><p>A type error is raised if any of the explicitly supplied or defaulted
                        parameters, after applying the
                        <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>, does not match the required type 
                        of the corresponding parameter.</p><p>In addition, a dynamic error <span class="verb">may</span> 
                        be raised if any of the explicitly supplied or defaulted parameters does not match other constraints on the
                        value of that parameter (for example, if the value supplied for a parameter expecting
                        a regular expression is not a valid regular expression); or if the processor is
                        able to establish that evaluation of the resulting function will fail
                        for any other reason (for example, if an error is raised while evaluating 
                        a subexpression in the function
                        body that depends only on explicitly supplied and defaulted parameters).</p><p>In all cases the error code is the same as for a static
                        function call supplying the same invalid value(s).</p><p>In the particular case where all the supplied arguments
                     are placeholders, the error behavior <span class="verb">should</span> be the same as
                     for an equivalent <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a>: for example, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-id"><code>fn:id#1</code></a>
                     fails if there is no context node, and <code>fn:id(?)</code>
                        <span class="verb">should</span>
                     fail likewise.</p></li><li><p>
                        The result is a <a title="partially applied function" class="termref" href="#dt-partially-applied-function">partially applied function</a> having
                        the following properties (which are defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#function-items">8.1 Function Items</a>):
                     </p><ul><li><p>
                              <b>name</b>: The name of <var>FD</var> if all parameters map
                              to placeholders, that is, if the partial function application is
                              equivalent to the corresponding <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a>.
                              Otherwise, the name is absent.
                           </p></li><li><p>
                              <b>identity</b>: A new function
                           identity distinct from the identity of any other function item.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>See also <a href="#id-function-identity"><b>4.5.7 Function Identity</b></a>.</p></div></li><li><p>
                              <b>arity</b>: The number of placeholders in the function call.</p></li><li><p>
                              <b>signature</b>: The parameters in the returned function
                              are the parameters of <var>FD</var>
                              that have been identified as placeholder parameters,
                              retaining the order in which the placeholders appear in the
                              function call. The result type of the returned function
                              is the same as the result type of <var>FD</var>.</p><p>An implementation which can determine a more specific signature (for example, 
                              through use of type analysis) is permitted to do so.
                           </p></li><li><p>
                              <b>annotations</b>: The annotations of 
                           <var>FD</var>.</p></li><li><p>
                              <b>body</b>: The body of <var>FD</var>.</p></li><li><p>
                              <b>captured context</b>: The
                              static and dynamic context of the function call, augmented,
                              for each explicitly supplied parameter and each defaulted parameter, with
                              a binding of the converted argument value
                              to the corresponding parameter name.
                           </p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>A partial function application can be used to change the order
                           of parameters, for example <code>fn:contains(substring := ?, value := ?)</code>
                           returns a function item that is equivalent to <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-contains"><code>fn:contains#2</code></a>,
                           but with the order of arguments reversed.</p></div><div class="example">
<div class="exampleHeader"><a id="d2e20297"/>Example: Partial Application of a System Function</div><p>The following partial function application creates a function 
                           item that computes the sum of squares of a sequence.</p><div class="exampleInner"><pre>let $sum-of-squares := fold-right(?, 0, function($a, $b) { $a*$a + $b })
return $sum-of-squares(1 to 3)</pre></div><p>
                           <code>$sum-of-squares</code> is an anonymous function. It has one parameter, named <code>$seq</code>, which is taken from the corresponding parameter in <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-fold-right"><code>fn:fold-right</code></a> (the other two parameters are fixed). The implementation is the implementation of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-fold-right"><code>fn:fold-right</code></a>, which is a context-independent system function. The nonlocal bindings contain the fixed bindings for the second and third parameters of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-fold-right"><code>fn:fold-right</code></a>.</p></div></li></ol><p>For dynamic function calls,  the result is obtained as follows:</p><ol class="enumar"><li><p>
                          The base expression of the function call is evaluated.
                          If this is not of type <code>function(*)*</code> (a sequence
                        of zero or more function items) then a type error is raised.
                     </p></li><li><p>The result of the dynamic function call is the <a title="sequence concatenation" class="termref" href="#dt-sequence-concatenation">sequence concatenation</a>
                        of the results of partial applying each function item, retaining order. That is, the
                        result of <code>
                           <var>F</var>(<var>X</var>, <var>Y</var>, ...)</code> is 
                        <code>for $FI in <var>F</var> return <var>$FI</var>(<var>X</var>, <var>Y</var>, ...)</code>.
                        The result of a dynamic function call applied to a single function item <var>FI</var> is defined
                        by the rules that follow.
                     </p></li><li><p>An <code>ArgumentPlaceholder</code> contributes to the count of
                        arguments.</p></li><li><p>The parameters of <var>FI</var> are classified into two categories:</p><ul><li><p>Parameters that map to a placeholder, referred to as <b>placeholder parameters</b>.</p></li><li><p>Parameters for which an explicit value is given in the function call, 
                           referred to as <b>supplied parameters</b>.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>A partial function application need not have any explicitly supplied parameters.
                        For example, if <code>$f</code> is a function with arity 2, then
                           the partial function application <code>$f(?, ?)</code> returns
                           a function that has exactly the same effect as <code>$f</code>. </p></div></li><li><p>Arguments corresponding to supplied parameters are evaluated
                        and converted to the required
                     type of the parameter, using the rules for dynamic function calls.</p><p>A type error is raised if any of the supplied
                        parameters, after applying the
                        <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>, does not match the required type.</p><p>In addition, a dynamic error <span class="verb">may</span> 
                     be raised if any of the supplied parameters does not match other constraints on the
                     value of that parameter (for example, if the value supplied for a parameter expecting
                     a regular expression is not a valid regular expression); or if the processor is
                     able to establish that evaluation of the resulting function will fail
                     for any other reason (for example, if an error is raised while evaluating 
                     a subexpression in the function
                     body that depends only on explicitly supplied parameters).</p><p>In both cases the error code is the same as for a dynamic
                     function call supplying the same invalid value.</p></li><li><p>
                              The result of the partial function application is a  <a title="partially applied function" class="termref" href="#dt-partially-applied-function">partially applied function</a> with
                              the following properties (which are defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#function-items">8.1 Function Items</a>):
                            </p><ul><li><p>
                              <b>name</b>:
                                  Absent.
                                </p></li><li><p>
                              <b>arity</b>: The number of placeholders in the function call.</p></li><li><p>
                              <b>signature</b>:
                                  The signature of <var>FI</var>,
                                  removing the types of supplied parameters.
				  
				                      An implementation which can determine a more specific signature (for example, 
				                      through use of type analysis) is permitted to do so.
                                </p></li><li><p>
                              <b>annotations</b>: The annotations of <var>FI</var>.</p></li><li><p>
                              <b>body</b>: The body of <var>FI</var>.
                                </p></li><li><p>
                              <b>captured context</b>: the
                                    captured context of <var>FI</var>, augmented,
                                  for each supplied parameter, with
                                  a binding of the converted argument value
                                  to the corresponding parameter name.
                                </p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>In a dynamic partial function application, argument keywords
                                 are not available, so it is not possible to change the order of parameters.</p></div><div class="example">
<div class="exampleHeader"><a id="d2e20446"/>Example: Partial Application of an Anonymous Function</div><p>In the following example, <code>$f</code> is an anonymous function, and <code>$paf</code> is a partially applied function created from <code>$f</code>.</p><div class="exampleInner"><pre>
let $f := function($seq, $delim) { fold-left($seq, "", concat(?, $delim, ?)) }
let $paf := $f(?, ".")
return $paf(1 to 5)</pre></div><p>
                           <code>$paf</code> is also an anonymous function.  It has one parameter, named <code>$delim</code>, which is taken from the corresponding parameter in <code>$f</code>
                              (the other parameter is fixed).  The implementation of <code>$paf</code> is the implementation of <code>$f</code>, which is <code>fn:fold-left($seq, "", fn:concat(?, $delim, ?))</code>.  This implementation is associated with the <code>SC</code> and <code>DC</code> of the original expression in <code>$f</code>.  The nonlocal bindings associate the value <code>"."</code> with the parameter <code>$delim</code>.</p></div></li></ol><p>Partial function application never returns a map or an array.  If <code>$f</code> is a map or an array, then <code>$f(?)</code> is 
                  a partial function application that returns a function, but the function it returns is neither a map nor an array.</p><div class="example">
<div class="exampleHeader"><a id="d2e20506"/>Example: Partial Application of a Map</div><p>The following partial function application converts a map to an equivalent function that is not a map.</p><div class="exampleInner"><pre>let $a := { "A": 1, "B": 2 }(?)
return $a("A")</pre></div></div></div><div class="div3">
<h4><a id="id-named-function-ref"/>4.5.5 <a href="#id-named-function-ref" style="text-decoration: none">Named Function References</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedFunctionRef"/><code><a href="#prod-xquery40-NamedFunctionRef">NamedFunctionRef</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-NamedFunctionRef-EQName">EQName</a>  "#"  <a href="#doc-xquery40-NamedFunctionRef-IntegerLiteral">IntegerLiteral</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedFunctionRef-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedFunctionRef-IntegerLiteral"/><code><a href="#prod-xquery40-IntegerLiteral">IntegerLiteral</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-NamedFunctionRef-Digits">Digits</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedFunctionRef-Digits"/><code><a href="#prod-xquery40-Digits">Digits</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-NamedFunctionRef-DecDigit">DecDigit</a>  ((<a href="#doc-xquery40-NamedFunctionRef-DecDigit">DecDigit</a>  |  "_")*  <a href="#doc-xquery40-NamedFunctionRef-DecDigit">DecDigit</a>)?</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedFunctionRef-DecDigit"/><code><a href="#prod-xquery40-DecDigit">DecDigit</a></code></td><td>::=</td><td><code>[0-9]</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody></table><p>
                  [<a id="dt-named-function-ref" title="named function reference">Definition</a>: 
          A <b>named function reference</b> is an instance of the production
                  <a href="#doc-xquery40-NamedFunctionRef">NamedFunctionRef</a>: 
                  it is an expression (written <code>name#arity</code>)
                  which evaluates to a <a title="function item" class="termref" href="#dt-function-item">function item</a>, the details
                  of the function item being based on the properties of a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
                  in the <a title="static context" class="termref" href="#dt-static-context">static context</a>.]
               </p><p>The name and arity of the required function are known statically.</p><p>The EQName is expanded using the <a title="default function namespace rule" class="termref" href="#dt-default-function-namespace-rule">default function namespace rule</a>.</p><p>The <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> and arity must correspond to a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
               present in the <a title="static context" class="termref" href="#dt-static-context">static context</a>.
            <span>More specifically, for a named function reference <code>F#N</code>,
               there must be a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> in the <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a>
               whose name matches <var>F</var>, and whose <a title="arity range" class="termref" href="#dt-arity-range">arity range</a> includes <var>N</var>
                  </span>.
               Call this <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
                  <var>FD</var>.</p><p>If <var>FD</var> is
          <a title="context dependent" class="termref" href="#dt-context-dependent">context dependent</a> for the given arity, then the returned function item has
               a captured context comprising
          the static and dynamic context of the named function reference.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In practice, it is necessary to retain only those
            parts of the static and dynamic context that can affect the outcome. These means it is 
            unnecessary to retain parts of the context that no <a title="system function" class="termref" href="#dt-system-function">system function</a>
            depends on (for example, local variables), or parts that are invariant within an
            execution scope (for example, the implicit timezone).</p></div><div class="example">
<div class="exampleHeader"><a id="d2e20654"/>Example: A Context-Dependent Named Function Reference</div><p>Consider:</p><div class="exampleInner"><pre>let $f := &lt;foo/&gt;/fn:name#0 return &lt;bar/&gt;/$f()</pre></div><p>The function <code>fn:name()</code>, with no arguments, returns the name of the context node. The function
               item delivered by evaluating the expression <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-name"><code>fn:name#0</code></a> returns the name of the element that was the
               context node at the point where the function reference was evaluated (that is, the <code>&lt;foo&gt;</code> element).
               This expression therefore returns <code>"foo"</code>, not <code>"bar"</code>.</p></div><p>An error is raised if the identified function depends on components of the static or dynamic
                  context that are not present, or that have unsuitable values. For example [<a href="#ERRXPDY0002" title="err:XPDY0002">err:XPDY0002</a>] is raised for the expression <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-name"><code>fn:name#0</code></a>
                  if the context item is absent, and [<a href="https://www.w3.org/TR/xpath-functions/#ERRFODC0001" title="err:FODC0001">err:FODC0001</a>]<sup><small>FO</small></sup> is raised for the call <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-id"><code>fn:id#1</code></a> if the context item is not a node
                  in a tree that is rooted at a document node. The error that is raised is the same as the error that would
                  be raised by the corresponding function if called with the same static and dynamic context.</p><p>If the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> and arity in a named function reference do not match the 
               name and <a title="arity range" class="termref" href="#dt-arity-range">arity range</a> of a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> in the
          static context, a static error is raised [<a href="#ERRXPST0017" title="err:XPST0017">err:XPST0017</a>].</p><p>
            The value of a <code>NamedFunctionRef</code>
               is a <a title="function item" class="termref" href="#dt-function-item">function item</a>
                  <var>FI</var> 
               obtained from <var>FD</var>
               as follows:
               </p><ul><li><p>
                           <b>name</b>: The name of <var>FD</var>.</p></li><li><p>
                           <b>identity</b>:</p><ul><li><p>If <var>FD</var> is <a title="context dependent" class="termref" href="#dt-context-dependent">context dependent</a> for the given arity, then a new function
                        identity distinct from the identity of any other function item.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In the general case, a function reference to a context-dependent function
                           will produce different results every time it is evaluated, because the resulting function
                           item has a <b>captured context</b> 
                              (see <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#function-items">8.1 Function Items</a>) that includes the dynamic context
                           of the particular evaluation. Optimizers, however, are allowed to detect cases where
                           the captured context happens to be the same, or where any variations are immaterial,
                           and where it is therefore safe to return the same function item each time. This might be
                           the case, for example, where the only context dependency of a function is on the default
                           collation, and the default collation for both evaluations is known to be the same.</p></div></li><li><p>Otherwise, a function identity that is the same as that produced by the evaluation
                           of any other named function reference with the same function name and arity.</p><p>This rule applies even across different 
                                <a href="https://qt4cg.org/specifications/xpath-functions-40/#execution-scope">execution scopes</a><sup><small>FO</small></sup>:
                             for example if a parameter to a call to <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-transform"><code>fn:transform</code></a> is set to the
                             result of the expression <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-abs"><code>fn:abs#1</code></a>, then the function item passed as the parameter
                                value will be identical to that obtained by evaluating the expression <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-abs"><code>fn:abs#1</code></a>
                             within the target XSLT stylesheet.</p><p>This rule also applies when the target function definition is 
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/#dt-nondeterministic">nondeterministic</a><sup><small>FO</small></sup>. 
                           For example all evaluations of the named function reference <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-map-keys"><code>map:keys#2</code></a>
                           return identical function items, even though two evaluations of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-map-keys"><code>map:keys</code></a>
                           with the same arguments may produce different results.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>See also <a href="#id-function-identity"><b>4.5.7 Function Identity</b></a>.</p></div></li><li><p>
                           <b>arity</b>: As specified in the named function reference.</p></li><li><p>
                           <b>signature</b>: Formed from the required types of the first
                        <var>A</var> parameters of <var>FD</var>, and the function result type of
                        <var>FD</var>.</p></li><li><p>
                           <b>annotations</b>: The annotations of 
                           <var>FD</var>.</p></li><li><p>
                           <b>body</b>: The body of <var>FD</var>.</p></li><li><p>
                           <b>captured context</b>: Comprises the
                        static and dynamic context of the named function reference, augmented with
                        bindings of the names of parameters of <var>FD</var> beyond the
                        <var>A</var>’th parameter, to their respective default values.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In practice, it is necessary to retain
                        only the parts of the context that the function actually depends on
                        (if any).</p></div></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>Consider the system function <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-date"><code>fn:format-date</code></a>,
            which has an arity range of 2 to 5. The named function reference <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-date"><code>fn:format-date#3</code></a>
            returns a function item whose three parameters correspond to the first three parameters
            of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-date"><code>fn:format-date</code></a>; the remaining two arguments will take their default values.
               To obtain an arity-3 function that binds to arguments 1, 2, and 5 of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-date"><code>fn:format-date</code></a>,
            use the partial function application <code>format-date(?, ?, place := ?)</code>.</p></div><p>The following are examples of named function references:
          </p><ul><li><p>
                        <code>fn:abs#1</code> references the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-abs"><code>fn:abs</code></a> function which takes a single argument.</p></li><li><p>
                        <code>fn:concat#5</code> references the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-concat"><code>fn:concat</code></a> function which takes 5 arguments.</p></li><li><p>
                        <code>local:myfunc#2</code> references a function named <code>local:myfunc</code> which takes 2 arguments.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>Function items, as values in the data model, have a fixed arity, and
            a dynamic function call always supplies the arguments positionally. In effect, the result of evaluating <code>my:func#3</code> is the
            same as the result of evaluating the inline function expression <code>fn($x, $y, $z) { my:func($x, $y, $z) }</code>,
            except that the returned function has a name (it retains the name <code>my:func</code>).</p></div></div><div class="div3">
<h4><a id="id-inline-func"/>4.5.6 <a href="#id-inline-func" style="text-decoration: none">Inline Function Expressions</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-path-expressions">⬇</a> <a href="#id-eval-dynamic-function-call">⬆</a></p><ol><li><p>
                  In inline function expressions, the keyword <code>function</code> may be abbreviated
                  as <code>fn</code>.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1192">1192</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1197">1197</a> 21 May 2024]</i></p></li><li><p>New abbreviated syntax is introduced 
                     (<a title="focus function" class="termref" href="#dt-focus-function">focus function</a>) 
                     for simple inline functions taking a single argument. 
                     An example is <code>fn { ../@code }</code>
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/503">503</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/521">521</a> 30 May 2023]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InlineFunctionExpr"/><code><a href="#prod-xquery40-InlineFunctionExpr">InlineFunctionExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-InlineFunctionExpr-Annotation">Annotation</a>*  ("function"  |  "fn")  <a href="#doc-xquery40-InlineFunctionExpr-FunctionSignature">FunctionSignature</a>?  <a href="#doc-xquery40-InlineFunctionExpr-FunctionBody">FunctionBody</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InlineFunctionExpr-Annotation"/><code><a href="#prod-xquery40-Annotation">Annotation</a></code></td><td>::=</td><td><code>"%"  <a href="#doc-xquery40-InlineFunctionExpr-EQName">EQName</a>  ("("  (<a href="#prod-xquery40-Constant">Constant</a> ++ ",")  ")")?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InlineFunctionExpr-FunctionSignature"/><code><a href="#prod-xquery40-FunctionSignature">FunctionSignature</a></code></td><td>::=</td><td><code>"("  <a href="#doc-xquery40-InlineFunctionExpr-ParamList">ParamList</a>  ")"  <a href="#doc-xquery40-InlineFunctionExpr-TypeDeclaration">TypeDeclaration</a>?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InlineFunctionExpr-ParamList"/><code><a href="#prod-xquery40-ParamList">ParamList</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-InlineFunctionExpr-VarNameAndType">VarNameAndType</a> ** ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InlineFunctionExpr-VarNameAndType"/><code><a href="#prod-xquery40-VarNameAndType">VarNameAndType</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-InlineFunctionExpr-EQName">EQName</a>
                        <a href="#doc-xquery40-InlineFunctionExpr-TypeDeclaration">TypeDeclaration</a>?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InlineFunctionExpr-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InlineFunctionExpr-TypeDeclaration"/><code><a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a></code></td><td>::=</td><td><code>"as"  <a href="#doc-xquery40-InlineFunctionExpr-SequenceType">SequenceType</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InlineFunctionExpr-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                        <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InlineFunctionExpr-FunctionBody"/><code><a href="#prod-xquery40-FunctionBody">FunctionBody</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-InlineFunctionExpr-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InlineFunctionExpr-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>
                  [<a id="dt-inline-func" title="inline function expression">Definition</a>: An 
                  <b>inline function expression</b> is an instance of the
                  construct <a href="#doc-xquery40-InlineFunctionExpr">InlineFunctionExpr</a>. When evaluated, 
                  an inline function expression creates
          an <a title="anonymous function" class="termref" href="#dt-anonymous-function">anonymous function</a>
          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.</p><p>An <a title="inline function expression" class="termref" href="#dt-inline-func">inline function expression</a> whose 
               <a href="#prod-xquery40-FunctionSignature">FunctionSignature</a> is omitted
               is known as a <a title="focus function" class="termref" href="#dt-focus-function">focus function</a>. Focus functions are 
               described in <a href="#id-focus-functions"><b>4.5.6.1 Focus Functions</b></a>.</p><p>
                  [<a id="dt-anonymous-function" title="anonymous function">Definition</a>: 
             An <b>anonymous function</b> is a <a title="function item" class="termref" href="#dt-function-item">function item</a> with no name.  
             Anonymous functions may be created, for example, by evaluating an inline function 
             expression or by partial function application.]
               </p><p>The keywords <code>function</code> and <code>fn</code> 
               are synonymous.</p><p>The syntax allows the names and types of the function argument to be declared, along
           with the type of the result:</p><div class="exampleInner"><pre>function($x as xs:integer, $y as xs:integer) as xs:integer { $x + $y }</pre></div><p>The types can be omitted<span>, and the keyword can be abbreviated</span>:</p><div class="exampleInner"><pre>fn($x, $y) { $x + $y }</pre></div><p>A zero-arity function can be written as, for example, <code>fn() { current-date() }</code>.</p><p>
          If a function parameter is declared using a name but no type, its default type is <code>item()*</code>.
                  
               If the result type is omitted, its default result type is <code>item()*</code>.
          </p><p>
          The parameters of an inline function expression are considered to be variables whose scope is the function body. It is a static error
          [<a href="#ERRXQST0039" title="err:XQST0039">err:XQST0039</a>] for an inline function expression to have more than one parameter with the same name.
          </p><p>An inline function
	  expression may have
	  annotations; however, no annotations are defined in XQuery 4.0 
	  for inline function
	  expressions.
                  It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
                  [<a href="#ERRXQST0125" title="err:XQST0125">err:XQST0125</a>] if an inline function expression is annotated as
	  <code>%public</code> or <code>%private</code>. An
	  implementation can define annotations, in its own namespace,
	  to support functionality beyond the scope of this
	  specification.</p><p>
          The static context for the function body is inherited from the location of the inline function expression.
          </p><p>
          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.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>
            Function parameter names can mask variables that would otherwise be in scope for the function body.
          </p></div><p>The result of an inline function expression is a single function item
                  with the following properties (as defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#function-items">8.1 Function Items</a>):</p><ul><li><p>
                        <b>name</b>:
              Absent.
            </p></li><li><p>
                        <b>identity</b>: A new function
                              identity distinct from the identity of any other function item.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>See also <a href="#id-function-identity"><b>4.5.7 Function Identity</b></a>.</p></div></li><li><p>
                        <b>signature</b>:
              A <code>FunctionType</code>
              constructed from the
              <span class="xquery">
                           <code>Annotation</code>s and</span>
                        <code>SequenceType</code>s in the <code>InlineFunctionExpr</code>.
	      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.
            </p></li><li><p>
                        <b>annotations</b>: 
                              <span class="xquery">The annotations explicitly
                                 included in the inline function expression.</span>
                     </p></li><li><p>
                        <b>body</b>:
              The <code>FunctionBody</code> of the <code>InlineFunctionExpr</code>.
            </p></li><li><p>
                        <b>captured context</b>: the static context
                           is the static context of the inline function expression. The dynamic context has an absent
                           <a title="focus" class="termref" href="#dt-focus">focus</a>, and a set of variable bindings
                           comprising the <a title="variable values" class="termref" href="#dt-variable-values">variable values</a> component
                           of the dynamic context of the <code>InlineFunctionExpr</code>.
            </p></li></ul><p>The following are examples of some inline function expressions:</p><ul><li><p>This example creates a function that takes no arguments and returns a sequence of the first 6 primes:
                </p><div class="exampleInner"><pre>function() as xs:integer+ { 2, 3, 5, 7, 11, 13 }</pre></div></li><li><p>This example creates a function that takes two <code>xs:double</code> arguments and returns their product:
                </p><div class="exampleInner"><pre>fn($a as xs:double, $b as xs:double) as xs:double { $a * $b }</pre></div></li><li><p>This example creates and invokes a function that captures the value of a local variable in its scope:
                        </p><div class="exampleInner"><pre>let $incrementors := (
  for $x in 1 to 10
  return function($y) as xs:integer { $x + $y }
)
return $incrementors[2](4)</pre></div><p>The result of this expression is <code>6</code>
                     </p></li></ul><div class="div4">
<h5><a id="id-focus-functions"/>4.5.6.1 <a href="#id-focus-functions" style="text-decoration: none">Focus Functions</a></h5><p>
                     [<a id="dt-focus-function" title="focus function">Definition</a>: A <b>focus function</b>
               is an inline function expression in which the function signature is implicit: the function takes
               a single argument of type <code>item()*</code> (that is, any value), and binds this to the 
                  context value when evaluating
               the function body, which returns a result of type <code>item()*</code>.]
                  </p><p>Here are some examples of focus functions:</p><ul><li><p>
                           <code>fn { @age }</code> - a function that expects a node as its argument, and returns
                  the <code>@age</code> attribute of that node.</p></li><li><p>
                           <code>fn { . + 1 }</code> - a function that expects a number as its argument, and returns
                  that number plus one.</p></li><li><p>
                           <code>function { `${ . }` }</code> - a function that expects a string as its argument, and prepends
                     a <code>"$"</code> character.</p></li><li><p>
                           <code>function { head(.) + foot(.) }</code> - a function that expects a sequence of numbers
                     as its argument, and returns the sum of the first and last items in the sequence.</p></li></ul><p>Focus functions are often useful as arguments to simple higher-order functions such as <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-sort"><code>fn:sort</code></a>.
               For example, to sort employees by salary, write <code>sort(//employee, (), fn { +@salary })</code>.
               (The unary plus has the effect of converting the attribute’s value to a number, for numeric sorting).</p><p>Focus functions can also be useful on the right-hand side of the <a title="sequence arrow operator" class="termref" href="#dt-sequence-arrow-operator">sequence arrow operator</a>
                  and <a title="mapping arrow operator" class="termref" href="#dt-mapping-arrow-operator">mapping arrow operator</a>.
               For example, <code>$s =&gt; tokenize() =!&gt; fn { `"{.}"` }()</code> first tokenizes the string <code>$s</code>,
               then wraps each token in double quotation marks.</p><p>The result of calling the <code>function { EXPR }</code> (or <code>fn { EXPR }</code>), with
                  a single argument whose value is <var>$Z</var> arguments, is obtained by evaluating <code>EXPR</code>
                  with a <a title="fixed focus" class="termref" href="#dt-fixed-focus">fixed focus</a> in which the context value is <var>$Z</var>, the context position is 1 (one),
                  and the context size is 1 (one).</p><p>The expression <code>function { EXPR }</code> is thus formally equivalent to the expression
               <code>function($Z as item()*) as item()* { $Z -&gt; (EXPR) }</code>, where <code>$Z</code> is some variable name
               that is otherwise unused. Here <code>-&gt;</code> is the pipeline operator described
               in <a href="#id-pipeline-operator"><b>4.22 Pipeline operator</b></a>.</p><p>For example, the expression <code>every(1 to 10, fn { . gt 0 })</code> returns <code>true</code>.</p></div></div><div class="div3">
<h4><a id="id-function-identity"/>4.5.7 <a href="#id-function-identity" style="text-decoration: none">Function Identity</a></h4><p>It is sometimes useful to be able to establish whether two variables refer to the same function
               or to different functions. For this purpose, every function item has an identity. Functions with the
               same identity are indistinguishable in every way; in particular, any function call with identical
               arguments will produce an identical result.</p><p>In general, evaluation of an expression that returns a function item other than one that was
               present in its operands delivers a function item whose identity is unique, and thus distinct
               from any other function item. There are two exceptions to this rule:</p><ul><li><p>Evaluating a function reference such as <code>count#1</code> returns the same function
                  every time. Specifically, if the function name identifies a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
                  that is not <a title="context dependent" class="termref" href="#dt-context-dependent">context dependent</a> (which is the most usual case), then all 
                     function references using this function name and arity return the same function.
                  For more details see <a href="#id-named-function-ref"><b>4.5.5 Named Function References</b></a>.</p></li><li><p>An optimizer is permitted to rewrite <a href="https://qt4cg.org/specifications/xpath-functions-40/#dt-deterministic">deterministic</a><sup><small>FO</small></sup>
                     expressions in such a way that repeated evaluation is avoided, and this may be
                     done without consideration of function identity. For example:</p><ul><li><p>If the expression
                           <code>contains(?, "e")</code> appears within the body of a <code>for</code>
                           clause, or if the same expression is written repeatedly in a query, then an
                           optimizer may decide to evaluate it once only, and thus return the same function
                           item each time.</p></li><li><p>Similarly, if the expression <code>fn($x) { $x + 1 }</code>
                           appears more than once, or is evaluated repeatedly, then it may return the same
                           function each time.</p></li><li><p>Optimizers are allowed to replace any expression with an
                           equivalent expression. For example, <code>count(?)</code> may be rewritten as
                           <code>count#1</code>. Similarly, <code>fn($x) { $x + 1 }</code> may be
                           rewritten as <code>fn($y) { $y + 1 }</code>. This may lead to different
                           expressions returning identical function items.</p></li><li><p>In principle, two function items are not identical if they
                           differ in their captured context. Optimizers, however, will often
                           be able to eliminate parts of the captured context that a function does
                           not actually use. For example, an inline function expression delivers
                           a function item whose captured context includes the values of all nonlocal
                           in-scope variables; but in practice the implementation is unlikely to retain the
                           values of such variables unless they are actually referenced.
                        </p></li></ul></li></ul></div></div><div class="div2">
<h3><a id="id-path-expressions"/>4.6 <a href="#id-path-expressions" style="text-decoration: none">Path Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#axes">⬇</a> <a href="#id-inline-func">⬆</a></p><ol><li><p>
               Path expressions are extended to handle JNodes (found in trees of maps and arrays)
               as well as XNodes (found in trees representing parsed XML).
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2054">2054</a> ]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PathExpr"/><code><a href="#prod-xquery40-PathExpr">PathExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PathExpr-AbsolutePathExpr">AbsolutePathExpr</a>
                     <br/>|  <a href="#doc-xquery40-PathExpr-RelativePathExpr">RelativePathExpr</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-leading-lone-slash">xgc: leading-lone-slash</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PathExpr-AbsolutePathExpr"/><code><a href="#prod-xquery40-AbsolutePathExpr">AbsolutePathExpr</a></code></td><td>::=</td><td><code>("/"  <a href="#doc-xquery40-PathExpr-RelativePathExpr">RelativePathExpr</a>?)  |  ("//"  <a href="#doc-xquery40-PathExpr-RelativePathExpr">RelativePathExpr</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PathExpr-RelativePathExpr"/><code><a href="#prod-xquery40-RelativePathExpr">RelativePathExpr</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-StepExpr">StepExpr</a>  (("/"  |  "//")  <a href="#prod-xquery40-StepExpr">StepExpr</a>)*</code></td></tr></tbody></table><p>
               [<a id="dt-path-expression" title="path expression">Definition</a>: A <b>path expression</b>
            is either an <a title="absolute path expression" class="termref" href="#dt-absolute-path-expression">absolute path expression</a> or a
            <a title="relative path expression" class="termref" href="#dt-relative-path-expression">relative path expression</a>
               ]
            </p><p>
               [<a id="dt-absolute-path-expression" title="absolute path expression">Definition</a>: 
            An <b>absolute path expression</b> is an instance 
            of the production <a href="#prod-xquery40-AbsolutePathExpr">AbsolutePathExpr</a>:
            it consists of either (a) the operator <code>/</code> followed by zero or more 
            operands separated by <code>/</code> or <code>//</code> operators, or (b) the operator <code>//</code>
            followed by one or more operands separated by <code>/</code> or <code>//</code>
            operators.]
            </p><p>
               [<a id="dt-relative-path-expression" title="relative path expression">Definition</a>: 
            A <b>relative path expression</b> is a <a title="non-trivial" class="termref" href="#dt-non-trivial">non-trivial</a>
            instance of the production <a href="#doc-xquery40-RelativePathExpr">RelativePathExpr</a>:
            it consists of two or more operand expressions 
            separated by <code>/</code> or <code>//</code> operators.]
            </p><p>
               [<a id="dt-step" title="step">Definition</a>: The operands of a path expression
            are conventionally referred to as <b>steps</b>.]
            </p><div class="note"><p class="prefix"><b>Note:</b></p><p>The term <b>step</b> must not be confused with
         <a title="axis step" class="termref" href="#dt-axis-step">axis step</a>. A <b>step</b> can be any kind of
         expression, often but not necessarily an <a title="axis step" class="termref" href="#dt-axis-step">axis step</a>,
         while an <a title="axis step" class="termref" href="#dt-axis-step">axis step</a> can be used in any expression
         context, not necessarily as a <a title="step" class="termref" href="#dt-step">step</a> in a path
         expression.</p></div><p>A path expression is typically used to locate <a title="GNode" class="termref" href="#dt-GNode">GNodes</a> 
            within <a title="GTree" class="termref" href="#dt-GTree">GTrees</a>. </p><div class="note"><p class="prefix"><b>Note:</b></p><p>Note the terminology:</p><ul><li><p>A <a title="GNode" class="termref" href="#dt-GNode">GNode</a> is a generalized node, either an
               <a title="XNode" class="termref" href="#dt-XNode">XNode</a> or a <a title="JNode" class="termref" href="#dt-JNode">JNode</a>.</p></li><li><p>A <a title="GTree" class="termref" href="#dt-GTree">GTree</a> is a generalized tree, either an
               <a title="XTree" class="termref" href="#dt-XTree">XTree</a> or a <a title="JTree" class="termref" href="#dt-JTree">JTree</a>.</p></li></ul></div><p>The following definitions are copied from the data model specification,
         for convenience:</p><ul><li><p>
                     [<a id="dt-JTree" title="JTree">Definition</a>: A tree that is rooted at a parentless
    <a title="JNode" class="termref" href="#dt-JNode">JNode</a> is referred to as a <b>JTree</b>.]
                  </p></li><li><p>
                     [<a id="dt-XTree" title="XTree">Definition</a>: A tree that is rooted at a parentless
    <a title="XNode" class="termref" href="#dt-XNode">XNode</a> is referred to as an <b>XTree</b>.]
                  </p></li><li><p>
                     [<a id="dt-GNode" title="GNode">Definition</a>: The term <b>generic node</b> or <b>GNode</b>
    is a collective term for <a title="XNode" class="termref" href="#dt-XNode">XNodes</a> (more commonly called simply
      <a title="node" class="termref" href="#dt-node">nodes</a>) representing
    the parts of an XML document, and <a title="JNode" class="termref" href="#dt-JNode">JNodes</a>, 
    often used to represent the parts of a JSON document.]
                  </p></li><li><p>
                     [<a id="dt-JNode" title="JNode">Definition</a>: A <b>JNode</b> is a kind of <a title="item" class="termref" href="#dt-item">item</a>
      used to represent a value within the context of a tree of <a title="map" class="termref" href="#dt-map">maps</a>
      and <a title="array" class="termref" href="#dt-array">arrays</a>. A root <b>JNode</b> represents
      a map or array; a non-root <b>JNode</b> represents a <a title="member" class="termref" href="#dt-member">member</a> of an 
      array or an <a title="entry" class="termref" href="#dt-entry">entry</a> in a map.]
                  </p></li></ul><p>
               [<a id="dt-GTree" title="GTree">Definition</a>: The term <b>GTree</b>
         means <a title="JTree" class="termref" href="#dt-JTree">JTree</a> or <a title="XTree" class="termref" href="#dt-XTree">XTree</a>.]
            </p><p>
               <a title="absolute path expression" class="termref" href="#dt-absolute-path-expression">Absolute path expressions</a> 
            (those starting with an initial <code>/</code>
            or <code>//</code>), start their selection from the root GNode of a GTree;
            relative path expressions (those without a leading <code>/</code> or
            <code>//</code>) start from the <a title="context value" class="termref" href="#dt-context-value">context value</a>.</p><div class="div3">
<h4><a id="id-absolute-path-expressions"/>4.6.1 <a href="#id-absolute-path-expressions" style="text-decoration: none">Absolute Path Expressions</a></h4><p>The expression consisting of <code>/</code> on its own
            is treated as an abbreviation for the 
            <a title="path expression" class="termref" href="#dt-path-expression">path expression</a>
                  <code>/.</code>.</p><p>An expression of the form <code>/<var>PP</var>
                  </code> (that is, a <a title="path expression" class="termref" href="#dt-path-expression">path expression</a>
            with a leading <code>/</code>) is treated as an abbreviation for
	 the expression <code>self::gnode()/(fn:root(.) treat as (document-node()|jnode())/<var>PP</var>
                  </code>. 
            The effect of this expansion is that for every item <var>J</var> 
            in the context value <var>V</var>:</p><ol class="enumar"><li><p>A <a title="type error" class="termref" href="#dt-type-error">type error</a> occurs if <var>J</var> is not a GNode
	       [<a href="#ERRXPTY0020" title="err:XPTY0020">err:XPTY0020</a>].</p></li><li><p>The root GNode <var>R</var> of the GTree containing <var>J</var> is selected.</p></li><li><p>A <a title="type error" class="termref" href="#dt-type-error">type error</a> occurs if <var>R</var> is neither a JNode nor 
	       a document node [<a href="#ERRXPDY0050" title="err:XPDY0050">err:XPDY0050</a>].</p></li><li><p>The expression that follows the leading <code>/</code> is evaluated with 
	       <var>R</var> as the context value.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>If the context value includes a map or array, it is <em>not</em>
            converted implicitly to a JNode; rather, a type error occurs.</p></div><p>The results of these multiple evaluations are then combined into a single sequence;
       if the result is a set of GNodes, the GNodes are delivered in document order with
       duplicates eliminated.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The <code>/</code> character
	 can be used either as a complete expression or as the
	 beginning of a longer <a title="path expression" class="termref" href="#dt-path-expression">path expression</a> such as
	 <code>/*</code>.  Also, <code>*</code>
	 is both the multiply operator and a wildcard in path
	 expressions.  This can cause parsing difficulties when
	 <code>/</code> appears on the left-hand side of
	 <code>*</code>.  This is resolved using the <a href="#parse-note-leading-lone-slash">leading-lone-slash
	 </a> constraint.  For example, <code>/*</code> and <code>/
	 *</code> are valid path expressions containing wildcards,
	 but <code>/*5</code> and <code>/ * 5</code> raise syntax
	 errors. Parentheses must be used when <code>/</code> is
	 used on the left-hand side of an operator that could be confused with a node test, as in <code>(/) * 5</code>. Similarly, <code>4 + / *
	 5</code> raises a syntax error, but <code>4 + (/) * 5</code> is a valid expression.
	 The expression <code>4 + /</code> is also
	 valid, because <code>/</code> does not occur on the left-hand
	 side of the operator.</p><p>Similarly, in the expression <code>/
	 union /*</code>, <code>union</code> is interpreted as an element name
	 rather than an operator. For it to be parsed as an operator,
	 the expression should be written <code>(/)
	 union /*</code>.</p></div><p>An expression of the form <code>//<var>PP</var>
                  </code> (that is, an <a title="absolute path expression" class="termref" href="#dt-absolute-path-expression">absolute path expression</a>
            with a leading <code>//</code>) is treated as an abbreviation for
            the expression <code>self::gnode()/(fn:root(.) treat as (document-node()|jnode())/descendant-or-self::gnode()/<var>PP</var>
                  </code>. 
            The effect of this expansion is that for every item <var>J</var> 
            in the context value <var>V</var>:</p><ol class="enumar"><li><p>A <a title="type error" class="termref" href="#dt-type-error">type error</a> occurs if <var>J</var> is not a GNode
               [<a href="#ERRXPTY0020" title="err:XPTY0020">err:XPTY0020</a>].</p></li><li><p>The root GNode <var>R</var> of the GTree containing <var>J</var> is selected.</p></li><li><p>A <a title="type error" class="termref" href="#dt-type-error">type error</a> occurs if <var>R</var> is neither a JNode nor a document node
               [<a href="#ERRXPDY0050" title="err:XPDY0050">err:XPDY0050</a>].</p></li><li><p>The descendants of <var>R</var> are selected, along with <var>R</var> itself.</p></li><li><p>For every GNode <var>D</var> in this set of GNodes, the expression that 
               follows the leading <code>//</code> is evaluated with <var>D</var> as the context value.</p></li></ol><p>The results of these multiple evaluations are then combined into a single sequence;
            if the result is a set of GNodes, the GNodes are delivered in document order with
            duplicates eliminated.</p><p>Any map or array that is present in the context value is first
            coerced to a JNode by applying the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-jtree"><code>fn:jtree</code></a> function.</p><p>If (after this coercion) the context value is not a sequence of GNodes, a
	 <a title="type error" class="termref" href="#dt-type-error">type error</a> is
	 raised [<a href="#ERRXPTY0020" title="err:XPTY0020">err:XPTY0020</a>]. At evaluation time, if the
	 root GNode of any item in the context value is not a document node or a JNode, a
	 <a title="type error" class="termref" href="#dt-type-error">type error</a> is
	 raised [<a href="#ERRXPDY0050" title="err:XPDY0050">err:XPDY0050</a>].</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The descendants of an XNode do not include attribute
	 nodes. However, the rules for expanding <code>//</code>
            ensure that <code>.//@*</code> selects all attributes of all descendants</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>
                     <code>//</code> on its own is not a valid expression.</p></div></div><div class="div3">
<h4><a id="id-relative-path-expressions"/>4.6.2 <a href="#id-relative-path-expressions" style="text-decoration: none">Relative Path Expressions</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RelativePathExpr"/><code><a href="#prod-xquery40-RelativePathExpr">RelativePathExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-RelativePathExpr-StepExpr">StepExpr</a>  (("/"  |  "//")  <a href="#doc-xquery40-RelativePathExpr-StepExpr">StepExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RelativePathExpr-StepExpr"/><code><a href="#prod-xquery40-StepExpr">StepExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-RelativePathExpr-PostfixExpr">PostfixExpr</a>  |  <a href="#doc-xquery40-RelativePathExpr-AxisStep">AxisStep</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RelativePathExpr-PostfixExpr"/><code><a href="#prod-xquery40-PostfixExpr">PostfixExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-PrimaryExpr">PrimaryExpr</a>  |  <a href="#doc-xquery40-FilterExpr">FilterExpr</a>  |  <a href="#doc-xquery40-DynamicFunctionCall">DynamicFunctionCall</a>  |  <a href="#doc-xquery40-LookupExpr">LookupExpr</a>  |  <a href="#doc-xquery40-MethodCall">MethodCall</a>  |  <a href="#doc-xquery40-FilterExprAM">FilterExprAM</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RelativePathExpr-AxisStep"/><code><a href="#prod-xquery40-AxisStep">AxisStep</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-AbbreviatedStep">AbbreviatedStep</a>  |  <a href="#prod-xquery40-FullStep">FullStep</a>)  <a href="#doc-xquery40-Predicate">Predicate</a>*</code></td></tr></tbody></table><p>
          A <a title="relative path expression" class="termref" href="#dt-relative-path-expression">relative path expression</a> 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).
          </p><p>
          Each non-initial occurrence of <code>//</code> in a path expression is
          expanded as described in <a href="#abbrev"><b>4.6.7 Abbreviated Syntax</b></a>, leaving a
          sequence of steps separated by <code>/</code>. This sequence of steps
          is then evaluated from left to right. So a path such as
          <code>
                     <var>E<sub>1</sub></var>/<var>E<sub>2</sub></var>/<var>E<sub>3</sub></var>/<var>E<sub>4</sub></var>
                  </code> is evaluated
          as <code>((<var>E<sub>1</sub></var>/<var>E<sub>2</sub></var>)/<var>E<sub>3</sub></var>)/<var>E<sub>4</sub></var>
                  </code>. 
               The semantics of a path
          expression are thus defined by the semantics of the
          binary <code>/</code> operator, which is defined in
          <a href="#id-path-operator"><b>4.6.3 Path operator (/)</b></a>.
          </p><div class="note"><p class="prefix"><b>Note:</b></p><p>
         Although the semantics describe the evaluation of a path with
         more than two steps as proceeding from left to right, the <code>/</code>
         operator is in most cases associative, so evaluation from
         right to left usually delivers the same result. The cases
         where <code>/</code> is not associative arise when the functions
         <code>fn:position()</code> and <code>fn:last()</code> are
         used: <code>A/B/position()</code> delivers a sequence of
         integers from 1 to the size of <code>(A/B)</code>, whereas
         <code>A/(B/position())</code> restarts the counting at each <code>B</code> element.
         </p></div><p>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.</p><div class="example"><ul><li><p>
                           <code>child::div1/child::para</code>
                        </p><p>Selects the
	     <code>para</code> element children of the <code>div1</code>
	     element children of the context node; that is, the
	     <code>para</code> element grandchildren of the context node
	     that have <code>div1</code> parents.</p></li></ul></div><div class="note"><p class="prefix"><b>Note:</b></p><p>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.</p></div></div><div class="div3">
<h4><a id="id-path-operator"/>4.6.3 <a href="#id-path-operator" style="text-decoration: none">Path operator (<code>/</code>)</a></h4><p>The path operator <code>/</code> is primarily used for 
                  locating GNodes within GTrees. The value of the left-hand operand
                  may include maps and arrays; such items are implicitly converted to JNodes
                  as if by a call on the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-jtree"><code>fn:jtree</code></a> function.
                  After this conversion, the left-hand operand must return 
                  a sequence of GNodes. The result of the operator is either a sequence of GNodes
                  (in document order, with no duplicates), or a sequence of non-GNodes.</p><p>The operation <code>
                     <var>E<sub>1</sub></var>/<var>E<sub>2</sub></var>
                  </code> is evaluated as follows: Expression <var>E<sub>1</sub></var> 
                  is evaluated. Any maps or arrays in the result are converted to JNodes
                  by applying the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-jtree"><code>fn:jtree</code></a> function. If the result is not a 
                  (possibly empty) sequence <var>S</var> of GNodes, 
                  a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0019" title="err:XPTY0019">err:XPTY0019</a>]. Each GNode in <var>S</var> then serves in turn to provide an inner focus 
                  (the GNode as the context value, its position in <var>S</var> as the context 
                  position, the length of <code>S</code> as the context size) for an evaluation 
                  of <var>E<sub>2</sub></var>, as described in  <a href="#eval_context"><b>2.2.2 Dynamic Context</b></a>. The sequences resulting from all the evaluations of <var>E<sub>2</sub></var> 
                  are combined as follows:</p><ol class="enumar"><li><p>If every evaluation of <var>E<sub>2</sub></var> returns a (possibly empty) sequence of GNodes, 
                        these sequences are combined, and duplicate GNodes are eliminated based on GNode identity.
                        The resulting GNode sequence is returned in <a title="document order" class="termref" href="#dt-document-order">document order</a>.
                     </p></li><li><p>If every evaluation of <var>E<sub>2</sub></var> returns a (possibly empty) 
                        sequence of non-GNodes, these sequences are concatenated, in order, and returned.
                        The returned sequence preserves the orderings within and among the subsequences 
                        generated by the evaluations of <var>E<sub>2</sub></var>.
                     </p><div class="note"><p class="prefix"><b>Note:</b></p><p>The use of <a title="path expression" class="termref" href="#dt-path-expression">path expressions</a> 
                        to select values other than GNodes is for
                     backwards compatibility. Generally it is preferable to use the simple mapping
                     operator <code>!</code> for this purpose. For example, write <code>$nodes!node-name()</code>
                     in preference to <code>$nodes/node-name()</code>.</p></div></li><li><p>If the multiple evaluations of <var>E<sub>2</sub></var> return at least one GNode and at least one non-GNode, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0018" title="err:XPTY0018">err:XPTY0018</a>].</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>The semantics of the path operator can also be defined using the simple 
                     map operator (<code>!</code>) as follows (the function
                     <code>fn:distinct-ordered-nodes($R)</code> has the effect of 
                     eliminating duplicates and sorting nodes into document order):</p><div class="exampleInner"><pre>let $R := E1 ! E2
return if (every $r in $R satisfies $r instance of gnode())
       then (fn:distinct-ordered-nodes($R))
       else if (every $r in $R satisfies not($r instance of gnode()))
       then $R
       else error()</pre></div><p>For a table comparing the step operator to the map operator, see <a href="#id-map-operator"><b>4.23 Simple map operator (!)</b></a>.</p></div></div><div class="div3">
<h4><a id="id-axis-steps"/>4.6.4 <a href="#id-axis-steps" style="text-decoration: none">Axis Steps</a></h4>
<a id="d2e22122"/><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AxisStep"/><code><a href="#prod-xquery40-AxisStep">AxisStep</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-AxisStep-AbbreviatedStep">AbbreviatedStep</a>  |  <a href="#doc-xquery40-AxisStep-FullStep">FullStep</a>)  <a href="#doc-xquery40-AxisStep-Predicate">Predicate</a>*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AxisStep-AbbreviatedStep"/><code><a href="#prod-xquery40-AbbreviatedStep">AbbreviatedStep</a></code></td><td>::=</td><td><code>".."  |  ("@"  <a href="#doc-xquery40-AxisStep-NodeTest">NodeTest</a>)  |  <a href="#prod-xquery40-SimpleNodeTest">SimpleNodeTest</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AxisStep-FullStep"/><code><a href="#prod-xquery40-FullStep">FullStep</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-AxisStep-Axis">Axis</a>
                        <a href="#doc-xquery40-AxisStep-NodeTest">NodeTest</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AxisStep-Axis"/><code><a href="#prod-xquery40-Axis">Axis</a></code></td><td>::=</td><td><code>("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")  "::"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AxisStep-NodeTest"/><code><a href="#prod-xquery40-NodeTest">NodeTest</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-UnionNodeTest">UnionNodeTest</a>  |  <a href="#prod-xquery40-SimpleNodeTest">SimpleNodeTest</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AxisStep-Predicate"/><code><a href="#prod-xquery40-Predicate">Predicate</a></code></td><td>::=</td><td><code>"["  <a href="#doc-xquery40-Expr">Expr</a>  "]"</code></td></tr></tbody></table><p>
                  [<a id="dt-axis-step" title="axis step">Definition</a>: An <b>axis step</b> is an instance of the production
                  <a href="#doc-xquery40-AxisStep">AxisStep</a>: 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
		<b>axis</b>, which defines the direction of
		movement for the step, a <a title="node test" class="termref" href="#dt-node-test">node test</a>,
		which selects GNodes based on their properties, and zero or more predicates which are used
               to filter the results.]
               </p><div class="note"><p class="prefix"><b>Note:</b></p><p>An <a title="axis step" class="termref" href="#dt-axis-step">axis step</a> is an expression in its own right.
               While axis steps are often used as the operands of 
               <a title="path expression" class="termref" href="#dt-path-expression">path expressions</a>,
            they can also appear in other contexts (without a <code>/</code> or <code>//</code>
            operator); equally, the operands of a path expression can be any expression,
            not restricted to an <a title="axis step" class="termref" href="#dt-axis-step">axis step</a>.</p></div><p>If the context value for an <a title="axis step" class="termref" href="#dt-axis-step">axis step</a> includes a map or array, this is implicitly
               converted to a JNode as if by applying the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-jtree"><code>fn:jtree</code></a> function.
               If, after this conversion, the sequence contains a value that is not a GNode, 
               a <a title="type error" class="termref" href="#dt-type-error">type error</a> is
		         raised [<a href="#ERRXPTY0020" title="err:XPTY0020">err:XPTY0020</a>]. The result of evaluating the axis step
               is a sequence of zero or more GNodes.</p><p>The <a title="axis step" class="termref" href="#dt-axis-step">axis step</a>
                  <code>S</code> is equivalent to <code>./S</code>.
               Thus, if the context value is a sequence containing multiple GNodes,
               the semantics of a <a title="axis step" class="termref" href="#dt-axis-step">axis step</a> are equivalent to a <a title="path expression" class="termref" href="#dt-path-expression">path expression</a>
               in which the step is always applied to a single GNode. The following
               description therefore explains the semantics for the case where
               the context value is a single GNode, called the <b>origin</b>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The equivalence of a <a title="axis step" class="termref" href="#dt-axis-step">axis step</a>
                     <code>S</code> to the
            <a title="path expression" class="termref" href="#dt-path-expression">path expression</a>
                     <code>./S</code> means that 
            the resulting GNode sequence is returned in <a title="document order" class="termref" href="#dt-document-order">document
	         order</a>.</p></div><p>In the <b>abbreviated syntax</b> for a step, the axis can
		be omitted and other shorthand notations can be used as described in
		<a href="#abbrev"><b>4.6.7 Abbreviated Syntax</b></a>.</p><p>The unabbreviated syntax for an axis step consists of the axis name
		and node test separated by a double colon. The result of the step consists of the GNodes
		reachable from the origin via the specified axis that match the node test. For example, the
		step <code>child::para</code> selects the <code>para</code> element children of the origin XNode: 
               <code>child</code> is the name of the axis, and <code>para</code> is the name of the element nodes 
               to be selected on this axis. The available axes are described in <a href="#axes"><b>4.6.4.1 Axes</b></a>. The
		available node tests are described in <a href="#node-tests"><b>4.6.4.2 Node Tests</b></a>. Examples of
		steps are provided in <a href="#unabbrev"><b>4.6.6 Unabbreviated Syntax</b></a> and <a href="#abbrev"><b>4.6.7 Abbreviated Syntax</b></a>.</p><div class="div4">
<h5><a id="axes"/>4.6.4.1 <a href="#axes" style="text-decoration: none">Axes</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#node-tests">⬇</a> <a href="#id-path-expressions">⬆</a></p><ol><li><p>
                     Four new axes have been defined: <code>preceding-or-self</code>, <code>preceding-sibling-or-self</code>,
                     <code>following-or-self</code>, and <code>following-sibling-or-self</code>.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1519">1519</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1532">1532</a> 29 October 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Axis"/><code><a href="#prod-xquery40-Axis">Axis</a></code></td><td>::=</td><td><code>("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")  "::"</code></td></tr></tbody></table><p>An axis is essentially a function that takes a GNode (the origin)
               as input, and delivers a sequence of GNodes (always from within the same
               GTree as the origin) as its result.</p><p>XQuery supports the following axes:</p><ul><li><p>The <code>child</code> axis
				contains the children of the origin.</p><p>If the origin is an XNode, these are the XNodes returned by the
				<a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#dm-children">7.6.3 children Accessor</a> accessor.
                                </p><div class="note"><p class="prefix"><b>Note:</b></p><p>In an XTree, only document nodes and element
                        nodes have children. If the origin is any
                         other kind of XNode, or if the origin is an empty
                         document or element node, then the child
                         axis returns an empty sequence.  The
                         children of a document node or element node may be
                         element, processing instruction, comment, or text
                         nodes.  Attribute, namespace, and
                         document nodes can never appear as children.</p></div><p>If the origin is a JNode, these are the JNodes returned
                     by the <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-j-children">j-children</a><sup><small>DM</small></sup> accessor.</p></li><li><p>The <code>descendant</code>
			 axis is defined as the transitive closure of
			 the child axis; it contains the descendants
			 of the origin (the children, the children of the children, and so on).</p><p>More formally, <code>$node/descendant::gnode()</code> delivers the result
                     of <code>fn:transitive-closure($node, fn { child::gnode() })</code>.</p></li><li><p>The <code>descendant-or-self</code> axis contains the origin and the descendants 
                        of the origin.</p><p>More formally, <code>$node/descendant-or-self::gnode()</code> delivers the result
                     of <code>$node/(. | descendant::gnode())</code>.</p></li><li><p>The <code>parent</code> axis returns the parent of the origin.</p><p>If the origin is an XNode, this is the result of the 
				          <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#dm-parent">7.6.11 parent Accessor</a> accessor.</p><p>If the origin is a JNode, this is the value of the
                     <b>·parent·</b> property of the origin.</p><p>If the GNode has no parent, the axis returns an empty sequence.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>An attribute node may have an element node as its parent, 
                           even though the attribute node is not a child of the element node.</p></div></li><li><p>The <code>ancestor</code> axis is
                        defined as the transitive closure of the parent axis; it
                        contains the ancestors of the origin (the parent, the
                        parent of the parent, and so on).</p><p>More formally, <code>$node/ancestor::gnode()</code> delivers the result
                     of <code>fn:transitive-closure($node, fn { parent::gnode() })</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The ancestor axis includes the root GNode of the
                           GTree in which the origin is found, unless the origin is 
                           itself the root GNode.</p></div></li><li><p>The <code>ancestor-or-self</code> axis contains the origin and the ancestors of the origin;
				            thus, the ancestor-or-self axis will always include the root.</p><p>More formally, <code>$node/ancestor-or-self::gnode()</code> delivers the result
                     of <code>$node/(. | ancestor::gnode())</code>.</p></li><li><p>The <code>following-sibling</code>
			 axis returns the origin’s following
			 siblings, that is, those children of the origin’s parent that occur after the origin in <a title="document order" class="termref" href="#dt-document-order">document order</a>. If the origin
			 is an attribute or namespace node, the
			 <code>following-sibling</code> axis is
			 empty.</p><p>More formally, <code>$node/following-sibling::gnode()</code> delivers the result
                     of <code>fn:siblings($node)[. &gt;&gt; $node])</code>.</p></li><li><p>The <code>following-sibling-or-self</code> axis contains the origin,
                     together with the contents of the <code>following-sibling</code> axis.</p><p>More formally, <code>$node/following-sibling-or-self::gnode()</code> delivers the result
                     of <code>fn:siblings($node)[not(. &lt;&lt; $node)]</code>
                        </p></li><li><p>The <code>preceding-sibling</code>
			 axis returns the origin’s preceding
			 siblings, that is, those children of the origin’s parent that occur before the context
			 node in <a title="document order" class="termref" href="#dt-document-order">document order</a>. If the origin
			 is an attribute or namespace node, the
			 <code>preceding-sibling</code> axis is
			 empty.</p><p>More formally, <code>$node/preceding-sibling::gnode()</code> delivers the result
                     of <code>fn:siblings($node)[. &lt;&lt; $node]</code>.</p></li><li><p>The <code>preceding-sibling-or-self</code> axis contains the origin,
                     together with the contents of the <code>preceding-sibling</code> axis.</p><p>More formally, <code>$node/preceding-sibling-or-self::gnode()</code> delivers the result
                     of <code>fn:siblings($node)[not(. &gt;&gt; $node)</code>.</p></li><li><p>The <code>following</code> axis
				contains all 
				descendants of the root of the GTree in
				which the origin is found, are
				not descendants of the origin,
				and occur after the origin in
				<a title="document order" class="termref" href="#dt-document-order">document order</a>.
                     </p><p>More formally, <code>$node/following::gnode()</code> delivers the result
                     of <code>$node/ancestor-or-self::gnode()/following-sibling::gnode()/descendant-or-self::gnode()</code>
                        </p></li><li><p>The <code>following-or-self</code> axis contains the origin,
                     together with the contents of the <code>following</code> axis.</p><p>More formally, <code>$node/following-or-self::gnode()</code> delivers the result
                     of <code>$node/(. | following::gnode())</code>.</p></li><li><p>The <code>preceding</code> axis
				returns all 
				descendants of the root of the GTree in
				which the origin is found, are
				not ancestors of the origin, and
				occur before the origin in
				<a title="document order" class="termref" href="#dt-document-order">document order</a>.
                     </p><p>More formally, <code>$node/preceding::gnode()</code> delivers the result
                     of <code>$node/ancestor-or-self::gnode()/preceding-sibling::gnode()/descendant-or-self::gnode()</code>.</p></li><li><p>The <code>preceding-or-self</code> axis returns the origin,
                     together with the contents of the <code>preceding</code> axis.</p><p>More formally, <code>$node/preceding-or-self::gnode()</code> delivers the result
                     of <code>$node/(. | preceding::gnode())</code>.</p></li><li><p>The <code>attribute</code> axis is defined only for XNodes.
			 It returns the attributes of the origin,
			 which are the nodes returned by the
			 <span>
                              <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#dm-attributes">7.6.1 attributes Accessor</a>
                           </span>; the axis will be
			 empty unless the context node is an
			 element.</p><p>If the <code>attribute</code> axis is applied to a JNode,
                     a type error [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>] is raised.</p></li><li><p>The <code>self</code> axis contains just the origin itself.</p><p>The <code>self</code> axis is primarily useful when testing whether the origin
                     satisfies particular conditions, for example <code>if ($x[self::chapter])</code>.</p><p>More formally, <code>$node/self::gnode()</code> delivers the result
                     of <code>$node</code>.</p></li></ul><p>Axes can be categorized as <b>forward axes</b> and
		  <b>reverse axes</b>. An axis that only ever contains the origin or
		  nodes that are after the context node in <a title="document order" class="termref" href="#dt-document-order">document order</a> is a forward axis. An
		  axis that only ever contains the context node or nodes that are before the
		  context node in <a title="document order" class="termref" href="#dt-document-order">document order</a> is a reverse axis.</p><p>The <code>parent</code>, <code>ancestor</code>, <code>ancestor-or-self</code>, 
                  <code>preceding</code>, <code>preceding-or-self</code>, 
                  <code>preceding-sibling</code>, and <code>preceding-sibling-or-self</code> axes 
                  are reverse axes; all other axes are forward axes.</p><p>The <code>ancestor</code>, <code>descendant</code>, 
                  <code>following</code>, <code>preceding</code> and <code>self</code> axes partition a GTree (ignoring attribute  nodes):
		  they do not overlap and together they contain all the GNodes in the
		  GTree.</p><p>
                     [<a id="dt-principal-node-kind" title="principal node kind">Definition</a>: Every axis has a <b>principal node kind</b>. 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.] Thus:</p><ul><li><p>For the attribute axis, the principal node kind is
				attribute.</p></li><li><p>For all other axes, the principal node kind is element.</p></li></ul></div><div class="div4">
<h5><a id="node-tests"/>4.6.4.2 <a href="#node-tests" style="text-decoration: none">Node Tests</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#implausible-axis-steps">⬇</a> <a href="#axes">⬆</a></p><ol><li><p>
                     If the default namespace for elements and types has the special value <code>##any</code>,
                     then an unprefixed name in a <code>NameTest</code> acts as a wildcard, matching
                     names in any namespace or none.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/296">296</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1181">1181</a> 30 April 2024]</i></p></li></ol></div><p>
                     [<a id="dt-node-test" title="node test">Definition</a>: A <b>node test</b> is a condition 
                     on the properties of a <a title="GNode" class="termref" href="#dt-GNode">GNode</a>. 
      A node test determines which GNodes returned by an axis are selected by a <a title="step" class="termref" href="#dt-step">step</a>.]
                  </p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeTest"/><code><a href="#prod-xquery40-NodeTest">NodeTest</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-NodeTest-UnionNodeTest">UnionNodeTest</a>  |  <a href="#doc-xquery40-NodeTest-SimpleNodeTest">SimpleNodeTest</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeTest-UnionNodeTest"/><code><a href="#prod-xquery40-UnionNodeTest">UnionNodeTest</a></code></td><td>::=</td><td><code>"("  (<a href="#doc-xquery40-NodeTest-SimpleNodeTest">SimpleNodeTest</a> ++ "|")  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeTest-SimpleNodeTest"/><code><a href="#prod-xquery40-SimpleNodeTest">SimpleNodeTest</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-NodeTest-TypeTest">TypeTest</a>  |  <a href="#doc-xquery40-NodeTest-Selector">Selector</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeTest-TypeTest"/><code><a href="#prod-xquery40-TypeTest">TypeTest</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-RegularItemType">RegularItemType</a>  |  ("type"  "("  <a href="#doc-xquery40-SequenceType">SequenceType</a>  ")")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeTest-Selector"/><code><a href="#prod-xquery40-Selector">Selector</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-NodeTest-EQName">EQName</a>  |  <a href="#doc-xquery40-NodeTest-Wildcard">Wildcard</a>  |  ("get"  "("  <a href="#doc-xquery40-NodeTest-ExprSingle">ExprSingle</a>  ")")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeTest-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeTest-Wildcard"/><code><a href="#prod-xquery40-Wildcard">Wildcard</a></code></td><td>::=</td><td><code>"*"<br/>|  (<a href="#prod-xquery40-NCName">NCName</a>  ":*")<br/>|  ("*:"  <a href="#prod-xquery40-NCName">NCName</a>)<br/>|  (<a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>  "*")</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeTest-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                           <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                           <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                           <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                           <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                           <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                           <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                        </code></td></tr></tbody></table><p>Node tests fall into three categories:</p><ul><li><p>Type tests, which test the type of the GNode;</p></li><li><p>Selectors, which act as keys used to identify the GNode
                     among its siblings (in the case of XNodes, this is the node name);</p></li><li><p>Union node tests, which provide multiple conditions: a GNode satisfies
                  the union node test if it satisfies any of its operand node tests.</p></li></ul><p>A <a href="#prod-xquery40-UnionNodeTest">UnionNodeTest</a> matches a node <var>N</var>
                  if at least one of the constituent <a href="#prod-xquery40-SimpleNodeTest">SimpleNodeTest</a>s matches <var>N</var>.</p><p>For example, <code>(div1|div2|div3)</code> matches a node named <code>div1</code>, <code>div2</code>, or <code>div3</code>
                  </p><p>The semantics of selectors varies between XNodes and JNodes, so the two
               cases are described separately.</p></div><div class="div4">
<h5><a id="id-selectors-for-xnodes"/>4.6.4.3 <a href="#id-selectors-for-xnodes" style="text-decoration: none">Selectors for XNodes</a></h5><p>This section describes the semantics of a name test in the case
               where the origin is an XNode.</p><p>
                     [<a id="dt-name-test" title="name test">Definition</a>: A node test that consists only of an EQName or a
		  Wildcard is called a <b>name test</b>.]
                  </p><p>A node test written as an NCName is expanded as follows:</p><ul><li><p>If the principal node kind of the axis step is <code>element</code>, 
                  using the <a title="element name matching rule" class="termref" href="#dt-element-name-matching-rule">element name matching rule</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>If the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> has the
                     special value <code>"##any</code>, the result of the expanding an unprefixed name
                  <var>NN</var> is the wildcard <code>*:<var>NN</var>
                              </code>.</p></div></li><li><p>Otherwise, using the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.</p></li></ul><p>If the expanded node test is an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>
                     <var>Q</var>, then it
               matches a node <var>N</var> if and only if the <b>kind</b> of
                  node <var>N</var> is the <a title="principal node kind" class="termref" href="#dt-principal-node-kind">principal node kind</a> for the step axis and the
		  <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> of the node is equal (as defined by the <code>eq</code> operator) to <var>Q</var>. For
		  example, <code>child::para</code>
		  selects the <code>para</code> element children of
		  the context node; if the context node has no
		  <code>para</code> children, it selects an empty set
		  of nodes. <code>attribute::abc:href</code> selects
		  the attribute of the context node with the QName
		  <code>abc:href</code>; if the context node has no
		  such attribute, it selects an empty set of
		  nodes.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>A name test is not satisfied by an element node whose name does not match the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> of the name test, even if it is in a <a title="substitution group" class="termref" href="#dt-substitution-group">substitution group</a> whose head is the named element.</p></div><p>Wildcard node tests are interpreted as follows:</p><ul><li><p>The node test <code>*</code> is true for any node of the
		  <a title="principal node kind" class="termref" href="#dt-principal-node-kind">principal node
		  kind</a> of the step axis. For example, <code>child::*</code> will select all element
		  children of the context node, and <code>attribute::*</code> will select all
		  attributes of the context node.</p></li><li><p>A node test can have the form
		  <code>NCName:*</code>. In this case, the prefix is
		  expanded in the same way as with a <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>, using the
		  <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known
		  namespaces</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>. If
		  the prefix is not found in the statically known namespaces,
		  a <a title="static error" class="termref" href="#dt-static-error">static
		  error</a> is raised [<a href="#ERRXPST0081" title="err:XPST0081">err:XPST0081</a>].
		  The node test is true for any node of the <a title="principal node kind" class="termref" href="#dt-principal-node-kind">principal
		  node kind</a> of the step axis whose <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> has the namespace URI
		  to which the prefix is bound, regardless of the
		  local part of the name.</p></li><li><p>A node test can contain a <a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>, for example
		  <code>Q{http://example.com/msg}*</code>. Such a node test is true for any node of the principal 
                  node kind of the step axis whose <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> has the namespace URI specified in 
                  the <a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>, regardless of the local part of the name.</p></li><li><p>A node test can also
		  have the form <code>*:NCName</code>. In this case,
		  the node test is true for any node of the <a title="principal node kind" class="termref" href="#dt-principal-node-kind">principal
		  node kind</a> of the step axis whose local name matches the given NCName,
		  regardless of its namespace or lack of a namespace.</p></li></ul><p>A selector can also take the form <code>get(<var>E</var>)</code>
                  where <var>E</var> is an <a href="#doc-xquery40-ExprSingle">ExprSingle</a>.
               The contained expression <var>E</var> is evaluated with an
                  <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>
                     <a title="focus" class="termref" href="#dt-focus">focus</a>. 
                  An XNode satisfies the selector if its node kind is the principal
                  node kind of the axis and its node name
                  is equal to one of the values (necessarily an <code>xs:QName</code>)
                  present in the atomized value of the selector expression.</p><p>That is, if the context item is an XNode, then 
                  <code>
                        <var>Axis</var>::get(<var>E</var>)</code> returns the result
               of the expression:</p><div class="exampleInner"><pre>let $selector := fn(){ data(<var>E</var>) }()
return <var>Axis</var>::*[some($selector, atomic-equal(?, node-name()))]</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The purpose of evaluating <var>E</var> within the body of
                  an anonymous inline function is to ensure that it is evaluated
                  with an absent focus.</p><p>It is not an error if the atomized value of <var>E</var>
               includes atomic items that are not <code>xs:QName</code> values:
               such values are effectively ignored.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Unnamed nodes (such as text nodes) will never be selected</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The result is in document order. The order of items in
               the result of the selector expression is immaterial.</p></div><p>For example, <code>child::get((#body, #x:body))</code> selects
               all child elements whose name is one of the QName values <code>body</code>
               or <code>x:body</code>. Note that the evaluation of QName literals
               is not sensitive to the default namespace for elements and types.</p><p>A further example: <code>descendant::(get(#para) | text())</code> returns
               all descendants of the context node that are either elements named
               <code>para</code> (in no namespace) or text nodes; the results are in document order.</p></div><div class="div4">
<h5><a id="id-selectors-for-JNodes"/>4.6.4.4 <a href="#id-selectors-for-JNodes" style="text-decoration: none">Selectors for JNodes</a></h5><p>When the origin is a JNode, the selector filters the JNodes returned
               by the axis according to the JNode's <b>·selector·</b> property.
               In the case of a JNode that wraps an entry in a map, this can be any
               atomic value; for a JNode that wraps a member of an array, it will
               be a non-negative integer.</p><p>If the selector takes the form <code>*</code>, then it matches
               every JNode (including one whose <b>·selector·</b> property
               is absent).</p><p>If the selector takes the form of an <code>NCName</code>, then it matches
               every JNode whose <b>·selector·</b> property is an atomic item
                  (necessarily an <code>xs:string</code>, <code>xs:anyURI</code>
                  or <code>xs:untypedAtomic</code> value) that is equal to this <code>NCName</code>
                  under the rules of the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-atomic-equal"><code>fn:atomic-equal</code></a> function.</p><p>If the selector takes the form of any other <code>EQName</code> or wildcard,
               then it matches every JNode whose <b>·selector·</b> property is a matching 
                  <code>xs:QName</code>, using the same rules as for wildcards in XNode steps
               (see <a href="#id-selectors-for-xnodes"><b>4.6.4.3 Selectors for XNodes</b></a>).</p><p>If the selector takes the form <code>get(<var>E</var>)</code>,
                  where <var>E</var> is an <a href="#doc-xquery40-ExprSingle">ExprSingle</a>,
               the contained expression <var>E</var> is evaluated with an
                  <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>
                     <a title="focus" class="termref" href="#dt-focus">focus</a>. 
                  A JNode satisfies the selector if the value of its 
                  <b>·selector·</b> property is equal to one of the values
                  present in the atomized value of the selector expression <var>E</var>, under the rules
                  of the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-atomic-equal"><code>atomic-equal</code></a> function.</p><p>That is, if the context item is a JNode, then 
                  <code>
                        <var>Axis</var>::get(<var>E</var>)</code> returns the result
               of the expression:</p><div class="exampleInner"><pre>let $selector := fn(){ data(&lt;var&gt;E&lt;/var&gt;) }()
return &lt;var&gt;Axis&lt;/var&gt;::*[some($selector, atomic-equal(?, jnode-selector()))]</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The purpose of evaluating <var>E</var> within the body of
                  an anonymous inline function is to ensure that it is evaluated
                  with an absent focus.</p><p>It is not an error if the atomized value of <var>E</var>
               includes atomic items that select nothing: such values are effectively ignored.
               This is true both for maps and arrays.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The result is in document order. The order of items in
               the result of the selector expression is immaterial.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>A performant implementation might reasonably be expected,
               at least in the case where the value of the selector is a single
               atomic item, to select an entry in a map or a member in an array
               in constant time.</p></div><p>For example:</p><ul><li><p>
                           <code>child::code</code> selects
               an entry in a map whose key is the string <code>"code"</code>
                        </p></li><li><p>
                           <code>child::get("date of birth")</code> selects
               an entry in a map whose key is the string <code>"date of birth"</code>
                        </p></li><li><p>
                           <code>child::get(3)</code> selects the third member
                  of an array</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The same result can be achieved using the expression <code>child::*[3]</code>.</p></div></li><li><p>
                           <code>child::get(1 to 3)</code> selects the first three members
                  of an array, in document order.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>
                              <code>child::get((3, 2, 1))</code> also returns the first three
                  members in document order.</p></div></li><li><p>
                           <code>child::get(current-date())</code>
               selects an entry in a map whose key is an <code>xs:date</code> value
               equal to the current date.</p></li></ul><p>All the above expressions return a sequence of JNodes. If the containing
               expression expects atomic values, then the JNodes are automatically atomized.</p></div><div class="div4">
<h5><a id="id-type-tests"/>4.6.4.5 <a href="#id-type-tests" style="text-decoration: none">Type Tests</a></h5><p>
                     [<a id="dt-kind-test" title="kind test">Definition</a>: An alternative
		  form of a node test called a
		  <b>type test</b> can select XNodes based
		  on their type, or in the case of JNodes, the type of their
                  contained <b>·content·</b>
                     ].</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest"/><code><a href="#prod-xquery40-TypeTest">TypeTest</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-TypeTest-RegularItemType">RegularItemType</a>  |  ("type"  "("  <a href="#doc-xquery40-TypeTest-SequenceType">SequenceType</a>  ")")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-RegularItemType"/><code><a href="#prod-xquery40-RegularItemType">RegularItemType</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-TypeTest-AnyItemTest">AnyItemTest</a>  |  <a href="#doc-xquery40-TypeTest-NodeKindTest">NodeKindTest</a>  |  <a href="#doc-xquery40-TypeTest-GNodeType">GNodeType</a>  |  <a href="#doc-xquery40-TypeTest-JNodeType">JNodeType</a>  |  <a href="#doc-xquery40-TypeTest-MapType">MapType</a>  |  <a href="#doc-xquery40-TypeTest-ArrayType">ArrayType</a>  |  <a href="#doc-xquery40-TypeTest-RecordType">RecordType</a>  |  <a href="#doc-xquery40-TypeTest-EnumerationType">EnumerationType</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-AnyItemTest"/><code><a href="#prod-xquery40-AnyItemTest">AnyItemTest</a></code></td><td>::=</td><td><code>"item"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-NodeKindTest"/><code><a href="#prod-xquery40-NodeKindTest">NodeKindTest</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-TypeTest-DocumentTest">DocumentTest</a>
                           <br/>|  <a href="#doc-xquery40-TypeTest-ElementTest">ElementTest</a>
                           <br/>|  <a href="#doc-xquery40-TypeTest-AttributeTest">AttributeTest</a>
                           <br/>|  <a href="#doc-xquery40-TypeTest-SchemaElementTest">SchemaElementTest</a>
                           <br/>|  <a href="#doc-xquery40-TypeTest-SchemaAttributeTest">SchemaAttributeTest</a>
                           <br/>|  <a href="#doc-xquery40-TypeTest-PITest">PITest</a>
                           <br/>|  <a href="#doc-xquery40-TypeTest-CommentTest">CommentTest</a>
                           <br/>|  <a href="#doc-xquery40-TypeTest-TextTest">TextTest</a>
                           <br/>|  <a href="#doc-xquery40-TypeTest-NamespaceNodeTest">NamespaceNodeTest</a>
                           <br/>|  <a href="#doc-xquery40-TypeTest-AnyNodeKindTest">AnyNodeKindTest</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-DocumentTest"/><code><a href="#prod-xquery40-DocumentTest">DocumentTest</a></code></td><td>::=</td><td><code>"document-node"  "("  (<a href="#doc-xquery40-TypeTest-ElementTest">ElementTest</a>  |  <a href="#doc-xquery40-TypeTest-SchemaElementTest">SchemaElementTest</a>  |  <a href="#doc-xquery40-TypeTest-NameTestUnion">NameTestUnion</a>)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-ElementTest"/><code><a href="#prod-xquery40-ElementTest">ElementTest</a></code></td><td>::=</td><td><code>"element"  "("  (<a href="#doc-xquery40-TypeTest-NameTestUnion">NameTestUnion</a>  (","  <a href="#prod-xquery40-TypeName">TypeName</a>  "?"?)?)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-SchemaElementTest"/><code><a href="#prod-xquery40-SchemaElementTest">SchemaElementTest</a></code></td><td>::=</td><td><code>"schema-element"  "("  <a href="#prod-xquery40-ElementName">ElementName</a>  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-NameTestUnion"/><code><a href="#prod-xquery40-NameTestUnion">NameTestUnion</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-TypeTest-NameTest">NameTest</a> ++ "|")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-NameTest"/><code><a href="#prod-xquery40-NameTest">NameTest</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-EQName">EQName</a>  |  <a href="#prod-xquery40-Wildcard">Wildcard</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-AttributeTest"/><code><a href="#prod-xquery40-AttributeTest">AttributeTest</a></code></td><td>::=</td><td><code>"attribute"  "("  (<a href="#doc-xquery40-TypeTest-NameTestUnion">NameTestUnion</a>  (","  <a href="#prod-xquery40-TypeName">TypeName</a>)?)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-SchemaAttributeTest"/><code><a href="#prod-xquery40-SchemaAttributeTest">SchemaAttributeTest</a></code></td><td>::=</td><td><code>"schema-attribute"  "("  <a href="#prod-xquery40-AttributeName">AttributeName</a>  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-PITest"/><code><a href="#prod-xquery40-PITest">PITest</a></code></td><td>::=</td><td><code>"processing-instruction"  "("  (<a href="#prod-xquery40-NCName">NCName</a>  |  <a href="#doc-xquery40-TypeTest-StringLiteral">StringLiteral</a>)?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#ws-explicit">ws: explicit</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-CommentTest"/><code><a href="#prod-xquery40-CommentTest">CommentTest</a></code></td><td>::=</td><td><code>"comment"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-TextTest"/><code><a href="#prod-xquery40-TextTest">TextTest</a></code></td><td>::=</td><td><code>"text"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-NamespaceNodeTest"/><code><a href="#prod-xquery40-NamespaceNodeTest">NamespaceNodeTest</a></code></td><td>::=</td><td><code>"namespace-node"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-AnyNodeKindTest"/><code><a href="#prod-xquery40-AnyNodeKindTest">AnyNodeKindTest</a></code></td><td>::=</td><td><code>"node"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-GNodeType"/><code><a href="#prod-xquery40-GNodeType">GNodeType</a></code></td><td>::=</td><td><code>"gnode"  "("  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-JNodeType"/><code><a href="#prod-xquery40-JNodeType">JNodeType</a></code></td><td>::=</td><td><code>"jnode"  "("  <a href="#doc-xquery40-TypeTest-SequenceType">SequenceType</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-MapType"/><code><a href="#prod-xquery40-MapType">MapType</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-AnyMapType">AnyMapType</a>  |  <a href="#prod-xquery40-TypedMapType">TypedMapType</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-ArrayType"/><code><a href="#prod-xquery40-ArrayType">ArrayType</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-AnyArrayType">AnyArrayType</a>  |  <a href="#prod-xquery40-TypedArrayType">TypedArrayType</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-RecordType"/><code><a href="#prod-xquery40-RecordType">RecordType</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-AnyRecordType">AnyRecordType</a>  |  <a href="#prod-xquery40-TypedRecordType">TypedRecordType</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-EnumerationType"/><code><a href="#prod-xquery40-EnumerationType">EnumerationType</a></code></td><td>::=</td><td><code>"enum"  "("  (<a href="#doc-xquery40-TypeTest-StringLiteral">StringLiteral</a> ++ ",")  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeTest-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                           <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody></table><p>The most general form of type test uses the syntax 
           <code>type(<var>SequenceType</var>)</code>. This selects:</p><ul><li><p>XNodes that are instances of the supplied <var>SequenceType</var>;</p></li><li><p>JNodes whose <b>·content·</b> property is an instance of the 
              supplied <var>SequenceType</var>.</p></li></ul><p>For the most commonly encountered types, this syntax can be abbreviated: for example
           <code>node()</code>, <code>text()</code>, <code>array(*)</code>, and <code>record(x, y)</code>
           can be written directly without the enclosing <code>type(...)</code>.</p><p>If the origin is an XNode the type used will normally be a 
           <a href="#prod-xquery40-NodeKindTest">NodeKindTest</a> such as <code>node()</code>
           or <code>comment()</code>. Specifying a type that cannot select nodes,
           such as <code>map(*)</code>, is allowed but pointless.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>If <var>T</var> is a <a href="#prod-xquery40-NodeKindTest">NodeKindTest</a>, there is
        a subtle difference between the expressions <code>$N/T</code> and
        <code>$N/type(T)</code>: if no explicit axis is specified, and if <var>T</var>
        is in the form <code>attribute(N)</code> or <code>schema-attribute(N)</code>, this
        changes the default axis to be the attribute axis; and similarly for tests implicitly
        using the namespace axis. This rule does not apply when the step is
        written as <code>type(attribute(N))</code> or <code>type(schema-attribute(N))</code>.
        Such constructs make sense, for example, when selecting members of an array that
        are XNodes: the expressions <code>$array/type(element(*))</code> and <code>$array/type(attribute(*))</code>
        can be used to select the members of an array that are element nodes or attribute nodes
        respectively.</p><p>Such expressions return a sequence of JNodes, whose <b>·content·</b> property is 
        an XNode. Note that it is not directly possible to start with a JNode, select
        a contained XNode, and then navigate from the XNode: a path such as <code>$array/type(element(p))/@id</code>
        will not work. This is because the first step, <code>$array/type(element(p))</code>, does not select
        an element node, it selects a JNode whose <b>·content·</b> property is that element node, and use of the
        attribute axis starting from a JNode has no effect.</p><p>Instead, the required effect can be achieved by adding a step that explicitly 
           extracts the content of the JNode: <code>$array/type(element(p))/jnode-content()/@id</code>.</p></div><p>The syntax
		  and semantics of a kind test are described in
		  <a href="#id-sequencetype-syntax"><b>3.1 Sequence Types</b></a> and <a href="#id-sequencetype-matching"><b>3.1.2 Sequence Type Matching</b></a>.</p><p>Shown below are several examples of type tests that might
		  be used in path expressions selecting within an XTree:</p><ul><li><p>
                           <code>node()</code> matches any XNode.</p></li><li><p>
                           <code>text()</code> matches
		  any text
		  node.</p></li><li><p>
                           <code>comment()</code>
		  matches any comment
		  node.</p></li><li><p>
                           <code>namespace-node()</code> matches any
		  namespace node.</p></li><li><p>
                           <code>element()</code>
		  matches any element
		  node.</p></li><li><p>
                           <code>schema-element(person)</code>
		  matches any element node whose name is
		  <code>person</code> (or is in the <a title="substitution group" class="termref" href="#dt-substitution-group">substitution group</a>
		  headed by <code>person</code>), and whose type
		  annotation is the same as (or is derived from) the declared type of the <code>person</code>
		  element in the <a title="in-scope element declarations" class="termref" href="#dt-is-elems">in-scope element declarations</a>.</p></li><li><p>
                           <code>element(person)</code> matches any element node whose name is
		  <code>person</code>, regardless of its type annotation.</p></li><li><p>
                           <code>element(doctor|nurse)</code> matches any element node whose name is
                        <code>doctor</code> or <code>nurse</code>, regardless of its type annotation.</p></li><li><p>
                           <code>element(person, surgeon)</code> matches any non-nilled element node whose name
		  is <code>person</code>, and whose type
		  annotation is
		  <code>surgeon</code> or is derived from <code>surgeon</code>.</p></li><li><p>
                           <code>element(doctor|nurse, medical-staff)</code> matches any non-nilled element node whose name
                        is <code>doctor</code> or <code>nurse</code>, and whose type
                        annotation is
                        <code>medical-staff</code> or is derived from <code>medical-staff</code>.</p></li><li><p>
                           <code>element(*,
		  surgeon)</code> matches any non-nilled element node whose type
		  annotation is <code>surgeon</code> (or is derived from <code>surgeon</code>), regardless of
		  its
		  name.</p></li><li><p>
                           <code>attribute()</code> matches any
                  attribute node.</p></li><li><p>
                           <code>attribute(price)</code> matches
                  any attribute whose name is <code>price</code>,
                  regardless of its type annotation.</p></li><li><p>
                           <code>attribute(*,
                  xs:decimal)</code> matches any attribute whose type
                  annotation is <code>xs:decimal</code> (or is derived from <code>xs:decimal</code>), regardless of
                  its
                  name.</p></li><li><p>
                           <code>document-node()</code>
                  matches any document
                  node.</p></li><li><p>
                           <code>document-node(element(book))</code>
                  matches any document node whose children consist of
                  a single element node that satisfies the <a title="kind test" class="termref" href="#dt-kind-test">kind test</a>
                           <code>element(book)</code>, interleaved with zero or more
                  comments and processing
                  instructions, and no text nodes.</p></li><li><p>
                           <code>document-node(book)</code> is an abbreviation
                  for <code>document-node(element(book))</code>.</p></li></ul><p>The following examples show type type tests that might
		  be used in path expressions selecting within a JTree:</p><ul><li><p>
                           <code>array(*)</code> matches any JNode
                        whose <b>·content·</b> is an array.</p></li><li><p>
                           <code>record(longitude, latitude, *)</code> matches any JNode
                     whose <b>·content·</b> is a map having entries with keys
                     <code>"longitude"</code> and <code>"latitude"</code>.</p></li><li><p>
                           <code>type(empty-sequence())</code> matches any JNode
                     whose <b>·content·</b> is an empty sequence.</p></li><li><p>
                           <code>type(xs:date)</code> matches any JNode
                     whose <b>·content·</b> is an instance of <code>xs:date</code>.</p></li></ul></div><div class="div4">
<h5><a id="implausible-axis-steps"/>4.6.4.6 <a href="#implausible-axis-steps" style="text-decoration: none">Implausible Axis Steps</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-arithmetic">⬇</a> <a href="#node-tests">⬆</a></p><ol><li><p>
                     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 <code>@price/@value</code>, even though dynamic evaluation
                     is defined to return an empty sequence rather than an error.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/602">602</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/603">603</a> 25 July 2023]</i></p></li></ol></div><p>Certain axis steps, given an inferred type for the context value, are
               classified as <a title="implausible" class="termref" href="#dt-implausible">implausible</a>. During the static analysis
               phase, a processor <span class="verb">may</span> (subject to the rules in
               <a href="#id-implausible-expressions"><b>2.4.6 Implausible Expressions</b></a>) report a static error
               when such axis steps are encountered: [<a href="#ERRXPTY0144" title="err:XPTY0144">err:XPTY0144</a>].</p><p>More specifically, an axis step is classified as <a title="implausible" class="termref" href="#dt-implausible">implausible</a>
               if any of the following conditions applies:</p><ol class="enumar"><li><p>The inferred item type of the context value is a node kind for which the
                     specified axis is always empty: for example, the inferred item type
                     of the context value is <code>attribute()</code> 
                     and the axis is <code>child</code>.</p></li><li><p>The node test exclusively selects node kinds that cannot appear
                  on the specified axis: for example, the axis is <code>child</code>
                  and the node test is <code>document-node()</code>.</p></li><li><p>In a schema-aware environment, when using the <code>child</code>,
                     <code>descendant</code>, <code>descendant-or-self</code>, or <code>attribute</code>
                     axes, the inferred item type of the
                     context value has a content type that does not allow any node matching
                  the node test to be present on the relevant axis. For example, if the inferred
                  item type of the context value 
                  is <code>schema-element(list)</code> and the relevant element declaration 
                     (taking into account substitution group membership and wildcards) 
                     only allows <code>item</code> children,
                  the axis step <code>child::li</code> will never select anything and is therefore
                  classified as <a title="implausible" class="termref" href="#dt-implausible">implausible</a>.</p></li></ol><p>Examples of implausible axis steps include the following:</p><ul><li><p>
                           <code>@code/text()</code>: attributes cannot have text node children.</p></li><li><p>
                           <code>/@code</code>: document nodes cannot have attributes.</p></li><li><p>
                           <code>ancestor::text()</code>: the ancestor axis never returns text nodes.</p></li><li><p>
                           <code>element(*)/child::map</code>: the child axis starting at an element node
                     will never select a map.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>Processors may choose not to classify the expression <code>/..</code>
               as implausible, since XSLT 1.0 users were sometimes advised to use this construct
               as an explicit way of denoting the empty sequence.</p></div></div></div><div class="div3">
<h4><a id="id-predicate"/>4.6.5 <a href="#id-predicate" style="text-decoration: none">Predicates within Steps</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Predicate"/><code><a href="#prod-xquery40-Predicate">Predicate</a></code></td><td>::=</td><td><code>"["  <a href="#doc-xquery40-Predicate-Expr">Expr</a>  "]"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Predicate-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody></table><p>A predicate within an <a href="#doc-xquery40-AxisStep">AxisStep</a> has similar syntax and semantics
	 to a predicate within a <a title="filter expression" class="termref" href="#dt-filter-expression">filter expression</a>.  The
	 only difference is in the way the context position is set for
	 evaluation of the predicate.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The operator <code>[]</code> binds more tightly than <code>/</code>.
            This means that the expression <code>a/b[1]</code> is interpreted as <code>child::a/(child::b[1])</code>:
                  it selects the first <code>b</code>
            child of every <code>a</code> element, in contrast to <code>(a/b)[1]</code> which
            selects the first <code>b</code> element that is a child of some <code>a</code>
            element.</p><p>A common mistake is to write <code>//a[1]</code> where <code>(//a)[1]</code>
               is intended. The first expression, <code>//a[1]</code>, selects every descendant 
                  <code>a</code> element that is the first child of its parent (it expands
                  to <code>/descendant-or-self::node()/child::a[1]</code>), whereas 
               <code>(//a)[1]</code> selects the <code>a</code> element in the document.
               </p></div><p>For the purpose of evaluating the context position within
	 a predicate, the input sequence is considered to be sorted as
	 follows: into document order if the predicate is in a
	 forward-axis step, into reverse document order if the
	 predicate is in a reverse-axis step, or in its original order
	 if the predicate is not in a step.</p><p>More formally:</p><ul><li><p>For a step using a forwards axis, such as <code>child::<var>test</var>[<var>P</var>]</code>,
               the result is the same as for the equivalent <a title="filter expression" class="termref" href="#dt-filter-expression">filter expression</a>
                        <code>(child::<var>test</var>)[<var>P</var>]</code> (note the parentheses). The same applies if there
               are multiple predicates, for example <code>child::<var>test</var>[<var>P<sub>1</sub></var>][<var>P<sub>2</sub></var>][<var>P<sub>3</sub></var>]</code>
               is equivalent to <code>(child::<var>test</var>)[<var>P<sub>1</sub></var>][<var>P<sub>2</sub></var>][<var>P<sub>3</sub></var>]</code>.</p></li><li><p>For a step using a reverse axis, such as <code>ancestor::<var>test</var>[<var>P</var>]</code>,
               the result is the same as the expression  
               <code>reverse(ancestor::<var>test</var>)[<var>P</var>] =&gt; reverse()</code>. The same applies if there
               are multiple predicates, for example <code>ancestor::<var>test</var>[<var>P<sub>1</sub></var>][<var>P<sub>2</sub></var>][<var>P<sub>3</sub></var>]</code>
               is equivalent to <code>reverse(ancestor::<var>test</var>)[<var>P<sub>1</sub></var>][<var>P<sub>2</sub></var>][<var>P<sub>3</sub></var>] =&gt; reverse()</code>.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>The result of the expression <code>preceding-sibling::*</code> is in document order, but
               <code>preceding-sibling::*[1]</code> selects the last preceding sibling element,
               that is, the one that immediately precedes the context node.</p><p>Similarly, the expression <code>preceding-sibling::x[1, 2, 3]</code> selects the last three
               preceding siblings, returning them in document order. For example, given the input:</p><div class="exampleInner"><pre>&lt;doc&gt;&lt;a/&gt;&lt;b/&gt;&lt;c/&gt;&lt;d/&gt;&lt;e/&gt;&lt;f/&gt;&lt;/doc&gt;</pre></div><p>The result of <code>//e ! preceding-sibling::*[1, 2, 3]</code> is <code>&lt;b/&gt;, &lt;c/&gt;, &lt;d/&gt;</code>.
               The expression <code>//e ! preceding-sibling::*[3, 2, 1]</code> delivers exactly the same result.</p></div><p>Here are some examples of <a title="axis step" class="termref" href="#dt-axis-step">axis steps</a> that contain predicates to select XNodes:</p><ul><li><p>This example selects the second <code>chapter</code> element that is a child
			 of the context node:</p><div class="exampleInner"><pre>child::chapter[2]</pre></div></li><li><p>This example selects all the descendants of the
		  context node that are elements named
		  <code>"toy"</code> and whose <code>color</code>
		  attribute has the value <code>"red"</code>:</p><div class="exampleInner"><pre>descendant::toy[attribute::color = "red"]</pre></div></li><li><p>This example selects all the <code>employee</code> children of the context node
		that have both a <code>secretary</code> child element and an <code>assistant</code> child element:</p><div class="exampleInner"><pre>child::employee[secretary][assistant]</pre></div></li><li><p>This example selects the innermost <code>div</code> ancestor of the context node:</p><div class="exampleInner"><pre>ancestor::div[1]</pre></div></li><li><p>This example selects the outermost <code>div</code> ancestor of the context node:</p><div class="exampleInner"><pre>ancestor::div[last()]</pre></div></li><li><p>This example selects the names of all the ancestor elements of the context node that have an
                     <code>@id</code> attribute, outermost element first:</p><div class="exampleInner"><pre>ancestor::*[@id]</pre></div></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>The expression <code>ancestor::div[1]</code> parses as an <a href="#doc-xquery40-AxisStep">AxisStep</a>
                  with a reverse axis, and the position <code>1</code> therefore
                  refers to the first ancestor <code>div</code> in reverse document order,
                  that is, the innermost <code>div</code>. By
contrast, <code>(ancestor::div)[1]</code> parses as a <a href="#doc-xquery40-FilterExpr">FilterExpr</a>,
                  and therefore returns the first qualifying <code>div</code>
element in the order of the <code>ancestor::div</code> expression, which is
                  in <a title="document order" class="termref" href="#dt-document-order">document order</a>.</p><p>The fact that a reverse-axis step assigns context positions in reverse
document order for the purpose of evaluating predicates does not alter the
fact that the final result of the step is always in document order.</p><p>The expression <code>ancestor::(div1|div2)[1]</code> 
               does not have the same meaning as <code>(ancestor::div1|ancestor::div2)[1]</code>. 
                  In the first expression,
               the predicate <code>[1]</code> is within a step that uses a reverse axis, so nodes are counted
               in reverse document order. In the second expression, the predicate applies to the result of
               a union expression, so nodes are counted in document order.</p></div><p>When the context value for evaluation of a step includes multiple GNodes, the step is evaluated
            separately for each of those GNodes, and the results are combined, eliminating duplicates
            and sorting into document order.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>To avoid reordering and elimination of duplicates, replace the step <code>S</code> by <code>.!S</code>.</p></div></div><div class="div3">
<h4><a id="unabbrev"/>4.6.6 <a href="#unabbrev" style="text-decoration: none">Unabbreviated Syntax</a></h4><p>This section provides a number of examples of path expressions in which the
axis is explicitly specified in each <a title="step" class="termref" href="#dt-step">step</a>. The syntax used in these examples is
called the <b>unabbreviated syntax</b>. In many common cases, it is
possible to write path expressions more concisely using an <b>abbreviated
syntax</b>, as explained in <a href="#abbrev"><b>4.6.7 Abbreviated Syntax</b></a>.</p><p>These examples assume that the context value is a single node, referred to as the context node.</p><ul><li><p>
                        <code>child::para</code> selects
the <code>para</code> element children of the context node.</p></li><li><p>
                        <code>child::(para|bullet)</code> selects
                     the <code>para</code> and <code>bullet</code> element children of the context node.</p></li><li><p>
                        <code>child::*</code> selects all element children of the context node.</p></li><li><p>
                        <code>child::text()</code> selects all text node children of the context node.</p></li><li><p>
                        <code>child::(text()|comment())</code> selects all text node and comment node children of the context node.</p></li><li><p>
                        <code>child::node()</code> selects all the children of the context node. Note that no attribute nodes are returned, because attributes are not children.</p></li><li><p>
                        <code>attribute::name</code> selects the <code>name</code> attribute of the context node.</p></li><li><p>
                        <code>attribute::*</code> selects all the attributes of the context node.</p></li><li><p>
                        <code>parent::node()</code> selects the parent of the context node. If the context node is an attribute node, this expression returns the element node (if any) to which the attribute node is attached.</p></li><li><p>
                        <code>descendant::para</code> selects the <code>para</code> element descendants of the context node.</p></li><li><p>
                        <code>ancestor::div</code> selects all <code>div</code> ancestors of the context node.</p></li><li><p>
                        <code>ancestor-or-self::div</code> selects the <code>div</code> ancestors of the context node and, if the context node is a <code>div</code> element, the context node as well.</p></li><li><p>
                        <code>descendant-or-self::para</code> selects the <code>para</code> element descendants of the context node and, if the context node is a <code>para</code> element, the context node as well.</p></li><li><p>
                        <code>self::para</code> selects the context node if it is a <code>para</code> element, and otherwise returns an empty sequence.</p></li><li><p>
                        <code>self::(chapter|appendix)</code> selects the context node if it is a
                     <code>chapter</code> or <code>appendix</code> element, and otherwise returns an empty sequence.</p></li><li><p>
                        <code>child::chapter/descendant::para</code> selects the <code>para</code> element
descendants of the <code>chapter</code> element children of the context node.</p></li><li><p>
                        <code>child::*/child::para</code> selects all <code>para</code> grandchildren of the context node.</p></li><li><p>
                        <code>/</code> selects the root of the tree that contains the context node, but raises a dynamic error if this root is not a document node.</p></li><li><p>
                        <code>/descendant::para</code> selects all the <code>para</code> elements in the same document as the context node.</p></li><li><p>
                        <code>/descendant::list/child::member</code> selects all
the <code>member</code> elements that have a <code>list</code> parent and that are in the same document as the context node.</p></li><li><p>
                        <code>child::para[position() = 1]</code> selects the first <code>para</code> child of the context node.</p></li><li><p>
                        <code>child::para[position() = last()]</code> selects the last <code>para</code> child of the context node.</p></li><li><p>
                        <code>child::para[position() = last()-1]</code> selects the last but one <code>para</code> child of the context node.</p></li><li><p>
                        <code>child::para[position() &gt; 1]</code> selects all the <code>para</code> children of the context node other than the first <code>para</code> child of the context node.</p></li><li><p>
                        <code>following-sibling::chapter[position() = 1]</code> selects the next <code>chapter</code> sibling of the context node.</p></li><li><p>
                        <code>following-sibling::(chapter|appendix)[position() = 1]</code> selects the next sibling of the context node
                        that is either a <code>chapter</code> or an <code>appendix</code>.</p></li><li><p>
                        <code>preceding-sibling::chapter[position() = 1]</code> selects the previous <code>chapter</code> sibling of the context node.</p></li><li><p>
                        <code>/descendant::figure[position() = 42]</code> selects the forty-second <code>figure</code> element in the document containing the context node.</p></li><li><p>
                        <code>/child::book/child::chapter[position() = 5]/child::section[position() = 2]</code> selects the
second <code>section</code> of the fifth <code>chapter</code> of the <code>book</code> whose parent is the document node that contains the context node.</p></li><li><p>
                        <code>child::para[attribute::type eq "warning"]</code> selects
all <code>para</code> children of the context node that have a <code>type</code> attribute with value <code>warning</code>.
                  </p></li><li><p>
                        <code>child::para[attribute::type eq 'warning'][position() = 5]</code> selects the fifth <code>para</code> child of the context node that has a <code>type</code> attribute with value <code>warning</code>.
                  </p></li><li><p>
                        <code>child::para[position() = 5][attribute::type eq "warning"]</code> selects the fifth <code>para</code> child of the context node if that child has a <code>type</code> attribute with value <code>warning</code>.
                  </p></li><li><p>
                        <code>child::chapter[child::title = 'Introduction']</code> selects
the <code>chapter</code> children of the context node that have one or
more <code>title</code> children whose <a title="typed value" class="termref" href="#dt-typed-value">typed value</a> is equal to the
string <code>Introduction</code>.
                  </p></li><li><p>
                        <code>child::chapter[child::title]</code> selects the <code>chapter</code> children of the context node that have one or more <code>title</code> children.</p></li><li><p>
                        <code>child::*[self::chapter or self::appendix]</code>
selects the <code>chapter</code> and <code>appendix</code> children of the context node.</p></li><li><p>
                        <code>child::*[self::(chapter|appendix)][position() = last()]</code> selects the
last <code>chapter</code> or <code>appendix</code> child of the context node.</p></li></ul></div><div class="div3">
<h4><a id="abbrev"/>4.6.7 <a href="#abbrev" style="text-decoration: none">Abbreviated Syntax</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AbbreviatedStep"/><code><a href="#prod-xquery40-AbbreviatedStep">AbbreviatedStep</a></code></td><td>::=</td><td><code>".."  |  ("@"  <a href="#doc-xquery40-AbbreviatedStep-NodeTest">NodeTest</a>)  |  <a href="#doc-xquery40-AbbreviatedStep-SimpleNodeTest">SimpleNodeTest</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AbbreviatedStep-NodeTest"/><code><a href="#prod-xquery40-NodeTest">NodeTest</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-UnionNodeTest">UnionNodeTest</a>  |  <a href="#doc-xquery40-AbbreviatedStep-SimpleNodeTest">SimpleNodeTest</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AbbreviatedStep-SimpleNodeTest"/><code><a href="#prod-xquery40-SimpleNodeTest">SimpleNodeTest</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-AbbreviatedStep-TypeTest">TypeTest</a>  |  <a href="#doc-xquery40-AbbreviatedStep-Selector">Selector</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AbbreviatedStep-TypeTest"/><code><a href="#prod-xquery40-TypeTest">TypeTest</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-RegularItemType">RegularItemType</a>  |  ("type"  "("  <a href="#doc-xquery40-SequenceType">SequenceType</a>  ")")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AbbreviatedStep-Selector"/><code><a href="#prod-xquery40-Selector">Selector</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-AbbreviatedStep-EQName">EQName</a>  |  <a href="#doc-xquery40-AbbreviatedStep-Wildcard">Wildcard</a>  |  ("get"  "("  <a href="#doc-xquery40-AbbreviatedStep-ExprSingle">ExprSingle</a>  ")")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AbbreviatedStep-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AbbreviatedStep-Wildcard"/><code><a href="#prod-xquery40-Wildcard">Wildcard</a></code></td><td>::=</td><td><code>"*"<br/>|  (<a href="#prod-xquery40-NCName">NCName</a>  ":*")<br/>|  ("*:"  <a href="#prod-xquery40-NCName">NCName</a>)<br/>|  (<a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>  "*")</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AbbreviatedStep-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody></table><p>The abbreviated syntax permits the following abbreviations:</p><ol class="enumar"><li><p>The attribute axis <code>attribute::</code> can be
    abbreviated by <code>@</code>. For example, the expression <code>para[@type = "warning"]</code> is short
    for <code>child::para[attribute::type = "warning"]</code> and
    so selects <code>para</code> children with a <code>type</code> attribute with value
    equal to <code>warning</code>.</p></li><li><p>If the axis name is omitted from an <a title="axis step" class="termref" href="#dt-axis-step">axis step</a>, the default axis is
    <code>child</code>, with two exceptions:

    (1) if the <a href="#doc-xquery40-NodeTest">NodeTest</a> in an axis step contains an <a href="#doc-xquery40-AttributeTest">AttributeTest</a> or <a href="#doc-xquery40-SchemaAttributeTest">SchemaAttributeTest</a> then the
    default axis is <code>attribute</code>;     
    (2) if the <a href="#doc-xquery40-NodeTest">NodeTest</a> in an axis step is a <a href="#prod-xquery40-NamespaceNodeTest">NamespaceNodeTest</a>
                        <span class="xquery">then a static error
    is raised [<a href="#ERRXQST0134" title="err:XQST0134">err:XQST0134</a>].</span>
                        </p><div class="note"><p class="prefix"><b>Note:</b></p><p> The namespace
    axis is deprecated as of XPath 2.0, but is required in some languages
    that use XPath, including XSLT.</p></div><p>

    For example, the path expression <code>section/para</code> is an abbreviation for <code>child::section/child::para</code>, and the path
    expression <code>section/@id</code> is an
    abbreviation for <code>child::section/attribute::id</code>.  Similarly,
    <code>section/attribute(id)</code> is an
    abbreviation for <code>child::section/attribute::attribute(id)</code>. Note
    that the latter expression contains both an axis specification and
    a <a title="node test" class="termref" href="#dt-node-test">node test</a>.</p><p>Similarly, within a JTree rooted at an array, the expression <code>get(1)/parts/get(2)/part-no</code>
                  gets the first member of the top-level array (presumably a map), then the <code>"parts"</code>
                  entry within this map (presumably an array), then the second member of this array (presumably
                  a map), and finally the <code>part-no</code> entry within this map.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The same selection could be made using the lookup expression <code>?1?parts?2?part-no</code>.
                  The main difference is that path expressions offer more flexibility in being able to navigate around
                  the containing JTree. Also, the lookup expression <code>$a?1</code> fails if the
                  array index is out of bounds; the path expression <code>$a/get(1)</code> 
                  (or <code>$a/*[1]</code>) instead returns an empty sequence.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>An abbreviated axis step that omits the axis name must use a
                  <a href="#prod-xquery40-SimpleNodeTest">SimpleNodeTest</a> rather than a <a href="#prod-xquery40-UnionNodeTest">UnionNodeTest</a>.
                  This means that a construct such as <code>(ul|ol)</code>
                  is treated as an abbreviation for <code>(child::ul|child::ol)</code> rather than <code>child::(ul|ol)</code>.
                  Since the two constructs have exactly the same semantics, this is not actually a restriction.</p></div></li><li><p>A step consisting
of <code>..</code> is short
for <code>parent::gnode()</code>. For example (assuming the context
                     item is an XNode), <code>../title</code> is short for <code>parent::gnode()/child::title</code> and so will select the 
                     <code>title</code> children of the parent of the context node.</p><p>Similarly, if <code>$dateOfBirth</code> is a JNode resulting from the expression
                  <code>$map/get("date of birth")</code>, then <code>$dateOfBirth/../gender</code>
                  will select the entry having key <code>"gender"</code> within <code>$map</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The expression <code>.</code>, known as a <b>context value
   reference</b>, is a <a title="primary expression" class="termref" href="#dt-primary-expression">primary expression</a>,
   and is described in <a href="#id-context-value-references"><b>4.2.3 Context Value References</b></a>.</p></div></li></ol><p>Here are some examples of path expressions that use the abbreviated
syntax. These examples assume that the context value is a single XNode, referred to as the context node:</p><ul><li><p>
                        <code>para</code> selects the <code>para</code> element children of the context node.</p></li><li><p>
                        <code>*</code> selects all element children of the context node.</p></li><li><p>
                        <code>text()</code> selects all text node children of the context node.</p></li><li><p>
                        <code>@name</code> selects
the <code>name</code> attribute of the context node.</p></li><li><p>
                        <code>@(id|name)</code> selects
                     the <code>id</code> and <code>name</code> attributes of the context node.</p></li><li><p>
                        <code>@*</code> selects all the attributes of the context node.</p></li><li><p>
                        <code>para[1]</code> selects the first <code>para</code> child of the context node.</p></li><li><p>
                        <code>para[last()]</code> selects the last <code>para</code> child of the context node.</p></li><li><p>
                        <code>*/para</code> selects
all <code>para</code> grandchildren of the context node.</p></li><li><p>
                        <code>/book/chapter[5]/section[2]</code> selects the
second <code>section</code> of the fifth <code>chapter</code> of the <code>book</code> whose parent is the document node that contains the context node.</p></li><li><p>
                        <code>chapter//para</code> selects the <code>para</code> element descendants of the <code>chapter</code> element children of the context node.</p></li><li><p>
                        <code>//para</code> selects all
the <code>para</code> descendants of the root document node and thus selects all <code>para</code> elements in the same document as the context node.</p></li><li><p>
                        <code>//@version</code> selects all the <code>version</code> attribute nodes that are in the same document as the context node.</p></li><li><p>
                        <code>//list/member</code> selects all the <code>member</code> elements in the same document as the context node that have a <code>list</code> parent.</p></li><li><p>
                        <code>.//para</code> selects
the <code>para</code> element descendants of the context node.</p></li><li><p>
                        <code>..</code> selects the parent of the context node.</p></li><li><p>
                        <code>../@lang</code> selects
the <code>lang</code> attribute of the parent of the context node.</p></li><li><p>
                        <code>para[@type = "warning"]</code> selects all <code>para</code> children of the context node that have a <code>type</code> attribute with value <code>warning</code>.
                  </p></li><li><p>
                        <code>para[@type = "warning"][5]</code> selects the fifth <code>para</code> child of the context node that has a <code>type</code> attribute with value <code>warning</code>.
                  </p></li><li><p>
                        <code>para[5][@type = "warning"]</code> selects the fifth <code>para</code> child of the context node if that child has a <code>type</code> attribute with value <code>warning</code>.
                  </p></li><li><p>
                        <code>chapter[title = "Introduction"]</code> selects the <code>chapter</code> children of the context node that have one
or more <code>title</code> children whose <a title="typed value" class="termref" href="#dt-typed-value">typed value</a> is equal to the string <code>Introduction</code>.
                  </p></li><li><p>
                        <code>chapter[title]</code> selects the <code>chapter</code> children of the context node that have one or more <code>title</code> children.</p></li><li><p>
                        <code>employee[@secretary and @assistant]</code> selects all
the <code>employee</code> children of the context node that have both a <code>secretary</code> attribute and
an <code>assistant</code> attribute.</p></li><li><p>
                        <code>book/(chapter|appendix)/section</code> selects
every <code>section</code> element that has a parent that is either a <code>chapter</code> or an <code>appendix</code> element, that in turn is a child of a <code>book</code> element that is a child of the context node.</p></li><li><p>If <code>E</code> is any expression that returns a sequence of nodes, then the expression <code>E/.</code> returns the same nodes in <a title="document order" class="termref" href="#dt-document-order">document order</a>, with duplicates eliminated based on node identity.</p></li></ul><p>The following examples use abbreviated paths to access data within the JTree
               obtained by parsing the JSON text:</p><div class="exampleInner"><pre>[
  { "first": "John", 
    "last": "Baker", 
    "date of birth": "2003-04-19", 
    "occupation": "cook"}, 
  { "first": "Mary", 
    "last": "Smith", 
    "date of birth": "2006-08-12", 
    "occupation": "teacher"},                 
]</pre></div><ul><li><p>
                        <code>get(1)/first</code> returns a JNode whose <b>·content·</b>
               is the string <code>"John"</code>.</p></li><li><p>
                        <code>//first[. = "Mary"]/../last</code> returns a JNode whose <b>·content·</b>
               is the string <code>"Smith"</code>.</p></li><li><p>
                        <code>//first[. = "Mary"]/../get("date of birth")</code> returns a JNode whose <b>·content·</b>
               is the string <code>"2006-08-12"</code>.</p></li><li><p>
                        <code>//*[occupation = "cook"]!`{first} {last}`</code> returns the
               string <code>"John Baker"</code>.</p></li><li><p>
                        <code>//*[occupation = "cook"]/following-sibling::*[1]!`{first} {last}`</code> returns the
               string <code>"Mary Smith"</code>.</p></li><li><p>
                        <code>//*[last = "Smith"]/../get(1)/last</code> returns the
               string <code>"Baker"</code>.</p></li><li><p>
                        <code>//record(first, last, *) ! string(last)</code> returns the sequence of two
               strings <code>"Baker"</code>, <code>"Smith"</code>.</p></li></ul></div><div class="div3">
<h4><a id="comparison-with-JSONPath"/>4.6.8 <a href="#comparison-with-JSONPath" style="text-decoration: none">Comparison with JSONPath</a></h4><p>Path expressions applied to a JTree offer similar capability to
            JSONPath, which is an XPath-like language design for querying JSON.</p><div class="example">
<div class="exampleHeader"><a id="d2e25404"/>Example: Comparison with JSONPath</div><p>This example provides XPath equivalents to some examples given in the
                  JSONPath specification. [TODO: add a reference].</p><p>The examples query the result of parsing the following JSON value, representing
                     a store whose stock consists of four books and a bicycle:</p><div class="exampleInner"><pre>{
  "store": {
    "book": [
      {
        "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      {
        "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      {
        "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      {
        "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 399
    }
  }
}</pre></div><p>The following table illustrates some queries on this data, expressed
                  both in JSONPath and in XQuery 4.0.</p><table style="width:100%" class="small"><caption>JSONPath vs XQuery 4.0 Comparison</caption><col style="width:40%" span="1"/><col style="width:30%" span="1"/><col style="width:30%" span="1"/><thead><tr><th>Query</th><th>JSONPath</th><th>XQuery 4.0</th></tr></thead><tbody><tr><td style="vertical-align:top">The authors of all books in the store</td><td style="vertical-align:top">
                              <code>$.store.book[*].author</code>
                           </td><td style="vertical-align:top">
                              <code>/store/book//author</code>
                           </td></tr><tr><td style="vertical-align:top">All authors</td><td style="vertical-align:top">
                              <code>$..author</code>
                           </td><td style="vertical-align:top">
                              <code>//author</code>
                           </td></tr><tr><td style="vertical-align:top">All things in store (four books and a red bicycle)</td><td style="vertical-align:top">
                              <code>$.store.*</code>
                           </td><td style="vertical-align:top">
                              <code>/store/*</code>
                           </td></tr><tr><td style="vertical-align:top">The prices of everything in the store</td><td style="vertical-align:top">
                              <code>$.store..price</code>
                           </td><td style="vertical-align:top">
                              <code>/store//price</code>
                           </td></tr><tr><td style="vertical-align:top">The third book</td><td style="vertical-align:top">
                              <code>$..book[2]  </code>
                           </td><td style="vertical-align:top">
                              <code>//book/*[3]</code>
                           </td></tr><tr><td style="vertical-align:top">The third book's author</td><td style="vertical-align:top">
                              <code>$..book[2].author</code>
                           </td><td style="vertical-align:top">
                              <code>//book/*[3]/author</code>
                           </td></tr><tr><td style="vertical-align:top">The third book's publisher (empty result)</td><td style="vertical-align:top">
                              <code>$..book[2].publisher</code>
                           </td><td style="vertical-align:top">
                              <code>//book/*[3]/publisher</code>
                           </td></tr><tr><td style="vertical-align:top">The last book (in order)</td><td style="vertical-align:top">
                              <code>$..book[-1]</code>
                           </td><td style="vertical-align:top">
                              <code>//book/*[last()]</code>
                           </td></tr><tr><td style="vertical-align:top">The first two books</td><td style="vertical-align:top">
                              <code>$..book[0,1]</code>
                           </td><td style="vertical-align:top">
                              <code>//book/*[1,2]</code>
                           </td></tr><tr><td style="vertical-align:top">All books with an ISBN</td><td style="vertical-align:top">
                              <code>$..book[?@.isbn]</code>
                           </td><td style="vertical-align:top">
                              <code>//book[isbn]</code>
                           </td></tr><tr><td style="vertical-align:top">All books cheaper than 10</td><td style="vertical-align:top">
                              <code>$..book[?@.price&lt;10]</code>
                           </td><td style="vertical-align:top">
                              <code>//book[price lt 10]</code>
                           </td></tr><tr><td style="vertical-align:top">All member values and array elements contained in the input value</td><td style="vertical-align:top">
                              <code>$..*</code>
                           </td><td style="vertical-align:top">
                              <code>//*</code>
                           </td></tr></tbody></table></div></div></div><div class="div2">
<h3><a id="id-sequence-expressions"/>4.7 <a href="#id-sequence-expressions" style="text-decoration: none">Sequence Expressions</a></h3><p>XQuery 4.0 supports operators to construct, filter,  and combine
<a title="sequence" class="termref" href="#dt-sequence">sequences</a> of <a title="item" class="termref" href="#dt-item">items</a>.
Sequences are never nested—for
example, combining the values <code>1</code>, <code>(2, 3)</code>, and <code>( )</code> into a single sequence results
in the sequence <code>(1, 2, 3)</code>.</p><div class="div3">
<h4><a id="construct_seq"/>4.7.1 <a href="#construct_seq" style="text-decoration: none">Sequence Concatenation</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="x2-x2-doc-xquery40-Expr"/><code>Expr</code></td><td>::=</td><td><code>(<a href="#x2-x2-doc-xquery40-Expr-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="x2-x2-doc-xquery40-Expr-ExprSingle"/><code>ExprSingle</code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody></table><p>
                  [<a id="dt-sequence-expression" title="sequence expression">Definition</a>: A
            <b>sequence expression</b> is a <a title="non-trivial" class="termref" href="#dt-non-trivial">non-trivial</a> instance
            of the production rule <a href="#doc-xquery40-Expr">Expr</a>, that is, an expression
            containing two or more instances of the production <a href="#doc-xquery40-ExprSingle">ExprSingle</a>
            separated by the comma operator.]
               </p><p>The result of a <a title="sequence expression" class="termref" href="#dt-sequence-expression">sequence expression</a> is the
            <a title="sequence concatenation" class="termref" href="#dt-sequence-concatenation">sequence concatenation</a> of the values of its operands.
            See <a href="#doc-xquery40-Expr"/>
               </p><p>
                  [<a id="dt-comma-operator" title="comma operator">Definition</a>: A <b>comma operator</b> is a comma used specifically
                  as the operator in a <a title="sequence expression" class="termref" href="#dt-sequence-expression">sequence expression</a>.]
               </p><p>Empty parentheses can be used to denote an empty sequence.</p><p>A sequence may contain duplicate
<a title="item" class="termref" href="#dt-item">items</a>, but a sequence is never an item in another sequence. When a
new sequence is created by concatenating two or more input sequences, the new
sequence contains all the items of the input sequences and its length is the
sum of the lengths of the input sequences.</p><p>
                  [<a id="dt-sequence-concatenation" title="sequence concatenation">Definition</a>: The 
               <b>sequence concatenation</b> of a number of sequences <var>S<sub>1</sub></var>, <var>S<sub>2</sub></var>, ... <var>S<sub>n</sub></var>
               is defined to be the sequence formed from the items of <var>S<sub>1</sub></var>, followed by the items
               from <var>S<sub>2</sub></var>, and so on, retaining order.] The 
               <a title="comma operator" class="termref" href="#dt-comma-operator">comma operator</a> returns the sequence
            concatenation of its two operands; repeated application (for example <code>$s1, $s2, $s3, $s4</code>)
            delivers the sequence concatenation of multiple sequences.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In places where the grammar calls for <a href="#doc-xquery40-ExprSingle">ExprSingle</a>, such as the arguments of a function call, any expression that contains a top-level comma operator must be enclosed in parentheses.</p></div><p>Here are some examples of expressions that construct sequences:
</p><ul><li><p>The result of this expression is a sequence of five integers:</p><div class="exampleInner"><pre>(10, 1, 2, 3, 4)</pre></div></li><li><p>This expression combines four sequences of length one, two, zero, and two, respectively, into a single sequence of length five. The result of this expression is the sequence <code>10, 1, 2, 3, 4</code>.</p><div class="exampleInner"><pre>(10, (1, 2), (), (3, 4))</pre></div></li><li><p>The result of this expression is a sequence containing
all <code>salary</code> children of the context node followed by all <code>bonus</code> children.</p><div class="exampleInner"><pre>(salary, bonus)</pre></div></li><li><p>Assuming that <code>$price</code> is bound to
the value <code>10.50</code>, the result of this expression is the sequence <code>10.50, 10.50</code>.</p><div class="exampleInner"><pre>($price, $price)</pre></div></li></ul></div><div class="div3">
<h4><a id="id-range-expressions"/>4.7.2 <a href="#id-range-expressions" style="text-decoration: none">Range Expressions</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RangeExpr"/><code><a href="#prod-xquery40-RangeExpr">RangeExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-RangeExpr-AdditiveExpr">AdditiveExpr</a>  ("to"  <a href="#doc-xquery40-RangeExpr-AdditiveExpr">AdditiveExpr</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-RangeExpr-AdditiveExpr"/><code><a href="#prod-xquery40-AdditiveExpr">AdditiveExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-MultiplicativeExpr">MultiplicativeExpr</a>  (("+"  |  "-")  <a href="#prod-xquery40-MultiplicativeExpr">MultiplicativeExpr</a>)*</code></td></tr></tbody></table><p>
                  [<a id="dt-range-expression" title="range expression">Definition</a>: A 
               <b>range expression</b> is a <a title="non-trivial" class="termref" href="#dt-non-trivial">non-trivial</a>
               instance of the production <a href="#doc-xquery40-RangeExpr">RangeExpr</a>. A range expression
               is used to construct a sequence of 
integers.] Each of the operands is
converted as though it was an argument of a function with the expected
parameter type <code>xs:integer?</code>.
If either operand is an empty sequence, or if the integer derived from the first operand is greater than the integer derived from the second operand, the result of the range expression is an empty sequence. If the two operands convert to the same integer, the result of the range expression is that integer. Otherwise, the result is a sequence containing the two integer operands and
every integer between the two operands, in increasing order. </p><p>The following examples illustrate the semantics:</p><ul><li><p>
                        <code>1 to 4</code> returns the sequence <code>1, 2, 3, 4</code>
                     </p></li><li><p>
                        <code>10 to 10</code> returns the <a title="singleton" class="termref" href="#dt-singleton">singleton</a> sequence <code>10</code>
                     </p></li><li><p>
                        <code>10 to 1</code> returns the empty sequence</p></li><li><p>
                        <code>-13 to -10</code> returns the sequence <code>-13, -12, -11, -10</code>
                     </p></li></ul><p>More formally, a <a title="range expression" class="termref" href="#dt-range-expression">range expression</a> is evaluated as follows:</p><ol class="enumar"><li><p>Each of the operands of the <code>to</code> operator is converted as though it was an argument of a function
                  with the expected parameter type <code>xs:integer?</code>.</p></li><li><p>If either operand is an empty sequence, or if the integer derived from the first operand is greater
                  than the integer derived from the second operand, the result of the range expression is an empty sequence.</p></li><li><p>If the two operands convert to the same integer, the result of the range expression is that integer.</p></li><li><p>Otherwise, the result is a sequence containing the two integer operands and every integer between the 
                  two operands, in increasing order.</p></li></ol><p>The following examples illustrate the use of 
               <a title="range expression" class="termref" href="#dt-range-expression">range expressions</a>.</p><div class="example"><p>This example uses a range expression as one operand in constructing a sequence. 
                  It evaluates to the sequence <code>10, 1, 2, 3, 4</code>.</p><div class="exampleInner"><pre>(10, 1 to 4)</pre></div><p>This example selects the first four items from an input sequence:</p><div class="exampleInner"><pre>$input[1 to 4]</pre></div><p>This example returns the sequence <code>(0, 0.1, 0.2, 0.3, 0.5)</code>:</p><div class="exampleInner"><pre>$x = (1 to 5) ! . * 0.1</pre></div><p>This example constructs a sequence of length one containing the single integer 10.</p><div class="exampleInner"><pre>10 to 10</pre></div><p>The result of this example is a sequence of length zero.</p><div class="exampleInner"><pre>15 to 10</pre></div><p>This example uses the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-reverse"><code>fn:reverse</code></a> function to construct a sequence of six integers in decreasing order. 
                  It evaluates to the sequence 15, 14, 13, 12, 11, 10.</p><div class="exampleInner"><pre>reverse(10 to 15)</pre></div></div><div class="note"><p class="prefix"><b>Note:</b></p><p>To construct a sequence of integers based on steps other than 1, use the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-slice"><code>fn:slice</code></a>
               function, as defined in <a href="https://www.w3.org/TR/xpath-functions-31/#general-seq-funcs">
            
               14.1 General functions and operators on sequences
         </a><sup><small>FO31</small></sup>.</p></div></div><div class="div3">
<h4><a id="combining_seq"/>4.7.3 <a href="#combining_seq" style="text-decoration: none">Combining GNode Sequences</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnionExpr"/><code><a href="#prod-xquery40-UnionExpr">UnionExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-UnionExpr-IntersectExceptExpr">IntersectExceptExpr</a>  (("union"  |  "|")  <a href="#doc-xquery40-UnionExpr-IntersectExceptExpr">IntersectExceptExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnionExpr-IntersectExceptExpr"/><code><a href="#prod-xquery40-IntersectExceptExpr">IntersectExceptExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-UnionExpr-InstanceofExpr">InstanceofExpr</a>  (("intersect"  |  "except")  <a href="#doc-xquery40-UnionExpr-InstanceofExpr">InstanceofExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnionExpr-InstanceofExpr"/><code><a href="#prod-xquery40-InstanceofExpr">InstanceofExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-TreatExpr">TreatExpr</a>  ("instance"  "of"  <a href="#doc-xquery40-SequenceType">SequenceType</a>)?</code></td></tr></tbody></table><p>XQuery 4.0 provides the following operators for combining sequences of
<a title="GNode" class="termref" href="#dt-GNode">GNodes</a>:</p><ul><li><p>The <code>union</code> and <code>|</code> operators are equivalent. They take two node sequences as operands and
return a sequence containing all the GNodes that occur in either of the
operands.</p></li><li><p>The <code>intersect</code> operator takes two GNodes sequences as operands and returns a sequence
containing all the GNodes that occur in both operands.</p></li><li><p>The <code>except</code> operator takes two node sequences as operands and returns a sequence
containing all the GNodes that occur in the first operand but not in the second
operand.</p></li></ul><p>All these operators eliminate duplicate GNodes from their result sequences based on GNode identity. 
               The resulting sequence is returned in <a title="document order" class="termref" href="#dt-document-order">document order</a>.
            </p><p>If an operand
of <code>union</code>, <code>intersect</code>, or <code>except</code> contains an item that is not a <a title="GNode" class="termref" href="#dt-GNode">GNode</a>, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p><p>
If an <a href="#prod-xquery40-IntersectExceptExpr">IntersectExceptExpr</a> contains more than two 
               <a href="#doc-xquery40-InstanceofExpr">InstanceofExpr</a> operands,
they are evaluated from left to right.
With a <code>UnionExpr</code>, it makes no difference how operands are grouped,
the results are the same.
</p><div class="example"><p>Here are some examples of expressions that combine sequences. 
                  Assume the existence of three element nodes that we will refer to by symbolic names A, B, and C. 
                  Assume that the variables <code>$seq1</code>, <code>$seq2</code>  and <code>$seq3</code> 
                  are bound to the following sequences of these nodes:</p><ul><li><p>
                           <code>$seq1</code> is bound to (A, B)</p></li><li><p>
                           <code>$seq2</code> is bound to (A, B)</p></li><li><p>
                           <code>$seq3</code> is bound to (B, C)</p></li></ul><p>Then: </p><ul><li><p>
                           <code>$seq1 union $seq2</code>  evaluates to the sequence (A, B). </p></li><li><p>
                           <code>$seq2 union $seq3</code>   evaluates to the sequence (A, B, C). </p></li><li><p>
                           <code>$seq1 intersect $seq2</code>  evaluates to the sequence (A, B). </p></li><li><p>
                           <code>$seq2 intersect $seq3</code>  evaluates to the sequence containing B only.</p></li><li><p>
                           <code>$seq1 except $seq2</code>   evaluates to the empty sequence.</p></li><li><p>
                           <code>$seq2 except $seq3</code>  evaluates to the sequence containing A only.</p></li></ul></div><p>The following example demonstrates the use of the <code>except</code> operator
            with JNodes:</p><div class="exampleInner"><pre>let $m := jtree($map)
for $e in $m/child::* except $m/child::xx 
return ...</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Because the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-jtree"><code>fn:jtree</code></a> creates a new JTree root,
            calling it twice potentially creates two different trees, in which the JNodes have
            different identity. The expression <code>$map/child::* except $map/child::xx</code>
            might therefore have the wrong effect, because JNodes in two different trees 
            are being compared. For more details see the specification of the
            <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-jtree"><code>fn:jtree</code></a> function.</p></div><p>In addition to the sequence operators described here, see <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#sequence-functions">2 Processing sequences</a> for functions defined on sequences.
</p></div></div><div class="div2">
<h3><a id="id-arithmetic"/>4.8 <a href="#id-arithmetic" style="text-decoration: none">Arithmetic Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-string-templates">⬇</a> <a href="#implausible-axis-steps">⬆</a></p><ol><li><p>
               The symbols <code>×</code> and <code>÷</code> can be used for multiplication and division.
            </p></li></ol></div><p>XQuery 4.0 provides binary arithmetic operators for addition, subtraction,
multiplication, division, and modulus:</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AdditiveExpr"/><code><a href="#prod-xquery40-AdditiveExpr">AdditiveExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-AdditiveExpr-MultiplicativeExpr">MultiplicativeExpr</a>  (("+"  |  "-")  <a href="#doc-xquery40-AdditiveExpr-MultiplicativeExpr">MultiplicativeExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AdditiveExpr-MultiplicativeExpr"/><code><a href="#prod-xquery40-MultiplicativeExpr">MultiplicativeExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-AdditiveExpr-UnionExpr">UnionExpr</a>  (("*"  |  "×"  |  "div"  |  "÷"  |  "idiv"  |  "mod")  <a href="#doc-xquery40-AdditiveExpr-UnionExpr">UnionExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-AdditiveExpr-UnionExpr"/><code><a href="#prod-xquery40-UnionExpr">UnionExpr</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-IntersectExceptExpr">IntersectExceptExpr</a>  (("union"  |  "|")  <a href="#prod-xquery40-IntersectExceptExpr">IntersectExceptExpr</a>)*</code></td></tr></tbody></table><p>In addition, unary operators are provided for addition and subtraction:</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryExpr"/><code><a href="#prod-xquery40-UnaryExpr">UnaryExpr</a></code></td><td>::=</td><td><code>("-"  |  "+")*  <a href="#doc-xquery40-UnaryExpr-ValueExpr">ValueExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryExpr-ValueExpr"/><code><a href="#prod-xquery40-ValueExpr">ValueExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-UnaryExpr-ValidateExpr">ValidateExpr</a>  |  <a href="#doc-xquery40-UnaryExpr-ExtensionExpr">ExtensionExpr</a>  |  <a href="#doc-xquery40-UnaryExpr-SimpleMapExpr">SimpleMapExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryExpr-ValidateExpr"/><code><a href="#prod-xquery40-ValidateExpr">ValidateExpr</a></code></td><td>::=</td><td><code>"validate"  (<a href="#prod-xquery40-ValidationMode">ValidationMode</a>  |  ("type"  <a href="#prod-xquery40-TypeName">TypeName</a>))?  "{"  <a href="#doc-xquery40-Expr">Expr</a>  "}"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryExpr-ExtensionExpr"/><code><a href="#prod-xquery40-ExtensionExpr">ExtensionExpr</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-Pragma">Pragma</a>+  "{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryExpr-SimpleMapExpr"/><code><a href="#prod-xquery40-SimpleMapExpr">SimpleMapExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PathExpr">PathExpr</a>  ("!"  <a href="#doc-xquery40-PathExpr">PathExpr</a>)*</code></td></tr></tbody></table><p>A subtraction operator must be preceded by whitespace if
it could otherwise be interpreted as part of the previous token. For
example, <code>a-b</code> will be interpreted as a
name, but <code>a - b</code> and <code>a -b</code> will be interpreted as arithmetic expressions. (See <a href="#whitespace-rules"><b>A.3.4 Whitespace Rules</b></a> for further details on whitespace handling.)</p><p>The arithmetic operator symbols <code>*</code> and <span class="unicode-codepoint">U+00D7</span> (<span class="unicode-name">MULTIPLICATION SIGN</span>, <code>×</code>)  are interchangeable,
         and denote multiplication.</p><p>The arithmetic operator symbols <code>div</code> and <span class="unicode-codepoint">U+00F7</span> (<span class="unicode-name">DIVISION SIGN</span>, <code>÷</code>)  are interchangeable,
            and denote division.</p><p>
If an <code>AdditiveExpr</code> contains more than two <code>MultiplicativeExprs</code>,
they are grouped from left to right. So, for instance,
</p><div class="exampleInner"><pre>A - B + C - D</pre></div><p>
is equivalent to
</p><div class="exampleInner"><pre>((A - B) + C) - D</pre></div><p>
Similarly, the operands of a <code>MultiplicativeExpr</code> are grouped from left to right.
</p><p>The first step in evaluating an arithmetic expression is to evaluate its operand (for
            a unary operator) or operands (for a binary operator). 
            The order in which the operands are evaluated is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>.</p><p>
               <span class="xquery">Each</span> operand is evaluated by applying the following steps, in order:</p><ol class="enumar"><li><p>
                     <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is applied to the operand. The result of this
    operation is called the <b>atomized operand</b>.</p></li><li><p>If the atomized operand is an empty sequence, the result of
    the arithmetic expression is an empty sequence, and the implementation
    need not evaluate the other operand or apply the operator. However,
    an implementation may choose to evaluate the other operand in order
    to determine whether it raises an error.</p></li><li><p> If the atomized operand is a sequence of
length greater than one, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>If the atomized operand is of type <code>xs:untypedAtomic</code>, it is cast to  <code>xs:double</code>. If
the cast fails, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic
error</a> is raised. [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFORG0001" title="err:FORG0001">err:FORG0001</a>]<sup><small>FO40</small></sup>
                  </p></li></ol><p>If, after this process, both operands of a binary arithmetic operator
            are instances of <code>xs:numeric</code>
         but have different primitive types, they are coerced to a common type by applying
         the following rules:</p><ol class="enumar"><li><p>If either of the items is of type <code>xs:double</code>, then 
            both the values are cast to type <code>xs:double</code>.</p></li><li><p>Otherwise, if either of the items is of type <code>xs:float</code>, then 
              both the values are cast to type <code>xs:float</code>.</p></li><li><p>Otherwise, no casting takes place: the values remain as <code>xs:decimal</code>.</p></li></ol><p>After this preparation, the arithmetic expression is evaluated by applying the appropriate
         function listed in the table below. The definitions of these functions are found in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>.</p><table style="border:1px solid" class="small"><caption>Unary Arithmetic Operators</caption><thead><tr><th>Expression</th><th>Type of A</th><th>Function</th><th>Result type</th></tr></thead><tbody><tr><td>+ A</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-numeric-unary-plus"><code>op:numeric-unary-plus</code></a>
                        <code>(A)</code>
                     </td><td>xs:numeric</td></tr><tr><td>- A</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-numeric-unary-minus"><code>op:numeric-unary-minus</code></a>
                        <code>(A)</code>
                     </td><td>xs:numeric</td></tr></tbody></table><table style="border:1px solid" class="small"><caption>Binary Arithmetic Operators</caption><tbody><tr><th>Expression</th><th>Type of A</th><th>Type of B</th><th>Function</th><th>Result type</th></tr><tr><td>A + B</td><td>xs:numeric</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-numeric-add"><code>op:numeric-add</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:numeric</td></tr><tr><td>A + B</td><td>xs:date</td><td>xs:yearMonthDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-yearMonthDuration-to-date"><code>op:add-yearMonthDuration-to-date</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:date</td></tr><tr><td>A + B</td><td>xs:yearMonthDuration</td><td>xs:date</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-yearMonthDuration-to-date"><code>op:add-yearMonthDuration-to-date</code></a>
                        <code>(B, A)</code>
                     </td><td>xs:date</td></tr><tr><td>A + B</td><td>xs:date</td><td>xs:dayTimeDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-dayTimeDuration-to-date"><code>op:add-dayTimeDuration-to-date</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:date</td></tr><tr><td>A + B</td><td>xs:dayTimeDuration</td><td>xs:date</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-dayTimeDuration-to-date"><code>op:add-dayTimeDuration-to-date</code></a>
                        <code>(B, A)</code>
                     </td><td>xs:date</td></tr><tr><td>A + B</td><td>xs:time</td><td>xs:dayTimeDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-dayTimeDuration-to-time"><code>op:add-dayTimeDuration-to-time</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:time</td></tr><tr><td>A + B</td><td>xs:dayTimeDuration</td><td>xs:time</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-dayTimeDuration-to-time"><code>op:add-dayTimeDuration-to-time</code></a>
                        <code>(B, A)</code>
                     </td><td>xs:time</td></tr><tr><td>A + B</td><td>xs:dateTime</td><td>xs:yearMonthDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-yearMonthDuration-to-dateTime"><code>op:add-yearMonthDuration-to-dateTime</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:dateTime</td></tr><tr><td>A + B</td><td>xs:yearMonthDuration</td><td>xs:dateTime</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-yearMonthDuration-to-dateTime"><code>op:add-yearMonthDuration-to-dateTime</code></a>
                        <code>(B, A)</code>
                     </td><td>xs:dateTime</td></tr><tr><td>A + B</td><td>xs:dateTime</td><td>xs:dayTimeDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-dayTimeDuration-to-dateTime"><code>op:add-dayTimeDuration-to-dateTime</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:dateTime</td></tr><tr><td>A + B</td><td>xs:dayTimeDuration</td><td>xs:dateTime</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-dayTimeDuration-to-dateTime"><code>op:add-dayTimeDuration-to-dateTime</code></a>
                        <code>(B, A)</code>
                     </td><td>xs:dateTime</td></tr><tr><td>A + B</td><td>xs:yearMonthDuration</td><td>xs:yearMonthDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-yearMonthDurations"><code>op:add-yearMonthDurations</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:yearMonthDuration</td></tr><tr><td>A + B</td><td>xs:dayTimeDuration</td><td>xs:dayTimeDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-add-dayTimeDurations"><code>op:add-dayTimeDurations</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:dayTimeDuration</td></tr><tr><td>A - B</td><td>xs:numeric</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-numeric-subtract"><code>op:numeric-subtract</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:numeric</td></tr><tr><td>A - B</td><td>xs:date</td><td>xs:date</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-subtract-dates"><code>op:subtract-dates</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:dayTimeDuration</td></tr><tr><td>A - B</td><td>xs:date</td><td>xs:yearMonthDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-subtract-yearMonthDuration-from-date"><code>op:subtract-yearMonthDuration-from-date</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:date</td></tr><tr><td>A - B</td><td>xs:date</td><td>xs:dayTimeDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-subtract-dayTimeDuration-from-date"><code>op:subtract-dayTimeDuration-from-date</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:date</td></tr><tr><td>A - B</td><td>xs:time</td><td>xs:time</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-subtract-times"><code>op:subtract-times</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:dayTimeDuration</td></tr><tr><td>A - B</td><td>xs:time</td><td>xs:dayTimeDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-subtract-dayTimeDuration-from-time"><code>op:subtract-dayTimeDuration-from-time</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:time</td></tr><tr><td>A - B</td><td>xs:dateTime</td><td>xs:dateTime</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-subtract-dateTimes"><code>op:subtract-dateTimes</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:dayTimeDuration</td></tr><tr><td>A - B</td><td>xs:dateTime</td><td>xs:yearMonthDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-subtract-yearMonthDuration-from-dateTime"><code>op:subtract-yearMonthDuration-from-dateTime</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:dateTime</td></tr><tr><td>A - B</td><td>xs:dateTime</td><td>xs:dayTimeDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-subtract-dayTimeDuration-from-dateTime"><code>op:subtract-dayTimeDuration-from-dateTime</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:dateTime</td></tr><tr><td>A - B</td><td>xs:yearMonthDuration</td><td>xs:yearMonthDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-subtract-yearMonthDurations"><code>op:subtract-yearMonthDurations</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:yearMonthDuration</td></tr><tr><td>A - B</td><td>xs:dayTimeDuration</td><td>xs:dayTimeDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-subtract-dayTimeDurations"><code>op:subtract-dayTimeDurations</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:dayTimeDuration</td></tr><tr><td>A * B</td><td>xs:numeric</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-numeric-multiply"><code>op:numeric-multiply</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:numeric</td></tr><tr><td>A * B</td><td>xs:yearMonthDuration</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-multiply-yearMonthDuration"><code>op:multiply-yearMonthDuration</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:yearMonthDuration</td></tr><tr><td>A * B</td><td>xs:numeric</td><td>xs:yearMonthDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-multiply-yearMonthDuration"><code>op:multiply-yearMonthDuration</code></a>
                        <code>(B, A)</code>
                     </td><td>xs:yearMonthDuration</td></tr><tr><td>A * B</td><td>xs:dayTimeDuration</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-multiply-dayTimeDuration"><code>op:multiply-dayTimeDuration</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:dayTimeDuration</td></tr><tr><td>A * B</td><td>xs:numeric</td><td>xs:dayTimeDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-multiply-dayTimeDuration"><code>op:multiply-dayTimeDuration</code></a>
                        <code>(B, A)</code>
                     </td><td>xs:dayTimeDuration</td></tr><tr><td>A idiv B</td><td>xs:numeric</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-numeric-integer-divide"><code>op:numeric-integer-divide</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:integer</td></tr><tr><td>A div B</td><td>xs:numeric</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-numeric-divide"><code>op:numeric-divide</code></a>
                        <code>(A, B)</code>
                     </td><td>numeric; but xs:decimal if both operands are xs:integer</td></tr><tr><td>A div B</td><td>xs:yearMonthDuration</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-divide-yearMonthDuration"><code>op:divide-yearMonthDuration</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:yearMonthDuration</td></tr><tr><td>A div B</td><td>xs:dayTimeDuration</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-divide-dayTimeDuration"><code>op:divide-dayTimeDuration</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:dayTimeDuration</td></tr><tr><td>A div B</td><td>xs:yearMonthDuration</td><td>xs:yearMonthDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-divide-yearMonthDuration-by-yearMonthDuration"><code>op:divide-yearMonthDuration-by-yearMonthDuration</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:decimal</td></tr><tr><td>A div B</td><td>xs:dayTimeDuration</td><td>xs:dayTimeDuration</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-divide-dayTimeDuration-by-dayTimeDuration"><code>op:divide-dayTimeDuration-by-dayTimeDuration</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:decimal</td></tr><tr><td>A mod B</td><td>xs:numeric</td><td>xs:numeric</td><td>
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-numeric-mod"><code>op:numeric-mod</code></a>
                        <code>(A, B)</code>
                     </td><td>xs:numeric</td></tr></tbody></table><div class="note"><p class="prefix"><b>Note:</b></p><p>The operator symbol <code>×</code> is a synonym of <code>*</code>, while <code>÷</code> is
a synonym of <code>div</code>.</p></div><p>If there is no entry in the table for the combination of operator and operands,
    then a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p><p>Errors may also occur during coercion of the operands, or during evaluation of the
 identified function (for example, an error
might result from dividing by zero).</p><div class="note"><p class="prefix"><b>Note:</b></p><p>XQuery 4.0 provides three division operators:</p><ul><li><p>The <code>div</code> and <code>÷</code> operators are synonyms, and implement
               numeric division as well as division of duration values; the semantics are defined in
               <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#func-numeric-divide">4.2.4 op:numeric-divide</a>
                     </p></li><li><p>The <code>idiv</code> operator implements integer division; the semantics are defined
               in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#func-numeric-integer-divide">4.2.5 op:numeric-integer-divide</a>
                     </p></li></ul></div><p>Here are some examples of arithmetic expressions:</p><ul><li><p>The first expression below returns the <code>xs:decimal</code> value <code>-1.5</code>, and the second expression returns the <code>xs:integer</code> value <code>-1</code>:</p><div class="exampleInner"><pre>-3 div 2
-3 idiv 2</pre></div></li><li><p>Subtraction of two date values results in a value of type <code>xs:dayTimeDuration</code>:</p><div class="exampleInner"><pre>$emp/hiredate - $emp/birthdate</pre></div></li><li><p>This example illustrates the difference between a subtraction operator and a
hyphen:</p><div class="exampleInner"><pre>$unit-price - $unit-discount</pre></div></li><li><p>Unary operators have higher precedence than binary operators (other than <code>!</code>, <code>/</code>, and <code>[]</code>), subject of
course to the use of parentheses. Therefore, the following two examples have different meanings:</p><div class="exampleInner"><pre>-$bellcost + $whistlecost
-($bellcost + $whistlecost)</pre></div></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>Multiple consecutive unary arithmetic operators are permitted (though not useful).</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Negation is not the same as subtraction from zero: if <code>$x</code> is positive zero,
            then <code>-$x</code> returns negative zero, wheras <code>0 - $x</code> returns positive zero.</p></div></div><div class="div2">
<h3><a id="id-string-expr"/>4.9 <a href="#id-string-expr" style="text-decoration: none">String Expressions</a></h3><p>This section describes several ways of constructing strings.</p><div class="div3">
<h4><a id="id-string-concat-expr"/>4.9.1 <a href="#id-string-concat-expr" style="text-decoration: none">String Concatenation Expressions</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringConcatExpr"/><code><a href="#prod-xquery40-StringConcatExpr">StringConcatExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-StringConcatExpr-RangeExpr">RangeExpr</a>  ("||"  <a href="#doc-xquery40-StringConcatExpr-RangeExpr">RangeExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringConcatExpr-RangeExpr"/><code><a href="#prod-xquery40-RangeExpr">RangeExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-AdditiveExpr">AdditiveExpr</a>  ("to"  <a href="#doc-xquery40-AdditiveExpr">AdditiveExpr</a>)?</code></td></tr></tbody></table><p>String concatenation expressions allow the string representations of values to be
               concatenated. In XQuery 4.0, <code>$a || $b</code> is equivalent to
               <code>fn:concat($a, $b)</code>.
               The following expression evaluates to the string <code>concatenate</code>:</p><div class="exampleInner"><pre>() || "con" || ("cat", "enate")</pre></div></div><div class="div3">
<h4><a id="id-string-templates"/>4.9.2 <a href="#id-string-templates" style="text-decoration: none">String Templates</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-value-comparisons">⬇</a> <a href="#id-arithmetic">⬆</a></p><ol><li><p>
                  String templates provide a new way of constructing strings: for example <code>`{$greeting}, {$planet}!`</code>
                  is equivalent to <code>$greeting || ', ' || $planet || '!'</code>
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/58">58</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/324">324</a> 29 January 2023]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringTemplate"/><code><a href="#prod-xquery40-StringTemplate">StringTemplate</a></code></td><td>::=</td><td><code>"`"  (<a href="#doc-xquery40-StringTemplate-StringTemplateFixedPart">StringTemplateFixedPart</a>  |  <a href="#doc-xquery40-StringTemplate-StringTemplateVariablePart">StringTemplateVariablePart</a>)*  "`"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringTemplate-StringTemplateFixedPart"/><code><a href="#prod-xquery40-StringTemplateFixedPart">StringTemplateFixedPart</a></code></td><td>::=</td><td><code>((<a href="#doc-xquery40-StringTemplate-Char">Char</a> - ('{' | '}' | '`'))  |  "{{"  |  "}}"  |  "``")+</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringTemplate-Char"/><code><a href="#prod-xquery40-Char">Char</a></code></td><td>::=</td><td><code>
                        <a href="https://www.w3.org/TR/REC-xml/#NT-Char">[http://www.w3.org/TR/REC-xml#NT-Char]</a><sup><small>XML</small></sup>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-xml-version">xgc: xml-version</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringTemplate-StringTemplateVariablePart"/><code><a href="#prod-xquery40-StringTemplateVariablePart">StringTemplateVariablePart</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-StringTemplate-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringTemplate-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>String templates provide an alternative way of constructing strings. For example,
            the expression <code>`Pi is { round(math:pi(), 4) }`</code> returns the string <code>"Pi is 3.1416"</code>.</p><p>A string template starts and ends with <span class="unicode-codepoint">U+0060</span> (<span class="unicode-name">GRAVE ACCENT, BACKTICK</span>, <code>`</code>) , popularly known as a back-tick. Between
               the back-ticks is a string consisting of an sequence of fixed parts and
               variable parts:</p><ul><li><p>A variable part consists of an optional XPath expression enclosed in curly brackets (<code>{}</code>):
                  more specifically, a string conforming 
                  to the XPath production <code>Expr?</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>An expression within a variable part may contain an unescaped <span class="unicode-codepoint">U+007B</span> (<span class="unicode-name">LEFT CURLY BRACKET</span>, <code>{</code>)  
                        or <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>)  within
                        a <a href="#doc-xquery40-StringLiteral">StringLiteral</a> or within
                        a comment.</p><p>The fact that the expression is optional means that the
                        string contained between the curly brackets may be zero-length, may comprise whitespace
                        only, or may contain XPath comments. The effective value in this case is a zero-length
                        string, which is equivalent to omitting the variable part entirely, together with its 
                        curly-bracket delimiters. </p></div></li><li><p>A fixed part may contain any characters, except that:</p><ul><li><p>The character <span class="unicode-codepoint">U+007B</span> (<span class="unicode-name">LEFT CURLY BRACKET</span>, <code>{</code>) 
                              <span class="verb">must</span>
                        be written as <code>{{</code>.</p></li><li><p>The character <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>) 
                              <span class="verb">must</span> be
                        written as <code>}}</code>.</p></li><li><p>The character <span class="unicode-codepoint">U+0060</span> (<span class="unicode-name">GRAVE ACCENT, BACKTICK</span>, <code>`</code>) 
                              <span class="verb">must</span> be
                        written as <code>``</code>.</p></li></ul><p>Following the principles of the “longest token” rule, any occurrence
                  of <code>{{</code> within the fixed part is interpreted as an escaped left
                  curly bracket. This means that the enclosed expression must not start with
                  <span class="unicode-codepoint">U+007B</span> (<span class="unicode-name">LEFT CURLY BRACKET</span>, <code>{</code>) : if this is required, the two left curly brackets can
                  be separated by whitespace. For example the string template
                     <code>`{{"key":"{ {1:"yes", 0:"no"}?$condition}"}}`</code>
                     evaluates to the string <code>{"key":"yes"}</code> or <code>{"key":"no"}</code>
                     depending on the value of <code>$condition</code>.</p><p>By contrast, if the enclosed expression ends with <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>) ,
                  this can be immediately followed by the closing <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>) 
                  delimiter without intervening whitespace.</p></li></ul><p>
               The result of evaluating a
                  string template is the string obtained by concatenating the expansions of the fixed
               and variable parts:</p><ul><li><p>The expansion of a fixed part is obtained by replacing any double curly
                     brackets (<code>{{</code> or <code>}}</code>) by the corresponding single curly
                     bracket, and replacing doubled back-ticks (<code>``</code>) by a single back-tick.</p></li><li><p>The expansion of a variable part containing an expression is as follows:</p><ol class="enumar"><li><p>
                              <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is applied to the value of the enclosed expression, 
                           converting it to a sequence of atomic items.</p></li><li><p>If the result of atomization is an empty sequence, the result 
                           is the zero-length string. Otherwise, each atomic item in the 
                           atomized sequence is cast into a string.</p></li><li><p>The individual strings resulting from the previous step are 
                           merged into a single string by concatenating them with a 
                           single space character between each pair.</p></li></ol></li><li><p>The expansion of an empty variable part (one that contains no expression) is a zero-length string.</p></li></ul><p>For example:</p><div class="exampleInner"><pre>let $greeting := "Hello", $planet := "Mars"
return `{ $greeting }, { $planet }!`</pre></div><p>returns <code>"Hello, Mars!"</code>.</p><p>The expression:</p><div class="exampleInner"><pre>let $long-months := (1, 3, 5, 7, 8, 10, 12)
return `The months with 31 days are: { $long-months }.`</pre></div><p>returns <code>"The months with 31 days are: 1 3 5 7 8 10 12."</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The rules for processing an enclosed expression are identical to the rules for attributes in
               XQuery direct element constructors. These rules differ slightly from the rules in XSLT
               attribute value templates, where adjacent text nodes are concatenated with no separator,
               prior to atomization.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>A string template containing no variable parts is effectively just another
                  way of writing a string literal: <code>"Goethe"</code>, <code>'Goethe'</code>, and <code>`Goethe`</code>
               are interchangeable. This means that back-ticks can sometimes be a useful way of delimiting a string
               that contains both single and double quotes: <code>`He said: "I didn't."`</code>.</p><p>It is sometimes useful to use string templates in conjunction with the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-char"><code>fn:char</code></a> function
                  to build strings containing special characters, for example <code>`Chapter{ fn:char("nbsp") }{ $chapNr }`</code>.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>String literals containing an ampersand behave differently between XPath and XQuery: in XPath 
               (unless first expanded by an XML parser) the string literal <code>"Bacon &amp; Eggs"</code> 
               represents a string containing an ampersand, while in XQuery
               it is an error, because an ampersand is taken as introducing a character reference. This difference
               does not arise for string templates, since neither XPath nor XQuery recognizes entity or character references
               in a string template.
               This means that back-tick delimited strings (such as <code>`Bacon &amp; Eggs`</code>) 
                  may be useful in contexts where an XPath expression
               is required to have the same effect whether it is evaluated using an XPath or an XQuery processor.</p></div><p>In XQuery, the token <code>``[</code> is recognized as the start of a 
               <a title="string constructor" class="termref" href="#dt-string-constructor">string constructor</a>,
            under the “longest token” rule (see <a href="#lexical-structure"><b>A.3 Lexical structure</b></a>). This means that the construct
               <code>``[1]</code> is not recognized as a <a href="#doc-xquery40-StringTemplate">StringTemplate</a> followed by a predicate. 
                In the unlikely event that an empty <a href="#doc-xquery40-StringTemplate">StringTemplate</a>
            followed by a predicate is wanted, whitespace or parentheses can be used to avoid the tokenization problem.</p></div><div class="div3 xquery">
<h4><a id="id-string-constructors"/>4.9.3 <a href="#id-string-constructors" style="text-decoration: none">String Constructors</a></h4><p>
                  [<a id="dt-string-constructor" title="string constructor">Definition</a>: A
                  <b>string constructor</b> is an instance of the production
                  <a href="#doc-xquery40-StringConstructor">StringConstructor</a>: it
                  is an expression that creates a string from literal text and interpolated subexpressions.
               ]
               </p><p>The syntax of a string constructor is convenient for generating
               JSON, JavaScript, CSS, SPARQL, XQuery, XPath, or other languages that
               use curly brackets, quotation marks, or other strings that are
               delimiters in XQuery 4.0.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringConstructor"/><code><a href="#prod-xquery40-StringConstructor">StringConstructor</a></code></td><td>::=</td><td><code>"``["  <a href="#doc-xquery40-StringConstructor-StringConstructorContent">StringConstructorContent</a>  "]``"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringConstructor-StringConstructorContent"/><code><a href="#prod-xquery40-StringConstructorContent">StringConstructorContent</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-StringConstructor-StringConstructorChars">StringConstructorChars</a>  (<a href="#doc-xquery40-StringConstructor-StringInterpolation">StringInterpolation</a>
                        <a href="#doc-xquery40-StringConstructor-StringConstructorChars">StringConstructorChars</a>)*</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringConstructor-StringConstructorChars"/><code><a href="#prod-xquery40-StringConstructorChars">StringConstructorChars</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-StringConstructor-Char">Char</a>* - (Char* ('`{' | ']``') Char*))</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringConstructor-Char"/><code><a href="#prod-xquery40-Char">Char</a></code></td><td>::=</td><td><code>
                        <a href="https://www.w3.org/TR/REC-xml/#NT-Char">[http://www.w3.org/TR/REC-xml#NT-Char]</a><sup><small>XML</small></sup>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-xml-version">xgc: xml-version</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringConstructor-StringInterpolation"/><code><a href="#prod-xquery40-StringInterpolation">StringInterpolation</a></code></td><td>::=</td><td><code>"`{"  <a href="#doc-xquery40-StringConstructor-Expr">Expr</a>?  "}`"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-StringConstructor-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody></table><div class="note"><p class="prefix"><b>Note:</b></p><p>String templates (see <a href="#id-string-templates"><b>4.9.2 String Templates</b></a>) and string constructors
               have overlapping functionality. String constructors were introduced in XQuery 3.1,
               and are not available in XPath; string templates are new in XQuery 4.0 and XPath 4.0.
               String constructors were designed specifically for convenience when generating
               code in languages that use curly brackets, but with experience, they have been found to
               be somewhat unwieldy for simpler applications; this motivated the introduction of
               a simpler syntax in 4.0.</p></div><p>In a <a href="#doc-xquery40-StringConstructor">string constructor</a>, adjacent
               <a href="#prod-xquery40-StringConstructorChars">string constructor characters</a>
               are treated as literal text. Line endings are processed as elsewhere
               in XQuery; no other processing is performed on this text. 
               
               To evaluate a string constructor, each sequence of adjacent string
               constructor characters is converted to a string containing the same
               characters, and each <a href="#prod-xquery40-StringInterpolation">string
                  constructor interpolation</a>
                  <code>$i</code> is evaluated, then
               converted to a string using the expression <code>string-join($i, ' ')</code>.  
               
               A string constructor interpolation that does not contain an expression (<code>`{ }`</code>) is ignored. 
               
               The strings
               created from string constructor characters and the strings created
               from string constructor interpolations are then concatenated, in
               order.</p><p>For instance, the following expression:</p><div class="exampleInner"><pre>for $s in ("one", "two", "red", "blue")
return ``[`{ $s }` fish]``</pre></div><p>evaluates to the sequence  <code>("one fish", "two fish", "red fish", "blue fish")</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Character entities are not expanded in string constructor
                  content.  Thus, <code>``[&amp;lt;]``</code> evaluates to the string
                  <code>"&amp;lt;"</code>, not the string
                  <code>"&lt;"</code>.</p></div><p>Interpolations can contain string constructors. For instance, consider the following expression:</p><div class="exampleInner"><pre>``[`{ $i, ``[literal text]``, $j, ``[more literal text]`` }`]``</pre></div><p>Assuming the values <code>$i := 1</code> and <code>$j := 2</code>, this evaluates to the string <code>"1 literal text 2 more literal text"</code>.</p><p>The following examples are based on an example taken from the documentation of <a href="#Moustache">[Moustache]</a>, a JavaScript template library. Each function takes a map, containing values like these:</p><div class="exampleInner"><pre>{
  "name": "Chris",
  "value": 10000,
  "taxed_value": 10000 - (10000 * 0.4),
  "in_ca": true
}</pre></div><p>This function creates a simple string.</p><div class="exampleInner"><pre>declare function local:prize-message($a) as xs:string {
  ``[Hello `{ $a?name }`
You have just won `{ $a?value }` dollars!
`{ 
   if ($a?in_ca) 
   then ``[Well, `{ $a?taxed_value }` dollars, after taxes.]``
   else ""
}`]``
};</pre></div><p>This is the output of the above function :</p><div class="exampleInner"><pre>Hello Chris
You have just won 10000 dollars!
Well, 6000 dollars, after taxes.</pre></div><p>This function creates a similar string in HTML syntax.</p><div class="exampleInner"><pre>declare function local:prize-message($a) as xs:string {
  ``[&lt;div&gt;
  &lt;h1&gt;Hello `{ $a?name }`&lt;/h1&gt;
  &lt;p&gt;You have just won `{ $a?value }` dollars!&lt;/p&gt;
    `{ 
      if ($a?in_ca) 
      then ``[  &lt;p&gt;Well, `{ $a?taxed_value }` dollars, after taxes.&lt;/p&gt; ]``
      else ""
    }`
&lt;/div&gt;]``
};</pre></div><p>This is the output of the above function :</p><div class="exampleInner"><pre>&lt;div&gt;
  &lt;h1&gt;Hello Chris&lt;/h1&gt;
  &lt;p&gt;You have just won 10000 dollars!&lt;/p&gt;
  &lt;p&gt;Well, 6000 dollars, after taxes.&lt;/p&gt; 
&lt;/div&gt;</pre></div><p>This function creates a similar string in JSON syntax.</p><div class="exampleInner"><pre>
declare function local:prize-message($a) as xs:string {
  ``[{ 
  "name": `{ $a?name }`
  "value": `{ $a?value }`
  `{
  if ($a?in_ca) 
  then 
  ``[, 
  "taxed_value": `{ $a?taxed_value }`]``  
  else ""
  }`
}]`` 
};</pre></div><p>This is the output of the above function :</p><div class="exampleInner"><pre>{ 
  "name": "Chris",
  "value": 10000,
  "taxed_value": 6000
}</pre></div><p>Within an enclosed expression, the handling of expressions that start with <span class="unicode-codepoint">U+007B</span> (<span class="unicode-name">LEFT CURLY BRACKET</span>, <code>{</code>)  or that
            end with <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>)  is the same as for <a href="#id-string-templates"><b>4.9.2 String Templates</b></a>.</p></div></div><div class="div2">
<h3><a id="id-comparisons"/>4.10 <a href="#id-comparisons" style="text-decoration: none">Comparison Expressions</a></h3><p>Comparison expressions allow two values to be compared. XQuery 4.0 provides
three kinds of comparison expressions, called value comparisons, general
comparisons, and GNode comparisons.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComparisonExpr"/><code><a href="#prod-xquery40-ComparisonExpr">ComparisonExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ComparisonExpr-OtherwiseExpr">OtherwiseExpr</a>  ((<a href="#doc-xquery40-ComparisonExpr-ValueComp">ValueComp</a>  |  <a href="#doc-xquery40-ComparisonExpr-GeneralComp">GeneralComp</a>  |  <a href="#doc-xquery40-ComparisonExpr-NodeComp">NodeComp</a>)  <a href="#doc-xquery40-ComparisonExpr-OtherwiseExpr">OtherwiseExpr</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComparisonExpr-OtherwiseExpr"/><code><a href="#prod-xquery40-OtherwiseExpr">OtherwiseExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-StringConcatExpr">StringConcatExpr</a>  ("otherwise"  <a href="#doc-xquery40-StringConcatExpr">StringConcatExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComparisonExpr-ValueComp"/><code><a href="#prod-xquery40-ValueComp">ValueComp</a></code></td><td>::=</td><td><code>"eq"  |  "ne"  |  "lt"  |  "le"  |  "gt"  |  "ge"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComparisonExpr-GeneralComp"/><code><a href="#prod-xquery40-GeneralComp">GeneralComp</a></code></td><td>::=</td><td><code>"="  |  "!="  |  "&lt;"  |  "&lt;="  |  "&gt;"  |  "&gt;="</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComparisonExpr-NodeComp"/><code><a href="#prod-xquery40-NodeComp">NodeComp</a></code></td><td>::=</td><td><code>"is"  |  "is-not"  |  <a href="#doc-xquery40-ComparisonExpr-NodePrecedes">NodePrecedes</a>  |  <a href="#doc-xquery40-ComparisonExpr-NodeFollows">NodeFollows</a>  |  "precedes-or-is"  |  "follows-or-is"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComparisonExpr-NodePrecedes"/><code><a href="#prod-xquery40-NodePrecedes">NodePrecedes</a></code></td><td>::=</td><td><code>"&lt;&lt;"  |  "precedes"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComparisonExpr-NodeFollows"/><code><a href="#prod-xquery40-NodeFollows">NodeFollows</a></code></td><td>::=</td><td><code>"&gt;&gt;"  |  "follows"</code></td></tr></tbody></table><p>For a summary of the differences between different ways of comparing atomic items
         in XQuery 4.0, see <a href="#id-atomic-comparisons"><b>H Atomic Comparisons: An Overview</b></a>.</p><div class="div3">
<h4><a id="id-value-comparisons"/>4.10.1 <a href="#id-value-comparisons" style="text-decoration: none">Value Comparisons</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-general-comparisons">⬇</a> <a href="#id-string-templates">⬆</a></p><ol><li><p>
                  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.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/986">986</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2218">2218</a> 29 September 2025]</i></p></li></ol></div><p>The value comparison operators are <code>eq</code>, <code>ne</code>, <code>lt</code>, <code>le</code>, <code>gt</code>, and <code>ge</code>. Value comparisons are used for comparing single values.</p><p>The first step in evaluating a value comparison is to evaluate its operands. The order in which the operands are evaluated is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>. Each operand is evaluated by applying the following steps, in order:</p><ol class="enumar"><li><p>
                        <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is applied to each  operand. The result of this
    operation is called the <b>atomized operand</b>.</p></li><li><p>If an atomized operand is an empty sequence, the result of
    the value comparison is an empty sequence, and the implementation
    need not evaluate the other operand or apply the operator. However,
    an implementation may choose to evaluate the other operand in order
    to determine whether it raises an error.</p></li><li><p> If an atomized operand is a sequence of
length greater than one, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>If an  atomized operand is of type
  <code>xs:untypedAtomic</code> or <code>xs:anyURI</code>, then it is cast to
  <code>xs:string</code>.</p></li><li><p>Expressions using operators other than <code>eq</code> and <code>lt</code>
                  are rewritten as follows:</p><blockquote><p>
                           <code>A ne B</code> becomes <code>not(A eq B)</code>
                        <br/>
                           <code>A le B</code> becomes <code>A lt B or A eq B</code>
                        <br/>
                           <code>A gt B</code> becomes <code>B lt A</code>
                        <br/>
                           <code>A ge B</code> becomes <code>B lt A or B eq A</code>
                        </p></blockquote></li><li><p>If the types of the two operands correspond to an entry
                     in the table below, the operator is applied to the
                     operands by applying the appropriate function from the table.</p><p>If the table contains no entry corresponding to the types of the operands, 
               then a <a title="type error" class="termref" href="#dt-type-error">type error</a>
is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li></ol><table style="border:1px solid" class="small"><caption>Value Comparison Operators</caption><tbody><tr><th>Expression</th><th>Type(A)</th><th>Type(B)</th><th>Function</th></tr><tr><td>A eq B</td><td>xs:numeric</td><td>xs:numeric</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-numeric-equal"><code>op:numeric-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:boolean</td><td>xs:boolean</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean-equal"><code>op:boolean-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:string</td><td>xs:string</td><td>
                           <code>fn:atomic-equal(fn:compare(A, B), 0)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:date</td><td>xs:date</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-date-equal"><code>op:date-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:time</td><td>xs:time</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-time-equal"><code>op:time-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:dateTime</td><td>xs:dateTime</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-dateTime-equal"><code>op:dateTime-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:duration</td><td>xs:duration</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-duration-equal"><code>op:duration-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:gYear</td><td>xs:gYear</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-gYear-equal"><code>op:gYear-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:gYearMonth</td><td>xs:gYearMonth</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-gYearMonth-equal"><code>op:gYearMonth-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:gMonth</td><td>xs:gMonth</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-gMonth-equal"><code>op:gMonth-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:gMonthDay</td><td>xs:gMonthDay</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-gMonthDay-equal"><code>op:gMonthDay-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:gDay</td><td>xs:gDay</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-gDay-equal"><code>op:gDay-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>(xs:hexBinary | xs:base64Binary)</td><td>(xs:hexBinary | xs:base64Binary)</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-binary-equal"><code>op:binary-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:QName</td><td>xs:QName</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-QName-equal"><code>op:QName-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A eq B</td><td>xs:NOTATION</td><td>xs:NOTATION</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-NOTATION-equal"><code>op:NOTATION-equal</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A lt B</td><td>xs:numeric</td><td>xs:numeric</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-numeric-less-than"><code>op:numeric-less-than</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A lt B</td><td>xs:boolean</td><td>xs:boolean</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean-less-than"><code>op:boolean-less-than</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A lt B</td><td>xs:string</td><td>xs:string</td><td>
                           <code>fn:atomic-equal(fn:compare(A, B), -1)</code>
                        </td></tr><tr><td>A lt B</td><td>xs:date</td><td>xs:date</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-date-less-than"><code>op:date-less-than</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A lt B</td><td>xs:time</td><td>xs:time</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-time-less-than"><code>op:time-less-than</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A lt B</td><td>xs:dateTime</td><td>xs:dateTime</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-dateTime-less-than"><code>op:dateTime-less-than</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A lt B</td><td>xs:yearMonthDuration</td><td>xs:yearMonthDuration</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-yearMonthDuration-less-than"><code>op:yearMonthDuration-less-than</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A lt B</td><td>xs:dayTimeDuration</td><td>xs:dayTimeDuration</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-dayTimeDuration-less-than"><code>op:dayTimeDuration-less-than</code></a>
                           <code>(A, B)</code>
                        </td></tr><tr><td>A lt B</td><td>(xs:hexBinary | xs:base64Binary)</td><td>(xs:hexBinary | xs:base64Binary)</td><td>
                           <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-binary-less-than"><code>op:binary-less-than</code></a>
                           <code>(A, B)</code>
                        </td></tr></tbody></table><p>The definitions of the operator functions are found in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Comparison of strings is defined
               by reference to the specification of the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-compare"><code>fn:compare</code></a>
                  function with two arguments; this implies that the comparison is performed
                  using the <a title="default collation" class="termref" href="#dt-def-collation">default collation</a> from the
                  <a title="static context" class="termref" href="#dt-static-context">static context</a>.</p></div><p>Here are some examples of value comparisons:</p><ul><li><p>The following comparison atomizes the node(s) that are returned by the expression <code>$book/author</code>. The comparison is true only if the result of atomization is the value "Kennedy" as an instance of <code>xs:string</code> or <code>xs:untypedAtomic</code>. If the result of atomization is an empty sequence, the result of the comparison is an empty sequence. If the result of atomization is a sequence containing more than one value, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p><div class="exampleInner"><pre>$book1/author eq "Kennedy"</pre></div></li><li><p>The following comparison is <code>true</code> because atomization converts an array to its member sequence:</p><div class="exampleInner"><pre>[ "Kennedy" ] eq "Kennedy"</pre></div></li><li><p>The following <a title="path expression" class="termref" href="#dt-path-expression">path expression</a> contains a predicate that selects products whose weight is greater than 100. For any product that does not have a <code>weight</code> subelement, the value of the predicate is the empty sequence, and the product is not selected. This example assumes that <code>weight</code> is a validated element with a numeric type.</p><div class="exampleInner"><pre>//product[weight gt 100]</pre></div></li><li class="xquery"><p>The following comparisons are true because, in each case, the two constructed nodes have the same value after atomization, even though they have different identities and/or names:</p><div class="exampleInner"><pre>&lt;a&gt;5&lt;/a&gt; eq &lt;a&gt;5&lt;/a&gt;</pre></div><div class="exampleInner"><pre>&lt;a&gt;5&lt;/a&gt; eq &lt;b&gt;5&lt;/b&gt;</pre></div></li><li><p>The following comparison is true if <code>my:hatsize</code> and <code>my:shoesize</code> are both user-defined types that are derived by restriction from a primitive <a title="numeric" class="termref" href="#dt-numeric">numeric</a> type:</p><div class="exampleInner"><pre>my:hatsize(5) eq my:shoesize(5)</pre></div></li><li><p>The following comparison is true. The <code>eq</code> operator compares 
                     two QNames by performing codepoint-comparisons of their namespace URIs 
                     and their local names, ignoring their namespace prefixes.</p><div class="exampleInner"><pre>QName("http://example.com/ns1", "this:color") eq
QName("http://example.com/ns1", "that:color")</pre></div></li><li><p>The following comparison is false. The <code>xs:double</code> value
                  <code>1.1e0</code> is converted to type <code>xs:decimal</code>, giving
                  the result <code>1.100000000000000088817841970012523233890533447265625</code>, 
                  which is not equal to the <code>xs:decimal</code> value <code>1.1</code>.</p><div class="exampleInner"><pre>1.1 eq 1.1e0</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>This is incompatible with previous versions, which converted
                  both operands to <code>xs:double</code> before comparing them. This change
                  has been made because there are contexts (such as sorting and grouping) where it
                  is important that comparison results should be transitive, and this was
                  not previously the case.</p></div></li></ul></div><div class="div3">
<h4><a id="id-general-comparisons"/>4.10.2 <a href="#id-general-comparisons" style="text-decoration: none">General Comparisons</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-node-comparisons">⬇</a> <a href="#id-value-comparisons">⬆</a></p><ol><li><p>The rules for comparing untyped atomic values with numeric values have changed. 
                  Rather than converting an untyped atomic value unconditionally to <code>xs:double</code>,
                  it is now converted to the type of the numeric operand. This is designed to ensure that
                  comparisons such as <code>&lt;a&gt;1.1&lt;/a&gt; = 1.1</code> succeed, given that the values
                  will now be compared as decimals rather than as doubles.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/986">986</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2218">2218</a> 29 September 2025]</i></p></li></ol></div><p>The general comparison operators are <code>=</code>, <code>!=</code>, <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code>. General comparisons are existentially quantified comparisons that may be applied to operand sequences of any length. The result of a general comparison that does not raise an error is
always <code>true</code> or <code>false</code>.</p><p>
                  <span class="xquery">A</span> general comparison is evaluated by applying the following rules, in order:</p><ol class="enumar"><li><p>
                        <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is applied to each operand. After atomization, each operand is a sequence of atomic items.</p></li><li><p>The result of the comparison is <code>true</code> if and only if there is a pair of
atomic items, one in the first operand sequence and the other in the second operand sequence, that have the required
<b>magnitude relationship</b>. Otherwise the result of the  comparison is
<code>false</code> or an error. The <b>magnitude relationship</b> between two atomic items is determined by
applying the following rules. If a <code>cast</code> operation called for by these rules is not successful, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>  is raised. [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFORG0001" title="err:FORG0001">err:FORG0001</a>]<sup><small>FO40</small></sup>
                     </p><div class="note"><p class="prefix"><b>Note:</b></p><p>The purpose of these rules is to preserve compatibility with XPath 1.0, in which (for example) <code>x &lt; 17</code> is a numeric comparison if <code>x</code> is an untyped value. 
                        Users should be aware that the value comparison operators have different rules 
                        for casting of <code>xs:untypedAtomic</code> operands.</p></div><ol class="enumla"><li><p>If both atomic items are instances of <code>xs:untypedAtomic</code>,
                then the values are cast to the type <code>xs:string</code>.
             </p></li><li><p>If exactly one of the atomic items is an instance of
                <code>xs:untypedAtomic</code>, it is cast to a type depending on
                the other value’s dynamic type <var>T</var> according to the following rules,
                in which <var>V</var> denotes the value to be cast:
             </p><ol class="enumlr"><li><p>If <var>T</var> is a numeric type or is derived from a numeric type,
                      then <var>V</var> is cast first to the primitive base type of <var>T</var>
                                 (one of <code>xs:decimal</code>, <code>xs:double</code>,
                                 or <code>xs:float</code>); or if that fails, to <code>xs:double</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Casting to <code>xs:decimal</code> might fail if <var>V</var>
                              uses exponential notation or is positive or negative infinity. Casting to
                              <code>xs:float</code> might fail because of numeric overflow.</p></div></li><li><p>If <var>T</var> is <code>xs:dayTimeDuration</code> or is derived from
                      <code>xs:dayTimeDuration</code>,
                      then <var>V</var> is cast to <code>xs:dayTimeDuration</code>.</p></li><li><p>If <var>T</var> is <code>xs:yearMonthDuration</code> or is derived from
                      <code>xs:yearMonthDuration</code>,
                      then <var>V</var> is cast to <code>xs:yearMonthDuration</code>.</p></li><li><p>In all other cases, <var>V</var> is cast to the primitive base type of <var>T</var>.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>
                The special treatment of the duration types is required to avoid
                errors that may arise when comparing the primitive type
                <code>xs:duration</code> with any duration type.
             </p></div></li><li><p>After performing the conversions described above, the atomic items are
compared using one of the value comparison operators <code>eq</code>, <code>ne</code>, <code>lt</code>, <code>le</code>, <code>gt</code>, or
<code>ge</code>, depending on whether the general comparison operator was <code>=</code>, <code>!=</code>, <code>&lt;</code>, <code>&lt;=</code>,
<code>&gt;</code>, or <code>&gt;=</code>. The values have the required <b>magnitude relationship</b> if and only if the result
of this value comparison is <code>true</code>.</p></li></ol></li></ol><p>When evaluating a general comparison in which either operand is a sequence of items, an implementation may return <code>true</code> as soon as it finds an item in the first operand and an item in the second operand that have the required <b>magnitude relationship</b>. Similarly, a general comparison may raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> as soon as it encounters an error in evaluating either operand, or in comparing a pair of items from the two operands. As a result of these rules, the result of a general comparison is not deterministic in the presence of errors.</p><p>Here are some examples of  general comparisons:</p><ul><li><p>The following comparison is true if the <a title="typed value" class="termref" href="#dt-typed-value">typed value</a> of any
<code>author</code> child element of <code>$book1</code> is "Kennedy" as an instance of <code>xs:string</code> or <code>xs:untypedAtomic</code>:</p><div class="exampleInner"><pre>$book1/author = "Kennedy"</pre></div></li><li><p>The following comparison is true if the <a title="typed value" class="termref" href="#dt-typed-value">typed value</a> of any
<code>price</code> child element of <code>$book1</code> is (say) <code>"8.95"</code> as an instance of 
                     <code>xs:untypedAtomic</code>:</p><div class="exampleInner"><pre>$book1/price &gt; 8.50</pre></div><p>Because the operand <code>8.50</code> is expressed as an <code>xs:decimal</code>,
                  the <code>xs:untypedAtomic</code> value of the element node is converted
                  to type <code>xs:decimal</code>, and the two <code>xs:decimal</code>
                  values are compared.</p></li><li><p>The following comparison is <code>true</code> because atomization converts an array to its member sequence:</p><div class="exampleInner"><pre>[ "Obama", "Nixon", "Kennedy" ] = "Kennedy"</pre></div></li><li><p>The following example contains three general comparisons. The value of the first two 
                     comparisons is <code>true</code>, and the value of the third comparison is 
                     <code>false</code>. This example illustrates the fact that general comparisons are not transitive.</p><div class="exampleInner"><pre>(1, 2) = (2, 3)
(2, 3) = (3, 4)
(1, 2) = (3, 4)</pre></div></li><li><p>The following example contains two general comparisons, both of which are <code>true</code>. 
                     This example illustrates the fact that the <code>=</code> and <code>!=</code> operators 
                     are not inverses of each other.</p><div class="exampleInner"><pre>(1, 2) = (2, 3)
(1, 2) != (2, 3)</pre></div></li><li><p>Suppose that <code>$a</code>, <code>$b</code>, and <code>$c</code> are bound to 
                     element nodes with type annotation <code>xs:untypedAtomic</code>, with <a title="string value" class="termref" href="#dt-string-value">string values</a>
                        <code>"1"</code>, <code>"2"</code>, and <code>"2.0"</code> respectively. 
                     Then <code>($a, $b) = ($c, 3.0)</code> returns <code>false</code>, because 
                     <code>$b</code> and <code>$c</code> are compared as strings. However, <code>($a, $b) = ($c, 2.0)</code> returns <code>true</code>, 
                     because <code>$b</code> and <code>2.0</code> are compared as <code>xs:decimal</code> numbers.</p></li></ul></div><div class="div3">
<h4><a id="id-node-comparisons"/>4.10.3 <a href="#id-node-comparisons" style="text-decoration: none">GNode Comparisons</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-logical-expressions">⬇</a> <a href="#id-general-comparisons">⬆</a></p><ol><li><p>
                  Operator <code>is-not</code> is introduced, as a complement to the operator <code>is</code>.
               <i>  [ PR <a href="https://github.com/qt4cg/qtspecs/pull/2130">2130</a> 28 July 2025]</i></p></li><li><p>
                  Operators <code>precedes</code> and <code>follows</code> are introduced as synonyms
                  for operators <code>&lt;&lt;</code> and <code>&gt;&gt;</code>.
               <i>  [ PR <a href="https://github.com/qt4cg/qtspecs/pull/2130">2130</a> 28 July 2025]</i></p></li><li><p>
                  Operators <code>precedes-or-is</code> and <code>follows-or-is</code> are introduced as synonyms
                  for the union of operators <code>&lt;&lt;</code> and <code>is</code> and for the union of 
                  operators <code>&gt;&gt;</code> and <code>is</code>, respectively.
               <i>  [ PR <a href="https://github.com/qt4cg/qtspecs/pull/2130">2130</a> 22 August 2025]</i></p></li></ol></div><p>GNode comparisons are used to compare two <a title="GNode" class="termref" href="#dt-GNode">GNodes</a>

               (that is, <a title="XNode" class="termref" href="#dt-XNode">XNodes</a> or
               <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-JNode">JNodes</a><sup><small>DM</small></sup>), by their identity or by their <a title="document order" class="termref" href="#dt-document-order">document order</a>. The result of a GNode comparison is defined by the following rules:</p><ol class="enumar"><li><p>The operands of a <a title="GNode" class="termref" href="#dt-GNode">GNode</a> comparison are evaluated in <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> order.</p></li><li><p>If either operand is an empty sequence, the result of the
    comparison is an empty sequence, and the implementation need not
    evaluate the other operand or apply the operator. However, an
    implementation may choose to evaluate the other operand in order to
    determine whether it raises an error.</p></li><li><p> Each operand must be either a single <a title="GNode" class="termref" href="#dt-GNode">GNode</a> or an empty sequence; otherwise
a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>A comparison with the <code>is</code> operator is <code>true</code> if 
                     the values of two operands are the same GNode; otherwise it
is <code>false</code>. See <a href="#xpath-datamodel-40">[XDM 4.0]</a> for  the definition of GNode identity.</p></li><li><p>A comparison with the <code>is-not</code> operator is <code>false</code> if 
                     the values of two operands are the same GNode; otherwise it
is <code>true</code>. See <a href="#xpath-datamodel-40">[XDM 4.0]</a> for  the definition of GNode identity.</p></li><li><p>A comparison with the <code>&lt;&lt;</code> or <code>precedes</code> operator returns <code>true</code> 
                     if the left operand <a title="GNode" class="termref" href="#dt-GNode">GNode</a> precedes the right operand GNode in

<a title="document order" class="termref" href="#dt-document-order">document order</a>; otherwise it returns <code>false</code>.</p></li><li><p>A comparison with the <code>&gt;&gt;</code> or <code>follows</code> operator returns 
                     <code>true</code> if the left operand GNode follows the right operand GNode in
<a title="document order" class="termref" href="#dt-document-order">document order</a>; otherwise it returns <code>false</code>.</p></li><li><p>A comparison with the <code>precedes-or-is</code> operator returns <code>true</code> 
                     if the left operand <a title="GNode" class="termref" href="#dt-GNode">GNode</a> precedes the right operand GNode in
                     
                     <a title="document order" class="termref" href="#dt-document-order">document order</a> or if the values of two operands 
                     are the same GNode; otherwise it returns <code>false</code>.</p></li><li><p>A comparison with the <code>follows-or-is</code> operator returns <code>true</code> 
                     if the left operand <a title="GNode" class="termref" href="#dt-GNode">GNode</a> follows the right operand GNode in
                     
                     <a title="document order" class="termref" href="#dt-document-order">document order</a> or if the values of two operands 
                     are the same GNode; otherwise it returns <code>false</code>.</p></li></ol><p>Here are some examples of GNode comparisons:</p><ul><li><p>The following comparison is true only if the left and right sides each
evaluate to exactly the same single node:</p><div class="exampleInner"><pre>/books/book[isbn = "1558604820"] is /books/book[call = "QA76.9 C3845"]</pre></div></li><li class="xquery"><p>The following comparison is false because each constructed node has its own identity:</p><div class="exampleInner"><pre>&lt;a&gt;5&lt;/a&gt; is &lt;a&gt;5&lt;/a&gt;</pre></div></li><li><p>The following comparison is true only if the node identified by the left
side occurs before the node identified by the right side in document order:</p><div class="exampleInner"><pre>/transactions/purchase[parcel = "28-451"] &lt;&lt; /transactions/sale[parcel = "33-870"]</pre></div></li><li><p>The following comparison is true only if the first integer 
                     among the members of an array precedes the first string. This expression
                     compares two JNodes:</p><div class="exampleInner"><pre>let $A := ["Q", 3, "E", "R", "T", 5, "Y"]
return $A ? child::type(xs:integer)[1] precedes $A ? child::type(xs:string)[1]</pre></div></li></ul></div></div><div class="div2">
<h3><a id="id-logical-expressions"/>4.11 <a href="#id-logical-expressions" style="text-decoration: none">Logical Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-namespaces">⬇</a> <a href="#id-node-comparisons">⬆</a></p><ol><li><p>
                  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 <code>and</code> and <code>or</code>,
                  and of predicates in filter expressions, in a way that might allow the processor to raise dynamic
                  errors that the author intended to prevent.
               <i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/71">71</a> <a href="https://github.com/qt4cg/qtspecs/issues/2132">2132</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/230">230</a> 15 November 2022]</i></p></li></ol></div><p>
               [<a id="dt-logical-expression" title="logical expression">Definition</a>: 
            A <b>logical expression</b> is either an <a title="and expression" class="termref" href="#dt-and-expression">and expression</a>
            or an <a title="or expression" class="termref" href="#dt-or-expression">or expression</a>. If a logical expression does not raise an error, 
            its value is always one of the boolean values <code>true</code> or <code>false</code>.]
            </p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrExpr"/><code><a href="#prod-xquery40-OrExpr">OrExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-OrExpr-AndExpr">AndExpr</a>  ("or"  <a href="#doc-xquery40-OrExpr-AndExpr">AndExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrExpr-AndExpr"/><code><a href="#prod-xquery40-AndExpr">AndExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-OrExpr-ComparisonExpr">ComparisonExpr</a>  ("and"  <a href="#doc-xquery40-OrExpr-ComparisonExpr">ComparisonExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrExpr-ComparisonExpr"/><code><a href="#prod-xquery40-ComparisonExpr">ComparisonExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-OtherwiseExpr">OtherwiseExpr</a>  ((<a href="#prod-xquery40-ValueComp">ValueComp</a>  |  <a href="#prod-xquery40-GeneralComp">GeneralComp</a>  |  <a href="#prod-xquery40-NodeComp">NodeComp</a>)  <a href="#doc-xquery40-OtherwiseExpr">OtherwiseExpr</a>)?</code></td></tr></tbody></table><p>
               [<a id="dt-and-expression" title="and expression">Definition</a>: An <b>and expression</b>
         is a <a title="non-trivial" class="termref" href="#dt-non-trivial">non-trivial</a> instance of the production <a href="#prod-xquery40-AndExpr">AndExpr</a>.]
            </p><p>
               [<a id="dt-or-expression" title="or expression">Definition</a>: An <b>or expression</b>
         is a <a title="non-trivial" class="termref" href="#dt-non-trivial">non-trivial</a> instance of the production <a href="#doc-xquery40-OrExpr">OrExpr</a>.]
            </p><p>In the absence of errors, an <a title="and expression" class="termref" href="#dt-and-expression">and expression</a> returns <code>true</code>
            when both of its operands have an <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> of <code>true</code>, while an
            <a title="or expression" class="termref" href="#dt-or-expression">or expression</a> returns <code>true</code> when either or both of its operands have
            an <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> of <code>true</code>.</p><p>The rules for error handling follow the principles defined in <a href="#id-guarded-expressions"><b>2.4.5 Guarded Expressions</b></a>.
         Specifically, an <a title="and expression" class="termref" href="#dt-and-expression">and expression</a> returns false if the first operand has an 
         <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> of <code>false</code>, whether or not evaluation of the second
         operand raises an error; while an <a title="or expression" class="termref" href="#dt-or-expression">or expression</a> returns true if the first operand has an 
         <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> of <code>true</code>, whether or not evaluation of the second
         operand raises an error.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>This rule is consistent with the so-called “short-circuit” evaluation of
         logical operators defined in some procedural programming languages. However, unlike many
         such languages, the rule is concerned only with error behavior, and not with side-effects.
         A processor may evaluate the operands of a logical expression in any order, or in parallel,
         provided that the error semantics are respected. For example, an optimizer may choose to
         evaluate the second operand before evaluating the first, provided that any error in doing so
         is masked when the result can be determined from the value of the first operand.</p></div><p>The value of an <a title="and expression" class="termref" href="#dt-and-expression">and expression</a> is determined by the effective
          boolean values (EBVs) of its operands, as shown in the following table:</p><table style="width:80%; border:1px solid" class="medium"><tbody><tr><th>AND:</th><th>EBV<sub>2</sub> =
<code>true</code>
                     </th><th>EBV<sub>2</sub> = <code>false</code>
                     </th><th>error in EBV<sub>2</sub>
                     </th></tr><tr><th>EBV<sub>1</sub> =
<code>true</code>
                     </th><td>
                        <code>true</code>
                     </td><td>
                        <code>false</code>
                     </td><td>error</td></tr><tr><th>EBV<sub>1</sub>
= <code>false</code>
                     </th><td>
                        <code>false</code>
                     </td><td>
                        <code>false</code>
                     </td><td>
                        <code>false</code>
                     </td></tr><tr><th>error in EBV<sub>1</sub>
                     </th><td>error</td><td>error</td><td>error</td></tr></tbody></table><p>The value of an
<a title="or expression" class="termref" href="#dt-or-expression">or expression</a> is determined by the effective boolean values (EBVs) of
its operands, as shown in
the following table:</p><table style="width:80%; border:1px solid" class="medium"><tbody><tr><th>OR:</th><th>EBV<sub>2</sub> =
<code>true</code>
                     </th><th>EBV<sub>2</sub> = <code>false</code>
                     </th><th>error in
EBV<sub>2</sub>
                     </th></tr><tr><th>EBV<sub>1</sub> =
<code>true</code>
                     </th><td>
                        <code>true</code>
                     </td><td>
                        <code>true</code>
                     </td><td>
                        <code>true</code>
                     </td></tr><tr><th>EBV<sub>1</sub> =
<code>false</code>
                     </th><td>
                        <code>true</code>
                     </td><td>
                        <code>false</code>
                     </td><td>error</td></tr><tr><th>error
in EBV<sub>1</sub>
                     </th><td>error</td><td>error</td><td>error</td></tr></tbody></table><div class="note"><p class="prefix"><b>Note:</b></p><p>XPath 1.0 defined the order of evaluation for 
               <a title="and expression" class="termref" href="#dt-and-expression">and-expressions</a> and 
               <a title="or expression" class="termref" href="#dt-or-expression">or-expressions</a>, thus ensuring
               “short-circuit” semantics. XPath 2.0 and XQuery 1.0 changed the rules
               to allow operands to be evaluated in either order, in the interests
               of optimization, while retaining “short-circuit” semantics when
               running XPath in 1.0 compatibility mode. The same rules were retained in
               the 3.0 and 3.1 versions of the specifications.</p><p>The disadvantage
               of that formulation was that it was not possible to use the first operand
               of a logical expression to guard against dynamic errors in the second;
               for example the expression <code>$n instance of node() and exists($n/*)</code>
               might legitimately fail in the case where <code>$n</code> is not a node.</p><p>The 4.0 specification therefore guarantees that this expression will not fail;
               but it does so without mandating an order of evaluation for the operands. Instead
               it mandates only that any error in evaluating the second operand (<code>exists($n/*)</code>)
               is masked if the first operand (<code>$n instance of node()</code>) is false.
            </p></div><p>Here are some examples of logical expressions:</p><ul><li><p>The following expressions return
<code>true</code>:</p><div class="exampleInner"><pre>1 eq 1 and 2 eq 2</pre></div><div class="exampleInner"><pre>1 eq 1 or 2 eq 3</pre></div></li><li><p>The following returns <code>false</code>: it is not allowed to
               raise an error.</p><div class="exampleInner"><pre>1 eq 2 and 3 idiv 0 = 1</pre></div></li><li><p>The following expression returns <code>true</code>: it is not allowed to
               raise an error.</p><div class="exampleInner"><pre>1 eq 1 or 3 idiv 0 = 1</pre></div></li><li><p>The
following expression must raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>:</p><div class="exampleInner"><pre>1 eq 1 and 3 idiv 0 = 1</pre></div></li></ul><p>In addition to and- and or-expressions, XQuery 4.0 provides a
function named <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-not"><code>fn:not</code></a> that takes a general sequence as
parameter and returns a boolean value.  The <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-not"><code>fn:not</code></a> function
is defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>. The
<a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-not"><code>fn:not</code></a> function reduces its parameter to an <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a>. It then returns
<code>true</code> if the effective boolean value of its parameter is
<code>false</code>, and <code>false</code> if the effective boolean
value of its parameter is <code>true</code>. If an error is
encountered in finding the effective boolean value of its operand,
<a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-not"><code>fn:not</code></a> raises the same error.</p></div><div class="div2 xquery">
<h3><a id="id-constructors"/>4.12 <a href="#id-constructors" style="text-decoration: none">Node Constructors</a></h3><p>XQuery provides node constructors that can create XML nodes within a query.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor"/><code><a href="#prod-xquery40-NodeConstructor">NodeConstructor</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-NodeConstructor-DirectConstructor">DirectConstructor</a>
                     <br/>|  <a href="#doc-xquery40-NodeConstructor-ComputedConstructor">ComputedConstructor</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-DirectConstructor"/><code><a href="#prod-xquery40-DirectConstructor">DirectConstructor</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-NodeConstructor-DirElemConstructor">DirElemConstructor</a>
                     <br/>|  <a href="#doc-xquery40-NodeConstructor-DirCommentConstructor">DirCommentConstructor</a>
                     <br/>|  <a href="#doc-xquery40-NodeConstructor-DirPIConstructor">DirPIConstructor</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-DirElemConstructor"/><code><a href="#prod-xquery40-DirElemConstructor">DirElemConstructor</a></code></td><td>::=</td><td><code>"&lt;"  <a href="#prod-xquery40-QName">QName</a>
                     <a href="#doc-xquery40-NodeConstructor-DirAttributeList">DirAttributeList</a>  ("/&gt;"  |  ("&gt;"  <a href="#doc-xquery40-NodeConstructor-DirElemContent">DirElemContent</a>*  "&lt;/"  <a href="#prod-xquery40-QName">QName</a>
                     <a href="#prod-xquery40-S">S</a>?  "&gt;"))</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-DirAttributeList"/><code><a href="#prod-xquery40-DirAttributeList">DirAttributeList</a></code></td><td>::=</td><td><code>(<a href="#prod-xquery40-S">S</a>  (<a href="#prod-xquery40-QName">QName</a>
                     <a href="#prod-xquery40-S">S</a>?  "="  <a href="#prod-xquery40-S">S</a>?  <a href="#doc-xquery40-NodeConstructor-DirAttributeValue">DirAttributeValue</a>)?)*</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-DirAttributeValue"/><code><a href="#prod-xquery40-DirAttributeValue">DirAttributeValue</a></code></td><td>::=</td><td><code>('"'  (<a href="#prod-xquery40-EscapeQuot">EscapeQuot</a>  |  <a href="#doc-xquery40-NodeConstructor-QuotAttrValueContent">QuotAttrValueContent</a>)*  '"')<br/>|  ("'"  (<a href="#prod-xquery40-EscapeApos">EscapeApos</a>  |  <a href="#doc-xquery40-NodeConstructor-AposAttrValueContent">AposAttrValueContent</a>)*  "'")</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-QuotAttrValueContent"/><code><a href="#prod-xquery40-QuotAttrValueContent">QuotAttrValueContent</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QuotAttrContentChar">QuotAttrContentChar</a>
                     <br/>|  <a href="#doc-xquery40-NodeConstructor-CommonContent">CommonContent</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-AposAttrValueContent"/><code><a href="#prod-xquery40-AposAttrValueContent">AposAttrValueContent</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposAttrContentChar">AposAttrContentChar</a>
                     <br/>|  <a href="#doc-xquery40-NodeConstructor-CommonContent">CommonContent</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-DirElemContent"/><code><a href="#prod-xquery40-DirElemContent">DirElemContent</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-NodeConstructor-DirectConstructor">DirectConstructor</a>
                     <br/>|  <a href="#doc-xquery40-NodeConstructor-CDataSection">CDataSection</a>
                     <br/>|  <a href="#doc-xquery40-NodeConstructor-CommonContent">CommonContent</a>
                     <br/>|  <a href="#doc-xquery40-NodeConstructor-ElementContentChar">ElementContentChar</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-DirCommentConstructor"/><code><a href="#prod-xquery40-DirCommentConstructor">DirCommentConstructor</a></code></td><td>::=</td><td><code>"&lt;!--"  <a href="#doc-xquery40-NodeConstructor-DirCommentContents">DirCommentContents</a>  "--&gt;"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-DirPIConstructor"/><code><a href="#prod-xquery40-DirPIConstructor">DirPIConstructor</a></code></td><td>::=</td><td><code>"&lt;?"  <a href="#prod-xquery40-PITarget">PITarget</a>  (<a href="#prod-xquery40-S">S</a>
                     <a href="#prod-xquery40-DirPIContents">DirPIContents</a>)?  "?&gt;"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-CDataSection"/><code><a href="#prod-xquery40-CDataSection">CDataSection</a></code></td><td>::=</td><td><code>"&lt;![CDATA["  <a href="#doc-xquery40-NodeConstructor-CDataSectionContents">CDataSectionContents</a>  "]]&gt;"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-CDataSectionContents"/><code><a href="#prod-xquery40-CDataSectionContents">CDataSectionContents</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-NodeConstructor-Char">Char</a>* - (Char* ']]&gt;' Char*))</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-Char"/><code><a href="#prod-xquery40-Char">Char</a></code></td><td>::=</td><td><code>
                     <a href="https://www.w3.org/TR/REC-xml/#NT-Char">[http://www.w3.org/TR/REC-xml#NT-Char]</a><sup><small>XML</small></sup>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-xml-version">xgc: xml-version</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-CommonContent"/><code><a href="#prod-xquery40-CommonContent">CommonContent</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-PredefinedEntityRef">PredefinedEntityRef</a>  |  <a href="#prod-xquery40-CharRef">CharRef</a>  |  "{{"  |  "}}"  |  <a href="#doc-xquery40-NodeConstructor-EnclosedExpr">EnclosedExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-ElementContentChar"/><code><a href="#prod-xquery40-ElementContentChar">ElementContentChar</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-NodeConstructor-Char">Char</a> - [{}&lt;&amp;])</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-DirCommentContents"/><code><a href="#prod-xquery40-DirCommentContents">DirCommentContents</a></code></td><td>::=</td><td><code>((<a href="#doc-xquery40-NodeConstructor-Char">Char</a> - '-')  |  ("-"  (<a href="#doc-xquery40-NodeConstructor-Char">Char</a> - '-')))*</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NodeConstructor-ComputedConstructor"/><code><a href="#prod-xquery40-ComputedConstructor">ComputedConstructor</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-CompDocConstructor">CompDocConstructor</a>
                     <br/>|  <a href="#doc-xquery40-CompElemConstructor">CompElemConstructor</a>
                     <br/>|  <a href="#doc-xquery40-CompAttrConstructor">CompAttrConstructor</a>
                     <br/>|  <a href="#doc-xquery40-CompNamespaceConstructor">CompNamespaceConstructor</a>
                     <br/>|  <a href="#doc-xquery40-CompTextConstructor">CompTextConstructor</a>
                     <br/>|  <a href="#doc-xquery40-CompCommentConstructor">CompCommentConstructor</a>
                     <br/>|  <a href="#doc-xquery40-CompPIConstructor">CompPIConstructor</a>
                  </code></td></tr></tbody></table><p>Constructors are provided for element, attribute, document, text, comment, and processing instruction nodes. Two kinds of constructors are provided: <b>direct constructors</b>, which use an XML-like notation that can incorporate enclosed expressions, and <b>computed constructors</b>, which use a notation based on enclosed expressions. </p><p>The rest of this section contains a conceptual description of the semantics of various kinds of constructor expressions. An XQuery implementation is free to use any implementation technique that produces the same result as the processing steps described here.</p><div class="div3">
<h4><a id="id-element-constructor"/>4.12.1 <a href="#id-element-constructor" style="text-decoration: none">Direct Element Constructors</a></h4><p>An <b>element constructor</b> creates an element node. [<a id="dt-direct-elem-const" title="direct element constructor">Definition</a>: A <b>direct element constructor</b> is a form of element constructor in which the name 
               of the constructed element is a constant.] Direct element constructors are based on 
               standard XML notation. For example, the following expression is a direct element constructor
               that creates a <code>book</code> element containing an attribute and some nested elements:</p><div class="exampleInner"><pre>&lt;book isbn="isbn-0060229357"&gt;
  &lt;title&gt;Harold and the Purple Crayon&lt;/title&gt;
  &lt;author&gt;
    &lt;first&gt;Crockett&lt;/first&gt;
    &lt;last&gt;Johnson&lt;/last&gt;
  &lt;/author&gt;
&lt;/book&gt;</pre></div><p>The element name, written as a lexical QName, is expanded using the
            <a title="constructed element namespace rule" class="termref" href="#dt-constructed-element-namespace-rule">constructed element namespace rule</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The statically known namespaces 
               may be affected by <a title="namespace declaration attribute" class="termref" href="#dt-namespace-decl-attr">namespace declaration attributes</a> 
               found inside the element constructor.</p></div><p>The namespace prefix of the element name is retained after 
               expansion of the <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>, as described in 
               <a href="#xpath-datamodel-40">[XDM 4.0]</a>. The resulting <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> 
               becomes the <code>node-name</code> property of the constructed element node.</p><p>The name used in the end tag must exactly match the name
used in the corresponding start tag, including its prefix or absence of a prefix  [<a href="#ERRXQST0118" title="err:XQST0118">err:XQST0118</a>].</p><p>In a direct element constructor, curly brackets 
               (<span class="unicode-codepoint">U+007B</span> (<span class="unicode-name">LEFT CURLY BRACKET</span>, <code>{</code>)  and <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>) ) delimit  <a title="enclosed expression" class="termref" href="#dt-enclosed-expression">enclosed expressions</a>, distinguishing them from literal text. Enclosed expressions
are evaluated and replaced by their value, as illustrated by the following
example:</p><div class="exampleInner"><pre>&lt;example&gt;
  &lt;p&gt; Here is a query. &lt;/p&gt;
  &lt;eg&gt; $b/title &lt;/eg&gt;
  &lt;p&gt; Here is the result of the query. &lt;/p&gt;
  &lt;eg&gt;{ $b/title }&lt;/eg&gt;
&lt;/example&gt;</pre></div><p>The above query might generate the following result (whitespace has been added for readability to this result and other result examples in this document):</p><div class="exampleInner"><pre>
&lt;example&gt;
  &lt;p&gt; Here is a query. &lt;/p&gt;
  &lt;eg&gt; $b/title &lt;/eg&gt;
  &lt;p&gt; Here is the result of the query. &lt;/p&gt;
  &lt;eg&gt;&lt;title&gt;Harold and the Purple Crayon&lt;/title&gt;&lt;/eg&gt;
&lt;/example&gt;</pre></div><p>Since XQuery uses <span class="unicode-codepoint">U+007B</span> (<span class="unicode-name">LEFT CURLY BRACKET</span>, <code>{</code>)  and <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>)  to delimit enclosed expressions, some
convention is needed to denote a curly bracket used as an ordinary character. For
this purpose, a pair of identical curly bracket characters within the content of an element or attribute are interpreted by XQuery  as a single curly bracket
character (that is, the pair <code>"{{"</code> represents the
  character <span class="unicode-codepoint">U+007B</span> (<span class="unicode-name">LEFT CURLY BRACKET</span>, <code>{</code>)  and the pair <code>"}}"</code> represents
  the character <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>) .) Alternatively, the <a title="character reference" class="termref" href="#dt-character-reference">character references</a>
                  <code>&amp;#x7b;</code> and <code>&amp;#x7d;</code> can be used to denote curly bracket characters.  
               A single <span class="unicode-codepoint">U+007B</span> (<span class="unicode-name">LEFT CURLY BRACKET</span>, <code>{</code>)  is interpreted as the beginning delimiter for an
  enclosed expression. A single <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>) 
  without a matching left curly bracket is treated as a <a title="static error" class="termref" href="#dt-static-error">static error</a>
                  [<a href="#ERRXPST0003" title="err:XPST0003">err:XPST0003</a>].</p><p>Within an enclosed expression, the handling of expressions that start with <span class="unicode-codepoint">U+007B</span> (<span class="unicode-name">LEFT CURLY BRACKET</span>, <code>{</code>)  or that
            end with <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>)  is the same as for <a href="#id-string-templates"><b>4.9.2 String Templates</b></a>.</p><p>The result of an element constructor is a new element node, with its own node identity. All the attribute and descendant nodes of the new element node are also new nodes with their own identities, even if they are copies of existing nodes.</p><div class="div4">
<h5><a id="id-attributes"/>4.12.1.1 <a href="#id-attributes" style="text-decoration: none">Attributes</a></h5><p>The start tag of a direct element constructor may contain one or more attributes. As in XML, each attribute is specified by a name and a value. In a direct element constructor, the name of each attribute is specified by a constant <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>, and the value of the attribute is specified by a string of characters enclosed in single or double quotes. As in the main content of the element constructor, an attribute value may contain  <a title="enclosed expression" class="termref" href="#dt-enclosed-expression">enclosed expressions</a>, which are evaluated and replaced by their value during processing of the element constructor.</p><p>Each attribute in a direct element constructor creates a new attribute node, with its own node identity, whose parent is the constructed element node. However, note that <a title="namespace declaration attribute" class="termref" href="#dt-namespace-decl-attr">namespace declaration attributes</a> (see <a href="#id-namespaces"><b>4.12.1.2 Namespace Declaration Attributes</b></a>) do not create attribute nodes.</p><p>The attribute name, written as a lexical QName, is expanded using the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>
                  The <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a> used in resolving an attribute name may be affected by <a title="namespace declaration attribute" class="termref" href="#dt-namespace-decl-attr">namespace declaration attributes</a> that are found inside the same element constructor.
               </p></div><p>
                  The namespace prefix of the attribute name is retained after expansion of the <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>, as described in <a href="#xpath-datamodel-40">[XDM 4.0]</a>. The resulting <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> becomes the <code>node-name</code> property of the constructed attribute node.</p><p>If the attributes in a direct element constructor do not have distinct <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded
			        QNames</a> as their respective <code>node-name</code> properties, a <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0040" title="err:XQST0040">err:XQST0040</a>].</p><p>Conceptually, an attribute (other than a namespace declaration attribute) in a 
                  direct element constructor is processed by the following steps:</p><ol class="enumar"><li><p>Each consecutive sequence of literal characters in the
	attribute content is processed as a string literal containing
	those characters, with the following exceptions:</p><ol class="enumla"><li><p>Each occurrence of two consecutive <code>{</code>
             characters is replaced by a single <code>{</code> character.
             </p></li><li><p>Each occurrence of two consecutive <code>}</code>
             characters is replaced by a single <code>}</code> character.
             </p></li><li><p>Each occurrence of <a href="#prod-xquery40-EscapeQuot">EscapeQuot</a> is replaced by a single
             <code>"</code> character.  </p></li><li><p>Each occurrence of <a href="#prod-xquery40-EscapeApos">EscapeApos</a> is replaced by a single
             <code>'</code> character.  </p></li></ol><p>Within an enclosed expression, the handling of expressions that start with <span class="unicode-codepoint">U+007B</span> (<span class="unicode-name">LEFT CURLY BRACKET</span>, <code>{</code>)  or that
            end with <span class="unicode-codepoint">U+007D</span> (<span class="unicode-name">RIGHT CURLY BRACKET</span>, <code>}</code>)  is the same as for <a href="#id-string-templates"><b>4.9.2 String Templates</b></a>.</p><p>Attribute value normalization is then applied to
          normalize whitespace and expand <a title="character reference" class="termref" href="#dt-character-reference">character references</a>
          and <a title="predefined entity reference" class="termref" href="#dt-predefined-entity-reference">predefined
          entity references</a>. 
	  The rules for attribute value
	  normalization are the rules from Section 3.3.3 of [XML 1.0]
	  or Section 3.3.3 of [XML 1.1] (it is implementation-defined
	  which version is used). The rules are applied as though the
	  type of the attribute were CDATA (leading and trailing
	  whitespace characters are not stripped.)
          </p></li><li><p>Each enclosed expression is converted to a string as follows:</p><ol class="enumla"><li><p>
                                 <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is applied to the value of the enclosed expression, converting it to a sequence of atomic items.</p></li><li><p>If the result of atomization is an empty sequence, the result is the zero-length string. Otherwise, each atomic item in the atomized sequence is cast into a string.</p></li><li><p>The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair.</p></li></ol></li><li><p>Adjacent strings resulting from the above steps are concatenated with no intervening blanks. The resulting string becomes the <code>string-value</code> property of the attribute node. The attribute node is given a <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> of <code>xs:untypedAtomic</code> (this type annotation may change if the parent element is validated). The <code>typed-value</code> property of the attribute node is the same as its <code>string-value</code>, as an instance of <code>xs:untypedAtomic</code>.</p></li><li><p>The <code>parent</code> property of the attribute node is set to the element node constructed by the direct element constructor that contains this attribute.</p></li><li><p>If the attribute name is <code>xml:id</code>, then <code>xml:id</code> processing is performed as defined in <a href="#XMLID">[XML ID]</a>. This ensures that the attribute has the type <code>xs:ID</code> and that its value is properly normalized. If an error is encountered during <code>xml:id</code> processing, an implementation may raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>
                           [<a href="#ERRXQDY0091" title="err:XQDY0091">err:XQDY0091</a>].</p></li><li><p>If the attribute name is <code>xml:id</code>, the <code>is-id</code> property of the resulting attribute node is set to <code>true</code>; otherwise the <code>is-id</code> property is set to <code>false</code>. The <code>is-idrefs</code> property of the attribute node is unconditionally set to <code>false</code>.</p></li></ol><ul><li><p>Example:</p><div class="exampleInner"><pre>&lt;shoe size="7"/&gt;</pre></div><p>The string value of the <code>size</code> attribute is <code>"7"</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;shoe size="{ 7 }"/&gt;</pre></div><p>The string value of the <code>size</code> attribute is <code>"7"</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;shoe size="{ () }"/&gt;</pre></div><p>The string value of the <code>size</code> attribute is the zero-length string.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;chapter ref="[ { 1, 5 to 7, 9 } ]"/&gt;</pre></div><p>The string value of the <code>ref</code> attribute is <code>"[1 5 6 7 9]"</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;shoe size="As big as { $hat/@size }"/&gt;</pre></div><p>The string value of the <code>size</code> attribute is the
string <code>"As big as "</code>, concatenated with the string value of the
node denoted by the expression
  <code>$hat/@size</code>.</p></li></ul></div><div class="div4">
<h5><a id="id-namespaces"/>4.12.1.2 <a href="#id-namespaces" style="text-decoration: none">Namespace Declaration Attributes</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-computedElements">⬇</a> <a href="#id-logical-expressions">⬆</a></p><ol><li><p>
                     The <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> 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.
                   <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/65">65</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/753">753</a> 31 October 2023]</i></p></li></ol></div><p>The names of
  a constructed element and its attributes may be <a title="lexical QName" class="termref" href="#dt-qname">lexical QNames</a> that
  include <b>namespace prefixes</b>. Namespace prefixes can be
  bound to namespaces in the <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a> or by  <b>namespace
  declaration attributes</b>. It is a
  <a title="static error" class="termref" href="#dt-static-error">static error</a> to use a
  namespace prefix that has not been bound to a namespace [<a href="#ERRXPST0081" title="err:XPST0081">err:XPST0081</a>].</p><p>
                     [<a id="dt-namespace-decl-attr" title="namespace declaration attribute">Definition</a>: A <b>namespace declaration
attribute</b> is used inside a direct element constructor. Its
purpose is to bind a namespace prefix <span>(including the zero-length prefix)</span> for
the constructed element node, including its attributes.]
Syntactically, a namespace declaration attribute has the form of an
attribute with namespace prefix <code>xmlns</code>, or with name
<code>xmlns</code> and no namespace prefix. All the namespace
declaration attributes of a given element must have distinct names
[<a href="#ERRXQST0071" title="err:XQST0071">err:XQST0071</a>]. Each namespace declaration
attribute is processed as follows:</p><ul><li><p>The value of the namespace declaration attribute (a <a href="#prod-xquery40-DirAttributeValue">DirAttributeValue</a>) is processed as follows. If the <a href="#prod-xquery40-DirAttributeValue">DirAttributeValue</a> contains an <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a>, a static error is raised [<a href="#ERRXQST0022" title="err:XQST0022">err:XQST0022</a>]. Otherwise, it is processed as described in rule 1 of <a href="#id-attributes"><b>4.12.1.1 Attributes</b></a>. An implementation may raise a static error[<a href="#ERRXQST0046" title="err:XQST0046">err:XQST0046</a>] if the resulting value is of
                           nonzero length and is neither an absolute URI nor a
                           relative URI. The resulting value is used as the namespace
                           URI in the following rules.
                           </p></li><li><p>If the prefix of the attribute name is <code>xmlns</code>, then the
                     local part of the attribute name is interpreted as a namespace prefix.
                     This prefix and the namespace URI are added to the
                     <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>
                     of the constructor expression (overriding any existing binding of
                     the given prefix), and are also added as a <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> to the
                     <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a>
                        of the constructed element. If the namespace URI is a zero-length
                        string and the implementation supports <a href="#XMLNAMES11">[XML Names 1.1]</a>,
                        any existing namespace binding for the given prefix is removed from the
                        <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a>
                        of the constructed element and from the
                        <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>
                        of the constructor expression. If the namespace URI is a zero-length
                        string and the implementation does not support <a href="#XMLNAMES11">[XML Names 1.1]</a>,
                        a static error is raised [<a href="#ERRXQST0085" title="err:XQST0085">err:XQST0085</a>]. It is
                        <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>
                        whether an implementation supports <a href="#XMLNAMES">[XML Names]</a> or
                        <a href="#XMLNAMES11">[XML Names 1.1]</a>.
                     </p></li><li><p>If the name of the namespace declaration attribute is <code>xmlns</code>
                        with no prefix, then:</p><ul><li><p>If the namespace URI is a zero-length string, then:</p><ul><li><p>Any <a title="default in-scope namespace" class="termref" href="#dt-default-in-scope-namespace">default in-scope namespace</a> is removed from the
                                 <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> of the constructed element
                                 and from the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>
                                 of the constructor expression.</p></li><li><p>Unless
                                 the query prolog contains a default namespace declaration or import schema declaration
                                 defining the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> as being
                                 <code>fixed</code>, the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> 
                                 in the static context of the element constructor is set to <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>.</p></li></ul></li><li><p>Otherwise (when the namespace URI is not a zero-length string):
                           </p><ul><li><p>The namespace URI is added (with no prefix) to the <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> of the constructed element 
                                 (overriding any existing binding of the zero-length prefix), 
                                 and to the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>
                                 of the constructor expression.</p></li><li><p>Unless
                                 the query prolog contains a default namespace declaration or import schema declaration
                                 defining the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> as being
                                 <code>fixed</code>, the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> 
                                 in the static context of the constructor expression is set to the specified namespace URI.</p></li></ul></li></ul></li><li><p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
                           [<a href="#ERRXQST0070" title="err:XQST0070">err:XQST0070</a>] if a namespace declaration
                attribute attempts to do any of the following:
                </p><ul><li><p>Bind the prefix <code>xml</code> to some namespace URI
                      other than <code>http://www.w3.org/XML/1998/namespace</code>.
                   </p></li><li><p>Bind a prefix other than <code>xml</code> to the namespace
                      URI <code>http://www.w3.org/XML/1998/namespace</code>.
                   </p></li><li><p>Bind the prefix <code>xmlns</code> to any namespace URI.
                   </p></li><li><p>Bind a prefix to the namespace
                      URI <code>http://www.w3.org/2000/xmlns/</code>.
                   </p></li></ul></li></ul><p> A namespace declaration attribute does not cause an attribute node to be created. </p><p>The following examples illustrate namespace declaration attributes:</p><ul><li><p>In this element constructor, a namespace declaration attribute
                        is used to set the default namespace
                        to <code>http://example.org/animals</code>:</p><div class="exampleInner"><pre>&lt;cat xmlns="http://example.org/animals"&gt;
  &lt;breed&gt;{ variety/@name }&lt;/breed&gt;
&lt;/cat&gt;</pre></div><p>More specifically:</p><ul><li><p>The expanded name of the constructed element will be 
                           <code>Q{http://example.org/animals}cat</code>.</p></li><li><p>The constructed element will have the
                           <a title="default in-scope namespace" class="termref" href="#dt-default-in-scope-namespace">default in-scope namespace</a>
                                 <code>http://example.org/animals</code>.</p></li><li><p>The static context for evaluation of any expressions within the
                        element constructor will include a binding of the empty prefix
                        to the namespace URI <code>http://example.org/animals</code>. This ensures
                        that the nested <code>breed</code> element will also be in the namespace
                           <code>http://example.org/animals</code>.</p></li><li><p>The <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>
                           within the element constructor will be <code>http://example.org/animals</code>,
                        which means that the element name <code>variety</code> is also interpreted
                        as being in this namespace. This effect may be unwanted, since the document
                        containing the context node may well use a different default namespace. 
                        In XQuery 4.0 this effect can
                        be prevented by declaring, in the query prolog, that the 
                           <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> is <code>fixed</code>.
                        Alternatively the path expression can be written <code>Q{}variety/@name</code>
                        to make it explicit that <code>variety</code> refers to a no-namespace element.</p></li></ul></li><li><p>In this element constructor, namespace declaration attributes are used to bind the namespace prefixes <code>metric</code> and <code>english</code>:</p><div class="exampleInner"><pre>&lt;box xmlns:metric="http://example.org/metric/units"
     xmlns:english = "http://example.org/english/units"&gt;
  &lt;height&gt; &lt;metric:meters&gt;3&lt;/metric:meters&gt; &lt;/height&gt;
  &lt;width&gt; &lt;english:feet&gt;6&lt;/english:feet&gt; &lt;/width&gt;
  &lt;depth&gt; &lt;english:inches&gt;18&lt;/english:inches&gt; &lt;/depth&gt;
&lt;/box&gt;</pre></div></li></ul></div><div class="div4">
<h5><a id="id-content"/>4.12.1.3 <a href="#id-content" style="text-decoration: none">Content</a></h5><p>The part of a direct element constructor between the start tag and the end tag is called the <b>content</b> of the element constructor. This content may consist of text characters (parsed as <a href="#prod-xquery40-ElementContentChar">ElementContentChar</a>), nested direct constructors, <a href="#prod-xquery40-CDataSection">CDataSections</a>, character and <a title="predefined entity reference" class="termref" href="#dt-predefined-entity-reference">predefined entity references</a>, and <a title="enclosed expression" class="termref" href="#dt-enclosed-expression">enclosed expressions</a>. In general, the value of an enclosed expression may be any sequence of nodes and/or atomic items. Enclosed expressions can be used in the content of an element  constructor to compute both the content and the attributes of the constructed node.</p><p>Conceptually, the content of an element constructor is processed as
follows:</p><ol class="enumar"><li><p>The content is evaluated to produce a
sequence of nodes called the <b>content sequence</b>, as
follows:</p><ol class="enumla"><li><p>If the <a title="boundary-space policy" class="termref" href="#dt-boundary-space-policy">boundary-space policy</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a> is <code>strip</code>, <a title="boundary whitespace" class="termref" href="#dt-boundary-whitespace">boundary whitespace</a> is identified and deleted (see <a href="#id-whitespace"><b>4.12.1.4 Boundary Whitespace</b></a> for the definition of boundary whitespace.)</p></li><li><p>
                                 <a title="predefined entity reference" class="termref" href="#dt-predefined-entity-reference">Predefined entity references</a>
and <a title="character reference" class="termref" href="#dt-character-reference">character references</a> are expanded into their
referenced strings, as described in <a href="#id-literals"><b>4.2.1 Literals</b></a>. Characters inside a <a href="#prod-xquery40-CDataSection">CDataSection</a>, including special characters such as <code>&lt;</code> and <code>&amp;</code>, are treated as literal characters rather than as markup characters (except for the sequence <code>]]&gt;</code>, which terminates the CDataSection).</p></li><li><p>Each consecutive sequence of
literal characters evaluates to a single text node containing the
characters.</p></li><li><p>Each nested direct constructor is evaluated according to the rules in <a href="#id-element-constructor"><b>4.12.1 Direct Element Constructors</b></a> or <a href="#id-otherConstructors"><b>4.12.2 Other Direct Constructors</b></a>, resulting in a new element, comment, or processing instruction node. Then:</p><ol class="enumlr"><li><p>The <code>parent</code> property of the resulting node is then set to the newly constructed element node.</p></li><li><p>The <code>base-uri</code> property of the
resulting node, and of each of its descendants, is set to be the same as that
of its new parent, unless it (the child node) has an <code>xml:base</code> attribute, in
which case its <code>base-uri</code> property is set to the value of that attribute,
<a title="resolve" class="termref" href="#dt-resolve-relative-uri">resolved (if it is relative)</a> against the <code>base-uri</code> property of its new parent
node.</p></li></ol></li><li><p>Enclosed expressions are evaluated as follows: </p><ol class="enumlr"><li><p>Each array returned by the enclosed expression is flattened by calling the function <code>array:flatten()</code> before the steps that follow.</p></li><li><p>If an enclosed expression returns a <a title="function item" class="termref" href="#dt-function-item">function item</a>, a type error is raised [<a href="#ERRXQTY0105" title="err:XQTY0105">err:XQTY0105</a>].</p></li><li><p>For each adjacent sequence of one or more atomic items returned by an enclosed expression, a new text node is constructed, containing the result of casting each atomic item to a string, with a single space character inserted between adjacent values.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The insertion of blank characters between adjacent values applies even if one or both of the values is a zero-length string.</p></div></li><li><p>For each node returned by an enclosed expression, a new copy is made of the given node and all nodes that have the given node as an ancestor,  collectively referred to as <b>copied nodes</b>. The properties of the copied nodes are as follows:</p><ol class="enumua"><li><p>Each copied node receives a new node identity.</p></li><li><p>The <code>parent</code>, <code>children</code>, and <code>attributes</code> properties of the copied nodes are set so as to preserve their inter-node relationships. For the topmost node (the node directly returned by the enclosed expression), the <code>parent</code> property is set to the node constructed by this constructor.</p></li><li><p>If <a title="construction mode" class="termref" href="#dt-construction-mode">construction mode</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a> is <code>strip</code>:</p><ol class="enumur"><li><p>If the copied node is an element node, its <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> is set to  <code>xs:untyped</code>. Its <code>nilled</code>, <code>is-id</code>, and <code>is-idrefs</code> properties are set to <code>false</code>.</p></li><li><p>If the copied node is an attribute node, its <code>type-name</code> property  is set to <code>xs:untypedAtomic</code>. Its <code>is-idrefs</code> property is set to <code>false</code>. Its <code>is-id</code> property is set to <code>true</code> if the qualified name of the attribute node is <code>xml:id</code>; otherwise it is set to <code>false</code>.</p></li><li><p>The <code>string-value</code> of each copied element and attribute node remains unchanged, and its <code>typed-value</code> becomes equal to its <code>string-value</code> as an instance of <code>xs:untypedAtomic</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p> Implementations that store only the <a title="typed value" class="termref" href="#dt-typed-value">typed value</a> of a node are required at this point to convert the typed value to a string form.</p></div></li></ol><p>On the other hand, if <a title="construction mode" class="termref" href="#dt-construction-mode">construction mode</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a> is <code>preserve</code>, the <code>type-name</code>, <code>nilled</code>, 
                                          <code>string-value</code>, <code>typed-value</code>, <code>is-id</code>, and <code>is-idrefs</code> 
                                          properties of the copied nodes are preserved.</p></li><li><p>The <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> property of a copied element node is
                                          determined by the following rules. In applying these rules, the 
                                          <a title="default in-scope namespace" class="termref" href="#dt-default-in-scope-namespace">default in-scope namespace</a>
                                          or absence of a default in-scope namespace is treated like any other
                                          <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a>:</p><ol class="enumur"><li><p>If <a title="copy-namespaces mode" class="termref" href="#dt-copy-namespaces-mode">copy-namespaces mode</a> specifies <code>preserve</code>, 
                                                all <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> of the original element are
                                                   retained in the new copy.
                                                   If <a title="copy-namespaces mode" class="termref" href="#dt-copy-namespaces-mode">copy-namespaces mode</a> specifies <code>no-preserve</code>, 
                                                the new copy retains only those in-scope namespaces of the original 
                                                element that are used in the names of the element and its
                                                 attributes.</p></li><li><p>If <a title="copy-namespaces mode" class="termref" href="#dt-copy-namespaces-mode">copy-namespaces mode</a> specifies <code>inherit</code>, 
                                                the copied node inherits all the <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> of the constructed node,
                                                augmented and overridden by the in-scope namespaces of the original element 
                                                that were preserved by the preceding rule. If <a title="copy-namespaces mode" class="termref" href="#dt-copy-namespaces-mode">copy-namespaces mode</a> specifies <code>no-inherit</code>, 
                                                the copied node does not inherit any in-scope namespaces from the constructed node.</p></li></ol></li><li><p>An enclosed expression in the content of an element constructor may cause 
                                          one or more existing nodes to be copied. Type error
                                          [<a href="#ERRXQTY0086" title="err:XQTY0086">err:XQTY0086</a>]
                                          is raised in the following cases:</p><ol class="enumur"><li><p>
                                                An element node is copied, and the
                                                <a title="typed value" class="termref" href="#dt-typed-value">typed value</a> of the element node 
                                                or one of its attributes is
                                                <a title="namespace-sensitive" class="termref" href="#dt-namespace-sensitive">namespace-sensitive</a>,
                                                and <a title="construction mode" class="termref" href="#dt-construction-mode">construction mode</a>
                                                is <code>preserve</code>, and
                                                <a title="copy-namespaces mode" class="termref" href="#dt-copy-namespaces-mode">copy-namespaces mode</a>
                                                is <code>no-preserve</code>.
                                                </p></li><li><p>
An attribute node is copied but its parent element node is not
copied, and the <a title="typed value" class="termref" href="#dt-typed-value">typed value</a>
of the copied attribute node is
<a title="namespace-sensitive" class="termref" href="#dt-namespace-sensitive">namespace-sensitive</a>,
and <a title="construction mode" class="termref" href="#dt-construction-mode">construction mode</a>
is <code>preserve</code>.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>
                The rationale for error [<a href="#ERRXQTY0086" title="err:XQTY0086">err:XQTY0086</a>] is as follows:
                It is not possible to preserve the type of a QName without also preserving
                the <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> that defines the prefix of the QName.</p></div></li><li><p>When an element or processing instruction node is copied, its <code>base-uri</code>
property is set to be the same as that of its new parent,
with the following exception: if a copied element node has an <code>xml:base</code> attribute, its <code>base-uri</code> property is set to
the value of that attribute, <a title="resolve" class="termref" href="#dt-resolve-relative-uri">resolved (if it is relative)</a> against
the <code>base-uri</code> property of the new parent node.</p></li><li><p>All other properties of the copied nodes are preserved.</p></li></ol></li></ol></li></ol></li><li><p> If the content sequence contains a document node, the document node is replaced in the content sequence by its children.</p></li><li><p>Adjacent text nodes in the content sequence are merged into a single text node by concatenating their contents, with no intervening blanks. After concatenation, any text node whose content is a zero-length string is deleted from the content sequence.</p></li><li><p>If the content sequence contains an attribute node or a
namespace node following a node that is not an attribute node or a
namespace node, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is
raised [<a href="#ERRXQTY0024" title="err:XQTY0024">err:XQTY0024</a>].</p></li><li><p>The properties of the newly constructed element node are determined as follows:</p><ol class="enumla"><li><p>
                                 <code>node-name</code> is the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> resulting from resolving the element name in the start tag, including its original namespace prefix (if any), as described in <a href="#id-element-constructor"><b>4.12.1 Direct Element Constructors</b></a>.</p></li><li><p>
                                 <code>parent</code> is set to empty.</p></li><li><p>
                                 <code>attributes</code> consist of all the attributes specified in the start tag as described in <a href="#id-attributes"><b>4.12.1.1 Attributes</b></a>, together with all the attribute nodes in the content sequence, in <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> order. Note that the <code>parent</code> property of each of these attribute nodes has been set to the newly constructed element node. If two or more attributes have the same <code>node-name</code>,  a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> is raised [<a href="#ERRXQDY0025" title="err:XQDY0025">err:XQDY0025</a>]. If an attribute named <code>xml:space</code> has a value other than <code>preserve</code> or <code>default</code>, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>  may be raised [<a href="#ERRXQDY0092" title="err:XQDY0092">err:XQDY0092</a>].</p></li><li><p>
                                 <code>children</code> consist of all the element, text, comment, and processing
   instruction nodes in the content sequence. Note that the <code>parent</code> property of each of these nodes has been set to the newly constructed element node.</p></li><li><p>
                                 <code>base-uri</code> is set to the following value:</p><ol class="enumlr"><li><p>If the constructed node has an attribute named <code>xml:base</code>, then the value of this attribute, <a title="resolve" class="termref" href="#dt-resolve-relative-uri">resolved (if it is relative)</a> against the
                                       <span>
                                          <a title="Executable Base URI" class="termref" href="#dt-executable-base-uri">Executable Base URI</a>
                                       </span>, as described in
                                       <a href="#id-resolve-relative-uri"><b>2.5.6 Resolving a Relative URI Reference</b></a>. </p></li><li><p>Otherwise,
                                       the <span>
                                          <a title="Executable Base URI" class="termref" href="#dt-executable-base-uri">Executable Base URI</a>
                                       </span>.</p></li></ol></li><li><p>
                              The <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> comprise all 
                              the <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace bindings</a> 
                              resulting from namespace declaration attributes as described in <a href="#id-namespaces"><b>4.12.1.2 Namespace Declaration Attributes</b></a>, and possibly additional namespace bindings as described in <a href="#id-ns-nodes-on-elements"><b>4.12.4 In-scope Namespaces of a Constructed Element</b></a>.</p></li><li><p>The <code>nilled</code> property is <code>false</code>.</p></li><li><p>The <code>string-value</code> property is equal to the concatenated contents of the text-node descendants in document order. If there are no text-node descendants, the <code>string-value</code> property is a zero-length string.</p></li><li><p>The <code>typed-value</code> property is equal to the <code>string-value</code> property, as an instance of <code>xs:untypedAtomic</code>.</p></li><li><p>If <a title="construction mode" class="termref" href="#dt-construction-mode">construction mode</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a> is <code>strip</code>, the <code>type-name</code> property is <code>xs:untyped</code>. On the other hand, if construction mode is <code>preserve</code>, the <code>type-name</code> property is <code>xs:anyType</code>.</p></li><li><p>The <code>is-id</code> and <code>is-idrefs</code> properties are set to <code>false</code>.</p></li></ol></li></ol><ul><li><p>Example:</p><div class="exampleInner"><pre>&lt;a&gt;{ 1 }&lt;/a&gt;</pre></div><p>The constructed element node has one child, a text node containing the value <code>"1"</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;a&gt;{ 1, 2, 3 }&lt;/a&gt;</pre></div><p>The constructed element node has one child, a text node containing the value <code>"1 2 3"</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;c&gt;{ 1 }{ 2 }{ 3 }&lt;/c&gt;</pre></div><p>The constructed element node has one child, a text node containing the value <code>"123"</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;b&gt;{ 1, "2", "3" }&lt;/b&gt;</pre></div><p>The constructed element node has one child, a text node containing the value <code>"1 2 3"</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;fact&gt;I saw 8 cats.&lt;/fact&gt;</pre></div><p>The constructed element node has one child, a text node containing the value <code>"I saw 8 cats."</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;fact&gt;I saw { 5 + 3 } cats.&lt;/fact&gt;</pre></div><p>The constructed element node has one child, a text node containing the value <code>"I saw 8 cats."</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;fact&gt;I saw &lt;howmany&gt;{ 5 + 3 }&lt;/howmany&gt; cats.&lt;/fact&gt;</pre></div><p>The constructed element node has three children: a text node containing
                        <code>"I saw </code> ", a child element node named <code>howmany</code>,
                        and a text node containing <code>" cats."</code>. The child element node
                        in turn has a single text node child containing the value <code>"8"</code>.</p></li></ul></div><div class="div4">
<h5><a id="id-whitespace"/>4.12.1.4 <a href="#id-whitespace" style="text-decoration: none">Boundary Whitespace</a></h5><p>In a direct element constructor, whitespace characters may appear in the content of the constructed element. In some cases, enclosed expressions and/or nested elements may be separated only by whitespace characters.   For
example, in the expression below, the end-tag
<code>&lt;/title&gt;</code> and the start-tag <code>&lt;author&gt;</code> are separated by a newline character and four space
characters:</p><div class="exampleInner"><pre>&lt;book isbn="isbn-0060229357"&gt;
  &lt;title&gt;Harold and the Purple Crayon&lt;/title&gt;
  &lt;author&gt;
    &lt;first&gt;Crockett&lt;/first&gt;
    &lt;last&gt;Johnson&lt;/last&gt;
  &lt;/author&gt;
&lt;/book&gt;</pre></div><p>
                     [<a id="dt-boundary-whitespace" title="boundary whitespace">Definition</a>: 
                        <b>Boundary whitespace</b> is a
sequence of consecutive whitespace characters within the content of a <a title="direct element constructor" class="termref" href="#dt-direct-elem-const">direct element constructor</a>, that is delimited at each end either by the start or
end of the content, or by a <a href="#prod-xquery40-DirectConstructor">DirectConstructor</a>, or by an <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a>. For this purpose, characters generated by
   <a title="character reference" class="termref" href="#dt-character-reference">character references</a> such as <code>&amp;#x20;</code> or by <a href="#prod-xquery40-CDataSection">CDataSections</a> are not
   considered to be whitespace characters.]
                  </p><p>The <a title="boundary-space policy" class="termref" href="#dt-boundary-space-policy">boundary-space policy</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a> controls whether boundary whitespace is
   preserved by element constructors. If boundary-space policy is <code>strip</code>, boundary whitespace is not considered significant and
   is discarded. On the other hand, if boundary-space policy is <code>preserve</code>, boundary whitespace is
   considered significant and is
   preserved.</p><ul><li><p>Example:</p><div class="exampleInner"><pre>&lt;cat&gt;
  &lt;breed&gt;{ $b }&lt;/breed&gt;
  &lt;color&gt;{ $c }&lt;/color&gt;
&lt;/cat&gt;</pre></div><p>The constructed
   <code>cat</code> element node has two child element nodes named
   <code>breed</code> and <code>color</code>. Whitespace surrounding
   the child elements will be stripped away by the element
   constructor if boundary-space policy is
   <code>strip</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;a&gt; { "abc" } &lt;/a&gt;</pre></div><p>If
   boundary-space policy is <code>strip</code>, this example is equivalent to <code>&lt;a&gt;abc&lt;/a&gt;</code>. However, if
   boundary-space policy is <code>preserve</code>, this example is
   equivalent to <code>&lt;a&gt;  abc  &lt;/a&gt;</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;a&gt; z { "abc" }&lt;/a&gt;</pre></div><p>Since the
   whitespace surrounding the <code>z</code> is not boundary
   whitespace, it is always preserved. This example is equivalent to
   <code>&lt;a&gt; z abc&lt;/a&gt;</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;a&gt;&amp;#x20;{ "abc" }&lt;/a&gt;</pre></div><p>This
   example is equivalent to <code>&lt;a&gt; abc&lt;/a&gt;</code>, regardless
   of the boundary-space policy, because the space generated by the <a title="character reference" class="termref" href="#dt-character-reference">character reference</a> is not treated as a whitespace character.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;a&gt;{ "  " }&lt;/a&gt;</pre></div><p>This example constructs an element containing two space characters,
   regardless of the boundary-space policy, because whitespace inside an enclosed expression is never considered to be boundary whitespace.</p></li><li><p>Example:</p><div class="exampleInner"><pre>&lt;a&gt;{ [ "one", "little", "fish" ] }&lt;/a&gt;</pre></div><p>This example constructs an element containing the text <code>one little fish</code>, because the array is flattened, and the resulting sequence of atomic items is converted to a text node with a single blank between values.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>Element constructors treat attributes named <code>xml:space</code> as ordinary attributes. An <code>xml:space</code> attribute does not affect the handling of whitespace by an element constructor.</p></div></div></div><div class="div3">
<h4><a id="id-otherConstructors"/>4.12.2 <a href="#id-otherConstructors" style="text-decoration: none">Other Direct Constructors</a></h4><p>XQuery allows an expression to generate a processing instruction node or a comment node. This can be accomplished by using a <b>direct processing instruction constructor</b> or a <b>direct comment constructor</b>. In each case, the syntax of the constructor expression is
based on the syntax of a similar construct in XML.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DirPIConstructor"/><code><a href="#prod-xquery40-DirPIConstructor">DirPIConstructor</a></code></td><td>::=</td><td><code>"&lt;?"  <a href="#doc-xquery40-DirPIConstructor-PITarget">PITarget</a>  (<a href="#doc-xquery40-DirPIConstructor-S">S</a>
                        <a href="#doc-xquery40-DirPIConstructor-DirPIContents">DirPIContents</a>)?  "?&gt;"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DirPIConstructor-PITarget"/><code><a href="#prod-xquery40-PITarget">PITarget</a></code></td><td>::=</td><td><code>
                        <a href="https://www.w3.org/TR/REC-xml/#NT-PITarget">[http://www.w3.org/TR/REC-xml#NT-PITarget]</a><sup><small>XML</small></sup>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-xml-version">xgc: xml-version</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DirPIConstructor-S"/><code><a href="#prod-xquery40-S">S</a></code></td><td>::=</td><td><code>
                        <a href="https://www.w3.org/TR/REC-xml/#NT-S">[http://www.w3.org/TR/REC-xml#NT-S]</a><sup><small>XML</small></sup>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-xml-version">xgc: xml-version</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DirPIConstructor-DirPIContents"/><code><a href="#prod-xquery40-DirPIContents">DirPIContents</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-DirPIConstructor-Char">Char</a>* - (Char* '?&gt;' Char*))</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DirPIConstructor-Char"/><code><a href="#prod-xquery40-Char">Char</a></code></td><td>::=</td><td><code>
                        <a href="https://www.w3.org/TR/REC-xml/#NT-Char">[http://www.w3.org/TR/REC-xml#NT-Char]</a><sup><small>XML</small></sup>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-xml-version">xgc: xml-version</a>
                      */</td></tr></tbody></table><p>A direct processing instruction constructor creates a processing instruction node whose <code>target</code> property is <a href="#prod-xquery40-PITarget">PITarget</a> and whose <code>content</code> property is <a href="#prod-xquery40-DirPIContents">DirPIContents</a>. The <code>base-uri</code> property of the node is empty.  The <code>parent</code> property of the node is empty.</p><p>The <a href="#prod-xquery40-PITarget">PITarget</a> of a processing instruction must not consist of the characters <code>XML</code> in any combination of upper and lower case,
               <span>and must not contain a colon</span>. The <a href="#prod-xquery40-DirPIContents">DirPIContents</a> of a processing instruction must not contain the string <code>"?&gt;"</code>.</p><p>The following example illustrates a direct processing instruction constructor:</p><div class="exampleInner"><pre>&lt;?format role="output" ?&gt;</pre></div><p>A direct comment constructor creates a comment node whose  <code>content</code> property is <a href="#prod-xquery40-DirCommentContents">DirCommentContents</a>. Its <code>parent</code> property is empty.</p><p>The <a href="#prod-xquery40-DirCommentContents">DirCommentContents</a> of a comment must not contain two consecutive hyphens or end with a hyphen. These rules are syntactically enforced by the grammar shown above.</p><p>The following example illustrates a direct comment constructor:</p><div class="exampleInner"><pre>&lt;!-- Tags are ignored in the following section --&gt;</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>A direct comment constructor is different from a <a href="#doc-xquery40-Comment">comment</a>, since a direct comment constructor actually constructs a comment node, whereas a <a href="#doc-xquery40-Comment">comment</a> is simply used in documenting a query and is not evaluated.</p></div></div><div class="div3">
<h4><a id="id-computedConstructors"/>4.12.3 <a href="#id-computedConstructors" style="text-decoration: none">Computed Constructors</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComputedConstructor"/><code><a href="#prod-xquery40-ComputedConstructor">ComputedConstructor</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-ComputedConstructor-CompDocConstructor">CompDocConstructor</a>
                        <br/>|  <a href="#doc-xquery40-ComputedConstructor-CompElemConstructor">CompElemConstructor</a>
                        <br/>|  <a href="#doc-xquery40-ComputedConstructor-CompAttrConstructor">CompAttrConstructor</a>
                        <br/>|  <a href="#doc-xquery40-ComputedConstructor-CompNamespaceConstructor">CompNamespaceConstructor</a>
                        <br/>|  <a href="#doc-xquery40-ComputedConstructor-CompTextConstructor">CompTextConstructor</a>
                        <br/>|  <a href="#doc-xquery40-ComputedConstructor-CompCommentConstructor">CompCommentConstructor</a>
                        <br/>|  <a href="#doc-xquery40-ComputedConstructor-CompPIConstructor">CompPIConstructor</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComputedConstructor-CompDocConstructor"/><code><a href="#prod-xquery40-CompDocConstructor">CompDocConstructor</a></code></td><td>::=</td><td><code>"document"  <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComputedConstructor-CompElemConstructor"/><code><a href="#prod-xquery40-CompElemConstructor">CompElemConstructor</a></code></td><td>::=</td><td><code>"element"  <a href="#prod-xquery40-CompNodeName">CompNodeName</a>
                        <a href="#prod-xquery40-EnclosedContentExpr">EnclosedContentExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComputedConstructor-CompAttrConstructor"/><code><a href="#prod-xquery40-CompAttrConstructor">CompAttrConstructor</a></code></td><td>::=</td><td><code>"attribute"  <a href="#prod-xquery40-CompNodeName">CompNodeName</a>
                        <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComputedConstructor-CompNamespaceConstructor"/><code><a href="#prod-xquery40-CompNamespaceConstructor">CompNamespaceConstructor</a></code></td><td>::=</td><td><code>"namespace"  <a href="#prod-xquery40-CompNodeNCName">CompNodeNCName</a>
                        <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComputedConstructor-CompTextConstructor"/><code><a href="#prod-xquery40-CompTextConstructor">CompTextConstructor</a></code></td><td>::=</td><td><code>"text"  <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComputedConstructor-CompCommentConstructor"/><code><a href="#prod-xquery40-CompCommentConstructor">CompCommentConstructor</a></code></td><td>::=</td><td><code>"comment"  <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ComputedConstructor-CompPIConstructor"/><code><a href="#prod-xquery40-CompPIConstructor">CompPIConstructor</a></code></td><td>::=</td><td><code>"processing-instruction"  <a href="#prod-xquery40-CompNodeNCName">CompNodeNCName</a>
                        <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr></tbody></table><p>An alternative way to create nodes is by using a <b>computed constructor</b>. A computed
constructor begins with a keyword that identifies the type of node to
be created: <code>element</code>, <code>attribute</code>,
<code>document</code>, <code>text</code>,
<code>processing-instruction</code>, <code>comment</code>, or
<code>namespace</code>.</p><p>For those kinds of nodes that have names (element, attribute, 
processing instruction, and namespace nodes), the keyword that specifies the node
kind is followed by the name of the node to be created. This name may
be specified either as an EQName or as an expression enclosed in
braces. [<a id="dt-name-expression" title="name expression">Definition</a>: When
an expression is used to specify the name of a constructed node, that
expression is called the <b>name expression</b> of the
constructor.]
               </p><p>The following example illustrates the use of computed element and
attribute constructors in a simple case where the names of the
constructed nodes are constants. This example generates exactly the
same result as the first example in <a href="#id-element-constructor"><b>4.12.1 Direct Element Constructors</b></a>:</p><div class="exampleInner"><pre>element book {
  attribute isbn { "isbn-0060229357" },
  element title { "Harold and the Purple Crayon" },
  element author {
    element first { "Crockett" },
    element last { "Johnson" }
  }
}</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>XQuery 4.0 allows the node name to be written in quotation
            marks (for example, <code>element "book" {}</code>, and at the same
            time it disallows the use of a defined set of language keywords
            without quotes: for example <code>element div {}</code> was allowed
            in XQuery 3.1 but must now be written <code>element #div {}</code> or
            <code>element { "div" } {}</code>. The reason for this incompatible
            change is that allowing map constructors to omit the <code>map</code>
            keyword would otherwise create an ambiguity: consider for example the
            expression <code>element otherwise {}</code>.</p><p>Because the list of reserved keywords may be extended in future
            versions of this specification, the safest strategy is to always use
            the <code>QNameLiteral</code> syntax (for example <code>element #div</code>).
            To avoid any dependency on the default namespace context, the form
            <code>element Q{}div</code> might also be used.</p><p>To write code that is portable between XQuery 3.1 and XQuery 4.0,
            the best advice is to use either the form <code>element { "div" }</code>
            or the form <code>element Q{}div</code>.</p></div><div class="div4">
<h5><a id="id-computedElements"/>4.12.3.1 <a href="#id-computedElements" style="text-decoration: none">Computed Element Constructors</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-computedAttributes">⬇</a> <a href="#id-namespaces">⬆</a></p><ol><li><p>
                     When the element name matches a language keyword such as <code>div</code> or <code>value</code>, 
                     it must now be written as a QName literal. This is a backwards incompatible change.
                  <i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/1450">1450</a> <a href="https://github.com/qt4cg/qtspecs/issues/1983">1983</a> PRs <a href="https://github.com/qt4cg/qtspecs/pull/1480">1480</a> <a href="https://github.com/qt4cg/qtspecs/pull/1989">1989</a> 3 October 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompElemConstructor"/><code><a href="#prod-xquery40-CompElemConstructor">CompElemConstructor</a></code></td><td>::=</td><td><code>"element"  <a href="#doc-xquery40-CompElemConstructor-CompNodeName">CompNodeName</a>
                           <a href="#doc-xquery40-CompElemConstructor-EnclosedContentExpr">EnclosedContentExpr</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompElemConstructor-CompNodeName"/><code><a href="#prod-xquery40-CompNodeName">CompNodeName</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-CompElemConstructor-QNameLiteral">QNameLiteral</a>  |  <a href="#doc-xquery40-CompElemConstructor-UnreservedName">UnreservedName</a>  |  ("{"  <a href="#doc-xquery40-CompElemConstructor-Expr">Expr</a>  "}")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompElemConstructor-QNameLiteral"/><code><a href="#prod-xquery40-QNameLiteral">QNameLiteral</a></code></td><td>::=</td><td><code>"#"  <a href="#doc-xquery40-CompElemConstructor-EQName">EQName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompElemConstructor-UnreservedName"/><code><a href="#prod-xquery40-UnreservedName">UnreservedName</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-CompElemConstructor-EQName">EQName</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#parse-note-unreserved-name">xgc: unreserved-name</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompElemConstructor-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompElemConstructor-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompElemConstructor-EnclosedContentExpr"/><code><a href="#prod-xquery40-EnclosedContentExpr">EnclosedContentExpr</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-CompElemConstructor-EnclosedExpr">EnclosedExpr</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompElemConstructor-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-CompElemConstructor-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>
                     [<a id="dt-computed-elem-const" title="computed element constructor">Definition</a>: A <b>computed element constructor</b> creates an element node, allowing both the name 
                     and the content of the node to be computed.]
                  </p><p>The element name is determined by the <a href="#prod-xquery40-CompNodeName">CompNodeName</a>, which 
                  may be provided in a number of ways:</p><ol class="enumar"><li><p>As a QName literal, for example:</p><blockquote><p>
                              <code>element #table {}</code>
                           <br/>
                              <code>element #html:table {}</code>
                           <br/>
                              <code>element #Q{}table {}</code>
                           <br/>
                              <code>element #Q{http://http://www.w3.org/1999/xhtml}table {}</code>
                           </p></blockquote><p>A QName literal written as an unprefixed <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>
                     (the first form above) is resolved using the 
                     <a title="constructed element namespace rule" class="termref" href="#dt-constructed-element-namespace-rule">constructed element namespace rule</a>. This differs from the normal rules for evaluating
                     a QName literal as an atomic item of type <code>xs:QName</code>.</p><p>Note that the last two examples (<code>#Q{}table</code> and 
                        <code>#Q{http://http://www.w3.org/1999/xhtml}table</code>) will result in the name of the
                     constructed element having no prefix, which may in turn trigger the generation of a default
                     namespace declaration.</p></li><li><p>As a simple <a href="#doc-xquery40-EQName">EQName</a>, for example:</p><blockquote><p>
                              <code>element table {}</code>
                           <br/>
                              <code>element html:table {}</code>
                           <br/>
                              <code>element Q{}table {}</code>
                           <br/>
                              <code>element Q{http://http://www.w3.org/1999/xhtml}table {}</code>
                           </p></blockquote><p>In XQuery 4.0 the first form (using an unprefixed <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>)
                     is allowed only if the element name is not a reserved keyword (such as <code>div</code> or <code>value</code>): see
                  <a href="#parse-note-unreserved-name">unreserved-name</a>. In all other cases,
                     the effect is exactly the same as when a leading <code>#</code>
                     is added to turn the EQName into a QName literal.</p><p>This syntax is retained for compatibility, but is deprecated.</p></li><li><p>As an expression in curly brackets. This is processed as follows:</p><ol class="enumla"><li><p>
                                 <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is applied to the value of the <a title="name expression" class="termref" href="#dt-name-expression">name expression</a>. If the result of atomization is not a single atomic item of type <code>xs:QName</code>, <code>xs:string</code>, or <code>xs:untypedAtomic</code>, a <a title="type error" class="termref" href="#dt-type-error">type
   error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>If the atomized value of the <a title="name expression" class="termref" href="#dt-name-expression">name expression</a> is of type
   <code>xs:QName</code>, that <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> is used as the <code>node-name</code> property of the constructed
   element, retaining the prefix part of the QName.</p></li><li><p>If the atomized value of the <a title="name expression" class="termref" href="#dt-name-expression">name expression</a> is of type <code>xs:string</code> or <code>xs:untypedAtomic</code>, 
                        that value is converted to an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>
                                 <span>as follows:</span>
                              </p><ol class="enumlr"><li><p>Leading and trailing whitespace is removed.</p></li><li><p>If the value is a lexical QName, it is expanded
                           using the <a title="constructed element namespace rule" class="termref" href="#dt-constructed-element-namespace-rule">constructed element namespace rule</a>.</p></li><li><p>If the value is a URI-qualified name (<code>Q{uri}local</code>), it
                           is converted to an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> with the supplied namespace URI and
                           local name, and with no prefix.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>This was under-specified in XQuery 3.1.</p></div></li><li><p>If conversion of the atomized <a title="name expression" class="termref" href="#dt-name-expression">name expression</a> to an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> is not successful, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> is raised [<a href="#ERRXQDY0074" title="err:XQDY0074">err:XQDY0074</a>].</p></li></ol></li></ol><p>The resulting <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> is used as the
                        <code>node-name</code> property of the constructed element, retaining the prefix part of the QName
                        <span>(or its absence)</span>.</p><p>An error is raised
             [<a href="#ERRXQDY0096" title="err:XQDY0096">err:XQDY0096</a>] if the node-name of the constructed
             element node has any of the following properties:
          </p><ul><li><p>Its namespace prefix is <code>xmlns</code>.
             </p></li><li><p>Its namespace URI is <code>http://www.w3.org/2000/xmlns/</code>.
             </p></li><li><p>Its namespace prefix is <code>xml</code> and its namespace
                URI is not <code>http://www.w3.org/XML/1998/namespace</code>.
             </p></li><li><p>Its namespace prefix is other than <code>xml</code> and its
                namespace URI is <code>http://www.w3.org/XML/1998/namespace</code>.
             </p></li></ul><p>The above error <span class="verb">may</span> be raised as a <a title="static error" class="termref" href="#dt-static-error">static error</a> if
               the element name is computed statically; in other cases it <span class="verb">must</span> 
                  be raised as a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>.</p><p>The <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> of a computed element constructor (if present) is processed in exactly the same way as an enclosed expression in the content of a <a title="direct element constructor" class="termref" href="#dt-direct-elem-const">direct element constructor</a>, as described in Step 1e of <a href="#id-content"><b>4.12.1.3 Content</b></a>. The result of processing the content expression is a sequence of nodes called the <b>content sequence</b>. If the <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> is absent, the content sequence is an empty sequence.</p><p>Processing of the computed element constructor proceeds as follows:</p><ol class="enumar"><li><p>If the content sequence contains a document node, the document node is replaced in the content sequence by its children.</p></li><li><p>Adjacent text nodes in the content sequence are merged into a single text node by concatenating their contents, with no intervening blanks. After concatenation, any text node whose content is a zero-length string is deleted from the content sequence.</p></li><li><p> If the content
   sequence contains an attribute node or a namespace node following a node that is not an
   attribute node or a namespace node, a <a title="type error" class="termref" href="#dt-type-error">type error</a>
   is raised [<a href="#ERRXQTY0024" title="err:XQTY0024">err:XQTY0024</a>].</p></li><li><p>The properties of the newly constructed element node are determined as follows:</p><ol class="enumla"><li><p>
                                 <code>node-name</code> is the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> resulting from processing the specified 
                              <a href="#prod-xquery40-CompNodeName">CompNodeName</a>, as described above.</p></li><li><p>
                                 <code>parent</code> is empty.</p></li><li><p>
                                 <code>attributes</code> consist of all the attribute nodes in the content sequence, in <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> order. Note that the <code>parent</code> property of each of these attribute nodes has been set to the newly constructed element node. If two or more  attributes have the same <code>node-name</code>,  a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> is raised [<a href="#ERRXQDY0025" title="err:XQDY0025">err:XQDY0025</a>]. If an attribute named <code>xml:space</code> has a value other than <code>preserve</code> or <code>default</code>, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>  may be raised [<a href="#ERRXQDY0092" title="err:XQDY0092">err:XQDY0092</a>].</p></li><li><p>
                                 <code>children</code> consist of all the element, text, comment, and processing
   instruction nodes in the content sequence. Note that the <code>parent</code> property of each of these nodes has been set to the newly constructed element node.</p></li><li><p>
                                 <code>base-uri</code> is set to the following value:

                              </p><ol class="enumlr"><li><p>If the constructed node has an attribute named <code>xml:base</code>, then the value of this attribute, <a title="resolve" class="termref" href="#dt-resolve-relative-uri">resolved (if it is relative)</a> against the 
                                       <span>
                                             <a title="Executable Base URI" class="termref" href="#dt-executable-base-uri">Executable Base URI</a>
                                          </span>, as described
                                       in <a href="#id-resolve-relative-uri"><b>2.5.6 Resolving a Relative URI Reference</b></a>.</p></li><li><p>Otherwise, the <span>
                                             <a title="Executable Base URI" class="termref" href="#dt-executable-base-uri">Executable Base URI</a>
                                          </span>.</p></li></ol></li><li><p>
                              The <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> are computed as described in <a href="#id-ns-nodes-on-elements"><b>4.12.4 In-scope Namespaces of a Constructed Element</b></a>.</p></li><li><p>The <code>nilled</code> property is <code>false</code>.</p></li><li><p>The <code>string-value</code> property is equal to the concatenated contents of the text-node descendants in document order.</p></li><li><p>The <code>typed-value</code> property is equal to the <code>string-value</code> property, as an instance of <code>xs:untypedAtomic</code>.</p></li><li><p>If <a title="construction mode" class="termref" href="#dt-construction-mode">construction mode</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a> is <code>strip</code>, the <code>type-name</code> property is <code>xs:untyped</code>. On the other hand, if construction mode is <code>preserve</code>, the <code>type-name</code> property is <code>xs:anyType</code>.</p></li><li><p>The <code>is-id</code> and <code>is-idrefs</code> properties are set to <code>false</code>.</p></li></ol></li></ol><p>A computed element constructor might be
   used to make a modified copy of an existing element. For example,
   if the variable <code>$e</code> is bound to an element with <a title="numeric" class="termref" href="#dt-numeric">numeric</a>
   content, the following constructor might be used to create a new
   element with the same name and attributes as <code>$e</code> and
   with numeric content equal to twice the value of
   <code>$e</code>:</p><div class="exampleInner"><pre>element { node-name($e) } { $e/@*, 2 * data($e) }</pre></div><p>In this example, if <code>$e</code> is
   bound by the expression <code>let $e := &lt;length
   units="inches"&gt;{ 5 }&lt;/length&gt;</code>, then the result of the
   example expression is the element <code>&lt;length
   units="inches"&gt;10&lt;/length&gt;</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The <a title="static type" class="termref" href="#dt-static-type">static type</a> of the expression <code>fn:node-name($e)</code> is <code>xs:QName?</code>, denoting zero or one QName. 
                     The example can be successfully evaluated as written provided that 
                     <code>$e</code> is bound to exactly one element node with numeric content.</p></div><p>One important
   purpose of computed constructors is to allow the name of a node to
   be computed. We will illustrate this feature by an expression that
   translates the name of an element from one language to
   another. Suppose that the variable <code>$dict</code> is bound to a
   <code>dictionary</code> element containing a sequence of <code>entry</code> elements, each of which encodes translations for a specific word.  Here is an example
   entry that encodes the German and Italian variants of the word “address”:</p><div class="exampleInner"><pre>
&lt;entry word="address"&gt;
  &lt;variant xml:lang="de"&gt;Adresse&lt;/variant&gt;
  &lt;variant xml:lang="it"&gt;indirizzo&lt;/variant&gt;
&lt;/entry&gt;</pre></div><p>Suppose further that the variable <code>$e</code> is bound to the following element:</p><div class="exampleInner"><pre>&lt;address&gt;123 Roosevelt Ave. Flushing, NY 11368&lt;/address&gt;</pre></div><p>Then the following expression generates a new element in which the name of <code>$e</code> has been translated into Italian and the content of <code>$e</code> (including its attributes, if any) has been preserved. The first enclosed expression after the <code>element</code> keyword generates the name of the element, and the second enclosed
expression generates the content and attributes:</p><div class="exampleInner"><pre>
element {
  $dict/entry[@word = name($e)]/variant[@xml:lang = "it"]
} {
  $e/@*, $e/node()
}</pre></div><p>The result of this expression is as follows:</p><div class="exampleInner"><pre>&lt;indirizzo&gt;123 Roosevelt Ave. Flushing, NY 11368&lt;/indirizzo&gt;</pre></div></div><div class="div4">
<h5><a id="id-computedAttributes"/>4.12.3.2 <a href="#id-computedAttributes" style="text-decoration: none">Computed Attribute Constructors</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-computed-pis">⬇</a> <a href="#id-computedElements">⬆</a></p><ol><li><p>
                     When the attribute name matches a language keyword such as <code>by</code> or <code>of</code>, 
                     it must now be written as a QName literal. This is a backwards incompatible change.
                  <i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/1450">1450</a> <a href="https://github.com/qt4cg/qtspecs/issues/1983">1983</a> PRs <a href="https://github.com/qt4cg/qtspecs/pull/1480">1480</a> <a href="https://github.com/qt4cg/qtspecs/pull/1989">1989</a> 3 October 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompAttrConstructor"/><code><a href="#prod-xquery40-CompAttrConstructor">CompAttrConstructor</a></code></td><td>::=</td><td><code>"attribute"  <a href="#doc-xquery40-CompAttrConstructor-CompNodeName">CompNodeName</a>
                           <a href="#doc-xquery40-CompAttrConstructor-EnclosedExpr">EnclosedExpr</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompAttrConstructor-CompNodeName"/><code><a href="#prod-xquery40-CompNodeName">CompNodeName</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-CompAttrConstructor-QNameLiteral">QNameLiteral</a>  |  <a href="#doc-xquery40-CompAttrConstructor-UnreservedName">UnreservedName</a>  |  ("{"  <a href="#doc-xquery40-CompAttrConstructor-Expr">Expr</a>  "}")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompAttrConstructor-QNameLiteral"/><code><a href="#prod-xquery40-QNameLiteral">QNameLiteral</a></code></td><td>::=</td><td><code>"#"  <a href="#doc-xquery40-CompAttrConstructor-EQName">EQName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompAttrConstructor-UnreservedName"/><code><a href="#prod-xquery40-UnreservedName">UnreservedName</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-CompAttrConstructor-EQName">EQName</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#parse-note-unreserved-name">xgc: unreserved-name</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompAttrConstructor-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompAttrConstructor-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompAttrConstructor-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-CompAttrConstructor-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>A computed attribute constructor creates a new attribute node,
   with its own node identity.</p><p>Attributes have no default namespace. The rules that expand attribute names create an  <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> prefix if an attribute name has a namespace URI but no prefix is provided.</p><p>The attribute name may be provided in a number of ways:</p><ol class="enumar"><li><p>As a QName literal, for example:</p><blockquote><p>
                              <code>attribute #width {}</code>
                           <br/>
                              <code>attribute #xsi:type {}</code>
                           <br/>
                              <code>attribute #Q{}width {}</code>
                           <br/>
                              <code>attribute #Q{http://www.w3.org/2001/XMLSchema-instance}type {}</code>
                           </p></blockquote><p>A QName literal written as an unprefixed <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>
                     (the first form above) is resolved using the <b>no-namespace rule</b>
                           <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.</p><p>Note that the last example (<code>#Q{http://www.w3.org/2001/XMLSchema-instance}type</code>) 
                        will result in the name of the
                     constructed attribute having a system-generated prefix.</p></li><li><p>As a simple <a href="#doc-xquery40-EQName">EQName</a>, for example:</p><blockquote><p>
                              <code>attribute width {}</code>
                           <br/>
                              <code>attribute xsi:type {}</code>
                           <br/>
                              <code>attribute Q{}width {}</code>
                           <br/>
                              <code>attribute Q{http://www.w3.org/2001/XMLSchema-instance}type {}</code>
                           </p></blockquote><p>In XQuery 4.0 the first form (using an unprefixed <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>)
                     is allowed only if the attribute name is not a reserved keyword (such as <code>div</code> or <code>value</code>): see
                  <a href="#parse-note-unreserved-name">unreserved-name</a>. In all other cases,
                     the effect is exactly the same as when a leading <code>#</code>
                     is added to turn the EQName into a QName literal.</p><p>This syntax is retained for compatibility, but is deprecated.</p></li><li><p>As an expression in curly brackets. This is processed as follows:</p><ol class="enumla"><li><p>
                                 <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is
     applied to the result of the <a title="name expression" class="termref" href="#dt-name-expression">name expression</a>. If the result
     of <a title="atomization" class="termref" href="#dt-atomization">atomization</a> is not a
     single atomic item of type <code>xs:QName</code>,
     <code>xs:string</code>, or <code>xs:untypedAtomic</code>, a
     <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised
     [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>If the atomized value of the <a title="name expression" class="termref" href="#dt-name-expression">name expression</a> is of type
   <code>xs:QName</code>:</p><ol class="enumlr"><li><p>If the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> returned by the atomized name expression has a namespace URI but has no prefix, it is given an <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> prefix.</p></li><li><p>The resulting <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> (including its prefix) is used as the <code>node-name</code> property of the constructed
attribute node.</p></li></ol></li><li><p>If the atomized value of the <a title="name expression" class="termref" href="#dt-name-expression">name expression</a> is of type <code>xs:string</code> or <code>xs:untypedAtomic</code>, 
                        that value is converted to an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>
                                 <span>as follows:</span>
                              </p><ol class="enumlr"><li><p>Leading and trailing whitespace is removed.</p></li><li><p>If the value is a lexical QName, it is expanded
                           using the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.</p></li><li><p>If the value is a URI-qualified name (<code>Q{uri}local</code>), it
                           is converted to an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> with the supplied namespace URI and
                           local name, and with an <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation   dependent</a> prefix.</p></li><li><p>If conversion of the atomized name expression to an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> is not successful, 
                           a dynamic error is raised [<a href="#ERRXQDY0074" title="err:XQDY0074">err:XQDY0074</a>].</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>This was under-specified in XQuery 3.1.</p></div></li></ol></li></ol><p>The resulting <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> (including its
   prefix) is used as the <code>node-name</code> property of the
   constructed attribute node. If expansion of the QName is not
   successful, a <a title="static error" class="termref" href="#dt-static-error">static error</a>
   is raised [<a href="#ERRXPST0081" title="err:XPST0081">err:XPST0081</a>].</p><p>If the keyword <code>attribute</code> is followed by a <a title="name expression" class="termref" href="#dt-name-expression">name expression</a>, the name
   expression is processed as follows:</p><p>A <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> is raised
             [<a href="#ERRXQDY0044" title="err:XQDY0044">err:XQDY0044</a>] if the node-name of the constructed
             attribute node has any of the following properties:
          </p><ul><li><p>Its namespace prefix is <code>xmlns</code>.
             </p></li><li><p>It has no namespace prefix and its local name is
                <code>xmlns</code>.
             </p></li><li><p>Its namespace URI is <code>http://www.w3.org/2000/xmlns/</code>.
             </p></li><li><p>Its namespace prefix is <code>xml</code> and its namespace
                URI is not <code>http://www.w3.org/XML/1998/namespace</code>.
             </p></li><li><p>Its namespace prefix is other than <code>xml</code> and its
                namespace URI is <code>http://www.w3.org/XML/1998/namespace</code>.
             </p></li></ul><p>The <a title="content expression" class="termref" href="#dt-content-expression">content
   expression</a> of a computed attribute constructor is
   processed as follows:</p><ol class="enumar"><li><p>
                           <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is
     applied to the result of the <a title="content expression" class="termref" href="#dt-content-expression">content expression</a>,
     converting it to a sequence of atomic items. (If the <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> is
     absent, the result of this step is an empty
     sequence.)</p></li><li><p>If the result of atomization is an empty sequence, the
     value of the attribute is the zero-length string. Otherwise, each
     atomic item in the atomized sequence is cast into a
     string.</p></li><li><p>The individual strings resulting from the previous step
     are merged into a single string by concatenating them with a
     single space character between each pair. The resulting string
     becomes the <code>string-value</code> property of the new
     attribute node. The <a title="type annotation" class="termref" href="#dt-type-annotation">type
     annotation</a> (<code>type-name</code> property) of the new
     attribute node is <code>xs:untypedAtomic</code>. The
     <code>typed-value</code> property of the attribute node is the
     same as its <code>string-value</code>, as an instance of
     <code>xs:untypedAtomic</code>.</p></li><li><p>The <code>parent</code> property of the attribute node
     is set to empty.</p></li><li><p>If the attribute name is <code>xml:id</code>, then
     <code>xml:id</code> processing is performed as defined in <a href="#XMLID">[XML ID]</a>. This ensures that the attribute node has the type
     <code>xs:ID</code> and that its value is properly normalized. If
     an error is encountered during <code>xml:id</code> processing, an
     implementation may raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>
                           [<a href="#ERRXQDY0091" title="err:XQDY0091">err:XQDY0091</a>].</p></li><li><p>If the attribute name is <code>xml:id</code>, the
     <code>is-id</code> property of the resulting attribute node is
     set to <code>true</code>; otherwise the <code>is-id</code>
     property is set to <code>false</code>. The <code>is-idrefs</code>
     property of the attribute node is unconditionally set to
     <code>false</code>.</p></li><li><p>If the attribute name is <code>xml:space</code> and the
     attribute value is other than <code>preserve</code> or
     <code>default</code>, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>  may be raised [<a href="#ERRXQDY0092" title="err:XQDY0092">err:XQDY0092</a>].</p></li></ol><ul><li><p>Example:</p><div class="exampleInner"><pre>attribute size { 4 + 3 }</pre></div><p>The <a title="string value" class="termref" href="#dt-string-value">string
     value</a> of the <code>size</code> attribute is
     <code>"7"</code> and its type is
     <code>xs:untypedAtomic</code>.</p></li><li><p>Example:</p><div class="exampleInner"><pre>
attribute {
  if ($sex = "M") then "husband" else "wife"
} {
  &lt;a&gt;Hello&lt;/a&gt;, 1 to 3, &lt;b&gt;Goodbye&lt;/b&gt;
}</pre></div><p>The name of the constructed attribute is
     either <code>husband</code> or
     <code>wife</code>. Its <a title="string value" class="termref" href="#dt-string-value">string
     value</a> is "<code>Hello 1 2 3
     Goodbye</code>".</p></li></ul></div><div class="div4">
<h5><a id="id-documentConstructors"/>4.12.3.3 <a href="#id-documentConstructors" style="text-decoration: none">Document Node Constructors</a></h5><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompDocConstructor"/><code><a href="#prod-xquery40-CompDocConstructor">CompDocConstructor</a></code></td><td>::=</td><td><code>"document"  <a href="#doc-xquery40-CompDocConstructor-EnclosedExpr">EnclosedExpr</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompDocConstructor-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>All document node constructors are computed constructors. The result of a document node constructor is a new document node, with its own node identity.</p><p>A document node constructor is useful when the result of a query is to be a document in its own right. The following example illustrates a query that returns an XML document containing a root element named <code>author-list</code>:</p><div class="exampleInner"><pre>document {
  &lt;author-list&gt;{
    doc("bib.xml")/bib/book/author
  }&lt;/author-list&gt;
}</pre></div><p>The <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> of a document node constructor is processed in exactly the same way as an enclosed expression in the content of a <a title="direct element constructor" class="termref" href="#dt-direct-elem-const">direct element constructor</a>, as described in Step 1e of <a href="#id-content"><b>4.12.1.3 Content</b></a>. The result of processing the content expression is a sequence of nodes called the <b>content sequence</b>. Processing of the document node constructor then proceeds as follows:</p><ol class="enumar"><li><p>If the content sequence contains a document node, the document node is replaced in the content sequence by its children.</p></li><li><p>Adjacent text nodes in the content sequence are merged into a single text node by concatenating their contents, with no intervening blanks. After concatenation, any text node whose content is a zero-length string is deleted from the content sequence.</p></li><li><p> If the content sequence contains an attribute node, a
<a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p> If the content sequence contains a namespace node, a
<a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>The properties of the newly constructed document node are determined as follows:</p><ol class="enumla"><li><p>
                                 <code>base-uri</code> is
    set to the <span>
                                    <a title="Executable Base URI" class="termref" href="#dt-executable-base-uri">Executable Base URI</a>
                                 </span>.</p></li><li><p>
                                 <code>children</code> consist of all the element, text, comment, and processing
   instruction nodes in the content sequence. Note that the <code>parent</code> property of each of these nodes has been set to the newly constructed document node.</p></li><li><p>The <code>unparsed-entities</code> and <code>document-uri</code> properties are empty.</p></li><li><p>The <code>string-value</code> property is equal to the concatenated contents of the text-node descendants in document order.</p></li><li><p>The <code>typed-value</code> property is equal to the <code>string-value</code> property, as an instance of <code>xs:untypedAtomic</code>.</p></li></ol></li></ol><p>No validation is performed on the constructed document node. The <a href="#XML">[XML 1.0]</a> rules that govern the structure of an XML document (for example, the document node must have exactly one child that is an element node)  are not enforced by the XQuery document node constructor.</p></div><div class="div4">
<h5><a id="id-textConstructors"/>4.12.3.4 <a href="#id-textConstructors" style="text-decoration: none">Text Node Constructors</a></h5><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompTextConstructor"/><code><a href="#prod-xquery40-CompTextConstructor">CompTextConstructor</a></code></td><td>::=</td><td><code>"text"  <a href="#doc-xquery40-CompTextConstructor-EnclosedExpr">EnclosedExpr</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompTextConstructor-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>All text node constructors are computed constructors. The result of a text node constructor is a new text node, with its own node identity.</p><p>The <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> of a text node constructor is processed as follows:</p><ol class="enumar"><li><p>
                           <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is applied to the value of the <a title="content expression" class="termref" href="#dt-content-expression">content expression</a>, converting it to a sequence of atomic items.</p></li><li><p>If the result of atomization is an empty sequence, no text node is constructed. Otherwise, each atomic item in the atomized sequence is cast into a string.</p></li><li><p>The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair. The resulting string becomes the <code>content</code> property of the constructed text node.</p></li></ol><p>The <code>parent</code> property of the constructed text node is set to empty.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>It is possible for a text node constructor to construct a text node containing a zero-length string. However, if used in the content of a constructed element or document node, such a text node will be deleted or merged with another text node.</p></div><p>The following example illustrates a text node constructor:</p><div class="exampleInner"><pre>text { "Hello" }</pre></div></div><div class="div4">
<h5><a id="id-computed-pis"/>4.12.3.5 <a href="#id-computed-pis" style="text-decoration: none">Computed Processing Instruction Constructors</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-computed-namespaces">⬇</a> <a href="#id-computedAttributes">⬆</a></p><ol><li><p>
                     When the processing instruction name matches a language keyword such as <code>try</code> or <code>validate</code>, 
                     it must now be written with a preceding <code>#</code> character. This is a backwards incompatible change.
                  <i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/1512">1512</a> <a href="https://github.com/qt4cg/qtspecs/issues/2027">2027</a> PRs <a href="https://github.com/qt4cg/qtspecs/pull/1513">1513</a> <a href="https://github.com/qt4cg/qtspecs/pull/2028">2028</a> 18 October 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompPIConstructor"/><code><a href="#prod-xquery40-CompPIConstructor">CompPIConstructor</a></code></td><td>::=</td><td><code>"processing-instruction"  <a href="#doc-xquery40-CompPIConstructor-CompNodeNCName">CompNodeNCName</a>
                           <a href="#doc-xquery40-CompPIConstructor-EnclosedExpr">EnclosedExpr</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompPIConstructor-CompNodeNCName"/><code><a href="#prod-xquery40-CompNodeNCName">CompNodeNCName</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-CompPIConstructor-MarkedNCName">MarkedNCName</a>  |  <a href="#doc-xquery40-CompPIConstructor-UnreservedNCName">UnreservedNCName</a>  |  ("{"  <a href="#doc-xquery40-CompPIConstructor-Expr">Expr</a>  "}")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompPIConstructor-MarkedNCName"/><code><a href="#prod-xquery40-MarkedNCName">MarkedNCName</a></code></td><td>::=</td><td><code>"#"  <a href="#prod-xquery40-NCName">NCName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompPIConstructor-UnreservedNCName"/><code><a href="#prod-xquery40-UnreservedNCName">UnreservedNCName</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-NCName">NCName</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#parse-note-unreserved-name">xgc: unreserved-name</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompPIConstructor-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompPIConstructor-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-CompPIConstructor-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>A computed processing instruction constructor (<a href="#doc-xquery40-CompPIConstructor">CompPIConstructor</a>) constructs a new processing instruction node with its own node identity.
   </p><p>The name of a processing-instruction node is always an NCName, and may be provided in a number of ways:</p><ol class="enumar"><li><p>As an <code>NCName</code> with a preceding <code>#</code> sign, 
                     for example <code>processing-instruction #xref {}</code>.
                  </p></li><li><p>As a simple <code>NCName</code> without the preceding <code>#</code>, 
                     for example <code>processing-instruction xref {}</code>. This
                  form is allowed only if the name is not a reserved keyword: see
                  <a href="#parse-note-unreserved-name">unreserved-name</a>.</p></li><li><p>As an expression in curly braces. This is processed as follows:</p><ol class="enumla"><li><p>
                                 <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is applied to the value of the <a title="name expression" class="termref" href="#dt-name-expression">name expression</a>. If the result of <a title="atomization" class="termref" href="#dt-atomization">atomization</a> is not a single atomic item of type <code>xs:NCName</code>, 
                              <code>xs:string</code>, or <code>xs:untypedAtomic</code>, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>If the atomized value of the <a title="name expression" class="termref" href="#dt-name-expression">name expression</a> is of type <code>xs:string</code> or <code>xs:untypedAtomic</code>, 
                              that value is cast to the type <code>xs:NCName</code>. If the value cannot be cast to <code>xs:NCName</code>, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> is raised [<a href="#ERRXQDY0041" title="err:XQDY0041">err:XQDY0041</a>].</p></li><li><p>The resulting NCName is then used as the <code>target</code> property of the newly constructed 
                              processing instruction node. However, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> is raised if the  NCName is equal to <code>"XML"</code> (in any combination of upper and lower case) [<a href="#ERRXQDY0064" title="err:XQDY0064">err:XQDY0064</a>].</p></li></ol></li></ol><p>The
   <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> of a computed processing instruction constructor
   is processed as follows:</p><ol class="enumar"><li><p>
                           <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is applied to the value of the <a title="content expression" class="termref" href="#dt-content-expression">content expression</a>, converting it to a sequence of atomic items. (If the <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> is absent, the result of this step is an empty sequence.)</p></li><li><p>If the result of atomization is an empty sequence, it is replaced by a zero-length string.
                        Otherwise, each atomic item in the atomized sequence is cast into a string.
                        If any of the resulting strings contains the string <code>"?&gt;"</code>, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>
                           [<a href="#ERRXQDY0026" title="err:XQDY0026">err:XQDY0026</a>] is raised.</p></li><li><p>The individual strings resulting from the previous step are merged into a single string by
                        concatenating them with a single space character between each pair.
                        Leading whitespace is removed from the resulting string. The resulting string then
                        becomes the <code>content</code> property of the constructed processing instruction node.</p></li></ol><p>The remaining properties of the new processing instruction node are determined as follows:</p><ol class="enumar"><li><p>The <code>parent</code> property is empty.</p></li><li><p>The <code>base-uri</code> property is empty.</p></li></ol><p>The following example illustrates a computed processing instruction constructor:</p><div class="exampleInner"><pre>let $target := "audio-output",
return processing-instruction { $target } { "beep" }</pre></div><p>The processing instruction node constructed by this example might be serialized as follows:</p><div class="exampleInner"><pre>&lt;?audio-output beep?&gt;</pre></div></div><div class="div4">
<h5><a id="id-computed-comments"/>4.12.3.6 <a href="#id-computed-comments" style="text-decoration: none">Computed Comment Constructors</a></h5>
<a id="d2e32903"/><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompCommentConstructor"/><code><a href="#prod-xquery40-CompCommentConstructor">CompCommentConstructor</a></code></td><td>::=</td><td><code>"comment"  <a href="#doc-xquery40-CompCommentConstructor-EnclosedExpr">EnclosedExpr</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompCommentConstructor-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>A computed comment constructor (<a href="#doc-xquery40-CompCommentConstructor">CompCommentConstructor</a>) constructs a new comment node with its own node identity.
   The <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> of a computed comment constructor is processed as follows:</p><ol class="enumar"><li><p>
                           <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is applied to the value of the <a title="content expression" class="termref" href="#dt-content-expression">content expression</a>, converting it to a sequence of atomic items.</p></li><li><p>If the result of atomization is an empty sequence, it is replaced by a zero-length string. Otherwise, each atomic item in the atomized sequence is cast into a string.</p></li><li><p>The individual strings resulting from the previous step are merged into a single string by concatenating them with a single space character between each pair. The resulting string becomes the <code>content</code> property of the constructed comment node.</p></li><li><p>It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic
 error</a>
                           [<a href="#ERRXQDY0072" title="err:XQDY0072">err:XQDY0072</a>] if the result of the <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> of a computed comment constructor contains two adjacent hyphens or ends with a hyphen.</p></li></ol><p>The <code>parent</code> property of the constructed comment node is set to empty.</p><p>The following example illustrates a computed comment constructor:</p><div class="exampleInner"><pre>let $homebase := "Houston"
return comment { concat($homebase, ", we have a problem.") }</pre></div><p>The comment node constructed by this example might be serialized as follows:</p><div class="exampleInner"><pre>&lt;!--Houston, we have a problem.--&gt;</pre></div></div><div class="div4">
<h5><a id="id-computed-namespaces"/>4.12.3.7 <a href="#id-computed-namespaces" style="text-decoration: none">Computed Namespace Constructors</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-xquery-for-clause">⬇</a> <a href="#id-computed-pis">⬆</a></p><ol><li><p>
                     When the namespace prefix matches a language keyword such as <code>as</code> or <code>at</code>, 
                     it must now be written with a preceding <code>#</code> character. This is a backwards incompatible change.
                  <i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/1512">1512</a> <a href="https://github.com/qt4cg/qtspecs/issues/2027">2027</a> PRs <a href="https://github.com/qt4cg/qtspecs/pull/1513">1513</a> <a href="https://github.com/qt4cg/qtspecs/pull/2028">2028</a> 18 October 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompNamespaceConstructor"/><code><a href="#prod-xquery40-CompNamespaceConstructor">CompNamespaceConstructor</a></code></td><td>::=</td><td><code>"namespace"  <a href="#doc-xquery40-CompNamespaceConstructor-CompNodeNCName">CompNodeNCName</a>
                           <a href="#doc-xquery40-CompNamespaceConstructor-EnclosedExpr">EnclosedExpr</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompNamespaceConstructor-CompNodeNCName"/><code><a href="#prod-xquery40-CompNodeNCName">CompNodeNCName</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-CompNamespaceConstructor-MarkedNCName">MarkedNCName</a>  |  <a href="#doc-xquery40-CompNamespaceConstructor-UnreservedNCName">UnreservedNCName</a>  |  ("{"  <a href="#doc-xquery40-CompNamespaceConstructor-Expr">Expr</a>  "}")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompNamespaceConstructor-MarkedNCName"/><code><a href="#prod-xquery40-MarkedNCName">MarkedNCName</a></code></td><td>::=</td><td><code>"#"  <a href="#prod-xquery40-NCName">NCName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompNamespaceConstructor-UnreservedNCName"/><code><a href="#prod-xquery40-UnreservedNCName">UnreservedNCName</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-NCName">NCName</a>
                        </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                           <a href="#parse-note-unreserved-name">xgc: unreserved-name</a>
                         */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompNamespaceConstructor-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CompNamespaceConstructor-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-CompNamespaceConstructor-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>A computed namespace constructor creates a new namespace node,
   with its own node identity. The parent of the newly created
   namespace node is absent.</p><p>The name of a namespace node is always an <code>NCName</code>, and represents
               the namespace prefix.</p><p>The string value of a namespace node should be a <code>URI</code>, and represents
               the namespace URI.</p><p>The namespace prefix may be provided in a number of ways:</p><ol class="enumar"><li><p>As an <code>NCName</code> with a preceding <code>#</code> sign, 
                     for example <code>namespace #xlink { "http://www.w3.org/1999/xlink" }</code>.
                  </p></li><li><p>As a simple <code>NCName</code> with no preceding <code>#</code> sign, 
                     for example <code>namespace xlink { "http://www.w3.org/1999/xlink" }</code>. This
                  form is allowed only if the namespace prefix is not a reserved keyword: see
                  <a href="#parse-note-unreserved-name">unreserved-name</a>.</p></li><li><p>As an expression in curly braces. This is processed as follows:</p><ol class="enumla"><li><p>
                                 <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is
      applied to the result of the enclosed expression.</p></li><li><p>
      If the result of <a title="atomization" class="termref" href="#dt-atomization">atomization</a>
        is an empty sequence
        or a single atomic item of type <code>xs:string</code> or <code>xs:untypedAtomic</code>,
      then the following rules are applied in order:</p><ol class="enumlr"><li><p>If the result is castable to <code>xs:NCName</code>, then it is used as the local name
         of the newly constructed namespace node. (The local name of a namespace node
         represents the prefix part of the <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a>.)</p></li><li><p>If the result is the empty sequence
                      or a zero-length <code>xs:string</code>
                      or <code>xs:untypedAtomic</code> item,
               the new namespace node has no name (such a namespace node represents a binding for the default namespace).</p></li><li><p>Otherwise, a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>  is raised  [<a href="#ERRXQDY0074" title="err:XQDY0074">err:XQDY0074</a>].</p></li></ol></li><li><p>If the result of atomization is not an empty sequence
                               or a single atomic item of type <code>xs:string</code> or <code>xs:untypedAtomic</code>,
      a type error is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li></ol></li></ol><p>The <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> is evaluated, and the result is cast
    to <code>xs:anyURI</code> to create the <code>URI</code> property
    for the newly created node.  
    An implementation may raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>
                     [<a href="#ERRXQDY0074" title="err:XQDY0074">err:XQDY0074</a>] if the <code>URIExpr</code> of a computed namespace constructor is not a valid instance of <code>xs:anyURI</code>.</p><p>An error [<a href="#ERRXQDY0101" title="err:XQDY0101">err:XQDY0101</a>] is raised if a
    computed namespace constructor attempts to do any of the
    following:</p><ul><li><p>Bind the prefix <code>xml</code> to some namespace URI
      other than <code>http://www.w3.org/XML/1998/namespace</code>.
      </p></li><li><p>Bind a prefix other than <code>xml</code> to the namespace
      URI <code>http://www.w3.org/XML/1998/namespace</code>.
      </p></li><li><p>Bind the prefix <code>xmlns</code> to any namespace URI.
      </p></li><li><p>Bind a prefix to the namespace
      URI <code>http://www.w3.org/2000/xmlns/</code>.
      </p></li><li><p>Bind any prefix (including the empty prefix) to a zero-length namespace URI.</p></li></ul><p>By itself, a computed namespace constructor has no effect on
                  the <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> of any element,
                  but if an element constructor’s content
                  sequence contains a namespace node, the <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> it
                  represents is added to that element’s <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a>.</p><p>A computed namespace constructor has no effect on the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>
                  in the <a title="static context" class="termref" href="#dt-static-context">static context</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The newly created namespace node has all properties defined
      for a namespace node in the data model, but its parent is always absent.  As defined in the
      data model, the name of the node is the prefix, the string value
      of the node is the URI. Since the nodes are parentless, their relative order is implementation
      dependent.</p></div><p>Examples:</p><ul><li><p>A computed namespace constructor with a prefix:</p><div class="exampleInner"><pre>namespace a { "http://a.example.com" }</pre></div></li><li><p>A computed namespace constructor with a prefix expression:</p><div class="exampleInner"><pre>namespace { "a" } { "http://a.example.com" }</pre></div></li><li><p>A computed namespace constructor with an empty prefix:</p><div class="exampleInner"><pre>namespace "" { "http://a.example.com" }</pre></div></li></ul><p>Computed namespace constructors are generally used to add to the
<a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> of elements created with element constructors:</p><div class="exampleInner"><pre>
&lt;age xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; {
  namespace xs { "http://www.w3.org/2001/XMLSchema" },
  attribute xsi:type { "xs:integer" },
  23
}&lt;/age&gt;</pre></div><p>In the above example, note that the <code>xsi</code>
                     <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> 
                  is created for the element because it is used in an attribute name. The attribute’s 
                  content is simply character data, and has no effect on namespace bindings. 
                  The computed namespace constructor ensures that the <code>xs</code> binding is created.</p><p>Computed namespace constructors have no effect on the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>. 
                  If the prefix a is not already defined in the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>, 
                  the following expression results in a static error
[<a href="#ERRXPST0081" title="err:XPST0081">err:XPST0081</a>].</p><div class="exampleInner"><pre>
&lt;a:form&gt;{
  namespace a { "http://a.example.com" }
}&lt;/a:form&gt;</pre></div></div></div><div class="div3">
<h4><a id="id-ns-nodes-on-elements"/>4.12.4 <a href="#id-ns-nodes-on-elements" style="text-decoration: none">In-scope Namespaces of a Constructed Element</a></h4><p>An element node constructed by a direct or computed element
constructor has an <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> property that consists of a set of 
               <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace bindings</a>.  The
in-scope namespaces of an element node may affect the way the node is
serialized (see <a href="#id-serialization"><b>2.3.5 Serialization</b></a>), and may also
affect the behavior of certain functions that operate on nodes, such
as <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-name"><code>fn:name</code></a>. Note the difference between <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a>, which is a
dynamic property of an element node, and <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>,
which is a static property of an expression.  One of
the namespace bindings in the in-scope namespaces may have an empty prefix:
this is referred to as the <a title="default in-scope namespace" class="termref" href="#dt-default-in-scope-namespace">default in-scope namespace</a> of the element. The in-scope
namespaces of a constructed element node consist of the following
<a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace bindings</a>:</p><ul><li><p>A <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> is created for each namespace declared
  in the current element constructor by a <a title="namespace declaration attribute" class="termref" href="#dt-namespace-decl-attr">namespace declaration
  attribute</a>.</p></li><li><p>A <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> is created for each namespace node in
  the content sequence of the current element constructor.</p></li><li><p>A <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> is created for each namespace that is
  declared in a <a title="namespace declaration attribute" class="termref" href="#dt-namespace-decl-attr">namespace
  declaration attribute</a> of an enclosing <a title="direct element constructor" class="termref" href="#dt-direct-elem-const">direct element constructor</a> and
  not overridden by the current element constructor or an intermediate
  constructor.</p></li><li><p>A <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> is always created to bind the prefix
  <code>xml</code> to the namespace URI
  <code>http://www.w3.org/XML/1998/namespace</code>.</p></li><li><p>For each prefix used in the name of the
  constructed element or in the names of its attributes, a <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> must exist.</p><p>If a <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> does not already exist for one of these
  prefixes, a new namespace binding is created for it.</p><p>If this would result in a conflict, because it would require two
  different bindings of the same prefix, then the prefix used in the
  node name is changed to an arbitrary <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>
  prefix that does not cause such a conflict, and a <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a>
  is created for this new prefix.</p><p>If there is a <a title="default in-scope namespace" class="termref" href="#dt-default-in-scope-namespace">default in-scope namespace</a>, then 
                     a binding is created between the empty prefix and that URI.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>
                     <a title="copy-namespaces mode" class="termref" href="#dt-copy-namespaces-mode">Copy-namespaces
mode</a> does not affect the <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> of a newly
constructed element node. It applies only to existing nodes that are
copied by a constructor expression.</p></div><p>In an element constructor, if two or more <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace bindings</a> in the
<a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> would have the same prefix, then an error is raised
if they have different URIs [<a href="#ERRXQDY0102" title="err:XQDY0102">err:XQDY0102</a>]; if they
would have the same prefix and URI, duplicate bindings are
ignored. 
If the name of an element in an element constructor is in no namespace,
creating a default namespace for that element using a computed namespace constructor is an error [<a href="#ERRXQDY0102" title="err:XQDY0102">err:XQDY0102</a>]. 
For instance, the following computed constructor raises an error because the element’s name is not in a namespace, 
but a default namespace is defined.</p><div class="exampleInner"><pre>element e { namespace { '' } { 'u' } }</pre></div><p>The following query illustrates the <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> of a constructed element:</p><div class="exampleInner"><pre>declare namespace p = "http://example.com/ns/p";
declare namespace q = "http://example.com/ns/q";
declare namespace f = "http://example.com/ns/f";

&lt;p:a q:b="{ f:func(2) }" xmlns:r="http://example.com/ns/r"/&gt;</pre></div><p>The <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a> of the resulting <code>p:a</code> element compirse 
               the following <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace bindings</a>:</p><ul><li><p>
                        <code>p = "http://example.com/ns/p"</code>
                     </p></li><li><p>
                        <code>q = "http://example.com/ns/q"</code>
                     </p></li><li><p>
                        <code>r = "http://example.com/ns/r"</code>
                     </p></li><li><p>
                        <code>xml = "http://www.w3.org/XML/1998/namespace"</code>
                     </p></li></ul><p>The <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace bindings</a> for <code>p</code> and <code>q</code> 
               are added to the result element because their respective namespaces
are used in the names of the element and its attributes. The namespace binding <code>r="http://example.com/ns/r"</code> is added to the in-scope namespaces of the constructed
element because it is defined by a <a title="namespace declaration attribute" class="termref" href="#dt-namespace-decl-attr">namespace declaration attribute</a>, even though it is not used in a name.</p><p>No <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a> corresponding to <code>f="http://example.com/ns/f"</code> is created, 
               because the namespace prefix <code>f</code> appears only in the query prolog and is not used in an element 
               or attribute name of the constructed node. This namespace binding does not appear in the query result, 
               even though it is present in the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a> and is available for use 
               during processing of the query.</p><p>Note that the following constructed element, if nested within a <code>validate</code> expression, cannot be validated:
</p><div class="exampleInner"><pre>&lt;p xsi:type="xs:integer"&gt;3&lt;/p&gt;</pre></div><p>The constructed element will have <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace bindings</a> 
               for the prefixes <code>xsi</code> 
               (because it is used in a name) and <code>xml</code> (because it is defined for every 
               constructed element node). During validation of the constructed element, the validator 
               will be unable to interpret the namespace prefix <code>xs</code> because it is has 
               no namespace binding. Validation of this constructed element could be made possible 
               by providing a <a title="namespace declaration attribute" class="termref" href="#dt-namespace-decl-attr">namespace declaration attribute</a>, as in the following example:</p><div class="exampleInner"><pre>&lt;p xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:integer"&gt;3&lt;/p&gt;</pre></div></div></div><div class="div2">
<h3><a id="id-flwor-expressions"/>4.13 <a href="#id-flwor-expressions" style="text-decoration: none">
               <span class="xquery">FLWOR Expressions</span>
            </a></h3><p>XQuery provides a versatile expression called a FLWOR expression 
            that may contain multiple clauses. The FLWOR expression can be used for many purposes, 
            including iterating over sequences, joining multiple documents, and performing grouping 
            and aggregation. The name FLWOR, pronounced "flower", is suggested by the keywords 
            <code>for</code>, <code>let</code>, <code>where</code>, <code>order by</code>, 
            and <code>return</code>, which introduce some of the clauses used in FLWOR expressions 
            (but this is not a complete list of such clauses.)</p><p>The overall syntax of a FLWOR expression is shown here, and relevant parts 
            of the syntax are expanded in subsequent sections.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr"/><code><a href="#prod-xquery40-FLWORExpr">FLWORExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FLWORExpr-InitialClause">InitialClause</a>
                     <a href="#doc-xquery40-FLWORExpr-IntermediateClause">IntermediateClause</a>*  <a href="#doc-xquery40-FLWORExpr-ReturnClause">ReturnClause</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr-InitialClause"/><code><a href="#prod-xquery40-InitialClause">InitialClause</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FLWORExpr-ForClause">ForClause</a>  |  <a href="#doc-xquery40-FLWORExpr-LetClause">LetClause</a>  |  <a href="#doc-xquery40-FLWORExpr-WindowClause">WindowClause</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr-ForClause"/><code><a href="#prod-xquery40-ForClause">ForClause</a></code></td><td>::=</td><td><code>"for"  (<a href="#prod-xquery40-ForBinding">ForBinding</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr-LetClause"/><code><a href="#prod-xquery40-LetClause">LetClause</a></code></td><td>::=</td><td><code>"let"  (<a href="#prod-xquery40-LetBinding">LetBinding</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr-WindowClause"/><code><a href="#prod-xquery40-WindowClause">WindowClause</a></code></td><td>::=</td><td><code>"for"  (<a href="#prod-xquery40-TumblingWindowClause">TumblingWindowClause</a>  |  <a href="#prod-xquery40-SlidingWindowClause">SlidingWindowClause</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr-IntermediateClause"/><code><a href="#prod-xquery40-IntermediateClause">IntermediateClause</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FLWORExpr-InitialClause">InitialClause</a>  |  <a href="#doc-xquery40-FLWORExpr-WhereClause">WhereClause</a>  |  <a href="#doc-xquery40-FLWORExpr-WhileClause">WhileClause</a>  |  <a href="#doc-xquery40-FLWORExpr-GroupByClause">GroupByClause</a>  |  <a href="#doc-xquery40-FLWORExpr-OrderByClause">OrderByClause</a>  |  <a href="#doc-xquery40-FLWORExpr-CountClause">CountClause</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr-WhereClause"/><code><a href="#prod-xquery40-WhereClause">WhereClause</a></code></td><td>::=</td><td><code>"where"  <a href="#doc-xquery40-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr-WhileClause"/><code><a href="#prod-xquery40-WhileClause">WhileClause</a></code></td><td>::=</td><td><code>"while"  <a href="#doc-xquery40-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr-GroupByClause"/><code><a href="#prod-xquery40-GroupByClause">GroupByClause</a></code></td><td>::=</td><td><code>"group"  "by"  (<a href="#prod-xquery40-GroupingSpec">GroupingSpec</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr-OrderByClause"/><code><a href="#prod-xquery40-OrderByClause">OrderByClause</a></code></td><td>::=</td><td><code>"stable"?  "order"  "by"  (<a href="#prod-xquery40-OrderSpec">OrderSpec</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr-CountClause"/><code><a href="#prod-xquery40-CountClause">CountClause</a></code></td><td>::=</td><td><code>"count"  <a href="#prod-xquery40-VarName">VarName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FLWORExpr-ReturnClause"/><code><a href="#prod-xquery40-ReturnClause">ReturnClause</a></code></td><td>::=</td><td><code>"return"  <a href="#doc-xquery40-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody></table><p>The semantics of FLWOR expressions are based on a concept called a <b>tuple stream</b>. [<a id="id-tuple-stream-foobar" title="tuple stream">Definition</a>: A <b>tuple stream</b> is an ordered sequence of zero or more <b>tuples</b>.]
               [<a id="id-tuple-foobar" title="tuple">Definition</a>: A <b>tuple</b> is a set of zero or more named variables, each of which is bound to a value that is an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a>.] Each tuple stream is homogeneous in the sense that all its  tuples contain variables with the same names and the same <a title="static type" class="termref" href="#dt-static-type">static types</a>. The following example illustrates a tuple stream consisting of four tuples, each containing three variables named <code>$x</code>, <code>$y</code>, and <code>$z</code>:</p><div class="exampleInner"><pre>($x = 1003, $y = "Fred", $z = &lt;age&gt;21&lt;/age&gt;)
($x = 1017, $y = "Mary", $z = &lt;age&gt;35&lt;/age&gt;)
($x = 1020, $y = "Bill", $z = &lt;age&gt;18&lt;/age&gt;)
($x = 1024, $y = "John", $z = &lt;age&gt;29&lt;/age&gt;)</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>In this section, tuple streams are represented as shown in the above example. Each tuple is on a separate line and is enclosed in parentheses, and the variable bindings inside each tuple are separated by commas. This notation does not represent XQuery syntax, but is simply a representation of a tuple stream for the purpose of defining the semantics of  FLWOR expressions.</p></div><p>Tuples and tuple streams are not part of the <a title="data model" class="termref" href="#dt-datamodel">data model</a>. They exist only as conceptual intermediate results during the processing of a FLWOR expression.</p><p>Conceptually, the first clause generates a tuple stream. Each clause between the first clause and the return clause takes the tuple stream generated by the previous clause as input and generates a (possibly different) tuple stream as output. The return clause takes a tuple stream as input and, for each tuple in this tuple stream, generates an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a>; the final result of the FLWOR expression is the ordered concatenation of these <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instances</a>.</p><p>The initial clause in a FLWOR expression may be a <code>for</code>, <code>let</code>, or <code>window</code> clause. 
Intermediate clauses may be <code>for</code>, <code>let</code>, <code>window</code>, <code>count</code>, <code>where</code>, <code>group by</code>, or <code>order by</code> clauses. These intermediate clauses may be repeated as many times as desired, in any order. The final clause of the FLWOR expression must be a <code>return</code> clause. The semantics of the various clauses are described in the following sections.</p><div class="div3 xquery">
<h4><a id="id-binding-rules"/>4.13.1 <a href="#id-binding-rules" style="text-decoration: none">Variable Bindings</a></h4><p>The following clauses in FLWOR expressions bind values to variables: 
<code>for</code>, <code>let</code>, <code>window</code>, <code>count</code>, and <code>group by</code>. 
The binding of variables for <code>for</code>, <code>let</code>, and <code>count</code> is governed by the following rules
(the binding of variables in <code>group by</code> is discussed in <a href="#id-group-by"><b>4.13.8 Group By Clause</b></a>,
the binding of variables in <code>window</code> clauses is discussed in <a href="#id-windows"><b>4.13.4 Window Clause</b></a>):</p><ol class="enumar"><li><p>The scope of a bound variable includes all subexpressions of the containing FLWOR that appear after the variable binding. The scope does not include the expression to which the variable is bound. The following code fragment, containing two <code>let</code> clauses, illustrates how variable bindings may reference variables that were bound in earlier clauses, or in earlier bindings in the same clause:</p><div class="exampleInner"><pre>let $x := 47, $y := f($x)
let $z := g($x, $y)</pre></div></li><li><p>A given variable name may be bound more than once in a FLWOR expression, 
                     or even within one clause of a FLWOR expression. In such a case, each new 
                     binding occludes the previous one, which becomes inaccessible in the 
                     remainder of the FLWOR expression.</p><p>For example, it is valid to write:</p><div class="exampleInner"><pre>let $x := 0, $x := $x*2, $x := $x + 1</pre></div><p>This binds three separate variables, each of which happens to have the
                  same name. It should not be construed as binding a series of different values
                  to the same variable.</p></li><li><p>
                        [<a id="dt-type-declaration" title="type declaration">Definition</a>: A variable binding may be accompanied by a <b>type declaration</b>, which consists of the 
                        keyword <code>as</code> followed by the static type of the variable, declared using the syntax in  <a href="#id-sequencetype-syntax"><b>3.1 Sequence Types</b></a>.] The type declaration defines a required type for the
                        value. At run-time, the supplied value for the variable is converted to the required type
                        by applying the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>. If conversion is not possible,                     
                        a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>]. For example, the following <code>let</code> clause raises a <a title="type error" class="termref" href="#dt-type-error">type error</a> because the variable <code>$salary</code> has a type declaration that is not satisfied by the value that is bound to it:</p><div class="exampleInner"><pre>let $salary as xs:decimal := "cat"</pre></div><p>The following <code>let</code> clause, however, succeeds, because the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>
                  allow an <code>xs:decimal</code> to be supplied where an <code>xs:double</code> is required:</p><div class="exampleInner"><pre>let $temperature as xs:double := 32.5</pre></div><p>In applying the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>, <a title="XPath 1.0 compatibility     mode" class="termref" href="#dt-xpath-compat-mode">XPath 1.0 compatibility     mode</a> does not apply.</p></li><li><p>
                        [<a id="dt-binding-collection" title="binding collection">Definition</a>: In a <code>for</code> clause, when an expression is 
                        preceded by the keyword <code>in</code>, the value of that expression is 
                        called a <b>binding collection</b>.] The collection may be either
                     a sequence, an array, or a map. The <code>for</code>  
                     clause iterates over its binding collection, producing multiple bindings for one or more variables. 
                     Details on how binding collections are used in <code>for</code> clauses 
                     are described in the following sections.</p></li><li><p>
                        [<a id="dt-binding-sequence" title="binding sequence">Definition</a>: In a <code>window</code> clause, when an expression is 
                        preceded by the keyword <code>in</code>, the value of that expression is 
                        called a <b>binding sequence</b>.] The <code>window</code> 
                     clause iterates over its binding sequence, producing multiple bindings for one or more variables. 
                     Details on how binding sequences are used in <code>for</code> and <code>window</code> clauses 
                     are described in the following sections.</p></li></ol></div><div class="div3 xquery">
<h4><a id="id-xquery-for-clause"/>4.13.2 <a href="#id-xquery-for-clause" style="text-decoration: none">For Clause</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-xquery-let-clause">⬇</a> <a href="#id-computed-namespaces">⬆</a></p><ol><li><p>A <code>for member</code> clause is added to 
                  FLWOR expressions to allow iteration over an array.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/49">49</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/344">344</a> 10 February 2023]</i></p></li><li><p>A <code>for key/value</code> clause is added to 
                  FLWOR expressions to allow iteration over a map.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/31">31</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1249">1249</a> 1 June 2024]</i></p></li><li><p>
                  The value bound to a variable in a <code>for</code> clause is now converted
                     to the declared type by applying the coercion rules.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/189">189</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/820">820</a> 8 November 2023]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause"/><code><a href="#prod-xquery40-ForClause">ForClause</a></code></td><td>::=</td><td><code>"for"  (<a href="#doc-xquery40-ForClause-ForBinding">ForBinding</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-ForBinding"/><code><a href="#prod-xquery40-ForBinding">ForBinding</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-ForClause-ForItemBinding">ForItemBinding</a>  |  <a href="#doc-xquery40-ForClause-ForMemberBinding">ForMemberBinding</a>  |  <a href="#doc-xquery40-ForClause-ForEntryBinding">ForEntryBinding</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-ForItemBinding"/><code><a href="#prod-xquery40-ForItemBinding">ForItemBinding</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-ForClause-VarNameAndType">VarNameAndType</a>
                        <a href="#doc-xquery40-ForClause-AllowingEmpty">AllowingEmpty</a>?  <a href="#doc-xquery40-ForClause-PositionalVar">PositionalVar</a>?  "in"  <a href="#doc-xquery40-ForClause-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-VarNameAndType"/><code><a href="#prod-xquery40-VarNameAndType">VarNameAndType</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-ForClause-EQName">EQName</a>
                        <a href="#doc-xquery40-ForClause-TypeDeclaration">TypeDeclaration</a>?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-TypeDeclaration"/><code><a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a></code></td><td>::=</td><td><code>"as"  <a href="#doc-xquery40-ForClause-SequenceType">SequenceType</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                        <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-AllowingEmpty"/><code><a href="#prod-xquery40-AllowingEmpty">AllowingEmpty</a></code></td><td>::=</td><td><code>"allowing"  "empty"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-PositionalVar"/><code><a href="#prod-xquery40-PositionalVar">PositionalVar</a></code></td><td>::=</td><td><code>"at"  <a href="#doc-xquery40-ForClause-VarName">VarName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-VarName"/><code><a href="#prod-xquery40-VarName">VarName</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-ForClause-EQName">EQName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-ForMemberBinding"/><code><a href="#prod-xquery40-ForMemberBinding">ForMemberBinding</a></code></td><td>::=</td><td><code>"member"  <a href="#doc-xquery40-ForClause-VarNameAndType">VarNameAndType</a>
                        <a href="#doc-xquery40-ForClause-PositionalVar">PositionalVar</a>?  "in"  <a href="#doc-xquery40-ForClause-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-ForEntryBinding"/><code><a href="#prod-xquery40-ForEntryBinding">ForEntryBinding</a></code></td><td>::=</td><td><code>((<a href="#doc-xquery40-ForClause-ForEntryKeyBinding">ForEntryKeyBinding</a>
                        <a href="#doc-xquery40-ForClause-ForEntryValueBinding">ForEntryValueBinding</a>?)  |  <a href="#doc-xquery40-ForClause-ForEntryValueBinding">ForEntryValueBinding</a>)  <a href="#doc-xquery40-ForClause-PositionalVar">PositionalVar</a>?  "in"  <a href="#doc-xquery40-ForClause-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-ForEntryKeyBinding"/><code><a href="#prod-xquery40-ForEntryKeyBinding">ForEntryKeyBinding</a></code></td><td>::=</td><td><code>"key"  <a href="#doc-xquery40-ForClause-VarNameAndType">VarNameAndType</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ForClause-ForEntryValueBinding"/><code><a href="#prod-xquery40-ForEntryValueBinding">ForEntryValueBinding</a></code></td><td>::=</td><td><code>"value"  <a href="#doc-xquery40-ForClause-VarNameAndType">VarNameAndType</a>
                     </code></td></tr></tbody></table><p>A <code>for</code> clause is used for iteration. Each variable in a <code>for</code> clause iterates over a 
               sequence, an array, or a map.</p><p>The expression following the keyword <code>in</code> is evaluated; we refer to the 
               resulting sequence, array, or map generically as the <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a>, and to
               its items, members, or entries as the <code>components</code> of the collection.</p><ul><li><p>When a <a href="#prod-xquery40-ForItemBinding">ForItemBinding</a> is used (that is, when none of the
                  keywords <code>member</code>, <code>key</code>, or <code>value</code> is used), 
                  the range variable is bound in turn to each item in the <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a>,
                  which is treated as a sequence of items.</p></li><li><p>When a <a href="#prod-xquery40-ForItemBinding">ForMemberBinding</a> is used (that is, when the
               keyword <code>member</code> is used), 
               the range variable is bound in turn to each member of the array.</p><p>In this case the corresponding <code>ExprSingle</code>
                  must evaluate to a single array, otherwise a type error is raised [<a href="#ERRXPTY0141" title="err:XPTY0141">err:XPTY0141</a>]. However, the coercion rules also allow a JNode
                  whose <b>·content·</b> is an array to be supplied.</p></li><li><p>When a <a href="#prod-xquery40-ForItemBinding">ForEntryBinding</a> is used (that is, when either
                  or both of the keywords <code>key</code> and <code>value</code> are used), 
                  the <code>key</code> range variable (if present) is bound in turn to each key in the map 
                  (in <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-entry-order">entry order</a><sup><small>DM</small></sup>), and the <code>value</code>
                  range variable (if present) is bound to the corresponding value.</p><p>In this case the corresponding <code>ExprSingle</code>
                  must evaluate to a single map, otherwise a type error is raised [<a href="#ERRXPTY0141" title="err:XPTY0141">err:XPTY0141</a>]. However, the coercion rules also allow a JNode
                  whose <b>·content·</b> is a map to be supplied.</p><p>If both the <code>key</code> and <code>value</code> variables are declared,
               their <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded
			        QNames</a> must be distinct [<a href="#ERRXQST0089" title="err:XQST0089">err:XQST0089</a>].</p></li></ul><p>If a <code>for</code> clause contains multiple bindings separated by commas 
               it is semantically equivalent to multiple <code>for</code> clauses, 
               each containing one of the bindings in the original <code>for</code> clause.</p><p>Example:</p><ul><li><p>The clause</p><div class="exampleInner"><pre>for $x in $expr1, $y in $expr2</pre></div><p>is semantically equivalent to:</p><div class="exampleInner"><pre>for $x in $expr1
for $y in $expr2</pre></div></li><li><p>The clause</p><div class="exampleInner"><pre>for member $x in $expr1, member $y in $expr2</pre></div><p>is semantically equivalent to:</p><div class="exampleInner"><pre>for member $x in $expr1
for member $y in $expr2</pre></div></li></ul><p>In the remainder of this section, we define the semantics of a <code>for</code> clause containing 
               a single variable and an associated expression 
               (following the keyword <code>in</code>) whose value is the <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a> for that variable.</p><p>If a single-variable <code>for</code> clause is the initial clause in a FLWOR expression, it iterates over its <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a>, binding the variable(s) to each component in turn. 
               The resulting sequence of variable bindings becomes the initial tuple stream that serves as input to the next clause 
               of the FLWOR expression. The order of tuples in the tuple stream preserves the order of the <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a>.</p><p>If the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding collection</a> is empty, the output tuple stream depends on whether <code>allowing empty</code> is specified. 
               If <code>allowing empty</code> is specified, the output tuple stream consists of one tuple in which the variable is bound to an empty sequence.
               This option is not available when the keywords <code>member</code>, <code>key</code>, or <code>value</code>
               are used.
               If <code>allowing empty</code> is not specified, the output tuple stream consists of zero tuples.</p><p>The following  examples illustrates tuple streams that are generated by initial <code>for</code> clauses:</p><ul><li><p>Initial clause:</p><div class="exampleInner"><pre>for $x in (100, 200, 300)</pre></div><p>or (equivalently):</p><div class="exampleInner"><pre>for $x allowing empty in (100, 200, 300)</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($x = 100)
($x = 200)
($x = 300)</pre></div></li><li><p>Initial clause:</p><div class="exampleInner"><pre>for $x in ()</pre></div><p>Output tuple stream contains no tuples.</p></li><li><p>Initial clause:</p><div class="exampleInner"><pre>for $x allowing empty in ()</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($x = ())</pre></div></li><li><p>Initial clause:</p><div class="exampleInner"><pre>for member $x in [ 1, 2, (5 to 10) ]</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($x = (1))
($x = (2))
($x = (5, 6, 7, 8, 9, 10)</pre></div></li><li><p>Initial clause:</p><div class="exampleInner"><pre>for member $x in []</pre></div><p>Output tuple stream contains no tuples.</p></li><li><p>Initial clause:</p><div class="exampleInner"><pre>for key $k value $v in { 'x': 1, 'y': 2 }</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($k = 'x', $v = 1)
($k = 'y', $v = 2)</pre></div></li></ul><p>
                  [<a id="dt-positional-variable" title="positional variable">Definition</a>: A <b>positional variable</b> 
                  is a variable that is preceded by the keyword <code>at</code>.] A positional variable 
               may be associated with the range variable(s) that are bound in a <code>for</code> clause. In this case, as 
               the main range variable(s) iterate over the components of its <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a>, 
               the positional variable iterates over the integers that represent the ordinal numbers of these component in the 
               <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a>, starting with one. Each tuple in the output 
               tuple stream contains bindings for both the main variable and the positional variable. If the 
               <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a> is empty and <code>allowing empty</code> is 
               specified, the positional variable in the output tuple is bound to the integer zero. Positional variables  
               have the implied type <code>xs:integer</code>.</p><p>The <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded
			        QName</a> of a positional variable must be distinct from the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> of the main variable with which it is associated [<a href="#ERRXQST0089" title="err:XQST0089">err:XQST0089</a>].</p><p>The following  examples illustrate how a positional variable would have affected the results of the previous examples that generated tuples:</p><ul><li><p>Initial clause:</p><div class="exampleInner"><pre>for $x at $i in (100, 200, 300)</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($x = 100, $i = 1)
($x = 200, $i = 2)
($x = 300, $i = 3)</pre></div></li><li><p>Initial clause:</p><div class="exampleInner"><pre>for $x at $i in [1 to 3, 11 to 13, 21 to 23</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($x = (1, 2, 3), $i = 1)
($x = (11, 12, 13), $i = 2)
($x = (21, 22, 23), $i = 3)</pre></div></li><li><p>Initial clause:</p><div class="exampleInner"><pre>for $x allowing empty at $i in ()</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($x = (), $i = 0)</pre></div></li></ul><p>If a single-variable <code>for</code> clause is an intermediate clause in a FLWOR expression, its <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a> is evaluated for each input tuple, given the bindings in that input tuple. Each input tuple generates 
                  zero or more tuples in the output tuple stream. Each of these output tuples consists of  the original variable bindings of the 
                  input tuple plus a binding of the new variable to one of the items in its <a title="binding collection" class="termref" href="#dt-binding-collection">binding collecction</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Although the <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a> is conceptually evaluated independently for each input tuple, 
                  an optimized implementation may sometimes be able to avoid re-evaluating the <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a> if it can show that the variables that the <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a> depends on have the same values as in a previous evaluation.</p></div><p>For a given input tuple, if the <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a> for the new variable in the <code>for</code> clause <span>is empty 
               (that is, it is an empty sequence or an <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-empty-array">empty array</a><sup><small>DM</small></sup> depending on whether <code>member</code> is specified)</span>,
               and if <code>allowing empty</code> is not specified, the input tuple generates zero output tuples 
               (it is not represented in the output tuple stream.)</p><p>The <code>allowing empty</code> option is available only when processing sequences, not when processing arrays or maps.
               The effect is that if the binding collection is an empty sequence, the input tuple generates one output tuple, 
               with the original variable bindings plus a binding of the new variable to an empty sequence.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>If a type declaration is present and <code>allowing empty</code> is specified, the type declaration
            should include an occurrence indicator of <code>"?"</code> to indicate that the variable may be bound to an
            empty sequence.</p></div><p>If the new variable introduced by a <code>for</code> clause has an associated <a title="positional variable" class="termref" href="#dt-positional-variable">positional variable</a>, the output tuples generated by the <code>for</code> clause  also contain bindings for the <a title="positional variable" class="termref" href="#dt-positional-variable">positional variable</a>. In this case, as the new variable is bound to each item in its <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a>, the <a title="positional variable" class="termref" href="#dt-positional-variable">positional variable</a> is bound to the ordinal position of that item within the <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a>, starting with one. Note that, since the <a title="positional variable" class="termref" href="#dt-positional-variable">positional variable</a> represents a position within a <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a>, the output tuples corresponding to each input tuple are independently numbered, starting with one. For a given input tuple, if the <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a> is empty and <code>allowing empty</code> is specified, the <a title="positional variable" class="termref" href="#dt-positional-variable">positional variable</a> in the output tuple is bound to the integer zero.</p><p>The tuples in the output tuple stream are ordered primarily by the order of the 
               input tuples from which they are derived, and secondarily by the order of the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a> for the new variable; otherwise the order of the output tuple stream is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>.</p><p>The following examples illustrates the effects of  intermediate <code>for</code> clauses:</p><ul><li><p>Input tuple stream:</p><div class="exampleInner"><pre>($x = 1)
($x = 2)
($x = 3)
($x = 4)</pre></div><p>Intermediate <code>for</code> clause:</p><div class="exampleInner"><pre>for $y in ($x to 3)</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($x = 1, $y = 1)
($x = 1, $y = 2)
($x = 1, $y = 3)
($x = 2, $y = 2)
($x = 2, $y = 3)
($x = 3, $y = 3)</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>In this example, there is no output tuple that corresponds to the input tuple <code>($x = 4)</code> because, when the <code>for</code> clause is evaluated with the bindings in this input tuple, the resulting <a title="binding collection" class="termref" href="#dt-binding-collection">binding collection</a> for <code>$y</code> is empty.</p></div></li><li><p>This  example shows how the previous example would have been affected by a <a title="positional variable" class="termref" href="#dt-positional-variable">positional variable</a> (assuming the same input tuple stream):</p><div class="exampleInner"><pre>for $y at $j in ($x to 3)</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($x = 1, $y = 1, $j = 1)
($x = 1, $y = 2, $j = 2)
($x = 1, $y = 3, $j = 3)
($x = 2, $y = 2, $j = 1)
($x = 2, $y = 3, $j = 2)
($x = 3, $y = 3, $j = 1)</pre></div></li><li><p>This example shows how the previous example would have been affected by <code>allowing empty</code>. Note that <code>allowing empty</code> causes the input tuple <code>($x = 4)</code> to be represented in the output tuple stream, even though the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a> for <code>$y</code> contains no items for this input tuple.
                        This example illustrates that <code>allowing empty</code> in a <code>for</code> clause
                        serves a purpose similar to that of an “outer join” in a relational database query.
                        (Assume the same input tuple stream as in the previous example.)</p><div class="exampleInner"><pre>for $y allowing empty at $j in ($x to 3)</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($x = 1, $y = 1, $j = 1)
($x = 1, $y = 2, $j = 2)
($x = 1, $y = 3, $j = 3)
($x = 2, $y = 2, $j = 1)
($x = 2, $y = 3, $j = 2)
($x = 3, $y = 3, $j = 1)
($x = 4, $y = (), $j = 0)</pre></div></li><li><p>This example illustrates processing of arrays:</p><p>Input tuple stream:</p><div class="exampleInner"><pre>($x = 1)
($x = 2)
($x = 3)</pre></div><p>Intermediate <code>for</code> clause:</p><div class="exampleInner"><pre>for member $y in [[$x+1, $x+2], [[$x+3, $x+4]]</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($x = 1, $y = [ 2, 3 ])
($x = 1, $y = [ 4, 5 ])
($x = 2, $y = [ 3, 4 ])
($x = 2, $y = [ 5, 6 ])
($x = 3, $y = [ 4, 5 ])
($x = 3, $y = [ 6, 7 ])</pre></div></li><li><p>This example shows how a <code>for</code> clause that binds two variables is semantically equivalent to two <code>for</code> clauses that bind one variable each. We assume that this <code>for</code> clause occurs at the beginning of a FLWOR expression. It is equivalent to an initial single-variable <code>for</code> clause that provides an input tuple stream to an intermediate single-variable <code>for</code> clause.</p><div class="exampleInner"><pre>for $x in (1, 2, 3, 4), $y in ($x to 3)</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($x = 1, $y = 1)
($x = 1, $y = 2)
($x = 1, $y = 3)
($x = 2, $y = 2)
($x = 2, $y = 3)
($x = 3, $y = 3)</pre></div></li></ul><p>A <code>for</code> clause may contain one or more <a title="type declaration" class="termref" href="#dt-type-declaration">type declarations</a>, identified by the keyword <code>as</code>. The semantics of <a title="type declaration" class="termref" href="#dt-type-declaration">type declarations</a> are defined in <a href="#id-binding-rules"><b>4.13.1 Variable Bindings</b></a>.</p></div><div class="div3 xquery">
<h4><a id="id-xquery-let-clause"/>4.13.3 <a href="#id-xquery-let-clause" style="text-decoration: none">Let Clause</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-windows">⬇</a> <a href="#id-xquery-for-clause">⬆</a></p><ol><li><p>
                  The value bound to a variable in a <code>let</code> clause is now converted
               to the declared type by applying the coercion rules.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/189">189</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/254">254</a> 29 November 2022]</i></p></li><li><p>
               Sequences, arrays, and maps can be destructured in a <code>let</code> 
               clause to extract their components into multiple variables. 
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/37">37</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2055">2055</a> 17 June 2025]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LetClause"/><code><a href="#prod-xquery40-LetClause">LetClause</a></code></td><td>::=</td><td><code>"let"  (<a href="#doc-xquery40-LetClause-LetBinding">LetBinding</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LetClause-LetBinding"/><code><a href="#prod-xquery40-LetBinding">LetBinding</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-LetClause-LetValueBinding">LetValueBinding</a>  |  <a href="#doc-xquery40-LetClause-LetSequenceBinding">LetSequenceBinding</a>  |  <a href="#doc-xquery40-LetClause-LetArrayBinding">LetArrayBinding</a>  |  <a href="#doc-xquery40-LetClause-LetMapBinding">LetMapBinding</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LetClause-LetValueBinding"/><code><a href="#prod-xquery40-LetValueBinding">LetValueBinding</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-LetClause-VarNameAndType">VarNameAndType</a>  ":="  <a href="#doc-xquery40-LetClause-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LetClause-VarNameAndType"/><code><a href="#prod-xquery40-VarNameAndType">VarNameAndType</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-LetClause-EQName">EQName</a>
                        <a href="#doc-xquery40-LetClause-TypeDeclaration">TypeDeclaration</a>?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LetClause-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LetClause-TypeDeclaration"/><code><a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a></code></td><td>::=</td><td><code>"as"  <a href="#doc-xquery40-LetClause-SequenceType">SequenceType</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LetClause-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                        <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LetClause-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LetClause-LetSequenceBinding"/><code><a href="#prod-xquery40-LetSequenceBinding">LetSequenceBinding</a></code></td><td>::=</td><td><code>"$"  "("  (<a href="#doc-xquery40-LetClause-VarNameAndType">VarNameAndType</a> ++ ",")  ")"  <a href="#doc-xquery40-LetClause-TypeDeclaration">TypeDeclaration</a>?  ":="  <a href="#doc-xquery40-LetClause-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LetClause-LetArrayBinding"/><code><a href="#prod-xquery40-LetArrayBinding">LetArrayBinding</a></code></td><td>::=</td><td><code>"$"  "["  (<a href="#doc-xquery40-LetClause-VarNameAndType">VarNameAndType</a> ++ ",")  "]"  <a href="#doc-xquery40-LetClause-TypeDeclaration">TypeDeclaration</a>?  ":="  <a href="#doc-xquery40-LetClause-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LetClause-LetMapBinding"/><code><a href="#prod-xquery40-LetMapBinding">LetMapBinding</a></code></td><td>::=</td><td><code>"$"  "{"  (<a href="#doc-xquery40-LetClause-VarNameAndType">VarNameAndType</a> ++ ",")  "}"  <a href="#doc-xquery40-LetClause-TypeDeclaration">TypeDeclaration</a>?  ":="  <a href="#doc-xquery40-LetClause-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody></table><p>The purpose of a <code>let</code> clause is to bind values to one or more variables. 
               Each variable is bound to the result of evaluating an expression.</p><p>If a <code>let</code> clause declares multiple variables separated by commas, 
               it is semantically equivalent to multiple <code>let</code> clauses, 
               each containing a single variable. For example, the clause</p><div class="exampleInner"><pre>let $x := $expr1, $y := $expr2</pre></div><p>is semantically equivalent to the following sequence of clauses:</p><div class="exampleInner"><pre>let $x := $expr1
let $y := $expr2</pre></div><p>After performing this expansion, the effect of a <code>let</code> clause is as follows:</p><ol class="enumar"><li><p>If the let expression uses multiple variables, it is first expanded to a
set of nested let expressions, each of which uses only one variable. 
Specifically, any separating comma is replaced by <code>let</code>.</p><div class="example">
<div class="exampleHeader"><a id="d2e34849"/>Example:</div><p>The expression:</p><div class="exampleInner"><pre>let $x := 4, $y := 3 return $x + $y</pre></div><p>is expanded to:</p><div class="exampleInner"><pre>let $x := 4 let $y := 3 return $x + $y</pre></div></div></li><li><p>In a <a href="#prod-xquery40-LetValueBinding">LetValueBinding</a>
                  such as <code>let $<var>V</var> as <var>T</var> := <var>EXPR</var>
                        </code>:</p><ol class="enumla"><li><p>The variable <var>V</var> is declared as a <b>range variable</b>.</p></li><li><p>The sequence type <var>T</var> is called the <b>declared type</b>.
                     If there is no declared type, then <code>item()*</code> is assumed.</p></li><li><p>The expression <var>EXPR</var> is evaluated, and its value is converted
                     to the declared type by applying the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>.
                     The resulting value forms the <b>binding sequence</b> for the range variable.</p></li></ol></li><li><p>In a <a href="#prod-xquery40-LetSequenceBinding">LetSequenceBinding</a>
                  such as <code>let $( $<var>A<sub>1</sub></var> as <var>T<sub>1</sub></var>, $<var>A<sub>2</sub></var> as <var>T<sub>2</sub></var>, ...
                     , $<var>A<sub>n</sub></var> as <var>T<sub>n</sub></var> ) as <var>ST</var> := <var>EXPR</var>
                        </code>:</p><ol class="enumla"><li><p>The sequence type <var>ST</var> is called the <b>declared sequence type</b>.
                     If there is no declared sequence type, then <code>item()*</code> is assumed.</p></li><li><p>The expression <var>EXPR</var> is evaluated, and its value is converted
                     to the declared sequence type <var>ST</var> by applying the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>.
                     Call the resulting (coerced) value <var>V</var>.</p></li><li><p>Each variable <var>A<sub>i</sub></var> (for <var>i</var> in 1 to <var>n</var>-1)
                     is effectively replaced by a <a href="#prod-xquery40-LetValueBinding">LetValueBinding</a>
                        of the form <code>let <var>A<sub>i</sub></var> as <var>T<sub>i</sub></var> := items-at(<var>V</var>, <var>i</var>)</code>.
                     That is, a <b>range variable</b> named <var>A<sub>i</sub></var> is declared, whose <b>binding sequence</b>
                     is the item <var>V[ i ]</var>, after coercion to the type <var>T<sub>i</sub></var> if specified.
                     If <var>T<sub>i</sub></var> is absent, no further coercion takes place (the default is effectively
                     <code>item()?</code>).</p></li><li><p>The last variable <var>A<sub>n</sub></var> 
                     is effectively replaced by a <a href="#prod-xquery40-LetValueBinding">LetValueBinding</a>
                        of the form <code>let <var>A<sub>n</sub></var> as <var>T<sub>n</sub></var> := subsequence(<var>V</var>, <var>n</var>)</code>.
                        That is, the last variable is bound to the rest of the binding sequence (or to the empty sequence
                        if the binding sequence has fewer items than the number of variables).
                     </p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>For any variable <var>A<sub>i</sub></var>, including the last, 
                           if <var>i</var> exceeds the length of the sequence <var>V</var>, then
                        <var>A<sub>i</sub></var> is bound to an empty sequence. This will cause a type error if
                        type <var>T<sub>i</sub></var> does not permit an empty sequence.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>It is permissible to bind several variables with the same name;
                        all but the last are occluded. A useful convention is therefore to bind
                        items in the sequence that are of no interest to the variable <code>$_</code>:
                        for example <code>let $( $_, $_, $x ) := <var>EXPR</var>
                           </code> effectively
                        binds <code>$x</code> to the subsequence starting at the third item, while causing the first two
                        items to be ignored.</p></div><div class="example">
<div class="exampleHeader"><a id="d2e35037"/>Example:</div><p>The expression:</p><div class="exampleInner"><pre>let $( $a, $b as xs:integer, $local:c ) := (2, 4, 6)
return $a + $b + $local:c</pre></div><p>is expanded to:</p><div class="exampleInner"><pre>let $temp := (2, 4, 6)
let $a := fn:items-at($temp, 1)
let $b as xs:integer := fn:items-at($temp, 2)
let $local:c := fn:subsequence($temp, 3)
return $a + $b + $local:c</pre></div><p>where <code>$temp</code> is some variable name that is otherwise unused.</p></div><p> </p><div class="example">
<div class="exampleHeader"><a id="d2e35050"/>Example:</div><p>Consider the element <var>$E</var> := <code>&lt;e A="p q r" B="x y z"/&gt;</code>.</p><p>Then consider the expression:</p><div class="exampleInner"><pre>let $( $a, $b ) := $E!(@A, @B)</pre></div><p>Here the binding sequence is a sequence of two attribute nodes, so
                        <code>$a</code> is bound to the attribute <code>@A</code>, and <code>$b</code>
                        is bound to the attribute node <code>@B</code>.</p><p>If the operator <code>"!"</code> were replaced by <code>"/"</code>, or if
                        <code>","</code> were replaced by <code>"|"</code>, then the binding sequence
                        would be sorted into document order, and since the order of attributes is
                        not defined, this would make it unpredictable which variable is bound
                        to which attribute node.</p><p>Now consider what happens when a declared sequence type is added:</p><div class="exampleInner"><pre>let $( $a, $b ) as xs:string* := $E!(@A, @B)</pre></div><p>The sequence of two attribute nodes is now atomized to form a sequence of strings.
                        The first string in this sequence is bound to <code>$a</code>, and the remainder
                        of the sequence is bound to <code>$b</code>. If the element <code>$E</code> is untyped,
                        this will result in <code>$a</code> being bound to the <code>xs:untypedAtomic</code>
                        value <code>"p q r"</code>, while <code>$b</code> is bound to the <code>xs:untypedAtomic</code>
                        value <code>"x y z"</code>.</p><p>However, suppose that the element <code>$E</code> has been validated against a schema
                        that defines both attributes <code>@A</code> and <code>@B</code> as list types with
                        item type <code>xs:string</code>. In this case, the atomized value of <code>$E</code>
                        will be a sequence of six strings. The variable <code>$a</code> is bound to the first
                        of these strings (that is, <code>"p"</code>), while <code>$b</code> is bound to a
                        sequence containing the remaining five strings (that is, <code>("q", "r", "x", "y", "z")</code>).</p><p>By contrast, if the expression is written as:</p><div class="exampleInner"><pre>let $( $a as xs:string*, $b as xs:string* ) := $E!(@A, @B)</pre></div><p>then <code>$a</code> is bound to the result of atomizing the first attribute
                     (the <code>untypedAtomic</code> value <code>"p q r"</code> in the untyped case, or
                     the sequence of three strings <code>("p", "q", "r")</code> in the schema-validated case),
                     while <code>$b</code> is similarly bound to the result of atomizing the second attribute.</p></div><p> </p><div class="example">
<div class="exampleHeader"><a id="d2e35174"/>Example:</div><p>Consider transforming the string <code>"Nf3 Nf6 c4 g6 Nc3 Bg7 d4 O-O Bf4 d5"</code>
                     (notation for the start of a chess game) to the form 
                     <code>(["Nf3", "Nf6",] ["c4", "g6"], [ "Nc3", "Bg7"], [ "d4", "O-O"], ["Bf4", "d5"])</code>.
                     This can be achieved as follows:</p><div class="exampleInner"><pre>declare function local:grouped-moves($moves) {
   if (exists($moves)) {
     let $($m1, $m2, $rest) := $moves
     return [$m1, $m2], local:grouped-moves($rest)
  }
};
local:grouped-moves(tokenize("Nf3 Nf6 c4 g6 Nc3 Bg7 d4 O-O Bf4 d5"))</pre></div></div></li><li><p>In a <a href="#prod-xquery40-LetArrayBinding">LetArrayBinding</a>
                  such as <code>let $[ $<var>A<sub>1</sub></var> as <var>T<sub>1</sub></var>, $<var>A<sub>2</sub></var> as <var>T<sub>2</sub></var>, ...
                     , $<var>A<sub>n</sub></var> as <var>T<sub>n</sub></var> ] as <var>AT</var> := <var>EXPR</var>
                        </code>:</p><ol class="enumla"><li><p>The sequence type <var>AT</var> is called the <b>declared array type</b>.
                     If there is no declared array type, then <code>array(*)</code> is assumed.</p></li><li><p>The expression <var>EXPR</var> is evaluated, and its value is converted
                     to the declared array type <var>AT</var> by applying the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>.
                     A type error [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>] is raised if the result is not
                        a <a title="singleton" class="termref" href="#dt-singleton">singleton</a> array.
                     Call the resulting (coerced) value <var>V</var>.</p></li><li><p>Each variable <var>A<sub>i</sub></var> (for <var>i</var> in 1 to <var>n</var>)
                     is effectively replaced by a <a href="#prod-xquery40-LetValueBinding">LetValueBinding</a>
                        of the form <code>let <var>A<sub>i</sub></var> as <var>T<sub>i</sub></var> := array:get(<var>V</var>, <var>i</var>)</code>.
                     That is, a <b>range variable</b> named <var>A<sub>i</sub></var> is declared, whose <b>binding sequence</b>
                     is the array member <var>V ? i</var>, after coercion to the type <var>T<sub>i</sub></var> if specified.
                     If <var>T<sub>i</sub></var> is absent, no further coercion takes place (the default is effectively
                     <code>item()*</code>).</p><div class="note"><p class="prefix"><b>Note:</b></p><p>If <var>i</var> exceeds the length of the array <var>V</var>, then
                        an error [<a href="https://www.w3.org/TR/xpath-functions/#ERRFOAR0001" title="err:FOAR0001">err:FOAR0001</a>]<sup><small>FO</small></sup> is raised.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>It is permissible to bind several variables with the same name;
                        all but the last are occluded. A useful convention is therefore to bind
                        items in the sequence that are of no interest to the variable <code>$_</code>:
                        for example <code>let $( $_, $_, $x ) := <var>EXPR</var>
                                 </code> effectively
                        binds <code>$x</code> to the third item in the sequence and causes the first two
                        items to be ignored.</p></div><div class="example">
<div class="exampleHeader"><a id="d2e35304"/>Example:</div><p>The expression:</p><div class="exampleInner"><pre>let $[ $a, $b as xs:integer, $local:c ] := [ 2, 4, 6 ]
return $a + $b + $local:c</pre></div><p>is expanded to:</p><div class="exampleInner"><pre>let $temp := [ 2, 4, 6 ]
let $a := array:get($temp, 1, ())
let $b as xs:integer := array:get($temp, 2)
let $local:c := array:get($temp, 3, ())
return $a + $b + $local:c</pre></div><p>where <code>$temp</code> is some variable name that is otherwise unused.</p></div></li></ol></li><li><p>In a <a href="#prod-xquery40-LetMapBinding">LetMapBinding</a>
                  such as <code>let ${ $<var>A<sub>1</sub></var> as <var>T<sub>1</sub></var>, $<var>A<sub>2</sub></var> as <var>T<sub>2</sub></var>, ...
                     , $<var>A<sub>n</sub></var> as <var>T<sub>n</sub></var> } as <var>MT</var> := <var>EXPR</var>
                        </code>:</p><ol class="enumla"><li><p>The sequence type <var>MT</var> is called the <b>declared map type</b>.
                     If there is no declared map type, then <code>map(*)</code> is assumed.</p></li><li><p>The expression <var>EXPR</var> is evaluated, and its value is converted
                     to the declared map type <var>MT</var> by applying the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>.
                     A type error [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>] is raised if the result is not
                        a <a title="singleton" class="termref" href="#dt-singleton">singleton</a> map.
                     Call the resulting (coerced) value <var>V</var>.</p></li><li><p>Each variable <var>A<sub>i</sub></var> (for <var>i</var> in 1 to <var>n</var>)
                     is effectively replaced by a <a href="#prod-xquery40-LetValueBinding">LetValueBinding</a>
                        of the form <code>let <var>A<sub>i</sub></var> as <var>T<sub>i</sub></var> := map:get(<var>V</var>, "<var>N<sub>i</sub></var>", ())</code>,
                        where <var>N<sub>i</sub></var> is the local part of the name of the variable <var>A<sub>i</sub></var>.
                     That is, a <b>range variable</b> named <var>A<sub>i</sub></var> is declared, whose <b>binding sequence</b>
                     is the value of the map entry in <var>V</var> whose key is an <code>xs:string</code> (or <code>xs:anyURI</code> or <code>xs:untypedAtomic</code>)
                        equal to the local part of the variable name, after coercion to the type <var>T<sub>i</sub></var> if specified.
                     If <var>T<sub>i</sub></var> is absent, no further coercion takes place (the default is effectively
                     <code>item()*</code>).</p><div class="note"><p class="prefix"><b>Note:</b></p><p>If there is no entry in the map with a key corresponding to the variable
                           name, then the variable
                        <var>A<sub>i</sub></var> is bound to an empty sequence. This will cause a type error if
                        type <var>T<sub>i</sub></var> does not permit an empty sequence.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>It is not possible to use this mechanism to bind variables to values
                        in a map unless the keys in the map are strings in the form of <code>NCNames</code>.</p></div><div class="example">
<div class="exampleHeader"><a id="d2e35438"/>Example:</div><p>The expression:</p><div class="exampleInner"><pre>let ${ $a, $b as xs:integer, $local:c } := { "a": 2, "b": 4, "c": 6, "d": 8 }
return $a + $b + $local:c</pre></div><p>is expanded to:</p><div class="exampleInner"><pre>let $temp := { "a": 2, "b": 4, "c": 6 }
let $a := map:get($temp, "a", ())
let $b as xs:integer := map:get($temp, "b", ())
let $local:c := map:get($temp, "c", ())
return $a + $b + $local:c</pre></div><p>where <code>$temp</code> is some variable name that is otherwise unused.</p></div></li></ol></li><li><p>The effect of the <a href="#doc-xquery40-LetClause">LetClause</a> is to add
             one or more variable bindings to the tuple stream. Specifically, each
             <b>range variable</b> declared within the <code>LetClause</code>
             is bound to its corresponding <b>binding sequence</b>, and 
             the resulting variable binding is added to the current tuple, replacing
             any existing variable binding with the same variable name.</p><p>If the <code>LetClause</code> is the initial clause in a FLWOR expression, 
                it creates an initial tuple for the tuple stream, containing these variable
                bindings. This tuple stream serves as input to the next clause in the FLWOR expression.</p><p>If the <code>LetClause</code> is an intermediate clause in a FLWOR expression, 
               it adds the relevant variable bindings to each tuple in the input tuple stream. 
               The resulting tuples become the output tuple stream of the <code>let</code> clause.</p><p>The number of tuples in the output tuple stream of an intermediate <code>let</code> 
               clause is the same as the number of tuples in the input tuple stream. 
               The number of variable bindings in the output tuples is always greater than
               the number of variable bindings in the input tuples, unless the input tuples 
               already contain bindings for every variable binding created by the <code>LetClause</code>; 
               in this case, the new binding for any given variable name occludes (replaces) 
               an earlier binding for that variable name, and the number of bindings is unchanged.</p></li></ol><p>The semantics of type declarations are further defined in <a href="#id-binding-rules"><b>4.13.1 Variable Bindings</b></a>.</p><p>The following code fragment illustrates how a <code>for</code> clause 
               and a <code>let</code> clause can be used together. The <code>for</code> 
               clause produces an initial tuple stream containing a binding for variable 
               <code>$d</code> to each department number found in a given input document. 
               The <code>let</code> clause adds an additional binding to each tuple, 
               binding variable <code>$e</code> to a sequence of employees whose department 
               number matches the value of <code>$d</code> in that tuple.</p><div class="exampleInner"><pre>for $d in doc("depts.xml")/depts/deptno
let $e := doc("emps.xml")/emps/emp[deptno eq $d]</pre></div></div><div class="div3 xquery">
<h4><a id="id-windows"/>4.13.4 <a href="#id-windows" style="text-decoration: none">Window Clause</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-while">⬇</a> <a href="#id-xquery-let-clause">⬆</a></p><ol><li><p>
                  The <code>start</code> clause in window expressions has become optional, as well as
                  the <code>when</code> keyword and its associated expression.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/452">452</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/483">483</a> 18 May 2023]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause"/><code><a href="#prod-xquery40-WindowClause">WindowClause</a></code></td><td>::=</td><td><code>"for"  (<a href="#doc-xquery40-WindowClause-TumblingWindowClause">TumblingWindowClause</a>  |  <a href="#doc-xquery40-WindowClause-SlidingWindowClause">SlidingWindowClause</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-TumblingWindowClause"/><code><a href="#prod-xquery40-TumblingWindowClause">TumblingWindowClause</a></code></td><td>::=</td><td><code>"tumbling"  "window"  <a href="#doc-xquery40-WindowClause-VarNameAndType">VarNameAndType</a>  "in"  <a href="#doc-xquery40-WindowClause-ExprSingle">ExprSingle</a>
                        <a href="#doc-xquery40-WindowClause-WindowStartCondition">WindowStartCondition</a>?  <a href="#doc-xquery40-WindowClause-WindowEndCondition">WindowEndCondition</a>?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-VarNameAndType"/><code><a href="#prod-xquery40-VarNameAndType">VarNameAndType</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-WindowClause-EQName">EQName</a>
                        <a href="#doc-xquery40-WindowClause-TypeDeclaration">TypeDeclaration</a>?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-TypeDeclaration"/><code><a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a></code></td><td>::=</td><td><code>"as"  <a href="#doc-xquery40-WindowClause-SequenceType">SequenceType</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                        <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-WindowStartCondition"/><code><a href="#prod-xquery40-WindowStartCondition">WindowStartCondition</a></code></td><td>::=</td><td><code>"start"  <a href="#doc-xquery40-WindowClause-WindowVars">WindowVars</a>  ("when"  <a href="#doc-xquery40-WindowClause-ExprSingle">ExprSingle</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-WindowVars"/><code><a href="#prod-xquery40-WindowVars">WindowVars</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-WindowClause-CurrentVar">CurrentVar</a>?  <a href="#doc-xquery40-WindowClause-PositionalVar">PositionalVar</a>?  <a href="#doc-xquery40-WindowClause-PreviousVar">PreviousVar</a>?  <a href="#doc-xquery40-WindowClause-NextVar">NextVar</a>?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-CurrentVar"/><code><a href="#prod-xquery40-CurrentVar">CurrentVar</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-WindowClause-VarName">VarName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-VarName"/><code><a href="#prod-xquery40-VarName">VarName</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-WindowClause-EQName">EQName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-PositionalVar"/><code><a href="#prod-xquery40-PositionalVar">PositionalVar</a></code></td><td>::=</td><td><code>"at"  <a href="#doc-xquery40-WindowClause-VarName">VarName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-PreviousVar"/><code><a href="#prod-xquery40-PreviousVar">PreviousVar</a></code></td><td>::=</td><td><code>"previous"  <a href="#doc-xquery40-WindowClause-VarName">VarName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-NextVar"/><code><a href="#prod-xquery40-NextVar">NextVar</a></code></td><td>::=</td><td><code>"next"  <a href="#doc-xquery40-WindowClause-VarName">VarName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-WindowEndCondition"/><code><a href="#prod-xquery40-WindowEndCondition">WindowEndCondition</a></code></td><td>::=</td><td><code>"only"?  "end"  <a href="#doc-xquery40-WindowClause-WindowVars">WindowVars</a>  ("when"  <a href="#doc-xquery40-WindowClause-ExprSingle">ExprSingle</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WindowClause-SlidingWindowClause"/><code><a href="#prod-xquery40-SlidingWindowClause">SlidingWindowClause</a></code></td><td>::=</td><td><code>"sliding"  "window"  <a href="#doc-xquery40-WindowClause-VarNameAndType">VarNameAndType</a>  "in"  <a href="#doc-xquery40-WindowClause-ExprSingle">ExprSingle</a>
                        <a href="#doc-xquery40-WindowClause-WindowStartCondition">WindowStartCondition</a>?  <a href="#doc-xquery40-WindowClause-WindowEndCondition">WindowEndCondition</a>
                     </code></td></tr></tbody></table><p>Like a <code>for</code> clause, a <code>window</code> clause
iterates over its <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding
sequence</a> and generates a sequence of tuples. In the case of
a <code>window</code> clause, each tuple represents a window. [<a id="dt-window" title="window">Definition</a>: A <b>window</b> is a sequence of
consecutive items drawn from the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>.] Each
window is represented by at least one and at most nine bound
variables. The variables have user-specified names, but their roles
are as follows:</p><ul><li><p>
                        <em>Window-variable:</em> Bound to the sequence of
  items from the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding
  sequence</a> that comprise the window.</p></li><li><p>
                        <em>Start-item:</em> (Optional) Bound to the first item
  in the window.</p></li><li><p>
                        <em>Start-item-position:</em> (Optional) Bound to the
  ordinal position of the first window item in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding
  sequence</a>. <em>Start-item-position</em> is a <a title="positional variable" class="termref" href="#dt-positional-variable">positional variable</a>; hence, its type
  is <code>xs:integer</code>.
                  </p></li><li><p>
                        <em>Start-previous-item:</em> (Optional) Bound to the
  item in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding
  sequence</a> that precedes the first item in the window (empty
  sequence if none).</p></li><li><p>
                        <em>Start-next-item:</em> (Optional) Bound to the item
  in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>
  that follows the first item in the window (empty sequence if
  none).</p></li><li><p>
                        <em>End-item:</em> (Optional) Bound to the last item in
  the window.</p></li><li><p>
                        <em>End-item-position:</em> (Optional) Bound to the
  ordinal position of the last window item in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding
  sequence</a>. <em>End-item-position</em> is a <a title="positional variable" class="termref" href="#dt-positional-variable">positional variable</a>; hence, its type
  is <code>xs:integer</code>.
                  </p></li><li><p>
                        <em>End-previous-item:</em> (Optional) Bound to the
  item in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding
  sequence</a> that precedes the last item in the window (empty
  sequence if none).</p></li><li><p>
                        <em>End-next-item:</em> (Optional) Bound to the item in
  the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>
  that follows the last item in the window (empty sequence if
  none).</p></li></ul><p>All variables in a <code>window</code> clause must have distinct names;
 otherwise a <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0103" title="err:XQST0103">err:XQST0103</a>].</p><p>The following is an example of a <code>window</code> clause that
binds nine variables to the roles listed above. In this example, the
variables are named <code>$w</code>, <code>$s</code>,
<code>$spos</code>, <code>$sprev</code>, <code>$snext</code>,
<code>$e</code>, <code>$epos</code>, <code>$eprev</code>, and
<code>$enext</code> respectively. A <code>window</code> clause always
binds the window variable, but typically binds only a subset of the
other variables.</p><div class="exampleInner"><pre>for tumbling window $w in (2, 4, 6, 8, 10)
  start $s at $spos previous $sprev next $snext when true() 
  end   $e at $epos previous $eprev next $enext when true()</pre></div><p>Windows are
created by iterating over the items in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>, in order,
identifying the start item and the end item of each window by
evaluating the <a href="#prod-xquery40-WindowStartCondition">WindowStartCondition</a> and the <a href="#prod-xquery40-WindowEndCondition">WindowEndCondition</a>. Each of these
conditions is satisfied if the <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean
value</a> of the expression following the <code>when</code>
keyword is <code>true</code>.

The start item of the window is an item that satisfies the <a href="#prod-xquery40-WindowStartCondition">WindowStartCondition</a> (see <a href="#id-tumbling-windows"><b>4.13.4.1 Tumbling Windows</b></a> and <a href="#id-sliding-windows"><b>4.13.4.2 Sliding Windows</b></a> for a more complete explanation.) The end item of the window is the first item in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>, beginning with the start item, that satisfies the <a href="#prod-xquery40-WindowEndCondition">WindowEndCondition</a> (again, see <a href="#id-tumbling-windows"><b>4.13.4.1 Tumbling Windows</b></a> and <a href="#id-sliding-windows"><b>4.13.4.2 Sliding Windows</b></a> for more details.) Each window contains its start item, its end
item, and all items that occur between them in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>.
If the end item is the start item, then the window contains only one
item.  If a start item is identified, but no following item in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a> satisfies the <a href="#prod-xquery40-WindowEndCondition">WindowEndCondition</a>, then the <code>only</code> keyword determines whether a window is
generated: if <code>only end</code> is specified, then no window is
generated; otherwise, the end item is set to the last item in the
<a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a> and a window is generated.</p><p>In the above example, the <a href="#prod-xquery40-WindowStartCondition">WindowStartCondition</a> and <a href="#prod-xquery40-WindowEndCondition">WindowEndCondition</a> are both <code>true</code>,
which causes each item in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a> to be in a separate window. 
Typically, the <a href="#prod-xquery40-WindowStartCondition">WindowStartCondition</a> and <a href="#prod-xquery40-WindowEndCondition">WindowEndCondition</a> are expressed in terms of bound variables. For example, the following <a href="#prod-xquery40-WindowStartCondition">WindowStartCondition</a> might be used to start a new window for every item in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a> that is larger than both the previous item and the following item:</p><div class="exampleInner"><pre>start $s previous $sprev next $snext
when  $s &gt; $sprev and $s &gt; $snext</pre></div><p>The scoping rules for the variables bound by a <code>window</code> clause are as follows:</p><ul><li><p>In the <code>when</code>-expression of the <a href="#prod-xquery40-WindowStartCondition">WindowStartCondition</a>, the following variables (identified here by their roles) are in scope (if bound): <em>start-item, start-item-position, start-previous-item, start-next-item.</em>
                     </p></li><li><p>In the <code>when</code>-expression of the <a href="#prod-xquery40-WindowEndCondition">WindowEndCondition</a>, the following variables (identified here by their roles) are in scope (if bound): <em>start-item, start-item-position, start-previous-item, start-next-item, end-item, end-item-position, end-previous-item, end-next-item.</em>
                     </p></li><li><p>In the clauses of the FLWOR expression that follow the <code>window</code> clause, all nine of the variables bound by the <code>window</code> clause (including <em>window-variable</em>) are in scope (if bound).</p></li></ul><p>The <code>when</code> keyword of a condition and the associated expression is optional.
               If omitted, the expression defaults to <code>true()</code>.
               If the complete <code>start</code> clause is omitted, no variables are bound and
               the expression also defaults to <code>true()</code>.
               The <code>end</code> clause can be omitted only within a <a href="#prod-xquery40-TumblingWindowClause">TumblingWindowClause</a>.</p><p>In a <code>window</code> clause, the keyword <code>tumbling</code> or <code>sliding</code> determines the way in which the starting item of each window is identified, as explained in the following sections.</p><div class="div4">
<h5><a id="id-tumbling-windows"/>4.13.4.1 <a href="#id-tumbling-windows" style="text-decoration: none">Tumbling Windows</a></h5><p>If the window type is <code>tumbling</code>, then windows
never overlap. The search for the start of the first window begins at the beginning of the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>. After each window is generated, the search
for the start of the next window begins with the item in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a> that occurs after the ending item of the last generated
window. Thus, no item that occurs in one window can occur in another
window drawn from the same <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a> (unless the sequence contains the same item more than once). 
In a tumbling window clause,
the <code>end</code> clause is optional; if it is omitted, the
<code>start</code> clause is applied to identify all potential
starting items in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>, and a window is constructed
for each starting item, including all items from that starting item up
to the item before the next window’s starting item, or the end of the
<a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>, whichever comes first.</p><p>The following examples illustrate the use of tumbling windows.</p><ul><li><p>Show non-overlapping windows of three items.</p><div class="exampleInner"><pre>for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)
  start at $s
  only end at $e when $e - $s eq 2
return &lt;window&gt;{ $w }&lt;/window&gt;</pre></div><p>Result:</p><div class="exampleInner"><pre>&lt;window&gt;2 4 6&lt;/window&gt;
&lt;window&gt;8 10 12&lt;/window&gt;</pre></div></li><li><p>Show averages of non-overlapping three-item windows.</p><div class="exampleInner"><pre>
for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)
  start at $s
  only end at $e when $e - $s eq 2
return avg($w)</pre></div><p>Result:</p><div class="exampleInner"><pre>4 10</pre></div></li><li><p>Show first and last items in each window of three items.</p><div class="exampleInner"><pre>for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)
  start $first at $s
  only end $last at $e when $e - $s eq 2
return &lt;window&gt;{ $first, $last }&lt;/window&gt;</pre></div><p>Result:</p><div class="exampleInner"><pre>&lt;window&gt;2 6&lt;/window&gt;
&lt;window&gt;8 12&lt;/window&gt;</pre></div></li><li><p>Show non-overlapping windows of up to three items (illustrates <code>end</code> clause without the <code>only</code> keyword).</p><div class="exampleInner"><pre>for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)
  start at $s
  end at $e when $e - $s eq 2
return &lt;window&gt;{ $w }&lt;/window&gt;</pre></div><p>Result:</p><div class="exampleInner"><pre>&lt;window&gt;2 4 6&lt;/window&gt;
&lt;window&gt;8 10 12&lt;/window&gt;
&lt;window&gt;14&lt;/window&gt;</pre></div></li><li><p>Show non-overlapping windows of up to three items (illustrates use of <code>start</code> without explicit <code>end</code>).</p><div class="exampleInner"><pre>for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)
  start at $s when $s mod 3 = 1
return &lt;window&gt;{ $w }&lt;/window&gt;</pre></div><p>Result:</p><div class="exampleInner"><pre>&lt;window&gt;2 4 6&lt;/window&gt;
&lt;window&gt;8 10 12&lt;/window&gt;
&lt;window&gt;14&lt;/window&gt;</pre></div></li><li><p>Show non-overlapping sequences starting with a number divisible by 3.</p><div class="exampleInner"><pre>for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)
  start $first when $first mod 3 = 2
return &lt;window&gt;{ $w }&lt;/window&gt;</pre></div><p>Result:</p><div class="exampleInner"><pre>&lt;window&gt;2 4 6&lt;/window&gt;
&lt;window&gt;8 10 12&lt;/window&gt;
&lt;window&gt;14&lt;/window&gt;</pre></div></li><li><p>Show non-overlapping sequences ending with a number divisible by 3.</p><div class="exampleInner"><pre>for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)
  end $last when $last mod 3 = 0
return &lt;window&gt;{ $w }&lt;/window&gt;</pre></div><p>Result (identical to the result of the previous query):</p><div class="exampleInner"><pre>&lt;window&gt;2 4 6&lt;/window&gt;
&lt;window&gt;8 10 12&lt;/window&gt;
&lt;window&gt;14&lt;/window&gt;</pre></div></li></ul></div><div class="div4">
<h5><a id="id-sliding-windows"/>4.13.4.2 <a href="#id-sliding-windows" style="text-decoration: none">Sliding Windows</a></h5><p>If the window type is <code>sliding window</code>, then windows may
overlap. Every item in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a> that satisfies the <a href="#prod-xquery40-WindowStartCondition">WindowStartCondition</a> is the starting item of a new window. Thus, a given
item may be found in multiple windows drawn from the same <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>.</p><p>The following examples illustrate the use of sliding windows.</p><ul><li><p>Show windows of three items.</p><div class="exampleInner"><pre>for sliding window $w in (2, 4, 6, 8, 10, 12, 14)
  start at $s
  only end at $e when $e - $s eq 2
return &lt;window&gt;{ $w }&lt;/window&gt;</pre></div><p>Result:</p><div class="exampleInner"><pre>&lt;window&gt;2 4 6&lt;/window&gt;
&lt;window&gt;4 6 8&lt;/window&gt;
&lt;window&gt;6 8 10&lt;/window&gt;
&lt;window&gt;8 10 12&lt;/window&gt;
&lt;window&gt;10 12 14&lt;/window&gt;</pre></div></li><li><p>Show moving averages of three items.</p><div class="exampleInner"><pre>for sliding window $w in (2, 4, 6, 8, 10, 12, 14)
  start at $s
  only end at $e when $e - $s eq 2
return avg($w)</pre></div><p>Result:</p><div class="exampleInner"><pre>4 6 8 10 12</pre></div></li><li><p>Show overlapping windows of up to three items (illustrates <code>end</code> clause without the <code>only</code> keyword).</p><div class="exampleInner"><pre>for sliding window $w in (2, 4, 6, 8, 10, 12, 14)
  start at $s
  end at $e when $e - $s eq 2
return &lt;window&gt;{ $w }&lt;/window&gt;</pre></div><p>Result:</p><div class="exampleInner"><pre>&lt;window&gt;2 4 6&lt;/window&gt;
&lt;window&gt;4 6 8&lt;/window&gt;
&lt;window&gt;6 8 10&lt;/window&gt;
&lt;window&gt;8 10 12&lt;/window&gt;
&lt;window&gt;10 12 14&lt;/window&gt;
&lt;window&gt;12 14&lt;/window&gt;
&lt;window&gt;14&lt;/window&gt;</pre></div></li></ul></div><div class="div4">
<h5><a id="id-effects-of-window-clauses"/>4.13.4.3 <a href="#id-effects-of-window-clauses" style="text-decoration: none">Effects of Window Clauses on the Tuple Stream</a></h5><p>The effects of a <code>window</code> clause on the tuple stream are similar to the effects of a <code>for</code> clause. As described in <a href="#id-windows"><b>4.13.4 Window Clause</b></a>, a <code>window</code> clause generates zero or more windows, each of which is represented by at least one and at most nine bound variables.</p><p>If the <code>window</code> clause is the initial clause in a FLWOR expression, 
                  the bound variables that describe each window become an output tuple. 
                  These tuples form the initial tuple stream that serves as input to the next clause of the FLWOR expression. 
                  The order of tuples in the tuple stream is the
                  order in which their start items appear in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>. The cardinality of the tuple stream is equal to the number of windows.</p><p>If a <code>window</code> clause is an intermediate clause in a FLWOR expression, each input tuple generates zero or more output tuples, each consisting of  the original bound variables of the input tuple plus the new bound variables that represent one of the generated windows. For each tuple <em>T</em> in the input tuple stream, the output tuple stream will contain <em>N<sub>T</sub>
                     </em> tuples, where <em>N<sub>T</sub>
                     </em> is the number of windows generated by the <code>window</code> clause, 
                  given the bindings in the input tuple <em>T</em>. Input tuples for which no windows 
                  are generated are not represented in the output tuple stream. 
                  The order of tuples in the output stream is determined primarily by the order of the 
                  input tuples from which they were derived, and secondarily by the order in which their 
                  start items appear in the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>. </p><p>The following example illustrates a <code>window</code> clause that is the initial clause in a FLWOR expression. The example is based on input data that consists of a sequence of closing stock prices for a specific company. For this example we assume the following input data (assume that the <code>price</code> elements have a validated type of <code>xs:decimal</code>):</p><div class="exampleInner"><pre>&lt;stock&gt;
  &lt;closing&gt; &lt;date&gt;2008-01-01&lt;/date&gt; &lt;price&gt;105&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;date&gt;2008-01-02&lt;/date&gt; &lt;price&gt;101&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;date&gt;2008-01-03&lt;/date&gt; &lt;price&gt;102&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;date&gt;2008-01-04&lt;/date&gt; &lt;price&gt;103&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;date&gt;2008-01-05&lt;/date&gt; &lt;price&gt;102&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;date&gt;2008-01-06&lt;/date&gt; &lt;price&gt;104&lt;/price&gt; &lt;/closing&gt;
&lt;/stock&gt;</pre></div><p>A user wishes to find “run-ups,” which are defined as sequences of dates that begin with a “low” and end with a “high” price (that is, the stock price begins to rise on the first day of the run-up, and continues to rise or remain even through the last day of the run-up.) The following query uses a tumbling window to find run-ups in the input data:</p><div class="exampleInner"><pre>for tumbling window $w in //closing
   start $first next $second when $first/price &lt; $second/price
   end $last next $beyond when $last/price &gt; $beyond/price
return
  &lt;run-up&gt;
    &lt;start-date&gt;{ data($first/date) }&lt;/start-date&gt;
    &lt;start-price&gt;{ data($first/price) }&lt;/start-price&gt;
    &lt;end-date&gt;{ data($last/date) }&lt;/end-date&gt;
    &lt;end-price&gt;{ data($last/price) }&lt;/end-price&gt;
  &lt;/run-up&gt;</pre></div><p>For our sample input data, this <code>tumbling window</code> clause generates a tuple stream consisting of two tuples, each representing a window and containing five bound variables named <code>$w</code>, <code>$first</code>, <code>$second</code>, <code>$last</code>, and <code>$beyond</code>. The <code>return</code> clause is evaluated for each of these tuples, generating the following query result:</p><div class="exampleInner"><pre>&lt;run-up&gt;
  &lt;start-date&gt;2008-01-02&lt;/start-date&gt;
  &lt;start-price&gt;101&lt;/start-price&gt;
  &lt;end-date&gt;2008-01-04&lt;/end-date&gt;
  &lt;end-price&gt;103&lt;/end-price&gt;
&lt;/run-up&gt;
&lt;run-up&gt;
  &lt;start-date&gt;2008-01-05&lt;/start-date&gt;
  &lt;start-price&gt;102&lt;/start-price&gt;
  &lt;end-date&gt;2008-01-06&lt;/end-date&gt;
  &lt;end-price&gt;104&lt;/end-price&gt;
&lt;/run-up&gt;</pre></div><p>The following example illustrates a <code>window</code> clause that is an intermediate clause in a FLWOR expression. In this example, the input data contains closing stock prices for several different companies, each identified by a three-letter symbol. We assume the following input data (again assuming that the type of the <code>price</code> element is <code>xs:decimal</code>):</p><div class="exampleInner"><pre>&lt;stocks&gt;
  &lt;closing&gt; &lt;symbol&gt;ABC&lt;/symbol&gt; &lt;date&gt;2008-01-01&lt;/date&gt; &lt;price&gt;105&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;symbol&gt;DEF&lt;/symbol&gt; &lt;date&gt;2008-01-01&lt;/date&gt; &lt;price&gt;057&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;symbol&gt;ABC&lt;/symbol&gt; &lt;date&gt;2008-01-02&lt;/date&gt; &lt;price&gt;101&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;symbol&gt;DEF&lt;/symbol&gt; &lt;date&gt;2008-01-02&lt;/date&gt; &lt;price&gt;054&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;symbol&gt;ABC&lt;/symbol&gt; &lt;date&gt;2008-01-03&lt;/date&gt; &lt;price&gt;102&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;symbol&gt;DEF&lt;/symbol&gt; &lt;date&gt;2008-01-03&lt;/date&gt; &lt;price&gt;056&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;symbol&gt;ABC&lt;/symbol&gt; &lt;date&gt;2008-01-04&lt;/date&gt; &lt;price&gt;103&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;symbol&gt;DEF&lt;/symbol&gt; &lt;date&gt;2008-01-04&lt;/date&gt; &lt;price&gt;052&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;symbol&gt;ABC&lt;/symbol&gt; &lt;date&gt;2008-01-05&lt;/date&gt; &lt;price&gt;101&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;symbol&gt;DEF&lt;/symbol&gt; &lt;date&gt;2008-01-05&lt;/date&gt; &lt;price&gt;055&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;symbol&gt;ABC&lt;/symbol&gt; &lt;date&gt;2008-01-06&lt;/date&gt; &lt;price&gt;104&lt;/price&gt; &lt;/closing&gt;
  &lt;closing&gt; &lt;symbol&gt;DEF&lt;/symbol&gt; &lt;date&gt;2008-01-06&lt;/date&gt; &lt;price&gt;059&lt;/price&gt; &lt;/closing&gt;
&lt;/stocks&gt;</pre></div><p>As in the previous example, we want to find "run-ups," which are defined as sequences of dates that begin with a "low" and end with a "high" price for a specific company. In this example, however, the input data consists of stock prices for multiple companies. Therefore it is necessary to isolate the stock prices of each company before forming windows. This can be accomplished by an initial <code>for</code> and <code>let</code> clause, followed by a <code>window</code> clause, as follows:</p><div class="exampleInner"><pre>for $symbol in distinct-values(//symbol)
let $closings := //closing[symbol = $symbol]
for tumbling window $w in $closings
  start $first next $second when $first/price &lt; $second/price
  end $last next $beyond when $last/price &gt; $beyond/price
return
  &lt;run-up symbol="{ $symbol }"&gt;
    &lt;start-date&gt;{ data($first/date) }&lt;/start-date&gt;
    &lt;start-price&gt;{ data($first/price) }&lt;/start-price&gt;
    &lt;end-date&gt;{ data($last/date) }&lt;/end-date&gt;
    &lt;end-price&gt;{ data($last/price) }&lt;/end-price&gt;
  &lt;/run-up&gt;</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>In the above example, the <code>for</code> and <code>let</code> clauses could be rewritten as follows:</p><div class="exampleInner"><pre>for $closings in //closing
let $symbol := $closings/symbol
group by $symbol</pre></div><p>The <code>group by</code> clause is described in <a href="#id-group-by"><b>4.13.8 Group By Clause</b></a>.</p></div><p>The <code>for</code> and <code>let</code> clauses in this query generate an initial tuple stream consisting of two tuples. In the first tuple, <code>$symbol</code> is bound to "ABC" and <code>$closings</code> is bound to the sequence of <code>closing</code> elements for company ABC. In the second tuple, <code>$symbol</code> is bound to "DEF" and <code>$closings</code> is bound to the sequence of <code>closing</code> elements for company DEF.</p><p>The <code>window</code> clause operates on this initial tuple stream, generating two windows for the first tuple and two windows for the second tuple. The result is a tuple stream consisting of four tuples, each with the following bound variables: <code>$symbol</code>, <code>$closings</code>, <code>$w</code>, <code>$first</code>, <code>$second</code>, <code>$last</code>, and <code>$beyond</code>. The <code>return</code> clause is then evaluated for each of these tuples, generating the following query result:</p><div class="exampleInner"><pre>&lt;run-up symbol="ABC"&gt;
   &lt;start-date&gt;2008-01-02&lt;/start-date&gt;
   &lt;start-price&gt;101&lt;/start-price&gt;
   &lt;end-date&gt;2008-01-04&lt;/end-date&gt;
   &lt;end-price&gt;103&lt;/end-price&gt;
&lt;/run-up&gt;
&lt;run-up symbol="ABC"&gt;
   &lt;start-date&gt;2008-01-05&lt;/start-date&gt;
   &lt;start-price&gt;101&lt;/start-price&gt;
   &lt;end-date&gt;2008-01-06&lt;/end-date&gt;
   &lt;end-price&gt;104&lt;/end-price&gt;
&lt;/run-up&gt;
&lt;run-up symbol="DEF"&gt;
   &lt;start-date&gt;2008-01-02&lt;/start-date&gt;
   &lt;start-price&gt;054&lt;/start-price&gt;
   &lt;end-date&gt;2008-01-03&lt;/end-date&gt;
   &lt;end-price&gt;056&lt;/end-price&gt;
&lt;/run-up&gt;
&lt;run-up symbol="DEF"&gt;
   &lt;start-date&gt;2008-01-04&lt;/start-date&gt;
   &lt;start-price&gt;052&lt;/start-price&gt;
   &lt;end-date&gt;2008-01-06&lt;/end-date&gt;
   &lt;end-price&gt;059&lt;/end-price&gt;
&lt;/run-up&gt;</pre></div></div></div><div class="div3 xquery">
<h4><a id="id-where"/>4.13.5 <a href="#id-where" style="text-decoration: none">Where Clause</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WhereClause"/><code><a href="#prod-xquery40-WhereClause">WhereClause</a></code></td><td>::=</td><td><code>"where"  <a href="#doc-xquery40-WhereClause-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WhereClause-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody></table><p>A <code>where</code> clause serves as a filter for the tuples in its input tuple stream. The expression in the <code>where</code> clause, called the <b>where-expression</b>, is evaluated once for
               each of these tuples. If the <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> of the
               where-expression is <code>true</code>, the tuple is retained in the output tuple stream; otherwise the tuple is discarded.</p><p>Examples:</p><ul><li><p>This example illustrates the effect of a <code>where</code> clause on a tuple stream:</p><p>Input tuple stream:</p><div class="exampleInner"><pre>($a = 5, $b = 11)
($a = 91, $b = 42)
($a = 17, $b = 30)
($a = 85, $b = 63)</pre></div><p>
                        <code>where</code> clause:</p><div class="exampleInner"><pre>where $a &gt; $b</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($a = 91, $b = 42)
($a = 85, $b = 63)</pre></div></li><li><p>The following query illustrates how a <code>where</code> clause might be used with a <a title="positional variable" class="termref" href="#dt-positional-variable">positional variable</a> to perform sampling on an input sequence. The query returns one value out of each one hundred input values.</p><div class="exampleInner"><pre><span class="parse-test">for $x at $i in $input
where $i mod 100 = 0
return $x</span></pre></div></li></ul></div><div class="div3 xquery">
<h4><a id="id-while"/>4.13.6 <a href="#id-while" style="text-decoration: none">While Clause</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-maps">⬇</a> <a href="#id-windows">⬆</a></p><ol><li><p>
                  A FLWOR expression may now include a <code>while</code> clause,
               which causes early exit from the iteration when a condition is encountered.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/187">187</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/943">943</a> 6 February 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WhileClause"/><code><a href="#prod-xquery40-WhileClause">WhileClause</a></code></td><td>::=</td><td><code>"while"  <a href="#doc-xquery40-WhileClause-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-WhileClause-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody></table><p>A <code>while</code> clause serves as a filter for the tuples 
               in its input tuple stream. The expression in the while clause, 
               called the <code>while-expression</code>, is evaluated once for each of these tuples. 
               If the <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> 
               of the <code>while-expression</code> is true, the 
               tuple is retained in the output tuple stream; otherwise the tuple 
               and all subsequent tuples in the stream are discarded.</p><p>Examples:</p><ul><li><p>This example illustrates the effect of a <code>while</code> clause on a tuple stream.</p><p>Input tuple stream:</p><div class="exampleInner"><pre>($a = 13, $b = 11)
($a = 91, $b = 42)
($a = 17, $b = 30)
($a = 85, $b = 63)</pre></div><p>while clause:</p><div class="exampleInner"><pre>while $a &gt; $b</pre></div><p> Output tuple stream:</p><div class="exampleInner"><pre>($a = 13, $b = 11)
($a = 91, $b = 42)</pre></div></li><li><p>The following query illustrates how a <code>while</code> clause might be used to 
                     extract all items in an input sequence before the first one that 
                     fails to satisfy some condition. In this case it selects the 
                     leading <code>para</code> elements in the input sequence, stopping 
                     before the first element that is not a <code>para</code> element.
                  </p><div class="exampleInner"><pre>for $x in $section/*
while $x[self::para]
return $x</pre></div></li><li><p>The following query illustrates how a <code>while</code> clause might be used to 
                     limit the number of items returned in the query result.
                  </p><div class="exampleInner"><pre>for $x in $section/para
where contains($x, 'the')
count $total
while $total le 10
return $x</pre></div><p>In this example a <code>where</code> clause would have exactly the same effect,
                  but might require a smarter optimizer to deliver the same performance.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>Although the semantics are described in terms of discarding 
                  all the tuples following the first one that fails to match 
                  the condition, a practical implementation is likely to avoid 
                  evaluating those tuples, thus giving an "early exit" from 
                  the iteration performed by the FLWOR expression.
               </p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The expression <code>for $i in $input while $i le 3</code> differs
               from the expression <code>subsequence-where($input, to := fn {. gt 3 })</code> in that
               the <code>while</code> expression drops the first item that is greater than 3,
               while the <code>subsequence-where</code> expression retains it.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The effect of the <code>while</code> clause is unpredictable in cases
            where the ordering of the tuple stream is unpredictable. This can happen, for example,
            when iterating over the entries in a map.</p></div></div><div class="div3 xquery">
<h4><a id="id-count"/>4.13.7 <a href="#id-count" style="text-decoration: none">Count Clause</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CountClause"/><code><a href="#prod-xquery40-CountClause">CountClause</a></code></td><td>::=</td><td><code>"count"  <a href="#doc-xquery40-CountClause-VarName">VarName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CountClause-VarName"/><code><a href="#prod-xquery40-VarName">VarName</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-CountClause-EQName">EQName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CountClause-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody></table><p>The purpose of a <code>count</code> clause is to enhance the tuple
stream with a new variable that is bound, in each tuple, to the
ordinal position of that tuple in the tuple stream. The name of the
new variable is specified in the <code>count</code> clause. Its type
            is implicitly <code>xs:integer</code>.</p><p>The output tuple stream of a <code>count</code> clause is the same
as its input tuple stream, with each tuple enhanced by one additional
variable that is bound to the ordinal position of that tuple in the
tuple stream. However, if the name of the new variable is the same as
the name of an existing variable in the input tuple stream, the new
variable occludes (replaces) the existing variable of the same name,
and the number of bound variables in each tuple is unchanged.</p><p>The following examples illustrate uses of the <code>count</code> clause:</p><ul><li><p>This example illustrates the effect of a <code>count</code> clause on an input tuple stream:</p><p>Input tuple stream:</p><div class="exampleInner"><pre>($name = "Bob", $age = 21)
($name = "Carol", $age = 19)
($name = "Ted", $age = 20)
($name = "Alice", $age = 22)</pre></div><p>
                        <code>count</code> clause:</p><div class="exampleInner"><pre>count $counter</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($name = "Bob", $age = 21, $counter = 1)
($name = "Carol", $age = 19, $counter = 2)
($name = "Ted", $age = 20, $counter = 3)
($name = "Alice", $age = 22, $counter = 4)</pre></div></li><li><p>This example illustrates how a counter might be used to filter the result of a query. The query ranks products in order by decreasing sales, and returns the three products with the highest sales. Assume that the variable <code>$products</code> is bound to a sequence of <code>product</code> elements, each of which has <code>name</code> and <code>sales</code> child-elements.</p><div class="exampleInner"><pre>for $p in $products
order by $p/sales descending
count $rank
while $rank &lt;= 3
return &lt;product rank="{ $rank }"&gt;{ $p/name, $p/sales }&lt;/product&gt;</pre></div><p>The result of this query has the following structure:</p><div class="exampleInner"><pre>&lt;product rank="1"&gt;
  &lt;name&gt;Toaster&lt;/name&gt;
  &lt;sales&gt;968&lt;/sales&gt;
&lt;/product&gt;
&lt;product rank="2"&gt;
  &lt;name&gt;Blender&lt;/name&gt;
  &lt;sales&gt;520&lt;/sales&gt;
&lt;/product&gt;
&lt;product rank="3"&gt;
  &lt;name&gt;Can Opener&lt;/name&gt;
  &lt;sales&gt;475&lt;/sales&gt;
&lt;/product&gt;</pre></div></li></ul></div><div class="div3 xquery">
<h4><a id="id-group-by"/>4.13.8 <a href="#id-group-by" style="text-decoration: none">Group By Clause</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-GroupByClause"/><code><a href="#prod-xquery40-GroupByClause">GroupByClause</a></code></td><td>::=</td><td><code>"group"  "by"  (<a href="#doc-xquery40-GroupByClause-GroupingSpec">GroupingSpec</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-GroupByClause-GroupingSpec"/><code><a href="#prod-xquery40-GroupingSpec">GroupingSpec</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-GroupByClause-VarName">VarName</a>  (<a href="#doc-xquery40-GroupByClause-TypeDeclaration">TypeDeclaration</a>?  ":="  <a href="#doc-xquery40-GroupByClause-ExprSingle">ExprSingle</a>)?  ("collation"  <a href="#doc-xquery40-GroupByClause-URILiteral">URILiteral</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-GroupByClause-VarName"/><code><a href="#prod-xquery40-VarName">VarName</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-GroupByClause-EQName">EQName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-GroupByClause-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-GroupByClause-TypeDeclaration"/><code><a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a></code></td><td>::=</td><td><code>"as"  <a href="#doc-xquery40-GroupByClause-SequenceType">SequenceType</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-GroupByClause-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                        <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-GroupByClause-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-GroupByClause-URILiteral"/><code><a href="#prod-xquery40-URILiteral">URILiteral</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-GroupByClause-StringLiteral">StringLiteral</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-GroupByClause-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody></table><p>A <code>group by</code> clause generates an output tuple stream in which each tuple represents a group of tuples from the input tuple stream
that have equivalent grouping keys. 
We will refer to the tuples in the input tuple stream as  <b>pre-grouping tuples</b>, and the tuples in the output tuple stream as <b>post-grouping tuples</b>.</p><p>The <code>group by</code> clause assigns each pre-grouping tuple to a group, and
generates one post-grouping tuple for each group. 

In the post-grouping tuple for a group, each grouping key is represented by a variable that was specified in a <a href="#prod-xquery40-GroupingSpec">GroupingSpec</a>, and every variable that appears in the pre-grouping tuples that were assigned to that group is represented by a variable of the same name, bound to a sequence of all values bound to the variable in any of these pre-grouping tuples.

Subsequent clauses in the FLWOR expression see only the variable
bindings in the post-grouping tuples; they no longer have access to
the variable bindings in the pre-grouping tuples. 
The number of post-grouping tuples is less than or equal to
the number of pre-grouping tuples.</p><p>A <code>group by</code> clause contains one or more <a href="#prod-xquery40-GroupingSpec">grouping specifications</a>, as shown in the grammar. [<a id="dt-grouping-variable" title="grouping variable">Definition</a>: Each grouping specification specifies one <b>grouping variable</b>, 
                     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.] Each grouping specification may optionally provide an expression to which its grouping variable is bound.  If no expression is provided, the grouping variable name must be equal (by the <code>eq</code> operator on <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a>) to the name of a variable in the input tuple stream, and it refers to that variable; otherwise a <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0094" title="err:XQST0094">err:XQST0094</a>]. For each grouping specification that contains a binding expression, a <code>let</code> binding is created in the pre-grouping tuples, and the grouping variable refers to that <code>let</code> binding. For example, the clause:</p><div class="exampleInner"><pre>group by $g1, $g2 := $expr1, $g3 := $expr2 collation "Spanish"</pre></div><p>is semantically equivalent to the following sequence of clauses:</p><div class="exampleInner"><pre>let $g2 := $expr1
let $g3 := $expr2
group by $g1, $g2, $g3 collation "Spanish"</pre></div><p>The process of group formation proceeds as follows:

</p><ol class="enumar"><li><p>
                           [<a id="dt-grouping-key" title="grouping key">Definition</a>: The
  atomized value of a <a title="grouping variable" class="termref" href="#dt-grouping-variable">grouping
  variable</a> is called a <b>grouping key</b>.]
  For each pre-grouping tuple, the <a title="grouping key" class="termref" href="#dt-grouping-key">grouping keys</a> are created by
  <a title="atomization" class="termref" href="#dt-atomization">atomizing</a> the values of the
  <a title="grouping variable" class="termref" href="#dt-grouping-variable">grouping variables</a> (in
  the post-grouping tuples, each grouping variable is set to the value
  of the corresponding grouping key, as discussed below).

  If the value of any <a title="grouping variable" class="termref" href="#dt-grouping-variable">grouping variable</a> consists of
  more than one item, a <a title="type error" class="termref" href="#dt-type-error">type
  error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>]. If a type declaration is present
  and the resulting atomized value is not an instance of the specified
  type, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised
  [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>The input tuple stream is partitioned into groups of tuples
  whose grouping keys are <a title="equivalent grouping keys" class="termref" href="#dt-equivalent-grouping-keys">equivalent</a>. [<a id="dt-equivalent-grouping-keys" title="equivalent grouping keys">Definition</a>: Two
  tuples <var>T<sub>1</sub></var> and <var>T<sub>2</sub></var> have <b>equivalent
  grouping keys</b> if and only if, for each grouping variable
  <var>GV</var>, the atomized value of <var>GV</var> in <var>T<sub>1</sub></var>
  is deep-equal to the atomized value of <var>GV</var> in
  <var>T<sub>2</sub></var>, as defined by applying the function
  <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-deep-equal"><code>fn:deep-equal</code></a> using the appropriate
  collation.]
                        </p><div class="note"><p class="prefix"><b>Note:</b></p><p>The <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-deep-equal"><code>fn:deep-equal</code></a> has been changed
                     in XQuery 4.0 so that it is now transitive; the problem that existed
                     in earlier versions when comparing numeric values of different
                     types has thereby been resolved.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The atomized grouping key will always be either an empty
     sequence or a single atomic item. Defining equivalence by
     reference to the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-deep-equal"><code>fn:deep-equal</code></a> function
     ensures that the empty sequence is equivalent only to the empty
     sequence, that <code>NaN</code> is equivalent to
     <code>NaN</code>, that untypedAtomic items are compared as
     strings, and that values for which the <code>eq</code> operator
     is not defined are considered
     non-equivalent.</p></div></li><li><p>The appropriate collation for comparing two grouping keys is the collation
   specified in the pertinent <a href="#prod-xquery40-GroupingSpec">GroupingSpec</a> if present, or the default collation
                        from the <span>dynamic</span> context otherwise. 
                        If the collation is specified by a relative
   URI, that relative URI is  <a title="resolve" class="termref" href="#dt-resolve-relative-uri">resolved to
   an absolute URI</a> using the <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a>.
   If the specified collation is not found in statically known
   collations, a static error is raised  [<a href="#ERRXQST0076" title="err:XQST0076">err:XQST0076</a>].</p></li></ol><p>Each group of tuples produced by the above process results in one
post-grouping tuple. The pre-grouping tuples from which the group is
derived have <em>equivalent</em>
                  <a title="grouping key" class="termref" href="#dt-grouping-key">grouping keys</a>, but these keys are not
necessarily identical (for example, the strings <code>"Frog"</code> and <code>"frog"</code>
might be <em>equivalent</em> according to the collation in use.)

In the post-grouping tuple, each <a title="grouping variable" class="termref" href="#dt-grouping-variable">grouping variable</a> is bound to the
value of the corresponding grouping key. 
</p><p>In the post-grouping tuple generated for a given group, each
non-grouping variable is bound to a sequence containing the
concatenated values of that variable in all the pre-grouping tuples
that were assigned to that group. The values derived from individual tuples are
concatenated in a way that preserves the order of the pre-grouping
tuple stream.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>This behavior may be surprising to SQL programmers, since SQL reduces
the equivalent of a non-grouping variable to one representative
value. Consider the following query:</p><div class="exampleInner"><pre>let $x := 64000
for $c in //customer
where $c/salary &gt; $x
group by $d := $c/department
return &lt;department name="{ $d }"&gt;
  Number of employees earning more than ${ $x } is { count($c) }
&lt;/department&gt;</pre></div><p>If there are three qualifying customers in the sales department this
evaluates to:</p><div class="exampleInner"><pre>
&lt;department name="sales"&gt;
  Number of employees earning more than $64000 64000 64000 is 3
&lt;/department&gt;</pre></div><p>In XQuery, each group is a sequence of items that match the group
by criteria—in a tree-structured language like XQuery, this is
convenient, because further structures can be built based on the items
in this sequence. Because there are three items in the group,
<code>$x</code> evaluates to a sequence of three items. To reduce this
to one item, use <code>fn:distinct-values()</code>:</p><div class="exampleInner"><pre>
let $x := 64000
for $c in //customer
let $d := $c/department
where $c/salary &gt; $x
group by $d
return &lt;department name="{ $d }"&gt;
  Number of employees earning more than ${ distinct-values($x) } is { count($c) }
&lt;/department&gt;</pre></div></div><div class="note"><p class="prefix"><b>Note:</b></p><p>In general, the <a title="static type" class="termref" href="#dt-static-type">static
type</a> of a variable in a post-grouping tuple is different
from the <a title="static type" class="termref" href="#dt-static-type">static type</a> of the
variable with the same name in the pre-grouping
tuples.</p></div><p>The order in which tuples appear in the
post-grouping tuple stream is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>An
<code>order by</code> clause can be used to impose a value-based
ordering on the post-grouping tuple stream. Similarly, if it is
desired to impose a value-based ordering within a group (i.e., on the
sequence of items bound to a non-grouping variable), this can be
accomplished by a nested FLWOR expression that iterates over these
items and applies an <code>order by</code> clause. In some cases, a
value-based ordering within groups can be accomplished by applying an
<code>order by</code> clause on a non-grouping variable before
applying the <code>group by</code> clause.</p></div><p>A <code>group
by</code> clause rebinds all the variables in the input tuple
stream. The scopes of these variables are not affected by the
<code>group by</code> clause, but in post-grouping tuples the values
of the variables represent group properties rather than properties of
individual pre-grouping tuples.</p><p>Examples:</p><ul><li><p>This example illustrates the effect of a <code>group by</code> clause on a tuple stream.</p><p>Input tuple stream:</p><div class="exampleInner"><pre>($storeno = &lt;storeno&gt;S101&lt;/storeno&gt;, $itemno = &lt;itemno&gt;P78395&lt;/itemno&gt;)
($storeno = &lt;storeno&gt;S102&lt;/storeno&gt;, $itemno = &lt;itemno&gt;P94738&lt;/itemno&gt;)
($storeno = &lt;storeno&gt;S101&lt;/storeno&gt;, $itemno = &lt;itemno&gt;P41653&lt;/itemno&gt;)
($storeno = &lt;storeno&gt;S102&lt;/storeno&gt;, $itemno = &lt;itemno&gt;P70421&lt;/itemno&gt;)</pre></div><p>
                        <code>group by</code> clause:</p><div class="exampleInner"><pre>group by $storeno</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($storeno = S101, $itemno = (&lt;itemno&gt;P78395&lt;/itemno&gt;, &lt;itemno&gt;P41653&lt;/itemno&gt;))
($storeno = S102, $itemno = (&lt;itemno&gt;P94738&lt;/itemno&gt;, &lt;itemno&gt;P70421&lt;/itemno&gt;))</pre></div></li></ul><ul><li><p>This example and the ones that follow are based on two separate sequences of elements, named <code>$sales</code> and <code>$products</code>. We assume that the variable <code>$sales</code> is bound to a sequence of elements with the following structure:</p><div class="exampleInner"><pre>&lt;sales&gt;
  &lt;storeno&gt;S101&lt;/storeno&gt;
  &lt;itemno&gt;P78395&lt;/itemno&gt;
  &lt;qty&gt;125&lt;/qty&gt;
&lt;/sales&gt;</pre></div><p>We also assume that the variable <code>$products</code> is bound to a sequence of  elements with the following structure:</p><div class="exampleInner"><pre>&lt;product&gt;
  &lt;itemno&gt;P78395&lt;/itemno&gt;
  &lt;price&gt;25.00&lt;/price&gt;
  &lt;category&gt;Men's Wear&lt;/category&gt;
&lt;/product&gt;</pre></div><p>The simplest kind of grouping query has a single <a title="grouping variable" class="termref" href="#dt-grouping-variable">grouping variable</a>. The query in this example finds the total quantity of items sold by each store:</p><div class="exampleInner"><pre>for $s in $sales
let $storeno := $s/storeno
group by $storeno
return &lt;store number="{ $storeno }" total-qty="{ sum($s/qty) }"/&gt;</pre></div><p>The result of this query is a sequence of elements with the following structure:</p><div class="exampleInner"><pre>&lt;store number="S101" total-qty="1550" /&gt;
&lt;store number="S102" total-qty="2125" /&gt;</pre></div></li><li><p>In a more realistic example, a user might be interested in the total revenue generated by each store for each product category. Revenue depends on both the quantity sold of various items and the price of each item. The following query joins the two input sequences and groups the resulting tuples by two <a title="grouping variable" class="termref" href="#dt-grouping-variable">grouping variables</a>:</p><div class="exampleInner"><pre>
for $s in $sales
for $p in $products[itemno = $s/itemno]
let $revenue := $s/qty * $p/price
group by $storeno := $s/storeno, 
         $category := $p/category
return &lt;summary storeno="{ $storeno }"
                category="{ $category }"
                revenue="{ sum($revenue) }"/&gt;</pre></div><p>The result of this query is a sequence of elements with the following structure:</p><div class="exampleInner"><pre>&lt;summary storeno="S101" category="Men's Wear" revenue="10185"/&gt;
&lt;summary storeno="S101" category="Stationery" revenue="4520"/&gt;
&lt;summary storeno="S102" category="Men's Wear" revenue="9750"/&gt;
&lt;summary storeno="S102" category="Appliances" revenue="22650"/&gt;
&lt;summary storeno="S102" category="Jewelry" revenue="30750"/&gt;</pre></div></li><li><p>The result of the previous example was a “flat” list of elements. A user might prefer the query result to be presented in the form of a  hierarchical report, grouped primarily by store (in order by store number) and secondarily by product category. Within each store, the user might want to see only those product categories whose total revenue exceeds $10,000, presented in descending order by their total revenue. This report is generated by the following query:</p><div class="exampleInner"><pre>for $s1 in $sales
let $storeno := $s1/storeno
group by $storeno
order by $storeno
return &lt;store storeno="{ $storeno }"&gt;{
  for $s2 in $s1
  for $p in $products[itemno = $s2/itemno]
  let $category := $p/category
  let $revenue := $s2/qty * $p/price
  group by $category
  let $group-revenue := sum($revenue)
  where $group-revenue &gt; 10000
  order by $group-revenue descending
  return &lt;category name="{ $category }" revenue="{ $group-revenue }"/&gt;
}&lt;/store&gt;</pre></div><p>The result of this example query has the following structure:</p><div class="exampleInner"><pre>&lt;store storeno="S101"&gt;
  &lt;category name="Men's Wear" revenue="10185"/&gt;
&lt;/store&gt;
&lt;store storeno="S102"&gt;
  &lt;category name="Jewelry" revenue="30750"/&gt;
  &lt;category name="Appliances" revenue="22650"/&gt;
&lt;/store&gt;</pre></div></li><li><p>The following example illustrates how to avoid a possible pitfall in writing grouping queries.</p><p>In each post-grouping tuple, all variables except for the grouping
variable are bound to sequences of items derived from all the
pre-grouping tuples from which the group was formed. For instance, in
the following query, <code>$high-price</code> is bound to a sequence
of items in the post-grouping tuple.</p><div class="exampleInner"><pre>let $high-price := 1000
for $p in $products[price &gt; $high-price]
let $category := $p/category
group by $category
return &lt;category name="{ $category }"&gt;{
  count($p) || ' products have price greater than ' || $high-price || '.'
}&lt;/category&gt;</pre></div><p>If three products in the “Men’s Wear” category have prices greater than 1000, the result of this query might look (in part) like this:</p><div class="exampleInner"><pre>&lt;category name="Men’s Wear"&gt;
  3 products have price greater than 1000 1000 1000.
&lt;/category&gt;</pre></div><p>The repetition of "1000" in this query result is due to the fact that <code>$high-price</code> is not a <a title="grouping variable" class="termref" href="#dt-grouping-variable">grouping variable</a>. One way to avoid this repetition is to move the binding of <code>$high-price</code> to an outer-level FLWOR expression, as follows:</p><div class="exampleInner"><pre>let $high-price := 1000
return (
  for $p in $products[price &gt; $high-price]
  let $category := $p/category
  group by $category
  return &lt;category name="{ $category }"&gt;{
    count($p) || ' products have price greater than ' || $high-price || '.'
  }&lt;/category&gt;  
)</pre></div><p>The result of the revised query might contain the following element:</p><div class="exampleInner"><pre>&lt;category name="Men's Wear"&gt;
  3 products have price greater than 1000.
&lt;/category&gt;</pre></div></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>If a collation name is specified, it must be supplied as a literal string; it cannot
                  be computed dynamically. A workaround in such cases is to use
                   the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collation-key"><code>fn:collation-key</code></a> function. For example:</p><div class="exampleInner"><pre>for $p in $products
group by collation-key($p/description, $collation)
return $product/@code</pre></div><p>Note however that the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collation-key"><code>fn:collation-key</code></a> function might not work
                  for all collations.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Grouping can also be achieved by constructing a map. For example, 
            the function call <code>map:build(//employee, fn { department })</code> constructs a map
            in which employees are grouped by department.</p></div></div><div class="div3 xquery">
<h4><a id="id-order-by-clause"/>4.13.9 <a href="#id-order-by-clause" style="text-decoration: none">Order By Clause</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrderByClause"/><code><a href="#prod-xquery40-OrderByClause">OrderByClause</a></code></td><td>::=</td><td><code>"stable"?  "order"  "by"  (<a href="#doc-xquery40-OrderByClause-OrderSpec">OrderSpec</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrderByClause-OrderSpec"/><code><a href="#prod-xquery40-OrderSpec">OrderSpec</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-OrderByClause-ExprSingle">ExprSingle</a>
                        <a href="#doc-xquery40-OrderByClause-OrderModifier">OrderModifier</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrderByClause-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrderByClause-OrderModifier"/><code><a href="#prod-xquery40-OrderModifier">OrderModifier</a></code></td><td>::=</td><td><code>("ascending"  |  "descending")?  ("empty"  ("greatest"  |  "least"))?  ("collation"  <a href="#doc-xquery40-OrderByClause-URILiteral">URILiteral</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrderByClause-URILiteral"/><code><a href="#prod-xquery40-URILiteral">URILiteral</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-OrderByClause-StringLiteral">StringLiteral</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrderByClause-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody></table><p>The purpose of an <code>order by</code> clause is to impose a value-based ordering on the tuples in the tuple stream. The output tuple stream of the <code>order by</code> clause contains the same tuples as its input tuple stream, but the tuples may be in a different order.</p><p>An <code>order by</code> clause contains one or more ordering specifications, called <a href="#prod-xquery40-OrderSpec">orderspecs</a>, as shown in the grammar. For each tuple in the input tuple stream, the orderspecs are evaluated, using the variable bindings in that tuple. The relative order of two tuples is determined by comparing the values of their orderspecs, working from left to right until a pair of unequal values is encountered. If an orderspec specifies a <a title="collation" class="termref" href="#dt-collation">collation</a>, that collation is used in comparing values of type <code>xs:string</code>, <code>xs:anyURI</code>, or types derived from them (otherwise, the <a title="default collation" class="termref" href="#dt-def-collation">default collation</a> is used in comparing values of these types). If an orderspec specifies a collation by a relative URI, that relative URI is  <a title="resolve" class="termref" href="#dt-resolve-relative-uri">resolved to an absolute URI</a> using the <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a>. 
If an orderspec specifies a collation that is not found in <a title="statically known collations" class="termref" href="#dt-static-collations">statically known collations</a>, an error is raised [<a href="#ERRXQST0076" title="err:XQST0076">err:XQST0076</a>].</p><p>The process of evaluating and comparing the orderspecs is based on
the following rules:</p><ul><li><p>
                        <a title="atomization" class="termref" href="#dt-atomization">Atomization</a> is applied to the result of the expression
    in each orderspec.  If the result of atomization is neither a single atomic item nor an empty sequence, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li></ul><p>For the purpose of determining their relative position in the ordering sequence, the <em>greater-than</em>
             relationship between two orderspec values <var>W</var> and <var>V</var> is defined as follows:</p><ul><li><p>When the orderspec specifies <code>empty least</code>,
                   the following rules are applied in order:
                </p><ol class="enumar"><li><p>If <var>V</var> is an empty sequence and <var>W</var> is not an empty sequence,
                         then <var>W</var>
                              <em>greater-than</em>
                              <var>V </var> is true.</p></li><li><p>If <var>V</var> is <code>NaN</code> and <var>W</var> is neither <code>NaN</code>
                         nor an empty sequence, then
                         <var>W</var>
                              <em>greater-than</em>
                              <var>V</var> is true.</p></li><li><p>If <var>V</var> and <var>W</var> are both instances of <code>xs:string</code>,
                        <code>xs:anyURI</code>, or <code>xs:untypedAtomic</code>, they are compared
                           using the function <code>fn:compare(V, W, C)</code> where <var>C</var> is the
                        requested collation, defaulting to the default collation from the static context.</p><p>If <code>fn:compare(V, W, C)</code> is less than
                         zero, then <em>W</em>
                              <em>greater-than</em>
                              <em>V</em> is true; otherwise <em>W</em>
                              <em>greater-than</em>
                              <em>V</em> is false.</p></li><li><p>If <var>V</var> and <var>W</var> are both instances of <code>xs:numeric</code>,
                           they are compared
                           using the function <code>fn:compare(V, W)</code>.</p><p>If <code>fn:compare(V, W)</code> is less than
                           zero, then <var>W</var>
                              <em>greater-than</em>
                              <var>V</var> is true; otherwise <var>W</var>
                              <em>greater-than</em>
                              <var>V</var> is false.</p></li><li><p>If none of the above rules apply, then:</p><p>If <code>W gt V</code> is true,
                         then <var>W</var>
                              <em>greater-than</em>
                              <var>V</var> is true; otherwise <var>W</var>
                              <em>greater-than</em>
                              <var>V</var> is false.</p></li></ol></li><li><p>When the orderspec specifies <code>empty greatest</code>,
                   the following rules are applied in order:
                </p><ol class="enumar"><li><p>If <var>W</var> is an empty sequence and <em>V</em> is not an empty sequence,
                         then <var>W</var>
                              <em>greater-than</em>
                              <var>V</var> is true.</p></li><li><p>If <var>W</var> is <code>NaN</code> and <var>V</var> is neither <code>NaN</code>
                         nor an empty sequence, then
                         <var>W</var>
                              <em>greater-than</em>
                              <var>V</var> is true.</p></li><li><p>If <var>V</var> and <var>W</var> are both instances of <code>xs:string</code>,
                           <code>xs:anyURI</code>, or <code>xs:untypedAtomic</code>, they are compared
                           using the function <code>fn:compare(V, W, C)</code> where <var>C</var> is the
                           requested collation, defaulting to the default collation from the static context.</p><p>If <code>fn:compare(V, W, C)</code> is less than
                           zero, then <em>W</em>
                              <em>greater-than</em>
                              <em>V</em> is true; otherwise <em>W</em>
                              <em>greater-than</em>
                              <em>V</em> is false.</p></li><li><p>If <var>V</var> and <var>W</var> are both instances of <code>xs:numeric</code>,
                           they are compared
                           using the function <code>fn:compare(V, W)</code>.</p><p>If <code>fn:compare(V, W)</code> is less than
                           zero, then <var>W</var>
                              <em>greater-than</em>
                              <var>V</var> is true; otherwise <var>W</var>
                              <em>greater-than</em>
                              <var>V</var> is false.</p></li><li><p>If none of the above rules apply, then:</p><p>If <code>W gt V</code> is true,
                           then <var>W</var>
                              <em>greater-than</em>
                              <var>V</var> is true; otherwise <var>W</var>
                              <em>greater-than</em>
                              <var>V</var> is false.</p></li></ol></li><li><p>When the orderspec specifies neither <code>empty least</code>
                   nor <code>empty greatest</code>, the
                   <a title="default order for empty sequences" class="termref" href="#dt-default-empty-order">default order for empty
                   sequences</a> in the
                   <a title="static context" class="termref" href="#dt-static-context">static context</a>
                   determines whether the rules for <code>empty least</code>
                   or <code>empty greatest</code> are used.
                </p></li></ul><p>If <em>T1</em> and <em>T2</em> are two tuples in the input tuple stream, and <em>V1</em> and <em>V2</em> are the first pair of  values encountered when evaluating their orderspecs  from left to right for which one value is <em>greater-than</em> the other (as defined above), then:</p><ol class="enumar"><li><p>If <em>V1</em> is <em>greater-than</em>
                        <em>V2:</em> If the orderspec specifies <code>descending</code>, then <em>T1</em> precedes <em>T2</em> in the output tuple stream; otherwise, <em>T2</em> precedes <em>T1</em> in the output tuple stream.</p></li><li><p>If <em>V2</em> is <em>greater-than</em>
                        <em>V1</em>: If the orderspec specifies <code>descending</code>, then <em>T2</em> precedes <em>T1</em> in the output tuple stream; otherwise, <em>T1</em> precedes <em>T2</em> in the output tuple stream.</p></li></ol><p>If neither <em>V1</em> nor <em>V2</em> is <em>greater-than</em> the other for any pair of orderspecs for tuples <em>T1</em> and <em>T2</em>, the following rules apply.</p><ol class="enumar"><li><p>If <code>stable</code> is specified, the original order of <em>T1</em> and <em>T2</em> is preserved in the output tuple stream.</p></li><li><p>If <code>stable</code> is not specified, the order of <em>T1</em> and <em>T2</em> in the output tuple stream is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>If two orderspecs return the special floating-point values positive and negative zero, neither of these values is <em>greater-than</em> the other, since <code>+0.0 gt -0.0</code> and <code>-0.0 gt +0.0</code> are both <code>false</code>.</p></div><p>Examples:</p><ul><li><p>This example illustrates the effect of an <code>order by</code> clause on a tuple stream. The keyword <code>stable</code> indicates that, when two tuples have equal sort keys, their order in the input tuple stream is preserved.</p><p>Input tuple stream:</p><div class="exampleInner"><pre>($license = "PFQ519", $make = "Ford",  $value = 16500)
($license = "HAJ865", $make = "Honda", $value = 22750)
($license = "NKV473", $make = "Ford",  $value = 21650)
($license = "RCM922", $make = "Dodge", $value = 11400)
($license = "ZBX240", $make = "Ford",  $value = 16500)
($license = "KLM030", $make = "Dodge", $value = ())</pre></div><p>
                        <code>order by</code> clause:</p><div class="exampleInner"><pre>stable order by $make,
  $value descending empty least</pre></div><p>Output tuple stream:</p><div class="exampleInner"><pre>($license = "RCM922", $make = "Dodge", $value = 11400)
($license = "KLM030", $make = "Dodge", $value = ())
($license = "NKV473", $make = "Ford",  $value = 21650)
($license = "PFQ519", $make = "Ford",  $value = 16500)
($license = "ZBX240", $make = "Ford",  $value = 16500)
($license = "HAJ865", $make = "Honda", $value = 22750)</pre></div></li><li><p>The following example shows how an <code>order by</code> clause can be used to sort the result of a query, even if the sort key is not included in the query result. This query returns employee names in descending order by salary, without returning the actual salaries:</p><div class="exampleInner"><pre>for $e in $employees
order by $e/salary descending
return $e/name</pre></div></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>If a collation name is specified, it must be supplied as a literal string; it cannot
                  be computed dynamically. Two possible workarounds are to use the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-sort"><code>fn:sort</code></a> function
               or the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collation-key"><code>fn:collation-key</code></a> function.</p><p>Using <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-sort"><code>fn:sort</code></a> the expression</p><div class="exampleInner"><pre>for $b in $books/book[price &lt; 100]
order by $b/title
return $b</pre></div><p>can be replaced with the following, which uses a dynamically-chosen collation:</p><div class="exampleInner"><pre>
sort(
  $books/book[price &lt; 100],
  $collation,
  function($book) { $book/title }
)</pre></div><p>Alternatively, it is possible to compute collation keys using a dynamically-chosen
               collation, and sort on the values of the collation keys:</p><div class="exampleInner"><pre>for $b in $books/book[price &lt; 100]
order by collation-key($b/title, $collation)
return $b</pre></div><p>Note however that the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collation-key"><code>fn:collation-key</code></a> function might not work
               for all collations.</p></div></div><div class="div3 xquery">
<h4><a id="id-return-clause"/>4.13.10 <a href="#id-return-clause" style="text-decoration: none">Return Clause</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ReturnClause"/><code><a href="#prod-xquery40-ReturnClause">ReturnClause</a></code></td><td>::=</td><td><code>"return"  <a href="#doc-xquery40-ReturnClause-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ReturnClause-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody></table><p>The <code>return</code> clause is the final clause of a FLWOR expression. 
               The <code>return</code> clause is evaluated once for each tuple in its input tuple stream,  
               using the variable bindings in the respective tuples, in the order in which these 
               tuples appear in the input tuple stream. The result of the FLWOR
               expression is the <a title="sequence concatenation" class="termref" href="#dt-sequence-concatenation">sequence concatenation</a> of the results
               of these evaluations.</p><p>The following example illustrates a FLWOR expression containing several clauses. The <code>for</code> clause iterates over all the departments in an input document named <code>depts.xml</code>, binding the variable <code>$d</code> to each department  in turn. For each binding of <code>$d</code>, the <code>let</code> clause binds variable <code>$e</code> to all the employees in the given department, selected from another input document named <code>emps.xml</code> (the relationship between employees and departments is represented by matching their <code>deptno</code> values). Each tuple in the resulting tuple stream contains a pair of bindings for <code>$d</code> and <code>$e</code> (<code>$d</code> is bound to a department and <code>$e</code> is bound to a set of employees in that department). The <code>where</code> clause filters the tuple stream, retaining only those tuples that represent departments having at least ten employees. The <code>order by</code> clause orders the surviving tuples in descending order by the average salary of the employees in the department. The <code>return</code> clause constructs a new <code>big-dept</code> element for each surviving tuple, containing the department number, headcount, and average salary.</p><div class="exampleInner"><pre>for $d in doc("depts.xml")//dept
let $e := doc("emps.xml")//emp[deptno eq $d/deptno]
where count($e) &gt;= 10
order by avg($e/salary) descending
return &lt;big-dept&gt;{
  $d/deptno,
  &lt;headcount&gt;{ count($e) }&lt;/headcount&gt;,
  &lt;avgsal&gt;{ avg($e/salary) }&lt;/avgsal&gt;
}&lt;/big-dept&gt;</pre></div><div class="note"><p class="prefix"><b>Notes:</b></p>
                  <ul><li><p>The order in which items appear in the result of a FLWOR expression depends
                        on the ordering of the input tuple stream to the <code>return</code> clause, 
                        which in turn is influenced by <code>order by</code> clauses. For example, 
                        consider the following query, which is based on the same two input documents as the previous example:</p><div class="exampleInner"><pre>for $d in doc("depts.xml")//dept
order by $d/deptno
for $e in doc("emps.xml")//emp[deptno eq $d/deptno]
return &lt;assignment&gt;{
  $d/deptno, $e/name
}&lt;/assignment&gt;</pre></div><p>The result of this query is a sequence of <code>assignment</code> elements, 
                        each containing a <code>deptno</code> element and a <code>name</code> element. 
                        The sequence will be ordered primarily by the <code>deptno</code> values because 
                        of the <code>order by</code> clause. 
                        Subsequences of <code>assignment</code> elements with equal <code>deptno</code> 
                        values will be ordered by the document order of their <code>name</code> elements 
                        within the <code>emps.xml</code> document.</p></li><li><p>Parentheses are helpful in <code>return</code> clauses that contain comma operators,
since FLWOR expressions have a higher precedence than the comma
operator. For example, the following query raises an error because
after the comma, <code>$j</code> is no longer within the FLWOR expression, and is an
undefined variable:</p><div class="exampleInner"><pre>let $i := 5
let $j := 20 * $i
return $i, $j</pre></div><p>Parentheses can be used to bring <code>$j</code> into the <code>return</code> clause of the FLWOR expression, as the
programmer probably intended:</p><div class="exampleInner"><pre>let $i := 5
let $j := 20 * $i
return ($i, $j)</pre></div></li></ul>
               </div></div></div><div class="div2">
<h3><a id="id-maps-and-arrays"/>4.14 <a href="#id-maps-and-arrays" style="text-decoration: none">Maps and Arrays</a></h3><p>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.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The XQuery 4.0 specification focuses on syntax provided for maps
  and arrays, especially constructors and lookup.</p><p>Some of the functionality typically needed for maps and
  arrays is provided by functions defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#maps">14 Processing maps</a>
               and <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#arrays">15 Processing arrays</a>, 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.</p></div><div class="div3">
<h4><a id="id-maps"/>4.14.1 <a href="#id-maps" style="text-decoration: none">Maps</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-map-constructors">⬇</a> <a href="#id-while">⬆</a></p><ol><li><p>Ordered maps are introduced.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1651">1651</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1703">1703</a> 14 January 2025]</i></p></li></ol></div><p>
                  [<a id="dt-map" title="map">Definition</a>: A <b>map</b> is a function
  that associates a set of keys with values, resulting in a collection
  of key / value pairs.]
                  [<a id="dt-entry" title="entry">Definition</a>: Each key / value pair in a map
  is called an <b>entry</b>.]
                  [<a id="dt-associated-value" title="associated value">Definition</a>: The value
  associated with a given key is called the <b>associated
  value</b> of the key.]
               </p><p>Maps and their properties are defined in the data model:
               see <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#map-items">8.2 Map Items</a>. For an overview
            of the functions available for processing maps,
            see <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#maps">14 Processing maps</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Maps in XQuery 4.0 are ordered.
                  The effect of this property is explained 
                  in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#map-items">8.2 Map Items</a>. 
                  In an ordered map, the order of entries is predictable
                  and depends on the order in which they were added to the map.</p></div><div class="div4">
<h5><a id="id-map-constructors"/>4.14.1.1 <a href="#id-map-constructors" style="text-decoration: none">Map Constructors</a></h5><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-lookup">⬇</a> <a href="#id-maps">⬆</a></p><ol><li><p>
                     In map constructors, the keyword <code>map</code> is now optional, so 
                     <code>map { 0: false(), 1: true() }</code> can now be written <code>{ 0: false(), 1: true() }</code>,
                     provided it is used in a context where this creates no ambiguity.
                  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1070">1070</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1071">1071</a> 26 March 2024]</i></p></li><li><p>The order of key-value
                     pairs in the map constructor is now retained in the constructed map.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1651">1651</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1703">1703</a> 14 January 2025]</i></p></li><li><p>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.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2003">2003</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2094">2094</a> 13 July 2025]</i></p></li></ol></div><p>A map can be created using a <a href="#doc-xquery40-MapConstructor">MapConstructor</a>.</p><p>Examples are:</p><div class="exampleInner"><pre>{ "a": 1, "b": 2 }</pre></div><p>which constructs a map with two entries, and</p><div class="exampleInner"><pre>{ "a": 1, if ($condition) { map{ "b": 2 } } }</pre></div><p>which constructs a map having either one or two entries depending on the
               value of <code>$condition</code>.</p><p>Both the keys and the values in a map constructor can be supplied as expressions
               rather than as constants.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MapConstructor"/><code><a href="#prod-xquery40-MapConstructor">MapConstructor</a></code></td><td>::=</td><td><code>"map"?  "{"  (<a href="#doc-xquery40-MapConstructor-MapConstructorEntry">MapConstructorEntry</a> ** ",")  "}"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MapConstructor-MapConstructorEntry"/><code><a href="#prod-xquery40-MapConstructorEntry">MapConstructorEntry</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-MapConstructor-ExprSingle">ExprSingle</a>  (":"  <a href="#doc-xquery40-MapConstructor-ExprSingle">ExprSingle</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MapConstructor-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                           <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                           <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                           <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                           <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                           <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                           <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                        </code></td></tr></tbody></table><div class="note"><p class="prefix"><b>Note:</b></p><p>The keyword <code>map</code> 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.</p><p>In order to allow the <code>map</code> 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
                  <code>QNameLiteral</code> syntax, for example <code>element #div {}</code>.</p><p>Although the grammar allows a <a href="#doc-xquery40-MapConstructor">MapConstructor</a>
                  to appear within an <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a> (that is, between
                  curly brackets), this may be confusing to readers, and using the <code>map</code>
                  keyword in such cases may improve clarity. The keyword <code>map</code> is used in the
                  second example above to avoid any confusion between the braces required for the
                  <code>then</code> part of the conditional expression, and the braces
                  required for the inner map constructor.</p><p>If the <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a>
                  appears in a context such as a <a href="#doc-xquery40-StringTemplate">StringTemplate</a>,
                  the two adjacent left opening braces must at least be separated by whitespace.</p></div><p>When a <a href="#prod-xquery40-MapConstructorEntry">MapConstructorEntry</a> is written as two instances of
               <a href="#doc-xquery40-ExprSingle">ExprSingle</a> 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 <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-single-entry-map">single-entry map</a><sup><small>DM</small></sup>
               which will be merged into the constructed map, as described below.
               A <a title="type error" class="termref" href="#dt-type-error">type error</a>
                     [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>] occurs if the result of the first
                  expression (after atomization) is not a single atomic item. The result
               of the second expression is used <em>as is</em>.</p><p>When the <a href="#prod-xquery40-MapConstructorEntry">MapConstructorEntry</a> is written as a
               single instance of <a href="#doc-xquery40-ExprSingle">ExprSingle</a> with no colon, it must evaluate
               to a sequence of zero or more map items ([<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>]).
                  However, the coercion rules also allow a JNode
                  whose <b>·content·</b> is a map (or a sequence of maps) to be supplied.
                  These map items will be merged into the constructed map, as described below.</p><p>Each contained <a href="#prod-xquery40-MapConstructorEntry">MapConstructorEntry</a> 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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-map-merge"><code>map:merge</code></a>
                  function.</p><p>
                     [<a id="dt-same-key" title="same key">Definition</a>: Two atomic items <var>K<sub>1</sub></var> and
    <var>K<sub>2</sub></var> have the <b>same key value</b> if
    
    
      <code>fn:atomic-equal(<var>K<sub>1</sub></var>, <var>K<sub>2</sub></var>)</code> returns <code>true</code>, as specified in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#func-atomic-equal">2.2.1 fn:atomic-equal</a>
                     ]

    If two or more entries have the <a title="same key" class="termref" href="#dt-same-key">same key value</a> then a dynamic
    error is raised [<a href="#ERRXQDY0137" title="err:XQDY0137">err:XQDY0137</a>].
                  
                  The error <span class="verb">may</span> be raised statically if two or more entries can be determined statically
                  to have the <a title="same key" class="termref" href="#dt-same-key">same key value</a>.

    
    </p><p>The <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-entry-order">entry order</a><sup><small>DM</small></sup>
                  of the entries in the constructed map retains the order of the 
                  <a href="#prod-xquery40-MapConstructorEntry">MapConstructorEntry</a> entries
                  in the input.</p><div class="example">
<div class="exampleHeader"><a id="d2e38345"/>Example: Constructing a fixed map</div><p>The following expression constructs a map with seven entries:</p><div class="exampleInner"><a id="map-weekdays"/><pre>
{
  "Su" : "Sunday",
  "Mo" : "Monday",
  "Tu" : "Tuesday",
  "We" : "Wednesday",
  "Th" : "Thursday",
  "Fr" : "Friday",
  "Sa" : "Saturday"
}</pre></div></div><p> </p><div class="example">
<div class="exampleHeader"><a id="d2e38350"/>Example: Constructing a map with conditional entries</div><p>The following expression constructs a map with either five or seven entries,
                  depending on a supplied condition:</p><div class="exampleInner"><pre>
{
  "Mo" : "Monday",
  "Tu" : "Tuesday",
  "We" : "Wednesday",
  "Th" : "Thursday",
  "Fr" : "Friday",
  if ($include-weekends) {
    { "Sa" : "Saturday",
      "Su" : "Sunday"
    }
  }
}</pre></div><p>This could also be written:</p><div class="exampleInner"><pre>
{
  "Mo" : "Monday",
  "Tu" : "Tuesday",
  "We" : "Wednesday",
  "Th" : "Thursday",
  "Fr" : "Friday",
  { "Sa" : "Saturday",
    "Su" : "Sunday"
  } [$include-weekends]
}</pre></div></div><p> </p><div class="example">
<div class="exampleHeader"><a id="d2e38358"/>Example: Constructing a map to index nodes</div><p>The following expression (which uses two nested map constructors)
                  constructs a map that indexes employees by the value 
                  of their <code>@id</code> attribute:</p><div class="exampleInner"><pre>{ //employee ! {@id : .} }</pre></div></div><p> </p><div class="example">
<div class="exampleHeader"><a id="d2e38367"/>Example: Constructing nested maps</div><p>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:</p><div class="exampleInner"><a id="map-book"/><pre>

{
  "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
  }
}</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>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 <code>true</code>, <code>false</code>,
               and <code>null</code>, and backslash-escaped characters such as <code>"\n"</code>
               in string literals. In an XQuery 4.0 map constructor, of course, any literal 
               value can be replaced with an expression.</p></div></div><div class="note"><p class="prefix"><b>Note:</b></p><p>
    In some circumstances, it is necessary to include whitespace before or after the colon
    of a <a href="#prod-xquery40-MapConstructorEntry">MapConstructorEntry</a> to ensure that it is parsed as intended.
    </p><p>
    For instance, consider the expression <code>{a:b}</code>.
    Although it matches the EBNF for <a href="#doc-xquery40-MapConstructor">MapConstructor</a>,
    the “longest terminal” rule (see <a href="#lexical-structure"><b>A.3 Lexical structure</b></a>)
     requires that <code>a:b</code> be parsed as a QName,
    which is likely to result in an error indicating that the prefix <code>a</code>
    has not been declared.
    Changing the expression to <code>{a :b}</code> or <code>{a: b}</code>
    will prevent this, resulting in the intended parse.
    </p><p>Similarly, consider these three expressions:</p><div class="exampleInner"><pre>
{a:b:c}
{a:*:c}
{*:b:c}</pre></div><p>
    In each case, the expression matches the EBNF in two different ways,
    but the “longest possible match” rule forces the parse in which
    the first subexpression is <code>a:b</code>, <code>a:*</code>, or <code>*:b</code> (respectively)
    and the second subexpression is <code>c</code>.
    To achieve the alternative parse
    (in which the first expression is merely <code>a</code> or <code>*</code>),
    insert whitespace before and/or after the first colon.
    </p><p>See <a href="#lexical-structure"><b>A.3 Lexical structure</b></a>.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>There are also several functions that can be used to construct maps with a variable
               number of entries:</p><ul><li><p>
                              <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-map-build"><code>map:build</code></a> takes any sequence as input, and for each
                  item in the sequence, it computes a key and a value, by calling user-supplied functions.</p></li><li><p>
                              <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-map-merge"><code>map:merge</code></a> takes a sequence of maps (often but not necessarily
                  <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-single-entry-map">single-entry map</a><sup><small>DM</small></sup>) and merges them into a single map.</p></li></ul><p>Either of these functions can be used to build an index of employee
                  elements using the value of the <code>@id</code> attribute as a key:</p><ul><li><p>
                              <code>map:build(//employee, fn { @id })</code>
                           </p></li><li><p>
                              <code>map:merge(//employee ! { @id, . })</code>
                           </p></li></ul><p>Both functions also provide control over:</p><ul><li><p>The way in which duplicate keys are handled, and </p></li><li><p>The ordering of entries in the resulting map.</p></li></ul></div></div><div class="div4">
<h5><a id="id-map-lookup"/>4.14.1.2 <a href="#id-map-lookup" style="text-decoration: none">Maps as Functions</a></h5><p>Maps are <a title="function item" class="termref" href="#dt-function-item">function items</a>, and 
                  a <a title="dynamic function call" class="termref" href="#dt-dynamic-function-call">dynamic function call</a> can be used to look up
    the value associated with a key in a map.

    
    If <code>$map</code> is a map and <code>$key</code> is a key,
    then <code>$map($key)</code> is equivalent to <code>map:get($map, $key)</code>.
    The semantics of such a function call are formally defined in
    <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#func-map-get">14.4.9 map:get</a>.
    
    </p><p>Examples:</p><ul><li><p>
                           <code>$weekdays("Su")</code> returns the <a title="associated value" class="termref" href="#dt-associated-value">associated value</a> of the key <code>Su</code>.</p></li><li><p>
                           <code>$books("Green Eggs and Ham")</code> returns  <a title="associated value" class="termref" href="#dt-associated-value">associated value</a>  of the key <code>Green Eggs and Ham</code>.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>XQuery 4.0 also provides an alternate syntax for map and
      array lookup that is more terse, supports wildcards, and allows lookup to
      iterate over a sequence of maps or arrays. See <a href="#id-lookup"><b>4.14.3 Lookup Expressions</b></a> for details.</p></div><p>Map lookups can be chained.</p><p>Examples: (These examples assume that <code>$b</code> is bound to the books map from the previous section)</p><ul><li><p>The expression <code>$b("book")("title")</code> returns the string <code>Data on the Web</code>.</p></li><li><p>The expression <code>$b("book")("author")</code> returns the array of authors.</p></li><li><p>The expression <code>$b("book")("author")(1)("last")</code> returns the string <code>Abiteboul</code>.</p><p>(This example combines <a href="#id-array-lookup"><b>4.14.2.2 Arrays as Functions</b></a> with map lookups.)</p></li></ul></div></div><div class="div3">
<h4><a id="id-arrays"/>4.14.2 <a href="#id-arrays" style="text-decoration: none">Arrays</a></h4><div class="div4">
<h5><a id="id-array-constructors"/>4.14.2.1 <a href="#id-array-constructors" style="text-decoration: none">Array Constructors</a></h5><p>
                     [<a id="dt-array" title="array">Definition</a>: An <b>array</b> is
      a <a title="function item" class="termref" href="#dt-function-item">function item</a> that associates a set of positions, represented as
      positive integer keys, with values.] The first position
      in an array is associated with the integer 1.
      [<a id="dt-member" title="member">Definition</a>: The values of an array are called
      its <b>members</b>.]

      In the type hierarchy, array has a distinct type, which is
      derived from function.
      Atomization converts arrays to sequences (see <a title="atomization" class="termref" href="#dt-atomization">Atomization</a>).  
      </p><p>An array is created using an <a href="#doc-xquery40-ArrayConstructor">ArrayConstructor</a>.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrayConstructor"/><code><a href="#prod-xquery40-ArrayConstructor">ArrayConstructor</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-ArrayConstructor-SquareArrayConstructor">SquareArrayConstructor</a>  |  <a href="#doc-xquery40-ArrayConstructor-CurlyArrayConstructor">CurlyArrayConstructor</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrayConstructor-SquareArrayConstructor"/><code><a href="#prod-xquery40-SquareArrayConstructor">SquareArrayConstructor</a></code></td><td>::=</td><td><code>"["  (<a href="#doc-xquery40-ArrayConstructor-ExprSingle">ExprSingle</a> ** ",")  "]"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrayConstructor-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                           <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                           <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                           <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                           <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                           <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                           <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrayConstructor-CurlyArrayConstructor"/><code><a href="#prod-xquery40-CurlyArrayConstructor">CurlyArrayConstructor</a></code></td><td>::=</td><td><code>"array"  <a href="#doc-xquery40-ArrayConstructor-EnclosedExpr">EnclosedExpr</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrayConstructor-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>
      If a member of an array is a
      node, its node identity is preserved.

      

        In both forms of an <a href="#doc-xquery40-ArrayConstructor">ArrayConstructor</a>, if a member
        expression evaluates to a node, the associated value is the
        node itself, not a new node with the same values.  If the
        member expression evaluates to a map or array, the associated
        value is a new map or array with the same values.

        </p><p>A <a href="#prod-xquery40-SquareArrayConstructor">SquareArrayConstructor</a> 
      consists of a comma-delimited set of argument expressions. It returns an array in which each member contains the value of the corresponding argument expression.</p><p>Examples:</p><ul><li><p>
                           <code>[ 1, 2, 5, 7 ]</code> creates an array with four members: <code>1</code>, <code>2</code>, <code>5</code>, and <code>7</code>.</p></li><li><p>
                           <code>[ (), (27, 17, 0) ]</code> creates an array with two members: <code>()</code> and the sequence <code>(27, 17, 0)</code>.</p></li><li><p>
                           <code>[ $x, local:items(), &lt;tautology&gt;It is what it is.&lt;/tautology&gt; ]</code> creates an array with three members: the value of $x, the result of evaluating the function call, and a tautology element.</p></li></ul><p>A <a href="#prod-xquery40-CurlyArrayConstructor">CurlyArrayConstructor</a>
      can use any  expression to create its members.  It
      evaluates its operand expression to obtain a sequence of items
      and creates an array with these items as members.  Unlike a
      SquareArrayConstructor, a comma in a CurlyArrayConstructor is
      the  <a title="comma operator" class="termref" href="#dt-comma-operator">comma operator</a>, not a delimiter.
      </p><p>Examples:</p><ul><li><p>
                           <code>array { $x }</code> creates an array with one member for each item in the sequence to which $x is bound.</p></li><li><p>
                           <code>array { local:items() }</code> creates an array with one member for each item  in the sequence to which <code>local:items()</code> evaluates.</p></li><li><p>
                           <code>array { 1, 2, 5, 7 }</code> creates an array with four members: <code>1</code>, <code>2</code>, <code>5</code>, and <code>7</code>.</p></li><li><p>
                           <code>array { (), (27, 17, 0) }</code> creates an array with three members: <code>27</code>, <code>17</code>, and <code>0</code>.</p></li><li><p>
                           <code>array { $x, local:items(), &lt;tautology&gt;It is what it is.&lt;/tautology&gt; }</code> creates an array with the following members: the items to which <code>$x</code> is bound, followed by the items to which <code>local:items()</code> evaluates, followed by a tautology element.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>XQuery 4.0 does not provide explicit support for sparse arrays. Use integer-valued maps to represent sparse arrays, 
                     for example: <code>{ 27 : -1, 153 : 17 }</code>.</p></div></div><div class="div4">
<h5><a id="id-array-lookup"/>4.14.2.2 <a href="#id-array-lookup" style="text-decoration: none">Arrays as Functions</a></h5><p>Arrays are <a title="function item" class="termref" href="#dt-function-item">function items</a>, 
                  and a <a title="dynamic function call" class="termref" href="#dt-dynamic-function-call">dynamic function call</a> can be used to look up
    the value associated with position in an array.

    

    
    If <code>$array</code> is an array and <code>$index</code> is an integer corresponding to a position in the array,
    then <code>$array($key)</code> is equivalent to <code>array:get($array, $key)</code>.
    The semantics of such a function call are formally defined in
    <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#func-array-get">15.2.11 array:get</a>.
    
    </p><p>Examples:</p><ul><li><p>
                           <code>[ 1, 2, 5, 7 ](4)</code> evaluates to <code>7</code>.</p></li><li><p>
                           <code>[ [ 1, 2, 3 ], [ 4, 5, 6 ] ](2)</code> evaluates to <code>[ 4, 5, 6 ]</code>.</p></li><li><p>
                           <code>[ [ 1, 2, 3 ], [ 4, 5, 6 ] ](2)(2)</code> evaluates to <code>5</code>.</p></li><li><p>
                           <code>[ 'a', 123, &lt;name&gt;Robert Johnson&lt;/name&gt; ](3)</code> evaluates to <code>&lt;name&gt;Robert Johnson&lt;/name&gt;</code>.</p></li><li><p>
                           <code>array { (), (27, 17, 0) }(1)</code> evaluates to  <code>27</code>.</p></li><li><p>
                           <code>array { (), (27, 17, 0) }(2)</code> evaluates to  <code>17</code>.</p></li><li><p>
                           <code>array { "licorice", "ginger" }(20)</code> raises a dynamic error [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFOAY0001" title="err:FOAY0001">err:FOAY0001</a>]<sup><small>FO40</small></sup>.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>XQuery 4.0 also provides an alternate syntax for map and
      array lookup that is more terse, supports wildcards, and allows
      lookup to iterate over a sequence of maps or arrays. See
      <a href="#id-lookup"><b>4.14.3 Lookup Expressions</b></a> for details.</p></div></div></div><div class="div3">
<h4><a id="id-lookup"/>4.14.3 <a href="#id-lookup" style="text-decoration: none">Lookup Expressions</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-methods">⬇</a> <a href="#id-map-constructors">⬆</a></p><ol><li><p>
                  The lookup operator <code>?</code> can now be followed by an arbitrary literal,
                  for cases where keys are items other than integers or NCNames.
                  It can also be followed by a variable reference or a context value reference.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1996">1996</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2134">2134</a> 29 July 2025]</i></p></li></ol></div><p>The operator "?", known as the lookup operator,
               returns values found in the operand map or array.</p><div class="div4">
<h5><a id="id-postfix-lookup"/>4.14.3.1 <a href="#id-postfix-lookup" style="text-decoration: none">Postfix Lookup Expressions</a></h5><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LookupExpr"/><code><a href="#prod-xquery40-LookupExpr">LookupExpr</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-LookupExpr-PostfixExpr">PostfixExpr</a>
                           <a href="#doc-xquery40-LookupExpr-Lookup">Lookup</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LookupExpr-PostfixExpr"/><code><a href="#prod-xquery40-PostfixExpr">PostfixExpr</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-PrimaryExpr">PrimaryExpr</a>  |  <a href="#doc-xquery40-FilterExpr">FilterExpr</a>  |  <a href="#doc-xquery40-DynamicFunctionCall">DynamicFunctionCall</a>  |  <a href="#doc-xquery40-LookupExpr">LookupExpr</a>  |  <a href="#doc-xquery40-MethodCall">MethodCall</a>  |  <a href="#doc-xquery40-FilterExprAM">FilterExprAM</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LookupExpr-Lookup"/><code><a href="#prod-xquery40-Lookup">Lookup</a></code></td><td>::=</td><td><code>"?"  <a href="#doc-xquery40-LookupExpr-KeySpecifier">KeySpecifier</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LookupExpr-KeySpecifier"/><code><a href="#prod-xquery40-KeySpecifier">KeySpecifier</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-NCName">NCName</a>  |  <a href="#doc-xquery40-LookupExpr-Literal">Literal</a>  |  <a href="#doc-xquery40-LookupExpr-ContextValueRef">ContextValueRef</a>  |  <a href="#doc-xquery40-LookupExpr-VarRef">VarRef</a>  |  <a href="#doc-xquery40-LookupExpr-ParenthesizedExpr">ParenthesizedExpr</a>  |  <a href="#doc-xquery40-LookupExpr-LookupWildcard">LookupWildcard</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LookupExpr-Literal"/><code><a href="#prod-xquery40-Literal">Literal</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-NumericLiteral">NumericLiteral</a>  |  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>  |  <a href="#doc-xquery40-QNameLiteral">QNameLiteral</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LookupExpr-ContextValueRef"/><code><a href="#prod-xquery40-ContextValueRef">ContextValueRef</a></code></td><td>::=</td><td><code>"."</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LookupExpr-VarRef"/><code><a href="#prod-xquery40-VarRef">VarRef</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-EQName">EQName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LookupExpr-ParenthesizedExpr"/><code><a href="#prod-xquery40-ParenthesizedExpr">ParenthesizedExpr</a></code></td><td>::=</td><td><code>"("  <a href="#doc-xquery40-Expr">Expr</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-LookupExpr-LookupWildcard"/><code><a href="#prod-xquery40-LookupWildcard">LookupWildcard</a></code></td><td>::=</td><td><code>"*"</code></td></tr></tbody></table><p>A postfix <code>Lookup</code> has two parts: the left hand operand
                  selects maps or arrays to be searched, and
                  the <code>KeySelector</code> defines the search criteria.</p><p>First a simple example: given an array <code>$array</code> of maps:</p><div class="exampleInner"><pre>[ { "John": 3, "Jill": 5}, {"Peter": 8, "Mary": 6} ]</pre></div><ul><li><p>
                           <code>$array?1?John</code> returns <code>3</code>
                        </p></li><li><p>
                           <code>$array?2?Mary</code> returns <code>6</code>
                        </p></li><li><p>
                           <code>$array?*?*</code> returns <code>(3, 5, 8, 6)</code>
                        </p></li><li><p>
                           <code>$array?2?*</code> returns <code>(8, 6)</code>
                        </p></li><li><p>
                           <code>$array?*?Peter</code> returns <code>8</code>
                        </p></li><li><p>
                           <code>'Peter' -&gt; $array?*?.</code> returns <code>8</code>
                        </p></li></ul><p>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 <b>·content·</b> property of the JNode). The lookup
               operation is applied independently to each of these maps or arrays,
               and the final expression result is the <a title="sequence concatenation" class="termref" href="#dt-sequence-concatenation">sequence concatenation</a>
               of the individual results.</p><p>The semantics of a postfix lookup expression <code>
                        <var>E</var>?<var>KS</var>
                     </code> are 
                  defined by the following rules:</p><ol class="enumar"><li><p>
                           <var>E</var> is evaluated to produce a value <code>$V</code>.</p></li><li><p>If <code>$V</code> is not a <a title="singleton" class="termref" href="#dt-singleton">singleton</a> 
                     (that is if <code>count($V) ne 1</code>),
                  then the result (by recursive application of these rules) is the value of
                  <code>for $v in $V return $v?<var>KS</var>
                           </code>.</p></li><li><p>If <code>$V</code> is a <a title="JNode" class="termref" href="#dt-JNode">JNode</a> then it is
                  coerced to the required type <code>(map(*)|array(*))</code>: see
                  <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>.</p></li><li><p>If <code>$V</code> (after coercion) is a <a title="singleton" class="termref" href="#dt-singleton">singleton</a> array item (that is, 
                     if <code>$V instance of array(*)</code>) then:</p><ol class="enumla"><li><p>If the <a href="#prod-xquery40-KeySpecifier">KeySpecifier</a>
                                 <var>KS</var> is either a
                         <code>Literal</code>, a <code>ContextValueRef</code>, a <code>VarRef</code>,
                        or a <code>ParenthesizedExpr</code>,
                        then it is evaluated as an expression to produce a value <code>$K</code>
                        and the result is:</p><div class="exampleInner"><pre>data($K) ! array:get($V, .)</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The focus for evaluating the key specifier expression is the 
                              same as the focus for the <code>Lookup</code> expression itself.</p><p>The order of items in the result reflects the order of subscripts in
                              <code>$K</code>: <code>[10, 20, 30]?(3, 1)</code> returns <code>(30, 10)</code>.</p><p>This rule implies that a type error ([<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>])
                              is raised if an item in the atomized value of <var>$K</var> cannot be coerced 
                              to the type <code>xs:integer</code>.</p><p>This rule also implies that a dynamic error ([<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFOAY0001" title="err:FOAY0001">err:FOAY0001</a>]<sup><small>FO40</small></sup>)
                              is raised if an integer in the atomized value of <var>$K</var> is outside
                              the range 1 to <code>array:size($V)</code>.</p></div></li><li><p>If the <a href="#prod-xquery40-KeySpecifier">KeySpecifier</a>
                                 <var>KS</var> is an <code>NCName</code>
                           then it is evaluated in the same way as if the <code>NCName</code> were written
                           in quotation marks as a <code>StringLiteral</code>: in consequence,
                           the expression raises a type error [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>If the <a href="#prod-xquery40-KeySpecifier">KeySpecifier</a>
                                 <code>KS</code> is a wildcard
                           (<code>*</code>), 
                           the result is the same as <code>$V?(1 to array:size($V))</code>:</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Note that array items are returned in order.</p></div></li></ol></li><li><p>If <var>$V</var> is a <a title="singleton" class="termref" href="#dt-singleton">singleton</a> 
                     map item (that is, if <code>$V instance of map(*)</code>)
                     then:</p><ol class="enumla"><li><p>If the <a href="#prod-xquery40-KeySpecifier">KeySpecifier</a>
                                 <var>KS</var> is either a
                         <code>Literal</code>, a <code>ContextValueRef</code>, a <code>VarRef</code>,
                        or a <code>ParenthesizedExpr</code>,
                        then it is evaluated as an expression to produce a value <code>$K</code>
                        and the result is:</p><div class="exampleInner"><pre>data($K) ! map:get($V, .)</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The focus for evaluating the key specifier expression is the 
                                 same as the focus for the <code>Lookup</code> expression itself.</p><p>The order of items in the result reflects the order of keys in
                              <code>$K</code>: <code>{'a':10, 'b':20, 'c':30}?('c', 'a')</code> 
                                 returns <code>(30, 10)</code>.</p><p>There is no error when <code>$K</code> includes a key that is not
                              present in the map.</p></div></li><li><p>If the <a href="#prod-xquery40-KeySpecifier">KeySpecifier</a>
                                 <var>KS</var> is an <code>NCName</code>, then the result
                              is the same as if it were written in quotes as
                              a <code>StringLiteral</code>: for example <code>$map?name</code>
                           returns the same result as <code>map?"name"</code>.</p></li><li><p>If the <a href="#prod-xquery40-KeySpecifier">KeySpecifier</a>
                                 <var>KS</var> is a wildcard (<code>*</code>), 
                              the result is the same as <code>$V?(map:keys($V))</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The order of entries in the result sequence 
                                 reflects the <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-entry-order">entry order</a><sup><small>DM</small></sup>
                                 of the map.</p></div></li></ol></li><li><p>Otherwise (that is, if <code>$V</code> is neither a map nor an array)
                     a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li></ol><p>Examples:</p><ul><li><p>
                           <code>[ 1, 2, 5, 7 ]?*</code> evaluates to <code>(1, 2, 5, 7)</code>.</p></li><li><p>
                           <code>[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]?*</code> evaluates to <code>([ 1, 2, 3 ], [ 4, 5, 6 ])</code>
                        </p></li><li><p>
                           <code>[ [ 1, 2, 3 ], 4, 5 ]?*[. instance of array(xs:integer)]</code> evaluates to <code>([ 1, 2, 3 ])</code>
                        </p></li><li><p>
                           <code>[ [ 1, 2, 3 ], [ 4, 5, 6 ], 7 ]?*[. instance of array(*)]?2</code> evaluates to <code>(2, 5)</code>
                        </p></li><li><p>
                           <code>[ [ 1, 2, 3 ], 4, 5 ]?*[. instance of xs:integer]</code> 
                        evaluates to <code>(4, 5)</code>.
                     </p></li></ul></div><div class="div4">
<h5><a id="id-unary-lookup"/>4.14.3.2 <a href="#id-unary-lookup" style="text-decoration: none">Unary Lookup</a></h5><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryLookup"/><code><a href="#prod-xquery40-UnaryLookup">UnaryLookup</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-UnaryLookup-Lookup">Lookup</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryLookup-Lookup"/><code><a href="#prod-xquery40-Lookup">Lookup</a></code></td><td>::=</td><td><code>"?"  <a href="#doc-xquery40-UnaryLookup-KeySpecifier">KeySpecifier</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryLookup-KeySpecifier"/><code><a href="#prod-xquery40-KeySpecifier">KeySpecifier</a></code></td><td>::=</td><td><code>
                           <a href="#prod-xquery40-NCName">NCName</a>  |  <a href="#doc-xquery40-UnaryLookup-Literal">Literal</a>  |  <a href="#doc-xquery40-UnaryLookup-ContextValueRef">ContextValueRef</a>  |  <a href="#doc-xquery40-UnaryLookup-VarRef">VarRef</a>  |  <a href="#doc-xquery40-UnaryLookup-ParenthesizedExpr">ParenthesizedExpr</a>  |  <a href="#doc-xquery40-UnaryLookup-LookupWildcard">LookupWildcard</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryLookup-Literal"/><code><a href="#prod-xquery40-Literal">Literal</a></code></td><td>::=</td><td><code>
                           <a href="#doc-xquery40-NumericLiteral">NumericLiteral</a>  |  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>  |  <a href="#doc-xquery40-QNameLiteral">QNameLiteral</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryLookup-ContextValueRef"/><code><a href="#prod-xquery40-ContextValueRef">ContextValueRef</a></code></td><td>::=</td><td><code>"."</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryLookup-VarRef"/><code><a href="#prod-xquery40-VarRef">VarRef</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-EQName">EQName</a>
                        </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryLookup-ParenthesizedExpr"/><code><a href="#prod-xquery40-ParenthesizedExpr">ParenthesizedExpr</a></code></td><td>::=</td><td><code>"("  <a href="#doc-xquery40-Expr">Expr</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-UnaryLookup-LookupWildcard"/><code><a href="#prod-xquery40-LookupWildcard">LookupWildcard</a></code></td><td>::=</td><td><code>"*"</code></td></tr></tbody></table><p>Unary lookup is most commonly used in predicates (for example, <code>$map[?name = 'Mike']</code>)
                  or with the simple map operator (for example, <code>avg($maps ! (?price - ?discount))</code>).</p><p>The unary lookup expression <code>?KS</code> is defined to be equivalent to the postfix lookup
                  expression <code>.?KS</code>, which has the context value (<code>.</code>) as the implicit first operand.
                  See <a href="#id-postfix-lookup"><b>4.14.3.1 Postfix Lookup Expressions</b></a> for the postfix lookup operator.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Although the grammar allows the key specifier to be a context value expression,
               this is of no practical use with a unary lookup. The expression <code>[1, 2, 3] -&gt; ?.</code> expands to
               <code>[1, 2, 3]?(1, 2, 3)</code> which returns <code>(1, 2, 3)</code>; but a more
               likely result is a type error or array bounds error.</p></div><p>Examples:</p><ul><li><p>
                           <code>?name</code> is equivalent to <code>.("name")</code>, an appropriate lookup for a map.</p></li><li><p>
                           <code>?2</code> is equivalent to <code>.(2)</code>, an appropriate lookup for an array or an integer-valued map.</p></li><li><p>
                           <code>?"first name"</code> is equivalent to <code>.("first name")</code>
                        </p></li><li><p>
                           <code>?#code</code> is equivalent to <code>.(#code)</code>
                        </p></li><li><p>
                           <code>?($a)</code> and <code>?$a</code> are 
                        equivalent to <code>for $k in $a return .($k)</code>, 
                        allowing keys for an array or map to be passed using a variable.</p></li><li><p>
                           <code>?(3e0)</code> and <code>?3e0</code> return the same result as
                        <code>?3</code>, because <code>xs:double(3e0)</code> and
                        <code>xs:integer(3)</code> compare equal under the rules of the
                        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-atomic-equal"><code>atomic-equal</code></a> function.</p></li><li><p>
                           <code>?(2 to 4)</code> is equivalent to <code>for $k in (2, 3, 4) return .($k)</code>, 
                        a convenient way to return a range of values from an array.</p></li><li class="xquery"><p>If the context value is an array, <code>let $x:= &lt;node i="3"/&gt; return ?($x/@i)</code> 
                        does not raise a type error, because the attribute is untyped.</p><p>But <code>let $x:= &lt;node i="3"/&gt; return ?($x/@i+1)</code> does raise a type error
                        because the <code>+</code> operator with an untyped operand returns a double.</p></li><li><p>
                           <code>([ 1, 2, 3 ], [ 1, 2, 5 ], [ 1, 2 ])[?3 = 5]</code> raises an error,
                        because <code>?3</code> applied to one of the
                        items in the sequence fails.</p></li></ul></div><div class="div4">
<h5><a id="id-lookup-vs-path-expressions"/>4.14.3.3 <a href="#id-lookup-vs-path-expressions" style="text-decoration: none">Comparing Lookup and Path Expressions</a></h5><p>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.</p><p>For more complex queries into trees of maps and arrays, XQuery 4.0
                  introduces a generalization of path expressions (see <a href="#id-path-expressions"><b>4.6 Path Expressions</b></a>)
                  which can now handle <a title="JTree" class="termref" href="#dt-JTree">JTrees</a> 
                     as well as <a title="XTree" class="termref" href="#dt-XTree">XTrees</a>.</p><p>For simple expressions, the capabilities of the two constructs overlap.
                  For example, if <code>$m</code> is a map, then the expressions
                  <code>$m?code = 3</code> and <code>$m/code = 3</code> have the same effect.
                  Path expressions, however, have more power, and with it, more complexity.
                  The expression <code>$m/code = 3</code> (unless simplified by an optimizer)
                  effectively expands the expression to <code>(jtree($m)/child::get("code") =&gt; jnode-content()) = 3</code>:
                  that is, the supplied map is wrapped in a JNode, the child axis returns a sequence of JNodes,
                  and the <b>·content·</b> properties of these JNodes are compared with the
                  supplied value <code>3</code>.</p><p>Whereas simple lookups of specific entries in maps and arrays work well,
                  experience has shown that the <code>?*</code> wildcard lookup can be problematic.
                  This is because of the flattening effect: for example, given the array
                  <code>let $A := [(1,2), (3,4), (), 5]</code> the result of the expression
                  <code>$A?*</code> is the sequence <code>(1, 2, 3, 4, 5)</code> which loses information
                  that might be needed for further processing. By contrast, the path expression
                  <code>$A/*</code> (or <code>$A/child::*</code>) returns a sequence of four
                  JNodes, whose <b>·content·</b> properties are respectively <code>(1,2)</code>, 
                     <code>(3,4)</code>, <code>()</code>, and <code>5</code>.</p><p>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 <a title="sequence concatenation" class="termref" href="#dt-sequence-concatenation">sequence concatenation</a> 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 <b>·content·</b> properties of the JNodes are 
                  needed, these will usually be extracted automatically by virtue of the
                  <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>: for example if the value is used in an
                  arithmetic expression or a value comparison, atomization of the JNode
                  automatically extracts its <b>·content·</b>. In other cases the value can
                  be extracted explicitly by a call of the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-jnode-content"><code>jnode-content</code></a> function.</p><p>Lookup expressions on arrays result in a dynamic error if the subscript is out
                  of bounds, whereas the equivalent path expression succeeds, returning an empty
                  sequence. For example <code>array{1 to 5}?10</code> raises 
                     [<a href="https://qt4cg.org/specifications/xpath-functions-40/#ERRFOAY0001" title="err:FOAY0001">err:FOAY0001</a>]<sup><small>FO40</small></sup>, whereas <code>array{1 to 5}/get(10)</code>
                     returns a empty sequence.
                 </p></div><div class="div4">
<h5><a id="id-implausible-lookup-expressions"/>4.14.3.4 <a href="#id-implausible-lookup-expressions" style="text-decoration: none">Implausible Lookup Expressions</a></h5><p>Under certain conditions a lookup expression that will never select anything
                  is classified as <a title="implausible" class="termref" href="#dt-implausible">implausible</a>. During the static analysis
                  phase, a processor <span class="verb">may</span> (subject to the rules in
                  <a href="#id-implausible-expressions"><b>2.4.6 Implausible Expressions</b></a>) report a static error
                  when such lookup expressions are encountered: [<a href="#ERRXPTY0145" title="err:XPTY0145">err:XPTY0145</a>].</p><p>More specifically, a shallow unary or postfix lookup is classified as 
                  <a title="implausible" class="termref" href="#dt-implausible">implausible</a> if any of the following conditions applies:</p><ol class="enumar"><li><p>The inferred type of the left-hand operand (or the context value, in the case
                  of a unary expression) is a record type (see <a href="#id-record-test"><b>3.2.8.3 Record Types</b></a>),
                  and the <code>KeySpecifier</code> is an <code>IntegerLiteral</code>.
                  </p></li><li><p>The inferred type of the left-hand operand (or the context value, in the case
                     of a unary expression) is a record type (see <a href="#id-record-test"><b>3.2.8.3 Record Types</b></a>),
                     and the <code>KeySpecifier</code> is an <code>NCName</code> or <code>StringLiteral</code>
                     that cannot validly appear as a field name in the record.
                  </p></li><li><p>The inferred type of the left-hand operand (or the context value, in the case
                     of a unary expression) is a map type,
                     and the inferred type of the <code>KeySpecifier</code>, after coercion, is a type that
                     is disjoint with the key type of the map.
                  </p></li><li><p>The inferred type of the left-hand operand (or the context value, in the case
                     of a unary expression) is an array type,
                     and the <code>KeySpecifier</code> is the <code>IntegerLiteral</code>
                           <code>0</code> (zero).
                  </p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>Other errors, such as using an <code>NCName</code>
                        <code>KeySpecifier</code>
               for an array lookup, are handled under the general provisions for type errors.</p></div><p>Examples of implausible lookup expressions include the following:</p><ul><li><p>
                           <code>parse-uri($uri)?3</code>: the declared result type of <code>parse-uri</code> is a record
                  test, so the selector <code>3</code> will never select anything.</p></li><li><p>
                           <code>in-scope-namespaces($node)(current-date())</code>: the result type of
                  <code>in-scope-namespaces</code> is a map with <code>xs:string</code> keys, so the selector
                  <code>current-date()</code> will never select anything.</p></li><li><p>
                           <code>array:subarray($a, 2, 5)?0</code>: the integer zero cannot select any member
                  of an array, because numbering starts at 1.</p></li></ul></div></div><div class="div3">
<h4><a id="id-methods"/>4.14.4 <a href="#id-methods" style="text-decoration: none">Method Calls</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-filter-maps-and-arrays">⬇</a> <a href="#id-lookup">⬆</a></p><ol><li><p>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.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2143">2143</a>  4 August 2025]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MethodCall"/><code><a href="#prod-xquery40-MethodCall">MethodCall</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-MethodCall-PostfixExpr">PostfixExpr</a>  "=?&gt;"  <a href="#prod-xquery40-NCName">NCName</a>
                        <a href="#doc-xquery40-MethodCall-PositionalArgumentList">PositionalArgumentList</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MethodCall-PostfixExpr"/><code><a href="#prod-xquery40-PostfixExpr">PostfixExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-PrimaryExpr">PrimaryExpr</a>  |  <a href="#doc-xquery40-FilterExpr">FilterExpr</a>  |  <a href="#doc-xquery40-DynamicFunctionCall">DynamicFunctionCall</a>  |  <a href="#doc-xquery40-LookupExpr">LookupExpr</a>  |  <a href="#doc-xquery40-MethodCall">MethodCall</a>  |  <a href="#doc-xquery40-FilterExprAM">FilterExprAM</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MethodCall-PositionalArgumentList"/><code><a href="#prod-xquery40-PositionalArgumentList">PositionalArgumentList</a></code></td><td>::=</td><td><code>"("  <a href="#doc-xquery40-MethodCall-PositionalArguments">PositionalArguments</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MethodCall-PositionalArguments"/><code><a href="#prod-xquery40-PositionalArguments">PositionalArguments</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-MethodCall-Argument">Argument</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MethodCall-Argument"/><code><a href="#prod-xquery40-Argument">Argument</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-MethodCall-ExprSingle">ExprSingle</a>  |  <a href="#doc-xquery40-MethodCall-ArgumentPlaceholder">ArgumentPlaceholder</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MethodCall-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-MethodCall-ArgumentPlaceholder"/><code><a href="#prod-xquery40-ArgumentPlaceholder">ArgumentPlaceholder</a></code></td><td>::=</td><td><code>"?"</code></td></tr></tbody></table><p>A method call combines accessing a map <var>M</var> to look up an entry
               whose value is a function item <var>F</var>, and calling the function item <var>F</var>
               supplying the map <var>M</var> as the implicit value of the first argument.</p><p>For example, given the variable:</p><div class="exampleInner"><pre>
let $rectangle := {
  'height':    3,
  'width':     4,
  'area':      fn ($rect) { 
                  $rect?height × $rect?width 
               },
  'perimeter': fn ($rect) { 
                 2 × ($rect?height + $rect?width) 
               },
  'resize':    fn ($rect, $factor) { 
                  $rect 
                     =&gt; map:put('height', $rect?height × $factor)
                     =&gt; map:put('width', $rect?width × $factor)
               }
}</pre></div><p>The method call <code>$rectangle =?&gt; area()</code> returns <code>12</code>, while
               the method call <code>$rectangle =?&gt; perimeter()</code> returns <code>14</code>,
                  and <code>$rectangle =?&gt; resize(2)</code> returns a map representing
               a rectangle with <code>height = 6</code> and <code>width = 8</code>.</p><p>An arity-one function can also be written as a <a title="focus function" class="termref" href="#dt-focus-function">focus function</a>:</p><div class="exampleInner"><pre>
let $rectangle := {
  'height': 3,
  'width': 4,
  'area': fn { ?height × ?width }
}</pre></div><p>The expression <code>
                     <var>M</var> =?&gt; <var>N</var>(<var>X</var>, <var>Y</var>, ...)</code>
                  is by definition equivalent to:</p><div class="exampleInner"><pre>for $map as map(*) in <var>M</var>
let $f as function(*) := $map?<var>N</var>                 
return $f($map, <var>X</var>, <var>Y</var>, ...)</pre></div><p>(where <code>$map</code> and <code>$f</code>
                  are otherwise unused variable names).</p><p>The argument list in a method call must not include an argument placeholder; that is,
               the call must not be a partial function application ([<a href="#ERRXPST0003" title="err:XPST0003">err:XPST0003</a>]).</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Implicit in this definition are the following rules:</p><ul><li><p>The value of <var>M</var> must be
                     a sequence of zero or more maps;</p></li><li><p>Each of those maps must have an entry with the
                        key <var>N</var> (as an instance of <code>xs:string</code>,
                        <code>xs:untypedAtomic</code>, or <code>xs:anyURI</code>);</p></li><li><p>The value of that entry must be
                     a single function item;</p></li><li><p>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.</p></li></ul><p>The error codes raised if these conditions are not satisfied are
                  exactly the same as if the expanded code were used directly.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Although methods mimic some of the capability of object-oriented
                  languages, the functionality is more limited:</p><ul><li><p>There is no encapsulation: the entries in a map are all publicly
                     exposed.</p></li><li><p>There is no class hierarchy, and no inheritance or overriding.</p></li><li><p>Methods within a map can be removed or replaced in the same way as
                     any other entries in the map.</p></li></ul></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Methods can be useful when there is a need to write inline recursive
                  functions. For example:</p><div class="exampleInner"><pre>
let $lib := {
  'product': fn($map as map(*), $in as xs:double*) {
    if (empty( $in ))
    then 1
    else head($in) × $map =?&gt; product(tail($in))
  }
}
return $lib =?&gt; product((1.2, 1.3, 1.4))</pre></div><p>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.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Methods are often useful in conjunction with named record types:
                  see <a href="#id-functions-as-fields"><b>5.20.3 Using Methods in Records</b></a>.</p></div><div class="example">
<div class="exampleHeader"><a id="d2e40111"/>Example: Chaining method calls</div><p>In the example above, <code>$rectangle =?&gt; area()</code>, <code>$rectangle</code>
               is typically a single map, and <code>area</code> 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
                  <code>$rectangle =?&gt; area()</code> first performs a map lookup (<code>$rectangle?area</code>)
                  to select the function item, and then calls the function item, supplying the containing
                  map as the first (and in this case only) argument.</p><p>Such calls can be chained. For example, <code>$rectangle =?&gt; resize(2)</code> returns a rectangle that
               is twice the size of the original, so <code>$rectangle =?&gt; resize(2) =?&gt; area()</code> returns the area of the
               enlarged rectangle.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Note how the <code>resize</code> function is implemented using <code>map:put</code>, which
               ensures that the map entries holding function items (<code>area</code>, <code>perimeter</code>, and
               <code>resize</code>, are automatically present and unchanged in the modified map.</p></div><p>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 <code>$rectangle =?&gt; contents()</code> delivers a sequence of zero or more 
               rectangles. Then the expression <code>$rectangle =?&gt; area() - sum($rectangle =?&gt; contents() =?&gt; area())</code> 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 <code>$rectangle =?&gt; contents() =?&gt; area()</code>
               applies the <code>area</code> function in each of the maps in the sequence returned
               by the expression <code>$rectangle =?&gt; contents()</code>.</p><p>A record type representing a rectangle containing nested rectangles might be defined
               in XQuery 4.0  like this:</p><div class="exampleInner"><pre>
declare record my:rectangle (
   height as xs:double,
   width as xs:double,
   children as my:rectangle* 
     := (),
   area as fn(my:rectangle) as xs:double 
     := fn{?height × ?width},
   resize as fn(my:rectangle, xs:double) as my:rectangle 
     := fn($rect, $factor) {
           $rect =&gt; map:put('height', $rect?height × $factor)
             =&gt; map:put('width', $rect?width × $factor)
             =&gt; map:put('children', $rect?children =?&gt; resize($factor))
        },
   contents as fn(my:rectangle) as my:rectangle*
     := fn{?children}
);</pre></div></div></div><div class="div3">
<h4><a id="id-filter-maps-and-arrays"/>4.14.5 <a href="#id-filter-maps-and-arrays" style="text-decoration: none">Filter Expressions for Maps and Arrays</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-unordered-expressions">⬇</a> <a href="#id-methods">⬆</a></p><ol><li><p>
                  Filter expressions for maps and arrays are introduced.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1159">1159</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1163">1163</a> 20 April 2024]</i></p></li><li><p>
                  Predicates in filter expressions for maps and arrays can now be numeric.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1207">1207</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1217">1217</a> 15 May 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FilterExprAM"/><code><a href="#prod-xquery40-FilterExprAM">FilterExprAM</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FilterExprAM-PostfixExpr">PostfixExpr</a>  "?["  <a href="#doc-xquery40-FilterExprAM-Expr">Expr</a>  "]"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FilterExprAM-PostfixExpr"/><code><a href="#prod-xquery40-PostfixExpr">PostfixExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-PrimaryExpr">PrimaryExpr</a>  |  <a href="#doc-xquery40-FilterExpr">FilterExpr</a>  |  <a href="#doc-xquery40-DynamicFunctionCall">DynamicFunctionCall</a>  |  <a href="#doc-xquery40-LookupExpr">LookupExpr</a>  |  <a href="#doc-xquery40-MethodCall">MethodCall</a>  |  <a href="#doc-xquery40-FilterExprAM">FilterExprAM</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FilterExprAM-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody></table><p>Maps and arrays can be filtered using the construct <code>
                     <var>INPUT</var>?[<var>FILTER</var>]</code>.
            For example, <code>$array?[count(.)=1]</code> filters an array to retain only those members that 
            are single items.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The character-pair <code>?[</code> forms a single token; no intervening whitespace
            or comment is allowed.</p></div><p>The required type of the left-hand operand <code>
                     <var>INPUT</var>
                  </code> is
               <code>(map(*)|array(*))?</code>: that is, it must be either an empty sequence, a single
            map, or a single array [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>]. 
               However, the coercion rules also allow a JNode
                  whose <b>·content·</b> is a map or array to be supplied.
               If the value is an empty sequence, 
               the result of the expression is an empty sequence.</p><p>If the value of <code>
                     <var>INPUT</var>
                  </code> is an array, then the 
               <code>
                     <var>FILTER</var>
                  </code> 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 <a title="predicate truth value" class="termref" href="#dt-predicate-truth-value">predicate truth value</a> of the 
               <code>
                     <var>FILTER</var>
                  </code> expression is true. The order
            of retained members is preserved.</p><p>For example, the following expression:</p><div class="exampleInner"><pre>let $array := [ (), 1, (2, 3), (4, 5, 6) ]
return $array?[count(.) ge 2]</pre></div><p>returns:</p><div class="exampleInner"><pre>[ (2, 3), (4, 5, 6) ]</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>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 <code>$array</code> shown above, the result
            of <code>$array?[3]</code> is the <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-single-member-array">single-member array</a><sup><small>DM</small></sup>
                     <code>[ (2, 3) ]</code>.
            Contrast this with <code>$array?3</code> which delivers the sequence <code>2, 3</code>.</p></div><p>If the value of <code>
                     <var>INPUT</var>
                  </code> is a map, then the 
               <code>
                     <var>FILTER</var>
                  </code> expression is evaluated
               for each entry in the map, with the context value set to an item of type
               <code>record(key as xs:anyAtomicType, value as item()*)</code>, in which the <code>key</code>
               and <code>value</code> fields represent the key and value of the map entry. 
               The context position is the position of the entry in the map 
               (in <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-entry-order">entry order</a><sup><small>DM</small></sup>),
               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 <a title="predicate truth value" class="termref" href="#dt-predicate-truth-value">predicate truth value</a> of the <code>
                     <var>FILTER</var>
                  </code> expression is true.
               The relative order of entries in the result retains the relative order of entries in the input.
            </p><p>For example, the following expression:</p><div class="exampleInner"><pre>let map := { 1: "alpha", 2: "beta", 3: "gamma" }
return $map?[?key ge 2]</pre></div><p>returns:</p><div class="exampleInner"><pre>{ 2: "beta", 3: "gamma" }</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>A filter expression such as <code>$map?[last()-1, last()]</code>
                  might be used to return the last two entries of a map in
                  <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-entry-order">entry order</a><sup><small>DM</small></sup>.</p></div></div></div><div class="div2 xquery">
<h3><a id="id-unordered-expressions"/>4.15 <a href="#id-unordered-expressions" style="text-decoration: none">Ordered and Unordered Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-conditionals">⬇</a> <a href="#id-filter-maps-and-arrays">⬆</a></p><ol><li><p>
               The <code>ordered { E }</code> and <code>unordered { E }</code> expressions are retained for
               backwards compatibility reasons, but in XQuery 4.0 they are deprecated and have no useful effect.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1339">1339</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1342">1342</a> 3 September 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrderedExpr"/><code><a href="#prod-xquery40-OrderedExpr">OrderedExpr</a></code></td><td>::=</td><td><code>"ordered"  <a href="#doc-xquery40-OrderedExpr-EnclosedExpr">EnclosedExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrderedExpr-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>This syntax is retained from earlier versions of XQuery; in XQuery 4.0 it is deprecated and has
         no effect.</p><p>The constructs <code>ordered { E }</code> and <code>unordered { E }</code> both return the result
         of evaluating the expression <code>E</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In addition to <code>ordered</code> and <code>unordered</code> expressions, 
            XQuery provides a function named <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-unordered"><code>fn:unordered</code></a> that operates on any sequence 
            of items and returns the same sequence in an <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> order. A call to the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-unordered"><code>fn:unordered</code></a> 
            function may be thought of as giving permission for the argument expression to be 
            materialized in whatever order the system finds most efficient. The <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-unordered"><code>fn:unordered</code></a> 
            function relaxes ordering only for the sequence that is its immediate operand, whereas the <code>unordered</code> 
            expression in earlier XQuery versions sets the ordering mode for its operand expression and 
            all nested expressions.</p></div></div><div class="div2">
<h3><a id="id-conditionals"/>4.16 <a href="#id-conditionals" style="text-decoration: none">Conditional Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-otherwise">⬇</a> <a href="#id-unordered-expressions">⬆</a></p><ol><li><p>
               Alternative syntax for conditional expressions is available: <code>if (condition) { X }</code>.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/234">234</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/284">284</a> 23 January 2023]</i></p></li></ol></div><p>XQuery 4.0 allows conditional expressions to be written in several different ways.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-IfExpr"/><code><a href="#prod-xquery40-IfExpr">IfExpr</a></code></td><td>::=</td><td><code>"if"  "("  <a href="#doc-xquery40-IfExpr-Expr">Expr</a>  ")"  (<a href="#doc-xquery40-IfExpr-UnbracedActions">UnbracedActions</a>  |  <a href="#doc-xquery40-IfExpr-BracedAction">BracedAction</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-IfExpr-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-IfExpr-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-IfExpr-UnbracedActions"/><code><a href="#prod-xquery40-UnbracedActions">UnbracedActions</a></code></td><td>::=</td><td><code>"then"  <a href="#doc-xquery40-IfExpr-ExprSingle">ExprSingle</a>  "else"  <a href="#doc-xquery40-IfExpr-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-IfExpr-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                     <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                     <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                     <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                     <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-IfExpr-BracedAction"/><code><a href="#prod-xquery40-BracedAction">BracedAction</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-IfExpr-EnclosedExpr">EnclosedExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-IfExpr-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-IfExpr-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p>The braced expression <code>if (<var>C</var>) then {<var>T</var>}</code> is equivalent to the
         unbraced expression <code>if (<var>C</var>) then <var>T</var> else ()</code>.</p><p>The value <var>V</var> of a conditional expression in the form <code>if (<var>C</var>) then <var>T</var>
         else <var>E</var>
               </code> is obtained as follows:</p><ol class="enumar"><li><p>Let <var>B</var> be the <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> of the test expression
                       <var>C</var>, as defined in <a href="#id-ebv"><b>2.5.4 Effective Boolean Value</b></a>.</p></li><li><p>If <var>B</var> is true, <var>V</var> is the
                    result of evaluating <var>T</var>.</p></li><li><p>Otherwise, <var>V</var> is the
                    result of evaluating <var>E</var>.</p></li></ol><p>Conditional expressions have a special rule for propagating <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic errors</a>: <span>expressions whose value is not needed for
                  computing the result are
            <a title="guarded" class="termref" href="#dt-guarded">guarded</a>, as described in <a href="#id-guarded-expressions"><b>2.4.5 Guarded Expressions</b></a>, to prevent
                  spurious dynamic errors.</span>
            </p><p>Here are some examples of conditional expressions:</p><ul><li><p>In this example, the test expression is a comparison expression:</p><div class="exampleInner"><pre>if ($widget1/unit-cost &lt; $widget2/unit-cost)
then $widget1
else $widget2</pre></div></li><li><p>In this example, the test expression tests for the existence of an attribute
named <code>discounted</code>, independently of its value:</p><div class="exampleInner"><pre>if ($part/@discounted)
then $part/wholesale
else $part/retail</pre></div></li><li><p>The following example returns the attribute node <code>@discount</code> provided the value of <code>@price</code>
                  is greater than 100; otherwise it returns the empty sequence:</p><div class="exampleInner"><pre>if (@price gt 100) { @discount }</pre></div></li><li><p>The following example tests a number of conditions:</p><div class="exampleInner"><pre>if (@code = 1) then
  "food"
else if (@code = 2) then
  "fashion"
else if (@code = 3) then
  "household"
else 
  "general"</pre></div></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>The “dangling else ambiguity” found in many other languages cannot arise:</p><ul><li><p>In the unbraced format, both the <code>then</code> and <code>else</code> clauses
                  are mandatory.</p></li><li><p>In the braced format, the expression terminates unambiguously with the closing
                  brace.</p></li></ul></div></div><div class="div2">
<h3><a id="id-otherwise"/>4.17 <a href="#id-otherwise" style="text-decoration: none">Otherwise Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-switch">⬇</a> <a href="#id-conditionals">⬆</a></p><ol><li><p>
               An <code>otherwise</code> operator is introduced: <code>A otherwise B</code> returns the
               value of <code>A</code>, unless it is an empty sequence, in which case it returns the value of <code>B</code>.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1024">1024</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1031">1031</a> 27 February 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OtherwiseExpr"/><code><a href="#prod-xquery40-OtherwiseExpr">OtherwiseExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-OtherwiseExpr-StringConcatExpr">StringConcatExpr</a>  ("otherwise"  <a href="#doc-xquery40-OtherwiseExpr-StringConcatExpr">StringConcatExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OtherwiseExpr-StringConcatExpr"/><code><a href="#prod-xquery40-StringConcatExpr">StringConcatExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-RangeExpr">RangeExpr</a>  ("||"  <a href="#doc-xquery40-RangeExpr">RangeExpr</a>)*</code></td></tr></tbody></table><p>The <code>otherwise</code> expression returns the value of its first operand, unless this is an empty
         sequence, in which case it returns the value of its second operand.</p><p>For example, <code>@price - (@discount otherwise 0)</code> returns the value of <code>@price - @discount</code>,
         if the attribute <code>@discount</code> exists, or the value of <code>@price</code> if the <code>@discount</code>
            attribute is absent.</p><p>To prevent spurious errors, the right hand operand is <a title="guarded" class="termref" href="#dt-guarded">guarded</a>: it cannot throw any
            dynamic error unless the left-hand operand returns an empty sequence.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The operator is associative (even under error conditions): <code>A otherwise (B otherwise C)</code> returns
         the same result as <code>(A otherwise B) otherwise C</code>.</p><p>The <code>otherwise</code> operator binds more tightly than comparison operators such as
            <code>=</code>, but less tightly than string concatenation (<code>||</code>) or arithemetic
            operators. The expression <code>$a = @x otherwise @y + 1</code> parses as 
               <code>$a = (@x otherwise (@y + 1))</code>.</p></div></div><div class="div2 xquery">
<h3><a id="id-switch"/>4.18 <a href="#id-switch" style="text-decoration: none">Switch Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-quantified-expressions">⬇</a> <a href="#id-otherwise">⬆</a></p><ol><li><p>
               Switch expressions now allow a <code>case</code> clause to match multiple atomic items.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/328">328</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/364">364</a> 7 March 2023]</i></p></li><li><p>
               Switch and typeswitch expressions can now be written with curly brackets,
                  to improve readability.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/365">365</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/587">587</a> 7 November 2023]</i></p></li><li><p>
               The comparand expression in a switch expression can be omitted, allowing
               the switch cases to be provided as arbitrary boolean expressions.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/671">671</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/678">678</a> 12 September 2023]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SwitchExpr"/><code><a href="#prod-xquery40-SwitchExpr">SwitchExpr</a></code></td><td>::=</td><td><code>"switch"  <a href="#doc-xquery40-SwitchExpr-SwitchComparand">SwitchComparand</a>  (<a href="#doc-xquery40-SwitchExpr-SwitchCases">SwitchCases</a>  |  <a href="#doc-xquery40-SwitchExpr-BracedSwitchCases">BracedSwitchCases</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SwitchExpr-SwitchComparand"/><code><a href="#prod-xquery40-SwitchComparand">SwitchComparand</a></code></td><td>::=</td><td><code>"("  <a href="#doc-xquery40-SwitchExpr-Expr">Expr</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SwitchExpr-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-SwitchExpr-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SwitchExpr-SwitchCases"/><code><a href="#prod-xquery40-SwitchCases">SwitchCases</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-SwitchExpr-SwitchCaseClause">SwitchCaseClause</a>+  "default"  "return"  <a href="#doc-xquery40-SwitchExpr-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SwitchExpr-SwitchCaseClause"/><code><a href="#prod-xquery40-SwitchCaseClause">SwitchCaseClause</a></code></td><td>::=</td><td><code>("case"  <a href="#doc-xquery40-SwitchExpr-SwitchCaseOperand">SwitchCaseOperand</a>)+  "return"  <a href="#doc-xquery40-SwitchExpr-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SwitchExpr-SwitchCaseOperand"/><code><a href="#prod-xquery40-SwitchCaseOperand">SwitchCaseOperand</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-SwitchExpr-Expr">Expr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SwitchExpr-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                     <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                     <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                     <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                     <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SwitchExpr-BracedSwitchCases"/><code><a href="#prod-xquery40-BracedSwitchCases">BracedSwitchCases</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-SwitchExpr-SwitchCases">SwitchCases</a>  "}"</code></td></tr></tbody></table><p>
The <b>switch expression</b> chooses one of several expressions to evaluate based on the
input value.
</p><p>
In a <code>switch</code> expression, the <code>switch</code> keyword is followed by an expression enclosed
in parentheses, called the <b>switch comparand</b>. This is the expression whose value is
being compared. <span>This expression is optional, and defaults to <code>true()</code>.</span>
            The remainder of the <code>switch</code> expression consists of one or more
<code>case</code> clauses, with one or more <code>case operand
expressions</code> each, and a <code>default</code> clause. </p><p>The first step in evaluating a switch expression is to apply
atomization to the value of the switch comparand. <span>Call the result the <b>switch value</b>.
            If the <b>switch value</b>
               </span> is a sequence of length greater than one, a type error is
raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>]. In the absence of a switch comparand, the switch value is the
         <code>xs:boolean</code> value <code>true</code>.</p><p>The <span>
                  <b>switch value</b> is compared to</span> 
            each <a href="#prod-xquery40-SwitchCaseOperand">SwitchCaseOperand</a> in turn until a
            match is found or the list is exhausted. The matching is performed as follows:</p><ol class="enumar"><li><p>The <a href="#prod-xquery40-SwitchCaseOperand">SwitchCaseOperand</a> is evaluated.</p></li><li><p>The resulting value is atomized: call this the <b>case value</b>.</p></li><li><p>If the <b>case value</b> is an empty sequence, then a match occurs if and only if
               the <b>switch value</b> is an empty sequence.</p></li><li><p>Otherwise, the <a title="singleton" class="termref" href="#dt-singleton">singleton</a>
                     <b>switch value</b> is compared individually
               with each item in the <b>case value</b> in turn, and a match
               occurs if and only if these two atomic items compare equal under the rules of
               the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-deep-equal"><code>fn:deep-equal</code></a> function with default options, using the default 
               collation in the static context.</p></li></ol><p>
               [<a id="id-effective-case-switch-expression" title="effective case">Definition</a>:  The <b>effective case</b> 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 value of
the switch expression is the value of the return expression in the
effective case.</p><p>Switch expressions have rules regarding the propagation of dynamic
errors: <span>see <a href="#id-guarded-expressions"><b>2.4.5 Guarded Expressions</b></a>. These rules mean that</span>
the return clauses of a switch expression must not raise any dynamic
errors except in the effective case.  Dynamic errors raised in the
operand expressions of the switch or the case clauses are propagated;
however, an implementation must not raise dynamic errors in the
operand expressions of case clauses that occur after the effective
case. An implementation is permitted to raise dynamic errors in the
operand expressions of case clauses that occur before the effective
case, but not required to do so.</p><p>The following example shows how a switch expression might be used:</p><div class="exampleInner"><pre>
switch ($animal) {
  case "Cow" return "Moo"
  case "Cat" return "Meow"
  case "Duck", "Goose" return "Quack"
  default return "What's that odd noise?"
}</pre></div><p>The curly brackets in a switch expression are optional. The above example can equally
         be written:</p><div class="exampleInner"><pre>
switch ($animal) 
  case "Cow" return "Moo"
  case "Cat" return "Meow"
  case "Duck", "Goose" return "Quack"
  default return "What's that odd noise?"</pre></div><p>The following example illustrates a switch expression where the comparand is defaulted to
            <code>true</code>:</p><div class="exampleInner"><pre>
switch () {
  case ($a le $b) return "lesser"
  case ($a ge $b) return "greater"
  case ($a eq $b) return "equal"
  default return "not comparable"
}</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The comparisons are performed using the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-deep-equal"><code>fn:deep-equal</code></a>
         function, after atomization. This means that a case expression such as <code>@married</code>
            tests <code>fn:data(@married)</code> rather than <code>fn:boolean(@married)</code>. 
         If the effective boolean value of the expression is wanted,
         this can be achieved with an explicit call of <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean"><code>fn:boolean</code></a>.</p></div></div><div class="div2">
<h3><a id="id-quantified-expressions"/>4.19 <a href="#id-quantified-expressions" style="text-decoration: none">Quantified Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-try-catch">⬇</a> <a href="#id-switch">⬆</a></p><ol><li><p>
               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.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1316">1316</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1384">1384</a> 13 August 2024]</i></p></li></ol></div><p>Quantified expressions support existential and universal quantification. The
value of a quantified expression is always <code>true</code> or <code>false</code>.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-QuantifiedExpr"/><code><a href="#prod-xquery40-QuantifiedExpr">QuantifiedExpr</a></code></td><td>::=</td><td><code>("some"  |  "every")  (<a href="#doc-xquery40-QuantifiedExpr-QuantifierBinding">QuantifierBinding</a> ++ ",")  "satisfies"  <a href="#doc-xquery40-QuantifiedExpr-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-QuantifiedExpr-QuantifierBinding"/><code><a href="#prod-xquery40-QuantifierBinding">QuantifierBinding</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-QuantifiedExpr-VarNameAndType">VarNameAndType</a>  "in"  <a href="#doc-xquery40-QuantifiedExpr-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-QuantifiedExpr-VarNameAndType"/><code><a href="#prod-xquery40-VarNameAndType">VarNameAndType</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-QuantifiedExpr-EQName">EQName</a>
                     <a href="#doc-xquery40-QuantifiedExpr-TypeDeclaration">TypeDeclaration</a>?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-QuantifiedExpr-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-QuantifiedExpr-TypeDeclaration"/><code><a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a></code></td><td>::=</td><td><code>"as"  <a href="#doc-xquery40-QuantifiedExpr-SequenceType">SequenceType</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-QuantifiedExpr-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                     <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-QuantifiedExpr-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                     <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                     <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                     <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                     <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                  </code></td></tr></tbody></table><p>A <b>quantified expression</b> begins with
a <b>quantifier</b>, which is the keyword <code>some</code> or <code>every</code>, 
followed by one or more in-clauses that are used to bind variables,
followed by the keyword <code>satisfies</code> and a test expression. Each in-clause associates a variable with an
expression that returns a sequence of items, called the binding sequence for that variable. 
The value of the quantified expression is defined by the following rules:</p><ol class="enumar"><li><p>If the <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a> contains
               more than one <a href="#prod-xquery40-QuantifierBinding">QuantifierBinding</a>, then it is equivalent
            to the expression obtained by replacing each comma with <code>satisfies some</code> or <code>satisfies every</code>
            respectively. For example, the expression <code>some $x in X, $y in Y satisfies $x = $y</code>
               is equivalent to <code>some $x in X satisfies some $y in Y satisfies $x = $y</code>,
               while the expression <code>every $x in X, $y in Y satisfies $x lt $y</code> is equivalent to
               <code>every $x in X satisfies every $y in Y satisfies $x lt $y</code>
                  </p></li><li><p>If the quantifier is <code>some</code>, the <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a> returns <code>true</code> 
                  if at least one evaluation of the test expression has the <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a>
                     <code>true</code>; otherwise it returns <code>false</code>. In consequence, if the binding sequence is empty, 
                  the result of the <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a> is <code>false</code>.</p></li><li><p>If the quantifier is <code>every</code>, the <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a> returns <code>true</code> 
                  if every evaluation of the test expression has the <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a>
                     <code>true</code>; otherwise it returns <code>false</code>. In consequence, if the binding sequence is empty, 
                  the result of the <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a> is <code>true</code>.</p></li></ol><p>The scope of a variable bound in a quantified expression comprises all
subexpressions of the quantified expression that appear after the variable binding. The scope does not include the expression to which the variable is bound.
</p><p>Each variable binding may be accompanied by a <b>type declaration</b>, 
            which consists of the keyword <code>as</code> followed by the static type of 
            the variable, declared using the syntax in  <a href="#id-sequencetype-syntax"><b>3.1 Sequence Types</b></a>. 
            The type declaration defines a required type for the
            value. At run-time, the supplied value for the variable is converted to the required type
            by applying the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>. If conversion is not possible,                     
            a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p><p>The order in which test expressions are evaluated 
            for the various items in the binding sequence is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>. If the quantifier
               is <code>some</code>, an implementation may
               return <code>true</code> as soon as it finds one item for which the test expression has
               an <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> of <code>true</code>, and it may raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> as soon as it finds one item for
            which the test expression raises an error. Similarly, if the quantifier is <code>every</code>, an 
            implementation may return <code>false</code> as soon as it finds one item for which the test expression has
            an <a title="effective boolean value" class="termref" href="#dt-ebv">effective boolean value</a> of <code>false</code>, and it may raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> as soon as it finds one item for
            which the test expression raises an error. As a result of these rules, the
            value of a quantified expression is not deterministic in the presence of
            errors, as illustrated in the examples below.</p><p>Here are some examples of quantified expressions:</p><ul><li><p>This expression is <code>true</code> if every <code>part</code> element has a <code>discounted</code> attribute (regardless of the values of these attributes):</p><div class="exampleInner"><pre>every $part in /parts/part satisfies $part/@discounted</pre></div></li><li><p>This expression is <code>true</code> if at least
one <code>employee</code> element satisfies the given comparison expression:</p><div class="exampleInner"><pre>some $emp in /emps/employee satisfies $emp/bonus &gt; 0.25 * $emp/salary</pre></div></li><li><p>This expression is <code>true</code> if every
                  <code>employee</code> element has at least one <code>salary</code> child with the attribute <code>current="true"</code>:</p><div class="exampleInner"><pre>every $emp in /emps/employee satisfies (
  some $sal in $emp/salary satisfies $sal/@current = 'true'
)</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>Like many quantified expressions, this can be simplified. This example can be written
                  <code>every $emp in /emps/employee satisfies $emp/salary[@current = 'true']</code>, or even
                  more concisely as <code>empty(/emps/employee[not(salary/@current = 'true')]</code>.</p><p>Another alternative in XQuery 4.0 is to use the higher-order functions <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-some"><code>fn:some</code></a> and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-every"><code>fn:every</code></a>.
               This example can be written <code>every(/emps/employee, fn { salary/@current = 'true' })</code>
                     </p></div></li><li><p>In the following examples, each quantified expression evaluates its test
expression over nine pairs of items, formed from the Cartesian
product of the sequences <code>(1, 2, 3)</code> and <code>(2, 3, 4)</code>. 
                  The expression beginning with <code>some</code> evaluates to <code>true</code>, 
                  and the expression beginning with <code>every</code> evaluates to <code>false</code>.</p><div class="exampleInner"><pre>some $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4</pre></div><div class="exampleInner"><pre>every $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4</pre></div></li><li><p>This quantified expression may either return  <code>true</code> or raise a <a title="type error" class="termref" href="#dt-type-error">type error</a>, since its test expression returns <code>true</code> for one item
and raises a <a title="type error" class="termref" href="#dt-type-error">type error</a> for another:</p><div class="exampleInner"><pre>some $x in (1, 2, "cat") satisfies $x * 2 = 4</pre></div></li><li><p>This quantified expression may either return <code>false</code> or raise a <a title="type error" class="termref" href="#dt-type-error">type error</a>, since its test expression returns <code>false</code> for one item and raises a <a title="type error" class="termref" href="#dt-type-error">type error</a> for another:</p><div class="exampleInner"><pre>every $x in (1, 2, "cat") satisfies $x * 2 = 4</pre></div></li><li><p>This quantified expression returns <code>true</code>, because the binding sequence
                  is empty, despite the fact that the condition can never be satisfied:</p><div class="exampleInner"><pre>every $x in () satisfies ($x lt 0 and $x gt 0)</pre></div></li><li><p>This quantified expression is <a title="implausible" class="termref" href="#dt-implausible">implausible</a> because
                  it will always fail with a type error except in the case where <code>$input</code>
                  is an empty sequence. If <code>$input</code> contains one or more <code>xs:date</code>
                  values, a processor <span class="verb">must</span> raise a type error on the grounds that an <code>xs:date</code>
                  cannot be compared to an <code>xs:integer</code>. If <code>$input</code> is empty, the
                  processor <span class="verb">may</span> (or may not) report this error:</p><div class="exampleInner"><pre>every $x as xs:date in $input satisfies ($x lt 0)</pre></div></li><li><p>This quantified expression  contains a <a href="#prod-xquery40-TypeDeclaration">type declaration</a> that is not satisfied by every item in the  test expression. 
                  The expression may either return <code>true</code> or raise a <a title="type error" class="termref" href="#dt-type-error">type error</a>.</p><div class="exampleInner"><pre>some $x as xs:integer in (1, 2, "cat") satisfies $x * 2 = 4</pre></div></li></ul></div><div class="div2 xquery">
<h3><a id="id-try-catch"/>4.20 <a href="#id-try-catch" style="text-decoration: none">Try/Catch Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-typeswitch">⬇</a> <a href="#id-quantified-expressions">⬆</a></p><ol><li><p>
               A new variable <code>$err:map</code> is available, capturing all error information in one place.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/32">32</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/493">493</a> 16 May 2023]</i></p></li><li><p>
                  <code>$err:stack-trace</code> provides information about the current state of execution.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/689">689</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1470">1470</a> 1 October 2024]</i></p></li><li><p>
               A <code>finally</code> clause can be supplied, which will always be evaluated after the
               expressions of the try/catch clauses.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/501">501</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1914">1914</a> 4 April 2025]</i></p></li></ol></div><p>The try/catch expression provides error handling for dynamic errors
and type errors raised during dynamic evaluation, including errors
raised by the XQuery implementation and errors explicitly raised in a
query using the <code>fn:error()</code> function.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TryCatchExpr"/><code><a href="#prod-xquery40-TryCatchExpr">TryCatchExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-TryCatchExpr-TryClause">TryClause</a>  ((<a href="#doc-xquery40-TryCatchExpr-CatchClause">CatchClause</a>+  <a href="#doc-xquery40-TryCatchExpr-FinallyClause">FinallyClause</a>?)  |  <a href="#doc-xquery40-TryCatchExpr-FinallyClause">FinallyClause</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TryCatchExpr-TryClause"/><code><a href="#prod-xquery40-TryClause">TryClause</a></code></td><td>::=</td><td><code>"try"  <a href="#doc-xquery40-TryCatchExpr-EnclosedExpr">EnclosedExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TryCatchExpr-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TryCatchExpr-CatchClause"/><code><a href="#prod-xquery40-CatchClause">CatchClause</a></code></td><td>::=</td><td><code>"catch"  <a href="#doc-xquery40-TryCatchExpr-NameTestUnion">NameTestUnion</a>
                     <a href="#doc-xquery40-TryCatchExpr-EnclosedExpr">EnclosedExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TryCatchExpr-NameTestUnion"/><code><a href="#prod-xquery40-NameTestUnion">NameTestUnion</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-TryCatchExpr-NameTest">NameTest</a> ++ "|")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TryCatchExpr-NameTest"/><code><a href="#prod-xquery40-NameTest">NameTest</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-TryCatchExpr-EQName">EQName</a>  |  <a href="#doc-xquery40-TryCatchExpr-Wildcard">Wildcard</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TryCatchExpr-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TryCatchExpr-Wildcard"/><code><a href="#prod-xquery40-Wildcard">Wildcard</a></code></td><td>::=</td><td><code>"*"<br/>|  (<a href="#prod-xquery40-NCName">NCName</a>  ":*")<br/>|  ("*:"  <a href="#prod-xquery40-NCName">NCName</a>)<br/>|  (<a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>  "*")</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TryCatchExpr-FinallyClause"/><code><a href="#prod-xquery40-FinallyClause">FinallyClause</a></code></td><td>::=</td><td><code>"finally"  <a href="#doc-xquery40-TryCatchExpr-EnclosedExpr">EnclosedExpr</a>
                  </code></td></tr></tbody></table><p>A try/catch expression catches <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic errors</a> and
                <a title="type error" class="termref" href="#dt-type-error">type errors</a>
                raised by the evaluation of the target expression of
                the <code>try</code>  clause. If the <a title="content expression" class="termref" href="#dt-content-expression">content expression</a> of the try clause does not raise a
                dynamic error or a type error, the result of the
                try/catch expression is the result of the content
                expression.</p><p>If the target expression raises a dynamic error or
                a type error, the result of the try/catch expression
                is obtained by evaluating the first <code>catch</code>
                clause that “matches” the error value, as described
                below.  

		If no catch clause “matches” the
		error value, then the try/catch expression raises the
		error that was raised by the target
		expression.

		A <code>catch</code> clause with one or more
                NameTests matches any error whose error code matches
                one of these NameTests. For instance, if the error
                code is <code>err:FOER0000</code>, then it matches a
                <code>catch</code> clause whose ErrorList is
                <code>err:FOER0000 | err:FOER0001</code>. Wildcards
                may be used in NameTests; thus, the error code
                <code>err:FOER0000</code> also matches a
                <code>catch</code> clause whose ErrorList is
                <code>err:*</code> or <code>*:FOER0000</code> or
                <code>*</code>.</p><p>Within the scope of the <code>catch</code> clause, a
            number of variables are implicitly declared, giving
            information about the error that occurred.  These
            variables are initialized as described in the following
            table:</p><table class="medium"><thead><tr><th style="text-align:left">Variable</th><th style="text-align:left">Type</th><th style="text-align:left">Value</th></tr></thead><tbody><tr><td style="vertical-align:top">
                        <code>$err:code</code>
                     </td><td style="vertical-align:top">
                        <code>xs:QName</code>
                     </td><td style="vertical-align:top">The error code</td></tr><tr><td style="vertical-align:top">
                        <code>$err:description</code>
                     </td><td style="vertical-align:top">
                        <code>xs:string?</code>
                     </td><td style="vertical-align:top">A description of the error condition; an empty sequence
                     if no description is available (for example, if the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-error"><code>error</code></a>
                     function was called with one argument).</td></tr><tr><td style="vertical-align:top">
                        <code>$err:value</code>
                     </td><td style="vertical-align:top">
                        <code>item()*</code>
                     </td><td style="vertical-align:top">Value associated with the error. For an error raised by
                        calling the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-error"><code>error</code></a> function, this is the value of the
                        third argument (if supplied).</td></tr><tr><td style="vertical-align:top">
                        <code>$err:module</code>
                     </td><td style="vertical-align:top">
                        <code>xs:string?</code>
                     </td><td style="vertical-align:top">The URI (or system ID) of the module containing the
                        expression where the error occurred, or an empty sequence if the information
                        is not available.</td></tr><tr><td style="vertical-align:top">
                        <code>$err:line-number</code>
                     </td><td style="vertical-align:top">
                        <code>xs:integer?</code>
                     </td><td style="vertical-align:top">The line number within the module
                        where the error occurred, or an empty sequence if the information
                        is not available. The value <span class="verb">may</span> be approximate.</td></tr><tr><td style="vertical-align:top">
                        <code>$err:column-number</code>
                     </td><td style="vertical-align:top">
                        <code>xs:integer?</code>
                     </td><td style="vertical-align:top">The column number within the module
                        where the error occurred, or an empty sequence if the information
                        is not available. The value <span class="verb">may</span> be approximate.</td></tr><tr><td style="vertical-align:top">
                        <code>$err:stack-trace</code>
                     </td><td style="vertical-align:top">
                        <code>xs:string?</code>
                     </td><td style="vertical-align:top">
                        <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">Implementation-dependent</a> information about the current state of
                     execution, or an empty sequence if no stack trace is available.
                     The variable must be bound so that a query can reference it without
                     raising an error.</td></tr><tr><td style="vertical-align:top">
                        <code>$err:additional</code>
                     </td><td style="vertical-align:top">
                        <code>item()*</code>
                     </td><td style="vertical-align:top">
                        <a title="implementation defined" class="termref" href="#dt-implementation-defined">Implementation-defined</a>.
                     Allows implementations to provide any additional information that might be useful.
                     The variable must be bound so that a query can reference it without
                     raising an error.</td></tr><tr><td style="vertical-align:top">
                        <code>$err:map</code>
                     </td><td style="vertical-align:top">
                        <code>map(*)</code>
                     </td><td style="vertical-align:top">A map with entries for all values that are bound to the variables above.
                        The local names of the variables are assigned as keys.
                        No map entries are created for those values that are empty sequences.
                        The variable can be used to pass on all error information to another
                        function.</td></tr></tbody></table><p>Try/catch expressions have a special rule for
                propagating dynamic errors. The try/catch expression
                ignores any dynamic errors encountered in catch
                clauses other than the first catch clause that matches
                an error raised by the try clause, and these catch
                clause expressions need not be evaluated.</p><p>Static errors are not caught by the try/catch
                expression.</p><p>If a function call occurs within a <code>try</code> clause,
                errors raised by evaluating the corresponding function are caught by the try/catch
                expression. If a variable reference is used in a <code>try</code>
                clause, errors raised by binding a value to the variable are not
                caught unless the binding expression occurs within the <code>try</code>
                clause.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The presence of a try/catch expression does not
                  prevent an implementation from using a lazy
                  evaluation strategy, nor does it prevent an
                  optimizer performing expression rewrites. However,
                  if the evaluation of an expression inside a
                  try/catch is rewritten or deferred in this way, it
                  must take its try/catch context with it. Similarly,
                  expressions that were written outside the try/catch
                  expression may be evaluated inside the try/catch,
                  but only if they retain their original try/catch
                  behavior. The presence of a try/catch does not
                  change the rules that allow the processor to
                  evaluate expressions in such a way that may avoid
                  the detection of some errors. </p></div><p>If a concluding <code>finally</code> clause exists, its expression will be evaluated
            after the expressions of the <code>try</code> clause and a possibly evaluated
            <code>catch</code> clause. If it raises an error, this error is returned instead of
            a result or an error that resulted from a <code>try</code> or <code>catch</code>
            expression. If it raises no error, it must yield an empty sequence;
            otherwise, a <a title="type error" class="termref" href="#dt-type-error">type error</a>
            is raised [<a href="#ERRXQTY0153" title="err:XQTY0153">err:XQTY0153</a>].</p><div class="note"><p class="prefix"><b>Note:</b></p><p>A <code>finally</code> clause can be used to ensure that an expression will always be
               evaluated, no matter if the <code>try</code> expression is successful or if it fails.
               For example, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-message"><code>fn:message</code></a> can be called in the <code>finally</code>
               clause to ensure that an expression has been evaluated even if an error is raised.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>If <code>try</code> and <code>finally</code> clauses are specified,
            <code>catch</code> clauses can be omitted.</p></div><p>Here are some examples of try/catch expressions.</p><ul><li><p>A try/catch expression without name tests catches any error:</p><div class="exampleInner"><pre>try {
  $x cast as xs:integer
} catch * {
  0
}</pre></div></li><li><p>With the following catch clause, only <code>err:FORG0001</code> is caught:</p><div class="exampleInner"><pre>try {
  $x cast as xs:integer
} catch err:FORG0001 {
  0
}</pre></div></li><li><p>This try/catch expression specifies that errors <code>err:FORG0001</code> and <code>err:XPTY0004</code> are caught:</p><div class="exampleInner"><pre>try {
  $x cast as xs:integer
} catch err:FORG0001 | err:XPTY0004 {
  0
}</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>In some implementations, <code>err:XPTY0004</code> is detected during static
	evaluation; it can only be caught if it is raised during dynamic evaluation.</p></div></li><li><p>This try/catch expression shows how to return information about the error using implicitly defined error variables:</p><div class="exampleInner"><pre>try {
  error(QName('http://www.w3.org/2005/xqt-errors', 'err:FOER0000'))
} catch * {
  $err:code, $err:value, " module: ",
  $err:module, "(", $err:line-number, ",", $err:column-number, ")"
}</pre></div></li><li><p>Errors raised by using the result of a try/catch expression are not caught, since they are outside the scope of the <code>try</code> expression.</p><div class="exampleInner"><pre>
declare function local:thrice($x as xs:integer) as xs:integer {
  3 * $x
};

local:thrice(try { "oops" } catch * { 3 } )</pre></div><p>In this example, the try block succeeds, returning the string <code>"oops"</code>, which is not a valid argument to the function.</p></li><li><p>All available information about the error is serialized:</p><div class="exampleInner"><pre>try {
  1 + &lt;empty/&gt;
} catch * {
  serialize($err:map, { 'method': 'adaptive' })
}</pre></div></li><li><p>
                     <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-message"><code>fn:message</code></a> will always be called, no matter if the division succeeds:</p><div class="exampleInner"><pre>
for $i in 0 to 2
return try {
  1 div $i
} catch err:FOAR0001 {
  'division error'
} finally {
  message('1 was divided by ' || $i)
}</pre></div></li></ul></div><div class="div2">
<h3><a id="id-expressions-on-datatypes"/>4.21 <a href="#id-expressions-on-datatypes" style="text-decoration: none">Expressions on SequenceTypes</a></h3><p>
The <code>instance
of</code>, <code>cast</code>, <code>castable</code>,
and <code>treat</code> expressions are used to test whether a value
conforms to a given type or to convert it to an instance of a given
type.
</p><div class="div3">
<h4><a id="id-instance-of"/>4.21.1 <a href="#id-instance-of" style="text-decoration: none">Instance Of</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InstanceofExpr"/><code><a href="#prod-xquery40-InstanceofExpr">InstanceofExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-InstanceofExpr-TreatExpr">TreatExpr</a>  ("instance"  "of"  <a href="#doc-xquery40-InstanceofExpr-SequenceType">SequenceType</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InstanceofExpr-TreatExpr"/><code><a href="#prod-xquery40-TreatExpr">TreatExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-CastableExpr">CastableExpr</a>  ("treat"  "as"  <a href="#doc-xquery40-InstanceofExpr-SequenceType">SequenceType</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-InstanceofExpr-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                        <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody></table><p>The boolean
operator <code>instance of</code>
returns <code>true</code> if the value of its first operand matches
the <a href="#doc-xquery40-SequenceType">SequenceType</a> in its second
operand, according to the rules for <a title="SequenceType matching" class="termref" href="#dt-sequencetype-matching">SequenceType
matching</a>; otherwise it returns <code>false</code>. For example:</p><ul><li><p>
                        <code>5 instance of xs:integer</code>
                     </p><p>This example returns <code>true</code> because the given value is an instance of the given type.</p></li><li><p>
                        <code>5 instance of xs:decimal</code>
                     </p><p>This example returns <code>true</code> because the given value is an integer literal, and <code>xs:integer</code> is derived by restriction from <code>xs:decimal</code>.</p></li><li class="xquery"><p>
                        <code>&lt;a&gt;{ 5 }&lt;/a&gt; instance of xs:integer</code>
                     </p><p>This example returns <code>false</code> because the given value is an element rather than an integer.</p></li><li><p>
                        <code>(5, 6) instance of xs:integer+</code>
                     </p><p>This example returns <code>true</code> because the given sequence contains two integers, and is a valid instance of the specified type.</p></li><li><p>
                        <code>. instance of element()</code>
                     </p><p>This example returns <code>true</code> if the context value is a
                     single element node or <code>false</code> if the context value is defined 
                     but is not a single element node. If the context value is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>, a <a title="type error" class="termref" href="#dt-type-error">type error</a>
                        is raised [<a href="#ERRXPDY0002" title="err:XPDY0002">err:XPDY0002</a>].</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>An <code>instance of</code> test does not allow any kind of casting or coercion.
            The results may therefore be counterintuitive. For example, the expression
            <code>3 instance of xs:positiveInteger</code> returns <code>false</code>, because
            the expression <code>3</code> evaluates to an instance of <code>xs:integer</code>,
            not <code>xs:positiveInteger</code>. For similar reasons, <code>"red" instance of
            enum("red", "green", "blue")</code> returns false.</p><p>On such occasions, a <code>castable as</code> test may be more appropriate:
            see <a href="#id-castable"><b>4.21.4 Castable</b></a>
                  </p></div></div><div class="div3 xquery">
<h4><a id="id-typeswitch"/>4.21.2 <a href="#id-typeswitch" style="text-decoration: none">Typeswitch</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-treat">⬇</a> <a href="#id-try-catch">⬆</a></p><ol><li><p>
                  Switch and typeswitch expressions can now be written with curly brackets,
                  to improve readability.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/365">365</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/587">587</a> 7 November 2023]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeswitchExpr"/><code><a href="#prod-xquery40-TypeswitchExpr">TypeswitchExpr</a></code></td><td>::=</td><td><code>"typeswitch"  "("  <a href="#doc-xquery40-TypeswitchExpr-Expr">Expr</a>  ")"  (<a href="#doc-xquery40-TypeswitchExpr-TypeswitchCases">TypeswitchCases</a>  |  <a href="#doc-xquery40-TypeswitchExpr-BracedTypeswitchCases">BracedTypeswitchCases</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeswitchExpr-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-TypeswitchExpr-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeswitchExpr-TypeswitchCases"/><code><a href="#prod-xquery40-TypeswitchCases">TypeswitchCases</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-TypeswitchExpr-CaseClause">CaseClause</a>+  "default"  <a href="#doc-xquery40-TypeswitchExpr-VarName">VarName</a>?  "return"  <a href="#doc-xquery40-TypeswitchExpr-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeswitchExpr-CaseClause"/><code><a href="#prod-xquery40-CaseClause">CaseClause</a></code></td><td>::=</td><td><code>"case"  (<a href="#doc-xquery40-TypeswitchExpr-VarName">VarName</a>  "as")?  <a href="#doc-xquery40-TypeswitchExpr-SequenceTypeUnion">SequenceTypeUnion</a>  "return"  <a href="#doc-xquery40-TypeswitchExpr-ExprSingle">ExprSingle</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeswitchExpr-VarName"/><code><a href="#prod-xquery40-VarName">VarName</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-TypeswitchExpr-EQName">EQName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeswitchExpr-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeswitchExpr-SequenceTypeUnion"/><code><a href="#prod-xquery40-SequenceTypeUnion">SequenceTypeUnion</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-TypeswitchExpr-SequenceType">SequenceType</a>  ("|"  <a href="#doc-xquery40-TypeswitchExpr-SequenceType">SequenceType</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeswitchExpr-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                        <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeswitchExpr-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TypeswitchExpr-BracedTypeswitchCases"/><code><a href="#prod-xquery40-BracedTypeswitchCases">BracedTypeswitchCases</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-TypeswitchExpr-TypeswitchCases">TypeswitchCases</a>  "}"</code></td></tr></tbody></table><p>The <b>typeswitch</b> expression chooses one of
several expressions to evaluate based on the <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a> of an input value.</p><p>In a <code>typeswitch</code> expression, the
<code>typeswitch</code> keyword is followed by an expression enclosed
in parentheses, called the <b>operand expression</b>. This is
the expression whose type is being tested. The remainder of the
<code>typeswitch</code> expression consists of one or more
<code>case</code> clauses and a <code>default</code> clause.</p><p>Each <code>case</code> clause specifies one or more
<a href="#doc-xquery40-SequenceType">SequenceType</a>s followed by a
<code>return</code> expression. [<a id="dt-effective-case" title="effective case">Definition</a>: The <b>effective case</b> in a
<code>typeswitch</code> expression is the first <code>case</code>
clause in which the value of the operand expression matches a <a href="#doc-xquery40-SequenceType">SequenceType</a> in the <a href="#doc-xquery40-SequenceType">SequenceTypeUnion</a> of the <code>case</code>
clause, using the rules of <a title="SequenceType matching" class="termref" href="#dt-sequencetype-matching">SequenceType matching</a>.
]

The value of the <code>typeswitch</code> expression is the value of
the <code>return</code> expression in the effective case. If the value
of the operand expression does not match any <a href="#doc-xquery40-SequenceType">SequenceType</a> named in a <code>case</code>
clause, the value of the <code>typeswitch</code> expression is the
value of the <code>return</code> expression in the
<code>default</code> clause.</p><p>In a <code>case</code> or
<code>default</code> clause, if the value to be returned depends on
the value of the operand expression, the clause must specify a
variable name. Within the <code>return</code> expression of the
<code>case</code> or <code>default</code> clause, this variable name
is bound to the value of the operand expression.

Inside a <code>case</code> clause, the <a title="static type" class="termref" href="#dt-static-type">static type</a> of the variable is the
union of the <a href="#doc-xquery40-SequenceType">SequenceType</a>s named in the
<a href="#doc-xquery40-SequenceType">SequenceTypeUnion</a>.  Inside a
<code>default</code> clause, the static type of the variable is the
same as the static type of the operand expression.

If the value to be returned by a <code>case</code> or
<code>default</code> clause does not depend on the value of the
operand expression, the clause need not specify a variable.</p><p>The
scope of a variable binding in a <code>case</code> or
<code>default</code> clause comprises that clause. It is not an error
for more than one <code>case</code> or <code>default</code> clause in
the same <code>typeswitch</code> expression to bind variables with the
same name.
</p><p>Typeswitch expressions have rules regarding the propagation of dynamic
               errors: <span>see <a href="#id-guarded-expressions"><b>2.4.5 Guarded Expressions</b></a>.
               These rules mean that</span> a <code>typeswitch</code> expression ignores (does not raise) any dynamic errors encountered in <code>case</code> clauses other than the <a title="effective case" class="termref" href="#dt-effective-case">effective case</a>. Dynamic errors encountered in the <code>default</code> clause are raised only if there is no <a title="effective case" class="termref" href="#dt-effective-case">effective case</a>.
An implementation is permitted to raise dynamic errors in the
operand expressions of case clauses that occur before the  <a title="effective case" class="termref" href="#dt-effective-case">effective
case</a>, but not required to do so.</p><p>The following example shows how a <code>typeswitch</code> expression might
be used to process an expression in a way that depends on its <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a>.</p><div class="exampleInner"><pre>typeswitch ($customer/billing-address) {
  case $a as element(*, USAddress)     return $a/state
  case $a as element(*, CanadaAddress) return $a/province
  case $a as element(*, JapanAddress)  return $a/prefecture
  default                              return "unknown"
}</pre></div><p>The curly brackets in a <code>typeswitch</code> expression are optional. The
            above example can equally be written:</p><div class="exampleInner"><pre>typeswitch ($customer/billing-address)
  case $a as element(*, USAddress)     return $a/state
  case $a as element(*, CanadaAddress) return $a/province
  case $a as element(*, JapanAddress)  return $a/prefecture
  default                              return "unknown"</pre></div><p>The following example shows a union of sequence types in a single case:</p><div class="exampleInner"><pre>typeswitch ($customer/billing-address) {
  case $a as element(*, USAddress) | element(*, MexicoAddress)
    return $a/state
  case $a as element(*, CanadaAddress)
    return $a/province
  case $a as element(*, JapanAddress)
    return $a/prefecture
  default
    return "unknown"
}</pre></div></div><div class="div3">
<h4><a id="id-cast"/>4.21.3 <a href="#id-cast" style="text-decoration: none">Cast</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastExpr"/><code><a href="#prod-xquery40-CastExpr">CastExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-CastExpr-PipelineExpr">PipelineExpr</a>  ("cast"  "as"  <a href="#doc-xquery40-CastExpr-CastTarget">CastTarget</a>  "?"?)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastExpr-PipelineExpr"/><code><a href="#prod-xquery40-PipelineExpr">PipelineExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-ArrowExpr">ArrowExpr</a>  ("-&gt;"  <a href="#doc-xquery40-ArrowExpr">ArrowExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastExpr-CastTarget"/><code><a href="#prod-xquery40-CastTarget">CastTarget</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-CastExpr-TypeName">TypeName</a>  |  <a href="#doc-xquery40-CastExpr-ChoiceItemType">ChoiceItemType</a>  |  <a href="#doc-xquery40-CastExpr-EnumerationType">EnumerationType</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastExpr-TypeName"/><code><a href="#prod-xquery40-TypeName">TypeName</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-CastExpr-EQName">EQName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastExpr-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastExpr-ChoiceItemType"/><code><a href="#prod-xquery40-ChoiceItemType">ChoiceItemType</a></code></td><td>::=</td><td><code>"("  (<a href="#doc-xquery40-CastExpr-ItemType">ItemType</a> ++ "|")  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastExpr-ItemType"/><code><a href="#prod-xquery40-ItemType">ItemType</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-RegularItemType">RegularItemType</a>  |  <a href="#doc-xquery40-FunctionType">FunctionType</a>  |  <a href="#doc-xquery40-CastExpr-TypeName">TypeName</a>  |  <a href="#doc-xquery40-CastExpr-ChoiceItemType">ChoiceItemType</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastExpr-EnumerationType"/><code><a href="#prod-xquery40-EnumerationType">EnumerationType</a></code></td><td>::=</td><td><code>"enum"  "("  (<a href="#doc-xquery40-StringLiteral">StringLiteral</a> ++ ",")  ")"</code></td></tr></tbody></table><p>Sometimes
it is necessary to convert a value to a specific datatype. For this
purpose, XQuery 4.0 provides a <code>cast</code> expression that
creates a new value of a specific type based on an existing value. A
<code>cast</code> expression takes two operands: an <b>input
expression</b> and a <b>target type</b>. The type of the
atomized value of the input expression is called the <b>input type</b>. 
The target type must be a <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a>. In practice
               this means it may be any of:</p><ul><li><p>The name of an <a title="named item type" class="termref" href="#dt-named-item-type">named item type</a>
               defined in the <a title="static context" class="termref" href="#dt-static-context">static context</a>, which in turn must refer to an item
               type in one of the following categories.</p></li><li><p>The name of a type defined in the  <a title="in-scope schema type" class="termref" href="#dt-is-types">in-scope schema types</a>, 
                  which must be a simple type (of variety atomic, list or union) [<a href="#ERRXQST0052" title="err:XQST0052">err:XQST0052</a>] .
                  In addition, the target type cannot be <code>xs:NOTATION</code>, <code>xs:anySimpleType</code>,
                  or <code>xs:anyAtomicType</code>
                     </p></li><li><p>A <code>ChoiceItemType</code> representing a 
                  <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a> (such as <code>(xs:date | xs:dateTime)</code>).</p></li><li><p>An <code>EnumerationType</code> such as <code>enum("red", "green", "blue")</code>.</p></li></ul><p>Otherwise, a static error is raised [<a href="#ERRXPST0080" title="err:XPST0080">err:XPST0080</a>].</p><p>The optional occurrence indicator <code>?</code> denotes that an empty
sequence is permitted.</p><p>Casting a node to <code>xs:QName</code> can cause surprises because it uses the <a title="static context" class="termref" href="#dt-static-context">static context</a>
               of the cast expression to provide the <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace bindings</a> for this operation. 
               Instead of casting to <code>xs:QName</code>, it is generally preferable to use the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-QName"><code>fn:QName</code></a> 
               function, which allows the namespace context to be taken from the document containing the QName.</p><p>The semantics of the <code>cast</code> expression
are as follows:</p><ol class="enumar"><li><p>The input expression is evaluated.</p></li><li><p>The result of the first step is <a title="atomization" class="termref" href="#dt-atomization">atomized</a>.</p></li><li><p> If the result of atomization is a
sequence of more than one atomic item, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li><li><p>If the result
of atomization is an empty sequence:</p><ol class="enumla"><li><p>If
<code>?</code> is specified after the target type, the result of the
<code>cast</code> expression is an empty sequence.</p></li><li><p>
If <code>?</code> is not specified after the target type, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></li></ol></li><li><p>If the result of atomization is a single
atomic item, the result of the cast expression is determined by
casting to the target type as described in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#casting">23 Casting</a>. When casting, an
implementation may need to determine whether one type is derived by
restriction from another. An implementation can determine this either
by examining the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema
definitions</a> or by using an alternative, <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>
mechanism such as a data dictionary.

The result of a cast expression is one of the following: 

</p><ol class="enumla"><li><p> 
    A value of the target type (or, in the case of list types,
    a sequence of values that are instances of the item type of the
    list type).
  </p></li><li><p> 
    A type error, if casting from the source type to the
    target type is not supported (for example attempting to convert an
    integer to a date).
  </p></li><li><p> 
    A dynamic error, if the particular input value cannot be
    converted to the target type (for example, attempting to convert
    the string <code>"three"</code> to an integer).
  </p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>Casting to an enumeration type relies on the fact that an enumeration type
                  is a generalized atomic type. So the expression <code>cast $x as enum("red", "green")</code> 
                  has the following effect:</p><ul><li><p>If <code>$x</code> is an instance of <code>xs:string</code>,
                           the expression returns <code>$x</code> unchanged if it is one of the
                           permitted strings, and raises a dynamic error otherwise;</p></li><li><p>In other cases, the expression first casts <code>$x</code> to
                     <code>xs:string</code>, and then proceeds as above.</p></li></ul></div></li></ol></div><div class="div3">
<h4><a id="id-castable"/>4.21.4 <a href="#id-castable" style="text-decoration: none">Castable</a></h4><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastableExpr"/><code><a href="#prod-xquery40-CastableExpr">CastableExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-CastableExpr-CastExpr">CastExpr</a>  ("castable"  "as"  <a href="#doc-xquery40-CastableExpr-CastTarget">CastTarget</a>  "?"?)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastableExpr-CastExpr"/><code><a href="#prod-xquery40-CastExpr">CastExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-PipelineExpr">PipelineExpr</a>  ("cast"  "as"  <a href="#doc-xquery40-CastableExpr-CastTarget">CastTarget</a>  "?"?)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastableExpr-CastTarget"/><code><a href="#prod-xquery40-CastTarget">CastTarget</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-CastableExpr-TypeName">TypeName</a>  |  <a href="#doc-xquery40-CastableExpr-ChoiceItemType">ChoiceItemType</a>  |  <a href="#doc-xquery40-CastableExpr-EnumerationType">EnumerationType</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastableExpr-TypeName"/><code><a href="#prod-xquery40-TypeName">TypeName</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-CastableExpr-EQName">EQName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastableExpr-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastableExpr-ChoiceItemType"/><code><a href="#prod-xquery40-ChoiceItemType">ChoiceItemType</a></code></td><td>::=</td><td><code>"("  (<a href="#doc-xquery40-CastableExpr-ItemType">ItemType</a> ++ "|")  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastableExpr-ItemType"/><code><a href="#prod-xquery40-ItemType">ItemType</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-RegularItemType">RegularItemType</a>  |  <a href="#doc-xquery40-FunctionType">FunctionType</a>  |  <a href="#doc-xquery40-CastableExpr-TypeName">TypeName</a>  |  <a href="#doc-xquery40-CastableExpr-ChoiceItemType">ChoiceItemType</a>
                     </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CastableExpr-EnumerationType"/><code><a href="#prod-xquery40-EnumerationType">EnumerationType</a></code></td><td>::=</td><td><code>"enum"  "("  (<a href="#doc-xquery40-StringLiteral">StringLiteral</a> ++ ",")  ")"</code></td></tr></tbody></table><p>XQuery 4.0
provides an expression that tests whether a given value
is castable into a given target type. 

The <span>target type</span> is subject to the same
               rules as the target type of a <code>cast</code> expression.</p><p>The expression <code>E castable as T</code> returns <code>true</code> 
if the result of evaluating <code>E</code>  
can be successfully cast into the target type <code>T</code> by using a <code>cast</code> expression; 
otherwise it returns <code>false</code>. 
If evaluation of <code>E</code> fails with a dynamic error or if the value of <code>E</code> cannot be atomized, 
the <code>castable</code> expression as a whole fails.</p><p>The <code>castable</code> expression can be used as a <a title="" class="termref" href="#dt-predicate">predicate</a>  to
avoid errors at evaluation time. 
It can also be used to select an appropriate type for processing of a given value, as illustrated in
the following example:</p><div class="exampleInner"><pre>
if ($x castable as hatsize)
then $x cast as hatsize
else if ($x castable as IQ)
then $x cast as IQ
else $x cast as xs:string</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The expression <code>$x castable as enum("red", "green", "blue")</code>
               is for most practical purposes equivalent to <code>$x = ("red", "green", "blue")</code>;
            the main difference is that it uses the Unicode codepoint collation for comparing strings,
            not the default collation from the static context.</p></div></div><div class="div3">
<h4><a id="id-constructor-functions"/>4.21.5 <a href="#id-constructor-functions" style="text-decoration: none">Constructor Functions</a></h4><p>For every simple type in the <a title="in-scope schema type" class="termref" href="#dt-is-types">in-scope schema types</a>  (except <code>xs:NOTATION</code> and 
               <code>xs:anyAtomicType</code>, and <code>xs:anySimpleType</code>, which 
               are not instantiable), a <b>constructor function</b> is implicitly defined. 
               In each case, the name of the constructor function is the same as the name of 
               its target type (including namespace). The signature of the constructor 
               function for  a given type depends on the type that is being constructed, 
               and can be found in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#constructor-functions">22 Constructor functions</a>.</p><p>There is also a constructor function for every <a title="named item type" class="termref" href="#dt-named-item-type">named item type</a> 
               in the <a title="static context" class="termref" href="#dt-static-context">static context</a>
            that expands either to a <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a>
                  <span>or to
            a <a href="#doc-xquery40-RecordType">RecordType</a>
                  </span>.</p><p>All such constructor functions are classified as
               <a title="system function" class="termref" href="#dt-system-function">system functions</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The constructor function is present in the static
            context if and only if the corresponding type is present in the static context.</p><p>For XSLT, this means that a constructor function corresponding to an imported
            schema type is private to the stylesheet package, and a constructor function
            corresponding to an <code>xsl:item-type</code> declaration has the same visibility
               as the <code>xsl:item-type</code> declaration.</p><p>For XQuery, this means that a constructor function corresponding to an imported
                  schema type is private to the query module, and a constructor function
                  corresponding to a named item type declaration is <code>%public</code>
                  or <code>%private</code> according to the annotations on the item type declaration.</p></div><p>
                  [<a id="dt-constructor-function" title="constructor function">Definition</a>: The <b>constructor function</b> 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 <code>T($arg)</code> are defined to be equivalent to the expression <code>$arg cast as T?</code>.]
               </p><p>The following examples illustrate the use of constructor functions:</p><ul><li><p>This
example is equivalent to <code>"2000-01-01" cast as
xs:date?</code>.</p><div class="exampleInner"><pre>xs:date("2000-01-01")</pre></div></li><li><p>This
example is equivalent to

<code>($floatvalue * 0.2E-5) cast as xs:decimal?</code>.</p><div class="exampleInner"><pre>xs:decimal($floatvalue * 0.2E-5)</pre></div></li><li><p>This example returns an
<code>xs:dayTimeDuration</code> value equal to 21 days. It is
equivalent to <code>"P21D" cast as xs:dayTimeDuration?</code>.</p><div class="exampleInner"><pre>xs:dayTimeDuration("P21D")</pre></div></li><li><p>If
                     <code>usa:zipcode</code> is a user-defined <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a>
in the <a title="in-scope schema type" class="termref" href="#dt-is-types">in-scope schema types</a>, then the
following expression is equivalent to the
expression <code>("12345" cast as
usa:zipcode?)</code>.</p><div class="exampleInner"><pre>usa:zipcode("12345")</pre></div></li><li><p>If <code>my:chrono</code> is a named item type that expands to
                     <code>(xs:date | xs:time | xs:dateTime)</code>, then the result
                     of <code>my:chrono("12:00:00Z")</code> is the <code>xs:time</code>
                     value <code>12:00:00Z</code>.</p></li><li><p>If <code>my:location</code> is a named item type that expands
                  to <code>record(latitude as xs:double, longitude as xs:double)</code>,
                  then the result of <code>my:location(50.52, -3.02)</code> is
                  the map <code>{ 'latitude': 50.52e0, 'longitude': -3.02e0 }</code>.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>
                  An instance of an <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a> whose name is in no namespace can be
  constructed by using a <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a> 
  in either a cast expression or a constructor function call.  Examples:
  </p><div class="exampleInner"><pre>17 cast as Q{}apple</pre></div><div class="exampleInner"><pre>Q{}apple(17)</pre></div><p>In either context, using an unqualified NCName might not work:
                  in a cast expression, an unqualified name is it is interpreted
                  according to the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>,
                  while an unqualified name in a constructor function call is resolved using the
                  <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a> which will often be inappropriate.
               </p></div></div><div class="div3">
<h4><a id="id-treat"/>4.21.6 <a href="#id-treat" style="text-decoration: none">Treat</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-pipeline-operator">⬇</a> <a href="#id-typeswitch">⬆</a></p><ol><li><p>The <code>treat as</code> expression now raises
               a type error rather than a dynamic error when it fails.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2165">2165</a> ]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TreatExpr"/><code><a href="#prod-xquery40-TreatExpr">TreatExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-TreatExpr-CastableExpr">CastableExpr</a>  ("treat"  "as"  <a href="#doc-xquery40-TreatExpr-SequenceType">SequenceType</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TreatExpr-CastableExpr"/><code><a href="#prod-xquery40-CastableExpr">CastableExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-CastExpr">CastExpr</a>  ("castable"  "as"  <a href="#prod-xquery40-CastTarget">CastTarget</a>  "?"?)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-TreatExpr-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                        <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody></table><p>The expression <code>
                     <var>E</var> treat as <var>T</var>
                  </code>
            evaluates the subexpression <var>E</var> to produce a value <var>V</var>,
               and then checks whether <var>V</var> matches
            the <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>
                  <var>T</var>. If it matches,
            the result of the expression is <var>V</var>; otherwise, the expression
            fails with a type error [<a href="#ERRXPDY0050" title="err:XPDY0050">err:XPDY0050</a>].</p><p>The value <var>V</var> must be an actual instance of the type <var>T</var>.
            No casting or coercion is applied to change the value to make it an instance
            of <var>T</var>. The result of the expression is equivalent to:</p><div class="exampleInner"><pre>let $V := <var>E</var>
return if ($V instance of <var>T</var>)
       then $V
       else error(#err:XPDY0050)</pre></div><ul><li><p>Example:</p><div class="exampleInner"><pre>$myaddress treat as element(*, USAddress)</pre></div><p>The
<a title="static type" class="termref" href="#dt-static-type">static type</a> of
<code>$myaddress</code> may be <code>element(*, Address)</code>, a
less specific type than <code>element(*, USAddress)</code>. However,
at run-time, the value of <code>$myaddress</code> must match the type
<code>element(*, USAddress)</code> using rules for <a title="SequenceType matching" class="termref" href="#dt-sequencetype-matching">SequenceType
matching</a>;
otherwise a <a title="type error" class="termref" href="#dt-type-error">type error</a> is
raised [<a href="#ERRXPDY0050" title="err:XPDY0050">err:XPDY0050</a>].</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>Earlier releases of XPath and XQuery defined a mode of operation,
               sometimes called strict static typing, in which it was required that the static
               type of every expression should conform to the required type of the context
               in which it appeared. In this situation it was often necessary to define
               a more precise static type for an expression by the use of <code>treat as</code>.
               In the absence of this feature, the <code>treat as</code> expression is
               rarely necessary, though it can be useful for documentation, and might in
               some cases (depending on the processor) have performance benefits.
             </p><p>XQuery 4.0 redefines the error raised by a <code>treat as</code> expression
             as a type error rather than a dynamic error, which allows a processor to raise
             the error statically in the case of an expression (such as <code>3 treat as xs:string</code>)
             which can never succeed. However, the error code remains unchanged, for compatibility.</p></div></div></div><div class="div2">
<h3><a id="id-pipeline-operator"/>4.22 <a href="#id-pipeline-operator" style="text-decoration: none">Pipeline operator</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-arrow-operator">⬇</a> <a href="#id-treat">⬆</a></p><ol><li><p>
               With the pipeline operator <code>-&gt;</code>, the result of an expression
               can be bound to the context value before evaluating another expression.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1685">1685</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1686">1686</a> 9 January 2025]</i></p></li></ol></div>
<a id="d2e43235"/><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PipelineExpr"/><code><a href="#prod-xquery40-PipelineExpr">PipelineExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-PipelineExpr-ArrowExpr">ArrowExpr</a>  ("-&gt;"  <a href="#doc-xquery40-PipelineExpr-ArrowExpr">ArrowExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-PipelineExpr-ArrowExpr"/><code><a href="#prod-xquery40-ArrowExpr">ArrowExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-UnaryExpr">UnaryExpr</a>  (<a href="#prod-xquery40-SequenceArrowTarget">SequenceArrowTarget</a>  |  <a href="#prod-xquery40-MappingArrowTarget">MappingArrowTarget</a>)*</code></td></tr></tbody></table><p>
               [<a id="dt-pipeline-operator" title="pipeline operator">Definition</a>: 
            The <b>pipeline operator</b>
                  <code>-&gt;</code> evaluates an expression and
            binds the result to the context value before evaluating another expression.]
            </p><p>Each operation <code>
                  <var>E<sub>1</sub></var> -&gt; <var>E<sub>2</sub></var>
               </code> is evaluated as follows: 
            Expression <var>E<sub>1</sub></var> is evaluated to a sequence <code>S</code>. 
            <var>S</var> then serves in turn to provide an inner <a title="fixed focus" class="termref" href="#dt-fixed-focus">fixed focus</a>
            (with the context value set to <var>S</var>) for an evaluation of <var>E<sub>2</sub></var> in the
            <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a>.
            Unlike the <a href="#id-map-operator"><b>4.23 Simple map operator (!)</b></a>, the result of <var>E<sub>1</sub></var> is bound
            just once and as a whole to the context value.
         </p><p>The following examples illustrate the use of pipeline operators:</p><div class="example"><ul><li><p>Tokenizes a string, counts the tokens, creates a concatenated string and returns
                     <code>count=3</code>:</p><div class="exampleInner"><pre>'a b c' -&gt; tokenize(.) -&gt; count(.) -&gt; concat('count=', .)</pre></div><p>An equivalent expression is:
                     </p><div class="exampleInner"><pre>
let $string := 'a b c'
let $tokens := tokenize($string)
let $count := count($tokens)
return concat('count=', $count)</pre></div></li><li><p>Calculates the sum of powers of <code>2</code> and returns
                     <code>2046</code>.</p><div class="exampleInner"><pre>(1 to 10) ! math:pow(2, .) -&gt; sum(.)</pre></div><p>An equivalent expression is:
                     </p><div class="exampleInner"><pre>
let $powers := (
  for $exp in 1 to 10
  return math:pow(2, $exp)
)
return sum($powers)</pre></div></li><li><p>Doubles the values of a sequence, compares the values pairwise with another
                     sequence, checks if some comparisons were successful, and returns
                     <code>true</code>.</p><div class="exampleInner"><pre>
(1 to 4)
-&gt; for-each(., op('+'))
-&gt; for-each-pair(4 to 7, ., op('&gt;'))
-&gt; some(.)</pre></div><p>An equivalent expression is:
                     </p><div class="exampleInner"><pre>
let $data := 1 to 4
let $data := for-each($data, op('+'))
let $data := for-each-pair(4 to 7, $data, op('&gt;'))
return some($data)</pre></div></li><li><p>Reduces a long sequence to at most 9 elements, with dots appended,
                  and returns a single string.</p><div class="exampleInner"><pre>
$dictionary/word
-&gt; (if (count(.) &lt; 10) then . else (.[1 to 9], '…'))
-&gt; string-join(., '; ')</pre></div><p>An equivalent expression is:
                     </p><div class="exampleInner"><pre>
let $words := $dictionary/word
let $chopped := (if (count($words) &lt; 10) then $words else ($words[1 to 9], '…'))
return string-join($chopped, '; ')</pre></div></li></ul></div></div><div class="div2">
<h3><a id="id-map-operator"/>4.23 <a href="#id-map-operator" style="text-decoration: none">Simple map operator (<code>!</code>)</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SimpleMapExpr"/><code><a href="#prod-xquery40-SimpleMapExpr">SimpleMapExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-SimpleMapExpr-PathExpr">PathExpr</a>  ("!"  <a href="#doc-xquery40-SimpleMapExpr-PathExpr">PathExpr</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SimpleMapExpr-PathExpr"/><code><a href="#prod-xquery40-PathExpr">PathExpr</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AbsolutePathExpr">AbsolutePathExpr</a>
                     <br/>|  <a href="#doc-xquery40-RelativePathExpr">RelativePathExpr</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-leading-lone-slash">xgc: leading-lone-slash</a>
                   */</td></tr></tbody></table><p>
    A mapping expression <code>
                  <var>S</var>!<var>E</var>
               </code> evaluates the
    expression <var>E</var> once for every item in the sequence
    obtained by evaluating <var>S</var>. The simple mapping operator
    <code>!</code> can be applied to any sequence, regardless of the
    types of its items, and it can deliver a mixed sequence of nodes,
    atomic items, and functions. Unlike the similar <code>/</code>
    operator, it does not sort nodes into document order or eliminate
    duplicates.
  </p><p>Each operation <code>
                  <var>E<sub>1</sub></var>!<var>E<sub>2</sub></var>
               </code> is evaluated as follows: 
            Expression <var>E<sub>1</sub></var> is evaluated to a sequence <code>S</code>. 
            Each item in <var>S</var> then serves in turn to provide an inner focus 
            (the item as the context value, its position in <var>S</var> as the 
            context position, the length of <var>S</var> as the context size) 
            for an evaluation of <var>E<sub>2</sub></var> in the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a>. The sequences resulting from all the 
            evaluations of <var>E<sub>2</sub></var> are combined as follows: Every evaluation 
            of <var>E<sub>2</sub></var> returns a (possibly empty) sequence of items. 
            The final result is the <a title="sequence concatenation" class="termref" href="#dt-sequence-concatenation">sequence concatenation</a> of these sequences.
            The returned sequence preserves the orderings within and among the subsequences 
            generated by the evaluations of <var>E<sub>2</sub></var>.
         </p><p>Simple map operators have functionality similar to <a href="#id-path-operator"><b>4.6.3 Path operator (/)</b></a>.
  The following table summarizes the differences between these two operators</p><table style="width:100%" class="medium"><thead><tr><th>Operator</th><th>Path operator (<code>E1 / E2</code>)</th><th>Simple map operator (<code>E1 ! E2</code>)</th></tr></thead><tbody><tr><th>E1</th><td>Any sequence of nodes</td><td>Any sequence of items</td></tr><tr><th>E2</th><td>Either a sequence of nodes or a sequence of non-node items</td><td>A sequence of items</td></tr><tr><th>Additional processing</th><td>Duplicate elimination and document ordering</td><td>Simple <a title="sequence concatenation" class="termref" href="#dt-sequence-concatenation">sequence concatenation</a>
                     </td></tr></tbody></table><p>The following examples illustrate the use of simple map operators combined with path expressions.</p><div class="example"><ul><li><p>
                        <code>child::div1 / child::para / string() ! concat("id-", .)</code>
                     </p><p>Selects the <code>para</code> element children of the <code>div1</code> element children of the context node; that is, the <code>para</code> element grandchildren of the context node that have <code>div1</code> parents. It then outputs the strings obtained by prepending <code>"id-"</code> to each of the string values of these grandchildren.</p></li><li><p>
                        <code>$emp ! (@first, @middle, @last)</code>
                     </p><p>Returns the values of the attributes <code>first</code>, <code>middle</code>, and <code>last</code> for each element in <code>$emp</code>, in the order given. (The <code>/</code> operator, if used here, would return the attributes in an unpredictable order.)</p></li><li><p>
                        <code>$docs ! ( //employee)</code>
                     </p><p>Returns all the <code>employee</code> elements within all the documents identified by the variable <code>$docs</code>, in document order within each document, but retaining the order of documents.</p></li><li><p>
                        <code>avg( //employee / salary ! translate(., '$', '') ! number(.))</code>
                     </p><p>Returns the average salary of the employees, having converted the salary to a number by removing any <code>$</code> sign and then converting to a number. (The second occurrence of <code>!</code> could not be written as <code>/</code> because the left-hand operand of <code>/</code> cannot be an atomic item.)</p></li><li><p>
                        <code>string-join((1 to $n) ! "*")</code>
                     </p><p>Returns a string containing <code>$n</code> asterisks.</p></li><li><p>
                        <code>$values ! (.*.) =&gt; sum()</code>
                     </p><p>Returns the sum of the squares of a sequence of numbers.</p></li><li><p>
                        <code>string-join(ancestor::* ! name(), '/')</code>
                     </p><p>Returns the names of ancestor elements, joined by <code>/</code> characters, i.e., the path to the parent of the context.</p></li></ul></div></div><div class="div2">
<h3><a id="id-arrow-operator"/>4.24 <a href="#id-arrow-operator" style="text-decoration: none">Arrow Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-mapping-arrow-expression">⬇</a> <a href="#id-pipeline-operator">⬆</a></p><ol><li><p>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.<i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/1716">1716</a> <a href="https://github.com/qt4cg/qtspecs/issues/1829">1829</a> PRs <a href="https://github.com/qt4cg/qtspecs/pull/1763">1763</a> <a href="https://github.com/qt4cg/qtspecs/pull/1830">1830</a> 25 February 2025]</i></p></li></ol></div><p>Arrow expressions apply a function to a value, using the value of the
         left-hand expression as the first argument to the function.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr"/><code><a href="#prod-xquery40-ArrowExpr">ArrowExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ArrowExpr-UnaryExpr">UnaryExpr</a>  (<a href="#doc-xquery40-ArrowExpr-SequenceArrowTarget">SequenceArrowTarget</a>  |  <a href="#doc-xquery40-ArrowExpr-MappingArrowTarget">MappingArrowTarget</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-UnaryExpr"/><code><a href="#prod-xquery40-UnaryExpr">UnaryExpr</a></code></td><td>::=</td><td><code>("-"  |  "+")*  <a href="#prod-xquery40-ValueExpr">ValueExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-SequenceArrowTarget"/><code><a href="#prod-xquery40-SequenceArrowTarget">SequenceArrowTarget</a></code></td><td>::=</td><td><code>"=&gt;"  <a href="#doc-xquery40-ArrowExpr-ArrowTarget">ArrowTarget</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-ArrowTarget"/><code><a href="#prod-xquery40-ArrowTarget">ArrowTarget</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ArrowExpr-FunctionCall">FunctionCall</a>  |  <a href="#doc-xquery40-ArrowExpr-RestrictedDynamicCall">RestrictedDynamicCall</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-FunctionCall"/><code><a href="#prod-xquery40-FunctionCall">FunctionCall</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-EQName">EQName</a>
                     <a href="#prod-xquery40-ArgumentList">ArgumentList</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                   */</td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-parens">gn: parens</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-RestrictedDynamicCall"/><code><a href="#prod-xquery40-RestrictedDynamicCall">RestrictedDynamicCall</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ArrowExpr-VarRef">VarRef</a>  |  <a href="#doc-xquery40-ArrowExpr-ParenthesizedExpr">ParenthesizedExpr</a>  |  <a href="#doc-xquery40-ArrowExpr-FunctionItemExpr">FunctionItemExpr</a>  |  <a href="#doc-xquery40-ArrowExpr-MapConstructor">MapConstructor</a>  |  <a href="#doc-xquery40-ArrowExpr-ArrayConstructor">ArrayConstructor</a>)  <a href="#doc-xquery40-ArrowExpr-PositionalArgumentList">PositionalArgumentList</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-VarRef"/><code><a href="#prod-xquery40-VarRef">VarRef</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-EQName">EQName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-ParenthesizedExpr"/><code><a href="#prod-xquery40-ParenthesizedExpr">ParenthesizedExpr</a></code></td><td>::=</td><td><code>"("  <a href="#doc-xquery40-Expr">Expr</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-FunctionItemExpr"/><code><a href="#prod-xquery40-FunctionItemExpr">FunctionItemExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ArrowExpr-NamedFunctionRef">NamedFunctionRef</a>  |  <a href="#doc-xquery40-ArrowExpr-InlineFunctionExpr">InlineFunctionExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-NamedFunctionRef"/><code><a href="#prod-xquery40-NamedFunctionRef">NamedFunctionRef</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-EQName">EQName</a>  "#"  <a href="#prod-xquery40-IntegerLiteral">IntegerLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-InlineFunctionExpr"/><code><a href="#prod-xquery40-InlineFunctionExpr">InlineFunctionExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-Annotation">Annotation</a>*  ("function"  |  "fn")  <a href="#prod-xquery40-FunctionSignature">FunctionSignature</a>?  <a href="#prod-xquery40-FunctionBody">FunctionBody</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-MapConstructor"/><code><a href="#prod-xquery40-MapConstructor">MapConstructor</a></code></td><td>::=</td><td><code>"map"?  "{"  (<a href="#prod-xquery40-MapConstructorEntry">MapConstructorEntry</a> ** ",")  "}"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-ArrayConstructor"/><code><a href="#prod-xquery40-ArrayConstructor">ArrayConstructor</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-SquareArrayConstructor">SquareArrayConstructor</a>  |  <a href="#prod-xquery40-CurlyArrayConstructor">CurlyArrayConstructor</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-PositionalArgumentList"/><code><a href="#prod-xquery40-PositionalArgumentList">PositionalArgumentList</a></code></td><td>::=</td><td><code>"("  <a href="#doc-xquery40-ArrowExpr-PositionalArguments">PositionalArguments</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-PositionalArguments"/><code><a href="#prod-xquery40-PositionalArguments">PositionalArguments</a></code></td><td>::=</td><td><code>(<a href="#prod-xquery40-Argument">Argument</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ArrowExpr-MappingArrowTarget"/><code><a href="#prod-xquery40-MappingArrowTarget">MappingArrowTarget</a></code></td><td>::=</td><td><code>"=!&gt;"  <a href="#doc-xquery40-ArrowExpr-ArrowTarget">ArrowTarget</a>
                  </code></td></tr></tbody></table><p>The arrow syntax is particularly helpful when applying multiple
            functions to a value in turn. For example, the following
            expression invites syntax errors due to misplaced parentheses:
         </p><div class="exampleInner"><pre>tokenize((normalize-unicode(upper-case($string))),"\s+")</pre></div><p>In the following reformulation, it is easier to see that the parentheses are balanced:</p><div class="exampleInner"><pre>$string =&gt; upper-case() =&gt; normalize-unicode() =&gt; tokenize("\s+")</pre></div><p>When the operator is written as <code>=!&gt;</code>, the function
            is applied to each item in the sequence in turn. 
            Assuming that <code>$string</code> is a single string, the above example could
            equally be written:</p><div class="exampleInner"><pre>$string =!&gt; upper-case() =!&gt; normalize-unicode() =!&gt; tokenize("\s+")</pre></div><p>The difference between the two operators is seen when the left-hand
            operand evaluates to a sequence:</p><div class="exampleInner"><pre>(1, 2, 3) =&gt; avg()</pre></div><p>returns a value of only one item, <code>2</code>, the average of all three items. </p><p>This example could also be written as using the <a title="pipeline operator" class="termref" href="#dt-pipeline-operator">pipeline operator</a> as:</p><div class="exampleInner"><pre>(1, 2, 3) -&gt; avg(.)</pre></div><p>By contrast, an expression using the <a title="mapping arrow operator" class="termref" href="#dt-mapping-arrow-operator">mapping arrow operator</a>:</p><div class="exampleInner"><pre>(1, 2, 3) =!&gt; avg()</pre></div><p>would return the original sequence of three items, <code>(1, 2, 3)</code>, 
            each item being the average of itself.</p><p>There are two significant differences between the <a title="pipeline operator" class="termref" href="#dt-pipeline-operator">pipeline operator</a>
               <code>-&gt;</code>
            and the <a title="sequence arrow operator" class="termref" href="#dt-sequence-arrow-operator">sequence arrow operator</a>
               <code>=&gt;</code>:</p><ul><li><p>The <code>-&gt;</code> operator takes an arbitrary expression as its right-hand operand,
            whereas the <code>=&gt;</code> operator only accepts a function call.</p></li><li><p>When the right hand operand is a function call, the first argument
            is omitted in the case of the <code>=&gt;</code> operator, but is included explicitly
            (as a context value expression, <code>.</code>) in the case of the <code>-&gt;</code> operator.</p></li></ul><p>The following example:</p><div class="exampleInner"><pre>"The cat sat on the mat"
=&gt; tokenize()
=!&gt; concat(".")
=!&gt; upper-case()
=&gt; string-join(" ")</pre></div><p>returns <code>"THE. CAT. SAT. ON. THE. MAT."</code>. The first arrow
            could be written either as <code>=&gt;</code> or <code>=!&gt;</code> because the operand is a 
            <a title="singleton" class="termref" href="#dt-singleton">singleton</a>; the next two

            arrows have to be <code>=!&gt;</code> because the function is applied to each item in the tokenized
            sequence individually; the final arrow must be <code>=&gt;</code> because the <code>string-join</code>
            function applies to the sequence as a whole.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>It may be useful to think of this as a map/reduce pipeline. The functions
            introduced by <code>=!&gt;</code> are mapping operations; the function introduced by <code>=&gt;</code>
            is a reduce operation.</p></div><p>The following example introduces an inline function to the pipeline:</p><div class="exampleInner"><pre>(1 to 5) =!&gt; xs:double() =!&gt; math:sqrt() =!&gt; fn($a) { $a + 1 }() =&gt; sum()</pre></div><p>This is equivalent to <code>sum((1 to 5) ! (math:sqrt(xs:double(.)) + 1))</code>.</p><p>The same effect can be achieved using a <a title="focus function" class="termref" href="#dt-focus-function">focus function</a>:</p><div class="exampleInner"><pre>(1 to 5) =!&gt; xs:double() =!&gt; math:sqrt() =!&gt; fn { . + 1 }() =&gt; sum()</pre></div><p>It could also be expressed using the mapping operator <code>!</code>:</p><div class="exampleInner"><pre>(1 to 5) ! xs:double(.) ! math:sqrt(.) ! (. + 1) =&gt; sum()</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The <code>ArgumentList</code> may include <code>PlaceHolders</code>,
            though this is not especially useful. For example, the expression <code>"$" =&gt; concat(?)</code> is equivalent
            to <code>concat("$", ?)</code>: its value is a function that prepends a supplied string with
            a <code>$</code> symbol.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The <code>ArgumentList</code> may include keyword arguments if the
            function is identified statically (that is, by name). For example,
            the following is valid: <code>$xml =&gt; xml-to-json(indent := true()) =&gt; parse-json(escape := false())</code>.</p></div><p>The sequence arrow operator thus applies the supplied function to 
            the left-hand operand as a whole, while the mapping arrow operator applies the function to
            each item in the value of the left-hand operand individually. In the case where the result
            of the left-hand operand is a single item, the two operators have the same effect.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The mapping arrow symbol <code>=!&gt;</code> is intended to suggest a combination of
            function application (<code>=&gt;</code>) and sequence mapping
            (<code>!</code>) combined in a single operation.</p><p>Similarly, the method call operator <code>=?&gt;</code> is intended to suggest a combination
               of function application (<code>=&gt;</code>) and map lookup (<code>?</code>) in a single
            operation.</p></div><p>The construct on the right-hand side of the arrow operator (<code>=&gt;</code>) can
         either be a static function call, or a restricted form of dynamic function call. The
         restrictions are there to ensure that the two forms can be distinguished by the parser
         with limited lookahead. For a dynamic call, the function item to be called can be 
         expressed as a variable reference, an inline function expression, a named function reference, 
         a map constructor, or an array constructor. Any other expression used to return the required function
         item must be enclosed in parentheses.</p><div class="div3">
<h4><a id="id-sequence-arrow-expression"/>4.24.1 <a href="#id-sequence-arrow-expression" style="text-decoration: none">Sequence Arrow Expressions</a></h4><p>
                  [<a id="dt-sequence-arrow-operator" title="sequence arrow operator">Definition</a>: 
               The <b>sequence arrow operator</b>
                     <code>=&gt;</code> applies a function to a
               supplied sequence.] It is defined as follows:</p><ul><li><p>If the arrow is followed by a static <a href="#doc-xquery40-FunctionCall">FunctionCall</a>:</p><p>Given a  <a href="#doc-xquery40-UnaryExpr">UnaryExpr</a>
                        <var>U</var> and a <a href="#doc-xquery40-FunctionCall">FunctionCall</a>
                        <code>
                           <var>F</var>(<var>A</var>, <var>B</var>, <var>C</var>...)</code>, 
                  the expression <code>
                           <var>U</var> =&gt; <var>F</var>(<var>A</var>, <var>B</var>, <var>C</var>...)</code> 
                  is equivalent to the expression 
                  <code>
                           <var>F</var>(<var>U</var>, <var>A</var>, <var>B</var>, <var>C</var>...)</code>.</p></li><li><p>If the arrow is followed by a <a href="#prod-xquery40-RestrictedDynamicCall">RestrictedDynamicCall</a>:</p><p>Given a  <a href="#doc-xquery40-UnaryExpr">UnaryExpr</a>
                        <var>U</var>, and a <a href="#prod-xquery40-RestrictedDynamicCall">RestrictedDynamicCall</a>
                        <code>
                           <var>E</var>(<var>A</var>, <var>B</var>, <var>C</var>...)</code>, the expression 
                  <code>
                           <var>U</var> =&gt; <var>E</var>(<var>A</var>, <var>B</var>, <var>C</var>...)</code> is equivalent to the
                  dynamic function call <code>
                           <var>E</var>(<var>U</var>, <var>A</var>, <var>B</var>, <var>C</var>...)</code>.</p></li></ul></div><div class="div3">
<h4><a id="id-mapping-arrow-expression"/>4.24.2 <a href="#id-mapping-arrow-expression" style="text-decoration: none">Mapping Arrow Expressions</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-validate">⬇</a> <a href="#id-arrow-operator">⬆</a></p><ol><li><p>
               The arrow operator <code>=&gt;</code> is now complemented by a “mapping arrow” operator <code>=!&gt;</code>
               which applies the supplied function to each item in the input sequence independently.
            </p></li></ol></div><p>
                  [<a id="dt-mapping-arrow-operator" title="mapping arrow operator">Definition</a>: 
            The <b>mapping arrow operator</b>
                     <code>=!&gt;</code> applies a function to each
            item in a sequence.] It is defined as follows:</p><ul><li><p>If the arrow is followed by a static <a href="#doc-xquery40-FunctionCall">FunctionCall</a>:</p><p>Given a <a href="#doc-xquery40-UnaryExpr">UnaryExpr</a>
                        <var>U</var> and a <a href="#doc-xquery40-FunctionCall">FunctionCall</a>
                        <code>
                           <var>F</var>(<var>A</var>, <var>B</var>, <var>C</var>...)</code>, 
                  the expression <code>
                           <var>U</var> =!&gt; <var>F</var>(<var>A</var>, <var>B</var>, <var>C</var>...)</code> 
                  is equivalent to the expression 
                  <code>for $u in <var>U</var> return 
                     <var>F</var>(<var>$u</var>, <var>A</var>, <var>B</var>, <var>C</var>...)</code>.</p></li><li><p>If the arrow is followed by a <a href="#prod-xquery40-RestrictedDynamicCall">RestrictedDynamicCall</a>:</p><p>Given a  <a href="#doc-xquery40-UnaryExpr">UnaryExpr</a>
                        <var>U</var>, and a <a href="#prod-xquery40-RestrictedDynamicCall">RestrictedDynamicCall</a>
                        <code>
                           <var>E</var>(<var>A</var>, <var>B</var>, <var>C</var>...)</code>, the expression 
               <code>
                           <var>U</var> =&gt; <var>E</var>(<var>A</var>, <var>B</var>, <var>C</var>...)</code> is equivalent to the
               expression <code>for $u in U return <var>E</var>(<var>$u</var>, <var>A</var>, <var>B</var>, <var>C</var>...)</code>.</p></li></ul></div></div><div class="div2 xquery">
<h3><a id="id-validate"/>4.25 <a href="#id-validate" style="text-decoration: none">Validate Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-extension-expressions">⬇</a> <a href="#id-mapping-arrow-expression">⬆</a></p><ol><li><p>
                  The rules concerning the interpretation of <code>xsi:schemaLocation</code>
                  and <code>xsi:noNamespaceSchemaLocation</code> attributes have been tightened up.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/729">729</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1254">1254</a> 8 June 2024]</i></p></li><li><p>
                  The technical details of how validation works have been moved to the
                  <em>Functions and Operators</em> specification. The XQuery <code>validate</code>
               expression is now defined in terms of the new <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-xsd-validator"><code>xsd-validator</code></a> function.
               <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2029">2029</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2030">2030</a> 28 May 2025]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ValidateExpr"/><code><a href="#prod-xquery40-ValidateExpr">ValidateExpr</a></code></td><td>::=</td><td><code>"validate"  (<a href="#doc-xquery40-ValidateExpr-ValidationMode">ValidationMode</a>  |  ("type"  <a href="#doc-xquery40-ValidateExpr-TypeName">TypeName</a>))?  "{"  <a href="#doc-xquery40-ValidateExpr-Expr">Expr</a>  "}"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ValidateExpr-ValidationMode"/><code><a href="#prod-xquery40-ValidationMode">ValidationMode</a></code></td><td>::=</td><td><code>"lax"  |  "strict"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ValidateExpr-TypeName"/><code><a href="#prod-xquery40-TypeName">TypeName</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ValidateExpr-EQName">EQName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ValidateExpr-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ValidateExpr-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody></table><p>A <code>validate</code> expression can be used to validate a
        document node or an element node with respect to the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a>, using the schema
        validation process defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#xsd-validation">17.2.4 XSD validation</a>.
         The <b>effective schema</b> used for validation is the set
         of schema components contained in the 
            <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a>. The
         operand node is the result of evaluating the expression within
         the curly brackets.</p><p>A <code>validate</code> expression returns a new node with its own identity and with no parent.
        The new node and its descendants are given <a title="type annotation" class="termref" href="#dt-type-annotation">type annotations</a>
        that are generated by applying a validation process to the operand node. Default values
        for elements and attributes may also be generated by the validation process.</p><p>If a type name is provided, and the type name is <code>xs:untyped</code>, 
                  no validation takes place: all elements receive the type annotation <code>xs:untyped</code>,
        and all attributes receive the type annotation <code>xs:untypedAtomic</code>. 
        If the type name is <code>xs:untypedAtomic</code>, the node receives the type annotation <code>xs:untypedAtomic</code>;
        a type error [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>] is raised if the node has element children.
         The typed value of each node is changed to be the same as its string value, as an instance of
         <code>xs:untypedAtomic</code>. In the case of elements the
         <code>nilled</code> property is set to <code>false</code>. The values
         of the <code>is-id</code> and <code>is-idrefs</code> properties are
          unchanged.</p><p>In all other cases, the result of a <code>validate</code> expression is defined by reference
         to the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-xsd-validator"><code>fn:xsd-validator</code></a> function:</p><ul><li><p>The expressions <code>validate { <var>E</var> }</code>
               and <code>validate strict { <var>E</var> }</code> translate to:</p><div class="exampleInner"><pre><code>fn:xsd-validator({'validation-mode':'strict'})(<var>E</var>) -&gt;
    if (?is-valid) then ?typed-node else error()</code></pre></div></li><li><p>The expression <code>validate lax { <var>E</var> }</code> translates to:</p><div class="exampleInner"><pre><code>fn:xsd-validator({'validation-mode':'lax'})(<var>E</var>) -&gt;
    if (?is-valid) then ?typed-node else error()</code></pre></div></li><li><p>The expression <code>validate type <var>T</var> { <var>E</var> }</code>
               translates to:</p><div class="exampleInner"><pre><code>fn:xsd-validator({'type':<var>T′</var>})(<var>E</var>) -&gt;
    if (?is-valid) then ?typed-node else error()</code></pre></div><p>where <var>T′</var> is the <code>xs:QName</code> value obtained by expanding <var>T</var>
               (the supplied <code>TypeName</code>) using the <a title="default type namespace rule" class="termref" href="#dt-default-type-namespace-rule">default type namespace rule</a>.</p></li><li><p>The error reporting when <code>?is-valid</code> returns false is defined in more
            detail below.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>The effect of these rules is that when validation succeeds, the <code>validate</code>
         expression returns a copy of the operand node, augmented with type annotations and expanded
         default values. When validation fails (more accurately, when the outcome of validity assessment
         is that the operand node is found to be invalid), the expression raises a dynamic error.</p></div><p>It is <span class="verb">recommended</span> that the call on <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-xsd-validator"><code>xsd-validator</code></a>
	     should use the default option setting <code>use-xsi-schema-location = false()</code>.
	     In previous versions of the specification it was <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation defined</a> 
	        whether the validity assessment process should take account of any <code>xsi:schemaLocation</code> or <code>xsi:noNamespaceSchemaLocation</code>
           attributes in the tree being validated; and for backwards compatibility processors
	     <span class="verb">may</span> therefore set this option to <code>true</code>. This version of
	     the specification also defines more prescriptive rules for how instance-defined
	     schema locations should be handled if the processor chooses not to ignore them.</p><p>The error conditions that may arise are as follows. The error codes, for backwards
         compatibility reasons, are not the same as those raised by the <code>xsd-validator</code>
         function.</p><table style="border:1px solid" class="medium"><caption>Error Codes Raised by the Validate Expression</caption><col style="width:30%" span="1"/><col style="width:70%" span="1"/><thead><tr><th>Error Code</th><th>Meaning</th></tr></thead><tbody><tr><td style="vertical-align:top">
                        <p>Static error [<a href="#ERRXQST0009" title="err:XQST0009">err:XQST0009</a>]
                        </p>
                     </td><td style="vertical-align:top">
                        <p>The processor does not provide the <b>Schema Aware Feature</b>.</p>
                     </td></tr><tr><td style="vertical-align:top">
                        <p>Type error [<a href="#ERRXQTY0030" title="err:XQTY0030">err:XQTY0030</a>]
                        </p>
                     </td><td style="vertical-align:top">
                        <p>The result of the operand expression is not a single document 
                     or element node.</p>
                     </td></tr><tr><td style="vertical-align:top">
                        <p>Type error [<a href="#ERRXQDY0061" title="err:XQDY0061">err:XQDY0061</a>]
                        </p>
                     </td><td style="vertical-align:top">
                        <p>The result of the operand expression is a document node
                  whose content does not consist of exactly one element node and
                  zero or more comment and processing instruction nodes.</p>
                     </td></tr><tr><td style="vertical-align:top">
                        <p>Static error [<a href="#ERRXQST0104" title="err:XQST0104">err:XQST0104</a>]
                        </p>
                     </td><td style="vertical-align:top">
                        <p>The supplied <code>TypeName</code> is not found in the
                  <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a>.</p>
                     </td></tr><tr><td style="vertical-align:top">
                        <p>Type error [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>]
                        </p>
                     </td><td style="vertical-align:top">
                        <p>The specified type is <code>xs:untypedAtomic</code>,
                  but the operand node has element children.</p>
                     </td></tr><tr><td style="vertical-align:top">
                        <p>Dynamic error [<a href="#ERRXQDY0084" title="err:XQDY0084">err:XQDY0084</a>]
                        </p>
                     </td><td style="vertical-align:top">
                        <p>Strict validation was requested, but there is no
                  element declaration in the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a> whose name
                  matches the name of the operand node (or the top-level element
                  in the case where the operand node is a document node).</p>
                     </td></tr><tr><td style="vertical-align:top">
                        <p>Dynamic error [<a href="#ERRXQDY0027" title="err:XQDY0027">err:XQDY0027</a>]
                        </p>
                     </td><td style="vertical-align:top">
                        <p>After validation, the <code>validity</code> property
                  of the root element is not <code>valid</code>; or, after
                  lax validation, the <code>validity</code> property is
                  neither <code>valid</code> nor <code>notKnown</code>.</p>
                     </td></tr></tbody></table><div class="note"><p class="prefix"><b>Note:</b></p><p>A query might take as its primary input a document conforming to schema <var>X</var>,
            and produce as its primary output a document conforming to schema <var>Y</var>.
            To be sure that the output is indeed valid against schema <var>Y</var>, the safest
            course of action is to evaluate a <code>validate</code> expression within
            a query module that imports schema <var>Y</var> and nothing else. Otherwise,
               if the validation occurs within a module that imports both <var>X</var>
            and <code>Y</code>, the outcome of validation might differ because of the
            differences between the two schemas.</p></div></div><div class="div2 xquery">
<h3><a id="id-extension-expressions"/>4.26 <a href="#id-extension-expressions" style="text-decoration: none">Extension Expressions</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-default-ordering-decl">⬇</a> <a href="#id-validate">⬆</a></p><ol><li><p>
               Whitespace is now required after the opening <code>(#</code> of a pragma. This
               is an incompatible change, made to ensure that an expression such as <code>error(#err:XPTY0004)</code>
               can be parsed as a function call taking a QName literal as its argument value.
            <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1981">1981</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1982">1982</a> 8 May 2024]</i></p></li></ol></div><p>
               [<a id="dt-extension-expression" title="extension expression">Definition</a>: An <b>extension expression</b> is an expression whose semantics are
<a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>.] Typically a particular extension will be recognized
by some implementations and not by others. The syntax is designed so that
extension expressions can be successfully parsed by all implementations, and
so that fallback behavior can be defined for implementations that do not
recognize a particular extension.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExtensionExpr"/><code><a href="#prod-xquery40-ExtensionExpr">ExtensionExpr</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ExtensionExpr-Pragma">Pragma</a>+  "{"  <a href="#doc-xquery40-ExtensionExpr-Expr">Expr</a>?  "}"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExtensionExpr-Pragma"/><code><a href="#prod-xquery40-Pragma">Pragma</a></code></td><td>::=</td><td><code>"(#"  <a href="#prod-xquery40-S">S</a>
                     <a href="#doc-xquery40-ExtensionExpr-EQName">EQName</a>  (<a href="#prod-xquery40-S">S</a>
                     <a href="#doc-xquery40-ExtensionExpr-PragmaContents">PragmaContents</a>)?  "#)"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExtensionExpr-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExtensionExpr-PragmaContents"/><code><a href="#prod-xquery40-PragmaContents">PragmaContents</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExtensionExpr-Char">Char</a>* - (Char* '#)' Char*))</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExtensionExpr-Char"/><code><a href="#prod-xquery40-Char">Char</a></code></td><td>::=</td><td><code>
                     <a href="https://www.w3.org/TR/REC-xml/#NT-Char">[http://www.w3.org/TR/REC-xml#NT-Char]</a><sup><small>XML</small></sup>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-xml-version">xgc: xml-version</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ExtensionExpr-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody></table><p>An extension expression consists of one or more <b>pragmas</b>, 
            followed by an optional expression (the <b>associated expression</b>). [<a id="dt-pragma" title="pragma">Definition</a>: A <b>pragma</b> is denoted by the delimiters <code>(#</code> and <code>#)</code>, 
               and consists of an identifying EQName followed by <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> content.]
            </p><p>The identifying EQName is expanded using the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>If the EQName is an unprefixed NCName, it is interpreted as a name in no namespace, and the pragma is therefore ignored.</p></div><p>The content of a pragma may consist of any string of characters 
            that does not contain the ending delimiter <code>#)</code>.</p><p>Each implementation recognizes an <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> set
of namespace URIs used to denote pragmas.</p><p>If the namespace URI of a pragma’s <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> 
is not recognized by the implementation as a pragma namespace, 
 or if the name is in no namespace, 
then the pragma is ignored. If all the pragmas in an <a href="#doc-xquery40-ExtensionExpr">ExtensionExpr</a> are ignored, then the
value of the <a href="#doc-xquery40-ExtensionExpr">ExtensionExpr</a> is the value of the 
 

associated expression; if no associated expression is provided,  a <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0079" title="err:XQST0079">err:XQST0079</a>].
</p><p>If an implementation recognizes the namespace of one or more
pragmas in an <a href="#doc-xquery40-ExtensionExpr">ExtensionExpr</a>, then the
value of the <a href="#doc-xquery40-ExtensionExpr">ExtensionExpr</a>, including its
error behavior, is <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>. For
example, an implementation that recognizes the namespace of a pragma’s
<a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>, but does
not recognize the local part of the name, might choose either to raise
an error or to ignore the pragma.</p><p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
               [<a href="#ERRXQST0013" title="err:XQST0013">err:XQST0013</a>] if an implementation recognizes a pragma but determines
that its content is invalid.</p><p>If an implementation recognizes a
pragma, it must report any static errors in the following expression
even if it will not evaluate that expression.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The following examples illustrate three ways in
which extension expressions might be used.</p><ul><li><p>A pragma can be used to furnish a hint for how to evaluate the
following expression, without actually changing the result.
For example:</p><div class="exampleInner"><pre>declare namespace exq = "http://example.org/XQueryImplementation";
(# exq:use-index #) {
  $bib/book/author[name = 'Berners-Lee']
}</pre></div><p>An implementation that recognizes the <code>exq:use-index</code> pragma might use an
index to evaluate the  expression that follows. An implementation that
does not recognize this pragma would evaluate the expression in its normal
way.</p></li><li><p>A pragma might be used to modify the semantics of the following
expression in ways that would not (in the absence of the pragma) be
conformant with this specification. For example, a pragma might be used to
permit comparison of <code>xs:duration</code> values using implementation-defined
semantics (this would normally be an error). Such changes to the language
semantics must be scoped to the <a title="enclosed expression" class="termref" href="#dt-enclosed-expression">enclosed expression</a> following the pragma.</p></li><li><p>A pragma might contain syntactic constructs that are
evaluated in place of the following expression. In this case, the
following expression itself (if it is present) provides a fallback for use by
implementations that do not recognize the pragma. For example:</p><div class="exampleInner"><pre>declare namespace exq = "http://example.org/XQueryImplementation";

for $x in (# exq:distinct //city by @country #) {
  //city[not(@country = preceding::city/@country)]
}
return f:show-city($x)</pre></div><p>Here an implementation that recognizes the pragma will return the result of
evaluating the proprietary syntax <code>exq:distinct //city by
@country</code>,
while an implementation that does not recognize the pragma will instead
return the result of the expression <code>//city[not(@country =
preceding::city/@country)]</code>. If no fallback expression is required, or
if none is feasible, then the expression between the curly brackets may be
omitted, in which case implementations that do not recognize the pragma will
raise a <a title="static error" class="termref" href="#dt-static-error">static error</a>.</p></li></ul></div></div></div><div class="div1 xquery">
<h2><a id="id-query-prolog"/>5 <a href="#id-query-prolog" style="text-decoration: none">Modules and Prologs</a></h2><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module"/><code><a href="#prod-xquery40-Module">Module</a></code></td><td>::=</td><td><code>
                  <a href="#doc-xquery40-Module-VersionDecl">VersionDecl</a>?  (<a href="#doc-xquery40-Module-LibraryModule">LibraryModule</a>  |  <a href="#doc-xquery40-Module-MainModule">MainModule</a>)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-VersionDecl"/><code><a href="#prod-xquery40-VersionDecl">VersionDecl</a></code></td><td>::=</td><td><code>"xquery"  (("encoding"  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>)  |  ("version"  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>  ("encoding"  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>)?))  <a href="#doc-xquery40-Module-Separator">Separator</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-LibraryModule"/><code><a href="#prod-xquery40-LibraryModule">LibraryModule</a></code></td><td>::=</td><td><code>
                  <a href="#doc-xquery40-Module-ModuleDecl">ModuleDecl</a>
                  <a href="#doc-xquery40-Module-Prolog">Prolog</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-ModuleDecl"/><code><a href="#prod-xquery40-ModuleDecl">ModuleDecl</a></code></td><td>::=</td><td><code>"module"  "namespace"  <a href="#prod-xquery40-NCName">NCName</a>  "="  <a href="#prod-xquery40-URILiteral">URILiteral</a>
                  <a href="#doc-xquery40-Module-Separator">Separator</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-Prolog"/><code><a href="#prod-xquery40-Prolog">Prolog</a></code></td><td>::=</td><td><code>((<a href="#doc-xquery40-Module-DefaultNamespaceDecl">DefaultNamespaceDecl</a>  |  <a href="#doc-xquery40-Module-Setter">Setter</a>  |  <a href="#doc-xquery40-Module-NamespaceDecl">NamespaceDecl</a>  |  <a href="#doc-xquery40-Module-Import">Import</a>)  <a href="#doc-xquery40-Module-Separator">Separator</a>)*  ((<a href="#doc-xquery40-Module-ContextValueDecl">ContextValueDecl</a>  |  <a href="#doc-xquery40-Module-VarDecl">VarDecl</a>  |  <a href="#doc-xquery40-Module-FunctionDecl">FunctionDecl</a>  |  <a href="#doc-xquery40-Module-ItemTypeDecl">ItemTypeDecl</a>  |  <a href="#doc-xquery40-Module-NamedRecordTypeDecl">NamedRecordTypeDecl</a>  |  <a href="#doc-xquery40-Module-OptionDecl">OptionDecl</a>)  <a href="#doc-xquery40-Module-Separator">Separator</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-DefaultNamespaceDecl"/><code><a href="#prod-xquery40-DefaultNamespaceDecl">DefaultNamespaceDecl</a></code></td><td>::=</td><td><code>"declare"  "fixed"?  "default"  ("element"  |  "function")  "namespace"  <a href="#prod-xquery40-URILiteral">URILiteral</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-Setter"/><code><a href="#prod-xquery40-Setter">Setter</a></code></td><td>::=</td><td><code>
                  <a href="#doc-xquery40-Module-BoundarySpaceDecl">BoundarySpaceDecl</a>  |  <a href="#doc-xquery40-Module-DefaultCollationDecl">DefaultCollationDecl</a>  |  <a href="#doc-xquery40-Module-BaseURIDecl">BaseURIDecl</a>  |  <a href="#doc-xquery40-Module-ConstructionDecl">ConstructionDecl</a>  |  <a href="#doc-xquery40-Module-OrderingModeDecl">OrderingModeDecl</a>  |  <a href="#doc-xquery40-Module-EmptyOrderDecl">EmptyOrderDecl</a>  |  <a href="#doc-xquery40-Module-CopyNamespacesDecl">CopyNamespacesDecl</a>  |  <a href="#doc-xquery40-Module-DecimalFormatDecl">DecimalFormatDecl</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-BoundarySpaceDecl"/><code><a href="#prod-xquery40-BoundarySpaceDecl">BoundarySpaceDecl</a></code></td><td>::=</td><td><code>"declare"  "boundary-space"  ("preserve"  |  "strip")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-DefaultCollationDecl"/><code><a href="#prod-xquery40-DefaultCollationDecl">DefaultCollationDecl</a></code></td><td>::=</td><td><code>"declare"  "default"  "collation"  <a href="#prod-xquery40-URILiteral">URILiteral</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-BaseURIDecl"/><code><a href="#prod-xquery40-BaseURIDecl">BaseURIDecl</a></code></td><td>::=</td><td><code>"declare"  "base-uri"  <a href="#prod-xquery40-URILiteral">URILiteral</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-ConstructionDecl"/><code><a href="#prod-xquery40-ConstructionDecl">ConstructionDecl</a></code></td><td>::=</td><td><code>"declare"  "construction"  ("strip"  |  "preserve")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-OrderingModeDecl"/><code><a href="#prod-xquery40-OrderingModeDecl">OrderingModeDecl</a></code></td><td>::=</td><td><code>"declare"  "ordering"  ("ordered"  |  "unordered")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-EmptyOrderDecl"/><code><a href="#prod-xquery40-EmptyOrderDecl">EmptyOrderDecl</a></code></td><td>::=</td><td><code>"declare"  "default"  "order"  "empty"  ("greatest"  |  "least")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-CopyNamespacesDecl"/><code><a href="#prod-xquery40-CopyNamespacesDecl">CopyNamespacesDecl</a></code></td><td>::=</td><td><code>"declare"  "copy-namespaces"  <a href="#prod-xquery40-PreserveMode">PreserveMode</a>  ","  <a href="#prod-xquery40-InheritMode">InheritMode</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-DecimalFormatDecl"/><code><a href="#prod-xquery40-DecimalFormatDecl">DecimalFormatDecl</a></code></td><td>::=</td><td><code>"declare"  (("decimal-format"  <a href="#doc-xquery40-EQName">EQName</a>)  |  ("default"  "decimal-format"))  (<a href="#prod-xquery40-DFPropertyName">DFPropertyName</a>  "="  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-NamespaceDecl"/><code><a href="#prod-xquery40-NamespaceDecl">NamespaceDecl</a></code></td><td>::=</td><td><code>"declare"  "namespace"  <a href="#prod-xquery40-NCName">NCName</a>  "="  <a href="#prod-xquery40-URILiteral">URILiteral</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-Import"/><code><a href="#prod-xquery40-Import">Import</a></code></td><td>::=</td><td><code>
                  <a href="#doc-xquery40-Module-SchemaImport">SchemaImport</a>  |  <a href="#doc-xquery40-Module-ModuleImport">ModuleImport</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-SchemaImport"/><code><a href="#prod-xquery40-SchemaImport">SchemaImport</a></code></td><td>::=</td><td><code>"import"  "schema"  <a href="#prod-xquery40-SchemaPrefix">SchemaPrefix</a>?  <a href="#prod-xquery40-URILiteral">URILiteral</a>  ("at"  (<a href="#prod-xquery40-URILiteral">URILiteral</a> ++ ","))?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-ModuleImport"/><code><a href="#prod-xquery40-ModuleImport">ModuleImport</a></code></td><td>::=</td><td><code>"import"  "module"  ("namespace"  <a href="#prod-xquery40-NCName">NCName</a>  "=")?  <a href="#prod-xquery40-URILiteral">URILiteral</a>  ("at"  (<a href="#prod-xquery40-URILiteral">URILiteral</a> ++ ","))?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-Separator"/><code><a href="#prod-xquery40-Separator">Separator</a></code></td><td>::=</td><td><code>";"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-ContextValueDecl"/><code><a href="#prod-xquery40-ContextValueDecl">ContextValueDecl</a></code></td><td>::=</td><td><code>"declare"  "context"  (("value"  ("as"  <a href="#doc-xquery40-SequenceType">SequenceType</a>)?)  |  ("item"  ("as"  <a href="#doc-xquery40-ItemType">ItemType</a>)?))  ((":="  <a href="#prod-xquery40-VarValue">VarValue</a>)  |  ("external"  (":="  <a href="#prod-xquery40-VarDefaultValue">VarDefaultValue</a>)?))</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-VarDecl"/><code><a href="#prod-xquery40-VarDecl">VarDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#doc-xquery40-Annotation">Annotation</a>*  "variable"  <a href="#prod-xquery40-VarNameAndType">VarNameAndType</a>  ((":="  <a href="#prod-xquery40-VarValue">VarValue</a>)  |  ("external"  (":="  <a href="#prod-xquery40-VarDefaultValue">VarDefaultValue</a>)?))</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-FunctionDecl"/><code><a href="#prod-xquery40-FunctionDecl">FunctionDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#doc-xquery40-Annotation">Annotation</a>*  "function"  <a href="#doc-xquery40-EQName">EQName</a>  "("  <a href="#prod-xquery40-ParamListWithDefaults">ParamListWithDefaults</a>?  ")"  <a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a>?  (<a href="#prod-xquery40-FunctionBody">FunctionBody</a>  |  "external")</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                  <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-ItemTypeDecl"/><code><a href="#prod-xquery40-ItemTypeDecl">ItemTypeDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#doc-xquery40-Annotation">Annotation</a>*  "type"  <a href="#doc-xquery40-EQName">EQName</a>  "as"  <a href="#doc-xquery40-ItemType">ItemType</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-NamedRecordTypeDecl"/><code><a href="#prod-xquery40-NamedRecordTypeDecl">NamedRecordTypeDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#doc-xquery40-Annotation">Annotation</a>*  "record"  <a href="#doc-xquery40-EQName">EQName</a>  "("  (<a href="#prod-xquery40-ExtendedFieldDeclaration">ExtendedFieldDeclaration</a> ** ",")  <a href="#prod-xquery40-ExtensibleFlag">ExtensibleFlag</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-OptionDecl"/><code><a href="#prod-xquery40-OptionDecl">OptionDecl</a></code></td><td>::=</td><td><code>"declare"  "option"  <a href="#doc-xquery40-EQName">EQName</a>
                  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-MainModule"/><code><a href="#prod-xquery40-MainModule">MainModule</a></code></td><td>::=</td><td><code>
                  <a href="#doc-xquery40-Module-Prolog">Prolog</a>
                  <a href="#doc-xquery40-Module-QueryBody">QueryBody</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-QueryBody"/><code><a href="#prod-xquery40-QueryBody">QueryBody</a></code></td><td>::=</td><td><code>
                  <a href="#doc-xquery40-Module-Expr">Expr</a>
               </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Module-Expr"/><code><a href="#prod-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr></tbody></table><p>A query can be assembled from one or more fragments called <b>modules</b>. [<a id="dt-module" title="module">Definition</a>: A <b>module</b> is a fragment of XQuery code that conforms
      to the <a href="#doc-xquery40-Module">Module</a> grammar and can independently undergo the <a title="static analysis phase" class="termref" href="#dt-static-analysis">static analysis phase</a> described in <a href="#id-expression-processing"><b>2.3.3 Expression
Processing</b></a>. Each module is either a <a title="main module" class="termref" href="#dt-main-module">main
        module</a> or a <a title="library module" class="termref" href="#dt-library-module">library
    module</a>.]
         </p><p>
            [<a id="dt-main-module" title="main module">Definition</a>: A <b>main module</b> consists of a
        <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a> followed by a <a title="query body" class="termref" href="#dt-queryBody">Query
        Body</a>.] A query has exactly one main module. In a main module, the
      <a title="query body" class="termref" href="#dt-queryBody">Query Body</a> 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.</p><p>
            [<a id="dt-library-module" title="library module">Definition</a>: A module that does not contain a <a title="query body" class="termref" href="#dt-queryBody">Query Body</a> is called a <b>library module</b>. A library
      module consists of a <a title="module declaration" class="termref" href="#dt-module-declaration">module declaration</a>
      followed by a <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a>.] A library module cannot be
    evaluated directly; instead, it provides function and variable declarations that can be imported
    into other modules.</p><p>The XQuery syntax does not allow a <a title="module" class="termref" href="#dt-module">module</a> to contain both a
      <a title="module declaration" class="termref" href="#dt-module-declaration">module declaration</a> and a <a title="query body" class="termref" href="#dt-queryBody">Query Body</a>.</p><p>
            [<a id="dt-prolog" title="Prolog">Definition</a>: A <b>Prolog</b> is a series of declarations and
      imports that define the processing environment for the <a title="module" class="termref" href="#dt-module">module</a> that contains the Prolog.] Each declaration or import is followed
    by a semicolon. A Prolog is organized into two parts. </p><p>The first part of the Prolog consists of setters, imports, namespace declarations, and default
    namespace declarations. [<a id="dt-setter" title="setter">Definition</a>: 
               <b>Setters</b> 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 <a title="lexical QName" class="termref" href="#dt-qname">lexical
      QNames</a> within the query. Imports are used to import definitions from schemas and
    modules. [<a id="dt-target-namespace" title="target namespace">Definition</a>:  The <b>target
        namespace</b> of a module is the namespace of the objects (such as elements or functions)
      that it defines. ]
         </p><p>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.</p><p>
            [<a id="dt-queryBody" title="query body">Definition</a>: The <b>Query Body</b>, if present, consists
      of an expression that defines the result of the query.] Evaluation of expressions is
    described in <a href="#id-expressions"><b>4 Expressions</b></a>. A module can be evaluated only if it has a Query
    Body.</p><div class="div2">
<h3><a id="id-version-declaration"/>5.1 <a href="#id-version-declaration" style="text-decoration: none">Version Declaration</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VersionDecl"/><code><a href="#prod-xquery40-VersionDecl">VersionDecl</a></code></td><td>::=</td><td><code>"xquery"  (("encoding"  <a href="#doc-xquery40-VersionDecl-StringLiteral">StringLiteral</a>)  |  ("version"  <a href="#doc-xquery40-VersionDecl-StringLiteral">StringLiteral</a>  ("encoding"  <a href="#doc-xquery40-VersionDecl-StringLiteral">StringLiteral</a>)?))  <a href="#doc-xquery40-VersionDecl-Separator">Separator</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VersionDecl-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VersionDecl-Separator"/><code><a href="#prod-xquery40-Separator">Separator</a></code></td><td>::=</td><td><code>";"</code></td></tr></tbody></table><p>
               [<a id="dt-version-declaration" title="version declaration">Definition</a>: 
      A <b>version declaration</b> can identify the applicable
      XQuery syntax and semantics for a <a title="module" class="termref" href="#dt-module">module</a>, as well as its
      encoding.]
            </p><p>
               [<a id="dt-version-number" title="XQuery version number">Definition</a>: An <b>XQuery version number</b> 
        consists of two integers, referred to as the 
        <b>major version number</b> and the  <b>minor version number</b>.]
            </p><p>The version number is written as a <code>StringLiteral</code> following the <code>version</code>
      keyword, and in a conformant XQuery 4.0 query it <span class="verb">must</span> match the regular expression 
      <code>[1-9][0-9]*\.[0-9]</code>: for example <code>"4.0"</code>. The major version is the integer 
        preceding the dot (which must be written without any leading zero); the minor version is the
      integer after the dot (which must be a single digit).</p><div class="note"><p class="prefix"><b>Note:</b></p><p>XQuery 1.0 and 3.0 allowed the version number to be any string; XQuery 3.1 constrained it
        to consist of two integers separated by a dot. This left it unclear, for example,
        whether "3.01" was the same version number as "3.1", or whether "3.10" represented a higher version
        than "3.2". In 4.0 the rules have therefore been made stricter, to avoid any ambiguity.</p></div><p>If the version declaration is not
      present or the version is not included in the declaration, an
      XQuery 4.0 processor assumes a version of "4.0", unless configured otherwise using
      some external mechanism.</p><p>The version number "4.0" indicates the intent that the module
      be processed by an <a title="XQuery 4.0 Processor" class="termref" href="#dt-xquery-40-processor">XQuery
        4.0 processor</a>.</p><p>An XQuery 4.0 processor must accept a module in which the version number is given as
      "1.0", "3.0", or "3.1". It is then <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation defined</a> whether
      the module is processed using the syntax and semantics of the XQuery 4.0 specification, or the rules
      of the relevant earlier version. For example, if a query module specifies version <code>"3.0"</code>
      but contains a call to the <code>parse-html</code> function, the processor at its option can
      either raise an error, or process the function call according to the XQuery 4.0 specification.</p><p>The XQuery 4.0 specification does not attempt to define the semantics of a query in which
      different modules use different version numbers. One approach is to process all modules as if
      they specified version "4.0". Another approach (which may be appropriate if modules
      are separately compiled) is to process each module using its own version number; but it is then
      <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation defined</a> what happens if (say) a 3.1 module imports a 
      4.0 library module that declares a function with a signature that 3.1 does not recognize.</p><p>A conformant XQuery 4.0 processor <span class="verb">may</span> raise an error if the version number is anything
      other than "1.0", "3.0", "3.1", or "4.0". If the processor does not raise an error, the effect of such
      a query is <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation defined</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The effect of this rule is to permit the use of non-standard version numbers to
        label non-standard extensions of the XQuery language. It also leaves flexibility as
        to how an XQuery 4.0 processor should handle future version numbers such as "4.1",
        or version numbers such as "1" or "3.00" that were permitted by earlier XQuery
        specifications.</p></div><p>If a query is rejected because of a version mismatch with the processor, a static error  
      [<a href="#ERRXQST0031" title="err:XQST0031">err:XQST0031</a>] must be raised.</p><p>
               [<a id="dt-encoding-declaration" title="encoding declaration">Definition</a>: If present, a version
        declaration may optionally include an <b>encoding declaration</b>. The value of the
        string literal following the keyword <code>encoding</code> is an encoding name, and must
        conform to the definition of <code>EncName</code> specified in <a href="#XML">[XML 1.0]</a>
                  [<a href="#ERRXQST0087" title="err:XQST0087">err:XQST0087</a>]. 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
          <code>"UTF-8"</code>, <code>"UTF-16"</code>, or <code>"US-ASCII"</code>.] Since
      the encoding of a query may change as the query moves from one environment to another, there
      can be no guarantee that the encoding declaration is correct.</p><p>The handling of an encoding declaration is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>. If an implementation has <em>a priori</em>
      knowledge of the encoding of a query, it may use this knowledge and disregard the encoding
      declaration. The semantics of a query are not affected by the presence or absence of an
      encoding declaration.</p><p>If a version declaration is present, no <a href="#doc-xquery40-Comment">Comment</a> may occur before the
      end of the version declaration. If such a <a href="#doc-xquery40-Comment">Comment</a> is present, the
      result is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>; an
      implementation may raise an implementation-dependent static error, or ignore the comment. </p><div class="note"><p class="prefix"><b>Note:</b></p><p>The effect of a <code>Comment</code> before the end of a version declaration is
          implementation-dependent because it may suppress query processing by interfering with
          detection of the encoding declaration.</p></div><p>The following examples illustrate version declarations:</p><div class="exampleInner"><pre>xquery version "3.1";</pre></div><div class="exampleInner"><pre>xquery version "4.0" encoding "utf-8";</pre></div></div><div class="div2">
<h3><a id="id-module-declaration"/>5.2 <a href="#id-module-declaration" style="text-decoration: none">Module Declaration</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ModuleDecl"/><code><a href="#prod-xquery40-ModuleDecl">ModuleDecl</a></code></td><td>::=</td><td><code>"module"  "namespace"  <a href="#prod-xquery40-NCName">NCName</a>  "="  <a href="#doc-xquery40-ModuleDecl-URILiteral">URILiteral</a>
                     <a href="#doc-xquery40-ModuleDecl-Separator">Separator</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ModuleDecl-URILiteral"/><code><a href="#prod-xquery40-URILiteral">URILiteral</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ModuleDecl-StringLiteral">StringLiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ModuleDecl-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ModuleDecl-Separator"/><code><a href="#prod-xquery40-Separator">Separator</a></code></td><td>::=</td><td><code>";"</code></td></tr></tbody></table><p>
               [<a id="dt-module-declaration" title="module declaration">Definition</a>: A <b>module
          declaration</b> serves to identify a <a title="module" class="termref" href="#dt-module">module</a> as a
          <a title="library module" class="termref" href="#dt-library-module">library module</a>. A module declaration begins
        with the keyword <code>module</code> and contains a namespace prefix and a <a href="#prod-xquery40-URILiteral">URILiteral</a>.] The URILiteral must be of nonzero length
        [<a href="#ERRXQST0088" title="err:XQST0088">err:XQST0088</a>]. The URILiteral identifies the <a title="target namespace" class="termref" href="#dt-target-namespace">target namespace</a> of the library module, which is the
      namespace for all variables and functions exported by the library module. The name of every
      variable and function declared in a library module must have a namespace URI that is the same
      as the target namespace of the module; otherwise a <a title="static error" class="termref" href="#dt-static-error">static
        error</a> is raised [<a href="#ERRXQST0048" title="err:XQST0048">err:XQST0048</a>]. The (prefix,URI) pair is added
      to the set of <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>. </p><p>The namespace prefix specified in a module declaration must not be <code>xml</code> or
        <code>xmlns</code>
               [<a href="#ERRXQST0070" title="err:XQST0070">err:XQST0070</a>], and must not be the same as any namespace prefix bound in
      the same module by a <a title="schema import" class="termref" href="#dt-schema-import">schema import</a>, by a <a title="namespace declaration" class="termref" href="#dt-namespace-declaration">namespace declaration</a>, or by a <a title="module import" class="termref" href="#dt-module-import">module import</a> with a different target namespace [<a href="#ERRXQST0033" title="err:XQST0033">err:XQST0033</a>].</p><p>Any <a title="module" class="termref" href="#dt-module">module</a> may import one or more library modules by means
      of a <a title="module import" class="termref" href="#dt-module-import">module import</a> that specifies the target
      namespace of the library modules to be imported. When a module imports one or more library
      modules, the variables and functions declared in the imported modules are added to the
        <a title="static context" class="termref" href="#dt-static-context">static context</a> and (where applicable) to the
        <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> of the importing module.</p><p>The following is an example of a module declaration:</p><div class="exampleInner"><pre>module namespace gis = "http://example.org/gis-functions";</pre></div></div><div class="div2">
<h3><a id="id-boundary-space-decls"/>5.3 <a href="#id-boundary-space-decls" style="text-decoration: none">Boundary-space Declaration</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-BoundarySpaceDecl"/><code><a href="#prod-xquery40-BoundarySpaceDecl">BoundarySpaceDecl</a></code></td><td>::=</td><td><code>"declare"  "boundary-space"  ("preserve"  |  "strip")</code></td></tr></tbody></table><p>
               [<a id="dt-boundary-space-decl" title="boundary-space declaration">Definition</a>: A <b>boundary-space
          declaration</b> sets the <a title="boundary-space policy" class="termref" href="#dt-boundary-space-policy">boundary-space
          policy</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>,
        overriding any implementation-defined default. Boundary-space policy controls whether
          <a title="boundary whitespace" class="termref" href="#dt-boundary-whitespace">boundary whitespace</a> is preserved by
        element constructors during processing of the query.] If boundary-space policy is
        <code>preserve</code>, boundary whitespace is preserved. If boundary-space policy is
        <code>strip</code>, boundary whitespace is stripped (deleted). A further discussion of
      whitespace in constructed elements can be found in <a href="#id-whitespace"><b>4.12.1.4 Boundary Whitespace</b></a>.</p><p>The following example illustrates a boundary-space declaration:</p><div class="exampleInner"><pre>declare boundary-space preserve;</pre></div><p>If a Prolog contains more than one boundary-space declaration, a <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0068" title="err:XQST0068">err:XQST0068</a>].</p></div><div class="div2">
<h3><a id="id-default-collation-declaration"/>5.4 <a href="#id-default-collation-declaration" style="text-decoration: none">Default Collation Declaration</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DefaultCollationDecl"/><code><a href="#prod-xquery40-DefaultCollationDecl">DefaultCollationDecl</a></code></td><td>::=</td><td><code>"declare"  "default"  "collation"  <a href="#doc-xquery40-DefaultCollationDecl-URILiteral">URILiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DefaultCollationDecl-URILiteral"/><code><a href="#prod-xquery40-URILiteral">URILiteral</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-DefaultCollationDecl-StringLiteral">StringLiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DefaultCollationDecl-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody></table><p>
               [<a id="dt-default-collation-decl" title="default collation declaration">Definition</a>: A <b>default
          collation declaration</b> sets the value of the <a title="default collation" class="termref" href="#dt-def-collation">default
          collation</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>,
        overriding any implementation-defined default.] The default collation is the
      collation that is used by functions and operators that require a collation if no other
      collation is specified. For example, the <code>gt</code> operator on strings is defined by a
      call to the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-compare"><code>fn:compare</code></a> function, which takes an optional collation parameter.
      Since the <code>gt</code> operator does not specify a collation, the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-compare"><code>fn:compare</code></a>
      function implements <code>gt</code> by using the default collation.</p><p>If neither the implementation nor the Prolog specifies a default collation, the Unicode
      codepoint collation (<code>http://www.w3.org/2005/xpath-functions/collation/codepoint</code>)
      is used. </p><p>The following example illustrates a default collation declaration:</p><div class="exampleInner"><pre>declare default collation "http://example.org/languages/Icelandic";</pre></div><p>If a default collation declaration specifies a collation by a relative URI, that relative URI
      is <a title="resolve" class="termref" href="#dt-resolve-relative-uri">resolved to an absolute URI</a> using the
        <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a>. If a Prolog contains more than
      one default collation declaration, or the value specified by a default collation declaration
      (after resolution of a relative URI, if necessary) is not present in <a title="statically known collations" class="termref" href="#dt-static-collations">statically known collations</a>, a <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0038" title="err:XQST0038">err:XQST0038</a>].</p></div><div class="div2">
<h3><a id="id-base-uri-decl"/>5.5 <a href="#id-base-uri-decl" style="text-decoration: none">Base URI Declaration</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-BaseURIDecl"/><code><a href="#prod-xquery40-BaseURIDecl">BaseURIDecl</a></code></td><td>::=</td><td><code>"declare"  "base-uri"  <a href="#doc-xquery40-BaseURIDecl-URILiteral">URILiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-BaseURIDecl-URILiteral"/><code><a href="#prod-xquery40-URILiteral">URILiteral</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-BaseURIDecl-StringLiteral">StringLiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-BaseURIDecl-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody></table><p>
               [<a id="dt-base-uri-decl" title="base URI declaration">Definition</a>: A <b>base URI declaration</b>
        specifies the <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a> property. The
          <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a> property is used when
        resolving relative URI references.] For example, the <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a> property is used when resolving relative
      references for <a title="module import" class="termref" href="#dt-module-import">module import</a> and for the
        <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-doc"><code>fn:doc</code></a> function.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>As discussed in the definition of <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base
          URI</a>, if there is no base URI declaration, or if the value of the declaration is
        a relative URI reference, then the value of the Static Base URI may depend on the location
        of the query, and it is permissible for this to vary between the static analysis phase and
        the dynamic evaluation phase.</p></div><p>The following is an example of a base URI declaration:</p><div class="exampleInner"><pre>declare base-uri "http://example.org";</pre></div><p>If a Prolog contains more than one base URI declaration, a <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0032" title="err:XQST0032">err:XQST0032</a>].</p><p>In the terminology of <a href="#RFC3986">[RFC3986]</a> Section 5.1, the URILiteral of the base URI
      declaration is considered to be a “base URI embedded in content”. If no base URI declaration
      is present, <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a> property is
      established according to the principles outlined in <a href="#RFC3986">[RFC3986]</a> Section
      5.1—that is, it defaults first to the base URI of the encapsulating entity, then to the
      URI used to retrieve the entity, and finally to an implementation-defined default. If the
      URILiteral in the base URI declaration is a relative URI, then it is made absolute by
      resolving it with respect to this same hierarchy. For example, if the URILiteral in the base
      URI declaration is <code>../data/</code>, and the query is contained in a file whose URI is
        <code>file:///C:/temp/queries/query.xq</code>, then the <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a> property is <code>file:///C:/temp/data/</code>.</p><p>It is not intrinsically an error if this process fails to establish an absolute base URI;
      however, the <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a> property is then
        <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>
               [<a href="#ERRXPST0001" title="err:XPST0001">err:XPST0001</a>]. When the <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base
        URI</a> property is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>, any attempt to use its
      value to <a title="resolve" class="termref" href="#dt-resolve-relative-uri">resolve a relative URI reference</a>
      will result in an error [<a href="#ERRXPST0001" title="err:XPST0001">err:XPST0001</a>]. </p></div><div class="div2">
<h3><a id="id-construction-declaration"/>5.6 <a href="#id-construction-declaration" style="text-decoration: none">Construction Declaration</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ConstructionDecl"/><code><a href="#prod-xquery40-ConstructionDecl">ConstructionDecl</a></code></td><td>::=</td><td><code>"declare"  "construction"  ("strip"  |  "preserve")</code></td></tr></tbody></table><p>
               [<a id="dt-construction-decl" title="construction declaration">Definition</a>: A <b>construction
          declaration</b> sets the <a title="construction mode" class="termref" href="#dt-construction-mode">construction
          mode</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>,
        overriding any implementation-defined default.] The construction mode governs the
      behavior of element and document node constructors. If construction mode is
        <code>preserve</code>, the type of a constructed element node is <code>xs:anyType</code>,
      and all attribute and element nodes copied during node construction retain their original
      types. If construction mode is <code>strip</code>, the type of a constructed element node is
        <code>xs:untyped</code>; all element nodes copied during node construction receive the type
        <code>xs:untyped</code>, and all attribute nodes copied during node construction receive the
      type <code>xs:untypedAtomic</code>.</p><p>The following example illustrates a construction declaration:</p><div class="exampleInner"><pre>declare construction strip;</pre></div><p>If a Prolog specifies more than one construction declaration, a <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0067" title="err:XQST0067">err:XQST0067</a>].</p></div><div class="div2">
<h3><a id="id-default-ordering-decl"/>5.7 <a href="#id-default-ordering-decl" style="text-decoration: none">Ordering Mode Declaration</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-decimal-format-decl">⬇</a> <a href="#id-extension-expressions">⬆</a></p><ol><li><p>
               The ordering mode declaration is retained for
               backwards compatibility reasons, but in XQuery 4.0 it is deprecated and has no useful effect.
       <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1339">1339</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1342">1342</a> 3 September 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OrderingModeDecl"/><code><a href="#prod-xquery40-OrderingModeDecl">OrderingModeDecl</a></code></td><td>::=</td><td><code>"declare"  "ordering"  ("ordered"  |  "unordered")</code></td></tr></tbody></table><p>
      The ordering mode declaration is retained from earlier XQuery versions,
      but in XQuery 4.0 it is deprecated and has no effect.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>That is to say, XQuery 4.0 always operates as if ordering mode were set to <code>ordered</code>
    in earlier versions.</p></div><p>If a Prolog contains more than one ordering mode declaration, a <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0065" title="err:XQST0065">err:XQST0065</a>].</p></div><div class="div2">
<h3><a id="id-empty-order-decl"/>5.8 <a href="#id-empty-order-decl" style="text-decoration: none">Empty Order Declaration</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-EmptyOrderDecl"/><code><a href="#prod-xquery40-EmptyOrderDecl">EmptyOrderDecl</a></code></td><td>::=</td><td><code>"declare"  "default"  "order"  "empty"  ("greatest"  |  "least")</code></td></tr></tbody></table><p>
               [<a id="dt-empty-order-decl" title="empty order declaration">Definition</a>: An <b>empty order
          declaration</b> sets the <a title="default order for empty sequences" class="termref" href="#dt-default-empty-order">default order for empty
          sequences</a> in the <a title="static context" class="termref" href="#dt-static-context">static context,</a>
        overriding any implementation-defined default. This declaration controls the processing of
        empty sequences and <code>NaN</code> values as ordering keys in an <code>order by</code>
        clause in a FLWOR expression.] An individual <code>order by</code> clause may
      override the default order for empty sequences by specifying <code>empty greatest</code> or
        <code>empty least</code>.</p><p>The following example illustrates an empty order declaration:</p><div class="exampleInner"><pre>declare default order empty least;</pre></div><p>If a Prolog contains more than one empty order declaration, a <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0069" title="err:XQST0069">err:XQST0069</a>].</p></div><div class="div2">
<h3><a id="id-copy-namespaces-decl"/>5.9 <a href="#id-copy-namespaces-decl" style="text-decoration: none">Copy-Namespaces Declaration</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CopyNamespacesDecl"/><code><a href="#prod-xquery40-CopyNamespacesDecl">CopyNamespacesDecl</a></code></td><td>::=</td><td><code>"declare"  "copy-namespaces"  <a href="#doc-xquery40-CopyNamespacesDecl-PreserveMode">PreserveMode</a>  ","  <a href="#doc-xquery40-CopyNamespacesDecl-InheritMode">InheritMode</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CopyNamespacesDecl-PreserveMode"/><code><a href="#prod-xquery40-PreserveMode">PreserveMode</a></code></td><td>::=</td><td><code>"preserve"  |  "no-preserve"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-CopyNamespacesDecl-InheritMode"/><code><a href="#prod-xquery40-InheritMode">InheritMode</a></code></td><td>::=</td><td><code>"inherit"  |  "no-inherit"</code></td></tr></tbody></table><p>
               [<a id="dt-copy-namespaces-decl" title="copy-namespaces declaration">Definition</a>: A
          <b>copy-namespaces declaration</b> sets the value of <a title="copy-namespaces mode" class="termref" href="#dt-copy-namespaces-mode">copy-namespaces mode</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>, 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.]
      Handling of namespace bindings by element constructors is described in <a href="#id-element-constructor"><b>4.12.1 Direct Element Constructors</b></a>.</p><p>The following example illustrates a copy-namespaces declaration:</p><div class="exampleInner"><pre>declare copy-namespaces preserve, no-inherit;</pre></div><p>If a Prolog contains more than one copy-namespaces declaration, a <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0055" title="err:XQST0055">err:XQST0055</a>].</p></div><div class="div2">
<h3><a id="id-decimal-format-decl"/>5.10 <a href="#id-decimal-format-decl" style="text-decoration: none">Decimal Format Declaration</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-schema-import">⬇</a> <a href="#id-default-ordering-decl">⬆</a></p><ol><li><p>
         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.
      <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1048">1048</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1250">1250</a> 3 June 2024]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DecimalFormatDecl"/><code><a href="#prod-xquery40-DecimalFormatDecl">DecimalFormatDecl</a></code></td><td>::=</td><td><code>"declare"  (("decimal-format"  <a href="#doc-xquery40-DecimalFormatDecl-EQName">EQName</a>)  |  ("default"  "decimal-format"))  (<a href="#doc-xquery40-DecimalFormatDecl-DFPropertyName">DFPropertyName</a>  "="  <a href="#doc-xquery40-DecimalFormatDecl-StringLiteral">StringLiteral</a>)*</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DecimalFormatDecl-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DecimalFormatDecl-DFPropertyName"/><code><a href="#prod-xquery40-DFPropertyName">DFPropertyName</a></code></td><td>::=</td><td><code>"decimal-separator"  |  "grouping-separator"  |  "infinity"  |  "minus-sign"  |  "NaN"  |  "percent"  |  "per-mille"  |  "zero-digit"  |  "digit"  |  "pattern-separator"  |  "exponent-separator"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DecimalFormatDecl-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody></table><p>
               [<a id="dt-decimal-format-decl" title="decimal-format         declaration">Definition</a>: A <b>decimal format
          declaration</b> adds a decimal format to the <a title="statically known decimal formats" class="termref" href="#dt-static-decimal-formats">statically known decimal formats</a>, which define the properties used to format
        numbers using the <code>fn:format-number()</code> function], as described in
      <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>. 
      
      If the form <code>decimal-format EQName</code> is used, then the declaration 
        defines the properties of the decimal format whose name is <code>EQName</code>, while the form <code>default decimal-format</code> 
        defines the properties of the unnamed decimal format. The declaration contains a set of 
        (<code>DFPropertyName</code>, <code>StringLiteral</code>) pairs, where the <code>DFPropertyName</code> is the name 
        of the property and the <code>StringLiteral</code> is its value. The valid values and default values for each 
        property are defined in <a title="statically known decimal formats" class="termref" href="#dt-static-decimal-formats">statically known decimal formats</a>.
      </p><p>If a format declares no properties, default values are
      used for all properties.</p><p>Error conditions are defined as follows:</p><ul><li><p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> for a query prolog to contain
        two decimal format declarations with the same name, or to contain two default decimal format
        declarations [<a href="#ERRXQST0111" title="err:XQST0111">err:XQST0111</a>].</p></li><li><p>It is a <a title="static error" class="termref" href="#dt-static-error">static
        error</a> for a decimal format declaration to define the same property more than once
        [<a href="#ERRXQST0114" title="err:XQST0114">err:XQST0114</a>].</p></li><li><p>It is a <a title="static error" class="termref" href="#dt-static-error">static
        error</a> for a decimal format declaration to specify a value that is not valid for a
        given property, as described in <a title="statically known decimal formats" class="termref" href="#dt-static-decimal-formats">statically known
          decimal formats</a>
                     [<a href="#ERRXQST0097" title="err:XQST0097">err:XQST0097</a>].</p></li><li><p>It is a <a title="static error" class="termref" href="#dt-static-error">static
        error</a> if, for any named or unnamed decimal format, the properties identifying
        <b>marker</b> characters to be used in a picture string do identify distinct values [<a href="#ERRXQST0098" title="err:XQST0098">err:XQST0098</a>].</p><p>The following properties identify <b>marker</b> characters used in a picture string:
        <a title="decimal-separator" class="termref" href="#id-static-decimal-format-decimal-separator">decimal-separator</a>, 
        <a title="exponent-separator" class="termref" href="#id-static-decimal-format-exponent-separator">exponent-separator</a>,
        <a title="grouping-separator" class="termref" href="#id-static-decimal-format-grouping-separator">grouping-separator</a>, 
        <a title="percent" class="termref" href="#id-static-decimal-format-percent">percent</a>, 
        <a title="per-mille" class="termref" href="#id-static-decimal-format-per-mille">per-mille</a>, 
        the family of ten decimal digits starting with <a title="zero-digit" class="termref" href="#id-static-decimal-format-zero-digit">zero-digit</a>, 
        <a title="digit" class="termref" href="#id-static-decimal-format-digit">digit</a>, 
        and <a title="pattern-separator" class="termref" href="#id-static-decimal-format-pattern-separator">pattern-separator</a>.</p></li></ul><div class="example"><p>The following query formats numbers using two different decimal format declarations:</p><div class="exampleInner"><pre>
declare decimal-format local:de decimal-separator = "," grouping-separator = "."; 
declare decimal-format local:en decimal-separator = "." grouping-separator = ","; 
       
let $numbers := (1234.567, 789, 1234567.765) 
for $i in $numbers
return ( 
  format-number($i, "#.###,##", "local:de"), 
  format-number($i, "#,###.##", "local:en") 
)</pre></div><p>The output of this query is:</p><div class="exampleInner"><pre>1.234,57 1,234.57 789 789 1.234.567,76 1,234,567.76</pre></div></div></div><div class="div2">
<h3><a id="id-schema-import"/>5.11 <a href="#id-schema-import" style="text-decoration: none">Schema Import</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-namespace-declaration">⬇</a> <a href="#id-decimal-format-decl">⬆</a></p><ol><li><p>In previous versions the interpretation of location hints in 
        <code>import schema</code> 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.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/647">647</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/659">659</a> 24 October 2023]</i></p></li><li><p>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.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/451">451</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/635">635</a>]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SchemaImport"/><code><a href="#prod-xquery40-SchemaImport">SchemaImport</a></code></td><td>::=</td><td><code>"import"  "schema"  <a href="#doc-xquery40-SchemaImport-SchemaPrefix">SchemaPrefix</a>?  <a href="#doc-xquery40-SchemaImport-URILiteral">URILiteral</a>  ("at"  (<a href="#doc-xquery40-SchemaImport-URILiteral">URILiteral</a> ++ ","))?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SchemaImport-SchemaPrefix"/><code><a href="#prod-xquery40-SchemaPrefix">SchemaPrefix</a></code></td><td>::=</td><td><code>("namespace"  <a href="#prod-xquery40-NCName">NCName</a>  "=")  |  ("fixed"?  "default"  "element"  "namespace")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SchemaImport-URILiteral"/><code><a href="#prod-xquery40-URILiteral">URILiteral</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-SchemaImport-StringLiteral">StringLiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-SchemaImport-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody></table><p>
               [<a id="dt-schema-import" title="schema import">Definition</a>: A <b>schema import</b> imports the
        element declarations, attribute declarations, and type definitions from a schema into the
          <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a>. For each named user-defined
        simple type in the schema, schema import also adds a corresponding <a title="constructor function" class="termref" href="#dt-constructor-function">constructor function</a>. ] The schema to be
      imported is identified by its <a title="target namespace" class="termref" href="#dt-target-namespace">target namespace</a>.
      The schema import may bind a namespace prefix to the target namespace of the imported schema,
      adding the (prefix, URI) pair to the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known
        namespaces</a>, or it may declare that target namespace to be the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>. The schema import may
      also provide optional hints for locating the schema.</p><p>The namespace prefix specified in a schema import must not be <code>xml</code> or
        <code>xmlns</code>
               [<a href="#ERRXQST0070" title="err:XQST0070">err:XQST0070</a>], and must not be the same as any namespace prefix bound in
      the same module by another schema import, a <a title="module import" class="termref" href="#dt-module-import">module
        import</a>, a <a title="namespace declaration" class="termref" href="#dt-namespace-declaration">namespace declaration</a>,
      or a <a title="module import" class="termref" href="#dt-module-import">module declaration</a>
               [<a href="#ERRXQST0033" title="err:XQST0033">err:XQST0033</a>]. </p><div class="note"><p class="prefix"><b>Note:</b></p><p>If schema definitions from the <code>xml</code> namespace
    are to be used (for example, <code>schema-attribute(xml:space)</code>, then the prolog should
      include a declaration in the form <code>import schema "http://www.w3.org/XML/1998/namespace"</code>.
    No prefix should be supplied (the <code>xml</code> prefix is predeclared), and no location hint
    should be provided (the schema definitions for the namespace are built in, and cannot be varied).</p></div><p>If the schema import declaration specifies <code>default element namespace</code>
      then the prolog must not contain a <a title="namespace declaration" class="termref" href="#dt-namespace-declaration">namespace declaration</a>
      that specifies <code>default element namespace</code> or <code>default type namespace</code>.</p><p>If the keyword <code>"fixed"</code>, is present, the 
      <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> is fixed throughout the module,
      and is not affected by default namespace declarations (<code>xmlns=""</code>) appearing
      on direct element constructors.</p><p> The first <a href="#prod-xquery40-URILiteral">URILiteral</a> in a schema import specifies the target
      namespace of the schema to be imported.
    </p><p>
      If the target
      namespace is <code>http://www.w3.org/2005/xpath-functions</code> then the schema described in 
      <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#schemata">D Schemas</a> is imported; any location hints are ignored.
    </p><p>A schema import that specifies a zero-length string as target namespace is considered to
      import a schema that has no target namespace. Such a schema import must not bind a namespace
      prefix [<a href="#ERRXQST0057" title="err:XQST0057">err:XQST0057</a>], but it may set the default element and/or type namespace
      to a zero-length string (representing “no namespace”), thus enabling the definitions in the
      imported namespace to be referenced. If the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> is not set to "no
      namespace", <span>the only way to reference the definitions in an imported schema that has no
        target namespace is using the EQName syntax <code>Q{}local-name</code>
               </span>.</p><p>The <a href="#prod-xquery40-URILiteral">URILiterals</a> 
      that follow the <code>at</code> keyword are 
      optional location hints, intended to allow a processor to locate schema documents containing 
      definitions of the required schema components in the target namespace. Processors <span class="verb">may</span> 
      interpret or disregard these hints in an <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> way. The preferred strategy,
      which <span class="verb">should</span> be used by default unless the user indicates otherwise, 
      is as follows:</p><ol class="enumar"><li><p>If the target namespace is one for which the processor has built-in knowledge,
      for example the schema for a <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespace</a>, the location hints
      <span class="verb">should</span> be ignored, and the built-in schema used in preference.</p></li><li><p>In other cases, the location hints are taken in order, treating them as URI references relative
        to the static base URI of the query module.</p></li><li><p>If the first location hint cannot be successfully dereferenced, then that location hint is disregarded 
        (optionally with a warning), and the process continues with the next location hint, until
        one is found that can be successfully dereferenced; if none of the location hints can be dereferenced, 
        then a static error is reported.</p></li><li><p>The dereferencing of a location hint <span class="verb">may</span> make use of <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>
        indirection mechanisms such as resolver callbacks and catalog files.</p></li><li><p>If a location hint is successfully dereferenced, but yields a resource that cannot be parsed as a valid
        XSD schema document with the correct target namespace, then a static error is reported.</p></li><li><p>If a valid schema document is located, then it is combined with the schema documents obtained
        from other import schema declarations, in the same way as a schema is assembled from multiple
        schema documents referenced using <code>xs:import</code> declarations. This implies that the 
        several schema documents must together comprise a valid schema, for example there cannot be two 
        different type definitions with the same name.</p></li><li><p>Once one location hint has been successfully processed, subsequent location hints are
      ignored.</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>Processors that adopted a different strategy in earlier releases <span class="verb">may</span>
      continue to use that strategy by default, in order to retain compatibility; however such
      processors <span class="verb">should</span> offer the above strategy as an option. </p><p>The process described above is not intended to be totally prescriptive, or to guarantee complete 
      interoperability. Processors are likely to exhibit variations, depending both on design decisions made
      by the product vendor, and on decisions made when configuring the platform
      and network infrastructure on which it runs. For example, when retrieving HTTP resources,
      the details of the HTTP request are likely to vary, and the criteria used to decide whether
      a request was successful may also vary. In addition, the XSD specification itself describes
      some aspects of the process incompletely, including for example the criteria used to decide 
      whether two components (such as type definitions) should be considered identical.</p></div><p>Different query modules may import different schemas, but there is a requirement that all the schemas
      used by a query <span class="verb">must</span> be compatible. The rules for compatibility are defined
      in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#schema-consistency">4.1.2 Schema Consistency</a>. This means, for example:</p><ul><li><p>If any schema component (such as an element declaration or complex type definition)
      is imported into more than one query module, the definitions of these components must effectively 
      be the same.</p></li><li><p>This leaves room, however, for some differences between modules. For example, 
      the substitution group membership of an element declaration may vary between one module
      and another, depending on what other element declarations are present in the schema. This
      means that an element can be validated in one module and passed as a function parameter
      to another module in which the element would be considered invalid. Any static type inferencing
      that is performed must take such possibilities into account; this is particularly important
      if query modules are compiled independently from one another.</p></li></ul><p>
      If the target
      namespace is <code>http://www.w3.org/2005/xpath-functions</code> then the schema described in 
      <a href="https://www.w3.org/TR/xpath-functions-31/#schemata">
         
            C Schemas
      </a><sup><small>FO31</small></sup> is imported; any location hints are ignored.
    </p><p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
               [<a href="#ERRXQST0058" title="err:XQST0058">err:XQST0058</a>] if more than one schema import in the same <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a> specifies the same target namespace. It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
               [<a href="#ERRXQST0059" title="err:XQST0059">err:XQST0059</a>] if the implementation is not able to process a schema
      import by finding a valid schema with the specified target namespace. 
      
            </p><p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
               [<a href="#ERRXQST0012" title="err:XQST0012">err:XQST0012</a>] if the set of definitions contained in all schemas imported
      by a Prolog do not satisfy the conditions for schema validity specified in Sections 3 and 5 of
        <a href="#XMLSchema10">[XML Schema 1.0]</a> or <a href="#XMLSchema11">[XML Schema 1.1]</a> Part 1: in particular, each definition
      must be valid, complete, and unique.</p><p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
               [<a href="#ERRXQST0149" title="err:XQST0149">err:XQST0149</a>] if the schemas imported by different modules of a query
      are not compatible as defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#schema-consistency">4.1.2 Schema Consistency</a>.</p><p>The following example imports a schema, specifying both its target namespace and its
      location, and binding the prefix <code>soap</code> to the target namespace:</p><div class="exampleInner"><pre>import schema namespace soap="http://www.w3.org/2003/05/soap-envelope" 
  at "http://www.w3.org/2003/05/soap-envelope/";</pre></div><p>The following example imports a schema by specifying only its target namespace, and makes it
      the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>:</p><div class="exampleInner"><pre>import schema default element namespace "http://example.org/abc";</pre></div><p>The following example imports a schema that has no target namespace, providing a location
      hint, and sets the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> to “no namespace” so that the definitions in
      the imported schema can be referenced:</p><div class="exampleInner"><pre>import schema default element namespace "" at "http://example.org/xyz.xsd";</pre></div><p>The following example imports a schema that has no target namespace and sets the 
      <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> to “no namespace”. 
      Since no location hint is provided, it is up to the
      implementation to find the schema to be imported.</p><div class="exampleInner"><pre>import schema default element namespace "";</pre></div></div><div class="div2">
<h3><a id="id-module-import"/>5.12 <a href="#id-module-import" style="text-decoration: none">Module Import</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ModuleImport"/><code><a href="#prod-xquery40-ModuleImport">ModuleImport</a></code></td><td>::=</td><td><code>"import"  "module"  ("namespace"  <a href="#prod-xquery40-NCName">NCName</a>  "=")?  <a href="#doc-xquery40-ModuleImport-URILiteral">URILiteral</a>  ("at"  (<a href="#doc-xquery40-ModuleImport-URILiteral">URILiteral</a> ++ ","))?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ModuleImport-URILiteral"/><code><a href="#prod-xquery40-URILiteral">URILiteral</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ModuleImport-StringLiteral">StringLiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ModuleImport-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody></table><p>
               [<a id="dt-module-import" title="module import">Definition</a>: A <b>module import</b> imports the
        public variable declarations, public function declarations<span>, 
          and public item type declarations</span> from one or more <a title="library module" class="termref" href="#dt-library-module">library modules</a> into the <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a>, <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a>
                  <span>,
          or <a title="in-scope named item types" class="termref" href="#dt-in-scope-named-item-types">in-scope named item types</a>
                  </span> of the importing <a title="module" class="termref" href="#dt-module">module</a>.] Each module import names a <a title="target namespace" class="termref" href="#dt-target-namespace">target namespace</a> and imports an <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> set of modules that share
      this target namespace. The module import may bind a namespace prefix to the target namespace,
      adding the (prefix, URI) pair to the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known
        namespaces</a>, and it may provide optional hints for locating the modules to be
      imported.</p><p>If a module <var>A</var> imports module <var>B</var>, the static context of module
      <var>A</var> will contain the <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a>, <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a>
               <span>,
            or <a title="in-scope named item types" class="termref" href="#dt-in-scope-named-item-types">in-scope named item types</a>
               </span> of
      module <var>B</var>, and the dynamic context of module <var>A</var> will contain the
        public <a title="variable values" class="termref" href="#dt-variable-values">variable values</a> and <a title="dynamically known function definitions" class="termref" href="#dt-dynamically-known-function-definitions">dynamically known function definitions</a> of module <var>B</var>. It will
      not contain:</p><ul><li><p>Private functions, variables, and item types declared in <var>B</var>.</p></li><li><p>Functions, variables, and item types not
      declared directly in <var>B</var>, but imported from some other library module.</p></li><li><p>Other components such as <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a> or <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a> declared in <var>B</var>.</p></li></ul><p>The following example illustrates a module import:</p><div class="exampleInner"><pre>import module namespace gis="http://example.org/gis-functions";</pre></div><p>If a query imports the same module via multiple paths, only one instance of the module is
      imported. Because only one instance of a module is imported, there is only one instance of
      each variable declared in a module's prolog.</p><p>A module may import its own target namespace (this is interpreted as importing an <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> set of other modules that
      share its target namespace.)</p><p>The namespace prefix specified in a module import must not be <code>xml</code> or
        <code>xmlns</code>
               [<a href="#ERRXQST0070" title="err:XQST0070">err:XQST0070</a>], and must not be the same as any namespace prefix bound in
      the same module by another module import, a <a title="schema import" class="termref" href="#dt-schema-import">schema
        import</a>, a <a title="namespace declaration" class="termref" href="#dt-namespace-declaration">namespace declaration</a>,
      or a <a title="module declaration" class="termref" href="#dt-module-declaration">module declaration</a> with a different target
      namespace [<a href="#ERRXQST0033" title="err:XQST0033">err:XQST0033</a>].</p><p>The first <a href="#prod-xquery40-URILiteral">URILiteral</a> in a module import must be of nonzero length
        [<a href="#ERRXQST0088" title="err:XQST0088">err:XQST0088</a>], and specifies the target namespace of the modules to be
      imported. The <a href="#prod-xquery40-URILiteral">URILiterals</a> that follow the <code>at</code> keyword are 
      optional location hints, and can be interpreted or disregarded in
      an <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> way.</p><p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
               [<a href="#ERRXQST0047" title="err:XQST0047">err:XQST0047</a>] if more than one module import in a <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a> specifies the same target namespace. It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
               [<a href="#ERRXQST0059" title="err:XQST0059">err:XQST0059</a>] if the implementation is not able to process a module
      import by finding a valid module definition with the specified target namespace. It is a
        <a title="static error" class="termref" href="#dt-static-error">static error</a> if two or more variables declared or
      imported by a <a title="module" class="termref" href="#dt-module">module</a> have equal <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a> (as defined by the <code>eq</code>
      operator) [<a href="#ERRXQST0049" title="err:XQST0049">err:XQST0049</a>].</p><p>Module imports are not transitive. Importing a module provides access only to 
      declarations contained directly in the imported module. For example, if 
      module <var>A</var> imports
      module <var>B</var>, and module <var>B</var> imports module <var>C</var>, 
      module <var>A</var> does not have access to the functions and
      variables declared in module <var>C</var>. </p><div class="example">
<div class="exampleHeader"><a id="d2e46835"/>Example: Schema Information and Module Import</div><p>A module import does not import schema definitions from the imported module. In the
        following query, the type <code>geometry:triangle</code> is not defined, even if it is known in the
        imported module, so the variable declaration raises an error [<a href="#ERRXPST0051" title="err:XPST0051">err:XPST0051</a>]:</p><div class="exampleInner"><pre>(: Error - geometry:triangle is not defined :) 
import module namespace geo = "http://example.org/geo-functions"; 
declare variable $triangle as geometry:triangle := geo:make-triangle(); 
$triangle</pre></div><p>Without the type declaration for the variable, the variable declaration succeeds:</p><div class="exampleInner"><pre>import module namespace geo = "http://example.org/geo-functions";
declare variable $triangle := geo:make-triangle();
$triangle</pre></div><p>Importing the schema that defines the type of the variable,
      the variable declaration succeeds:</p><div class="exampleInner"><pre>import schema namespace geometry = "http://example.org/geo-schema-declarations"; 
import module namespace geo = "http://example.org/geo-functions"; 
declare variable $triangle as geometry:triangle := geo:make-triangle();
$triangle</pre></div></div><div class="div3">
<h4><a id="id-module-handling-module-uris"/>5.12.1 <a href="#id-module-handling-module-uris" style="text-decoration: none">The Target Namespace of a Module</a></h4><p>The target namespace of a module should be treated in the same way as other namespace
        URIs.</p><p>To maximize interoperability, query authors should use a string that is a valid absolute
        IRI.</p><p>Implementions must accept any string of Unicode characters. Target namespace URIs are
        compared using the Unicode codepoint collation rather than any concept of semantic
        equivalence.</p><p>Implementations may provide mechanisms allowing the target namespace URI to be used as
        input to a process that delivers the module as a resource, for example a catalog, module
        repository, or URI resolver. For interoperability, such mechanisms should not prevent the
        user from choosing an arbitrary URI for naming a module.</p><p>Similarly, implementations may perform syntactic transformations on the target namespace
        URI to obtain the names of related resources, for example to implement a convention relating
        the name or location of compiled code to the target namespace URI; but again, such
        mechanisms should not prevent the user from choosing an arbitrary target namespace URI.</p><p>As with other namespace URIs, it is common practice to use target namespace URIs whose
        scheme is <code>http</code> and whose authority part uses a DNS domain name under the control of the
        user.</p><p>The specifications allow, and some users might consider it good practice, for the target
        namespace URI of a function library to be the same as the namespace URI of the XML
        vocabulary manipulated by the functions in that library.</p></div><div class="div3">
<h4><a id="id-module-handling-multiple-same"/>5.12.2 <a href="#id-module-handling-multiple-same" style="text-decoration: none">Multiple Modules with the same Namespace</a></h4><p>Several different modules with the same target namespace can be used in the same query. The
        names of public variables and public functions must be unique within the <a title="static context" class="termref" href="#dt-static-context">static context</a> of a query: this means that if two modules with
        the same target namespace URI are used in the same query, the names of the public variables
        and functions in their module contexts must not overlap.</p><p>If one module contains an <code>import module</code> declaration with the target namespace
          <code>M</code>, then all public variables and public functions in the contexts of modules
        whose target namespace is <code>M</code> must be accessible in the importing module,
        regardless whether the participation of the imported module was directly due to this "import
        module" declaration.</p></div><div class="div3">
<h4><a id="id-module-handling-location-uris"/>5.12.3 <a href="#id-module-handling-location-uris" style="text-decoration: none">Location URIs</a></h4><p>The term “location URIs” refers to the URIs in the <code>at</code> clause of an
        <code>import module</code> declaration.</p><p>Products should (by default or at user option) take account of all the location URIs in an
        <code>import module</code> declaration, treating each location URI as a reference to a module with the
        specified target namespace URI. Location URIs should be made absolute with respect to the
        static base URI of the module containing the <code>import module</code> declaration where they appear.
        The mapping from location URIs to module source code or compiled code MAY be done in any way
        convenient to the implementation. If possible given the product’s architecture, security
        requirements, etc, the product should allow this to fetch the source code of the module to
        use the standard web mechanisms for dereferencing URIs in standard schemes such as the
        <code>http</code> URI scheme.</p><p>When the same absolutized location URI is used more than once, either in the same
        <code>import module</code> declaration or in different
        <code>import module</code> declarations within the same query, a
        single copy of the resource containing the module is loaded. When different absolutized
        location URIs are used, each results in a single module being loaded, unless the
        implementation is able to determine that the different URIs are references to the same
        resource. No error due to duplicate variable or functions names should arise from the same
        module being imported more than once, so long as the absolute location URI is the same in
        each case.</p><p>Implementations must report a static error if a location URI cannot be resolved after all
        available recovery strategies have been exhausted.</p></div><div class="div3">
<h4><a id="id-module-handling-cycles"/>5.12.4 <a href="#id-module-handling-cycles" style="text-decoration: none">Cycles</a></h4><p>Implementations must resolve cycles in the import graph, either at the level of target
        namespace URIs or at the level of location URIs, and ensure that each module is imported
        only once. </p></div></div><div class="div2">
<h3><a id="id-namespace-declaration"/>5.13 <a href="#id-namespace-declaration" style="text-decoration: none">Namespace Declaration</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-default-namespace">⬇</a> <a href="#id-schema-import">⬆</a></p><ol><li><p>
        All implementations must now predeclare the namespace prefixes
        <code>math</code>, <code>map</code>, <code>array</code>, and <code>err</code>. In XQuery 3.1 it was permitted
        but not required to predeclare these namespaces.
      </p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamespaceDecl"/><code><a href="#prod-xquery40-NamespaceDecl">NamespaceDecl</a></code></td><td>::=</td><td><code>"declare"  "namespace"  <a href="#prod-xquery40-NCName">NCName</a>  "="  <a href="#doc-xquery40-NamespaceDecl-URILiteral">URILiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamespaceDecl-URILiteral"/><code><a href="#prod-xquery40-URILiteral">URILiteral</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-NamespaceDecl-StringLiteral">StringLiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamespaceDecl-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody></table><p>
               [<a id="dt-namespace-declaration" title="namespace declaration">Definition</a>: A <b>namespace
          declaration</b> declares a namespace prefix and associates it with a namespace URI,
        adding the (prefix, URI) pair to the set of <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically
          known namespaces</a>.] The namespace declaration is in scope throughout the
      query in which it is declared, unless it is overridden by a <a title="namespace declaration attribute" class="termref" href="#dt-namespace-decl-attr">namespace declaration attribute</a> in a <a title="direct element constructor" class="termref" href="#dt-direct-elem-const">direct element constructor</a>.</p><p>If the URILiteral part of a namespace declaration is a zero-length string, any existing
      namespace binding for the given prefix is removed from the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>. This feature provides a way to remove predeclared
      namespace prefixes such as <code>local</code>.</p><p>The following query illustrates a namespace declaration:</p><div class="exampleInner"><pre>
declare namespace foo = "http://example.org";
&lt;foo:bar&gt; Lentils &lt;/foo:bar&gt;</pre></div><p>In the query result, the newly created node is in the namespace associated with the namespace
      URI <code>http://example.org</code>.</p><p>The namespace prefix specified in a namespace declaration must not be <code>xml</code> or
        <code>xmlns</code>
               [<a href="#ERRXQST0070" title="err:XQST0070">err:XQST0070</a>]. The namespace URI specified in a namespace declaration
      must not be <code>http://www.w3.org/XML/1998/namespace</code> or
        <code>http://www.w3.org/2000/xmlns/</code>
               [<a href="#ERRXQST0070" title="err:XQST0070">err:XQST0070</a>]. The namespace prefix specified in a namespace declaration
      must not be the same as any namespace prefix bound in the same module by a <a title="module import" class="termref" href="#dt-module-import">module import</a>, <a title="schema import" class="termref" href="#dt-schema-import">schema
        import</a>, <a title="module import" class="termref" href="#dt-module-import">module declaration</a>, or another
      namespace declaration [<a href="#ERRXQST0033" title="err:XQST0033">err:XQST0033</a>]. </p><p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
               [<a href="#ERRXPST0081" title="err:XPST0081">err:XPST0081</a>] if an expression contains a <a title="lexical QName" class="termref" href="#dt-qname">lexical
        QName</a> with a namespace prefix that is not in the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>.</p><p>XQuery has several predeclared namespace prefixes, which are listed in
      <a href="#id-namespaces-and-qnames"><b>2.1.4 Namespaces and QNames</b></a>.
        These prefixes may be used without an explicit declaration; they are present in the
        <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>
        before each query is processed. They may be overridden by
        <a title="namespace declaration" class="termref" href="#dt-namespace-declaration">namespace declarations</a> in a <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a> or by <a title="namespace declaration attribute" class="termref" href="#dt-namespace-decl-attr">namespace
        declaration attributes</a> on constructed elements (however, the prefix
        <code>xml</code> must not be redeclared, and no other prefix may be bound to the namespace
      URI associated with the prefix <code>xml</code>
               [<a href="#ERRXQST0070" title="err:XQST0070">err:XQST0070</a>]).
    </p><p>Additional predeclared namespace prefixes may be added to the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a> by an implementation.</p><p>When element or attribute names are compared, they are considered identical if the local
      parts and namespace URIs match on a codepoint basis. Namespace prefixes need not be identical
      for two names to match, as illustrated by the following example:</p><div class="exampleInner"><pre>
declare namespace xx = "http://example.org";

let $node := &lt;foo:bar xmlns:foo = "http://example.org"&gt;
  &lt;foo:bing&gt; Lentils &lt;/foo:bing&gt;
&lt;/foo:bar&gt;
return $node/xx:bing</pre></div><p>Although the namespace prefixes <code>xx</code> and <code>foo</code> differ, both are bound
      to the namespace URI <code>http://example.org</code>. Since <code>xx:bing</code> and
        <code>foo:bing</code> have the same local name and the same namespace URI, they match. The
      output of the above query is as follows.</p><div class="exampleInner"><pre>
&lt;foo:bing xmlns:foo="http://example.org"&gt; Lentils &lt;/foo:bing&gt;</pre></div></div><div class="div2">
<h3><a id="id-default-namespace"/>5.14 <a href="#id-default-namespace" style="text-decoration: none">Default Namespace Declaration</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-variable-declarations">⬇</a> <a href="#id-namespace-declaration">⬆</a></p><ol><li><p>
        The <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> 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.
      <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/65">65</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/753">753</a> 31 October 2023]</i></p></li><li><p>
        The <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> can be set to the value <code>##any</code>,
        allowing unprefixed names in axis steps to match elements with a given local name in any namespace.
      <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/296">296</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1181">1181</a> 30 April 2023]</i></p></li><li><p>
        The effect of not declaring a default function namespace has changed: user-defined functions can
        now be in no namespace, and a search for an unprefixed function name will be resolved first
        against functions in no namespace, and only then against functions in the standard function namespace.
      <i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/657">657</a> <a href="https://github.com/qt4cg/qtspecs/issues/2235">2235</a> PRs <a href="https://github.com/qt4cg/qtspecs/pull/2200">2200</a> <a href="https://github.com/qt4cg/qtspecs/pull/2236">2236</a> 7 October 2025]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DefaultNamespaceDecl"/><code><a href="#prod-xquery40-DefaultNamespaceDecl">DefaultNamespaceDecl</a></code></td><td>::=</td><td><code>"declare"  "fixed"?  "default"  ("element"  |  "function")  "namespace"  <a href="#doc-xquery40-DefaultNamespaceDecl-URILiteral">URILiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DefaultNamespaceDecl-URILiteral"/><code><a href="#prod-xquery40-URILiteral">URILiteral</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-DefaultNamespaceDecl-StringLiteral">StringLiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-DefaultNamespaceDecl-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody></table><p>
               <b>Default namespace declarations</b> can be used in a <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a> to facilitate the use of unprefixed QNames.</p><p>The namespace URI specified in a default namespace declaration must not be
        <code>http://www.w3.org/XML/1998/namespace</code> or
        <code>http://www.w3.org/2000/xmlns/</code>
               [<a href="#ERRXQST0070" title="err:XQST0070">err:XQST0070</a>].</p><p>There are two kinds of default namespace declarations, described in the following sections.</p><div class="div3">
<h4><a id="id-default-element-namespace-declaration"/>5.14.1 <a href="#id-default-element-namespace-declaration" style="text-decoration: none">Default Element Namespace Declaration</a></h4><p>A <b>default element namespace declaration</b> declares how unprefixed element and type
          names are to be interpreted. The relevant value 
          is recorded as the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> in the
          <a title="static context" class="termref" href="#dt-static-context">static context</a> for the query module. A <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a> may contain at most one default element namespace declaration
          <span>and it must not contain
          both a default element namespace declaration and an <code>import schema</code> declaration
            that specifies a default element namespace</span>
                  [<a href="#ERRXQST0066" title="err:XQST0066">err:XQST0066</a>].</p><p>The <code>URILiteral</code> may take one of the following forms:</p><ul><li><p>A namespace URI. This namespace will typically be used for unprefixed names appearing
            where an element or type name is expected.</p></li><li><p>The empty string <code>""</code>. In this case unprefixed names appearing where
              an element or type name is expected are treated as being in no namespace: the
              <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> is set to <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>.</p></li><li><p>The string <code>"##any"</code>. In this case an unprefixed name appearing
              as a <a href="#prod-xquery40-NameTest">NameTest</a> in an axis step whose principal node kind is element
              is interpreted as a wildcard (the unprefixed name <code>N</code> is treated as equivalent
              to the wildcard <code>*:N</code>); an unprefixed name used appearing where an item type name
              is expected is interpreted as a local name in namespace <code>http://www.w3.org/2001/XMLSchema</code>,
              while an unprefixed name appearing in any other context
              where an element or type name is expected is treated as being in no namespace.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>To take an example, older versions of the internet index of RFCs (requests for comments)
              use the namespace URI <code>http://www.rfc-editor.org/rfc-index</code>, while newer
              versions use <code>https://www.rfc-editor.org/rfc-index</code> (note the change of URI scheme).
              XPath code that needs to work with either version can be simplified by setting the
              default namespace to <code>##any</code>: but be aware that this might lead to spurious matching
              of names in an unrelated namespace.</p></div></li></ul><p>The following example illustrates the declaration of a
          default namespace for elements and types:</p><div class="exampleInner"><pre>declare default element namespace "http://example.org/names";</pre></div><p>If no default element namespace declaration is present, unprefixed element and type
          names are in no namespace (however, an implementation may define a different default as
          specified in <a href="#id-xq-static-context-components"><b>B.1 Static Context Components</b></a>.)</p><p>If the keyword <code>"fixed"</code>, is present, the 
          <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> is fixed throughout the module,
          and is not affected by default namespace declarations (<code>xmlns=""</code>) appearing
          on direct element constructors.</p></div><div class="div3">
<h4><a id="id-default-function-namespace-declaration"/>5.14.2 <a href="#id-default-function-namespace-declaration" style="text-decoration: none">Default Function Namespace Declaration</a></h4><p>A <b>default function namespace declaration</b> declares a namespace URI that is
          associated with unprefixed function names in 
          <a title="static function call" class="termref" href="#dt-static-function-call">static function calls</a> and 
          <a title="named function reference" class="termref" href="#dt-named-function-ref">named function references</a>. It also
          affects the interpretation of unprefixed <a title="lexical QName" class="termref" href="#dt-qname">lexical QNames</a>
          used in function declarations.</p><p>The following example illustrates the declaration of a default function namespace:</p><div class="exampleInner"><pre>declare default function namespace "http://www.w3.org/2005/xpath-functions/math";</pre></div><p>A <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a> may contain at most one
          default function namespace declaration [<a href="#ERRXQST0066" title="err:XQST0066">err:XQST0066</a>].</p><p>There are three cases to consider.</p><ol class="enumar"><li><p>If there is an explicit default function namespace declaration and the
          <code>StringLiteral</code> is a zero-length string, the
          default function namespace is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>.</p><p>In this case:</p><ol class="enumla"><li><p>Any function declaration using an unprefixed <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> declares a function
              in no namespace.</p></li><li><p>Any <a title="static function call" class="termref" href="#dt-static-function-call">static function call</a> or 
                <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a> using an unprefixed
              <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> refers to a function in no namespace.</p></li><li><p>Any function whose name is in a namespace (including the standard
              function namespace <code>http://www.w3.org/2005/xpath-functions</code>)
              can be referenced only by using an explicit namespace prefix
              (for example, <code>fn:abs(3)</code>) or an EQName that identifies
                the namespace explicitly (for example, 
                <code>Q{http://www.w3.org/2005/xpath-functions}abs(3)</code>).</p></li></ol></li><li><p>If there is an explicit default function namespace declaration and the
          <code>StringLiteral</code> is a non-zero-length string (call it <var>NS</var>), the
          default function namespace is set to <var>NS</var>.</p><p>In this case:</p><ol class="enumla"><li><p>Any function declaration using an unprefixed <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> declares a function
              in namespace <var>NS</var>.</p></li><li><p>Any <a title="static function call" class="termref" href="#dt-static-function-call">static function call</a> or 
                <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a> using an unprefixed
              <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> refers to a function in namespace <var>NS</var>.</p></li><li><p>Any function whose name is in a different namespace (including the standard
              function namespace <code>http://www.w3.org/2005/xpath-functions</code>)
              can be referenced only by using an explicit namespace prefix (for example <code>fn:abs($x)</code>), or using
              an EQName that explicitly identifies the namespace (for example
              <code>Q{http://www.w3.org/2005/xpath-functions}abs($x)</code>).</p></li><li><p>Any function whose name is in no namespace (for example,
                a constructor function for an atomic type declared in a no-namespace schema)
              can be called only by using a no-namespace EQName, for example
              <code>Q{}local-name($x)</code>.</p></li></ol></li><li><p>If there is no explicit default function namespace declaration, then:</p><ol class="enumla"><li><p>Any function declaration using an unprefixed <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> declares a function
              in no namespace.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>This is allowed only for functions in the main module, and for private
              functions in a library module.</p><p>In previous XQuery versions this would have been an error, as the 
              default namespace <code>http://www.w3.org/2005/xpath-functions</code> was
              (and remains) a <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespace</a>.</p></div></li><li><p>Any <a title="static function call" class="termref" href="#dt-static-function-call">static function call</a> or 
                <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a> using an unprefixed
              <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> is resolved by first searching the static context for a declaration
              of a no-namespace function having the right local name and arity range, and if that
              is unsuccessful, by searching for a function in the standard
              function namespace <code>http://www.w3.org/2005/xpath-functions</code>
                having the right local name and arity range.</p><p>A no-namespace function can be referenced without risk of ambiguity
                  by using a no-namespace EQName, for example <code>Q{}local-name($x)</code>.</p><p>A function in the standard function namespace 
                  <code>http://www.w3.org/2005/xpath-functions</code> can be referenced without
                  risk of ambiguity by using the pre-declared namespace prefix <code>fn</code>
              (for example <code>fn:abs($x)</code>), or by using
              an EQName that explicitly identifies the namespace (for example
              <code>Q{http://www.w3.org/2005/xpath-functions}abs($x)</code>).</p></li></ol></li></ol><p>The keyword <code>"fixed"</code> has no effect when declaring
          a default function namespace, since there is no mechanism to change the default function
          namespace within a query module.</p></div></div><div class="div2">
<h3><a id="id-annotations"/>5.15 <a href="#id-annotations" style="text-decoration: none">Annotations</a></h3><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Annotation"/><code><a href="#prod-xquery40-Annotation">Annotation</a></code></td><td>::=</td><td><code>"%"  <a href="#doc-xquery40-Annotation-EQName">EQName</a>  ("("  (<a href="#doc-xquery40-Annotation-Constant">Constant</a> ++ ",")  ")")?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Annotation-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Annotation-Constant"/><code><a href="#prod-xquery40-Constant">Constant</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-Annotation-StringLiteral">StringLiteral</a>  |  ("-"?  <a href="#doc-xquery40-Annotation-NumericLiteral">NumericLiteral</a>)  |  <a href="#doc-xquery40-Annotation-QNameLiteral">QNameLiteral</a>  |  ("true"  "("  ")")  |  ("false"  "("  ")")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Annotation-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Annotation-NumericLiteral"/><code><a href="#prod-xquery40-NumericLiteral">NumericLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-IntegerLiteral">IntegerLiteral</a>  |  <a href="#prod-xquery40-HexIntegerLiteral">HexIntegerLiteral</a>  |  <a href="#prod-xquery40-BinaryIntegerLiteral">BinaryIntegerLiteral</a>  |  <a href="#prod-xquery40-DecimalLiteral">DecimalLiteral</a>  |  <a href="#prod-xquery40-DoubleLiteral">DoubleLiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-Annotation-QNameLiteral"/><code><a href="#prod-xquery40-QNameLiteral">QNameLiteral</a></code></td><td>::=</td><td><code>"#"  <a href="#doc-xquery40-Annotation-EQName">EQName</a>
                  </code></td></tr></tbody></table><p>XQuery uses annotations to declare properties associated with functions (inline or declared
      in the prolog), variables, and named types. For instance, a function may be declared <code>%public</code> or
        <code>%private</code>. The semantics associated with these properties are described in
        <a href="#FunctionDeclns"><b>5.18 Function Declarations</b></a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>For ease of exposition, the EBNF grammar includes several productions that all start
      with <code>"declare" Annotation*</code>, followed by the type of declaration (one of
      <code>"variable"</code>, <code>"function"</code>, <code>"type"</code>, <code>"record"</code>).
      A parser generated automatically from the grammar in this form would require unbounded
      lookahead. For implementation purposes, the grammar can be refactored as
      <code>"declare" Annotation* ( "variable"... | "function"... | "type"... | "record"... )</code>.</p></div><p>Annotations are <code>(QName, value)</code> pairs. If the EQName of the annotation is a
        <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> then it is expanded using the 
      <a title="default annotation namespace rule" class="termref" href="#dt-default-annotation-namespace-rule">default annotation namespace rule</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The default namespace is a <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespace</a>, which means
    that unprefixed names cannot be used for implementation-defined or user-defined
    annotations. It is permitted to use a no-namespace name, which
    might be written, for example, as <code>%Q{}inline</code>; however, this
    is discouraged because it is likely to reduce portability across implementations.</p></div><p>In general there is no rule preventing two annotations on the same declaration having
    the same name, although this is disallowed for some specific annotations such as
    <code>%public</code> and <code>%private</code>. The order of annotations may be significant.</p><p>If there is no value associated with an annotation, the effective value is the empty sequence.
    This is the case, for example, with the annotations <code>%public</code> and <code>%private</code>.</p><p> A few annotations, such as <code>%public</code> and <code>%private</code>,
      have rules defined by this specification. Implementations may define further annotations, whose behavior is
        implementation-defined. For instance, if the <code>eg</code> prefix is bound to a namespace
        recognized by a particular implementation, then it could be used to define an annotation like
          <code>eg:sequential</code>. 
        If the namespace URI of an annotation is not recognized by the 
        implementation, then the annotation has no effect, other than being available for inspection
        using the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-function-annotations"><code>fn:function-annotations</code></a> function.</p><p>Implementations may also provide 
      a way for users to define their own annotations.
        Implementations must not define annotations, or allow users to define annotations, in 
         <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespaces</a>; it 
        is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
               [<a href="#ERRXQST0045" title="err:XQST0045">err:XQST0045</a>] 
        for the name of an annotation to be in a <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespace</a>.
     </p><p> An annotation can provide values explicitly using a parenthesized list of 
      constant values. These values may take any of the following forms:</p><ul><li><p>A string literal, for example <code>"Paris"</code> or <code>'London'</code>, denoting
      a value of type <code>xs:string</code>.</p></li><li><p>A numeric literal, for example <code>0</code>, <code>0.1</code>, <code>0x7FFF</code>,
        or <code>1e-6</code>,
        denoting a value of type <code>xs:decimal</code>, <code>xs:integer</code>, 
        or <code>xs:double</code>. The literal may be preceded by a minus sign to represent a negative
        number.</p></li><li><p>One of the constructs <code>true()</code> or <code>false()</code>, denoting
      the <code>xs:boolean</code> values <code>true</code> and <code>false</code> respectively.</p></li><li><p>A QName literal, for example <code>#div</code> or <code>#xml:space</code>, denoting
      a value of type <code>xs:QName</code>.</p></li></ul><p>For example, the annotation
        <code>%java:method("java.lang.Math.sin")</code> sets the value of the
        <code>java:method</code> annotation to the string value <code>java.lang.Math.sin</code>. An implementation
      might define such annotations to facilitate calling external functions.
    </p><div class="note"><p class="prefix"><b>Note:</b></p><p>The constructs <code>true()</code> and <code>false()</code> must be written as
    prescribed by the grammar. No namespace prefix is allowed. Although the values resemble calls to
    functions in the default function namespace, they are unaffected by the namespace
    context.</p></div></div><div class="div2">
<h3><a id="id-variable-declarations"/>5.16 <a href="#id-variable-declarations" style="text-decoration: none">Variable Declaration</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-context-value-declarations">⬇</a> <a href="#id-default-namespace">⬆</a></p><ol><li><p>
        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.
      <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/189">189</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/254">254</a> 29 November 2022]</i></p></li><li><p>
         In earlier versions, the static context for the <a title="initializing expression" class="termref" href="#dt-initializing-expression">initializing expression</a>
         excluded the variable being declared. This restriction has been lifted.
      <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1379">1379</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1432">1432</a> 12 September 2024]</i></p></li><li><p>
        Private variables declared in a library module are no longer required to be in the module namespace.
      <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1954">1954</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1956">1956</a> 24 April 2025]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VarDecl"/><code><a href="#prod-xquery40-VarDecl">VarDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#doc-xquery40-VarDecl-Annotation">Annotation</a>*  "variable"  <a href="#doc-xquery40-VarDecl-VarNameAndType">VarNameAndType</a>  ((":="  <a href="#doc-xquery40-VarDecl-VarValue">VarValue</a>)  |  ("external"  (":="  <a href="#doc-xquery40-VarDecl-VarDefaultValue">VarDefaultValue</a>)?))</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VarDecl-Annotation"/><code><a href="#prod-xquery40-Annotation">Annotation</a></code></td><td>::=</td><td><code>"%"  <a href="#doc-xquery40-VarDecl-EQName">EQName</a>  ("("  (<a href="#prod-xquery40-Constant">Constant</a> ++ ",")  ")")?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VarDecl-VarNameAndType"/><code><a href="#prod-xquery40-VarNameAndType">VarNameAndType</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-VarDecl-EQName">EQName</a>
                     <a href="#doc-xquery40-VarDecl-TypeDeclaration">TypeDeclaration</a>?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VarDecl-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VarDecl-TypeDeclaration"/><code><a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a></code></td><td>::=</td><td><code>"as"  <a href="#doc-xquery40-VarDecl-SequenceType">SequenceType</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VarDecl-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                     <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VarDecl-VarValue"/><code><a href="#prod-xquery40-VarValue">VarValue</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-VarDecl-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VarDecl-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                     <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                     <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                     <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                     <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-VarDecl-VarDefaultValue"/><code><a href="#prod-xquery40-VarDefaultValue">VarDefaultValue</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-VarDecl-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody></table><p>
               [<a id="dt-variable-declaration" title="variable declaration">Definition</a>: A <b>variable declaration</b> 
      in the XQuery prolog defines the name and <a title="static type" class="termref" href="#dt-static-type">static
        type</a> of a variable, and optionally a value for the variable. It adds to the 
        <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope
        variables</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>, and may also add to the <a title="variable values" class="termref" href="#dt-variable-values">variable values</a> in the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a>.]
            </p><div class="note"><p class="prefix"><b>Note:</b></p><p>The term <b>variable declaration</b> always refers to a declaration of a variable in a
        Prolog. The binding of a variable to a value in a query expression, such as a FLWOR
        expression, is known as a <b>variable binding</b>, and does not make the variable
        visible to an importing module.</p></div><p>The variable name, if written as a <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a>, is expanded
      using the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.</p><p>During static analysis, a variable declaration causes a pair <code>(expanded QName N, type
        T)</code> to be added to the <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope
        variables</a>. The <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> N is the <code>VarName</code>. If N is equal (as
      defined by the eq operator) to the expanded QName of another variable in in-scope variables, a
        <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0049" title="err:XQST0049">err:XQST0049</a>].
        
      The type T of the declared variable is as follows:
    </p><ul><li><p>If <code>TypeDeclaration</code> is present, then the <code>SequenceType</code> in the
          <code>TypeDeclaration</code>; otherwise</p></li><li><p> Otherwise, <code>item()*</code>.</p></li></ul><p>A variable declaration may
      use annotations to specify that the variable is <code>%private</code> or <code>%public</code>
      (which is the default). [<a id="dt-private-variable" title="private   variable">Definition</a>: A
          <b>private variable</b> is a variable with a <code>%private</code> annotation. A
        private variable is hidden from <a title="module import" class="termref" href="#dt-module-import">module import</a>,
        which can not import it into the <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope
          variables</a> of another module.]
               [<a id="dt-public-variable" title="public variable">Definition</a>: A <b>public variable</b> is a
        variable without a <code>%private</code> annotation. A public variable is accessible to
          <a title="module import" class="termref" href="#dt-module-import">module import</a>, which can import it into the
          <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a> of another module. Using
          <code>%public</code> and <code>%private</code> 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 <a title="static error" class="termref" href="#dt-static-error">static error</a>
                  [<a href="#ERRXQST0116" title="err:XQST0116">err:XQST0116</a>] if a variable declaration contains both a
          <code>%private</code> and a <code>%public</code> annotation, more than one
          <code>%private</code> annotation, or more than one <code>%public</code>
        annotation.]
            </p><p>All <a title="public variable" class="termref" href="#dt-public-variable">public variable</a> names declared in a library module must (when expanded) be in the target
      namespace of the library module [<a href="#ERRXQST0048" title="err:XQST0048">err:XQST0048</a>].</p><p>Here are some examples of variable declarations:</p><ul><li><p>The following declaration specifies both the type and the value of a variable. This
          declaration causes the type <code>xs:integer</code> to be associated with variable
            <code>$x</code> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>, and
          the value <code>7</code> to be associated with variable <code>$x</code> in the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a>.</p><div class="exampleInner"><pre>declare variable $x as xs:integer := 7;</pre></div></li><li><p>The following declaration specifies a value but not a type. The <a title="static type" class="termref" href="#dt-static-type">static type</a> of the variable is inferred from the static
          type of its value. In this case, the variable <code>$x</code> has a static type of
            <code>xs:decimal</code>, inferred from its value which is 7.5.</p><div class="exampleInner"><pre>declare variable $x := 7.5;</pre></div></li><li><p>The following declaration specifies a type but not a value. The keyword
            <code>external</code> indicates that the value of the variable will be provided by the
          external environment. At evaluation time, if the variable <code>$x</code> in the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> does not have a value of type
            <code>xs:integer</code>, a <a title="type error" class="termref" href="#dt-type-error">type error</a> is
          raised.</p><div class="exampleInner"><pre>declare variable $x as xs:integer external;</pre></div></li><li><p>The following declaration specifies neither a type nor a value. It simply declares that
          the query depends on the existence of a variable named <code>$x</code>, whose type and
          value will be provided by the external environment. During query analysis, the type of
            <code>$x</code> is considered to be <code>item()*</code>. During query evaluation, the
            <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> must include a type and a
          value for <code>$x</code>, and its value must be compatible with its type.</p><div class="exampleInner"><pre>declare variable $x external;</pre></div></li><li><p>The following declaration, which might appear in a library module, declares a variable
          whose name includes a namespace prefix:</p><div class="exampleInner"><pre>declare variable $sasl:username as xs:string := "jonathan@example.com";</pre></div></li><li><p>This is an example of an external variable declaration that provides a
            <code>VarDefaultValue</code>:</p><div class="exampleInner"><pre>declare variable $x as xs:integer external := 47;</pre></div></li></ul><p>
      An implementation can provide annotations it needs. For instance,
      an implementation that supports volatile external variables
      might allow them to be declared using an annotation:</p><div class="exampleInner"><pre>declare %eg:volatile variable $time as xs:time external;</pre></div><p>
               [<a id="dt-initializing-expression" title="initializing expression">Definition</a>: If a variable
        declaration includes an expression (<code>VarValue</code> or <code>VarDefaultValue</code>),
        the expression is called an <b>initializing expression.</b> The static context for an
        initializing expression includes all functions, variables, and namespaces that are declared
        or imported anywhere in the Prolog.]
            </p><p>If a required type is defined, then the value obtained by 
      evaluating the initializing expression is converted to the required type by applying
    the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>. A type error occurs if this is not possible.
      In invoking the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>, <a title="XPath 1.0 compatibility     mode" class="termref" href="#dt-xpath-compat-mode">XPath 1.0 compatibility     mode</a> does not apply.</p><p>In a module's dynamic context, a variable value (or the context value) may <a title="depends on" class="termref" href="#dt-depends-on">depend on</a> another variable value (or the context value).
        [<a id="dt-depends-on" title="depends on">Definition</a>: A variable value (or the context value)
          <b>depends on</b> 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.]
            </p><p>In the following example, the value of variable <code>$a</code>
               <a title="depends on" class="termref" href="#dt-depends-on">depends on</a> the value of variable <code>$b</code>
      because the evaluation of $a's initializing expression accesses the value of $b during the
      evaluation of <code>local:f()</code>.</p><div class="exampleInner"><pre>declare variable $a := local:f(); 
declare variable $b := 1;
declare function local:f() { $b };</pre></div><p>A directed graph can be built with all variable values and the context value as nodes, and
      with the <a title="depends on" class="termref" href="#dt-depends-on">depend on</a> relation as edges. This graph must
      not contain cycles, as it makes the population of the dynamic context impossible. If it is
      discovered, during static analysis or during dynamic evaluation, that such a cycle exists,
      error [<a href="#ERRXQDY0054" title="err:XQDY0054">err:XQDY0054</a>] must be raised.</p><p>During query evaluation, each variable declaration causes a pair <code>(expanded QName <var>N</var>,
        value <var>V</var>)</code> to be added to the <a title="variable values" class="termref" href="#dt-variable-values">variable
        values</a>. The <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>
               <var>N</var> is the expanded name of the variable. The value <var>V</var> is as
      follows:</p><ul><li><p>If <code>VarValue</code> is specified, then <var>V</var> is the result of evaluating
            <code>VarValue</code>.</p></li><li><p> If <code>external</code> is specified, then:</p><ul><li><p> if a value is provided for the variable by the external environment, then <var>V</var> is that
              value. The means by which typed values of external variables are provided by the
              external environment is implementation-defined.</p></li><li><p> if no value is provided for the variable by the external environment, and
                <code>VarDefaultValue</code> is specified, then <var>V</var> is the result of evaluating
                <code>VarDefaultValue</code>.</p></li><li><p>If no value is provided for the variable by the external environment, and
                <code>VarDefaultValue</code> is not specified, then a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> is raised [<a href="#ERRXPDY0002" title="err:XPDY0002">err:XPDY0002</a>]. </p><p>It is implementation-dependent whether this error is raised if the evaluation of the
              query does not reference the value of the variable.</p></li></ul></li></ul><p>In all cases the value <var>V</var> must match the type <var>T</var> according to the rules for SequenceType
      matching; otherwise a <a title="type error" class="termref" href="#dt-type-error">type error</a> is raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>].</p></div><div class="div2">
<h3><a id="id-context-value-declarations"/>5.17 <a href="#id-context-value-declarations" style="text-decoration: none">Context Value Declaration</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#FunctionDeclns">⬇</a> <a href="#id-variable-declarations">⬆</a></p><ol><li><p>
        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.
      <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/129">129</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/368">368</a> 21 July 2023]</i></p></li><li><p>
        The supplied context value is now coerced to the required type specified in the main module
        using the coercion rules.
      <i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/189">189</a> <a href="https://github.com/qt4cg/qtspecs/issues/2040">2040</a> PRs <a href="https://github.com/qt4cg/qtspecs/pull/254">254</a> <a href="https://github.com/qt4cg/qtspecs/pull/2050">2050</a> 13 June 2025]</i></p></li></ol></div><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ContextValueDecl"/><code><a href="#prod-xquery40-ContextValueDecl">ContextValueDecl</a></code></td><td>::=</td><td><code>"declare"  "context"  (("value"  ("as"  <a href="#doc-xquery40-ContextValueDecl-SequenceType">SequenceType</a>)?)  |  ("item"  ("as"  <a href="#doc-xquery40-ContextValueDecl-ItemType">ItemType</a>)?))  ((":="  <a href="#doc-xquery40-ContextValueDecl-VarValue">VarValue</a>)  |  ("external"  (":="  <a href="#doc-xquery40-ContextValueDecl-VarDefaultValue">VarDefaultValue</a>)?))</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ContextValueDecl-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ContextValueDecl-ItemType">ItemType</a>
                     <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ContextValueDecl-ItemType"/><code><a href="#prod-xquery40-ItemType">ItemType</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-RegularItemType">RegularItemType</a>  |  <a href="#doc-xquery40-FunctionType">FunctionType</a>  |  <a href="#prod-xquery40-TypeName">TypeName</a>  |  <a href="#prod-xquery40-ChoiceItemType">ChoiceItemType</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ContextValueDecl-VarValue"/><code><a href="#prod-xquery40-VarValue">VarValue</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ContextValueDecl-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ContextValueDecl-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                     <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                     <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                     <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                     <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ContextValueDecl-VarDefaultValue"/><code><a href="#prod-xquery40-VarDefaultValue">VarDefaultValue</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-ContextValueDecl-ExprSingle">ExprSingle</a>
                  </code></td></tr></tbody></table><p>A context value declaration allows a query to specify the <a title="static type" class="termref" href="#dt-static-type">static
        type</a>, value, or default value for the <a title="initial context value" class="termref" href="#dt-initial-context-value">initial context value</a>.</p><p>Only the main module can set the <a title="initial context value" class="termref" href="#dt-initial-context-value">initial
        context value</a>. In a library module, a context value declaration must be external,
      and specifies only the static type. Specifying a <a href="#prod-xquery40-VarValue">VarValue</a> or <a href="#prod-xquery40-VarDefaultValue">VarDefaultValue</a> for a context value declaration in a library
      module is a static error [<a href="#ERRXQST0113" title="err:XQST0113">err:XQST0113</a>].</p><p>The form <code>declare context value</code> allows the <a title="initial context value" class="termref" href="#dt-initial-context-value">initial context value</a>
    to be set to any value, with any sequence type. The alternative form <code>declare context item</code>
    is retained for compatibility with earlier versions of XQuery, and requires the value to be a single
    item, and the type (if specified) to be an item type.</p><p>In every module that does not contain a context value declaration, the effect is as if the
      declaration</p><div class="exampleInner"><pre>declare context value as item()* external;</pre></div><p>appeared in that module.</p><p>The context value declaration has the effect of defining a required type for the context value.
      When the form <code>declare context value</code> is used, the default type is <code>item()*</code>.
      When the alternative form <code>declare context item</code> is used, the default type is
      <code>item()</code>.</p><p>If a module contains more than one context value declaration, a static error is raised
        [<a href="#ERRXQST0099" title="err:XQST0099">err:XQST0099</a>].</p><p>During query evaluation, a <a title="fixed focus" class="termref" href="#dt-fixed-focus">fixed focus</a> is
      created in the dynamic context for the evaluation of the <code>QueryBody</code> in the main
      module, and for the initializing expression of every variable declaration in every module.
      
      
      The context value of this fixed focus is called
      the <a title="initial context value" class="termref" href="#dt-initial-context-value">initial context value</a>,
      which is selected as follows:
      
      </p><ul><li><p>If <code>VarValue</code> is specified, then
          the initial context value is
          the result of evaluating <code>VarValue</code>, coerced to the required type
          as described below.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>
            In such a case,
            the initial context value does not obtain its value from the external environment.
            If the external environment attempts to provide a value for the initial context value,
            it is outside the scope of this specification
            whether that is ignored, or results in an error.
          </p></div></li><li><p>If <code>external</code> is specified, then:</p><ul><li><p>If the declaration occurs in a main module and a value is provided for the context value by the external environment, then
              the initial context value is
              that value, coerced to the required type as described below.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>If the declaration occurs in a library module, then it does not set the 
                value of the initial context value, the value is set by the main module.</p></div><p>The means by which an external value is provided by the external environment is
              implementation-defined.</p></li><li><p>If no value is provided for the context value by the external environment, and
                <code>VarDefaultValue</code> is specified, then
                the initial context value is
                the result of evaluating
                <code>VarDefaultValue</code>, coerced to the required type as described below. </p></li></ul></li></ul><p>If <code>VarValue</code> or <code>VarDefaultValue</code> is evaluated, the static and dynamic
      contexts for the evaluation are the current module's static and dynamic context.
      The static context for the initializing expression includes all functions, variables, and
      namespaces that are declared or imported anywhere in the Prolog.</p><p>If a required type is defined in the main module, then the value obtained by 
      evaluating <code>VarValue</code> or <code>VarDefaultValue</code>, or the value supplied externally,
      is converted to the required type by applying
      the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>. A type error occurs if this is not possible.
      In invoking the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>, <a title="XPath 1.0 compatibility     mode" class="termref" href="#dt-xpath-compat-mode">XPath 1.0 compatibility     mode</a> does not apply.</p><p>If a required type is defined in any library module, then the value obtained by 
      evaluating <code>VarValue</code> or <code>VarDefaultValue</code>, or the value supplied externally,
      after coercion to any required type defined in the main module, must match that required
      type, without any further coercion; otherwise a type error is
      raised [<a href="#ERRXPTY0004" title="err:XPTY0004">err:XPTY0004</a>]. If more than one library module contains a context value
      declaration, the context value must match the type declared in each one. </p><p>Here are some examples of context value declarations.</p><ul><li><p>Declare the type of the context value as a single element item with a required element name:</p><div class="exampleInner"><pre>declare namespace env = "http://www.w3.org/2003/05/soap-envelope"; 
declare context item as element(env:Envelope) external;</pre></div></li><li><p>Declare a default context value, which is a system log in a default location. If the
          system log is in a different location, it can be specified in the external
          environment:</p><div class="exampleInner"><pre>declare context value as element(sys:log) external :=
  doc("/var/xlogs/sysevent.xml")/sys:log;</pre></div></li><li><p>Declare a context value, which is collection whose collection URI is supplied as an external
          parameter to the query. If the
          system log is in a different location, it can be specified in the external
          environment:</p><div class="exampleInner"><pre>declare variable $uri as xs:string external;
declare context value as document-node()* := collection($uri);</pre></div><p>With this declaration, a query body such as <code>//person[name="Mandela"]</code> returns all matching
        <code>person</code> elements appearing in any document in the collection.</p></li></ul></div><div class="div2">
<h3><a id="FunctionDeclns"/>5.18 <a href="#FunctionDeclns" style="text-decoration: none">Function Declarations</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-function-names">⬇</a> <a href="#id-context-value-declarations">⬆</a></p><ol><li><p>
        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).
      </p></li><li><p>
        A user-defined function whose name is given as an unprefixed QName is now in no namespace.
        In previous versions of the language, it represented a name in the <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a>
        (which only worked if the <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a> was explicitly set to an unreserved
        namespace, which was rarely done because it caused other problems).
      <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/657">657</a> ]</i></p></li></ol></div><p>In addition to the <a title="system function" class="termref" href="#dt-system-function">system functions</a>, 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 <a href="#id-types"><b>3 Types</b></a>.</p><p>Including a function declaration in the query causes a corresponding <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> to be
        added to the <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a> of the <a title="static context" class="termref" href="#dt-static-context">static context</a>.
        The associated functions also become available in the
        <a title="dynamically known function definitions" class="termref" href="#dt-dynamically-known-function-definitions">dynamically known function definitions</a> 
        of the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a>.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionDecl"/><code><a href="#prod-xquery40-FunctionDecl">FunctionDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#doc-xquery40-FunctionDecl-Annotation">Annotation</a>*  "function"  <a href="#doc-xquery40-FunctionDecl-EQName">EQName</a>  "("  <a href="#doc-xquery40-FunctionDecl-ParamListWithDefaults">ParamListWithDefaults</a>?  ")"  <a href="#doc-xquery40-FunctionDecl-TypeDeclaration">TypeDeclaration</a>?  (<a href="#doc-xquery40-FunctionDecl-FunctionBody">FunctionBody</a>  |  "external")</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionDecl-Annotation"/><code><a href="#prod-xquery40-Annotation">Annotation</a></code></td><td>::=</td><td><code>"%"  <a href="#doc-xquery40-FunctionDecl-EQName">EQName</a>  ("("  (<a href="#prod-xquery40-Constant">Constant</a> ++ ",")  ")")?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionDecl-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionDecl-ParamListWithDefaults"/><code><a href="#prod-xquery40-ParamListWithDefaults">ParamListWithDefaults</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-FunctionDecl-ParamWithDefault">ParamWithDefault</a> ++ ",")</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionDecl-ParamWithDefault"/><code><a href="#prod-xquery40-ParamWithDefault">ParamWithDefault</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FunctionDecl-VarNameAndType">VarNameAndType</a>  (":="  <a href="#doc-xquery40-FunctionDecl-ExprSingle">ExprSingle</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionDecl-VarNameAndType"/><code><a href="#prod-xquery40-VarNameAndType">VarNameAndType</a></code></td><td>::=</td><td><code>"$"  <a href="#doc-xquery40-FunctionDecl-EQName">EQName</a>
                     <a href="#doc-xquery40-FunctionDecl-TypeDeclaration">TypeDeclaration</a>?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionDecl-TypeDeclaration"/><code><a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a></code></td><td>::=</td><td><code>"as"  <a href="#doc-xquery40-FunctionDecl-SequenceType">SequenceType</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionDecl-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                     <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionDecl-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                     <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                     <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                     <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                     <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionDecl-FunctionBody"/><code><a href="#prod-xquery40-FunctionBody">FunctionBody</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FunctionDecl-EnclosedExpr">EnclosedExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-FunctionDecl-EnclosedExpr"/><code><a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#doc-xquery40-Expr">Expr</a>?  "}"</code></td></tr></tbody></table><p> A function declaration specifies whether the implementation of the function 
      is <a title="user-defined function" class="termref" href="#dt-udf">user-defined</a> or <a title="external function" class="termref" href="#dt-external-function">external</a>.</p><p>In addition to <a title="user-defined function" class="termref" href="#dt-udf">user-defined functions</a>
      and <a title="external function" class="termref" href="#dt-external-function">external functions</a>, XQuery 4.0 allows anonymous
      functions to be declared in the body of a query using <a title="inline function expression" class="termref" href="#dt-inline-func">inline function expressions</a>.</p><p>The following example illustrates the declaration and use of a local function that accepts a
      sequence of <code>employee</code> elements, summarizes them by department, and returns a
      sequence of <code>dept</code> elements.</p><div class="example">
<div class="exampleHeader"><a id="d2e48743"/>Example: Using a function, prepare a summary of employees that are located in Denver.</div><div class="exampleInner"><pre>declare function local:summary($emps as element(employee)*) as element(dept)* { 
  for $no in distinct-values($emps/deptno) 
  let $emp := $emps[deptno = $no]
  return &lt;dept&gt; 
    &lt;deptno&gt;{ $no }&lt;/deptno&gt; 
    &lt;headcount&gt;{ count($emp) }&lt;/headcount&gt; 
    &lt;payroll&gt;{ sum($emp/salary) }&lt;/payroll&gt; 
  &lt;/dept&gt; 
};
local:summary(doc("acme_corp.xml")//employee[location = "Denver"])</pre></div></div><div class="div3">
<h4><a id="id-user-defined-functions"/>5.18.1 <a href="#id-user-defined-functions" style="text-decoration: none">User-Defined Functions</a></h4><p>
                  [<a id="dt-udf" title="user-defined function">Definition</a>: 
                     <b>User defined functions</b> are functions that contain a <b>function body</b>,
          which provides the implementation of the function as a <a title="content expression" class="termref" href="#dt-content-expression">content expression</a>.] The
          <a title="static context" class="termref" href="#dt-static-context">static context</a> for a function body includes all
        functions, variables, and namespaces that are declared or imported anywhere in the <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a>, including the function being declared. Its <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a> component also includes the
        parameters of the function being declared. </p><p>An implementation <span class="verb">should</span> raise a static error [<a href="#ERRXPST0008" title="err:XPST0008">err:XPST0008</a>] if the function body depends on 
        the context value.
      </p><p>The properties of the <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
                  <var>F</var> are derived from the syntax of the
        function declaration as follows:</p><ul><li><p>The name of <var>F</var> is the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> obtained by expanding the <code>EQName</code>
          that follows the keyword <code>function</code> as follows:</p><ul><li><p>If the query module includes an explicit declaration of a <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a>,
            then the name is expanded using the <a title="default function namespace rule" class="termref" href="#dt-default-function-namespace-rule">default function namespace rule</a>.
            That is, an unprefixed name represents a name in the default function namespace.</p></li><li><p>Otherwise (if the query module does not include an explicit declaration of a 
              <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a>), the name is expanded 
            using the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.
            That is, an unprefixed name represents a name in no namespace.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>In previous XQuery versions this would generally be an error, because in the
            absence of an explicit default function namespace declaration, the default function
            namespace would generally be a <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespace</a>.</p><p>In 4.0, an unprefixed function name used in a static function call is resolved first
              by looking for a function in no namespace, and only if that fails to find a match, by looking
              for a function in the default function namespace.</p></div></li></ul></li><li><p>The parameters of <var>F</var> are derived from the <code>ParamWithDefault</code> entries in the
          <code>ParamListWithDefaults</code>:</p><ul><li><p>The parameter name is the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> obtained by expanding the <code>EQName</code>
              that follows the <code>$</code> symbol using the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.</p></li><li><p>The required type of the parameter is given by the <code>TypeDeclaration</code>, defaulting to <code>item()*</code>.</p></li><li><p>The default value of the parameter is given by the expression that follows the <code>:=</code> symbol; if there
              is no default value, then the parameter is a required parameter.</p></li></ul></li><li><p>The return type of the function is given by the final <code>TypeDeclaration</code> that follows the <code>ParamListWithDefaults</code>
          if present, defaulting to <code>item()*</code>.</p></li><li><p>The function annotations are derived from the annotations that follow the <code>%</code> symbol, if present.</p></li><li><p>The implementation of the function is given by the enclosed expression.</p></li></ul><p>The static context may include more than one declared function with the same expanded name, but their arity ranges must 
        not overlap [<a href="#ERRXQST0034" title="err:XQST0034">err:XQST0034</a>].</p><div class="note"><p class="prefix"><b>Note:</b></p><p>A consequence of this rule is that a function declaration must not declare a function that has arity 1 (one)
          if its name is the same as the name of an imported atomic type, since the name would then clash with the
          constructor function for that type.</p></div></div><div class="div3">
<h4><a id="id-function-names"/>5.18.2 <a href="#id-function-names" style="text-decoration: none">Function Names</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-function-annotations">⬇</a> <a href="#FunctionDeclns">⬆</a></p><ol><li><p>
          Private functions declared in a library module are no longer required to be in the module namespace.
        <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1954">1954</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1956">1956</a> 24 April 2025]</i></p></li><li><p>
          A user-defined function whose name is given as an unprefixed QName is now in no namespace.
          In previous versions of the language, it represented a name in the <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a>
          (which only worked if the <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a> was explicitly set to an unreserved
          namespace, which was rarely done because it caused other problems).
        <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/657">657</a> ]</i></p></li></ol></div><div class="note"><p class="prefix"><b>Note:</b></p><p>In XQuery 4.0 it is no longer the case that all declared functions must be in a namespace; the
        function name can be unprefixed, in which case it represents a no-namespace function name,
        which will match an unprefixed name in a function call in preference to a system function
        with the same name.</p></div><p>A <a title="public function" class="termref" href="#dt-public-function">public function</a> 
        declared in a <a title="library module" class="termref" href="#dt-library-module">library module</a> must be in
        the <a title="target namespace" class="termref" href="#dt-target-namespace">target namespace</a> of the library module
        [<a href="#ERRXQST0048" title="err:XQST0048">err:XQST0048</a>]. </p><p>
                  [<a id="dt-reserved-namespaces" title="reserved namespaces">Definition</a>: A <b>reserved namespace</b> is a namespace
        that must not be used in the name of a function declaration.]  
        It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
                  [<a href="#ERRXQST0045" title="err:XQST0045">err:XQST0045</a>] 
        if the function name in a function declaration (when expanded) is 
        in a <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespace</a>. 
        The following namespaces are reserved namespaces:
        </p><ul><li><p>
                           <code>http://www.w3.org/XML/1998/namespace</code>
                        </p></li><li><p>
                           <code>http://www.w3.org/2001/XMLSchema</code>
                        </p></li><li><p>
                           <code>http://www.w3.org/2001/XMLSchema-instance</code>
                        </p></li><li><p>
                           <code>http://www.w3.org/2005/xpath-functions</code>
                        </p></li><li><p>
                           <code>http://www.w3.org/2005/xpath-functions/array</code>
                        </p></li><li><p>
                           <code>http://www.w3.org/2005/xpath-functions/map</code>
                        </p></li><li><p>
                           <code>http://www.w3.org/2005/xpath-functions/math</code>
                        </p></li><li><p>
                           <code>http://www.w3.org/2012/xquery</code>
                        </p></li></ul><p>If the function name in a function declaration has no namespace prefix, it is considered to be 
      in no namespace.</p><p>In order to allow modules to declare functions for local use within the module without
        defining a new namespace, and without any risk of conflicts with the 
        standard <code>fn</code> namespace, XQuery predefines the namespace prefix <code>local</code> to the
        namespace <code>http://www.w3.org/2005/xquery-local-functions</code>. It is suggested (but not
        required) that this namespace be used for defining local functions, including 
        <a title="private function" class="termref" href="#dt-private-function">private functions</a> declared in 
        <a title="library module" class="termref" href="#dt-library-module">library modules</a>.</p></div><div class="div3">
<h4><a id="id-function-parameters"/>5.18.3 <a href="#id-function-parameters" style="text-decoration: none">Function Parameters</a></h4><p>A function declaration includes a list of zero or more function parameters.</p><p>The parameters of a function declaration are considered to be variables whose scope is the
        function body. It is an <a title="static error" class="termref" href="#dt-static-error">static error</a>
                  [<a href="#ERRXQST0039" title="err:XQST0039">err:XQST0039</a>] for a function declaration to have more than one parameter
        with the same name. The type of a function parameter can be any type that can be expressed as
        a <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>.</p><p>If a function parameter is declared using a name but no type, its default type is
        <code>item()*</code>. If the result type is omitted from a function declaration, its default
        result type is <code>item()*</code>.</p><p>The function body defines the implementation of the <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>. 
        The rules for static function calls (see <a href="#id-eval-static-function-call"><b>4.5.1.2 Evaluating Static Function Calls</b></a>)
        ensure that a value is available for each parameter, whether required or optional, and that the value
        will always be an instance of the declared type.
      </p><p>A parameter is
    optional if a default value is supplied using the construct <code>:= ExprSingle</code>; otherwise it is required. If a parameter
    is optional, then all subsequent parameters in the list must also be optional; otherwise, a
    <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised [<a href="#ERRXQST0148" title="err:XQST0148">err:XQST0148</a>].
    In other words, the parameter list includes
    zero or more required parameters followed by zero or more optional parameters.</p><p>The number of arguments that may be supplied in a call to this family of functions is thus in the range <var>M</var> to <var>N</var>,
    where <var>M</var> is the number of required parameters, and <var>N</var> is the total number of parameters (whether required or optional).
    This is refered to as the <a title="arity range" class="termref" href="#dt-arity-range">arity range</a> of the <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>.</p><p>The default value for an optional parameter will often be supplied using a 
       simple literal or constant expression, for example
     <code>$married as xs:boolean := false()</code> or <code>$options as map(*) := { }</code>. However, to allow greater flexibility,
     the initial value can also be context-dependent. For example, <code>$node as node() := .</code> declares a parameter whose
     default value is the context value from the dynamic context of the caller, while <code>$collation as xs:string := default-collation()</code>
     declares a parameter whose default value is the default collation from the dynamic context of the caller.
     The detailed rules are as follows. In these rules, the term <b>caller</b> means the function call or function reference
     that invokes the function being defined.</p><p>The <a title="static context" class="termref" href="#dt-static-context">static context</a> for the initializing expression of an optional parameter is the same as the static
      context for the <a title="initializing expression" class="termref" href="#dt-initializing-expression">initializing expression</a> of a variable declaration (see <a href="#id-variable-declarations"><b>5.16 Variable Declaration</b></a>),
      with the following exceptions:</p><ul><li><p>The <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a> component is empty. This means that the 
          initializing expression cannot refer to any variables, other than local variables declared within the expression itself. 
          Note in particular that it cannot refer to other parameters of the function.</p></li><li><p>The <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a> excludes all user-defined functions.</p></li></ul><p>The <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> for the initializing expression of an optional parameter 
        is the same as the dynamic context of the <b>caller</b>, with the following exceptions:</p><ul><li><p>The <a title="variable values" class="termref" href="#dt-variable-values">variable values</a> component is empty.</p></li><li><p>The <a title="dynamically known function definitions" class="termref" href="#dt-dynamically-known-function-definitions">dynamically known function definitions</a> excludes all user-defined functions.</p></li></ul></div><div class="div3">
<h4><a id="id-function-annotations"/>5.18.4 <a href="#id-function-annotations" style="text-decoration: none">Function Annotations</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-conformance">⬇</a> <a href="#id-function-names">⬆</a></p><ol><li><p>
          The values <code>true()</code> and <code>false()</code> are allowed
          in function annotations, as well as negated numeric literals and
          QName literals.
        <i>  [Issues <a href="https://github.com/qt4cg/qtspecs/issues/637">637</a> <a href="https://github.com/qt4cg/qtspecs/issues/2058">2058</a> PRs <a href="https://github.com/qt4cg/qtspecs/pull/682">682</a> <a href="https://github.com/qt4cg/qtspecs/pull/TODO">TODO</a> 24 June 2025]</i></p></li></ol></div><p>A function declaration may use the <code>%private</code> or <code>%public</code> annotations
      to specify that a function is public or private; if neither of these annotations is used, the
      function is public. [<a id="dt-private-function" title="private function">Definition</a>: A <b>private
          function</b> is a function with a <code>%private</code> annotation. A private function
        is hidden from <a title="module import" class="termref" href="#dt-module-import">module import</a>, which can not import
        it into the <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a> of another module. ]
                  [<a id="dt-public-function" title="public function">Definition</a>: A <b>public function</b> is a
        function without a <code>%private</code> annotation. A public function is accessible to
          <a title="module import" class="termref" href="#dt-module-import">module import</a>, which can import it into the
        <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a> of
        another module. ] Using <code>%public</code> and <code>%private</code> 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 <a title="static error" class="termref" href="#dt-static-error">static error</a>
                  [<a href="#ERRXQST0106" title="err:XQST0106">err:XQST0106</a>] if a function declaration contains both a
        <code>%private</code> and a <code>%public</code> annotation, more than one
        <code>%private</code> annotation, or more than one <code>%public</code> annotation. </p><p>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:</p><div class="exampleInner"><pre>declare 
  %java:method("java.lang.StrictMath.copySign") 
function smath:copySign($magnitude, $sign) external;</pre></div></div><div class="div3">
<h4><a id="id-external-functions"/>5.18.5 <a href="#id-external-functions" style="text-decoration: none">External Functions</a></h4><p>
        In function declarations, <a title="external function" class="termref" href="#dt-external-function">external functions</a> are identified by the keyword
        <code>external</code>. The purpose of a function declaration for an external function is to
        declare the datatypes of the function parameters and result, for use in type checking of the
        query that contains or imports the function declaration.</p><p>An XQuery implementation may provide a facility whereby external functions can be implemented, 
      but it is not required to do so. If such a facility is
      provided, the protocols by which parameters are passed to an external function, and the result
      of the function is returned to the invoking query, are <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>. An XQuery implementation
      may augment the type system of <a href="#xpath-datamodel-40">[XDM 4.0]</a> with additional types that
      are designed to facilitate exchange of data, or it may provide
      mechanism for the user to define such types. For example, a type might be provided that
      encapsulates an object returned by an external function, such as an SQL database connection.
      These additional types, if defined, are considered to be derived by restriction from
        <code>xs:anyAtomicType</code>.</p></div><div class="div3">
<h4><a id="id-recursion"/>5.18.6 <a href="#id-recursion" style="text-decoration: none">Recursion</a></h4><p>A function declaration may be recursive—that is, it may reference itself. Mutually
      recursive functions, whose bodies reference each other, are also allowed.</p><div class="example">
<div class="exampleHeader"><a id="d2e49202"/>Example: A recursive function to compute the maximum depth of a document</div><p>The following
      example declares a recursive function that computes the maximum depth of a node hierarchy, and
      calls the function to find the maximum depth of a particular document. The function
        <code>local:depth</code> calls the built-in functions <code>empty</code> and
        <code>max</code>, which are in the default function namespace.</p><div class="exampleInner"><pre>
declare function local:depth($e as node()) as xs:integer {
  (: A node with no children has depth 1 :)
  (: Otherwise, add 1 to max depth of children :)
  if (empty($e/*)) 
  then 1
  else max(for $c in $e/* return local:depth($c)) + 1
};

local:depth(doc("partlist.xml"))</pre></div><p>[TODO: add an example of a function with an optional parameter.]</p></div></div></div><div class="div2">
<h3><a id="id-item-type-declaration"/>5.19 <a href="#id-item-type-declaration" style="text-decoration: none">Item Type Declarations</a></h3><p>An item type declaration defines a name for an <a title="item type" class="termref" href="#dt-item-type">item type</a>. Defining a name for an item type
    allows it to be referenced by name rather than repeating
    the <a title="item type designator" class="termref" href="#dt-item-type-designator">item type designator</a> in full.</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemTypeDecl"/><code><a href="#prod-xquery40-ItemTypeDecl">ItemTypeDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#doc-xquery40-ItemTypeDecl-Annotation">Annotation</a>*  "type"  <a href="#doc-xquery40-ItemTypeDecl-EQName">EQName</a>  "as"  <a href="#doc-xquery40-ItemTypeDecl-ItemType">ItemType</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemTypeDecl-Annotation"/><code><a href="#prod-xquery40-Annotation">Annotation</a></code></td><td>::=</td><td><code>"%"  <a href="#doc-xquery40-ItemTypeDecl-EQName">EQName</a>  ("("  (<a href="#prod-xquery40-Constant">Constant</a> ++ ",")  ")")?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemTypeDecl-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-ItemTypeDecl-ItemType"/><code><a href="#prod-xquery40-ItemType">ItemType</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-RegularItemType">RegularItemType</a>  |  <a href="#doc-xquery40-FunctionType">FunctionType</a>  |  <a href="#prod-xquery40-TypeName">TypeName</a>  |  <a href="#prod-xquery40-ChoiceItemType">ChoiceItemType</a>
                  </code></td></tr></tbody></table><p>An item type declaration adds a <a title="named item type" class="termref" href="#dt-named-item-type">named item type</a> to the <a title="in-scope named item types" class="termref" href="#dt-in-scope-named-item-types">in-scope named item types</a>
    of the containing module. This enables the item type to be referred to using a simple name.</p><div class="example"><p>For example, given the declaration:</p><div class="exampleInner"><pre>declare type app:invoice as map("xs:string", element(inv:paid-invoice));</pre></div><p>It becomes possible to declare a variable containing a sequence of such items as:</p><div class="exampleInner"><pre>declare variable $invoices as app:invoice*;</pre></div><p>The definition can also be used within another item type declaration:</p><div class="exampleInner"><pre>declare type app:overdue-invoices as map("xs:date", app:invoice*);</pre></div></div><p>If the name of the item type being declared is written as an (unprefixed) NCName, then 
      it is interpreted as being in the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>.</p><p>An item type declaration may use the <code>%private</code> or <code>%public</code> annotations
      to specify that an item type name is public or private; if neither of these annotations is used, the
      declaration is public.</p><ul><li><p>
                     [<a id="dt-private-item-type" title="private item type">Definition</a>: A <b>private
        item type</b> is a named item type with a <code>%private</code> annotation. A private item type
        is hidden from <a title="module import" class="termref" href="#dt-module-import">module import</a>, which can not import
        it into the <a title="in-scope named item types" class="termref" href="#dt-in-scope-named-item-types">in-scope named item types</a> of another module. ]
                  </p></li><li><p>
                     [<a id="dt-public-item-type" title="public item type">Definition</a>: A <b>public item type</b> is an
         item type declaration without a <code>%private</code> annotation. A public item type is accessible to
        <a title="module import" class="termref" href="#dt-module-import">module import</a>, which can import it into the
        <a title="in-scope named item types" class="termref" href="#dt-in-scope-named-item-types">in-scope named item types</a> of
        another module. ]
                  </p></li><li><p>Using <code>%public</code> and <code>%private</code> annotations
      in a main module is not an error, but it does not affect module imports, since a main module
      cannot be imported. </p></li><li><p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
                     [<a href="#ERRXQST0106" title="err:XQST0106">err:XQST0106</a>] if an item type declaration contains both a
      <code>%private</code> and a <code>%public</code> annotation, more than one
      <code>%private</code> annotation, or more than one <code>%public</code> annotation. </p></li><li><p>The name of a <a title="public item type" class="termref" href="#dt-public-item-type">public item type</a> declared in a <a title="library module" class="termref" href="#dt-library-module">library module</a>
        must (when expanded) be in the <a title="target namespace" class="termref" href="#dt-target-namespace">target namespace</a> of the 
      <a title="library module" class="termref" href="#dt-library-module">library module</a>
                     [<a href="#ERRXQST0048" title="err:XQST0048">err:XQST0048</a>].
      </p></li><li><p>The name of a <a title="private item type" class="termref" href="#dt-private-item-type">private item type</a>, or of a <a title="public item type" class="termref" href="#dt-public-item-type">public item type</a> declared
      in a <a title="main module" class="termref" href="#dt-main-module">main module</a>, must be in a namespace, which may be any namespace
        that is not a <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespace</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Writing the name as an unprefixed NCName is generally possible, except when the
      <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> is a reserved namespace.</p></div></li></ul><p>The declaration of an item type is available throughout the containing module; if it is
      public then it is also available throughout any importing modules. Forwards references are
      permitted, but cyclic and self-referential definitions are not allowed [<a href="#ERRXQST0140" title="err:XQST0140">err:XQST0140</a>]. This means that a reference to
      a named item type can always be replaced by the definition of the item type, but this can only happen after the item
      type declaration has been processed.</p><p>The name of an item type must be unique among the names of all
      declared item types and <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic types</a>
      in the <a title="static context" class="termref" href="#dt-static-context">static context</a> of the query module. [<a href="#ERRXQST0146" title="err:XQST0146">err:XQST0146</a>]
            </p><div class="note"><p class="prefix"><b>Note:</b></p><p>Named item types have been designed so that a reference to an item type name can be expanded
      (that is, replaced by its definition) as soon as the declaration is encountered during query parsing.
      There is never any need to retain item type names at execution time except optionally for diagnostics.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The specification allows forwards references to named item type declarations. 
      While disallowing this would appear to make life easier for implementers, it is not practical because it
    would make cyclic module imports impossible.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>It is possible to import a public variable or function into a different module
    even if its declaration refers to named item types that are not themselves imported (because they
    are declared as <code>%private</code>). This is because the type name can always be replaced by 
    its definition. However, it is generally more convenient if any named item types used
    in public function and variable declarations are themselves public.</p></div></div><div class="div2">
<h3><a id="id-named-record-types"/>5.20 <a href="#id-named-record-types" style="text-decoration: none">Named Record Types</a></h3><p>Although item type declarations, as described in <a href="#id-item-type-declaration"><b>5.19 Item Type Declarations</b></a>, 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:</p><ul><li><p>Named record types can be recursive.</p></li><li><p>Named record types implicitly create a constructor function that can be
        used to create instances of the record type.</p></li><li><p>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.</p></li></ul><p>The syntax is as follows:</p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedRecordTypeDecl"/><code><a href="#prod-xquery40-NamedRecordTypeDecl">NamedRecordTypeDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#doc-xquery40-NamedRecordTypeDecl-Annotation">Annotation</a>*  "record"  <a href="#doc-xquery40-NamedRecordTypeDecl-EQName">EQName</a>  "("  (<a href="#doc-xquery40-NamedRecordTypeDecl-ExtendedFieldDeclaration">ExtendedFieldDeclaration</a> ** ",")  <a href="#doc-xquery40-NamedRecordTypeDecl-ExtensibleFlag">ExtensibleFlag</a>?  ")"</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedRecordTypeDecl-Annotation"/><code><a href="#prod-xquery40-Annotation">Annotation</a></code></td><td>::=</td><td><code>"%"  <a href="#doc-xquery40-NamedRecordTypeDecl-EQName">EQName</a>  ("("  (<a href="#prod-xquery40-Constant">Constant</a> ++ ",")  ")")?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedRecordTypeDecl-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedRecordTypeDecl-ExtendedFieldDeclaration"/><code><a href="#prod-xquery40-ExtendedFieldDeclaration">ExtendedFieldDeclaration</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-NamedRecordTypeDecl-FieldDeclaration">FieldDeclaration</a>  (":="  <a href="#doc-xquery40-NamedRecordTypeDecl-ExprSingle">ExprSingle</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedRecordTypeDecl-FieldDeclaration"/><code><a href="#prod-xquery40-FieldDeclaration">FieldDeclaration</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-NamedRecordTypeDecl-FieldName">FieldName</a>  "?"?  ("as"  <a href="#doc-xquery40-NamedRecordTypeDecl-SequenceType">SequenceType</a>)?</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedRecordTypeDecl-FieldName"/><code><a href="#prod-xquery40-FieldName">FieldName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-NCName">NCName</a>  |  <a href="#doc-xquery40-NamedRecordTypeDecl-StringLiteral">StringLiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedRecordTypeDecl-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedRecordTypeDecl-SequenceType"/><code><a href="#prod-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#doc-xquery40-ItemType">ItemType</a>
                     <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedRecordTypeDecl-ExprSingle"/><code><a href="#prod-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                     <a href="#doc-xquery40-FLWORExpr">FLWORExpr</a>
                     <br/>|  <a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                     <br/>|  <a href="#doc-xquery40-SwitchExpr">SwitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                     <br/>|  <a href="#doc-xquery40-IfExpr">IfExpr</a>
                     <br/>|  <a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a>
                     <br/>|  <a href="#doc-xquery40-OrExpr">OrExpr</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-NamedRecordTypeDecl-ExtensibleFlag"/><code><a href="#prod-xquery40-ExtensibleFlag">ExtensibleFlag</a></code></td><td>::=</td><td><code>","  "*"</code></td></tr></tbody></table><p>A named record declaration serves as both a <a title="named item type" class="termref" href="#dt-named-item-type">named item type</a> and as a 
      <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>, and
      it therefore inherits rules from both these roles. In particular:</p><ol class="enumar"><li><p>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 [<a href="#ERRXQST0048" title="err:XQST0048">err:XQST0048</a>].</p></li><li><p>If the declaration is public and is within a <a title="library module" class="termref" href="#dt-library-module">library module</a>, then its name
       must be in the <a title="target namespace" class="termref" href="#dt-target-namespace">target namespace</a> of the library module [<a href="#ERRXQST0048" title="err:XQST0048">err:XQST0048</a>].
       </p></li><li><p>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.</p></li><li><p>The order of field declarations is significant, because it determines the order of
       arguments in a call to the constructor function.</p></li><li><p>The fields must have distinct names. [<a href="#ERRXPST0021" title="err:XPST0021">err:XPST0021</a>]
                  </p></li><li><p>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
         [<a href="#ERRXPST0003" title="err:XPST0003">err:XPST0003</a>].</p><div class="note"><p class="prefix"><b>Note:</b></p><p>This is described here as a semantic constraint, but an implementation might choose
       to impose it at the level of the grammar.</p></div></li><li><p>If an initializing expression is present in an <a href="#prod-xquery40-ExtendedFieldDeclaration">ExtendedFieldDeclaration</a>, it must
       follow the rules for the initializing expression of a parameter in a function declaration,
       given in <a href="#id-function-parameters"><b>5.18.3 Function Parameters</b></a>. In particular, if any field has an initializing
       expression then all following fields must have an initializing expression.</p></li><li><p>Any annotations that are present, such as <code>%public</code> or <code>%private</code>,
       apply both to the item type declaration and to the function declaration.</p></li></ol><div class="div3">
<h4><a id="named-records-as-item-types"/>5.20.1 <a href="#named-records-as-item-types" style="text-decoration: none">Named Records as Item Types</a></h4><p>As a named item type declaration, the construct:</p><div class="exampleInner"><pre>declare record cx:complex(r as xs:double, i as xs:double := 0);</pre></div><p>is equivalent to:</p><div class="exampleInner"><pre>declare type cx:complex as record(r as xs:double, i as xs:double);</pre></div><p>Any initializing expressions for fields are ignored for this purpose.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>The initializing expression only provides a default for values constructed using the 
          constructor function. It has no effect on the rules for determining whether a particular value is a valid instance
        of the type, and it does not affect the result of retrieval operations such as the lookup operator.</p></div><p>The name of a named record declaration is available throughout the static
          context of the module in which it is declared, including within the record declaration itself. This means that
          named record declarations can be self-recursive or mutually recursive.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Unlike a named item type declared using <code>declare type</code>, a reference to a named record type
        cannot (in general) be directly replaced by the corresponding record definition during parsing, because
        in the case of a recursive definition, simple textual replacement would not terminate.</p></div><p>A recursive record type will only be instantiable if every field whose value may contain instances of the record type
        (directly or indirectly) is optional or emptiable. Specifically, it must either be an optional field, or its type
        declaration must be such that it can hold an empty sequence or a value of a different type. 
        A recursive record type that is not instantiable is considered to be <a title="implausible" class="termref" href="#dt-implausible">implausible</a>, 
        which means that a processor may treat it as an error but is not obliged to do so [<a href="#ERRXPST0023" title="err:XPST0023">err:XPST0023</a>].</p></div><div class="div3">
<h4><a id="named-records-as-functions"/>5.20.2 <a href="#named-records-as-functions" style="text-decoration: none">Constructor Functions for Named Record Types</a></h4><p>The construct:</p><div class="exampleInner"><pre>declare record cx:complex(r as xs:double, i as xs:double := 0);</pre></div><p>implicitly defines the function:</p><div class="exampleInner"><pre>declare function cx:complex($r as xs:double, $i as xs:double := 0) as cx:complex {
  map:merge(({ "r": $r }, { "i": $i }))
};</pre></div><p>So the call <code>cx:complex(3, 2)</code> produces the value <code>{ "r": 3e0, "i": 2e0 }</code>,
      while the call <code>cx:complex(3)</code> produces the value <code>{ "r": 3e0, "i": 0e0 }</code>
               </p><p>The order of entries in the map corresponds
      to the order of field declarations in the record type. This means, for example, that when
      the map is serialized using the JSON output method, the order of entries in the output will
      correspond to the order of field declarations.</p><p>If a field is declared as optional, by including a question mark after the name, and if it has no initializer,
      then the initializer <code>:= ()</code> is added implicitly. If the declared type of an optional field does
        not permit an empty sequence, then the declared type of the function parameter is adjusted by changing the
        occurrence indicator (from absent to <code>?</code> or from <code>+</code> to <code>*</code>) in order
      to make the empty sequence an acceptable value.</p><p>Furthermore, if a field is optional and has no explicit initializer, the relevant entry in the constructed 
        map will be absent when the value supplied (implicitly or explicitly) to the function argument is an empty sequence. 
        This is achieved by modifying the function body. Given the declaration:</p><div class="exampleInner"><pre>declare record cx:complex(r as xs:double, i? as xs:double);</pre></div><p>the equivalent function declaration is:</p><div class="exampleInner"><pre>declare function cx:complex($r as xs:double, $i as xs:double? := ()) as cx:complex {
  map:merge((
    { "r": $r },
    if (exists($i)) { { "i": $i } }
  ), { "retain-order" : true() })
};</pre></div><p>If any field is either declared optional, or has an explicit initializer, 
        then all subsequent fields must also either be declared optional, or have an explicit initializer
        [<a href="#ERRXQST0148" title="err:XQST0148">err:XQST0148</a>].</p><p>If the record type is declared as extensible (by the presence of a final <code>,*</code>), then
      an additional paremeter is added to the function declaration. The name of the parameter is <code>options</code>
      (provided this name is available for use), its declared type is <code>map(*)</code>, and its default
      value is <code>{}</code> (an empty map). The function body is then modified as shown in the following example.
      Given the declaration:</p><div class="exampleInner"><pre>declare record p:person($first as xs:string, $last as xs:string, *);</pre></div><p>the equivalent function declaration is:</p><div class="exampleInner"><pre>declare function p:person(
  $first   as xs:string, 
  $last    as xs:string, 
  $options as map(*) := {}
) as p:person {
  map:merge((
    { "first": $first },
    { "last": $last },
    $options
  ),
  { "duplicates": "use-first" }
 };</pre></div><p>The effect of the <code>duplicates</code> option here is that when two values are supplied for the same field,
      one as a direct argument in the function call and the other in the <code>options</code> map, the value supplied
      as a direct argument is used in preference. The resulting
      map has an <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-entry-order">entry order</a><sup><small>DM</small></sup> in which the named fields appear first, in order of
      declaration, followed by the extension entries supplied in <code>$options</code>, retaining the 
        <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-entry-order">entry order</a><sup><small>DM</small></sup> of the <code>$options</code> map.</p><p>If the name <code>options</code> is already in use for one of the fields, then the first available name from the
      sequence <code>("options1", "options2", ...)</code> is used instead for the additional function parameter.</p><p>More formally, the equivalent function declaration is derived as follows:</p><ul><li><p>The function annotations are the annotations on the named record declaration.</p></li><li><p>The function name is the QName of the named record declaration, expanded using
         the <a title="default type namespace rule" class="termref" href="#dt-default-type-namespace-rule">default type namespace rule</a>. The resulting QName must be the same as the
       module namespace if the declaration appears in a library module, and in any event, it must be in some
       namespace.</p></li><li><p>The parameters of the function declaration are derived from the fields of the named record
       declaration, in order.</p><ul><li><p>The name of the parameter is the name of the field (always an NCName).</p></li><li><p>The declared type of the parameter is the declared type of the field, if present; but
         if the field is optional, indicated by a question mark (<code>?</code>) after its name, and has no initializer,
           then the occurrence indicator is adjusted to permit an empty sequence, as described earlier.</p></li><li><p>The default value for the parameter is given by the initializing expression in
         the <a href="#prod-xquery40-ExtendedFieldDeclaration"/>, if present. If the field is optional and has no initializer, then
         it is given a default value of <code>()</code>, the empty sequence.</p></li></ul></li><li><p>If the record type is extensible, then a further parameter is added at the end:</p><ul><li><p>The name of the parameter is the first available name from the sequence
          <code>("options", "options1", "options2", ...)</code>.</p></li><li><p>The declared type of the parameter is <code>map(*)</code>.</p></li><li><p>The default value of the parameter is <code>{}</code>, the empty map.</p></li></ul></li><li><p>The return type of the function is the name of the record declaration, with no occurrence
       indicator.</p></li><li><p>The body of the function is a call of the function <code>map:merge</code> with two arguments:</p><ul><li><p>The first argument is a parenthesized expression containing a 
             comma-separated sequence of subexpressions, containing one
           subexpression for each field, in order, and optionally a further subexpression for the
           <code>options</code> parameter if present.</p></li><li><p>By default, the relevant subexpression is the map constructor <code>{ "N": $N }</code>
           where <var>N</var> is the field name.</p></li><li><p>If the field is optional and is declared without an explicit initializer, then the
           relevant subexpression takes the form <code>if (exists($N)) { { "N": $N } }</code>
           where <var>N</var> is the field name.</p></li><li><p>The optional final subexpression, if present, takes the form <code>$options</code>,
           where <code>$options</code> is the name allocated to the final parameter.</p></li><li><p>The second argument in the call of the function <code>map:merge</code>
           is the map <code>{ "duplicates": "use-first" }</code>.</p></li></ul></li></ul><p>Note that a question mark <code>?</code> after the field name indicates that the field is optional from the point of
       view of conformance of an item to the record type. The presence of an initializer indicates that it is optional
       from the point of view of a call on the constructor function. The two things are independent of each other. For example:</p><ul><li><p>
                        <code>record(longitude, latitude, altitude?)</code>
                     </p><p>Defines a record type in which <code>altitude</code> entry may be absent, and a constructor
           function with three arguments, of which the last is optional; if the function is called
           with two arguments (or with the third argument set to an empty sequence), then there will be no
           <code>altitude</code> entry in the resulting map.</p><p>
                        <code>record(longitude, latitude, altitude := 0)</code>
                     </p><p>Defines a record type in which all three fields will always be present, and a constructor
           function in which the third argument can be omitted, defaulting to zero.</p><p>
                        <code>record(longitude, latitude, altitude? := ())</code>
                     </p><p>Defines a record type in which the <code>altitude</code> entry may be absent both from the
             record and in the function call: but because a default value has been supplied explicitly,
             the constructed map will always have an entry for <code>altitude</code>.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>Although the constructor function for a named record type produces a map in which the
        order of entries corresponds to the order of field declarations in the record type, the order
        of entries in a map is immaterial when testing whether a map matches the record type: the entries
        can be in any order.</p></div></div><div class="div3">
<h4><a id="id-functions-as-fields"/>5.20.3 <a href="#id-functions-as-fields" style="text-decoration: none">Using Methods in Records</a></h4><p>Named record declarations are useful in conjunction with method calls, 
         described in <a href="#id-methods"><b>4.14.4 Method Calls</b></a>. For example, given the declaration:</p><div class="exampleInner"><pre>
declare record my:rectangle (
   height as xs:double,
   width as xs:double,
   area as fn(my:rectangle) as xs:double 
     := fn{?height × ?width},
   resize as fn(my:rectangle, xs:double) as my:rectangle 
     := fn($rect, $factor) {
           $rect =&gt; map:put('height', $rect?height × $factor)
                 =&gt; map:put('width', $rect?width × $factor)
        }
);</pre></div><p>The following expression constructs a rectangle and calculates its area:</p><div class="exampleInner"><pre>let $box := my:rectangle(3, 2)
return $box =?&gt; area()</pre></div><p>The following expands the dimensions of the rectangle and 
        calculates the perimeter of the result:</p><div class="exampleInner"><pre>let $box := my:rectangle(3, 2)
return $box =?&gt; expand(2) =?&gt; perimeter()</pre></div><div class="note"><p class="prefix"><b>Note:</b></p><p>There is nothing to stop a user constructing an instance of <code>my:rectangle</code>
     in which the <code>area</code> entry holds some different function: while the syntax imitates
     that of object-oriented languages, there is no encapsulation.</p></div></div><div class="div3">
<h4><a id="id-atomic-set-example"/>5.20.4 <a href="#id-atomic-set-example" style="text-decoration: none">Example: Defining an Atomic Set</a></h4><p>This example demonstrates an XQuery library module that provides a new data type
               to manipulate sets of atomic items.</p><p>A query that incorporates this module (by referencing
               it in an <code>import module</code> declaration) can use constructs such as:</p><ul><li><div class="exampleInner"><pre>declare variable $empty-set as set:atomic-set
    := set:build(());</pre></div></li><li><div class="exampleInner"><pre>declare variable $evens as set:atomic-set
    := set:build((1 to 100)[. mod 2 = 0]);</pre></div></li><li><div class="exampleInner"><pre>declare variable $odds as set:atomic-set
    := set:build((1 to 100)) =?&gt; except($evens)</pre></div></li><li><div class="exampleInner"><pre>declare function my:is-even ($n as xs:integer) as xs:boolean {
    $evens =?&gt; contains($n)
};</pre></div></li></ul><p>Here is the implementation of the package. It relies heavily
               on the use of the function annotation <code>%method</code>, which
               gives a function item contained in a map access to the containing
               map: methods are described in <a href="#id-methods"><b>4.14.4 Method Calls</b></a>.</p><div class="exampleInner"><pre>
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=?&gt;size() - returns the number of items in the set
      $A=?&gt;empty() - returns true if the set is empty
      $A=?&gt;contains($k) - determines whether $k is a member of the set
      $A=?&gt;contains-all($B) - returns true if $B is a subset of $A
      $A=?&gt;values() - returns the items in $A, as a sequence
      $A=?&gt;add($k) - returns a new atomic set containing an additional item
      $A=?&gt;remove($k) - returns a new atomic set in which the given item is absent
      $A=?&gt;union($B) - returns a new atomic set holding the union of $A and $B
      $A=?&gt;intersect($B) - returns a new atomic set holding the intersection of $A and $B
      $A=?&gt;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())) }
      }
   };</pre></div><table class="ednote" caption="Editorial note"><tr><td style="text-align: left; vertical-align:top; width: 50%;"><b>Editorial note</b></td><td style="text-align: right; vertical-align:top; width: 50%;"> </td></tr><tr style="text-align: left; vertical-align: top;"><td colspan="2">The example is not yet tested. It could also be written
               using the new xsl:record instruction, which might be more concise.</td></tr></table></div></div><div class="div2">
<h3><a id="id-option-declaration"/>5.21 <a href="#id-option-declaration" style="text-decoration: none">Option Declarations</a></h3><p>
               [<a id="dt-option-declaration" title="option declaration">Definition</a>: An <b>option
          declaration</b> declares an option that affects the behavior of a particular
        implementation. Each option consists of an identifying EQName and a StringLiteral.]
            </p><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OptionDecl"/><code><a href="#prod-xquery40-OptionDecl">OptionDecl</a></code></td><td>::=</td><td><code>"declare"  "option"  <a href="#doc-xquery40-OptionDecl-EQName">EQName</a>
                     <a href="#doc-xquery40-OptionDecl-StringLiteral">StringLiteral</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OptionDecl-EQName"/><code><a href="#prod-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="doc-xquery40-OptionDecl-StringLiteral"/><code><a href="#prod-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                  </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                     <a href="#ws-explicit">ws: explicit</a>
                   */</td></tr></tbody></table><p>Typically, a particular option will be recognized by some implementations and not by others.
      The syntax is designed so that option declarations can be successfully parsed by all
      implementations.</p><p>If the EQName of an option is a <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> then it is expanded
    using the <a title="default annotation namespace rule" class="termref" href="#dt-default-annotation-namespace-rule">default annotation namespace rule</a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>If the name is unprefixed, the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> will be in the <code>http://www.w3.org/2012/xquery</code> namespace,
      which is reserved for option declarations defined by the XQuery family of specifications.
      XQuery does not currently define declaration options in this namespace.</p></div><p>Each implementation recognizes the <code>http://www.w3.org/2012/xquery</code> namespace URI
      and and all options defined in this namespace in this specification. In addition, each
      implementation recognizes an <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> set of namespace URIs and an implementation-defined set of
      option names defined in those namespaces. If the namespace part of an option declaration's
      name is not recognized, the option declaration is ignored.</p><p>Otherwise, the effect of the option declaration, including its error behavior, is <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>. For example, if the local
      part of the QName is not recognized, or if the StringLiteral does not conform to the rules
      defined by the implementation for the particular option declaration, the implementation may
      choose whether to raise an error, ignore the option declaration, or take some other
      action.</p><p>Implementations may impose rules on where particular option declarations may appear relative
      to variable declarations and function declarations, and the interpretation of an option
      declaration may depend on its position.</p><p>An option declaration must not be used to change the syntax accepted by the processor, or to
      suppress the detection of <a title="static error" class="termref" href="#dt-static-error">static errors</a>. However, it
      may be used without restriction to modify the semantics of the query. The scope of the option
      declaration is <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>—for example, an option declaration might apply to the
      whole query, to the current module, or to the immediately following function declaration.</p><p>The following examples illustrate several possible uses for option declarations:</p><ul><li><p>This option declaration might be used to specify how comments in source documents
          returned by the <code>fn:doc()</code> function should be handled:</p><div class="exampleInner"><pre>declare option exq:strip-comments "true";</pre></div></li><li><p>This option declaration might be used to associate a namespace used in function names
          with a Java class: </p><div class="exampleInner"><pre>declare namespace smath = "http://example.org/MathLibrary";
declare option exq:java-class "smath = java.lang.StrictMath";</pre></div></li></ul></div><div class="div2">
<h3><a id="id-output-declarations"/>5.22 <a href="#id-output-declarations" style="text-decoration: none">Output Declarations</a></h3><p>
               <a href="#xslt-xquery-serialization-40">[Serialization 4.0]</a> defines a set
of <b>serialization parameters</b> that govern the serialization
process. If an XQuery implementation provides a serialization
interface, it may support (and may expose to users) any of the
serialization parameters listed (with default values) in
in this section.
If an implementation does not support one of these parameters, it must ignore it without raising an error.</p><p>
               [<a id="dt-output-declaration" title="output declaration">Definition</a>: An <b>output declaration</b>
is an option declaration in the namespace <code>http://www.w3.org/2010/xslt-xquery-serialization</code>;
it is used to declare serialization parameters.]
Except for <code>parameter-document</code>, each option corresponds to a serialization parameter element defined in <a href="#xslt-xquery-serialization-40">[Serialization 4.0]</a> section <a href="../xslt-xquery-serialization-40/#serparams-schema">B Schema for Serialization Parameters</a>. 
The name of each option is the same as the name of the corresponding serialization parameter element, 
and the values permitted for each option are the same as the values allowed in the serialization parameter element. 
QName values are expanded using the <a title="default element namespace rule" class="termref" href="#dt-default-element-namespace-rule">default element namespace rule</a>.</p><p>There is no output declaration for <code>use-character-maps</code>, it can be set only by means of a parameter document. 
When the application requests serialization of the output, the
processor may use these parameters to control the way in which the
serialization takes place.  Processors may also allow external
mechanisms for specifying serialization parameters, which may or may
not override serialization parameters specified in the query prolog.</p><p>The following example illustrates the use of declaration options. </p><div class="example"><div class="exampleInner"><pre>
declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization";
declare option output:method "xml";
declare option output:encoding "iso-8859-1";
declare option output:indent "yes";
declare option output:parameter-document "file:///home/serialization-parameters.xml";</pre></div></div><p>An <b>output declaration</b> may appear only in a main module;
it is a static error  [<a href="#ERRXQST0108" title="err:XQST0108">err:XQST0108</a>] if an output declaration appears in a <a title="library module" class="termref" href="#dt-library-module">library module</a>. 
It is a static error  [<a href="#ERRXQST0110" title="err:XQST0110">err:XQST0110</a>] if the same serialization parameter is declared more than once.
It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
               [<a href="#ERRXQST0109" title="err:XQST0109">err:XQST0109</a>] if the local name of an
output declaration in the <code>http://www.w3.org/2010/xslt-xquery-serialization</code> namespace is not  one of the
serialization parameter names listed in <a href="#id-xq-static-context-components"><b>B.1 Static Context Components</b></a> or <code>parameter-document</code>,
or if the name of an output declaration is <code>use-character-maps</code>. 
The default value for the <code>method</code> parameter is <code>"xml"</code>. An
implementation may define additional <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>
serialization parameters in its own namespaces.
</p><p>If the local name of an output declaration in the
<code>http://www.w3.org/2010/xslt-xquery-serialization</code> namespace is
<code>parameter-document</code>, the value of the output declaration is treated as a
URI literal.  The value is a location hint, and identifies an XDM instance
in an implementation-defined way.  If a processor is performing
serialization, it is a static error [<a href="#ERRXQST0119" title="err:XQST0119">err:XQST0119</a>]  if the implementation
is not able to process the value of the
<code>output:parameter-document</code> declaration to produce an XDM instance.</p><p>If a processor is performing serialization, the XDM instance identified by
an <code>output:parameter-document</code> output declaration specifies the values of
serialization parameters in the manner defined by
<a href="#xslt-xquery-serialization-40">[Serialization 4.0]</a> section <a href="../xslt-xquery-serialization-40/#serparams-in-xdm-instance">3.1 Setting Serialization Parameters by Means of a Parameter Document</a>.
It is a static error  [<a href="#ERRXQST0115" title="err:XQST0115">err:XQST0115</a>]  if this
yields a serialization error.  The value of any other output declaration
overrides any value that might have been specified for the same
serialization parameter using an output declaration in the
<code>http://www.w3.org/2010/xslt-xquery-serialization</code> namespace with the local name
parameter-document declaration.</p><p>A serialization parameter that is not applicable to the chosen output method
must be ignored, except that if its value is not a valid value for that
parameter, an error may be raised.</p><p>A processor that is performing serialization must raise a
serialization error if the values of any serialization parameters that it supports (other than any that are ignored under the previous paragraph) are
incorrect.</p><p>A processor that is not performing serialization may report errors if any
serialization parameters are incorrect, or may ignore such parameters.</p><p>Specifying serialization parameters in a query does not by itself demand
that the output be serialized. It merely defines the desired form of the
serialized output for use in situations where the processor has been asked
to perform serialization. </p><div class="note"><p class="prefix"><b>Note:</b></p><p>The <a title="data model" class="termref" href="#dt-datamodel">data
model</a> permits an element node to have
fewer <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope
namespaces</a> than its parent. Correct serialization of such an
element node would require “undeclaration” of namespaces, which is a
feature of <a href="#XMLNAMES11">[XML Names 1.1]</a>. An implementation that does not
support <a href="#XMLNAMES11">[XML Names 1.1]</a> is permitted to serialize such an
element without “undeclaration” of namespaces, which effectively
causes the element to inherit the in-scope namespaces of its
parent. </p></div><div class="div3">
<h4><a id="id-serialization-parameters"/>5.22.1 <a href="#id-serialization-parameters" style="text-decoration: none">Serialization Parameters</a></h4><table style="width:100%; border:1px solid" class="small"><tbody><tr><th>Component</th><th>Default initial value</th></tr><tr><td>allow-duplicate-names</td><td>no</td></tr><tr><td>byte-order-mark</td><td>implementation-defined</td></tr><tr><td>cdata-section-elements</td><td>empty</td></tr><tr><td>doctype-public</td><td>none</td></tr><tr><td>doctype-system</td><td>none</td></tr><tr><td>encoding</td><td>implementation-defined choice between <code>"utf-8"</code> and <code>"utf-16"</code>
                        </td></tr><tr><td>escape-solidus</td><td>yes</td></tr><tr><td>escape-uri-attributes</td><td>yes</td></tr><tr><td>html-version</td><td>implementation-defined</td></tr><tr><td>include-content-type</td><td>yes</td></tr><tr><td>indent</td><td>no</td></tr><tr><td>item-separator</td><td>implementation-defined</td></tr><tr><td>json-node-output-method</td><td>xml</td></tr><tr><td>media-type</td><td>implementation-defined</td></tr><tr><td>method</td><td>xml</td></tr><tr><td>normalization-form</td><td>implementation-defined</td></tr><tr><td>omit-xml-declaration</td><td>implementation-defined</td></tr><tr><td>standalone</td><td>implementation-defined</td></tr><tr><td>suppress-indentation</td><td>empty</td></tr><tr><td>undeclare-prefixes</td><td>no</td></tr><tr><td>use-character-maps</td><td>empty</td></tr><tr><td>version</td><td>implementation-defined</td></tr></tbody></table></div></div></div><div class="div1">
<h2><a id="id-conformance"/>6 <a href="#id-conformance" style="text-decoration: none">Conformance</a></h2><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-grammar">⬇</a> <a href="#id-function-annotations">⬆</a></p><ol><li><p>
           Support for higher-order functions is now a mandatory feature (in 3.1 it was optional).
        <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/205">205</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/326">326</a> 1 February 2023]</i></p></li><li><p>
          The static typing feature has been dropped. 
        <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1343">1343</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1344">1344</a> 3 September 2024]</i></p></li><li><p>
          The module feature is no longer an optional feature; processing of library modules
          is now required.
        <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/2022">2022</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/2026">2026</a> 28 May 2025]</i></p></li></ol></div><p>This section defines the conformance criteria for an XQuery 4.0 processor. In this section, the
        following terms are used to indicate the requirement levels defined in <a href="#RFC2119">[RFC2119]</a>. [<a id="must" title="must">Definition</a>: 
               <b>MUST</b> means that the item is an absolute
            requirement of the specification.]
            [<a id="mustnot" title="must not">Definition</a>: 
               <b>MUST NOT</b> means that the item is an
            absolute prohibition of the specification.]
            [<a id="may" title="may">Definition</a>: 
               <b>MAY</b> means that an item is truly
            optional.]
            [<a id="should" title="should">Definition</a>: 
               <b>SHOULD</b> 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.]
         </p><p>An XQuery processor that claims to conform to
      this specification <a title="must" class="termref" href="#must">MUST</a> include a
      claim of Minimal Conformance as defined in <a href="#id-minimal-conformance"><b>6.1 Minimal Conformance</b></a>. In addition to a claim of
      Minimal Conformance, it <a title="may" class="termref" href="#may">MAY</a> claim
      conformance to one or more optional features defined in <a href="#id-conform-optional-features"><b>6.2 Optional Features</b></a>.</p><div class="div2 xquery">
<h3><a id="id-minimal-conformance"/>6.1 <a href="#id-minimal-conformance" style="text-decoration: none">Minimal Conformance</a></h3><p>An implementation that claims <b>Minimal Conformance</b> to this specification
                <a title="must" class="termref" href="#must">MUST</a> provide all of the following items:</p><ol class="enumar"><li><p>An implementation of everything specified in this document except those features
                    specified in <a href="#id-conform-optional-features"><b>6.2 Optional Features</b></a> to be optional. If an
                    implementation does not provide a given optional feature, it <a title="must" class="termref" href="#must">MUST</a> implement any requirements specified in <a href="#id-conform-optional-features"><b>6.2 Optional Features</b></a> for implementations that do not provide
                    that feature.</p></li><li><p>A definition of every item specified to be <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>, unless
                    that item is part of an optional feature that is not provided by the
                    implementation. A list of <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> items can be found in <a href="#id-impl-defined-items"><b>C Implementation-Defined Items</b></a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Implementations are not required to define items specified to be <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>.</p></div></li><li><p>An implementation of <a href="#xpath-datamodel-40">[XDM 4.0]</a>, as specified in <a href="#id-data-model-conformance"><b>6.3 Data Model Conformance</b></a>, and a definition of every item specified
                    to be <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>,
                    unless that item is part of an optional feature that is not provided by the
                    implementation.</p></li><li><p>An implementation of all functions defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>,
                    and a definition of every item specified to be <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>, unless
                    that function or item is part of an optional feature that is not provided by the
                    implementation.</p></li></ol></div><div class="div2 xquery">
<h3><a id="id-conform-optional-features"/>6.2 <a href="#id-conform-optional-features" style="text-decoration: none">Optional Features</a></h3><p>The features discussed in this section are optional. An implementation <a title="may" class="termref" href="#may">MAY</a> claim conformance to one or more of these features.</p><p>The description of each feature mentions any errors that occur if a query relies on a
            feature that is not present.</p><div class="div3">
<h4><a id="id-schema-aware-feature"/>6.2.1 <a href="#id-schema-aware-feature" style="text-decoration: none">Schema Aware Feature</a></h4><p>
                  [<a id="dt-schema-aware-feature" title="schema aware feature">Definition</a>: The <b>Schema Aware Feature</b> permits the query Prolog to contain a
                        <a title="schema import" class="termref" href="#dt-schema-import">schema import</a>, and permits a query
                    to contain a <code>validate</code> expression (see <a href="#id-validate"><b>4.25 Validate Expressions</b></a>). ]
               </p><p>If an XQuery implementation does not provide the Schema Aware Feature, it <a title="must" class="termref" href="#must">MUST</a> raise a static error [<a href="#ERRXQST0009" title="err:XQST0009">err:XQST0009</a>] if it encounters a schema import, and it <a title="must" class="termref" href="#must">MUST</a> raise
                a static error [<a href="#ERRXQST0075" title="err:XQST0075">err:XQST0075</a>] if it encounters a
                    <code>validate</code> expression.</p><p>If an implementation provides the Schema Aware Feature, it <a title="must" class="termref" href="#must">MUST</a> also provide the <a href="#id-typed-data-feature"><b>6.2.2 Typed Data Feature</b></a>.</p></div><div class="div3">
<h4><a id="id-typed-data-feature"/>6.2.2 <a href="#id-typed-data-feature" style="text-decoration: none">Typed Data Feature</a></h4><p>
                  [<a id="dt-typed-data-feature" title="typed data feature">Definition</a>: The
                        <b>Typed Data Feature</b> permits an XDM instance to contain element
                    node types other than <code>xs:untyped</code> and attributes node types other
                    than <code>xs:untypedAtomic</code>.]
               </p><p>If an XQuery implementation does not provide the Typed Data Feature, it <a title="must" class="termref" href="#must">MUST</a> guarantee that:</p><ol class="enumar"><li><p>The XDM has the type <code>xs:untyped</code> for every element node and
                            <code>xs:untypedAtomic</code> for every attribute node, including nodes
                        created by the query.</p></li><li><p>Elements constructed by the query always have the type
                            <code>xs:untyped</code>; attributes constructed by the query always have
                        the type <code>xs:untypedAtomic</code>. (This is equivalent to using
                            <code>construction mode = strip</code>.)</p></li></ol></div><div class="div3">
<h4><a id="id-serialization-feature"/>6.2.3 <a href="#id-serialization-feature" style="text-decoration: none">Serialization Feature</a></h4><p>
                  [<a id="dt-serialization-feature" title="serialization feature">Definition</a>: The
                        <b>Serialization Feature</b> provides means for serializing the result
                    of a query as specified in <a href="#id-serialization"><b>2.3.5 Serialization</b></a>.] A
                conforming XQuery implementation that provides the Serialization Feature <a title="must" class="termref" href="#must">MUST</a> conform to <a href="#id-serialization"><b>2.3.5 Serialization</b></a>. An
                implementation <a title="may" class="termref" href="#may">MAY</a> provide other forms of
                serialization, which do not conform to the Serialization Feature, and are beyond the
                scope of this specification. </p><p>The means by which serialization is invoked is <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>.</p><p>If an error is raised during the serialization process as specified in <a href="#xslt-xquery-serialization-40">[Serialization 4.0]</a>, an implementation <a title="must" class="termref" href="#must">MUST</a> report the error to the calling environment.</p><p>An implementation that does not provide the Serialization Feature <a title="must" class="termref" href="#must">MUST NOT</a> raise errors when reading an <a title="output declaration" class="termref" href="#dt-output-declaration">output declaration</a>, and <a title="must" class="termref" href="#must">MUST</a> implement <code>fn:serialize</code>; it <a title="may" class="termref" href="#may">MAY</a>, however, raise an error when <code>fn:serialize</code>
                is invoked, as specified in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#func-serialize">17.2.3 fn:serialize</a>. An
                implementation that does not provide the Serialization Feature <a title="may" class="termref" href="#may">MAY</a> provide results of a query using a vendor-defined
                serialization.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Some implementations return query results without serialization. For instance, an
                    implementation might provide results via an XML API or a binary representation
                    such as a persistent DOM.</p></div></div></div><div class="div2 xquery">
<h3><a id="id-data-model-conformance"/>6.3 <a href="#id-data-model-conformance" style="text-decoration: none">Data Model Conformance</a></h3><p>All XQuery implementations process data represented in the <a title="data model" class="termref" href="#dt-datamodel">data model</a> as specified in <a href="#xpath-datamodel-40">[XDM 4.0]</a>. The data
            model specification relies on languages such as XQuery to specify conformance criteria
            for the data model in their respective environments, and suggests that the following
            issues should be considered:</p><ol class="enumar"><li><p>
                     <em>Support for normative construction from an infoset.</em> An
                    implementation <a title="may" class="termref" href="#may">MAY</a> choose to claim conformance to
                        <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#const-infoset">7.4.2 Construction from an Infoset</a>, which defines a normative way
                    to construct an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a>
                    from an XML document that is merely well-formed or is governed by a DTD.</p></li><li><p>
                     <em>Support for normative construction from a PSVI.</em> An implementation
                        <a title="may" class="termref" href="#may">MAY</a> choose to claim conformance to <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#const-psvi">7.4.3 Construction from a PSVI</a>, which defines a normative way to construct
                    an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a> from an XML
                    document that is governed by a W3C XML Schema.</p></li><li><p>
                     <em>Support for versions of XML and XSD.</em> As stated in <a href="#xpath-datamodel-40">[XDM 4.0]</a>, the
                    definitions of primitives such as strings, characters, and names <a title="should" class="termref" href="#should">SHOULD</a> be taken
                    from the latest applicable version of the base specifications in which they are
                    defined; it is implementation-defined which definitions are used in cases where
                    these differ. </p><div class="note"><p class="prefix"><b>Note:</b></p><p>For suggestions on processing XML 1.1 documents with XSD 1.0, see <a href="#xml11schema10">[XML 1.1 and Schema 1.0]</a>.</p></div></li><li><p>
                     <em>Ranges of data values.</em> In XQuery, the following limits are <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>:</p><ol class="enumla"><li><p>For the <code>xs:decimal</code> type, the maximum number of decimal
                            digits (<code>totalDigits</code> facet) <a title="must" class="termref" href="#must">MUST</a> be at least 18.
                            This limit <a title="should" class="termref" href="#should">SHOULD</a> be at least 20 digits in order to 
                            accommodate the full range of values of built-in subtypes of <code>xs:integer</code>, such as 
                            <code>xs:long</code> and <code>xs:unsignedLong</code>.
                        </p></li><li><p>For the types <code>xs:date</code>, <code>xs:dateTime</code>, <code>xs:gYear</code>, and <code>xs:gYearMonth</code>: the minimum and maximum value of the year component (must be at least 1 to 9999).</p><p>For the types <code>xs:time</code> and <code>xs:dateTime</code>: the maximum number of fractional second digits (must be at least 3).</p></li><li><p>For the <code>xs:duration type</code>: the maximum absolute values of the
                            years, months, days, hours, minutes, and seconds components.</p></li><li><p>For the <code>xs:yearMonthDuration</code> type: the maximum absolute
                            value, expressed as an integer number of months.</p></li><li><p>For the <code>xs:dayTimeDuration</code> type: the maximum absolute value,
                            expressed as a decimal number of seconds.</p></li><li><p>For the types <code>xs:string</code>, <code>xs:hexBinary</code>,
                                <code>xs:base64Binary</code>, <code>xs:QName</code>,
                                <code>xs:anyURI</code>, <code>xs:NOTATION</code>, and types derived
                            from them: limitations (if any) imposed by the implementation on lengths
                            of values.</p></li></ol><p>The limits listed above need not be fixed, but <a title="may" class="termref" href="#may">MAY</a>  depend on environmental
                    factors such as system resources. For example, the length of a value of type
                        <code>xs:string</code> might be limited by available memory.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>For discussion of errors due to <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> limits, see <a href="#id-kinds-of-errors"><b>2.4.1 Kinds of Errors</b></a>.</p></div></li></ol></div><div class="div2 xquery">
<h3><a id="id-syntax-extensions"/>6.4 <a href="#id-syntax-extensions" style="text-decoration: none">Syntax Extensions</a></h3><p>Any syntactic extensions to XQuery are <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>. The effect of syntactic extensions, including
            their error behavior, is <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>. Syntactic extensions <a title="may" class="termref" href="#may">MAY</a> be used without
            restriction to modify the semantics of a XQuery expression.</p></div></div></div><div class="back"><div class="div1">
<h2><a id="nt-bnf"/>A <a href="#nt-bnf" style="text-decoration: none">XQuery 4.0 Grammar</a></h2><div class="div2">
<h3><a id="id-grammar"/>A.1 <a href="#id-grammar" style="text-decoration: none">EBNF</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#EBNFNotation">⬇</a> <a href="#id-conformance">⬆</a></p><ol><li><p>The EBNF operators <code>++</code> and <code>**</code>
      have been introduced, for more concise representation of sequences using a character
      such as <code>","</code> as a separator. The notation is borrowed from Invisible XML.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1366">1366</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1498">1498</a>]</i></p></li></ol></div><p>The grammar of XQuery 4.0 uses the same simple Extended Backus-Naur Form (EBNF) notation as
        <a href="#XML">[XML 1.0]</a> with the following differences.</p><ul><li><p>The notation <code>XYZ ** ","</code> indicates a sequence of zero or more occurrences of
        <code>XYZ</code>, with a single comma between adjacent occurrences.</p></li><li><p>The notation <code>XYZ ++ ","</code> indicates a sequence of one or more occurrences of
        <code>XYZ</code>, with a single comma between adjacent occurrences.</p></li><li><p>All named symbols have a name that begins with an uppercase letter.</p></li><li><p>It adds a notation for referring to productions in external specifications.</p></li><li><p>Comments or extra-grammatical constraints on grammar productions are between '/*' and
          '*/' symbols.</p><ul><li><p>A 'xgc:' prefix is an extra-grammatical constraint, the details of which are
              explained in <a href="#extra-grammatical-constraints"><b>A.1.2 Extra-grammatical Constraints</b></a>
                        </p></li><li><p>A 'ws:' prefix explains the whitespace rules for the production, the details of which
              are explained in <a href="#whitespace-rules"><b>A.3.4 Whitespace Rules</b></a>
                        </p></li><li><p>A 'gn:' prefix means a 'Grammar Note', and is meant as a clarification for parsing
              rules, and is explained in <a href="#notes-on-parsing"><b>A.1.3 Grammar Notes</b></a>. These notes are not
              normative.</p></li></ul></li></ul><p>The terminal symbols for this grammar include the quoted strings used in the production rules
      below, and the terminal symbols defined in section <a href="#terminal-symbols"><b>A.3.1 Terminal Symbols</b></a>.
    <span>The grammar is a little unusual in that parsing and tokenization
    are somewhat intertwined: for more details see <a href="#lexical-structure"><b>A.3 Lexical structure</b></a>.</span>
            </p><p>The EBNF notation is described in more detail in <a href="#EBNFNotation"><b>A.1.1 Notation</b></a>.</p>
<a id="BNF-Grammar"/><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AbbreviatedStep"/><code><a href="#doc-xquery40-AbbreviatedStep">AbbreviatedStep</a></code></td><td>::=</td><td><code>".."  |  ("@"  <a href="#doc-xquery40-NodeTest">NodeTest</a>)  |  <a href="#prod-xquery40-SimpleNodeTest">SimpleNodeTest</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AbsolutePathExpr"/><code>AbsolutePathExpr</code></td><td>::=</td><td><code>("/"  <a href="#prod-xquery40-RelativePathExpr">RelativePathExpr</a>?)  |  ("//"  <a href="#prod-xquery40-RelativePathExpr">RelativePathExpr</a>)</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AdditiveExpr"/><code><a href="#doc-xquery40-AdditiveExpr">AdditiveExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-MultiplicativeExpr">MultiplicativeExpr</a>  (("+"  |  "-")  <a href="#prod-xquery40-MultiplicativeExpr">MultiplicativeExpr</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AllowingEmpty"/><code>AllowingEmpty</code></td><td>::=</td><td><code>"allowing"  "empty"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AndExpr"/><code>AndExpr</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-ComparisonExpr">ComparisonExpr</a>  ("and"  <a href="#prod-xquery40-ComparisonExpr">ComparisonExpr</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Annotation"/><code><a href="#doc-xquery40-Annotation">Annotation</a></code></td><td>::=</td><td><code>"%"  <a href="#prod-xquery40-EQName">EQName</a>  ("("  (<a href="#prod-xquery40-Constant">Constant</a> ++ ",")  ")")?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AnyArrayType"/><code>AnyArrayType</code></td><td>::=</td><td><code>"array"  "("  "*"  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AnyFunctionType"/><code>AnyFunctionType</code></td><td>::=</td><td><code>("function"  |  "fn")  "("  "*"  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AnyItemTest"/><code>AnyItemTest</code></td><td>::=</td><td><code>"item"  "("  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AnyMapType"/><code>AnyMapType</code></td><td>::=</td><td><code>"map"  "("  "*"  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AnyNodeKindTest"/><code>AnyNodeKindTest</code></td><td>::=</td><td><code>"node"  "("  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AnyRecordType"/><code>AnyRecordType</code></td><td>::=</td><td><code>"record"  "("  "*"  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AposAttrValueContent"/><code>AposAttrValueContent</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AposAttrContentChar">AposAttrContentChar</a>
                        <br/>|  <a href="#prod-xquery40-CommonContent">CommonContent</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Argument"/><code>Argument</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-ExprSingle">ExprSingle</a>  |  <a href="#prod-xquery40-ArgumentPlaceholder">ArgumentPlaceholder</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ArgumentList"/><code>ArgumentList</code></td><td>::=</td><td><code>"("  ((<a href="#prod-xquery40-PositionalArguments">PositionalArguments</a>  (","  <a href="#prod-xquery40-KeywordArguments">KeywordArguments</a>)?)  |  <a href="#prod-xquery40-KeywordArguments">KeywordArguments</a>)?  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ArgumentPlaceholder"/><code>ArgumentPlaceholder</code></td><td>::=</td><td><code>"?"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ArrayConstructor"/><code><a href="#doc-xquery40-ArrayConstructor">ArrayConstructor</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-SquareArrayConstructor">SquareArrayConstructor</a>  |  <a href="#prod-xquery40-CurlyArrayConstructor">CurlyArrayConstructor</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ArrayType"/><code><a href="#doc-xquery40-ArrayType">ArrayType</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AnyArrayType">AnyArrayType</a>  |  <a href="#prod-xquery40-TypedArrayType">TypedArrayType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ArrowExpr"/><code><a href="#doc-xquery40-ArrowExpr">ArrowExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-UnaryExpr">UnaryExpr</a>  (<a href="#prod-xquery40-SequenceArrowTarget">SequenceArrowTarget</a>  |  <a href="#prod-xquery40-MappingArrowTarget">MappingArrowTarget</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ArrowTarget"/><code>ArrowTarget</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-FunctionCall">FunctionCall</a>  |  <a href="#prod-xquery40-RestrictedDynamicCall">RestrictedDynamicCall</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AttributeName"/><code>AttributeName</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EQName">EQName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AttributeTest"/><code><a href="#doc-xquery40-AttributeTest">AttributeTest</a></code></td><td>::=</td><td><code>"attribute"  "("  (<a href="#prod-xquery40-NameTestUnion">NameTestUnion</a>  (","  <a href="#prod-xquery40-TypeName">TypeName</a>)?)?  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Axis"/><code><a href="#doc-xquery40-Axis">Axis</a></code></td><td>::=</td><td><code>("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")  "::"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AxisStep"/><code><a href="#doc-xquery40-AxisStep">AxisStep</a></code></td><td>::=</td><td><code>(<a href="#doc-xquery40-AbbreviatedStep">AbbreviatedStep</a>  |  <a href="#prod-xquery40-FullStep">FullStep</a>)  <a href="#prod-xquery40-Predicate">Predicate</a>*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-BaseURIDecl"/><code><a href="#doc-xquery40-BaseURIDecl">BaseURIDecl</a></code></td><td>::=</td><td><code>"declare"  "base-uri"  <a href="#prod-xquery40-URILiteral">URILiteral</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-BoundarySpaceDecl"/><code><a href="#doc-xquery40-BoundarySpaceDecl">BoundarySpaceDecl</a></code></td><td>::=</td><td><code>"declare"  "boundary-space"  ("preserve"  |  "strip")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-BracedAction"/><code>BracedAction</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-BracedSwitchCases"/><code>BracedSwitchCases</code></td><td>::=</td><td><code>"{"  <a href="#prod-xquery40-SwitchCases">SwitchCases</a>  "}"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-BracedTypeswitchCases"/><code>BracedTypeswitchCases</code></td><td>::=</td><td><code>"{"  <a href="#prod-xquery40-TypeswitchCases">TypeswitchCases</a>  "}"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CaseClause"/><code>CaseClause</code></td><td>::=</td><td><code>"case"  (<a href="#prod-xquery40-VarName">VarName</a>  "as")?  <a href="#prod-xquery40-SequenceTypeUnion">SequenceTypeUnion</a>  "return"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CastableExpr"/><code><a href="#doc-xquery40-CastableExpr">CastableExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-CastExpr">CastExpr</a>  ("castable"  "as"  <a href="#prod-xquery40-CastTarget">CastTarget</a>  "?"?)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CastExpr"/><code><a href="#doc-xquery40-CastExpr">CastExpr</a></code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-PipelineExpr">PipelineExpr</a>  ("cast"  "as"  <a href="#prod-xquery40-CastTarget">CastTarget</a>  "?"?)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CastTarget"/><code>CastTarget</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-TypeName">TypeName</a>  |  <a href="#prod-xquery40-ChoiceItemType">ChoiceItemType</a>  |  <a href="#prod-xquery40-EnumerationType">EnumerationType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CatchClause"/><code>CatchClause</code></td><td>::=</td><td><code>"catch"  <a href="#prod-xquery40-NameTestUnion">NameTestUnion</a>
                        <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CDataSection"/><code>CDataSection</code></td><td>::=</td><td><code>"&lt;![CDATA["  <a href="#prod-xquery40-CDataSectionContents">CDataSectionContents</a>  "]]&gt;"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CDataSectionContents"/><code>CDataSectionContents</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-Char">Char</a>* - (Char* ']]&gt;' Char*))</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ChoiceItemType"/><code>ChoiceItemType</code></td><td>::=</td><td><code>"("  (<a href="#prod-xquery40-ItemType">ItemType</a> ++ "|")  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CommentTest"/><code>CommentTest</code></td><td>::=</td><td><code>"comment"  "("  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CommonContent"/><code>CommonContent</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-PredefinedEntityRef">PredefinedEntityRef</a>  |  <a href="#prod-xquery40-CharRef">CharRef</a>  |  "{{"  |  "}}"  |  <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ComparisonExpr"/><code><a href="#doc-xquery40-ComparisonExpr">ComparisonExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-OtherwiseExpr">OtherwiseExpr</a>  ((<a href="#prod-xquery40-ValueComp">ValueComp</a>  |  <a href="#prod-xquery40-GeneralComp">GeneralComp</a>  |  <a href="#prod-xquery40-NodeComp">NodeComp</a>)  <a href="#prod-xquery40-OtherwiseExpr">OtherwiseExpr</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CompAttrConstructor"/><code><a href="#doc-xquery40-CompAttrConstructor">CompAttrConstructor</a></code></td><td>::=</td><td><code>"attribute"  <a href="#prod-xquery40-CompNodeName">CompNodeName</a>
                        <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CompCommentConstructor"/><code><a href="#doc-xquery40-CompCommentConstructor">CompCommentConstructor</a></code></td><td>::=</td><td><code>"comment"  <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CompDocConstructor"/><code><a href="#doc-xquery40-CompDocConstructor">CompDocConstructor</a></code></td><td>::=</td><td><code>"document"  <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CompElemConstructor"/><code><a href="#doc-xquery40-CompElemConstructor">CompElemConstructor</a></code></td><td>::=</td><td><code>"element"  <a href="#prod-xquery40-CompNodeName">CompNodeName</a>
                        <a href="#prod-xquery40-EnclosedContentExpr">EnclosedContentExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CompNamespaceConstructor"/><code><a href="#doc-xquery40-CompNamespaceConstructor">CompNamespaceConstructor</a></code></td><td>::=</td><td><code>"namespace"  <a href="#prod-xquery40-CompNodeNCName">CompNodeNCName</a>
                        <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CompNodeName"/><code>CompNodeName</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QNameLiteral">QNameLiteral</a>  |  <a href="#prod-xquery40-UnreservedName">UnreservedName</a>  |  ("{"  <a href="#prod-xquery40-Expr">Expr</a>  "}")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CompNodeNCName"/><code>CompNodeNCName</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-MarkedNCName">MarkedNCName</a>  |  <a href="#prod-xquery40-UnreservedNCName">UnreservedNCName</a>  |  ("{"  <a href="#prod-xquery40-Expr">Expr</a>  "}")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CompPIConstructor"/><code><a href="#doc-xquery40-CompPIConstructor">CompPIConstructor</a></code></td><td>::=</td><td><code>"processing-instruction"  <a href="#prod-xquery40-CompNodeNCName">CompNodeNCName</a>
                        <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CompTextConstructor"/><code><a href="#doc-xquery40-CompTextConstructor">CompTextConstructor</a></code></td><td>::=</td><td><code>"text"  <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ComputedConstructor"/><code><a href="#doc-xquery40-ComputedConstructor">ComputedConstructor</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-CompDocConstructor">CompDocConstructor</a>
                        <br/>|  <a href="#prod-xquery40-CompElemConstructor">CompElemConstructor</a>
                        <br/>|  <a href="#prod-xquery40-CompAttrConstructor">CompAttrConstructor</a>
                        <br/>|  <a href="#prod-xquery40-CompNamespaceConstructor">CompNamespaceConstructor</a>
                        <br/>|  <a href="#prod-xquery40-CompTextConstructor">CompTextConstructor</a>
                        <br/>|  <a href="#prod-xquery40-CompCommentConstructor">CompCommentConstructor</a>
                        <br/>|  <a href="#prod-xquery40-CompPIConstructor">CompPIConstructor</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Constant"/><code>Constant</code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-StringLiteral">StringLiteral</a>  |  ("-"?  <a href="#prod-xquery40-NumericLiteral">NumericLiteral</a>)  |  <a href="#prod-xquery40-QNameLiteral">QNameLiteral</a>  |  ("true"  "("  ")")  |  ("false"  "("  ")")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ConstructionDecl"/><code><a href="#doc-xquery40-ConstructionDecl">ConstructionDecl</a></code></td><td>::=</td><td><code>"declare"  "construction"  ("strip"  |  "preserve")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ContextValueDecl"/><code><a href="#doc-xquery40-ContextValueDecl">ContextValueDecl</a></code></td><td>::=</td><td><code>"declare"  "context"  (("value"  ("as"  <a href="#prod-xquery40-SequenceType">SequenceType</a>)?)  |  ("item"  ("as"  <a href="#prod-xquery40-ItemType">ItemType</a>)?))  ((":="  <a href="#prod-xquery40-VarValue">VarValue</a>)  |  ("external"  (":="  <a href="#prod-xquery40-VarDefaultValue">VarDefaultValue</a>)?))</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ContextValueRef"/><code><a href="#doc-xquery40-ContextValueRef">ContextValueRef</a></code></td><td>::=</td><td><code>"."</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CopyNamespacesDecl"/><code><a href="#doc-xquery40-CopyNamespacesDecl">CopyNamespacesDecl</a></code></td><td>::=</td><td><code>"declare"  "copy-namespaces"  <a href="#prod-xquery40-PreserveMode">PreserveMode</a>  ","  <a href="#prod-xquery40-InheritMode">InheritMode</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CountClause"/><code><a href="#doc-xquery40-CountClause">CountClause</a></code></td><td>::=</td><td><code>"count"  <a href="#prod-xquery40-VarName">VarName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CurlyArrayConstructor"/><code>CurlyArrayConstructor</code></td><td>::=</td><td><code>"array"  <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CurrentVar"/><code>CurrentVar</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-VarName">VarName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DecimalFormatDecl"/><code><a href="#doc-xquery40-DecimalFormatDecl">DecimalFormatDecl</a></code></td><td>::=</td><td><code>"declare"  (("decimal-format"  <a href="#prod-xquery40-EQName">EQName</a>)  |  ("default"  "decimal-format"))  (<a href="#prod-xquery40-DFPropertyName">DFPropertyName</a>  "="  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DefaultCollationDecl"/><code><a href="#doc-xquery40-DefaultCollationDecl">DefaultCollationDecl</a></code></td><td>::=</td><td><code>"declare"  "default"  "collation"  <a href="#prod-xquery40-URILiteral">URILiteral</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DefaultNamespaceDecl"/><code><a href="#doc-xquery40-DefaultNamespaceDecl">DefaultNamespaceDecl</a></code></td><td>::=</td><td><code>"declare"  "fixed"?  "default"  ("element"  |  "function")  "namespace"  <a href="#prod-xquery40-URILiteral">URILiteral</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DFPropertyName"/><code>DFPropertyName</code></td><td>::=</td><td><code>"decimal-separator"  |  "grouping-separator"  |  "infinity"  |  "minus-sign"  |  "NaN"  |  "percent"  |  "per-mille"  |  "zero-digit"  |  "digit"  |  "pattern-separator"  |  "exponent-separator"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DirAttributeList"/><code>DirAttributeList</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-S">S</a>  (<a href="#prod-xquery40-QName">QName</a>
                        <a href="#prod-xquery40-S">S</a>?  "="  <a href="#prod-xquery40-S">S</a>?  <a href="#prod-xquery40-DirAttributeValue">DirAttributeValue</a>)?)*</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DirAttributeValue"/><code>DirAttributeValue</code></td><td>::=</td><td><code>('"'  (<a href="#prod-xquery40-EscapeQuot">EscapeQuot</a>  |  <a href="#prod-xquery40-QuotAttrValueContent">QuotAttrValueContent</a>)*  '"')<br/>|  ("'"  (<a href="#prod-xquery40-EscapeApos">EscapeApos</a>  |  <a href="#prod-xquery40-AposAttrValueContent">AposAttrValueContent</a>)*  "'")</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DirCommentConstructor"/><code>DirCommentConstructor</code></td><td>::=</td><td><code>"&lt;!--"  <a href="#prod-xquery40-DirCommentContents">DirCommentContents</a>  "--&gt;"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DirCommentContents"/><code>DirCommentContents</code></td><td>::=</td><td><code>((<a href="#prod-xquery40-Char">Char</a> - '-')  |  ("-"  (<a href="#prod-xquery40-Char">Char</a> - '-')))*</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DirectConstructor"/><code>DirectConstructor</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-DirElemConstructor">DirElemConstructor</a>
                        <br/>|  <a href="#prod-xquery40-DirCommentConstructor">DirCommentConstructor</a>
                        <br/>|  <a href="#prod-xquery40-DirPIConstructor">DirPIConstructor</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DirElemConstructor"/><code>DirElemConstructor</code></td><td>::=</td><td><code>"&lt;"  <a href="#prod-xquery40-QName">QName</a>
                        <a href="#prod-xquery40-DirAttributeList">DirAttributeList</a>  ("/&gt;"  |  ("&gt;"  <a href="#prod-xquery40-DirElemContent">DirElemContent</a>*  "&lt;/"  <a href="#prod-xquery40-QName">QName</a>
                        <a href="#prod-xquery40-S">S</a>?  "&gt;"))</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DirElemContent"/><code>DirElemContent</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-DirectConstructor">DirectConstructor</a>
                        <br/>|  <a href="#prod-xquery40-CDataSection">CDataSection</a>
                        <br/>|  <a href="#prod-xquery40-CommonContent">CommonContent</a>
                        <br/>|  <a href="#prod-xquery40-ElementContentChar">ElementContentChar</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DirPIConstructor"/><code><a href="#doc-xquery40-DirPIConstructor">DirPIConstructor</a></code></td><td>::=</td><td><code>"&lt;?"  <a href="#prod-xquery40-PITarget">PITarget</a>  (<a href="#prod-xquery40-S">S</a>
                        <a href="#prod-xquery40-DirPIContents">DirPIContents</a>)?  "?&gt;"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DirPIContents"/><code>DirPIContents</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-Char">Char</a>* - (Char* '?&gt;' Char*))</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DocumentTest"/><code>DocumentTest</code></td><td>::=</td><td><code>"document-node"  "("  (<a href="#prod-xquery40-ElementTest">ElementTest</a>  |  <a href="#prod-xquery40-SchemaElementTest">SchemaElementTest</a>  |  <a href="#prod-xquery40-NameTestUnion">NameTestUnion</a>)?  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DynamicFunctionCall"/><code><a href="#doc-xquery40-DynamicFunctionCall">DynamicFunctionCall</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-PostfixExpr">PostfixExpr</a>
                        <a href="#prod-xquery40-PositionalArgumentList">PositionalArgumentList</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ElementName"/><code>ElementName</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EQName">EQName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ElementTest"/><code><a href="#doc-xquery40-ElementTest">ElementTest</a></code></td><td>::=</td><td><code>"element"  "("  (<a href="#prod-xquery40-NameTestUnion">NameTestUnion</a>  (","  <a href="#prod-xquery40-TypeName">TypeName</a>  "?"?)?)?  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-EmptyOrderDecl"/><code><a href="#doc-xquery40-EmptyOrderDecl">EmptyOrderDecl</a></code></td><td>::=</td><td><code>"declare"  "default"  "order"  "empty"  ("greatest"  |  "least")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-EnclosedContentExpr"/><code>EnclosedContentExpr</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-EnclosedExpr"/><code><a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a></code></td><td>::=</td><td><code>"{"  <a href="#prod-xquery40-Expr">Expr</a>?  "}"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-EnumerationType"/><code><a href="#doc-xquery40-EnumerationType">EnumerationType</a></code></td><td>::=</td><td><code>"enum"  "("  (<a href="#doc-xquery40-StringLiteral">StringLiteral</a> ++ ",")  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-EQName"/><code><a href="#doc-xquery40-EQName">EQName</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QName">QName</a>  |  <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Expr"/><code><a href="#doc-xquery40-Expr">Expr</a></code></td><td>::=</td><td><code>(<a href="#prod-xquery40-ExprSingle">ExprSingle</a> ++ ",")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ExprSingle"/><code><a href="#doc-xquery40-ExprSingle">ExprSingle</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-FLWORExpr">FLWORExpr</a>
                        <br/>|  <a href="#prod-xquery40-QuantifiedExpr">QuantifiedExpr</a>
                        <br/>|  <a href="#prod-xquery40-SwitchExpr">SwitchExpr</a>
                        <br/>|  <a href="#prod-xquery40-TypeswitchExpr">TypeswitchExpr</a>
                        <br/>|  <a href="#prod-xquery40-IfExpr">IfExpr</a>
                        <br/>|  <a href="#prod-xquery40-TryCatchExpr">TryCatchExpr</a>
                        <br/>|  <a href="#prod-xquery40-OrExpr">OrExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ExtendedFieldDeclaration"/><code>ExtendedFieldDeclaration</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-FieldDeclaration">FieldDeclaration</a>  (":="  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ExtensibleFlag"/><code>ExtensibleFlag</code></td><td>::=</td><td><code>","  "*"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ExtensionExpr"/><code><a href="#doc-xquery40-ExtensionExpr">ExtensionExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-Pragma">Pragma</a>+  "{"  <a href="#prod-xquery40-Expr">Expr</a>?  "}"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FieldDeclaration"/><code>FieldDeclaration</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-FieldName">FieldName</a>  "?"?  ("as"  <a href="#prod-xquery40-SequenceType">SequenceType</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FieldName"/><code>FieldName</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-NCName">NCName</a>  |  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FilterExpr"/><code><a href="#doc-xquery40-FilterExpr">FilterExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-PostfixExpr">PostfixExpr</a>
                        <a href="#prod-xquery40-Predicate">Predicate</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FilterExprAM"/><code><a href="#doc-xquery40-FilterExprAM">FilterExprAM</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-PostfixExpr">PostfixExpr</a>  "?["  <a href="#prod-xquery40-Expr">Expr</a>  "]"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FinallyClause"/><code>FinallyClause</code></td><td>::=</td><td><code>"finally"  <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FLWORExpr"/><code><a href="#doc-xquery40-FLWORExpr">FLWORExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-InitialClause">InitialClause</a>
                        <a href="#prod-xquery40-IntermediateClause">IntermediateClause</a>*  <a href="#prod-xquery40-ReturnClause">ReturnClause</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ForBinding"/><code>ForBinding</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-ForItemBinding">ForItemBinding</a>  |  <a href="#prod-xquery40-ForMemberBinding">ForMemberBinding</a>  |  <a href="#prod-xquery40-ForEntryBinding">ForEntryBinding</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ForClause"/><code><a href="#doc-xquery40-ForClause">ForClause</a></code></td><td>::=</td><td><code>"for"  (<a href="#prod-xquery40-ForBinding">ForBinding</a> ++ ",")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ForEntryBinding"/><code>ForEntryBinding</code></td><td>::=</td><td><code>((<a href="#prod-xquery40-ForEntryKeyBinding">ForEntryKeyBinding</a>
                        <a href="#prod-xquery40-ForEntryValueBinding">ForEntryValueBinding</a>?)  |  <a href="#prod-xquery40-ForEntryValueBinding">ForEntryValueBinding</a>)  <a href="#prod-xquery40-PositionalVar">PositionalVar</a>?  "in"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ForEntryKeyBinding"/><code>ForEntryKeyBinding</code></td><td>::=</td><td><code>"key"  <a href="#prod-xquery40-VarNameAndType">VarNameAndType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ForEntryValueBinding"/><code>ForEntryValueBinding</code></td><td>::=</td><td><code>"value"  <a href="#prod-xquery40-VarNameAndType">VarNameAndType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ForItemBinding"/><code>ForItemBinding</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-VarNameAndType">VarNameAndType</a>
                        <a href="#prod-xquery40-AllowingEmpty">AllowingEmpty</a>?  <a href="#prod-xquery40-PositionalVar">PositionalVar</a>?  "in"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ForMemberBinding"/><code>ForMemberBinding</code></td><td>::=</td><td><code>"member"  <a href="#prod-xquery40-VarNameAndType">VarNameAndType</a>
                        <a href="#prod-xquery40-PositionalVar">PositionalVar</a>?  "in"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FullStep"/><code>FullStep</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-Axis">Axis</a>
                        <a href="#doc-xquery40-NodeTest">NodeTest</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FunctionBody"/><code>FunctionBody</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FunctionCall"/><code><a href="#doc-xquery40-FunctionCall">FunctionCall</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EQName">EQName</a>
                        <a href="#prod-xquery40-ArgumentList">ArgumentList</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                      */</td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-parens">gn: parens</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FunctionDecl"/><code><a href="#doc-xquery40-FunctionDecl">FunctionDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#prod-xquery40-Annotation">Annotation</a>*  "function"  <a href="#prod-xquery40-EQName">EQName</a>  "("  <a href="#prod-xquery40-ParamListWithDefaults">ParamListWithDefaults</a>?  ")"  <a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a>?  (<a href="#prod-xquery40-FunctionBody">FunctionBody</a>  |  "external")</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FunctionItemExpr"/><code>FunctionItemExpr</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-NamedFunctionRef">NamedFunctionRef</a>  |  <a href="#prod-xquery40-InlineFunctionExpr">InlineFunctionExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FunctionSignature"/><code>FunctionSignature</code></td><td>::=</td><td><code>"("  <a href="#prod-xquery40-ParamList">ParamList</a>  ")"  <a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a>?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-FunctionType"/><code><a href="#doc-xquery40-FunctionType">FunctionType</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-Annotation">Annotation</a>*  (<a href="#prod-xquery40-AnyFunctionType">AnyFunctionType</a>
                        <br/>|  <a href="#prod-xquery40-TypedFunctionType">TypedFunctionType</a>)</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-GeneralComp"/><code>GeneralComp</code></td><td>::=</td><td><code>"="  |  "!="  |  "&lt;"  |  "&lt;="  |  "&gt;"  |  "&gt;="</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-GNodeType"/><code><a href="#doc-xquery40-GNodeType">GNodeType</a></code></td><td>::=</td><td><code>"gnode"  "("  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-GroupByClause"/><code><a href="#doc-xquery40-GroupByClause">GroupByClause</a></code></td><td>::=</td><td><code>"group"  "by"  (<a href="#prod-xquery40-GroupingSpec">GroupingSpec</a> ++ ",")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-GroupingSpec"/><code>GroupingSpec</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-VarName">VarName</a>  (<a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a>?  ":="  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>)?  ("collation"  <a href="#prod-xquery40-URILiteral">URILiteral</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-IfExpr"/><code><a href="#doc-xquery40-IfExpr">IfExpr</a></code></td><td>::=</td><td><code>"if"  "("  <a href="#prod-xquery40-Expr">Expr</a>  ")"  (<a href="#prod-xquery40-UnbracedActions">UnbracedActions</a>  |  <a href="#prod-xquery40-BracedAction">BracedAction</a>)</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Import"/><code>Import</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-SchemaImport">SchemaImport</a>  |  <a href="#prod-xquery40-ModuleImport">ModuleImport</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-InheritMode"/><code>InheritMode</code></td><td>::=</td><td><code>"inherit"  |  "no-inherit"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-InitialClause"/><code>InitialClause</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-ForClause">ForClause</a>  |  <a href="#prod-xquery40-LetClause">LetClause</a>  |  <a href="#prod-xquery40-WindowClause">WindowClause</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-InlineFunctionExpr"/><code><a href="#doc-xquery40-InlineFunctionExpr">InlineFunctionExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-Annotation">Annotation</a>*  ("function"  |  "fn")  <a href="#prod-xquery40-FunctionSignature">FunctionSignature</a>?  <a href="#prod-xquery40-FunctionBody">FunctionBody</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-InstanceofExpr"/><code><a href="#doc-xquery40-InstanceofExpr">InstanceofExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-TreatExpr">TreatExpr</a>  ("instance"  "of"  <a href="#prod-xquery40-SequenceType">SequenceType</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-IntermediateClause"/><code>IntermediateClause</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-InitialClause">InitialClause</a>  |  <a href="#prod-xquery40-WhereClause">WhereClause</a>  |  <a href="#prod-xquery40-WhileClause">WhileClause</a>  |  <a href="#prod-xquery40-GroupByClause">GroupByClause</a>  |  <a href="#prod-xquery40-OrderByClause">OrderByClause</a>  |  <a href="#prod-xquery40-CountClause">CountClause</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-IntersectExceptExpr"/><code>IntersectExceptExpr</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-InstanceofExpr">InstanceofExpr</a>  (("intersect"  |  "except")  <a href="#prod-xquery40-InstanceofExpr">InstanceofExpr</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ItemType"/><code><a href="#doc-xquery40-ItemType">ItemType</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-RegularItemType">RegularItemType</a>  |  <a href="#prod-xquery40-FunctionType">FunctionType</a>  |  <a href="#prod-xquery40-TypeName">TypeName</a>  |  <a href="#prod-xquery40-ChoiceItemType">ChoiceItemType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ItemTypeDecl"/><code><a href="#doc-xquery40-ItemTypeDecl">ItemTypeDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#prod-xquery40-Annotation">Annotation</a>*  "type"  <a href="#prod-xquery40-EQName">EQName</a>  "as"  <a href="#prod-xquery40-ItemType">ItemType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-JNodeType"/><code><a href="#doc-xquery40-JNodeType">JNodeType</a></code></td><td>::=</td><td><code>"jnode"  "("  <a href="#prod-xquery40-SequenceType">SequenceType</a>?  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-KeySpecifier"/><code>KeySpecifier</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-NCName">NCName</a>  |  <a href="#prod-xquery40-Literal">Literal</a>  |  <a href="#prod-xquery40-ContextValueRef">ContextValueRef</a>  |  <a href="#prod-xquery40-VarRef">VarRef</a>  |  <a href="#prod-xquery40-ParenthesizedExpr">ParenthesizedExpr</a>  |  <a href="#prod-xquery40-LookupWildcard">LookupWildcard</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-KeywordArgument"/><code>KeywordArgument</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EQName">EQName</a>  ":="  <a href="#prod-xquery40-Argument">Argument</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-KeywordArguments"/><code>KeywordArguments</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-KeywordArgument">KeywordArgument</a> ++ ",")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-LetArrayBinding"/><code>LetArrayBinding</code></td><td>::=</td><td><code>"$"  "["  (<a href="#prod-xquery40-VarNameAndType">VarNameAndType</a> ++ ",")  "]"  <a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a>?  ":="  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-LetBinding"/><code>LetBinding</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-LetValueBinding">LetValueBinding</a>  |  <a href="#prod-xquery40-LetSequenceBinding">LetSequenceBinding</a>  |  <a href="#prod-xquery40-LetArrayBinding">LetArrayBinding</a>  |  <a href="#prod-xquery40-LetMapBinding">LetMapBinding</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-LetClause"/><code><a href="#doc-xquery40-LetClause">LetClause</a></code></td><td>::=</td><td><code>"let"  (<a href="#prod-xquery40-LetBinding">LetBinding</a> ++ ",")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-LetMapBinding"/><code>LetMapBinding</code></td><td>::=</td><td><code>"$"  "{"  (<a href="#prod-xquery40-VarNameAndType">VarNameAndType</a> ++ ",")  "}"  <a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a>?  ":="  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-LetSequenceBinding"/><code>LetSequenceBinding</code></td><td>::=</td><td><code>"$"  "("  (<a href="#prod-xquery40-VarNameAndType">VarNameAndType</a> ++ ",")  ")"  <a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a>?  ":="  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-LetValueBinding"/><code>LetValueBinding</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-VarNameAndType">VarNameAndType</a>  ":="  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-LibraryModule"/><code>LibraryModule</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-ModuleDecl">ModuleDecl</a>
                        <a href="#prod-xquery40-Prolog">Prolog</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Literal"/><code><a href="#doc-xquery40-Literal">Literal</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-NumericLiteral">NumericLiteral</a>  |  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>  |  <a href="#prod-xquery40-QNameLiteral">QNameLiteral</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Lookup"/><code>Lookup</code></td><td>::=</td><td><code>"?"  <a href="#prod-xquery40-KeySpecifier">KeySpecifier</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-LookupExpr"/><code><a href="#doc-xquery40-LookupExpr">LookupExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-PostfixExpr">PostfixExpr</a>
                        <a href="#prod-xquery40-Lookup">Lookup</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-LookupWildcard"/><code>LookupWildcard</code></td><td>::=</td><td><code>"*"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-MainModule"/><code>MainModule</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-Prolog">Prolog</a>
                        <a href="#prod-xquery40-QueryBody">QueryBody</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-MapConstructor"/><code><a href="#doc-xquery40-MapConstructor">MapConstructor</a></code></td><td>::=</td><td><code>"map"?  "{"  (<a href="#prod-xquery40-MapConstructorEntry">MapConstructorEntry</a> ** ",")  "}"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-MapConstructorEntry"/><code>MapConstructorEntry</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-ExprSingle">ExprSingle</a>  (":"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-MappingArrowTarget"/><code>MappingArrowTarget</code></td><td>::=</td><td><code>"=!&gt;"  <a href="#prod-xquery40-ArrowTarget">ArrowTarget</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-MapType"/><code><a href="#doc-xquery40-MapType">MapType</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AnyMapType">AnyMapType</a>  |  <a href="#prod-xquery40-TypedMapType">TypedMapType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-MarkedNCName"/><code>MarkedNCName</code></td><td>::=</td><td><code>"#"  <a href="#prod-xquery40-NCName">NCName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-MethodCall"/><code><a href="#doc-xquery40-MethodCall">MethodCall</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-PostfixExpr">PostfixExpr</a>  "=?&gt;"  <a href="#prod-xquery40-NCName">NCName</a>
                        <a href="#prod-xquery40-PositionalArgumentList">PositionalArgumentList</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Module"/><code><a href="#doc-xquery40-Module">Module</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-VersionDecl">VersionDecl</a>?  (<a href="#prod-xquery40-LibraryModule">LibraryModule</a>  |  <a href="#prod-xquery40-MainModule">MainModule</a>)</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ModuleDecl"/><code><a href="#doc-xquery40-ModuleDecl">ModuleDecl</a></code></td><td>::=</td><td><code>"module"  "namespace"  <a href="#prod-xquery40-NCName">NCName</a>  "="  <a href="#prod-xquery40-URILiteral">URILiteral</a>
                        <a href="#prod-xquery40-Separator">Separator</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ModuleImport"/><code><a href="#doc-xquery40-ModuleImport">ModuleImport</a></code></td><td>::=</td><td><code>"import"  "module"  ("namespace"  <a href="#prod-xquery40-NCName">NCName</a>  "=")?  <a href="#prod-xquery40-URILiteral">URILiteral</a>  ("at"  (<a href="#prod-xquery40-URILiteral">URILiteral</a> ++ ","))?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-MultiplicativeExpr"/><code>MultiplicativeExpr</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-UnionExpr">UnionExpr</a>  (("*"  |  "×"  |  "div"  |  "÷"  |  "idiv"  |  "mod")  <a href="#prod-xquery40-UnionExpr">UnionExpr</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NamedFunctionRef"/><code><a href="#doc-xquery40-NamedFunctionRef">NamedFunctionRef</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EQName">EQName</a>  "#"  <a href="#prod-xquery40-IntegerLiteral">IntegerLiteral</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-reserved-function-names">xgc: reserved-function-names</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NamedRecordTypeDecl"/><code><a href="#doc-xquery40-NamedRecordTypeDecl">NamedRecordTypeDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#prod-xquery40-Annotation">Annotation</a>*  "record"  <a href="#prod-xquery40-EQName">EQName</a>  "("  (<a href="#prod-xquery40-ExtendedFieldDeclaration">ExtendedFieldDeclaration</a> ** ",")  <a href="#prod-xquery40-ExtensibleFlag">ExtensibleFlag</a>?  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NamespaceDecl"/><code><a href="#doc-xquery40-NamespaceDecl">NamespaceDecl</a></code></td><td>::=</td><td><code>"declare"  "namespace"  <a href="#prod-xquery40-NCName">NCName</a>  "="  <a href="#prod-xquery40-URILiteral">URILiteral</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NamespaceNodeTest"/><code>NamespaceNodeTest</code></td><td>::=</td><td><code>"namespace-node"  "("  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NameTest"/><code>NameTest</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EQName">EQName</a>  |  <a href="#prod-xquery40-Wildcard">Wildcard</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NameTestUnion"/><code>NameTestUnion</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-NameTest">NameTest</a> ++ "|")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NextVar"/><code>NextVar</code></td><td>::=</td><td><code>"next"  <a href="#prod-xquery40-VarName">VarName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NodeComp"/><code>NodeComp</code></td><td>::=</td><td><code>"is"  |  "is-not"  |  <a href="#prod-xquery40-NodePrecedes">NodePrecedes</a>  |  <a href="#prod-xquery40-NodeFollows">NodeFollows</a>  |  "precedes-or-is"  |  "follows-or-is"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NodeConstructor"/><code><a href="#doc-xquery40-NodeConstructor">NodeConstructor</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-DirectConstructor">DirectConstructor</a>
                        <br/>|  <a href="#prod-xquery40-ComputedConstructor">ComputedConstructor</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NodeFollows"/><code>NodeFollows</code></td><td>::=</td><td><code>"&gt;&gt;"  |  "follows"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NodeKindTest"/><code>NodeKindTest</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-DocumentTest">DocumentTest</a>
                        <br/>|  <a href="#prod-xquery40-ElementTest">ElementTest</a>
                        <br/>|  <a href="#doc-xquery40-AttributeTest">AttributeTest</a>
                        <br/>|  <a href="#prod-xquery40-SchemaElementTest">SchemaElementTest</a>
                        <br/>|  <a href="#prod-xquery40-SchemaAttributeTest">SchemaAttributeTest</a>
                        <br/>|  <a href="#prod-xquery40-PITest">PITest</a>
                        <br/>|  <a href="#prod-xquery40-CommentTest">CommentTest</a>
                        <br/>|  <a href="#prod-xquery40-TextTest">TextTest</a>
                        <br/>|  <a href="#prod-xquery40-NamespaceNodeTest">NamespaceNodeTest</a>
                        <br/>|  <a href="#prod-xquery40-AnyNodeKindTest">AnyNodeKindTest</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NodePrecedes"/><code>NodePrecedes</code></td><td>::=</td><td><code>"&lt;&lt;"  |  "precedes"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NodeTest"/><code><a href="#doc-xquery40-NodeTest">NodeTest</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-UnionNodeTest">UnionNodeTest</a>  |  <a href="#prod-xquery40-SimpleNodeTest">SimpleNodeTest</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NumericLiteral"/><code><a href="#doc-xquery40-NumericLiteral">NumericLiteral</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-IntegerLiteral">IntegerLiteral</a>  |  <a href="#prod-xquery40-HexIntegerLiteral">HexIntegerLiteral</a>  |  <a href="#prod-xquery40-BinaryIntegerLiteral">BinaryIntegerLiteral</a>  |  <a href="#prod-xquery40-DecimalLiteral">DecimalLiteral</a>  |  <a href="#prod-xquery40-DoubleLiteral">DoubleLiteral</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-OccurrenceIndicator"/><code>OccurrenceIndicator</code></td><td>::=</td><td><code>"?"  |  "*"  |  "+"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-occurrence-indicators">xgc: occurrence-indicators</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-OptionDecl"/><code><a href="#doc-xquery40-OptionDecl">OptionDecl</a></code></td><td>::=</td><td><code>"declare"  "option"  <a href="#prod-xquery40-EQName">EQName</a>
                        <a href="#doc-xquery40-StringLiteral">StringLiteral</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-OrderByClause"/><code><a href="#doc-xquery40-OrderByClause">OrderByClause</a></code></td><td>::=</td><td><code>"stable"?  "order"  "by"  (<a href="#prod-xquery40-OrderSpec">OrderSpec</a> ++ ",")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-OrderedExpr"/><code><a href="#doc-xquery40-OrderedExpr">OrderedExpr</a></code></td><td>::=</td><td><code>"ordered"  <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-OrderingModeDecl"/><code><a href="#doc-xquery40-OrderingModeDecl">OrderingModeDecl</a></code></td><td>::=</td><td><code>"declare"  "ordering"  ("ordered"  |  "unordered")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-OrderModifier"/><code>OrderModifier</code></td><td>::=</td><td><code>("ascending"  |  "descending")?  ("empty"  ("greatest"  |  "least"))?  ("collation"  <a href="#prod-xquery40-URILiteral">URILiteral</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-OrderSpec"/><code>OrderSpec</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                        <a href="#prod-xquery40-OrderModifier">OrderModifier</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-OrExpr"/><code><a href="#doc-xquery40-OrExpr">OrExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AndExpr">AndExpr</a>  ("or"  <a href="#prod-xquery40-AndExpr">AndExpr</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-OtherwiseExpr"/><code><a href="#doc-xquery40-OtherwiseExpr">OtherwiseExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-StringConcatExpr">StringConcatExpr</a>  ("otherwise"  <a href="#prod-xquery40-StringConcatExpr">StringConcatExpr</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ParamList"/><code>ParamList</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-VarNameAndType">VarNameAndType</a> ** ",")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ParamListWithDefaults"/><code>ParamListWithDefaults</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-ParamWithDefault">ParamWithDefault</a> ++ ",")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ParamWithDefault"/><code>ParamWithDefault</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-VarNameAndType">VarNameAndType</a>  (":="  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ParenthesizedExpr"/><code><a href="#doc-xquery40-ParenthesizedExpr">ParenthesizedExpr</a></code></td><td>::=</td><td><code>"("  <a href="#prod-xquery40-Expr">Expr</a>?  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PathExpr"/><code><a href="#doc-xquery40-PathExpr">PathExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AbsolutePathExpr">AbsolutePathExpr</a>
                        <br/>|  <a href="#prod-xquery40-RelativePathExpr">RelativePathExpr</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-leading-lone-slash">xgc: leading-lone-slash</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PipelineExpr"/><code><a href="#doc-xquery40-PipelineExpr">PipelineExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-ArrowExpr">ArrowExpr</a>  ("-&gt;"  <a href="#prod-xquery40-ArrowExpr">ArrowExpr</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PITest"/><code>PITest</code></td><td>::=</td><td><code>"processing-instruction"  "("  (<a href="#prod-xquery40-NCName">NCName</a>  |  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>)?  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PositionalArgumentList"/><code>PositionalArgumentList</code></td><td>::=</td><td><code>"("  <a href="#prod-xquery40-PositionalArguments">PositionalArguments</a>?  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PositionalArguments"/><code>PositionalArguments</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-Argument">Argument</a> ++ ",")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PositionalVar"/><code>PositionalVar</code></td><td>::=</td><td><code>"at"  <a href="#prod-xquery40-VarName">VarName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PostfixExpr"/><code><a href="#doc-xquery40-PostfixExpr">PostfixExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-PrimaryExpr">PrimaryExpr</a>  |  <a href="#prod-xquery40-FilterExpr">FilterExpr</a>  |  <a href="#prod-xquery40-DynamicFunctionCall">DynamicFunctionCall</a>  |  <a href="#prod-xquery40-LookupExpr">LookupExpr</a>  |  <a href="#prod-xquery40-MethodCall">MethodCall</a>  |  <a href="#prod-xquery40-FilterExprAM">FilterExprAM</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Pragma"/><code>Pragma</code></td><td>::=</td><td><code>"(#"  <a href="#prod-xquery40-S">S</a>
                        <a href="#prod-xquery40-EQName">EQName</a>  (<a href="#prod-xquery40-S">S</a>
                        <a href="#prod-xquery40-PragmaContents">PragmaContents</a>)?  "#)"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PragmaContents"/><code>PragmaContents</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-Char">Char</a>* - (Char* '#)' Char*))</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Predicate"/><code><a href="#doc-xquery40-Predicate">Predicate</a></code></td><td>::=</td><td><code>"["  <a href="#prod-xquery40-Expr">Expr</a>  "]"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PreserveMode"/><code>PreserveMode</code></td><td>::=</td><td><code>"preserve"  |  "no-preserve"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PreviousVar"/><code>PreviousVar</code></td><td>::=</td><td><code>"previous"  <a href="#prod-xquery40-VarName">VarName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PrimaryExpr"/><code><a href="#doc-xquery40-PrimaryExpr">PrimaryExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-Literal">Literal</a>
                        <br/>|  <a href="#prod-xquery40-VarRef">VarRef</a>
                        <br/>|  <a href="#prod-xquery40-ParenthesizedExpr">ParenthesizedExpr</a>
                        <br/>|  <a href="#prod-xquery40-ContextValueRef">ContextValueRef</a>
                        <br/>|  <a href="#prod-xquery40-FunctionCall">FunctionCall</a>
                        <br/>|  <a href="#prod-xquery40-OrderedExpr">OrderedExpr</a>
                        <br/>|  <a href="#prod-xquery40-UnorderedExpr">UnorderedExpr</a>
                        <br/>|  <a href="#prod-xquery40-NodeConstructor">NodeConstructor</a>
                        <br/>|  <a href="#prod-xquery40-FunctionItemExpr">FunctionItemExpr</a>
                        <br/>|  <a href="#prod-xquery40-MapConstructor">MapConstructor</a>
                        <br/>|  <a href="#prod-xquery40-ArrayConstructor">ArrayConstructor</a>
                        <br/>|  <a href="#prod-xquery40-StringTemplate">StringTemplate</a>
                        <br/>|  <a href="#prod-xquery40-StringConstructor">StringConstructor</a>
                        <br/>|  <a href="#prod-xquery40-UnaryLookup">UnaryLookup</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Prolog"/><code>Prolog</code></td><td>::=</td><td><code>((<a href="#prod-xquery40-DefaultNamespaceDecl">DefaultNamespaceDecl</a>  |  <a href="#prod-xquery40-Setter">Setter</a>  |  <a href="#prod-xquery40-NamespaceDecl">NamespaceDecl</a>  |  <a href="#prod-xquery40-Import">Import</a>)  <a href="#prod-xquery40-Separator">Separator</a>)*  ((<a href="#prod-xquery40-ContextValueDecl">ContextValueDecl</a>  |  <a href="#prod-xquery40-VarDecl">VarDecl</a>  |  <a href="#prod-xquery40-FunctionDecl">FunctionDecl</a>  |  <a href="#prod-xquery40-ItemTypeDecl">ItemTypeDecl</a>  |  <a href="#prod-xquery40-NamedRecordTypeDecl">NamedRecordTypeDecl</a>  |  <a href="#prod-xquery40-OptionDecl">OptionDecl</a>)  <a href="#prod-xquery40-Separator">Separator</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-QNameLiteral"/><code><a href="#doc-xquery40-QNameLiteral">QNameLiteral</a></code></td><td>::=</td><td><code>"#"  <a href="#prod-xquery40-EQName">EQName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-QuantifiedExpr"/><code><a href="#doc-xquery40-QuantifiedExpr">QuantifiedExpr</a></code></td><td>::=</td><td><code>("some"  |  "every")  (<a href="#prod-xquery40-QuantifierBinding">QuantifierBinding</a> ++ ",")  "satisfies"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-QuantifierBinding"/><code>QuantifierBinding</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-VarNameAndType">VarNameAndType</a>  "in"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-QueryBody"/><code>QueryBody</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-Expr">Expr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-QuotAttrValueContent"/><code>QuotAttrValueContent</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-QuotAttrContentChar">QuotAttrContentChar</a>
                        <br/>|  <a href="#prod-xquery40-CommonContent">CommonContent</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-RangeExpr"/><code><a href="#doc-xquery40-RangeExpr">RangeExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AdditiveExpr">AdditiveExpr</a>  ("to"  <a href="#prod-xquery40-AdditiveExpr">AdditiveExpr</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-RecordType"/><code><a href="#doc-xquery40-RecordType">RecordType</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AnyRecordType">AnyRecordType</a>  |  <a href="#prod-xquery40-TypedRecordType">TypedRecordType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-RegularItemType"/><code>RegularItemType</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AnyItemTest">AnyItemTest</a>  |  <a href="#prod-xquery40-NodeKindTest">NodeKindTest</a>  |  <a href="#prod-xquery40-GNodeType">GNodeType</a>  |  <a href="#prod-xquery40-JNodeType">JNodeType</a>  |  <a href="#prod-xquery40-MapType">MapType</a>  |  <a href="#prod-xquery40-ArrayType">ArrayType</a>  |  <a href="#prod-xquery40-RecordType">RecordType</a>  |  <a href="#prod-xquery40-EnumerationType">EnumerationType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-RelativePathExpr"/><code><a href="#doc-xquery40-RelativePathExpr">RelativePathExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-StepExpr">StepExpr</a>  (("/"  |  "//")  <a href="#prod-xquery40-StepExpr">StepExpr</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-RestrictedDynamicCall"/><code>RestrictedDynamicCall</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-VarRef">VarRef</a>  |  <a href="#prod-xquery40-ParenthesizedExpr">ParenthesizedExpr</a>  |  <a href="#prod-xquery40-FunctionItemExpr">FunctionItemExpr</a>  |  <a href="#prod-xquery40-MapConstructor">MapConstructor</a>  |  <a href="#prod-xquery40-ArrayConstructor">ArrayConstructor</a>)  <a href="#prod-xquery40-PositionalArgumentList">PositionalArgumentList</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ReturnClause"/><code><a href="#doc-xquery40-ReturnClause">ReturnClause</a></code></td><td>::=</td><td><code>"return"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SchemaAttributeTest"/><code><a href="#doc-xquery40-SchemaAttributeTest">SchemaAttributeTest</a></code></td><td>::=</td><td><code>"schema-attribute"  "("  <a href="#prod-xquery40-AttributeName">AttributeName</a>  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SchemaElementTest"/><code><a href="#doc-xquery40-SchemaElementTest">SchemaElementTest</a></code></td><td>::=</td><td><code>"schema-element"  "("  <a href="#prod-xquery40-ElementName">ElementName</a>  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SchemaImport"/><code><a href="#doc-xquery40-SchemaImport">SchemaImport</a></code></td><td>::=</td><td><code>"import"  "schema"  <a href="#prod-xquery40-SchemaPrefix">SchemaPrefix</a>?  <a href="#prod-xquery40-URILiteral">URILiteral</a>  ("at"  (<a href="#prod-xquery40-URILiteral">URILiteral</a> ++ ","))?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SchemaPrefix"/><code>SchemaPrefix</code></td><td>::=</td><td><code>("namespace"  <a href="#prod-xquery40-NCName">NCName</a>  "=")  |  ("fixed"?  "default"  "element"  "namespace")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Selector"/><code>Selector</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EQName">EQName</a>  |  <a href="#prod-xquery40-Wildcard">Wildcard</a>  |  ("get"  "("  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>  ")")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Separator"/><code>Separator</code></td><td>::=</td><td><code>";"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SequenceArrowTarget"/><code>SequenceArrowTarget</code></td><td>::=</td><td><code>"=&gt;"  <a href="#prod-xquery40-ArrowTarget">ArrowTarget</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SequenceType"/><code><a href="#doc-xquery40-SequenceType">SequenceType</a></code></td><td>::=</td><td><code>("empty-sequence"  "("  ")")<br/>|  (<a href="#prod-xquery40-ItemType">ItemType</a>
                        <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>?)</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SequenceTypeUnion"/><code>SequenceTypeUnion</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-SequenceType">SequenceType</a>  ("|"  <a href="#prod-xquery40-SequenceType">SequenceType</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Setter"/><code>Setter</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-BoundarySpaceDecl">BoundarySpaceDecl</a>  |  <a href="#prod-xquery40-DefaultCollationDecl">DefaultCollationDecl</a>  |  <a href="#prod-xquery40-BaseURIDecl">BaseURIDecl</a>  |  <a href="#prod-xquery40-ConstructionDecl">ConstructionDecl</a>  |  <a href="#prod-xquery40-OrderingModeDecl">OrderingModeDecl</a>  |  <a href="#prod-xquery40-EmptyOrderDecl">EmptyOrderDecl</a>  |  <a href="#prod-xquery40-CopyNamespacesDecl">CopyNamespacesDecl</a>  |  <a href="#prod-xquery40-DecimalFormatDecl">DecimalFormatDecl</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SimpleMapExpr"/><code><a href="#doc-xquery40-SimpleMapExpr">SimpleMapExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-PathExpr">PathExpr</a>  ("!"  <a href="#prod-xquery40-PathExpr">PathExpr</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SimpleNodeTest"/><code>SimpleNodeTest</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-TypeTest">TypeTest</a>  |  <a href="#prod-xquery40-Selector">Selector</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SlidingWindowClause"/><code>SlidingWindowClause</code></td><td>::=</td><td><code>"sliding"  "window"  <a href="#prod-xquery40-VarNameAndType">VarNameAndType</a>  "in"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                        <a href="#prod-xquery40-WindowStartCondition">WindowStartCondition</a>?  <a href="#prod-xquery40-WindowEndCondition">WindowEndCondition</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SquareArrayConstructor"/><code>SquareArrayConstructor</code></td><td>::=</td><td><code>"["  (<a href="#prod-xquery40-ExprSingle">ExprSingle</a> ** ",")  "]"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-StepExpr"/><code>StepExpr</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-PostfixExpr">PostfixExpr</a>  |  <a href="#prod-xquery40-AxisStep">AxisStep</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-StringConcatExpr"/><code><a href="#doc-xquery40-StringConcatExpr">StringConcatExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-RangeExpr">RangeExpr</a>  ("||"  <a href="#prod-xquery40-RangeExpr">RangeExpr</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-StringConstructor"/><code><a href="#doc-xquery40-StringConstructor">StringConstructor</a></code></td><td>::=</td><td><code>"``["  <a href="#prod-xquery40-StringConstructorContent">StringConstructorContent</a>  "]``"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-StringConstructorChars"/><code>StringConstructorChars</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-Char">Char</a>* - (Char* ('`{' | ']``') Char*))</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-StringConstructorContent"/><code>StringConstructorContent</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-StringConstructorChars">StringConstructorChars</a>  (<a href="#prod-xquery40-StringInterpolation">StringInterpolation</a>
                        <a href="#prod-xquery40-StringConstructorChars">StringConstructorChars</a>)*</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-StringInterpolation"/><code>StringInterpolation</code></td><td>::=</td><td><code>"`{"  <a href="#prod-xquery40-Expr">Expr</a>?  "}`"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-StringTemplate"/><code><a href="#doc-xquery40-StringTemplate">StringTemplate</a></code></td><td>::=</td><td><code>"`"  (<a href="#prod-xquery40-StringTemplateFixedPart">StringTemplateFixedPart</a>  |  <a href="#prod-xquery40-StringTemplateVariablePart">StringTemplateVariablePart</a>)*  "`"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-StringTemplateFixedPart"/><code>StringTemplateFixedPart</code></td><td>::=</td><td><code>((<a href="#prod-xquery40-Char">Char</a> - ('{' | '}' | '`'))  |  "{{"  |  "}}"  |  "``")+</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-StringTemplateVariablePart"/><code>StringTemplateVariablePart</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SwitchCaseClause"/><code>SwitchCaseClause</code></td><td>::=</td><td><code>("case"  <a href="#prod-xquery40-SwitchCaseOperand">SwitchCaseOperand</a>)+  "return"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SwitchCaseOperand"/><code>SwitchCaseOperand</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-Expr">Expr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SwitchCases"/><code>SwitchCases</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-SwitchCaseClause">SwitchCaseClause</a>+  "default"  "return"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SwitchComparand"/><code>SwitchComparand</code></td><td>::=</td><td><code>"("  <a href="#prod-xquery40-Expr">Expr</a>?  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-SwitchExpr"/><code><a href="#doc-xquery40-SwitchExpr">SwitchExpr</a></code></td><td>::=</td><td><code>"switch"  <a href="#prod-xquery40-SwitchComparand">SwitchComparand</a>  (<a href="#prod-xquery40-SwitchCases">SwitchCases</a>  |  <a href="#prod-xquery40-BracedSwitchCases">BracedSwitchCases</a>)</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TextTest"/><code>TextTest</code></td><td>::=</td><td><code>"text"  "("  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TreatExpr"/><code><a href="#doc-xquery40-TreatExpr">TreatExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-CastableExpr">CastableExpr</a>  ("treat"  "as"  <a href="#prod-xquery40-SequenceType">SequenceType</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TryCatchExpr"/><code><a href="#doc-xquery40-TryCatchExpr">TryCatchExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-TryClause">TryClause</a>  ((<a href="#prod-xquery40-CatchClause">CatchClause</a>+  <a href="#prod-xquery40-FinallyClause">FinallyClause</a>?)  |  <a href="#prod-xquery40-FinallyClause">FinallyClause</a>)</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TryClause"/><code>TryClause</code></td><td>::=</td><td><code>"try"  <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TumblingWindowClause"/><code>TumblingWindowClause</code></td><td>::=</td><td><code>"tumbling"  "window"  <a href="#prod-xquery40-VarNameAndType">VarNameAndType</a>  "in"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                        <a href="#prod-xquery40-WindowStartCondition">WindowStartCondition</a>?  <a href="#prod-xquery40-WindowEndCondition">WindowEndCondition</a>?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TypedArrayType"/><code>TypedArrayType</code></td><td>::=</td><td><code>"array"  "("  <a href="#prod-xquery40-SequenceType">SequenceType</a>  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TypeDeclaration"/><code>TypeDeclaration</code></td><td>::=</td><td><code>"as"  <a href="#prod-xquery40-SequenceType">SequenceType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TypedFunctionParam"/><code>TypedFunctionParam</code></td><td>::=</td><td><code>("$"  <a href="#prod-xquery40-EQName">EQName</a>  "as")?  <a href="#prod-xquery40-SequenceType">SequenceType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TypedFunctionType"/><code>TypedFunctionType</code></td><td>::=</td><td><code>("function"  |  "fn")  "("  (<a href="#prod-xquery40-TypedFunctionParam">TypedFunctionParam</a> ** ",")  ")"  "as"  <a href="#prod-xquery40-SequenceType">SequenceType</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TypedMapType"/><code>TypedMapType</code></td><td>::=</td><td><code>"map"  "("  <a href="#prod-xquery40-ItemType">ItemType</a>  ","  <a href="#prod-xquery40-SequenceType">SequenceType</a>  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TypedRecordType"/><code>TypedRecordType</code></td><td>::=</td><td><code>"record"  "("  (<a href="#prod-xquery40-FieldDeclaration">FieldDeclaration</a> ** ",")  <a href="#prod-xquery40-ExtensibleFlag">ExtensibleFlag</a>?  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TypeName"/><code>TypeName</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EQName">EQName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TypeswitchCases"/><code>TypeswitchCases</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-CaseClause">CaseClause</a>+  "default"  <a href="#prod-xquery40-VarName">VarName</a>?  "return"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TypeswitchExpr"/><code><a href="#doc-xquery40-TypeswitchExpr">TypeswitchExpr</a></code></td><td>::=</td><td><code>"typeswitch"  "("  <a href="#prod-xquery40-Expr">Expr</a>  ")"  (<a href="#prod-xquery40-TypeswitchCases">TypeswitchCases</a>  |  <a href="#prod-xquery40-BracedTypeswitchCases">BracedTypeswitchCases</a>)</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-TypeTest"/><code><a href="#doc-xquery40-TypeTest">TypeTest</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-RegularItemType">RegularItemType</a>  |  ("type"  "("  <a href="#prod-xquery40-SequenceType">SequenceType</a>  ")")</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-UnaryExpr"/><code><a href="#doc-xquery40-UnaryExpr">UnaryExpr</a></code></td><td>::=</td><td><code>("-"  |  "+")*  <a href="#prod-xquery40-ValueExpr">ValueExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-UnaryLookup"/><code><a href="#doc-xquery40-UnaryLookup">UnaryLookup</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-Lookup">Lookup</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-UnbracedActions"/><code>UnbracedActions</code></td><td>::=</td><td><code>"then"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>  "else"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-UnionExpr"/><code><a href="#doc-xquery40-UnionExpr">UnionExpr</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-IntersectExceptExpr">IntersectExceptExpr</a>  (("union"  |  "|")  <a href="#prod-xquery40-IntersectExceptExpr">IntersectExceptExpr</a>)*</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-UnionNodeTest"/><code>UnionNodeTest</code></td><td>::=</td><td><code>"("  (<a href="#prod-xquery40-SimpleNodeTest">SimpleNodeTest</a> ++ "|")  ")"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-UnorderedExpr"/><code>UnorderedExpr</code></td><td>::=</td><td><code>"unordered"  <a href="#prod-xquery40-EnclosedExpr">EnclosedExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-UnreservedName"/><code>UnreservedName</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-EQName">EQName</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-unreserved-name">xgc: unreserved-name</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-UnreservedNCName"/><code>UnreservedNCName</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-NCName">NCName</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-unreserved-name">xgc: unreserved-name</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-URILiteral"/><code>URILiteral</code></td><td>::=</td><td><code>
                        <a href="#doc-xquery40-StringLiteral">StringLiteral</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ValidateExpr"/><code><a href="#doc-xquery40-ValidateExpr">ValidateExpr</a></code></td><td>::=</td><td><code>"validate"  (<a href="#prod-xquery40-ValidationMode">ValidationMode</a>  |  ("type"  <a href="#prod-xquery40-TypeName">TypeName</a>))?  "{"  <a href="#prod-xquery40-Expr">Expr</a>  "}"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ValidationMode"/><code>ValidationMode</code></td><td>::=</td><td><code>"lax"  |  "strict"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ValueComp"/><code>ValueComp</code></td><td>::=</td><td><code>"eq"  |  "ne"  |  "lt"  |  "le"  |  "gt"  |  "ge"</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ValueExpr"/><code>ValueExpr</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-ValidateExpr">ValidateExpr</a>  |  <a href="#prod-xquery40-ExtensionExpr">ExtensionExpr</a>  |  <a href="#prod-xquery40-SimpleMapExpr">SimpleMapExpr</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-VarDecl"/><code><a href="#doc-xquery40-VarDecl">VarDecl</a></code></td><td>::=</td><td><code>"declare"  <a href="#prod-xquery40-Annotation">Annotation</a>*  "variable"  <a href="#prod-xquery40-VarNameAndType">VarNameAndType</a>  ((":="  <a href="#prod-xquery40-VarValue">VarValue</a>)  |  ("external"  (":="  <a href="#prod-xquery40-VarDefaultValue">VarDefaultValue</a>)?))</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-VarDefaultValue"/><code>VarDefaultValue</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-VarName"/><code>VarName</code></td><td>::=</td><td><code>"$"  <a href="#prod-xquery40-EQName">EQName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-VarNameAndType"/><code>VarNameAndType</code></td><td>::=</td><td><code>"$"  <a href="#prod-xquery40-EQName">EQName</a>
                        <a href="#prod-xquery40-TypeDeclaration">TypeDeclaration</a>?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-VarRef"/><code><a href="#doc-xquery40-VarRef">VarRef</a></code></td><td>::=</td><td><code>"$"  <a href="#prod-xquery40-EQName">EQName</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-VarValue"/><code>VarValue</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-VersionDecl"/><code><a href="#doc-xquery40-VersionDecl">VersionDecl</a></code></td><td>::=</td><td><code>"xquery"  (("encoding"  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>)  |  ("version"  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>  ("encoding"  <a href="#doc-xquery40-StringLiteral">StringLiteral</a>)?))  <a href="#prod-xquery40-Separator">Separator</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-WhereClause"/><code><a href="#doc-xquery40-WhereClause">WhereClause</a></code></td><td>::=</td><td><code>"where"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-WhileClause"/><code><a href="#doc-xquery40-WhileClause">WhileClause</a></code></td><td>::=</td><td><code>"while"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>
                     </code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Wildcard"/><code>Wildcard</code></td><td>::=</td><td><code>"*"<br/>|  (<a href="#prod-xquery40-NCName">NCName</a>  ":*")<br/>|  ("*:"  <a href="#prod-xquery40-NCName">NCName</a>)<br/>|  (<a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>  "*")</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-WindowClause"/><code><a href="#doc-xquery40-WindowClause">WindowClause</a></code></td><td>::=</td><td><code>"for"  (<a href="#prod-xquery40-TumblingWindowClause">TumblingWindowClause</a>  |  <a href="#prod-xquery40-SlidingWindowClause">SlidingWindowClause</a>)</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-WindowEndCondition"/><code>WindowEndCondition</code></td><td>::=</td><td><code>"only"?  "end"  <a href="#prod-xquery40-WindowVars">WindowVars</a>  ("when"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-WindowStartCondition"/><code>WindowStartCondition</code></td><td>::=</td><td><code>"start"  <a href="#prod-xquery40-WindowVars">WindowVars</a>  ("when"  <a href="#prod-xquery40-ExprSingle">ExprSingle</a>)?</code></td></tr><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-WindowVars"/><code>WindowVars</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-CurrentVar">CurrentVar</a>?  <a href="#prod-xquery40-PositionalVar">PositionalVar</a>?  <a href="#prod-xquery40-PreviousVar">PreviousVar</a>?  <a href="#prod-xquery40-NextVar">NextVar</a>?</code></td></tr></tbody></table><div class="div3">
<h4><a id="EBNFNotation"/>A.1.1 <a href="#EBNFNotation" style="text-decoration: none">Notation</a></h4><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#lexical-structure">⬇</a> <a href="#id-grammar">⬆</a></p><ol><li><p>The EBNF operators <code>++</code> and <code>**</code>
        have been introduced, for more concise representation of sequences using a character
        such as <code>","</code> as a separator. The notation is borrowed from Invisible XML.<i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1366">1366</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1498">1498</a>]</i></p></li></ol></div><p>
                  [<a id="symbol" title="symbol">Definition</a>: Each rule in the grammar defines one <b>symbol</b>,
          using the following format: </p><div class="exampleInner"><pre>symbol ::= expression</pre></div><p>
                  ]
               </p><p>
                  [<a id="terminal" title="terminal">Definition</a>: A <b>terminal</b> 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.] The following constructs are used to match strings
        of one or more characters in a terminal:</p><dl><dt class="label">[a-zA-Z]</dt><dd><p>matches any <a href="#prod-xquery40-Char">Char</a> with a value in the range(s) indicated
              (inclusive).</p></dd><dt class="label">[abc]</dt><dd><p>matches any <a href="#prod-xquery40-Char">Char</a> with a value among the characters enumerated.
            </p></dd><dt class="label">[^abc]</dt><dd><p>matches any <a href="#prod-xquery40-Char">Char</a> with a value not among the characters given.</p></dd><dt class="label">"string" or 'string'</dt><dd><p>matches the sequence of characters that appear inside the double or single quotation marks.</p></dd><dt class="label"> [http://www.w3.org/TR/REC-example/#NT-Example]</dt><dd><p>matches any string matched by the production defined in the external specification as
              per the provided reference.</p></dd></dl><p>Patterns (including the above constructs) can be combined with grammatical operators to
        form more complex patterns, matching more complex sets of character strings. In the examples
        that follow, <var>A</var> and <var>B</var> represent (sub-)patterns.</p><dl><dt class="label">(A)</dt><dd><p>
                           <code>A</code> is treated as a unit and may be combined as described in this list.</p></dd><dt class="label">A?</dt><dd><p>matches <code>A</code> or nothing; optional <code>A</code>.</p></dd><dt class="label">A B</dt><dd><p>matches <code>A</code> followed by <code>B</code>. This implicit operator has higher
              precedence than the choice operator <code>|</code>; thus <code>A B | C D</code> is 
              interpreted as <code>(A B) | (C D)</code>.</p></dd><dt class="label">A | B</dt><dd><p>matches <code>A</code> or <code>B</code> but not both.</p></dd><dt class="label">A - B</dt><dd><p>matches any string that matches <code>A</code> but does not match <code>B</code>.</p></dd><dt class="label">A+</dt><dd><p>matches one or more occurrences of <code>A</code>. Concatenation has higher
              precedence than choice; thus <code>A+ | B+</code> is identical to <code>(A+) |
                (B+)</code>.</p></dd><dt class="label">A*</dt><dd><p>matches zero or more occurrences of <code>A</code>. Concatenation has higher
              precedence than choice; thus <code>A* | B*</code> is identical to <code>(A*) |
                (B*)</code>
                        </p></dd><dt class="label">(A ++ B)</dt><dd><p>matches one or more occurrences of <code>A</code>, with one occurrence of <code>B</code>
              between adjacent occurrences of <code>A</code>. 
              The notation <code>A ++ B</code> is a shorthand for <code>A (B A)*</code>. The construct
              is always parenthesized to avoid ambiguity, and although in principle
              <code>B</code> could be any pattern, in practice the notation is used only when it is a simple string literal
              (typically but not invariably <code>","</code>).</p><p>For example, <code>(Digit ++ ".")</code> matches <code>1</code> or <code>1.2</code>
            or <code>1.2.3</code>.</p></dd><dt class="label">(A ** B)</dt><dd><p>matches zero or more occurrences of <code>A</code>, with one occurrence of <code>B</code>
              between adjacent occurrences of <code>A</code>.  
              The notation <code>A ** B</code> is a shorthand for <code>(A (B A)*)?</code>. The construct
              is always parenthesized to avoid ambiguity, and although in principle
              <code>B</code> could be any pattern, in practice the notation is used only when it is a simple string literal
              (typically but not invariably <code>","</code>).</p><p>For example, <code>"[" (Digit ** "|") "]"</code> matches <code>[]</code> or <code>[1]</code> or <code>[1|2]</code>
            or <code>[1|2|3]</code>.</p></dd></dl></div><div class="div3">
<h4><a id="extra-grammatical-constraints"/>A.1.2 <a href="#extra-grammatical-constraints" style="text-decoration: none">Extra-grammatical Constraints</a></h4><p>This section contains constraints on the EBNF productions, which are required to parse
        syntactically valid sentences. The notes below are referenced from the right side of the
        production, with the notation: <em>/* xgc: &lt;id&gt; */</em>.</p><div class="constraint"><p class="prefix"><a id="parse-note-leading-lone-slash"/><b>Constraint: leading-lone-slash</b></p><p>A single slash may appear either as a complete path expression or as the first part of a
          path expression in which it is followed by a <a href="#doc-xquery40-RelativePathExpr">RelativePathExpr</a>. In some cases, the next terminal after the slash is insufficient to
          allow a parser to distinguish these two possibilities: a <code>*</code> symbol or a
          keyword like <code>union</code> could be either an operator or a <a href="#prod-xquery40-NameTest">NameTest</a>. For example, the expression <code>/union/*</code> could be parsed
          either as <code>(/) union (/*)</code> or as <code>/child::union/child::*</code> (the
          second interpretation is the one chosen).</p><p>The situation where <code>/</code> is followed by <code>&lt;</code> is a little more
          complicated. In XPath, this is unambiguous: the <code>&lt;</code> can only indicate
          one of the operators <code>&lt;</code>, <code>&lt;=</code>, or <code>&lt;&lt;</code>.
          In XQuery, however, it can also be the start of a direct constructor: specifically,
          a direct constructor for an element node, processing instruction node, or comment node.
          These constructs are identified by the tokenizer, independently of their syntactic
          context, as described in <a href="#lexical-structure"><b>A.3 Lexical structure</b></a>.</p><p>The rule adopted is as follows: if the terminal immediately following a slash
          can form the start of a <a href="#doc-xquery40-RelativePathExpr">RelativePathExpr</a>, then the slash
          must be the beginning of a <a href="#doc-xquery40-PathExpr">PathExpr</a>, not the entirety of it.</p><p>The terminals that can form the start of a <a href="#doc-xquery40-RelativePathExpr">RelativePathExpr</a>
        are: <code>NCName</code>, <code>QName</code>, <code>URIQualifiedName</code>,
          <code>StringLiteral</code>, <code>NumericLiteral</code>, 
          <code>Wildcard</code>, and <code>StringTemplate</code>; 
        plus <code>@</code>
                     <code>.</code>
                     <code>..</code>
                     <code>*</code>
                     <code>$</code>
                     <code>?</code>
                     <code>??</code>
                     <code>%</code>
                     <code>(</code>
                     <code>[</code>; and in XQuery <code>StringConstructor</code> and <code>DirectConstructor</code>.
        </p><p>A single slash may be used as the left-hand argument of an operator by parenthesizing it:
            <code>(/) * 5</code>. The expression <code>5 *
            /</code>, on the other hand, is syntactically valid without parentheses.</p></div><div class="constraint"><p class="prefix"><a id="parse-note-unreserved-name"/><b>Constraint: unreserved-name</b></p><p>In a computed node constructor of the form
        <code>element <var>NNN</var> {}</code>, <code>attribute <var>NNN</var> {}</code>,
          <code>processing-instruction <var>NNN</var> {}</code>, or <code>namespace <var>NNN</var> {}</code>,
          XQuery 4.0 allows the name <var>NNN</var>
        to be written as a plain <code>NCName</code> only if it is not a language keyword: more specifically, if it
        is not one of the <a title="literal terminal" class="termref" href="#dt-literal-terminal">literal terminals</a> taking the form of
        an <code>NCName</code> that are listed in <a href="#lexical-structure"><b>A.3 Lexical structure</b></a>. If such names (for example
        <code>div</code> or <code>value</code>) are to be used as node names in a computed
        node constructor, they must be preceded with a leading <code>#</code> character.</p><p>This rule is new in XQuery 4.0, and represents a backwards incompatibility. To ease transition, implementations
        may provide an option to allow such names to be accepted with a warning that the construct is deprecated.
        The reason for the change is that the construct has proved an obstacle to extending the language without
        introducing ambiguity or extensive lookahead; it also makes syntax errors difficult to diagnose.</p></div><div class="constraint"><p class="prefix"><a id="parse-note-xml-version"/><b>Constraint: xml-version</b></p><p>The version of XML and XML Names (e.g. <a href="#XML">[XML 1.0]</a> and <a href="#XMLNAMES">[XML Names]</a>,
          or <a href="#XML1.1">[XML 1.1]</a> and <a href="#XMLNAMES11">[XML Names 1.1]</a>) is <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>. It is recommended that
          the latest applicable version be used (even if it is published later than this
          specification). The EBNF in this specification links only to the 1.0 versions. Note also
          that these external productions follow the whitespace rules of their respective
          specifications, and not the rules of this specification, in particular <a href="#DefaultWhitespaceHandling"><b>A.3.4.1 Default Whitespace Handling</b></a>. Thus <code>prefix : localname</code> is not a
          syntactically valid <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> for purposes of this
          specification, just as it is not permitted in a XML document. Also, comments are not
          permissible on either side of the colon. Also extra-grammatical constraints such as
          well-formedness constraints must be taken into account.</p><p>XML 1.0 and XML 1.1 differ in their handling of C0 control characters
          (specifically #x1 through #x1F, excluding #x9, #xA, and #xD) and C1 control characters
          (#x7F through #x9F). In XML 1.0, these C0 characters are prohibited, and the C1 characters
          are permitted. In XML 1.1, both sets of control characters are permitted, but only if
          written as character references. It is RECOMMENDED that implementations should follow the
          XML 1.1 rules in this respect; however, for backwards compatibility with <span class="xquery">XQuery 1.0</span>
          , implementations MAY allow C1 control characters
          to be used directly. </p><div class="note"><p class="prefix"><b>Note:</b></p><p>Direct use of C1 control characters often suggests a
              character encoding error, such as using encoding CP-1252 and mislabeling it as
              iso-8859-1.</p></div></div><div class="constraint"><p class="prefix"><a id="parse-note-reserved-function-names"/><b>Constraint: reserved-function-names</b></p><p>Unprefixed function names spelled the same way as language keywords could make the
          language impossible to parse. For instance, <code>element(foo)</code> could be taken either as
          a <a href="#doc-xquery40-FunctionCall">FunctionCall</a> or as an <a href="#doc-xquery40-ElementTest">ElementTest</a>. Therefore, an unprefixed function name must not be any of the names in
            <a href="#id-reserved-fn-names"><b>A.4 Reserved Function Names</b></a>.</p><p>A function named <code>if</code> can be called by binding its namespace to a prefix and using the
          prefixed form: <code>library:if(foo)</code> instead of <code>if(foo)</code>.</p></div><div class="constraint"><p class="prefix"><a id="parse-note-occurrence-indicators"/><b>Constraint: occurrence-indicators</b></p><p>As written, the grammar in <a href="#nt-bnf"><b>A XQuery 4.0 Grammar</b></a> is ambiguous for some forms using the
          <code>"+"</code>, <code>"?"</code> and <code>"*"</code>
                     <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicators</a>. 
          The ambiguity is resolved as follows: these operators are
          tightly bound to the <a href="#doc-xquery40-SequenceType">SequenceType</a> expression, and have higher
          precedence than other uses of these symbols. Any occurrence of <code>"+"</code>, 
          <code>"?"</code> or <code>"*"</code>, that follows a sequence type is assumed to be an occurrence indicator, which binds to
          the last <a href="#doc-xquery40-ItemType">ItemType</a> in the <a href="#doc-xquery40-SequenceType">SequenceType</a>.</p><p>Thus, <code>4 treat as item() + - 5</code> must be interpreted as <code>(4 treat as item()+) - 5</code>, taking the '+' as an
          occurrence indicator and the '-' as a subtraction operator. To force the interpretation of
          "+" as an addition operator (and the corresponding interpretation of the "-" as a unary
          minus), parentheses may be used: the form <code>(4 treat as item()) +
            -5</code> surrounds the <a href="#doc-xquery40-SequenceType">SequenceType</a> expression with
          parentheses and leads to the desired interpretation.</p><p>
                     <code>function () as xs:string *</code> is interpreted as <code>function () as (xs:string
            *)</code>, not as <code>(function () as xs:string) *</code>. Parentheses can be used as
          shown to force the latter interpretation.</p><p>This rule has as a consequence that certain forms which would otherwise be syntactically
          valid and unambiguous are not recognized: in <code>4 treat as item() + 5</code>, the <code>"+"</code> is taken as
          an <a href="#prod-xquery40-OccurrenceIndicator">OccurrenceIndicator</a>, and not as an operator, which
          means this is not a syntactically valid expression.</p></div></div><div class="div3">
<h4><a id="notes-on-parsing"/>A.1.3 <a href="#notes-on-parsing" style="text-decoration: none">Grammar Notes</a></h4><p>This section contains general notes on the EBNF productions, which may be helpful in
        understanding how to interpret and implement the EBNF. These notes are not normative. The
        notes below are referenced from the right side of the production, with the notation:
          <em>/* gn: &lt;id&gt; */</em>.</p><div class="note"><p class="prefix"><b>Note:</b></p><dl><dt class="label"><a id="parse-note-parens"/>grammar-note: parens</dt><dd><p>Lookahead is required to distinguish a <a href="#doc-xquery40-FunctionCall">FunctionCall</a> from
                an EQName or keyword followed by a <span class="xquery">
                                 <a href="#prod-xquery40-Pragma">Pragma</a> or </span>
                              <a href="#doc-xquery40-Comment">Comment</a>. For example: <code>address (: this
                  may be empty :)</code> may be mistaken for a call to a function named "address"
                unless this lookahead is employed. Another example is <code>for (:
                  whom the bell :) $tolls in 3 return $tolls</code>, where the keyword "for" must
                not be mistaken for a function name.</p></dd><dt class="label"><a id="parse-note-comments"/>grammar-note: comments</dt><dd><p>Comments are allowed everywhere that <a title="ignorable whitespace" class="termref" href="#IgnorableWhitespace">ignorable
                  whitespace</a> is allowed, and the <a href="#doc-xquery40-Comment">Comment</a> symbol
                does not explicitly appear on the right-hand side of the grammar (except in its own
                production). See <a href="#DefaultWhitespaceHandling"><b>A.3.4.1 Default Whitespace Handling</b></a>. <span class="xquery">Note that comments are not allowed in direct constructor content, though they are
                  allowed in nested <a href="#doc-xquery40-EnclosedExpr"> EnclosedExprs</a>.</span>
                           </p><p>A comment can contain nested comments, as long as all <code>"(:"</code> and <code>":)"</code> patterns are
                balanced, no matter where they occur within the outer comment.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Lexical analysis may typically handle nested comments by incrementing a counter
                  for each <code>"(:"</code> pattern, and decrementing the counter for each <code>":)"</code> pattern. The
                  comment does not terminate until the counter is back to zero.</p></div><p>Some illustrative examples:</p><ul><li><p>
                                    <code>(: commenting out a (: comment :) may be confusing, but often helpful
                      :)</code> is a syntactically valid <a href="#doc-xquery40-Comment">Comment</a>, since balanced nesting of comments
                    is allowed.</p></li><li><p>
                                    <code>"this is just a string :)"</code> is a syntactically
                    valid expression. However, <code>(: "this is just a string :)" :)</code> will
                    cause a syntax error. Likewise, <code>"this is another string
                      (:"</code> is a syntactically valid expression, but <code>(: "this is another
                      string (:" :)</code> will cause a syntax error. It is a limitation of nested
                    comments that literal content can cause unbalanced nesting of comments.</p></li><li><p>
                                    <code>for (: set up loop :) $i in $x return $i</code> is
                    syntactically valid, ignoring the comment.</p></li><li><p>
                                    <code>5 instance (: strange place for a comment :) of
                      xs:integer</code> is also syntactically valid.</p></li><li class="xquery"><p>
                                    <code>
                      &lt;eg (: an example:)&gt;{$i//title}&lt;/eg&gt;
                    </code> is not syntactically valid.</p></li><li class="xquery"><p>
                                    <code>
                      &lt;eg&gt; (: an example:) &lt;/eg&gt;
                    </code> is syntactically valid, but the characters that look like a comment are
                    in fact literal element content.</p></li></ul></dd></dl></div></div></div><div class="div2">
<h3><a id="productions-derived-from-XML"/>A.2 <a href="#productions-derived-from-XML" style="text-decoration: none">Productions Derived from XML</a></h3><p>Some productions are defined by reference to the XML and XML Names specifications (e.g.
      <a href="#XML">[XML 1.0]</a> and <a href="#XMLNAMES">[XML Names]</a>, or <a href="#XML1.1">[XML 1.1]</a> and <a href="#XMLNAMES11">[XML Names 1.1]</a>. <span class="xquery">It is implementation-defined</span> which version of these specifications is
      used; it is recommended that the latest applicable version be used (even if it is published
      later than this specification).</p><p>It is <a title="implementation defined" class="termref" href="#dt-implementation-defined">
      implementation-defined</a> whether the lexical rules of <a href="#XML">[XML 1.0]</a> and
      <a href="#XMLNAMES">[XML Names]</a> are followed, or alternatively, the lexical rules of <a href="#XML1.1">[XML 1.1]</a> and <a href="#XMLNAMES11">[XML Names 1.1]</a> are followed. Implementations that support the
      full <a href="#XML1.1">[XML 1.1]</a> character set <a title="should" class="termref" href="#should">SHOULD</a>, for purposes
      of interoperability, provide a mode that follows only the <a href="#XML">[XML 1.0]</a> and <a href="#XMLNAMES">[XML Names]</a> lexical rules.</p></div><div class="div2">
<h3><a id="lexical-structure"/>A.3 <a href="#lexical-structure" style="text-decoration: none">Lexical structure</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-reserved-fn-names">⬇</a> <a href="#EBNFNotation">⬆</a></p><ol><li><p>
        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.
      <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/327">327</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/519">519</a> 30 May 2023]</i></p></li></ol></div><p>This section describes how an XQuery 4.0 text is tokenized prior to parsing.</p><p>All keywords are case sensitive. Keywords are not reserved—that is, any <a title="lexical QName" class="termref" href="#dt-qname">lexical QName</a> may duplicate a keyword except as noted in <a href="#id-reserved-fn-names"><b>A.4 Reserved Function Names</b></a>.</p><p>Tokenizing an input string is a process that follows the following rules:</p><ul><li><p>
                     [<a id="dt-ordinary-production-rule" title="ordinary production rule">Definition</a>: An <b>ordinary production rule</b> 
        is a production rule in <a href="#id-grammar"><b>A.1 EBNF</b></a> that is not annotated <code>ws:explicit</code>.]
                  </p></li><li><p>
                     [<a id="dt-literal-terminal" title="literal terminal">Definition</a>: A <b>literal terminal</b> is a token appearing as a string 
        in quotation marks on the right-hand side of an <a title="ordinary production rule" class="termref" href="#dt-ordinary-production-rule">ordinary production rule</a>.]
                  </p><div class="note"><p class="prefix"><b>Note:</b></p><p>Strings that appear in other production rules do not qualify.
        <span class="xquery">For example, <code>"]]&gt;"</code> is not a literal terminal, because it appears only in the rule
        <a href="#prod-xquery40-CDataSection">CDataSection</a>, which is not an ordinary production rule; similarly <a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>
          does not qualify because it appears only in <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>, and <code>"0x"</code> does not qualify
        because it appears only in <a href="#prod-xquery40-HexIntegerLiteral">HexIntegerLiteral</a>.</span>
                     </p></div><p>
          The <a title="literal terminal" class="termref" href="#dt-literal-terminal">literal terminals</a>  in XQuery 4.0 are: <code>!</code>
                     <code>!=</code>
                     <code>#</code>
                     <code>$</code>
                     <code>%</code>
                     <code>(</code>
                     <code>)</code>
                     <code>*</code>
                     <code>+</code>
                     <code>,</code>
                     <code>.</code>
                     <code>..</code>
                     <code>/</code>
                     <code>//</code>
                     <code>:</code>
                     <code>::</code>
                     <code>:=</code>
                     <code>;</code>
                     <code>&lt;</code>
                     <code>&lt;&lt;</code>
                     <code>&lt;=</code>
                     <code>=</code>
                     <code>=!&gt;</code>
                     <code>=&gt;</code>
                     <code>=?&gt;</code>
                     <code>&gt;</code>
                     <code>&gt;=</code>
                     <code>&gt;&gt;</code>
                     <code>?</code>
                     <code>?[</code>
                     <code>@</code>
                     <code>[</code>
                     <code>]</code>
                     <code>`{</code>
                     <code>{</code>
                     <code>|</code>
                     <code>||</code>
                     <code>}</code>
                     <code>}`</code>
                     <code>×</code>
                     <code>÷</code>
                     <code>-</code>
                     <code>-&gt;</code>
                     <code>allowing</code>
                     <code>ancestor</code>
                     <code>ancestor-or-self</code>
                     <code>and</code>
                     <code>array</code>
                     <code>as</code>
                     <code>ascending</code>
                     <code>at</code>
                     <code>attribute</code>
                     <code>base-uri</code>
                     <code>boundary-space</code>
                     <code>by</code>
                     <code>case</code>
                     <code>cast</code>
                     <code>castable</code>
                     <code>catch</code>
                     <code>child</code>
                     <code>collation</code>
                     <code>comment</code>
                     <code>construction</code>
                     <code>context</code>
                     <code>copy-namespaces</code>
                     <code>count</code>
                     <code>decimal-format</code>
                     <code>decimal-separator</code>
                     <code>declare</code>
                     <code>default</code>
                     <code>descendant</code>
                     <code>descendant-or-self</code>
                     <code>descending</code>
                     <code>digit</code>
                     <code>div</code>
                     <code>document</code>
                     <code>document-node</code>
                     <code>element</code>
                     <code>else</code>
                     <code>empty</code>
                     <code>empty-sequence</code>
                     <code>encoding</code>
                     <code>end</code>
                     <code>enum</code>
                     <code>eq</code>
                     <code>every</code>
                     <code>except</code>
                     <code>exponent-separator</code>
                     <code>external</code>
                     <code>false</code>
                     <code>finally</code>
                     <code>fixed</code>
                     <code>fn</code>
                     <code>following</code>
                     <code>following-or-self</code>
                     <code>following-sibling</code>
                     <code>following-sibling-or-self</code>
                     <code>follows</code>
                     <code>follows-or-is</code>
                     <code>for</code>
                     <code>function</code>
                     <code>ge</code>
                     <code>get</code>
                     <code>gnode</code>
                     <code>greatest</code>
                     <code>group</code>
                     <code>grouping-separator</code>
                     <code>gt</code>
                     <code>idiv</code>
                     <code>if</code>
                     <code>import</code>
                     <code>in</code>
                     <code>infinity</code>
                     <code>inherit</code>
                     <code>instance</code>
                     <code>intersect</code>
                     <code>is</code>
                     <code>is-not</code>
                     <code>item</code>
                     <code>jnode</code>
                     <code>key</code>
                     <code>lax</code>
                     <code>le</code>
                     <code>least</code>
                     <code>let</code>
                     <code>lt</code>
                     <code>map</code>
                     <code>member</code>
                     <code>minus-sign</code>
                     <code>mod</code>
                     <code>module</code>
                     <code>namespace</code>
                     <code>namespace-node</code>
                     <code>NaN</code>
                     <code>ne</code>
                     <code>next</code>
                     <code>no-inherit</code>
                     <code>no-preserve</code>
                     <code>node</code>
                     <code>of</code>
                     <code>only</code>
                     <code>option</code>
                     <code>or</code>
                     <code>order</code>
                     <code>ordered</code>
                     <code>ordering</code>
                     <code>otherwise</code>
                     <code>parent</code>
                     <code>pattern-separator</code>
                     <code>per-mille</code>
                     <code>percent</code>
                     <code>precedes</code>
                     <code>precedes-or-is</code>
                     <code>preceding</code>
                     <code>preceding-or-self</code>
                     <code>preceding-sibling</code>
                     <code>preceding-sibling-or-self</code>
                     <code>preserve</code>
                     <code>previous</code>
                     <code>processing-instruction</code>
                     <code>record</code>
                     <code>return</code>
                     <code>satisfies</code>
                     <code>schema</code>
                     <code>schema-attribute</code>
                     <code>schema-element</code>
                     <code>self</code>
                     <code>sliding</code>
                     <code>some</code>
                     <code>stable</code>
                     <code>start</code>
                     <code>strict</code>
                     <code>strip</code>
                     <code>switch</code>
                     <code>text</code>
                     <code>then</code>
                     <code>to</code>
                     <code>treat</code>
                     <code>true</code>
                     <code>try</code>
                     <code>tumbling</code>
                     <code>type</code>
                     <code>typeswitch</code>
                     <code>union</code>
                     <code>unordered</code>
                     <code>validate</code>
                     <code>value</code>
                     <code>variable</code>
                     <code>version</code>
                     <code>when</code>
                     <code>where</code>
                     <code>while</code>
                     <code>window</code>
                     <code>xquery</code>
                     <code>zero-digit</code> 
                  </p></li><li><p>
                     [<a id="dt-variable-terminal" title="variable terminal">Definition</a>: A <b>variable terminal</b> is an instance
        of a production rule that is not itself an <a title="ordinary production rule" class="termref" href="#dt-ordinary-production-rule">ordinary production rule</a> but that is named (directly) on the right-hand
        side of an <a title="ordinary production rule" class="termref" href="#dt-ordinary-production-rule">ordinary production rule</a>.]
                  </p><p>
          The <a title="variable terminal" class="termref" href="#dt-variable-terminal">variable terminals</a> in XQuery 4.0 are: <a href="#prod-xquery40-BinaryIntegerLiteral">BinaryIntegerLiteral</a>
                     <a href="#prod-xquery40-CDataSection">CDataSection</a>
                     <a href="#prod-xquery40-DecimalLiteral">DecimalLiteral</a>
                     <a href="#prod-xquery40-DirCommentConstructor">DirCommentConstructor</a>
                     <a href="#prod-xquery40-DirElemConstructor">DirElemConstructor</a>
                     <a href="#prod-xquery40-DirPIConstructor">DirPIConstructor</a>
                     <a href="#prod-xquery40-DoubleLiteral">DoubleLiteral</a>
                     <a href="#prod-xquery40-HexIntegerLiteral">HexIntegerLiteral</a>
                     <a href="#prod-xquery40-IntegerLiteral">IntegerLiteral</a>
                     <code>NCName</code>
                     <a href="#prod-xquery40-Pragma">Pragma</a>
                     <a href="#prod-xquery40-QName">QName</a>
                     <a href="#prod-xquery40-StringConstructor">StringConstructor</a>
                     <a href="#prod-xquery40-StringLiteral">StringLiteral</a>
                     <a href="#prod-xquery40-StringTemplate">StringTemplate</a>
                     <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                     <a href="#prod-xquery40-Wildcard">Wildcard</a> 
                  </p></li><li><p>
                     [<a id="dt-complex-terminal" title="complex terminal">Definition</a>: A <b>complex terminal</b> is
        a <a title="variable terminal" class="termref" href="#dt-variable-terminal">variable terminal</a> whose production rule references, directly or indirectly, an 
        <a title="ordinary production rule" class="termref" href="#dt-ordinary-production-rule">ordinary production rule</a>.]
                  </p><p>
          The <a title="complex terminal" class="termref" href="#dt-complex-terminal">complex terminals</a>  in XQuery 4.0 are: <a href="#prod-xquery40-DirElemConstructor">DirElemConstructor</a>
                     <a href="#prod-xquery40-Pragma">Pragma</a>
                     <a href="#prod-xquery40-StringConstructor">StringConstructor</a>
                     <a href="#prod-xquery40-StringTemplate">StringTemplate</a> 
                  </p><div class="note"><p class="prefix"><b>Note:</b></p><p>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.</p></div></li><li><p>Tokenization is the process of splitting the supplied input string into a sequence of terminals, where each
      terminal is either a <a title="literal terminal" class="termref" href="#dt-literal-terminal">literal terminal</a> or a <a title="variable terminal" class="termref" href="#dt-variable-terminal">variable terminal</a> (which may itself
      be a <a title="complex terminal" class="termref" href="#dt-complex-terminal">complex terminal</a>). Tokenization is done by repeating the following steps:</p><ol class="enumar"><li><p>Starting at the current position, skip any whitespace and comments.</p></li><li><p>If the current position is not the end of the input, then
          return the longest <a title="literal terminal" class="termref" href="#dt-literal-terminal">literal terminal</a> or <a title="variable terminal" class="termref" href="#dt-variable-terminal">variable terminal</a> 
        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.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Here are some examples showing the effect of the longest token rule:</p><ul><li><p>The expression <code>map{a:b}</code> is a syntax error. Although there is a 
              tokenization of this string that satisfies the grammar (by treating <code>a</code> and <code>b</code>
              as separate expressions), this tokenization does not satisfy the longest token rule,
              which requires that <code>a:b</code> is interpreted as a single <code>QName</code>.</p></li><li><p>The expression <code>10 div3</code> is a syntax error. The longest token rule requires that this
              be interpreted as two tokens (<code>"10"</code> and <code>"div3"</code>) even though it would
              be a valid expression if treated as three tokens (<code>"10"</code>, <code>"div"</code>, and <code>"3"</code>).</p></li><li><p>The expression <code>$x-$y</code> is a syntax error. This is interpreted as four tokens,
              (<code>"$"</code>, <code>"x-"</code>, <code>"$"</code>, and <code>"y"</code>).</p></li></ul></div><div class="note"><p class="prefix"><b>Note:</b></p><p>The lexical production rules for <a title="variable terminal" class="termref" href="#dt-variable-terminal">variable terminals</a>
        have been designed so that there is minimal need for backtracking. For example, if the next terminal
        starts with <code>"0x"</code>, then it can only be either a <a href="#prod-xquery40-HexIntegerLiteral">HexIntegerLiteral</a> or an error;
        if it starts with <code>"`"</code> (and not with <code>"```"</code>) then it can only be a
          <a href="#doc-xquery40-StringTemplate">StringTemplate</a> or an error. <span class="xquery">Direct element constructors
          and pragmas in XQuery, however, need special treatment, described below.</span>
                           </p><p>This convention, together with the rules for whitespace separation of tokens (see <a href="#id-terminal-delimitation"><b>A.3.2 Terminal Delimitation</b></a>) 
          means that the longest-token rule does not normally result in any need for backtracking. For example, suppose 
          that a <a title="variable terminal" class="termref" href="#dt-variable-terminal">variable terminal</a> has been identified as a <a href="#doc-xquery40-StringTemplate">StringTemplate</a> by examining
          its first few characters. If the construct turns out not to be a valid <a href="#doc-xquery40-StringTemplate">StringTemplate</a>, 
          an error can be reported without first considering whether there is some shorter token that might be returned instead.</p></div></li></ol></li><li class="xquery"><p>Tokenization requires special care when the current character is
      <span class="unicode-codepoint">U+003C</span> (<span class="unicode-name">LESS-THAN SIGN</span>, <code>&lt;</code>) :</p><ul><li><p>If the following character is <span class="unicode-codepoint">U+003D</span> (<span class="unicode-name">EQUALS SIGN</span>, <code>=</code>)  then the token can be identified
          unambiguously as the operator <code>&lt;=</code>.</p></li><li><p>If the following character is <span class="unicode-codepoint">U+003C</span> (<span class="unicode-name">LESS-THAN SIGN</span>, <code>&lt;</code>)  then the token can be identified
          unambiguously as the operator <code>&lt;&lt;</code>.</p></li><li><p>If the following character is <span class="unicode-codepoint">U+0021</span> (<span class="unicode-name">EXCLAMATION MARK</span>, <code>!</code>)  then the token can be identified
          unambiguously as being a <a href="#prod-xquery40-DirCommentConstructor">DirCommentConstructor</a> (a
            <a href="#prod-xquery40-CDataSection">CDataSection</a>, which also starts with <code>&lt;!</code> can appear
            only within a direct element constructor, not as a free-standing token).</p></li><li><p>If the following character is <span class="unicode-codepoint">U+003F</span> (<span class="unicode-name">QUESTION MARK</span>, <code>?</code>) , then the token is identified
          as a <a href="#doc-xquery40-DirPIConstructor">DirPIConstructor</a> if and only if a match for the
          relevant production (<code>"&lt;?" PITarget (S DirPIContents)? "?&gt;"</code>) is found. If there
          is no such match, then the string <code>"&lt;?"</code> is identified as a less-than operator
            followed by a lookup operator.</p></li><li><p>If the following character is a <a href="http://www.w3.org/TR/REC-xml/#NameStartChar">NameStartChar</a>
          then the token is identified as a <a href="#prod-xquery40-DirElemConstructor">DirElemConstructor</a> if and only
          if a match for the leading part of a <a href="#prod-xquery40-DirElemConstructor">DirElemConstructor</a> is
          found: specifically if a substring starting at the <span class="unicode-codepoint">U+003C</span> (<span class="unicode-name">LESS-THAN SIGN</span>, <code>&lt;</code>)  character matches one of
          the following regular expressions:</p><blockquote><p>
                              <code>^&lt;\i\c*\s*&gt;</code> (as in <code>&lt;element&gt;...</code>)<br/>
                              <code>^&lt;\i\c*\s*/&gt;</code>(as in <code>&lt;element/&gt;</code>)<br/>
                              <code>^&lt;\i\c*\s+\i\c*\s*=</code>(as in <code>&lt;element att=...</code>)</p></blockquote><p>If the content matches one of these regular expressions but further analysis shows that the subsequent
            content does not satisfy the <a href="#prod-xquery40-DirElemConstructor">DirElemConstructor</a> production,
            then a static error is reported.</p><p>If the content does not match any of these regular expressions then the token is identified
              as the less-than operator <code>&lt;</code>.</p></li><li><p>If the following character is any other character then the token can be identified
          unambiguously as the less-than operator <code>&lt;</code>.</p></li></ul><p>This analysis is done without regard to the syntactic context of the <span class="unicode-codepoint">U+003C</span> (<span class="unicode-name">LESS-THAN SIGN</span>, <code>&lt;</code>)  character.
        However, a tokenizer <span class="verb">may</span> avoid looking for a <a href="#doc-xquery40-DirPIConstructor">DirPIConstructor</a>
        or <a href="#prod-xquery40-DirElemConstructor">DirElemConstructor</a> if it knows that such a constructor cannot appear
        in the current syntactic context.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>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.</p></div><div class="note"><p class="prefix"><b>Note:</b></p><p>To avoid potential confusion, simply add whitespace after any less-than operator.</p></div></li><li class="xquery"><p>In XQuery the initial characters <code>(#</code> followed by whitespace are taken to signal the start
      of a <a href="#prod-xquery40-Pragma">Pragma</a>. 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 <code>(#</code>, for example
        a parenthesized QName literal.</p></li><li><p>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 <code>"div"</code> as a terminal, but it does not
      resolve whether this is the operator symbol <code>div</code>, or an <code>NCName</code> 
        or <code>QName</code> 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.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>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 
        <code>"parent::x"</code> is made up of three
      tokens, <code>"parent"</code>, <code>"::"</code>, and <code>"x"</code>. The name <code>"parent"</code>
        can be classified as an axis name as soon as the following token <code>"::"</code> 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 <code>"::"</code>.)</p></div></li><li><p>In the case of a <a title="complex terminal" class="termref" href="#dt-complex-terminal">complex terminal</a>, 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.</p></li></ul><div class="note"><p class="prefix"><b>Note:</b></p><p>Previous versions of this specification included the statement: 
      <em>When tokenizing, the longest possible match that is consistent with the EBNF is used.</em>
               </p><p>Different processors are known to have interpreted this in different ways. One interpretation,
      for example, was that the expression <code>10 div-3</code> should be split into four tokens (<code>10</code>,
      <code>div</code>, <code>-</code>, <code>3</code>) 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.</p><p>This rule has therefore been rewritten in version 4.0. Tokenization is now entirely insensitive to the
      grammatical context; <code>div-3</code> 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.</p><p>A more subtle example is: <code>(. &lt;?b ) cast as xs:integer?&gt; 0)</code>
      in which <code>&lt;?b ) cast as xs:integer?&gt;</code> is recognized as a single token (a direct
      processing instruction constructor) even though such a token cannot validly appear in this
      grammatical context.</p></div><div class="div3">
<h4><a id="terminal-symbols"/>A.3.1 <a href="#terminal-symbols" style="text-decoration: none">Terminal Symbols</a></h4>
<a id="d2e56271"/><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-IntegerLiteral"/><code>IntegerLiteral</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-Digits">Digits</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-HexIntegerLiteral"/><code>HexIntegerLiteral</code></td><td>::=</td><td><code>"0x"  <a href="#prod-xquery40-HexDigits">HexDigits</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-BinaryIntegerLiteral"/><code>BinaryIntegerLiteral</code></td><td>::=</td><td><code>"0b"  <a href="#prod-xquery40-BinaryDigits">BinaryDigits</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DecimalLiteral"/><code>DecimalLiteral</code></td><td>::=</td><td><code>("."  <a href="#prod-xquery40-Digits">Digits</a>)  |  (<a href="#prod-xquery40-Digits">Digits</a>  "."  <a href="#prod-xquery40-Digits">Digits</a>?)</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DoubleLiteral"/><code>DoubleLiteral</code></td><td>::=</td><td><code>(("."  <a href="#prod-xquery40-Digits">Digits</a>)  |  (<a href="#prod-xquery40-Digits">Digits</a>  ("."  <a href="#prod-xquery40-Digits">Digits</a>?)?))  [eE]  [+-]?  <a href="#prod-xquery40-Digits">Digits</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-StringLiteral"/><code><a href="#doc-xquery40-StringLiteral">StringLiteral</a></code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>  |  <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AposStringLiteral"/><code>AposStringLiteral</code></td><td>::=</td><td><code>"'"  (<a href="#prod-xquery40-PredefinedEntityRef">PredefinedEntityRef</a>  |  <a href="#prod-xquery40-CharRef">CharRef</a>  |  <a href="#prod-xquery40-EscapeApos">EscapeApos</a>  |  [^'&amp;])*  "'"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-QuotStringLiteral"/><code>QuotStringLiteral</code></td><td>::=</td><td><code>'"'  (<a href="#prod-xquery40-PredefinedEntityRef">PredefinedEntityRef</a>  |  <a href="#prod-xquery40-CharRef">CharRef</a>  |  <a href="#prod-xquery40-EscapeQuot">EscapeQuot</a>  |  [^"&amp;])*  '"'</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-URIQualifiedName"/><code>URIQualifiedName</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>  (<a href="#prod-xquery40-NCName">NCName</a>  ":")?  <a href="#prod-xquery40-NCName">NCName</a>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-BracedURILiteral"/><code>BracedURILiteral</code></td><td>::=</td><td><code>"Q"  "{"  (<a href="#prod-xquery40-PredefinedEntityRef">PredefinedEntityRef</a>  |  <a href="#prod-xquery40-CharRef">CharRef</a>  |  [^&amp;{}])*  "}"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PredefinedEntityRef"/><code>PredefinedEntityRef</code></td><td>::=</td><td><code>"&amp;"  ("lt"  |  "gt"  |  "amp"  |  "quot"  |  "apos")  ";"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-EscapeQuot"/><code>EscapeQuot</code></td><td>::=</td><td><code>'""'</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-EscapeApos"/><code>EscapeApos</code></td><td>::=</td><td><code>"''"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-ElementContentChar"/><code>ElementContentChar</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-Char">Char</a> - [{}&lt;&amp;])</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-QuotAttrContentChar"/><code>QuotAttrContentChar</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-Char">Char</a> - ["{}&lt;&amp;])</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-AposAttrContentChar"/><code>AposAttrContentChar</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-Char">Char</a> - ['{}&lt;&amp;])</code></td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Comment"/><code><a href="#doc-xquery40-Comment">Comment</a></code></td><td>::=</td><td><code>"(:"  (<a href="#prod-xquery40-CommentContents">CommentContents</a>  |  <a href="#prod-xquery40-Comment">Comment</a>)*  ":)"</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-comments">gn: comments</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-PITarget"/><code>PITarget</code></td><td>::=</td><td><code>
                        <a href="https://www.w3.org/TR/REC-xml/#NT-PITarget">[http://www.w3.org/TR/REC-xml#NT-PITarget]</a><sup><small>XML</small></sup>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-xml-version">xgc: xml-version</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CharRef"/><code>CharRef</code></td><td>::=</td><td><code>
                        <a href="https://www.w3.org/TR/REC-xml/#NT-CharRef">[http://www.w3.org/TR/REC-xml#NT-CharRef]</a><sup><small>XML</small></sup>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-xml-version">xgc: xml-version</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-QName"/><code>QName</code></td><td>::=</td><td><code>
                        <a href="https://www.w3.org/TR/REC-xml-names/#NT-QName">[http://www.w3.org/TR/REC-xml-names/#NT-QName]</a><sup><small>Names</small></sup>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-xml-version">xgc: xml-version</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-NCName"/><code>NCName</code></td><td>::=</td><td><code>
                        <a href="https://www.w3.org/TR/REC-xml-names/#NT-NCName">[http://www.w3.org/TR/REC-xml-names/#NT-NCName]</a><sup><small>Names</small></sup>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-xml-version">xgc: xml-version</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-S"/><code>S</code></td><td>::=</td><td><code>
                        <a href="https://www.w3.org/TR/REC-xml/#NT-S">[http://www.w3.org/TR/REC-xml#NT-S]</a><sup><small>XML</small></sup>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-xml-version">xgc: xml-version</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Char"/><code>Char</code></td><td>::=</td><td><code>
                        <a href="https://www.w3.org/TR/REC-xml/#NT-Char">[http://www.w3.org/TR/REC-xml#NT-Char]</a><sup><small>XML</small></sup>
                     </code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#parse-note-xml-version">xgc: xml-version</a>
                      */</td></tr></tbody></table><p>The following symbols are used only in the definition of terminal symbols; they are not
        terminal symbols in the grammar of <a href="#id-grammar"><b>A.1 EBNF</b></a>.</p>
<a id="d2e56603"/><table class="scrap"><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-Digits"/><code>Digits</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-DecDigit">DecDigit</a>  ((<a href="#prod-xquery40-DecDigit">DecDigit</a>  |  "_")*  <a href="#prod-xquery40-DecDigit">DecDigit</a>)?</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-DecDigit"/><code>DecDigit</code></td><td>::=</td><td><code>[0-9]</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-HexDigits"/><code>HexDigits</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-HexDigit">HexDigit</a>  ((<a href="#prod-xquery40-HexDigit">HexDigit</a>  |  "_")*  <a href="#prod-xquery40-HexDigit">HexDigit</a>)?</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-HexDigit"/><code>HexDigit</code></td><td>::=</td><td><code>[0-9a-fA-F]</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-BinaryDigits"/><code>BinaryDigits</code></td><td>::=</td><td><code>
                        <a href="#prod-xquery40-BinaryDigit">BinaryDigit</a>  ((<a href="#prod-xquery40-BinaryDigit">BinaryDigit</a>  |  "_")*  <a href="#prod-xquery40-BinaryDigit">BinaryDigit</a>)?</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-BinaryDigit"/><code>BinaryDigit</code></td><td>::=</td><td><code>[01]</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody><tbody><tr style="vertical-align:baseline;"><td><a id="prod-xquery40-CommentContents"/><code>CommentContents</code></td><td>::=</td><td><code>(<a href="#prod-xquery40-Char">Char</a>+ - (Char* ('(:' | ':)') Char*))</code></td></tr><tr><td/><td/><td style="text-align: right;" class="prodComment">/* 
                        <a href="#ws-explicit">ws: explicit</a>
                      */</td></tr></tbody></table></div><div class="div3">
<h4><a id="id-terminal-delimitation"/>A.3.2 <a href="#id-terminal-delimitation" style="text-decoration: none">Terminal Delimitation</a></h4><p>XQuery 4.0 expressions consist of <a href="#terminal-symbols">terminal symbols</a> and
          <a title="symbol separators" class="termref" href="#symbolseparators">symbol separators</a>.</p><p>
                  <span>
                     <a title="literal terminal" class="termref" href="#dt-literal-terminal">Literal</a> 
        and <a title="variable terminal" class="termref" href="#dt-variable-terminal">variable</a>
                  </span>
        terminal symbols are of two kinds: delimiting and non-delimiting.</p><p>
                  [<a id="delimiting-token" title="delimiting terminal symbol">Definition</a>: The <b>delimiting
            terminal symbols</b> are: <code>!</code>
                     <code>!=</code>
                     <code>#</code>
                     <code>#)</code>
                     <code>$</code>
                     <code>%</code>
                     <code>(</code>
                     <code>(#</code>
                     <code>)</code>
                     <code>*</code>
                     <code>*:</code>
                     <code>+</code>
                     <code>,</code>
                     <code>-</code>
                     <code>--&gt;</code>
                     <code>-&gt;</code>
                     <code>.</code>
                     <code>..</code>
                     <code>/</code>
                     <code>//</code>
                     <code>/&gt;</code>
                     <code>:</code>
                     <code>:*</code>
                     <code>::</code>
                     <code>:=</code>
                     <code>;</code>
                     <code>&lt;</code>
                     <code>&lt;!--</code>
                     <code>&lt;![CDATA[</code>
                     <code>&lt;/</code>
                     <code>&lt;&lt;</code>
                     <code>&lt;=</code>
                     <code>&lt;?</code>
                     <code>=</code>
                     <code>=!&gt;</code>
                     <code>=&gt;</code>
                     <code>=?&gt;</code>
                     <code>&gt;</code>
                     <code>&gt;=</code>
                     <code>&gt;&gt;</code>
                     <code>?</code>
                     <code>?&gt;</code>
                     <code>?[</code>
                     <code>@</code>
                     <code>[</code>
                     <code>]</code>
                     <code>]]&gt;</code>
                     <code>]``</code>
                     <code>`</code>
                     <code>``</code>
                     <code>``[</code>
                     <code>`{</code>
                     <code>{</code>
                     <code>{{</code>
                     <code>|</code>
                     <code>||</code>
                     <code>}</code>
                     <code>}`</code>
                     <code>}}</code>
                     <code>×</code>
                     <code>÷</code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>
                     <a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>
                     <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                     <a href="#prod-xquery40-S">S</a>
                     <a href="#prod-xquery40-StringLiteral">StringLiteral</a>
                     <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  ]
               </p><p>
                  [<a id="non-delimiting-token" title="non-delimiting terminal symbol">Definition</a>: The
            <b>non-delimiting terminal symbols</b> are: <code>allowing</code>
                     <code>ancestor</code>
                     <code>ancestor-or-self</code>
                     <code>and</code>
                     <code>array</code>
                     <code>as</code>
                     <code>ascending</code>
                     <code>at</code>
                     <code>attribute</code>
                     <code>base-uri</code>
                     <code>boundary-space</code>
                     <code>by</code>
                     <code>case</code>
                     <code>cast</code>
                     <code>castable</code>
                     <code>catch</code>
                     <code>child</code>
                     <code>collation</code>
                     <code>comment</code>
                     <code>construction</code>
                     <code>context</code>
                     <code>copy-namespaces</code>
                     <code>count</code>
                     <code>decimal-format</code>
                     <code>decimal-separator</code>
                     <code>declare</code>
                     <code>default</code>
                     <code>descendant</code>
                     <code>descendant-or-self</code>
                     <code>descending</code>
                     <code>digit</code>
                     <code>div</code>
                     <code>document</code>
                     <code>document-node</code>
                     <code>element</code>
                     <code>else</code>
                     <code>empty</code>
                     <code>empty-sequence</code>
                     <code>encoding</code>
                     <code>end</code>
                     <code>enum</code>
                     <code>eq</code>
                     <code>every</code>
                     <code>except</code>
                     <code>exponent-separator</code>
                     <code>external</code>
                     <code>false</code>
                     <code>finally</code>
                     <code>fixed</code>
                     <code>fn</code>
                     <code>following</code>
                     <code>following-or-self</code>
                     <code>following-sibling</code>
                     <code>following-sibling-or-self</code>
                     <code>follows</code>
                     <code>follows-or-is</code>
                     <code>for</code>
                     <code>function</code>
                     <code>ge</code>
                     <code>get</code>
                     <code>gnode</code>
                     <code>greatest</code>
                     <code>group</code>
                     <code>grouping-separator</code>
                     <code>gt</code>
                     <code>idiv</code>
                     <code>if</code>
                     <code>import</code>
                     <code>in</code>
                     <code>infinity</code>
                     <code>inherit</code>
                     <code>instance</code>
                     <code>intersect</code>
                     <code>is</code>
                     <code>is-not</code>
                     <code>item</code>
                     <code>jnode</code>
                     <code>key</code>
                     <code>lax</code>
                     <code>le</code>
                     <code>least</code>
                     <code>let</code>
                     <code>lt</code>
                     <code>map</code>
                     <code>member</code>
                     <code>minus-sign</code>
                     <code>mod</code>
                     <code>module</code>
                     <code>namespace</code>
                     <code>namespace-node</code>
                     <code>NaN</code>
                     <code>ne</code>
                     <code>next</code>
                     <code>no-inherit</code>
                     <code>no-preserve</code>
                     <code>node</code>
                     <code>of</code>
                     <code>only</code>
                     <code>option</code>
                     <code>or</code>
                     <code>order</code>
                     <code>ordered</code>
                     <code>ordering</code>
                     <code>otherwise</code>
                     <code>parent</code>
                     <code>pattern-separator</code>
                     <code>per-mille</code>
                     <code>percent</code>
                     <code>precedes</code>
                     <code>precedes-or-is</code>
                     <code>preceding</code>
                     <code>preceding-or-self</code>
                     <code>preceding-sibling</code>
                     <code>preceding-sibling-or-self</code>
                     <code>preserve</code>
                     <code>previous</code>
                     <code>processing-instruction</code>
                     <code>record</code>
                     <code>return</code>
                     <code>satisfies</code>
                     <code>schema</code>
                     <code>schema-attribute</code>
                     <code>schema-element</code>
                     <code>self</code>
                     <code>sliding</code>
                     <code>some</code>
                     <code>stable</code>
                     <code>start</code>
                     <code>strict</code>
                     <code>strip</code>
                     <code>switch</code>
                     <code>text</code>
                     <code>then</code>
                     <code>to</code>
                     <code>treat</code>
                     <code>true</code>
                     <code>try</code>
                     <code>tumbling</code>
                     <code>type</code>
                     <code>typeswitch</code>
                     <code>union</code>
                     <code>unordered</code>
                     <code>validate</code>
                     <code>value</code>
                     <code>variable</code>
                     <code>version</code>
                     <code>when</code>
                     <code>where</code>
                     <code>while</code>
                     <code>window</code>
                     <code>xquery</code>
                     <code>zero-digit</code>
                     <a href="#prod-xquery40-BinaryIntegerLiteral">BinaryIntegerLiteral</a>
                     <a href="#prod-xquery40-DecimalLiteral">DecimalLiteral</a>
                     <a href="#prod-xquery40-DoubleLiteral">DoubleLiteral</a>
                     <a href="#prod-xquery40-HexIntegerLiteral">HexIntegerLiteral</a>
                     <a href="#prod-xquery40-IntegerLiteral">IntegerLiteral</a>
                     <a href="#prod-xquery40-NCName">NCName</a>
                     <a href="#prod-xquery40-QName">QName</a>
                  ]
               </p><p>
                  [<a id="symbolseparators" title="symbol separators">Definition</a>: 
                     <a title="whitespace" class="termref" href="#Whitespace">Whitespace</a> and <a href="#doc-xquery40-Comment">Comments</a>
          function as <b>symbol separators</b>. 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 <a href="#ws-explicit">/* ws: explicit */</a>
          annotation in the EBNF, or by the <a href="#parse-note-xml-version">/* xgc: xml-version
            */</a> annotation.]
               </p><p>
                  <span>As a consequence of the longest token rule (see <a href="#lexical-structure"><b>A.3 Lexical structure</b></a>), </span>
        one or more <a title="symbol separators" class="termref" href="#symbolseparators">symbol separators</a>
        are required between two consecutive terminal symbols
        <var>T</var> and <var>U</var> (where <var>T</var> precedes <var>U</var>) when any of the following is true:
      </p><ul><li><p>
                        <var>T</var> and <var>U</var> are both <a title="non-delimiting terminal symbol" class="termref" href="#non-delimiting-token">non-delimiting terminal symbols</a>.</p></li><li><p>
                        <var>T</var> is a QName or an NCName and <var>U</var> is <code>"."</code> or <code>"-"</code>.</p></li><li><p>
                        <var>T</var> is a numeric literal and <var>U</var> is <code>"."</code>, or vice versa.</p></li></ul></div><div class="div3">
<h4><a id="id-eol-handling"/>A.3.3 <a href="#id-eol-handling" style="text-decoration: none">End-of-Line Handling</a></h4><p>Prior to parsing, the XQuery 4.0 processor must normalize all line breaks.
        The rules for line breaking follow the rules of <a href="#XML">[XML 1.0]</a> or <a href="#XML1.1">[XML 1.1]</a>. It is implementation-defined which version is used.</p><div class="div4">
<h5><a id="id-xml10-eol-handling"/>A.3.3.1 <a href="#id-xml10-eol-handling" style="text-decoration: none">XML 1.0 End-of-Line Handling</a></h5><p>For <a href="#XML">[XML 1.0]</a> processing, all of the following must be translated to a single
          <span class="unicode-codepoint">U+000A</span> (<span class="unicode-name">NEWLINE</span>) :</p><ol class="enumar"><li><p>the two-character sequence <span class="unicode-codepoint">U+000D</span> (<span class="unicode-name">CARRIAGE RETURN</span>) , <span class="unicode-codepoint">U+000A</span> (<span class="unicode-name">NEWLINE</span>) ;</p></li><li><p>any <span class="unicode-codepoint">U+000D</span> (<span class="unicode-name">CARRIAGE RETURN</span>)  character that is not immediately followed by <span class="unicode-codepoint">U+000A</span> (<span class="unicode-name">NEWLINE</span>) .</p></li></ol></div><div class="div4">
<h5><a id="id-xml11-eol-handling"/>A.3.3.2 <a href="#id-xml11-eol-handling" style="text-decoration: none">XML 1.1 End-of-Line Handling</a></h5><p>For <a href="#XML1.1">[XML 1.1]</a> processing, all of the following must be translated to a
          single <span class="unicode-codepoint">U+000A</span> (<span class="unicode-name">NEWLINE</span>)  character:</p><ol class="enumar"><li><p>the two-character sequence <span class="unicode-codepoint">U+000D</span> (<span class="unicode-name">CARRIAGE RETURN</span>) , <span class="unicode-codepoint">U+000A</span> (<span class="unicode-name">NEWLINE</span>) ;</p></li><li><p>the two-character sequence <span class="unicode-codepoint">U+000D</span> (<span class="unicode-name">CARRIAGE RETURN</span>) , <span class="unicode-codepoint">U+0085</span> (<span class="unicode-name">NEXT LINE, NEL</span>) ;</p></li><li><p>the single character <span class="unicode-codepoint">U+0085</span> (<span class="unicode-name">NEXT LINE, NEL</span>) ;</p></li><li><p>the single character <span class="unicode-codepoint">U+2028</span> (<span class="unicode-name">LINE SEPARATOR</span>) ;</p></li><li><p>any <span class="unicode-codepoint">U+000D</span> (<span class="unicode-name">CARRIAGE RETURN</span>)  character that is not immediately followed by <span class="unicode-codepoint">U+000A</span> (<span class="unicode-name">NEWLINE</span>)  or <span class="unicode-codepoint">U+0085</span> (<span class="unicode-name">NEXT LINE, NEL</span>) .</p></li></ol><p>The characters <span class="unicode-codepoint">U+0085</span> (<span class="unicode-name">NEXT LINE, NEL</span>)  and <span class="unicode-codepoint">U+2028</span> (<span class="unicode-name">LINE SEPARATOR</span>)  cannot be reliably recognized and translated
          until the <a href="#doc-xquery40-VersionDecl">VersionDecl</a> declaration (if present) has been
          read.</p></div></div><div class="div3">
<h4><a id="whitespace-rules"/>A.3.4 <a href="#whitespace-rules" style="text-decoration: none">Whitespace Rules</a></h4><div class="div4">
<h5><a id="DefaultWhitespaceHandling"/>A.3.4.1 <a href="#DefaultWhitespaceHandling" style="text-decoration: none">Default Whitespace Handling</a></h5><p>
                     [<a id="Whitespace" title="whitespace">Definition</a>: A <b>whitespace</b> character is any of
            the characters defined by <a href="http://www.w3.org/TR/REC-xml/#NT-S">
              [http://www.w3.org/TR/REC-xml/#NT-S]</a>.]
                  </p><p>
                     [<a id="IgnorableWhitespace" title="ignorable whitespace">Definition</a>: 
                        <b>Ignorable whitespace</b> consists of any <a title="whitespace" class="termref" href="#Whitespace">whitespace</a> characters that may occur between <a title="terminal" class="termref" href="#terminal">terminals</a>, unless these characters occur in the context of a production
            marked with a <a href="#ExplicitWhitespaceHandling"> ws:explicit</a> annotation, in
            which case they can occur only where explicitly specified (see <a href="#ExplicitWhitespaceHandling"><b>A.3.4.2 Explicit Whitespace Handling</b></a>).] Ignorable whitespace characters are not
          significant to the semantics of an expression. Whitespace is allowed before the first
          terminal and after the last terminal <span class="xquery">of a module</span>. Whitespace is allowed between any two <a title="terminal" class="termref" href="#terminal">terminals</a>. <a href="#doc-xquery40-Comment">Comments</a> may also act as
          "whitespace" to prevent two adjacent terminals from being recognized as one. Some
          illustrative examples are as follows:</p><ul><li><p>
                           <code>foo- foo</code> results in a syntax error. "foo-" would be recognized as a
              QName.</p></li><li><p>
                           <code>foo -foo</code> is syntactically equivalent to <code>foo - foo</code>, two QNames separated by a subtraction
              operator.</p></li><li><p>
                           <code>foo(: This is a comment :)- foo</code> is syntactically
              equivalent to <code>foo - foo</code>. This is because the comment prevents the two
              adjacent terminals from being recognized as one.</p></li><li><p>
                           <code>foo-foo</code> is syntactically equivalent to single QName.
              This is because "-" is a valid character in a QName. When used as an operator after
              the characters of a name, the "-" must be separated from the name, e.g. by using
              whitespace or parentheses.</p></li><li><p>
                           <code>10div 3</code> results in a syntax error.</p></li><li><p>
                           <code>10 div3</code> also results in a syntax error.</p></li><li><p>
                           <code>10div3</code> also results in a syntax error.</p></li></ul></div><div class="div4">
<h5><a id="ExplicitWhitespaceHandling"/>A.3.4.2 <a href="#ExplicitWhitespaceHandling" style="text-decoration: none">Explicit Whitespace Handling</a></h5><p>Explicit whitespace notation is specified with the EBNF productions, when it is different
          from the default rules, using the notation shown below. This notation is not inherited. In
          other words, if an EBNF rule is marked as /* ws: explicit */, the notation does not
          automatically apply to all the 'child' EBNF productions of that rule.</p><dl><dt class="label"><a id="ws-explicit"/>ws: explicit</dt><dd><p>/* ws: explicit */ means that the EBNF notation explicitly notates, with
                  <code>S</code> or otherwise, where <a title="whitespace" class="termref" href="#Whitespace">whitespace
                  characters</a> are allowed. In productions with the /* ws: explicit */
                  annotation, <a href="#DefaultWhitespaceHandling"><b>A.3.4.1 Default Whitespace Handling</b></a> does not apply.
		  Comments are not allowed in these productions except where the <a href="#doc-xquery40-Comment">Comment</a> non-terminal appears.
	      </p></dd></dl><p>For example, whitespace is not freely allowed
          by the direct constructor productions, but is specified explicitly in the grammar, in
          order to be more consistent with XML.</p></div></div></div><div class="div2">
<h3><a id="id-reserved-fn-names"/>A.4 <a href="#id-reserved-fn-names" style="text-decoration: none">Reserved Function Names</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-xq-static-context-components">⬇</a> <a href="#lexical-structure">⬆</a></p><ol><li><p>
          New keywords introducing item types, such as <code>record</code>, <code>item</code>, and <code>enum</code>,
            have been added to the list of reserved function names.
      <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1208">1208</a> PR <a href="https://github.com/qt4cg/qtspecs/pull/1212">1212</a> 15 May 2024]</i></p></li></ol></div><p>The following names are not allowed as function names in an unprefixed form, because they
    can appear, followed by a left parenthesis, at the start of an XPath or XQuery expression that
    is not a function call.</p><p>Names used in <a href="#doc-xquery40-TypeTest">NodeKindTests</a>:</p><blockquote><p>attribute<br/>comment<br/>document-node<br/>element<br/>namespace-node<br/>node<br/>schema-attribute<br/>schema-element<br/>processing-instruction<br/>text</p></blockquote><p>Names used as syntactic keywords:</p><blockquote><p>array<br/>enum<br/>fn<br/>function<br/>gnode<br/>get<br/>if<br/>item<br/>jnode<br/>map<br/>record<br/>switch<br/>type<br/>typeswitch</p></blockquote><div class="note"><p class="prefix"><b>Note:</b></p><p>As the language evolves in the future, it may become necessary to reserve additional
      names. Furthermore, use of common programming terms like <code>return</code> and
      <code>while</code> as function names may cause confusion even though they are not reserved. 
        The easiest way to avoid problems is to use an explicit namespace prefix in all calls 
        to user-defined functions.</p></div></div><div class="div2">
<h3><a id="id-precedence-order"/>A.5 <a href="#id-precedence-order" style="text-decoration: none">Precedence Order (Non-Normative)</a></h3><p>The grammar in <a href="#id-grammar"><b>A.1 EBNF</b></a> normatively defines built-in precedence among the
      operators of <span class="xquery">XQuery</span>. These operators are summarized here to make clear the order of their
      precedence from lowest to highest. The associativity column indicates the order in which
      operators of equal precedence in an expression are applied (further details below).</p><table class="medium"><tbody><tr><th>#</th><th>Operator</th><th>Associativity</th></tr><tr><td>1</td><td>
                        <a href="#doc-xquery40-Expr">, (comma)</a>
                     </td><td>associative</td></tr><tr><td>2</td><td>
                        <span class="xquery">
                           <a href="#doc-xquery40-FLWORExpr">FLWOR</a>,</span>
                        <a href="#doc-xquery40-QuantifiedExpr">some, every</a>, <span class="xquery">
                           <a href="#doc-xquery40-SwitchExpr">switch</a>,</span>
                        <span class="xquery">
                           <a href="#doc-xquery40-TypeswitchExpr">typeswitch</a>,</span>
                        <span class="xquery">
                           <a href="#doc-xquery40-TryCatchExpr">try</a>,</span>
                        <a href="#doc-xquery40-IfExpr">if</a>
                     </td><td>NA</td></tr><tr><td>3</td><td>
                        <a href="#doc-xquery40-OrExpr">or</a>
                     </td><td>associative</td></tr><tr><td>4</td><td>
                        <a href="#prod-xquery40-AndExpr">and</a>
                     </td><td>associative</td></tr><tr><td>5</td><td>
                        <a href="#prod-xquery40-ValueComp">eq, ne, lt, le, gt, ge</a>, <a href="#prod-xquery40-GeneralComp">=, !=, &lt;,
              &lt;=, &gt;, &gt;=</a>, <a href="#prod-xquery40-NodeComp">is, is-not, &lt;&lt;, &gt;&gt;, precedes, follows, precedes-or-is, follows-or-is</a>
                     </td><td>NA</td></tr><tr><td>6</td><td>
                        <a href="#doc-xquery40-OtherwiseExpr">otherwise</a>
                     </td><td>associative</td></tr><tr><td>7</td><td>
                        <a href="#doc-xquery40-StringConcatExpr">||</a>
                     </td><td>associative</td></tr><tr><td>8</td><td>
                        <a href="#doc-xquery40-RangeExpr">to</a>
                     </td><td>NA</td></tr><tr><td>9</td><td>
                        <a href="#doc-xquery40-AdditiveExpr">+, - (binary)</a>
                     </td><td>left-to-right</td></tr><tr><td>10</td><td>
                        <a href="#prod-xquery40-MultiplicativeExpr">*, div, idiv, mod</a>
                     </td><td>left-to-right</td></tr><tr><td>11</td><td>
                        <a href="#doc-xquery40-UnionExpr">union, |</a>
                     </td><td>associative</td></tr><tr><td>12</td><td>
                        <a href="#prod-xquery40-IntersectExceptExpr">intersect, except</a>
                     </td><td>left-to-right</td></tr><tr><td>13</td><td>
                        <a href="#doc-xquery40-InstanceofExpr">instance of</a>
                     </td><td>NA</td></tr><tr><td>14</td><td>
                        <a href="#doc-xquery40-TreatExpr">treat as</a>
                     </td><td>NA</td></tr><tr><td>15</td><td>
                        <a href="#doc-xquery40-CastableExpr">castable as</a>
                     </td><td>NA</td></tr><tr><td>16</td><td>
                        <a href="#doc-xquery40-CastExpr">cast as</a>
                     </td><td>NA</td></tr><tr><td>17</td><td>
                        <a href="#doc-xquery40-ArrowExpr">=&gt;, =!&gt;</a>
                     </td><td>left-to-right</td></tr><tr><td>18</td><td>
                        <a href="#doc-xquery40-UnaryExpr">-, + (unary)</a>
                     </td><td>right-to-left</td></tr><tr><td>19</td><td>
                        <a href="#doc-xquery40-SimpleMapExpr">!</a>
                     </td><td>left-to-right</td></tr><tr><td>20</td><td>
                        <a href="#doc-xquery40-PathExpr">/, //</a>
                     </td><td>left-to-right</td></tr><tr><td>21</td><td>
                        <a href="#doc-xquery40-Predicate">a[b]</a>, <a href="#doc-xquery40-FilterExprAM">a?[b]</a>, <a href="#prod-xquery40-Lookup">a?b, a??b</a>,
            <a href="#doc-xquery40-DynamicFunctionCall">a(b)</a>
                     </td><td>left-to-right</td></tr><tr><td>22</td><td>
                        <a href="#doc-xquery40-UnaryLookup">? (unary)</a>
                     </td><td>NA</td></tr></tbody></table><p>Entries in the <b>Associativity</b> column have the following meaning (where the symbol <code>⊙</code>
      represents any operator):</p><ul><li><p>
                     <b>associative</b> means that the order of evaluation is immaterial: for example <code>a, b, c</code>
      can be evaluated either as <code>(a, b), c</code> or as <code>a, (b, c)</code>, producing the same
      result either way.</p></li><li><p>
                     <b>NA</b> indicates that it is not possible to write an expression of the form <code>a ⊙ b ⊙ c</code>
      for this particular operator: for example, the grammar does not allow <code>a = b = c</code>.</p></li><li><p>
                     <b>left-to-right</b> means that for expressions using these operators, 
      <code>a ⊙ b ⊙ c</code> is evaluated as <code>(a ⊙ b) ⊙ c</code>. As a special case, the operators <code>+</code>
      and <code>*</code> are associative provided they are not mixed with other operators of the same precedence.</p></li><li><p>
                     <b>right-to-left</b> is used only for unary operators, and indicates that <code>⊙ ⊙ a</code>
      is evaluated as <code>⊙ (⊙ a)</code>
                  </p></li></ul><p>These rules do not constrain the order in which the operands of an expression are evaluated (which might affect
    error behavior). See also <a href="#errors"><b>2.4 Error Handling</b></a>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>Parentheses can be used to override the operator precedence in the usual way. Square
        brackets in an expression such as <code>A[B]</code>
                  <code>A?[B]</code>or serve two roles: they act as an operator causing B to
        be evaluated once for each item in the value of A, and they act as parentheses enclosing the
        expression B.</p><p>Curly braces in an expression such as validate { E } or ordered { E } perform a
        similar bracketing role to the parentheses in a function call, but with the difference in
        most cases that E is an Expr rather than ExprSingle, meaning that it can use the comma
        operator.</p></div></div></div><div class="div1 xquery">
<h2><a id="id-xq-context-components"/>B <a href="#id-xq-context-components" style="text-decoration: none">Context Components</a></h2><p>The tables in this section describe how values are assigned to
  the various components of the <a title="static context" class="termref" href="#dt-static-context">static context</a> and <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a>.</p><div class="div2">
<h3><a id="id-xq-static-context-components"/>B.1 <a href="#id-xq-static-context-components" style="text-decoration: none">Static Context Components</a></h3><div class="changes"><p class="changesHeading">Changes in 4.0 <a href="#id-reserved-fn-names">⬆</a></p><ol><li><p>
    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.
  <i>  [Issue <a href="https://github.com/qt4cg/qtspecs/issues/1343">1343</a> ]</i></p></li></ol></div><p>The following table describes the components of the <b>static context</b>. The following aspects of each component are described:</p><ul><li><p>
                     <em>Default initial value:</em> This is the
initial value of the component if it is not overridden or augmented by
the implementation or by a query.</p></li><li><p>
                     <em>Can be
overwritten or augmented by implementation:</em> Indicates whether
an XQuery implementation is allowed to replace the default initial
value of the component by a different, <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> value
and/or to augment the default initial value by additional <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>
values.</p></li><li><p>
                     <em>Can be overwritten or augmented by prolog:</em>
Indicates whether there are prolog declarations that can replace and/or augment
the initial value provided by default or by the implementation.
</p></li><li><p>
                     <em>Can be overwritten or augmented by expressions:</em>
Indicates whether there are expressions that can replace and/or augment
the value of the component for their subexpressions.
</p></li><li><p>
                     <em>Consistency
Rules:</em> Indicates rules that must be observed in assigning
values to the component. Additional consistency rules may be found in
<a href="#id-consistency-constraints"><b>2.3.6 Consistency Constraints</b></a>.</p></li></ul><table style="width:100%; border:1px solid" class="small"><caption>Static Context Components</caption><tbody><tr><th>Component</th><th>Default initial value</th><th>Can be overwritten or augmented by implementation?</th><th>Can be overwritten or augmented by prolog?</th><th>Can be overwritten or augmented by expressions?</th><th>Consistency rules</th></tr><tr><td>Statically known namespaces</td><td>See <a href="#id-namespaces-and-qnames"><b>2.1.4 Namespaces and QNames</b></a>
                     </td><td>overwriteable and augmentable (except for <code>xml</code>)</td><td>overwriteable and augmentable by <a href="#id-namespace-declaration"><b>5.13 Namespace Declaration</b></a>
                     </td><td>overwriteable and augmentable by element constructor</td><td>Only one namespace can be assigned to a given prefix
per lexical scope.</td></tr><tr><td>Default element/type namespace</td><td>no namespace</td><td>overwriteable</td><td>overwriteable by <a href="#id-default-namespace"><b>5.14 Default Namespace Declaration</b></a>
                     </td><td>overwriteable by element constructor</td><td>Only one default namespace per lexical scope.</td></tr><tr><td>In-scope variables</td><td>none</td><td>augmentable</td><td>overwriteable and augmentable by <a href="#id-variable-declarations"><b>5.16 Variable Declaration</b></a> and  <a href="#id-inline-func"><b>4.5.6 Inline Function Expressions</b></a>, augmentable by <a href="#id-module-import"><b>5.12 Module Import</b></a>
                     </td><td>overwriteable and augmentable by variable-binding expressions</td><td>Only one definition per variable per lexical scope.</td></tr><tr><td>Context value static type</td><td>item()</td><td>overwriteable</td><td>overwriteable by <a href="#id-context-value-declarations"><b>5.17 Context Value Declaration</b></a>
                     </td><td>overwriteable by expressions that set the context value</td><td>None.</td></tr><tr><td>Ordering mode</td><td>
                        <code>ordered</code>
                     </td><td>overwriteable</td><td>overwriteable by <a href="#id-default-ordering-decl"><b>5.7 Ordering Mode Declaration</b></a>
                     </td><td>overwriteable by expression</td><td>Value must be <code>ordered</code> or <code>unordered</code>.</td></tr><tr><td>Default function namespace</td><td>
                        <code>fn</code>
                     </td><td>overwriteable (not recommended)</td><td>overwriteable by <a href="#id-default-namespace"><b>5.14 Default Namespace Declaration</b></a>
                     </td><td>no</td><td>None.</td></tr><tr><td>In-scope schema types</td><td>built-in types in <code>xs</code>
                     </td><td>augmentable</td><td>augmentable by <a href="#id-schema-import"><b>5.11 Schema Import</b></a>
                     </td><td>no</td><td>Only one definition per global or local type.</td></tr><tr><td>In-scope element declarations</td><td>none</td><td>augmentable</td><td>augmentable by  <a href="#id-schema-import"><b>5.11 Schema Import</b></a>
                     </td><td>no</td><td>Only one definition per global or local element name.</td></tr><tr><td>In-scope attribute declarations</td><td>none</td><td>augmentable</td><td>augmentable by  <a href="#id-schema-import"><b>5.11 Schema Import</b></a>
                     </td><td>no</td><td>Only one definition per global or local attribute name.</td></tr><tr><td>Statically known function signatures</td><td>the signatures of the <a title="system function" class="termref" href="#dt-system-function">system functions</a>
                     </td><td>augmentable</td><td>augmentable by  <a href="#id-module-import"><b>5.12 Module Import</b></a> and by  <a href="#FunctionDeclns"><b>5.18 Function Declarations</b></a>; augmentable by  <a href="#id-schema-import"><b>5.11 Schema Import</b></a> (which adds constructor functions for user-defined types)</td><td>no</td><td>Each function must have a unique <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> and number of arguments.</td></tr><tr><td>Default collation</td><td>Unicode codepoint collation</td><td>overwriteable</td><td>overwriteable by <a href="#id-default-collation-declaration"><b>5.4 Default Collation Declaration</b></a>
                     </td><td>no</td><td>None.</td></tr><tr><td>Construction mode</td><td>
                        <code>preserve</code>
                     </td><td>overwriteable</td><td>overwriteable by <a href="#id-construction-declaration"><b>5.6 Construction Declaration</b></a>
                     </td><td>no</td><td>Value must be <code>preserve</code> or <code>strip</code>. </td></tr><tr><td>Default order for empty sequences</td><td>implementation-defined</td><td>overwriteable</td><td>overwriteable by <a href="#id-empty-order-decl"><b>5.8 Empty Order Declaration</b></a>
                     </td><td>no</td><td>Value must be <code>greatest</code> or <code>least</code>.</td></tr><tr><td>Boundary-space policy</td><td>
                        <code>strip</code>
                     </td><td>overwriteable</td><td>overwriteable by <a href="#id-boundary-space-decls"><b>5.3 Boundary-space Declaration</b></a>
                     </td><td>no</td><td>Value must be <code>preserve</code> or <code>strip</code>. </td></tr><tr><td>Copy-namespaces mode</td><td>
                        <code>inherit, preserve</code>
                     </td><td>overwriteable</td><td>overwriteable by <a href="#id-copy-namespaces-decl"><b>5.9 Copy-Namespaces Declaration</b></a>
                     </td><td>no</td><td>Value consists of <code>inherit</code> or <code>no-inherit</code>, and <code>preserve</code> or <code>no-preserve</code>.</td></tr><tr><td>Static Base URI</td><td>See rules in <a href="#id-base-uri-decl"><b>5.5 Base URI Declaration</b></a>
                     </td><td>overwriteable</td><td>overwriteable by <a href="#id-base-uri-decl"><b>5.5 Base URI Declaration</b></a>
                     </td><td>no</td><td>Value must be a valid lexical representation of the type xs:anyURI.</td></tr><tr><td>Statically known decimal formats</td><td>the default (unnamed) decimal format, which has an implementation-dependent value</td><td>augmentable</td><td>augmentable, using <a title="decimal-format         declaration" class="termref" href="#dt-decimal-format-decl">decimal format declarations</a>
                     </td><td>no</td><td>each QName uniquely identifies a decimal format</td></tr><tr><td>Statically known collations</td><td>only the default collation</td><td>augmentable</td><td>no</td><td>no</td><td>Each URI uniquely identifies a collation.</td></tr><tr><td>XPath 1.0 Compatibility Mode</td><td>
                        <code>false</code>
                     </td><td>no</td><td>no</td><td>no</td><td>Must be <code>false</code>.</td></tr></tbody></table></div><div class="div2">
<h3><a id="id-xq-evaluation-context-components"/>B.2 <a href="#id-xq-evaluation-context-components" style="text-decoration: none">Dynamic Context Components</a></h3><p>The following table describes the components of the <b>dynamic context</b>. The following aspects of each component are described:</p><ul><li><p>
                     <em>Default initial value:</em> This is the initial value of the component if it is not overridden or augmented by the implementation or by a query.</p></li><li><p>
                     <em>Can be overwritten or augmented by implementation:</em> Indicates whether an XQuery implementation is allowed to replace the default initial value of the component by a different <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> value and/or to augment the default initial value by additional <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> values.</p></li><li><p>
                     <em>Can be overwritten or augmented by prolog:</em>
Indicates whether there are prolog declarations that can replace and/or augment
the initial value provided by default or by the implementation.</p></li><li><p>
                     <em>Can be overwritten or augmented by expressions:</em>
Indicates whether there are expressions that can replace and/or augment
the value of the component for their subexpressions.</p></li><li><p>
                     <em>Consistency Rules:</em> Indicates rules that must be observed in assigning values to the component. Additional consistency rules may be found in <a href="#id-consistency-constraints"><b>2.3.6 Consistency Constraints</b></a>.</p></li></ul><table style="width:100%; border:1px solid" class="small"><caption>Dynamic Context Components</caption><tbody><tr><th>Component</th><th>Default initial value</th><th>Can be overwritten or augmented by implementation?</th><th>Can be overwritten or augmented by prolog?</th><th>Can be overwritten or augmented by expressions?</th><th>Consistency rules</th></tr><tr><td>Context value</td><td>none</td><td>overwriteable</td><td>overwriteable by a  <a href="#id-context-value-declarations"><b>5.17 Context Value Declaration</b></a> in the main module
  </td><td>overwritten during evaluation of path expressions and predicates</td><td>Must be the same in the dynamic context of every module in a query.
  </td></tr><tr><td>Context position</td><td>none</td><td>overwriteable</td><td>overwriteable by a  <a href="#id-context-value-declarations"><b>5.17 Context Value Declaration</b></a> in the main module
  </td><td>overwritten during evaluation of path expressions and predicates</td><td>If context value is defined, context position must be &gt;0 and &lt;= context size; else  context position is <a href="https://www.w3.org/TR/xpath-datamodel-31/#dt-absent">absent</a><sup><small>DM31</small></sup>. </td></tr><tr><td>Context size</td><td>none
  </td><td>overwriteable</td><td>overwriteable by a  <a href="#id-context-value-declarations"><b>5.17 Context Value Declaration</b></a> in the main module
      
  </td><td>overwritten during evaluation of path expressions and predicates</td><td>If context value is defined, context size must be &gt;0; else context size is <a href="https://www.w3.org/TR/xpath-datamodel-31/#dt-absent">absent</a><sup><small>DM31</small></sup>.</td></tr><tr><td>Variable values</td><td>none</td><td>augmentable</td><td>overwriteable and augmentable by  <a href="#id-variable-declarations"><b>5.16 Variable Declaration</b></a>  and  <a href="#id-inline-func"><b>4.5.6 Inline Function Expressions</b></a>, augmentable by <a href="#id-module-import"><b>5.12 Module Import</b></a>
                     </td><td>overwriteable and augmentable by variable-binding expressions</td><td>Names and values must be consistent with in-scope variables.</td></tr><tr><td>Named functions</td><td>the <a title="system function" class="termref" href="#dt-system-function">system functions</a>
                     </td><td>augmentable</td><td>augmentable by 
 <a href="#FunctionDeclns"><b>5.18 Function Declarations</b></a>, 
<a href="#id-module-import"><b>5.12 Module Import</b></a>,
and
<a href="#id-schema-import"><b>5.11 Schema Import</b></a> ( (which adds constructor functions for user-defined types)</td><td>no</td><td>Must be consistent with statically known function signatures</td></tr><tr><td>Current dateTime</td><td>none</td><td>must be initialized <span class="xquery">by implementation</span>
                     </td><td>no</td><td>no</td><td>Must include a timezone. Remains constant during evaluation of a query.</td></tr><tr><td>Implicit timezone</td><td>none</td><td>must be initialized <span class="xquery">by implementation</span>
                     </td><td>no</td><td>no</td><td>Remains constant during evaluation of a query.</td></tr><tr><td>Available documents</td><td>none</td><td>must be initialized <span class="xquery">by implementation</span>
                     </td><td>no</td><td>no</td><td>None</td></tr><tr><td>Available text resources</td><td>none</td><td>must be initialized <span class="xquery">by implementation</span>
                     </td><td>no</td><td>no</td><td>None</td></tr><tr><td>Available collections</td><td>none</td><td>must be initialized <span class="xquery">by implementation</span>
                     </td><td>no</td><td>no</td><td>None</td></tr><tr><td>Default collection</td><td>none</td><td>overwriteable</td><td>no</td><td>no</td><td>None</td></tr><tr><td>Available URI collections</td><td>none</td><td>must be initialized <span class="xquery">by implementation</span>
                     </td><td>no</td><td>no</td><td>None</td></tr><tr><td>Default URI collection</td><td>none</td><td>overwriteable</td><td>no</td><td>no</td><td>None</td></tr></tbody></table></div></div><div class="div1">
<h2><a id="id-impl-defined-items"/>C <a href="#id-impl-defined-items" style="text-decoration: none">Implementation-Defined Items</a></h2><p>The following items in this specification 
  are <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>:</p><ol class="enumar"><li><p>The version of Unicode that is used to construct expressions.</p></li><li><p>The <a title="statically known collations" class="termref" href="#dt-static-collations">statically-known collations</a>.</p></li><li><p>The <a title="implicit timezone" class="termref" href="#dt-timezone">implicit timezone</a>.</p></li><li><p>The circumstances in which <a title="warning" class="termref" href="#dt-warning">warnings</a> are raised, and the ways in which warnings are handled.</p></li><li><p>The method by which errors are reported to the external processing environment.</p></li><li><p>Which version of XML and XML Names (e.g. <a href="#XML">[XML 1.0]</a> and <a href="#XMLNAMES">[XML Names]</a> or <a href="#XML1.1">[XML 1.1]</a> and <a href="#XMLNAMES11">[XML Names 1.1]</a>) and which version of XML Schema (e.g. <a href="#XMLSchema10">[XML Schema 1.0]</a> or <a href="#XMLSchema11">[XML Schema 1.1]</a>) is used for the definitions of primitives such as characters and names, and for the definitions  of operations such as normalization of line endings and normalization of whitespace in attribute values. It is recommended that the latest applicable version be used (even if it is published later than this specification).</p></li><li><p>How XDM instances are created from sources other than an Infoset or PSVI.</p></li><li class="xquery"><p>Any components of the <a title="static context" class="termref" href="#dt-static-context">static context</a> 
  or <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a> that are overwritten or augmented 
  by the implementation.</p></li><li class="xquery"><p>The default handling of empty sequences returned by an ordering key (orderspec) 
  in an <code>order by</code> clause (<code>empty least</code> or <code>empty greatest</code>).</p></li><li class="xquery"><p>The names and semantics of any 
      <a title="extension expression" class="termref" href="#dt-extension-expression">extension expressions</a> 
      (<a title="pragma" class="termref" href="#dt-pragma">pragmas</a>) recognized by the implementation.</p></li><li class="xquery"><p>The names and semantics of any 
      <a title="option declaration" class="termref" href="#dt-option-declaration">option declarations</a> 
      recognized by the implementation.</p></li><li class="xquery"><p>Protocols (if any) by which parameters can be passed to an external function,
          and the result of the function can returned to the invoking query.</p></li><li class="xquery"><p>The process by which the specific modules to be imported by a
<a title="module import" class="termref" href="#dt-module-import">module import</a> are identified 
      (includes processing of location hints, if any.)</p></li><li class="xquery"><p>The means by which serialization is invoked, if the <a title="serialization feature" class="termref" href="#dt-serialization-feature">Serialization Feature</a> is supported.</p></li><li class="xquery"><p>The default values for the <code>byte-order-mark</code>, <code>encoding</code>, <code>html-version</code>, <code>item-separator</code>, <code>media-type</code>, <code>normalization-form</code>, <code>omit-xml-declaration</code>, <code>standalone</code>, and <code>version</code> parameters, if the <a title="serialization feature" class="termref" href="#dt-serialization-feature">Serialization Feature</a> is supported.</p></li><li class="xquery"><p>The result of an unsuccessful call to an external function (for example,
if the function implementation cannot be found or does not return a value
of the declared type).</p></li><li class="xquery"><p>Limits on ranges of values for various data types, as enumerated in <a href="#id-data-model-conformance"><b>6.3 Data Model Conformance</b></a>.</p></li><li class="xquery"><p>Syntactic extensions to XQuery, including both their syntax and semantics, as discussed in <a href="#id-syntax-extensions"><b>6.4 Syntax Extensions</b></a>.</p></li><li><p>Whether the type system is based on <a href="#XMLSchema10">[XML Schema 1.0]</a> or <a href="#XMLSchema11">[XML Schema 1.1]</a>. An implementation that has based its type system on XML Schema 1.0 is not required to support the use of the <code>xs:dateTimeStamp</code> constructor or the use of <code>xs:dateTimeStamp</code> or <code>xs:error</code> as <a href="#prod-xquery40-TypeName">TypeName</a> in any expression.</p></li><li><p>The signatures of functions provided by the implementation or via an implementation-defined API (see <a href="#static_context"><b>2.2.1 Static Context</b></a>).</p></li><li><p>Any <a title="environment variables" class="termref" href="#dt-environment-variables">environment variables</a> provided by the implementation.</p></li><li><p>Any rules used for static typing (see <a href="#id-static-analysis"><b>2.3.3.1 Static Analysis Phase</b></a>).</p></li><li><p>Any serialization parameters provided by the implementation<span class="xquery"> (see  <a href="#id-serialization"><b>2.3.5 Serialization</b></a>).</span>
               </p></li><li class="xquery"><p>The means by which the location hint for a serialization parameter document identifies the corresponding XDM instance (see  <a href="#id-serialization"><b>2.3.5 Serialization</b></a>).</p></li><li><p>What error, if any, is returned if an external function's implementation does not return the declared result type (see <a href="#id-consistency-constraints"><b>2.3.6 Consistency Constraints</b></a>).</p></li><li class="xquery"><p>Any annotations defined by the implementation, and their associated behavior (see <a href="#id-annotations"><b>5.15 Annotations</b></a>).</p></li><li class="xquery"><p>Any <a title="function assertion" class="termref" href="#dt-function-assertion">function assertions</a> defined by the implementation.</p></li><li class="xquery"><p>The effect of function assertions understood by the implementation on <a href="#id-assertions-subtype"><b>3.3.3 The judgement subtype-assertions(AnnotationsA, AnnotationsB)</b></a>.</p></li><li class="xquery"><p>Any implementation-defined variables defined by the implementation. (see <a href="#id-variables"><b>4.2.2 Variable References</b></a>).</p></li><li class="xquery"><p>The ordering associated with <code>fn:unordered</code> in the implementation (see <a href="#id-unordered-expressions"><b>4.15 Ordered and Unordered Expressions</b></a>).</p></li><li class="xquery"><p>Any additional information provided for try/catch via the <code>err:additional</code> variable (see <a href="#id-try-catch"><b>4.20 Try/Catch Expressions</b></a>).</p></li><li class="xquery"><p>The default boundary-space policy (see <a href="#id-boundary-space-decls"><b>5.3 Boundary-space Declaration</b></a>).</p></li><li class="xquery"><p>The default collation (see <a href="#id-default-collation-declaration"><b>5.4 Default Collation Declaration</b></a>).</p></li><li class="xquery"><p>The default base URI (see <a href="#id-base-uri-decl"><b>5.5 Base URI Declaration</b></a>).</p></li></ol><div class="note"><p class="prefix"><b>Note:</b></p><p>Additional <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> 
  items are listed in <a href="#xpath-datamodel-40">[XDM 4.0]</a> and <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>.</p></div></div><div class="div1">
<h2><a id="id-references"/>D <a href="#id-references" style="text-decoration: none">References</a></h2><div class="div2">
<h3><a id="id-normative-references"/>D.1 <a href="#id-normative-references" style="text-decoration: none">Normative References</a></h3><dl><dt class="label"><span><a id="RFC2119"/>RFC2119</span></dt><dd><div>S. Bradner.
      <em>Key Words for use in RFCs to Indicate Requirement Levels.</em> IETF RFC 2119.
      See <a href="http://www.ietf.org/rfc/rfc2119.txt">http://www.ietf.org/rfc/rfc2119.txt</a>.</div></dd><dt class="label"><span><a id="RFC3986"/>RFC3986</span></dt><dd><div>T. Berners-Lee, R. Fielding, and
      L. Masinter.  <em>Uniform Resource Identifiers (URI): Generic
      Syntax</em>. IETF RFC 3986.
      See <a href="http://www.ietf.org/rfc/rfc3986.txt">http://www.ietf.org/rfc/rfc3986.txt</a>.</div></dd><dt class="label"><span><a id="RFC3987"/>RFC3987</span></dt><dd><div>M. Duerst and M. Suignard.
      <em>Internationalized Resource Identifiers (IRIs)</em>.
      IETF RFC 3987. See <a href="http://www.ietf.org/rfc/rfc3987.txt">http://www.ietf.org/rfc/rfc3987.txt</a>.</div></dd><dt class="label"><span><a id="ISO10646"/>ISO/IEC 10646</span></dt><dd><div>ISO (International Organization for Standardization).
      <em>ISO/IEC 10646:2003. Information technology—Universal Multiple-Octet Coded Character Set (UCS)</em>,
      as, from time to time, amended, replaced by a new edition, or expanded by the addition of new parts.
      [Geneva]: International Organization for Standardization.
      (See <a href="http://www.iso.org">http://www.iso.org</a> for the latest version.)</div></dd><dt class="label"><span><a id="Unicode"/>Unicode</span></dt><dd><div>The Unicode Consortium. <em>The Unicode Standard.</em>
      Reading, Mass.: Addison-Wesley, 2003, as updated from time to time by the publication of new versions.
      See <a href="http://www.unicode.org/standard/versions/">http://www.unicode.org/standard/versions/</a>
      for the latest version and additional information on versions of the standard and of the Unicode Character Database.
      The version of Unicode to be used is <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>,
      but implementations are recommended to use the latest Unicode version.</div></dd><dt class="label"><span><a id="XML"/>XML 1.0</span></dt><dd><div>World Wide Web Consortium.
      <em>Extensible Markup Language (XML) 1.0.</em>
      W3C Recommendation.
      See <a href="http://www.w3.org/TR/REC-xml/">http://www.w3.org/TR/REC-xml/</a>.
      The edition of XML 1.0 must be no earlier than the Third Edition;
      the edition used is <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>,
      but we recommend that implementations use the latest version.
</div></dd><dt class="label"><span><a id="XML1.1"/>XML 1.1</span></dt><dd><div>World Wide Web Consortium.
      <em>Extensible Markup Language (XML) 1.1.</em>
      W3C Recommendation.
      See <a href="http://www.w3.org/TR/xml11/">http://www.w3.org/TR/xml11/</a>
               </div></dd><dt class="label"><span><a id="XMLBASE"/>XML Base</span></dt><dd><div>World Wide Web Consortium.
      <em>XML Base.</em> W3C Recommendation. See
      <a href="http://www.w3.org/TR/xmlbase/">http://www.w3.org/TR/xmlbase/</a>
               </div></dd><dt class="label"><span><a id="XMLNAMES"/>XML Names</span></dt><dd><div>World Wide Web Consortium.
      <em>Namespaces in XML.</em> W3C Recommendation. See
      <a href="http://www.w3.org/TR/REC-xml-names/">http://www.w3.org/TR/REC-xml-names/</a>
               </div></dd><dt class="label"><span><a id="XMLNAMES11"/>XML Names 1.1</span></dt><dd><div>World Wide Web Consortium.
      <em>Namespaces in XML 1.1.</em> W3C Recommendation. See
      <a href="http://www.w3.org/TR/xml-names11/">http://www.w3.org/TR/xml-names11/</a>
               </div></dd><dt class="label"><span><a id="XMLID"/>XML ID</span></dt><dd><div>World Wide Web Consortium. <em>xml:id Version 1.0.</em>
      W3C Recommendation. See <a href="http://www.w3.org/TR/xml-id/">http://www.w3.org/TR/xml-id/</a>
               </div></dd><dt class="label"><span><a id="XMLSchema10"/>XML Schema 1.0</span></dt><dd><div>World Wide Web Consortium.
      <em>XML Schema, Parts 0, 1, and 2 (Second Edition)</em>. W3C Recommendation, 28 October 2004.
      See <a href="http://www.w3.org/TR/xmlschema-0/">http://www.w3.org/TR/xmlschema-0/</a>,
      <a id="schema1" href="http://www.w3.org/TR/xmlschema-1/">http://www.w3.org/TR/xmlschema-1/</a>,
      and <a id="schema2" href="http://www.w3.org/TR/xmlschema-2/">http://www.w3.org/TR/xmlschema-2/</a>.</div></dd><dt class="label"><span><a id="XMLSchema11"/>XML Schema 1.1</span></dt><dd><div>World Wide Web Consortium.
      <em>XML Schema, Parts 1, and 2</em>. W3C Recommendation 5 April 2012.
      See <a id="schema1-11" href="http://www.w3.org/TR/xmlschema11-1/">http://www.w3.org/TR/xmlschema11-1/</a>,
      and <a id="schema2-11" href="http://www.w3.org/TR/xmlschema11-2/">http://www.w3.org/TR/xmlschema11-2/</a>.</div></dd><dt class="label"><span><a id="xpath-datamodel-40"/>XDM 4.0</span></dt><dd><div>
<a href="../xpath-datamodel-40/Overview.html"><cite>XQuery and XPath Data Model (XDM) 4.0</cite></a>,
XSLT Extensions Community Group,
World Wide Web Consortium.</div></dd><dt class="label"><span><a id="xpath-functions-40"/>Functions and Operators 4.0</span></dt><dd><div>
<a href="../xpath-functions-40/Overview.html"><cite>XQuery and XPath Functions and Operators 4.0</cite></a>,
XSLT Extensions Community Group,
World Wide Web Consortium.</div></dd><dt class="label"><span><a id="xpath-40"/>XPath 4.0</span></dt><dd><div>
<a href="../xquery-40/xpath-40.html"><cite>XML Path Language (XPath) 4.0</cite></a>,
XSLT Extensions Community Group,
World Wide Web Consortium.</div></dd><dt class="label"><span><a id="xslt-xquery-serialization-40"/>Serialization 4.0</span></dt><dd><div>
<a href="../xslt-xquery-serialization-40/Overview.html"><cite>XSLT and XQuery Serialization 4.0</cite></a>,
XSLT Extensions Community Group,
World Wide Web Consortium.</div></dd></dl></div><div class="div2">
<h3><a id="id-non-normative-references"/>D.2 <a href="#id-non-normative-references" style="text-decoration: none">Non-normative References</a></h3><dl><dt class="label"><span class="xquery"><a id="xquery-30-requirements"/>XQuery 3.0 Requirements</span></dt><dd><div class="xquery">
<a href="https://www.w3.org/TR/xquery-30-requirements/"><cite>XQuery 3.0 Requirements</cite></a>,
Daniel Engovatov, Jonathan Robie, Editors.
World Wide Web Consortium,
08 April 2014. 
This version is https://www.w3.org/TR/2014/NOTE-xquery-30-requirements-20140408/.
The <a href="https://www.w3.org/TR/xquery-30-requirements/">latest version</a>
is available at https://www.w3.org/TR/xquery-30-requirements/.</div></dd><dt class="label"><span class="xquery"><a id="xquery-31-requirements"/>XQuery 3.1 Requirements</span></dt><dd><div class="xquery">
<a href="https://www.w3.org/TR/xquery-31-requirements/"><cite>XQuery 3.1 Requirements and Use Cases</cite></a>,
Jonathan Robie, Editor.
World Wide Web Consortium,
13 December 2016. 
This version is https://www.w3.org/TR/2016/NOTE-xquery-31-requirements-20161213/.
The <a href="https://www.w3.org/TR/xquery-31-requirements/">latest version</a>
is available at https://www.w3.org/TR/xquery-31-requirements/.</div></dd><dt class="label"><span class="xquery"><a id="xquery-30"/>XQuery 3.0</span></dt><dd><div class="xquery">
<a href="https://www.w3.org/TR/xquery-30/"><cite>XQuery 3.0: An XML Query Language</cite></a>,
Jonathan Robie, Don Chamberlin, Michael Dyck, John Snelson, Editors.
World Wide Web Consortium,
08 April 2014. 
This version is https://www.w3.org/TR/2014/REC-xquery-30-20140408/.
The <a href="https://www.w3.org/TR/xquery-30/">latest version</a>
is available at https://www.w3.org/TR/xquery-30/.</div></dd><dt class="label"><span><a id="xquery-semantics"/>XQuery 1.0 and XPath 2.0 Formal Semantics</span></dt><dd><div>
<a href="https://www.w3.org/TR/xquery-semantics/"><cite>XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition)</cite></a>,
Jérôme Siméon, Denise Draper, Peter Frankhauser, <em>et. al.</em>, Editors.
World Wide Web Consortium,
14 December 2010.
This version is https://www.w3.org/TR/2010/REC-xquery-semantics-20101214/.
The <a href="https://www.w3.org/TR/xquery-semantics/">latest version</a>
is available at https://www.w3.org/TR/xquery-semantics/.</div></dd><dt class="label"><span><a id="xslt-40"/>XSLT 4.0</span></dt><dd><div>
<a href="../xslt-40/Overview.html"><cite>XSL Transformations (XSLT) Version 4.0</cite></a>,
XSLT Extensions Community Group,
World Wide Web Consortium.</div></dd><dt class="label"><span class="xquery"><a id="DOM"/>Document Object Model</span></dt><dd><div class="xquery">World Wide Web Consortium. <em>Document Object Model (DOM) Level 3 Core Specification.</em> W3C Recommendation, April 7, 2004. See <a href="http://www.w3.org/TR/DOM-Level-3-Core/">http://www.w3.org/TR/DOM-Level-3-Core/</a>.</div></dd><dt class="label"><span><a id="XINFO"/>XML Infoset</span></dt><dd><div>World Wide Web
Consortium. <em>XML Information Set (Second Edition).</em> W3C Recommendation 4 February 2004. See
<a href="http://www.w3.org/TR/xml-infoset/">http://www.w3.org/TR/xml-infoset/</a>
               </div></dd><dt class="label"><span><a id="xpath"/>XPath 1.0</span></dt><dd><div>
      <a href="http://www.w3.org/TR/xpath/"><cite>XML Path Language (XPath) Version 1.0</cite></a>, James Clark and Steven DeRose, Editors. World Wide Web Consortium, 16 Nov 1999. This version is http://www.w3.org/TR/1999/REC-xpath-19991116. The <a href="http://www.w3.org/TR/xpath/">latest version</a> is available at http://www.w3.org/TR/xpath.</div></dd><dt class="label"><span><a id="xpath20"/>XPath 2.0</span></dt><dd><div>
<a href="https://www.w3.org/TR/xpath20/"><cite>XML Path Language (XPath) 2.0 (Second Edition)</cite></a>,
Don Chamberlin, Anders Berglund, Scott Boag, <em>et. al.</em>, Editors.
World Wide Web Consortium,
14 December 2010.
This version is https://www.w3.org/TR/2010/REC-xpath20-20101214/.
The <a href="https://www.w3.org/TR/xpath20/">latest version</a>
is available at https://www.w3.org/TR/xpath20/.</div></dd><dt class="label"><span><a id="xpath-30"/>XPath 3.0</span></dt><dd><div>
<a href="https://www.w3.org/TR/xpath-30/"><cite>XML Path Language (XPath) 3.0</cite></a>,
Jonathan Robie, Don Chamberlin, Michael Dyck, John Snelson, Editors.
World Wide Web Consortium,
08 April 2014. 
This version is https://www.w3.org/TR/2014/REC-xpath-30-20140408/.
The <a href="https://www.w3.org/TR/xpath-30/">latest version</a>
is available at https://www.w3.org/TR/xpath-30/.</div></dd><dt class="label"><span class="xquery"><a id="xpath-31"/>XPath 3.1</span></dt><dd><div class="xquery">
<a href="https://www.w3.org/TR/xpath-31/"><cite>XML Path Language (XPath) 3.1</cite></a>,
Jonathan Robie, Michael Dyck and Josh Spiegel, Editors.
World Wide Web Consortium,
21 March 2017. 
This version is https://www.w3.org/TR/2017/REC-xpath-31-20170321/.
The <a href="https://www.w3.org/TR/xpath-31/">latest version</a>
is available at https://www.w3.org/TR/xpath-31/.</div></dd><dt class="label"><span><a id="XPTR"/>XPointer</span></dt><dd><div>World Wide Web Consortium. <em>XML
Pointer Language (XPointer).</em> W3C Last Call Working Draft 8 January 2001.
See <a href="http://www.w3.org/TR/WD-xptr">http://www.w3.org/TR/WD-xptr</a>
               </div></dd><dt class="label"><span class="xquery"><a id="UseCases"/>XML Query Use Cases</span></dt><dd><div class="xquery">World Wide
Web Consortium. <em>XML Query Use Cases</em>. W3C Working Draft, 8 June 2006.
See <a href="http://www.w3.org/TR/xquery-use-cases/">http://www.w3.org/TR/xquery-use-cases/</a>.</div></dd><dt class="label"><span class="xquery"><a id="xml11schema10"/>XML 1.1 and Schema 1.0</span></dt><dd><div class="xquery">World Wide
Web Consortium. <em>Processing XML 1.1 Documents with XML Schema 1.0 Processors</em>.
W3C Working Group Note, 11 May 2005.
See <a href="http://www.w3.org/TR/xml11schema10/">http://www.w3.org/TR/xml11schema10/</a>.</div></dd><dt class="label"><span class="xquery"><a id="RFC1738"/>Uniform Resource Locators (URL)</span></dt><dd><div class="xquery">Internet Engineering Task Force (IETF).
<em>Uniform Resource Locators (URL)</em>. Request For Comment No. 1738, Dec. 1994.
See <a href="http://www.ietf.org/rfc/rfc1738.txt">http://www.ietf.org/rfc/rfc1738.txt</a>.</div></dd><dt class="label"><span class="xquery"><a id="ODMG"/>ODMG</span></dt><dd><div class="xquery">Rick Cattell et al. <em>The
Object Database Standard: ODMG-93, Release 1.2</em>. Morgan Kaufmann
Publishers, San Francisco, 1996.</div></dd><dt class="label"><span class="xquery"><a id="Quilt"/>Quilt</span></dt><dd><div class="xquery">Don Chamberlin,
Jonathan Robie, and Daniela Florescu. <em>Quilt: an XML Query Language for
Heterogeneous Data Sources</em>.  In <em>Lecture Notes in Computer
Science</em>, Springer-Verlag, Dec. 2000.  

</div></dd><dt class="label"><span class="xquery"><a id="XML-QL"/>XML-QL</span></dt><dd><div class="xquery">Alin Deutsch, Mary Fernandez,
Daniela Florescu, Alon Levy, and Dan Suciu.
<em>A Query Language for XML</em>.
</div></dd><dt class="label"><span class="xquery"><a id="SQL"/>SQL</span></dt><dd><div class="xquery">International Organization for
Standardization (ISO).  <em>Information Technology — Database Language
SQL</em>. Standard No. ISO/IEC 9075:2011.  (Available from American
National Standards Institute, New York, NY 10036, (212)
642-4900.)</div></dd><dt class="label"><span class="xquery"><a id="XQL"/>XQL</span></dt><dd><div class="xquery">J. Robie, J. Lapp, D. Schach. <em>XML
Query Language (XQL)</em>. See <a href="http://www.w3.org/TandS/QL/QL98/pp/xql.html">http://www.w3.org/TandS/QL/QL98/pp/xql.html</a>.</div></dd></dl></div><div class="div2">
<h3><a id="id-background-material"/>D.3 <a href="#id-background-material" style="text-decoration: none">Background Material</a></h3><dl><dt class="label"><span><a id="CHARMOD"/>Character Model</span></dt><dd><div>World Wide Web Consortium.
<em>Character Model for the World Wide Web.</em> W3C Working
Draft. See <a href="http://www.w3.org/TR/charmod/">http://www.w3.org/TR/charmod/</a>.</div></dd><dt class="label"><span><a id="xslt"/>XSL Transformations (XSLT) Version 1.0</span></dt><dd><div>
      <a href="http://www.w3.org/TR/xslt"><cite>XSL Transformations (XSLT) Version 1.0</cite></a>, James Clark, Editor. World Wide Web Consortium, 16 Nov 1999. This version is http://www.w3.org/TR/1999/REC-xslt-19991116. The <a href="http://www.w3.org/TR/xslt">latest version</a> is available at http://www.w3.org/TR/xslt.</div></dd><dt class="label"><span class="xquery"><a id="UseCaseQueries"/>Use Case Sample Queries</span></dt><dd><div class="xquery">Queries
from the XQuery 1.0 Use Cases, presented in a single file.
See
<a href="http://www.w3.org/2010/12/xquery-30-use-cases/xquery-30-use-case-queries.txt">http://www.w3.org/2010/12/xquery-30-use-cases/xquery-30-use-case-queries.txt</a>.
</div></dd><dt class="label"><span class="xquery"><a id="XQueryQueries"/>XQuery Sample Queries</span></dt><dd><div class="xquery">Queries
from this document, presented in a single file.
See
<a href="http://www.w3.org/2013/01/xquery-30-use-cases/xquery-30-example-queries.txt">http://www.w3.org/2013/01/xquery-30-use-cases/xquery-30-example-queries.txt</a>.
</div></dd><dt class="label"><span class="xquery"><a id="Moustache"/>Moustache</span></dt><dd><div class="xquery">
                  <em>mustache</em> - Logic-less templates. See
<a href="http://mustache.github.io/mustache.5.html">http://mustache.github.io/mustache.5.html</a>.
</div></dd></dl></div></div><div class="div1">
<h2><a id="id-errors"/>E <a href="#id-errors" style="text-decoration: none">Error Conditions</a></h2><div class="note"><p class="prefix"><b>Note:</b></p><p>Historically, codes starting "XP" were for XPath errors, "XQ" for XQuery errors.
   This was followed by "ST" for static errors, "TY" for type errors, or "DY" for dynamic
   errors. Over time, some errors have been reclassified, but the error codes
   have been retained for compatibility reasons. Applications should therefore attach no
   significance to the choice of codes.</p></div><dl>
            <dt><a id="ERRXPST0001"/>err:XPST0001</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if analysis of an
            expression relies on some component of the <a title="static context" class="termref" href="#dt-static-context">static
               context</a> that 
                  <span>is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>
                  </span>.</p>
            </dd>
            <dt><a id="ERRXPDY0002"/>err:XPDY0002</dt><dd>
               <p>It is a <a title="type error" class="termref" href="#dt-type-error">type error</a> if evaluation of an
            expression relies on some part of the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic
               context</a> that is <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>.</p>
               <div class="note"><p class="prefix"><b>Note:</b></p><p>In version 4.0 this has been reclassified as a type error rather than
         a dynamic error. This change allows a processor to report the error during static
         analysis where possible; for example if the body of a user-defined
         function is written as <code>fn($x) { @code }</code>.
         The error code is prefixed <code>XPDY</code> rather than <code>XPTY</code>
         for backwards compatibility reasons.</p></div>
            </dd>
            <dt><a id="ERRXPST0003"/>err:XPST0003</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if an expression is not a
            valid instance of the grammar defined in <a href="#id-grammar"><b>A.1 EBNF</b></a>.</p>
            </dd>
            <dt><a id="ERRXPTY0004"/>err:XPTY0004</dt><dd>
               <p>It is a <a title="type error" class="termref" href="#dt-type-error">type error</a> if, during the <a title="static analysis phase" class="termref" href="#dt-static-analysis">static analysis phase</a>, an expression is found to
            have a <a title="static type" class="termref" href="#dt-static-type">static type</a> that is not appropriate for
            the context in which the expression occurs, or during the <a title="dynamic evaluation phase" class="termref" href="#dt-dynamic-evaluation">dynamic evaluation phase</a>, the <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a> of a value does not match a required
            type as specified by the matching rules in <a href="#id-sequencetype-matching"><b>3.1.2 Sequence Type Matching</b></a>.</p>
            </dd>
            
            <dt><a id="ERRXPTY0006"/>err:XPTY0006</dt><dd>
               <p>During the analysis phase, an expression is classified as <a title="implausible" class="termref" href="#dt-implausible">implausible</a>
            if the inferred <a title="static type" class="termref" href="#dt-static-type">static type</a>
                  <var>S</var> and
            the required type <var>R</var> are substantively disjoint; more specifically, if neither
            of the types is a subtype of the other, and if the only values
            that are instances of both types are one or more of: the empty sequence, the empty map, 
            and the empty array.</p>
            </dd>
            <dt><a id="ERRXPST0008"/>err:XPST0008</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if an expression refers
            to an element name, attribute name, schema type name, or variable name
            that is not defined in the <a title="static context" class="termref" href="#dt-static-context">static context</a>,
            except for an ElementName in an <a href="#doc-xquery40-ElementTest">ElementTest</a> or an
            AttributeName in an <a href="#doc-xquery40-AttributeTest">AttributeTest</a>.</p>
            </dd>
            <dt><a id="ERRXQST0009"/>err:XQST0009</dt><dd>
               <p> An implementation that does not support the Schema Aware Feature must raise
            a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a Prolog contains a schema
            import.</p>
            </dd>
            <dt><a id="ERRXQST0012"/>err:XQST0012</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the set of definitions
            contained in all schemas imported by a Prolog do not satisfy the conditions for schema
            validity specified in Sections 3 and 5 of Part 1 of <a href="#XMLSchema10">[XML Schema 1.0]</a> or
               <a href="#XMLSchema11">[XML Schema 1.1]</a>.</p>
            </dd>
            <dt><a id="ERRXQST0013"/>err:XQST0013</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if an implementation
            recognizes a pragma but determines that its content is invalid.</p>
            </dd>
            
            
            
            <dt><a id="ERRXPST0017"/>err:XPST0017</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>
            and number of arguments in a static function call do not match the name and
            <a title="arity range" class="termref" href="#dt-arity-range">arity range</a> of a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> in the
            <a title="static context" class="termref" href="#dt-static-context">static context</a>, or if an argument keyword in the function call
            does not match a parameter name in that function definition, or if two arguments
            in the function call bind to the same parameter in the function definition.</p>
            </dd>
            <dt><a id="ERRXPTY0018"/>err:XPTY0018</dt><dd>
               <p>It is a <a title="type error" class="termref" href="#dt-type-error">type error</a> if the result of a path
            operator contains both nodes and non-nodes.</p>
            </dd>
            <dt><a id="ERRXPTY0019"/>err:XPTY0019</dt><dd>
               <p> It is a <a title="type error" class="termref" href="#dt-type-error">type error</a> if <code>E1</code> in a path
            expression <code>E1/E2</code> does not evaluate to a sequence of nodes.</p>
            </dd>
            <dt><a id="ERRXPTY0020"/>err:XPTY0020</dt><dd>
               <p> It is a <a title="type error" class="termref" href="#dt-type-error">type error</a> if, in an axis step, the
            context item is not a node.</p>
            </dd>
            <dt><a id="ERRXPST0021"/>err:XPST0021</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if two fields in a record declaration
            have the same name.</p>
            </dd>
            <dt><a id="ERRXQST0022"/>err:XQST0022</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if  a <a title="namespace declaration attribute" class="termref" href="#dt-namespace-decl-attr">namespace declaration
               attribute</a>
                  
                  <span>contains an <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a>.</span>
               </p>
            </dd>
            <dt><a id="ERRXPST0023"/>err:XPST0023</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a recursive record type
            cannot be instantiated (typically because it contains a self-reference that is neither optional
            nor emptiable). Processors are not required to detect this error.</p>
            </dd>
            <dt><a id="ERRXQTY0024"/>err:XQTY0024</dt><dd>
               <p> It is a <a title="type error" class="termref" href="#dt-type-error">type error</a> if the content sequence in an
            element constructor contains an attribute node following a node that is not an attribute
            node.</p>
            </dd>
            <dt><a id="ERRXQDY0025"/>err:XQDY0025</dt><dd>
               <p> It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> if any attribute of a
            constructed element does not have a name that is distinct from the names of all other
            attributes of the constructed element.</p>
            </dd>
            <dt><a id="ERRXQDY0026"/>err:XQDY0026</dt><dd>
               <p> It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> if the result of the
            content expression of a computed processing instruction constructor contains the string
               <code>"?&gt;"</code>.</p>
            </dd>
            <dt><a id="ERRXQDY0027"/>err:XQDY0027</dt><dd>
               <p> In a validate expression, it is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic
               error</a> if the root element information item in the PSVI resulting from
            validation does not have the expected validity property: <code>valid</code> if
            validation mode is <code>strict</code>, or either <code>valid</code> or
               <code>notKnown</code> if validation mode is <code>lax</code>.</p>
            </dd>
            
            
            <dt><a id="ERRXQTY0030"/>err:XQTY0030</dt><dd>
               <p> It is a <a title="type error" class="termref" href="#dt-type-error">type error</a> if the argument of a
               <code>validate</code> expression does not evaluate to exactly one document or element
            node. </p>
            </dd>
            <dt><a id="ERRXQST0031"/>err:XQST0031</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the version number
            specified in a version declaration is not supported by the implementation. </p>
            </dd>
            <dt><a id="ERRXQST0032"/>err:XQST0032</dt><dd>
               <p>A <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised if a Prolog contains
            more than one <a title="base URI declaration" class="termref" href="#dt-base-uri-decl">base URI declaration</a>.</p>
            </dd>
            <dt><a id="ERRXQST0033"/>err:XQST0033</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a module contains
            multiple bindings for the same namespace prefix.</p>
            </dd>
            <dt><a id="ERRXQST0034"/>err:XQST0034</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if multiple functions
            declared <span class="xquery">or imported by a <a title="module" class="termref" href="#dt-module">module</a>
                  </span> have the same <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>
            and overlapping arity ranges (the arity range of a function declaration is <var>M</var> to <var>M+N</var>,
            where <var>M</var> is the number of required parameters and <var>N</var> is the number of 
            optional parameters).</p>
            </dd>
            <dt><a id="ERRXQST0035"/>err:XQST0035</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> to import two schema
            components that both define the same name in the same symbol space and in the same
            scope. </p>
            </dd>
            
            
            <dt><a id="ERRXQST0038"/>err:XQST0038</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a Prolog contains more
            than one <a title="default collation declaration" class="termref" href="#dt-default-collation-decl">default collation
               declaration</a>, or the value specified by a default collation declaration is
            not present in <a title="statically known collations" class="termref" href="#dt-static-collations">statically known
            collations</a>.</p>
            </dd>
            <dt><a id="ERRXQST0039"/>err:XQST0039</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> for <span class="xquery">a function declaration or</span>
                  <span>an inline function expression</span> to have more than one
            parameter with the same name. </p>
            </dd>
            <dt><a id="ERRXQST0040"/>err:XQST0040</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the attributes
            specified by a direct element constructor do not have distinct <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a>.</p>
            </dd>
            <dt><a id="ERRXQDY0041"/>err:XQDY0041</dt><dd>
               <p> It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> if the value of the
            name expression in a computed processing instruction constructor cannot be cast to the
            type <code>xs:NCName</code>.</p>
            </dd>
            
            
            <dt><a id="ERRXQDY0044"/>err:XQDY0044</dt><dd>
               <p>It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> the node-name of a node
            constructed by a computed attribute constructor has any of the following properties: </p>
               <ul><li><p>Its namespace prefix is <code>xmlns</code>. </p></li><li><p>It has no namespace prefix and its local name is <code>xmlns</code>. </p></li><li><p>Its namespace URI is <code>http://www.w3.org/2000/xmlns/</code>. </p></li><li><p>Its namespace prefix is <code>xml</code> and its namespace URI is not
                     <code>http://www.w3.org/XML/1998/namespace</code>. </p></li><li><p>Its namespace prefix is other than <code>xml</code> and its namespace URI is
                     <code>http://www.w3.org/XML/1998/namespace</code>. </p></li></ul>
               
            </dd>
            <dt><a id="ERRXQST0045"/>err:XQST0045</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if <span>the
               name of <span>a variable annotation,</span> a function annotation, or</span> the function name in a function declaration
            is  <span>in a <a title="reserved namespaces" class="termref" href="#dt-reserved-namespaces">reserved namespace</a>.</span>
               </p>
            </dd>
            <dt><a id="ERRXQST0046"/>err:XQST0046</dt><dd>
               <p>An implementation <span class="xquery">
                     <a title="may" class="termref" href="#may">MAY</a>
                  </span> raise a <a title="static error" class="termref" href="#dt-static-error">static
               error</a> if the value of <span class="xquery">a <a href="#prod-xquery40-URILiteral">URILiteral</a> or </span>a <a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a> is
            of nonzero length and is 
                  <span>neither an absolute URI nor a
               relative URI</span>.</p>
            </dd>
            <dt><a id="ERRXQST0047"/>err:XQST0047</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if multiple module
            imports in the same <a href="#prod-xquery40-Prolog"/> specify the same target namespace.</p>
            </dd>
            <dt><a id="ERRXQST0048"/>err:XQST0048</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a function, variable,
            or item type declared in a <a title="library module" class="termref" href="#dt-library-module">library module</a> is not 
            in the <a title="target namespace" class="termref" href="#dt-target-namespace">target namespace</a> of the library module.</p>
            </dd>
            <dt><a id="ERRXQST0049"/>err:XQST0049</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if two or more variables
            declared or imported by a <a title="module" class="termref" href="#dt-module">module</a> have equal <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a> (as defined by the <code>eq</code>
            operator.)</p>
            </dd>
            <dt><a id="ERRXPDY0050"/>err:XPDY0050</dt><dd>
               <p>It is a <a title="type error" class="termref" href="#dt-type-error">type error</a> if the <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a> of the operand of a <code>treat</code>
            expression does not match the <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>
            designated by the <code>treat</code> expression.</p>
               <div class="note"><p class="prefix"><b>Note:</b></p><p>This error might also be raised by a
            path expression beginning with <code>/</code> or <code>//</code> if the context node
            is not in a tree that is rooted at a document node. This is because a leading
               <code>/</code> or <code>//</code> in a path expression is an abbreviation for an
            initial step that includes the clause <code>treat as document-node()</code>.</p></div>
            </dd>
            <dt><a id="ERRXPST0051"/>err:XPST0051</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> used as an <a href="#doc-xquery40-ItemType">ItemType</a>
               in a <a href="#doc-xquery40-SequenceType"/> is not defined
            in the <a title="static context" class="termref" href="#dt-static-context">static context</a> either as a <a title="named item type" class="termref" href="#dt-named-item-type">named item type</a>
            in the <a title="in-scope named item types" class="termref" href="#dt-in-scope-named-item-types">in-scope named item types</a>,
            or as a <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a>
            in the <a title="in-scope schema type" class="termref" href="#dt-is-types">in-scope schema type</a>.</p>
            </dd>
            <dt><a id="ERRXQST0052"/>err:XQST0052</dt><dd>
               <p>The type named in a cast or castable expression must be the name of a type defined in the <a title="in-scope schema type" class="termref" href="#dt-is-types">in-scope
               schema types</a>, and the type must be
               <code>simple</code>.</p>
            </dd>
            
            <dt><a id="ERRXQDY0054"/>err:XQDY0054</dt><dd>
               <p>It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> if a cycle is
            encountered in the definition of a module’s dynamic context components, for example
            because of a cycle in variable declarations.</p>
            </dd>
            <dt><a id="ERRXQST0055"/>err:XQST0055</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a Prolog contains more
            than one <a title="copy-namespaces declaration" class="termref" href="#dt-copy-namespaces-decl">copy-namespaces
            declaration</a>.</p>
            </dd>
            
            <dt><a id="ERRXQST0057"/>err:XQST0057</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a schema import binds
            a namespace prefix but does not specify a target namespace other than a zero-length
            string.</p>
            </dd>
            <dt><a id="ERRXQST0058"/>err:XQST0058</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if multiple schema
            imports specify the same target namespace.</p>
            </dd>
            <dt><a id="ERRXQST0059"/>err:XQST0059</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if an implementation is
            unable to process a schema or module import by finding a schema or module with the
            specified target namespace.</p>
            </dd>
            <dt><a id="ERRXQST0060"/>err:XQST0060</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the name of a function
            in a function declaration is not in a namespace (<a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> has a null namespace URI).</p>
            </dd>
            <dt><a id="ERRXQDY0061"/>err:XQDY0061</dt><dd>
               <p> It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> if the operand of a
            validate expression is a document node whose children do not consist of exactly one
            element node and zero or more comment and processing instruction nodes, in any
            order.</p>
            </dd>
            
            
            <dt><a id="ERRXQDY0064"/>err:XQDY0064</dt><dd>
               <p> It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> if the value of the
            name expression in a computed processing instruction constructor is equal to
            <code>XML</code> (in any combination of upper and lower case).</p>
            </dd>
            <dt><a id="ERRXQST0065"/>err:XQST0065</dt><dd>
               <p>A <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised if a Prolog contains
            more than one ordering mode declaration.</p>
            </dd>
            <dt><a id="ERRXQST0066"/>err:XQST0066</dt><dd>
               <p>A <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised if a Prolog contains
            more than one default element/type namespace declaration, or more than one default
            function namespace declaration. </p>
            </dd>
            <dt><a id="ERRXQST0067"/>err:XQST0067</dt><dd>
               <p>A <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised if a Prolog contains
            more than one <a title="construction declaration" class="termref" href="#dt-construction-decl">construction
            declaration</a>.</p>
            </dd>
            <dt><a id="ERRXQST0068"/>err:XQST0068</dt><dd>
               <p>A <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised if a Prolog contains
            more than one <a title="boundary-space declaration" class="termref" href="#dt-boundary-space-decl">boundary-space
            declaration</a>.</p>
            </dd>
            <dt><a id="ERRXQST0069"/>err:XQST0069</dt><dd>
               <p>A <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised if a Prolog contains
            more than one <a title="empty order declaration" class="termref" href="#dt-empty-order-decl">empty order declaration</a>.</p>
            </dd>
            <dt><a id="ERRXQST0070"/>err:XQST0070</dt><dd>
               <p>A namespace declaration must not define a binding for the prefix <code>xml</code>
         or <code>xmlns</code>, nor for the URI <code>http://www.w3.org/XML/1998/namespace</code>
         or <code>http://www.w3.org/2000/xmlns/</code>.</p>
               <p>The same rule applies to namespace declaration attributes
         (see <a href="#id-namespaces"><b>4.12.1.2 Namespace Declaration Attributes</b></a>), except that in this case it is permitted to provide
         a redundant namespace declaration attribute in the form 
            <code>xmlns:xml="http://www.w3.org/XML/1998/namespace"</code>.</p>
            </dd>
            <dt><a id="ERRXQST0071"/>err:XQST0071</dt><dd>
               <p>A <a title="static error" class="termref" href="#dt-static-error">static error</a> is raised if the namespace
            declaration attributes of a direct element constructor do not have distinct names.</p>
            </dd>
            <dt><a id="ERRXQDY0072"/>err:XQDY0072</dt><dd>
               <p> It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> if the result of the
            content expression of a computed comment constructor contains two adjacent hyphens or
            ends with a hyphen.</p>
            </dd>
            
            <dt><a id="ERRXQDY0074"/>err:XQDY0074</dt><dd>
               <p> It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> if the value of the
            name expression in a computed element or attribute constructor cannot be converted to an
               <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> (for example, because it
            contains a namespace prefix not found in <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically
               known namespaces</a>.)</p>
            </dd>
            <dt><a id="ERRXQST0075"/>err:XQST0075</dt><dd>
               <p> An implementation that does not support the <span>Schema Aware Feature</span>
                   must raise a <a title="static error" class="termref" href="#dt-static-error">static error</a> if it encounters a <code>validate</code>
            expression.</p>
            </dd>
            <dt><a id="ERRXQST0076"/>err:XQST0076</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a
               <code>collation</code> subclause in an <code>order by</code>
                  <span>or <code>group by</code>
                  </span> clause of a FLWOR
            expression does not identify a collation that is present in <a title="statically known collations" class="termref" href="#dt-static-collations">statically known collations</a>.</p>
            </dd>
            
            
            <dt><a id="ERRXQST0079"/>err:XQST0079</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if an extension
            expression contains neither a <a title="pragma" class="termref" href="#dt-pragma">pragma</a> that is
            recognized by the implementation nor an expression enclosed in curly braces.</p>
            </dd>
            <dt><a id="ERRXPST0080"/>err:XPST0080</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the target type of a
               <code>cast</code> or <code>castable</code> expression is
               <code>xs:NOTATION</code>, <span>
                     <code>xs:anySimpleType</code>,</span> or
               <code>xs:anyAtomicType</code>.</p>
            </dd>
            <dt><a id="ERRXPST0081"/>err:XPST0081</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a QName used in
               <span class="xquery">a query</span>
            contains a namespace prefix that cannot be expanded into a namespace URI by using the
               <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a>.</p>
            </dd>
            
            
            <dt><a id="ERRXQDY0084"/>err:XQDY0084</dt><dd>
               <p> It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> if the element
            validated by a <code>validate</code> statement does not have a top-level element
            declaration in the <a title="in-scope element declarations" class="termref" href="#dt-is-elems">in-scope element declarations</a>,
            if validation mode is <code>strict</code>.</p>
            </dd>
            <dt><a id="ERRXQST0085"/>err:XQST0085</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the namespace URI in a
            namespace declaration attribute is a zero-length string, and the implementation does not
            support <a href="#XMLNAMES11">[XML Names 1.1]</a>.</p>
            </dd>
            <dt><a id="ERRXQTY0086"/>err:XQTY0086</dt><dd>
               <p> It is a <a title="type error" class="termref" href="#dt-type-error">type error</a> if the typed value of a
            copied element or attribute node is <a title="namespace-sensitive" class="termref" href="#dt-namespace-sensitive">namespace-sensitive</a> when <a title="construction mode" class="termref" href="#dt-construction-mode">construction
               mode</a> is <code>preserve</code> and <a title="copy-namespaces mode" class="termref" href="#dt-copy-namespaces-mode">copy-namespaces mode</a> is <code>no-preserve</code>.</p>
            </dd>
            <dt><a id="ERRXQST0087"/>err:XQST0087</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the encoding specified
            in a Version Declaration does not conform to the definition of <code>EncName</code>
            specified in <a href="#XML">[XML 1.0]</a>.</p>
            </dd>
            <dt><a id="ERRXQST0088"/>err:XQST0088</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the literal that
            specifies the target namespace in a <a title="module import" class="termref" href="#dt-module-import">module
               import</a> or a <a title="module declaration" class="termref" href="#dt-module-declaration">module
               declaration</a> is of zero length.</p>
            </dd>
            <dt><a id="ERRXQST0089"/>err:XQST0089</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a variable bound in a
               <code>for</code> or <code>window</code> clause of a FLWOR expression, and its
            associated positional variable, do not have distinct names (<a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a>).</p>
            </dd>
            <dt><a id="ERRXQST0090"/>err:XQST0090</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a <a title="character reference" class="termref" href="#dt-character-reference">character reference</a> does not identify a valid
            character in the version of XML that is in use.</p>
            </dd>
            <dt><a id="ERRXQDY0091"/>err:XQDY0091</dt><dd>
               <p>An implementation <a title="may" class="termref" href="#may">MAY</a> raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> if an <code>xml:id</code> error, as
            defined in <a href="#XMLID">[XML ID]</a>, is encountered during construction of an attribute
            named <code>xml:id</code>.</p>
            </dd>
            <dt><a id="ERRXQDY0092"/>err:XQDY0092</dt><dd>
               <p>An implementation <a title="may" class="termref" href="#may">MAY</a> raise a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> if a constructed attribute named
               <code>xml:space</code> has a value other than <code>preserve</code> or
               <code>default</code>.</p>
            </dd>
            
            <dt><a id="ERRXQST0094"/>err:XQST0094</dt><dd>
               <p> The name of each grouping variable must be equal (by the <code>eq</code> operator on
               <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a>) to the name of a variable
            in the input tuple stream.</p>
            </dd>
            
            
            <dt><a id="ERRXQDY0096"/>err:XQDY0096</dt><dd>
               <p>It is a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a>
                  <span>if</span> the node-name of a node constructed by a computed element
            constructor has any of the following properties: </p>
               <ul><li><p>Its namespace prefix is <code>xmlns</code>. </p></li><li><p>Its namespace URI is <code>http://www.w3.org/2000/xmlns/</code>. </p></li><li><p>Its namespace prefix is <code>xml</code> and its namespace URI is not
                     <code>http://www.w3.org/XML/1998/namespace</code>. </p></li><li><p>Its namespace prefix is other than <code>xml</code> and its namespace URI is
                     <code>http://www.w3.org/XML/1998/namespace</code>. </p></li></ul>
               
            </dd>
            <dt><a id="ERRXQST0097"/>err:XQST0097</dt><dd>
               <p> It is a static error for a decimal-format to specify a value that is not valid for a
            given property, as described in <a title="statically known decimal formats" class="termref" href="#dt-static-decimal-formats">statically
               known decimal formats</a>
               </p>
            </dd>
            <dt><a id="ERRXQST0098"/>err:XQST0098</dt><dd>
               <p> It is a static error if, for any named or unnamed decimal format, the properties
            representing characters used in a picture string do not each have distinct values. 
            <span>
              The following properties represent characters used in a picture
              string: 
                <a title="decimal-separator" class="termref" href="#id-static-decimal-format-decimal-separator">decimal-separator</a>, 
                <a title="exponent-separator" class="termref" href="#id-static-decimal-format-exponent-separator">exponent-separator</a>, 
                <a title="grouping-separator" class="termref" href="#id-static-decimal-format-grouping-separator">grouping-separator</a>,
                <a title="percent" class="termref" href="#id-static-decimal-format-percent">percent</a>, 
                <a title="per-mille" class="termref" href="#id-static-decimal-format-per-mille">per-mille</a>, 
                the family of ten decimal digits starting with <a title="zero-digit" class="termref" href="#id-static-decimal-format-zero-digit">zero-digit</a>, 
                <a title="digit" class="termref" href="#id-static-decimal-format-digit">digit</a>, and 
                <a title="pattern-separator" class="termref" href="#id-static-decimal-format-pattern-separator">pattern-separator</a>.
            </span>
               </p>
            </dd>
            <dt><a id="ERRXQST0099"/>err:XQST0099</dt><dd>
               <p>
                  
                  <span>No
               module</span> may contain more than one ContextItemDecl. </p>
            </dd>
            
            <dt><a id="ERRXQDY0101"/>err:XQDY0101</dt><dd>
               <p>An error is raised if a computed namespace constructor attempts to do any of the
            following:</p>
               <ul><li><p>Bind the prefix <code>xml</code> to some namespace URI other than
                     <code>http://www.w3.org/XML/1998/namespace</code>. </p></li><li><p>Bind a prefix other than <code>xml</code> to the namespace URI
                     <code>http://www.w3.org/XML/1998/namespace</code>. </p></li><li><p>Bind the prefix <code>xmlns</code> to any namespace URI. </p></li><li><p>Bind a prefix to the namespace URI <code>http://www.w3.org/2000/xmlns/</code>.
               </p></li><li><p>Bind any prefix (including the empty prefix) to a zero-length namespace
                  URI.</p></li></ul>
            </dd>
            <dt><a id="ERRXQDY0102"/>err:XQDY0102</dt><dd>
               <p> In an element constructor, if two or more namespace bindings in the in-scope bindings
            would have the same prefix, then an error is raised if they have different URIs; if they
            would have the same prefix and URI, duplicate bindings are ignored. </p>
               <p> If the name of an element in an element constructor is in no namespace, creating a
            default namespace for that element using a computed namespace constructor is an error.
         </p>
            </dd>
            <dt><a id="ERRXQST0103"/>err:XQST0103</dt><dd>
               <p>All variables in a <code>window</code> clause must have distinct names.</p>
            </dd>
            <dt><a id="ERRXQST0104"/>err:XQST0104</dt><dd>
               <p>A <a href="#prod-xquery40-TypeName">TypeName</a> that is specified in a <code>validate</code>
            expression must be found in the <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema
               definitions</a>
               </p>
            </dd>
            <dt><a id="ERRXQTY0105"/>err:XQTY0105</dt><dd>
               <p> It is a <a title="type error" class="termref" href="#dt-type-error">type error</a> if the content sequence in an
            element constructor contains a function .</p>
            </dd>
            <dt><a id="ERRXQST0106"/>err:XQST0106</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a function
            declaration contains both a <code>%private</code> and a <code>%public</code>
            annotation.</p>
               
               
            </dd>
            <dt><a id="ERRXQST0108"/>err:XQST0108</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if an <a title="output declaration" class="termref" href="#dt-output-declaration">output declaration</a> occurs in a <a title="library module" class="termref" href="#dt-library-module">library module</a>. </p>
            </dd>
            <dt><a id="ERRXQST0109"/>err:XQST0109</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the local name of an
            output declaration in the <code>http://www.w3.org/2010/xslt-xquery-serialization</code>
            namespace is not one of the serialization parameter names listed in <a href="#id-xq-static-context-components"><b>B.1 Static Context Components</b></a>, <span>or if the name of an
               output declaration is <code>use-character-maps</code>
                  </span>. </p>
            </dd>
            <dt><a id="ERRXQST0110"/>err:XQST0110</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the same serialization
            parameter is used more than once in an <a title="output declaration" class="termref" href="#dt-output-declaration">output
               declaration</a>.</p>
            </dd>
            <dt><a id="ERRXQST0111"/>err:XQST0111</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> for a query prolog to
            contain two decimal formats with the same name, or to contain two default decimal
            formats. </p>
            </dd>
            
            <dt><a id="ERRXQST0113"/>err:XQST0113</dt><dd>
               <p> Specifying a <a href="#prod-xquery40-VarValue">VarValue</a> or <a href="#prod-xquery40-VarDefaultValue">VarDefaultValue</a> for a context item declaration in a library module is a
               <a title="static error" class="termref" href="#dt-static-error">static error</a>. </p>
            </dd>
            <dt><a id="ERRXQST0114"/>err:XQST0114</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> for a decimal format
            declaration to define the same property more than once. </p>
            </dd>
            <dt><a id="ERRXQST0115"/>err:XQST0115</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if the document specified
            by the option <code>Q{http://www.w3.org/2010/xslt-xquery-serialization}parameter-document</code>
            raises a serialization error. </p>
            </dd>
            <dt><a id="ERRXQST0116"/>err:XQST0116</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a>
                  
                  <span>if a variable declaration contains both a <code>%private</code> and a
                  <code>%public</code> annotation, more than one <code>%private</code> annotation,
               or more than one <code>%public</code> annotation.</span>
               </p>
            </dd>
            <dt><a id="ERRXPTY0117"/>err:XPTY0117</dt><dd>
               <p>When applying the <a title="coercion rules" class="termref" href="#dt-coercion-rules">coercion rules</a>, if an item is of type <code>xs:untypedAtomic</code> and the
            expected type is <a title="namespace-sensitive" class="termref" href="#dt-namespace-sensitive">namespace-sensitive</a>, a
               <a title="type error" class="termref" href="#dt-type-error">type error</a>
                  [<a href="#ERRXPTY0117" title="err:XPTY0117">err:XPTY0117</a>] is raised. </p>
            </dd>
            <dt><a id="ERRXQST0118"/>err:XQST0118</dt><dd>
               <p>In a direct element constructor, the name used in the end tag must exactly match the
            name used in the corresponding start tag, including its prefix or absence of a
            prefix.</p>
            </dd>
            <dt><a id="ERRXQST0119"/>err:XQST0119</dt><dd>
               <p>It is a static error if the implementation is not able to process the value of an
               <code>output:parameter-document</code> declaration to produce an XDM instance.</p>
            </dd>
            
            
            <dt><a id="ERRXQST0125"/>err:XQST0125</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if an inline function
               <span>expression</span> is annotated as <code>%public</code> or
               <code>%private</code>. </p>
            </dd>
            
            
            <dt><a id="ERRXPDY0130"/>err:XPDY0130</dt><dd>
               <p>An implementation-dependent limit has been exceeded.</p>
            </dd>
            
            
            <dt><a id="ERRXQST0134"/>err:XQST0134</dt><dd>
               <p>The namespace axis is not supported.</p>
            </dd>
            
            
            <dt><a id="ERRXQDY0137"/>err:XQDY0137</dt><dd>
               <p>No two keys in a map may have the  <a title="same key" class="termref" href="#dt-same-key">same key value</a>.</p>
            </dd>
            
            <dt><a id="ERRXQST0140"/>err:XQST0140</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if a named item type declaration 
            is recursive, unless it satisfies the conditions defined in <a href="#id-recursive-record-tests"><b>3.2.8.3.1 Recursive Record Types</b></a>.</p>
            </dd>
            <dt><a id="ERRXPTY0141"/>err:XPTY0141</dt><dd>
               <p>In a <code>for</code>
                  <span class="xquery">clause</span>,
         when the keyword <code>member</code> is present, the value of the binding collection
         must be a single array; and when either or both of the keywords <code>key</code> and <code>value</code>
         are present, the value of the binding collection must be a single map.</p>
            </dd>
            <dt><a id="ERRXPTY0144"/>err:XPTY0144</dt><dd>
               <p>During the analysis phase, an axis step is classified as <a title="implausible" class="termref" href="#dt-implausible">implausible</a>
            if the combination of the inferred context item type, the choice of axis, and the
            supplied node test, is such that the axis step will always return an empty sequence.</p>
            </dd>
            <dt><a id="ERRXPTY0145"/>err:XPTY0145</dt><dd>
               <p>During the analysis phase, a unary or postfix lookup expression is classified as <a title="implausible" class="termref" href="#dt-implausible">implausible</a>
            if the combination of the inferred type of the left-hand operand (or the context item type
            in the case of a unary expression) and the choice of key specifier is such that the lookup expression
            will always return an empty sequence.</p>
            </dd>
            <dt><a id="ERRXQST0146"/>err:XQST0146</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if two or more item types
            declared or imported by a <a title="module" class="termref" href="#dt-module">module</a> have equal <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a> (as defined by the <code>eq</code>
            operator.)</p>
            </dd>
            
            <dt><a id="ERRXQST0148"/>err:XQST0148</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> if an optional parameter
            in a function declaration is followed by a parameter that does not have a default value.</p>
            </dd>
            <dt><a id="ERRXQST0149"/>err:XQST0149</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> 
         if the schemas imported by different modules of a query
         are not compatible as defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#schema-consistency">4.1.2 Schema Consistency</a>.</p>
            </dd>
            
            <dt><a id="ERRXQST0151"/>err:XQST0151</dt><dd>
               <p> It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> 
            if a node name supplied as a string literal in a computed element or
            attribute constructor does not take the form of an 
            <a href="#doc-xquery40-EQName">EQName</a>.</p>
            </dd>
            <dt><a id="ERRXPST0152"/>err:XPST0152</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> 
            if a key type named in a <a href="#prod-xquery40-TypedMapType"/> is not a
            <a title="generalized atomic type" class="termref" href="#dt-generalized-atomic-type">generalized atomic type</a>.</p>
            </dd>
            <dt><a id="ERRXQTY0153"/>err:XQTY0153</dt><dd>
               <p>The expression of a <code>finally</code> clause must return an empty sequence.</p>
            </dd>
            <dt><a id="ERRXPST0154"/>err:XPST0154</dt><dd>
               <p>It is a <a title="static error" class="termref" href="#dt-static-error">static error</a> 
            if a <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a> includes a prefix but no URI.</p>
            </dd>
         </dl></div><div class="div1 xquery">
<h2><a id="id-mime-type"/>F <a href="#id-mime-type" style="text-decoration: none">The <code>application/xquery</code> Media Type</a></h2><p>This Appendix 

    specifies the media type for XQuery Version 1.0.  XQuery is a language for querying over

    collections of data from XML data sources, as specified in the main body of this document. This media type is being 

submitted to the IESG (Internet Engineering Steering Group)

for review, approval, and registration with IANA (Internet Assigned Numbers

Authority.)</p><div class="div2">
<h3><a id="id-mime-type-intro"/>F.1 <a href="#id-mime-type-intro" style="text-decoration: none">Introduction</a></h3><p>

	This document, found at

	<a href="http://www.w3.org/TR/xquery/">http://www.w3.org/TR/xquery/</a>,

	together with its normative references,  defines the language XQuery Version 1.0.  This Appendix

      provides information about the <code>application/xquery</code> media type,

      which is intended to be used for transmitting queries written in the

      XQuery language.</p><p>This document was prepared by members of the W3C XML Query Working

      Group.  Please send comments to public-qt-comments@w3.org,

      a public mailing list with archives at

      <a href="http://lists.w3.org/Archives/Public/public-qt-comments">http://lists.w3.org/Archives/Public/public-qt-comments</a>.</p></div><div class="div2">
<h3><a id="id-registration-of-mime-type"/>F.2 <a href="#id-registration-of-mime-type" style="text-decoration: none">Registration of MIME Media Type <code>application/xquery</code>
            </a></h3><p>MIME media type name:  <code>application</code>
            </p><p>MIME subtype name:    <code>xquery</code>
            </p><p>Required parameters:  none</p><p>Optional parameters: none</p><p>The syntax of XQuery is expressed in Unicode but may be written

	with any Unicode-compatible character encoding, including UTF-8 or

	UTF-16, or transported as US-ASCII or ISO-8859-1 with Unicode

	characters outside the range of the given encoding represented using

	an XML-style <code>&amp;#xddd;</code> syntax.</p><div class="div3">
<h4><a id="id-interoperability-considerations"/>F.2.1 <a href="#id-interoperability-considerations" style="text-decoration: none">Interoperability Considerations</a></h4><p>None known.</p></div><div class="div3">
<h4><a id="id-applications-of-media-type"/>F.2.2 <a href="#id-applications-of-media-type" style="text-decoration: none">Applications Using this Media Type</a></h4><p>The public

	  <a href="http://www.w3.org/XML/Query/">XQuery Web page</a>

	  lists more than two dozen implementations of the XQuery language,

	  both proprietary and open source.</p><p>This  media
	type is 
	registered to allow for deployment of XQuery on the World Wide
	Web.</p></div><div class="div3">
<h4><a id="id-file-extensions"/>F.2.3 <a href="#id-file-extensions" style="text-decoration: none">File Extensions</a></h4><p>The most common file extensions in use for XQuery are

	  <code>.xq</code> and <code>.xquery</code>.</p><p>The appropriate Macintosh file type code is <code>TEXT</code>.</p></div><div class="div3">
<h4><a id="id-intended-usage"/>F.2.4 <a href="#id-intended-usage" style="text-decoration: none">Intended Usage</a></h4><p>The intended usage of this media type is for interchange

	of XQuery expressions.</p></div><div class="div3">
<h4><a id="id-author-change-controller"/>F.2.5 <a href="#id-author-change-controller" style="text-decoration: none">Author/Change Controller</a></h4><p>XQuery was produced by, and is maintained by, the World Wide Web

	Consortium’s XML Query Working Group.  The W3C has change

	control over this specification.</p></div></div><div class="div2">
<h3><a id="xquery-mime-encoding"/>F.3 <a href="#xquery-mime-encoding" style="text-decoration: none">Encoding Considerations</a></h3><p>For use with transports that are not 8-bit clean, quoted-printable

    encoding is recommended since the XQuery syntax itself uses the

    US-ASCII-compatible subset of Unicode.</p><p>An XQuery document may contain an <a title="encoding declaration" class="termref" href="#dt-encoding-declaration">encoding 

declaration</a> as part of its <a title="version declaration" class="termref" href="#dt-version-declaration">version declaration</a>:</p><div class="exampleInner"><pre>xquery version "3.1" encoding "utf-8";</pre></div></div><div class="div2">
<h3><a id="xquery-mime-recognizing"/>F.4 <a href="#xquery-mime-recognizing" style="text-decoration: none">Recognizing XQuery Files</a></h3><p>An XQuery file may have the string <code>xquery version "V.V"</code> near the

    beginning of the document, where <code>"V.V"</code> is a version number.

    Currently the version number, if present, must be <code>"1.0"</code>
               <span>, <code>"3.0"</code>, or <code>"3.1"</code>
               </span>.</p></div><div class="div2">
<h3><a id="id-charset-default-rules"/>F.5 <a href="#id-charset-default-rules" style="text-decoration: none">Charset Default Rules</a></h3><p>XQuery documents use the Unicode character set and, by default, the UTF-8 encoding.</p></div><div class="div2">
<h3><a id="id-security-considerations"/>F.6 <a href="#id-security-considerations" style="text-decoration: none">Security Considerations</a></h3><p>Queries written in XQuery may cause arbitrary URIs or IRIs to be

    dereferenced.  Therefore, the security issues of <a href="#RFC3987">[RFC3987]</a> Section 8 should be considered.

    In addition, the contents of resources identified by  <code>file:</code> URIs can in some cases be

    accessed, processed and returned as results. XQuery expressions can invoke any of the functions defined in

<a href="#xpath-functions-40">[Functions and Operators 4.0]</a>. For example, the

<code>fn:doc()</code> and <code>fn:doc-available()</code> functions  allow local filesystem probes as well as

access to any URI-defined resource accessible from the system

evaluating the XQuery expression.

<span>
The <code>fn:transform()</code> function allows calls to URI-identified
XSLT transformations which may in turn call external extension functions
and access or write to the file system. The <code>fn:transform()</code> function
should be sandboxed or disabled if untrusted queries are run.
</span>
            </p><p>XQuery is a full declarative programming language, and supports

user-defined functions, external function libraries (modules)

referenced by URI, and system-specific “native” functions.</p><p>Arbitrary recursion is possible, as is arbitrarily large

memory usage, and implementations may place limits on CPU

and memory usage, as well as restricting access to system-defined

functions.

</p><p>
      The optional XQuery Update Facility allows XQuery expressions to
      create and update persistent data, potentially including writing
      to arbitrary locations on the local filesystem as well as to
      remote URIs. Untrusted queries should not be given write access
      to data.
    </p><p>Furthermore, because the XQuery language permits extensions, 

    it is possible that <code>application/xquery</code>

    may describe content that has

    security implications beyond those described here.</p></div></div><div class="div1">
<h2><a id="id-glossary"/>G <a href="#id-glossary" style="text-decoration: none">Glossary</a> (Non-Normative)</h2><dl><dt><a href="#dt-absolute-path-expression">absolute path expression</a></dt><dd><p>
            An <b>absolute path expression</b> is an instance 
            of the production <a href="#prod-xquery40-AbsolutePathExpr">AbsolutePathExpr</a>:
            it consists of either (a) the operator <code>/</code> followed by zero or more 
            operands separated by <code>/</code> or <code>//</code> operators, or (b) the operator <code>//</code>
            followed by one or more operands separated by <code>/</code> or <code>//</code>
            operators.</p></dd><dt><a href="#dt-and-expression">and expression</a></dt><dd><p>An <b>and expression</b>
         is a <a title="non-trivial" class="termref" href="#dt-non-trivial">non-trivial</a> instance of the production <a href="#prod-xquery40-AndExpr">AndExpr</a>.</p></dd><dt><a href="#dt-anonymous-function">anonymous function</a></dt><dd><p>
             An <b>anonymous function</b> is a <a title="function item" class="termref" href="#dt-function-item">function item</a> with no name.  
             Anonymous functions may be created, for example, by evaluating an inline function 
             expression or by partial function application.</p></dd><dt><a href="#dt-application-function">application function</a></dt><dd><p>
                                    <b>Application functions</b> 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.</p></dd><dt><a href="#dt-arg-expr">argument expression</a></dt><dd><p>An argument to a function call is either an
               <b>argument expression</b> or an <a href="#prod-xquery40-ArgumentPlaceholder">ArgumentPlaceholder</a> 
               (<code>?</code>); in both cases it may
            either be supplied positionally, or identified by a name (called a keyword).</p></dd><dt><a href="#dt-arity-range">arity range</a></dt><dd><p>A <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> has an <b>arity range</b>,
                        which is a range of consecutive non-negative integers. If the function definition has <var>M</var> required parameters
                        and <var>N</var> optional parameters, then its arity range is from <var>M</var> to <var>M</var>+<var>N</var>
                        inclusive.</p></dd><dt><a href="#dt-array">array</a></dt><dd><p>An <b>array</b> is
      a <a title="function item" class="termref" href="#dt-function-item">function item</a> that associates a set of positions, represented as
      positive integer keys, with values.</p></dd><dt><a href="#dt-associated-value">associated value</a></dt><dd><p>The value
  associated with a given key is called the <b>associated
  value</b> of the key.</p></dd><dt><a href="#dt-atomic-item">atomic item</a></dt><dd><p>An <b>atomic
	 item</b> is a value in the value space of an <b>atomic
	 type</b>, as defined in <a href="#XMLSchema10">[XML Schema 1.0]</a>  or <a href="#XMLSchema11">[XML Schema 1.1]</a>.</p></dd><dt><a href="#dt-atomic-type">atomic type</a></dt><dd><p>An <b>atomic type</b>
            is a simple <a title="schema type" class="termref" href="#dt-schema-type">schema type</a> whose 
            <a href="https://www.w3.org/TR/xmlschema11-1/#std-variety">{variety}<sup><small>XS11-1</small></sup></a>
            is <code>atomic</code>.</p></dd><dt><a href="#dt-atomization">atomization</a></dt><dd><p>
                     <b>Atomization</b> of a sequence
is defined as the result of invoking the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-data"><code>fn:data</code></a> function, as defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#func-data">12.1.6 fn:data</a>.</p></dd><dt><a href="#dt-available-binary-resources">available binary resources</a></dt><dd><p>
                           <b>Available binary resources</b>. 
  This is a mapping of strings to binary resources. Each string
  represents the absolute URI of a resource. The resource is returned
  by the <code>fn:unparsed-binary</code> function when applied to that
  URI.</p></dd><dt><a href="#dt-available-docs">available documents</a></dt><dd><p>
                           <b>Available
    documents.</b> 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 <a title="data model" class="termref" href="#dt-datamodel">data model</a>. The document node is returned by the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-doc"><code>fn:doc</code></a> 
    function when applied to that URI.</p></dd><dt><a href="#dt-available-collections">available item collections</a></dt><dd><p>
                           <b>Available
                           collections.</b> 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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collection"><code>fn:collection</code></a>
                         function when that URI is supplied as the
                         argument. </p></dd><dt><a href="#dt-available-text-resources">available text resources</a></dt><dd><p>
                           <b>Available text resources</b>. 
  This is a mapping of strings to text resources. Each string
  represents the absolute URI of a resource. The resource is returned
  by the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-unparsed-text"><code>fn:unparsed-text</code></a> function when applied to that
  URI.</p></dd><dt><a href="#dt-available-uri-collections">available uri collections</a></dt><dd><p>
                           <b>Available
    URI collections.</b> 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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-uri-collection"><code>fn:uri-collection</code></a>
    function when that URI is supplied as the
    argument. </p></dd><dt><a href="#dt-axis-step">axis step</a></dt><dd><p>An <b>axis step</b> is an instance of the production
                  <a href="#doc-xquery40-AxisStep">AxisStep</a>: 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
		<b>axis</b>, which defines the direction of
		movement for the step, a <a title="node test" class="termref" href="#dt-node-test">node test</a>,
		which selects GNodes based on their properties, and zero or more predicates which are used
               to filter the results.</p></dd><dt><a href="#dt-base-uri-decl">base URI declaration</a></dt><dd><p>A <b>base URI declaration</b>
        specifies the <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a> property. The
          <a title="Static Base URI" class="termref" href="#dt-static-base-uri">Static Base URI</a> property is used when
        resolving relative URI references.</p></dd><dt><a href="#dt-binding-collection">binding collection</a></dt><dd><p>In a <code>for</code> clause, when an expression is 
                        preceded by the keyword <code>in</code>, the value of that expression is 
                        called a <b>binding collection</b>.</p></dd><dt><a href="#dt-binding-sequence">binding sequence</a></dt><dd><p>In a <code>window</code> clause, when an expression is 
                        preceded by the keyword <code>in</code>, the value of that expression is 
                        called a <b>binding sequence</b>.</p></dd><dt><a href="#dt-boundary-space-decl">boundary-space declaration</a></dt><dd><p>A <b>boundary-space
          declaration</b> sets the <a title="boundary-space policy" class="termref" href="#dt-boundary-space-policy">boundary-space
          policy</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>,
        overriding any implementation-defined default. Boundary-space policy controls whether
          <a title="boundary whitespace" class="termref" href="#dt-boundary-whitespace">boundary whitespace</a> is preserved by
        element constructors during processing of the query.</p></dd><dt><a href="#dt-boundary-space-policy">boundary-space policy</a></dt><dd><p>
                           <b>Boundary-space
			 policy.</b> This component controls the processing of <a title="boundary whitespace" class="termref" href="#dt-boundary-whitespace">boundary whitespace</a>
			 by <a title="direct element constructor" class="termref" href="#dt-direct-elem-const">direct element constructors</a>, as described in <a href="#id-whitespace"><b>4.12.1.4 Boundary Whitespace</b></a>.</p></dd><dt><a href="#dt-boundary-whitespace">boundary whitespace</a></dt><dd><p>
                        <b>Boundary whitespace</b> is a
sequence of consecutive whitespace characters within the content of a <a title="direct element constructor" class="termref" href="#dt-direct-elem-const">direct element constructor</a>, that is delimited at each end either by the start or
end of the content, or by a <a href="#prod-xquery40-DirectConstructor">DirectConstructor</a>, or by an <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a>. For this purpose, characters generated by
   <a title="character reference" class="termref" href="#dt-character-reference">character references</a> such as <code>&amp;#x20;</code> or by <a href="#prod-xquery40-CDataSection">CDataSections</a> are not
   considered to be whitespace characters.</p></dd><dt><a href="#dt-character-reference">character reference</a></dt><dd><p>A <b>character reference</b> is an XML-style reference to a <a href="#Unicode">[Unicode]</a> character, identified by its decimal or hexadecimal codepoint.</p></dd><dt><a href="#dt-choice-item-type">choice item type</a></dt><dd><p>A 
                  <b>choice item type</b> defines an item type that is the union
               of a number of alternatives. For example the type 
               <code>(xs:hexBinary | xs:base64Binary)</code> defines the union of 
                  these two primitive <a title="atomic type" class="termref" href="#dt-atomic-type">atomic types</a>, 
                  while the type <code>(map(*) | array(*))</code>
               matches any item that is either a map or an array.</p></dd><dt><a href="#dt-coercion-rules">coercion rules</a></dt><dd><p>The <b>coercion rules</b> 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.
                  </p></dd><dt><a href="#dt-collation">collation</a></dt><dd><p>A <b>collation</b> 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 <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#string-compare">5.3 Comparison of strings</a>.</p></dd><dt><a href="#dt-comma-operator">comma operator</a></dt><dd><p>A <b>comma operator</b> is a comma used specifically
                  as the operator in a <a title="sequence expression" class="termref" href="#dt-sequence-expression">sequence expression</a>.</p></dd><dt><a href="#dt-complex-terminal">complex terminal</a></dt><dd><p>A <b>complex terminal</b> is
        a <a title="variable terminal" class="termref" href="#dt-variable-terminal">variable terminal</a> whose production rule references, directly or indirectly, an 
        <a title="ordinary production rule" class="termref" href="#dt-ordinary-production-rule">ordinary production rule</a>.</p></dd><dt><a href="#dt-computed-elem-const">computed element constructor</a></dt><dd><p>A <b>computed element constructor</b> creates an element node, allowing both the name 
                     and the content of the node to be computed.</p></dd><dt><a href="#dt-constructed-element-namespace-rule">constructed element namespace rule</a></dt><dd><p>
                  When  an unprefixed lexical QName
               is expanded using the <b>constructed element namespace rule</b>, then it uses the namespace URI
                     that is bound to the empty (zero-length) prefix in the <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically known namespaces</a> of the
                     <a title="static context" class="termref" href="#dt-static-context">static context</a>. If there is no such <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace binding</a>
                  then it uses the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>.</p></dd><dt><a href="#dt-construction-decl">construction declaration</a></dt><dd><p>A <b>construction
          declaration</b> sets the <a title="construction mode" class="termref" href="#dt-construction-mode">construction
          mode</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>,
        overriding any implementation-defined default.</p></dd><dt><a href="#dt-construction-mode">construction mode</a></dt><dd><p>
                           <b>Construction mode.</b> The
			 construction mode governs the behavior of element and document node constructors. If construction mode is <code>preserve</code>, the type of a constructed element node is <code>xs:anyType</code>, and all attribute and element nodes copied during node construction    retain their original types. If construction mode is <code>strip</code>, the type of a constructed element node is <code>xs:untyped</code>; all element nodes copied during node construction receive the type <code>xs:untyped</code>, and all attribute nodes copied during node construction receive the type <code>xs:untypedAtomic</code>.</p></dd><dt><a href="#dt-constructor-function">constructor function</a></dt><dd><p>The <b>constructor function</b> 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 <code>T($arg)</code> are defined to be equivalent to the expression <code>$arg cast as T?</code>.</p></dd><dt><a href="#dt-content-expression">content expression</a></dt><dd><p>In an  <a title="enclosed expression" class="termref" href="#dt-enclosed-expression">enclosed expression</a>, the optional expression enclosed in curly brackets is called the <b>content expression</b>.</p></dd><dt><a href="#dt-context-dependent">context dependent</a></dt><dd><p>A 
                        <a title="function definition" class="termref" href="#dt-function-definition">function definition</a> is said to be <b>context dependent</b>
                        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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-name"><code>fn:name#0</code></a> is context-dependent
                        while <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-name"><code>fn:name#1</code></a> is context-independent.</p></dd><dt><a href="#dt-context-node">context node</a></dt><dd><p>When the context value is a single item, it can also be referred
                        to as the <b>context item</b>; when it is a single node,
it can also be referred to as the <b>context
node</b>.</p></dd><dt><a href="#dt-context-position">context position</a></dt><dd><p>The <b>context
position</b> is the position of the context value within the
series of values currently being processed.</p></dd><dt><a href="#dt-context-size">context size</a></dt><dd><p>The <b>context
size</b> is the number of values in the series of values currently
being processed.</p></dd><dt><a href="#dt-context-value">context value</a></dt><dd><p>The <b>context value</b>
is the <a title="value" class="termref" href="#dt-value">value</a> currently being processed.</p></dd><dt><a href="#dt-copy-namespaces-decl">copy-namespaces declaration</a></dt><dd><p>A
          <b>copy-namespaces declaration</b> sets the value of <a title="copy-namespaces mode" class="termref" href="#dt-copy-namespaces-mode">copy-namespaces mode</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>, 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.</p></dd><dt><a href="#dt-copy-namespaces-mode">copy-namespaces mode</a></dt><dd><p>
                           <b>Copy-namespaces mode.</b> This component controls the <a title="in-scope namespaces" class="termref" href="#dt-in-scope-namespaces">in-scope namespaces</a>
                        property that
is assigned when an existing element node is copied by an element
constructor, as described in <a href="#id-element-constructor"><b>4.12.1 Direct Element Constructors</b></a>. Its value consists of two parts: <code>preserve</code> or <code>no-preserve</code>, and <code>inherit</code> or <code>no-inherit</code>.</p></dd><dt><a href="#dt-date-time">current dateTime</a></dt><dd><p>
                           <b>Current dateTime.</b> This information represents
				an <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> point in time during the processing of <span class="xquery">a query</span>
                        , and includes an explicit timezone. It can be retrieved by the  <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-current-dateTime"><code>fn:current-dateTime</code></a> function. 
                        If called multiple times during the execution of <span class="xquery">a query</span>
                        ,
				this function always returns the same result.</p></dd><dt><a href="#dt-datamodel">data model</a></dt><dd><p>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 <b>data model</b>, is defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a>.</p></dd><dt><a href="#dt-decimal-format-decl">decimal-format         declaration</a></dt><dd><p>A <b>decimal format
          declaration</b> adds a decimal format to the <a title="statically known decimal formats" class="termref" href="#dt-static-decimal-formats">statically known decimal formats</a>, which define the properties used to format
        numbers using the <code>fn:format-number()</code> function</p></dd><dt><a href="#id-static-decimal-format-decimal-separator">decimal-separator</a></dt><dd><p>
                              <b>decimal-separator</b>
                              <em>(<var>M</var>, <var>R</var>)</em> 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 <span class="unicode-codepoint">U+002E</span> (<span class="unicode-name">FULL STOP, PERIOD</span>, <code>.</code>) .</p></dd><dt><a href="#dt-default-annotation-namespace-rule">default annotation namespace rule</a></dt><dd><p>
                  When  an unprefixed lexical QName
               is expanded using the <b>annotation namespace rule</b>, then it uses the namespace URI
                     <code>http://www.w3.org/2012/xquery</code>.</p></dd><dt><a href="#dt-default-calendar">default calendar</a></dt><dd><p>
                           <b>Default calendar.</b>
    This is the calendar used when formatting dates in human-readable output
    (for example, by the functions <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-date"><code>fn:format-date</code></a> and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-dateTime"><code>fn:format-dateTime</code></a>)
    if no other calendar is requested. 
    The value is a string.</p></dd><dt><a href="#dt-def-collation">default collation</a></dt><dd><p>
                           <b>Default
                           collation.</b> This identifies one of the collations in <a title="statically known collations" class="termref" href="#dt-static-collations">statically known collations</a> as the  collation to be
                        used by functions and operators for comparing and ordering values of type <code>xs:string</code> and <code>xs:anyURI</code> (and types derived from them) when no
                        explicit collation is
                        specified.</p></dd><dt><a href="#dt-default-collation-decl">default collation declaration</a></dt><dd><p>A <b>default
          collation declaration</b> sets the value of the <a title="default collation" class="termref" href="#dt-def-collation">default
          collation</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>,
        overriding any implementation-defined default.</p></dd><dt><a href="#dt-default-collection">default collection</a></dt><dd><p>
                           <b>Default  collection.</b>
    This is the sequence of items  that would result from calling the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collection"><code>fn:collection</code></a> function
    with no arguments.</p></dd><dt><a href="#dt-default-element-namespace-rule">default element namespace rule</a></dt><dd><p>When 
                  an unprefixed lexical QName
               is expanded using the <b>default element namespace rule</b>, then it uses the 
                  <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>. If this is absent, or if it takes
                  the special value <code>##any</code>, then the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>
                  is used.</p></dd><dt><a href="#dt-default-function-namespace">default function namespace</a></dt><dd><p>
                           <b>Default function namespace.</b> This determines how unprefixed lexical QNames
                        appearing in a <a title="static function call" class="termref" href="#dt-static-function-call">static function call</a> or a
                        <a title="named function reference" class="termref" href="#dt-named-function-ref">named function reference</a> are interpreted.</p></dd><dt><a href="#dt-default-function-namespace-rule">default function namespace rule</a></dt><dd><p>When 
                     an unprefixed lexical QName
                     is expanded using the <b>default function namespace rule</b>, 
                     the processor searches for a matching function definition as follows: 
                     first, if the static context includes a no-namespace function definition 
                     with the required local name and arity, then that function definition is used; 
                     otherwise, the name is expanded using the <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a> from 
                     the <a title="static context" class="termref" href="#dt-static-context">static context</a>.</p></dd><dt><a href="#dt-default-in-scope-namespace">default in-scope namespace</a></dt><dd><p>The <b>default in-scope namespace</b>
         of an element node</p></dd><dt><a href="#dt-default-language">default language</a></dt><dd><p>
                           <b>Default language.</b>
  This is the natural language used when creating human-readable output
  (for example, by the functions <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-date"><code>fn:format-date</code></a> and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-integer"><code>fn:format-integer</code></a>)
  if no other language is requested. 
  The value is a language code as defined by the type <code>xs:language</code>.</p></dd><dt><a href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a></dt><dd><p>
                           <b>Default namespace for elements and types.</b> This is either a
				namespace URI, or the special value <code>"##any"</code>, or <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>. This indicates how unprefixed QNames are interpreted when
                        they appear in a position  where an element name or type name is expected.</p></dd><dt><a href="#dt-default-empty-order">default order for empty sequences</a></dt><dd><p>
                           <b>Default order for empty sequences.</b> This component controls the processing of empty sequences and <code>NaN</code> values as ordering keys in an <code>order by</code> clause in a FLWOR expression, as described in <a href="#id-order-by-clause"><b>4.13.9 Order By Clause</b></a>.</p></dd><dt><a href="#dt-default-place">default place</a></dt><dd><p>
                           <b>Default place.</b>
    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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-date"><code>fn:format-date</code></a>, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-dateTime"><code>fn:format-dateTime</code></a>,
     and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-civil-timezone"><code>fn:civil-timezone</code></a>,
    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.</p></dd><dt><a href="#dt-default-type-namespace-rule">default type namespace rule</a></dt><dd><p>When 
                  an unprefixed lexical QName
               is expanded using the <b>default type namespace rule</b>, it uses the 
                  <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>. If this is absent, the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>
                  is used. If the <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> has the special value <code>##any</code>,
                  then the lexical QName refers to a name in the namespace <code>http://www.w3.org/2001/XMLSchema</code>.</p></dd><dt><a href="#dt-default-uri-collection">default URI collection</a></dt><dd><p>
                           <b>Default URI collection.</b>
    This is the sequence of URIs that would result from calling the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-uri-collection"><code>fn:uri-collection</code></a> function
    with no arguments.</p></dd><dt><a href="#delimiting-token">delimiting terminal symbol</a></dt><dd><p>The <b>delimiting
            terminal symbols</b> are: <code>!</code>
                     <code>!=</code>
                     <code>#</code>
                     <code>#)</code>
                     <code>$</code>
                     <code>%</code>
                     <code>(</code>
                     <code>(#</code>
                     <code>)</code>
                     <code>*</code>
                     <code>*:</code>
                     <code>+</code>
                     <code>,</code>
                     <code>-</code>
                     <code>--&gt;</code>
                     <code>-&gt;</code>
                     <code>.</code>
                     <code>..</code>
                     <code>/</code>
                     <code>//</code>
                     <code>/&gt;</code>
                     <code>:</code>
                     <code>:*</code>
                     <code>::</code>
                     <code>:=</code>
                     <code>;</code>
                     <code>&lt;</code>
                     <code>&lt;!--</code>
                     <code>&lt;![CDATA[</code>
                     <code>&lt;/</code>
                     <code>&lt;&lt;</code>
                     <code>&lt;=</code>
                     <code>&lt;?</code>
                     <code>=</code>
                     <code>=!&gt;</code>
                     <code>=&gt;</code>
                     <code>=?&gt;</code>
                     <code>&gt;</code>
                     <code>&gt;=</code>
                     <code>&gt;&gt;</code>
                     <code>?</code>
                     <code>?&gt;</code>
                     <code>?[</code>
                     <code>@</code>
                     <code>[</code>
                     <code>]</code>
                     <code>]]&gt;</code>
                     <code>]``</code>
                     <code>`</code>
                     <code>``</code>
                     <code>``[</code>
                     <code>`{</code>
                     <code>{</code>
                     <code>{{</code>
                     <code>|</code>
                     <code>||</code>
                     <code>}</code>
                     <code>}`</code>
                     <code>}}</code>
                     <code>×</code>
                     <code>÷</code>
                     <a href="#prod-xquery40-AposStringLiteral">AposStringLiteral</a>
                     <a href="#prod-xquery40-BracedURILiteral">BracedURILiteral</a>
                     <a href="#prod-xquery40-QuotStringLiteral">QuotStringLiteral</a>
                     <a href="#prod-xquery40-S">S</a>
                     <a href="#prod-xquery40-StringLiteral">StringLiteral</a>
                     <a href="#prod-xquery40-URIQualifiedName">URIQualifiedName</a>
                  </p></dd><dt><a href="#dt-depends-on">depends on</a></dt><dd><p>A variable value (or the context value)
          <b>depends on</b> 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.</p></dd><dt><a href="#dt-derives-from">derives from</a></dt><dd><p>A 
               <a title="schema type" class="termref" href="#dt-schema-type">schema type</a>
                     <var>S<sub>1</sub></var> is said to <b>derive from</b>
                     <a title="schema type" class="termref" href="#dt-schema-type">schema type</a>
                     <var>S<sub>2</sub></var> if any of the following
               conditions is true:</p><ul><li><p>
                        <var>S<sub>1</sub></var> is the same type as <var>S<sub>2</sub></var>.</p></li><li><p>
                        <var>S<sub>2</sub></var> is the base type of <var>S<sub>1</sub></var>.</p></li><li><p>
                        <var>S<sub>2</sub></var> is a <a title="pure union type" class="termref" href="#dt-pure-union-type">pure union type</a>
                     of which <var>S<sub>1</sub></var> is a member type.</p></li><li><p>There is a <a title="schema type" class="termref" href="#dt-schema-type">schema type</a>
                        <var>M</var> such that 
                     <var>S<sub>1</sub></var>
                        <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                        <var>M</var>
                     and <var>M</var>
                        <a title="derives from" class="termref" href="#dt-derives-from">derives from</a>
                        <var>S<sub>2</sub></var>.</p></li></ul></dd><dt><a href="#id-static-decimal-format-digit">digit</a></dt><dd><p>
                              <b>digit</b>
                              <em>(<var>M</var>)</em>
                                 is a character used in the picture string to represent an optional digit; 
                                 the default value is <span class="unicode-codepoint">U+0023</span> (<span class="unicode-name">NUMBER SIGN</span>, <code>#</code>) .</p></dd><dt><a href="#dt-direct-elem-const">direct element constructor</a></dt><dd><p>A <b>direct element constructor</b> is a form of element constructor in which the name 
               of the constructed element is a constant.</p></dd><dt><a href="#dt-document-order">document order</a></dt><dd><p>Informally, <b>document order</b> is the order in which nodes appear in the XML serialization of a document.</p></dd><dt><a href="#dt-dynamically-known-function-definitions">dynamically known function definitions</a></dt><dd><p>
                           <b>Dynamically known function definitions</b>.
        This is a set of <a title="function definition" class="termref" href="#dt-function-definition">function definitions</a>. It includes the
                        <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a> as a subset, but may include
                        other function definitions that are not known statically.
      </p></dd><dt><a href="#dt-dynamic-context">dynamic context</a></dt><dd><p>The <b>dynamic
context</b> 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 <a title="static context" class="termref" href="#dt-static-context">static context</a>.</p></dd><dt><a href="#dt-dynamic-error">dynamic error</a></dt><dd><p>A <b>dynamic
error</b> is an error that
must be detected during the dynamic evaluation phase and may be detected
during the static analysis phase.</p></dd><dt><a href="#dt-dynamic-evaluation">dynamic evaluation phase</a></dt><dd><p>The <b>dynamic evaluation phase</b> is the phase during which the value of an expression is computed.</p></dd><dt><a href="#dt-dynamic-function-call">dynamic function call</a></dt><dd><p>
               is 
            </p></dd><dt><a href="#dt-dynamic-type">dynamic type</a></dt><dd><p>
                  Every value matches one or more <a title="sequence type" class="termref" href="#dt-sequence-type">sequence types</a>. 
                     A value is said to have a <b>dynamic type</b>
                        <var>T</var> if it matches (or <b>is an instance of</b>) 
                     the sequence type <var>T</var>.</p></dd><dt><a href="#dt-ebv">effective boolean value</a></dt><dd><p>The
<b>effective boolean value</b> of a value is defined as the result
of applying the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-boolean"><code>fn:boolean</code></a> function to the value.</p></dd><dt><a href="#id-effective-case-switch-expression">effective case</a></dt><dd><p> The <b>effective case</b> 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.</p></dd><dt><a href="#dt-effective-case">effective case</a></dt><dd><p>The <b>effective case</b> in a
<code>typeswitch</code> expression is the first <code>case</code>
clause in which the value of the operand expression matches a <a href="#doc-xquery40-SequenceType">SequenceType</a> in the <a href="#doc-xquery40-SequenceType">SequenceTypeUnion</a> of the <code>case</code>
clause, using the rules of <a title="SequenceType matching" class="termref" href="#dt-sequencetype-matching">SequenceType matching</a>.
</p></dd><dt><a href="#dt-element-name-matching-rule">element name matching rule</a></dt><dd><p>When 
                  an unprefixed lexical QName
               is expanded using the <b>element name matching rule</b> rule, then it uses the 
                  <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a>. If this is absent, then 
                  it uses the <a title="no-namespace rule" class="termref" href="#dt-no-namespace-rule">no-namespace rule</a>. But if it takes the special value <code>##any</code>,
                  then the name is taken as matching any <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> with the corresponding local part,
                  regardless of namespace: that is, the  unprefixed name <code>local</code> is interpreted
                  as <code>*:local</code>.</p></dd><dt><a href="#dt-empty-order-decl">empty order declaration</a></dt><dd><p>An <b>empty order
          declaration</b> sets the <a title="default order for empty sequences" class="termref" href="#dt-default-empty-order">default order for empty
          sequences</a> in the <a title="static context" class="termref" href="#dt-static-context">static context,</a>
        overriding any implementation-defined default. This declaration controls the processing of
        empty sequences and <code>NaN</code> values as ordering keys in an <code>order by</code>
        clause in a FLWOR expression.</p></dd><dt><a href="#dt-empty-sequence">empty sequence</a></dt><dd><p>A sequence containing zero items is called an <b>empty sequence</b>.</p></dd><dt><a href="#dt-enclosed-expression">enclosed expression</a></dt><dd><p>An <b>enclosed expression</b> is an instance of the <a href="#doc-xquery40-EnclosedExpr">EnclosedExpr</a> production, which allows an optional expression within curly brackets.</p></dd><dt><a href="#dt-encoding-declaration">encoding declaration</a></dt><dd><p>If present, a version
        declaration may optionally include an <b>encoding declaration</b>. The value of the
        string literal following the keyword <code>encoding</code> is an encoding name, and must
        conform to the definition of <code>EncName</code> specified in <a href="#XML">[XML 1.0]</a>
                  [<a href="#ERRXQST0087" title="err:XQST0087">err:XQST0087</a>]. 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
          <code>"UTF-8"</code>, <code>"UTF-16"</code>, or <code>"US-ASCII"</code>.</p></dd><dt><a href="#dt-entry">entry</a></dt><dd><p>Each key / value pair in a map
  is called an <b>entry</b>.</p></dd><dt><a href="#dt-enumeration-type">enumeration type</a></dt><dd><p>An <b>EnumerationType</b>
                  accepts a fixed set of string values.</p></dd><dt><a href="#dt-environment-variables">environment variables</a></dt><dd><p>
                           <b>Environment variables.</b>
  This is a mapping from names to values. 
    Both the names and the values are strings. The names are compared using an
    <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> collation, and are unique under this collation. The set of environment variables is
  <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> and <span class="verb">may</span> be empty.</p></dd><dt><a href="#dt-equivalent-grouping-keys">equivalent grouping keys</a></dt><dd><p>Two
  tuples <var>T<sub>1</sub></var> and <var>T<sub>2</sub></var> have <b>equivalent
  grouping keys</b> if and only if, for each grouping variable
  <var>GV</var>, the atomized value of <var>GV</var> in <var>T<sub>1</sub></var>
  is deep-equal to the atomized value of <var>GV</var> in
  <var>T<sub>2</sub></var>, as defined by applying the function
  <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-deep-equal"><code>fn:deep-equal</code></a> using the appropriate
  collation.</p></dd><dt><a href="#dt-error-value">error value</a></dt><dd><p>In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called <b>error values</b>.</p></dd><dt><a href="#dt-executable-base-uri">Executable Base URI</a></dt><dd><p>
                           <b>Executable Base URI.</b> 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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-doc"><code>fn:doc</code></a> or <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-unparsed-text"><code>fn:unparsed-text</code></a>
                     functions.
                  </p></dd><dt><a href="#dt-expanded-qname">expanded QName</a></dt><dd><p>An <b>expanded QName</b> 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.</p></dd><dt><a href="#id-static-decimal-format-exponent-separator">exponent-separator</a></dt><dd><p>
                              <b>exponent-separator</b>
                              <em>(<var>M</var>, <var>R</var>)</em> is
                                 used to separate the mantissa from the exponent in
                                 scientific notation. The default value 
                                 for both the marker and the rendition is <span class="unicode-codepoint">U+0065</span> (<span class="unicode-name">LATIN SMALL LETTER E</span>, <code>e</code>) .</p></dd><dt><a href="#dt-expression-context">expression context</a></dt><dd><p>The <b>expression
		context</b> for a given expression consists of all
		the information that can affect the result of the
		expression.</p></dd><dt><a href="#dt-extension-expression">extension expression</a></dt><dd><p>An <b>extension expression</b> is an expression whose semantics are
<a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>.</p></dd><dt><a href="#dt-external-function">external function</a></dt><dd><p>
                                    <b>External functions</b> 
                           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 
                           <a href="https://www.w3.org/TR/xslt-30/#extension-functions">
            
               24.1 Extension Functions
         </a><sup><small>XT30</small></sup>. </p></dd><dt><a href="#dt-filter-expression">filter expression</a></dt><dd><p>
               A <b>filter expression</b> is an
               instance of the construct <a href="#doc-xquery40-FilterExpr">FilterExpr</a>:
               that is, it is an expression in the form <code>
                           <var>E<sub>1</sub></var>[<var>E<sub>2</sub></var>]</code>. 
               Its effect is to return those items from the value of <var>E<sub>1</sub></var> that
               satisfy the predicate in <var>E<sub>2</sub></var>.</p></dd><dt><a href="#dt-filter-expression-ma">filter expression for maps and arrays</a></dt><dd><p>
               A <b>filter expression for maps and arrays</b> is an
               instance of the construct <a href="#doc-xquery40-FilterExprAM">FilterExprAM</a>:
               that is, it is an expression in the form <code>
                           <var>E<sub>1</sub></var>?[<var>E<sub>2</sub></var>]</code>. 
               Its effect is to evaluate <var>E<sub>1</sub></var> to return an array or map, and to select
               members of the array, or entries from the map, that satisfy the predicate in <var>E<sub>2</sub></var>.</p></dd><dt><a href="#dt-fixed-focus">fixed focus</a></dt><dd><p>A <b>fixed focus</b> 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.</p></dd><dt><a href="#dt-focus">focus</a></dt><dd><p>The first three components of
the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a>
(context value, context position, and context size) are called the
<b>focus</b> of the expression. </p></dd><dt><a href="#dt-focus-function">focus function</a></dt><dd><p>A <b>focus function</b>
               is an inline function expression in which the function signature is implicit: the function takes
               a single argument of type <code>item()*</code> (that is, any value), and binds this to the 
                  context value when evaluating
               the function body, which returns a result of type <code>item()*</code>.</p></dd><dt><a href="#dt-function-assertion">function assertion</a></dt><dd><p> A
    <b>function assertion</b> is a predicate that restricts the
    set of functions matched by a FunctionType. It uses the same
    syntax as <a href="#id-annotations"><b>5.15 Annotations</b></a>.</p></dd><dt><a href="#dt-function-coercion">function coercion</a></dt><dd><p>
                     <b>Function coercion</b> wraps a <a title="function item" class="termref" href="#dt-function-item">function item</a>
        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.</p></dd><dt><a href="#dt-function-definition">function definition</a></dt><dd><p>A <b>function definition</b>
                  contains information used to evaluate a static function call, including the name, parameters,
                  and return type of the function.</p></dd><dt><a href="#dt-function-item">function item</a></dt><dd><p>A <b>function item</b> is an item that can
         be called using a <a title="dynamic function call" class="termref" href="#dt-dynamic-function-call">dynamic function call</a>.</p></dd><dt><a href="#dt-generalized-atomic-type">generalized atomic type</a></dt><dd><p>A <b>generalized atomic type</b> is an 
                        <a title="item type" class="termref" href="#dt-item-type">item type</a> whose instances are all
                        atomic items. Generalized atomic types include (a) 
                        <a title="atomic type" class="termref" href="#dt-atomic-type">atomic types</a>, either built-in
                        (for example <code>xs:integer</code>) or imported from a schema, 
                        (b) <a title="pure union type" class="termref" href="#dt-pure-union-type">pure union types</a>, either built-in
                        (<code>xs:numeric</code> and <code>xs:error</code>) or imported from a schema,
                        (c) <a title="choice item type" class="termref" href="#dt-choice-item-type">choice item types</a> if their alternatives
                        are all generalized atomic types, and 
                        (d) <a title="enumeration type" class="termref" href="#dt-enumeration-type">enumeration types</a>.
                     </p></dd><dt><a href="#dt-GNode">GNode</a></dt><dd><p>The term <b>generic node</b> or <b>GNode</b>
    is a collective term for <a title="XNode" class="termref" href="#dt-XNode">XNodes</a> (more commonly called simply
      <a title="node" class="termref" href="#dt-node">nodes</a>) representing
    the parts of an XML document, and <a title="JNode" class="termref" href="#dt-JNode">JNodes</a>, 
    often used to represent the parts of a JSON document.</p></dd><dt><a href="#dt-grouping-key">grouping key</a></dt><dd><p>The
  atomized value of a <a title="grouping variable" class="termref" href="#dt-grouping-variable">grouping
  variable</a> is called a <b>grouping key</b>.</p></dd><dt><a href="#id-static-decimal-format-grouping-separator">grouping-separator</a></dt><dd><p>
                              <b>grouping-separator</b>
                              <em>(<var>M</var>, <var>R</var>)</em> is used to 
                                 separate groups of digits (for example as a thousands separator).
                                 The default value for both the marker and the rendition is <span class="unicode-codepoint">U+002C</span> (<span class="unicode-name">COMMA</span>, <code>,</code>) .</p></dd><dt><a href="#dt-grouping-variable">grouping variable</a></dt><dd><p>Each grouping specification specifies one <b>grouping variable</b>, 
                     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.</p></dd><dt><a href="#dt-GTree">GTree</a></dt><dd><p>The term <b>GTree</b>
         means <a title="JTree" class="termref" href="#dt-JTree">JTree</a> or <a title="XTree" class="termref" href="#dt-XTree">XTree</a>.</p></dd><dt><a href="#dt-guarded">guarded</a></dt><dd><p>An expression <var>E</var> is said to be <b>guarded</b>
               by some governing condition <var>C</var> if evaluation of <var>E</var> is not allowed to fail
               with a <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic error</a> except when <var>C</var> applies.</p></dd><dt><a href="#IgnorableWhitespace">ignorable whitespace</a></dt><dd><p>
                        <b>Ignorable whitespace</b> consists of any <a title="whitespace" class="termref" href="#Whitespace">whitespace</a> characters that may occur between <a title="terminal" class="termref" href="#terminal">terminals</a>, unless these characters occur in the context of a production
            marked with a <a href="#ExplicitWhitespaceHandling"> ws:explicit</a> annotation, in
            which case they can occur only where explicitly specified (see <a href="#ExplicitWhitespaceHandling"><b>A.3.4.2 Explicit Whitespace Handling</b></a>).</p></dd><dt><a href="#dt-implausible">implausible</a></dt><dd><p>Certain expressions, while not
            erroneous, are classified as being <b>implausible</b>,
            because they achieve no useful effect.</p></dd><dt><a href="#dt-implementation-defined">implementation defined</a></dt><dd><p>
                        <b>Implementation-defined</b> indicates an aspect that may differ
					between implementations, but must be specified by the implementer for each
					particular implementation.</p></dd><dt><a href="#dt-implementation-dependent">implementation   dependent</a></dt><dd><p>
                        <b>Implementation-dependent</b> 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.</p></dd><dt><a href="#dt-timezone">implicit timezone</a></dt><dd><p>
                           <b>Implicit timezone.</b> 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  <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> value of type
<code>xs:dayTimeDuration</code>. See <a href="https://www.w3.org/TR/xmlschema-2/#dateTime-timezones">
                  
                     3.2.7.3 Timezones
               </a><sup><small>XS1-2</small></sup> or
<a href="https://www.w3.org/TR/xmlschema11-2/#dateTime">
               
                  3.3.7 dateTime
            </a><sup><small>XS11-2</small></sup> for the range of valid values of a timezone.</p></dd><dt><a href="#id-static-decimal-format-infinity">infinity</a></dt><dd><p>
                              <b>infinity</b>
                              <em>(<var>R</var>)</em>
                                 is the string used to represent the double value infinity (<code>INF</code>); the
                                 default value is the string <code>"Infinity"</code>
                           </p></dd><dt><a href="#dt-initial-context-value">initial context value</a></dt><dd><p>
    
    
      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 <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-absent">absent</a><sup><small>DM</small></sup>,
      it is referred to as the <b>initial context value</b>.
    
  </p></dd><dt><a href="#dt-initializing-expression">initializing expression</a></dt><dd><p>If a variable
        declaration includes an expression (<code>VarValue</code> or <code>VarDefaultValue</code>),
        the expression is called an <b>initializing expression.</b> The static context for an
        initializing expression includes all functions, variables, and namespaces that are declared
        or imported anywhere in the Prolog.</p></dd><dt><a href="#dt-inline-func">inline function expression</a></dt><dd><p>An 
                  <b>inline function expression</b> is an instance of the
                  construct <a href="#doc-xquery40-InlineFunctionExpr">InlineFunctionExpr</a>. When evaluated, 
                  an inline function expression creates
          an <a title="anonymous function" class="termref" href="#dt-anonymous-function">anonymous function</a>
          whose properties are defined directly in the inline function expression.</p></dd><dt><a href="#dt-is-attrs">in-scope attribute declarations</a></dt><dd><p>
                                 <b>In-scope attribute
declarations.</b> Each attribute declaration is identified either
by an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> (for a top-level attribute declaration) or by an
<a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> attribute identifier (for a local attribute
declaration).  <span class="xquery">If the
<a title="schema aware feature" class="termref" href="#dt-schema-aware-feature">Schema Aware Feature</a>
is supported, in-scope attribute declarations include all attribute
declarations found in imported
schemas.</span>
                              </p></dd><dt><a href="#dt-is-elems">in-scope element declarations</a></dt><dd><p>
                                 <b>In-scope element declarations.</b> Each element
declaration is identified either by an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> (for a top-level element
declaration) or by an <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> element identifier (for a
local element declaration). <span class="xquery"> If the
<a title="schema aware feature" class="termref" href="#dt-schema-aware-feature">Schema Aware Feature</a>
is supported, in-scope element declarations include all element
declarations found in imported schemas. </span>
                              </p></dd><dt><a href="#dt-in-scope-named-item-types">in-scope named item types</a></dt><dd><p>
                           <b>In-scope named item types.</b> This is a mapping from 
                        <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a> to 
                        <a title="named item type" class="termref" href="#dt-named-item-type">named item types</a>.</p></dd><dt><a href="#dt-in-scope-namespaces">in-scope namespaces</a></dt><dd><p>The <b>in-scope namespaces</b> property of an element node is a set of 
         <a title="namespace binding" class="termref" href="#dt-namespace-binding">namespace bindings</a>, each of which associates a namespace prefix with a URI.</p></dd><dt><a href="#dt-issd">in-scope schema definitions</a></dt><dd><p>
                           <b>In-scope schema
			 definitions</b> 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.</p></dd><dt><a href="#dt-is-types">in-scope schema type</a></dt><dd><p>
                                 <b>In-scope schema types.</b> Each schema type
			        definition is identified either by an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded
			        QName</a> (for a <b>named type</b>)
			        or by an <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a> type
			        identifier (for an <b>anonymous
			        type</b>). The in-scope schema types include the predefined schema types described in <a href="#id-predefined-types"><b>3.5 Schema Types</b></a>.

                                <span class="xquery">If the
                                <a title="schema aware feature" class="termref" href="#dt-schema-aware-feature">Schema Aware Feature</a>
                                is supported, in-scope schema types
                                also include all type definitions
                                found in imported schemas.</span>
                              </p></dd><dt><a href="#dt-in-scope-variables">in-scope variables</a></dt><dd><p>
                           <b>In-scope variables.</b> 
                           This is a mapping from <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a> to sequence types. It defines the
                           set of variables that are available for reference within an
                           expression. The <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> is the name of the variable, and the type is the
                           <a title="static type" class="termref" href="#dt-static-type">static type</a> of the
                           variable.</p></dd><dt><a href="#dt-item">item</a></dt><dd><p>
  An <b>item</b> is either an <a title="atomic item" class="termref" href="#dt-atomic-item">atomic item</a>, a <a title="node" class="termref" href="#dt-node">node</a>,
or a <a title="function item" class="termref" href="#dt-function-item">function item</a>.</p></dd><dt><a href="#dt-item-type">item type</a></dt><dd><p>An <b>item type</b> is a type that can be expressed using the <a href="#doc-xquery40-ItemType">ItemType</a> syntax, which forms part of the <a href="#doc-xquery40-SequenceType">SequenceType</a>
            syntax. Item types match individual <a title="item" class="termref" href="#dt-item">items</a>.</p></dd><dt><a href="#dt-item-type-designator">item type designator</a></dt><dd><p>An
         <b>item type designator</b> is a syntactic construct conforming to the grammar rule
         <a href="#doc-xquery40-ItemType">ItemType</a>. An item type designator is said
         to <b>designate</b> an <a title="item type" class="termref" href="#dt-item-type">item type</a>.</p></dd><dt><a href="#dt-JNode">JNode</a></dt><dd><p>A <b>JNode</b> is a kind of <a title="item" class="termref" href="#dt-item">item</a>
      used to represent a value within the context of a tree of <a title="map" class="termref" href="#dt-map">maps</a>
      and <a title="array" class="termref" href="#dt-array">arrays</a>. A root <b>JNode</b> represents
      a map or array; a non-root <b>JNode</b> represents a <a title="member" class="termref" href="#dt-member">member</a> of an 
      array or an <a title="entry" class="termref" href="#dt-entry">entry</a> in a map.</p></dd><dt><a href="#dt-JTree">JTree</a></dt><dd><p>A tree that is rooted at a parentless
    <a title="JNode" class="termref" href="#dt-JNode">JNode</a> is referred to as a <b>JTree</b>.</p></dd><dt><a href="#dt-kind-test">kind test</a></dt><dd><p>An alternative
		  form of a node test called a
		  <b>type test</b> can select XNodes based
		  on their type, or in the case of JNodes, the type of their
                  contained <b>·content·</b>
                     </p></dd><dt><a href="#dt-qname">lexical QName</a></dt><dd><p>A
          <b>lexical QName</b> is a name that conforms to the syntax of the
          <a href="#prod-xquery40-QName">QName</a> production</p></dd><dt><a href="#dt-library-module">library module</a></dt><dd><p>A module that does not contain a <a title="query body" class="termref" href="#dt-queryBody">Query Body</a> is called a <b>library module</b>. A library
      module consists of a <a title="module declaration" class="termref" href="#dt-module-declaration">module declaration</a>
      followed by a <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a>.</p></dd><dt><a href="#dt-literal">literal</a></dt><dd><p>A <b>literal</b> is a direct syntactic representation of an
		atomic item.</p></dd><dt><a href="#dt-literal-terminal">literal terminal</a></dt><dd><p>A <b>literal terminal</b> is a token appearing as a string 
        in quotation marks on the right-hand side of an <a title="ordinary production rule" class="termref" href="#dt-ordinary-production-rule">ordinary production rule</a>.</p></dd><dt><a href="#dt-logical-expression">logical expression</a></dt><dd><p>
            A <b>logical expression</b> is either an <a title="and expression" class="termref" href="#dt-and-expression">and expression</a>
            or an <a title="or expression" class="termref" href="#dt-or-expression">or expression</a>. If a logical expression does not raise an error, 
            its value is always one of the boolean values <code>true</code> or <code>false</code>.</p></dd><dt><a href="#dt-lookup-expression">lookup expression</a></dt><dd><p>
               A <b>lookup expression</b> is an instance of the production
                  <a href="#doc-xquery40-LookupExpr">LookupExpr</a>: that is, an expression in the form
                  <code>
                           <var>E<sub>1</sub></var>?<var>KS</var>
                        </code>, where <var>E<sub>1</sub></var> is an expression returning a sequence
            of maps or arrays, and <var>KS</var> is a key specifier, which indicates which
            entries in a map, or members in an array, should be selected.</p></dd><dt><a href="#dt-main-module">main module</a></dt><dd><p>A <b>main module</b> consists of a
        <a title="Prolog" class="termref" href="#dt-prolog">Prolog</a> followed by a <a title="query body" class="termref" href="#dt-queryBody">Query
        Body</a>.</p></dd><dt><a href="#dt-map">map</a></dt><dd><p>A <b>map</b> is a function
  that associates a set of keys with values, resulting in a collection
  of key / value pairs.</p></dd><dt><a href="#dt-mapping-arrow-operator">mapping arrow operator</a></dt><dd><p>
            The <b>mapping arrow operator</b>
                     <code>=!&gt;</code> applies a function to each
            item in a sequence.</p></dd><dt><a href="#may">may</a></dt><dd><p>
               <b>MAY</b> means that an item is truly
            optional.</p></dd><dt><a href="#dt-member">member</a></dt><dd><p>The values of an array are called
      its <b>members</b>.</p></dd><dt><a href="#id-static-decimal-format-minus-sign">minus-sign</a></dt><dd><p>
                              <b>minus-sign</b>
                              <em>(<var>R</var>)</em> is the string used to mark negative numbers; the
                                 default value is <span class="unicode-codepoint">U+002D</span> (<span class="unicode-name">HYPHEN-MINUS</span>, <code>-</code>) .</p></dd><dt><a href="#dt-module">module</a></dt><dd><p>A <b>module</b> is a fragment of XQuery code that conforms
      to the <a href="#doc-xquery40-Module">Module</a> grammar and can independently undergo the <a title="static analysis phase" class="termref" href="#dt-static-analysis">static analysis phase</a> described in <a href="#id-expression-processing"><b>2.3.3 Expression
Processing</b></a>. Each module is either a <a title="main module" class="termref" href="#dt-main-module">main
        module</a> or a <a title="library module" class="termref" href="#dt-library-module">library
    module</a>.</p></dd><dt><a href="#dt-module-declaration">module declaration</a></dt><dd><p>A <b>module
          declaration</b> serves to identify a <a title="module" class="termref" href="#dt-module">module</a> as a
          <a title="library module" class="termref" href="#dt-library-module">library module</a>. A module declaration begins
        with the keyword <code>module</code> and contains a namespace prefix and a <a href="#prod-xquery40-URILiteral">URILiteral</a>.</p></dd><dt><a href="#dt-module-import">module import</a></dt><dd><p>A <b>module import</b> imports the
        public variable declarations, public function declarations<span>, 
          and public item type declarations</span> from one or more <a title="library module" class="termref" href="#dt-library-module">library modules</a> into the <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a>, <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a>
                  <span>,
          or <a title="in-scope named item types" class="termref" href="#dt-in-scope-named-item-types">in-scope named item types</a>
                  </span> of the importing <a title="module" class="termref" href="#dt-module">module</a>.</p></dd><dt><a href="#must">must</a></dt><dd><p>
               <b>MUST</b> means that the item is an absolute
            requirement of the specification.</p></dd><dt><a href="#mustnot">must not</a></dt><dd><p>
               <b>MUST NOT</b> means that the item is an
            absolute prohibition of the specification.</p></dd><dt><a href="#dt-named-function-ref">named function reference</a></dt><dd><p>
          A <b>named function reference</b> is an instance of the production
                  <a href="#doc-xquery40-NamedFunctionRef">NamedFunctionRef</a>: 
                  it is an expression (written <code>name#arity</code>)
                  which evaluates to a <a title="function item" class="termref" href="#dt-function-item">function item</a>, the details
                  of the function item being based on the properties of a <a title="function definition" class="termref" href="#dt-function-definition">function definition</a>
                  in the <a title="static context" class="termref" href="#dt-static-context">static context</a>.</p></dd><dt><a href="#dt-named-item-type">named item type</a></dt><dd><p>A <b>named item type</b>
                      is an <code>ItemType</code> identified by an <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a>.</p></dd><dt><a href="#dt-name-expression">name expression</a></dt><dd><p>When
an expression is used to specify the name of a constructed node, that
expression is called the <b>name expression</b> of the
constructor.</p></dd><dt><a href="#dt-namespace-binding">namespace binding</a></dt><dd><p>A <b>namespace binding</b>
         is a pair comprising a namespace prefix (which is either an <code>xs:NCName</code> or empty),
         and a namespace URI.</p></dd><dt><a href="#dt-namespace-declaration">namespace declaration</a></dt><dd><p>A <b>namespace
          declaration</b> declares a namespace prefix and associates it with a namespace URI,
        adding the (prefix, URI) pair to the set of <a title="statically known namespaces" class="termref" href="#dt-static-namespaces">statically
          known namespaces</a>.</p></dd><dt><a href="#dt-namespace-decl-attr">namespace declaration attribute</a></dt><dd><p>A <b>namespace declaration
attribute</b> is used inside a direct element constructor. Its
purpose is to bind a namespace prefix <span>(including the zero-length prefix)</span> for
the constructed element node, including its attributes.</p></dd><dt><a href="#dt-namespace-sensitive">namespace-sensitive</a></dt><dd><p>The <b>namespace-sensitive</b>
                     types are <code>xs:QName</code>, <code>xs:NOTATION</code>, types
                     derived by restriction from <code>xs:QName</code> or
                     <code>xs:NOTATION</code>, list types that have a namespace-sensitive
                     item type, and union types with a namespace-sensitive type in their
                     transitive membership.</p></dd><dt><a href="#dt-name-test">name test</a></dt><dd><p>A node test that consists only of an EQName or a
		  Wildcard is called a <b>name test</b>.</p></dd><dt><a href="#id-static-decimal-format-NaN">NaN</a></dt><dd><p>
                              <b>NaN</b>
                              <em>(<var>R</var>)</em>
                                 is the string used to
                                 represent the double value <code>NaN</code> (not a number); the default value is the string <code>"NaN"</code>
                           </p></dd><dt><a href="#dt-node">node</a></dt><dd><p>Except where the context indicates otherwise, the term
         <b>node</b> is used as a synonym for <a title="XNode" class="termref" href="#dt-XNode">XNode</a>.</p></dd><dt><a href="#dt-node-test">node test</a></dt><dd><p>A <b>node test</b> is a condition 
                     on the properties of a <a title="GNode" class="termref" href="#dt-GNode">GNode</a>. 
      A node test determines which GNodes returned by an axis are selected by a <a title="step" class="termref" href="#dt-step">step</a>.</p></dd><dt><a href="#dt-no-namespace-rule">no-namespace rule</a></dt><dd><p>When an unprefixed lexical QName
               is expanded using the <b>no-namespace rule</b>, it is interpreted as having an absent namespace URI.</p></dd><dt><a href="#non-delimiting-token">non-delimiting terminal symbol</a></dt><dd><p>The
            <b>non-delimiting terminal symbols</b> are: <code>allowing</code>
                     <code>ancestor</code>
                     <code>ancestor-or-self</code>
                     <code>and</code>
                     <code>array</code>
                     <code>as</code>
                     <code>ascending</code>
                     <code>at</code>
                     <code>attribute</code>
                     <code>base-uri</code>
                     <code>boundary-space</code>
                     <code>by</code>
                     <code>case</code>
                     <code>cast</code>
                     <code>castable</code>
                     <code>catch</code>
                     <code>child</code>
                     <code>collation</code>
                     <code>comment</code>
                     <code>construction</code>
                     <code>context</code>
                     <code>copy-namespaces</code>
                     <code>count</code>
                     <code>decimal-format</code>
                     <code>decimal-separator</code>
                     <code>declare</code>
                     <code>default</code>
                     <code>descendant</code>
                     <code>descendant-or-self</code>
                     <code>descending</code>
                     <code>digit</code>
                     <code>div</code>
                     <code>document</code>
                     <code>document-node</code>
                     <code>element</code>
                     <code>else</code>
                     <code>empty</code>
                     <code>empty-sequence</code>
                     <code>encoding</code>
                     <code>end</code>
                     <code>enum</code>
                     <code>eq</code>
                     <code>every</code>
                     <code>except</code>
                     <code>exponent-separator</code>
                     <code>external</code>
                     <code>false</code>
                     <code>finally</code>
                     <code>fixed</code>
                     <code>fn</code>
                     <code>following</code>
                     <code>following-or-self</code>
                     <code>following-sibling</code>
                     <code>following-sibling-or-self</code>
                     <code>follows</code>
                     <code>follows-or-is</code>
                     <code>for</code>
                     <code>function</code>
                     <code>ge</code>
                     <code>get</code>
                     <code>gnode</code>
                     <code>greatest</code>
                     <code>group</code>
                     <code>grouping-separator</code>
                     <code>gt</code>
                     <code>idiv</code>
                     <code>if</code>
                     <code>import</code>
                     <code>in</code>
                     <code>infinity</code>
                     <code>inherit</code>
                     <code>instance</code>
                     <code>intersect</code>
                     <code>is</code>
                     <code>is-not</code>
                     <code>item</code>
                     <code>jnode</code>
                     <code>key</code>
                     <code>lax</code>
                     <code>le</code>
                     <code>least</code>
                     <code>let</code>
                     <code>lt</code>
                     <code>map</code>
                     <code>member</code>
                     <code>minus-sign</code>
                     <code>mod</code>
                     <code>module</code>
                     <code>namespace</code>
                     <code>namespace-node</code>
                     <code>NaN</code>
                     <code>ne</code>
                     <code>next</code>
                     <code>no-inherit</code>
                     <code>no-preserve</code>
                     <code>node</code>
                     <code>of</code>
                     <code>only</code>
                     <code>option</code>
                     <code>or</code>
                     <code>order</code>
                     <code>ordered</code>
                     <code>ordering</code>
                     <code>otherwise</code>
                     <code>parent</code>
                     <code>pattern-separator</code>
                     <code>per-mille</code>
                     <code>percent</code>
                     <code>precedes</code>
                     <code>precedes-or-is</code>
                     <code>preceding</code>
                     <code>preceding-or-self</code>
                     <code>preceding-sibling</code>
                     <code>preceding-sibling-or-self</code>
                     <code>preserve</code>
                     <code>previous</code>
                     <code>processing-instruction</code>
                     <code>record</code>
                     <code>return</code>
                     <code>satisfies</code>
                     <code>schema</code>
                     <code>schema-attribute</code>
                     <code>schema-element</code>
                     <code>self</code>
                     <code>sliding</code>
                     <code>some</code>
                     <code>stable</code>
                     <code>start</code>
                     <code>strict</code>
                     <code>strip</code>
                     <code>switch</code>
                     <code>text</code>
                     <code>then</code>
                     <code>to</code>
                     <code>treat</code>
                     <code>true</code>
                     <code>try</code>
                     <code>tumbling</code>
                     <code>type</code>
                     <code>typeswitch</code>
                     <code>union</code>
                     <code>unordered</code>
                     <code>validate</code>
                     <code>value</code>
                     <code>variable</code>
                     <code>version</code>
                     <code>when</code>
                     <code>where</code>
                     <code>while</code>
                     <code>window</code>
                     <code>xquery</code>
                     <code>zero-digit</code>
                     <a href="#prod-xquery40-BinaryIntegerLiteral">BinaryIntegerLiteral</a>
                     <a href="#prod-xquery40-DecimalLiteral">DecimalLiteral</a>
                     <a href="#prod-xquery40-DoubleLiteral">DoubleLiteral</a>
                     <a href="#prod-xquery40-HexIntegerLiteral">HexIntegerLiteral</a>
                     <a href="#prod-xquery40-IntegerLiteral">IntegerLiteral</a>
                     <a href="#prod-xquery40-NCName">NCName</a>
                     <a href="#prod-xquery40-QName">QName</a>
                  </p></dd><dt><a href="#dt-non-trivial">non-trivial</a></dt><dd><p>A construct is said to be a
            <b>non-trivial</b> instance of a grammatical production if it is not also
            an instance of one of its sub-productions.</p></dd><dt><a href="#dt-numeric">numeric</a></dt><dd><p>The type <code>xs:numeric</code>
               is defined as a union type with member types <code>xs:double</code>, 
               <code>xs:float</code>, and <code>xs:decimal</code>. An item that
               is an instance of any of these types is referred to as a <b>numeric value</b>,
               and a type that is a subtype of <code>xs:numeric</code> is referred to
               as a <b>numeric type</b>.</p></dd><dt><a href="#dt-numeric-predicate">numeric predicate</a></dt><dd><p>A predicate whose predicate
                     expression returns a value of type <code>xs:numeric+</code> is called a <b>numeric
                        predicate</b>.</p></dd><dt><a href="#dt-option-declaration">option declaration</a></dt><dd><p>An <b>option
          declaration</b> declares an option that affects the behavior of a particular
        implementation. Each option consists of an identifying EQName and a StringLiteral.</p></dd><dt><a href="#dt-ordinary-production-rule">ordinary production rule</a></dt><dd><p>An <b>ordinary production rule</b> 
        is a production rule in <a href="#id-grammar"><b>A.1 EBNF</b></a> that is not annotated <code>ws:explicit</code>.</p></dd><dt><a href="#dt-or-expression">or expression</a></dt><dd><p>An <b>or expression</b>
         is a <a title="non-trivial" class="termref" href="#dt-non-trivial">non-trivial</a> instance of the production <a href="#doc-xquery40-OrExpr">OrExpr</a>.</p></dd><dt><a href="#dt-output-declaration">output declaration</a></dt><dd><p>An <b>output declaration</b>
is an option declaration in the namespace <code>http://www.w3.org/2010/xslt-xquery-serialization</code>;
it is used to declare serialization parameters.</p></dd><dt><a href="#dt-partial-function-application">partial function application</a></dt><dd><p>
                     A <a title="static function call" class="termref" href="#dt-static-function-call">static</a> or 
                     <a title="dynamic function call" class="termref" href="#dt-dynamic-function-call">dynamic</a>
                     function call is a <b>partial function application</b>
                     if one or more arguments is an <a href="#prod-xquery40-ArgumentPlaceholder">ArgumentPlaceholder</a>.</p></dd><dt><a href="#dt-partially-applied-function">partially applied function</a></dt><dd><p>A <b>partially applied function</b>
                  is a function created by  <a title="partial function application" class="termref" href="#dt-partial-function-application">partial function application</a>.</p></dd><dt><a href="#dt-path-expression">path expression</a></dt><dd><p>A <b>path expression</b>
            is either an <a title="absolute path expression" class="termref" href="#dt-absolute-path-expression">absolute path expression</a> or a
            <a title="relative path expression" class="termref" href="#dt-relative-path-expression">relative path expression</a>
               </p></dd><dt><a href="#id-static-decimal-format-pattern-separator">pattern-separator</a></dt><dd><p>
                              <b>pattern-separator</b>
                              <em>(<var>M</var>)</em> is a character used
                                 to separate positive and negative sub-pictures
                                 in a picture string; the default value is <span class="unicode-codepoint">U+003B</span> (<span class="unicode-name">SEMICOLON</span>, <code>;</code>) .</p></dd><dt><a href="#id-static-decimal-format-percent">percent</a></dt><dd><p>
                              <b>percent</b>
                              <em>(<var>M</var>, <var>R</var>)</em> 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 <span class="unicode-codepoint">U+0025</span> (<span class="unicode-name">PERCENT SIGN</span>, <code>%</code>) .</p></dd><dt><a href="#id-static-decimal-format-per-mille">per-mille</a></dt><dd><p>
                              <b>per-mille</b>
                              <em>(<var>M</var>, <var>R</var>)</em> 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 <span class="unicode-codepoint">U+2030</span> (<span class="unicode-name">PER MILLE SIGN</span>, <code>‰</code>) .</p></dd><dt><a href="#dt-pipeline-operator">pipeline operator</a></dt><dd><p>
            The <b>pipeline operator</b>
                  <code>-&gt;</code> evaluates an expression and
            binds the result to the context value before evaluating another expression.</p></dd><dt><a href="#dt-positional-variable">positional variable</a></dt><dd><p>A <b>positional variable</b> 
                  is a variable that is preceded by the keyword <code>at</code>.</p></dd><dt><a href="#dt-pragma">pragma</a></dt><dd><p>A <b>pragma</b> is denoted by the delimiters <code>(#</code> and <code>#)</code>, 
               and consists of an identifying EQName followed by <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a> content.</p></dd><dt><a href="#dt-predefined-entity-reference">predefined entity reference</a></dt><dd><p>A <b>predefined entity reference</b> is a short sequence of characters, 
                  beginning with an ampersand, that represents a single character that might otherwise 
                  have syntactic significance.</p></dd><dt><a href="#dt-predicate-truth-value">predicate truth value</a></dt><dd><p>The
            <b>predicate truth value</b> of a value <code>$V</code>
            is the result of the expression <code>if ($V instance of xs:numeric+)
            then ($V = position()) else fn:boolean($V)</code>.</p></dd><dt><a href="#dt-primary-expression">primary expression</a></dt><dd><p>
               A <b>primary expression</b> is an instance of the production
               <a href="#doc-xquery40-PrimaryExpr">PrimaryExpr</a>. Primary expressions are the basic primitives of the
	 language. They include literals, variable references, context value references, <span class="xquery">constructors, </span> 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.</p></dd><dt><a href="#dt-principal-node-kind">principal node kind</a></dt><dd><p>Every axis has a <b>principal node kind</b>. 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.</p></dd><dt><a href="#dt-private-function">private function</a></dt><dd><p>A <b>private
          function</b> is a function with a <code>%private</code> annotation. A private function
        is hidden from <a title="module import" class="termref" href="#dt-module-import">module import</a>, which can not import
        it into the <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a> of another module. </p></dd><dt><a href="#dt-private-item-type">private item type</a></dt><dd><p>A <b>private
        item type</b> is a named item type with a <code>%private</code> annotation. A private item type
        is hidden from <a title="module import" class="termref" href="#dt-module-import">module import</a>, which can not import
        it into the <a title="in-scope named item types" class="termref" href="#dt-in-scope-named-item-types">in-scope named item types</a> of another module. </p></dd><dt><a href="#dt-private-variable">private   variable</a></dt><dd><p>A
          <b>private variable</b> is a variable with a <code>%private</code> annotation. A
        private variable is hidden from <a title="module import" class="termref" href="#dt-module-import">module import</a>,
        which can not import it into the <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope
          variables</a> of another module.</p></dd><dt><a href="#dt-prolog">Prolog</a></dt><dd><p>A <b>Prolog</b> is a series of declarations and
      imports that define the processing environment for the <a title="module" class="termref" href="#dt-module">module</a> that contains the Prolog.</p></dd><dt><a href="#dt-public-function">public function</a></dt><dd><p>A <b>public function</b> is a
        function without a <code>%private</code> annotation. A public function is accessible to
          <a title="module import" class="termref" href="#dt-module-import">module import</a>, which can import it into the
        <a title="statically known function definitions" class="termref" href="#dt-statically-known-function-definitions">statically known function definitions</a> of
        another module. </p></dd><dt><a href="#dt-public-item-type">public item type</a></dt><dd><p>A <b>public item type</b> is an
         item type declaration without a <code>%private</code> annotation. A public item type is accessible to
        <a title="module import" class="termref" href="#dt-module-import">module import</a>, which can import it into the
        <a title="in-scope named item types" class="termref" href="#dt-in-scope-named-item-types">in-scope named item types</a> of
        another module. </p></dd><dt><a href="#dt-public-variable">public variable</a></dt><dd><p>A <b>public variable</b> is a
        variable without a <code>%private</code> annotation. A public variable is accessible to
          <a title="module import" class="termref" href="#dt-module-import">module import</a>, which can import it into the
          <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a> of another module. Using
          <code>%public</code> and <code>%private</code> 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 <a title="static error" class="termref" href="#dt-static-error">static error</a>
                  [<a href="#ERRXQST0116" title="err:XQST0116">err:XQST0116</a>] if a variable declaration contains both a
          <code>%private</code> and a <code>%public</code> annotation, more than one
          <code>%private</code> annotation, or more than one <code>%public</code>
        annotation.</p></dd><dt><a href="#dt-pure-union-type">pure union type</a></dt><dd><p>A <b>pure union type</b> is a <span>
                        <b>simple type</b>
                     </span> 
                     that satisfies the following constraints:
                     (a) <a href="https://www.w3.org/TR/xmlschema11-1/#std-variety">{variety}<sup><small>XS11-1</small></sup></a> is <code>union</code>, 
                     (b) the <a href="https://www.w3.org/TR/xmlschema11-1/#std-facets">{facets}<sup><small>XS11-1</small></sup></a> property is empty, 
                     (c) no type in the transitive membership of the union type has 
                     <a href="https://www.w3.org/TR/xmlschema11-1/#std-variety">{variety}<sup><small>XS11-1</small></sup></a>
                     <code>list</code>, and 
                     (d) no type in the transitive membership of the union type is a type with 
                     <a href="https://www.w3.org/TR/xmlschema11-1/#std-variety">{variety}<sup><small>XS11-1</small></sup></a>
                     <code>union</code> having a non-empty <a href="https://www.w3.org/TR/xmlschema11-1/#std-facets">{facets}<sup><small>XS11-1</small></sup></a> property</p></dd><dt><a href="#dt-query">query</a></dt><dd><p>A <b>query</b> consists of one or more <a title="module" class="termref" href="#dt-module">modules</a>.</p></dd><dt><a href="#dt-queryBody">query body</a></dt><dd><p>The <b>Query Body</b>, if present, consists
      of an expression that defines the result of the query.</p></dd><dt><a href="#dt-range-expression">range expression</a></dt><dd><p>A 
               <b>range expression</b> is a <a title="non-trivial" class="termref" href="#dt-non-trivial">non-trivial</a>
               instance of the production <a href="#doc-xquery40-RangeExpr">RangeExpr</a>. A range expression
               is used to construct a sequence of 
integers.</p></dd><dt><a href="#dt-relative-path-expression">relative path expression</a></dt><dd><p>
            A <b>relative path expression</b> is a <a title="non-trivial" class="termref" href="#dt-non-trivial">non-trivial</a>
            instance of the production <a href="#doc-xquery40-RelativePathExpr">RelativePathExpr</a>:
            it consists of two or more operand expressions 
            separated by <code>/</code> or <code>//</code> operators.</p></dd><dt><a href="#dt-reserved-namespaces">reserved namespaces</a></dt><dd><p>A <b>reserved namespace</b> is a namespace
        that must not be used in the name of a function declaration.</p></dd><dt><a href="#dt-resolve-relative-uri">resolve</a></dt><dd><p>To
      <b>resolve a relative URI</b>
                     <code>$rel</code> against a
      base URI <code>$base</code> is to expand it to an absolute URI,
      as if by calling the function <code>fn:resolve-uri($rel,
      $base)</code>.</p></dd><dt><a href="#dt-reverse-document-order">reverse document order</a></dt><dd><p>The node ordering that is the reverse of document order is called <b>reverse document order</b>.</p></dd><dt><a href="#dt-same-key">same key</a></dt><dd><p>Two atomic items <var>K<sub>1</sub></var> and
    <var>K<sub>2</sub></var> have the <b>same key value</b> if
    
    
      <code>fn:atomic-equal(<var>K<sub>1</sub></var>, <var>K<sub>2</sub></var>)</code> returns <code>true</code>, as specified in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a> section <a href="../xpath-functions-40/#func-atomic-equal">2.2.1 fn:atomic-equal</a>
                     </p></dd><dt><a href="#dt-schema-aware-feature">schema aware feature</a></dt><dd><p>The <b>Schema Aware Feature</b> permits the query Prolog to contain a
                        <a title="schema import" class="termref" href="#dt-schema-import">schema import</a>, and permits a query
                    to contain a <code>validate</code> expression (see <a href="#id-validate"><b>4.25 Validate Expressions</b></a>). </p></dd><dt><a href="#dt-schema-import">schema import</a></dt><dd><p>A <b>schema import</b> imports the
        element declarations, attribute declarations, and type definitions from a schema into the
          <a title="in-scope schema definitions" class="termref" href="#dt-issd">in-scope schema definitions</a>. For each named user-defined
        simple type in the schema, schema import also adds a corresponding <a title="constructor function" class="termref" href="#dt-constructor-function">constructor function</a>. </p></dd><dt><a href="#dt-schema-type">schema type</a></dt><dd><p>A <b>schema type</b>
            is a complex type or simple type as defined in the <a href="#XMLSchema10">[XML Schema 1.0]</a> or <a href="#XMLSchema11">[XML Schema 1.1]</a> specifications, including built-in types as well as user-defined types.</p></dd><dt><a href="#dt-sequence">sequence</a></dt><dd><p>A
<b>sequence</b> is an ordered collection of zero or more
<a title="item" class="termref" href="#dt-item">items</a>.</p></dd><dt><a href="#dt-sequence-arrow-operator">sequence arrow operator</a></dt><dd><p>
               The <b>sequence arrow operator</b>
                     <code>=&gt;</code> applies a function to a
               supplied sequence.</p></dd><dt><a href="#dt-sequence-concatenation">sequence concatenation</a></dt><dd><p>The 
               <b>sequence concatenation</b> of a number of sequences <var>S<sub>1</sub></var>, <var>S<sub>2</sub></var>, ... <var>S<sub>n</sub></var>
               is defined to be the sequence formed from the items of <var>S<sub>1</sub></var>, followed by the items
               from <var>S<sub>2</sub></var>, and so on, retaining order.</p></dd><dt><a href="#dt-sequence-expression">sequence expression</a></dt><dd><p>A
            <b>sequence expression</b> is a <a title="non-trivial" class="termref" href="#dt-non-trivial">non-trivial</a> instance
            of the production rule <a href="#doc-xquery40-Expr">Expr</a>, that is, an expression
            containing two or more instances of the production <a href="#doc-xquery40-ExprSingle">ExprSingle</a>
            separated by the comma operator.</p></dd><dt><a href="#dt-sequence-type">sequence type</a></dt><dd><p>A <b>sequence type</b> is a type that can be expressed using the <a href="#doc-xquery40-SequenceType">SequenceType</a>
                  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 <b>sequence types</b>.</p></dd><dt><a href="#dt-sequence-type-designator">sequence type designator</a></dt><dd><p>A
      <b>sequence type designator</b> is a syntactic construct conforming to the grammar rule
         <a href="#doc-xquery40-SequenceType">SequenceType</a>. A sequence type designator is said
      to <b>designate</b> a <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>.</p></dd><dt><a href="#dt-sequencetype-matching">SequenceType matching</a></dt><dd><p>
                     <b>SequenceType matching</b> compares a value with an expected <a title="sequence type" class="termref" href="#dt-sequence-type">sequence type</a>. </p></dd><dt><a href="#dt-serialization">serialization</a></dt><dd><p>
                     <b>Serialization</b> is the process of
converting an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM
instance</a> to a sequence of octets (step DM4 in Figure 1.),
as described in <a href="#xslt-xquery-serialization-40">[Serialization 4.0]</a>.</p></dd><dt><a href="#dt-serialization-feature">serialization feature</a></dt><dd><p>The
                        <b>Serialization Feature</b> provides means for serializing the result
                    of a query as specified in <a href="#id-serialization"><b>2.3.5 Serialization</b></a>.</p></dd><dt><a href="#dt-setter">setter</a></dt><dd><p>
               <b>Setters</b> are
      declarations that set the value of some property that affects query processing, such as
      construction mode or default collation.</p></dd><dt><a href="#should">should</a></dt><dd><p>
               <b>SHOULD</b> 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.</p></dd><dt><a href="#dt-singleton">singleton</a></dt><dd><p>A sequence containing exactly one item is called a
	 <b>singleton</b>.</p></dd><dt><a href="#dt-singleton-enumeration-type">singleton enumeration type</a></dt><dd><p>An 
                     enumeration type with a single enumerated value <var>E</var> (such as
                     <code>enum("red")</code>) matches an item <var>S</var> if and only if (a) <var>S</var>
                     is an instance of <code>xs:string</code>, and (b) <var>S</var> is equal
                     to <var>E</var> when compared using Unicode codepoint collation. This is referred to
                     as a <b>singleton enumeration type</b>.</p></dd><dt><a href="#dt-singleton-focus">singleton focus</a></dt><dd><p>A <b>singleton focus</b> is a <a title="fixed focus" class="termref" href="#dt-fixed-focus">fixed focus</a> in which the
                  <a title="context value" class="termref" href="#dt-context-value">context value</a> is a <a title="singleton" class="termref" href="#dt-singleton">singleton</a> item.</p></dd><dt><a href="#stable">stable</a></dt><dd><p>Document order is <b>stable</b>, which means that the relative order of two nodes will not change during the processing of a given <span class="xquery">query</span>
                  , even if this order is <a title="implementation   dependent" class="termref" href="#dt-implementation-dependent">implementation-dependent</a>.</p></dd><dt><a href="#dt-static-collations">statically known collations</a></dt><dd><p>
                           <b>Statically known collations.</b> This is an <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>
        mapping from URI to collation. It defines the names of the collations that are available for
				use in processing <span class="xquery">queries and</span> expressions.</p></dd><dt><a href="#dt-static-decimal-formats">statically known decimal formats</a></dt><dd><p>
                           <b>Statically known decimal
		      formats.</b> 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 <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-format-number"><code>fn:format-number</code></a> function.</p></dd><dt><a href="#dt-statically-known-function-definitions">statically known function definitions</a></dt><dd><p>
                           <b>Statically known function definitions.</b> This is a set of 
                           <a title="function definition" class="termref" href="#dt-function-definition">function definitions</a>.</p></dd><dt><a href="#dt-static-namespaces">statically known namespaces</a></dt><dd><p>
                           <b>Statically known namespaces.</b> 
        This is a mapping from prefix to namespace URI that defines all the namespaces 
        that are known during static processing of a given expression.</p></dd><dt><a href="#dt-static-analysis">static analysis phase</a></dt><dd><p>The
<b>static analysis phase</b> depends on the expression itself
and on the <a title="static context" class="termref" href="#dt-static-context">static context</a>. The <b>static analysis phase</b> does
not depend on input data (other than schemas).</p></dd><dt><a href="#dt-static-base-uri">Static Base URI</a></dt><dd><p>
                           <b>Static Base URI.</b>
        This is an absolute URI, used to resolve relative URIs during static analysis.
                     </p></dd><dt><a href="#dt-static-context">static context</a></dt><dd><p>The <b>static context</b> of an expression is
		  the information that is available during static analysis of the expression, prior
		  to its evaluation.</p></dd><dt><a href="#dt-static-error">static error</a></dt><dd><p>
An error that can be detected during the static analysis phase, and is not a type error, is a <b>static error</b>.</p></dd><dt><a href="#dt-static-function-call">static function call</a></dt><dd><p>A <b>static function call</b>
               is an instance of the production <a href="#doc-xquery40-FunctionCall">FunctionCall</a>: it
               consists of an EQName followed by a parenthesized list of zero or more arguments.</p></dd><dt><a href="#dt-static-type">static type</a></dt><dd><p>The
<b>static type</b> of an expression is the best inference that
the processor is able to make statically about the type of the result
of the expression.</p></dd><dt><a href="#dt-step">step</a></dt><dd><p>The operands of a path expression
            are conventionally referred to as <b>steps</b>.</p></dd><dt><a href="#dt-string-constructor">string constructor</a></dt><dd><p>A
                  <b>string constructor</b> is an instance of the production
                  <a href="#doc-xquery40-StringConstructor">StringConstructor</a>: it
                  is an expression that creates a string from literal text and interpolated subexpressions.
               </p></dd><dt><a href="#dt-string-value">string value</a></dt><dd><p>The
                  <b>string value</b> of a node is a string and can be extracted
                  by applying the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-string"><code>string</code></a>
                  function to the node.</p></dd><dt><a href="#dt-substantively-disjoint">substantively disjoint</a></dt><dd><p>Two 
               <a title="sequence type" class="termref" href="#dt-sequence-type">sequence types</a> are
                     deemed to be <b>substantively disjoint</b> if (a) neither is a subtype
                     of the other (see <a href="#id-seqtype-subtype"><b>3.3.1 Subtypes of Sequence Types</b></a>) and 
                     (b) the only values that
                     are instances of both types are one or more of the following:</p><ul><li><p>The empty sequence, <code>()</code>.</p></li><li><p>The <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-empty-map">empty map</a><sup><small>DM</small></sup>, <code>{}</code>.</p></li><li><p>The <a href="https://qt4cg.org/specifications/xpath-datamodel-40/#dt-empty-array">empty array</a><sup><small>DM</small></sup>, <code>[]</code>.</p></li></ul></dd><dt><a href="#dt-substitution-group">substitution group</a></dt><dd><p>
                                 <b>Substitution groups</b> are defined in <a href="https://www.w3.org/TR/xmlschema-1/#Element_Equivalence_Class">
                  
                     2.2.2.2 Element Substitution Group
               </a><sup><small>XS1-1</small></sup> and 
<a href="https://www.w3.org/TR/xmlschema11-1/#Element_Equivalence_Class">
                  
                     2.2.2.2 Element Substitution Group
               </a><sup><small>XS11-1</small></sup>. Informally, the substitution group headed by a given element (called the <b>head element</b>) consists of  the set of elements that can be substituted for the head element without affecting the outcome of schema validation.</p></dd><dt><a href="#dt-subtype">subtype</a></dt><dd><p>Given two 
               <a title="sequence type" class="termref" href="#dt-sequence-type">sequence types</a>
               or <a title="item type" class="termref" href="#dt-item-type">item types</a>, the rules in this section determine if one 
               is a <b>subtype</b> of the other. If a type <var>A</var> is a subtype of type <var>B</var>,
               it follows that every value matched by <var>A</var> is also matched by <var>B</var>.</p></dd><dt><a href="#dt-subtype-substitution">subtype substitution</a></dt><dd><p>The use of a value that has a <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a>
                      that is a <a title="subtype" class="termref" href="#dt-subtype">subtype</a> of the
		  expected type is known as <b>subtype substitution</b>.</p></dd><dt><a href="#symbol">symbol</a></dt><dd><p>Each rule in the grammar defines one <b>symbol</b>,
          using the following format: </p><div class="exampleInner"><pre>symbol ::= expression</pre></div></dd><dt><a href="#symbolseparators">symbol separators</a></dt><dd><p>
                     <a title="whitespace" class="termref" href="#Whitespace">Whitespace</a> and <a href="#doc-xquery40-Comment">Comments</a>
          function as <b>symbol separators</b>. 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 <a href="#ws-explicit">/* ws: explicit */</a>
          annotation in the EBNF, or by the <a href="#parse-note-xml-version">/* xgc: xml-version
            */</a> annotation.</p></dd><dt><a href="#dt-system-function">system function</a></dt><dd><p>
                                    <b>System functions</b> include the functions defined in <a href="#xpath-functions-40">[Functions and Operators 4.0]</a>, functions defined by the specifications 
                           of a host language, <a title="constructor function" class="termref" href="#dt-constructor-function">constructor functions</a> 
                           for atomic types, and any additional functions provided
                           by the implementation. System functions are sometimes called built-in
                           functions.</p></dd><dt><a href="#dt-target-namespace">target namespace</a></dt><dd><p> The <b>target
        namespace</b> of a module is the namespace of the objects (such as elements or functions)
      that it defines. </p></dd><dt><a href="#terminal">terminal</a></dt><dd><p>A <b>terminal</b> 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.</p></dd><dt><a href="#id-tuple-foobar">tuple</a></dt><dd><p>A <b>tuple</b> is a set of zero or more named variables, each of which is bound to a value that is an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a>.</p></dd><dt><a href="#id-tuple-stream-foobar">tuple stream</a></dt><dd><p>A <b>tuple stream</b> is an ordered sequence of zero or more <b>tuples</b>.</p></dd><dt><a href="#dt-type-annotation">type annotation</a></dt><dd><p>Each element node and attribute node in an <a title="XDM instance" class="termref" href="#dt-data-model-instance">XDM instance</a> has a <b>type annotation</b> (described in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#types">4.1 Schema Information</a>). 
The type annotation of a node is a reference to a <a title="schema type" class="termref" href="#dt-schema-type">schema type</a>. 
</p></dd><dt><a href="#dt-typed-data-feature">typed data feature</a></dt><dd><p>The
                        <b>Typed Data Feature</b> permits an XDM instance to contain element
                    node types other than <code>xs:untyped</code> and attributes node types other
                    than <code>xs:untypedAtomic</code>.</p></dd><dt><a href="#dt-type-declaration">type declaration</a></dt><dd><p>A variable binding may be accompanied by a <b>type declaration</b>, which consists of the 
                        keyword <code>as</code> followed by the static type of the variable, declared using the syntax in  <a href="#id-sequencetype-syntax"><b>3.1 Sequence Types</b></a>.</p></dd><dt><a href="#dt-typed-value">typed value</a></dt><dd><p>The <b>typed
                     value</b> of a node is a sequence of atomic items and can be
                  extracted by applying the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-data"><code>data</code></a> function to the
                  node.</p></dd><dt><a href="#dt-type-error">type error</a></dt><dd><p>A <b>type
error</b> may be raised during the static analysis phase or the dynamic evaluation phase.
During the static analysis phase, a <a title="type error" class="termref" href="#dt-type-error">type error</a> occurs
when the <a title="static type" class="termref" href="#dt-static-type">static type</a> of an expression does not match the expected type
of the context in which the expression occurs.
During the dynamic evaluation phase, a <a title="type error" class="termref" href="#dt-type-error">type error</a> occurs
when the <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a> of a value does not match the expected type of
the context in which the value occurs.</p></dd><dt><a href="#dt-URI">URI</a></dt><dd><p>Within this specification, the term <b>URI</b> refers to a Universal Resource Identifier as defined in <a href="#RFC3986">[RFC3986]</a> and extended in <a href="#RFC3987">[RFC3987]</a> with the new name <b>IRI</b>.</p></dd><dt><a href="#dt-udf">user-defined function</a></dt><dd><p>
                     <b>User defined functions</b> are functions that contain a <b>function body</b>,
          which provides the implementation of the function as a <a title="content expression" class="termref" href="#dt-content-expression">content expression</a>.</p></dd><dt><a href="#dt-value">value</a></dt><dd><p>In the <a title="data model" class="termref" href="#dt-datamodel">data model</a>, a <b>value</b> is always a <a title="sequence" class="termref" href="#dt-sequence">sequence</a>.</p></dd><dt><a href="#dt-variable-declaration">variable declaration</a></dt><dd><p>A <b>variable declaration</b> 
      in the XQuery prolog defines the name and <a title="static type" class="termref" href="#dt-static-type">static
        type</a> of a variable, and optionally a value for the variable. It adds to the 
        <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope
        variables</a> in the <a title="static context" class="termref" href="#dt-static-context">static context</a>, and may also add to the <a title="variable values" class="termref" href="#dt-variable-values">variable values</a> in the <a title="dynamic context" class="termref" href="#dt-dynamic-context">dynamic context</a>.</p></dd><dt><a href="#dt-variable-reference">variable reference</a></dt><dd><p>A <b>variable reference</b> is an EQName preceded by a $-sign.</p></dd><dt><a href="#dt-variable-terminal">variable terminal</a></dt><dd><p>A <b>variable terminal</b> is an instance
        of a production rule that is not itself an <a title="ordinary production rule" class="termref" href="#dt-ordinary-production-rule">ordinary production rule</a> but that is named (directly) on the right-hand
        side of an <a title="ordinary production rule" class="termref" href="#dt-ordinary-production-rule">ordinary production rule</a>.</p></dd><dt><a href="#dt-variable-values">variable values</a></dt><dd><p>
                           <b>Variable values</b>. 
        This is a mapping from <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a> to values. 
        It contains the
				same <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QNames</a> as the <a title="in-scope variables" class="termref" href="#dt-in-scope-variables">in-scope variables</a> in the
				<a title="static context" class="termref" href="#dt-static-context">static context</a> for the expression. The <a title="expanded QName" class="termref" href="#dt-expanded-qname">expanded QName</a> is the name of the variable and the value is the dynamic value of the variable, which includes its <a title="dynamic type" class="termref" href="#dt-dynamic-type">dynamic type</a>.</p></dd><dt><a href="#dt-version-declaration">version declaration</a></dt><dd><p>
      A <b>version declaration</b> can identify the applicable
      XQuery syntax and semantics for a <a title="module" class="termref" href="#dt-module">module</a>, as well as its
      encoding.</p></dd><dt><a href="#dt-warning">warning</a></dt><dd><p>In addition to <a title="static error" class="termref" href="#dt-static-error">static errors</a>, <a title="dynamic error" class="termref" href="#dt-dynamic-error">dynamic errors</a>, and <a title="type error" class="termref" href="#dt-type-error">type
errors</a>, an XQuery 4.0
implementation may raise <b>warnings</b>, either during the <a title="static analysis phase" class="termref" href="#dt-static-analysis">static analysis
phase</a> or the
<a title="dynamic evaluation phase" class="termref" href="#dt-dynamic-evaluation">dynamic evaluation
phase</a>. The circumstances in which warnings are raised, and
the ways in which warnings are handled, are <a title="implementation defined" class="termref" href="#dt-implementation-defined">implementation-defined</a>.</p></dd><dt><a href="#Whitespace">whitespace</a></dt><dd><p>A <b>whitespace</b> character is any of
            the characters defined by <a href="http://www.w3.org/TR/REC-xml/#NT-S">
              [http://www.w3.org/TR/REC-xml/#NT-S]</a>.</p></dd><dt><a href="#dt-wildcard-matches">wildcard-matches</a></dt><dd><p>In these rules, if <var>MU</var> and <var>NU</var> 
                     are <a href="#prod-xquery40-NameTestUnion">NameTestUnions</a>, 
                     then <var>MU</var>
                           <b>wildcard-matches</b>
                           <var>NU</var> is true if every name that matches <var>MU</var>
                     also matches <var>NU</var>.</p></dd><dt><a href="#dt-window">window</a></dt><dd><p>A <b>window</b> is a sequence of
consecutive items drawn from the <a title="binding sequence" class="termref" href="#dt-binding-sequence">binding sequence</a>.</p></dd><dt><a href="#dt-data-model-instance">XDM instance</a></dt><dd><p>The term <b>XDM instance</b> is used,
    synonymously with the term <a title="value" class="termref" href="#dt-value">value</a>, to denote an unconstrained
    <a title="sequence" class="termref" href="#dt-sequence">sequence</a> of <a title="item" class="termref" href="#dt-item">items</a>.</p></dd><dt><a href="#dt-XNode">XNode</a></dt><dd><p>An <b>XNode</b> is an instance of one of the
	  <b>node kinds</b> defined in <a href="#xpath-datamodel-40">[XDM 4.0]</a> section <a href="../xpath-datamodel-40/#nodes">7.1 XML Nodes</a>.</p></dd><dt><a href="#dt-xpath-compat-mode">XPath 1.0 compatibility     mode</a></dt><dd><p>
                           <b>XPath 1.0 compatibility
			 mode.</b>
                           <span class="xquery">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
			 <code>false</code>.
                         </span>
                        </p></dd><dt><a href="#dt-xquery-10-processor">XQuery 1.0 Processor</a></dt><dd><p> An <b>XQuery 1.0
				Processor</b> processes a query according to the XQuery 1.0 specification.
		</p></dd><dt><a href="#dt-xquery-30-processor">XQuery 3.0 Processor</a></dt><dd><p> An <b>XQuery 3.0
				Processor</b> processes a query according to the XQuery 3.0 specification. </p></dd><dt><a href="#dt-xquery-31-processor">XQuery 3.1 Processor</a></dt><dd><p> An <b>XQuery 3.1
				Processor</b> processes a query according to the XQuery 3.1 specification. </p></dd><dt><a href="#dt-xquery-40-processor">XQuery 4.0 Processor</a></dt><dd><p> An <b>XQuery 4.0
			Processor</b> processes a query according to the XQuery 4.0 specification. </p></dd><dt><a href="#dt-version-number">XQuery version number</a></dt><dd><p>An <b>XQuery version number</b> 
        consists of two integers, referred to as the 
        <b>major version number</b> and the  <b>minor version number</b>.</p></dd><dt><a href="#dt-anyAtomicType">xs:anyAtomicType</a></dt><dd><p>
                        <code>xs:anyAtomicType</code> is an <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a> 
                     that includes all atomic items (and no values that
                     are not atomic). Its base type is
                     <code>xs:anySimpleType</code> from which all simple types, including atomic,
                     list, and union types, are derived. All primitive atomic types, such as
                     <code>xs:decimal</code> and <code>xs:string</code>, have <code>xs:anyAtomicType</code> as their base type.</p></dd><dt><a href="#dt-dayTimeDuration">xs:dayTimeDuration</a></dt><dd><p>
                        <code>xs:dayTimeDuration</code> is derived by restriction from <code>xs:duration</code>. The  lexical representation of <code>xs:dayTimeDuration</code>
                     is restricted to contain only day, hour, minute, and second
                     components.</p></dd><dt><a href="#dt-xs-error">xs:error</a></dt><dd><p>
                        <code>xs:error</code> is a simple type with no value space.  It is defined in <a href="https://www.w3.org/TR/xmlschema11-1/#xsd-error">
                  
                     3.16.7.3 xs:error
                  
               </a><sup><small>XS11-1</small></sup> and  can be used in the <a href="#id-sequencetype-syntax"><b>3.1 Sequence Types</b></a> to raise errors.</p></dd><dt><a href="#dt-untyped">xs:untyped</a></dt><dd><p>
                        <code>xs:untyped</code> is  used as the <a title="type annotation" class="termref" href="#dt-type-annotation">type annotation</a> of an element node that has not been validated, or has been validated in <code>skip</code> mode.</p></dd><dt><a href="#dt-untypedAtomic">xs:untypedAtomic</a></dt><dd><p>
                        <code>xs:untypedAtomic</code>
                     is an <a title="atomic type" class="termref" href="#dt-atomic-type">atomic type</a> that is used to denote untyped atomic data, 
                     such as text that has not been assigned a more specific type.</p></dd><dt><a href="#dt-yearMonthDuration">xs:yearMonthDuration</a></dt><dd><p>
                        <code>xs:yearMonthDuration</code> is derived by restriction from <code>xs:duration</code>. The lexical representation of <code>xs:yearMonthDuration</code> is
                     restricted to contain only year and month
                     components.</p></dd><dt><a href="#dt-XTree">XTree</a></dt><dd><p>A tree that is rooted at a parentless
    <a title="XNode" class="termref" href="#dt-XNode">XNode</a> is referred to as an <b>XTree</b>.</p></dd><dt><a href="#id-static-decimal-format-zero-digit">zero-digit</a></dt><dd><p>
                              <b>zero-digit</b>
                              <em>(<var>M</var>)</em>
                                 is the character used in the picture string to represent the digit zero; the default
                                 value is <span class="unicode-codepoint">U+0030</span> (<span class="unicode-name">DIGIT ZERO</span>, <code>0</code>) . 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.</p></dd></dl></div><div class="div1">
<h2><a id="id-atomic-comparisons"/>H <a href="#id-atomic-comparisons" style="text-decoration: none">Atomic Comparisons: An Overview</a> (Non-Normative)</h2><p>This appendix provides a non-normative summary of the various functions and operators used for comparison
    of atomic items, with some background on the history and rationale.</p><p>In XQuery 4.0 there are several ways of comparing two atomic items for equality or ordering.
    The rules for each are summarized in the following sections</p><div class="div2">
<h3><a id="value-comparisons-summary"/>H.1 <a href="#value-comparisons-summary" style="text-decoration: none">Value Comparisons</a></h3><p>For example <code>$A eq $B</code> or <code>$A lt $B</code>.</p><p>Value comparisons were introduced in XPath 2.0 and XQuery 1.0. One of the aims was to make
          the comparison transitive (a precondition for a wide variety of optimizations), however in edge
          cases involving comparisons across different numeric types this was not entirely achieved.
          To fix this problem, the rules have changed in the 4.0 specification.</p><p>With a value comparison, the rules are:</p><ul><li><p>Each operand must either be a single atomic item, or an empty sequence.</p></li><li><p>If either operand is an empty sequence, the result is an empty sequence; in most
            contexts this has the same effect as returning false.</p></li><li><p>Strings are compared using the default collation from the static context
          of the expression.</p></li><li><p>Date and time values are compared after normalizing the timezone offset.
          If the timezone is absent, the implicit timezone from the dynamic evaluation context
          is used.</p></li><li><p>If nodes are supplied, they are atomized. In the absence of schema validation,
          the result of atomizing a node is an untyped atomic value, which is treated as a string.
          Comparison of a node to a value such as a number or a date therefore raises an error.</p></li><li><p>Numeric values of types <code>xs:integer</code>, <code>xs:decimal</code>, 
            or <code>xs:float</code> are mutually comparable. Except for the special values <code>NaN</code>
            and positive and negative infinity, both operands
            are converted to <code>xs:decimal</code>, using an implementation of <code>xs:decimal</code>
          that supports unlimited precision (or at least, sufficient precision to represent every
          datum in the <code>xs:double</code> value space losslessly), and the comparison then
          follows the normal mathematical principles.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>This is a change from previous versions, where both values were converted
            to <code>xs:double</code>. The reason for the change is to make comparisons transitive,
            which is vital for operations such as sorting and grouping.</p></div></li><li><p>NaN is not equal to NaN; negative zero is equal to positive zero.</p></li><li><p>In 4.0, <code>xs:hexBinary</code> and <code>xs:base64Binary</code> values are mutually comparable:
            they are equal if they represent the same sequence of octets.</p></li><li><p>Comparing incompatible values (for example <code>xs:integer</code> and <code>xs:date</code>)
            raises an error.</p></li></ul></div><div class="div2">
<h3><a id="general-comparisons-summary"/>H.2 <a href="#general-comparisons-summary" style="text-decoration: none">General Comparisons</a></h3><p>For example <code>$A = $B</code> or <code>$A &lt; $B</code>.</p><p>These operators were introduced in XPath 1.0. The semantics were changed significantly in XPath 2.0, but the
          original semantics remain available when XPath 1.0 compatibility mode is enabled.</p><p>The following rules are observed:</p><ul><li><p>Either operand may be a sequence; the result is true if any pair of items from the
            two sequences have the required relationship (when compared using a value comparison,
            as described above). For equality tests, the result is reasonably
            intuitive, for example <code>(position() = 1 to 10)</code> is true if the value of 
            <code>position()</code> is equal to any of the values from 1 to 10 inclusive. For other
            operators, the result may be less obvious: for example <code>(position() &gt; 1 to 10)</code>
            has exactly the same meaning as <code>(position() &gt; 1)</code>.</p><p>In consequence, if either operand is an empty sequence, the result is false.</p></li><li><p>If nodes are supplied, they are atomized.</p></li><li><p>Untyped atomic items appearing in one operand are converted to the type of the
            other operand (if both operands are untyped atomic, they are compared as strings).
            As a result, the operator is not transitive: the untyped atomic items <code>"4.0"</code>
            and <code>"4"</code> are not equal to each other, but both compare equal to the integer value 
            <code>4</code>.</p></li><li><p>As with value comparisons, the result is context-sensitive. In particular, comparison of strings
            uses the default collation from the static context, while comparison of date/time values lacking
            a timezone takes the implicit timezone from the dynamic context.</p></li><li><p>Comparing incompatible values (for example <code>xs:integer</code> and <code>xs:date</code>)
            raises an error.</p></li><li><p>For version 4.0, two changes arise as a consequence of the changes
          to value comparisons, described above:</p><ol class="enumar"><li><p>
                           <code>xs:hexBinary</code> and <code>xs:base64Binary</code> values become 
                mutually comparable.</p></li><li><p>Comparison between mixed numeric types (for example <code>xs:decimal</code>
              and <code>xs:double</code>) now converts both values to <code>xs:decimal</code>
              rather than <code>xs:double</code>.</p></li></ol></li><li><p>To mitigate the compatibility impact of the above change, the rules for handling
            untyped atomic values have changed: for example, if <code>$a</code> is an untyped
            attribute node with the value <code>"8.95"</code>, then the comparison
            <code>$a = 8.95</code> remains true. This is because an untyped atomic value is
            now converted to the type of the other operand, which in this case is <code>xs:decimal</code>,
            and the two <code>xs:decimal</code> values compare equal.</p></li></ul></div><div class="div2">
<h3><a id="deep-equal-summary"/>H.3 <a href="#deep-equal-summary" style="text-decoration: none">fn:deep-equal</a></h3><p>For example, <code>deep-equal($A, $B)</code>
            </p><p>As the name implies, the <code>deep-equal</code> function was introduced primarily for comparing nodes,
          or sequences of nodes; however in its simplest form it can also be used to compare two atomic items. The semantics
          of the comparison used by <code>deep-equal($A, $B)</code> are also invoked by a wide variety of other functions
          including <code>distinct-values</code>, <code>all-equal</code>, and <code>all-different</code>; it is also
          used to underpin grouping constructs in both XQuery 4.0 and XSLT 4.0.</p><p>Some of the relevant rules are:</p><ul><li><p>Because <code>deep-equal</code> is used to compare sequences, if one of the operands is an empty
            sequence the result is false; but if both operands are empty sequences, the result is true.</p></li><li><p>If nodes are supplied, they are not atomized; they are compared as nodes.</p></li><li><p>Strings can be compared using the default collation or using an explicitly specified collation;
            there are also options to compare after normalizing whitespace or Unicode.</p></li><li><p>Comparisons of dates and times lacking a timezone uses the implicit timezone from the dynamic
            context.</p></li><li><p>To ensure that every value is equal to itself, comparing NaN to NaN returns true.</p></li><li><p>In all other cases comparison between numeric values, including comparison of mixed
            types such as <code>xs:double</code> and <code>xs:decimal</code>, follows the same
            rules as for value comparisons using the <code>eq</code> operator.</p></li><li><p>
                     <code>xs:hexBinary</code> and <code>xs:base64Binary</code> values are mutually comparable:
            they are equal if they represent the same sequence of octets.</p></li><li><p>Comparing incompatible values (for example <code>xs:integer</code> and <code>xs:date</code>)
            returns false; it does not raise an error.</p></li></ul></div><div class="div2">
<h3><a id="atomic-equal-summary"/>H.4 <a href="#atomic-equal-summary" style="text-decoration: none">fn:atomic-equal</a></h3><p>For example, <code>atomic-equal($A, $B)</code>
            </p><p>This comparison operation was introduced in XPath 3.0 (and XQuery 3.0) for comparing keys in maps;
          the 4.0 specifications expose it directly as a function that can be called from user applications.
          The dominant requirements for keys in maps were that the comparison should be transitive, error-free, 
          and context-independent. The relevant rules are:</p><ul><li><p>The type signature of the function ensures that it can only be used to compare
            single items; empty sequences do not arise.</p></li><li><p>If nodes are supplied, they are atomized.</p></li><li><p>Strings are compared codepoint-by-codepoint, without reference to any collation or
            normalization.</p></li><li><p>Dates and times lacking a timezone are never equal to dates and times that have a timezone.
            However, when comparing two dates or times that both have a timezone, the timezone is normalized.</p></li><li><p>Comparison of numeric values follows the same rules as <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-deep-equal"><code>deep-equal</code></a>:
            NaN is considered equal to NaN, positive zero is equal to negative zero, 
            and numeric values of differing type are converted to <code>xs:decimal</code> 
            prior to comparison.</p></li><li><p>
                     <code>xs:hexBinary</code> and <code>xs:base64Binary</code> values are mutually comparable:
            they are equal if they represent the same sequence of octets. This represents
          an incompatibility with previous versions, in that an <code>xs:hexBinary</code> and <code>xs:base64Binary</code>
          value representing the same sequence of octets can no longer co-exist in the same map;
          they are considered to be duplicate keys.</p></li><li><p>Comparing incompatible values (for example <code>xs:integer</code> and <code>xs:date</code>)
            returns false; it does not raise an error.</p></li></ul></div><div class="div2">
<h3><a id="fn-compare-summary"/>H.5 <a href="#fn-compare-summary" style="text-decoration: none">fn:compare</a></h3><p>The function <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-compare"><code>fn:compare</code></a> was introduced in XPath 3.0 and XQuery 3.0 for comparing
    strings; in 4.0 it has been extended to handle other data types. Unlike <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-deep-equal"><code>fn:deep-equal</code></a>
    and <code>fn:atomic-equal</code> it establishes the order relationship of two atomic items, rather than
    simply determining whether they are equal.</p><p>Broadly speaking, the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-compare"><code>fn:compare</code></a> function establishes the relationship between
    its first two operands in the same way as value comparisons using the <code>eq</code> and <code>lt</code>
    operators. The main differences are:</p><ol class="enumar"><li><p>
                     <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-compare"><code>fn:compare</code></a> allows a collation to be supplied explicitly, rather than
      relying on the static context.</p></li><li><p>
                     <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-compare"><code>fn:compare</code></a> treats <code>NaN</code> as equal to itself (and less than any
        other numeric value).</p></li></ol><p>All other functions and operations that depend on sorting values (for example the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-sort"><code>fn:sort</code></a>,
    <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-sort-by"><code>fn:sort-by</code></a>, and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-sort-with"><code>fn:sort-with</code></a> functions, the <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-min"><code>fn:min</code></a>
    and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-max"><code>fn:max</code></a> functions, <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-highest"><code>fn:highest</code></a> and <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-lowest"><code>fn:lowest</code></a>,
    the <code>order by</code> clause in XQuery, and the <code>xsl:sort</code> and <code>xsl:merge</code> instructions
    in XSLT, are ultimately defined in terms of either <code>fn:compare</code> or the value comparison operators
    <code>eq</code> and <code>lt</code>.</p></div><div class="div2">
<h3><a id="comparison-methods-summary"/>H.6 <a href="#comparison-methods-summary" style="text-decoration: none">Summary of Atomic Comparison Methods</a></h3><p>The following table summarizes these differences for different ways of comparing values. For all these examples it is assumed that
      (a) the default collation is the HTML case-blind collation, (b) the implicit timezone is
      +01:00, and (c) nodes are untyped.</p><table style="border:1px solid" class="small"><thead><tr><th>
                        <code>$A</code>
                     </th><th>
                        <code>$B</code>
                     </th><th>
                        <code>$A = $B</code>
                     </th><th>
                        <code>$A eq $B</code>
                     </th><th>
                        <code>deep-equal(​$A, $B)</code>
                     </th><th>
                        <code>atomic-equal(​$A, $B)</code>
                     </th><th>
                        <code>compare(​$A, $B)</code>
                     </th></tr></thead><tbody><tr><td>
                        <p>
                           <code>()</code>
                        </p>
                     </td><td>
                        <p>
                           <code>()</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>()</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>error</code>
                        </p>
                     </td><td>
                        <p>
                           <code>()</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>12</code>
                        </p>
                     </td><td>
                        <p>
                           <code>()</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>()</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>error</code>
                        </p>
                     </td><td>
                        <p>
                           <code>()</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>(1,2)</code>
                        </p>
                     </td><td>
                        <p>
                           <code>(2,3)</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>error</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>error</code>
                        </p>
                     </td><td>
                        <p>
                           <code>error</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>12</code>
                        </p>
                     </td><td>
                        <p>
                           <code>12e0</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>0</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>0.2</code>
                        </p>
                     </td><td>
                        <p>
                           <code>0.2e0</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>-1</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>NaN</code>
                        </p>
                     </td><td>
                        <p>
                           <code>NaN</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>0</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>+0e0</code>
                        </p>
                     </td><td>
                        <p>
                           <code>-0e0</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>0</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>"A"</code>
                        </p>
                     </td><td>
                        <p>
                           <code>"a"</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>0</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>"A"</code>
                        </p>
                     </td><td>
                        <p>
                           <code>12</code>
                        </p>
                     </td><td>
                        <p>
                           <code>error</code>
                        </p>
                     </td><td>
                        <p>
                           <code>error</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>error</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>&lt;a&gt;A&lt;/a&gt;</code>
                        </p>
                     </td><td>
                        <p>
                           <code>"A"</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>0</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>&lt;a&gt;12&lt;/a&gt;</code>
                        </p>
                     </td><td>
                        <p>
                           <code>12</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>error</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>error</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>xs:time(​'12:00:00Z')</code>
                        </p>
                     </td><td>
                        <p>
                           <code>xs:time(​'13:00:00+01:00')</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>0</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>xs:time(​'12:00:00Z')</code>
                        </p>
                     </td><td>
                        <p>
                           <code>xs:time(​'13:00:00')</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>false</code>
                        </p>
                     </td><td>
                        <p>
                           <code>0</code>
                        </p>
                     </td></tr><tr><td>
                        <p>
                           <code>xs:hexBinary(​"0000")</code>
                        </p>
                     </td><td>
                        <p>
                           <code>xs:base64Binary(​"AAA=")</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>true</code>
                        </p>
                     </td><td>
                        <p>
                           <code>0</code>
                        </p>
                     </td></tr></tbody></table></div></div><div class="div1">
<h2><a id="id-incompatibilities"/>I <a href="#id-incompatibilities" style="text-decoration: none">Backwards Compatibility</a> (Non-Normative)</h2><div class="div2">
<h3><a id="id-incompatibilities-31"/>I.1 <a href="#id-incompatibilities-31" style="text-decoration: none">Incompatibilities relative to XQuery 3.1</a></h3><p>Comparisons between numeric values of different types (for example <code>xs:double</code>
    and <code>xs:decimal</code>) may give a different result, because the values will now be compared
    as decimals rather than as doubles. For example, the comparison <code>3.1 = 3.1e0</code> will now return
    false, because the exact value of the <code>xs:double</code> written as <code>3.1e0</code>
    is actually <code>3.100000000000000088817841970012523233890533447265625</code>. This change is made
    to ensure that comparison operations are fully transitive, which is a prerequisite for certain
    sorting and grouping algorithms.</p><p>In <code>fn:format-integer</code>, certain formatting pictures using a circumflex as a grouping separator might
    be interpreted differently in 4.0: for example <code>format-integer(1234, "9^999")</code> would output <code>"1^234"</code>
      in 3.1, but will output <code>"1621"</code> (1234 in base 9) with 4.0. As a workaround, this can be rewritten as 
      <code>format-integer(1234, "0^000")</code>.</p><p>In computed node constructors, the node name must now be written as a QName literal
      (with a preceding <code>#</code> character)
    if it matches certain language keywords. For example <code>element div {}</code> must now be
    written <code>element #div {}</code>. (Alternatively, <code>element { "div" } {}</code>
    and <code>element Q{}div {}</code> are permitted by both XQuery 3.1 and XQuery 4.0.)
    This change is made because <code>{}</code> is now a valid expression representing an
    empty map, so expressions such as <code>element otherwise {}</code> could (without this rule) be 
    parsed in two different ways.</p><p>In a pragma, whitespace is now required after the opening <code>(#</code> and
    before the subsequent <code>EQName</code>. This change is made to ensure that an expression
    such as <code>error(#err:XPTY0004)</code> can be parsed as a function call taking a QName literal
    as its argument.</p><p>In XQuery 4.0, certain expressions are classified as <a title="implausible" class="termref" href="#dt-implausible">implausible</a>: an example
    is <code>@code/text()</code>, which will always return an empty sequence. A processor may report
    a static error when such expressions are encountered; however, processors are <span class="verb">required</span>
    to provide a mode of operation in which such expressions are accepted, thus retaining backwards
    compatibility.</p><p>In expressions that deliver a function item, notably partial function applications, named function references,
    and the <code>fn:function-lookup</code> function, errors may now be detected at the point where the function item
    is created when they were previously detected at the point where the function item was called. This was underspecified
    in previous versions. For example, the partial function application <code>contains(?, 42)</code> is now required to
    raise a type error (because the second argument should be a string, not an integer) at the point where the partial
    function application occurs, not at the point where the resulting function is called.</p><p>As explained in <a href="#id-function-coercion"><b>3.4.3 Function Coercion</b></a>, the fact that coercion rules are now applied
    to global variables and local variable bindings introduces an incompatibility in the case of variables
    whose value is a function item. Previously it was possible to supply a function item that accepted a wider
    range of argument values than those declared in the variable's type declaration; this is no longer the case.</p><p>Use of an unprefixed function name in a function declaration has a different meaning from XQuery 3.1. In
    3.1 and previous versions, this declared a function in the <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a>
    (which would cause an error unless the default function namespace was explicitly set to something other than
    the <code>fn</code> namespace). In XQuery 4.0, the function name will be in no namespace. The distinction will rarely
    be noticed, because an unprefixed function name in a call of such a function will still work in the same way.
    It could make a difference, however, if a function call uses a prefixed name in which the prefix is explicitly
    bound to the default function namespace.</p></div><div class="div2">
<h3><a id="id-incompatibilities-30"/>I.2 <a href="#id-incompatibilities-30" style="text-decoration: none">Incompatibilities relative to XQuery 3.0</a></h3><p>The following names are now reserved, and cannot appear as function names (see <a href="#id-reserved-fn-names"><b>A.4 Reserved Function Names</b></a>):</p><ul><li><p>
                     <code>map</code>
                  </p></li><li><p>
                     <code>array</code>
                  </p></li></ul></div><div class="div2">
<h3><a id="id-incompatibilities-10"/>I.3 <a href="#id-incompatibilities-10" style="text-decoration: none">Incompatibilities relative to XQuery <span class="xquery">1.0</span>
            </a></h3><p>The following names are now reserved, and cannot appear as function names (see <a href="#id-reserved-fn-names"><b>A.4 Reserved Function Names</b></a>):</p><ul><li><p>
                     <code>function</code>
                  </p></li><li><p>
                     <code>namespace-node</code>
                  </p></li><li><p>
                     <code>switch</code>
                  </p></li></ul><p>If <code>U</code> is a union type with <code>T</code> as one of its members,
  and if <code>E</code> is an element with <code>T</code> as its type annotation,
  the expression <code>E instance of element(*, U)</code>
  returns <code>true</code> in both XQuery 3.0 and 3.1.
  In <span class="xquery">XQuery 1.0</span>,
  it returns <code>false</code>.</p><div class="note"><p class="prefix"><b>Note:</b></p><p>This is not an incompatibility with XQuery 3.0.
 It should be included in XQuery 3.0 as an incompatibility with
 <span class="xquery">XQuery 1.0</span>,
 but it was discovered after publication.</p></div></div></div><div class="div1">
<h2><a id="id-revision-log"/>J <a href="#id-revision-log" style="text-decoration: none">Change Log</a> (Non-Normative)</h2><ol><li><p>Use the arrows to browse significant changes since the 3.1 version of this specification.</p><p>See <a href="#id-introduction"><b>1 Introduction</b></a></p></li><li><p>Sections with significant changes are marked Δ in the table of contents.</p><p>See <a href="#id-introduction"><b>1 Introduction</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/691 2154">691 2154 </a></p><p>Enumeration types are added as a new kind of <code>ItemType</code>, constraining
                     the value space of strings.</p><p>See <a href="#id-enumeration-types"><b>3.2.6 Enumeration Types</b></a></p></li><li><p>
                     Setting the default namespace for elements and types to the special value
                     <code>##any</code> causes an unprefixed element name to act as a wildcard,
                     matching by local name regardless of namespace.
                  </p><p>See <a href="#id-element-test"><b>3.2.7.2 Element Types</b></a></p></li><li><p>The terms <b>FunctionType</b>, <b>ArrayType</b>,
                     <b>MapType</b>, and <b>RecordType</b> replace 
                     <b>FunctionTest</b>, <b>ArrayTest</b>,
                     <b>MapTest</b>, and <b>RecordTest</b>, with no
                  change in meaning.</p><p>See <a href="#id-function-test"><b>3.2.8.1 Function Types</b></a></p></li><li><p>
                     Record types are added as a new kind of <code>ItemType</code>, constraining
                     the value space of maps.
                  </p><p>See <a href="#id-record-test"><b>3.2.8.3 Record Types</b></a></p></li><li><p>
                     Function coercion now allows a function with arity <var>N</var> to be supplied where a function of arity 
                     greater than <var>N</var> is expected. For example this allows the function <code>true#0</code> 
                     to be supplied where a predicate function is required.
                  </p><p>See <a href="#id-function-coercion"><b>3.4.3 Function Coercion</b></a></p></li><li><p>
               The symbols <code>×</code> and <code>÷</code> can be used for multiplication and division.
            </p><p>See <a href="#id-arithmetic"><b>4.8 Arithmetic Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1480 1989">1480 1989 </a></p><p>
                     When the element name matches a language keyword such as <code>div</code> or <code>value</code>, 
                     it must now be written as a QName literal. This is a backwards incompatible change.
                  </p><p>See <a href="#id-computedElements"><b>4.12.3.1 Computed Element Constructors</b></a></p><p>
                     When the attribute name matches a language keyword such as <code>by</code> or <code>of</code>, 
                     it must now be written as a QName literal. This is a backwards incompatible change.
                  </p><p>See <a href="#id-computedAttributes"><b>4.12.3.2 Computed Attribute Constructors</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1513 2028">1513 2028 </a></p><p>
                     When the processing instruction name matches a language keyword such as <code>try</code> or <code>validate</code>, 
                     it must now be written with a preceding <code>#</code> character. This is a backwards incompatible change.
                  </p><p>See <a href="#id-computed-pis"><b>4.12.3.5 Computed Processing Instruction Constructors</b></a></p><p>
                     When the namespace prefix matches a language keyword such as <code>as</code> or <code>at</code>, 
                     it must now be written with a preceding <code>#</code> character. This is a backwards incompatible change.
                  </p><p>See <a href="#id-computed-namespaces"><b>4.12.3.7 Computed Namespace Constructors</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1763 1830">1763 1830 </a></p><p>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.</p><p>See <a href="#id-arrow-operator"><b>4.24 Arrow Expressions</b></a></p></li><li><p>
               The arrow operator <code>=&gt;</code> is now complemented by a “mapping arrow” operator <code>=!&gt;</code>
               which applies the supplied function to each item in the input sequence independently.
            </p><p>See <a href="#id-mapping-arrow-expression"><b>4.24.2 Mapping Arrow Expressions</b></a></p></li><li><p>
        All implementations must now predeclare the namespace prefixes
        <code>math</code>, <code>map</code>, <code>array</code>, and <code>err</code>. In XQuery 3.1 it was permitted
        but not required to predeclare these namespaces.
      </p><p>See <a href="#id-namespace-declaration"><b>5.13 Namespace Declaration</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2200 2236">2200 2236 </a></p><p>
        The effect of not declaring a default function namespace has changed: user-defined functions can
        now be in no namespace, and a search for an unprefixed function name will be resolved first
        against functions in no namespace, and only then against functions in the standard function namespace.
      </p><p>See <a href="#id-default-namespace"><b>5.14 Default Namespace Declaration</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/254 2050">254 2050 </a></p><p>
        The supplied context value is now coerced to the required type specified in the main module
        using the coercion rules.
      </p><p>See <a href="#id-context-value-declarations"><b>5.17 Context Value Declaration</b></a></p></li><li><p>
        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).
      </p><p>See <a href="#FunctionDeclns"><b>5.18 Function Declarations</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/682 TODO">682 TODO </a></p><p>
          The values <code>true()</code> and <code>false()</code> are allowed
          in function annotations, as well as negated numeric literals and
          QName literals.
        </p><p>See <a href="#id-function-annotations"><b>5.18.4 Function Annotations</b></a></p></li><li><p>
        A user-defined function whose name is given as an unprefixed QName is now in no namespace.
        In previous versions of the language, it represented a name in the <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a>
        (which only worked if the <a title="default function namespace" class="termref" href="#dt-default-function-namespace">default function namespace</a> was explicitly set to an unreserved
        namespace, which was rarely done because it caused other problems).
      </p><p>See <a href="#FunctionDeclns"><b>5.18 Function Declarations</b></a></p><p>See <a href="#id-function-names"><b>5.18.2 Function Names</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1023 1128">1023 1128 </a></p><p>
                     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.
                  </p><p>See <a href="#id-function-coercion"><b>3.4.3 Function Coercion</b></a></p></li><li><p>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.</p><p>See <a href="#id-eval-dynamic-function-call"><b>4.5.3.1 Evaluating Dynamic Function Calls</b></a></p></li><li><p>
    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.
  </p><p>See <a href="#id-xq-static-context-components"><b>B.1 Static Context Components</b></a></p></li><li><p>
                     The syntax <code>document-node(<var>N</var>)</code>, where <var>N</var> is a <code>NameTestUnion</code>,
                     is introduced as an abbreviation for <code>document-node(element(<var>N</var>))</code>. For example,
                     <code>document-node(*)</code> matches any well-formed XML document (as distinct from a document fragment).
                  </p><p>See <a href="#node-types"><b>3.2.7 Node Types</b></a></p></li><li><p>QName literals are new in 4.0.</p><p>See <a href="#id-qname-literals"><b>4.2.1.3 QName Literals</b></a></p></li><li><p>
               Path expressions are extended to handle JNodes (found in trees of maps and arrays)
               as well as XNodes (found in trees representing parsed XML).
            </p><p>See <a href="#id-path-expressions"><b>4.6 Path Expressions</b></a></p></li><li><p>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.</p><p>See <a href="#id-methods"><b>4.14.4 Method Calls</b></a></p></li><li><p>The <code>treat as</code> expression now raises
               a type error rather than a dynamic error when it fails.</p><p>See <a href="#id-treat"><b>4.21.6 Treat</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/159">159 </a></p><p>
                  Keyword arguments are allowed on static function calls, as well as positional arguments.
               </p><p>See <a href="#id-function-calls"><b>4.5.1.1 Static Function Call Syntax</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/202">202 </a></p><p>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.</p><p>See <a href="#id-sequencetype-subtype"><b>3.3 Subtype Relationships</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/230">230 </a></p><p>
                  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 <code>and</code> and <code>or</code>,
                  and of predicates in filter expressions, in a way that might allow the processor to raise dynamic
                  errors that the author intended to prevent.
               </p><p>See <a href="#id-guarded-expressions"><b>2.4.5 Guarded Expressions</b></a></p><p>See <a href="#id-logical-expressions"><b>4.11 Logical Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/254">254 </a></p><p>
                  The term "function conversion rules" used in 3.1 has been replaced by the term "coercion rules".
               </p><p>See <a href="#id-coercion-rules"><b>3.4 Coercion Rules</b></a></p><p>
                  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 <code>xs:positiveInteger</code>.
               </p><p>See <a href="#id-coercion-rules"><b>3.4 Coercion Rules</b></a></p><p>
                  The value bound to a variable in a <code>let</code> clause is now converted
               to the declared type by applying the coercion rules.
               </p><p>See <a href="#id-xquery-let-clause"><b>4.13.3 Let Clause</b></a></p><p>
        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.
      </p><p>See <a href="#id-variable-declarations"><b>5.16 Variable Declaration</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/284">284 </a></p><p>
               Alternative syntax for conditional expressions is available: <code>if (condition) { X }</code>.
            </p><p>See <a href="#id-conditionals"><b>4.16 Conditional Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/286">286 </a></p><p>
                     Element and attribute tests can include alternative names: <code>element(chapter|section)</code>,
                     <code>attribute(role|class)</code>.
                  </p><p>See <a href="#node-types"><b>3.2.7 Node Types</b></a></p><p>
                     The <code>NodeTest</code> in an <code>AxisStep</code> now allows alternatives: 
                     <code>ancestor::(section|appendix)</code>
                  </p><p>See <a href="#node-types"><b>3.2.7 Node Types</b></a></p><p>
                     Element and attribute tests of the form <code>element(N)</code>
                     and <code>attribute(N)</code> now allow <code>N</code> to be any <code>NameTest</code>,
                     including a wildcard.
                  </p><p>See <a href="#id-element-test"><b>3.2.7.2 Element Types</b></a></p><p>See <a href="#id-attribute-test"><b>3.2.7.3 Attribute Types</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/324">324 </a></p><p>
                  String templates provide a new way of constructing strings: for example <code>`{$greeting}, {$planet}!`</code>
                  is equivalent to <code>$greeting || ', ' || $planet || '!'</code>
                  </p><p>See <a href="#id-string-templates"><b>4.9.2 String Templates</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/326">326 </a></p><p>
           Support for higher-order functions is now a mandatory feature (in 3.1 it was optional).
        </p><p>See <a href="#id-conformance"><b>6 Conformance</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/344">344 </a></p><p>A <code>for member</code> clause is added to 
                  FLWOR expressions to allow iteration over an array.
               </p><p>See <a href="#id-xquery-for-clause"><b>4.13.2 For Clause</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/364">364 </a></p><p>
               Switch expressions now allow a <code>case</code> clause to match multiple atomic items.
            </p><p>See <a href="#id-switch"><b>4.18 Switch Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/368">368 </a></p><p>
                  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.
               </p><p>See <a href="#eval_context"><b>2.2.2 Dynamic Context</b></a></p><p>See <a href="#id-context-value-declarations"><b>5.17 Context Value Declaration</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/433">433 </a></p><p>
                     Numeric literals can now be written in hexadecimal or binary notation; 
                     and underscores can be included for readability.
                  </p><p>See <a href="#id-numeric-literals"><b>4.2.1.1 Numeric Literals</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/483">483 </a></p><p>
                  The <code>start</code> clause in window expressions has become optional, as well as
                  the <code>when</code> keyword and its associated expression.
               </p><p>See <a href="#id-windows"><b>4.13.4 Window Clause</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/487">487 </a></p><p>In XQuery 4.0, an initial set of
            namespace bindings is prescribed for the static context.</p><p>See <a href="#id-namespaces-and-qnames"><b>2.1.4 Namespaces and QNames</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/493">493 </a></p><p>
               A new variable <code>$err:map</code> is available, capturing all error information in one place.
            </p><p>See <a href="#id-try-catch"><b>4.20 Try/Catch Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/519">519 </a></p><p>
        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.
      </p><p>See <a href="#lexical-structure"><b>A.3 Lexical structure</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/521">521 </a></p><p>New abbreviated syntax is introduced 
                     (<a title="focus function" class="termref" href="#dt-focus-function">focus function</a>) 
                     for simple inline functions taking a single argument. 
                     An example is <code>fn { ../@code }</code>
                  </p><p>See <a href="#id-inline-func"><b>4.5.6 Inline Function Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/587">587 </a></p><p>
               Switch and typeswitch expressions can now be written with curly brackets,
                  to improve readability.
            </p><p>See <a href="#id-switch"><b>4.18 Switch Expressions</b></a></p><p>See <a href="#id-typeswitch"><b>4.21.2 Typeswitch</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/603">603 </a></p><p>
                  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 <code>@price/@value</code>, even though dynamic evaluation
                  is defined to return an empty sequence rather than an error.
               </p><p>See <a href="#id-implausible-expressions"><b>2.4.6 Implausible Expressions</b></a></p><p>See <a href="#implausible-axis-steps"><b>4.6.4.6 Implausible Axis Steps</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/606">606 </a></p><p>
                     Element and attribute tests of the form <code>element(A|B)</code>
                     and <code>attribute(A|B)</code> are now allowed.
                  </p><p>See <a href="#id-element-test"><b>3.2.7.2 Element Types</b></a></p><p>See <a href="#id-attribute-test"><b>3.2.7.3 Attribute Types</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/635">635 </a></p><p>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.</p><p>See <a href="#id-schema-import"><b>5.11 Schema Import</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/659">659 </a></p><p>In previous versions the interpretation of location hints in 
        <code>import schema</code> 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.</p><p>See <a href="#id-schema-import"><b>5.11 Schema Import</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/678">678 </a></p><p>
               The comparand expression in a switch expression can be omitted, allowing
               the switch cases to be provided as arbitrary boolean expressions.
            </p><p>See <a href="#id-switch"><b>4.18 Switch Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/728">728 </a></p><p>
                     The syntax <code>record(*)</code> is allowed; it matches any map.
                  </p><p>See <a href="#id-record-test"><b>3.2.8.3 Record Types</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/753">753 </a></p><p>
                     The <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> 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.
                   </p><p>See <a href="#id-namespaces"><b>4.12.1.2 Namespace Declaration Attributes</b></a></p><p>See <a href="#id-default-namespace"><b>5.14 Default Namespace Declaration</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/815">815 </a></p><p>
                  The coercion rules now allow conversion in either direction between <code>xs:hexBinary</code>
                  and <code>xs:base64Binary</code>.
               </p><p>See <a href="#id-coercion-rules"><b>3.4 Coercion Rules</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/820">820 </a></p><p>
                  The value bound to a variable in a <code>for</code> clause is now converted
                     to the declared type by applying the coercion rules.
               </p><p>See <a href="#id-xquery-for-clause"><b>4.13.2 For Clause</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/911">911 </a></p><p>
                  The coercion rules now allow any numeric type to be implicitly converted to any other, for example
                  an <code>xs:double</code> is accepted where the required type is <code>xs:decimal</code>.
               </p><p>See <a href="#id-coercion-rules"><b>3.4 Coercion Rules</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/943">943 </a></p><p>
                  A FLWOR expression may now include a <code>while</code> clause,
               which causes early exit from the iteration when a condition is encountered.
               </p><p>See <a href="#id-while"><b>4.13.6 While Clause</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/996">996 </a></p><p>
                  The value of a predicate in a filter expression can now be a sequence of integers.
               </p><p>See <a href="#id-filter-expression"><b>4.4 Filter Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1031">1031 </a></p><p>
               An <code>otherwise</code> operator is introduced: <code>A otherwise B</code> returns the
               value of <code>A</code>, unless it is an empty sequence, in which case it returns the value of <code>B</code>.
            </p><p>See <a href="#id-otherwise"><b>4.17 Otherwise Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1071">1071 </a></p><p>
                     In map constructors, the keyword <code>map</code> is now optional, so 
                     <code>map { 0: false(), 1: true() }</code> can now be written <code>{ 0: false(), 1: true() }</code>,
                     provided it is used in a context where this creates no ambiguity.
                  </p><p>See <a href="#id-map-constructors"><b>4.14.1.1 Map Constructors</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1132">1132 </a></p><p>
                     Choice item types (an item type allowing a set of alternative item types)
                     are introduced.
                  </p><p>See <a href="#id-choice-item-types"><b>3.2.5 Choice Item Types</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1163">1163 </a></p><p>
                  Filter expressions for maps and arrays are introduced.
               </p><p>See <a href="#id-filter-maps-and-arrays"><b>4.14.5 Filter Expressions for Maps and Arrays</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1181">1181 </a></p><p>
                  The <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> can be set to the value <code>##any</code>,
                  allowing unprefixed names in axis steps to match elements with a given local name in any namespace.
               </p><p>See <a href="#static_context"><b>2.2.1 Static Context</b></a></p><p>
                     If the default namespace for elements and types has the special value <code>##any</code>,
                     then an unprefixed name in a <code>NameTest</code> acts as a wildcard, matching
                     names in any namespace or none.
                  </p><p>See <a href="#node-tests"><b>4.6.4.2 Node Tests</b></a></p><p>
        The <a title="default namespace for elements and types" class="termref" href="#dt-default-namespace-elements-and-types">default namespace for elements and types</a> can be set to the value <code>##any</code>,
        allowing unprefixed names in axis steps to match elements with a given local name in any namespace.
      </p><p>See <a href="#id-default-namespace"><b>5.14 Default Namespace Declaration</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1197">1197 </a></p><p>The keyword <code>fn</code> is allowed as a synonym for <code>function</code>
                  in function types, to align with changes to inline function declarations.</p><p>See <a href="#id-function-test"><b>3.2.8.1 Function Types</b></a></p><p>
                  In inline function expressions, the keyword <code>function</code> may be abbreviated
                  as <code>fn</code>.
               </p><p>See <a href="#id-inline-func"><b>4.5.6 Inline Function Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1212">1212 </a></p><p>
          New keywords introducing item types, such as <code>record</code>, <code>item</code>, and <code>enum</code>,
            have been added to the list of reserved function names.
      </p><p>See <a href="#id-reserved-fn-names"><b>A.4 Reserved Function Names</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1217">1217 </a></p><p>
                  Predicates in filter expressions for maps and arrays can now be numeric.
               </p><p>See <a href="#id-filter-maps-and-arrays"><b>4.14.5 Filter Expressions for Maps and Arrays</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1249">1249 </a></p><p>A <code>for key/value</code> clause is added to 
                  FLWOR expressions to allow iteration over a map.
               </p><p>See <a href="#id-xquery-for-clause"><b>4.13.2 For Clause</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1250">1250 </a></p><p>
                           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.
                        </p><p>See <a href="#id-decimal-formats"><b>2.2.1.2 Decimal Formats</b></a></p><p>See <a href="#id-decimal-format-decl"><b>5.10 Decimal Format Declaration</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1254">1254 </a></p><p>
                  The rules concerning the interpretation of <code>xsi:schemaLocation</code>
                  and <code>xsi:noNamespaceSchemaLocation</code> attributes have been tightened up.
               </p><p>See <a href="#id-validate"><b>4.25 Validate Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1265">1265 </a></p><p>
                  The rules regarding the <code>document-uri</code> property of nodes returned by the
                  <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-collection"><code>fn:collection</code></a> function have been relaxed.
               </p><p>See <a href="#eval_context"><b>2.2.2 Dynamic Context</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1342">1342 </a></p><p>
               The <code>ordered { E }</code> and <code>unordered { E }</code> expressions are retained for
               backwards compatibility reasons, but in XQuery 4.0 they are deprecated and have no useful effect.
            </p><p>See <a href="#id-unordered-expressions"><b>4.15 Ordered and Unordered Expressions</b></a></p><p>
               The ordering mode declaration is retained for
               backwards compatibility reasons, but in XQuery 4.0 it is deprecated and has no useful effect.
       </p><p>See <a href="#id-default-ordering-decl"><b>5.7 Ordering Mode Declaration</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1344">1344 </a></p><p>

                  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.
               </p><p>See <a href="#static_context"><b>2.2.1 Static Context</b></a></p><p>
             The static typing option has been dropped.
           </p><p>See <a href="#id-processing-model"><b>2.3 Processing Model</b></a></p><p>
          The static typing feature has been dropped. 
        </p><p>See <a href="#id-conformance"><b>6 Conformance</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1361">1361 </a></p><p>
               The term <b>atomic value</b> has been replaced by <a title="atomic item" class="termref" href="#dt-atomic-item">atomic item</a>.
            </p><p>See <a href="#id-values"><b>2.1.3 Values</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1384">1384 </a></p><p>
               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.
            </p><p>See <a href="#id-quantified-expressions"><b>4.19 Quantified Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1432">1432 </a></p><p>
         In earlier versions, the static context for the <a title="initializing expression" class="termref" href="#dt-initializing-expression">initializing expression</a>
         excluded the variable being declared. This restriction has been lifted.
      </p><p>See <a href="#id-variable-declarations"><b>5.16 Variable Declaration</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1470">1470 </a></p><p>
                  <code>$err:stack-trace</code> provides information about the current state of execution.
            </p><p>See <a href="#id-try-catch"><b>4.20 Try/Catch Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1496">1496 </a></p><p>
                  The context value static type, which was there purely to assist in static typing, has been dropped.
               </p><p>See <a href="#static_context"><b>2.2.1 Static Context</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1498">1498 </a></p><p>The EBNF operators <code>++</code> and <code>**</code>
      have been introduced, for more concise representation of sequences using a character
      such as <code>","</code> as a separator. The notation is borrowed from Invisible XML.</p><p>See <a href="#id-terminology"><b>2.1 Terminology</b></a></p><p>
                  The EBNF notation has been extended to allow the constructs <code>(A ++ ",")</code>
                  (one or more occurrences of <code>A</code>, comma-separated, and <code>(A ** ",")</code>
                  (zero or more occurrences of <code>A</code>, comma-separated.
               </p><p>See <a href="#id-ebnf-introduction"><b>2.1.1 Grammar Notation</b></a></p><p>The EBNF operators <code>++</code> and <code>**</code>
      have been introduced, for more concise representation of sequences using a character
      such as <code>","</code> as a separator. The notation is borrowed from Invisible XML.</p><p>See <a href="#id-grammar"><b>A.1 EBNF</b></a></p><p>See <a href="#EBNFNotation"><b>A.1.1 Notation</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1501">1501 </a></p><p>
                  The coercion rules now apply recursively to the members of an array and the entries in a map.
               </p><p>See <a href="#id-coercion-rules"><b>3.4 Coercion Rules</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1532">1532 </a></p><p>
                     Four new axes have been defined: <code>preceding-or-self</code>, <code>preceding-sibling-or-self</code>,
                     <code>following-or-self</code>, and <code>following-sibling-or-self</code>.
                  </p><p>See <a href="#axes"><b>4.6.4.1 Axes</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1577">1577 </a></p><p>
                     The syntax <code>record()</code> is allowed; the only thing it matches is an empty map.
                  </p><p>See <a href="#id-record-test"><b>3.2.8.3 Record Types</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1686">1686 </a></p><p>
               With the pipeline operator <code>-&gt;</code>, the result of an expression
               can be bound to the context value before evaluating another expression.
            </p><p>See <a href="#id-pipeline-operator"><b>4.22 Pipeline operator</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1696">1696 </a></p><p>
                     Parameter names may be included in a function signature; they are purely
                     documentary.
                  </p><p>See <a href="#id-function-test"><b>3.2.8.1 Function Types</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1703">1703 </a></p><p>Ordered maps are introduced.</p><p>See <a href="#id-maps"><b>4.14.1 Maps</b></a></p><p>The order of key-value
                     pairs in the map constructor is now retained in the constructed map.</p><p>See <a href="#id-map-constructors"><b>4.14.1.1 Map Constructors</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1874">1874 </a></p><p>
                  The coercion rules now reorder the entries in a map when the required type is a record type.
               </p><p>See <a href="#id-coercion-rules"><b>3.4 Coercion Rules</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1898">1898 </a></p><p>The rules for subtyping of document node types have been refined.</p><p>See <a href="#id-item-subtype-documents"><b>3.3.2.5.2 Subtyping Nodes: Document Nodes</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1914">1914 </a></p><p>
               A <code>finally</code> clause can be supplied, which will always be evaluated after the
               expressions of the try/catch clauses.
            </p><p>See <a href="#id-try-catch"><b>4.20 Try/Catch Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1956">1956 </a></p><p>
        Private variables declared in a library module are no longer required to be in the module namespace.
      </p><p>See <a href="#id-variable-declarations"><b>5.16 Variable Declaration</b></a></p><p>
          Private functions declared in a library module are no longer required to be in the module namespace.
        </p><p>See <a href="#id-function-names"><b>5.18.2 Function Names</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1982">1982 </a></p><p>
               Whitespace is now required after the opening <code>(#</code> of a pragma. This
               is an incompatible change, made to ensure that an expression such as <code>error(#err:XPTY0004)</code>
               can be parsed as a function call taking a QName literal as its argument value.
            </p><p>See <a href="#id-extension-expressions"><b>4.26 Extension Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/1991">1991 </a></p><p>
                  Named record types used in the signatures of built-in functions are now available as standard
                  in the static context.
               </p><p>See <a href="#static_context"><b>2.2.1 Static Context</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2026">2026 </a></p><p>
          The module feature is no longer an optional feature; processing of library modules
          is now required.
        </p><p>See <a href="#id-conformance"><b>6 Conformance</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2030">2030 </a></p><p>
                  The technical details of how validation works have been moved to the
                  <em>Functions and Operators</em> specification. The XQuery <code>validate</code>
               expression is now defined in terms of the new <a href="https://qt4cg.org/specifications/xpath-functions-40/Overview.html#func-xsd-validator"><code>xsd-validator</code></a> function.
               </p><p>See <a href="#id-validate"><b>4.25 Validate Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2031">2031 </a></p><p>
               The terms <b>XNode</b> and <code>JNode</code> are introduced; the existing
               term <b>node</b> remains in use as a synonym for <b>XNode</b> where
               the context does not specify otherwise.
            </p><p>See <a href="#id-values"><b>2.1.3 Values</b></a></p><p>
                     JNodes are introduced
                  </p><p>See <a href="#id-generalized-node-types"><b>3.2.9 Generalized Node Types</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2055">2055 </a></p><p>
               Sequences, arrays, and maps can be destructured in a <code>let</code> 
               clause to extract their components into multiple variables. 
            </p><p>See <a href="#id-xquery-let-clause"><b>4.13.3 Let Clause</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2094">2094 </a></p><p>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.</p><p>See <a href="#id-map-constructors"><b>4.14.1.1 Map Constructors</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2115">2115 </a></p><p>
                  This section describes and formalizes a convention that was already in use,
                  but not explicitly stated, in earlier versions of the specification.
               </p><p>See <a href="#id-expression-names"><b>2.1.2 Expression Names</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2130">2130 </a></p><p>
                  Operator <code>is-not</code> is introduced, as a complement to the operator <code>is</code>.
               </p><p>See <a href="#id-node-comparisons"><b>4.10.3 GNode Comparisons</b></a></p><p>
                  Operators <code>precedes</code> and <code>follows</code> are introduced as synonyms
                  for operators <code>&lt;&lt;</code> and <code>&gt;&gt;</code>.
               </p><p>See <a href="#id-node-comparisons"><b>4.10.3 GNode Comparisons</b></a></p><p>
                  Operators <code>precedes-or-is</code> and <code>follows-or-is</code> are introduced as synonyms
                  for the union of operators <code>&lt;&lt;</code> and <code>is</code> and for the union of 
                  operators <code>&gt;&gt;</code> and <code>is</code>, respectively.
               </p><p>See <a href="#id-node-comparisons"><b>4.10.3 GNode Comparisons</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2134">2134 </a></p><p>
                  The lookup operator <code>?</code> can now be followed by an arbitrary literal,
                  for cases where keys are items other than integers or NCNames.
                  It can also be followed by a variable reference or a context value reference.
               </p><p>See <a href="#id-lookup"><b>4.14.3 Lookup Expressions</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2202">2202 </a></p><p>The type <code>schema-element(N)</code> is now defined
                     to be a subtype of <code>element()</code> and of various other element tests.</p><p>See <a href="#id-item-subtype-elements"><b>3.3.2.5.3 Subtyping Nodes: Elements</b></a></p><p>The type <code>schema-attribute(N)</code> is now defined
                     to be a subtype of <code>attribute()</code> and of various other attribute tests.</p><p>See <a href="#id-item-subtype-attributes"><b>3.3.2.5.4 Subtyping Nodes: Attributes</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2218">2218 </a></p><p>
                  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.
               </p><p>See <a href="#id-value-comparisons"><b>4.10.1 Value Comparisons</b></a></p><p>The rules for comparing untyped atomic values with numeric values have changed. 
                  Rather than converting an untyped atomic value unconditionally to <code>xs:double</code>,
                  it is now converted to the type of the numeric operand. This is designed to ensure that
                  comparisons such as <code>&lt;a&gt;1.1&lt;/a&gt; = 1.1</code> succeed, given that the values
                  will now be compared as decimals rather than as doubles.</p><p>See <a href="#id-general-comparisons"><b>4.10.2 General Comparisons</b></a></p></li><li><p>PR <a href="https://github.com/qt4cg/qtspecs/pull/2227">2227 </a></p><p>A <code>URIQualifiedName</code> may now supply a prefix
            as well as a URI and local name.</p><p>See <a href="#id-namespaces-and-qnames"><b>2.1.4 Namespaces and QNames</b></a></p></li></ol></div></div><script src="https://www.w3.org/scripts/TR/2016/fixup.js"/><script src="js/toc.js"/></body></html><!--{xml-fix} XSLT Processor: Saxonica--><!--This document was created at (not provided)-->