From d5e834bbc2c314d7066c6a44faa0dfd79371803b Mon Sep 17 00:00:00 2001 From: michaelhkay Date: Wed, 15 Jan 2025 00:12:28 +0000 Subject: [PATCH] =?UTF-8?q?Deploying=20to=20gh-pages=20from=20@=20qt4cg/qt?= =?UTF-8?q?specs@972ce90796f852395d59ab33e43e46579e44054b=20=F0=9F=9A=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pr/1703/expath-binary-40/Overview.html | 2 +- pr/1703/expath-binary-40/Overview.xml | 2 +- pr/1703/expath-file-40/Overview.html | 2 +- pr/1703/expath-file-40/Overview.xml | 2 +- pr/1703/index.html | 2 +- pr/1703/xpath-datamodel-40/Overview-diff.html | 6 +- pr/1703/xpath-datamodel-40/Overview-diff.xml | 6 +- pr/1703/xpath-datamodel-40/Overview.html | 6 +- pr/1703/xpath-datamodel-40/Overview.xml | 6 +- pr/1703/xpath-datamodel-40/autodiff.html | 4 +- .../xpath-datamodel-40/xpath-datamodel-40.xml | 2 +- pr/1703/xpath-functions-40/Overview-diff.html | 78 ++----- pr/1703/xpath-functions-40/Overview-diff.xml | 52 ++--- pr/1703/xpath-functions-40/Overview.html | 78 ++----- pr/1703/xpath-functions-40/Overview.xml | 52 ++--- pr/1703/xpath-functions-40/autodiff.html | 32 +-- .../xpath-functions-40/function-catalog.xml | 30 ++- .../xpath-functions-40/xpath-functions-40.xml | 38 ++-- pr/1703/xquery-40/shared-40-autodiff.html | 38 ++-- pr/1703/xquery-40/shared-40-diff.html | 120 +++++----- pr/1703/xquery-40/shared-40.html | 120 +++++----- pr/1703/xquery-40/shared-40.xml | 93 ++++---- pr/1703/xquery-40/xpath-40-autodiff.html | 28 +-- pr/1703/xquery-40/xpath-40-diff.html | 104 ++++----- pr/1703/xquery-40/xpath-40.html | 104 ++++----- pr/1703/xquery-40/xpath-40.xml | 89 ++++---- pr/1703/xquery-40/xquery-40-autodiff.html | 56 ++--- pr/1703/xquery-40/xquery-40-diff.html | 208 ++++++++---------- pr/1703/xquery-40/xquery-40.html | 208 ++++++++---------- pr/1703/xquery-40/xquery-40.xml | 169 +++++++------- pr/1703/xslt-40/Overview-diff.html | 18 +- pr/1703/xslt-40/Overview.html | 18 +- pr/1703/xslt-40/autodiff.html | 6 +- pr/1703/xslt-40/xslt-40.xml | 4 +- .../Overview-diff.html | 31 ++- .../Overview-diff.xml | 20 +- .../Overview.html | 31 ++- .../xslt-xquery-serialization-40/Overview.xml | 20 +- .../autodiff.html | 6 +- .../xslt-xquery-serialization-40.xml | 6 +- 40 files changed, 891 insertions(+), 1006 deletions(-) diff --git a/pr/1703/expath-binary-40/Overview.html b/pr/1703/expath-binary-40/Overview.html index eda91af30..1171ef14a 100644 --- a/pr/1703/expath-binary-40/Overview.html +++ b/pr/1703/expath-binary-40/Overview.html @@ -13,7 +13,7 @@

EXPath Binary Module 4.0

-

W3C Editor's Draft 14 January 2025

+

W3C Editor's Draft 15 January 2025

This version:
https://qt4cg.org/pr/1703/EXPath/binary-40/
diff --git a/pr/1703/expath-binary-40/Overview.xml b/pr/1703/expath-binary-40/Overview.xml index fda8b319a..639881dcc 100644 --- a/pr/1703/expath-binary-40/Overview.xml +++ b/pr/1703/expath-binary-40/Overview.xml @@ -1,6 +1,6 @@ EXPath Binary Module 4.0 \ No newline at end of file +</xs:schema>

The schema is associated with the URI “http://www.example.com/dm-example.xsd”.

This example exposes the data model for a document that has an associated schema and has been validated successfully against it. In general, an XML Schema is not required, that is, the data model can represent a schemaless, well-formed XML document with the rules described in 2.8 Schema Information.

The XML document is represented by the nodes described below. The value D1 represents a document node; the values E1, E2, etc. represent element nodes; the values A1, A2, etc. represent attribute nodes; the values N1, N2, etc. represent namespace nodes; the values P1, P2, etc. represent processing instruction nodes; the values T1, T2, etc. represent text nodes.

For brevity:

// Document node D1
dm:base-uri(D1)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(D1)"document"
dm:string-value(D1)="  Staind:  Been  Awhile  Tee  Black  (1-sided)  \n            Lyrics  from  the  hit  song  'It's  Been  Awhile'\n            are  shown  in  white,  beneath  the  large\n            'Flock  &  Weld'  Staind  logo.\n          25.00    It's  Been  A  While    10.99    Staind  "
dm:typed-value(D1)=xs:untypedAtomic("  Staind:  Been  Awhile  Tee  Black  (1-sided)  \n            Lyrics  from  the  hit  song  'It's  Been  Awhile'\n            are  shown  in  white,  beneath  the  large\n            'Flock  &  Weld'  Staind  logo.\n          25.00    It's  Been  A  While    10.99    Staind  ")
dm:children(D1)([P1], [E1])
 
// Namespace node N1
dm:node-kind(N1)"namespace"
dm:node-name(N1)()
dm:string-value(N1)="http://www.example.com/catalog"
dm:typed-value(N1)="http://www.example.com/catalog"
 
// Namespace node N2
dm:node-kind(N2)"namespace"
dm:node-name(N2)xs:QName("", "html")
dm:string-value(N2)="http://www.w3.org/1999/xhtml"
dm:typed-value(N2)="http://www.w3.org/1999/xhtml"
 
// Namespace node N3
dm:node-kind(N3)"namespace"
dm:node-name(N3)xs:QName("", "xlink")
dm:string-value(N3)="http://www.w3.org/1999/xlink"
dm:typed-value(N3)="http://www.w3.org/1999/xlink"
 
// Namespace node N4
dm:node-kind(N4)"namespace"
dm:node-name(N4)xs:QName("", "xsi")
dm:string-value(N4)="http://www.w3.org/2001/XMLSchema-instance"
dm:typed-value(N4)="http://www.w3.org/2001/XMLSchema-instance"
 
// Namespace node N5
dm:node-kind(N5)"namespace"
dm:node-name(N5)xs:QName("", "xml")
dm:string-value(N5)="http://www.w3.org/XML/1998/namespace"
dm:typed-value(N5)="http://www.w3.org/XML/1998/namespace"
 
// Processing Instruction node P1
dm:base-uri(P1)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(P1)"processing-instruction"
dm:node-name(P1)xs:QName("", "xml-stylesheet")
dm:string-value(P1)="type="text/xsl"  href="dm-example.xsl""
dm:typed-value(P1)="type="text/xsl"  href="dm-example.xsl""
dm:parent(P1)([D1])
 
// Element node E1
dm:base-uri(E1)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(E1)"element"
dm:node-name(E1)xs:QName("http://www.example.com/catalog", "catalog")
dm:string-value(E1)="  Staind:  Been  Awhile  Tee  Black  (1-sided)  \n            Lyrics  from  the  hit  song  'It's  Been  Awhile'\n            are  shown  in  white,  beneath  the  large\n            'Flock  &  Weld'  Staind  logo.\n          25.00    It's  Been  A  While    10.99    Staind  "
dm:typed-value(E1)fn:error()
dm:type-name(E1)anon:TYP000001
dm:is-id(E1)false
dm:is-idrefs(E1)false
dm:parent(E1)([D1])
dm:children(E1)([C1], [E2], [E7])
dm:attributes(E1)([A1], [A2], [A3])
dm:namespace-nodes(E1)([N1], [N2], [N3], [N4], [N5])
dm:namespace-bindings(E1)("", "http://www.example.com/catalog", "html", "http://www.w3.org/1999/xhtml", "xlink", "http://www.w3.org/1999/xlink", "xsi", "http://www.w3.org/2001/XMLSchema-instance", "xml", "http://www.w3.org/XML/1998/namespace")
 
// Attribute node A1
dm:node-kind(A1)"attribute"
dm:node-name(A1)xs:QName("http://www.w3.org/2001/XMLSchema-instance", "xsi:schemaLocation")
dm:string-value(A1)="http://www.example.com/catalog                                                            dm-example.xsd"
dm:typed-value(A1)(xs:anyURI("http://www.example.com/catalog"), xs:anyURI("catalog.xsd"))
dm:type-name(A1)anon:TYP000002
dm:is-id(A1)false
dm:is-idrefs(A1)false
dm:parent(A1)([E1])
 
// Attribute node A2
dm:node-kind(A2)"attribute"
dm:node-name(A2)xs:QName("http://www.w3.org/XML/1998/namespace", "xml:lang")
dm:string-value(A2)="en"
dm:typed-value(A2)"en"
dm:type-name(A2)xs:NMTOKEN
dm:is-id(A2)false
dm:is-idrefs(A2)false
dm:parent(A2)([E1])
 
// Attribute node A3
dm:node-kind(A3)"attribute"
dm:node-name(A3)xs:QName("", "version")
dm:string-value(A3)="0.1"
dm:typed-value(A3)"0.1"
dm:type-name(A3)xs:string
dm:is-id(A3)false
dm:is-idrefs(A3)false
dm:parent(A3)([E1])
 
// Comment node C1
dm:base-uri(C1)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(C1)"comment"
dm:string-value(C1)="  This  example  is  for  data  model  illustration  only.\n          It  does  not  demonstrate  good  schema  design.  "
dm:typed-value(C1)"  This  example  is  for  data  model  illustration  only.\n          It  does  not  demonstrate  good  schema  design.  "
dm:parent(C1)([E1])
 
// Element node E2
dm:base-uri(E2)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(E2)"element"
dm:node-name(E2)xs:QName("http://www.example.com/catalog", "tshirt")
dm:string-value(E2)="  Staind:  Been  Awhile  Tee  Black  (1-sided)  \n            Lyrics  from  the  hit  song  'It's  Been  Awhile'\n            are  shown  in  white,  beneath  the  large\n            'Flock  &  Weld'  Staind  logo.\n          25.00  "
dm:typed-value(E2)fn:error()
dm:type-name(E2)cat:tshirtType
dm:is-id(E2)false
dm:is-idrefs(E2)false
dm:parent(E2)([E1])
dm:children(E2)([E3], [E4], [E6])
dm:attributes(E2)([A4], [A5], [A6], [A7])
dm:namespace-nodes(E2)([N1], [N2], [N3], [N4], [N5])
dm:namespace-bindings(E2)("", "http://www.example.com/catalog", "html", "http://www.w3.org/1999/xhtml", "xlink", "http://www.w3.org/1999/xlink", "xsi", "http://www.w3.org/2001/XMLSchema-instance", "xml", "http://www.w3.org/XML/1998/namespace")
 
// Attribute node A4
dm:node-kind(A4)"attribute"
dm:node-name(A4)xs:QName("", "code")
dm:string-value(A4)="T1534017"
dm:typed-value(A4)xs:ID("T1534017")
dm:type-name(A4)xs:ID
dm:is-id(A4)true
dm:is-idrefs(A4)false
dm:parent(A4)([E2])
 
// Attribute node A5
dm:node-kind(A5)"attribute"
dm:node-name(A5)xs:QName("", "label")
dm:string-value(A5)="Staind  :  Been  Awhile"
dm:typed-value(A5)xs:token("Staind : Been Awhile")
dm:type-name(A5)xs:token
dm:is-id(A5)false
dm:is-idrefs(A5)false
dm:parent(A5)([E2])
 
// Attribute node A6
dm:node-kind(A6)"attribute"
dm:node-name(A6)xs:QName("http://www.w3.org/1999/xlink", "xlink:href")
dm:string-value(A6)="http://example.com/0,,1655091,00.html"
dm:typed-value(A6)xs:anyURI("http://example.com/0,,1655091,00.html")
dm:type-name(A6)xs:anyURI
dm:is-id(A6)false
dm:is-idrefs(A6)false
dm:parent(A6)([E2])
 
// Attribute node A7
dm:node-kind(A7)"attribute"
dm:node-name(A7)xs:QName("", "sizes")
dm:string-value(A7)="M  L  XL"
dm:typed-value(A7)(xs:token("M"), xs:token("L"), xs:token("XL"))
dm:type-name(A7)cat:sizeList
dm:is-id(A7)false
dm:is-idrefs(A7)false
dm:parent(A7)([E2])
 
// Element node E3
dm:base-uri(E3)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(E3)"element"
dm:node-name(E3)xs:QName("http://www.example.com/catalog", "title")
dm:string-value(E3)="Staind:  Been  Awhile  Tee  Black  (1-sided)"
dm:typed-value(E3)xs:token("Staind: Been Awhile Tee Black (1-sided)")
dm:type-name(E3)xs:token
dm:is-id(E3)false
dm:is-idrefs(E3)false
dm:parent(E3)([E2])
dm:children(E3)([T1])
dm:attributes(E3)()
dm:namespace-nodes(E3)([N1], [N2], [N3], [N4], [N5])
dm:namespace-bindings(E3)("", "http://www.example.com/catalog", "html", "http://www.w3.org/1999/xhtml", "xlink", "http://www.w3.org/1999/xlink", "xsi", "http://www.w3.org/2001/XMLSchema-instance", "xml", "http://www.w3.org/XML/1998/namespace")
 
// Text node T1
dm:base-uri(T1)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(T1)"text"
dm:string-value(T1)="Staind:  Been  Awhile  Tee  Black  (1-sided)"
dm:typed-value(T1)xs:untypedAtomic("Staind:  Been  Awhile  Tee  Black  (1-sided)")
dm:type-name(T1)xs:untypedAtomic
dm:parent(T1)([E3])
 
// Element node E4
dm:base-uri(E4)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(E4)"element"
dm:node-name(E4)xs:QName("http://www.example.com/catalog", "description")
dm:string-value(E4)="\n            Lyrics  from  the  hit  song  'It's  Been  Awhile'\n            are  shown  in  white,  beneath  the  large\n            'Flock  &  Weld'  Staind  logo.\n        "
dm:typed-value(E4)xs:untypedAtomic("\n            Lyrics  from  the  hit  song  'It's  Been  Awhile'\n            are  shown  in  white,  beneath  the  large\n            'Flock  &  Weld'  Staind  logo.\n        ")
dm:type-name(E4)cat:description
dm:is-id(E4)false
dm:is-idrefs(E4)false
dm:parent(E4)([E2])
dm:children(E4)([E5])
dm:attributes(E4)()
dm:namespace-nodes(E4)([N1], [N2], [N3], [N4], [N5])
dm:namespace-bindings(E4)("", "http://www.example.com/catalog", "html", "http://www.w3.org/1999/xhtml", "xlink", "http://www.w3.org/1999/xlink", "xsi", "http://www.w3.org/2001/XMLSchema-instance", "xml", "http://www.w3.org/XML/1998/namespace")
 
// Element node E5
dm:base-uri(E5)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(E5)"element"
dm:node-name(E5)xs:QName("http://www.w3.org/1999/xhtml", "html:p")
dm:string-value(E5)="\n            Lyrics  from  the  hit  song  'It's  Been  Awhile'\n            are  shown  in  white,  beneath  the  large\n            'Flock  &  Weld'  Staind  logo.\n        "
dm:typed-value(E5)xs:untypedAtomic("\n            Lyrics  from  the  hit  song  'It's  Been  Awhile'\n            are  shown  in  white,  beneath  the  large\n            'Flock  &  Weld'  Staind  logo.\n        ")
dm:type-name(E5)xs:anyType
dm:is-id(E5)false
dm:is-idrefs(E5)false
dm:parent(E5)([E4])
dm:children(E5)([T2])
dm:attributes(E5)()
dm:namespace-nodes(E5)([N1], [N2], [N3], [N4], [N5])
dm:namespace-bindings(E5)("", "http://www.example.com/catalog", "html", "http://www.w3.org/1999/xhtml", "xlink", "http://www.w3.org/1999/xlink", "xsi", "http://www.w3.org/2001/XMLSchema-instance", "xml", "http://www.w3.org/XML/1998/namespace")
 
// Text node T2
dm:base-uri(T2)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(T2)"text"
dm:string-value(T2)="\n            Lyrics  from  the  hit  song  'It's  Been  Awhile'\n            are  shown  in  white,  beneath  the  large\n            'Flock  &  Weld'  Staind  logo.\n        "
dm:typed-value(T2)xs:untypedAtomic("\n            Lyrics  from  the  hit  song  'It's  Been  Awhile'\n            are  shown  in  white,  beneath  the  large\n            'Flock  &  Weld'  Staind  logo.\n        ")
dm:type-name(T2)xs:untypedAtomic
dm:parent(T2)([E5])
 
// Element node E6
dm:base-uri(E6)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(E6)"element"
dm:node-name(E6)xs:QName("http://www.example.com/catalog", "price")
dm:string-value(E6)="25.00"
// The typed-value is based on the content type of the complex type for the element
dm:typed-value(E6)cat:monetaryAmount(25.0)
dm:type-name(E6)cat:price
dm:is-id(E6)false
dm:is-idrefs(E6)false
dm:parent(E6)([E2])
dm:children(E6)([T3])
dm:attributes(E6)()
dm:namespace-nodes(E6)([N1], [N2], [N3], [N4], [N5])
dm:namespace-bindings(E6)("", "http://www.example.com/catalog", "html", "http://www.w3.org/1999/xhtml", "xlink", "http://www.w3.org/1999/xlink", "xsi", "http://www.w3.org/2001/XMLSchema-instance", "xml", "http://www.w3.org/XML/1998/namespace")
 
// Text node T3
dm:base-uri(T3)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(T3)"text"
dm:string-value(T3)="25.00"
dm:typed-value(T3)xs:untypedAtomic("25.00")
dm:type-name(T3)xs:untypedAtomic
dm:parent(T3)([E6])
 
// Element node E7
dm:base-uri(E7)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(E7)"element"
dm:node-name(E7)xs:QName("http://www.example.com/catalog", "album")
dm:string-value(E7)="  It's  Been  A  While    10.99    Staind  "
dm:typed-value(E7)fn:error()
dm:type-name(E7)cat:albumType
dm:is-id(E7)false
dm:is-idrefs(E7)false
dm:parent(E7)([E1])
dm:children(E7)([E8], [E9], [E10], [E11])
dm:attributes(E7)([A8], [A9], [A10])
dm:namespace-nodes(E7)([N1], [N2], [N3], [N4], [N5])
dm:namespace-bindings(E7)("", "http://www.example.com/catalog", "html", "http://www.w3.org/1999/xhtml", "xlink", "http://www.w3.org/1999/xlink", "xsi", "http://www.w3.org/2001/XMLSchema-instance", "xml", "http://www.w3.org/XML/1998/namespace")
 
// Attribute node A8
dm:node-kind(A8)"attribute"
dm:node-name(A8)xs:QName("", "code")
dm:string-value(A8)="A1481344"
dm:typed-value(A8)xs:ID("A1481344")
dm:type-name(A8)xs:ID
dm:is-id(A8)true
dm:is-idrefs(A8)false
dm:parent(A8)([E7])
 
// Attribute node A9
dm:node-kind(A9)"attribute"
dm:node-name(A9)xs:QName("", "label")
dm:string-value(A9)="Staind  :  Its  Been  A  While"
dm:typed-value(A9)xs:token("Staind : Its Been A While")
dm:type-name(A9)xs:token
dm:is-id(A9)false
dm:is-idrefs(A9)false
dm:parent(A9)([E7])
 
// Attribute node A10
dm:node-kind(A10)"attribute"
dm:node-name(A10)xs:QName("", "formats")
dm:string-value(A10)="CD"
dm:typed-value(A10)cat:formatType("CD")
dm:type-name(A10)cat:formatType
dm:is-id(A10)false
dm:is-idrefs(A10)false
dm:parent(A10)([E7])
 
// Element node E8
dm:base-uri(E8)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(E8)"element"
dm:node-name(E8)xs:QName("http://www.example.com/catalog", "title")
dm:string-value(E8)="It's  Been  A  While"
dm:typed-value(E8)xs:token("It's Been A While")
dm:type-name(E8)xs:token
dm:is-id(E8)false
dm:is-idrefs(E8)false
dm:parent(E8)([E7])
dm:children(E8)([T4])
dm:attributes(E8)()
dm:namespace-nodes(E8)([N1], [N2], [N3], [N4], [N5])
dm:namespace-bindings(E8)("", "http://www.example.com/catalog", "html", "http://www.w3.org/1999/xhtml", "xlink", "http://www.w3.org/1999/xlink", "xsi", "http://www.w3.org/2001/XMLSchema-instance", "xml", "http://www.w3.org/XML/1998/namespace")
 
// Text node T4
dm:base-uri(T4)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(T4)"text"
dm:string-value(T4)="It's  Been  A  While"
dm:typed-value(T4)xs:untypedAtomic("It's  Been  A  While")
dm:type-name(T4)xs:untypedAtomic
dm:parent(T4)([E8])
 
// Element node E9
dm:base-uri(E9)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(E9)"element"
dm:node-name(E9)xs:QName("http://www.example.com/catalog", "description")
dm:string-value(E9)=""
// xsi:nil is true so the typed value is the empty sequence
dm:typed-value(E9)()
dm:type-name(E9)cat:description
dm:is-id(E9)false
dm:is-idrefs(E9)false
dm:parent(E9)([E7])
dm:children(E9)()
dm:attributes(E9)([A11])
dm:namespace-nodes(E9)([N1], [N2], [N3], [N4], [N5])
dm:namespace-bindings(E9)("", "http://www.example.com/catalog", "html", "http://www.w3.org/1999/xhtml", "xlink", "http://www.w3.org/1999/xlink", "xsi", "http://www.w3.org/2001/XMLSchema-instance", "xml", "http://www.w3.org/XML/1998/namespace")
 
// Attribute node A11
dm:node-kind(A11)"attribute"
dm:node-name(A11)xs:QName("http://www.w3.org/2001/XMLSchema-instance", "xsi:nil")
dm:string-value(A11)="true"
dm:typed-value(A11)xs:boolean("true")
dm:type-name(A11)xs:boolean
dm:is-id(A11)false
dm:is-idrefs(A11)false
dm:parent(A11)([E9])
 
// Element node E10
dm:base-uri(E10)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(E10)"element"
dm:node-name(E10)xs:QName("http://www.example.com/catalog", "price")
dm:string-value(E10)="10.99"
dm:typed-value(E10)cat:monetaryAmount(10.99)
dm:type-name(E10)cat:price
dm:is-id(E10)false
dm:is-idrefs(E10)false
dm:parent(E10)([E7])
dm:children(E10)([T5])
dm:attributes(E10)([A12])
dm:namespace-nodes(E10)([N1], [N2], [N3], [N4], [N5])
dm:namespace-bindings(E10)("", "http://www.example.com/catalog", "html", "http://www.w3.org/1999/xhtml", "xlink", "http://www.w3.org/1999/xlink", "xsi", "http://www.w3.org/2001/XMLSchema-instance", "xml", "http://www.w3.org/XML/1998/namespace")
 
// Attribute node A12
dm:node-kind(A12)"attribute"
dm:node-name(A12)xs:QName("", "currency")
dm:string-value(A12)="USD"
dm:typed-value(A12)cat:currencyType("USD")
dm:type-name(A12)cat:currencyType
dm:is-id(A12)false
dm:is-idrefs(A12)false
dm:parent(A12)([E10])
 
// Text node T5
dm:base-uri(T5)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(T5)"text"
dm:string-value(T5)="10.99"
dm:typed-value(T5)xs:untypedAtomic("10.99")
dm:type-name(T5)xs:untypedAtomic
dm:parent(T5)([E10])
 
// Element node E11
dm:base-uri(E11)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(E11)"element"
dm:node-name(E11)xs:QName("http://www.example.com/catalog", "artist")
dm:string-value(E11)="  Staind  "
dm:typed-value(E11)" Staind "
dm:type-name(E11)xs:string
dm:is-id(E11)false
dm:is-idrefs(E11)false
dm:parent(E11)([E7])
dm:children(E11)([T6])
dm:attributes(E11)()
dm:namespace-nodes(E11)([N1], [N2], [N3], [N4], [N5])
dm:namespace-bindings(E11)("", "http://www.example.com/catalog", "html", "http://www.w3.org/1999/xhtml", "xlink", "http://www.w3.org/1999/xlink", "xsi", "http://www.w3.org/2001/XMLSchema-instance", "xml", "http://www.w3.org/XML/1998/namespace")
 
// Text node T6
dm:base-uri(T6)xs:anyURI("http://www.example.com/catalog.xml")
dm:node-kind(T6)"text"
dm:string-value(T6)="  Staind  "
dm:typed-value(T6)xs:untypedAtomic("  Staind  ")
dm:type-name(T6)xs:untypedAtomic
dm:parent(T6)([E11])
 

A graphical representation of the data model for the preceding example is shown below. Document order in this representation can be found by following the traditional left-to-right, depth-first traversal; however, because the image has been rotated for easier presentation, this appears to be bottom-to-top, depth-first order.

Graphic representation of the data model. [large view, SVG]

E Implementation-Defined and Implementation-Dependent Items (Non-Normative)

E.1 Implementation-Defined Items

The following items are implementation-defined.

  1. Support for additional user-defined or implementation-defined types is implementation-defined. (See 2.8.2 Representation of Types)
  2. When converting from an xs:string to an xs:float or xs:double, it is implementation-defined whether the lexical value “-0” (and similar forms such as “-0.0”) convert to negative zero or to positive zero in the value space. (See 2.9.3 Negative Zero)
  3. Data model construction from sources other than an Infoset or PSVI is implementation-defined. (See 3 Data Model Construction)
  4. Some typed values in the data model are absent. Attempting to access an absent typed value is an error. Behavior in these cases is implementation defined and the host language is responsible for determining the result. (See 4 Accessors)

E.2 Implementation-Dependent Items

The following items are implementation-dependent.

  1. The relative order of namespace nodes nodes is stable but implementation-dependent. (See 2.5 Document Order)
  2. The relative order of attribute nodes nodes is stable but implementation-dependent. (See 2.5 Document Order)
  3. The relative order of distinct trees is stable but implementation-dependent. (See 2.5 Document Order)
  4. The names of anonymous types are implementation-dependent. (See 2.8.2 Representation of Types)
  5. The prefix associated with type names is implementation-dependent. (See 3.3.1.1 Element and Attribute Node Types)

F Change Log (Non-Normative)

The following substantive changes have been made to this document since the XPath and XQuery Data Model 3.1 Recommendation of 21 March 2017.

  1. Use the arrows to browse significant changes since the 3.1 version of this specification.

    See 1 Introduction

  2. Sections with significant changes are marked Δ in the table of contents.

    See 1 Introduction

  3. Constructors are added, and the single accessor function is now an iterator over the key/value pairs in the map.

    See 2.9.5 Map Items

    Constructors are added, and the single accessor function is now an iterator over the members of the array.

    See 2.9.6 Array Items

  4. PR 232 

    Clarified the terminology concerning atomic types and type annotations.

    See 2.2 Basic Concepts

  5. PR 525 

    Introduced the concept of function identity.

    See 2.9.4 Function Items

  6. PR 546 

    Relaxed the rules regarding use of non-XML characters in instances of xs:string.

    See 2.8.4 XML and XSD Versions

  7. PR 988 

    Introduced the concept of labeled items.

    See 2.10 Labeled Items

  8. PR 1361 

    The term atomic value has been replaced by atomic item.

    See 2.2 Basic Concepts

    See 2.9.1 Atomic Items

  9. PR 1703 

    Ordered maps are introduced.

    See 2.9.5 Map Items

G Accessor Summary (Non-Normative)

This section summarizes the return values of each accessor by node type.

G.1 dm:attributes Accessor

Document nodes

Returns the empty sequence

Element nodes

Returns the value of the attributes property. The order of attribute nodes is stable but implementation dependent.

Attribute nodes

Returns the empty sequence.

Namespace nodes

Returns the empty sequence.

Processing instruction nodes

Returns the empty sequence.

Comment nodes

Returns the empty sequence.

Text nodes

Returns the empty sequence.

G.2 dm:base-uri Accessor

Document nodes

Returns the value of the base-uri property.

Element nodes

Returns the value of the base-uri property.

Attribute nodes

If the attribute has a parent, returns the value of the dm:base-uri of its parent; otherwise it returns the empty sequence.

Namespace nodes

Returns the empty sequence.

Processing instruction nodes

Returns the value of the base-uri property.

Comment nodes

If the comment has a parent, returns the value of the dm:base-uri of its parent; otherwise, returns the empty sequence.

Text nodes

If the text node has a parent, returns the value of the dm:base-uri of its parent; otherwise, returns the empty sequence.

G.3 dm:children Accessor

Document nodes

Returns the value of the children property.

Element nodes

Returns the value of the children property.

Attribute nodes

Returns the empty sequence.

Namespace nodes

Returns the empty sequence.

Processing instruction nodes

Returns the empty sequence.

Comment nodes

Returns the empty sequence.

Text nodes

Returns the empty sequence.

G.4 dm:document-uri Accessor

Document nodes

Returns the absolute URI of the resource from which the document node was constructed, or the empty sequence if no such absolute URI is available.

Element nodes

Returns the empty sequence.

Attribute nodes

Returns the empty sequence.

Namespace nodes

Returns the empty sequence.

Processing instruction nodes

Returns the empty sequence.

Comment nodes

Returns the empty sequence.

Text nodes

Returns the empty sequence.

G.5 dm:is-id Accessor

Document nodes

Returns the empty sequence.

Element nodes

Returns the value of the is-id property.

Attribute nodes

Returns the value of the is-id property.

Namespace nodes

Returns the empty sequence.

Processing instruction nodes

Returns the empty sequence.

Comment nodes

Returns the empty sequence.

Text nodes

Returns the empty sequence.

G.6 dm:is-idrefs Accessor

Document nodes

Returns the empty sequence.

Element nodes

Returns the value of the is-idrefs property.

Attribute nodes

Returns the value of the is-idrefs property.

Namespace nodes

Returns the empty sequence.

Processing instruction nodes

Returns the empty sequence.

Comment nodes

Returns the empty sequence.

Text nodes

Returns the empty sequence.

G.7 dm:namespace-nodes Accessor

Document nodes

Returns the empty sequence.

Element nodes

Returns the value of the namespaces property as a sequence of namespace nodes. The order of namespace nodes is stable but implementation dependent.

Attribute nodes

Returns the empty sequence.

Namespace nodes

Returns the empty sequence.

Processing instruction nodes

Returns the empty sequence.

Comment nodes

Returns the empty sequence.

Text nodes

Returns the empty sequence.

G.8 dm:nilled Accessor

Document nodes

Returns the empty sequence.

Element nodes

Returns the value of the nilled property.

Attribute nodes

Returns the empty sequence.

Namespace nodes

Returns the empty sequence.

Processing instruction nodes

Returns the empty sequence.

Comment nodes

Returns the empty sequence.

Text nodes

Returns the empty sequence.

G.9 dm:node-kind Accessor

Document nodes

Returns “document”.

Element nodes

Returns “element”.

Attribute nodes

Returns “attribute”.

Namespace nodes

Returns “namespace”.

Processing instruction nodes

Returns “processing-instruction”.

Comment nodes

Returns “comment”.

Text nodes

Returns “text”.

G.10 dm:node-name Accessor

Document nodes

Returns the empty sequence.

Element nodes

Returns the value of the node-name property.

Attribute nodes

Returns the value of the node-name property.

Namespace nodes

If the prefix is not empty, returns an xs:QName with the value of the prefix property in the local-name and an empty namespace name, otherwise returns the empty sequence.

Processing instruction nodes

Returns an xs:QName with the value of the target property in the local-name and an empty namespace URI and empty prefix.

Comment nodes

Returns the empty sequence.

Text nodes

Returns the empty sequence.

G.11 dm:parent Accessor

Document nodes

Returns the empty sequence.

Element nodes

Returns the value of the parent property.

Attribute nodes

Returns the value of the parent property.

Namespace nodes

Returns the value of the parent property.

Processing instruction nodes

Returns the value of the parent property.

Comment nodes

Returns the value of the parent property.

Text nodes

Returns the value of the parent property.

G.12 dm:string-value Accessor

Document nodes

Returns the value of the string-value property.

Element nodes

Returns the value of the string-value property.

Attribute nodes

Returns the value of the string-value property.

Namespace nodes

Returns the value of the uri property.

Processing instruction nodes

Returns the value of the content property.

Comment nodes

Returns the value of the content property.

Text nodes

Returns the value of the content property.

G.13 dm:type-name Accessor

Document nodes

Returns the empty sequence.

Element nodes

Returns the value of the schema-type property.

Attribute nodes

Returns the value of the schema-type property.

Namespace nodes

Returns the empty sequence.

Processing instruction nodes

Returns the empty sequence.

Comment nodes

Returns the empty sequence.

Text nodes

Returns xs:untypedAtomic.

G.14 dm:typed-value Accessor

Document nodes

Returns the value of the typed-value property.

Element nodes

Returns the value of the typed-value property.

Attribute nodes

Returns the value of the typed-value property.

Namespace nodes

Returns the value of the uri property as an xs:string.

Processing instruction nodes

Returns the value of the content property as a xs:string.

Comment nodes

Returns the value of the content property as a xs:string.

Text nodes

Returns the value of the content property as an xs:untypedAtomic.

G.15 dm:unparsed-entity-public-id Accessor

Document nodes

Returns the public identifier of the specified unparsed entity or the empty sequence if no such entity exists.

Element nodes

Returns the empty sequence.

Attribute nodes

Returns the empty sequence.

Namespace nodes

Returns the empty sequence.

Processing instruction nodes

Returns the empty sequence.

Comment nodes

Returns the empty sequence.

Text nodes

Returns the empty sequence.

G.16 dm:unparsed-entity-system-id Accessor

Document nodes

Returns the system identifier of the specified unparsed entity or the empty sequence if no such entity exists.

Element nodes

Returns the empty sequence.

Attribute nodes

Returns the empty sequence.

Namespace nodes

Returns the empty sequence.

Processing instruction nodes

Returns the empty sequence.

Comment nodes

Returns the empty sequence.

Text nodes

Returns the empty sequence.

H Infoset Construction Summary (Non-Normative)

This section summarizes data model construction from an Infoset for each kind of information item. General notes occur elsewhere.

H.1 Document nodes Information Items

The document information item is required. A document node is constructed for each document information item.

The following infoset properties are required: [children] and [base URI].

The following infoset properties are optional: [unparsed entities].

Document node properties are derived from the infoset as follows:

base-uri

The value of the [base URI] property, if available. Note that the base URI property, if available, is always an absolute URI (if an absolute URI can be computed) though it may contain Unicode characters that are not allowed in URIs. These characters, if they occur, are present in the base-uri property and will have to be encoded and escaped by the application to obtain a URI suitable for retrieval, if retrieval is required.

In practice a [base URI] is not always known. In this case the value of the base-uri property of the document node will be the empty sequence. This is not intrinsically an error, though it may cause some operations that depend on the base URI to fail.

children

The sequence of nodes constructed from the information items found in the [children] property.

For each element, processing instruction, and comment found in the [children] property, a corresponding element, processing instruction, or comment node is constructed and that sequence of nodes is used as the value of the children property.

If present among the [children], the document type declaration information item is ignored.

unparsed-entities

If the [unparsed entities] property is present and is not the empty set, the values of the unparsed entity information items must be used to support the dm:unparsed-entity-system-id and dm:unparsed-entity-public-id accessors.

The internal structure of the values of the unparsed-entities property is implementation defined.

string-value

The concatenation of the string-values of all its text node descendants in document order. If the document has no such descendants, the zero-length string.

typed-value

The dm:string-value of the node as an xs:untypedAtomic value.

document-uri

The document-uri property holds the absolute URI for the resource from which the document node was constructed, if one is available and can be made absolute. For example, if a collection of documents is returned by the fn:collection function, the document-uri property may serve to distinguish between them even though each has the same base-uri property.

If the document-uri is not the empty sequence, then the following constraint must hold: the node returned by evaluating fn:doc() with the document-uri as its argument must return the document node that provided the value of the document-uri property.

In other words, for any document node $arg, either fn:document-uri($arg) must return the empty sequence or fn:doc(fn:document-uri($arg)) must return $arg.

H.2 Element nodes Information Items

The element information items are required. An element node is constructed for each element information item.

The following infoset properties are required: [namespace name], [local name], [children], [attributes], [in-scope namespaces], [base URI], and [parent].

Element node properties are derived from the infoset as follows:

base-uri

The value of the [base URI] property, if available. Note that the base URI property, if available, is always an absolute URI (if an absolute URI can be computed) though it may contain Unicode characters that are not allowed in URIs. These characters, if they occur, are present in the base-uri property and will have to be encoded and escaped by the application to obtain a URI suitable for retrieval, if retrieval is required.

In practice a [base URI] is not always known. In this case the value of the base-uri property of the document node will be the empty sequence. This is not intrinsically an error, though it may cause some operations that depend on the base URI to fail.

node-name

An xs:QName constructed from the [prefix], [local name], and [namespace name] properties.

parent

The node that corresponds to the value of the [parent] property or the empty sequence if there is no parent.

schema-type

All element nodes constructed from an infoset have the type xs:untyped.

children

The sequence of nodes constructed from the information items found in the [children] property.

For each element, processing instruction, comment, and maximal sequence of adjacent character information items found in the [children] property, a corresponding element, processing instruction, comment, or text node is constructed and that sequence of nodes is used as the value of the children property.

Because the data model requires that all general entities be expanded, there will never be unexpanded entity reference information item children.

attributes

A set of attribute nodes constructed from the attribute information items appearing in the [attributes] property. This includes all of the “special” attributes (xml:lang, xml:space, xsi:type, etc.) but does not include namespace declarations (because they are not attributes).

Default and fixed attributes provided by the DTD are added to the [attributes] and are therefore included in the data model attributes of an element.

namespaces

A set of namespace nodes constructed from the namespace information items appearing in the [in-scope namespaces] property. Implementations that do not support namespace nodes may simply preserve the relevant bindings in this property.

Implementations may ignore namespace information items for namespaces which are not known to be used. A namespace is known to be used if:

  • It appears in the expanded QName of the node-name of the element.

  • It appears in the expanded QName of the node-name of any of the element’s attributes.

Note: applications may rely on namespaces that are not known to be used, for example when QNames are used in content and that content does not have a type of xs:QName Such applications may have difficulty processing data models where some namespaces have been ignored.

nilled

All element nodes constructed from an infoset have a nilled property of “false ”.

string-value

The string-value is constructed from the character information item[children] of the element and all its descendants. The precise rules for selecting significant character information items and constructing characters from them is described in 5.7.3 Construction from an Infoset of 5.7 Text nodes.

This process is equivalent to concatenating the dm:string-values of all of the text node descendants of the resulting element node.

If the element has no such descendants, the string-value is the empty string.

typed-value

The string-value as an xs:untypedAtomic.

is-id

All element nodes constructed from an infoset have a is-id property of “false ”.

is-idrefs

All element nodes constructed from an infoset have a is-idrefs property of “false ”.

H.3 Attribute nodes Information Items

The attribute information items are required. An attribute node is constructed for each attribute information item.

The following infoset properties are required: [namespace name], [local name], [normalized value], [attribute type], and [owner element].

Attribute node properties are derived from the infoset as follows:

node-name

An xs:QName constructed from the [prefix], [local name], and [namespace name] properties.

parent

The element node that corresponds to the value of the [owner element] property or the empty sequence if there is no owner.

schema-type

The value xs:untypedAtomic.

string-value

The [normalized value] of the attribute.

typed-value

The attribute’s typed-value is its dm:string-value as an xs:untypedAtomic.

is-id

If the attribute is named xml:id and its [attribute type] property does not have the value ID, then [xml:id] processing is performed. This will ensure that the value does have the type ID and that it is properly normalized. If an error is encountered during xml:id processing, an implementation may raise a dynamic error. The is-id property is always true for attributes named xml:id.

If the [attribute type] property has the value ID, true, otherwise false.

is-idrefs

If the [attribute type] property has the value IDREF or IDREFS, true, otherwise false.

H.4 Namespace nodes Information Items

The namespace information items are required.

The following infoset properties are required: [prefix], [namespace name].

Namespace node properties are derived from the infoset as follows:

prefix

The [prefix] property.

uri

The [namespace name] property.

parent

The element in whose [in-scope namespaces] property the namespace information item appears, if the implementation exposes any mechanism for accessing the dm:parent accessor of namespace nodes.

H.5 Processing instruction nodes Information Items

A processing instruction node is constructed for each processing instruction information item that is not ignored.

The following infoset properties are required: [target], [content], [base URI], and [parent].

Processing instruction node properties are derived from the infoset as follows:

target

The value of the [target] property.

content

The value of the [content] property.

base-uri

The value of the [base URI] property, if available. Note that the base URI property, if available, is always an absolute URI (if an absolute URI can be computed) though it may contain Unicode characters that are not allowed in URIs. These characters, if they occur, are present in the base-uri property and will have to be encoded and escaped by the application to obtain a URI suitable for retrieval, if retrieval is required.

In practice a [base URI] is not always known. In this case the value of the base-uri property of the document node will be the empty sequence. This is not intrinsically an error, though it may cause some operations that depend on the base URI to fail.

parent

The node corresponding to the value of the [parent] property.

There are no processing instruction nodes for processing instructions that are children of a document type declaration information item.

H.6 Comment nodes Information Items

The comment information items are optional.

A comment node is constructed for each comment information item.

The following infoset properties are required: [content] and [parent].

Comment node properties are derived from the infoset as follows:

content

The value of the [content] property.

parent

The node corresponding to the value of the [parent] property.

There are no comment nodes for comments that are children of a document type declaration information item.

H.7 Text nodes Information Items

The character information items are required. A text node is constructed for each maximal sequence of character information items in document order.

The following infoset properties are required: [character code] and [parent].

The following infoset properties are optional: [element content whitespace].

A sequence of character information items is maximal if it satisfies the following constraints:

  1. All of the information items in the sequence have the same parent.

  2. The sequence consists of adjacent character information items uninterrupted by other types of information item.

  3. No other such sequence exists that contains any of the same character information items and is longer.

Text node properties are derived from the infoset as follows:

content

A string comprised of characters that correspond to the [character code] properties of each of the character information items.

If the resulting text node consists entirely of whitespace and the [element content whitespace] property of the character information items used to construct this node are true, the content of the text node is the zero-length string. text nodes are allowed to be empty only if they have no parents; an empty text node will be discarded when its parent is constructed, if it has a parent.

The content of the text node is not necessarily normalized as described in the [Character Model]. It is the responsibility of data producers to provide normalized text, and the responsibility of applications to make sure that operations do not de-normalize text.

parent

The node corresponding to the value of the [parent] property.

I PSVI Construction Summary (Non-Normative)

This section summarizes data model construction from a PSVI for each kind of information item. General notes occur elsewhere.

I.1 Document nodes Information Items

Construction from a PSVI is identical to construction from the Infoset.

I.2 Element nodes Information Items

The following element node properties are affected by PSVI properties.

schema-type

The schema-type is determined as described in 3.3.1.1 Element and Attribute Node Types.

children

The sequence of nodes constructed from the information items found in the [children] property.

For each element, processing instruction, comment, and maximal sequence of adjacent character information items found in the [children] property, a corresponding element, processing instruction, comment, or text node is constructed and that sequence of nodes is used as the value of the children property.

For elements with schema simple types, or complex types with simple content, if the [schema normalized value] PSVI property exists, the processor may use a sequence of nodes containing the processing instruction and comment nodes corresponding to the processing instruction and comment information items found in the [children] property, plus an optional single text node whose string value is the [schema normalized value] for the children property. If the [schema normalized value] is the empty string, the text node must not be present, otherwise it must be present. The relative order of Processing Instruction and comment nodes must be preserved, but the position of the text node, if it is present, among them is implementation defined.

The effect of the above rules is that where a fixed or default value for an element is defined in the schema, and the element takes this default value, a text node will be created to contain the value, even though there are no character information items representing the value in the PSVI. The position of this text node relative to any comment or processing instruction children is implementation-dependent.

[Schema Part 1] also permits an element with mixed content to take a default or fixed value (which will always be a simple value), but it is unclear how such a defaulted value is represented in the PSVI. Implementations therefore may represent such a default value by creating a text node, but are not required to do so.

Note:

Section 3.3.1 in [Schema 1.1 Part 1] clarifies the PSVI contributions of element default or fixed values in mixed content: additional character information items are not added to the PSVI.

Because the data model requires that all general entities be expanded, there will never be unexpanded entity reference information item children.

attributes

A set of attribute nodes constructed from the attribute information items appearing in the [attributes] property. This includes all of the “special” attributes (xml:lang, xml:space, xsi:type, etc.) but does not include namespace declarations (because they are not attributes).

Default and fixed attributes provided by XML Schema processing are added to the [attributes] and are therefore included in the data model attributes of an element.

namespaces

A set of namespace nodes constructed from the namespace information items appearing in the [in-scope namespaces] property. Implementations that do not support namespace nodes may simply preserve the relevant bindings in this property.

Implementations may ignore namespace information items for namespaces which are not known to be used. A namespace is known to be used if:

  • It appears in the expanded QName of the node-name of the element.

  • It appears in the expanded QName of the node-name of any of the element’s attributes.

  • It appears in the expanded QName of any values of type xs:QName that appear among the element’s children or the typed values of its attributes.

Note: applications may rely on namespaces that are not known to be used, for example when QNames are used in content and that content does not have a type of xs:QName Such applications may have difficulty processing data models where some namespaces have been ignored.

nilled

If the [validity] property exists on an information item and is “valid ” then if the [nil] property exists and is true, then the nilled property is “true ”. In all other cases, including all cases where schema validity assessment was not attempted or did not succeed, the nilled property is “false ”.

string-value

The string-value is calculated as follows:

  • If the element is empty: its string value is the zero length string.

  • If the element has a type of xs:untyped, a complex type with element-only content, or a complex type with mixed content: its string-value is the concatenation of the string-values of all its text node descendants in document order.

  • If the element has a simple type or a complex type with simple content: its string-value is the [schema normalized value] of the node.

If an implementation stores only the typed value of an element, it may use any valid lexical representation of the typed value for the string-value property.

typed-value

The typed-value is calculated as follows:

  • If the element is of type xs:untyped, its typed-value is its dm:string-value as an xs:untypedAtomic.

  • If the element has a complex type with empty content, its typed-value is the empty sequence.

  • If the element has a simple type or a complex type with simple content: its typed value is computed as described in 3.3.1.2 Typed Value Determination. The result is a sequence of zero or more atomic items. The relationship between the type-name, typed-value, and string-value of an element node is consistent with XML Schema validation.

    Note that in the case of dates and times, the timezone is preserved as described in 3.3.2 Dates and Times, and in the case of xs:QNames and xs:NOTATIONs, the prefix is preserved as described in 3.3.3 QNames and NOTATIONS.

  • If the element has a complex type with mixed content (including xs:anyType), its typed-value is its dm:string-value as an xs:untypedAtomic.

  • Otherwise, the element must be a complex type with element-only content. The typed-value of such an element is absent. Attempting to access this property with the dm:typed-value accessor always raises an error.

is-id

If the element has a complex type with element-only content, the is-id property is false. Otherwise, if the typed-value of the element consists of exactly one atomic item and that value is of type xs:ID, or a type derived from xs:ID, the is-id property is true, otherwise it is false.

Note:

This means that in the case of a type constructed by list from xs:ID, the ID is recognized provided that the list is of length one. A type constructed as a union involving xs:ID is recognized provided the actual value is of type xs:ID.

Note:

The element that is marked with the is-id property, and which will therefore be retrieved by the fn:id function, is the node whose typed value contains the xs:ID value. This node is a child of the element node that, according to XML Schema, is uniquely identified by this ID.

is-idrefs

If the element has a complex type with element-only content, the is-idrefs property is false. Otherwise, if any of the atomic items in the typed-value of the element is of type xs:IDREF or xs:IDREFS, or a type derived from one of those types, the is-idrefs property is true, otherwise it is false.

All other properties have values that are consistent with construction from an infoset.

I.3 Attribute nodes Information Items

The following attribute node properties are affected by PSVI properties.

string-value
  • The [schema normalized value] PSVI property if that exists.

  • Otherwise, the [normalized value] property.

If an implementation stores only the typed value of an attribute, it may use any valid lexical representation of the typed value for the string-value property.

schema-type

The schema-type is determined as described in 3.3.1.1 Element and Attribute Node Types.

typed-value

The typed-value is calculated as follows:

  • If the attribute is of type xs:untypedAtomic: its typed-value is its dm:string-value as an xs:untypedAtomic.

  • Otherwise, a sequence of zero or more atomic items as described in 3.3.1.2 Typed Value Determination. The relationship between the type-name, typed-value, and string-value of an attribute node is consistent with XML Schema validation.

is-id

If the attribute is named xml:id and its [attribute type] property does not have the value xs:ID or a type derived from xs:ID, then [xml:id] processing is performed. This will ensure that the value does have the type xs:ID and that it is properly normalized. If an error is encountered during xml:id processing, an implementation may raise a dynamic error. The is-id property is always true for attributes named xml:id.

Otherwise, if the typed-value of the attribute consists of exactly one atomic item and that value is of type xs:ID, or a type derived from xs:ID, the is-id property is true, otherwise it is false.

Note:

This means that in the case of a type constructed by list from xs:ID, the ID is recognized provided that the list is of length one. A type constructed as a union involving xs:ID is recognized provided the actual value is of type xs:ID.

is-idrefs

If any of the atomic items in the typed-value of the attribute is of type xs:IDREF or xs:IDREFS, or a type derived from one of those types, the is-idrefs property is true, otherwise it is false.

Note:

This rule means that a node whose type is constructed by list with an item type of xs:IDREF (or a type derived from xs:IDREF) may have the is-idrefs property, whether or not the list type is named xs:IDREFS or is derived from xs:IDREFS. Because union types are allowed, it also means that an element or attribute with the is-idrefs property can contain atomic items of type xs:IDREF alongside values of other types. A node has the is-idrefs property only if the typed value contains at least one atomic item that is an instance of xs:IDREF; it is not sufficient that the type annotation permits such values.

All other properties have values that are consistent with construction from an infoset.

Note: attributes from the XML Schema instance namespace, “http://www.w3.org/2001/XMLSchema-instance” (xsi:schemaLocation, xsi:type, etc.), appear as ordinary attributes in the data model.

I.4 Namespace nodes Information Items

Construction from a PSVI is identical to construction from the Infoset.

I.5 Processing instruction nodes Information Items

Construction from a PSVI is identical to construction from the Infoset.

I.6 Comment nodes Information Items

Construction from a PSVI is identical to construction from the Infoset.

I.7 Text nodes Information Items

For text nodes constructed from the [schema normalized value] of elements, content contains the value of the [schema normalized value].

Otherwise, construction from a PSVI is the same as construction from the Infoset except for the content property. When constructing the content property, [element content whitespace] is not used to test if whitespace is collapsed. Instead, if the resulting text node consists entirely of whitespace and the character information items used to construct this node have a parent and that parent is an element and its {content type} is not “mixed”, then the content of the text node is the zero-length string.

text nodes are allowed to be empty only if they have no parents; an empty text node will be discarded when its parent is constructed, if it has a parent.

J Infoset Mapping Summary (Non-Normative)

This section summarizes the infoset mapping for each kind of node.

J.1 Document nodes Information Items

A document node maps to a document information item. The mapping fails and produces no value if the document node contains text node children that do not consist entirely of white space or if the document node contains more than one element node child.

The following properties are specified by this mapping:

[children]

A list of information items obtained by processing each of the dm:children in order and mapping each to the appropriate information item(s).

[document element]

The element information item that is among the [children].

[unparsed entities]

An unordered set of unparsed entity information items constructed from the unparsed-entities.

Each unparsed entity maps to an unparsed entity information item. The following properties are specified by this mapping:

[name]

The name of the entity.

[system identifier]

The system identifier of the entity.

[public identifier]

The public identifier of the entity.

[declaration base URI]

Implementation defined. In many cases, the document-uri is the correct answer and implementations must use this value if they have no better information. Implementations that keep track of the original [declaration base URI] for entities should use that value.

The following properties of the unparsed entity information item have no value: [notation name], [notation].

The following properties of the document information item have no value: [notations][character encoding scheme][standalone][version][all declarations processed].

J.2 Element nodes Information Items

An element node maps to an element information item.

The following properties are specified by this mapping:

[namespace name]

The namespace name of the value of dm:node-name.

[local name]

The local part of the value of dm:node-name.

[prefix]

The prefix associated with the value of dm:node-name.

[children]

A list of information items obtained by processing each of the dm:children in order and mapping each to the appropriate information item(s).

[attributes]

An unordered set of information items obtained by processing each of the dm:attributes and mapping each to the appropriate information item(s).

[in-scope namespaces]

An unordered set of namespace information items constructed from the namespaces.

Each in-scope namespace maps to a namespace information item. The following properties are specified by this mapping:

[prefix]

The prefix associated with the namespace.

[namespace name]

The URI associated with the namespace.

[base URI]

The value of dm:base-uri.

[parent]
  • If this node is the root of the infoset mapping operation, unknown.

  • If this node has a parent, the information item that corresponds to the node returned by dm:parent.

  • Otherwise no value.

The following property has no value: [namespace attributes].

J.3 Attribute nodes Information Items

An attribute node maps to an attribute information item.

The following properties are specified by this mapping:

[namespace name]

The namespace name of the value of dm:node-name.

[local name]

The local part of the value of dm:node-name.

[prefix]

The prefix associated with the value of dm:node-name.

[normalized value]

The value of dm:string-value.

[owner element]
  • If this node has a parent, the information item that corresponds to the node returned by dm:parent.

  • Otherwise no value.

The following properties have no value: [specified][attribute type][references].

J.4 Namespace nodes Information Items

A namespace node maps to a namespace information item.

The following properties are specified by this mapping:

[prefix]

The prefix associated with the namespace.

[namespace name]

The value of dm:string-value.

J.5 Processing instruction nodes Information Items

An processing instruction node maps to a processing instruction information item.

The following properties are specified by this mapping:

[target]

The local part of the value of dm:node-name.

[content]

The value of dm:string-value.

[base URI]

The value of dm:base-uri.

[parent]
  • If this node is the root of the infoset mapping operation, unknown.

  • If this node has a parent, the information item that corresponds to the node returned by dm:parent.

  • Otherwise no value.

[notation]

No value.

J.6 Comment nodes Information Items

A comment node maps to a comment information item.

The following properties are specified by this mapping:

[content]

The value of the dm:string-value.

[parent]
  • If this node is the root of the infoset mapping operation, unknown.

  • If this node has a parent, the information item that corresponds to the node returned by dm:parent.

  • Otherwise no value.

J.7 Text nodes Information Items

A text node maps to a sequence of character information items.

Each character of the dm:string-value of the node is converted into a character information item as specified by this mapping:

[character code]

The Unicode code point value of the character.

[parent]
  • If this node is the root of the infoset mapping operation, unknown.

  • If this node has a parent, the information item that corresponds to the node returned by dm:parent.

  • Otherwise no value.

[element content whitespace]

Unknown.

This sequence of characters constitutes the infoset mapping.

\ No newline at end of file diff --git a/pr/1703/xpath-datamodel-40/xpath-datamodel-40.xml b/pr/1703/xpath-datamodel-40/xpath-datamodel-40.xml index 175a7beaa..93a0a6f6d 100644 --- a/pr/1703/xpath-datamodel-40/xpath-datamodel-40.xml +++ b/pr/1703/xpath-datamodel-40/xpath-datamodel-40.xml @@ -1001,7 +1001,7 @@ must equal the function’s arity.

function(item()) as item() is a subtype of function(xs:string) as item()

Map ItemsConstructors are added, and the single accessor function - is now an iterator over the key/value pairs in the map.Ordered maps are introduced.

A map item + is now an iterator over the key/value pairs in the map.Ordered maps are introduced.

A map item is an item that represents an ordered sequence of key/value pairs, in which the keys are unique. In other languages this is sometimes diff --git a/pr/1703/xpath-functions-40/Overview-diff.html b/pr/1703/xpath-functions-40/Overview-diff.html index d96db0c50..7fb013796 100644 --- a/pr/1703/xpath-functions-40/Overview-diff.html +++ b/pr/1703/xpath-functions-40/Overview-diff.html @@ -22,7 +22,7 @@

XPath and XQuery Functions and Operators 4.0

-

W3C Editor's Draft 14 January 2025

+

W3C Editor's Draft 15 January 2025

This version:
https://qt4cg.org/pr/1703/xpath-functions-40/
@@ -35729,7 +35729,7 @@

10.2.6 ·implementation-dependent·.

+

The order of entries in the returned map is ·implementation-dependent·.

Notes
@@ -40049,8 +40049,7 @@

13.2.2

Note:

-

It is not required that both maps have the same ordering property, - nor that the order of entries matches.

+

It is not required that the order of entries in the two maps should be the same.

  • @@ -48290,7 +48289,7 @@

    14.2.2 Additional ·implementation-defined· parser options are allowed.

    -
    Example:
    +
    Example:

    An implementation may provide keys for options to the tidy HTML parser, allowing a user to configure the behaviour of that parser.

    @@ -48796,7 +48795,7 @@

    14.3.2
    -
    Example: A JSON Text and its XML Representation
    +
    Example: A JSON Text and its XML Representation

    Consider the following JSON text:

    @@ -49066,7 +49065,7 @@ 

    14.3.4 1555  11 November 2024]

  • -

    An option is provided to retain the order of entries in maps.  [Issue 564 PR 1609 27 November 2024]

    +

    The order of entries in maps is retained.  [Issue 1651 PR 1703 14 January 2025]

  • @@ -49132,10 +49131,6 @@

    14.3.4 duplicates? as xs:string, - - retain-order? - as xs:boolean, - escape? as xs:boolean, @@ -49243,34 +49238,6 @@

    14.3.4 -

    retain-order?

    - - Determines whether maps resulting from parsing of JSON objects should retain the input - order. -
      -
    • -

      Type: xs:boolean

      -
    • -
    • -

      Default: false

      -
    • -
    - - - - false - Any maps resulting from parsing of JSON objects have the ordering - property set to undefined. - - - true - Any maps resulting from parsing of JSON objects have the ordering - property set to insertion, and the -
    entry orderDM retains the order - of entries in the input. -

    escape?

    @@ -49451,7 +49418,7 @@

    14.3.4 .

    If duplicate keys are encountered in a JSON object, they are handled as determined by the duplicates option defined above.

    -

    The order of entries is retained if the retain-order option is set to true.

    +

    The order of entries is retained.

  • A JSON array is transformed to an array whose members are the result of converting @@ -51289,7 +51256,7 @@

    14.4.3 -
    Example: A CSV with fixed-width rows
    +
    Example: A CSV with fixed-width rows

    For example, given the input:

    @@ -51309,7 +51276,7 @@ 

    14.4.3 -
    Example: A CSV with variable-width rows
    +
    Example: A CSV with variable-width rows

    It is common practice for all rows in a CSV to have the same number of columns, but this is not required.

    @@ -61634,7 +61601,7 @@

    17.1 Changes in 4.0  

    1. -

      Ordered maps are introduced.  [Issue 564 PR 1609 25 November 2024]

      +

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

    @@ -61832,7 +61799,7 @@

    17.3 [XQuery and XPath Data Model (XDM) 4.0]) defines three primitive operations on maps:

    • -

      dm:empty-map constructs an empty map with a given ordering property.

      +

      dm:empty-map constructs an empty map.

    • dm:map-put adds or replaces an entry in a map.

      @@ -61847,7 +61814,7 @@

      17.3 map:get and map:put much more efficiently). They do, however, provide a framework that allows @@ -62801,7 +62768,7 @@

      17.4.6 1171 PR 1182 7 May 2024]

    • -

      Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

      +

      Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    @@ -62920,7 +62887,7 @@

    17.4.7 Changes in 4.0  

    1. -

      Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

      +

      Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    @@ -63106,7 +63073,7 @@

    17.4.8 Changes in 4.0  

    1. -

      Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

      +

      Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    @@ -64319,8 +64286,7 @@

    17.4.14 Notes

    If the input is an empty sequence, the result is an empty map.

    -

    Except when ordering=sorted, - there is no requirement that the supplied key-value pairs should have the same or compatible +

    There is no requirement that the supplied key-value pairs should have the same or compatible types. The type of a map (for example map(xs:integer, xs:string)) is descriptive of the entries it currently contains, but is not a constraint on how the map may be combined with other maps.

    @@ -64750,7 +64716,7 @@

    17.4.17 Changes in 4.0  

    1. -

      Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

      +

      Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    @@ -64815,7 +64781,7 @@

    17.4.17 There is no requirement that the type of $key and $value be consistent with the types of any existing keys and values in the supplied map.

    -

    With an ordered map, you can force the new entry to go at the end of the sequence by calling +

    It is possible to force the new entry to go at the end of the sequence by calling map:remove before calling map:put.

    Examples
    @@ -64924,7 +64890,7 @@

    17.4.18 Changes in 4.0  

    1. -

      Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

      +

      Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    @@ -74294,7 +74260,7 @@

    20.5 20.2 Constructor functions for xs:QName and xs:NOTATION.

    -
    Example: Using a Constructor Function for a User-Defined Atomic Type
    +
    Example: Using a Constructor Function for a User-Defined Atomic Type

    Consider a situation where the static context contains an atomic type called hatSize defined in a schema whose target namespace is bound to the prefix eg. In such a case the following constructor function is available to users:

    @@ -79917,8 +79883,8 @@

    G.1 19.1.3 fn:type-of

  • -

    PR 1609 

    -

    An option is provided to retain the order of entries in maps.

    +

    PR 1703 

    +

    The order of entries in maps is retained.

    See 14.3.4 fn:parse-json

    Ordered maps are introduced.

    See 17.1 Ordering of Maps

    diff --git a/pr/1703/xpath-functions-40/Overview-diff.xml b/pr/1703/xpath-functions-40/Overview-diff.xml index 2b36622a1..df17cf77d 100644 --- a/pr/1703/xpath-functions-40/Overview-diff.xml +++ b/pr/1703/xpath-functions-40/Overview-diff.xml @@ -4,7 +4,7 @@ changed text, and deleted text.


    W3C

    XPath and XQuery Functions and Operators 4.0

    -

    W3C Editor's Draft 14 January 2025

    This version:
    https://qt4cg.org/pr/1703/xpath-functions-40/
    Latest version of XPath and XQuery Functions and Operators 4.0:
    +

    W3C Editor's Draft 15 January 2025

    This version:
    https://qt4cg.org/pr/1703/xpath-functions-40/
    Latest version of XPath and XQuery Functions and Operators 4.0:
    https://qt4cg.org/specifications/xpath-functions-40/
    Most recent Recommendation of XPath and XQuery Functions and Operators:
    https://www.w3.org/TR/2017/REC-xpath-functions-31-20170321/ @@ -6732,7 +6732,7 @@ else QName("", $value)

    If the requirement is to const for each in-scope namespace: the key of the entry is the namespace prefix or a zero-length string, and the corresponding value is the namespace URI.

    For namespace bindings that have a prefix, the key represents the prefix as an instance of xs:NCName. For the default namespace, which has no prefix, the key is - the zero-length string as an instance of xs:string.

    The ordering of the returned map is ·implementation-dependent·.

  • Notes

    The XML namespace is in scope for every element, so the result will always include an entry + the zero-length string as an instance of xs:string.

    The order of entries in the returned map is ·implementation-dependent·.

    Notes

    The XML namespace is in scope for every element, so the result will always include an entry with key "xml" and corresponding value http://www.w3.org/XML/1998/namespace.

    Examples
    Variables
    let $e := 
     <z:a xmlns="http://example.org/one" xmlns:z="http://example.org/two">
       <b xmlns=""/>
    @@ -7066,8 +7066,7 @@ declare function equal-strings(
                                xs:gMonthDay, or xs:gDay.

  • Neither $i1 nor $i2 has a timezone component.

  • Both $i1 and $i2 have a timezone component and the timezone components are equal.

  • All of the following conditions are true:

    1. $i1 is a map.

    2. $i2 is a map.

    3. Both maps have the same number of entries.

    4. For every entry in the first map, there is an entry in the second map that:

      1. has the ·same key· (note that the collation is not used when comparing keys), and

      2. has the same associated value (compared using the fn:deep-equal - function, recursively).

    Note:

    It is not required that both maps have the same ordering property, - nor that the order of entries matches.

  • All the following conditions are true:

    1. $i1 is an array.

    2. $i2 is an array.

    3. Both arrays have the same number of members (array:size($i1) eq + function, recursively).

  • Note:

    It is not required that the order of entries in the two maps should be the same.

  • All the following conditions are true:

    1. $i1 is an array.

    2. $i2 is an array.

    3. Both arrays have the same number of members (array:size($i1) eq array:size($i2)).

    4. Members in the same position of both arrays are deep-equal to each other: that is, every $p in 1 to array:size($i1) satisfies deep-equal($i1($p), $i2($p), $collation, $options).

  • All the following conditions are true:

    1. $i1 is a function item and is not a map or array.

    2. $i2 is a function item and is not a map or array.

    3. $i1 and $i2 have the same function identity. @@ -8857,7 +8856,7 @@ serialize( is an empty sequence.

  • 14.2.3 fn:parse-html

    Changes in 4.0  

    1. New in 4.0  [Issues 74 850 PRs 259 956 10 January 2023]

    Summary

    This function takes as input an HTML document represented as a string, and returns the document node at the root of an XDM tree representing the parsed document.

    Signature
    fn:parse-html(
    $htmlas (xs:string | xs:hexBinary | xs:base64Binary)?,
    $optionsas map(*)?:= { "method": "html", "html-version": 5 }
    ) as document-node(*:html)?
    Properties

    This function is ·nondeterministic·, ·context-independent·, and ·focus-independent·.

    Rules

    If $html is the empty sequence the function returns the empty sequence.

    The entries that may appear in the $options map are as follows:

    record(
    method?as xs:string,
    html-version?as (enum('LS') | xs:decimal),
    encoding?as xs:string?,
    include-template-content?as xs:boolean?
    )
    KeyMeaning

    method?

    @@ -8985,7 +8984,7 @@ serialize( (a) JSON numbers are not exactly representable as double-precision floating point, or (b) duplicate key values appear within a JSON object.

    The following example demonstrates the correspondence of a JSON text and the corresponding XML representation.

    -

    Consider the following JSON text:

    +

    Consider the following JSON text:

    14.3.4 fn:parse-json

    Changes in 4.0  

    1. The rules regarding use of non-XML characters in JSON texts have been relaxed.  [Issue 414 PR 546 25 July 2023]

    2. An option is provided to control how the JSON null value should be handled.  [Issue 960 PR 1028 20 February 2024]

    3. An option is provided to control how JSON numbers should be formatted.  [Issues 973 1037 PRs 975 1058 1246 12 March 2024]

    4. The default for the escape option has been changed to false. The 3.1 specification gave the default value as true, but this appears to have been an error, - since it was inconsistent with examples given in the specification and with tests in the test suite.  [Issue 1555  11 November 2024]

    5. An option is provided to retain the order of entries in maps.  [Issue 564 PR 1609 27 November 2024]

    Summary

    Parses a string supplied in the form of a JSON text, returning the results typically in the form + since it was inconsistent with examples given in the specification and with tests in the test suite.  [Issue 1555  11 November 2024]

  • The order of entries in maps is retained.  [Issue 1651 PR 1703 14 January 2025]

  • Summary

    Parses a string supplied in the form of a JSON text, returning the results typically in the form of a map or array.

    Signature
    fn:parse-json(
    $valueas xs:string?,
    $optionsas map(*)?:= {}
    ) as item()?
    Properties

    This function is ·deterministic·, ·context-independent·, and ·focus-independent·.

    Rules

    If the second argument is omitted or an empty sequence, the result is the same as calling the two-argument form with an empty map as the value of the $options argument.

    The first argument is a JSON text as defined in [RFC 7159], in the form of a string. The function parses this string to return an XDM value.

    If $value is the empty sequence, the function returns the empty sequence.

    Note:

    The result will also be an empty sequence if $value is the string "null".

    The $options argument can be used to control the way in which the parsing - takes place. The ·option parameter conventions· apply.

    The entries that may appear in the $options map are as follows:

    record(
    liberal?as xs:boolean,
    duplicates?as xs:string,
    retain-order?as xs:boolean,
    escape?as xs:boolean,
    fallback?as (fn(xs:string) as xs:anyAtomicType)?,
    null?as item()*,
    number-parser?as (fn(xs:untypedAtomic) as item()?)?
    )
    KeyValueMeaning

    liberal?

    Determines whether deviations from the syntax of RFC7159 are permitted.
    • Type: xs:boolean

    • Default: false

    false + takes place. The ·option parameter conventions· apply.

    The entries that may appear in the $options map are as follows:

    record(
    liberal?as xs:boolean,
    duplicates?as xs:string,
    escape?as xs:boolean,
    fallback?as (fn(xs:string) as xs:anyAtomicType)?,
    null?as item()*,
    number-parser?as (fn(xs:untypedAtomic) as item()?)?
    )
    each row is represented as an array of xs:string values.

    The first row of the CSV is returned in the same way as all the other rows. fn:csv-to-arrays does not distinguish between a header row and data rows, and returns all of them.

    KeyValueMeaning

    liberal?

    Determines whether deviations from the syntax of RFC7159 are permitted.
    • Type: xs:boolean

    • Default: false

    false The input must consist of an optional byte order mark (which is ignored) followed by a string that conforms to the grammar of JSON-text in [RFC 7159]. An error must be raised [err:FOJS0001] if the input does not conform to the grammar. @@ -9184,11 +9183,7 @@ serialize( If duplicate keys are present in a JSON object, all but the first of a set of duplicates are ignored.
    use-last If duplicate keys are present in a JSON object, all but the last of a set of duplicates are ignored. -

    retain-order?

    Determines whether maps resulting from parsing of JSON objects should retain the input order.
    • Type: xs:boolean

    • Default: false

    falseAny maps resulting from parsing of JSON objects have the ordering - property set to undefined.
    trueAny maps resulting from parsing of JSON objects have the ordering - property set to insertion, and the - entry orderDM retains the order - of entries in the input.

    escape?

    Determines whether special characters are represented in the XDM output in backslash-escaped form.
    • Type: xs:boolean

    • Default: false

    false +

    escape?

    Determines whether special characters are represented in the XDM output in backslash-escaped form.
    • Type: xs:boolean

    • Default: false

    false Any ·permitted character· in the input, whether or not it is represented in the input by means of an escape sequence, is represented as an unescaped character @@ -9266,7 +9261,7 @@ serialize( value by recursive application of these rules. For example, the JSON text { "x": 2, "y": 5 } is transformed to the value { "x": 2, "y": 5 }.

    If duplicate keys are encountered in a JSON object, they are handled - as determined by the duplicates option defined above.

    The order of entries is retained if the retain-order option is set to true.

  • A JSON array is transformed to an array whose members are the result of converting + as determined by the duplicates option defined above.

    The order of entries is retained.

  • A JSON array is transformed to an array whose members are the result of converting the corresponding member of the array by recursive application of these rules. For example, the JSON text [ "a", "b", null ] is transformed (by default) to the value [ "a", "b", () ].

  • A JSON string is converted to an xs:string value. @@ -9759,7 +9754,7 @@ return pin($data)??languages[. = 'German'] ! label(.)?path()[1]

  • $books-by-isbn("0470192747") returns the book element with the given ISBN. The fact that a map is a function item allows it to be passed as an argument to higher-order functions that expect a function item as one of their arguments.

    -

    17.1 Ordering of Maps

    Changes in 4.0  

    1. Ordered maps are introduced.  [Issue 564 PR 1609 25 November 2024]

    In 4.0, the entries in a map are ordered. The entry orderDM of a map +

    17.1 Ordering of Maps

    Changes in 4.0  

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

    In 4.0, the entries in a map are ordered. The entry orderDM of a map is referred to as entry order.

    The entry order of the entries in a map is defined by the function or expression that creates the map, and affects the result of functions and expressions that process multiple entries in a map, for example the function map:keys @@ -12148,12 +12143,12 @@ return $result?output//body

  • Type: xs:anyAtomicType

  • value

    The value corresponding to the key.

    • Type: item()*

    *

    The record type is extensible (it may contain additional fields beyond those listed).

    -

    17.3 Formal Specification of Maps

    The XDM data model ([XQuery and XPath Data Model (XDM) 4.0]) defines three primitive operations on maps:

    • dm:empty-map constructs an empty map with a given ordering property.

    • dm:map-put adds or replaces an entry in a map.

    • dm:iterate-map applies a supplied function to every entry in a map.

    The functions in this section are all specified by means of equivalent expressions that either call +

    17.3 Formal Specification of Maps

    The XDM data model ([XQuery and XPath Data Model (XDM) 4.0]) defines three primitive operations on maps:

    • dm:empty-map constructs an empty map.

    • dm:map-put adds or replaces an entry in a map.

    • dm:iterate-map applies a supplied function to every entry in a map.

    The functions in this section are all specified by means of equivalent expressions that either call these primitives directly, or invoke other functions that rely on these primitives. The specifications avoid relying on XPath language constructs that manipulate maps, such as map constructor syntax, lookup expressions, or FLWOR expressions. This is done to allow these language constructs to be specified by reference to this function library, without risk of circularity.

    There is one exception to this rule: for convenience, the notation {} is used to represent - an empty map, in preference to a call on dm:empty-map(ordering := 'undefined').

    The formal equivalents are not intended to provide a realistic way of implementating the + an empty map, in preference to a call on dm:empty-map().

    The formal equivalents are not intended to provide a realistic way of implementating the functions (in particular, any real implementation might be expected to implement map:get and map:put much more efficiently). They do, however, provide a framework that allows the correctness of a practical implementation to be verified.

    Editorial note 
    TODO: as yet there is no formal equivalent for map:find().
    @@ -12283,7 +12278,7 @@ map:merge(( ))

    The map:merge function can be used to construct a map with a variable number of entries, for example:

     map:merge(//book ! map:entry(isbn, .))
    Examples
    ExpressionResult
    map:entry("M", "Monday")
    { "M": "Monday" }
    -

    17.4.6 map:filter

    Changes in 4.0  

    1. New in 4.0

    2. The $predicate callback function may return an empty sequence (meaning false).  [Issue 1171 PR 1182 7 May 2024]

    3. Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

    Summary

    Selects entries from a map, returning a new map.

    Signature
    map:filter(
    $mapas map(*),
    $predicateas fn($key as xs:anyAtomicType, $value as item()*) as xs:boolean?
    ) as map(*)
    Properties

    This function is ·context-independent·, and ·focus-independent·.

    Rules

    The function map:filter takes any ·map· as its $map argument and applies the supplied function +

    17.4.6 map:filter

    Changes in 4.0  

    1. New in 4.0

    2. The $predicate callback function may return an empty sequence (meaning false).  [Issue 1171 PR 1182 7 May 2024]

    3. Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    Summary

    Selects entries from a map, returning a new map.

    Signature
    map:filter(
    $mapas map(*),
    $predicateas fn($key as xs:anyAtomicType, $value as item()*) as xs:boolean?
    ) as map(*)
    Properties

    This function is ·context-independent·, and ·focus-independent·.

    Rules

    The function map:filter takes any ·map· as its $map argument and applies the supplied function to each entry in the map; the result is a new map containing those entries for which the function returns true. A return value of () from the predicate is treated as false.

    The function supplied as $predicate takes two arguments. It is called @@ -12303,7 +12298,7 @@ map:merge(//book ! map:entry(isbn, .))

    Example 5: "Thursday", 6: "Friday", 7: "Saturday" }, fn($k, $v) { $v = ("Saturday", "Sunday") } )
    Result:
    { 1: "Sunday", 7: "Saturday" }

    -

    17.4.7 map:find

    Changes in 4.0  

    1. Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

    Summary

    Searches the supplied input sequence and any contained maps and arrays for a map entry with the supplied key, +

    17.4.7 map:find

    Changes in 4.0  

    1. Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    Summary

    Searches the supplied input sequence and any contained maps and arrays for a map entry with the supplied key, and returns the corresponding values.

    Signature
    map:find(
    $inputas item()*,
    $keyas xs:anyAtomicType
    ) as array(*)
    Properties

    This function is ·deterministic·, ·context-independent·, and ·focus-independent·.

    Rules

    The function map:find searches the sequence supplied as $input looking for map entries whose key is the ·same key· as $key. The associated value in any such map entry (each being in general a sequence) @@ -12326,7 +12321,7 @@ map:merge(//book ! map:entry(isbn, .))

    Example [ { "name": "engine", "id": "YW678", "parts": [] } ], [] ]
    -

    17.4.8 map:for-each

    Changes in 4.0  

    1. Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

    Summary

    Applies a supplied function to every entry in a map, returning the +

    17.4.8 map:for-each

    Changes in 4.0  

    1. Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    Summary

    Applies a supplied function to every entry in a map, returning the sequence concatenationXP of the results.

    Signature
    map:for-each(
    $mapas map(*),
    $actionas fn($key as xs:anyAtomicType, $value as item()*) as item()*
    ) as item()*
    Properties

    This function is ·deterministic·, ·context-independent·, and ·focus-independent·.

    Rules

    The function map:for-each takes any ·map· as its $map argument and applies the supplied function to each entry in the map, in entry orderDM; the result is the sequence concatenationXP @@ -12558,8 +12553,7 @@ return fold-left($maps, dm:empty-map($options?ordering otherwise "undefined"), in the input sequence.

    • Type: (fn($existing-value as item()*, $new-value as item()*) as item()*)?

    • Default: fn:op(',')

    Formal Equivalent

    The effect of the function is equivalent to the result of the following XPath expression.

    map:build($input, map:get(?, 'key'), map:get(?, 'value'), $combine)
    Error Conditions

    The function can be made to fail with a dynamic error in the event that duplicate keys are present in the input sequence by supplying a $combine - function that invokes the fn:error function.

    Notes

    If the input is an empty sequence, the result is an empty map.

    Except when ordering=sorted, - there is no requirement that the supplied key-value pairs should have the same or compatible + function that invokes the fn:error function.

    Notes

    If the input is an empty sequence, the result is an empty map.

    There is no requirement that the supplied key-value pairs should have the same or compatible types. The type of a map (for example map(xs:integer, xs:string)) is descriptive of the entries it currently contains, but is not a constraint on how the map may be combined with other maps.

    Examples
    - - - - @@ -48996,34 +48991,6 @@

    14.3.4 -

    retain-order?

    - -

    - - - - - - - - -
    Variables
    let $week := {
    @@ -12633,7 +12627,7 @@ map:of-pairs((
              and the other (with key "value") holding the value.

    Formal Equivalent

    The effect of the function is equivalent to the result of the following XPath expression.

    map:for-each($map, map:pair#2)
    Examples
    Expression:
    map:pairs(
       { 1: "Y", 2: "N" }
     )
    Result:
    ({ "key": 1, "value": "Y" }, { "key": 2, "value": "N" })
    -

    17.4.17 map:put

    Changes in 4.0  

    1. Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

    Summary

    Returns a map containing all the contents of the supplied map, but with an additional entry, which replaces +

    17.4.17 map:put

    Changes in 4.0  

    1. Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    Summary

    Returns a map containing all the contents of the supplied map, but with an additional entry, which replaces any existing entry for the same key.

    Signature
    map:put(
    $mapas map(*),
    $keyas xs:anyAtomicType,
    $valueas item()*
    ) as map(*)
    Properties

    This function is ·deterministic·, ·context-independent·, and ·focus-independent·.

    Rules

    The function map:put returns a ·map· that contains all entries from the supplied $map, with the exception of any entry whose key is the ·same key· as $key, together with a new entry whose key is $key and whose associated value is $value.

    The entry orderDM @@ -12642,7 +12636,7 @@ map:of-pairs(( then the new value replaces the old value and the position of the entry is not changed; otherwise, the new entry is added after all existing entries.

    Formal Equivalent

    The function is defined as follows, making use of primitive constructors and accessors defined in [XQuery and XPath Data Model (XDM) 4.0].

    dm:map-put($map, $key, $value)
    Notes

    There is no requirement that the type of $key and $value be consistent with the types - of any existing keys and values in the supplied map.

    With an ordered map, you can force the new entry to go at the end of the sequence by calling + of any existing keys and values in the supplied map.

    It is possible to force the new entry to go at the end of the sequence by calling map:remove before calling map:put.

    Examples
    Variables
    let $week := {
       0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch",
       4: "Donnerstag", 5: "Freitag", 6: "Samstag"
    @@ -12654,7 +12648,7 @@ map:of-pairs((
       => map:put("red", -1) 
       => map:keys()
    Result:
    "red", "green", "blue"

    (Changing the value for an existing key does not change the order of the keys.)

    -

    17.4.18 map:remove

    Changes in 4.0  

    1. Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

    Summary

    Returns a map containing all the entries from a supplied map, except those having a specified key.

    Signature
    map:remove(
    $mapas map(*),
    $keysas xs:anyAtomicType*
    ) as map(*)
    Properties

    This function is ·deterministic·, ·context-independent·, and ·focus-independent·.

    Rules

    The function map:remove returns a ·map· containing all the entries in $map except for any entry whose key is +

    17.4.18 map:remove

    Changes in 4.0  

    1. Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    Summary

    Returns a map containing all the entries from a supplied map, except those having a specified key.

    Signature
    map:remove(
    $mapas map(*),
    $keysas xs:anyAtomicType*
    ) as map(*)
    Properties

    This function is ·deterministic·, ·context-independent·, and ·focus-independent·.

    Rules

    The function map:remove returns a ·map· containing all the entries in $map except for any entry whose key is the ·same key· as an item in $keys.

    No failure occurs if an item in $keys does not correspond to any entry in $map; that key value is simply ignored.

    The relative position of retained entries in the result map @@ -14073,7 +14067,7 @@ There is no constructor function for xs:NOTATION. Constructors are union types defined in a schema.

    Special rules apply to constructor functions for namespace-sensitive types, that is, atomic types derived from xs:QName and xs:NOTATION, list types that have a namespace-sensitive item type, and union types that have a namespace-sensitive member type. See 20.2 Constructor functions for xs:QName and xs:NOTATION.

    In the case of an atomic type A, the return type of the function is A?, reflecting the fact that the result will be an empty sequence if the input is an empty sequence. For a union or list type, @@ -16323,7 +16317,7 @@ currently, Version 9.0.0. in terms of XSD 1.1 canonical mappings, since the XSD 1.1 rules deliver exactly the same result as the XPath 3.1 rules.

    See 21.1.2.3 Casting xs:duration values to xs:string

  • PR 1455 

    Numbers now retain their original lexical form, except for - any changes needed to satisfy JSON syntax rules (for example, stripping leading zero digits).

    See 14.3.7 fn:xml-to-json

  • PR 1481 

    The function has been extended to handle other Gregorian types such as xs:gYearMonth.

    See 9.5.1 fn:year-from-dateTime

    See 9.5.2 fn:month-from-dateTime

    The function has been extended to handle other Gregorian types such as xs:gMonthDay.

    See 9.5.3 fn:day-from-dateTime

    The function has been extended to handle other types including xs:time.

    See 9.5.4 fn:hours-from-dateTime

    See 9.5.5 fn:minutes-from-dateTime

    The function has been extended to handle other types such as xs:gYearMonth.

    See 9.5.7 fn:timezone-from-dateTime

  • PR 1504 

    New in 4.0

    See 13.1.11 fn:sequence-join

    Optional $separator added.

    See 18.2.17 array:join

  • PR 1523 

    New in 4.0

    See 19.1.2 fn:schema-type

    See 19.1.4 fn:atomic-type-annotation

    See 19.1.5 fn:node-type-annotation

  • PR 1545 

    New in 4.0

    See 9.6.4 fn:civil-timezone

  • PR 1570 

    New in 4.0

    See 19.1.3 fn:type-of

  • PR 1609 

    An option is provided to retain the order of entries in maps.

    See 14.3.4 fn:parse-json

    Ordered maps are introduced.

    See 17.1 Ordering of Maps

    Enhanced to allow for ordered maps.

    See 17.4.6 map:filter

    See 17.4.7 map:find

    See 17.4.8 map:for-each

    See 17.4.17 map:put

    See 17.4.18 map:remove

  • + any changes needed to satisfy JSON syntax rules (for example, stripping leading zero digits).

    See 14.3.7 fn:xml-to-json

  • PR 1481 

    The function has been extended to handle other Gregorian types such as xs:gYearMonth.

    See 9.5.1 fn:year-from-dateTime

    See 9.5.2 fn:month-from-dateTime

    The function has been extended to handle other Gregorian types such as xs:gMonthDay.

    See 9.5.3 fn:day-from-dateTime

    The function has been extended to handle other types including xs:time.

    See 9.5.4 fn:hours-from-dateTime

    See 9.5.5 fn:minutes-from-dateTime

    The function has been extended to handle other types such as xs:gYearMonth.

    See 9.5.7 fn:timezone-from-dateTime

  • PR 1504 

    New in 4.0

    See 13.1.11 fn:sequence-join

    Optional $separator added.

    See 18.2.17 array:join

  • PR 1523 

    New in 4.0

    See 19.1.2 fn:schema-type

    See 19.1.4 fn:atomic-type-annotation

    See 19.1.5 fn:node-type-annotation

  • PR 1545 

    New in 4.0

    See 9.6.4 fn:civil-timezone

  • PR 1570 

    New in 4.0

    See 19.1.3 fn:type-of

  • PR 1703 

    The order of entries in maps is retained.

    See 14.3.4 fn:parse-json

    Ordered maps are introduced.

    See 17.1 Ordering of Maps

    Enhanced to allow for ordered maps.

    See 17.4.6 map:filter

    See 17.4.7 map:find

    See 17.4.8 map:for-each

    See 17.4.17 map:put

    See 17.4.18 map:remove

  • G.2 Changes to Casts and Constructor Functions

    1. The keyword for the argument has changed from arg to value.

    2. The argument is now optional, and defaults to the context value (which is atomized if necessary). This change aligns constructor functions such as xs:string, xs:boolean, and xs:numeric with fn:string, fn:boolean, diff --git a/pr/1703/xpath-functions-40/Overview.html b/pr/1703/xpath-functions-40/Overview.html index 20dfe906d..c8ae9b378 100644 --- a/pr/1703/xpath-functions-40/Overview.html +++ b/pr/1703/xpath-functions-40/Overview.html @@ -13,7 +13,7 @@

      XPath and XQuery Functions and Operators 4.0

      -

      W3C Editor's Draft 14 January 2025

      +

      W3C Editor's Draft 15 January 2025

      This version:
      https://qt4cg.org/pr/1703/xpath-functions-40/
      @@ -35549,7 +35549,7 @@

      10.2.6 ·implementation-dependent·.

      +

      The order of entries in the returned map is ·implementation-dependent·.

      Notes
      @@ -39846,8 +39846,7 @@

      13.2.2

      Note:

      -

      It is not required that both maps have the same ordering property, - nor that the order of entries matches.

      +

      It is not required that the order of entries in the two maps should be the same.

  • @@ -48043,7 +48042,7 @@

    14.2.2 Additional ·implementation-defined· parser options are allowed.

    -
    Example:
    +
    Example:

    An implementation may provide keys for options to the tidy HTML parser, allowing a user to configure the behaviour of that parser.

    @@ -48549,7 +48548,7 @@

    14.3.2
    -
    Example: A JSON Text and its XML Representation
    +
    Example: A JSON Text and its XML Representation

    Consider the following JSON text:

    @@ -48819,7 +48818,7 @@ 

    14.3.4 1555  11 November 2024]

  • -

    An option is provided to retain the order of entries in maps.  [Issue 564 PR 1609 27 November 2024]

    +

    The order of entries in maps is retained.  [Issue 1651 PR 1703 14 January 2025]

  • @@ -48885,10 +48884,6 @@

    14.3.4 duplicates?

    as xs:string,
    retain-order?as xs:boolean,
    escape? as xs:boolean,Determines whether maps resulting from parsing of JSON objects should retain the input - order. -
      -
    • -

      Type: xs:boolean

      -
    • -
    • -

      Default: false

      -
    • -
    -
    falseAny maps resulting from parsing of JSON objects have the ordering - property set to undefined.
    trueAny maps resulting from parsing of JSON objects have the ordering - property set to insertion, and the - entry orderDM retains the order - of entries in the input.

    escape?

    @@ -49204,7 +49171,7 @@

    14.3.4 .

    If duplicate keys are encountered in a JSON object, they are handled as determined by the duplicates option defined above.

    -

    The order of entries is retained if the retain-order option is set to true.

    +

    The order of entries is retained.

  • A JSON array is transformed to an array whose members are the result of converting @@ -51034,7 +51001,7 @@

    14.4.3 -
    Example: A CSV with fixed-width rows
    +
    Example: A CSV with fixed-width rows

    For example, given the input:

    @@ -51054,7 +51021,7 @@ 

    14.4.3 -
    Example: A CSV with variable-width rows
    +
    Example: A CSV with variable-width rows

    It is common practice for all rows in a CSV to have the same number of columns, but this is not required.

    @@ -61342,7 +61309,7 @@

    17.1 Changes in 4.0  

    1. -

      Ordered maps are introduced.  [Issue 564 PR 1609 25 November 2024]

      +

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

    @@ -61532,7 +61499,7 @@

    17.3 [XQuery and XPath Data Model (XDM) 4.0]) defines three primitive operations on maps:

    • -

      dm:empty-map constructs an empty map with a given ordering property.

      +

      dm:empty-map constructs an empty map.

    • dm:map-put adds or replaces an entry in a map.

      @@ -61547,7 +61514,7 @@

      17.3 map:get and map:put much more efficiently). They do, however, provide a framework that allows @@ -62496,7 +62463,7 @@

      17.4.6 1171 PR 1182 7 May 2024]

    • -

      Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

      +

      Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    @@ -62614,7 +62581,7 @@

    17.4.7 Changes in 4.0  

    1. -

      Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

      +

      Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    @@ -62800,7 +62767,7 @@

    17.4.8 Changes in 4.0  

    1. -

      Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

      +

      Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    @@ -64010,8 +63977,7 @@

    17.4.14 Notes

    If the input is an empty sequence, the result is an empty map.

    -

    Except when ordering=sorted, - there is no requirement that the supplied key-value pairs should have the same or compatible +

    There is no requirement that the supplied key-value pairs should have the same or compatible types. The type of a map (for example map(xs:integer, xs:string)) is descriptive of the entries it currently contains, but is not a constraint on how the map may be combined with other maps.

    @@ -64438,7 +64404,7 @@

    17.4.17 Changes in 4.0  

    1. -

      Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

      +

      Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    @@ -64503,7 +64469,7 @@

    17.4.17 There is no requirement that the type of $key and $value be consistent with the types of any existing keys and values in the supplied map.

    -

    With an ordered map, you can force the new entry to go at the end of the sequence by calling +

    It is possible to force the new entry to go at the end of the sequence by calling map:remove before calling map:put.

    Examples
    @@ -64612,7 +64578,7 @@

    17.4.18 Changes in 4.0  

    1. -

      Enhanced to allow for ordered maps.  [Issue 564 PR 1609 27 November 2024]

      +

      Enhanced to allow for ordered maps.  [Issue 1651 PR 1703 14 January 2025]

    @@ -73931,7 +73897,7 @@

    20.5 20.2 Constructor functions for xs:QName and xs:NOTATION.

    -
    Example: Using a Constructor Function for a User-Defined Atomic Type
    +
    Example: Using a Constructor Function for a User-Defined Atomic Type

    Consider a situation where the static context contains an atomic type called hatSize defined in a schema whose target namespace is bound to the prefix eg. In such a case the following constructor function is available to users:

    @@ -79531,8 +79497,8 @@

    G.1 19.1.3 fn:type-of

  • -

    PR 1609 

    -

    An option is provided to retain the order of entries in maps.

    +

    PR 1703 

    +

    The order of entries in maps is retained.

    See 14.3.4 fn:parse-json

    Ordered maps are introduced.

    See 17.1 Ordering of Maps

    diff --git a/pr/1703/xpath-functions-40/Overview.xml b/pr/1703/xpath-functions-40/Overview.xml index a1d232fdf..584ec02e6 100644 --- a/pr/1703/xpath-functions-40/Overview.xml +++ b/pr/1703/xpath-functions-40/Overview.xml @@ -1,6 +1,6 @@ XPath and XQuery Functions and Operators 4.0 \ No newline at end of file +

    D Glossary (Non-Normative)

    atomic item

    An atomic item is a pair (T, D) where T (the ·type annotation·) is an atomic type, and D (the ·datum·) is a point in the value space of T.

    capturing sub-expression

    A left parenthesis is recognized as a capturing left parenthesis provided it is not immediately followed by ?: (see below), is not within a character group (square brackets), and is not escaped with a backslash. The sub-expression enclosed by a capturing left parenthesis and its matching right parenthesis is referred to as a capturing sub-expression.

    character

    A character is an instance of the CharXML production of [Extensible Markup Language (XML) 1.0 (Fifth Edition)].

    codepoint

    A codepoint is an integer assigned to a ·character· by the Unicode consortium, or reserved for future assignment to a character.

    collation

    A collation is an algorithm that determines, for any two given strings S1 and S2, whether S1 is less than, equal to, or greater than S2. In this specification, a collation is identified by an absolute URI.

    context-dependent

    A function definitionXP may have the property of being context-dependent: the result of such a function depends on the values of properties in the static and dynamic evaluation context of the caller as well as on the actual supplied arguments (if any). A function definition may be context-dependent for some arities in its arity range, and context-independent for others: for example fn:name#0 is context-dependent while fn:name#1 is context-independent.

    context-independent

    A function definitionXP that is not ·context-dependent· is called context-independent.

    CSV

    The term comma separated values or CSV refers to a wide variety of plain-text tabular data formats with fields and records separated by standard character delimiters (often, but not invariably, commas).

    date formatting function

    The three functions fn:format-dateTime, fn:format-date, and fn:format-time are referred to collectively as the date formatting functions.

    datum

    The datum of an ·atomic item· is a point in the value space of its type, which is also a point in the value space of the primitive type from which that type is derived.

    deterministic

    A function that is guaranteed to produce ·identical· results from repeated calls within a single ·execution scope· if the explicit and ·implicit· arguments are identical is referred to as deterministic.

    digit family

    The decimal digit family of a decimal format is the sequence of ten digits with consecutive Unicode ·codepoints· starting with the character that is the value of the zero-digitXP31 property.

    execution scope

    An execution scope is a sequence of calls to the function library during which certain aspects of the state are required to remain invariant. For example, two calls to fn:current-dateTime within the same execution scope will return the same result. The execution scope is defined by the host language that invokes the function library.

    expanded-QName

    An expanded-QName is a value in the value space of the xs:QName datatype as defined in the XDM data model (see [XQuery and XPath Data Model (XDM) 4.0]): that is, a triple containing namespace prefix (optional), namespace URI (optional), and local name. Two expanded QNames are equal if the namespace URIs are the same (or both absent) and the local names are the same. The prefix plays no part in the comparison, but is used only if the expanded QName needs to be converted back to a string.

    focus-dependent

    A function is focus-dependent if its result depends on the focusXP31 (that is, the context item, position, or size) of the caller.

    focus-dependent

    A function that is not ·focus-dependent· is called focus-independent.

    Gregorian

    The eight primitive types xs:dateTime, xs:date, xs:time, xs:gYearMonth, xs:gYear, xs:gMonthDay, xs:gMonth, xs:gDay are referred to collectively as the Gregorian types.

    higher-order

    Functions that accept functions among their arguments, or that return functions in their result, are described in this specification as higher-order functions.

    identical

    Two values $V1 and $V2 are defined to be identical if they contain the same number of items and the items are pairwise identical. Two items are identical if and only if one of the following conditions applies:

    implementation-defined

    Where behavior is described as implementation-defined, variations between processors are permitted, but a conformant implementation must document the choices it has made.

    implementation-dependent

    Where behavior is described as implementation-dependent, variations between processors are permitted, and conformant implementations are not required to document the choices they have made.

    key-value pair map

    A key-value pair map is a map containing two entries, one (with the key "key") containing the key part of a key value pair, the other (with the key "value") containing the value part of a key value pair.

    map

    A map consists of a setsequence of entries, also known as key-value pairs. Each entry comprises a key which is an arbitrary atomic item, and an arbitrary sequence called the associated value.

    nondeterministic

    A function that is not ·deterministic· is referred to as nondeterministic.

    nondeterministic with respect to ordering

    Some functions (such as fn:distinct-values, fn:unordered, map:keys, and map:for-each) produce results in an ·implementation-defined· or ·implementation-dependent· order. In such cases two calls with the same arguments are not guaranteed to produce the results in the same order. These functions are said to be nondeterministic with respect to ordering.

    optional digit character

    The optional digit character is the character that is the value of the digitXP31 property.

    option parameter conventions

    Functions that take an options parameter adopt common conventions on how the options are used. These are referred to as the option parameter conventions. These rules apply only to functions that explicitly refer to them.

    permitted character

    A permitted character is one within the repertoire accepted by the implementation.

    picture string

    The formatting of a number is controlled by a picture string. The picture string is a sequence of ·characters·, in which the characters assigned to the properties decimal-separatorXP31 , exponent-separatorXP31, grouping-separatorXP31, digitXP31, and pattern-separatorXP31 and the members of the ·decimal digit family·, are classified as active characters, and all other characters (including the values of the properties percentXP31 and per-milleXP31) are classified as passive characters.

    primitive type

    A primitive type is one of the 19 primitive atomic types defined in Section 3.2 Primitive datatypesXS2 of [XML Schema Part 2: Datatypes Second Edition], or the type xs:untypedAtomic defined in [XQuery and XPath Data Model (XDM) 4.0].

    same key

    Within a map, no two entries have the same key. Two atomic items K1 and K2 are the same key for this purpose if the function call fn:atomic-equal($K1, $K2) returns true.

    singleton map

    A singleton map is a map containing a single entry.

    string

    A string is a sequence of zero or more ·characters·, or equivalently, a value in the value space of the xs:string datatype.

    type annotation

    The type annotation of an atomic item is the most specific atomic type that it is an instance of (it is also an instance of every type from which that type is derived).

    Unicode codepoint collation

    The collation URI http://www.w3.org/2005/xpath-functions/collation/codepoint identifies a collation which must be recognized by every implementation: it is referred to as the Unicode codepoint collation (not to be confused with the Unicode collation algorithm).

    URI

    Within this specification, the term URI refers to Universal Resource Identifiers as defined in [RFC 3986] and extended in [RFC 3987] with a new name IRI. The term URI Reference, unless otherwise stated, refers to a string in the lexical space of the xs:anyURI datatype as defined in [XML Schema Part 2: Datatypes Second Edition].

    variadic

    The function fn:concat is defined to be variadic: it accepts any number of arguments. No other function has this property.

    E Other Functions (Non-Normative)

    This Appendix describes some sources of functions that fall outside the scope of the function library defined in this specification. It includes both function specifications and function implementations. Inclusion of a function in this appendix does not constitute any kind of recommendation or endorsement; neither is omission from this appendix to be construed negatively. This Appendix does not attempt to give any information about licensing arrangements for these function specifications or implementations.

    E.1 XPath Functions Defined in Other W3C Recommendations

    A number of W3C Recommendations make use of XPath, and in some cases such Recommmendations define additional functions to be made available when XPath is used in a specific host language.

    E.1.1 Functions Defined in XSLT

    The various versions of XSLT have all included additional functions intended to be available only when XPath is used within XSLT, and not in other host language environments. Some of these functions were originally defined in XSLT, and subsequently migrated into the core function library defined in this specification.

    Generally, the reason that functions have been defined in XSLT rather than in the core library has been that they required additional static or dynamic context information.

    XSLT-defined functions share the core namespace http://www.w3.org/2005/xpath-functions (but in XPath 1.0 and XSLT 1.0, no namespace was defined for these functions).

    The conformance rules for XSLT 4.0 require implementations to support either XPath 3.0 or XPath 3.1. Some of the new functions in XPath 3.1, however, must be supported by all XSLT 4.0 implementations whether or not they implement other parts of XPath 3.1.

    The following table lists all functions that have been defined in XSLT 1.0, 2.0, or 3.0, and summarizes their status.

    Function nameAvailability
    fn:accumulator-afterXSLT 3.0 only
    fn:accumulator-beforeXSLT 3.0 only
    fn:available-system-propertiesXSLT 3.0 only
    fn:collation-keyCommon to XSLT 3.0 and XPath 3.1
    fn:copy-ofXSLT 3.0 only
    fn:currentXSLT 1.0, 2.0, and 3.0
    fn:current-groupXSLT 2.0 and 3.0
    fn:current-grouping-keyXSLT 2.0 and 3.0
    fn:current-merge-groupXSLT 3.0 only
    fn:current-merge-keyXSLT 3.0 only
    fn:current-output-uriXSLT 3.0 only
    fn:documentXSLT 1.0, 2.0, and 3.0
    fn:element-availableXSLT 1.0, 2.0, and 3.0
    fn:format-dateXSLT 2.0; migrated to XPath 3.0 and 3.1
    fn:format-dateTimeXSLT 2.0; migrated to XPath 3.0 and 3.1
    fn:format-numberXSLT 1.0 and 2.0; migrated to XPath 3.0 and 3.1
    fn:format-timeXSLT 2.0; migrated to XPath 3.0 and 3.1
    fn:function-availableXSLT 1.0, 2.0, and 3.0
    fn:generate-idXSLT 1.0 and 2.0; migrated to XPath 3.0 and 3.1
    fn:json-to-xmlCommon to XSLT 3.0 and XPath 3.1
    fn:keyXSLT 1.0, 2.0, and 3.0
    fn:regex-groupXSLT 2.0 and 3.0
    fn:snapshotXSLT 3.0 only
    fn:stream-availableXSLT 3.0 only
    fn:system-propertyXSLT 1.0, 2.0, and 3.0
    fn:type-availableXSLT 2.0 and 3.0
    fn:unparsed-entity-public-idXSLT 2.0 and 3.0
    fn:unparsed-entity-uriXSLT 1.0, 2.0, and 3.0
    fn:unparsed-textXSLT 2.0; migrated to XPath 3.0 and 3.1
    fn:xml-to-jsonCommon to XSLT 3.0 and XPath 3.1
    map:containsCommon to XSLT 3.0 and XPath 3.1
    map:entryCommon to XSLT 3.0 and XPath 3.1
    map:findCommon to XSLT 3.0 and XPath 3.1
    map:for-eachCommon to XSLT 3.0 and XPath 3.1
    map:getCommon to XSLT 3.0 and XPath 3.1
    map:keysCommon to XSLT 3.0 and XPath 3.1
    map:mergeCommon to XSLT 3.0 and XPath 3.1
    map:putCommon to XSLT 3.0 and XPath 3.1
    map:removeCommon to XSLT 3.0 and XPath 3.1
    map:sizeCommon to XSLT 3.0 and XPath 3.1

    E.1.2 Functions Defined in XForms

    XForms 1.1 is based on XPath 1.0. It adds the following functions to the set defined in XPath 1.0, using the same namespace:

    boolean-from-string, is-card-number, avg, min, max, count-non-empty, index, power, random, compare, if, property, digest, hmac, local-date, local-dateTime, now, days-from-date, days-to-date, seconds-from-dateTime, seconds-to-dateTime, adjust-dateTime-to-timezone, seconds, months, instance, current, id, context, choose, event.

    XForms 2.0 was first published as a W3C Working Draft, and subsequently as a W3C Community Group specification. These draft specifications do not include any additional functions beyond those in the core XPath specification.

    E.1.3 Function Defined in XQuery Update 1.0

    The XQuery Update 1.0 specification defines one additional function in the core namespace http://www.w3.org/2005/xpath-functions, namely fn:put. This function can be used to write a document to external storage. It is thus unusual in that it has side-effects; the XQuery Update 1.0 specification defines semantics for updating expressions including this function.

    Although XQuery Update 1.0 is defined as an extension of XQuery 1.0, a number of implementers have adapted it, in a fairly intuitive way, to work with later versions of XQuery. At the time of this publication, later versions of the XQuery Update specification remain at Working Draft status.

    E.2 Functions Defined by Community Groups

    A number of community groups, with varying levels of formal organization, have defined specifications for additional function libraries to augment the core functions defined in this specification. Many of the resulting function specifications have implementations available for popular XPath, XQuery, and XSLT processors, though the level of support is highly variable.

    The first such group was EXSLT. This activity was primarily concerned with augmenting the capability of XSLT 1.0, and many of its specifications were overtaken by core functions that became available in XPath 2.0. EXSLT defined a number of function modules covering:

    Dates and Times
    Dynamic XPath Evaluation
    Common (containing most notably the widely used node-set function)
    Math (max, min, abs, and trigonometric functions)
    Random Number Generation
    Regular Expressions
    Sets (operations on sets of nodes including set intersection and difference)
    String Manipulation (tokenize, replace, join and split, etc.)

    Specifications from the EXSLT group can be found at [EXSLT].

    A renewed attempt to define additional function libraries using XPath 2.0 as its baseline formed under the name EXPath. Again, the specifications are in various states of maturity and stability, and implementation across popular processors is patchy. At the time of this publication the function libraries that exist in stable published form include:

    Binary (functions for manipulating binary data)
    File Handling (reading and writing files)
    Geospatial (handling of geographic data)
    HTTP Client (sending HTTP requests)
    ZIP Facility (reading and creating ZIP files or similar archives)

    The EXPath community has also been engaged in other related projects, such as defining packaging standards for distribution of XSLT/XQuery components, and tools for unit testing. Its specifications can be found at [EXPath].

    A third activity has operated under the name EXQuery, which as the name suggests has focused on extensions to XQuery. EXQuery has published a single specification, RestXQ, which is primarily a system of function annotations allowing XQuery functions to act as endpoints for RESTful services. It also includes some simple functions to assist with the creation of such services. The RestXQ specification can be found at [EXQuery].

    E.3 The FunctX Library

    Many useful functions can be written in XSLT or XQuery, and in this case the function implementations themselves can be portable across different XSLT and XQuery processors. This section describes one such library.

    FunctX is an open-source library of general-purpose functions, supplied in the form of XQuery 1.0 and XSLT 2.0 implementations. It contains over a hundred functions. Typical examples of these functions are:

    Test whether a string is all-whitespace
    Trim leading and trailing whitespace
    Test whether all the values in a sequence are distinct
    Capitalize the first character of a string
    Change the namespace of all elements in a tree
    Get the number of days in a given month
    Get the first or last day in a given month
    Get the date of the preceding or following day
    Ask whether an element has element-only, mixed, or simple content
    Find the position of a node in a sequence
    Count words in a string

    The FunctX library can be found at [FunctX].

    F Checklist of implementation-defined features (Non-Normative)

    1. It is ·implementation-defined· which version of Unicode is supported, but it is recommended that the most recent version of Unicode be used. (See Conformance.)

    2. It is ·implementation-defined· whether the type system is based on XML Schema 1.0 or XML Schema 1.1. (See Conformance.)

    3. It is ·implementation-defined· whether definitions that rely on XML (for example, the set of valid XML characters) should use the definitions in XML 1.0 or XML 1.1. (See Conformance.)

    4. Implementations may attach an ·implementation-defined· meaning to options in the map that are not described in this specification. These options should use values of type xs:QName as the option names, using an appropriate namespace. (See Options.)

    5. It is ·implementation-defined· which version of [The Unicode Standard] is supported, but it is recommended that the most recent version of Unicode be used. (See Strings, characters, and codepoints.)

    6. [Definition] Some functions (such as fn:distinct-values, fn:unordered, map:keys, and map:for-each) produce results in an ·implementation-defined· or ·implementation-dependent· order. In such cases two calls with the same arguments are not guaranteed to produce the results in the same order. These functions are said to be nondeterministic with respect to ordering. (See Properties of functions.)

    7. Where the results of a function are described as being (to a greater or lesser extent) ·implementation-defined· or ·implementation-dependent·, this does not by itself remove the requirement that the results should be deterministic: that is, that repeated calls with the same explicit and implicit arguments must return identical results. (See Properties of functions.)

    8. In addition, the values of $input, typically serialized and converted to an xs:string, and $label (if supplied and non-empty) may be output to an ·implementation-defined· destination. (See fn:trace.)

    9. Consider a situation in which a user wants to investigate the actual value passed to a function. Assume that in a particular execution, $v is an xs:decimal with value 124.84. Writing fn:trace($v, 'the value of $v is:') will return $v. The processor may output "124.84" and "the value of $v is:" to an ·implementation-defined· destination. (See fn:trace.)

    10. Similar to fn:trace, the values of $input, typically serialized and converted to an xs:string, and $label (if supplied and non-empty) may be output to an ·implementation-defined· destination. (See fn:message.)

    11. They may provide an ·implementation-defined· mechanism that allows users to choose between raising an error and returning a result that is modulo the largest representable integer value. See [ISO 10967]. (See Arithmetic operators on numeric values.)

    12. For xs:decimal values, let N be the number of digits of precision supported by the implementation, and let M (M <= N) be the minimum limit on the number of digits required for conformance (18 digits for XSD 1.0, 16 digits for XSD 1.1). Then for addition, subtraction, and multiplication operations, the returned result should be accurate to N digits of precision, and for division and modulus operations, the returned result should be accurate to at least M digits of precision. The actual precision is ·implementation-defined·. If the number of digits in the mathematical result exceeds the number of digits that the implementation retains for that operation, the result is truncated or rounded in an ·implementation-defined· manner. (See Arithmetic operators on numeric values.)

    13. The [IEEE 754-2019] specification also describes handling of two exception conditions called divideByZero and invalidOperation. The IEEE divideByZero exception is raised not only by a direct attempt to divide by zero, but also by operations such as log(0). The IEEE invalidOperation exception is raised by attempts to call a function with an argument that is outside the function’s domain (for example, sqrt(-1) or log(-1)). Although IEEE defines these as exceptions, it also defines “default non-stop exception handling” in which the operation returns a defined result, typically positive or negative infinity, or NaN. With this function library, these IEEE exceptions do not cause a dynamic error at the application level; rather they result in the relevant function or operator returning the defined non-error result. The underlying IEEE exception may be notified to the application or to the user by some ·implementation-defined· warning condition, but the observable effect on an application using the functions and operators defined in this specification is simply to return the defined result (typically -INF, +INF, or NaN) with no error. (See Arithmetic operators on numeric values.)

    14. The [IEEE 754-2019] specification distinguishes two NaN values: a quiet NaN and a signaling NaN. These two values are not distinguishable in the XDM model: the value spaces of xs:float and xs:double each include only a single NaN value. This does not prevent the implementation distinguishing them internally, and triggering different ·implementation-defined· warning conditions, but such distinctions do not affect the observable behavior of an application using the functions and operators defined in this specification. (See Arithmetic operators on numeric values.)

    15. The implementation may adopt a different algorithm provided that it is equivalent to this formulation in all cases where ·implementation-dependent· or ·implementation-defined· behavior does not affect the outcome, for example, the implementation-defined precision of the result of xs:decimal division. (See op:numeric-integer-divide.)

    16. XSD 1.1 allows the string +INF as a representation of positive infinity; XSD 1.0 does not. It is ·implementation-defined· whether XSD 1.1 is supported. (See fn:number.)

    17. Any other format token, which indicates a numbering sequence in which that token represents the number 1 (one) (but see the note below). It is ·implementation-defined· which numbering sequences, additional to those listed above, are supported. If an implementation does not support a numbering sequence represented by the given token, it must use a format token of 1. (See fn:format-integer.)

    18. For all format tokens other than a digit-pattern, there may be ·implementation-defined· lower and upper bounds on the range of numbers that can be formatted using this format token; indeed, for some numbering sequences there may be intrinsic limits. For example, the format token U+2460 (CIRCLED DIGIT ONE, ) has a range imposed by the Unicode character repertoire — zero to 20 in Unicode versions prior to 3.2, or zero to 50 in subsequent versions. For the numbering sequences described above any upper bound imposed by the implementation must not be less than 1000 (one thousand) and any lower bound must not be greater than 1. Numbers that fall outside this range must be formatted using the format token 1. (See fn:format-integer.)

    19. The set of languages for which numbering is supported is ·implementation-defined·. If the $language argument is absent, or is set to an empty sequence, or is invalid, or is not a language supported by the implementation, then the number is formatted using the default language from the dynamic context. (See fn:format-integer.)

    20. ...either a or t, to indicate alphabetic or traditional numbering respectively, the default being ·implementation-defined·. (See fn:format-integer.)

    21. The string of characters between the parentheses, if present, is used to select between other possible variations of cardinal or ordinal numbering sequences. The interpretation of this string is ·implementation-defined·. No error occurs if the implementation does not define any interpretation for the defined string. (See fn:format-integer.)

    22. It is ·implementation-defined· what combinations of values of the format token, the language, and the cardinal/ordinal modifier are supported. If ordinal numbering is not supported for the combination of the format token, the language, and the string appearing in parentheses, the request is ignored and cardinal numbers are generated instead. (See fn:format-integer.)

    23. The use of the a or t modifier disambiguates between numbering sequences that use letters. In many languages there are two commonly used numbering sequences that use letters. One numbering sequence assigns numeric values to letters in alphabetic sequence, and the other assigns numeric values to each letter in some other manner traditional in that language. In English, these would correspond to the numbering sequences specified by the format tokens a and i. In some languages, the first member of each sequence is the same, and so the format token alone would be ambiguous. In the absence of the a or t modifier, the default is ·implementation-defined·. (See fn:format-integer.)

    24. The static context provides a set of decimal formats. One of the decimal formats is unnamed, the others (if any) are identified by a QName. There is always an unnamed decimal format available, but its contents are ·implementation-defined·. (See Defining a decimal format.)

    25. IEEE states that the preferred quantum is language-defined. In this specification, it is ·implementation-defined·. (See Trigonometric and exponential functions.)

    26. IEEE defines various rounding algorithms for inexact results, and states that the choice of rounding direction, and the mechanisms for influencing this choice, are language-defined. In this specification, the rounding direction and any mechanisms for influencing it are ·implementation-defined·. (See Trigonometric and exponential functions.)

    27. The map returned by the fn:random-number-generator function may contain additional entries beyond those specified here, but it must match the record type defined above. The meaning of any additional entries is ·implementation-defined·. To avoid conflict with any future version of this specification, the keys of any such entries should start with an underscore character. (See fn:random-number-generator.)

    28. If two query parameters use the same keyword then the last one wins. If a query parameter uses a keyword or value which is not defined in this specification then the meaning is ·implementation-defined·. If the implementation recognizes the meaning of the keyword and value then it should interpret it accordingly; if it does not recognize the keyword or value then if the fallback parameter is present with the value no it should reject the collation as unsupported, otherwise it should ignore the unrecognized parameter. (See The Unicode Collation Algorithm.)

    29. The following query parameters are defined. If any parameter is absent, the default is ·implementation-defined· except where otherwise stated. The meaning given for each parameter is non-normative; the normative specification is found in [UTS #35]. (See The Unicode Collation Algorithm.)

    30. Because the set of collations that are supported is ·implementation-defined·, an implementation has the option to support all collation URIs, in which case it will never raise this error. (See Choosing a collation.)

    31. The properties available are as defined for the Unicode Collation Algorithm (see 5.3.4 The Unicode Collation Algorithm). Additional ·implementation-defined· properties may be specified as described in the rules for UCA collation URIs. (See fn:collation.)

    32. It is possible to define collations that do not have the ability to generate collation keys. Supplying such a collation will cause the function to fail. The ability to generate collation keys is an ·implementation-defined· property of the collation. (See fn:collation-key.)

    33. Conforming implementations must support normalization form NFC and may support normalization forms NFD, NFKC, NFKD, and FULLY-NORMALIZED. They may also support other normalization forms with ·implementation-defined· semantics. (See fn:normalize-unicode.)

    34. It is ·implementation-defined· which version of Unicode (and therefore, of the normalization algorithms and their underlying data) is supported by the implementation. See [UAX #15] for details of the stability policy regarding changes to the normalization rules in future versions of Unicode. If the input string contains codepoints that are unassigned in the relevant version of Unicode, or for which no normalization rules are defined, the fn:normalize-unicode function leaves such codepoints unchanged. If the implementation supports the requested normalization form then it must be able to handle every input string without raising an error. (See fn:normalize-unicode.)

    35. It is possible to define collations that do not have the ability to decompose a string into units suitable for substring matching. An argument to a function defined in this section may be a URI that identifies a collation that is able to compare two strings, but that does not have the capability to split the string into collation units. Such a collation may cause the function to fail, or to give unexpected results, or it may be rejected as an unsuitable argument. The ability to decompose strings into collation units is an ·implementation-defined· property of the collation. The fn:collation-available function can be used to ask whether a particular collation has this property. (See Functions based on substring matching.)

    36. The result of the function will always be such that validation against this schema would succeed. However, it is ·implementation-defined· whether the result is typed or untyped, that is, whether the elements and attributes in the returned tree have type annotations that reflect the result of validating against this schema. (See fn:analyze-string.)

    37. Some URI schemes are hierarchical and some are non-hierarchical. Implementations must treat the following schemes as non-hierarchical: jar, mailto, news, tag, tel, and urn. Whether additional schemes are known to be non-hierarchical ·implementation-defined·. If a scheme is not known to be non-hierarchical, it must be treated as hierarchical. (See Parsing and building URIs.)

    38. If the omit-default-ports option is true, the port is discarded and set to the empty sequence if the port number is the same as the default port for the given scheme. Implementations should recognize the default ports for http (80), https (443), ftp (21), and ssh (22). Exactly which ports are recognized is ·implementation-defined·. (See fn:parse-uri.)

    39. If the omit-default-ports option is true then the $port is set to the empty sequence if the port number is the same as the default port for the given scheme. Implementations should recognize the default ports for http (80), https (443), ftp (21), and ssh (22). Exactly which ports are recognized is ·implementation-defined·. (See fn:build-uri.)

    40. Processors may support a greater range and/or precision. The limits are ·implementation-defined·. (See Limits and precision.)

    41. Similarly, a processor may be unable accurately to represent the result of dividing a duration by 2, or multiplying a duration by 0.5. A processor that limits the precision of the seconds component of duration values must deliver a result that is as close as possible to the mathematically precise result, given these limits; if two values are equally close, the one that is chosen is ·implementation-defined·. (See Limits and precision.)

    42. All conforming processors must support year values in the range 1 to 9999, and a minimum fractional second precision of 1 millisecond or three digits (i.e., s.sss). However, processors may set larger ·implementation-defined· limits on the maximum number of digits they support in these two situations. Processors may also choose to support the year 0 and years with negative values. The results of operations on dates that cross the year 0 are ·implementation-defined·. (See Limits and precision.)

    43. Similarly, a processor that limits the precision of the seconds component of date and time or duration values may need to deliver a rounded result for arithmetic operations. Such a processor must deliver a result that is as close as possible to the mathematically precise result, given these limits: if two values are equally close, the one that is chosen is ·implementation-defined·. (See Limits and precision.)

    44. ...the format token n, N, or Nn, indicating that the value of the component is to be output by name, in lower-case, upper-case, or title-case respectively. Components that can be output by name include (but are not limited to) months, days of the week, timezones, and eras. If the processor cannot output these components by name for the chosen calendar and language then it must use an ·implementation-defined· fallback representation. (See The picture string.)

    45. ...indicates alphabetic or traditional numbering respectively, the default being ·implementation-defined·. This has the same meaning as in the second argument of fn:format-integer. (See The picture string.)

    46. The sequence of characters in the (adjusted) first presentation modifier is reversed (for example, 999'### becomes ###'999). If the result is not a valid decimal digit pattern, then the output is ·implementation-defined·. (See Formatting Fractional Seconds.)

    47. The output for these components is entirely ·implementation-defined·. The default presentation modifier for these components is n, indicating that they are output as names (or conventional abbreviations), and the chosen names will in many cases depend on the chosen language: see 9.8.4.8 The language, calendar, and place arguments. (See Formatting Other Components.)

    48. The set of languages, calendars, and places that are supported in the ·date formatting functions· is ·implementation-defined·. When any of these arguments is omitted or is an empty sequence, an ·implementation-defined· default value is used. (See The language, calendar, and place arguments.)

    49. The choice of the names and abbreviations used in any given language is ·implementation-defined·. For example, one implementation might abbreviate July as Jul while another uses Jly. In German, one implementation might represent Saturday as Samstag while another uses Sonnabend. Implementations may provide mechanisms allowing users to control such choices. (See The language, calendar, and place arguments.)

    50. The choice of the names and abbreviations used in any given language for calendar units such as days of the week and months of the year is ·implementation-defined·. (See The language, calendar, and place arguments.)

    51. The calendar value if present must be a valid EQName (dynamic error: [err:FOFD1340]). If it is a lexical QName then it is expanded into an expanded QName using the statically known namespaces; if it has no prefix then it represents an expanded-QName in no namespace. If the expanded QName is in no namespace, then it must identify a calendar with a designator specified below (dynamic error: [err:FOFD1340]). If the expanded QName is in a namespace then it identifies the calendar in an ·implementation-defined· way. (See The language, calendar, and place arguments.)

    52. At least one of the above calendars must be supported. It is ·implementation-defined· which calendars are supported. (See The language, calendar, and place arguments.)

    53. The requirement to deliver a deterministic result has performance implications, and for this reason implementations may provide a user option to evaluate the function without a guarantee of determinism. The manner in which any such option is provided is ·implementation-defined·. If the user has not selected such an option, a call of the function must either return a deterministic result or must raise a dynamic error [err:FODC0003]. (See fn:doc.)

    54. Various aspects of this processing are ·implementation-defined·. Implementations may provide external configuration options that allow any aspect of the processing to be controlled by the user. In particular:... (See fn:doc.)

    55. It is ·implementation-defined· whether DTD validation and/or schema validation is applied to the source document. (See fn:doc.)

    56. The effect of a fragment identifier in the supplied URI is ·implementation-defined·. One possible interpretation is to treat the fragment identifier as an ID attribute value, and to return a document node having the element with the selected ID value as its only child. (See fn:doc.)

    57. By default, this function is ·deterministic·. This means that repeated calls on the function with the same argument will return the same result. However, for performance reasons, implementations may provide a user option to evaluate the function without a guarantee of determinism. The manner in which any such option is provided is ·implementation-defined·. If the user has not selected such an option, a call to this function must either return a deterministic result or must raise a dynamic error [err:FODC0003]. (See fn:collection.)

    58. By default, this function is ·deterministic·. This means that repeated calls on the function with the same argument will return the same result. However, for performance reasons, implementations may provide a user option to evaluate the function without a guarantee of determinism. The manner in which any such option is provided is ·implementation-defined·. If the user has not selected such an option, a call to this function must either return a deterministic result or must raise a dynamic error [err:FODC0003]. (See fn:uri-collection.)

    59. ...the processor may use ·implementation-defined· heuristics to determine the likely encoding, otherwise... (See fn:unparsed-text.)

    60. The fact that the resolution of URIs is defined by a mapping in the dynamic context means that in effect, various aspects of the behavior of this function are ·implementation-defined·. Implementations may provide external configuration options that allow any aspect of the processing to be controlled by the user. In particular:... (See fn:unparsed-text.)

    61. The collation used for matching names is ·implementation-defined·, but must be the same as the collation used to ensure that the names of all environment variables are unique. (See fn:environment-variable.)

    62. Except to the extent defined by these options, the precise process used to construct the XDM instance is ·implementation-defined·. In particular, it is implementation-defined whether an XML 1.0 or XML 1.1 parser is used. (See fn:parse-xml.)

    63. Except as explicitly defined, the precise process used to construct the XDM instance is ·implementation-defined·. In particular, it is implementation-defined whether an XML 1.0 or XML 1.1 parser is used. (See fn:parse-xml-fragment.)

    64. If the second argument is omitted, or is supplied in the form of an output:serialization-parameters element, then the values of any serialization parameters that are not explicitly specified is ·implementation-defined·, and may depend on the context. (See fn:serialize.)

    65. Because the [DOM: Living Standard] and [HTML: Living Standard] are not fixed, it is ·implementation-defined· which versions are used. (See XDM Mapping from HTML DOM Nodes.)

    66. If an implementation allows these nodes to be passed in via an API or similar mechanism, their behaviour is ·implementation-defined·. (See XDM Mapping from HTML DOM Nodes.)

    67. If the local name contains a character that is not a valid XML NameStartChar or NameChar, then an ·implementation-defined· replacement string is used. The result must be a valid NCName. (See node-name Accessor.)

    68. If the local name contains a character that is not a valid XML NameStartChar or NameChar, then an ·implementation-defined· replacement string is used. The result must be a valid NCName. (See node-name Accessor.)

    69. Additional ·implementation-defined· parser options are allowed. (See HTML parser options.)

    70. Any other method and html-version combinations are ·implementation-defined·. (See fn:parse-html.)

    71. The default behaviour is ·implementation-defined·. (See fn:parse-html.)

    72. An ·implementation-defined· parsing algorithm, tree construction, and validation consistent with the specified HTML version. (See fn:parse-html.)

    73. The input may contain deviations from the grammar of [RFC 7159], which are handled in an ·implementation-defined· way. (Note: some popular extensions include allowing quotes on keys to be omitted, allowing a comma to appear after the last item in an array, allowing leading zeroes in numbers, and allowing control characters such as tab and newline to be present in unescaped form.) Since the extensions accepted are implementation-defined, an error may be raised [err:FOJS0001] if the input does not conform to the grammar. (See fn:parse-json.)

    74. The supplied function is called to process the string value of any JSON number in the input. By default, numbers are processed by converting to xs:double using the XPath casting rules. Supplying the value xs:decimal#1 will instead convert to xs:decimal (which potentially retains more precision, but disallows exponential notation), while supplying a function that casts to (xs:decimal | xs:double) will treat the value as xs:decimal if there is no exponent, or as xs:double otherwise. Supplying the value fn:identity#1 causes the value to be retained unchanged as an xs:untypedAtomic. If the liberal option is false (the default), then the supplied number-parser is called if and only if the value conforms to the JSON grammar for numbers (for example, a leading plus sign and redundant leading zeroes are not allowed). If the liberal option is true then it is also called if the value conforms to an ·implementation-defined· extension of this grammar. (See fn:parse-json.)

    75. The input may contain deviations from the grammar of [RFC 7159], which are handled in an ·implementation-defined· way. (Note: some popular extensions include allowing quotes on keys to be omitted, allowing a comma to appear after the last item in an array, allowing leading zeroes in numbers, and allowing control characters such as tab and newline to be present in unescaped form.) Since the extensions accepted are implementation-defined, an error may be raised (see below) if the input does not conform to the grammar. (See fn:json-to-xml.)

    76. Default: ·Implementation-defined·. (See fn:json-to-xml.)

    77. Indicates that the resulting XDM instance must be typed; that is, the element and attribute nodes must carry the type annotations that result from validation against the schema given at C.2 Schema for the result of fn:json-to-xml, or against an ·implementation-defined· schema if the liberal option has the value true. (See fn:json-to-xml.)

    78. The result of the function will always be such that validation against this schema would succeed. However, it is ·implementation-defined· whether the result is typed or untyped, that is, whether the elements and attributes in the returned tree have type annotations that reflect the result of validating against this schema. (See fn:csv-to-xml.)

    79. Additional, ·implementation-defined· options may be available, for example, to control aspects of the XML serialization, to specify the grammar start symbol, or to produce output formats other than XML. (See fn:invisible-xml.)

    80. If the arguments to fn:function-lookup identify a function that is present in the static context of the function call, the function will always return the same function that a static reference to this function would bind to. If there is no such function in the static context, then the results depend on what is present in the dynamic context, which is ·implementation-defined·. (See fn:function-lookup.)

    81. Default: The version given in the prolog of the library module; or ·implementation-defined· if this is absent. (See fn:load-xquery-module.)

    82. A sequence of URIs (in the form of xs:string values) which may be used or ignored in an ·implementation-defined· way.... (See fn:load-xquery-module.)

    83. Values for vendor-defined configuration options for the XQuery processor used to process the request. The key is the name of an option, expressed as a QName: the namespace URI of the QName should be a URI controlled by the vendor of the XQuery processor. The meaning of the associated value is ·implementation-defined·. Implementations should ignore options whose names are in an unrecognized namespace. The ·option parameter conventions· do not apply to this contained map.... (See fn:load-xquery-module.)

    84. It is ·implementation-defined· whether constructs in the library module are evaluated in the same ·execution scope· as the calling module. (See fn:load-xquery-module.)

    85. The library module that is loaded may import schema declarations using an import schema declaration. It is ·implementation-defined· whether schema components in the in-scope schema definitions of the calling module are automatically added to the in-scope schema definitions of the dynamically loaded module. The in-scope schema definitions of the calling and called modules must be consistent, according to the rules defined in Section 2.2.5 Consistency Constraints XQ31. (See fn:load-xquery-module.)

    86. Default: ·Implementation-defined·. (See fn:transform.)

    87. Default: ·Implementation-defined·. (See fn:transform.)

    88. If the implementation provides a way of writing or invoking functions with side-effects, this post-processing function might be used to save a copy of the result document to persistent storage. For example, if the implementation provides access to the EXPath File library [EXPath], then a serialized document might be written to filestore by calling the file:write function. Similar mechanisms might be used to issue an HTTP POST request that posts the result to an HTTP server, or to send the document to an email recipient. The semantics of calling functions with side-effects are entirely ·implementation-defined·. (See fn:transform.)

    89. Calls to fn:transform can potentially have side-effects even in the absence of the post-processing option, because the XSLT specification allows a stylesheet to invoke extension functions that have side-effects. The semantics in this case are ·implementation-defined·. (See fn:transform.)

    90. A string intended to be used as the static base URI of the principal stylesheet module. This value must be used if no other static base URI is available. If the supplied stylesheet already has a base URI (which will generally be the case if the stylesheet is supplied using stylesheet-node or stylesheet-location) then it is ·implementation-defined· whether this parameter has any effect. If the value is a relative reference, it is resolved against the static base URI of the fn:transform function call.... (See fn:transform.)

    91. Values for vendor-defined configuration options for the XSLT processor used to process the request. The key is the name of an option, expressed as a QName: the namespace URI of the QName should be a URI controlled by the vendor of the XSLT processor. The meaning of the associated value is ·implementation-defined·. Implementations should ignore options whose names are in an unrecognized namespace. Default is an empty map.... (See fn:transform.)

    92. It is ·implementation-defined· whether the XSLT transformation is executed within the same ·execution scope· as the calling code. (See fn:transform.)

    93. XSLT 1.0 does not define any error codes, so this is the likely outcome with an XSLT 1.0 processor. XSLT 2.0 and 3.0 do define error codes, but some APIs do not expose them. If multiple errors are signaled by the transformation (which is most likely to happen with static errors) then the error code should where possible be that of one of these errors, chosen arbitrarily; the processor may make details of additional errors available to the application in an ·implementation-defined· way. (See fn:transform.)

    94. If ST is xs:float or xs:double, then TV is the xs:decimal value, within the set of xs:decimal values that the implementation is capable of representing, that is numerically closest to SV. If two values are equally close, then the one that is closest to zero is chosen. If SV is too large to be accommodated as an xs:decimal, (see [XML Schema Part 2: Datatypes Second Edition] for ·implementation-defined· limits on numeric values) a dynamic error is raised [err:FOCA0001]. If SV is one of the special xs:float or xs:double values NaN, INF, or -INF, a dynamic error is raised [err:FOCA0002]. (See Casting to xs:decimal.)

    95. In casting to xs:decimal or to a type derived from xs:decimal, if the value is not too large or too small but nevertheless cannot be represented accurately with the number of decimal digits available to the implementation, the implementation may round to the nearest representable value or may raise a dynamic error [err:FOCA0006]. The choice of rounding algorithm and the choice between rounding and error behavior is ·implementation-defined·. (See Casting from xs:string and xs:untypedAtomic.)

    96. If ST is xs:decimal, xs:float or xs:double, then TV is SV with the fractional part discarded and the value converted to xs:integer. Thus, casting 3.1456 returns 3 while -17.89 returns -17. Casting 3.124E1 returns 31. If SV is too large to be accommodated as an integer, (see [XML Schema Part 2: Datatypes Second Edition] for ·implementation-defined· limits on numeric values) a dynamic error is raised [err:FOCA0003]. If SV is one of the special xs:float or xs:double values NaN, INF, or -INF, a dynamic error is raised [err:FOCA0002]. (See Casting to xs:integer.)

    97. The tz timezone database, available at http://www.iana.org/time-zones. It is ·implementation-defined· which version of the database is used. (See IANA Timezone Database.)

    98. Unicode Standard Annex #15: Unicode Normalization Forms. Ed. Mark Davis and Ken Whistler, Unicode Consortium. The current version is 9.0.0, dated 2016-02-24. As with [The Unicode Standard], the version to be used is ·implementation-defined·. Available at: http://www.unicode.org/reports/tr15/. (See UAX #15.)

    99. Unicode Standard Annex #29: Unicode Text Segmentation. Ed. Josh Hadley, Unicode Consortium. The current version is 15.1.0, dated 2023-08-16. As with [The Unicode Standard], the version to be used is ·implementation-defined·. Available at: http://www.unicode.org/reports/tr29/. (See UAX #29.)

    100. The Unicode Consortium, Reading, MA, Addison-Wesley, 2016. The Unicode Standard as updated from time to time by the publication of new versions. See http://www.unicode.org/standard/versions/ 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 ·implementation-defined·, but implementations are recommended to use the latest Unicode version; currently, Version 9.0.0. (See The Unicode Standard.)

    101. Unicode Technical Standard #10: Unicode Collation Algorithm. Ed. Mark Davis and Ken Whistler, Unicode Consortium. The current version is 9.0.0, dated 2016-05-18. As with [The Unicode Standard], the version to be used is ·implementation-defined·. Available at: http://www.unicode.org/reports/tr10/. (See UTS #10.)

    102. Unicode Technical Standard #35: Unicode Locale Data Markup Language. Ed Mark Davis et al, Unicode Consortium. The current version is 29, dated 2016-03-15. As with [The Unicode Standard], the version to be used is ·implementation-defined·. Available at: http://www.unicode.org/reports/tr35/. (See UTS #35.)

    G Changes since version 3.1 (Non-Normative)

    G.1 Summary of Changes

    1. Use the arrows to browse significant changes since the 3.1 version of this specification.

      See 1 Introduction

    2. Sections with significant changes are marked Δ in the table of contents. New functions introduced in this version are marked ➕ in the table of contents.

      See 1 Introduction

    3. PR 1547 1551 

      New in 4.0

      See 2.2.8 fn:siblings

    4. PR 629 803 

      New in 4.0

      See 3.2.2 fn:message

    5. PR 1260 1275 

      A third argument has been added, providing control over the rounding mode.

      See 4.4.4 fn:round

    6. New in 4.0

      See 4.4.7 fn:is-NaN

    7. PR 1049 1151 

      Decimal format parameters can now be supplied directly as a map in the third argument, rather than referencing a format defined in the static context.

      See 4.7.2 fn:format-number

    8. PR 1205 1230 

      New in 4.0

      See 4.8.2 math:e

      See 4.8.16 math:sinh

      See 4.8.17 math:cosh

      See 4.8.18 math:tanh

    9. The 3.1 specification suggested that every value in the result range should have the same chance of being chosen. This has been corrected to say that the distribution should be arithmetically uniform (because there are as many xs:double values between 0.01 and 0.1 as there are between 0.1 and 1.0).

      See 4.9.2 fn:random-number-generator

    10. PR 261 306 993 

      New in 4.0

      See 5.4.1 fn:char

    11. New in 4.0

      See 5.4.2 fn:characters

    12. PR 937 995 1190 

      New in 4.0

      See 5.4.13 fn:hash

    13. The $action argument is new in 4.0.

      See 5.6.4 fn:replace

    14. New in 4.0

      See 6.6.2 fn:parse-uri

    15. PR 1423 1413 

      New in 4.0

      See 6.6.3 fn:build-uri

    16. New in 4.0

      See 10.2.6 fn:in-scope-namespaces

    17. Reformulated in 4.0 in terms of the new fn:in-scope-namespaces function; the semantics are unchanged.

      See 10.2.7 fn:in-scope-prefixes

    18. Reformulated in 4.0 in terms of the new fn:in-scope-namespaces function; the semantics are unchanged.

      See 10.2.8 fn:namespace-uri-for-prefix

    19. New in 4.0

      See 13.1.9 fn:replicate

    20. New in 4.0

      See 13.1.12 fn:slice

    21. New in 4.0. The function is identical to the internal op:same-key function in 3.1

      See 13.2.1 fn:atomic-equal

    22. PR 1120 1150 

      A callback function can be supplied for comparing individual items.

      See 13.2.2 fn:deep-equal

    23. Changed in 4.0 to use transitive equality comparisons for numeric values.

      See 13.2.4 fn:distinct-values

    24. New in 4.0. Originally proposed under the name fn:uniform

      See 13.4.6 fn:all-equal

    25. New in 4.0. Originally proposed under the name fn:unique

      See 13.4.7 fn:all-different

    26. PR 1117 1279 

      The $options parameter has been added.

      See 13.6.6 fn:unparsed-text-lines

    27. A new function is available for processing input data in HTML format.

      See 14.2 Functions on HTML Data

    28. PR 259 956 

      New in 4.0

      See 14.2.3 fn:parse-html

    29. PR 975 1058 1246 

      An option is provided to control how JSON numbers should be formatted.

      See 14.3.4 fn:parse-json

    30. Additional options are available, as defined by fn:parse-json.

      See 14.3.5 fn:json-doc

    31. PR 533 719 834 1066 

      New in 4.0

      See 14.4.4 fn:csv-to-arrays

      See 14.4.7 fn:parse-csv

    32. PR 533 719 834 1066 1605 

      New in 4.0

      See 14.4.9 fn:csv-to-xml

    33. PR 791 1256 1282 1405 

      New in 4.0

      See 14.5.1 fn:invisible-xml

    34. New in 4.0

      See 16.2.4 fn:every

    35. New in 4.0

      See 16.2.10 fn:highest

    36. New in 4.0

      See 16.2.11 fn:index-where

    37. New in 4.0

      See 16.2.12 fn:lowest

    38. New in 4.0

      See 16.2.15 fn:scan-right

    39. New in 4.0

      See 16.2.16 fn:some

    40. PR 521 761 

      New in 4.0

      See 16.2.21 fn:transitive-closure

    41. New in 4.0

      See 17.3.617.4.6 map:filter

    42. A third argument is added, allowing user control of how absent keys should be handled.

      See 17.3.917.4.9 map:get

    43. New in 4.0

      See 17.3.1017.4.10 map:items

    44. PR 478 515 

      New in 4.0

      See 17.3.1217.4.12 map:keys-where

    45. New in 4.0

      See 17.3.1417.4.14 map:of-pairs

    46. New in 4.0

      See 17.3.1517.4.15 map:pair

    47. New in 4.0

      See 17.3.1617.4.16 map:pairs

    48. New in 4.0

      See 17.3.1917.4.19 map:replace

    49. New in 4.0.

      See 17.4.717.5.7 fn:elements-to-maps

    50. New in 4.0

      See 18.2.3 array:empty

    51. A third argument is added, allowing user control of how index-out-of-bounds conditions should be handled.

      See 18.2.11 array:get

    52. PR 968 1295 

      New in 4.0

      See 18.2.13 array:index-of

    53. PR 476 1087 

      New in 4.0

      See 18.2.16 array:items

    54. PR 360 476 

      New in 4.0

      See 18.2.18 array:members

      See 18.2.19 array:of-members

    55. New in 4.0

      See 18.2.22 array:replace

    56. New in 4.0

      See 18.2.25 array:slice

    57. New in 4.0

      See 18.2.26 array:sort

    58. New in 4.0

      See 18.2.27 array:split

    59. Supplying an empty sequence as the value of an optional argument is equivalent to omitting the argument.

      See 18.2.28 array:subarray

    60. New functions are provided to obtain information about built-in types and types defined in an imported schema.

      See 19 Functions on types

    61. Options are added to customize the form of the output.

      See 2.2.6 fn:path

    62. PR 533 719 834 

      New functions are available for processing input data in CSV (comma separated values) format.

      See 14.4 Functions on CSV Data

    63. PR 734 1233 

      New in 4.0

      See 16.2.2 fn:chain

    64. A new function fn:elements-to-maps is provided for converting XDM trees to maps suitable for serialization as JSON. Unlike the fn:xml-to-json function retained from 3.1, this can handle arbitrary XML as input.

      See 17.417.5 Converting Elements to Maps

    65. New in 4.0

      See 13.1.5 fn:identity

    66. New in 4.0.

      See 4.4.6 fn:divide-decimals

    67. The default for the escape option has been changed to false. The 3.1 specification gave the default value as true, but this appears to have been an error, since it was inconsistent with examples given in the specification and with tests in the test suite.

      See 14.3.4 fn:parse-json

    68. The spec has been corrected to note that the function depends on the implicit timezone.

      See 13.2.3 fn:compare

    69. PR 173 

      New in 4.0

      See 16.3.4 fn:op

    70. PR 203 

      New in 4.0

      See 17.3.117.4.1 map:build

    71. PR 207 

      New in 4.0

      See 10.1.2 fn:parse-QName

      See 10.2.5 fn:expanded-QName

    72. PR 222 

      New in 4.0

      See 13.2.7 fn:starts-with-subsequence

      See 13.2.8 fn:ends-with-subsequence

      See 13.2.9 fn:contains-subsequence

    73. PR 250 

      New in 4.0

      See 13.1.3 fn:foot

      See 13.1.15 fn:trunk

      See 18.2.2 array:build

      See 18.2.8 array:foot

      See 18.2.30 array:trunk

    74. PR 258 

      New in 4.0

      See 18.2.14 array:index-where

    75. PR 313 

      The second argument can now be a sequence of integers.

      See 13.1.8 fn:remove

    76. PR 314 

      New in 4.0

      See 17.3.417.4.4 map:entries

    77. PR 326 

      Higher-order functions are no longer an optional feature.

      See 1.2 Conformance

    78. PR 419 

      New in 4.0

      See 13.1.7 fn:items-at

    79. PR 434 

      New in 4.0

      See 4.5.2 fn:parse-integer

      The function has been extended to allow output in a radix other than 10, for example in hexadecimal.

      See 4.6.1 fn:format-integer

    80. PR 482 

      Deleted an inaccurate statement concerning the behavior of NaN.

      See 4.3 Comparison operators on numeric values

    81. PR 507 

      New in 4.0

      See 16.2.13 fn:partition

    82. PR 546 

      The rules regarding use of non-XML characters in JSON texts have been relaxed.

      See 14.3.3 JSON character repertoire

      See 14.3.4 fn:parse-json

    83. PR 614 

      New in 4.0

      See 13.2.5 fn:duplicate-values

    84. PR 623 

      Substantially revised to allow multiple sort key definitions.

      See 16.2.17 fn:sort

    85. PR 631 

      New in 4.0

      See 6.3 fn:decode-from-uri

    86. PR 662 

      Constructor functions now have a zero-arity form; the first argument defaults to the context item.

      See 20 Constructor functions

    87. PR 680 

      The case-insensitive collation is now defined normatively within this specification, rather than by reference to the HTML "living specification", which is subject to change. The collation can now be used for ordering comparisons as well as equality comparisons.

      See 5.3.5 The HTML ASCII Case-Insensitive Collation

    88. PR 702 

      The function can now take any number of arguments (previously it had to be two or more), and the arguments can be sequences of strings rather than single strings.

      See 5.4.4 fn:concat

    89. PR 710 

      Changes the function to return a sequence of key-value pairs rather than a map.

      See 16.1.4 fn:function-annotations

    90. PR 727 

      It has been clarified that loading a module has no effect on the static or dynamic context of the caller.

      See 16.3.2 fn:load-xquery-module

    91. PR 795 

      New in 4.0

      See 16.2.18 fn:sort-with

    92. PR 828 

      The $predicate callback function accepts an optional position argument.

      See 16.2.5 fn:filter

      See 16.2.6 fn:fold-left

      The $action callback function accepts an optional position argument.

      See 16.2.7 fn:fold-right

      See 16.2.8 fn:for-each

      See 16.2.9 fn:for-each-pair

      The $predicate callback function now accepts an optional position argument.

      See 18.2.4 array:filter

      The $action callback function now accepts an optional position argument.

      See 18.2.6 array:fold-left

      See 18.2.7 array:fold-right

      See 18.2.9 array:for-each

      See 18.2.10 array:for-each-pair

    93. PR 881 

      The way that fn:min and fn:max compare numeric values of different types has changed. The most noticeable effect is that when these functions are applied to a sequence of xs:integer or xs:decimal values, the result is an xs:integer or xs:decimal, rather than the result of converting this to an xs:double

      See 13.4.3 fn:max

      See 13.4.4 fn:min

    94. PR 901 

      All three arguments are now optional, and each argument can be set to an empty sequence. Previously if $description was supplied, it could not be empty.

      See 3.1.1 fn:error

      The $label argument can now be set to an empty sequence. Previously if $label was supplied, it could not be empty.

      See 3.2.1 fn:trace

      The third argument can now be supplied as an empty sequence.

      See 5.4.6 fn:substring

      The second argument can now be an empty sequence.

      See 5.6.5 fn:tokenize

      The optional second argument can now be supplied as an empty sequence.

      See 6.1 fn:resolve-uri

      The 3rd, 4th, and 5th arguments are now optional; previously the function required either 2 or 5 arguments.

      See 9.8.1 fn:format-dateTime

      See 9.8.2 fn:format-date

      See 9.8.3 fn:format-time

      The optional third argument can now be supplied as an empty sequence.

      See 13.1.13 fn:subsequence

    95. PR 905 

      The rule that multiple calls on fn:doc supplying the same absolute URI must return the same document node has been clarified; in particular the rule does not apply if the dynamic context for the two calls requires different processing of the documents (such as schema validation or whitespace stripping).

      See 13.6.1 fn:doc

    96. PR 909 

      The function has been expanded in scope to handle comparison of values other than strings.

      See 13.2.3 fn:compare

    97. PR 924 

      Rules have been added clarifying that users should not be allowed to change the schema for the fn namespace.

      See C Schemas

    98. PR 925 

      The decimal format name can now be supplied as a value of type xs:QName, as an alternative to supplying a lexical QName as an instance of xs:string.

      See 4.7.2 fn:format-number

    99. PR 932 

      The specification now prescribes a minimum precision and range for durations.

      See 8.1.2 Limits and precision

    100. PR 933 

      When comments and processing instructions are ignored, any text nodes either side of the comment or processing instruction are now merged prior to comparison.

      See 13.2.2 fn:deep-equal

    101. PR 940 

      New in 4.0

      See 16.2.19 fn:subsequence-where

    102. PR 953 

      Constructor functions for named record types have been introduced.

      See 20.6 Constructor functions for named record types

    103. PR 962 

      New in 4.0

      See 16.2.3 fn:do-until

      See 16.2.22 fn:while-do

    104. PR 969 

      New in 4.0

      See 17.3.317.4.3 map:empty

    105. PR 984 

      New in 4.0

      See 8.4.1 fn:seconds

    106. PR 987 

      The order of results is now prescribed; it was previously implementation-dependent.

      See 13.2.4 fn:distinct-values

      See 13.2.5 fn:duplicate-values

    107. PR 988 

      New in 4.0

      See 14.3.8 fn:pin

      See 14.3.9 fn:label

    108. PR 1022 

      Regular expressions can include comments (starting and ending with #) if the c flag is set.

      See 5.6.1 Regular expression syntax

      See 5.6.2 Flags

    109. PR 1028 

      An option is provided to control how the JSON null value should be handled.

      See 14.3.4 fn:parse-json

    110. PR 1032 

      New in 4.0

      See 13.1.17 fn:void

    111. PR 1046 

      New in 4.0

      See 16.2.20 fn:take-while

    112. PR 1059 

      Use of an option keyword that is not defined in the specification and is not known to the implementation now results in a dynamic error; previously it was ignored.

      See 1.7 Options

    113. PR 1068 

      New in 4.0

      See 5.4.3 fn:graphemes

    114. PR 1072 

      The return type is now specified more precisely.

      See 16.3.2 fn:load-xquery-module

    115. PR 1090 

      When casting from a string to a duration or time or dateTime, it is now specified that when there are more digits in the fractional seconds than the implementation is able to retain, excess digits are truncated. Rounding upwards (which could affect the number of minutes or hours in the value) is not permitted.

      See 21.2 Casting from xs:string and xs:untypedAtomic

    116. PR 1093 

      New in 4.0

      See 5.3.8 fn:collation

    117. PR 1117 

      The $options parameter has been added.

      See 13.6.5 fn:unparsed-text

      See 13.6.7 fn:unparsed-text-available

    118. PR 1182 

      The $predicate callback function may return an empty sequence (meaning false).

      See 16.2.3 fn:do-until

      See 16.2.4 fn:every

      See 16.2.5 fn:filter

      See 16.2.6 fn:fold-left

      See 16.2.11 fn:index-where

      See 16.2.16 fn:some

      See 16.2.20 fn:take-while

      See 16.2.22 fn:while-do

      See 17.3.617.4.6 map:filter

      See 17.3.1217.4.12 map:keys-where

      See 18.2.4 array:filter

      See 18.2.14 array:index-where

    119. PR 1191 

      New in 4.0

      See 2.3.1 fn:distinct-ordered-nodes

      The $options parameter has been added, absorbing the $collation parameter.

      See 13.2.2 fn:deep-equal

    120. PR 1250 

      For selected properties including percent and exponent-separator, it is now possible to specify a single-character marker to be used in the picture string, together with a multi-character rendition to be used in the formatted output.

      See 4.7.2 fn:format-number

    121. PR 1257 

      The $options parameter has been added.

      See 14.1.1 fn:parse-xml

      See 14.1.2 fn:parse-xml-fragment

    122. PR 1262 

      New in 4.0

      See 5.3.9 fn:collation-available

    123. PR 1265 

      The constraints on the result of the function have been relaxed.

      See 2.1.6 fn:document-uri

    124. PR 1280 

      As a result of changes to the coercion rules, the number of supplied arguments can be greater than the number required: extra arguments are ignored.

      See 16.2.1 fn:apply

    125. PR 1288 

      Additional error conditions have been defined.

      See 14.1.1 fn:parse-xml

    126. PR 1296 

      New in 4.0

      See 16.2.14 fn:scan-left

    127. PR 1333 

      A new option is provided to allow the content of the loaded module to be supplied as a string.

      See 16.3.2 fn:load-xquery-module

    128. PR 1353 

      An option has been added to suppress the escaping of the solidus (forwards slash) character.

      See 14.3.7 fn:xml-to-json

    129. PR 1358 

      New in 4.0

      See 9.3.2 fn:unix-dateTime

    130. PR 1361 

      The term atomic value has been replaced by atomic item.

      See 1.9 Terminology

    131. PR 1393 

      Changes the function to return a sequence of key-value pairs rather than a map.

      See 16.1.4 fn:function-annotations

    132. PR 1409 

      This section now uses the term primitive type strictly to refer to the 20 atomic types that are not derived by restriction from another atomic type: that is, the 19 primitive atomic types defined in XSD, plus xs:untypedAtomic. The three types xs:integer, xs:dayTimeDuration, and xs:yearMonthDuration, which have custom casting rules but are not strictly-speaking primitive, are now handled in other subsections.

      See 21.1 Casting from primitive types to primitive types

      The rules for conversion of dates and times to strings are now defined entirely in terms of XSD 1.1 canonical mappings, since these deliver exactly the same result as the XPath 3.1 rules.

      See 21.1.2.2 Casting date/time values to xs:string

      The rules for conversion of durations to strings are now defined entirely in terms of XSD 1.1 canonical mappings, since the XSD 1.1 rules deliver exactly the same result as the XPath 3.1 rules.

      See 21.1.2.3 Casting xs:duration values to xs:string

    133. PR 1455 

      Numbers now retain their original lexical form, except for any changes needed to satisfy JSON syntax rules (for example, stripping leading zero digits).

      See 14.3.7 fn:xml-to-json

    134. PR 1481 

      The function has been extended to handle other Gregorian types such as xs:gYearMonth.

      See 9.5.1 fn:year-from-dateTime

      See 9.5.2 fn:month-from-dateTime

      The function has been extended to handle other Gregorian types such as xs:gMonthDay.

      See 9.5.3 fn:day-from-dateTime

      The function has been extended to handle other types including xs:time.

      See 9.5.4 fn:hours-from-dateTime

      See 9.5.5 fn:minutes-from-dateTime

      The function has been extended to handle other types such as xs:gYearMonth.

      See 9.5.7 fn:timezone-from-dateTime

    135. PR 1504 

      New in 4.0

      See 13.1.11 fn:sequence-join

      Optional $separator added.

      See 18.2.17 array:join

    136. PR 1523 

      New in 4.0

      See 19.1.2 fn:schema-type

      See 19.1.4 fn:atomic-type-annotation

      See 19.1.5 fn:node-type-annotation

    137. PR 1545 

      New in 4.0

      See 9.6.4 fn:civil-timezone

    138. PR 1570 

      New in 4.0

      See 19.1.3 fn:type-of

    139. PR 1703 

      The order of entries in maps is retained.

      See 14.3.4 fn:parse-json

      Ordered maps are introduced.

      See 17.1 Ordering of Maps

      Enhanced to allow for ordered maps.

      See 17.4.6 map:filter

      See 17.4.7 map:find

      See 17.4.8 map:for-each

      See 17.4.17 map:put

      See 17.4.18 map:remove

    G.2 Changes to Casts and Constructor Functions

    1. The keyword for the argument has changed from arg to value.

    2. The argument is now optional, and defaults to the context value (which is atomized if necessary). This change aligns constructor functions such as xs:string, xs:boolean, and xs:numeric with fn:string, fn:boolean, and fn:number.

    G.3 Miscellaneous Changes

    1. The semantics of the HTML case-insensitive collation "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive" are now defined normatively in this specification rather than by reference to the living HTML5 specification (which has changed since 3.1); and the rules now make ordering explicit rather than leaving it implementation-defined.

    2. An option in an ·option map· is now rejected if it is not described in the specification, if it is not supported by the implementation and if its name is in no namespace.

    G.4 Editorial Changes

    These changes are not highlighted in the change-marked version of the specification.

    1. The operator mapping table has been simplified so all the value comparison operators are now defined in terms of two functions (for each data type): op:XX-equal, and op:XX-less-than. The entries for op:XX-greater-than have therefore been removed.

    2. The names of parameters appearing in function signatures have been changed. This is to reflect the introduction of keyword arguments in XPath 4.0; the names chosen for parameters are now more consistent across the function library.

      In 3.1 and earlier versions, the keywords used in the specification were for documentation purposes only, so these changes do not affect backwards compatibility.

    3. Where appropriate, the phrase "the value of $x" has been replaced by the simpler $x. No change in meaning is intended.

    4. For functions that take a variable number of arguments, wherever possible the specification now gives a single function signature indicating default values for arguments that may be omitted, rather than multiple signatures.

    5. The formal specifications of array functions have been rewritten to use two new primitives: array:members which converts an array to a sequence of value records, and array:of-members which does the inverse. This has enabled many of the functions to be specified more concisely, and with less duplication between similar functions for sequences and arrays.

    6. The appendix containing illustrative user-written functions has been dropped; many of these functions are no longer needed.

    H Compatibility with Previous Versions (Non-Normative)

    This section summarizes the extent to which this specification is compatible with previous versions.

    Version 4.0 of this function library is fully backwards compatible with version 3.1, except as noted below:

    1. In fn:deep-equal, and in other functions such as fn:distinct-values that refer to fn:deep-equal, the rules for comparing values of different numeric types (for example, xs:double and xs:decimal) have changed. In previous versions of the specification, xs:decimal values were converted to xs:double, leading to a possible loss of precision. This could make comparisons non-transitive, leading to problems when grouping, and potentially (depending on the sort algorithm) with sorting. The problem has been fixed by requiring comparisons to be performed based on the exact mathematical value without any loss of precision.

      This means, for example, that deep-equal(0.2, 0.2e0) is now false, whereas in previous versions it was true. The two values are not mathematically equal, because the exact decimal equivalent of the xs:double value written as 0.2e0 is 0.200000000000000011102230246251565404236316680908203125.

      The corresponding change has not been made to the = and eq operators, because it was found to be too disruptive. For example, if the context node is the element <e price="10.0" discount="0.2"/>, there is an expectation that the expression @price - @discount = 9.8 should return true. But (assuming untyped data), the result of the subtraction is an xs:double whose precise value is 9.800000000000000710542735760100185871124267578125, so comparing the two values as decimals would return false.

    2. In previous versions, unrecognized options supplied to the $options parameter of functions such as fn:parse-json were silently ignored. In 4.0, they are rejected as a type error, unless they are QNames with a non-absent namespace, or are extensions recognized by the implementation.

    3. In version 4.0, omitting the $value of fn:error has the same effect as setting it to an empty sequence. In 3.1, the effects could be different (the effect of omitting the argument was implementation-defined).

    4. In version 3.1, the fn:deep-equal function did not merge adjacent text nodes after stripping comments and processing instructions, so the elements <a>abc<!--note1-->def</code> and <a>abcde<!--note2-->f</code> were considered non-equal. In version 4.0, the text nodes are now merged prior to comparison, so these two elements compare equal.

    5. The format of numeric values in the output of fn:xml-to-json may be different. In version 3.1, the supplied value was parsed as an xs:double and then serialized using the casting rules, resulting in an input value of 10000000 being output as 1e7. In version 4.0, the value is output as is, except for any changes (such as stripping of leading zeroes or a leading plus sign) that might be needed to ensure the result is valid JSON.

    6. In version 4.0, the function signature of fn:namespace-uri-for-prefix constrains the first argument to be either an xs:NCName or a zero-length string (the new coercion rules mean that any string in the form of an xs:NCName is acceptable). If a string is supplied that does not meet these requirements, a type error will be raised. In version 3.1, this was not an error: it came under the rule that when no namespace binding existed for the supplied prefix, the function would return an empty sequence.

      Furthermore, because the expected type of this parameter is no longer xs:string, the special coercion rules for xs:string parameters in XPath 1.0 compatibility mode no longer apply. For example, supplying xs:duration('PT1H') as the first argument will now raise a type error, rather than looking for a namespace binding for the prefix PT1H.

    7. Version 4.0 makes it clear that the casting of a value other than xs:string or xs:untypedAtomic to a list type (whether using a cast expression or a constructor function) is a type error [err:XPTY0004]XP. Previously this was defined as an error, but the kind of error and the error code were left unspecified. Accordingly, the function signatures of the constructor functions for built-in list types have been changed to use an argument type of xs:string?.

    8. The way that fn:min and fn:max compare numeric values of different types has changed. The most noticeable effect is that when these functions are applied to a sequence of xs:integer or xs:decimal values, the result is an xs:integer or xs:decimal, rather than the result of converting this to an xs:double.

    9. The type of the third argument of fn:format-number has changed from xs:string to (xs:string | xs:QName). Because the expected type of this parameter is no longer xs:string, the special coercion rules for xs:string parameters no longer apply. For example, it is no longer possible to supply an instance of xs:anyURI or (when XPath 1.0 compatibility mode is in force) an instance of xs:boolean or xs:duration.

    For compatibility issues regarding earlier versions, see the 3.1 version of this specification.

    \ No newline at end of file diff --git a/pr/1703/xpath-functions-40/function-catalog.xml b/pr/1703/xpath-functions-40/function-catalog.xml index e3f57a71a..3a507484d 100644 --- a/pr/1703/xpath-functions-40/function-catalog.xml +++ b/pr/1703/xpath-functions-40/function-catalog.xml @@ -12795,7 +12795,7 @@ else QName("", $value) instance of xs:NCName. For the default namespace, which has no prefix, the key is the zero-length string as an instance of xs:string.

    -

    The ordering of the returned map is .

    +

    The order of entries in the returned map is .

    @@ -16521,8 +16521,7 @@ declare function equal-strings( -

    It is not required that both maps have the same ordering property, - nor that the order of entries matches.

    +

    It is not required that the order of entries in the two maps should be the same.

    All the following conditions are true:

    @@ -23339,8 +23338,7 @@ map:build($input, map:get(?, 'key'), map:get(?, 'value'), $combine)

    If the input is an empty sequence, the result is an empty map.

    -

    Except when ordering=sorted, - there is no requirement that the supplied key-value pairs should have the same or compatible +

    There is no requirement that the supplied key-value pairs should have the same or compatible types. The type of a map (for example map(xs:integer, xs:string)) is descriptive of the entries it currently contains, but is not a constraint on how the map may be combined with other maps.

    @@ -24068,7 +24066,7 @@ declare function map:find($input as item()*, -

    Enhanced to allow for ordered maps.

    +

    Enhanced to allow for ordered maps.

    @@ -24138,7 +24136,7 @@ declare function map:find($input as item()*,

    There is no requirement that the type of $key and $value be consistent with the types of any existing keys and values in the supplied map.

    -

    With an ordered map, you can force the new entry to go at the end of the sequence by calling +

    It is possible to force the new entry to go at the end of the sequence by calling map:remove before calling map:put.

    @@ -24175,7 +24173,7 @@ declare function map:find($input as item()*, -

    Enhanced to allow for ordered maps.

    +

    Enhanced to allow for ordered maps.

    @@ -24356,7 +24354,7 @@ map:filter($map, fn($k, $v) { not(some($keys, atomic-equal($k, ?))) }) -

    Enhanced to allow for ordered maps.

    +

    Enhanced to allow for ordered maps.

    @@ -24440,7 +24438,7 @@ return { -

    Enhanced to allow for ordered maps.

    +

    Enhanced to allow for ordered maps.

    @@ -24509,7 +24507,7 @@ map:for-each($map, fn($key, $value) {

    The $predicate callback function may return an empty sequence (meaning false).

    -

    Enhanced to allow for ordered maps.

    +

    Enhanced to allow for ordered maps.

    @@ -27398,7 +27396,7 @@ return document { - + Determines whether special characters are represented in the XDM output in backslash-escaped form. @@ -27540,7 +27538,7 @@ return document { { "x": 2, "y": 5 }.

    If duplicate keys are encountered in a JSON object, they are handled as determined by the duplicates option defined above.

    -

    The order of entries is retained if the retain-order option is set to true.

    +

    The order of entries is retained.

    A JSON array is transformed to an array whose members are the result of converting @@ -27698,8 +27696,8 @@ return document { specification gave the default value as true, but this appears to have been an error, since it was inconsistent with examples given in the specification and with tests in the test suite.

    - -

    An option is provided to retain the order of entries in maps.

    + +

    The order of entries in maps is retained.

    diff --git a/pr/1703/xpath-functions-40/xpath-functions-40.xml b/pr/1703/xpath-functions-40/xpath-functions-40.xml index 7fe764e42..541dcacf3 100644 --- a/pr/1703/xpath-functions-40/xpath-functions-40.xml +++ b/pr/1703/xpath-functions-40/xpath-functions-40.xml @@ -6340,7 +6340,7 @@ else QName("", $value)

    If the requirement is to construct an for each in-scope namespace: the key of the entry is the namespace prefix or a zero-length string, and the corresponding value is the namespace URI.

    For namespace bindings that have a prefix, the key represents the prefix as an instance of xs:NCName. For the default namespace, which has no prefix, the key is - the zero-length string as an instance of xs:string.

    The ordering of the returned map is .

    The XML namespace is in scope for every element, so the result will always include an entry + the zero-length string as an instance of xs:string.

    The order of entries in the returned map is .

    The XML namespace is in scope for every element, so the result will always include an entry with key "xml" and corresponding value http://www.w3.org/XML/1998/namespace.

    Variables
    let $e := <z:a xmlns="http://example.org/one" xmlns:z="http://example.org/two"> <b xmlns=""/> @@ -6646,8 +6646,7 @@ declare function equal-strings( xs:gMonthDay, or xs:gDay.

    Neither $i1 nor $i2 has a timezone component.

    Both $i1 and $i2 have a timezone component and the timezone components are equal.

    All of the following conditions are true:

    $i1 is a map.

    $i2 is a map.

    Both maps have the same number of entries.

    For every entry in the first map, there is an entry in the second map that:

    has the same key (note that the collation is not used when comparing keys), and

    has the same associated value (compared using the fn:deep-equal - function, recursively).

    It is not required that both maps have the same ordering property, - nor that the order of entries matches.

    All the following conditions are true:

    $i1 is an array.

    $i2 is an array.

    Both arrays have the same number of members (array:size($i1) eq + function, recursively).

    It is not required that the order of entries in the two maps should be the same.

    All the following conditions are true:

    $i1 is an array.

    $i2 is an array.

    Both arrays have the same number of members (array:size($i1) eq array:size($i2)).

    Members in the same position of both arrays are deep-equal to each other: that is, every $p in 1 to array:size($i1) satisfies deep-equal($i1($p), $i2($p), $collation, $options).

    All the following conditions are true:

    $i1 is a function item and is not a map or array.

    $i2 is a function item and is not a map or array.

    $i1 and $i2 have the same function identity. @@ -8657,12 +8656,12 @@ serialize( in the input using JSON escape sequences, these specifications define mechanisms for dealing with them, for example by substituting a replacement character.

    fn:parse-jsonThe rules regarding use of non-XML characters in JSON texts have been relaxed.An option is provided to control how the JSON null value should be handled.An option is provided to control how JSON numbers should be formatted.The default for the escape option has been changed to false. The 3.1 specification gave the default value as true, but this appears to have been an error, - since it was inconsistent with examples given in the specification and with tests in the test suite.An option is provided to retain the order of entries in maps.

    Parses a string supplied in the form of a JSON text, returning the results typically in the form + since it was inconsistent with examples given in the specification and with tests in the test suite.The order of entries in maps is retained.

    Parses a string supplied in the form of a JSON text, returning the results typically in the form of a map or array.

    This function is deterministic, context-independent, and focus-independent.

    If the second argument is omitted or an empty sequence, the result is the same as calling the two-argument form with an empty map as the value of the $options argument.

    The first argument is a JSON text as defined in , in the form of a string. The function parses this string to return an XDM value.

    If $value is the empty sequence, the function returns the empty sequence.

    The result will also be an empty sequence if $value is the string "null".

    The $options argument can be used to control the way in which the parsing - takes place. The option parameter conventions apply.

    The entries that may appear in the $options map are as follows:

    KeyValueMeaning

    liberal?

    Determines whether deviations from the syntax of RFC7159 are permitted.

    Type: xs:boolean

    Default: false

    false + takes place. The option parameter conventions apply.

    The entries that may appear in the $options map are as follows:

    KeyValueMeaning

    liberal?

    Determines whether deviations from the syntax of RFC7159 are permitted.

    Type: xs:boolean

    Default: false

    false The input must consist of an optional byte order mark (which is ignored) followed by a string that conforms to the grammar of JSON-text in . An error must be raised if the input does not conform to the grammar. @@ -8684,11 +8683,7 @@ serialize( If duplicate keys are present in a JSON object, all but the first of a set of duplicates are ignored.
    use-last If duplicate keys are present in a JSON object, all but the last of a set of duplicates are ignored. -

    retain-order?

    Determines whether maps resulting from parsing of JSON objects should retain the input order.

    Type: xs:boolean

    Default: false

    falseAny maps resulting from parsing of JSON objects have the ordering - property set to undefined.
    trueAny maps resulting from parsing of JSON objects have the ordering - property set to insertion, and the - entry order retains the order - of entries in the input.

    escape?

    Determines whether special characters are represented in the XDM output in backslash-escaped form.

    Type: xs:boolean

    Default: false

    false +

    escape?

    Determines whether special characters are represented in the XDM output in backslash-escaped form.

    Type: xs:boolean

    Default: false

    false Any in the input, whether or not it is represented in the input by means of an escape sequence, is represented as an unescaped character @@ -8766,7 +8761,7 @@ serialize( value by recursive application of these rules. For example, the JSON text { "x": 2, "y": 5 } is transformed to the value { "x": 2, "y": 5 }.

    If duplicate keys are encountered in a JSON object, they are handled - as determined by the duplicates option defined above.

    The order of entries is retained if the retain-order option is set to true.

    A JSON array is transformed to an array whose members are the result of converting + as determined by the duplicates option defined above.

    The order of entries is retained.

    A JSON array is transformed to an array whose members are the result of converting the corresponding member of the array by recursive application of these rules. For example, the JSON text [ "a", "b", null ] is transformed (by default) to the value [ "a", "b", () ].

    A JSON string is converted to an xs:string value. @@ -11583,7 +11578,7 @@ return $result?output//body is a map whose keys are ISBNs and whose assocated values are book elements, then the expression $books-by-isbn("0470192747") returns the book element with the given ISBN. The fact that a map is a function item allows it to be passed as an argument to higher-order functions - that expect a function item as one of their arguments.

    Ordering of MapsOrdered maps are introduced.

    In 4.0, the entries in a map are ordered. The entry order of a map + that expect a function item as one of their arguments.

    Ordering of MapsOrdered maps are introduced.

    In 4.0, the entries in a map are ordered. The entry order of a map is referred to as entry order.

    The entry order of the entries in a map is defined by the function or expression that creates the map, and affects the result of functions and expressions that process multiple entries in a map, for example the function map:keys @@ -11612,12 +11607,12 @@ return $result?output//body

    A key suitable for use in a map entry.

    Type: xs:anyAtomicType

    value

    The value corresponding to the key.

    -

    Type: item()*

    *

    The record type is extensible (it may contain additional fields beyond those listed).

    Formal Specification of Maps

    The XDM data model () defines three primitive operations on maps:

    dm:empty-map constructs an empty map with a given ordering property.

    dm:map-put adds or replaces an entry in a map.

    dm:iterate-map applies a supplied function to every entry in a map.

    The functions in this section are all specified by means of equivalent expressions that either call +

    Type: item()*

    *

    The record type is extensible (it may contain additional fields beyond those listed).

    Formal Specification of Maps

    The XDM data model () defines three primitive operations on maps:

    dm:empty-map constructs an empty map.

    dm:map-put adds or replaces an entry in a map.

    dm:iterate-map applies a supplied function to every entry in a map.

    The functions in this section are all specified by means of equivalent expressions that either call these primitives directly, or invoke other functions that rely on these primitives. The specifications avoid relying on XPath language constructs that manipulate maps, such as map constructor syntax, lookup expressions, or FLWOR expressions. This is done to allow these language constructs to be specified by reference to this function library, without risk of circularity.

    There is one exception to this rule: for convenience, the notation {} is used to represent - an empty map, in preference to a call on dm:empty-map(ordering := 'undefined').

    The formal equivalents are not intended to provide a realistic way of implementating the + an empty map, in preference to a call on dm:empty-map().

    The formal equivalents are not intended to provide a realistic way of implementating the functions (in particular, any real implementation might be expected to implement map:get and map:put much more efficiently). They do, however, provide a framework that allows the correctness of a practical implementation to be verified.

    TODO: as yet there is no formal equivalent for map:find().
    Functions that Operate on Maps

    The functions defined in this section use a conventional namespace prefix map, which @@ -11741,7 +11736,7 @@ map:merge(( map:entry("Sa", "Saturday") ))

    The map:merge function can be used to construct a map with a variable number of entries, for example:

    -map:merge(//book ! map:entry(isbn, .))
    ExpressionResult
    map:entry("M", "Monday"){ "M": "Monday" }
    map:filterNew in 4.0The $predicate callback function may return an empty sequence (meaning false).Enhanced to allow for ordered maps.

    Selects entries from a map, returning a new map.

    This function is context-independent, and focus-independent.

    The function map:filter takes any map as its $map argument and applies the supplied function +map:merge(//book ! map:entry(isbn, .))
    ExpressionResult
    map:entry("M", "Monday"){ "M": "Monday" }
    map:filterNew in 4.0The $predicate callback function may return an empty sequence (meaning false).Enhanced to allow for ordered maps.

    Selects entries from a map, returning a new map.

    This function is context-independent, and focus-independent.

    The function map:filter takes any map as its $map argument and applies the supplied function to each entry in the map; the result is a new map containing those entries for which the function returns true. A return value of () from the predicate is treated as false.

    The function supplied as $predicate takes two arguments. It is called @@ -11760,7 +11755,7 @@ map:merge(//book ! map:entry(isbn, .))

    Result:{ 1: "Sunday", 7: "Saturday" }
    map:findEnhanced to allow for ordered maps.

    Searches the supplied input sequence and any contained maps and arrays for a map entry with the supplied key, +)

  • Result:{ 1: "Sunday", 7: "Saturday" }
    map:findEnhanced to allow for ordered maps.

    Searches the supplied input sequence and any contained maps and arrays for a map entry with the supplied key, and returns the corresponding values.

    This function is deterministic, context-independent, and focus-independent.

    The function map:find searches the sequence supplied as $input looking for map entries whose key is the same key as $key. The associated value in any such map entry (each being in general a sequence) @@ -11782,7 +11777,7 @@ map:merge(//book ! map:entry(isbn, .))map:for-eachEnhanced to allow for ordered maps.

    Applies a supplied function to every entry in a map, returning the +]map:for-eachEnhanced to allow for ordered maps.

    Applies a supplied function to every entry in a map, returning the sequence concatenation of the results.

    This function is deterministic, context-independent, and focus-independent.

    The function map:for-each takes any map as its $map argument and applies the supplied function to each entry in the map, in entry order; the result is the @@ -12011,8 +12006,7 @@ return fold-left($maps, dm:empty-map($options?ordering otherwise "undefined"), in the input sequence.

    Type: (fn($existing-value as item()*, $new-value as item()*) as item()*)?

    Default: fn:op(',')

    The effect of the function is equivalent to the result of the following XPath expression.

    map:build($input, map:get(?, 'key'), map:get(?, 'value'), $combine)

    The function can be made to fail with a dynamic error in the event that duplicate keys are present in the input sequence by supplying a $combine - function that invokes the fn:error function.

    If the input is an empty sequence, the result is an empty map.

    Except when ordering=sorted, - there is no requirement that the supplied key-value pairs should have the same or compatible + function that invokes the fn:error function.

    If the input is an empty sequence, the result is an empty map.

    There is no requirement that the supplied key-value pairs should have the same or compatible types. The type of a map (for example map(xs:integer, xs:string)) is descriptive of the entries it currently contains, but is not a constraint on how the map may be combined with other maps.

    Variables
    let $week := { @@ -12083,7 +12077,7 @@ map:of-pairs(( that is a map with two entries, one (with key "key") holding the key, and the other (with key "value") holding the value.

    The effect of the function is equivalent to the result of the following XPath expression.

    map:for-each($map, map:pair#2)
    Expression:map:pairs( { 1: "Y", 2: "N" } -)
    Result:({ "key": 1, "value": "Y" }, { "key": 2, "value": "N" })
    map:putEnhanced to allow for ordered maps.

    Returns a map containing all the contents of the supplied map, but with an additional entry, which replaces +)

    Result:({ "key": 1, "value": "Y" }, { "key": 2, "value": "N" })
    map:putEnhanced to allow for ordered maps.

    Returns a map containing all the contents of the supplied map, but with an additional entry, which replaces any existing entry for the same key.

    This function is deterministic, context-independent, and focus-independent.

    The function map:put returns a map that contains all entries from the supplied $map, with the exception of any entry whose key is the same key as $key, together with a new entry whose key is $key and whose associated value is $value.

    The entry order @@ -12092,7 +12086,7 @@ map:of-pairs(( then the new value replaces the old value and the position of the entry is not changed; otherwise, the new entry is added after all existing entries.

    The function is defined as follows, making use of primitive constructors and accessors defined in .

    dm:map-put($map, $key, $value)

    There is no requirement that the type of $key and $value be consistent with the types - of any existing keys and values in the supplied map.

    With an ordered map, you can force the new entry to go at the end of the sequence by calling + of any existing keys and values in the supplied map.

    It is possible to force the new entry to go at the end of the sequence by calling map:remove before calling map:put.

    Variables
    let $week := { 0: "Sonntag", 1: "Montag", 2: "Dienstag", 3: "Mittwoch", 4: "Donnerstag", 5: "Freitag", 6: "Samstag" @@ -12103,7 +12097,7 @@ map:of-pairs(( => map:keys()
    Result:"red", "green", "blue", "yellow"

    (The new entry is added at the end of the list.)

    Expression:parse-json('{ "red": 0, "green": 1, "blue" 2 }') => map:put("red", -1) => map:keys()
    Result:"red", "green", "blue"

    (Changing the value for an existing key does not - change the order of the keys.)

    map:removeEnhanced to allow for ordered maps.

    Returns a map containing all the entries from a supplied map, except those having a specified key.

    This function is deterministic, context-independent, and focus-independent.

    The function map:remove returns a map containing all the entries in $map except for any entry whose key is + change the order of the keys.)

    map:removeEnhanced to allow for ordered maps.

    Returns a map containing all the entries from a supplied map, except those having a specified key.

    This function is deterministic, context-independent, and focus-independent.

    The function map:remove returns a map containing all the entries in $map except for any entry whose key is the same key as an item in $keys.

    No failure occurs if an item in $keys does not correspond to any entry in $map; that key value is simply ignored.

    The relative position of retained entries in the result map diff --git a/pr/1703/xquery-40/shared-40-autodiff.html b/pr/1703/xquery-40/shared-40-autodiff.html index 2245e219c..888fc0ee8 100644 --- a/pr/1703/xquery-40/shared-40-autodiff.html +++ b/pr/1703/xquery-40/shared-40-autodiff.html @@ -16,7 +16,7 @@ Previous Next -

    W3C

    XQuery 4.0 and XPath 4.0 WG Review Draft

    W3C Editor's Draft 14 January 2025

    This version:
    http://www.w3.org/TR/2000/WD-shared-40-20000101/
    Most recent version of XQuery and XPath:
    http://www.w3.org/TR/shared/
    Most recent Recommendation of XQuery and XPath:
    https://www.w3.org/TR/2017/REC-xpath-31-20170321/https://www.w3.org/TR/2017/REC-xquery-31-20170321/
    Editor:
    Michael Kay, Saxonica <mike@saxonica.com>

    Please check the errata for any errors or issues reported since publication.

    See also translations.


    Abstract

    XQuery 4.0 and XPath 4.0 is an expression language that allows the processing of values conforming to the data model defined in [XQuery and XPath Data Model (XDM) 4.0]. The name of the language derives from its most distinctive feature, the path expression, which provides a means of hierarchic addressing of the nodes in an XML tree. As well as modeling the tree structure of XML, the data model also includes atomic items, function items, maps, arrays, and sequences. This version of XPath supports JSON as well as XML, and adds many new functions in [XQuery and XPath Functions and Operators 4.0].

    XQuery 4.0 and XPath 4.0 is a superset of XPath 3.1. A detailed list of changes made since XPath 3.1 can be found in L Change Log.

    XML is a versatile markup language, capable of labeling the information content of diverse data sources, including structured and semi-structured documents, relational databases, and object repositories. A query language that uses the structure of XML intelligently can express queries across all these kinds of data, whether physically stored in XML or viewed as XML via middleware. This specification describes a query language called XQuery, which is designed to be broadly applicable across many types of XML data sources.

    A list of changes made since XQuery 3.1 can be found in L Change Log.

    Status of this Document

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


    1 Introduction

    Changes in 4.0 

    1. Use the arrows to browse significant changes since the 3.1 version of this specification.

    2. Sections with significant changes are marked Δ in the table of contents.

    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.

    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.

    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 [Quilt], which in turn borrowed features from several other languages, including XPath 1.0 [XML Path Language (XPath) Version 1.0], XQL [XQL], XML-QL [XML-QL], SQL [SQL], and OQL [ODMG].

    XPath was originally designed as an expression language to address the nodes of XML trees; it has since been extended to address a variety of non-XML data sources. XPath gets its name from its use of a path notation for navigating through the hierarchical structure of an XML document; similar capabilities for navigating JSON structures were added in versions 3.0 and 3.1. XPath uses a compact, non-XML syntax, allowing XPath expressions to be embedded within URIs and to be used as XML attribute values. XPath is designed to be embedded in (or invoked from) other host languages, including both languages specialized towards XML processing (such as [XSL Transformations (XSLT) Version 4.0] and XSD), and general purpose programming languages such as Java, C#, Python, and Javascript. The interface between XPath and its host language is formalized with an abstract definition of a static and dynamic context, made available by the host language to the XPath processor.

    [Definition: A host language for XPath is any environment that provides capabilities for XPath expressions to be defined and evaluated, and that supplies a static and dynamic context for their evaluation. ]

    [Definition: XQuery 4.0 and XPath 4.0 operates on the abstract, logical structure of an XML document or JSON object rather than its surface syntax. This logical structure, known as the data model, is defined in [XQuery and XPath Data Model (XDM) 4.0].]

    XQuery 4.0 is an extension of XPath 4.0.XPath 4.0 is a subset of XQuery 4.0. 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:

    • Because XQuery expands predefined entity references and character references predefined entity references and character references and XPath does not, expressions containing these produce different results in the two languages. For instance, the value of the string literal "&amp;" is & in XQuery, and &amp; in XPath. (A host language may expand predefined entity references or character references before the XPath expression is evaluated.)

    • If XPath 1.0 compatibility mode is enabled, XPath behaves differently from XQuery in a number of ways, which are noted throughout this document, and listed in K.4.2 Incompatibilities when Compatibility Mode is false .which are discussed in [XPath 4.0].

    Because these languages are so closely related, their grammars and language descriptions are generated from a common source to ensure consistency.

    XQuery 4.0 and XPath 4.0 also depends on and is closely related to the following specifications:

    Note:

    The XML-based syntax for XQuery known as XQueryX is no longer maintained.

    [Definition: An XQuery 4.0 Processor processes a query according to the XQuery 4.0 specification. ] [Definition: An XQuery 3.1 Processor processes a query according to the XQuery 3.1 specification. ] [Definition: An XQuery 3.0 Processor processes a query according to the XQuery 3.0 specification. ] [Definition: An XQuery 1.0 Processor processes a query according to the XQuery 1.0 specification. ]

    This document specifies a grammar for XQuery 4.0 and XPath 4.0, using the same basic EBNF notation used in [XML 1.0]. Unless otherwise noted (see A.3 Lexical structure), whitespace is not significant in queriesexpressions. Grammar productions are introduced together with the features that they describe, and a complete grammar is also presented in the appendix [A XQuery 4.0 and XPath 4.0 Grammar]. The appendix is the normative version.

    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:

    [178]   FunctionCall   ::=   EQNameArgumentList/* xgc: reserved-function-names */
    EQNameArgumentList/* xgc: reserved-function-names */
    /* xgc: reserved-function-names */
    /* gn: parens */
    [156]   ArgumentList   ::=   "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"

    The productions should be read as follows: A function call consists of an EQName followed by an ArgumentList. The argument list consists of an opening parenthesis, an optional list of one or more arguments (separated by commas), and a closing parenthesis.

    This document normatively defines the static and dynamic semantics of XQuery 4.0 and XPath 4.0. In this document, examples and material labeled as “Note” are provided for explanatory purposes and are not normative.

    2 Basics

    2.1 Terminology

    Changes in 4.0  

    1. The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.  [Issue 1366 PR 1498]

    The basic building block of XQuery 4.0 and XPath 4.0 is the expression, which is a string of [Unicode] characters; the version of Unicode to be used is implementation-defined. The language provides several kinds of expressions which may be constructed from keywords, symbols, and operands. In general, the operands of an expression are other expressions. XQuery 4.0 and XPath 4.0 allows expressions to be nested with full generality. (However, unlike a pure functional language, it does not allow variable substitution if the variable declaration contains construction of new nodes.)

    Note:

    This specification contains no assumptions or requirements regarding the character set encoding of strings of [Unicode] characters.

    Like XML, XQuery 4.0 and XPath 4.0 is a case-sensitive language. Keywords in XQuery 4.0 and XPath 4.0 use lower-case characters and are not reserved—that is, names in XQuery 4.0 and XPath 4.0 expressions are allowed to be the same as language keywords, except for certain unprefixed function-names listed in A.4 Reserved Function Names.

    In this specification the phrases must, must not, should, should not, may, required, and recommended, when used in normative text and rendered in small capitals, are to be interpreted as described in [RFC2119].

    Certain aspects of language processing are described in this specification as implementation-defined or implementation-dependent.

    • [Definition: Implementation-defined indicates an aspect that may differ between implementations, but must be specified by the implementer for each particular implementation.]

    • [Definition: Implementation-dependent indicates an aspect that may differ between implementations, is not specified by this or any W3C specification, and is not required to be specified by the implementer for any particular implementation.]

    A language aspect described in this specification as implementation-defined or implementation dependent may be further constrained by the specifications of a host language in which XPath is embedded.

    2.1.1 Grammar Notation

    Changes in 4.0  

    1. The EBNF notation has been extended to allow the constructs (A ++ ",") (one or more occurrences of A, comma-separated, and (A ** ",") (zero or more occurrences of A, comma-separated.   [Issue 1366 PR 1498 30 October 2024]

    The grammar of XQuery 4.0 and XPath 4.0 is defined using a version of EBNF defined in A.1.1 Notation. The notation is based on the EBNF dialect used in the XML specification, with two notable additions derived from the Invisible XML grammar:

    (A ++ ",") represents a sequence of one or more comma-separated occurrences of A.

    (A ** ",") represents a sequence of zero or more comma-separated occurrences of A.

    For example the following production rule indicates that an Expr consists of one or more occurrences of ExprSingle, separated by commas:

    [46]   Expr   ::=   (ExprSingle ++ ",")
    (ExprSingle ++ ",")

    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.

    EBNF grammar rules appear throughout the specification for ease of reference, and the entire grammar is summarized in A.1 EBNF. For XQuery 4.0 and XPath 4.0, the top-level production rule is XPath, representing an XPath expression.For XQuery 4.0 and XPath 4.0, the top-level production rule is Module, representing an XQuery module.

    2.1.2 Values

    Changes in 4.0  

    1. The term atomic value has been replaced by atomic item.   [Issue 1337 PR 1361 2 August 2024]

    [Definition: In the data model, a value is always a sequence.]

    [Definition: A sequence is an ordered collection of zero or more items.]

    [Definition: An item is either an atomic item, a node, or a function item.]

    [Definition: An atomic item is a value in the value space of an atomic type, as defined in [XML Schema 1.0] or [XML Schema 1.1].]

    [Definition: A node is an instance of one of the node kinds defined in Section 5 NodesDM.] Each node has a unique node identity, a typed value, and a string value. In addition, some nodes have a name. The typed value of a node is a sequence of zero or more atomic items. The string value of a node is a value of type xs:string. The name of a node is a value of type xs:QName.

    [Definition: A function item is an item that can be called using a dynamic function call.]

    Maps (see 4.14.1 Maps) and arrays (see 4.14.2 Arrays) are specific kinds of function items.

    [Definition: A sequence containing exactly one item is called a singleton.] An item is identical to a singleton sequence containing that item. Sequences are never nested—for example, combining the values 1, (2, 3), and ( ) into a single sequence results in the sequence (1, 2, 3). [Definition: A sequence containing zero items is called an empty sequence.]

    [Definition: The term XDM instance is used, synonymously with the term value, to denote an unconstrained sequence of items.]

    Element nodes have a property called in-scope namespaces. [Definition: The in-scope namespaces property of an element node is a set of namespace bindings, each of which associates a namespace prefix with a URI.] For a given element, one namespace binding may have an empty prefix; the URI of this namespace binding is the default namespace within the scope of the element.

    In [XML Path Language (XPath) Version 1.0], the in-scope namespaces of an element node are represented by a collection of namespace nodes arranged on a namespace axis. As of XPath 2.0, the namespace axis is deprecated and need not be supported by a host language. A host language that does not support the namespace axis need not represent namespace bindings in the form of nodes.

    Note:

    In [XML Path Language (XPath) Version 1.0], the in-scope namespaces of an element node are represented by a collection of namespace nodes arranged on a namespace axis, which is optional and deprecated in [XPath 4.0]. XQuery does not support the namespace axis and does not represent namespace bindings in the form of nodes.

    However, where other specifications such as [XSLT and XQuery Serialization 4.0] refer to namespace nodes, these nodes may be synthesized from the in-scope namespaces of an element node by interpreting each namespace binding as a namespace node. An application that needs to create a set of namespace nodes to represent these bindings for an element bound to $e can do so using the following code.

    in-scope-prefixes($e) ! namespace {.}{ namespace-uri-for-prefix(., $e)}

    2.1.3 Namespaces and QNames

    [Definition: An expanded QName is a triple: its components are a prefix, a local name, and a namespace URI. In the case of a name in no namespace, the namespace URI and prefix are both absent. In the case of a name in the default namespace, the prefix is absent.] When comparing two expanded QNames, the prefixes are ignored: the local name parts must be equal under the Unicode codepoint collation (Section 5.3.1 CollationsFO), and the namespace URI parts must either both be absent, or must be equal under the Unicode codepoint collation.

    In the XQuery 4.0 and XPath 4.0 grammar, QNames representing the names of elements, attributes, functions, variables, types, or other such constructs are written as instances of the grammatical production EQName.

    [265]   EQName   ::=   QName | URIQualifiedName
    QName | URIQualifiedName
    [285]   QName   ::=   [http://www.w3.org/TR/REC-xml-names/#NT-QName]Names/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml-names/#NT-QName]Names/* xgc: xml-version */
    /* xgc: xml-version */
    [264]   URILiteral   ::=   StringLiteral
    StringLiteral
    [274]   URIQualifiedName   ::=   BracedURILiteralNCName/* ws: explicit */
    BracedURILiteralNCName/* ws: explicit */
    /* ws: explicit */
    [275]   BracedURILiteral   ::=   "Q" "{" (PredefinedEntityRef | CharRef | [^&{}])* "}"/* ws: explicit */
    "Q" "{" (PredefinedEntityRef | CharRef | [^&{}])* "}"/* ws: explicit */
    /* ws: explicit */
    [286]   NCName   ::=   [http://www.w3.org/TR/REC-xml-names/#NT-NCName]Names/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml-names/#NT-NCName]Names/* xgc: xml-version */
    /* xgc: xml-version */

    The EQName production allows a QName to be written in one of three ways:

    • local-name only (for example, invoice).

      A name written in this form has no prefix, and the rules for determining the namespace depend on the context in which the name appears. This form is a lexical QName.

    • prefix plus local-name (for example, my:invoice).

      In this case the prefix and local name of the QName are as written, and the namespace URI is inferred from the prefix by examining the in-scope namespaces in the static context where the QName appears; the context must include a binding for the prefix. This form is a lexical QName.

    • URI plus local-name (for example, Q{http://example.com/ns}invoice).

      In this case the local name and namespace URI are as written, and the prefix is absent. This way of writing a QName is context-free, which makes it particularly suitable for use in queriesexpressions that are generated by software. This form is a URIQualifiedName. If the BracedURILiteral has no content (for example, Q{}invoice) then the namespace URI of the QName is absent.

    [Definition: A lexical QName is a name that conforms to the syntax of the QName production].

    The namespace URI value in a URIQualifiedName is whitespace normalized according to the rules for the xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2. It is a static error [err:XQST0070] if the namespace URI for an EQName is http://www.w3.org/2000/xmlns/.

    Here are some examples of EQNames:

    This document uses the following namespace prefixes to represent the namespace URIs with which they are listed. Although these prefixes are used within this specification to refer to the corresponding namespaces, not all of these bindings will necessarily be present in the static context of every expression, and authors are free to use different prefixes for these namespaces, or to bind these prefixes to different namespaces.

    • xml: http://www.w3.org/XML/1998/namespace

    • xs: http://www.w3.org/2001/XMLSchema

    • xsi: http://www.w3.org/2001/XMLSchema-instance

    • fn: http://www.w3.org/2005/xpath-functions

    • array: http://www.w3.org/2005/xpath-functions/array

    • map: http://www.w3.org/2005/xpath-functions/map

    • math: http://www.w3.org/2005/xpath-functions/math

    • err: http://www.w3.org/2005/xqt-errors (see 2.4.2 Identifying and Reporting Errors).

    • local: http://www.w3.org/2005/xquery-local-functions (see 5.18 Function Declarations.)

    • output: http://www.w3.org/2010/xslt-xquery-serialization

    • xq: http://www.w3.org/2012/xquery

    [Definition: Within this specification, the term URI refers to a Universal Resource Identifier as defined in [RFC3986] and extended in [RFC3987] with the new name IRI.] The term URI has been retained in preference to IRI to avoid introducing new names for concepts such as “Base URI” that are defined or referenced across the whole family of XML specifications.

    Note:

    In most contexts, processors are not required to raise errors if a URI is not lexically valid according to [RFC3986] and [RFC3987]. See 2.5.5 URI Literalsand 4.12.1.2 Namespace Declaration Attributes for details.

    2.2 Expression Context

    [Definition: The expression context for a given expression consists of all the information that can affect the result of the expression.]

    This information is organized into two categories called the static context and the dynamic context.

    2.2.1 Static Context

    Changes in 4.0  

    1. The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.   [Issue 296 PR 1181 30 April 2024]

    2. 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.   [Issue 1343 PR 1344 23 September 2024]

    3. The context value static type, which was there purely to assist in static typing, has been dropped.   [Issue 1495 ]

    [Definition: The static context of an expression is the information that is available during static analysis of the expression, prior to its evaluation.] This information can be used to decide whether the expression contains a static error.

    The individual components of the static context are described below.

    In XQuery 4.0 and XPath 4.0, the static context for an expression is largely defined by the host language, that is, by the calling environment that causes an XPath expression to be evaluated. Most of the static context components are constant throughout an expression; the only exception is in-scope variables. (There are constructs in the language, such as the ForExpr and LetExpr, that add additional variables to the static context of their subexpressions.)

    In XQuery 4.0 and XPath 4.0, the static context for an expression is largely defined in the query prolog of a module: see 5 Modules and Prologs. 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 import module declaration: see 5.12 Module Import.

    In addition, some expressions modify the static context for their subexpressions. The most obvious example is in-scope variables (a FLWORExpr declares bindings of local variables that are available for reference within subsequent clauses of the expression). A further example is the statically known namespaces: an element constructor may contain namespace declarations such as xmlns:p="some_uri" which cause additional namespace prefixes to be available within the content of the element constructor.

    Appendix C.1 Static Context Components gives an overview of the components in the static context and the way they are initialized.

    Some components of the static context, but not all, also affect the dynamic semantics of expressions. For example, casting of a string such as "xbrl:xbrl" to an xs:QName might expand the prefix xbrl to the namespace URI http://www.xbrl.org/2003/instance using the statically known namespaces from the static context; since the input string "xbrl:xbrl" is in general not known until execution time (it might be read from a source document), this means that the values of the statically known namespaces must be available at execution time.

    • [Definition: XPath 1.0 compatibility mode.This component must be set by all host languages that include XPath 3.1 as a subset, indicating whether rules for compatibility with XPath 1.0 are in effect. XQuery sets the value of this component to false. This value is true if rules for backward compatibility with XPath Version 1.0 are in effect; otherwise it is false. ]

    • [Definition: Statically known namespaces. This is a mapping from prefix to namespace URI that defines all the namespaces that are known during static processing of a given expression.]

      The URI value is whitespace normalized according to the rules for the xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2.

      The statically known namespaces may include a binding for the zero-length prefix; however, this is used only in limited circumstances because the rules for resolving unprefixed QNames depend on how such a name is used.

      Note the difference between in-scope namespaces, which is a dynamic property of an element node, and statically known namespaces, which is a static property of an expression.

      Some namespaces are predefined; additional namespaces can be added to the statically known namespaces by namespace declarations, schema imports, or module imports in a Prolog, by a module declaration, and by namespace declaration attributes in direct element constructors.

    • [Definition: Default namespace for elements and types. This is either a namespace URI, or the special value "##any", or absentDM. This indicates how unprefixed QNames are interpreted when they appear in a position where an element name or type name is expected.]

      • 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 xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2.

      • The special value "##any" indicates that:

        • When an unprefixed QName is used as a name test for selecting named elements in an axis step, the name test will match an element having the specified local name, in any namespace or none.

        • 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 xs namespace, http://www.w3.org/2001/XMLSchema.

        • In any other context, an unprefixed QName represents a name in no namespace.

      • If the value is absentDM, an unprefixed QName representing an element or type name is interpreted as being in no namespace.

    • [Definition: Default function namespace. This is either a namespace URI, or absentDM. The namespace URI, if present, is used for any unprefixed QName appearing in a position where a function name is expected.] The URI value is whitespace-normalized according to the rules for the xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2

      In its simplest form its value is simply a whitespace-normalized xs:anyURI value (most commonly, the URI http://www.w3.org/2005/xpath-functions) to be used as the default namespace for unprefixed function names. However, the use of a more complex algorithm is not precluded, for example an algorithm which searches multiple namespaces for a matching name.

      In XQuery, a default function namespace can be declared in the prolog in a default function namespace declaration (see 5.14 Default Namespace Declaration); in the absence of such a declaration, the namespace http://www.w3.org/2005/xpath-functions is used.

    • [Definition: In-scope schema definitions is a generic term for all the element declarations, attribute declarations, and schema type definitions that are in scope during static analysis of an expression.] It includes the following three parts:

    • [Definition: In-scope variables. This is a mapping from expanded QName to type. It defines the set of variables that are available for reference within an expression. The expanded QName is the name of the variable, and the type is the static type of the variable.]

      Variable declarations in a Prolog are added to in-scope variables. An expression that binds a variable extends the in-scope variables, within the scope of the variable, with the variable and its type. Within the body of an inline function expression or user-defined function, the in-scope variables are extended by the names and types of the function parameters.

      The static type of a variable may either be declared in a query or inferred by static type inference as discussed in 2.3.3.1 Static Analysis Phase.

    • [Definition: In-scope named item types. This is a mapping from expanded QName to named item types.]

      [Definition: A named item type is an ItemType identified by an expanded QName.]

      Named item types serve two purposes:

      • 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.

      • They allow the definition of recursive types, which are useful for describing recursive data structures such as lists and trees. For details see 3.2.8.3.1 Recursive Record Types.

      Note:

      In XQuery, named item types can be declared in the Query Prolog.

      Named item types can be defined in a host language such as XQuery 4.0 and in XSLT 4.0, but not in XPath 4.0 itself. They are available in XPath only if the host language provides the ability to define them.

    • [Definition: Statically known function definitions. This is a set of function definitions.]

      Function definitions are described in 2.2.1.1 Function Definitions.

    • [Definition: Statically known collations. This is an implementation-defined mapping from URI to collation. It defines the names of the collations that are available for use in processing queries and expressions.] [Definition: A collation is a specification of the manner in which strings and URIs are compared and, by extension, ordered. For a more complete definition of collation, see Section 5.3 Comparison of stringsFO.]

    • [Definition: Construction mode. The construction mode governs the behavior of element and document node constructors. If construction mode is preserve, the type of a constructed element node is xs:anyType, and all attribute and element nodes copied during node construction retain their original types. If construction mode is strip, the type of a constructed element node is xs:untyped; all element nodes copied during node construction receive the type xs:untyped, and all attribute nodes copied during node construction receive the type xs:untypedAtomic.]

    • [Definition: Default order for empty sequences. This component controls the processing of empty sequences and NaN values as ordering keys in an order by clause in a FLWOR expression, as described in 4.13.9 Order By Clause.] Its value may be greatest or least.

    • [Definition: Boundary-space policy. This component controls the processing of boundary whitespace by direct element constructors, as described in 4.12.1.4 Boundary Whitespace.] Its value may be preserve or strip.

    • [Definition: Copy-namespaces mode. This component controls the namespace bindings that are assigned when an existing element node is copied by an element constructor, as described in 4.12.1 Direct Element Constructors. Its value consists of two parts: preserve or no-preserve, and inherit or no-inherit.]

    • [Definition: Static Base URI. 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 xsl:import and xsl:include in XSLT. All expressions within a module have the same static base URI. The Static Base URI can be set using a base URI declaration. If E is a subexpression of F then the Static Base URI of E is the same as the Static Base URI of F. There are no constructs in XPath that require resolution of relative URI references during static analysis.

      Relative URI references are resolved as described in 2.5.6 Resolving a Relative URI Reference.

      At execution time, relative URIs supplied to functions such as fn:doc are resolved against the Executable Base URI, which may or may not be the same as the Static Base URI.

    • [Definition: Statically known decimal formats. This is a mapping from QNames to decimal formats, with one default format that has no visible name, referred to as the unnamed decimal format. Each format is available for use when formatting numbers using the fn:format-number function.]

      Decimal formats are described in 2.2.1.2 Decimal Formats.

    2.2.1.1 Function Definitions

    [Definition: A function definition contains information used to evaluate a static function call, including the name, parameters, and return type of the function.]

    The properties of a function definition include:

    • The function name, which is an expanded QName.

    • Parameter definitions, specifically:

      The names of the parameters must be distinct.

      [Definition: A function definition has an arity range, which is a range of consecutive non-negative integers. If the function definition has M required parameters and N optional parameters, then its arity range is from M to M+N inclusive.]

      The static context may contain several function definitions with the same name, but the arity ranges of two such function definitions must not overlap. For example, if two function definitions A and B have the same function name, then:

      • It is acceptable for A to have two required parameters and no optional parameters, while B has three required parameters and one optional parameter.

      • It is not acceptable for A to have one required parameter while B has three optional parameters.

      Note:

      Implementations must ensure that no two function definitions have the same expanded QName and overlapping arity ranges (even if the signatures are consistent).

      XQuery and XSLT enforce this rule by defining a static error if the rule is violated; but further constraints may be needed if an API allows external functions to be added to the static context.

    • A return type (a sequence type)

    • The function category, which is one of application, system, or external:

      • [Definition: Application functions are function definitions written in a host language such as XQuery or XSLT whose syntax and semantics are defined in this family of specifications. Their behavior (including the rules determining the static and dynamic context) follows the rules for such functions in the relevant host language specification.] The most common application functions are functions written by users in XQuery or XSLT.

      • [Definition: System functions include the functions defined in [XQuery and XPath Functions and Operators 4.0], functions defined by the specifications of a host language, constructor functions for atomic types, and any additional functions provided by the implementation. System functions are sometimes called built-in functions.]

        The 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 dynamic context of the caller). Such functions are said to be context dependent.

      • [Definition: External functions can be characterized as functions that are neither part of the processor implementation, nor written in a language whose semantics are under the control of this family of specifications. The semantics of external functions, including any context dependencies, are entirely implementation-defined. In XSLT, external functions are called Section 24.1 Extension Functions XT30. ]

        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.

      [Definition: A function definition is said to be context dependent if its result depends on the static or dynamic context of its caller. A function definition may be context-dependent for some arities in its arity range, and context-independent for others: for example fn:name#0 is context-dependent while fn:name#1 is context-independent.]

      Note:

      Some system functions, such as fn:position, fn:last, and fn:static-base-uri, exist for the sole purpose of providing information about the static or dynamic context of their caller.

      Note:

      Application functions are context dependent only to the extent that they define optional parameters with default values that are context dependent.

    • A (possibly empty) set of function annotations

      In XQuery, function annotations are described in 5.15 Annotations.

    • 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.

    The function definitions present in the static context are available for reference from a static function call, or from a named function reference.

    2.2.1.2 Decimal Formats

    Changes in 4.0  

    1. 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.   [Issue 1048 PR 1250 3 June 2024]

    Each decimal format defines a set of properties, which control the interpretation of characters in the picture string supplied to the fn:format-number function, and also specify characters to be used in the result of formatting the number.

    Each property potentially has two parts: a marker character M used in the picture string to mark an insertion position, and a rendition string R to indicate how the relevant property is to be rendered in the output of the fn:format-number function. In the list below properties are annotated with (M), (R), or (M, R) to indicate whether the property includes a marker character, a rendition string, or both.

    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 M:R. For example the percent property may be expressed as %:pc to indicate that the character % will be used in the picture string, and the string pc will be used in the function output. In this example, the value 0.10, formatted with the picture string #0%, results in the output 10pc

    • [Definition: decimal-separator(M, R) is used to separate the integer part of the number from the fractional part. The default value for both the marker and the rendition is U+002E (FULL STOP, PERIOD, .) .]

    • [Definition: exponent-separator(M, R) is used to separate the mantissa from the exponent in scientific notation. The default value for both the marker and the rendition is U+0065 (LATIN SMALL LETTER E, e) .]

    • [Definition: grouping-separator(M, R) is used to separate groups of digits (for example as a thousands separator). The default value for both the marker and the rendition is U+002C (COMMA, ,) .]

    • [Definition: percent(M, R) is used to indicate that the number is written as a per-hundred fraction; the default value for both the marker and the rendition is U+0025 (PERCENT SIGN, %) .]

    • [Definition: per-mille(M, R) is used to indicate that the number is written as a per-thousand fraction; the default value for both the marker and the rendition is U+2030 (PER MILLE SIGN, ) .]

    • [Definition: zero-digit(M) is the character used in the picture string to represent the digit zero; the default value is U+0030 (DIGIT ZERO, 0) . This character must be a digit (category Nd in the Unicode property database), and it must have the numeric value zero. This property implicitly defines the ten Unicode characters that are used to represent the values 0 to 9 in the function output: Unicode is organized so that each set of decimal digits forms a contiguous block of characters in numerical sequence. Within the picture string any of these ten character can be used (interchangeably) as a place-holder for a mandatory digit. Within the final result string, these ten characters are used to represent the digits zero to nine.]

    • [Definition: digit(M) is a character used in the picture string to represent an optional digit; the default value is U+0023 (NUMBER SIGN, #) .]

    • [Definition: pattern-separator(M) is a character used to separate positive and negative sub-pictures in a picture string; the default value is U+003B (SEMICOLON, ;) .]

    • [Definition: infinity(R) is the string used to represent the double value infinity (INF); the default value is the string "Infinity" ]

    • [Definition: NaN(R) is the string used to represent the double value NaN (not a number); the default value is the string "NaN" ]

    • [Definition: minus-sign(R) is the string used to mark negative numbers; the default value is U+002D (HYPHEN-MINUS, -) .]

    2.2.2 Dynamic Context

    Changes in 4.0  

    1. 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.   [Issue 129 PR 368 14 September 2023]

    2. The rules regarding the document-uri property of nodes returned by the fn:collection function have been relaxed.   [Issue 1161 PR 1265 11 June 2024]

    [Definition: The dynamic context of an expression is defined as information that is needed for the dynamic evaluation of an expression, beyond any information that is needed from the static context.] If evaluation of an expression relies on some part of the dynamic context that is absentDM, a type error is raised [err:XPDY0002].

    Note:

    In previous versions of the specification, this was classified as a dynamic error. The change allows the error to be raised during static analysis when possible; for example a function written as fn($x) { @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.

    There are other cases where static detection of the error is not possible.

    The individual components of the dynamic context are described below.

    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 and XPath 4.0 expressions to be invoked from a host language. Application Programming Interfaces are outside the scope of this specification. In XQuery 4.0 and XPath 4.0, some aspects of the dynamic context (for example, initial values of variables) are defined within the query prolog. The dynamic context for inner subexpressions may be set by their containing expressions: for example in a mapping expression E1!E2, the value of the focus (part of the dynamic context) for evaluation of E2 is defined by the evaluation of E1.

    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 available documents, 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.

    Rules governing the initialization and alteration of these components can be found in C.2 Dynamic Context Components.Further rules governing the semantics of these components can be found in D.2 Dynamic Context Components.

    The components of the dynamic context are listed below.

    [Definition: The first three components of the dynamic context (context value, context position, and context size) are called the focus of the expression. ] The focus enables the processor to keep track of which items are being processed by the expression. If any component in the focus is defined, all components of the focus are defined.If any component in the focus is defined, both the context value and context position are known.

    Note:

    If any component in the focus is defined, context size is usually defined as well. However, when streaming, the context size cannot be determined without lookahead, so it may be undefined. If so, expressions like last() will raise a dynamic error because the context size is undefined.

    [Definition: A fixed focus is a focus for an expression that is evaluated once, rather than being applied to a series of values; in a fixed focus, the context value is set to one specific value, the context position is 1, and the context size is 1.]

    [Definition: A singleton focus is a fixed focus in which the context value is a singleton item.]. With a singleton focus, the context value is a single item, the context position is 1, and the context size is 1.

    Certain language constructs, notably the path operatorE1/E2, the simple map operatorE1!E2, and the predicateE1[E2], create a new focus for the evaluation of a sub-expression. In these constructs, E2 is evaluated once for each item in the sequence that results from evaluating E1. Each time E2 is evaluated, it is evaluated with a different focus. The focus for evaluating E2 is referred to below as the inner focus, while the focus for evaluating E1 is referred to as the outer focus. The inner focus is used only for the evaluation of E2. Evaluation of E1 continues with its original focus unchanged.

    • [Definition: The context value is the value currently being processed.] In many cases (but not always), the context value will be a single item. [Definition: When the context value is a single item, it can also be referred to as the context item; when it is a single node, it can also be referred to as the context node.] The context value is returned by an expression consisting of a single dot (.). When an expression E1/E2 or E1[E2] is evaluated, each item in the sequence obtained by evaluating E1 becomes the context value in the inner focus for an evaluation of E2.

      [Definition: In the dynamic context of every module in a query, the context value component must have the same setting. If this shared setting is not absentDM, it is referred to as the initial context value. ]

    • [Definition: The context position 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 fn:position(). When an expression E1/E2 or E1[E2] is evaluated, the context position in the inner focus for an evaluation of E2 is the position of the context value in the sequence obtained by evaluating E1. The position of the first item in a sequence is always 1 (one). The context position is always less than or equal to the context size.

    • [Definition: The context size is the number of 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 fn:last(). When an expression E1/E2 or E1[E2] is evaluated, the context size in the inner focus for an evaluation of E2 is the number of items in the sequence obtained by evaluating E1.

    • [Definition: Variable values. This is a mapping from expanded QName to value. It contains the same expanded QNames as the in-scope variables in the static context for the expression. The expanded QName is the name of the variable and the value is the dynamic value of the variable, which includes its dynamic type.]

    • [Definition: Dynamically known function definitions. This is a set of function definitions. It includes the statically known function definitions as a subset, but may include other function definitions that are not known statically. ]

      The function definitions in the dynamic context are used primarily by the fn:function-lookup function.

      If two function definitions in the dynamically known function definitions have the same name, then their arity ranges must not overlap.

      Note:

      The reason for allowing named functions to be available dynamically beyond those that are available statically is primarily to allow for cases where the run-time execution environment is significantly different from the compile-time environment. This could happen, for example, if a stylesheet or query is compiled within a web server and then executed in the web browser. The fn:function-lookup function allows dynamic discovery of resources that were not available statically.

    • [Definition: Current dateTime. This information represents an implementation-dependent point in time during the processing of a queryan expression, and includes an explicit timezone. It can be retrieved by the fn:current-dateTime function. If called multiple times during the execution of a queryan expression, this function always returns the same result.]

    • [Definition: Implicit timezone. This is the timezone to be used when a date, time, or dateTime value that does not have a timezone is used in a comparison or arithmetic operation. The implicit timezone is an implementation-defined value of type xs:dayTimeDuration. See Section 3.2.7.3 Timezones XS1-2 or Section 3.3.7 dateTime XS11-2 for the range of valid values of a timezone.]

    • [Definition: Executable Base URI. This is an absolute URI used to resolve relative URIs during the evaluation of expressions; it is used, for example, to resolve a relative URI supplied to the fn:doc or fn:unparsed-text functions. ]

      URIs are resolved as described in 2.5.6 Resolving a Relative URI Reference.

      The function fn:static-base-uri, despite its name, returns the value of the Executable Base URI.

      In many straightforward processing scenarios, the Executable Base URI in the dynamic context will be the same as the Static Base URI for the corresponding expression in the static context. There are situations, however, where they may differ:

      • 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 Static Base URI, while resources needed during execution (such as reference data files) will be located on the production machine, accessed via the Executable Base URI.

      • When the fn:static-base-uri 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 fn:static-base-uri(), allowing the code in the function body to resolve the relative URI against the executable base URI of the caller.

    • [Definition: Default collation. This identifies one of the collations in statically known collations as the collation to be used by functions and operators for comparing and ordering values of type xs:string and xs:anyURI (and types derived from them) when no explicit collation is specified.]

      Note:

      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 fn:default-collation 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.

    • [Definition: Default language. This is the natural language used when creating human-readable output (for example, by the functions fn:format-date and fn:format-integer) if no other language is requested. The value is a language code as defined by the type xs:language.]

    • [Definition: Default calendar. This is the calendar used when formatting dates in human-readable output (for example, by the functions fn:format-date and fn:format-dateTime) if no other calendar is requested. The value is a string.]

    • [Definition: Default place. This is a geographical location used to identify the place where events happened (or will happen) when processing dates and times using functions such as fn:format-date, fn:format-dateTime, and fn:civil-timezone, if no other place is specified. It is used when translating timezone offsets to civil timezone names, and when using calendars where the translation from ISO dates/times to a local representation is dependent on geographical location. Possible representations of this information are an ISO country code or an Olson timezone name, but implementations are free to use other representations from which the above information can be derived. The only requirement is that it should uniquely identify a civil timezone, which means that country codes for countries with multiple timezones, such as the United States, are inadequate.]

    • [Definition: Available documents. This is a mapping of strings to document nodes. Each string represents the absolute URI of a resource. The document node is the root of a tree that represents that resource using the data model. The document node is returned by the fn:doc function when applied to that URI.] The set of available documents may be empty.

    • [Definition: Available text resources. This is a mapping of strings to text resources. Each string represents the absolute URI of a resource. The resource is returned by the fn:unparsed-text function when applied to that URI.] The set of available text resources may be empty.

    • [Definition: Available collections. This is a mapping of strings to sequences of items. Each string represents the absolute URI of a resource. The sequence of items represents the result of the fn:collection function when that URI is supplied as the argument. ] The set of available collections may be empty.

      Ideally, for every document node D that is in the target of a mapping in available item collections, or that is the root of a tree containing such a node, the document-uri property of D should either be absent, or should be a URI U such that available documents contains a mapping from U to D.

      Note:

      That is to say, the document-uri property of nodes returned by the fn:collection function should be such that calling fn:doc with that URI returns the relevant node.

      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.

    • [Definition: Default collection. This is the sequence of items that would result from calling the fn:collection function with no arguments.] The value of default collection may be initialized by the implementation.

    • [Definition: Available URI collections. This is a mapping of strings to sequences of URIs. The string represents the absolute URI of a resource which can be interpreted as an aggregation of a number of individual resources each of which has its own URI. The sequence of URIs represents the result of the fn:uri-collection function when that URI is supplied as the argument. ] There is no implication that the URIs in this sequence can be successfully dereferenced, or that the resources they refer to have any particular media type.

      Note:

      An implementation may maintain some consistent relationship between the available collections and the available URI collections, for example by ensuring that the result of fn:uri-collection(X)!fn:doc(.) is the same as the result of fn:collection(X). However, this is not required. The fn:uri-collection function is more general than fn:collection in that fn:collection allows access to nodes that might lack individual URIs, for example nodes corresponding to XML fragments stored in the rows of a relational database.

    • [Definition: Default URI collection. This is the sequence of URIs that would result from calling the fn:uri-collection function with no arguments.] The value of default URI collection may be initialized by the implementation.

    • [Definition: Environment variables. This is a mapping from names to values. Both the names and the values are strings. The names are compared using an implementation-defined collation, and are unique under this collation. The set of environment variables is implementation-defined and may be empty.]

      Note:

      A possible implementation is to provide the set of POSIX environment variables (or their equivalent on other operating systems) appropriate to the process in which the query is initiatedexpression is evaluated.

    2.3 Processing Model

    Changes in 4.0  

    1. The static typing option has been dropped.   [Issue 1343 PR 1344 3 September 2024]

    The semantics of XQuery 4.0 and XPath 4.0 are defined in terms of the data model and the expression context.

    Processing                          Model OverviewProcessing                          Model Overview

    Figure 1: Processing Model Overview

    Figure 1 provides a schematic overview of the processing steps that are discussed in detail below. Some of these steps are completely outside the domain of XQuery 4.0 and XPath 4.0; in Figure 1, these are depicted outside the line that represents the boundaries of the language, an area labeled external processing. The external processing domain includes generation of XDM instances that represent the data to be queried (see 2.3.1 Data Model Generation), schema import processing (see 2.3.2 Schema Import Processing), and serialization (see 2.3.5 Serialization). The area inside the boundaries of the language is known as the query processing domainXPath processing domain, which includes the static analysis and dynamic evaluation phases (see 2.3.3 Expression Processing). Consistency constraints on the queryXPath processing domain are defined in 2.3.6 Consistency Constraints.

    2.3.1 Data Model Generation

    The input data for a queryan expression must be represented as one or more XDM instances. This process occurs outside the domain of XQuery 4.0 and XPath 4.0, which is why Figure 1 represents it in the external processing domain.

    In many cases the input data might originate as XML. Here are some steps by which an XML document might be converted to an XDM instance:

    1. A document may be parsed using an XML parser that generates an XML Information Set (see [XML Infoset]). The parsed document may then be validated against one or more schemas. This process, which is described in [XML Schema 1.0 Part 1] or [XML Schema 1.1 Part 1], results in an abstract information structure called the Post-Schema Validation Infoset (PSVI). If a document has no associated schema, its Information Set is preserved. (See DM1 in Figure 1)

    2. The Information Set or PSVI may be transformed into an XDM instance by a process described in [XQuery and XPath Data Model (XDM) 4.0]. (See DM2 in Figure 1)

    The above steps provide an example of how an XDM instance 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 and XPath 4.0 is defined in terms of the data model, but it does not place any constraints on how XDM instances are constructed.

    The remainder of this section is concerned with the common case where XML data is being processed.

    [Definition: Each element node and attribute node in an XDM instance has a type annotation (described in Section 2.8 Schema InformationDM). The type annotation of a node is a reference to a schema type. ] The type-name of a node is the name of the type referenced by its type annotation (but note that the type annotation can be a reference to an anonymous type). If the XDM instance was derived from a validated XML document as described in Section 3.3 Construction from a PSVIDM, the type annotations of the element and attribute nodes are derived from schema validation. XQuery 4.0 and XPath 4.0 does not provide a way to directly access the type annotation of an element or attribute node.

    The value of an attribute is represented directly within the attribute node. An attribute node whose type is unknown (such as might occur in a schemaless document) is given the type annotationxs:untypedAtomic.

    The value of an element is represented by the children of the element node, which may include text nodes and other element nodes. The type annotation of an element node indicates how the values in its child text nodes are to be interpreted. An element that has not been validated (such as might occur in a schemaless document) is annotated with the schema typexs:untyped. An element that has been validated and found to be partially valid is annotated with the schema type xs:anyType. If an element node is annotated as xs:untyped, all its descendant element nodes are also annotated as xs:untyped. However, if an element node is annotated as xs:anyType, some of its descendant element nodes may have a more specific type annotation.

    2.3.2 Schema Import Processing

    The in-scope schema definitions in the static context 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 2.3.6 Consistency Constraints.

    The in-scope schema definitions in the static context are provided by the host language (see step SI1 in Figure 1) and must satisfy the consistency constraints defined in 2.3.6 Consistency Constraints.

    2.3.3 Expression Processing

    XQuery 4.0 and XPath 4.0 defines two phases of processing called the static analysis phase and the dynamic evaluation phase (see Figure 1). During the static analysis phase, static errors, dynamic errors, or type errors may be raised. During the dynamic evaluation phase, only dynamic errors or type errors may be raised. These kinds of errors are defined in 2.4.1 Kinds of Errors.

    Within each phase, an implementation is free to use any strategy or algorithm whose result conforms to the specifications in this document.

    2.3.3.1 Static Analysis Phase

    [Definition: The static analysis phase depends on the expression itself and on the static context. The static analysis phase does not depend on input data (other than schemas).]

    During the static analysis phase, the queryXPath expression is typically parsed into an internal representation called the operation tree (step SQ1 in Figure 1). A parse error is raised as a static error [err:XPST0003]. The static context is initialized by the implementation (step SQ2). The static context is then changed and augmented based on information in the prolog (step SQ3). If the Schema Aware Feature is supported, the in-scope schema definitions are populated with information from imported schemas. If the Module Feature is supported, the static context is extended with function declarations and variable declarations from imported modules. The static context is used to resolve schema type names, function names, namespace prefixes, and variable names (step SQ4). If a name of one of these kinds in the operation tree is not found in the static context, a static error ([err:XPST0008] or [err:XPST0017]) is raised (however, see exceptions to this rule in 3.2.7.2 Element Types and 3.2.7.3 Attribute Types.)

    The operation tree is then typically normalized by making explicit the implicit operations such as atomization and extraction of effective boolean values (step SQ5).

    During the static analysis phase, a processor may perform type analysis. The effect of type analysis is to assign a static type to each expression in the operation tree. [Definition: The static type of an expression is the best inference that the processor is able to make statically about the type of the result of the expression.] This specification does not define the rules for type analysis nor the static types that are assigned to particular expressions: the only constraint is that the inferred type must match all possible values that the expression is capable of returning.

    Examples of inferred static types might be:

    • For the expression concat(a,b) the inferred static type is xs:string

    • For the expression $a = $v the inferred static type is xs:boolean

    • For the expression $s[exp] the inferred static type has the same item type as the static type of $s, but a cardinality that allows the empty sequence even if the static type of $s does not allow an empty sequence.

    • The inferred static type of the expression data($x) (whether written explicitly or inserted into the operation tree in places where atomization is implicit) depends on the inferred static type of $x: for example, if $x has type element(*, xs:integer) then data($x) has static type xs:integer.

    In XQuery 1.0 and XPath 2.0, rules for static type inferencing were published normatively in [XQuery 1.0 and XPath 2.0 Formal Semantics], but implementations were allowed to refine these rules to infer a more precise type where possible. In subsequent versions, the rules for static type inferencing are entirely implementation-dependent.

    Every kind of expression also imposes requirements on the type of its operands. For example, with the expression substring($a, $b, $c), $a must be of type xs:string (or something that can be converted to xs:string by the function calling rules), while $b and $c must be numeric.

    A processor may 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 coercion rules. For example, given the call fn:upper-case($s), the processor may raise an error if the declared or inferred type of $s is xs:integer, but not if it is xs:anyAtomicType.

    In addition, type analysis may conclude that an expression is implausible. Implausible expressions may be considered erroneous unless such checks have been disabled. This topic is described further in 2.4.6 Implausible Expressions.

    Alternatively, the processor may defer all type checking until the dynamic evaluation phase.

    2.3.3.2 Dynamic Evaluation Phase

    [Definition: The dynamic evaluation phase is the phase during which the value of an expression is computed.] It is dependent on successful completion of the static analysis phase.

    The dynamic evaluation phase can occur only if no errors were detected during the static analysis phase.

    The dynamic evaluation phase depends on the operation tree of the expression being evaluated (step DQ1), on the input data (step DQ4), and on the dynamic context (step DQ5), which in turn draws information from the external environment (step DQ3) and the static context (step DQ2). The dynamic evaluation phase may create new data-model values (step DQ4) and it may extend the dynamic context (step DQ5)—for example, by binding values to variables.

    [Definition: Every value matches one or more sequence types. A value is said to have a dynamic typeT if it matches (or is an instance of) the sequence type T.]

    In many cases (but not all), one of the dynamic types that a value matches will be a subtype of all the others, in which case it makes sense to speak of “the dynamic type” of the value as meaning this single most specific type. In other cases (examples are empty maps and empty arrays) none of the dynamic types is more specific than all the others.

    Note:

    An atomic item has a type annotation which will always be a subtype of all the other types that it matches; we can therefore refer to this as the dynamic type of the atomic item without ambiguity.

    A value may match a dynamic type that is more specific than the static type of the expression that computed it (for example, the static type of an expression might be xs:integer*, denoting a sequence of zero or more integers, but at evaluation time its value may be an instance of xs:integer, denoting exactly one integer).

    If an operand of an expression does not have a dynamic type that is a subtype of the static type required for that operand, a type error is raised [err:XPTY0004].

    Even though static typing can catch many type errors before an expression is executed, it is possible for an expression to raise an error during evaluation that was not detected by static analysis. For example, an expression may contain a cast of a string into an integer, which is statically valid. However, if the actual value of the string at run time cannot be cast into an integer, a dynamic error will result. Similarly, an expression may apply an arithmetic operator to a value whose static type is xs:untypedAtomic. This is not a static error, but at run time, if the value cannot be successfully cast to a numeric type, a dynamic error will be raised.

    2.3.4 Input Sources

    XQuery 4.0 and XPath 4.0 has a set of functions that provide access to XML documents (fn:doc, fn:doc-available), collections (fn:collection, fn:uri-collection), text files (fn:unparsed-text, fn:unparsed-text-lines, fn:unparsed-text-available), and environment variables (fn:environment-variable, fn:available-environment-variables). These functions are defined in Section 13.6 Functions giving access to external informationFO.

    An expression can access input data either by calling one of these input functions or by referencing some part of the dynamic context that is initialized by the external environment, such as a variable or context value.

    Note:

    The EXPath Community Group has developed a File Module, 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.

    2.3.5 Serialization

    [Definition: Serialization is the process of converting an XDM instance to a sequence of octets (step DM4 in Figure 1.), as described in [XSLT and XQuery Serialization 4.0].]

    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 5.22 Output Declarations.

    Serialization can also be invoked from within a query by calling the fn:serialize function.

    Note:

    This definition of serialization is the definition used in this specification. Any form of serialization that is not based on [XSLT and XQuery Serialization 4.0] is outside the scope of the XQuery 4.0 and XPath 4.0 specification.

    Serialization is outside the scope of the XPath specification, except to the extent that there is a function fn:serialize that enables serialization to be invoked.

    An XQuery implementation is not required to provide a serialization interface. For example, an implementation may provide only a DOM interface (see [Document Object Model]) or an interface based on an event stream.

    2.3.6 Consistency Constraints

    In order for XQuery 4.0 and XPath 4.0 to be well defined, the input XDM instances, the static context, and the dynamic context must be mutually consistent. The consistency constraints listed below are prerequisites for correct functioning of an XQuery 4.0 and XPath 4.0 implementation. Enforcement of these consistency constraints is beyond the scope of this specification. This specification does not define the result of a queryan expression under any condition in which one or more of these constraints is not satisfied.

    • For every node that has a type annotation, if that type annotation is found in the in-scope schema definitions (ISSD), then its definition in the ISSD must be compatibleDM with its definition in the schemaDM that was used to validate the node.

    • Every element name, attribute name, or schema type name referenced in in-scope variables or statically known function definitions must be in the in-scope schema definitions, unless it is an element name referenced as part of an ElementTest or an attribute name referenced as part of an AttributeTest.

    • Any reference to a global element, attribute, or type name in the in-scope schema definitions must have a corresponding element, attribute or type definition in the in-scope schema definitions.

    • For each (variable, type) pair in in-scope variables and the corresponding (variable, value) pair in variable values such that the variable names are equal, the value must match the type, using the matching rules in 3.1.2 Sequence Type Matching.

    • For each variable declared as external, if the variable declaration does not include a VarDefaultValue, the external environment must provide a value for the variable.

      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 3.1.2 Sequence Type Matching. 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.

    • For each function declared as external: the function’s implementation must either return a value that matches the declared result type, using the matching rules in 3.1.2 Sequence Type Matching, or raise an implementation-defined error.

    • For a given query, define a participating ISSD as the in-scope schema definitions of a module that is used in evaluating the query. All participating ISSDs must be compatibleDM.

      Note:

      This rule ensures that when one module M imports schema X, and another module N imports schema Y, then an element node validated against type T in M can be safely passed to a function in N that expects an argument of type element(*, T). 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.

    • In the statically known namespaces, the prefix xml must not be bound to any namespace URI other than http://www.w3.org/XML/1998/namespace, and no prefix other than xml may be bound to this namespace URI. The prefix xmlns must not be bound to any namespace URI, and no prefix may be bound to the namespace URI http://www.w3.org/2000/xmlns/.

    2.4 Error Handling

    2.4.1 Kinds of Errors

    As described in 2.3.3 Expression Processing, XQuery 4.0 and XPath 4.0 defines a static analysis phase, which does not depend on input data, and a dynamic evaluation phase, which does depend on input data. Errors may be raised during each phase.

    [Definition: An error that can be detected during the static analysis phase, and is not a type error, is a static error.] A syntax error is an example of a static error.

    [Definition: A dynamic error is an error that must be detected during the dynamic evaluation phase and may be detected during the static analysis phase.] Numeric overflow is an example of a dynamic error.

    [Definition: A type error may be raised during the static analysis phase or the dynamic evaluation phase. During the static analysis phase, a type error occurs when the static type of an expression does not match the expected type of the context in which the expression occurs. During the dynamic evaluation phase, a type error occurs when the dynamic type of a value does not match the expected type of the context in which the value occurs.]

    The outcome of the static analysis phase is either success or one or more type errors, static errors, or statically detected dynamic errors. The result of the dynamic evaluation phase is either a result value, a type error, or a dynamic error.

    If more than one error is present, or if an error condition comes within the scope of more than one error defined in this specification, then any non-empty subset of these errors may be reported.

    If an implementation can determine during the static analysis phase that a QueryBodyan XPath expression, if evaluated, would necessarily raise a dynamic error or that an expression, if evaluated, would necessarily raise a type error, the implementation may (but is not required to) report that error during the static analysis phase.

    An implementation can raise a dynamic error for a QueryBodyan XPath expression statically only if the queryexpression can never execute without raising that error, as in the following example:

    error()

    The following example contains a type error, which can be reported statically even if the implementation can not prove that the expression will actually be evaluated.

    if (empty($arg))
    +            

    W3C

    XQuery 4.0 and XPath 4.0 WG Review Draft

    W3C Editor's Draft 1415 January 2025

    This version:
    http://www.w3.org/TR/2000/WD-shared-40-20000101/
    Most recent version of XQuery and XPath:
    http://www.w3.org/TR/shared/
    Most recent Recommendation of XQuery and XPath:
    https://www.w3.org/TR/2017/REC-xpath-31-20170321/https://www.w3.org/TR/2017/REC-xquery-31-20170321/
    Editor:
    Michael Kay, Saxonica <mike@saxonica.com>

    Please check the errata for any errors or issues reported since publication.

    See also translations.


    Abstract

    XQuery 4.0 and XPath 4.0 is an expression language that allows the processing of values conforming to the data model defined in [XQuery and XPath Data Model (XDM) 4.0]. The name of the language derives from its most distinctive feature, the path expression, which provides a means of hierarchic addressing of the nodes in an XML tree. As well as modeling the tree structure of XML, the data model also includes atomic items, function items, maps, arrays, and sequences. This version of XPath supports JSON as well as XML, and adds many new functions in [XQuery and XPath Functions and Operators 4.0].

    XQuery 4.0 and XPath 4.0 is a superset of XPath 3.1. A detailed list of changes made since XPath 3.1 can be found in L Change Log.

    XML is a versatile markup language, capable of labeling the information content of diverse data sources, including structured and semi-structured documents, relational databases, and object repositories. A query language that uses the structure of XML intelligently can express queries across all these kinds of data, whether physically stored in XML or viewed as XML via middleware. This specification describes a query language called XQuery, which is designed to be broadly applicable across many types of XML data sources.

    A list of changes made since XQuery 3.1 can be found in L Change Log.

    Status of this Document

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


    1 Introduction

    Changes in 4.0 

    1. Use the arrows to browse significant changes since the 3.1 version of this specification.

    2. Sections with significant changes are marked Δ in the table of contents.

    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.

    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.

    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 [Quilt], which in turn borrowed features from several other languages, including XPath 1.0 [XML Path Language (XPath) Version 1.0], XQL [XQL], XML-QL [XML-QL], SQL [SQL], and OQL [ODMG].

    XPath was originally designed as an expression language to address the nodes of XML trees; it has since been extended to address a variety of non-XML data sources. XPath gets its name from its use of a path notation for navigating through the hierarchical structure of an XML document; similar capabilities for navigating JSON structures were added in versions 3.0 and 3.1. XPath uses a compact, non-XML syntax, allowing XPath expressions to be embedded within URIs and to be used as XML attribute values. XPath is designed to be embedded in (or invoked from) other host languages, including both languages specialized towards XML processing (such as [XSL Transformations (XSLT) Version 4.0] and XSD), and general purpose programming languages such as Java, C#, Python, and Javascript. The interface between XPath and its host language is formalized with an abstract definition of a static and dynamic context, made available by the host language to the XPath processor.

    [Definition: A host language for XPath is any environment that provides capabilities for XPath expressions to be defined and evaluated, and that supplies a static and dynamic context for their evaluation. ]

    [Definition: XQuery 4.0 and XPath 4.0 operates on the abstract, logical structure of an XML document or JSON object rather than its surface syntax. This logical structure, known as the data model, is defined in [XQuery and XPath Data Model (XDM) 4.0].]

    XQuery 4.0 is an extension of XPath 4.0.XPath 4.0 is a subset of XQuery 4.0. 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:

    • Because XQuery expands predefined entity references and character references predefined entity references and character references and XPath does not, expressions containing these produce different results in the two languages. For instance, the value of the string literal "&amp;" is & in XQuery, and &amp; in XPath. (A host language may expand predefined entity references or character references before the XPath expression is evaluated.)

    • If XPath 1.0 compatibility mode is enabled, XPath behaves differently from XQuery in a number of ways, which are noted throughout this document, and listed in K.4.2 Incompatibilities when Compatibility Mode is false .which are discussed in [XPath 4.0].

    Because these languages are so closely related, their grammars and language descriptions are generated from a common source to ensure consistency.

    XQuery 4.0 and XPath 4.0 also depends on and is closely related to the following specifications:

    Note:

    The XML-based syntax for XQuery known as XQueryX is no longer maintained.

    [Definition: An XQuery 4.0 Processor processes a query according to the XQuery 4.0 specification. ] [Definition: An XQuery 3.1 Processor processes a query according to the XQuery 3.1 specification. ] [Definition: An XQuery 3.0 Processor processes a query according to the XQuery 3.0 specification. ] [Definition: An XQuery 1.0 Processor processes a query according to the XQuery 1.0 specification. ]

    This document specifies a grammar for XQuery 4.0 and XPath 4.0, using the same basic EBNF notation used in [XML 1.0]. Unless otherwise noted (see A.3 Lexical structure), whitespace is not significant in queriesexpressions. Grammar productions are introduced together with the features that they describe, and a complete grammar is also presented in the appendix [A XQuery 4.0 and XPath 4.0 Grammar]. The appendix is the normative version.

    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:

    [178]   FunctionCall   ::=   EQNameArgumentList/* xgc: reserved-function-names */
    EQNameArgumentList/* xgc: reserved-function-names */
    /* xgc: reserved-function-names */
    /* gn: parens */
    [156]   ArgumentList   ::=   "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"

    The productions should be read as follows: A function call consists of an EQName followed by an ArgumentList. The argument list consists of an opening parenthesis, an optional list of one or more arguments (separated by commas), and a closing parenthesis.

    This document normatively defines the static and dynamic semantics of XQuery 4.0 and XPath 4.0. In this document, examples and material labeled as “Note” are provided for explanatory purposes and are not normative.

    2 Basics

    2.1 Terminology

    Changes in 4.0  

    1. The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.  [Issue 1366 PR 1498]

    The basic building block of XQuery 4.0 and XPath 4.0 is the expression, which is a string of [Unicode] characters; the version of Unicode to be used is implementation-defined. The language provides several kinds of expressions which may be constructed from keywords, symbols, and operands. In general, the operands of an expression are other expressions. XQuery 4.0 and XPath 4.0 allows expressions to be nested with full generality. (However, unlike a pure functional language, it does not allow variable substitution if the variable declaration contains construction of new nodes.)

    Note:

    This specification contains no assumptions or requirements regarding the character set encoding of strings of [Unicode] characters.

    Like XML, XQuery 4.0 and XPath 4.0 is a case-sensitive language. Keywords in XQuery 4.0 and XPath 4.0 use lower-case characters and are not reserved—that is, names in XQuery 4.0 and XPath 4.0 expressions are allowed to be the same as language keywords, except for certain unprefixed function-names listed in A.4 Reserved Function Names.

    In this specification the phrases must, must not, should, should not, may, required, and recommended, when used in normative text and rendered in small capitals, are to be interpreted as described in [RFC2119].

    Certain aspects of language processing are described in this specification as implementation-defined or implementation-dependent.

    • [Definition: Implementation-defined indicates an aspect that may differ between implementations, but must be specified by the implementer for each particular implementation.]

    • [Definition: Implementation-dependent indicates an aspect that may differ between implementations, is not specified by this or any W3C specification, and is not required to be specified by the implementer for any particular implementation.]

    A language aspect described in this specification as implementation-defined or implementation dependent may be further constrained by the specifications of a host language in which XPath is embedded.

    2.1.1 Grammar Notation

    Changes in 4.0  

    1. The EBNF notation has been extended to allow the constructs (A ++ ",") (one or more occurrences of A, comma-separated, and (A ** ",") (zero or more occurrences of A, comma-separated.   [Issue 1366 PR 1498 30 October 2024]

    The grammar of XQuery 4.0 and XPath 4.0 is defined using a version of EBNF defined in A.1.1 Notation. The notation is based on the EBNF dialect used in the XML specification, with two notable additions derived from the Invisible XML grammar:

    (A ++ ",") represents a sequence of one or more comma-separated occurrences of A.

    (A ** ",") represents a sequence of zero or more comma-separated occurrences of A.

    For example the following production rule indicates that an Expr consists of one or more occurrences of ExprSingle, separated by commas:

    [46]   Expr   ::=   (ExprSingle ++ ",")
    (ExprSingle ++ ",")

    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.

    EBNF grammar rules appear throughout the specification for ease of reference, and the entire grammar is summarized in A.1 EBNF. For XQuery 4.0 and XPath 4.0, the top-level production rule is XPath, representing an XPath expression.For XQuery 4.0 and XPath 4.0, the top-level production rule is Module, representing an XQuery module.

    2.1.2 Values

    Changes in 4.0  

    1. The term atomic value has been replaced by atomic item.   [Issue 1337 PR 1361 2 August 2024]

    [Definition: In the data model, a value is always a sequence.]

    [Definition: A sequence is an ordered collection of zero or more items.]

    [Definition: An item is either an atomic item, a node, or a function item.]

    [Definition: An atomic item is a value in the value space of an atomic type, as defined in [XML Schema 1.0] or [XML Schema 1.1].]

    [Definition: A node is an instance of one of the node kinds defined in Section 5 NodesDM.] Each node has a unique node identity, a typed value, and a string value. In addition, some nodes have a name. The typed value of a node is a sequence of zero or more atomic items. The string value of a node is a value of type xs:string. The name of a node is a value of type xs:QName.

    [Definition: A function item is an item that can be called using a dynamic function call.]

    Maps (see 4.14.1 Maps) and arrays (see 4.14.2 Arrays) are specific kinds of function items.

    [Definition: A sequence containing exactly one item is called a singleton.] An item is identical to a singleton sequence containing that item. Sequences are never nested—for example, combining the values 1, (2, 3), and ( ) into a single sequence results in the sequence (1, 2, 3). [Definition: A sequence containing zero items is called an empty sequence.]

    [Definition: The term XDM instance is used, synonymously with the term value, to denote an unconstrained sequence of items.]

    Element nodes have a property called in-scope namespaces. [Definition: The in-scope namespaces property of an element node is a set of namespace bindings, each of which associates a namespace prefix with a URI.] For a given element, one namespace binding may have an empty prefix; the URI of this namespace binding is the default namespace within the scope of the element.

    In [XML Path Language (XPath) Version 1.0], the in-scope namespaces of an element node are represented by a collection of namespace nodes arranged on a namespace axis. As of XPath 2.0, the namespace axis is deprecated and need not be supported by a host language. A host language that does not support the namespace axis need not represent namespace bindings in the form of nodes.

    Note:

    In [XML Path Language (XPath) Version 1.0], the in-scope namespaces of an element node are represented by a collection of namespace nodes arranged on a namespace axis, which is optional and deprecated in [XPath 4.0]. XQuery does not support the namespace axis and does not represent namespace bindings in the form of nodes.

    However, where other specifications such as [XSLT and XQuery Serialization 4.0] refer to namespace nodes, these nodes may be synthesized from the in-scope namespaces of an element node by interpreting each namespace binding as a namespace node. An application that needs to create a set of namespace nodes to represent these bindings for an element bound to $e can do so using the following code.

    in-scope-prefixes($e) ! namespace {.}{ namespace-uri-for-prefix(., $e)}

    2.1.3 Namespaces and QNames

    [Definition: An expanded QName is a triple: its components are a prefix, a local name, and a namespace URI. In the case of a name in no namespace, the namespace URI and prefix are both absent. In the case of a name in the default namespace, the prefix is absent.] When comparing two expanded QNames, the prefixes are ignored: the local name parts must be equal under the Unicode codepoint collation (Section 5.3.1 CollationsFO), and the namespace URI parts must either both be absent, or must be equal under the Unicode codepoint collation.

    In the XQuery 4.0 and XPath 4.0 grammar, QNames representing the names of elements, attributes, functions, variables, types, or other such constructs are written as instances of the grammatical production EQName.

    [265]   EQName   ::=   QName | URIQualifiedName
    QName | URIQualifiedName
    [285]   QName   ::=   [http://www.w3.org/TR/REC-xml-names/#NT-QName]Names/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml-names/#NT-QName]Names/* xgc: xml-version */
    /* xgc: xml-version */
    [264]   URILiteral   ::=   StringLiteral
    StringLiteral
    [274]   URIQualifiedName   ::=   BracedURILiteralNCName/* ws: explicit */
    BracedURILiteralNCName/* ws: explicit */
    /* ws: explicit */
    [275]   BracedURILiteral   ::=   "Q" "{" (PredefinedEntityRef | CharRef | [^&{}])* "}"/* ws: explicit */
    "Q" "{" (PredefinedEntityRef | CharRef | [^&{}])* "}"/* ws: explicit */
    /* ws: explicit */
    [286]   NCName   ::=   [http://www.w3.org/TR/REC-xml-names/#NT-NCName]Names/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml-names/#NT-NCName]Names/* xgc: xml-version */
    /* xgc: xml-version */

    The EQName production allows a QName to be written in one of three ways:

    • local-name only (for example, invoice).

      A name written in this form has no prefix, and the rules for determining the namespace depend on the context in which the name appears. This form is a lexical QName.

    • prefix plus local-name (for example, my:invoice).

      In this case the prefix and local name of the QName are as written, and the namespace URI is inferred from the prefix by examining the in-scope namespaces in the static context where the QName appears; the context must include a binding for the prefix. This form is a lexical QName.

    • URI plus local-name (for example, Q{http://example.com/ns}invoice).

      In this case the local name and namespace URI are as written, and the prefix is absent. This way of writing a QName is context-free, which makes it particularly suitable for use in queriesexpressions that are generated by software. This form is a URIQualifiedName. If the BracedURILiteral has no content (for example, Q{}invoice) then the namespace URI of the QName is absent.

    [Definition: A lexical QName is a name that conforms to the syntax of the QName production].

    The namespace URI value in a URIQualifiedName is whitespace normalized according to the rules for the xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2. It is a static error [err:XQST0070] if the namespace URI for an EQName is http://www.w3.org/2000/xmlns/.

    Here are some examples of EQNames:

    This document uses the following namespace prefixes to represent the namespace URIs with which they are listed. Although these prefixes are used within this specification to refer to the corresponding namespaces, not all of these bindings will necessarily be present in the static context of every expression, and authors are free to use different prefixes for these namespaces, or to bind these prefixes to different namespaces.

    • xml: http://www.w3.org/XML/1998/namespace

    • xs: http://www.w3.org/2001/XMLSchema

    • xsi: http://www.w3.org/2001/XMLSchema-instance

    • fn: http://www.w3.org/2005/xpath-functions

    • array: http://www.w3.org/2005/xpath-functions/array

    • map: http://www.w3.org/2005/xpath-functions/map

    • math: http://www.w3.org/2005/xpath-functions/math

    • err: http://www.w3.org/2005/xqt-errors (see 2.4.2 Identifying and Reporting Errors).

    • local: http://www.w3.org/2005/xquery-local-functions (see 5.18 Function Declarations.)

    • output: http://www.w3.org/2010/xslt-xquery-serialization

    • xq: http://www.w3.org/2012/xquery

    [Definition: Within this specification, the term URI refers to a Universal Resource Identifier as defined in [RFC3986] and extended in [RFC3987] with the new name IRI.] The term URI has been retained in preference to IRI to avoid introducing new names for concepts such as “Base URI” that are defined or referenced across the whole family of XML specifications.

    Note:

    In most contexts, processors are not required to raise errors if a URI is not lexically valid according to [RFC3986] and [RFC3987]. See 2.5.5 URI Literalsand 4.12.1.2 Namespace Declaration Attributes for details.

    2.2 Expression Context

    [Definition: The expression context for a given expression consists of all the information that can affect the result of the expression.]

    This information is organized into two categories called the static context and the dynamic context.

    2.2.1 Static Context

    Changes in 4.0  

    1. The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.   [Issue 296 PR 1181 30 April 2024]

    2. 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.   [Issue 1343 PR 1344 23 September 2024]

    3. The context value static type, which was there purely to assist in static typing, has been dropped.   [Issue 1495 ]

    [Definition: The static context of an expression is the information that is available during static analysis of the expression, prior to its evaluation.] This information can be used to decide whether the expression contains a static error.

    The individual components of the static context are described below.

    In XQuery 4.0 and XPath 4.0, the static context for an expression is largely defined by the host language, that is, by the calling environment that causes an XPath expression to be evaluated. Most of the static context components are constant throughout an expression; the only exception is in-scope variables. (There are constructs in the language, such as the ForExpr and LetExpr, that add additional variables to the static context of their subexpressions.)

    In XQuery 4.0 and XPath 4.0, the static context for an expression is largely defined in the query prolog of a module: see 5 Modules and Prologs. 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 import module declaration: see 5.12 Module Import.

    In addition, some expressions modify the static context for their subexpressions. The most obvious example is in-scope variables (a FLWORExpr declares bindings of local variables that are available for reference within subsequent clauses of the expression). A further example is the statically known namespaces: an element constructor may contain namespace declarations such as xmlns:p="some_uri" which cause additional namespace prefixes to be available within the content of the element constructor.

    Appendix C.1 Static Context Components gives an overview of the components in the static context and the way they are initialized.

    Some components of the static context, but not all, also affect the dynamic semantics of expressions. For example, casting of a string such as "xbrl:xbrl" to an xs:QName might expand the prefix xbrl to the namespace URI http://www.xbrl.org/2003/instance using the statically known namespaces from the static context; since the input string "xbrl:xbrl" is in general not known until execution time (it might be read from a source document), this means that the values of the statically known namespaces must be available at execution time.

    • [Definition: XPath 1.0 compatibility mode.This component must be set by all host languages that include XPath 3.1 as a subset, indicating whether rules for compatibility with XPath 1.0 are in effect. XQuery sets the value of this component to false. This value is true if rules for backward compatibility with XPath Version 1.0 are in effect; otherwise it is false. ]

    • [Definition: Statically known namespaces. This is a mapping from prefix to namespace URI that defines all the namespaces that are known during static processing of a given expression.]

      The URI value is whitespace normalized according to the rules for the xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2.

      The statically known namespaces may include a binding for the zero-length prefix; however, this is used only in limited circumstances because the rules for resolving unprefixed QNames depend on how such a name is used.

      Note the difference between in-scope namespaces, which is a dynamic property of an element node, and statically known namespaces, which is a static property of an expression.

      Some namespaces are predefined; additional namespaces can be added to the statically known namespaces by namespace declarations, schema imports, or module imports in a Prolog, by a module declaration, and by namespace declaration attributes in direct element constructors.

    • [Definition: Default namespace for elements and types. This is either a namespace URI, or the special value "##any", or absentDM. This indicates how unprefixed QNames are interpreted when they appear in a position where an element name or type name is expected.]

      • 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 xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2.

      • The special value "##any" indicates that:

        • When an unprefixed QName is used as a name test for selecting named elements in an axis step, the name test will match an element having the specified local name, in any namespace or none.

        • 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 xs namespace, http://www.w3.org/2001/XMLSchema.

        • In any other context, an unprefixed QName represents a name in no namespace.

      • If the value is absentDM, an unprefixed QName representing an element or type name is interpreted as being in no namespace.

    • [Definition: Default function namespace. This is either a namespace URI, or absentDM. The namespace URI, if present, is used for any unprefixed QName appearing in a position where a function name is expected.] The URI value is whitespace-normalized according to the rules for the xs:anyURI type in Section 3.2.17 anyURI XS1-2 or Section 3.3.17 anyURI XS11-2

      In its simplest form its value is simply a whitespace-normalized xs:anyURI value (most commonly, the URI http://www.w3.org/2005/xpath-functions) to be used as the default namespace for unprefixed function names. However, the use of a more complex algorithm is not precluded, for example an algorithm which searches multiple namespaces for a matching name.

      In XQuery, a default function namespace can be declared in the prolog in a default function namespace declaration (see 5.14 Default Namespace Declaration); in the absence of such a declaration, the namespace http://www.w3.org/2005/xpath-functions is used.

    • [Definition: In-scope schema definitions is a generic term for all the element declarations, attribute declarations, and schema type definitions that are in scope during static analysis of an expression.] It includes the following three parts:

    • [Definition: In-scope variables. This is a mapping from expanded QName to type. It defines the set of variables that are available for reference within an expression. The expanded QName is the name of the variable, and the type is the static type of the variable.]

      Variable declarations in a Prolog are added to in-scope variables. An expression that binds a variable extends the in-scope variables, within the scope of the variable, with the variable and its type. Within the body of an inline function expression or user-defined function, the in-scope variables are extended by the names and types of the function parameters.

      The static type of a variable may either be declared in a query or inferred by static type inference as discussed in 2.3.3.1 Static Analysis Phase.

    • [Definition: In-scope named item types. This is a mapping from expanded QName to named item types.]

      [Definition: A named item type is an ItemType identified by an expanded QName.]

      Named item types serve two purposes:

      • 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.

      • They allow the definition of recursive types, which are useful for describing recursive data structures such as lists and trees. For details see 3.2.8.3.1 Recursive Record Types.

      Note:

      In XQuery, named item types can be declared in the Query Prolog.

      Named item types can be defined in a host language such as XQuery 4.0 and in XSLT 4.0, but not in XPath 4.0 itself. They are available in XPath only if the host language provides the ability to define them.

    • [Definition: Statically known function definitions. This is a set of function definitions.]

      Function definitions are described in 2.2.1.1 Function Definitions.

    • [Definition: Statically known collations. This is an implementation-defined mapping from URI to collation. It defines the names of the collations that are available for use in processing queries and expressions.] [Definition: A collation is a specification of the manner in which strings and URIs are compared and, by extension, ordered. For a more complete definition of collation, see Section 5.3 Comparison of stringsFO.]

    • [Definition: Construction mode. The construction mode governs the behavior of element and document node constructors. If construction mode is preserve, the type of a constructed element node is xs:anyType, and all attribute and element nodes copied during node construction retain their original types. If construction mode is strip, the type of a constructed element node is xs:untyped; all element nodes copied during node construction receive the type xs:untyped, and all attribute nodes copied during node construction receive the type xs:untypedAtomic.]

    • [Definition: Default order for empty sequences. This component controls the processing of empty sequences and NaN values as ordering keys in an order by clause in a FLWOR expression, as described in 4.13.9 Order By Clause.] Its value may be greatest or least.

    • [Definition: Boundary-space policy. This component controls the processing of boundary whitespace by direct element constructors, as described in 4.12.1.4 Boundary Whitespace.] Its value may be preserve or strip.

    • [Definition: Copy-namespaces mode. This component controls the namespace bindings that are assigned when an existing element node is copied by an element constructor, as described in 4.12.1 Direct Element Constructors. Its value consists of two parts: preserve or no-preserve, and inherit or no-inherit.]

    • [Definition: Static Base URI. 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 xsl:import and xsl:include in XSLT. All expressions within a module have the same static base URI. The Static Base URI can be set using a base URI declaration. If E is a subexpression of F then the Static Base URI of E is the same as the Static Base URI of F. There are no constructs in XPath that require resolution of relative URI references during static analysis.

      Relative URI references are resolved as described in 2.5.6 Resolving a Relative URI Reference.

      At execution time, relative URIs supplied to functions such as fn:doc are resolved against the Executable Base URI, which may or may not be the same as the Static Base URI.

    • [Definition: Statically known decimal formats. This is a mapping from QNames to decimal formats, with one default format that has no visible name, referred to as the unnamed decimal format. Each format is available for use when formatting numbers using the fn:format-number function.]

      Decimal formats are described in 2.2.1.2 Decimal Formats.

    2.2.1.1 Function Definitions

    [Definition: A function definition contains information used to evaluate a static function call, including the name, parameters, and return type of the function.]

    The properties of a function definition include:

    • The function name, which is an expanded QName.

    • Parameter definitions, specifically:

      The names of the parameters must be distinct.

      [Definition: A function definition has an arity range, which is a range of consecutive non-negative integers. If the function definition has M required parameters and N optional parameters, then its arity range is from M to M+N inclusive.]

      The static context may contain several function definitions with the same name, but the arity ranges of two such function definitions must not overlap. For example, if two function definitions A and B have the same function name, then:

      • It is acceptable for A to have two required parameters and no optional parameters, while B has three required parameters and one optional parameter.

      • It is not acceptable for A to have one required parameter while B has three optional parameters.

      Note:

      Implementations must ensure that no two function definitions have the same expanded QName and overlapping arity ranges (even if the signatures are consistent).

      XQuery and XSLT enforce this rule by defining a static error if the rule is violated; but further constraints may be needed if an API allows external functions to be added to the static context.

    • A return type (a sequence type)

    • The function category, which is one of application, system, or external:

      • [Definition: Application functions are function definitions written in a host language such as XQuery or XSLT whose syntax and semantics are defined in this family of specifications. Their behavior (including the rules determining the static and dynamic context) follows the rules for such functions in the relevant host language specification.] The most common application functions are functions written by users in XQuery or XSLT.

      • [Definition: System functions include the functions defined in [XQuery and XPath Functions and Operators 4.0], functions defined by the specifications of a host language, constructor functions for atomic types, and any additional functions provided by the implementation. System functions are sometimes called built-in functions.]

        The 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 dynamic context of the caller). Such functions are said to be context dependent.

      • [Definition: External functions can be characterized as functions that are neither part of the processor implementation, nor written in a language whose semantics are under the control of this family of specifications. The semantics of external functions, including any context dependencies, are entirely implementation-defined. In XSLT, external functions are called Section 24.1 Extension Functions XT30. ]

        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.

      [Definition: A function definition is said to be context dependent if its result depends on the static or dynamic context of its caller. A function definition may be context-dependent for some arities in its arity range, and context-independent for others: for example fn:name#0 is context-dependent while fn:name#1 is context-independent.]

      Note:

      Some system functions, such as fn:position, fn:last, and fn:static-base-uri, exist for the sole purpose of providing information about the static or dynamic context of their caller.

      Note:

      Application functions are context dependent only to the extent that they define optional parameters with default values that are context dependent.

    • A (possibly empty) set of function annotations

      In XQuery, function annotations are described in 5.15 Annotations.

    • 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.

    The function definitions present in the static context are available for reference from a static function call, or from a named function reference.

    2.2.1.2 Decimal Formats

    Changes in 4.0  

    1. 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.   [Issue 1048 PR 1250 3 June 2024]

    Each decimal format defines a set of properties, which control the interpretation of characters in the picture string supplied to the fn:format-number function, and also specify characters to be used in the result of formatting the number.

    Each property potentially has two parts: a marker character M used in the picture string to mark an insertion position, and a rendition string R to indicate how the relevant property is to be rendered in the output of the fn:format-number function. In the list below properties are annotated with (M), (R), or (M, R) to indicate whether the property includes a marker character, a rendition string, or both.

    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 M:R. For example the percent property may be expressed as %:pc to indicate that the character % will be used in the picture string, and the string pc will be used in the function output. In this example, the value 0.10, formatted with the picture string #0%, results in the output 10pc

    • [Definition: decimal-separator(M, R) is used to separate the integer part of the number from the fractional part. The default value for both the marker and the rendition is U+002E (FULL STOP, PERIOD, .) .]

    • [Definition: exponent-separator(M, R) is used to separate the mantissa from the exponent in scientific notation. The default value for both the marker and the rendition is U+0065 (LATIN SMALL LETTER E, e) .]

    • [Definition: grouping-separator(M, R) is used to separate groups of digits (for example as a thousands separator). The default value for both the marker and the rendition is U+002C (COMMA, ,) .]

    • [Definition: percent(M, R) is used to indicate that the number is written as a per-hundred fraction; the default value for both the marker and the rendition is U+0025 (PERCENT SIGN, %) .]

    • [Definition: per-mille(M, R) is used to indicate that the number is written as a per-thousand fraction; the default value for both the marker and the rendition is U+2030 (PER MILLE SIGN, ) .]

    • [Definition: zero-digit(M) is the character used in the picture string to represent the digit zero; the default value is U+0030 (DIGIT ZERO, 0) . This character must be a digit (category Nd in the Unicode property database), and it must have the numeric value zero. This property implicitly defines the ten Unicode characters that are used to represent the values 0 to 9 in the function output: Unicode is organized so that each set of decimal digits forms a contiguous block of characters in numerical sequence. Within the picture string any of these ten character can be used (interchangeably) as a place-holder for a mandatory digit. Within the final result string, these ten characters are used to represent the digits zero to nine.]

    • [Definition: digit(M) is a character used in the picture string to represent an optional digit; the default value is U+0023 (NUMBER SIGN, #) .]

    • [Definition: pattern-separator(M) is a character used to separate positive and negative sub-pictures in a picture string; the default value is U+003B (SEMICOLON, ;) .]

    • [Definition: infinity(R) is the string used to represent the double value infinity (INF); the default value is the string "Infinity" ]

    • [Definition: NaN(R) is the string used to represent the double value NaN (not a number); the default value is the string "NaN" ]

    • [Definition: minus-sign(R) is the string used to mark negative numbers; the default value is U+002D (HYPHEN-MINUS, -) .]

    2.2.2 Dynamic Context

    Changes in 4.0  

    1. 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.   [Issue 129 PR 368 14 September 2023]

    2. The rules regarding the document-uri property of nodes returned by the fn:collection function have been relaxed.   [Issue 1161 PR 1265 11 June 2024]

    [Definition: The dynamic context of an expression is defined as information that is needed for the dynamic evaluation of an expression, beyond any information that is needed from the static context.] If evaluation of an expression relies on some part of the dynamic context that is absentDM, a type error is raised [err:XPDY0002].

    Note:

    In previous versions of the specification, this was classified as a dynamic error. The change allows the error to be raised during static analysis when possible; for example a function written as fn($x) { @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.

    There are other cases where static detection of the error is not possible.

    The individual components of the dynamic context are described below.

    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 and XPath 4.0 expressions to be invoked from a host language. Application Programming Interfaces are outside the scope of this specification. In XQuery 4.0 and XPath 4.0, some aspects of the dynamic context (for example, initial values of variables) are defined within the query prolog. The dynamic context for inner subexpressions may be set by their containing expressions: for example in a mapping expression E1!E2, the value of the focus (part of the dynamic context) for evaluation of E2 is defined by the evaluation of E1.

    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 available documents, 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.

    Rules governing the initialization and alteration of these components can be found in C.2 Dynamic Context Components.Further rules governing the semantics of these components can be found in D.2 Dynamic Context Components.

    The components of the dynamic context are listed below.

    [Definition: The first three components of the dynamic context (context value, context position, and context size) are called the focus of the expression. ] The focus enables the processor to keep track of which items are being processed by the expression. If any component in the focus is defined, all components of the focus are defined.If any component in the focus is defined, both the context value and context position are known.

    Note:

    If any component in the focus is defined, context size is usually defined as well. However, when streaming, the context size cannot be determined without lookahead, so it may be undefined. If so, expressions like last() will raise a dynamic error because the context size is undefined.

    [Definition: A fixed focus is a focus for an expression that is evaluated once, rather than being applied to a series of values; in a fixed focus, the context value is set to one specific value, the context position is 1, and the context size is 1.]

    [Definition: A singleton focus is a fixed focus in which the context value is a singleton item.]. With a singleton focus, the context value is a single item, the context position is 1, and the context size is 1.

    Certain language constructs, notably the path operatorE1/E2, the simple map operatorE1!E2, and the predicateE1[E2], create a new focus for the evaluation of a sub-expression. In these constructs, E2 is evaluated once for each item in the sequence that results from evaluating E1. Each time E2 is evaluated, it is evaluated with a different focus. The focus for evaluating E2 is referred to below as the inner focus, while the focus for evaluating E1 is referred to as the outer focus. The inner focus is used only for the evaluation of E2. Evaluation of E1 continues with its original focus unchanged.

    • [Definition: The context value is the value currently being processed.] In many cases (but not always), the context value will be a single item. [Definition: When the context value is a single item, it can also be referred to as the context item; when it is a single node, it can also be referred to as the context node.] The context value is returned by an expression consisting of a single dot (.). When an expression E1/E2 or E1[E2] is evaluated, each item in the sequence obtained by evaluating E1 becomes the context value in the inner focus for an evaluation of E2.

      [Definition: In the dynamic context of every module in a query, the context value component must have the same setting. If this shared setting is not absentDM, it is referred to as the initial context value. ]

    • [Definition: The context position 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 fn:position(). When an expression E1/E2 or E1[E2] is evaluated, the context position in the inner focus for an evaluation of E2 is the position of the context value in the sequence obtained by evaluating E1. The position of the first item in a sequence is always 1 (one). The context position is always less than or equal to the context size.

    • [Definition: The context size is the number of 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 fn:last(). When an expression E1/E2 or E1[E2] is evaluated, the context size in the inner focus for an evaluation of E2 is the number of items in the sequence obtained by evaluating E1.

    • [Definition: Variable values. This is a mapping from expanded QName to value. It contains the same expanded QNames as the in-scope variables in the static context for the expression. The expanded QName is the name of the variable and the value is the dynamic value of the variable, which includes its dynamic type.]

    • [Definition: Dynamically known function definitions. This is a set of function definitions. It includes the statically known function definitions as a subset, but may include other function definitions that are not known statically. ]

      The function definitions in the dynamic context are used primarily by the fn:function-lookup function.

      If two function definitions in the dynamically known function definitions have the same name, then their arity ranges must not overlap.

      Note:

      The reason for allowing named functions to be available dynamically beyond those that are available statically is primarily to allow for cases where the run-time execution environment is significantly different from the compile-time environment. This could happen, for example, if a stylesheet or query is compiled within a web server and then executed in the web browser. The fn:function-lookup function allows dynamic discovery of resources that were not available statically.

    • [Definition: Current dateTime. This information represents an implementation-dependent point in time during the processing of a queryan expression, and includes an explicit timezone. It can be retrieved by the fn:current-dateTime function. If called multiple times during the execution of a queryan expression, this function always returns the same result.]

    • [Definition: Implicit timezone. This is the timezone to be used when a date, time, or dateTime value that does not have a timezone is used in a comparison or arithmetic operation. The implicit timezone is an implementation-defined value of type xs:dayTimeDuration. See Section 3.2.7.3 Timezones XS1-2 or Section 3.3.7 dateTime XS11-2 for the range of valid values of a timezone.]

    • [Definition: Executable Base URI. This is an absolute URI used to resolve relative URIs during the evaluation of expressions; it is used, for example, to resolve a relative URI supplied to the fn:doc or fn:unparsed-text functions. ]

      URIs are resolved as described in 2.5.6 Resolving a Relative URI Reference.

      The function fn:static-base-uri, despite its name, returns the value of the Executable Base URI.

      In many straightforward processing scenarios, the Executable Base URI in the dynamic context will be the same as the Static Base URI for the corresponding expression in the static context. There are situations, however, where they may differ:

      • 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 Static Base URI, while resources needed during execution (such as reference data files) will be located on the production machine, accessed via the Executable Base URI.

      • When the fn:static-base-uri 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 fn:static-base-uri(), allowing the code in the function body to resolve the relative URI against the executable base URI of the caller.

    • [Definition: Default collation. This identifies one of the collations in statically known collations as the collation to be used by functions and operators for comparing and ordering values of type xs:string and xs:anyURI (and types derived from them) when no explicit collation is specified.]

      Note:

      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 fn:default-collation 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.

    • [Definition: Default language. This is the natural language used when creating human-readable output (for example, by the functions fn:format-date and fn:format-integer) if no other language is requested. The value is a language code as defined by the type xs:language.]

    • [Definition: Default calendar. This is the calendar used when formatting dates in human-readable output (for example, by the functions fn:format-date and fn:format-dateTime) if no other calendar is requested. The value is a string.]

    • [Definition: Default place. This is a geographical location used to identify the place where events happened (or will happen) when processing dates and times using functions such as fn:format-date, fn:format-dateTime, and fn:civil-timezone, if no other place is specified. It is used when translating timezone offsets to civil timezone names, and when using calendars where the translation from ISO dates/times to a local representation is dependent on geographical location. Possible representations of this information are an ISO country code or an Olson timezone name, but implementations are free to use other representations from which the above information can be derived. The only requirement is that it should uniquely identify a civil timezone, which means that country codes for countries with multiple timezones, such as the United States, are inadequate.]

    • [Definition: Available documents. This is a mapping of strings to document nodes. Each string represents the absolute URI of a resource. The document node is the root of a tree that represents that resource using the data model. The document node is returned by the fn:doc function when applied to that URI.] The set of available documents may be empty.

    • [Definition: Available text resources. This is a mapping of strings to text resources. Each string represents the absolute URI of a resource. The resource is returned by the fn:unparsed-text function when applied to that URI.] The set of available text resources may be empty.

    • [Definition: Available collections. This is a mapping of strings to sequences of items. Each string represents the absolute URI of a resource. The sequence of items represents the result of the fn:collection function when that URI is supplied as the argument. ] The set of available collections may be empty.

      Ideally, for every document node D that is in the target of a mapping in available item collections, or that is the root of a tree containing such a node, the document-uri property of D should either be absent, or should be a URI U such that available documents contains a mapping from U to D.

      Note:

      That is to say, the document-uri property of nodes returned by the fn:collection function should be such that calling fn:doc with that URI returns the relevant node.

      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.

    • [Definition: Default collection. This is the sequence of items that would result from calling the fn:collection function with no arguments.] The value of default collection may be initialized by the implementation.

    • [Definition: Available URI collections. This is a mapping of strings to sequences of URIs. The string represents the absolute URI of a resource which can be interpreted as an aggregation of a number of individual resources each of which has its own URI. The sequence of URIs represents the result of the fn:uri-collection function when that URI is supplied as the argument. ] There is no implication that the URIs in this sequence can be successfully dereferenced, or that the resources they refer to have any particular media type.

      Note:

      An implementation may maintain some consistent relationship between the available collections and the available URI collections, for example by ensuring that the result of fn:uri-collection(X)!fn:doc(.) is the same as the result of fn:collection(X). However, this is not required. The fn:uri-collection function is more general than fn:collection in that fn:collection allows access to nodes that might lack individual URIs, for example nodes corresponding to XML fragments stored in the rows of a relational database.

    • [Definition: Default URI collection. This is the sequence of URIs that would result from calling the fn:uri-collection function with no arguments.] The value of default URI collection may be initialized by the implementation.

    • [Definition: Environment variables. This is a mapping from names to values. Both the names and the values are strings. The names are compared using an implementation-defined collation, and are unique under this collation. The set of environment variables is implementation-defined and may be empty.]

      Note:

      A possible implementation is to provide the set of POSIX environment variables (or their equivalent on other operating systems) appropriate to the process in which the query is initiatedexpression is evaluated.

    2.3 Processing Model

    Changes in 4.0  

    1. The static typing option has been dropped.   [Issue 1343 PR 1344 3 September 2024]

    The semantics of XQuery 4.0 and XPath 4.0 are defined in terms of the data model and the expression context.

    Processing                          Model OverviewProcessing                          Model Overview

    Figure 1: Processing Model Overview

    Figure 1 provides a schematic overview of the processing steps that are discussed in detail below. Some of these steps are completely outside the domain of XQuery 4.0 and XPath 4.0; in Figure 1, these are depicted outside the line that represents the boundaries of the language, an area labeled external processing. The external processing domain includes generation of XDM instances that represent the data to be queried (see 2.3.1 Data Model Generation), schema import processing (see 2.3.2 Schema Import Processing), and serialization (see 2.3.5 Serialization). The area inside the boundaries of the language is known as the query processing domainXPath processing domain, which includes the static analysis and dynamic evaluation phases (see 2.3.3 Expression Processing). Consistency constraints on the queryXPath processing domain are defined in 2.3.6 Consistency Constraints.

    2.3.1 Data Model Generation

    The input data for a queryan expression must be represented as one or more XDM instances. This process occurs outside the domain of XQuery 4.0 and XPath 4.0, which is why Figure 1 represents it in the external processing domain.

    In many cases the input data might originate as XML. Here are some steps by which an XML document might be converted to an XDM instance:

    1. A document may be parsed using an XML parser that generates an XML Information Set (see [XML Infoset]). The parsed document may then be validated against one or more schemas. This process, which is described in [XML Schema 1.0 Part 1] or [XML Schema 1.1 Part 1], results in an abstract information structure called the Post-Schema Validation Infoset (PSVI). If a document has no associated schema, its Information Set is preserved. (See DM1 in Figure 1)

    2. The Information Set or PSVI may be transformed into an XDM instance by a process described in [XQuery and XPath Data Model (XDM) 4.0]. (See DM2 in Figure 1)

    The above steps provide an example of how an XDM instance 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 and XPath 4.0 is defined in terms of the data model, but it does not place any constraints on how XDM instances are constructed.

    The remainder of this section is concerned with the common case where XML data is being processed.

    [Definition: Each element node and attribute node in an XDM instance has a type annotation (described in Section 2.8 Schema InformationDM). The type annotation of a node is a reference to a schema type. ] The type-name of a node is the name of the type referenced by its type annotation (but note that the type annotation can be a reference to an anonymous type). If the XDM instance was derived from a validated XML document as described in Section 3.3 Construction from a PSVIDM, the type annotations of the element and attribute nodes are derived from schema validation. XQuery 4.0 and XPath 4.0 does not provide a way to directly access the type annotation of an element or attribute node.

    The value of an attribute is represented directly within the attribute node. An attribute node whose type is unknown (such as might occur in a schemaless document) is given the type annotationxs:untypedAtomic.

    The value of an element is represented by the children of the element node, which may include text nodes and other element nodes. The type annotation of an element node indicates how the values in its child text nodes are to be interpreted. An element that has not been validated (such as might occur in a schemaless document) is annotated with the schema typexs:untyped. An element that has been validated and found to be partially valid is annotated with the schema type xs:anyType. If an element node is annotated as xs:untyped, all its descendant element nodes are also annotated as xs:untyped. However, if an element node is annotated as xs:anyType, some of its descendant element nodes may have a more specific type annotation.

    2.3.2 Schema Import Processing

    The in-scope schema definitions in the static context 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 2.3.6 Consistency Constraints.

    The in-scope schema definitions in the static context are provided by the host language (see step SI1 in Figure 1) and must satisfy the consistency constraints defined in 2.3.6 Consistency Constraints.

    2.3.3 Expression Processing

    XQuery 4.0 and XPath 4.0 defines two phases of processing called the static analysis phase and the dynamic evaluation phase (see Figure 1). During the static analysis phase, static errors, dynamic errors, or type errors may be raised. During the dynamic evaluation phase, only dynamic errors or type errors may be raised. These kinds of errors are defined in 2.4.1 Kinds of Errors.

    Within each phase, an implementation is free to use any strategy or algorithm whose result conforms to the specifications in this document.

    2.3.3.1 Static Analysis Phase

    [Definition: The static analysis phase depends on the expression itself and on the static context. The static analysis phase does not depend on input data (other than schemas).]

    During the static analysis phase, the queryXPath expression is typically parsed into an internal representation called the operation tree (step SQ1 in Figure 1). A parse error is raised as a static error [err:XPST0003]. The static context is initialized by the implementation (step SQ2). The static context is then changed and augmented based on information in the prolog (step SQ3). If the Schema Aware Feature is supported, the in-scope schema definitions are populated with information from imported schemas. If the Module Feature is supported, the static context is extended with function declarations and variable declarations from imported modules. The static context is used to resolve schema type names, function names, namespace prefixes, and variable names (step SQ4). If a name of one of these kinds in the operation tree is not found in the static context, a static error ([err:XPST0008] or [err:XPST0017]) is raised (however, see exceptions to this rule in 3.2.7.2 Element Types and 3.2.7.3 Attribute Types.)

    The operation tree is then typically normalized by making explicit the implicit operations such as atomization and extraction of effective boolean values (step SQ5).

    During the static analysis phase, a processor may perform type analysis. The effect of type analysis is to assign a static type to each expression in the operation tree. [Definition: The static type of an expression is the best inference that the processor is able to make statically about the type of the result of the expression.] This specification does not define the rules for type analysis nor the static types that are assigned to particular expressions: the only constraint is that the inferred type must match all possible values that the expression is capable of returning.

    Examples of inferred static types might be:

    • For the expression concat(a,b) the inferred static type is xs:string

    • For the expression $a = $v the inferred static type is xs:boolean

    • For the expression $s[exp] the inferred static type has the same item type as the static type of $s, but a cardinality that allows the empty sequence even if the static type of $s does not allow an empty sequence.

    • The inferred static type of the expression data($x) (whether written explicitly or inserted into the operation tree in places where atomization is implicit) depends on the inferred static type of $x: for example, if $x has type element(*, xs:integer) then data($x) has static type xs:integer.

    In XQuery 1.0 and XPath 2.0, rules for static type inferencing were published normatively in [XQuery 1.0 and XPath 2.0 Formal Semantics], but implementations were allowed to refine these rules to infer a more precise type where possible. In subsequent versions, the rules for static type inferencing are entirely implementation-dependent.

    Every kind of expression also imposes requirements on the type of its operands. For example, with the expression substring($a, $b, $c), $a must be of type xs:string (or something that can be converted to xs:string by the function calling rules), while $b and $c must be numeric.

    A processor may 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 coercion rules. For example, given the call fn:upper-case($s), the processor may raise an error if the declared or inferred type of $s is xs:integer, but not if it is xs:anyAtomicType.

    In addition, type analysis may conclude that an expression is implausible. Implausible expressions may be considered erroneous unless such checks have been disabled. This topic is described further in 2.4.6 Implausible Expressions.

    Alternatively, the processor may defer all type checking until the dynamic evaluation phase.

    2.3.3.2 Dynamic Evaluation Phase

    [Definition: The dynamic evaluation phase is the phase during which the value of an expression is computed.] It is dependent on successful completion of the static analysis phase.

    The dynamic evaluation phase can occur only if no errors were detected during the static analysis phase.

    The dynamic evaluation phase depends on the operation tree of the expression being evaluated (step DQ1), on the input data (step DQ4), and on the dynamic context (step DQ5), which in turn draws information from the external environment (step DQ3) and the static context (step DQ2). The dynamic evaluation phase may create new data-model values (step DQ4) and it may extend the dynamic context (step DQ5)—for example, by binding values to variables.

    [Definition: Every value matches one or more sequence types. A value is said to have a dynamic typeT if it matches (or is an instance of) the sequence type T.]

    In many cases (but not all), one of the dynamic types that a value matches will be a subtype of all the others, in which case it makes sense to speak of “the dynamic type” of the value as meaning this single most specific type. In other cases (examples are empty maps and empty arrays) none of the dynamic types is more specific than all the others.

    Note:

    An atomic item has a type annotation which will always be a subtype of all the other types that it matches; we can therefore refer to this as the dynamic type of the atomic item without ambiguity.

    A value may match a dynamic type that is more specific than the static type of the expression that computed it (for example, the static type of an expression might be xs:integer*, denoting a sequence of zero or more integers, but at evaluation time its value may be an instance of xs:integer, denoting exactly one integer).

    If an operand of an expression does not have a dynamic type that is a subtype of the static type required for that operand, a type error is raised [err:XPTY0004].

    Even though static typing can catch many type errors before an expression is executed, it is possible for an expression to raise an error during evaluation that was not detected by static analysis. For example, an expression may contain a cast of a string into an integer, which is statically valid. However, if the actual value of the string at run time cannot be cast into an integer, a dynamic error will result. Similarly, an expression may apply an arithmetic operator to a value whose static type is xs:untypedAtomic. This is not a static error, but at run time, if the value cannot be successfully cast to a numeric type, a dynamic error will be raised.

    2.3.4 Input Sources

    XQuery 4.0 and XPath 4.0 has a set of functions that provide access to XML documents (fn:doc, fn:doc-available), collections (fn:collection, fn:uri-collection), text files (fn:unparsed-text, fn:unparsed-text-lines, fn:unparsed-text-available), and environment variables (fn:environment-variable, fn:available-environment-variables). These functions are defined in Section 13.6 Functions giving access to external informationFO.

    An expression can access input data either by calling one of these input functions or by referencing some part of the dynamic context that is initialized by the external environment, such as a variable or context value.

    Note:

    The EXPath Community Group has developed a File Module, 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.

    2.3.5 Serialization

    [Definition: Serialization is the process of converting an XDM instance to a sequence of octets (step DM4 in Figure 1.), as described in [XSLT and XQuery Serialization 4.0].]

    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 5.22 Output Declarations.

    Serialization can also be invoked from within a query by calling the fn:serialize function.

    Note:

    This definition of serialization is the definition used in this specification. Any form of serialization that is not based on [XSLT and XQuery Serialization 4.0] is outside the scope of the XQuery 4.0 and XPath 4.0 specification.

    Serialization is outside the scope of the XPath specification, except to the extent that there is a function fn:serialize that enables serialization to be invoked.

    An XQuery implementation is not required to provide a serialization interface. For example, an implementation may provide only a DOM interface (see [Document Object Model]) or an interface based on an event stream.

    2.3.6 Consistency Constraints

    In order for XQuery 4.0 and XPath 4.0 to be well defined, the input XDM instances, the static context, and the dynamic context must be mutually consistent. The consistency constraints listed below are prerequisites for correct functioning of an XQuery 4.0 and XPath 4.0 implementation. Enforcement of these consistency constraints is beyond the scope of this specification. This specification does not define the result of a queryan expression under any condition in which one or more of these constraints is not satisfied.

    • For every node that has a type annotation, if that type annotation is found in the in-scope schema definitions (ISSD), then its definition in the ISSD must be compatibleDM with its definition in the schemaDM that was used to validate the node.

    • Every element name, attribute name, or schema type name referenced in in-scope variables or statically known function definitions must be in the in-scope schema definitions, unless it is an element name referenced as part of an ElementTest or an attribute name referenced as part of an AttributeTest.

    • Any reference to a global element, attribute, or type name in the in-scope schema definitions must have a corresponding element, attribute or type definition in the in-scope schema definitions.

    • For each (variable, type) pair in in-scope variables and the corresponding (variable, value) pair in variable values such that the variable names are equal, the value must match the type, using the matching rules in 3.1.2 Sequence Type Matching.

    • For each variable declared as external, if the variable declaration does not include a VarDefaultValue, the external environment must provide a value for the variable.

      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 3.1.2 Sequence Type Matching. 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.

    • For each function declared as external: the function’s implementation must either return a value that matches the declared result type, using the matching rules in 3.1.2 Sequence Type Matching, or raise an implementation-defined error.

    • For a given query, define a participating ISSD as the in-scope schema definitions of a module that is used in evaluating the query. All participating ISSDs must be compatibleDM.

      Note:

      This rule ensures that when one module M imports schema X, and another module N imports schema Y, then an element node validated against type T in M can be safely passed to a function in N that expects an argument of type element(*, T). 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.

    • In the statically known namespaces, the prefix xml must not be bound to any namespace URI other than http://www.w3.org/XML/1998/namespace, and no prefix other than xml may be bound to this namespace URI. The prefix xmlns must not be bound to any namespace URI, and no prefix may be bound to the namespace URI http://www.w3.org/2000/xmlns/.

    2.4 Error Handling

    2.4.1 Kinds of Errors

    As described in 2.3.3 Expression Processing, XQuery 4.0 and XPath 4.0 defines a static analysis phase, which does not depend on input data, and a dynamic evaluation phase, which does depend on input data. Errors may be raised during each phase.

    [Definition: An error that can be detected during the static analysis phase, and is not a type error, is a static error.] A syntax error is an example of a static error.

    [Definition: A dynamic error is an error that must be detected during the dynamic evaluation phase and may be detected during the static analysis phase.] Numeric overflow is an example of a dynamic error.

    [Definition: A type error may be raised during the static analysis phase or the dynamic evaluation phase. During the static analysis phase, a type error occurs when the static type of an expression does not match the expected type of the context in which the expression occurs. During the dynamic evaluation phase, a type error occurs when the dynamic type of a value does not match the expected type of the context in which the value occurs.]

    The outcome of the static analysis phase is either success or one or more type errors, static errors, or statically detected dynamic errors. The result of the dynamic evaluation phase is either a result value, a type error, or a dynamic error.

    If more than one error is present, or if an error condition comes within the scope of more than one error defined in this specification, then any non-empty subset of these errors may be reported.

    If an implementation can determine during the static analysis phase that a QueryBodyan XPath expression, if evaluated, would necessarily raise a dynamic error or that an expression, if evaluated, would necessarily raise a type error, the implementation may (but is not required to) report that error during the static analysis phase.

    An implementation can raise a dynamic error for a QueryBodyan XPath expression statically only if the queryexpression can never execute without raising that error, as in the following example:

    error()

    The following example contains a type error, which can be reported statically even if the implementation can not prove that the expression will actually be evaluated.

    if (empty($arg))
     then "cat" * 2
     else 0

    [Definition: In addition to static errors, dynamic errors, and type errors, an XQuery 4.0 and XPath 4.0 implementation may raise warnings, either during the static analysis phase or the dynamic evaluation phase. The circumstances in which warnings are raised, and the ways in which warnings are handled, are implementation-defined.]

    In addition to the errors defined in this specification, an implementation may raise a dynamic error for a reason beyond the scope of this specification. For example, limitations may exist on the maximum numbers or sizes of various objects. An error must be raised if such a limitation is exceeded [err:XPDY0130].

    2.4.2 Identifying and Reporting Errors

    The errors defined in this specification are identified by QNames that have the form err:XPYYnnnnerr:XXYYnnnn, where:

    • err denotes the namespace for XPath and XQuery errors, http://www.w3.org/2005/xqt-errors. This binding of the namespace prefix err is used for convenience in this document, and is not normative.

    • XP identifies the error as an XPath error (some errors, originally defined by XQuery and later added to XPath, use the code XQ instead).

    • XX denotes the language in which the error is defined, using the following encoding:

      • XP denotes an error defined by XPath. Such an error may also occur XQuery since XQuery includes XPath as a subset.

      • XQ denotes an error defined by XQuery (or an error originally defined by XQuery and later added to XPath).

    • YY denotes the error category, using the following encoding:

      • ST denotes a static error.

      • DY denotes a dynamic error.

      • TY denotes a type error.

    • nnnn is a unique numeric code.

    Note:

    The namespace URI for XPath and XQuery errors is not expected to change from one version of XQueryXPath to another. However, the contents of this namespace may be extended to include additional error definitions.

    The method by which an XQuery 4.0 and XPath 4.0 processor reports error information to the external environment is implementation-defined.

    An error can be represented by a URI reference that is derived from the error QName as follows: an error with namespace URI NS and local part LP can be represented as the URI reference NS#LP. For example, an error whose QName is err:XPST0017 could be represented as http://www.w3.org/2005/xqt-errors#XPST0017.

    Note:

    Along with a code identifying an error, implementations may wish to return additional information, such as the location of the error or the processing phase in which it was detected. If an implementation chooses to do so, then the mechanism that it uses to return this information is implementation-defined.

    2.4.3 Handling Dynamic Errors

    Except as noted in this document, if any operand of an expression raises a dynamic error, the expression also raises a dynamic error. If an expression can validly return a value or raise a dynamic error, the implementation may choose to return the value or raise the dynamic error (see 2.4.4 Errors and Optimization). For example, the logical expression expr1 and expr2 may return the value false if either operand returns false, or may raise a dynamic error if either operand raises a dynamic error.

    If more than one operand of an expression raises an error, the implementation may choose which error is raised by the expression. For example, in this expression:

    ($x div $y) + xs:decimal($z)

    both the sub-expressions ($x div $y) and xs:decimal($z) may raise an error. The implementation may choose which error is raised by the + expression. Once one operand raises an error, the implementation is not required, but is permitted, to evaluate any other operands.

    [Definition: In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called error values.] An implementation may provide a mechanism whereby an application-defined error handler can process error values and produce diagnostic messages. XQuery 3.1 provides standard error handling via Section 4.20 Try/Catch ExpressionsXQ.The host language may also provide error handling mechanisms.

    A dynamic error may be raised by a system function or operator. For example, the div operator raises an error if its operands are xs:decimal values and its second operand is equal to zero. Errors raised by system functions and operators are defined in [XQuery and XPath Functions and Operators 4.0] or the host language.

    A dynamic error can also be raised explicitly by calling the fn:error function, which always raises a dynamic error and never returns a value. This function is defined in Section 3.1.1 fn:errorFO. For example, the following function call raises a dynamic error, providing a QName that identifies the error, a descriptive string, and a diagnostic value (assuming that the prefix app is bound to a namespace containing application-defined error codes):

    error(xs:QName("app:err057"), "Unexpected value", string($v))

    2.4.4 Errors and Optimization

    Because different implementations may choose to evaluate or optimize an expression in different ways, certain aspects of raising dynamic errors are implementation-dependent, as described in this section.

    An implementation is always free to evaluate the operands of an operator in any order.

    In some cases, a processor can determine the result of an expression without accessing all the data that would be implied by the formal expression semantics. For example, the formal description of filter expressions suggests that $s[1] should be evaluated by examining all the items in sequence $s, and selecting all those that satisfy the predicate position()=1. In practice, many implementations will recognize that they can evaluate this expression by taking the first item in the sequence and then exiting. If $s is defined by an expression such as //book[author eq 'Berners-Lee'], then this strategy may avoid a complete scan of a large document and may therefore greatly improve performance. However, a consequence of this strategy is that a dynamic error or type error that would be detected if the expression semantics were followed literally might not be detected at all if the evaluation exits early. In this example, such an error might occur if there is a book element in the input data with more than one author subelement.

    The extent to which a processor may optimize its access to data, at the cost of not raising errors, is defined by the following rules.

    Consider an expression Q that has an operand (sub-expression) E. In general the value of E is a sequence. At an intermediate stage during evaluation of the sequence, some of its items will be known and others will be unknown. If, at such an intermediate stage of evaluation, a processor is able to establish that there are only two possible outcomes of evaluating Q, namely the value V or an error, then the processor may deliver the result V without evaluating further items in the operand E. For this purpose, two values are considered to represent the same outcome if their items are pairwise the same, where nodes are the same if they have the same identity, and values are the same if they are equal and have exactly the same type.

    There is an exception to this rule: If a processor evaluates an operand E (wholly or in part), then it is required to establish that the actual value of the operand E does not violate any constraints on its cardinality. For example, the expression $e eq 0 results in a type error if the value of $e contains two or more items. A processor is not allowed to decide, after evaluating the first item in the value of $e and finding it equal to zero, that the only possible outcomes are the value true or a type error caused by the cardinality violation. It must establish that the value of $e contains no more than one item.

    These rules apply to all the operands of an expression considered in combination: thus if an expression has two operands E1 and E2, it may be evaluated using any samples of the respective sequences that satisfy the above rules.

    The rules cascade: if A is an operand of B and B is an operand of C, then the processor needs to evaluate only a sufficient sample of B to determine the value of C, and needs to evaluate only a sufficient sample of A to determine this sample of B.

    The effect of these rules is that the processor is free to stop examining further items in a sequence as soon as it can establish that further items would not affect the result except possibly by causing an error. For example, the processor may return true as the result of the expression S1 = S2 as soon as it finds a pair of equal values from the two sequences.

    Another consequence of these rules is that where none of the items in a sequence contributes to the result of an expression, the processor is not obliged to evaluate any part of the sequence. Again, however, the processor cannot dispense with a required cardinality check: if an empty sequence is not permitted in the relevant context, then the processor must ensure that the operand is not an empty sequence.

    Examples:

    • If an implementation can find (for example, by using an index) that at least one item returned by $expr1 in the following example has the value 47, it is allowed to return true as the result of the some expression, without searching for another item returned by $expr1 that would raise an error if it were evaluated.

      some $x in $expr1 satisfies $x = 47
    • In the following example, if an implementation can find (for example, by using an index) the product element-nodes that have an id child with the value 47, it is allowed to return these nodes as the result of the path expression, without searching for another product node that would raise an error because it has an id child whose value is not an integer.

      //product[id = 47]

    For a variety of reasons, including optimization, implementations may rewrite expressions into a different form. There are a number of rules that limit the extent of this freedom:

    • Other than the raising or not raising of errors, the result of evaluating a rewritten expression must conform to the semantics defined in this specification for the original expression.

      Note:

      This allows an implementation to return a result in cases where the original expression would have raised an error, or to raise an error in cases where the original expression would have returned a result. The main cases where this is likely to arise in practice are (a) where a rewrite changes the order of evaluation, such that a subexpression causing an error is evaluated when the expression is written one way and is not evaluated when the expression is written a different way, and (b) where intermediate results of the evaluation cause overflow or other out-of-range conditions.

      Note:

      This rule does not mean that the result of the expression will always be the same in non-error cases as if it had not been rewritten, because there are many cases where the result of an expression is to some degree implementation-dependent or implementation-defined.

    • The rules described in 2.4.5 Guarded Expressions ensure that for certain kinds of expression (for example conditional expressions), changing the order of evaluation of subexpressions does not result in dynamic errors that would not otherwise occur.

    • Expressions must not be rewritten in such a way as to create or remove static errors. The static errors in this specification are defined for the original expression, and must be preserved if the expression is rewritten.

    • As stated earlier, an expression must not be rewritten to dispense with a required cardinality check: for example, string-length(//title) must raise an error if the document contains more than one title element.

    2.4.5 Guarded Expressions

    Changes in 4.0  

    1. The rules for “errors and optimization” have been tightened up to disallow many cases of optimizations that alter error behavior. In particular there are restrictions on reordering the operands of and and or, and of predicates in filter expressions, in a way that might allow the processor to raise dynamic errors that the author intended to prevent.   [Issue 71 PR 230 15 November 2022]

    [Definition: An expression E is said to be guarded by some governing condition C if evaluation of E is not allowed to fail with a dynamic error except when C applies.]

    For example, in a conditional expression if (P) then T else F, the subexpression T is guarded by P, and the subexpression F is guarded by not(P). One way an implementation can satisfy this rule is by not evaluating T unless P is true, and likewise not evaluating F unless P is false. Another way of satisfying the rule is for the implementation to evaluate all the subexpressions, but to catch any errors that occur in a guarded subexpression so they are not propagated.

    The existence of this rule enables errors to be prevented by writing expressions such as if ($y eq 0) then "N/A" else ($x div $y). This example will never fail with a divide-by-zero error because the else branch of the conditional is guarded.

    Similarly, in the mapping expression E1!E2, the subexpression E2 is guarded by the existence of an item from E1. This means, for example, that the expression (1 to $n)!doc('bad.xml') must not raise a dynamic error if $n is zero. The rule governing evaluation of guarded expressions is phrased so as not to disallow “loop-lifting” or “constant-folding” optimizations whose aim is to avoid repeated evaluation of a common subexpression; but such optimizations must not result in errors that would not otherwise occur.

    The complete list of expressions that have guarded subexpressions is as follows:

    • In a conditional expression (IfExpr) the then branch is guarded by the condition being true, and the else branch is guarded by the condition being false.

    • In a switch expression (SwitchExpr), the return expression of a particular case is guarded by the condition for that case matching, and no earlier case matching.

    • In a typeswitch expression (TypeswitchExpr), the return expression of a particular case is guarded by the condition for that case matching, and no earlier case matching.

    • In an and expression (AndExpr), the second operand is guarded by the value of the first operand being true.

    • In an or expression (OrExpr), the second operand is guarded by the value of the first operand being false.

    • In an otherwise expression (OtherwiseExpr), the second operand is guarded by the value of the first operand being an empty sequence.

    • In a path expression of the form E1/E2 or E1//E2, and in a mapping expression of the form E1!E2, the right-hand operand E2 is guarded by the existence of at least one item in the result of evaluating E1.

      This rule applies even if E2 does not reference the context value. For example, no dynamic error can be thrown by the expression (1 to $n)!doc('bad.xml') in the case where $n is zero.

    • In a filter expression of the form E[P], the predicate P is guarded by the existence of at least one item in the result of evaluating E.

      This rule has the consequence that in a filter expression with multiple predicates, such as E[P1][P2], evaluation of P2 must not raise a dynamic error unless P1 returns true. This rule does not prevent reordering of predicates (for example, to take advantage of indexes), but it does require that any such reordering must not result in errors that would not otherwise occur.

    • In a for expression (ForExpr) such as for $x in S return E, the expression E is guarded by the existence of an item bound to $x.

      In a FLWOR expression (FLWORExpr), 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 for $x in S return E, the expression E is guarded by the existence of an item bound to $x.

      This means that the expression for $x in 1 to $n return doc('bad.xml') must not raise a dynamic error in the case where $n is zero.

    • In a quantified expression (QuantifiedExpr) such as some $x in S satisfies P, the expression P is guarded by the existence of an item bound to $x.

    The fact that an expression is guarded does not remove the obligation to report static errors in the expression; nor does it remove the option to report statically detectable type errors.

    Note:

    These rules do not constrain the order of evaluation of subexpressions. For example, given an expression such as //person[@first = "Winston"][@last = "Churchill"], or equivalently //person[@first = "Winston" and @last = "Churchill"], an implementation might use an index on the value of @last to select items that satisfy the second condition, and then filter these items on the value of the first condition. Alternatively, it might evaluate both predicates in parallel. Or it might interpose an additional redundant condition: //person[string-length(@first) + string-length(@last) = 16][@first = "Winston"][@last = "Churchill"]. But implementations must ensure that such rewrites do not result in dynamic errors being reported that would not occur if the predicates were evaluated in order as written.

    Note:

    Although the rules for guarded expressions prevent optimizations resulting in spurious errors, they do not prevent optimizations whose effect is to mask errors. For example, the rules guarantee that ("A", 3)[. instance of xs:integer][. eq 3] will not raise an error caused by the comparison ("A" eq 3), but they do not guarantee the converse: the expression ("A", 3)[. eq 3][. instance of xs:integer] may or may not raise a dynamic error.

    Note:

    The rules in this section do not disallow all expression rewrites that might result in dynamic errors. For example, rewriting ($x - $y + $z) as ($x + $z - $y) is permitted even though it might result in an arithmetic overflow.

    Note:

    Some implementations allow calls on external functions that have side-effects. The semantics of such function calls are entirely implementation defined. Processors may choose to reference the rules for guarded expressions when defining the behavior of such function calls, but this is outside the scope of the language specification.

    2.4.6 Implausible Expressions

    Changes in 4.0  

    1. The rules for reporting type errors during static analysis have been changed so that a processor has more freedom to report errors in respect of constructs that are evidently wrong, such as @price/@value, even though dynamic evaluation is defined to return an empty sequence rather than an error.   [Issue 602 PR 603 25 July 2023]

    [Definition: Certain expressions, while not erroneous, are classified as being implausible, because they achieve no useful effect.]

    An example of an implausible expression is @code/text(). 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.

    Where an expression is classified (by rules in this specification) as being implausible, a processor may (but is not required to) raise a static error.

    For reasons of backwards compatibility and interoperability, and to facilitate automatic generation of XQuery 4.0 and XPath 4.0 code, a processor must provide a mode of operation in which implausible expressions are not treated as static errors, but are evaluated with the defined semantics for the expression.

    Some other examples of implausible expressions include:

    • round(tokenize($input)). The result of fn:tokenize is a sequence of strings (xs:string*), while the required type for the first argument of fn:round is optional numeric (xs:numeric?). The expression can succeed only in the exceptional case where the result of fn:tokenize is an empty sequence, in which case the result of fn:round will also be an empty sequence; it is therefore highly likely that the expression was written in error.

    • parse-csv($input)?column-names. The signature of the parse-csv function declares its return type as record(columns, rows). There is no field in this record named column-names, 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.

    Note:

    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.

    Note:

    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.

    2.5 Concepts

    This section explains some concepts that are important to the processing of XQuery 4.0 and XPath 4.0 expressions.

    2.5.1 Document Order

    An ordering called document order is defined among all the nodes accessible during processing of a given queryexpression, which may consist of one or more trees (documents or fragments). Document order is defined in Section 2.5 Document OrderDM, and its definition is repeated here for convenience. Document order is a total ordering, although the relative order of some nodes is implementation-dependent. [Definition: Informally, document order is the order in which nodes appear in the XML serialization of a document.] [Definition: Document order is stable, which means that the relative order of two nodes will not change during the processing of a given queryexpression, even if this order is implementation-dependent.] [Definition: The node ordering that is the reverse of document order is called reverse document order.]

    Within a tree, document order satisfies the following constraints:

    1. The root node is the first node.

    2. Every node occurs before all of its children and descendants.

    3. Namespace nodes immediately follow the element node with which they are associated. The relative order of namespace nodes is stable but implementation-dependent.

    4. Attribute nodes immediately follow the namespace nodes of the element node with which they are associated. The relative order of attribute nodes is stable but implementation-dependent.

    5. The relative order of siblings is the order in which they occur in the children property of their parent node.

    6. Children and descendants occur before following siblings.

    The relative order of nodes in distinct trees is stable but implementation-dependent, subject to the following constraint: If any node in a given tree T1 is before any node in a different tree T2, then all nodes in tree T1 are before all nodes in tree T2.

    2.5.2 Typed Value and String Value

    Every node has a typed value and a string value, except for nodes whose value is absentDM. [Definition: The typed value of a node is a sequence of atomic items and can be extracted by applying the Section 2.1.4 fn:dataFO function to the node.] [Definition: The string value of a node is a string and can be extracted by applying the Section 2.1.3 fn:stringFO function to the node.]

    An implementation may store both the typed value and the string value 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 xs:integer value 30, its string value might be "30" or "0030".

    The typed value, string value, and type annotation of a node are closely related. If the node was created by mapping from an Infoset or PSVI, the relationships among these properties are defined by rules in Section 2.8 Schema InformationDM.

    The typed value, string value, and type annotation of a node are closely related, and are defined by rules found in the following locations:

    The relationship between typed value and string value for various kinds of nodes is summarized and illustrated by examples below.

    1. For text and document nodes, the typed value of the node is the same as its string value, as an instance of the type xs:untypedAtomic. The string value of a document node is formed by concatenating the string values of all its descendant text nodes, in document order.

    2. The typed value of a comment, namespace, or processing instruction node is the same as its string value. It is an instance of the type xs:string.

    3. The typed value of an attribute node with the type annotationxs:anySimpleType or xs:untypedAtomic is the same as its string value, as an instance of xs:untypedAtomic. 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 [XML Schema 1.0] or [XML Schema 1.1] Part 2 for the relevant type.

      Example: A1 is an attribute having string value "3.14E-2" and type annotation xs:double. The typed value of A1 is the xs:double value whose lexical representation is 3.14E-2.

      Example: A2 is an attribute with type annotation xs:IDREFS, which is a list datatype whose item type is the atomic datatype xs:IDREF. Its string value is "bar baz faz". The typed value of A2 is a sequence of three atomic items ("bar", "baz"", "faz""), each of type xs:IDREF. 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 xs:IDREFS), its typed value is treated as a sequence of the generalized atomic type from which it is derived (such as xs:IDREF).

    4. For an element node, the relationship between typed value and string value depends on the node’s type annotation, as follows:

      1. If the type annotation is xs:untyped or xs:anySimpleType or denotes a complex type with mixed content (including xs:anyType), then the typed value of the node is equal to its string value, as an instance of xs:untypedAtomic. However, if the nilled property of the node is true, then its typed value is the empty sequence.

        Example: E1 is an element node having type annotation xs:untyped and string value "1999-05-31". The typed value of E1 is "1999-05-31", as an instance of xs:untypedAtomic.

        Example: E2 is an element node with the type annotation formula, which is a complex type with mixed content. The content of E2 consists of the character H, a child element named subscript with string value "2", and the character O. The typed value of E2 is "H2O" as an instance of xs:untypedAtomic.

      2. 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 nilled property of the node is true, then its typed value is the empty sequence.

        Example: E3 is an element node with the type annotation cost, which is a complex type that has several attributes and a simple content type of xs:decimal. The string value of E3 is "74.95". The typed value of E3 is 74.95, as an instance of xs:decimal.

        Example: E4 is an element node with the type annotation hatsizelist, which is a simple type derived from the atomic typehatsize, which in turn is derived from xs:integer. The string value of E4 is "7 8 9". The typed value of E4 is a sequence of three values (7, 8, 9), each of type hatsize.

        Example: E5 is an element node with the type annotation my:integer-or-string which is a union type with member types xs:integer and xs:string. The string value of E5 is "47". The typed value of E5 is 47 as a xs:integer, since xs:integer 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.

        Note:

        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.

      3. 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.

      4. If the type annotation denotes a complex type with element-only content, then the typed value of the node is absentDM. The fn:data function raises a type error [err:FOTY0012]FO40 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.

        Example: E6 is an element node with the type annotation weather, which is a complex type whose content type specifies element-only. E6 has two child elements named temperature and precipitation. The typed value of E6 is absentDM, and the fn:data function applied to E6 raises an error.

    2.5.3 Atomization

    The semantics of some XQuery 4.0 and XPath 4.0 operators depend on a process called atomization. Atomization is applied to a value when the value is used in a context in which a sequence of atomic items is required. The result of atomization is either a sequence of atomic items or a type error [err:FOTY0012]FO40. [Definition: Atomization of a sequence is defined as the result of invoking the fn:data function, as defined in Section 2.1.4 fn:dataFO.]

    The semantics of fn:data are repeated here for convenience. The result of fn:data is the sequence of atomic items produced by applying the following rules to each item in the input sequence:

    • If the item is an atomic item, it is returned.

    • If the item is a node, its typed value is returned (a type error [err:FOTY0012]FO40 is raised if the node has no typed value.)

    • If the item is a function item (other than an array) or map a type error [err:FOTY0013]FO40 is raised.

    • If the item is an array $a, atomization is defined as $a?* ! fn:data(.), which is equivalent to atomizing the members of the array.

      Note:

      This definition recursively atomizes members that are arrays. Hence, the result of atomizing the array [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] is the sequence (1, 2, 3, 4, 5, 6).

    Atomization is used in processing the following types of expressions:

    • Arithmetic expressions

    • Comparison expressions

    • Function calls and returns

    • Cast expressions

    • Constructor expressions for various kinds of nodes

    • order by clauses in FLWOR expressions

    • group by clauses in FLWOR expressions

    • Switch expressions

    2.5.4 Effective Boolean Value

    Under certain circumstances (listed below), it is necessary to find the effective boolean value of a value. [Definition: The effective boolean value of a value is defined as the result of applying the fn:boolean function to the value, as defined in Section 7.3.1 fn:booleanFO.]

    The dynamic semantics of fn:boolean are repeated here for convenience:

    1. If its operand is an empty sequence, fn:boolean returns false.

    2. If its operand is a sequence whose first item is a node, fn:boolean returns true.

    3. If its operand is a singleton value of type xs:boolean or derived from xs:boolean, fn:boolean returns the value of its operand unchanged.

    4. If its operand is a singleton value of type xs:string, xs:anyURI, xs:untypedAtomic, or a type derived from one of these, fn:boolean returns false if the operand value has zero length; otherwise it returns true.

    5. If its operand is a singleton value of any numeric type or derived from a numeric type, fn:boolean returns false if the operand value is NaN or is numerically equal to zero; otherwise it returns true.

    6. In all other cases, fn:boolean raises a type error [err:FORG0006]FO40.

      Note:

      For instance, fn:boolean raises a type error if the operand is a function, a map, or an array.

    The effective boolean value of a sequence is computed implicitly during processing of the following types of expressions:

    Note:

    The definition of effective boolean value is not used when casting a value to the type xs:boolean, for example in a cast expression or when passing a value to a function whose expected parameter is of type xs:boolean.

    2.5.5 URI Literals

    XQuery 4.0 and XPath 4.0 requires a statically known, valid URI in a URILiteral or a BracedURILiteral. An implementation may raise a static error [err:XQST0046] if the value of a URI Literal or a Braced URI Literal is of nonzero length and is neither an absolute URI nor a relative URI.

    As in a string literal, any predefined entity reference (such as &amp;), character reference (such as &#x2022;), or EscapeQuot or EscapeApos (for example, "") is replaced by its appropriate expansion. Certain characters, notably the ampersand, can only be represented using a predefined entity reference or a character reference.

    Note:

    The xs:anyURI type is designed to anticipate the introduction of Internationalized Resource Identifiers (IRIs) as defined in [RFC3987].

    Whitespace is normalized using the whitespace normalization rules of fn:normalize-space. If the result of whitespace normalization contains only whitespace, the corresponding URI consists of the empty string. Whitespace normalization is done after the expansion of character references, so writing a newline (for example) as &#xA; does not prevent its being normalized to a space character.

    A Braced URI Literal or URI Literal is not subjected to percent-encoding or decoding as defined in [RFC3986].

    2.5.6 Resolving a Relative URI Reference

    [Definition: To resolve a relative URI$rel against a base URI $base is to expand it to an absolute URI, as if by calling the function fn:resolve-uri($rel, $base).] During static analysis, the base URI is the Static Base URI. During dynamic evaluation, the base URI used to resolve a relative URI reference depends on the semantics of the expression.

    Any process that attempts to resolve a URI against a base URI, or to dereference the URI, may apply percent-encoding or decoding as defined in the relevant RFCs.

    3 Types

    As noted in 2.1.2 Values, every value in XQuery 4.0 and XPath 4.0 is regarded as a sequence of zero, one, or more items. The type system of XQuery 4.0 and XPath 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.

    The type system of XQuery 4.0 and XPath 4.0 is related to the type system of [XML Schema 1.0] or [XML Schema 1.1] in two ways:

    • atomic items in XQuery 4.0 and XPath 4.0 (which are one kind of item) have atomic types such as xs:string, xs:boolean, and xs:integer. These types are taken directly from their definitions in [XML Schema 1.0] or [XML Schema 1.1].

    • Nodes (which are another kind of item) have a property called a type annotation which determines the type of their content. The type annotation is a schema type. The type annotation of a node must not be confused with the item type of the node. For example, an element <age>23</age> might have been validated against a schema that defines this element as having xs:integer content. If this is the case, the type annotation of the node will be xs:integer, and in the XQuery 4.0 and XPath 4.0 type system, the node will match the item typeelement(age, xs:integer).

    This chapter of the specification starts by defining sequence types and item types, which describe the range of values that can be bound to variables, used in expressions, or passed to functions. It then describes how these relate to schema types, that is, the simple and complex types defined in an XSD schema.

    Note:

    In many situations the terms item type and sequence type are used interchangeably to refer either to the type itself, or to the syntactic construct that designates the type: so in the expression $x instance of xs:string*, the construct xs:string* uses the SequenceType syntax to designate a sequence type whose instances are sequences of strings. When more precision is required, the specification is careful to use the terms item type and sequence type to refer to the actual types, while using the production names ItemType and SequenceType to refer to the syntactic designators of these types.

    3.1 Sequence Types

    [Definition: A sequence type is a type that can be expressed using the SequenceType syntax. Sequence types are used whenever it is necessary to refer to a type in an XQuery 4.0 and XPath 4.0 expression. Since all values are sequences, every value matches one or more sequence types.]

    Whenever it is necessary to refer to a sequence type in an XQuery 4.0 and XPath 4.0 expression, the SequenceType syntax is used.

    [228]   SequenceType   ::=   ("empty-sequence" "(" ")")
    | (ItemTypeOccurrenceIndicator?)
    ("empty-sequence" "(" ")")
    | (ItemTypeOccurrenceIndicator?)
    [230]   ItemType   ::=   AnyItemTest | TypeName | KindTest | FunctionType | MapType | ArrayType | RecordType | EnumerationType | ChoiceItemType
    AnyItemTest | TypeName | KindTest | FunctionType | MapType | ArrayType | RecordType | EnumerationType | ChoiceItemType
    [229]   OccurrenceIndicator   ::=   "?" | "*" | "+"/* xgc: occurrence-indicators */
    "?" | "*" | "+"/* xgc: occurrence-indicators */
    /* xgc: occurrence-indicators */

    [Definition: A sequence type designator is a syntactic construct conforming to the grammar rule SequenceType. A sequence type designator is said to designate a sequence type.]

    With the exception of the special type empty-sequence(), a sequence type consists of an item type that constrains the type of each item in the sequence, and a cardinality that constrains the number of items in the sequence. Apart from the item type item(), which permits any kind of item, item types divide into node types (such as element()), generalized atomic types (such as xs:integer) and function types (such as function() as item()*).

    The cardinality of a sequence type is represented in the sequence type designator syntax by an OccurrenceIndicator. The occurrence indicators +, *, and ? bind to the last ItemType in the SequenceType, as described in the occurrence-indicators constraint.

    3.1.1 Examples of Sequence Types

    Here are some examples of sequence types that might be used in XQuery 4.0 and XPath 4.0:

    • xs:date refers to the built-in atomic schema type named xs:date

    • attribute()? refers to an optional attribute node

    • element() refers to any element node

    • element(po:shipto, po:address) refers to an element node that has the name po:shipto and has the type annotation po:address (or a schema type derived from po:address)

    • element(*, po:address) refers to an element node of any name that has the type annotation po:address (or a type derived from po:address)

    • element(customer) refers to an element node named customer with any type annotation

    • schema-element(customer) refers to an element node whose name is customer (or is in the substitution group headed by customer) and whose type annotation matches the schema type declared for a customer element in the in-scope element declarations

    • node()* refers to a sequence of zero or more nodes of any kind

    • item()+ refers to a sequence of one or more items

    • function(*) refers to any function item, regardless of arity or type

    • function(node()) as xs:string* refers to a function item that takes a single argument whose value is a single node, and returns a sequence of zero or more xs:string values

    • (fn(node()) as xs:string)* refers to a sequence of zero or more function items, each of which takes a single argument whose value is a single node, and returns as its result a single xs:string value

    3.1.2 Sequence Type Matching

    [Definition: SequenceType matching compares a value with an expected sequence type. ] For example, an instance of expression returns true if a given value matches a given sequence type, and false if it does not.

    An XQuery 4.0 and XPath 4.0 implementation must be able to determine relationships among the types in type annotations in an XDM instance and the types in the in-scope schema definitions (ISSD). An XQuery 4.0 and XPath 4.0 implementation must be able to determine relationships among the types in ISSDs used in different modules of the same query.

    [Definition: The use of a value that has a dynamic type that is a subtype of the expected type is known as subtype substitution.] Subtype substitution does not change the actual type of a value. For example, if an xs:integer value is used where an xs:decimal value is expected, the value retains its type as xs:integer.

    The rules for SequenceType matching are given below, with examples (the examples are for purposes of illustration, and do not cover all possible cases).

    An OccurrenceIndicator specifies the number of items in a sequence, as follows:

    • ? matches zero or one items

    • * matches zero or more items

    • + matches one or more items

    As a consequence of these rules, any sequence type whose OccurrenceIndicator is * or ? matches a value that is an empty sequence.

    3.1.3 Schema Type Relationships

    Some item types are defined in terms of schema types, and the matching rules for such item types depend on the rules defining relationships between schema types in the XSD specification.

    [Definition: A schema typeS1 is said to derive fromschema typeS2 if any of the following conditions is true:

    ]

    Note:

    The XML Schema specification does not completely specify the circumstances under which S1 and S2 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.

    3.2 Item Types

    [Definition: An item type is a type that can be expressed using the ItemType syntax, which forms part of the SequenceType syntax. Item types match individual items.]

    Note:

    While this definition is adequate for the purpose of defining the syntax of XQuery 4.0 and XPath 4.0, it ignores the fact that there are also item types that cannot be expressed using XQuery 4.0 and XPath 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.

    In most cases, the set of items matched by an item type consists either exclusively of atomic items, exclusively of nodes, or exclusively of function itemsDM. Exceptions include the generic types item(), which matches all items, xs:error, which matches no items, and choice item types, which can match any combination of types.

    [Definition: An item type designator is a syntactic construct conforming to the grammar rule ItemType. An item type designator is said to designate an item type.]

    Note:

    Two item type designators may designate the same item type. For example, element() and element(*) are equivalent, as are attribute(A) and attribute(A, xs:anySimpleType).

    Lexical QNames appearing in an item type designator(other than within a function assertion) have their prefixes expanded to namespace URIs by means of the statically known namespaces and (where applicable) the default namespace for elements and types. Equality of QNames is defined by the eq operator.

    [230]   ItemType   ::=   AnyItemTest | TypeName | KindTest | FunctionType | MapType | ArrayType | RecordType | EnumerationType | ChoiceItemType
    AnyItemTest | TypeName | KindTest | FunctionType | MapType | ArrayType | RecordType | EnumerationType | ChoiceItemType
    [231]   AnyItemTest   ::=   "item" "(" ")"
    "item" "(" ")"
    [246]   TypeName   ::=   EQName
    EQName
    [232]   KindTest   ::=   DocumentTest
    | ElementTest
    | AttributeTest
    | SchemaElementTest
    | SchemaAttributeTest
    | PITest
    | CommentTest
    | TextTest
    | NamespaceNodeTest
    | AnyKindTest
    DocumentTest
    | ElementTest
    | AttributeTest
    | SchemaElementTest
    | SchemaAttributeTest
    | PITest
    | CommentTest
    | TextTest
    | NamespaceNodeTest
    | AnyKindTest
    [234]   DocumentTest   ::=   "document-node" "(" (ElementTest | SchemaElementTest | NameTestUnion)? ")"
    "document-node" "(" (ElementTest | SchemaElementTest | NameTestUnion)? ")"
    [241]   ElementTest   ::=   "element" "(" (NameTestUnion ("," TypeName "?"?)?)? ")"
    "element" "(" (NameTestUnion ("," TypeName "?"?)?)? ")"
    [242]   SchemaElementTest   ::=   "schema-element" "(" ElementName ")"
    "schema-element" "(" ElementName ")"
    [239]   AttributeTest   ::=   "attribute" "(" (NameTestUnion ("," TypeName)?)? ")"
    "attribute" "(" (NameTestUnion ("," TypeName)?)? ")"
    [240]   SchemaAttributeTest   ::=   "schema-attribute" "(" AttributeName ")"
    "schema-attribute" "(" AttributeName ")"
    [244]   ElementName   ::=   EQName
    EQName
    [243]   AttributeName   ::=   EQName
    EQName
    [238]   PITest   ::=   "processing-instruction" "(" (NCName | StringLiteral)? ")"
    "processing-instruction" "(" (NCName | StringLiteral)? ")"
    [236]   CommentTest   ::=   "comment" "(" ")"
    "comment" "(" ")"
    [237]   NamespaceNodeTest   ::=   "namespace-node" "(" ")"
    "namespace-node" "(" ")"
    [235]   TextTest   ::=   "text" "(" ")"
    "text" "(" ")"
    [233]   AnyKindTest   ::=   "node" "(" ")"
    "node" "(" ")"
    [247]   FunctionType   ::=   Annotation* (AnyFunctionType
    | TypedFunctionType)
    Annotation* (AnyFunctionType
    | TypedFunctionType)
    [248]   AnyFunctionType   ::=   ("function" | "fn") "(" "*" ")"
    ("function" | "fn") "(" "*" ")"
    [249]   TypedFunctionType   ::=   ("function" | "fn") "(" (SequenceType ** ",") ")" "as" SequenceType
    ("function" | "fn") "(" (SequenceType ** ",") ")" "as" SequenceType
    [263]   ChoiceItemType   ::=   "(" (ItemType ++ "|") ")"
    "(" (ItemType ++ "|") ")"
    [250]   MapType   ::=   AnyMapType | TypedMapType
    AnyMapType | TypedMapType
    [253]   RecordType   ::=   AnyRecordType | TypedRecordType
    AnyRecordType | TypedRecordType
    [260]   ArrayType   ::=   AnyArrayType | TypedArrayType
    AnyArrayType | TypedArrayType
    [259]   EnumerationType   ::=   "enum" "(" (StringLiteral ++ ",") ")"
    "enum" "(" (StringLiteral ++ ",") ")"

    This section defines the syntax and semantics of different ItemTypes in terms of the values that they match.

    Note:

    For an explanation of the EBNF grammar notation (and in particular, the operators ++ and **), see A.1 EBNF.

    An item type designator written simply as an EQName (that is, a TypeName) is interpreted as follows:

    1. If the name is written as a lexical QName, then it is expanded using the in-scope namespaces in the static context. If the name is an unprefixed NCName, then it is expanded according to the default namespace for elements and types.

    2. If the name matches a named item type in the static context, 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.

    3. Otherwise, it must match the name of a type in the in-scope schema types in the static context: specifically, an atomic type or a pure union type. See 3.5 Schema Types for details.

      Note:

      A name in the xs namespace will always fall into this category, since the namespace is reserved. See 2.1.3 Namespaces and QNames.

    4. If the name cannot be resolved to a type, a static error is raised [err:XPST0051].

    3.2.1 General item types

    • item() matches any single item.

      For example, item() matches the atomic item 1, the element <a/>, or the function fn:concat#3.

    • A ChoiceItemType lists a number of alternative item types in parentheses, separated by "|". An item matches a ChoiceItemType it if matches any of the alternatives.

      For example, (map(*) | array(*)) matches any item that is a map or an array.

      Note:

      If there is only one alternative, the ChoiceItemType designates the same item type as the ItemType 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 (fn() as xs:boolean)*. In this example the parentheses are needed to indicate where the occurrence indicator belongs.

    3.2.2 Atomic Types

    Atomic types in the XQuery 4.0 and XPath 4.0 type system correspond directly to atomic types as defined in the [XML Schema 1.0] or [XML Schema 1.1] type system.

    Atomic types are either built-in atomic types such as xs:integer, or user-defined atomic types imported from a schema. Atomic types are identified by a QName: see 2.1.3 Namespaces and QNames.

    Note:

    A schema may also include anonymous atomic types. Such types are not usable directly in XQuery 4.0 and XPath 4.0, though they may appear as the values of type annotations on nodes.

    [Definition: A generalized atomic type is an item type whose instances are all atomic items. Generalized atomic types include (a) atomic types, either built-in (for example xs:integer) or imported from a schema, (b) pure union types, either built-in (xs:numeric and xs:error) or imported from a schema, (c) choice item types if their alternatives are all generalized atomic types, and (d) enumeration types. ].

    A generalized atomic type may be designated by an ItemType in any of the following ways:

    An atomic item A matches the generalized atomic typeGAT if the type annotation of Aderives fromGAT.

    Example: The ItemTypexs:decimal matches any value of type xs:decimal. It also matches any value of type shoesize, if shoesize is an atomic type derived by restriction from xs:decimal.

    Example: Suppose ItemTypedress-size is a union type that allows either xs:decimal values for numeric sizes (for example: 4, 6, 10, 12), or one of an enumerated set of xs:strings (for example: small, medium, large). The ItemTypedress-size matches any of these values.

    Note:

    The names of list types such as xs:IDREFS are not accepted in this context, but can often be replaced by a generalized atomic type with an occurrence indicator, such as xs:IDREF+.

    3.2.3 Union Types

    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.

    [Definition: A pure union type is a simple type that satisfies the following constraints: (a) {variety}XS11-1 is union, (b) the {facets}XS11-1 property is empty, (c) no type in the transitive membership of the union type has {variety}XS11-1list, and (d) no type in the transitive membership of the union type is a type with {variety}XS11-1union having a non-empty {facets}XS11-1 property].

    Note:

    The definition of pure union type 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 atomic type defined as one of the member types of the union is also a valid instance of the union type.

    Note:

    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.

    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.

    Note:

    Local union types (see 3.2.5 Choice Item Types) and enumeration types cannot be used as the target for schema validation.

    3.2.4 Namespace-sensitive Types

    [Definition: The namespace-sensitive types are xs:QName, xs:NOTATION, types derived by restriction from xs:QName or xs:NOTATION, list types that have a namespace-sensitive item type, and union types with a namespace-sensitive type in their transitive membership.]

    It is not possible to preserve the type of a namespace-sensitive value without also preserving the namespace binding that defines the meaning of each namespace prefix used in the value. Therefore, XQuery 4.0 and XPath 4.0 defines some error conditions that occur only with namespace-sensitive values. For instance, casting to a namespace-sensitive type raises a type error [err:FONS0004]FO40 if the namespace bindings for the result cannot be determined.

    3.2.5 Choice Item Types

    Changes in 4.0  

    1. Choice item types (an item type allowing a set of alternative item types) are introduced.   [Issue 122 PR 1132 9 April 2024]

    [Definition: A choice item type defines an item type that is the union of a number of alternatives. For example the type (xs:hexBinary | xs:base64Binary) defines the union of these two primitive atomic types, while the type (map(*) | array(*)) matches any item that is either a map or an array.]

    An item matches a ChoiceItemType if it matches any of the alternatives listed within the parentheses.

    For example, the type (xs:NCName | enum("")) matches any value that is either an instance of xs:NCName, or a zero-length string. This might be a suitable type for a variable that holds a namespace prefix.

    If all the alternatives are generalized atomic types then the choice item type is itself a generalized atomic type, which means, for example, that it can be used as the target of a cast expression.

    Note:

    A choice item type in which all the alternatives are atomic behaves in most respects like a schema-defined pure union type. 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.

    Note:

    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.

    A local union type can also be used in a cast expression: cast @when as (xs:date | xs:dateTime) allows the attribute @when to be either an xs:date, or an xs:dateTime.

    An instance of expression can be used to test whether a value belongs to one of a number of specified types: $x instance of (xs:string | xs:anyURI | xs:untypedAtomic) returns true if $x is an instance of any of these three atomic types, while $x instance of (map(*) | array(*)) tests whether $x is a map or array.

    3.2.6 Enumeration Types

    Changes in 4.0  

    1. Enumeration types are added as a new kind of ItemType, constraining the value space of strings.  [Issue 688 PR 691 10 October 2023]

    [Definition: An EnumerationType accepts a fixed set of string values.]

    [259]   EnumerationType   ::=   "enum" "(" (StringLiteral ++ ",") ")"
    "enum" "(" (StringLiteral ++ ",") ")"

    An enumeration type has a value space consisting of a set of xs:string values. When matching strings against an enumeration type, strings are always compared using the Unicode codepoint collation.

    For example, if an argument of a function declares the required type as enum("red", "green", "blue"), then the string "green" is accepted, while "yellow" is rejected with a type error.

    Technically, enumeration types are defined as follows:

    • An enumeration type with a single enumerated value (such as enum("red")) is an anonymous atomic type derived from xs:string by restriction using an enumeration facet that permits only the value "red". This is referred to as a singleton enumeration type. It is equivalent to the XSD-defined type:

      <xs:simpleType>
         <xs:restriction base="xs:string">
      @@ -607,9 +607,9 @@
       return $y[@value gt $x/@min]

    Note:

    It is not required that the variables should have distinct names. It is permitted, for example, to write:

    let $x := "[A fine romance]"
     let $x := substring-after($x, "[")
     let $x := substring-before($x, "]")
    -return upper-case($x)

    which returns the result "A FINE ROMANCE". Note that this expression declares three separate variables which happen to have the same name; it should not be read as declaring a single variable and binding it successively to different values.

    4.14 Maps and Arrays

    Most modern programming languages have support for collections of key/value pairs, which may be called maps, dictionaries, associative arrays, hash tables, keyed lists, or objects (these are not the same thing as objects in object-oriented systems). In XQuery 4.0 and XPath 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 and XPath 4.0, we have both sequences and arrays. Unlike sequences, an array is an item, and can appear as an item in a sequence.

    Note:

    The XQuery 4.0 and XPath 4.0 specification focuses on syntax provided for maps and arrays, especially constructors and lookup.

    Some of the functionality typically needed for maps and arrays is provided by functions defined in Section 17 MapsFO and Section 18 ArraysFO, including functions used to read JSON to create maps and arrays, serialize maps and arrays to JSON, combine maps to create a new map, remove map entries to create a new map, iterate over the keys of a map, convert an array to create a sequence, combine arrays to form a new array, and iterate over arrays in various ways.

    4.14.1 Maps

    Changes in 4.0  

    1. Ordered maps are introduced.  [Issue 564 PR 1609 25 November 2024]

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

    Maps and their properties are defined in the data model: see Section 2.9.5 Map ItemsDM. For an overview of the functions available for processing maps, see Section 17 MapsFO.

    Note:

    Maps in XQuery 4.0 and XPath 4.0 have a property called [TERMDEF dt-map-ordered IN DM40], which takes the value true or false; a map is accordingly said to be ordered or unordered. The effect of this property is explained in Section 2.9.5 Map ItemsDM. In summary:

    • In an unordered map, the order of entries in the map is implementation dependent; it may, for example, be the result of a randomized hashing algorithm.

    • In an ordered map, the order of entries is predictable and depends on the order in which they were added to the map.

    4.14.1.1 Map Constructors

    Changes in 4.0  

    1. In map constructors, the keyword map is now optional, so map { 0: false(), 1: true() } can now be written { 0: false(), 1: true() }, provided it is used in a context where this creates no ambiguity.   [Issue 1070 PR 1071 26 March 2024]

    2. The order of key-value pairs in the map constructor is now retained in the constructed map.  [Issue 564 PR 1609 25 November 2024]

    A map can be created using a MapConstructor.

    [212]   MapConstructor   ::=   "map"? "{" (MapConstructorEntry ** ",") "}"
    "map"? "{" (MapConstructorEntry ** ",") "}"
    [213]   MapConstructorEntry   ::=   MapKeyExpr ":" MapValueExpr
    MapKeyExpr ":" MapValueExpr
    [214]   MapKeyExpr   ::=   ExprSingle
    ExprSingle
    [215]   MapValueExpr   ::=   ExprSingle
    ExprSingle

    Note:

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

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

    Although the grammar allows a MapConstructor to appear within an EnclosedExpr (that is, between curly brackets), this may be confusing to readers, and using the map keyword in such cases may improve clarity. In any event, if the EnclosedExpr appears in a context such as a StringTemplate, the two adjacent left opening braces must at least be separated by whitespace.

    Note:

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

    For instance, consider the expression {a:b}. Although it matches the EBNF for MapConstructor (with a matching MapKeyExpr and b matching MapValueExpr), the "longest possible match" rule requires that a:b be parsed as a QName, which results in a syntax error. Changing the expression to {a :b} or {a: b} will prevent this, resulting in the intended parse.

    Similarly, consider these three expressions:

    {a:b:c}
    +return upper-case($x)

    which returns the result "A FINE ROMANCE". Note that this expression declares three separate variables which happen to have the same name; it should not be read as declaring a single variable and binding it successively to different values.

    4.14 Maps and Arrays

    Most modern programming languages have support for collections of key/value pairs, which may be called maps, dictionaries, associative arrays, hash tables, keyed lists, or objects (these are not the same thing as objects in object-oriented systems). In XQuery 4.0 and XPath 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 and XPath 4.0, we have both sequences and arrays. Unlike sequences, an array is an item, and can appear as an item in a sequence.

    Note:

    The XQuery 4.0 and XPath 4.0 specification focuses on syntax provided for maps and arrays, especially constructors and lookup.

    Some of the functionality typically needed for maps and arrays is provided by functions defined in Section 17 MapsFO and Section 18 ArraysFO, including functions used to read JSON to create maps and arrays, serialize maps and arrays to JSON, combine maps to create a new map, remove map entries to create a new map, iterate over the keys of a map, convert an array to create a sequence, combine arrays to form a new array, and iterate over arrays in various ways.

    4.14.1 Maps

    Changes in 4.0  

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

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

    Maps and their properties are defined in the data model: see Section 2.9.5 Map ItemsDM. For an overview of the functions available for processing maps, see Section 17 MapsFO.

    Note:

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

    4.14.1.1 Map Constructors

    Changes in 4.0  

    1. In map constructors, the keyword map is now optional, so map { 0: false(), 1: true() } can now be written { 0: false(), 1: true() }, provided it is used in a context where this creates no ambiguity.   [Issue 1070 PR 1071 26 March 2024]

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

    A map can be created using a MapConstructor.

    [212]   MapConstructor   ::=   "map"? "{" (MapConstructorEntry ** ",") "}"
    "map"? "{" (MapConstructorEntry ** ",") "}"
    [213]   MapConstructorEntry   ::=   MapKeyExpr ":" MapValueExpr
    MapKeyExpr ":" MapValueExpr
    [214]   MapKeyExpr   ::=   ExprSingle
    ExprSingle
    [215]   MapValueExpr   ::=   ExprSingle
    ExprSingle

    Note:

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

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

    Although the grammar allows a MapConstructor to appear within an EnclosedExpr (that is, between curly brackets), this may be confusing to readers, and using the map keyword in such cases may improve clarity. In any event, if the EnclosedExpr appears in a context such as a StringTemplate, the two adjacent left opening braces must at least be separated by whitespace.

    Note:

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

    For instance, consider the expression {a:b}. Although it matches the EBNF for MapConstructor (with a matching MapKeyExpr and b matching MapValueExpr), the "longest possible match" rule requires that a:b be parsed as a QName, which results in a syntax error. Changing the expression to {a :b} or {a: b} will prevent this, resulting in the intended parse.

    Similarly, consider these three expressions:

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

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

    See A.3 Lexical structure.

    The value of the expression (whether or not the map keyword is present) is a map whose entries correspond to the key-value pairs obtained by evaluating the successive MapKeyExpr and MapValueExpr expressions.

    Each MapKeyExpr expression is evaluated and atomized; a type error [err:XPTY0004] occurs if the result is not a single atomic item. The associated value is the result of evaluating the corresponding MapValueExpr. If the MapValueExpr evaluates to a node, the associated value is the node itself, not a new node with the same values. [Definition: Two atomic items K1 and K2 have the same key value if fn:atomic-equal(K1, K2) returns true, as specified in Section 13.2.1 fn:atomic-equalFO ] If two or more entries have the same key value then a dynamic error is raised [err:XQDY0137]. The error may be raised statically if two or more entries can be determined statically to have the same key value.

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

    Example: Constructing a fixed map

    The following expression constructs a map with seven entries:

    {
    +{*:b:c}

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

    See A.3 Lexical structure.

    The value of the expression (whether or not the map keyword is present) is a map whose entries correspond to the key-value pairs obtained by evaluating the successive MapKeyExpr and MapValueExpr expressions.

    Each MapKeyExpr expression is evaluated and atomized; a type error [err:XPTY0004] occurs if the result is not a single atomic item. The associated value is the result of evaluating the corresponding MapValueExpr. If the MapValueExpr evaluates to a node, the associated value is the node itself, not a new node with the same values. [Definition: Two atomic items K1 and K2 have the same key value if fn:atomic-equal(K1, K2) returns true, as specified in Section 13.2.1 fn:atomic-equalFO ] If two or more entries have the same key value then a dynamic error is raised [err:XQDY0137]. The error may be raised statically if two or more entries can be determined statically to have the same key value.

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

    Example: Constructing a fixed map

    The following expression constructs a map with seven entries:

    {
       "Su" : "Sunday",
       "Mo" : "Monday",
       "Tu" : "Tuesday",
    @@ -617,7 +617,7 @@
       "Th" : "Thursday",
       "Fr" : "Friday",
       "Sa" : "Saturday"
    -}

     

    Example: Constructing nested maps

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

    +}

     

    Example: Constructing nested maps

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

     {
       "book": {
         "title": "Data on the Web",
    @@ -645,7 +645,7 @@
      { "key": 1, "value": ("a", "b") })
    $A?values::(3, 1)
    ([ "e", "f" ][ "a", "b" ])
    $A?keys::(3, 1)
    (3, 1)

    Similarly, given $M as a map { "X": ("a", "b"), "Y": ("c", "d"), "Z": ("e", "f") }, some example lookup expressions are as follows. Note that because maps are unordered, the results are not necessarily in the order shown.

    Example Lookup Expressions on a Map
    ExpressionResult
    $M?* (or $M?items::*)
    ("a", "b", "c", "d", "e", "f")
    $M?pairs::*
    ({ "key": "X", "value": ("a", "b") }, 
      { "key": "Y", "value": ("c", "d") }, 
      { "key": "Z", "value": ("e", "f") })
    $M?values::*
    ([ "a", "b" ], [ "c", "d" ], [ "e", "f" ])
    $M?keys::*
    ("X", "Y", "Z")
    $M?Y (or $M?items::Y)
    ("c", "d")
    $M?pairs::Y
    ({ "key": "Y", "value":("c", "d") })
    $M?values::Y
    ([ "c", "d" ])
    $M?keys::Y
    ("Y")
    $M?("Z", "X") (or $A?items::("Z", "X"))
    ("e", "f", "a", "b")
    $M?pairs::("Z", "X")
    ({ "key": "Z", "value": ("e", "f") }, 
    - { "key": "X", "value": ("a", "b") })
    $M?values::("Z", "X")
    ([ "e", "f" ][ "a", "b" ])
    $M?keys::("Z", "X")
    ("Z", "X")

    The semantics of a postfix lookup expression E?pairs::KS are defined as follows. The results with other modifiers can be derived from this result, as explained below.

    1. E is evaluated to produce a value $V.

    2. If $V is not a singleton (that is if count($V) ne 1), then the result (by recursive application of these rules) is the value of for $v in $V return $v?pairs::KS.

    3. If $V is a singleton array (that is, if $V instance of array(*)) then:

      1. If KS is a ParenthesizedExpr, then it is evaluated to produce a value $K and the result is:

        data($K) ! { "key": ., "value": array:get($V, .) }

        Note:

        The focus for evaluating the key specifier expression is the same as the focus for the Lookup expression itself.

      2. If the KeySpecifier is an IntegerLiteral with value $i, the result is the same as $V?pairs::($i).

      3. If the KeySpecifier is an NCNameor StringLiteral, the expression raises a type error [err:XPTY0004].

      4. If KS is a wildcard (*), the result is the same as $V?pairs::(1 to array:size($V)):

        Note:

        Note that array items are returned in order.

    4. If $V is a singleton map (that is, if $V instance of map(*)) then:

      1. If KS is a ParenthesizedExpr, then it is evaluated to produce a value $K and the result is:

        data($K) ! { "key": ., "value": map:get($V, .) }

        Note:

        The focus for evaluating the key specifier expression is the same as the focus for the Lookup expression itself.

      2. If KS is an NCName or a StringLiteral, with value $S, the result is the same as $V?pairs::($S)

      3. If KS is an IntegerLiteral with value $N, the result is the same as $V?pairs::($N).

      4. If KS is a wildcard (*), the result is the same as $V?pairs::(map:keys($V)).

        Note:

        The order of entries in the result sequence in thisreflects the entry ordercaseDM is implementation-dependentof the map.

    5. Otherwise (that is, if $V is neither a map nor an array) a type error is raised [err:XPTY0004].

    If the modifier is items (explicitly or by default), the result of $V?items::KS is the same as the result of $V?pairs::KS ! map:get(., "value"); that is, it is the sequence concatenation of the value parts.

    If the modifier is values, the result of $V?values::KS is the same as the result of $V?pairs::KS ! array { map:get(., "value") }.

    If the modifier is keys, the result of $V?keys::KS is the same as the result of $V?pairs::KS ! map:get(., "key").

    Examples:

    • { "first" : "Jenna", "last" : "Scott" }?first evaluates to "Jenna"

    • { "first name" : "Jenna", "last name" : "Scott" }?"first name" evaluates to "Jenna"

    • [ 4, 5, 6 ]?2 evaluates to 5.

    • ({ "first": "Tom" }, { "first": "Dick" }, { "first": "Harry" })?first evaluates to the sequence ("Tom", "Dick", "Harry").

    • ([ 1, 2, 3 ], [ 4, 5, 6 ])?2 evaluates to the sequence (2, 5).

    • ([ 1, [ "a", "b" ], [ 4, 5, [ "c", "d"] ])?value::*[. instance of array(xs:string)] evaluates to the sequence ([ "a", "b" ], [ "c", "d" ]).

    • [ "a", "b" ]?3 raises a dynamic error [err:FOAY0001]FO40

    4.14.3.2 Unary Lookup
    [226]   UnaryLookup   ::=   ("?" | "??") (Modifier "::")? KeySpecifier
    ("?" | "??") (Modifier "::")? KeySpecifier
    [165]   Modifier   ::=   "pairs" | "keys" | "values" | "items"
    "pairs" | "keys" | "values" | "items"
    [166]   KeySpecifier   ::=   NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard
    NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard
    [167]   LookupWildcard   ::=   "*"
    "*"

    Unary lookup is most commonly used in predicates (for example, $map[?name = 'Mike']) or with the simple map operator (for example, avg($maps ! (?price - ?discount))).

    The unary lookup expression ?modifier::KS is defined to be equivalent to the postfix lookup expression .?modifier::KS which has the context value (.) as the implicit first operand. See 4.14.3.1 Postfix Lookup Expressions for the postfix lookup operator.

    Examples:

    • ?name is equivalent to .("name"), an appropriate lookup for a map.

    • ?2 is equivalent to .(2), an appropriate lookup for an array or an integer-valued map.

    • If the context item is the result of parsing the JSON input:

      {
      + { "key": "X", "value": ("a", "b") })
      $M?values::("Z", "X")
      ([ "e", "f" ][ "a", "b" ])
      $M?keys::("Z", "X")
      ("Z", "X")

      The semantics of a postfix lookup expression E?pairs::KS are defined as follows. The results with other modifiers can be derived from this result, as explained below.

      1. E is evaluated to produce a value $V.

      2. If $V is not a singleton (that is if count($V) ne 1), then the result (by recursive application of these rules) is the value of for $v in $V return $v?pairs::KS.

      3. If $V is a singleton array (that is, if $V instance of array(*)) then:

        1. If KS is a ParenthesizedExpr, then it is evaluated to produce a value $K and the result is:

          data($K) ! { "key": ., "value": array:get($V, .) }

          Note:

          The focus for evaluating the key specifier expression is the same as the focus for the Lookup expression itself.

        2. If the KeySpecifier is an IntegerLiteral with value $i, the result is the same as $V?pairs::($i).

        3. If the KeySpecifier is an NCNameor StringLiteral, the expression raises a type error [err:XPTY0004].

        4. If KS is a wildcard (*), the result is the same as $V?pairs::(1 to array:size($V)):

          Note:

          Note that array items are returned in order.

      4. If $V is a singleton map (that is, if $V instance of map(*)) then:

        1. If KS is a ParenthesizedExpr, then it is evaluated to produce a value $K and the result is:

          data($K) ! { "key": ., "value": map:get($V, .) }

          Note:

          The focus for evaluating the key specifier expression is the same as the focus for the Lookup expression itself.

        2. If KS is an NCName or a StringLiteral, with value $S, the result is the same as $V?pairs::($S)

        3. If KS is an IntegerLiteral with value $N, the result is the same as $V?pairs::($N).

        4. If KS is a wildcard (*), the result is the same as $V?pairs::(map:keys($V)).

          Note:

          The order of entries in the result sequence in thisreflects the entry ordercaseDM is implementation-dependentof the map.

      5. Otherwise (that is, if $V is neither a map nor an array) a type error is raised [err:XPTY0004].

      If the modifier is items (explicitly or by default), the result of $V?items::KS is the same as the result of $V?pairs::KS ! map:get(., "value"); that is, it is the sequence concatenation of the value parts.

      If the modifier is values, the result of $V?values::KS is the same as the result of $V?pairs::KS ! array { map:get(., "value") }.

      If the modifier is keys, the result of $V?keys::KS is the same as the result of $V?pairs::KS ! map:get(., "key").

      Examples:

      • { "first" : "Jenna", "last" : "Scott" }?first evaluates to "Jenna"

      • { "first name" : "Jenna", "last name" : "Scott" }?"first name" evaluates to "Jenna"

      • [ 4, 5, 6 ]?2 evaluates to 5.

      • ({ "first": "Tom" }, { "first": "Dick" }, { "first": "Harry" })?first evaluates to the sequence ("Tom", "Dick", "Harry").

      • ([ 1, 2, 3 ], [ 4, 5, 6 ])?2 evaluates to the sequence (2, 5).

      • ([ 1, [ "a", "b" ], [ 4, 5, [ "c", "d"] ])?value::*[. instance of array(xs:string)] evaluates to the sequence ([ "a", "b" ], [ "c", "d" ]).

      • [ "a", "b" ]?3 raises a dynamic error [err:FOAY0001]FO40

    4.14.3.2 Unary Lookup
    [226]   UnaryLookup   ::=   ("?" | "??") (Modifier "::")? KeySpecifier
    ("?" | "??") (Modifier "::")? KeySpecifier
    [165]   Modifier   ::=   "pairs" | "keys" | "values" | "items"
    "pairs" | "keys" | "values" | "items"
    [166]   KeySpecifier   ::=   NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard
    NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard
    [167]   LookupWildcard   ::=   "*"
    "*"

    Unary lookup is most commonly used in predicates (for example, $map[?name = 'Mike']) or with the simple map operator (for example, avg($maps ! (?price - ?discount))).

    The unary lookup expression ?modifier::KS is defined to be equivalent to the postfix lookup expression .?modifier::KS which has the context value (.) as the implicit first operand. See 4.14.3.1 Postfix Lookup Expressions for the postfix lookup operator.

    Examples:

    • ?name is equivalent to .("name"), an appropriate lookup for a map.

    • ?2 is equivalent to .(2), an appropriate lookup for an array or an integer-valued map.

    • If the context item is the result of parsing the JSON input:

      {
         "name": "John Smith",
         "address": { "street": "18 Acacia Avenue", "postcode": "MK12 2EX" },
         "previous-address": { "street": "12 Seaview Road", "postcode": "EX8 9AA" }
      @@ -696,7 +696,7 @@
           ]
         }
       }

      Given two variables $from and $to containing the names of two cities that are present in this table, the distance between the two cities can be obtained with the expression:

      $tree ?? $from ?? *[. instance of record(to, distance)][?to = $to] ? distance

      The names of all pairs of cities whose distance is represented in the data can be obtained with the expression:

      $tree ?? $cities
      -=> map:for-each(fn($key, $val) { $val ?? to ! ($key || "-" || .) })

     

    Example: Comparison with JSONPath

    This example provides XPath equivalents to some examples given in the JSONPath specification. [TODO: add a reference].

    The examples query the result of parsing the following JSON value, representing a store whose stock consists of four books and a bicycle:

    {
    +=> map:for-each(fn($key, $val) { $val ?? to ! ($key || "-" || .) })

     

    Example: Comparison with JSONPath

    This example provides XPath equivalents to some examples given in the JSONPath specification. [TODO: add a reference].

    The examples query the result of parsing the following JSON value, representing a store whose stock consists of four books and a bicycle:

    {
       "store": {
         "book": [
           {
    @@ -732,8 +732,8 @@
         }
       }
     }

    The following table illustrates some queries on this data, expressed both in JSONPath and in XQuery 4.0 and XPath 4.0.

    JSONPath vs XQuery 4.0 and XPath 4.0 Comparison
    QueryJSONPathXQuery 4.0 and XPath 4.0
    The authors of all books in the store$.store.book[*].author$m?store?book??author
    All authors$..author$m??author
    All things in store (four books and a red bicycle)$.store.* $m?store?*
    The prices of everything in the store$.store..price$m?store??price
    The third book$..book[2] $m??book?3
    The third book's author$..book[2].author$m??book?3?author
    The third book's publisher (empty result)$..book[2].publisher$m??book?3?publisher
    The last book (in order)$..book[-1]$m??book => array:foot()
    The first two books$..book[0,1]$m??book?(1, 2)
    All books with an ISBN$..book[?@.isbn]$m??book[?isbn]
    All books cheaper than 10$..book[?@.price<10]$m??book[?price lt 10]
    All member values and array elements contained in the input value$..*$m??*
    4.14.3.4 Implausible Lookup Expressions

    Under certain conditions a lookup expression that will never select anything is classified as implausible. During the static analysis phase, a processor may (subject to the rules in 2.4.6 Implausible Expressions) report a static error when such lookup expressions are encountered: [err:XPTY0145].

    More specifically, a shallow unary or postfix lookup is classified as implausible if any of the following conditions applies:

    1. The inferred type of the left-hand operand (or the context value, in the case of a unary expression) is a record type (see 3.2.8.3 Record Types), and the KeySpecifier is an IntegerLiteral.

    2. The inferred type of the left-hand operand (or the context value, in the case of a unary expression) is a record type (see 3.2.8.3 Record Types), and the KeySpecifier is an NCName or StringLiteral that cannot validly appear as a field name in the record.

    3. 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 KeySpecifier, after coercion, is a type that is disjoint with the key type of the map.

    4. 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 KeySpecifier is the IntegerLiteral0 (zero).

    Note:

    Other errors, such as using an NCNameKeySpecifier for an array lookup, are handled under the general provisions for type errors.

    Examples of implausible lookup expressions include the following:

    • parse-uri($uri)?3: the declared result type of parse-uri is a record test, so the selector 3 will never select anything.

    • in-scope-namespaces($node)(current-date()): the result type of in-scope-namespaces is a map with xs:string keys, so the selector current-date() will never select anything.

    • array:subarray($a, 2, 5)?0: the integer zero cannot select any member of an array, because numbering starts at 1.

    4.14.4 Filter Expressions for Maps and Arrays

    Changes in 4.0  

    1. Filter expressions for maps and arrays are introduced.   [Issue 1159 PR 1163 20 April 2024]

    2. Predicates in filter expressions for maps and arrays can now be numeric.   [Issue 1207 PR tba 15 May 2024]

    [163]   FilterExprAM   ::=   PostfixExpr "?[" Expr "]"
    PostfixExpr "?[" Expr "]"

    Maps and arrays can be filtered using the construct INPUT?[FILTER]. For example, $array?[count(.)=1] filters an array to retain only those members that are single items.

    Note:

    The character-pair ?[ forms a single token; no intervening whitespace or comment is allowed.

    The required type of the left-hand operand INPUT is (map(*)|array(*))?: that is, it must be either an empty sequence, a single map, or a single array [err:XPTY0004]. If it is an empty sequence, the result of the expression is an empty sequence.

    If the value of INPUT is an array, then the FILTER expression is evaluated for each member of the array, with that member as the context value, with its position in the array as the context position, and with the size of the array as the context size. The result of the expression is an array containing those members of the input array for which the predicate truth value of the FILTER expression is true. The order of retained members is preserved.

    For example, the following expression:

    let $array := [ (), 1, (2, 3), (4, 5, 6) ]
    -return $array?[count(.) ge 2]

    returns:

    [ (2, 3), (4, 5, 6) ]

    Note:

    Numeric predicates are handled in the same way as with filter expressions for sequences. However, the result is always an array, even if only one member is selected. For example, given the $array shown above, the result of $array?[3] is the singleton array [ (2, 3) ]. Contrast this with $array?3 which delivers the sequence 2, 3.

    If the value of INPUT is a map, then the FILTER expression is evaluated for each entry in the map, with the context value set to an item of type record(key as xs:anyAtomicType, value as item()*), in which the key and value fields represent the key and value of the map entry. The context position is the position of the entry in the map (in an arbitrary ordering), and the context size is the number of entries in the map. The result of the expression is a map containing those entries of the input map for which the predicate truth value of the FILTER expression is true. The ordered property of the result is the same as the ordered property of the input map, and in the case of an ordered map, the relative order of entries in the result retains the relative order of entries in the input.

    For example, the following expression:

    let map := { 1: "alpha", 2: "beta", 3: "gamma" }
    -return $map?[?key ge 2]

    returns:

    { 2: "beta", 3: "gamma" }

    Note:

    Filtering of maps based on numeric positions is not generally useful when the map is unordered, because the order of entries in a map is unpredictable; but it is available in the interests of orthogonality.

    With an ordered map, a filter expression such as $map?[last()-1, last()] might be used to return the last two entries.

    4.14.5 Pinned Maps and Arrays

    Unlike navigation within node trees derived from XML, navigation within a tree of maps and arrays derived from JSON is normally “downwards only”: there is no equivalent of the parent or ancestor axis. This means, for example, that having selected leav nodes in the tree with an expression such as ??name, there is no way of navigating from the items in the result to any related items. Pinned maps and arrays provide a solution to this problem; if a map or array is pinned (by calling the fn:pin function), then values found by navigating within the map or array are labeled, which provides supplementary information about their location within the containing tree structure.

    For further information about pinned and labeled values see Section 2.10 Labeled ItemsDM.

    More specifically, if a map $M or an array $A is pinned, then any value returned by map:get($M, $key) or array:get($A, $index) will be a sequence of labeled items. The label can be obtained by calling the function fn:label, and the result will be a map having the following properties:

    • pinned: set to true. This means that any further selections from this value (if it is itself a map or array) will also deliver labeled items.

    • parent: the containing map ($M) or array ($A).

    • key: the key ($key) or index ($index) that was used to select the item.

    • position: in the general case the value returned by map:get or array:get is a sequence, and each item in the sequence is labeled with its 1-based position in that sequence.

    • ancestors: a zero-arity function that delivers the item's parent (its containing map or array), that item's parent, and so on, recursively, up to the map or array that was the root of the selection. The sequence is in upwards navigation order (the immediate parent comes first).

    • path: a zero-arity function that delivers the sequence of keys (in the case of maps) or integer indexes (in the case of arrays) by which the item was reached. The sequence is in downwards navigation order (the immediate key or index of the item comes last).

    The formal model for the fn:pin is that it returns a deep copy of the supplied map or array in which all items in the recursive content have been labeled. This is a useful model because it avoids the need to specify the effect of each individual function and operator on the structure. For example, the rule has the consequence that the result of pin([ 11, 12, 13, 14 ]) => array:remove(3) => array:for-each(fn { label(.)?key }) is [ 1, 2, 4 ]. In a practical implementation, however, it is likely that labels will be attached to items lazily, at the time they are retrieved. Such an implementation will need to recognize pinned maps and arrays and treat them specially when operations such as array:get, array:remove, array:for-each, array:subarray, and their map counterparts, are evaluated.

    Because maps and arrays selected from a pinned map or array are themselves pinned, deep lookup operations (whether conducted using the deep lookup operator ??, or the map:find function, or by user-written recursive code) will deliver a labeled value whose parent or ancestor properties can be used to navigate back up through the tree.

    For example, given the example map shown in 4.14.1.1 Map Constructors, the expression $map??last[. = "Suciu"] selects the map entry with key "last" and value "Suciu", but by itself gives no information about where this entry was found. By first pinning the map, this extra information can be made available through the label on the result. For example you can select all co-authors of "Suciu" by writing:

    pin($map)??last[. = "Suciu"] => label()?ancestors()?author??last

    Note:

    When an entry in a map, or a member of an array, has the empty sequence as its value, the value contains no items and is therefore unchanged in the pinned version of the containing structure. In addition, the lookup operators ? and ?? flatten their result to a single sequence, so any empty values are effectively discarded from the result. For this reason, pinned arrays and maps work best when all values in arrays and maps are singleton items. An option is therefore provided on the fn:parse-json and fn:json-doc functions to change the representation of JSON null values (whose default is an empty sequence, ()) to a user-supplied value.

    Editorial note 
    That note is anticipating a proposal in a separate PR.

    4.15 Ordered and Unordered Expressions

    Changes in 4.0  

    1. The ordered { E } and unordered { E } expressions are retained for backwards compatibility reasons, but in XQuery 4.0 they are deprecated and have no useful effect.   [Issue 1339 ]

    [176]   OrderedExpr   ::=   "ordered" EnclosedExpr
    "ordered" EnclosedExpr
    [177]   UnorderedExpr   ::=   "unordered" EnclosedExpr
    "unordered" EnclosedExpr
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    This syntax is retained from earlier versions of XQuery; in XQuery 4.0 it is deprecated and has no effect.

    The constructs ordered { E } and unordered { E } both return the result of evaluating the expression E.

    Note:

    In addition to ordered and unordered expressions, XQuery provides a function named fn:unordered that operates on any sequence of items and returns the same sequence in an implementation-defined order. A call to the fn:unordered function may be thought of as giving permission for the argument expression to be materialized in whatever order the system finds most efficient. The fn:unordered function relaxes ordering only for the sequence that is its immediate operand, whereas the unordered expression in earlier XQuery versions sets the ordering mode for its operand expression and all nested expressions.

    4.16 Conditional Expressions

    Changes in 4.0  

    1. Alternative syntax for conditional expressions is available: if (condition) { X } else { Y }, with the else part being optional.   [Issue 234 PR 284 23 January 2023]

    XQuery 4.0 and XPath 4.0 allows conditional expressions to be written in several different ways.

    [98]   IfExpr   ::=   "if" "(" Expr ")" (UnbracedActions | BracedActions)
    "if" "(" Expr ")" (UnbracedActions | BracedActions)
    [99]   UnbracedActions   ::=   "then" ExprSingle "else" ExprSingle
    "then" ExprSingle "else" ExprSingle
    [100]   BracedActions   ::=   ThenActionElseIfAction* ElseAction?
    ThenActionElseIfAction* ElseAction?
    [101]   ThenAction   ::=   EnclosedExpr
    EnclosedExpr
    [102]   ElseIfAction   ::=   "else" "if" "(" Expr ")" EnclosedExpr
    "else" "if" "(" Expr ")" EnclosedExpr
    [103]   ElseAction   ::=   "else" EnclosedExpr
    "else" EnclosedExpr
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    There are two formats with essentially the same semantics.

    Conditional expressions have a special rule for propagating dynamic errors: expressions whose value is not needed for computing the result are guarded, as described in 2.4.5 Guarded Expressions, to prevent spurious dynamic errors.

    Here are some examples of conditional expressions:

    • In this example, the test expression is a comparison expression:

      if ($widget1/unit-cost < $widget2/unit-cost)
      +return $array?[count(.) ge 2]

      returns:

      [ (2, 3), (4, 5, 6) ]

      Note:

      Numeric predicates are handled in the same way as with filter expressions for sequences. However, the result is always an array, even if only one member is selected. For example, given the $array shown above, the result of $array?[3] is the singleton array [ (2, 3) ]. Contrast this with $array?3 which delivers the sequence 2, 3.

      If the value of INPUT is a map, then the FILTER expression is evaluated for each entry in the map, with the context value set to an item of type record(key as xs:anyAtomicType, value as item()*), in which the key and value fields represent the key and value of the map entry. The context position is the position of the entry in the map (in entry orderan DMarbitrary ordering), and the context size is the number of entries in the map. The result of the expression is a map containing those entries of the input map for which the predicate truth value of the FILTER expression is true. The relative order of entries in the result retains the relative order of entries in the input.

      For example, the following expression:

      let map := { 1: "alpha", 2: "beta", 3: "gamma" }
      +return $map?[?key ge 2]

      returns:

      { 2: "beta", 3: "gamma" }

      Note:

      Filtering of maps based on numeric positions is not generally useful, because the order of entries in a map is unpredictable; but it is available in the interests of orthogonality.

      A filter expression such as $map?[last()-1, last()] might be used to return the last two entries of a map in entry orderDM.

      4.14.5 Pinned Maps and Arrays

      Unlike navigation within node trees derived from XML, navigation within a tree of maps and arrays derived from JSON is normally “downwards only”: there is no equivalent of the parent or ancestor axis. This means, for example, that having selected leav nodes in the tree with an expression such as ??name, there is no way of navigating from the items in the result to any related items. Pinned maps and arrays provide a solution to this problem; if a map or array is pinned (by calling the fn:pin function), then values found by navigating within the map or array are labeled, which provides supplementary information about their location within the containing tree structure.

      For further information about pinned and labeled values see Section 2.10 Labeled ItemsDM.

      More specifically, if a map $M or an array $A is pinned, then any value returned by map:get($M, $key) or array:get($A, $index) will be a sequence of labeled items. The label can be obtained by calling the function fn:label, and the result will be a map having the following properties:

      • pinned: set to true. This means that any further selections from this value (if it is itself a map or array) will also deliver labeled items.

      • parent: the containing map ($M) or array ($A).

      • key: the key ($key) or index ($index) that was used to select the item.

      • position: in the general case the value returned by map:get or array:get is a sequence, and each item in the sequence is labeled with its 1-based position in that sequence.

      • ancestors: a zero-arity function that delivers the item's parent (its containing map or array), that item's parent, and so on, recursively, up to the map or array that was the root of the selection. The sequence is in upwards navigation order (the immediate parent comes first).

      • path: a zero-arity function that delivers the sequence of keys (in the case of maps) or integer indexes (in the case of arrays) by which the item was reached. The sequence is in downwards navigation order (the immediate key or index of the item comes last).

      The formal model for the fn:pin is that it returns a deep copy of the supplied map or array in which all items in the recursive content have been labeled. This is a useful model because it avoids the need to specify the effect of each individual function and operator on the structure. For example, the rule has the consequence that the result of pin([ 11, 12, 13, 14 ]) => array:remove(3) => array:for-each(fn { label(.)?key }) is [ 1, 2, 4 ]. In a practical implementation, however, it is likely that labels will be attached to items lazily, at the time they are retrieved. Such an implementation will need to recognize pinned maps and arrays and treat them specially when operations such as array:get, array:remove, array:for-each, array:subarray, and their map counterparts, are evaluated.

      Because maps and arrays selected from a pinned map or array are themselves pinned, deep lookup operations (whether conducted using the deep lookup operator ??, or the map:find function, or by user-written recursive code) will deliver a labeled value whose parent or ancestor properties can be used to navigate back up through the tree.

      For example, given the example map shown in 4.14.1.1 Map Constructors, the expression $map??last[. = "Suciu"] selects the map entry with key "last" and value "Suciu", but by itself gives no information about where this entry was found. By first pinning the map, this extra information can be made available through the label on the result. For example you can select all co-authors of "Suciu" by writing:

      pin($map)??last[. = "Suciu"] => label()?ancestors()?author??last

      Note:

      When an entry in a map, or a member of an array, has the empty sequence as its value, the value contains no items and is therefore unchanged in the pinned version of the containing structure. In addition, the lookup operators ? and ?? flatten their result to a single sequence, so any empty values are effectively discarded from the result. For this reason, pinned arrays and maps work best when all values in arrays and maps are singleton items. An option is therefore provided on the fn:parse-json and fn:json-doc functions to change the representation of JSON null values (whose default is an empty sequence, ()) to a user-supplied value.

      Editorial note 
      That note is anticipating a proposal in a separate PR.

    4.15 Ordered and Unordered Expressions

    Changes in 4.0  

    1. The ordered { E } and unordered { E } expressions are retained for backwards compatibility reasons, but in XQuery 4.0 they are deprecated and have no useful effect.   [Issue 1339 ]

    [176]   OrderedExpr   ::=   "ordered" EnclosedExpr
    "ordered" EnclosedExpr
    [177]   UnorderedExpr   ::=   "unordered" EnclosedExpr
    "unordered" EnclosedExpr
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    This syntax is retained from earlier versions of XQuery; in XQuery 4.0 it is deprecated and has no effect.

    The constructs ordered { E } and unordered { E } both return the result of evaluating the expression E.

    Note:

    In addition to ordered and unordered expressions, XQuery provides a function named fn:unordered that operates on any sequence of items and returns the same sequence in an implementation-defined order. A call to the fn:unordered function may be thought of as giving permission for the argument expression to be materialized in whatever order the system finds most efficient. The fn:unordered function relaxes ordering only for the sequence that is its immediate operand, whereas the unordered expression in earlier XQuery versions sets the ordering mode for its operand expression and all nested expressions.

    4.16 Conditional Expressions

    Changes in 4.0  

    1. Alternative syntax for conditional expressions is available: if (condition) { X } else { Y }, with the else part being optional.   [Issue 234 PR 284 23 January 2023]

    XQuery 4.0 and XPath 4.0 allows conditional expressions to be written in several different ways.

    [98]   IfExpr   ::=   "if" "(" Expr ")" (UnbracedActions | BracedActions)
    "if" "(" Expr ")" (UnbracedActions | BracedActions)
    [99]   UnbracedActions   ::=   "then" ExprSingle "else" ExprSingle
    "then" ExprSingle "else" ExprSingle
    [100]   BracedActions   ::=   ThenActionElseIfAction* ElseAction?
    ThenActionElseIfAction* ElseAction?
    [101]   ThenAction   ::=   EnclosedExpr
    EnclosedExpr
    [102]   ElseIfAction   ::=   "else" "if" "(" Expr ")" EnclosedExpr
    "else" "if" "(" Expr ")" EnclosedExpr
    [103]   ElseAction   ::=   "else" EnclosedExpr
    "else" EnclosedExpr
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    There are two formats with essentially the same semantics.

    Conditional expressions have a special rule for propagating dynamic errors: expressions whose value is not needed for computing the result are guarded, as described in 2.4.5 Guarded Expressions, to prevent spurious dynamic errors.

    Here are some examples of conditional expressions:

    • In this example, the test expression is a comparison expression:

      if ($widget1/unit-cost < $widget2/unit-cost)
       then $widget1
       else $widget2
    • In this example, the test expression tests for the existence of an attribute named discounted, independently of its value:

      if ($part/@discounted)
       then $part/wholesale
      @@ -763,9 +763,9 @@
         case ($a ge $b) return "greater"
         case ($a eq $b) return "equal"
         default return "not comparable"
      -}

      Note:

      The comparisons are performed using the fn:deep-equal function, after atomization. This means that a case expression such as @married tests fn:data(@married) rather than fn:boolean(@married). If the effective boolean value of the expression is wanted, this can be achieved with an explicit call of fn:boolean.

    4.19 Quantified Expressions

    Changes in 4.0  

    1. 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.   [Issue 1316 PR 1384 13 August 2024]

    Quantified expressions support existential and universal quantification. The value of a quantified expression is always true or false.

    [85]   QuantifiedExpr   ::=   ("some" | "every") QuantifierBinding ("," QuantifierBinding)* "satisfies" ExprSingle
    ("some" | "every") QuantifierBinding ("," QuantifierBinding)* "satisfies" ExprSingle
    [86]   QuantifierBinding   ::=   VarNameAndType "in" ExprSingle
    VarNameAndType "in" ExprSingle
    [227]   TypeDeclaration   ::=   "as" SequenceType
    "as" SequenceType

    A quantified expression begins with a quantifier, which is the keyword some or every, followed by one or more in-clauses that are used to bind variables, followed by the keyword satisfies 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:

    1. If the QuantifiedExpr contains more than one QuantifierBinding, then it is equivalent to the expression obtained by replacing each comma with satisfies some or satisfies every respectively. For example, the expression some $x in X, $y in Y satisfies $x = $y is equivalent to some $x in X satisfies some $y in Y satisfies $x = $y, while the expression every $x in X, $y in Y satisfies $x lt $y is equivalent to every $x in X satisfies every $y in Y satisfies $x lt $y

    2. If the quantifier is some, the QuantifiedExpr returns true if at least one evaluation of the test expression has the effective boolean valuetrue; otherwise it returns false. In consequence, if the binding sequence is empty, the result of the QuantifiedExpr is false.

    3. If the quantifier is every, the QuantifiedExpr returns true if every evaluation of the test expression has the effective boolean valuetrue; otherwise it returns false. In consequence, if the binding sequence is empty, the result of the QuantifiedExpr is true.

    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.

    Each variable binding may be accompanied by a type declaration, which consists of the keyword as followed by the static type of the variable, declared using the syntax in 3.1 Sequence Types. The 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 coercion rules. If conversion is not possible, a type error is raised [err:XPTY0004].

    The order in which test expressions are evaluated for the various items in the binding sequence is implementation-dependent. If the quantifier is some, an implementation may return true as soon as it finds one item for which the test expression has an effective boolean value of true, and it may raise a dynamic error as soon as it finds one item for which the test expression raises an error. Similarly, if the quantifier is every, an implementation may return false as soon as it finds one item for which the test expression has an effective boolean value of false, and it may raise a dynamic error 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.

    Here are some examples of quantified expressions:

    • This expression is true if every part element has a discounted attribute (regardless of the values of these attributes):

      every $part in /parts/part satisfies $part/@discounted
    • This expression is true if at least one employee element satisfies the given comparison expression:

      some $emp in /emps/employee satisfies
      +}

      Note:

      The comparisons are performed using the fn:deep-equal function, after atomization. This means that a case expression such as @married tests fn:data(@married) rather than fn:boolean(@married). If the effective boolean value of the expression is wanted, this can be achieved with an explicit call of fn:boolean.

    4.19 Quantified Expressions

    Changes in 4.0  

    1. 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.   [Issue 1316 PR 1384 13 August 2024]

    Quantified expressions support existential and universal quantification. The value of a quantified expression is always true or false.

    [85]   QuantifiedExpr   ::=   ("some" | "every") QuantifierBinding ("," QuantifierBinding)* "satisfies" ExprSingle
    ("some" | "every") QuantifierBinding ("," QuantifierBinding)* "satisfies" ExprSingle
    [86]   QuantifierBinding   ::=   VarNameAndType "in" ExprSingle
    VarNameAndType "in" ExprSingle
    [227]   TypeDeclaration   ::=   "as" SequenceType
    "as" SequenceType

    A quantified expression begins with a quantifier, which is the keyword some or every, followed by one or more in-clauses that are used to bind variables, followed by the keyword satisfies 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:

    1. If the QuantifiedExpr contains more than one QuantifierBinding, then it is equivalent to the expression obtained by replacing each comma with satisfies some or satisfies every respectively. For example, the expression some $x in X, $y in Y satisfies $x = $y is equivalent to some $x in X satisfies some $y in Y satisfies $x = $y, while the expression every $x in X, $y in Y satisfies $x lt $y is equivalent to every $x in X satisfies every $y in Y satisfies $x lt $y

    2. If the quantifier is some, the QuantifiedExpr returns true if at least one evaluation of the test expression has the effective boolean valuetrue; otherwise it returns false. In consequence, if the binding sequence is empty, the result of the QuantifiedExpr is false.

    3. If the quantifier is every, the QuantifiedExpr returns true if every evaluation of the test expression has the effective boolean valuetrue; otherwise it returns false. In consequence, if the binding sequence is empty, the result of the QuantifiedExpr is true.

    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.

    Each variable binding may be accompanied by a type declaration, which consists of the keyword as followed by the static type of the variable, declared using the syntax in 3.1 Sequence Types. The 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 coercion rules. If conversion is not possible, a type error is raised [err:XPTY0004].

    The order in which test expressions are evaluated for the various items in the binding sequence is implementation-dependent. If the quantifier is some, an implementation may return true as soon as it finds one item for which the test expression has an effective boolean value of true, and it may raise a dynamic error as soon as it finds one item for which the test expression raises an error. Similarly, if the quantifier is every, an implementation may return false as soon as it finds one item for which the test expression has an effective boolean value of false, and it may raise a dynamic error 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.

    Here are some examples of quantified expressions:

    • This expression is true if every part element has a discounted attribute (regardless of the values of these attributes):

      every $part in /parts/part satisfies $part/@discounted
    • This expression is true if at least one employee element satisfies the given comparison expression:

      some $emp in /emps/employee satisfies
         $emp/bonus > 0.25 * $emp/salary
    • This expression is true if every employee element has at least one salary child with the attribute current="true":

      every $emp in /emps/employee satisfies
      -  some $sal in $emp/salary satisfies $sal/@current = 'true'

      Note:

      Like many quantified expressions, this can be simplified. This example can be written every $emp in /emps/employee satisfies $emp/salary[@current = 'true'], or even more concisely as empty(/emps/employee[not(salary/@current = 'true')].

      Another alternative in XQuery 4.0 and XPath 4.0 is to use the higher-order functions fn:some and fn:every. This example can be written fn:every(/emps/employee, fn { salary/@current = 'true' })

    • In the following examples, each quantified expression evaluates its test expression over nine pairs of items, formed from the Cartesian product of the sequences (1, 2, 3) and (2, 3, 4). The expression beginning with some evaluates to true, and the expression beginning with every evaluates to false.

      some $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4
      every $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4
    • This quantified expression may either return true or raise a type error, since its test expression returns true for one item and raises a type error for another:

      some $x in (1, 2, "cat") satisfies $x * 2 = 4
    • This quantified expression may either return false or raise a type error, since its test expression returns false for one item and raises a type error for another:

      every $x in (1, 2, "cat") satisfies $x * 2 = 4
    • This quantified expression returns true, because the binding sequence is empty, despite the fact that the condition can never be satisfied:

      every $x in () satisfies ($x lt 0 and $x gt 0)
    • This quantified expression is implausible because it will always fail with a type error except in the case where $input is an empty sequence. If $input contains one or more xs:date values, a processor must raise a type error on the grounds that an xs:date cannot be compared to an xs:integer. If $input is empty, the processor may (or may not) report this error:

      every $x as xs:date in $input satisfies ($x lt 0)
    • This quantified expression contains a type declaration that is not satisfied by every item in the test expression. The expression may either return true or raise a type error.

      some $x as xs:integer in (1, 2, "cat") satisfies $x * 2 = 4

    4.20 Try/Catch Expressions

    Changes in 4.0  

    1. $err:map contains entries for all values that are bound to the single variables.   [Issue 32  23 May 2023]

    2. A new variable err:map is available, capturing all error information in one place.   [Issue 32 PR 493 16 May 2023]

    3. $err:stack-trace provides information about the current state of execution.   [Issue 689  1 October 2024]

    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 fn:error() function.

    [104]   TryCatchExpr   ::=   TryClauseCatchClause+
    TryClauseCatchClause+
    [105]   TryClause   ::=   "try" EnclosedExpr
    "try" EnclosedExpr
    [106]   CatchClause   ::=   "catch" NameTestUnionEnclosedExpr
    "catch" NameTestUnionEnclosedExpr
    [107]   NameTestUnion   ::=   (NameTest ++ "|")
    (NameTest ++ "|")
    [151]   NameTest   ::=   EQName | Wildcard
    EQName | Wildcard
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    A try/catch expression catches dynamic errors and type errors raised by the evaluation of the target expression of the try clause. If the the content expression 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.

    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 catch 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 catch clause with one or more NameTests matches any error whose error code matches one of these NameTests. For instance, if the error code is err:FOER0000, then it matches a catch clause whose ErrorList is err:FOER0000 | err:FOER0001. Wildcards may be used in NameTests; thus, the error code err:FOER0000 also matches a catch clause whose ErrorList is err:* or *:FOER0000 or *.

    Within the scope of the catch 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:

    VariableTypeValue
    $err:codexs:QNameThe error code
    $err:descriptionxs:string?A description of the error condition; an empty sequence if no description is available (for example, if the error function was called with one argument).
    $err:valueitem()*Value associated with the error. For an error raised by calling the error function, this is the value of the third argument (if supplied).
    $err:modulexs:string?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.
    $err:line-numberxs:integer?The line number within the module where the error occurred, or an empty sequence if the information is not available. The value may be approximate.
    $err:column-numberxs:integer?The column number within the module where the error occurred, or an empty sequence if the information is not available. The value may be approximate.
    $err:stack-tracexs:string?Implementation-dependent 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.
    $err:additionalitem()*Implementation-defined. 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.
    $err:mapmap(*)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.

    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.

    Static errors are not caught by the try/catch expression.

    If a function call occurs within a try clause, errors raised by evaluating the corresponding function are caught by the try/catch expression. If a variable reference is used in a try clause, errors raised by binding a value to the variable are not caught unless the binding expression occurs within the try clause.

    Note:

    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.

    Here are some examples of try/catch expressions.

    • A try/catch expression without name tests catches any error:

      try {
      +  some $sal in $emp/salary satisfies $sal/@current = 'true'

      Note:

      Like many quantified expressions, this can be simplified. This example can be written every $emp in /emps/employee satisfies $emp/salary[@current = 'true'], or even more concisely as empty(/emps/employee[not(salary/@current = 'true')].

      Another alternative in XQuery 4.0 and XPath 4.0 is to use the higher-order functions fn:some and fn:every. This example can be written fn:every(/emps/employee, fn { salary/@current = 'true' })

    • In the following examples, each quantified expression evaluates its test expression over nine pairs of items, formed from the Cartesian product of the sequences (1, 2, 3) and (2, 3, 4). The expression beginning with some evaluates to true, and the expression beginning with every evaluates to false.

      some $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4
      every $x in (1, 2, 3), $y in (2, 3, 4) satisfies $x + $y = 4
    • This quantified expression may either return true or raise a type error, since its test expression returns true for one item and raises a type error for another:

      some $x in (1, 2, "cat") satisfies $x * 2 = 4
    • This quantified expression may either return false or raise a type error, since its test expression returns false for one item and raises a type error for another:

      every $x in (1, 2, "cat") satisfies $x * 2 = 4
    • This quantified expression returns true, because the binding sequence is empty, despite the fact that the condition can never be satisfied:

      every $x in () satisfies ($x lt 0 and $x gt 0)
    • This quantified expression is implausible because it will always fail with a type error except in the case where $input is an empty sequence. If $input contains one or more xs:date values, a processor must raise a type error on the grounds that an xs:date cannot be compared to an xs:integer. If $input is empty, the processor may (or may not) report this error:

      every $x as xs:date in $input satisfies ($x lt 0)
    • This quantified expression contains a type declaration that is not satisfied by every item in the test expression. The expression may either return true or raise a type error.

      some $x as xs:integer in (1, 2, "cat") satisfies $x * 2 = 4

    4.20 Try/Catch Expressions

    Changes in 4.0  

    1. $err:map contains entries for all values that are bound to the single variables.   [Issue 32  23 May 2023]

    2. A new variable err:map is available, capturing all error information in one place.   [Issue 32 PR 493 16 May 2023]

    3. $err:stack-trace provides information about the current state of execution.   [Issue 689  1 October 2024]

    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 fn:error() function.

    [104]   TryCatchExpr   ::=   TryClauseCatchClause+
    TryClauseCatchClause+
    [105]   TryClause   ::=   "try" EnclosedExpr
    "try" EnclosedExpr
    [106]   CatchClause   ::=   "catch" NameTestUnionEnclosedExpr
    "catch" NameTestUnionEnclosedExpr
    [107]   NameTestUnion   ::=   (NameTest ++ "|")
    (NameTest ++ "|")
    [151]   NameTest   ::=   EQName | Wildcard
    EQName | Wildcard
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    A try/catch expression catches dynamic errors and type errors raised by the evaluation of the target expression of the try clause. If the the content expression 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.

    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 catch 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 catch clause with one or more NameTests matches any error whose error code matches one of these NameTests. For instance, if the error code is err:FOER0000, then it matches a catch clause whose ErrorList is err:FOER0000 | err:FOER0001. Wildcards may be used in NameTests; thus, the error code err:FOER0000 also matches a catch clause whose ErrorList is err:* or *:FOER0000 or *.

    Within the scope of the catch 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:

    VariableTypeValue
    $err:codexs:QNameThe error code
    $err:descriptionxs:string?A description of the error condition; an empty sequence if no description is available (for example, if the error function was called with one argument).
    $err:valueitem()*Value associated with the error. For an error raised by calling the error function, this is the value of the third argument (if supplied).
    $err:modulexs:string?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.
    $err:line-numberxs:integer?The line number within the module where the error occurred, or an empty sequence if the information is not available. The value may be approximate.
    $err:column-numberxs:integer?The column number within the module where the error occurred, or an empty sequence if the information is not available. The value may be approximate.
    $err:stack-tracexs:string?Implementation-dependent 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.
    $err:additionalitem()*Implementation-defined. 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.
    $err:mapmap(*)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.

    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.

    Static errors are not caught by the try/catch expression.

    If a function call occurs within a try clause, errors raised by evaluating the corresponding function are caught by the try/catch expression. If a variable reference is used in a try clause, errors raised by binding a value to the variable are not caught unless the binding expression occurs within the try clause.

    Note:

    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.

    Here are some examples of try/catch expressions.

    • A try/catch expression without name tests catches any error:

      try {
         $x cast as xs:integer
       } catch * {
         0
      @@ -808,11 +808,11 @@
           return $a/prefecture
         default
           return "unknown"
      -}

    4.21.3 Cast

    [121]   CastExpr   ::=   ArrowExpr ( "cast" "as" CastTarget "?"? )?
    ArrowExpr ( "cast" "as" CastTarget "?"? )?
    [245]   CastTarget   ::=   TypeName | ChoiceItemType | EnumerationType
    TypeName | ChoiceItemType | EnumerationType
    [263]   ChoiceItemType   ::=   "(" (ItemType ++ "|") ")"
    "(" (ItemType ++ "|") ")"
    [259]   EnumerationType   ::=   "enum" "(" (StringLiteral ++ ",") ")"
    "enum" "(" (StringLiteral ++ ",") ")"

    Sometimes it is necessary to convert a value to a specific datatype. For this purpose, XQuery 4.0 and XPath 4.0 provides a cast expression that creates a new value of a specific type based on an existing value. A cast expression takes two operands: an input expression and a target type. The type of the atomized value of the input expression is called the input type. The target type must be a generalized atomic type. In practice this means it may be any of:

    • The name of an named item type defined in the static context, which in turn must refer to an item type in one of the following categories.

    • The name of a type defined in the in-scope schema types, which must be a simple type (of variety atomic, list or union) [err:XQST0052] . In addition, the target type cannot be xs:NOTATION, xs:anySimpleType, or xs:anyAtomicType

    • A ChoiceItemType representing a generalized atomic type (such as (xs:date | xs:dateTime)).

    • An EnumerationType such as enum("red", "green", "blue").

    Otherwise, a static error is raised [err:XPST0080].

    The optional occurrence indicator ? denotes that an empty sequence is permitted.

    Casting a node to xs:QName can cause surprises because it uses the static context of the cast expression to provide the namespace bindings for this operation. Instead of casting to xs:QName, it is generally preferable to use the fn:QName function, which allows the namespace context to be taken from the document containing the QName.

    The semantics of the cast expression are as follows:

    1. The input expression is evaluated.

    2. The result of the first step is atomized.

    3. If the result of atomization is a sequence of more than one atomic item, a type error is raised [err:XPTY0004].

    4. If the result of atomization is an empty sequence:

      1. If ? is specified after the target type, the result of the cast expression is an empty sequence.

      2. If ? is not specified after the target type, a type error is raised [err:XPTY0004].

    5. 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 Section 21 CastingFO. 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 in-scope schema definitions or by using an alternative, implementation-dependent mechanism such as a data dictionary. The result of a cast expression is one of the following:

      1. 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).

      2. 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).

      3. A dynamic error, if the particular input value cannot be converted to the target type (for example, attempting to convert the string "three" to an integer).

      Note:

      Casting to an enumeration type relies on the fact that an enumeration type is a generalized atomic type. So cast $x as enum("red") is equivalent to casting to an anonymous atomic type derived from xs:string whose enumeration facet restricts the value space to the single string "red", while cast $x as enum("red", "green") is equivalent to casting to (enum("red") | enum("green")).

    4.21.4 Castable

    [120]   CastableExpr   ::=   CastExpr ( "castable" "as" CastTarget "?"? )?
    CastExpr ( "castable" "as" CastTarget "?"? )?
    [245]   CastTarget   ::=   TypeName | ChoiceItemType | EnumerationType
    TypeName | ChoiceItemType | EnumerationType
    [263]   ChoiceItemType   ::=   "(" (ItemType ++ "|") ")"
    "(" (ItemType ++ "|") ")"
    [259]   EnumerationType   ::=   "enum" "(" (StringLiteral ++ ",") ")"
    "enum" "(" (StringLiteral ++ ",") ")"

    XQuery 4.0 and XPath 4.0 provides an expression that tests whether a given value is castable into a given target type. The target type is subject to the same rules as the target type of a cast expression.

    The expression E castable as T returns true if the result of evaluating E can be successfully cast into the target type T by using a cast expression; otherwise it returns false. If evaluation of E fails with a dynamic error or if the value of E cannot be atomized, the castable expression as a whole fails.

    The castable expression can be used as a predicate 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:

    if ($x castable as hatsize)
    +}

    4.21.3 Cast

    [121]   CastExpr   ::=   ArrowExpr ( "cast" "as" CastTarget "?"? )?
    ArrowExpr ( "cast" "as" CastTarget "?"? )?
    [245]   CastTarget   ::=   TypeName | ChoiceItemType | EnumerationType
    TypeName | ChoiceItemType | EnumerationType
    [263]   ChoiceItemType   ::=   "(" (ItemType ++ "|") ")"
    "(" (ItemType ++ "|") ")"
    [259]   EnumerationType   ::=   "enum" "(" (StringLiteral ++ ",") ")"
    "enum" "(" (StringLiteral ++ ",") ")"

    Sometimes it is necessary to convert a value to a specific datatype. For this purpose, XQuery 4.0 and XPath 4.0 provides a cast expression that creates a new value of a specific type based on an existing value. A cast expression takes two operands: an input expression and a target type. The type of the atomized value of the input expression is called the input type. The target type must be a generalized atomic type. In practice this means it may be any of:

    • The name of an named item type defined in the static context, which in turn must refer to an item type in one of the following categories.

    • The name of a type defined in the in-scope schema types, which must be a simple type (of variety atomic, list or union) [err:XQST0052] . In addition, the target type cannot be xs:NOTATION, xs:anySimpleType, or xs:anyAtomicType

    • A ChoiceItemType representing a generalized atomic type (such as (xs:date | xs:dateTime)).

    • An EnumerationType such as enum("red", "green", "blue").

    Otherwise, a static error is raised [err:XPST0080].

    The optional occurrence indicator ? denotes that an empty sequence is permitted.

    Casting a node to xs:QName can cause surprises because it uses the static context of the cast expression to provide the namespace bindings for this operation. Instead of casting to xs:QName, it is generally preferable to use the fn:QName function, which allows the namespace context to be taken from the document containing the QName.

    The semantics of the cast expression are as follows:

    1. The input expression is evaluated.

    2. The result of the first step is atomized.

    3. If the result of atomization is a sequence of more than one atomic item, a type error is raised [err:XPTY0004].

    4. If the result of atomization is an empty sequence:

      1. If ? is specified after the target type, the result of the cast expression is an empty sequence.

      2. If ? is not specified after the target type, a type error is raised [err:XPTY0004].

    5. 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 Section 21 CastingFO. 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 in-scope schema definitions or by using an alternative, implementation-dependent mechanism such as a data dictionary. The result of a cast expression is one of the following:

      1. 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).

      2. 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).

      3. A dynamic error, if the particular input value cannot be converted to the target type (for example, attempting to convert the string "three" to an integer).

      Note:

      Casting to an enumeration type relies on the fact that an enumeration type is a generalized atomic type. So cast $x as enum("red") is equivalent to casting to an anonymous atomic type derived from xs:string whose enumeration facet restricts the value space to the single string "red", while cast $x as enum("red", "green") is equivalent to casting to (enum("red") | enum("green")).

    4.21.4 Castable

    [120]   CastableExpr   ::=   CastExpr ( "castable" "as" CastTarget "?"? )?
    CastExpr ( "castable" "as" CastTarget "?"? )?
    [245]   CastTarget   ::=   TypeName | ChoiceItemType | EnumerationType
    TypeName | ChoiceItemType | EnumerationType
    [263]   ChoiceItemType   ::=   "(" (ItemType ++ "|") ")"
    "(" (ItemType ++ "|") ")"
    [259]   EnumerationType   ::=   "enum" "(" (StringLiteral ++ ",") ")"
    "enum" "(" (StringLiteral ++ ",") ")"

    XQuery 4.0 and XPath 4.0 provides an expression that tests whether a given value is castable into a given target type. The target type is subject to the same rules as the target type of a cast expression.

    The expression E castable as T returns true if the result of evaluating E can be successfully cast into the target type T by using a cast expression; otherwise it returns false. If evaluation of E fails with a dynamic error or if the value of E cannot be atomized, the castable expression as a whole fails.

    The castable expression can be used as a predicate 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:

    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

    Note:

    The expression $x castable as enum("red", "green", "blue") is for most practical purposes equivalent to $x = ("red", "green", "blue"); the main difference is that it uses the Unicode codepoint collation for comparing strings, not the default collation from the static context.

    4.21.5 Constructor Functions

    For every simple type in the in-scope schema types (except xs:NOTATION and xs:anyAtomicType, and xs:anySimpleType, which are not instantiable), a constructor function 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 Section 20 Constructor functionsFO.

    There is also a constructor function for every named item type in the static context that expands either to a generalized atomic typeor to a RecordType.

    All such constructor functions are classified as system functions.

    Note:

    The constructor function is present in the static context if and only if the corresponding type is present in the static context.

    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 xsl:item-type declaration has the same visibility as the xsl:item-type declaration.

    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 %public or %private according to the annotations on the item type declaration.

    [Definition: The constructor function for a given simple type is used to convert instances of other simple types into the given type. The semantics of the constructor function call T($arg) are defined to be equivalent to the expression $arg cast as T?.]

    The following examples illustrate the use of constructor functions:

    • This example is equivalent to "2000-01-01" cast as xs:date?.

      xs:date("2000-01-01")
    • This example is equivalent to ($floatvalue * 0.2E-5) cast as xs:decimal?.

      xs:decimal($floatvalue * 0.2E-5)
    • This example returns an xs:dayTimeDuration value equal to 21 days. It is equivalent to "P21D" cast as xs:dayTimeDuration?.

      xs:dayTimeDuration("P21D")
    • If usa:zipcode is a user-defined atomic type in the in-scope schema types, then the following expression is equivalent to the expression ("12345" cast as usa:zipcode?).

      usa:zipcode("12345")
    • If my:chrono is a named item type that expands to (xs:date | xs:time | xs:dateTime), then the result of my:chrono("12:00:00Z") is the xs:time value 12:00:00Z.

    • If my:location is a named item type that expands to record(latitude as xs:double, longitude as xs:double), then the result of my:location(50.52, -3.02) is the map { 'latitude': 50.52e0, 'longitude': -3.02e0 }.

    Note:

    An instance of an atomic type whose name is in no namespace can be constructed by using a URIQualifiedName in either a cast expression or a constructor function call. Examples:

    17 cast as Q{}apple
    Q{}apple(17)

    In either context, using an unqualified NCName might not work: in a cast expression, an unqualified name is it is interpreted according to the default namespace for elements and types, while an unqualified name in a constructor function call is resolved using the default function namespace which will often be inappropriate.

    4.21.6 Treat

    [119]   TreatExpr   ::=   CastableExpr ( "treat" "as" SequenceType )?
    CastableExpr ( "treat" "as" SequenceType )?

    XQuery 4.0 and XPath 4.0 provides an expression called treat that can be used to modify the static type of its operand.

    Like cast, the treat expression takes two operands: an expression and a SequenceType. Unlike cast, however, treat does not change the dynamic type or value of its operand. Instead, the purpose of treat is to ensure that an expression has an expected dynamic type at evaluation time.

    The semantics of expr1 treat as type1 are as follows:

    • During static analysis:

      The static type of the treat expression is type1. This enables the expression to be used as an argument of a function that requires a parameter of type1.

    • During expression evaluation:

      If expr1 matches type1, using the rules for SequenceType matching, the treat expression returns the value of expr1; otherwise, it raises a dynamic error [err:XPDY0050]. If the value of expr1 is returned, the identity of any nodes in the value is preserved. The treat expression ensures that the value of its expression operand conforms to the expected type at run-time.

    • Example:

      $myaddress treat as element(*, USAddress)

      The static type of $myaddress may be element(*, Address), a less specific type than element(*, USAddress). However, at run-time, the value of $myaddress must match the type element(*, USAddress) using rules for SequenceType matching; otherwise a dynamic error is raised [err:XPDY0050].

    Note:

    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 treat as. In the absence of this feature, the treat as expression is rarely necessary, though it can be useful for documentation, and might in some cases (depending on the processor) have performance benefits.

    4.22 Simple map operator (!)

    [137]   SimpleMapExpr   ::=   PathExpr ("!" PathExpr)*
    PathExpr ("!" PathExpr)*

    A mapping expression S!E evaluates the expression E once for every item in the sequence obtained by evaluating S. The simple mapping operator ! 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 / operator, it does not sort nodes into document order or eliminate duplicates.

    Each operation E1!E2 is evaluated as follows: Expression E1 is evaluated to a sequence S. Each item in S then serves in turn to provide an inner focus (the item as the context value, its position in S as the context position, the length of S as the context size) for an evaluation of E2 in the dynamic context. The sequences resulting from all the evaluations of E2 are combined as follows: Every evaluation of E2 returns a (possibly empty) sequence of items. The final result is the sequence concatenation of these sequences. The returned sequence preserves the orderings within and among the subsequences generated by the evaluations of E2.

    Simple map operators have functionality similar to 4.6.3 Path operator (/). The following table summarizes the differences between these two operators

    OperatorPath operator (E1 / E2)Simple map operator (E1 ! E2)
    E1Any sequence of nodesAny sequence of items
    E2Either a sequence of nodes or a sequence of non-node itemsA sequence of items
    Additional processingDuplicate elimination and document orderingSimple sequence concatenation

    The following examples illustrate the use of simple map operators combined with path expressions.

    • child::div1 / child::para / string() ! concat("id-", .)

      Selects the para element children of the div1 element children of the context node; that is, the para element grandchildren of the context node that have div1 parents. It then outputs the strings obtained by prepending "id-" to each of the string values of these grandchildren.

    • $emp ! (@first, @middle, @last)

      Returns the values of the attributes first, middle, and last for each element in $emp, in the order given. (The / operator, if used here, would return the attributes in an unpredictable order.)

    • $docs ! ( //employee)

      Returns all the employee elements within all the documents identified by the variable $docs, in document order within each document, but retaining the order of documents.

    • avg( //employee / salary ! translate(., '$', '') ! number(.))

      Returns the average salary of the employees, having converted the salary to a number by removing any $ sign and then converting to a number. (The second occurrence of ! could not be written as / because the left-hand operand of / cannot be an atomic item.)

    • string-join((1 to $n) ! "*")

      Returns a string containing $n asterisks.

    • $values ! (.*.) => sum()

      Returns the sum of the squares of a sequence of numbers.

    • string-join(ancestor::* ! name(), '/')

      Returns the names of ancestor elements, joined by / characters, i.e., the path to the parent of the context.

    4.23 Arrow Expressions

    Arrow expressions apply a function to a value, using the value of the left-hand expression as the first argument to the function.

    [122]   ArrowExpr   ::=   UnaryExpr ( (SequenceArrowTarget | MappingArrowTarget | LookupArrowTarget) )*
    UnaryExpr ( (SequenceArrowTarget | MappingArrowTarget | LookupArrowTarget) )*
    [125]   SequenceArrowTarget   ::=   "=>" ArrowTarget
    "=>" ArrowTarget
    [126]   MappingArrowTarget   ::=   "=!>" ArrowTarget
    "=!>" ArrowTarget
    [128]   LookupArrowTarget   ::=   "=?>" NCNamePositionalArgumentList
    "=?>" NCNamePositionalArgumentList
    [127]   ArrowTarget   ::=   (ArrowStaticFunctionArgumentList) | (ArrowDynamicFunctionPositionalArgumentList)
    (ArrowStaticFunctionArgumentList) | (ArrowDynamicFunctionPositionalArgumentList)
    [168]   ArrowStaticFunction   ::=   EQName
    EQName
    [169]   ArrowDynamicFunction   ::=   VarRef | InlineFunctionExpr | ParenthesizedExpr
    VarRef | InlineFunctionExpr | ParenthesizedExpr
    [211]   InlineFunctionExpr   ::=   Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    [156]   ArgumentList   ::=   "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    [157]   PositionalArgumentList   ::=   "(" PositionalArguments? ")"
    "(" PositionalArguments? ")"

    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:

    tokenize((normalize-unicode(upper-case($string))),"\s+")

    In the following reformulation, it is easier to see that the parentheses are balanced:

    $string => upper-case() => normalize-unicode() => tokenize("\s+")

    When the operator is written as =!>, the function is applied to each item in the sequence in turn. Assuming that $string is a single string, the above example could equally be written:

    $string =!> upper-case() =!> normalize-unicode() =!> tokenize("\s+")

    The difference between the two operators is seen when the left-hand operand evaluates to a sequence:

    (1, 2, 3) => avg()

    returns a value of only one item, 2, the average of all three items, whereas

    (1, 2, 3) =!> avg()

    returns the original sequence of three items, (1, 2, 3), each item being the average of itself. The following example:

    "The cat sat on the mat"
    +else $x cast as xs:string

    Note:

    The expression $x castable as enum("red", "green", "blue") is for most practical purposes equivalent to $x = ("red", "green", "blue"); the main difference is that it uses the Unicode codepoint collation for comparing strings, not the default collation from the static context.

    4.21.5 Constructor Functions

    For every simple type in the in-scope schema types (except xs:NOTATION and xs:anyAtomicType, and xs:anySimpleType, which are not instantiable), a constructor function 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 Section 20 Constructor functionsFO.

    There is also a constructor function for every named item type in the static context that expands either to a generalized atomic typeor to a RecordType.

    All such constructor functions are classified as system functions.

    Note:

    The constructor function is present in the static context if and only if the corresponding type is present in the static context.

    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 xsl:item-type declaration has the same visibility as the xsl:item-type declaration.

    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 %public or %private according to the annotations on the item type declaration.

    [Definition: The constructor function for a given simple type is used to convert instances of other simple types into the given type. The semantics of the constructor function call T($arg) are defined to be equivalent to the expression $arg cast as T?.]

    The following examples illustrate the use of constructor functions:

    • This example is equivalent to "2000-01-01" cast as xs:date?.

      xs:date("2000-01-01")
    • This example is equivalent to ($floatvalue * 0.2E-5) cast as xs:decimal?.

      xs:decimal($floatvalue * 0.2E-5)
    • This example returns an xs:dayTimeDuration value equal to 21 days. It is equivalent to "P21D" cast as xs:dayTimeDuration?.

      xs:dayTimeDuration("P21D")
    • If usa:zipcode is a user-defined atomic type in the in-scope schema types, then the following expression is equivalent to the expression ("12345" cast as usa:zipcode?).

      usa:zipcode("12345")
    • If my:chrono is a named item type that expands to (xs:date | xs:time | xs:dateTime), then the result of my:chrono("12:00:00Z") is the xs:time value 12:00:00Z.

    • If my:location is a named item type that expands to record(latitude as xs:double, longitude as xs:double), then the result of my:location(50.52, -3.02) is the map { 'latitude': 50.52e0, 'longitude': -3.02e0 }.

    Note:

    An instance of an atomic type whose name is in no namespace can be constructed by using a URIQualifiedName in either a cast expression or a constructor function call. Examples:

    17 cast as Q{}apple
    Q{}apple(17)

    In either context, using an unqualified NCName might not work: in a cast expression, an unqualified name is it is interpreted according to the default namespace for elements and types, while an unqualified name in a constructor function call is resolved using the default function namespace which will often be inappropriate.

    4.21.6 Treat

    [119]   TreatExpr   ::=   CastableExpr ( "treat" "as" SequenceType )?
    CastableExpr ( "treat" "as" SequenceType )?

    XQuery 4.0 and XPath 4.0 provides an expression called treat that can be used to modify the static type of its operand.

    Like cast, the treat expression takes two operands: an expression and a SequenceType. Unlike cast, however, treat does not change the dynamic type or value of its operand. Instead, the purpose of treat is to ensure that an expression has an expected dynamic type at evaluation time.

    The semantics of expr1 treat as type1 are as follows:

    • During static analysis:

      The static type of the treat expression is type1. This enables the expression to be used as an argument of a function that requires a parameter of type1.

    • During expression evaluation:

      If expr1 matches type1, using the rules for SequenceType matching, the treat expression returns the value of expr1; otherwise, it raises a dynamic error [err:XPDY0050]. If the value of expr1 is returned, the identity of any nodes in the value is preserved. The treat expression ensures that the value of its expression operand conforms to the expected type at run-time.

    • Example:

      $myaddress treat as element(*, USAddress)

      The static type of $myaddress may be element(*, Address), a less specific type than element(*, USAddress). However, at run-time, the value of $myaddress must match the type element(*, USAddress) using rules for SequenceType matching; otherwise a dynamic error is raised [err:XPDY0050].

    Note:

    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 treat as. In the absence of this feature, the treat as expression is rarely necessary, though it can be useful for documentation, and might in some cases (depending on the processor) have performance benefits.

    4.22 Simple map operator (!)

    [137]   SimpleMapExpr   ::=   PathExpr ("!" PathExpr)*
    PathExpr ("!" PathExpr)*

    A mapping expression S!E evaluates the expression E once for every item in the sequence obtained by evaluating S. The simple mapping operator ! 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 / operator, it does not sort nodes into document order or eliminate duplicates.

    Each operation E1!E2 is evaluated as follows: Expression E1 is evaluated to a sequence S. Each item in S then serves in turn to provide an inner focus (the item as the context value, its position in S as the context position, the length of S as the context size) for an evaluation of E2 in the dynamic context. The sequences resulting from all the evaluations of E2 are combined as follows: Every evaluation of E2 returns a (possibly empty) sequence of items. The final result is the sequence concatenation of these sequences. The returned sequence preserves the orderings within and among the subsequences generated by the evaluations of E2.

    Simple map operators have functionality similar to 4.6.3 Path operator (/). The following table summarizes the differences between these two operators

    OperatorPath operator (E1 / E2)Simple map operator (E1 ! E2)
    E1Any sequence of nodesAny sequence of items
    E2Either a sequence of nodes or a sequence of non-node itemsA sequence of items
    Additional processingDuplicate elimination and document orderingSimple sequence concatenation

    The following examples illustrate the use of simple map operators combined with path expressions.

    • child::div1 / child::para / string() ! concat("id-", .)

      Selects the para element children of the div1 element children of the context node; that is, the para element grandchildren of the context node that have div1 parents. It then outputs the strings obtained by prepending "id-" to each of the string values of these grandchildren.

    • $emp ! (@first, @middle, @last)

      Returns the values of the attributes first, middle, and last for each element in $emp, in the order given. (The / operator, if used here, would return the attributes in an unpredictable order.)

    • $docs ! ( //employee)

      Returns all the employee elements within all the documents identified by the variable $docs, in document order within each document, but retaining the order of documents.

    • avg( //employee / salary ! translate(., '$', '') ! number(.))

      Returns the average salary of the employees, having converted the salary to a number by removing any $ sign and then converting to a number. (The second occurrence of ! could not be written as / because the left-hand operand of / cannot be an atomic item.)

    • string-join((1 to $n) ! "*")

      Returns a string containing $n asterisks.

    • $values ! (.*.) => sum()

      Returns the sum of the squares of a sequence of numbers.

    • string-join(ancestor::* ! name(), '/')

      Returns the names of ancestor elements, joined by / characters, i.e., the path to the parent of the context.

    4.23 Arrow Expressions

    Arrow expressions apply a function to a value, using the value of the left-hand expression as the first argument to the function.

    [122]   ArrowExpr   ::=   UnaryExpr ( (SequenceArrowTarget | MappingArrowTarget | LookupArrowTarget) )*
    UnaryExpr ( (SequenceArrowTarget | MappingArrowTarget | LookupArrowTarget) )*
    [125]   SequenceArrowTarget   ::=   "=>" ArrowTarget
    "=>" ArrowTarget
    [126]   MappingArrowTarget   ::=   "=!>" ArrowTarget
    "=!>" ArrowTarget
    [128]   LookupArrowTarget   ::=   "=?>" NCNamePositionalArgumentList
    "=?>" NCNamePositionalArgumentList
    [127]   ArrowTarget   ::=   (ArrowStaticFunctionArgumentList) | (ArrowDynamicFunctionPositionalArgumentList)
    (ArrowStaticFunctionArgumentList) | (ArrowDynamicFunctionPositionalArgumentList)
    [168]   ArrowStaticFunction   ::=   EQName
    EQName
    [169]   ArrowDynamicFunction   ::=   VarRef | InlineFunctionExpr | ParenthesizedExpr
    VarRef | InlineFunctionExpr | ParenthesizedExpr
    [211]   InlineFunctionExpr   ::=   Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    [156]   ArgumentList   ::=   "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    [157]   PositionalArgumentList   ::=   "(" PositionalArguments? ")"
    "(" PositionalArguments? ")"

    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:

    tokenize((normalize-unicode(upper-case($string))),"\s+")

    In the following reformulation, it is easier to see that the parentheses are balanced:

    $string => upper-case() => normalize-unicode() => tokenize("\s+")

    When the operator is written as =!>, the function is applied to each item in the sequence in turn. Assuming that $string is a single string, the above example could equally be written:

    $string =!> upper-case() =!> normalize-unicode() =!> tokenize("\s+")

    The difference between the two operators is seen when the left-hand operand evaluates to a sequence:

    (1, 2, 3) => avg()

    returns a value of only one item, 2, the average of all three items, whereas

    (1, 2, 3) =!> avg()

    returns the original sequence of three items, (1, 2, 3), each item being the average of itself. The following example:

    "The cat sat on the mat"
     => tokenize()
     =!> concat(".")
     =!> upper-case()
    @@ -821,7 +821,7 @@
       "height": 12,
       "area": fn($this) { $this?width * $this?height }
     } 
    -return $rectangle =?> area()

    returns the value 240.

    An expression such as M =?> N(A, B, C) is evaluated as follows:

    1. The left-hand expression M is evaluated. If the value is an empty sequence, then the result of the expression is an empty sequence. If it is non-empty then it must be a single map: call it $m.

    2. The lookup expression $m?N is evaluated. The result must be a single function item: call it $f.

    3. The dynamic function call $f($m, A, B, C) is evaluated, and the result is returned.

    Any of the above steps can lead to errors:

    1. A type error [err:XPTY0004] is raised if the value of the left hand expression does not match the type map(*)?.

    2. A type error [err:XPTY0004] is raised if the value of the lookup expression $m?N does not match the type function(*), or if the arity of the function is not equal to the number of arguments in the argument list plus one.

    3. An error may occur in evaluating the dynamic function call, for example if the function does not expect a map to be supplied as the first argument.

    4.24 Validate Expressions

    Changes in 4.0  

    1. The rules concerning the interpretation of xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes have been tightened up.   [Issue 729 PR 1254 8 June 2024]

    [132]   ValidateExpr   ::=   "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    [133]   ValidationMode   ::=   "lax" | "strict"
    "lax" | "strict"
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    A validate expression can be used to validate a document node or an element node with respect to the in-scope schema definitions, using the schema validation process defined in [XML Schema 1.0] or [XML Schema 1.1]. If the operand of a validate expression does not evaluate to exactly one document or element node, a type error is raised [err:XQTY0030]. In this specification, the node that is the operand of a validate expression is called the operand node.

    A validate expression returns a new node with its own identity and with no parent. The new node and its descendants are given type annotation that are generated by applying a validation process to the operand node. In some cases, default values may also be generated by the validation process.

    A validate expression may optionally specify a validation mode. The default validation mode (applicable when no type name is provided) is strict.

    A validate expression may optionally specify a TypeName. This type name must be found in the in-scope schema definitions; if it is not, a static error is raised [err:XQST0104]. If the type name is unprefixed, it is interpreted according to the default namespace for elements and types.

    The result of a validate expression is defined by the following rules.

    1. If the operand node is a document node, its children must consist of exactly one element node and zero or more comment and processing instruction nodes, in any order; otherwise, a dynamic error [err:XQDY0061] is raised.

    2. The operand node is converted to an XML Information Set ([XML Infoset]) according to the “Infoset Mapping” rules defined in [XQuery and XPath Data Model (XDM) 4.0]. Note that this process discards any existing type annotations. Validity assessment is carried out on the root element information item of the resulting Infoset, using the in-scope schema definitions as the effective schema. The process of validation applies recursively to contained elements and attributes to the extent required by the effective schema.

    3. If a type name is provided, and the type name is xs:untyped, all elements receive the type annotation xs:untyped, and all attributes receive the type annotation xs:untypedAtomic. If the type name is xs:untypedAtomic, the node receives the type annotation xs:untypedAtomic; a type error [err:XPTY0004] is raised if the node has element children. Otherwise, schema-validity assessment is carried out according to the rules defined in [XML Schema 1.0] or [XML Schema 1.1] Part 1, section 3.3.4 "Element Declaration Validation Rules", “Validation Rule: Schema-Validity Assessment (Element)”, clauses 1.2 and 2, using this type definition as the “processor-stipulated type definition” for validation.

      If the instance being validated contains an xml:id attribute, both lax and strict validation cause this attribute to be subjected to [xml:id] processing: that is, the attribute is checked for uniqueness, and is typed as xs:ID, and the containing element is therefore eligible as a target for the id() function.

    4. It is implementation defined whether the validity assessment process takes account of any xsi:schemaLocation or xsi:noNamespaceSchemaLocation attributes in the tree being validated. If it does so, then it should adhere to the following rules:

      1. Any schema loaded using these attributes must be compatibleDM with the schema in the static context from which validation is invoked.

      2. Any schema loaded using these attributes must not override or redefine any schema components in the static context.

      3. Any schema components loaded using this mechanism must be used for this validity assessment only, and must not affect the outcome of any subsequent validity assessments of other documents.

        Note:

        A processor may choose to cache such schema components but the existence of such a cache should only affect performance, not the validation outcome.

      A consequence of validating a document using schema components that are not in the static context is that nodes may be annotated with types that are not in the static context. But the rules for schema compatibilityDM mean that this is not a problem.

    5. When no type name is provided:

      1. If validation mode is strict, then there must be a top-level element declaration in the in-scope element declarations that matches the root element information item in the Infoset, and schema-validity assessment is carried out using that declaration in accordance with [XML Schema 1.0] Part 1, section 5.2, “Assessing Schema-Validity”, item 2, or [XML Schema 1.1] Part 1, section 5.2, “Assessing Schema-Validity”, “element-driven validation”. If there is no such element declaration, a dynamic error is raised [err:XQDY0084].

      2. If validation mode is lax, then schema-validity assessment is carried out in accordance with [XML Schema 1.0] Part 1, section 5.2, “Assessing Schema-Validity”, item 3, or [XML Schema 1.1] Part 1, section 5.2, “Assessing Schema-Validity”, “lax wildcard validation”.

        If validation mode is lax and the root element information item has neither a top-level element declaration nor an xsi:type attribute, [XML Schema 1.0] defines the recursive checking of children and attributes as optional. During processing of an XQuery validate expression, this recursive checking is required.

      3. If the operand node is an element node, the validation rules named “Validation Root Valid (ID/IDREF)” are not applied. This means that document-level constraints relating to uniqueness and referential integrity are not enforced.

      4. There is no check that the document contains unparsed entities whose names match the values of nodes of type xs:ENTITY or xs:ENTITIES.

      Note:

      Validity assessment is affected by the presence or absence of xsi:type attributes on the elements being validated, and may generate new information items such as default attributes.

    6. The outcome of the validation expression depends on the validity property of the root element information item in the PSVI that results from the validation process.

      1. If the validity property of the root element information item is valid, or if validation mode is lax and the validity property of the root element information item is notKnown, the PSVI is converted back into an XDM instance as described in [XQuery and XPath Data Model (XDM) 4.0] Section 3.3, “Construction from a PSVI”. The resulting node (a new node of the same kind as the operand node) is returned as the result of the validate expression.

      2. Otherwise, a dynamic error is raised [err:XQDY0027].

    Note:

    The effect of these rules is as follows, where the validated element means either the operand node or (if the operand node is a document node) its element child:

    • If validation mode is strict, the validated element must have a top-level element declaration in the effective schema, and must conform to this declaration.

    • If validation mode is lax, the validated element must conform to its top-level element declaration if such a declaration exists in the effective schema. If validation mode is lax and there is no top-level element declaration for the element, and the element has an xsi:type attribute, then the xsi:type attribute must name a top-level type definition in the effective schema, and the element must conform to that type.

    • If a type name is specified in the validate expression, no attempt is made to locate an element declaration matching the name of the validated element; the element can have any name, and its content is validated against the named type.

    Note:

    During conversion of the PSVI into an XDM instance after validation, any element information items whose validity property is notKnown are converted into element nodes with type annotationxs:anyType, and any attribute information items whose validity property is notKnown are converted into attribute nodes with type annotationxs:untypedAtomic, as described in Section 3.3.1.1 Element and Attribute Node TypesDM.

    Note:

    A query might take as its primary input a document conforming to schema X, and produce as its primary output a document conforming to schema Y. To be sure that the output is indeed valid against schema Y, the safest course of action is to evaluate a validate expression within a query module that imports schema Y and nothing else. Otherwise, if the validation occurs within a module that imports both X and Y, the outcome of validation might differ because of the differences between the two schemas.

    4.25 Extension Expressions

    [Definition: An extension expression is an expression whose semantics are implementation-defined.] 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.

    [134]   ExtensionExpr   ::=   Pragma+ "{" Expr? "}"
    Pragma+ "{" Expr? "}"
    [135]   Pragma   ::=   "(#" S? EQName (SPragmaContents)? "#)"/* ws: explicit */
    "(#" S? EQName (SPragmaContents)? "#)"/* ws: explicit */
    /* ws: explicit */
    [136]   PragmaContents   ::=   (Char* - (Char* '#)' Char*))
    (Char* - (Char* '#)' Char*))

    An extension expression consists of one or more pragmas, followed by an optional expression (the associated expression). [Definition: A pragma is denoted by the delimiters (# and #), and consists of an identifying EQName followed by implementation-defined content.] The content of a pragma may consist of any string of characters that does not contain the ending delimiter #). If the EQName of a pragma is a lexical QName, it must resolve to a namespace URI and local name, using the statically known namespaces [err:XPST0081]. If the EQName is an unprefixed NCName, it is interpreted as a name in no namespace (and the pragma is therefore ignored).

    Each implementation recognizes an implementation-defined set of namespace URIs used to denote pragmas.

    If the namespace URI of a pragma’s expanded QName 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 ExtensionExpr are ignored, then the value of the ExtensionExpr is the value of the associated expression; if no associated expression is provided, a static error is raised [err:XQST0079].

    If an implementation recognizes the namespace of one or more pragmas in an ExtensionExpr, then the value of the ExtensionExpr, including its error behavior, is implementation-defined. For example, an implementation that recognizes the namespace of a pragma’s expanded QName, but does not recognize the local part of the name, might choose either to raise an error or to ignore the pragma.

    It is a static error [err:XQST0013] if an implementation recognizes a pragma but determines that its content is invalid.

    If an implementation recognizes a pragma, it must report any static errors in the following expression even if it will not evaluate that expression.

    Note:

    The following examples illustrate three ways in which extension expressions might be used.

    • A pragma can be used to furnish a hint for how to evaluate the following expression, without actually changing the result. For example:

      declare namespace exq = "http://example.org/XQueryImplementation";
      +return $rectangle =?> area()

      returns the value 240.

      An expression such as M =?> N(A, B, C) is evaluated as follows:

      1. The left-hand expression M is evaluated. If the value is an empty sequence, then the result of the expression is an empty sequence. If it is non-empty then it must be a single map: call it $m.

      2. The lookup expression $m?N is evaluated. The result must be a single function item: call it $f.

      3. The dynamic function call $f($m, A, B, C) is evaluated, and the result is returned.

      Any of the above steps can lead to errors:

      1. A type error [err:XPTY0004] is raised if the value of the left hand expression does not match the type map(*)?.

      2. A type error [err:XPTY0004] is raised if the value of the lookup expression $m?N does not match the type function(*), or if the arity of the function is not equal to the number of arguments in the argument list plus one.

      3. An error may occur in evaluating the dynamic function call, for example if the function does not expect a map to be supplied as the first argument.

    4.24 Validate Expressions

    Changes in 4.0  

    1. The rules concerning the interpretation of xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes have been tightened up.   [Issue 729 PR 1254 8 June 2024]

    [132]   ValidateExpr   ::=   "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    [133]   ValidationMode   ::=   "lax" | "strict"
    "lax" | "strict"
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    A validate expression can be used to validate a document node or an element node with respect to the in-scope schema definitions, using the schema validation process defined in [XML Schema 1.0] or [XML Schema 1.1]. If the operand of a validate expression does not evaluate to exactly one document or element node, a type error is raised [err:XQTY0030]. In this specification, the node that is the operand of a validate expression is called the operand node.

    A validate expression returns a new node with its own identity and with no parent. The new node and its descendants are given type annotation that are generated by applying a validation process to the operand node. In some cases, default values may also be generated by the validation process.

    A validate expression may optionally specify a validation mode. The default validation mode (applicable when no type name is provided) is strict.

    A validate expression may optionally specify a TypeName. This type name must be found in the in-scope schema definitions; if it is not, a static error is raised [err:XQST0104]. If the type name is unprefixed, it is interpreted according to the default namespace for elements and types.

    The result of a validate expression is defined by the following rules.

    1. If the operand node is a document node, its children must consist of exactly one element node and zero or more comment and processing instruction nodes, in any order; otherwise, a dynamic error [err:XQDY0061] is raised.

    2. The operand node is converted to an XML Information Set ([XML Infoset]) according to the “Infoset Mapping” rules defined in [XQuery and XPath Data Model (XDM) 4.0]. Note that this process discards any existing type annotations. Validity assessment is carried out on the root element information item of the resulting Infoset, using the in-scope schema definitions as the effective schema. The process of validation applies recursively to contained elements and attributes to the extent required by the effective schema.

    3. If a type name is provided, and the type name is xs:untyped, all elements receive the type annotation xs:untyped, and all attributes receive the type annotation xs:untypedAtomic. If the type name is xs:untypedAtomic, the node receives the type annotation xs:untypedAtomic; a type error [err:XPTY0004] is raised if the node has element children. Otherwise, schema-validity assessment is carried out according to the rules defined in [XML Schema 1.0] or [XML Schema 1.1] Part 1, section 3.3.4 "Element Declaration Validation Rules", “Validation Rule: Schema-Validity Assessment (Element)”, clauses 1.2 and 2, using this type definition as the “processor-stipulated type definition” for validation.

      If the instance being validated contains an xml:id attribute, both lax and strict validation cause this attribute to be subjected to [xml:id] processing: that is, the attribute is checked for uniqueness, and is typed as xs:ID, and the containing element is therefore eligible as a target for the id() function.

    4. It is implementation defined whether the validity assessment process takes account of any xsi:schemaLocation or xsi:noNamespaceSchemaLocation attributes in the tree being validated. If it does so, then it should adhere to the following rules:

      1. Any schema loaded using these attributes must be compatibleDM with the schema in the static context from which validation is invoked.

      2. Any schema loaded using these attributes must not override or redefine any schema components in the static context.

      3. Any schema components loaded using this mechanism must be used for this validity assessment only, and must not affect the outcome of any subsequent validity assessments of other documents.

        Note:

        A processor may choose to cache such schema components but the existence of such a cache should only affect performance, not the validation outcome.

      A consequence of validating a document using schema components that are not in the static context is that nodes may be annotated with types that are not in the static context. But the rules for schema compatibilityDM mean that this is not a problem.

    5. When no type name is provided:

      1. If validation mode is strict, then there must be a top-level element declaration in the in-scope element declarations that matches the root element information item in the Infoset, and schema-validity assessment is carried out using that declaration in accordance with [XML Schema 1.0] Part 1, section 5.2, “Assessing Schema-Validity”, item 2, or [XML Schema 1.1] Part 1, section 5.2, “Assessing Schema-Validity”, “element-driven validation”. If there is no such element declaration, a dynamic error is raised [err:XQDY0084].

      2. If validation mode is lax, then schema-validity assessment is carried out in accordance with [XML Schema 1.0] Part 1, section 5.2, “Assessing Schema-Validity”, item 3, or [XML Schema 1.1] Part 1, section 5.2, “Assessing Schema-Validity”, “lax wildcard validation”.

        If validation mode is lax and the root element information item has neither a top-level element declaration nor an xsi:type attribute, [XML Schema 1.0] defines the recursive checking of children and attributes as optional. During processing of an XQuery validate expression, this recursive checking is required.

      3. If the operand node is an element node, the validation rules named “Validation Root Valid (ID/IDREF)” are not applied. This means that document-level constraints relating to uniqueness and referential integrity are not enforced.

      4. There is no check that the document contains unparsed entities whose names match the values of nodes of type xs:ENTITY or xs:ENTITIES.

      Note:

      Validity assessment is affected by the presence or absence of xsi:type attributes on the elements being validated, and may generate new information items such as default attributes.

    6. The outcome of the validation expression depends on the validity property of the root element information item in the PSVI that results from the validation process.

      1. If the validity property of the root element information item is valid, or if validation mode is lax and the validity property of the root element information item is notKnown, the PSVI is converted back into an XDM instance as described in [XQuery and XPath Data Model (XDM) 4.0] Section 3.3, “Construction from a PSVI”. The resulting node (a new node of the same kind as the operand node) is returned as the result of the validate expression.

      2. Otherwise, a dynamic error is raised [err:XQDY0027].

    Note:

    The effect of these rules is as follows, where the validated element means either the operand node or (if the operand node is a document node) its element child:

    • If validation mode is strict, the validated element must have a top-level element declaration in the effective schema, and must conform to this declaration.

    • If validation mode is lax, the validated element must conform to its top-level element declaration if such a declaration exists in the effective schema. If validation mode is lax and there is no top-level element declaration for the element, and the element has an xsi:type attribute, then the xsi:type attribute must name a top-level type definition in the effective schema, and the element must conform to that type.

    • If a type name is specified in the validate expression, no attempt is made to locate an element declaration matching the name of the validated element; the element can have any name, and its content is validated against the named type.

    Note:

    During conversion of the PSVI into an XDM instance after validation, any element information items whose validity property is notKnown are converted into element nodes with type annotationxs:anyType, and any attribute information items whose validity property is notKnown are converted into attribute nodes with type annotationxs:untypedAtomic, as described in Section 3.3.1.1 Element and Attribute Node TypesDM.

    Note:

    A query might take as its primary input a document conforming to schema X, and produce as its primary output a document conforming to schema Y. To be sure that the output is indeed valid against schema Y, the safest course of action is to evaluate a validate expression within a query module that imports schema Y and nothing else. Otherwise, if the validation occurs within a module that imports both X and Y, the outcome of validation might differ because of the differences between the two schemas.

    4.25 Extension Expressions

    [Definition: An extension expression is an expression whose semantics are implementation-defined.] 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.

    [134]   ExtensionExpr   ::=   Pragma+ "{" Expr? "}"
    Pragma+ "{" Expr? "}"
    [135]   Pragma   ::=   "(#" S? EQName (SPragmaContents)? "#)"/* ws: explicit */
    "(#" S? EQName (SPragmaContents)? "#)"/* ws: explicit */
    /* ws: explicit */
    [136]   PragmaContents   ::=   (Char* - (Char* '#)' Char*))
    (Char* - (Char* '#)' Char*))

    An extension expression consists of one or more pragmas, followed by an optional expression (the associated expression). [Definition: A pragma is denoted by the delimiters (# and #), and consists of an identifying EQName followed by implementation-defined content.] The content of a pragma may consist of any string of characters that does not contain the ending delimiter #). If the EQName of a pragma is a lexical QName, it must resolve to a namespace URI and local name, using the statically known namespaces [err:XPST0081]. If the EQName is an unprefixed NCName, it is interpreted as a name in no namespace (and the pragma is therefore ignored).

    Each implementation recognizes an implementation-defined set of namespace URIs used to denote pragmas.

    If the namespace URI of a pragma’s expanded QName 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 ExtensionExpr are ignored, then the value of the ExtensionExpr is the value of the associated expression; if no associated expression is provided, a static error is raised [err:XQST0079].

    If an implementation recognizes the namespace of one or more pragmas in an ExtensionExpr, then the value of the ExtensionExpr, including its error behavior, is implementation-defined. For example, an implementation that recognizes the namespace of a pragma’s expanded QName, but does not recognize the local part of the name, might choose either to raise an error or to ignore the pragma.

    It is a static error [err:XQST0013] if an implementation recognizes a pragma but determines that its content is invalid.

    If an implementation recognizes a pragma, it must report any static errors in the following expression even if it will not evaluate that expression.

    Note:

    The following examples illustrate three ways in which extension expressions might be used.

    • A pragma can be used to furnish a hint for how to evaluate the following expression, without actually changing the result. For example:

      declare namespace exq = "http://example.org/XQueryImplementation";
       (# exq:use-index #) {
         $bib/book/author[name = 'Berners-Lee']
       }

      An implementation that recognizes the exq:use-index 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.

    • 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 xs:duration values using implementation-defined semantics (this would normally be an error). Such changes to the language semantics must be scoped to the enclosed expression following the pragma.

    • 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:

      declare namespace exq = "http://example.org/XQueryImplementation";
      @@ -838,7 +838,7 @@
         format-number($i, "#.###,##", "local:de"), 
         format-number($i, "#,###.##", "local:en") 
       )

      The output of this query is:

      1.234,57 1,234.57 789 789 1.234.567,76 1,234,567.76

    5.11 Schema Import

    Changes in 4.0  

    1. In previous versions the interpretation of location hints in import schema declarations was entirely at the discretion of the processor. To improve interoperability, XQuery 4.0 recommends (but does not mandate) a specific strategy for interpreting these hints.  [Issue 647 PR 659 24 October 2023]

    2. 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.  [Issue 451 PR 635]

    [22]   SchemaImport   ::=   "import" "schema" SchemaPrefix? URILiteral ("at" (URILiteral ++ ","))?
    "import" "schema" SchemaPrefix? URILiteral ("at" (URILiteral ++ ","))?
    [23]   SchemaPrefix   ::=   ("namespace" NCName "=") | ("fixed"? "default" "element" "namespace")
    ("namespace" NCName "=") | ("fixed"? "default" "element" "namespace")

    [Definition: A schema import imports the element declarations, attribute declarations, and type definitions from a schema into the in-scope schema definitions. For each named user-defined simple type in the schema, schema import also adds a corresponding constructor function. ] The schema to be imported is identified by its target namespace. The schema import may bind a namespace prefix to the target namespace of the imported schema, adding the (prefix, URI) pair to the statically known namespaces, or it may declare that target namespace to be the default namespace for elements and types. The schema import may also provide optional hints for locating the schema.

    The namespace prefix specified in a schema import must not be xml or xmlns [err:XQST0070], and must not be the same as any namespace prefix bound in the same module by another schema import, a module import, a namespace declaration, or a module declaration [err:XQST0033].

    Note:

    If schema definitions from the xml namespace are to be used (for example, schema-attribute(xml:space), then the prolog should include a declaration in the form import schema "http://www.w3.org/XML/1998/namespace". No prefix should be supplied (the xml prefix is predeclared), and no location hint should be provided (the schema definitions for the namespace are built in, and cannot be varied).

    If the schema import declaration specifies default element namespace then the prolog must not contain a namespace declaration that specifies default element namespace or default type namespace.

    If the keyword "fixed", is present, the default namespace for elements and types is fixed throughout the module, and is not affected by default namespace declarations (xmlns="") appearing on direct element constructors.

    The first URILiteral in a schema import specifies the target namespace of the schema to be imported.

    If the target namespace is http://www.w3.org/2005/xpath-functions then the schema described in Section C SchemasFO is imported; any location hints are ignored.

    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 [err:XQST0057], 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 default namespace for elements and types is not set to "no namespace", the only way to reference the definitions in an imported schema that has no target namespace is using the EQName syntax Q{}local-name.

    The URILiterals that follow the at 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 may interpret or disregard these hints in an implementation-defined way. The preferred strategy, which should be used by default unless the user indicates otherwise, is as follows:

    1. If the target namespace is one for which the processor has built-in knowledge, for example the schema for a reserved namespace, the location hints should be ignored, and the built-in schema used in preference.

    2. 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.

    3. 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.

    4. The dereferencing of a location hint may make use of implementation-defined indirection mechanisms such as resolver callbacks and catalog files.

    5. 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.

    6. 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 xs:import 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.

    7. Once one location hint has been successfully processed, subsequent location hints are ignored.

    Note:

    Processors that adopted a different strategy in earlier releases may continue to use that strategy by default, in order to retain compatibility; however such processors should offer the above strategy as an option.

    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.

    Different query modules may import different schemas, but there is a requirement that all the schemas used by a query must be compatible. The rules for compatibility are defined in Section 2.8.1 Schema ConsistencyDM. This means, for example:

    • 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.

    • 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.

    If the target namespace is http://www.w3.org/2005/xpath-functions then the schema described in Section C Schemas FO31 is imported; any location hints are ignored.

    It is a static error [err:XQST0058] if more than one schema import in the same Prolog specifies the same target namespace. It is a static error [err:XQST0059] if the implementation is not able to process a schema import by finding a valid schema with the specified target namespace.

    It is a static error [err:XQST0012] 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 [XML Schema 1.0] or [XML Schema 1.1] Part 1: in particular, each definition must be valid, complete, and unique.

    It is a static error [err:XQST0149] if the schemas imported by different modules of a query are not compatible as defined in Section 2.8.1 Schema ConsistencyDM.

    The following example imports a schema, specifying both its target namespace and its location, and binding the prefix soap to the target namespace:

    import schema namespace soap="http://www.w3.org/2003/05/soap-envelope" 
    -  at "http://www.w3.org/2003/05/soap-envelope/";

    The following example imports a schema by specifying only its target namespace, and makes it the default namespace for elements and types:

    import schema default element namespace "http://example.org/abc";

    The following example imports a schema that has no target namespace, providing a location hint, and sets the default namespace for elements and types to “no namespace” so that the definitions in the imported schema can be referenced:

    import schema default element namespace "" at "http://example.org/xyz.xsd";

    The following example imports a schema that has no target namespace and sets the default namespace for elements and types to “no namespace”. Since no location hint is provided, it is up to the implementation to find the schema to be imported.

    import schema default element namespace "";

    5.12 Module Import

    [24]   ModuleImport   ::=   "import" "module" ("namespace" NCName "=")? URILiteral ("at" (URILiteral ++ ","))?
    "import" "module" ("namespace" NCName "=")? URILiteral ("at" (URILiteral ++ ","))?

    [Definition: A module import imports the public variable declarations, public function declarations, and public item type declarations from one or more library modules into the statically known function definitions, in-scope variables, or in-scope named item types of the importing module.] Each module import names a target namespace and imports an implementation-defined 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 statically known namespaces, and it may provide optional hints for locating the modules to be imported.

    If a module A imports module B, the static context of module A will contain the statically known function definitions, in-scope variables, or in-scope named item types of module B, and the dynamic context of module A will contain the public variable values and dynamically known function definitions of module B. It will not contain:

    The following example illustrates a module import:

    import module namespace gis="http://example.org/gis-functions";

    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.

    A module may import its own target namespace (this is interpreted as importing an implementation-defined set of other modules that share its target namespace.)

    The namespace prefix specified in a module import must not be xml or xmlns [err:XQST0070], and must not be the same as any namespace prefix bound in the same module by another module import, a schema import, a namespace declaration, or a module declaration with a different target namespace [err:XQST0033].

    The first URILiteral in a module import must be of nonzero length [err:XQST0088], and specifies the target namespace of the modules to be imported. The URILiterals that follow the at keyword are optional location hints, and can be interpreted or disregarded in an implementation-defined way.

    It is a static error [err:XQST0047] if more than one module import in a Prolog specifies the same target namespace. It is a static error [err:XQST0059] 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 static error if two or more variables declared or imported by a module have equal expanded QNames (as defined by the eq operator) [err:XQST0049].

    Module imports are not transitive. Importing a module provides access only to declarations contained directly in the imported module. For example, if module A imports module B, and module B imports module C, module A does not have access to the functions and variables declared in module C.

    Example: Schema Information and Module Import

    A module import does not import schema definitions from the imported module. In the following query, the type geometry:triangle is not defined, even if it is known in the imported module, so the variable declaration raises an error [err:XPST0051]:

    (: Error - geometry:triangle is not defined :) 
    +  at "http://www.w3.org/2003/05/soap-envelope/";

    The following example imports a schema by specifying only its target namespace, and makes it the default namespace for elements and types:

    import schema default element namespace "http://example.org/abc";

    The following example imports a schema that has no target namespace, providing a location hint, and sets the default namespace for elements and types to “no namespace” so that the definitions in the imported schema can be referenced:

    import schema default element namespace "" at "http://example.org/xyz.xsd";

    The following example imports a schema that has no target namespace and sets the default namespace for elements and types to “no namespace”. Since no location hint is provided, it is up to the implementation to find the schema to be imported.

    import schema default element namespace "";

    5.12 Module Import

    [24]   ModuleImport   ::=   "import" "module" ("namespace" NCName "=")? URILiteral ("at" (URILiteral ++ ","))?
    "import" "module" ("namespace" NCName "=")? URILiteral ("at" (URILiteral ++ ","))?

    [Definition: A module import imports the public variable declarations, public function declarations, and public item type declarations from one or more library modules into the statically known function definitions, in-scope variables, or in-scope named item types of the importing module.] Each module import names a target namespace and imports an implementation-defined 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 statically known namespaces, and it may provide optional hints for locating the modules to be imported.

    If a module A imports module B, the static context of module A will contain the statically known function definitions, in-scope variables, or in-scope named item types of module B, and the dynamic context of module A will contain the public variable values and dynamically known function definitions of module B. It will not contain:

    The following example illustrates a module import:

    import module namespace gis="http://example.org/gis-functions";

    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.

    A module may import its own target namespace (this is interpreted as importing an implementation-defined set of other modules that share its target namespace.)

    The namespace prefix specified in a module import must not be xml or xmlns [err:XQST0070], and must not be the same as any namespace prefix bound in the same module by another module import, a schema import, a namespace declaration, or a module declaration with a different target namespace [err:XQST0033].

    The first URILiteral in a module import must be of nonzero length [err:XQST0088], and specifies the target namespace of the modules to be imported. The URILiterals that follow the at keyword are optional location hints, and can be interpreted or disregarded in an implementation-defined way.

    It is a static error [err:XQST0047] if more than one module import in a Prolog specifies the same target namespace. It is a static error [err:XQST0059] 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 static error if two or more variables declared or imported by a module have equal expanded QNames (as defined by the eq operator) [err:XQST0049].

    Module imports are not transitive. Importing a module provides access only to declarations contained directly in the imported module. For example, if module A imports module B, and module B imports module C, module A does not have access to the functions and variables declared in module C.

    Example: Schema Information and Module Import

    A module import does not import schema definitions from the imported module. In the following query, the type geometry:triangle is not defined, even if it is known in the imported module, so the variable declaration raises an error [err:XPST0051]:

    (: 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

    Without the type declaration for the variable, the variable declaration succeeds:

    import module namespace geo = "http://example.org/geo-functions";
    @@ -852,12 +852,12 @@
     let $node := <foo:bar xmlns:foo = "http://example.org">
       <foo:bing> Lentils </foo:bing>
     </foo:bar>
    -return $node/xx:bing

    Although the namespace prefixes xx and foo differ, both are bound to the namespace URI http://example.org. Since xx:bing and foo:bing have the same local name and the same namespace URI, they match. The output of the above query is as follows.

    <foo:bing xmlns:foo="http://example.org"> Lentils </foo:bing>

    5.14 Default Namespace Declaration

    Changes in 4.0  

    1. The default namespace for elements and types can now be declared to be fixed for a query module, meaning it is unaffected by a namespace declaration appearing on a direct element constructor.   [Issue 65 PR 753 31 October 2023]

    2. The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.   [Issue 296 PR 1181 30 April 2023]

    [26]   DefaultNamespaceDecl   ::=   "declare" "fixed"? "default" ("element" | "function") "namespace" URILiteral
    "declare" "fixed"? "default" ("element" | "function") "namespace" URILiteral

    Default namespace declarations can be used in a Prolog to facilitate the use of unprefixed QNames.

    The namespace URI specified in a default namespace declaration must not be http://www.w3.org/XML/1998/namespace or http://www.w3.org/2000/xmlns/ [err:XQST0070].

    The following kinds of default namespace declarations are supported:

    • A default element namespace declaration declares how unprefixed element and type names are to be interpreted. The relevant value is recorded as the default namespace for elements and types in the static context for the query module. A Prolog may contain at most one default element namespace declaration and it must not contain both a default element namespace declaration and an import schema declaration that specifies a default element namespace [err:XQST0066].

      The URILiteral may take one of the following forms:

      • A namespace URI. This namespace will be used for all unprefixed names appearing where an element or type name is expected.

      • The empty string "". In this case unprefixed names appearing where an element or type name is expected are treated as being in no namespace: the default namespace for elements and types is set to absentDM.

      • The string "##any". In this case an unprefixed name appearing as a NameTest in an axis step whose principal node kind is element is interpreted as a wildcard (the unprefixed name N is treated as equivalent to the wildcard *:N); an unprefixed name used appearing where an item type name is expected is interpreted as a local name in namespace http://www.w3.org/2001/XMLSchema, while an unprefixed name appearing in any other context where an element or type name is expected is treated as being in no namespace.

        Note:

        To take an example, older versions of the internet index of RFCs (requests for comments) use the namespace URI http://www.rfc-editor.org/rfc-index, while newer versions use https://www.rfc-editor.org/rfc-index (note the change of URI scheme). XPath code that needs to work with either version can be simplified by setting the default namespace to ##any: but be aware that this might lead to spurious matching of names in an unrelated namespace.

      The following example illustrates the declaration of a default namespace for elements and types:

      declare default element namespace "http://example.org/names";

      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 C.1 Static Context Components.)

      If the keyword "fixed", is present, the default namespace for elements and types is fixed throughout the module, and is not affected by default namespace declarations (xmlns="") appearing on direct element constructors.

    • A default function namespace declaration declares a namespace URI that is associated with unprefixed function names in static function calls and function declarations.

      A Prolog may contain at most one default function namespace declaration [err:XQST0066]. If the StringLiteral in a default function namespace declaration is a zero-length string, the default function namespace is undeclared (set to absentDM). In that case, any functions that are associated with a namespace can be called only by using an explicit namespace prefix.

      If no default function namespace declaration is present, the default function namespace is the namespace of XPath/XQuery functions, http://www.w3.org/2005/xpath-functions (however, an implementation may define a different default as specified in C.1 Static Context Components.)

      The following example illustrates the declaration of a default function namespace:

      declare default function namespace "http://www.w3.org/2005/xpath-functions/math";

      The effect of declaring a default function namespace is that all functions in the default function namespace, including implicitly declared constructor functions, can be invoked without specifying a namespace prefix. When a static function call uses a function name with no prefix, the local name of the function must match a function (including implicitly declared constructor functions) in the default function namespace [err:XPST0017].

      Note:

      Only constructor functions can be in no namespace.

      The keyword "fixed" has no effect when declaring a default function namespace, since there is no mechanism to change the default function namespace within a query module.

    Unprefixed attribute names and variable names are in no namespace.

    5.15 Annotations

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [211]   InlineFunctionExpr   ::=   Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [29]   AnnotationValue   ::=   StringLiteral | ("-"? NumericLiteral) | ("true" "(" ")") | ("false" "(" ")")
    StringLiteral | ("-"? NumericLiteral) | ("true" "(" ")") | ("false" "(" ")")

    XQuery uses annotations to declare properties associated with functions (inline or declared in the prolog) and variables. For instance, a function may be declared %public or %private. The semantics associated with these properties are described in 5.18 Function Declarations.

    Annotations are (QName, value) pairs. If the EQName of the annotation is a lexical QName, the prefix of the QName is resolved using the statically known namespaces; if no prefix is present, the name is in the http://www.w3.org/2012/xquery namespace.

    Note:

    The default namespace is a reserved namespace, 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 %Q{}inline; however, this is discouraged because it is likely to reduce portability across implementations.

    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 %public and %private. The order of annotations may be significant.

    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 %public and %private.

    A few annotations, such as %public and %private, have rules defined by this specification. Implementations may define further annotations, whose behavior is implementation-defined. For instance, if the eg prefix is bound to a namespace recognized by a particular implementation, then it could be used to define an annotation like eg:sequential. 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 fn:function-annotations function.

    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 reserved namespaces; it is a static error [err:XQST0045] for the name of an annotation to be in a reserved namespace.

    An annotation can provide values explicitly using a parenthesized list of constant values. These values may take any of the following forms:

    • A string literal, for example "Paris" or 'London', denoting a value of type xs:string.

    • A numeric literal, for example 0, 0.1, 0x7FFF, or 1e-6, denoting a value of type xs:decimal, xs:integer, or xs:double. The literal may be preceded by a minus sign to represent a negative number.

    • One of the constructs true() or false(), denoting the xs:boolean values true and false respectively.

    For example, the annotation %java:method("java.lang.Math.sin") sets the value of the java:method annotation to the string value java.lang.Math.sin. An implementation might define such annotations to facilitate calling external functions.

    Note:

    The constructs true() and false() 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.

    5.16 Variable Declaration

    Changes in 4.0  

    1. 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.   [Issue 189 PR 254 29 November 2022]

    2. In earlier versions, the static context for the initializing expression excluded the variable being declared. This restriction has been lifted.   [Issue 1379 PR 1432 12 September 2024]

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [30]   VarDecl   ::=   "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    [58]   VarNameAndType   ::=   "$" EQNameTypeDeclaration?
    "$" EQNameTypeDeclaration?
    [57]   VarName   ::=   "$" EQName
    "$" EQName
    [227]   TypeDeclaration   ::=   "as" SequenceType
    "as" SequenceType
    [31]   VarValue   ::=   ExprSingle
    ExprSingle
    [32]   VarDefaultValue   ::=   ExprSingle
    ExprSingle

    [Definition: A variable declaration in the XQuery prolog defines the name and static type of a variable, and optionally a value for the variable. It adds to the in-scope variables in the static context, and may also add to the variable values in the dynamic context.]

    Note:

    The term variable declaration 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 variable binding, and does not make the variable visible to an importing module.

    During static analysis, a variable declaration causes a pair (expanded QName N, type T) to be added to the in-scope variables. The expanded QName N is the VarName. If N is equal (as defined by the eq operator) to the expanded QName of another variable in in-scope variables, a static error is raised [err:XQST0049]. The type T of the declared variable is as follows:

    • If TypeDeclaration is present, then the SequenceType in the TypeDeclaration; otherwise

    • Otherwise, item()*.

    All variable names declared in a library module must (when expanded) be in the target namespace of the library module [err:XQST0048]. A variable declaration may use annotations to specify that the variable is %private or %public (which is the default). [Definition: A private variable is a variable with a %private annotation. A private variable is hidden from module import, which can not import it into the in-scope variables of another module.] [Definition: A public variable is a variable without a %private annotation. A public variable is accessible to module import, which can import it into the in-scope variables of another module. Using %public and %private annotations in a main module is not an error, but it does not affect module imports, since a main module cannot be imported. It is a static error [err:XQST0116] if a variable declaration contains both a %private and a %public annotation, more than one %private annotation, or more than one %public annotation.]

    Variable names that have no namespace prefix are in no namespace. Variable declarations that have no namespace prefix may appear only in a main module.

    Here are some examples of variable declarations:

    • The following declaration specifies both the type and the value of a variable. This declaration causes the type xs:integer to be associated with variable $x in the static context, and the value 7 to be associated with variable $x in the dynamic context.

      declare variable $x as xs:integer := 7;
    • The following declaration specifies a value but not a type. The static type of the variable is inferred from the static type of its value. In this case, the variable $x has a static type of xs:decimal, inferred from its value which is 7.5.

      declare variable $x := 7.5;
    • The following declaration specifies a type but not a value. The keyword external indicates that the value of the variable will be provided by the external environment. At evaluation time, if the variable $x in the dynamic context does not have a value of type xs:integer, a type error is raised.

      declare variable $x as xs:integer external;
    • The following declaration specifies neither a type nor a value. It simply declares that the query depends on the existence of a variable named $x, whose type and value will be provided by the external environment. During query analysis, the type of $x is considered to be item()*. During query evaluation, the dynamic context must include a type and a value for $x, and its value must be compatible with its type.

      declare variable $x external;
    • The following declaration, which might appear in a library module, declares a variable whose name includes a namespace prefix:

      declare variable $sasl:username as xs:string := "jonathan@example.com";
    • This is an example of an external variable declaration that provides a VarDefaultValue:

      declare variable $x as xs:integer external := 47;

    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:

    declare %eg:volatile variable $time as xs:time external;

    [Definition: If a variable declaration includes an expression (VarValue or VarDefaultValue), the expression is called an initializing expression. The static context for an initializing expression includes all functions, variables, and namespaces that are declared or imported anywhere in the Prolog.]

    If a required type is defined, then the value obtained by evaluating the initializing expression is converted to the required type by applying the coercion rules. A type error occurs if this is not possible. In invoking the coercion rules, XPath 1.0 compatibility mode does not apply.

    In a module's dynamic context, a variable value (or the context value) may depend on another variable value (or the context value). [Definition: A variable value (or the context value) depends on another variable value (or the context value) if, during the evaluation of the initializing expression of the former, the latter is accessed through the module context.]

    In the following example, the value of variable $adepends on the value of variable $b because the evaluation of $a's initializing expression accesses the value of $b during the evaluation of local:f().

    declare variable $a := local:f(); 
    +return $node/xx:bing

    Although the namespace prefixes xx and foo differ, both are bound to the namespace URI http://example.org. Since xx:bing and foo:bing have the same local name and the same namespace URI, they match. The output of the above query is as follows.

    <foo:bing xmlns:foo="http://example.org"> Lentils </foo:bing>

    5.14 Default Namespace Declaration

    Changes in 4.0  

    1. The default namespace for elements and types can now be declared to be fixed for a query module, meaning it is unaffected by a namespace declaration appearing on a direct element constructor.   [Issue 65 PR 753 31 October 2023]

    2. The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.   [Issue 296 PR 1181 30 April 2023]

    [26]   DefaultNamespaceDecl   ::=   "declare" "fixed"? "default" ("element" | "function") "namespace" URILiteral
    "declare" "fixed"? "default" ("element" | "function") "namespace" URILiteral

    Default namespace declarations can be used in a Prolog to facilitate the use of unprefixed QNames.

    The namespace URI specified in a default namespace declaration must not be http://www.w3.org/XML/1998/namespace or http://www.w3.org/2000/xmlns/ [err:XQST0070].

    The following kinds of default namespace declarations are supported:

    • A default element namespace declaration declares how unprefixed element and type names are to be interpreted. The relevant value is recorded as the default namespace for elements and types in the static context for the query module. A Prolog may contain at most one default element namespace declaration and it must not contain both a default element namespace declaration and an import schema declaration that specifies a default element namespace [err:XQST0066].

      The URILiteral may take one of the following forms:

      • A namespace URI. This namespace will be used for all unprefixed names appearing where an element or type name is expected.

      • The empty string "". In this case unprefixed names appearing where an element or type name is expected are treated as being in no namespace: the default namespace for elements and types is set to absentDM.

      • The string "##any". In this case an unprefixed name appearing as a NameTest in an axis step whose principal node kind is element is interpreted as a wildcard (the unprefixed name N is treated as equivalent to the wildcard *:N); an unprefixed name used appearing where an item type name is expected is interpreted as a local name in namespace http://www.w3.org/2001/XMLSchema, while an unprefixed name appearing in any other context where an element or type name is expected is treated as being in no namespace.

        Note:

        To take an example, older versions of the internet index of RFCs (requests for comments) use the namespace URI http://www.rfc-editor.org/rfc-index, while newer versions use https://www.rfc-editor.org/rfc-index (note the change of URI scheme). XPath code that needs to work with either version can be simplified by setting the default namespace to ##any: but be aware that this might lead to spurious matching of names in an unrelated namespace.

      The following example illustrates the declaration of a default namespace for elements and types:

      declare default element namespace "http://example.org/names";

      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 C.1 Static Context Components.)

      If the keyword "fixed", is present, the default namespace for elements and types is fixed throughout the module, and is not affected by default namespace declarations (xmlns="") appearing on direct element constructors.

    • A default function namespace declaration declares a namespace URI that is associated with unprefixed function names in static function calls and function declarations.

      A Prolog may contain at most one default function namespace declaration [err:XQST0066]. If the StringLiteral in a default function namespace declaration is a zero-length string, the default function namespace is undeclared (set to absentDM). In that case, any functions that are associated with a namespace can be called only by using an explicit namespace prefix.

      If no default function namespace declaration is present, the default function namespace is the namespace of XPath/XQuery functions, http://www.w3.org/2005/xpath-functions (however, an implementation may define a different default as specified in C.1 Static Context Components.)

      The following example illustrates the declaration of a default function namespace:

      declare default function namespace "http://www.w3.org/2005/xpath-functions/math";

      The effect of declaring a default function namespace is that all functions in the default function namespace, including implicitly declared constructor functions, can be invoked without specifying a namespace prefix. When a static function call uses a function name with no prefix, the local name of the function must match a function (including implicitly declared constructor functions) in the default function namespace [err:XPST0017].

      Note:

      Only constructor functions can be in no namespace.

      The keyword "fixed" has no effect when declaring a default function namespace, since there is no mechanism to change the default function namespace within a query module.

    Unprefixed attribute names and variable names are in no namespace.

    5.15 Annotations

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [211]   InlineFunctionExpr   ::=   Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [29]   AnnotationValue   ::=   StringLiteral | ("-"? NumericLiteral) | ("true" "(" ")") | ("false" "(" ")")
    StringLiteral | ("-"? NumericLiteral) | ("true" "(" ")") | ("false" "(" ")")

    XQuery uses annotations to declare properties associated with functions (inline or declared in the prolog) and variables. For instance, a function may be declared %public or %private. The semantics associated with these properties are described in 5.18 Function Declarations.

    Annotations are (QName, value) pairs. If the EQName of the annotation is a lexical QName, the prefix of the QName is resolved using the statically known namespaces; if no prefix is present, the name is in the http://www.w3.org/2012/xquery namespace.

    Note:

    The default namespace is a reserved namespace, 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 %Q{}inline; however, this is discouraged because it is likely to reduce portability across implementations.

    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 %public and %private. The order of annotations may be significant.

    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 %public and %private.

    A few annotations, such as %public and %private, have rules defined by this specification. Implementations may define further annotations, whose behavior is implementation-defined. For instance, if the eg prefix is bound to a namespace recognized by a particular implementation, then it could be used to define an annotation like eg:sequential. 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 fn:function-annotations function.

    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 reserved namespaces; it is a static error [err:XQST0045] for the name of an annotation to be in a reserved namespace.

    An annotation can provide values explicitly using a parenthesized list of constant values. These values may take any of the following forms:

    • A string literal, for example "Paris" or 'London', denoting a value of type xs:string.

    • A numeric literal, for example 0, 0.1, 0x7FFF, or 1e-6, denoting a value of type xs:decimal, xs:integer, or xs:double. The literal may be preceded by a minus sign to represent a negative number.

    • One of the constructs true() or false(), denoting the xs:boolean values true and false respectively.

    For example, the annotation %java:method("java.lang.Math.sin") sets the value of the java:method annotation to the string value java.lang.Math.sin. An implementation might define such annotations to facilitate calling external functions.

    Note:

    The constructs true() and false() 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.

    5.16 Variable Declaration

    Changes in 4.0  

    1. 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.   [Issue 189 PR 254 29 November 2022]

    2. In earlier versions, the static context for the initializing expression excluded the variable being declared. This restriction has been lifted.   [Issue 1379 PR 1432 12 September 2024]

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [30]   VarDecl   ::=   "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    [58]   VarNameAndType   ::=   "$" EQNameTypeDeclaration?
    "$" EQNameTypeDeclaration?
    [57]   VarName   ::=   "$" EQName
    "$" EQName
    [227]   TypeDeclaration   ::=   "as" SequenceType
    "as" SequenceType
    [31]   VarValue   ::=   ExprSingle
    ExprSingle
    [32]   VarDefaultValue   ::=   ExprSingle
    ExprSingle

    [Definition: A variable declaration in the XQuery prolog defines the name and static type of a variable, and optionally a value for the variable. It adds to the in-scope variables in the static context, and may also add to the variable values in the dynamic context.]

    Note:

    The term variable declaration 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 variable binding, and does not make the variable visible to an importing module.

    During static analysis, a variable declaration causes a pair (expanded QName N, type T) to be added to the in-scope variables. The expanded QName N is the VarName. If N is equal (as defined by the eq operator) to the expanded QName of another variable in in-scope variables, a static error is raised [err:XQST0049]. The type T of the declared variable is as follows:

    • If TypeDeclaration is present, then the SequenceType in the TypeDeclaration; otherwise

    • Otherwise, item()*.

    All variable names declared in a library module must (when expanded) be in the target namespace of the library module [err:XQST0048]. A variable declaration may use annotations to specify that the variable is %private or %public (which is the default). [Definition: A private variable is a variable with a %private annotation. A private variable is hidden from module import, which can not import it into the in-scope variables of another module.] [Definition: A public variable is a variable without a %private annotation. A public variable is accessible to module import, which can import it into the in-scope variables of another module. Using %public and %private annotations in a main module is not an error, but it does not affect module imports, since a main module cannot be imported. It is a static error [err:XQST0116] if a variable declaration contains both a %private and a %public annotation, more than one %private annotation, or more than one %public annotation.]

    Variable names that have no namespace prefix are in no namespace. Variable declarations that have no namespace prefix may appear only in a main module.

    Here are some examples of variable declarations:

    • The following declaration specifies both the type and the value of a variable. This declaration causes the type xs:integer to be associated with variable $x in the static context, and the value 7 to be associated with variable $x in the dynamic context.

      declare variable $x as xs:integer := 7;
    • The following declaration specifies a value but not a type. The static type of the variable is inferred from the static type of its value. In this case, the variable $x has a static type of xs:decimal, inferred from its value which is 7.5.

      declare variable $x := 7.5;
    • The following declaration specifies a type but not a value. The keyword external indicates that the value of the variable will be provided by the external environment. At evaluation time, if the variable $x in the dynamic context does not have a value of type xs:integer, a type error is raised.

      declare variable $x as xs:integer external;
    • The following declaration specifies neither a type nor a value. It simply declares that the query depends on the existence of a variable named $x, whose type and value will be provided by the external environment. During query analysis, the type of $x is considered to be item()*. During query evaluation, the dynamic context must include a type and a value for $x, and its value must be compatible with its type.

      declare variable $x external;
    • The following declaration, which might appear in a library module, declares a variable whose name includes a namespace prefix:

      declare variable $sasl:username as xs:string := "jonathan@example.com";
    • This is an example of an external variable declaration that provides a VarDefaultValue:

      declare variable $x as xs:integer external := 47;

    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:

    declare %eg:volatile variable $time as xs:time external;

    [Definition: If a variable declaration includes an expression (VarValue or VarDefaultValue), the expression is called an initializing expression. The static context for an initializing expression includes all functions, variables, and namespaces that are declared or imported anywhere in the Prolog.]

    If a required type is defined, then the value obtained by evaluating the initializing expression is converted to the required type by applying the coercion rules. A type error occurs if this is not possible. In invoking the coercion rules, XPath 1.0 compatibility mode does not apply.

    In a module's dynamic context, a variable value (or the context value) may depend on another variable value (or the context value). [Definition: A variable value (or the context value) depends on another variable value (or the context value) if, during the evaluation of the initializing expression of the former, the latter is accessed through the module context.]

    In the following example, the value of variable $adepends on the value of variable $b because the evaluation of $a's initializing expression accesses the value of $b during the evaluation of local:f().

    declare variable $a := local:f(); 
     declare variable $b := 1;
     declare function local:f() { $b };

    A directed graph can be built with all variable values and the context value as nodes, and with the depend on 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 [err:XQDY0054] must be raised.

    During query evaluation, each variable declaration causes a pair (expanded QName N, value V) to be added to the variable values. The expanded QName N is the VarName. The value V is as follows:

    • If VarValue is specified, then V is the result of evaluating VarValue.

    • If external is specified, then:

      • if a value is provided for the variable by the external environment, then V is that value. The means by which typed values of external variables are provided by the external environment is implementation-defined.

      • if no value is provided for the variable by the external environment, and VarDefaultValue is specified, then V is the result of evaluating VarDefaultValue.

      • If no value is provided for the variable by the external environment, and VarDefaultValue is not specified, then a dynamic error is raised [err:XPDY0002].

        It is implementation-dependent whether this error is raised if the evaluation of the query does not reference the value of the variable.

    In all cases the value V must match the type T according to the rules for SequenceType matching; otherwise a type error is raised [err:XPTY0004].

    5.17 Context Value Declaration

    Changes in 4.0  

    1. 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.   [Issue 129 PR 368 21 July 2023]

    [33]   ContextValueDecl   ::=   "declare" "context" (("value" ("as" SequenceType)?) | ("item" ("as" ItemType)?)) ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    "declare" "context" (("value" ("as" SequenceType)?) | ("item" ("as" ItemType)?)) ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))

    A context value declaration allows a query to specify the static type, value, or default value for the initial context value.

    Only the main module can set the initial context value. In a library module, a context value declaration must be external, and specifies only the static type. Specifying a VarValue or VarDefaultValue for a context value declaration in a library module is a static error [err:XQST0113].

    The form declare context value allows the initial context value to set to any value, with any sequence type. The alternative form declare context item 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.

    In every module that does not contain a context value declaration, the effect is as if the declaration

    declare context value as item()* external;

    appeared in that module.

    The context value declaration has the effect of setting the context value static type T in the static context. When the form declare context value is used, the default type is item()*. When the alternative form declare context item is used, the default type is item().

    If a module contains more than one context value declaration, a static error is raised [err:XQST0099].

    The static context for an initializing expression includes all functions, variables, and namespaces that are declared or imported anywhere in the Prolog.

    During query evaluation, a fixed focus is created in the dynamic context for the evaluation of the QueryBody 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 initial context value, which is selected as follows:

    • If VarValue is specified, then the initial context value is the result of evaluating VarValue.

      Note:

      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.

    • If external is specified, then:

      • 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.

        Note:

        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.

        The means by which an external value is provided by the external environment is implementation-defined.

      • If no value is provided for the context value by the external environment, and VarDefaultValue is specified, then the initial context value is the result of evaluating VarDefaultValue as described below.

    In all cases where the context value has a value, that value must match the type T according to the rules for SequenceType matching; otherwise a type error is raised [err:XPTY0004]. If more than one module contains a context value declaration, the context value must match the type declared in each one.

    If VarValue or VarDefaultValue is evaluated, the static and dynamic contexts for the evaluation are the current module's static and dynamic context.

    If a required type is defined, then the value obtained by evaluating VarValue or VarDefaultValue is converted to the required type by applying the coercion rules. A type error occurs if this is not possible. In invoking the coercion rules, XPath 1.0 compatibility mode does not apply.

    Here are some examples of context value declarations.

    • Declare the type of the context value as a single element item with a required element name:

      declare namespace env = "http://www.w3.org/2003/05/soap-envelope"; 
       declare context item as element(env:Envelope) external;
    • 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:

      declare context value as element(sys:log) external :=
         doc("/var/xlogs/sysevent.xml")/sys:log;
    • 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:

      declare variable $uri as xs:string external;
      -declare context value as document-node()* := collection($uri);

      With this declaration, a query body such as //person[name="Mandela"] returns all matching person elements appearing in any document in the collection.

    5.18 Function Declarations

    Changes in 4.0  

    1. Function definitions in the static context may now have optional parameters, provided this does not cause ambiguity across multiple function definitions with the same name. Optional parameters are given a default value, which can be any expression, including one that depends on the context of the caller (so an argument can default to the context value).

    In addition to the system functions, XQuery allows users to declare functions of their own. A function declaration declares a family of functions having the same name and similar parameters. The declaration specifies the name of the function, the names and datatypes of the parameters, and the datatype of the result. All datatypes are specified using the syntax described in 3 Types.

    Including a function declaration in the query causes a corresponding function definition to be added to the statically known function definitions of the static context. The associated functions also become available in the dynamically known function definitions of the dynamic context.

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [34]   FunctionDecl   ::=   "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")/* xgc: reserved-function-names */
    "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")/* xgc: reserved-function-names */
    /* xgc: reserved-function-names */
    [36]   ParamListWithDefaults   ::=   (ParamWithDefault ++ ",")
    (ParamWithDefault ++ ",")
    [37]   ParamWithDefault   ::=   VarNameAndType (":=" ExprSingle)?
    VarNameAndType (":=" ExprSingle)?
    [39]   FunctionBody   ::=   EnclosedExpr
    EnclosedExpr
    [227]   TypeDeclaration   ::=   "as" SequenceType
    "as" SequenceType
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    A function declaration specifies whether the implementation of the function is user-defined or external.

    In addition to user-defined functions and external functions, XQuery 4.0 and XPath 4.0 allows anonymous functions to be declared in the body of a query using inline function expressions.

    The following example illustrates the declaration and use of a local function that accepts a sequence of employee elements, summarizes them by department, and returns a sequence of dept elements.

    Example: Using a function, prepare a summary of employees that are located in Denver.
    declare function local:summary($emps as element(employee)*) as element(dept)* { 
    +declare context value as document-node()* := collection($uri);

    With this declaration, a query body such as //person[name="Mandela"] returns all matching person elements appearing in any document in the collection.

    5.18 Function Declarations

    Changes in 4.0  

    1. Function definitions in the static context may now have optional parameters, provided this does not cause ambiguity across multiple function definitions with the same name. Optional parameters are given a default value, which can be any expression, including one that depends on the context of the caller (so an argument can default to the context value).

    In addition to the system functions, XQuery allows users to declare functions of their own. A function declaration declares a family of functions having the same name and similar parameters. The declaration specifies the name of the function, the names and datatypes of the parameters, and the datatype of the result. All datatypes are specified using the syntax described in 3 Types.

    Including a function declaration in the query causes a corresponding function definition to be added to the statically known function definitions of the static context. The associated functions also become available in the dynamically known function definitions of the dynamic context.

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [34]   FunctionDecl   ::=   "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")/* xgc: reserved-function-names */
    "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")/* xgc: reserved-function-names */
    /* xgc: reserved-function-names */
    [36]   ParamListWithDefaults   ::=   (ParamWithDefault ++ ",")
    (ParamWithDefault ++ ",")
    [37]   ParamWithDefault   ::=   VarNameAndType (":=" ExprSingle)?
    VarNameAndType (":=" ExprSingle)?
    [39]   FunctionBody   ::=   EnclosedExpr
    EnclosedExpr
    [227]   TypeDeclaration   ::=   "as" SequenceType
    "as" SequenceType
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    A function declaration specifies whether the implementation of the function is user-defined or external.

    In addition to user-defined functions and external functions, XQuery 4.0 and XPath 4.0 allows anonymous functions to be declared in the body of a query using inline function expressions.

    The following example illustrates the declaration and use of a local function that accepts a sequence of employee elements, summarizes them by department, and returns a sequence of dept elements.

    Example: Using a function, prepare a summary of employees that are located in Denver.
    declare function local:summary($emps as element(employee)*) as element(dept)* { 
       for $no in distinct-values($emps/deptno) 
       let $emp := $emps[deptno = $no]
       return <dept> 
    @@ -868,7 +868,7 @@
     };
     local:summary(doc("acme_corp.xml")//employee[location = "Denver"])

    5.18.1 User-Defined Functions

    [Definition: User defined functions are functions that contain a function body, which provides the implementation of the function as a content expression.] The static context for a function body includes all functions, variables, and namespaces that are declared or imported anywhere in the Prolog, including the function being declared. Its in-scope variables component also includes the parameters of the function being declared.

    An implementation should raise a static error [err:XPST0008] if the function body depends on the context value.

    The properties of the function definitionF are derived from the syntax of the function declaration as follows:

    • The name of F is the expanded QName obtained by expanding the EQName that follows the keyword function.

    • The parameters of F are derived from the ParamWithDefault entries in the ParamListWithDefaults:

      • The parameter name is the expanded QName obtained by expanding the EQName that follows the $ symbol.

      • The required type of the parameter is given by the TypeDeclaration, defaulting to item()*.

      • The default value of the parameter is given by the expression that follows the := symbol; if there is no default value, then the parameter is a required parameter.

    • The return type of the function is given by the final TypeDeclaration that follows the ParamListWithDefaults if present, defaulting to item()*.

    • The function annotations are derived from the annotations that follow the % symbol, if present.

    • The implementation of the function is given by the enclosed expression.

    The static context may include more than one declared function with the same name, but their arity ranges must not overlap [err:XQST0034].

    Note:

    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.

    5.18.2 Function Names

    Every declared function must be in a namespace; that is, every declared function name must (when expanded) have a non-null namespace URI [err:XQST0060]. If the function name in a function declaration has no namespace prefix, it is considered to be in the default function namespace. Every function name declared in a library module must (when expanded) be in the target namespace of the library module [err:XQST0048].

    [Definition: A reserved namespace is a namespace that must not be used in the name of a function declaration.] It is a static error [err:XQST0045] if the function name in a function declaration (when expanded) is in a reserved namespace. The following namespaces are reserved namespaces:

    • http://www.w3.org/XML/1998/namespace

    • http://www.w3.org/2001/XMLSchema

    • http://www.w3.org/2001/XMLSchema-instance

    • http://www.w3.org/2005/xpath-functions

    • http://www.w3.org/2005/xpath-functions/array

    • http://www.w3.org/2005/xpath-functions/map

    • http://www.w3.org/2005/xpath-functions/math

    • http://www.w3.org/2012/xquery

    In order to allow main modules to declare functions for local use within the module without defining a new namespace, XQuery predefines the namespace prefix local to the namespace http://www.w3.org/2005/xquery-local-functions. It is suggested (but not required) that this namespace be used for defining local functions.

    5.18.3 Function Parameters

    The function declaration includes a list of zero or more function parameters.

    The parameters of a function declaration are considered to be variables whose scope is the function body. It is an static error [err:XQST0039] 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 sequence type.

    If a function parameter is declared using a name but no type, its default type is item()*. If the result type is omitted from a function declaration, its default result type is item()*.

    The function body defines the implementation of the function definition. The rules for static function calls (see 4.5.1.2 Evaluating Static Function Calls) 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.

    A parameter is optional if a default value is supplied using the construct := ExprSingle; otherwise it is required. If a parameter is optional, then all subsequent parameters in the list must also be optional; otherwise, a static error is raised [err:XQST0148]. In other words, the parameter list includes zero or more required parameters followed by zero or more optional parameters.

    The number of arguments that may be supplied in a call to this family of functions is thus in the range M to N, where M is the number of required parameters, and N is the total number of parameters (whether required or optional). This is refered to as the arity range of the function definition.

    The default value for an optional parameter will often be supplied using a simple literal or constant expression, for example $married as xs:boolean := false() or $options as map(*) := { }. However, to allow greater flexibility, the initial value can also be context-dependent. For example, $node as node() := . declares a parameter whose default value is the context value from the dynamic context of the caller, while $collation as xs:string := default-collation() 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 caller means the function call or function reference that invokes the function being defined.

    The static context for the initializing expression of an optional parameter is the same as the static context for the initializing expression of a variable declaration (see 5.16 Variable Declaration), with the following exceptions:

    • The in-scope variables 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.

    • The statically known function definitions excludes all user-defined functions.

    The dynamic context for the initializing expression of an optional parameter is the same as the dynamic context of the caller, with the following exceptions:

    5.18.4 Function Annotations

    Changes in 4.0  

    1. The values true() and false() are allowed in function annotations, and negated numeric literals are also allowed.   [Issue 637 PR 682 12 September 2023]

    A function declaration may use the %private or %public annotations to specify that a function is public or private; if neither of these annotations is used, the function is public. [Definition: A private function is a function with a %private annotation. A private function is hidden from module import, which can not import it into the statically known function definitions of another module. ] [Definition: A public function is a function without a %private annotation. A public function is accessible to module import, which can import it into the statically known function definitions of another module. ] Using %public and %private annotations in a main module is not an error, but it does not affect module imports, since a main module cannot be imported. It is a static error [err:XQST0106] if a function declaration contains both a %private and a %public annotation, more than one %private annotation, or more than one %public annotation.

    An implementation can define annotations, in its own namespace, to support functionality beyond the scope of this specification. For instance, an implementation that supports external Java functions might use an annotation to associate a Java function with an XQuery external function:

    declare 
       %java:method("java.lang.StrictMath.copySign") 
    -function smath:copySign($magnitude, $sign) external;

    5.18.5 External Functions

    In function declarations, external functions are identified by the keyword external. 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.

    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 implementation-defined. An XQuery implementation may augment the type system of [XQuery and XPath Data Model (XDM) 4.0] 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 xs:anyAtomicType.

    5.18.6 Recursion

    A function declaration may be recursive—that is, it may reference itself. Mutually recursive functions, whose bodies reference each other, are also allowed.

    Example: A recursive function to compute the maximum depth of a document

    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 local:depth calls the built-in functions empty and max, which are in the default function namespace.

    declare function local:depth($e as node()) as xs:integer {
    +function smath:copySign($magnitude, $sign) external;

    5.18.5 External Functions

    In function declarations, external functions are identified by the keyword external. 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.

    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 implementation-defined. An XQuery implementation may augment the type system of [XQuery and XPath Data Model (XDM) 4.0] 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 xs:anyAtomicType.

    5.18.6 Recursion

    A function declaration may be recursive—that is, it may reference itself. Mutually recursive functions, whose bodies reference each other, are also allowed.

    Example: A recursive function to compute the maximum depth of a document

    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 local:depth calls the built-in functions empty and max, which are in the default function namespace.

    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/*)) 
    @@ -876,7 +876,7 @@
       else max(for $c in $e/* return local:depth($c)) + 1
     };
     
    -local:depth(doc("partlist.xml"))

    [TODO: add an example of a function with an optional parameter.]

    5.19 Item Type Declarations

    An item type declaration defines a name for an item type. Defining a name for an item type allows it to be referenced by name rather than repeating the item type designator in full.

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [41]   ItemTypeDecl   ::=   "type" EQName "as" ItemType
    "type" EQName "as" ItemType

    An item type declaration adds a named item type to the in-scope named item types of the containing module. This enables the item type to be referred to using a simple name.

    For example, given the declaration:

    declare type app:invoice as map("xs:string", element(inv:paid-invoice));

    It becomes possible to declare a variable containing a sequence of such items as:

    declare variable $invoices as app:invoice*;

    The definition can also be used within another item type declaration:

    declare type app:overdue-invoices as map("xs:date", app:invoice*);

    If the name of the item type being declared is written as an (unprefixed) NCName, then it is interpreted as being in the default namespace for elements and types.

    An item type declaration may use the %private or %public annotations to specify that an item type name is public or private; if neither of these annotations is used, the declaration is public.

    The declaration of an item type (whether locally declared in a module or imported from a public declaration in an imported module) must precede any use of the item type name: that is, the name only becomes available in the static context of constructs that lexically follow the relevant item type declaration or module import. A consequence of this rule is that cyclic and self-referential definitions are not allowed.

    The name of an item type must be unique among the names of all declared item types and generalized atomic types in the static context of the query module. [err:XQST0146]

    Note:

    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 reference is encountered during query parsing. There is never any need to retain item type names at execution time except optionally for diagnostics.

    Note:

    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 %private). 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.

    5.20 Named Record Types

    Although item type declarations, as described in 5.19 Item Type Declarations, can be used to give names to record types as well as any other item type, named record types as described in this section provide a more concise syntax, plus additional functionality. In particular:

    • Named record types can be recursive.

    • Named record types implicitly create a constructor function that can be used to create instances of the record type.

    • A field in a named record type can be a function that has implicit access to the record on which it is defined, rather like methods in object-oriented languages.

    The syntax is as follows:

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [42]   NamedRecordTypeDecl   ::=   "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    [43]   ExtendedFieldDeclaration   ::=   FieldDeclaration (":=" ExprSingle)?
    FieldDeclaration (":=" ExprSingle)?
    [256]   FieldDeclaration   ::=   FieldName "?"? ("as" SequenceType)?
    FieldName "?"? ("as" SequenceType)?
    [257]   FieldName   ::=   NCName | StringLiteral
    NCName | StringLiteral

    A named record declaration serves as both a named item type and as a function definition, and it therefore inherits rules from both these roles. In particular:

    1. Its name must not be the same as the name of any other named item type, or any generalized atomic type, that is present in the same static context [err:XQST0048].

    2. If the declaration appears within a library module then its name must be in the target namespace of the library module [err:XQST0048].

    3. 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.

    4. The order of field declarations is significant, because it determines the order of arguments in a call to the constructor function.

    5. The fields must have distinct names. [err:XPST0021]

    6. In order to work as both a record type and a function declaration, the names of the fields must be simple NCNames in no namespace; the names must not be written as string literals [err:XPST0003].

      Note:

      This is described here as a semantic constraint, but an implementation might choose to impose it at the level of the grammar.

    7. If an initializing expression is present in an ExtendedFieldDeclaration, it must follow the rules for the initializing expression of a parameter in a function declaration, given in 5.18.3 Function Parameters. In particular, if any field has an initializing expression then all following fields must have an initializing expression.

    8. Any annotations that are present, such as %public or %private, apply both to the item type declaration and to the function declaration.

    5.20.1 Named Records as Item Types

    As a named item type declaration, the construct:

    declare record cx:complex(r as xs:double, i as xs:double := 0);

    is equivalent to:

    declare type cx:complex as record(r as xs:double, i as xs:double);

    Any initializing expressions for fields are ignored for this purpose.

    Note:

    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.

    There is however one significant difference: 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.

    Note:

    Unlike a named item type declared using declare type, a reference to a named record type cannot (in general) be directly replaced by the corresponding record definition during parsing. This is not only because forwards references are allowed; it is also because a recursive record type cannot be expressed using the usual RecordType syntax.

    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 implausible, which means that a processor may treat it as an error but is not obliged to do so [err:XPST0023].

    5.20.2 Constructor Functions for Named Record Types

    The construct:

    declare record cx:complex(r as xs:double, i as xs:double := 0);

    implicitly defines the function:

    declare function cx:complex($r as xs:double, $i as xs:double := 0) as cx:complex {
    +local:depth(doc("partlist.xml"))

    [TODO: add an example of a function with an optional parameter.]

    5.19 Item Type Declarations

    An item type declaration defines a name for an item type. Defining a name for an item type allows it to be referenced by name rather than repeating the item type designator in full.

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [41]   ItemTypeDecl   ::=   "type" EQName "as" ItemType
    "type" EQName "as" ItemType

    An item type declaration adds a named item type to the in-scope named item types of the containing module. This enables the item type to be referred to using a simple name.

    For example, given the declaration:

    declare type app:invoice as map("xs:string", element(inv:paid-invoice));

    It becomes possible to declare a variable containing a sequence of such items as:

    declare variable $invoices as app:invoice*;

    The definition can also be used within another item type declaration:

    declare type app:overdue-invoices as map("xs:date", app:invoice*);

    If the name of the item type being declared is written as an (unprefixed) NCName, then it is interpreted as being in the default namespace for elements and types.

    An item type declaration may use the %private or %public annotations to specify that an item type name is public or private; if neither of these annotations is used, the declaration is public.

    The declaration of an item type (whether locally declared in a module or imported from a public declaration in an imported module) must precede any use of the item type name: that is, the name only becomes available in the static context of constructs that lexically follow the relevant item type declaration or module import. A consequence of this rule is that cyclic and self-referential definitions are not allowed.

    The name of an item type must be unique among the names of all declared item types and generalized atomic types in the static context of the query module. [err:XQST0146]

    Note:

    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 reference is encountered during query parsing. There is never any need to retain item type names at execution time except optionally for diagnostics.

    Note:

    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 %private). 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.

    5.20 Named Record Types

    Although item type declarations, as described in 5.19 Item Type Declarations, can be used to give names to record types as well as any other item type, named record types as described in this section provide a more concise syntax, plus additional functionality. In particular:

    • Named record types can be recursive.

    • Named record types implicitly create a constructor function that can be used to create instances of the record type.

    • A field in a named record type can be a function that has implicit access to the record on which it is defined, rather like methods in object-oriented languages.

    The syntax is as follows:

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [42]   NamedRecordTypeDecl   ::=   "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    [43]   ExtendedFieldDeclaration   ::=   FieldDeclaration (":=" ExprSingle)?
    FieldDeclaration (":=" ExprSingle)?
    [256]   FieldDeclaration   ::=   FieldName "?"? ("as" SequenceType)?
    FieldName "?"? ("as" SequenceType)?
    [257]   FieldName   ::=   NCName | StringLiteral
    NCName | StringLiteral

    A named record declaration serves as both a named item type and as a function definition, and it therefore inherits rules from both these roles. In particular:

    1. Its name must not be the same as the name of any other named item type, or any generalized atomic type, that is present in the same static context [err:XQST0048].

    2. If the declaration appears within a library module then its name must be in the target namespace of the library module [err:XQST0048].

    3. 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.

    4. The order of field declarations is significant, because it determines the order of arguments in a call to the constructor function.

    5. The fields must have distinct names. [err:XPST0021]

    6. In order to work as both a record type and a function declaration, the names of the fields must be simple NCNames in no namespace; the names must not be written as string literals [err:XPST0003].

      Note:

      This is described here as a semantic constraint, but an implementation might choose to impose it at the level of the grammar.

    7. If an initializing expression is present in an ExtendedFieldDeclaration, it must follow the rules for the initializing expression of a parameter in a function declaration, given in 5.18.3 Function Parameters. In particular, if any field has an initializing expression then all following fields must have an initializing expression.

    8. Any annotations that are present, such as %public or %private, apply both to the item type declaration and to the function declaration.

    5.20.1 Named Records as Item Types

    As a named item type declaration, the construct:

    declare record cx:complex(r as xs:double, i as xs:double := 0);

    is equivalent to:

    declare type cx:complex as record(r as xs:double, i as xs:double);

    Any initializing expressions for fields are ignored for this purpose.

    Note:

    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.

    There is however one significant difference: 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.

    Note:

    Unlike a named item type declared using declare type, a reference to a named record type cannot (in general) be directly replaced by the corresponding record definition during parsing. This is not only because forwards references are allowed; it is also because a recursive record type cannot be expressed using the usual RecordType syntax.

    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 implausible, which means that a processor may treat it as an error but is not obliged to do so [err:XPST0023].

    5.20.2 Constructor Functions for Named Record Types

    The construct:

    declare record cx:complex(r as xs:double, i as xs:double := 0);

    implicitly defines the function:

    declare function cx:complex($r as xs:double, $i as xs:double := 0) as cx:complex {
       map:merge((
         { "r": $r },
         { "i": $i }
    @@ -930,4 +930,4 @@
     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";

    An output declaration may appear only in a main module; it is a static error [err:XQST0108] if an output declaration appears in a library module. It is a static error [err:XQST0110] if the same serialization parameter is declared more than once. It is a static error [err:XQST0109] if the local name of an output declaration in the http://www.w3.org/2010/xslt-xquery-serialization namespace is not one of the serialization parameter names listed in C.1 Static Context Components or parameter-document, or if the name of an output declaration is use-character-maps. The default value for the method parameter is "xml". An implementation may define additional implementation-defined serialization parameters in its own namespaces.

    If the local name of an output declaration in the http://www.w3.org/2010/xslt-xquery-serialization namespace is parameter-document, 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 [err:XQST0119] if the implementation is not able to process the value of the output:parameter-document declaration to produce an XDM instance.

    If a processor is performing serialization, the XDM instance identified by an output:parameter-document output declaration specifies the values of serialization parameters in the manner defined by Section 3.1 Setting Serialization Parameters by Means of a Parameter DocumentSE. It is a static error [err:XQST0115] 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 http://www.w3.org/2010/xslt-xquery-serialization namespace with the local name parameter-document declaration.

    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.

    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.

    A processor that is not performing serialization may report errors if any serialization parameters are incorrect, or may ignore such parameters.

    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.

    Note:

    The data model permits an element node to have fewer in-scope namespaces than its parent. Correct serialization of such an element node would require “undeclaration” of namespaces, which is a feature of [XML Names 1.1]. An implementation that does not support [XML Names 1.1] 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.

    5.22.1 Serialization Parameters

    ComponentDefault initial value
    allow-duplicate-namesno
    byte-order-markimplementation-defined
    cdata-section-elementsempty
    doctype-publicnone
    doctype-systemnone
    encodingimplementation-defined choice between "utf-8" and "utf-16"
    escape-solidusyes
    escape-uri-attributesyes
    html-versionimplementation-defined
    include-content-typeyes
    indentno
    item-separatorimplementation-defined
    json-node-output-methodxml
    media-typeimplementation-defined
    methodxml
    normalization-formimplementation-defined
    omit-xml-declarationimplementation-defined
    standaloneimplementation-defined
    suppress-indentationempty
    undeclare-prefixesno
    use-character-mapsempty
    versionimplementation-defined

    6 Conformance

    Changes in 4.0  

    1. Support for higher-order functions is now a mandatory feature (in 3.1 it was optional).   [Issue 205 PR 326 1 February 2023]

    2. The static typing feature has been dropped.   [Issue 1343 ]

    This section defines the conformance criteria for an XQuery 4.0 and XPath 4.0 processor. In this section, the following terms are used to indicate the requirement levels defined in [RFC2119]. [Definition: MUST means that the item is an absolute requirement of the specification.] [Definition: MUST NOT means that the item is an absolute prohibition of the specification.] [Definition: MAY means that an item is truly optional.] [Definition: SHOULD means that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.]

    XPath is intended primarily as a component that can be used by other specifications. Therefore, XPath relies on specifications that use it (such as [XPointer] and [XSL Transformations (XSLT) Version 4.0]) to specify conformance criteria for XPath in their respective environments. Specifications that set conformance criteria for their use of XPath MUST NOT change the syntactic or semantic definitions of XPath as given in this specification, except by subsetting and/or compatible extensions.

    If a language is described as an extension of XPath, then every expression that conforms to the XPath grammar MUST behave as described in this specification.

    An XQuery processor that claims to conform to this specification MUST include a claim of Minimal Conformance as defined in 6.1 Minimal Conformance. In addition to a claim of Minimal Conformance, it MAY claim conformance to one or more optional features defined in 6.2 Optional Features.

    6.1 Minimal Conformance

    An implementation that claims Minimal Conformance to this specification MUST provide all of the following items:

    1. An implementation of everything specified in this document except those features specified in 6.2 Optional Features to be optional. If an implementation does not provide a given optional feature, it MUST implement any requirements specified in 6.2 Optional Features for implementations that do not provide that feature.

    2. A definition of every item specified to be implementation-defined, unless that item is part of an optional feature that is not provided by the implementation. A list of implementation-defined items can be found in E Implementation-Defined Items.

      Note:

      Implementations are not required to define items specified to be implementation-dependent.

    3. An implementation of [XQuery and XPath Data Model (XDM) 4.0], as specified in 6.3 Data Model Conformance, and a definition of every item specified to be implementation-defined, unless that item is part of an optional feature that is not provided by the implementation.

    4. An implementation of all functions defined in [XQuery and XPath Functions and Operators 4.0], and a definition of every item specified to be implementation-defined, unless that function or item is part of an optional feature that is not provided by the implementation.

    6.2 Optional Features

    The features discussed in this section are optional. An implementation MAY claim conformance to one or more of these features.

    The description of each feature mentions any errors that occur if a query relies on a feature that is not present.

    6.2.1 Schema Aware Feature

    [Definition: The Schema Aware Feature permits the query Prolog to contain a schema import, and permits a query to contain a validate expression (see 4.24 Validate Expressions). ]

    If an XQuery implementation does not provide the Schema Aware Feature, it MUST raise a static error [err:XQST0009] if it encounters a schema import, and it MUST raise a static error [err:XQST0075] if it encounters a validate expression.

    If an implementation provides the Schema Aware Feature, it MUST also provide the 6.2.2 Typed Data Feature.

    6.2.2 Typed Data Feature

    [Definition: The Typed Data Feature permits an XDM instance to contain element node types other than xs:untyped and attributes node types other than xs:untypedAtomic.]

    If an XQuery implementation does not provide the Typed Data Feature, it MUST guarantee that:

    1. The XDM has the type xs:untyped for every element node and xs:untypedAtomic for every attribute node, including nodes created by the query.

    2. Elements constructed by the query always have the type xs:untyped; attributes constructed by the query always have the type xs:untypedAtomic. (This is equivalent to using construction mode = strip.)

    6.2.3 Module Feature

    [Definition: The Module Feature allows a query Prolog to contain a Module Import and allows library modules to be created.]

    An implementation that does not provide the Module Feature MUST raise a static error [err:XQST0016] if it encounters a module declaration or a module import. Since a module declaration is required in a library module, the Module Feature is required in order to create a library module.

    Note:

    In the absence of the Module Feature, each query consists of a single main module.

    6.2.4 Serialization Feature

    [Definition: The Serialization Feature provides means for serializing the result of a query as specified in 2.3.5 Serialization.] A conforming XQuery implementation that provides the Serialization Feature MUST conform to 2.3.5 Serialization. An implementation MAY provide other forms of serialization, which do not conform to the Serialization Feature, and are beyond the scope of this specification.

    The means by which serialization is invoked is implementation-defined.

    If an error is raised during the serialization process as specified in [XSLT and XQuery Serialization 4.0], an implementation MUST report the error to the calling environment.

    An implementation that does not provide the Serialization Feature MUST NOT raise errors when reading an output declaration, and MUST implement fn:serialize; it MAY, however, raise an error when fn:serialize is invoked, as specified in Section 14.1.3 fn:serializeFO. An implementation that does not provide the Serialization Feature MAY provide results of a query using a vendor-defined serialization.

    Note:

    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.

    6.3 Data Model Conformance

    All XQuery implementations process data represented in the data model as specified in [XQuery and XPath Data Model (XDM) 4.0]. 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:

    1. Support for normative construction from an infoset. An implementation MAY choose to claim conformance to Section 3.2 Construction from an InfosetDM, which defines a normative way to construct an XDM instance from an XML document that is merely well-formed or is governed by a DTD.

    2. Support for normative construction from a PSVI. An implementation MAY choose to claim conformance to Section 3.3 Construction from a PSVIDM, which defines a normative way to construct an XDM instance from an XML document that is governed by a W3C XML Schema.

    3. Support for versions of XML and XSD. As stated in [XQuery and XPath Data Model (XDM) 4.0], the definitions of primitives such as strings, characters, and names SHOULD 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.

      Note:

      For suggestions on processing XML 1.1 documents with XSD 1.0, see [XML 1.1 and Schema 1.0].

    4. Ranges of data values. In XQuery, the following limits are implementation-defined:

      1. For the xs:decimal type, the maximum number of decimal digits (totalDigits facet) MUST be at least 18. This limit SHOULD be at least 20 digits in order to accommodate the full range of values of built-in subtypes of xs:integer, such as xs:long and xs:unsignedLong.

      2. For the types xs:date, xs:dateTime, xs:gYear, and xs:gYearMonth: the minimum and maximum value of the year component (must be at least 1 to 9999).

        For the types xs:time and xs:dateTime: the maximum number of fractional second digits (must be at least 3).

      3. For the xs:duration type: the maximum absolute values of the years, months, days, hours, minutes, and seconds components.

      4. For the xs:yearMonthDuration type: the maximum absolute value, expressed as an integer number of months.

      5. For the xs:dayTimeDuration type: the maximum absolute value, expressed as a decimal number of seconds.

      6. For the types xs:string, xs:hexBinary, xs:base64Binary, xs:QName, xs:anyURI, xs:NOTATION, and types derived from them: limitations (if any) imposed by the implementation on lengths of values.

      The limits listed above need not be fixed, but MAY depend on environmental factors such as system resources. For example, the length of a value of type xs:string might be limited by available memory.

      Note:

      For discussion of errors due to implementation-dependent limits, see 2.4.1 Kinds of Errors.

    6.4 Syntax Extensions

    Any syntactic extensions to XQuery are implementation-defined. The effect of syntactic extensions, including their error behavior, is implementation-defined. Syntactic extensions MAY be used without restriction to modify the semantics of a XQuery expression.

    A XQuery 4.0 and XPath 4.0 Grammar

    A.1 EBNF

    Changes in 4.0  

    1. The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.  [Issue 1366 PR 1498]

    The grammar of XQuery 4.0 and XPath 4.0 uses the same simple Extended Backus-Naur Form (EBNF) notation as [XML 1.0] with the following differences.

    • The notation XYZ ** "," indicates a sequence of zero or more occurrences of XYZ, with a single comma between adjacent occurrences.

    • The notation XYZ ++ "," indicates a sequence of one or more occurrences of XYZ, with a single comma between adjacent occurrences.

    • All named symbols have a name that begins with an uppercase letter.

    • It adds a notation for referring to productions in external specifications.

    • Comments or extra-grammatical constraints on grammar productions are between '/*' and '*/' symbols.

      • A 'xgc:' prefix is an extra-grammatical constraint, the details of which are explained in A.1.2 Extra-grammatical Constraints

      • A 'ws:' prefix explains the whitespace rules for the production, the details of which are explained in A.3.5 Whitespace Rules

      • A 'gn:' prefix means a 'Grammar Note', and is meant as a clarification for parsing rules, and is explained in A.1.3 Grammar Notes. These notes are not normative.

    The terminal symbols for this grammar include the quoted strings used in the production rules below, and the terminal symbols defined in section A.3.1 Terminal Symbols. The grammar is a little unusual in that parsing and tokenization are somewhat intertwined: for more details see A.3 Lexical structure.

    The EBNF notation is described in more detail in A.1.1 Notation.

    [144]   AbbrevForwardStep   ::=   ("@" NodeTest) | SimpleNodeTest
    ("@" NodeTest) | SimpleNodeTest
    [147]   AbbrevReverseStep   ::=   ".."
    ".."
    [114]   AdditiveExpr   ::=   MultiplicativeExpr ( ("+" | "-") MultiplicativeExpr )*
    MultiplicativeExpr ( ("+" | "-") MultiplicativeExpr )*
    [60]   AllowingEmpty   ::=   "allowing" "empty"
    "allowing" "empty"
    [109]   AndExpr   ::=   ComparisonExpr ( "and" ComparisonExpr )*
    ComparisonExpr ( "and" ComparisonExpr )*
    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [29]   AnnotationValue   ::=   StringLiteral | ("-"? NumericLiteral) | ("true" "(" ")") | ("false" "(" ")")
    StringLiteral | ("-"? NumericLiteral) | ("true" "(" ")") | ("false" "(" ")")
    [261]   AnyArrayType   ::=   "array" "(" "*" ")"
    "array" "(" "*" ")"
    [248]   AnyFunctionType   ::=   ("function" | "fn") "(" "*" ")"
    ("function" | "fn") "(" "*" ")"
    [231]   AnyItemTest   ::=   "item" "(" ")"
    "item" "(" ")"
    [233]   AnyKindTest   ::=   "node" "(" ")"
    "node" "(" ")"
    [251]   AnyMapType   ::=   "map" "(" "*" ")"
    "map" "(" "*" ")"
    [254]   AnyRecordType   ::=   "record" "(" "*" ")"
    "record" "(" "*" ")"
    [187]   AposAttrValueContent   ::=   AposAttrContentChar
    | CommonContent
    AposAttrContentChar
    | CommonContent
    [179]   Argument   ::=   ExprSingle | ArgumentPlaceholder
    ExprSingle | ArgumentPlaceholder
    [156]   ArgumentList   ::=   "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    [180]   ArgumentPlaceholder   ::=   "?"
    "?"
    [216]   ArrayConstructor   ::=   SquareArrayConstructor | CurlyArrayConstructor
    SquareArrayConstructor | CurlyArrayConstructor
    [260]   ArrayType   ::=   AnyArrayType | TypedArrayType
    AnyArrayType | TypedArrayType
    [169]   ArrowDynamicFunction   ::=   VarRef | InlineFunctionExpr | ParenthesizedExpr
    VarRef | InlineFunctionExpr | ParenthesizedExpr
    [122]   ArrowExpr   ::=   UnaryExpr ( (SequenceArrowTarget | MappingArrowTarget | LookupArrowTarget) )*
    UnaryExpr ( (SequenceArrowTarget | MappingArrowTarget | LookupArrowTarget) )*
    [168]   ArrowStaticFunction   ::=   EQName
    EQName
    [127]   ArrowTarget   ::=   (ArrowStaticFunctionArgumentList) | (ArrowDynamicFunctionPositionalArgumentList)
    (ArrowStaticFunctionArgumentList) | (ArrowDynamicFunctionPositionalArgumentList)
    [243]   AttributeName   ::=   EQName
    EQName
    [239]   AttributeTest   ::=   "attribute" "(" (NameTestUnion ("," TypeName)?)? ")"
    "attribute" "(" (NameTestUnion ("," TypeName)?)? ")"
    [141]   AxisStep   ::=   (ReverseStep | ForwardStep) Predicate*
    (ReverseStep | ForwardStep) Predicate*
    [12]   BaseURIDecl   ::=   "declare" "base-uri" URILiteral
    "declare" "base-uri" URILiteral
    [10]   BoundarySpaceDecl   ::=   "declare" "boundary-space" ("preserve" | "strip")
    "declare" "boundary-space" ("preserve" | "strip")
    [100]   BracedActions   ::=   ThenActionElseIfAction* ElseAction?
    ThenActionElseIfAction* ElseAction?
    [90]   BracedSwitchCases   ::=   "{" SwitchCases "}"
    "{" SwitchCases "}"
    [95]   BracedTypeswitchCases   ::=   "{" TypeswitchCases "}"
    "{" TypeswitchCases "}"
    [96]   CaseClause   ::=   "case" (VarName "as")? SequenceTypeUnion "return" ExprSingle
    "case" (VarName "as")? SequenceTypeUnion "return" ExprSingle
    [120]   CastableExpr   ::=   CastExpr ( "castable" "as" CastTarget "?"? )?
    CastExpr ( "castable" "as" CastTarget "?"? )?
    [121]   CastExpr   ::=   ArrowExpr ( "cast" "as" CastTarget "?"? )?
    ArrowExpr ( "cast" "as" CastTarget "?"? )?
    [245]   CastTarget   ::=   TypeName | ChoiceItemType | EnumerationType
    TypeName | ChoiceItemType | EnumerationType
    [106]   CatchClause   ::=   "catch" NameTestUnionEnclosedExpr
    "catch" NameTestUnionEnclosedExpr
    [194]   CDataSection   ::=   "<![CDATA[" CDataSectionContents "]]>"/* ws: explicit */
    "<![CDATA[" CDataSectionContents "]]>"/* ws: explicit */
    /* ws: explicit */
    [195]   CDataSectionContents   ::=   (Char* - (Char* ']]>' Char*))/* ws: explicit */
    (Char* - (Char* ']]>' Char*))/* ws: explicit */
    /* ws: explicit */
    [263]   ChoiceItemType   ::=   "(" (ItemType ++ "|") ")"
    "(" (ItemType ++ "|") ")"
    [236]   CommentTest   ::=   "comment" "(" ")"
    "comment" "(" ")"
    [189]   CommonContent   ::=   PredefinedEntityRef | CharRef | "{{" | "}}" | EnclosedExpr
    PredefinedEntityRef | CharRef | "{{" | "}}" | EnclosedExpr
    [110]   ComparisonExpr   ::=   OtherwiseExpr ( (ValueComp
    | GeneralComp
    | NodeComp) OtherwiseExpr )?
    OtherwiseExpr ( (ValueComp
    | GeneralComp
    | NodeComp) OtherwiseExpr )?
    [204]   CompAttrConstructor   ::=   "attribute" CompNodeNameEnclosedExpr
    "attribute" CompNodeNameEnclosedExpr
    [207]   CompCommentConstructor   ::=   "comment" EnclosedExpr
    "comment" EnclosedExpr
    [197]   CompDocConstructor   ::=   "document" EnclosedExpr
    "document" EnclosedExpr
    [198]   CompElemConstructor   ::=   "element" CompNodeNameEnclosedContentExpr
    "element" CompNodeNameEnclosedContentExpr
    [205]   CompNamespaceConstructor   ::=   "namespace" CompNodeNCNameEnclosedExpr
    "namespace" CompNodeNCNameEnclosedExpr
    [199]   CompNodeName   ::=   StringLiteral | UnreservedName | ("{" Expr "}")
    StringLiteral | UnreservedName | ("{" Expr "}")
    [200]   CompNodeNCName   ::=   StringLiteral | UnreservedNCName | ("{" Expr "}")
    StringLiteral | UnreservedNCName | ("{" Expr "}")
    [208]   CompPIConstructor   ::=   "processing-instruction" CompNodeNCNameEnclosedExpr
    "processing-instruction" CompNodeNCNameEnclosedExpr
    [206]   CompTextConstructor   ::=   "text" EnclosedExpr
    "text" EnclosedExpr
    [196]   ComputedConstructor   ::=   CompDocConstructor
    | CompElemConstructor
    | CompAttrConstructor
    | CompNamespaceConstructor
    | CompTextConstructor
    | CompCommentConstructor
    | CompPIConstructor
    CompDocConstructor
    | CompElemConstructor
    | CompAttrConstructor
    | CompNamespaceConstructor
    | CompTextConstructor
    | CompCommentConstructor
    | CompPIConstructor
    [13]   ConstructionDecl   ::=   "declare" "construction" ("strip" | "preserve")
    "declare" "construction" ("strip" | "preserve")
    [33]   ContextValueDecl   ::=   "declare" "context" (("value" ("as" SequenceType)?) | ("item" ("as" ItemType)?)) ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    "declare" "context" (("value" ("as" SequenceType)?) | ("item" ("as" ItemType)?)) ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    [175]   ContextValueRef   ::=   "."
    "."
    [16]   CopyNamespacesDecl   ::=   "declare" "copy-namespaces" PreserveMode "," InheritMode
    "declare" "copy-namespaces" PreserveMode "," InheritMode
    [76]   CountClause   ::=   "count" VarName
    "count" VarName
    [218]   CurlyArrayConstructor   ::=   "array" EnclosedExpr
    "array" EnclosedExpr
    [73]   CurrentVar   ::=   VarName
    VarName
    [19]   DecimalFormatDecl   ::=   "declare" (("decimal-format" EQName) | ("default" "decimal-format")) (DFPropertyName "=" StringLiteral)*
    "declare" (("decimal-format" EQName) | ("default" "decimal-format")) (DFPropertyName "=" StringLiteral)*
    [11]   DefaultCollationDecl   ::=   "declare" "default" "collation" URILiteral
    "declare" "default" "collation" URILiteral
    [26]   DefaultNamespaceDecl   ::=   "declare" "fixed"? "default" ("element" | "function") "namespace" URILiteral
    "declare" "fixed"? "default" ("element" | "function") "namespace" URILiteral
    [20]   DFPropertyName   ::=   "decimal-separator" | "grouping-separator" | "infinity" | "minus-sign" | "NaN" | "percent" | "per-mille" | "zero-digit" | "digit" | "pattern-separator" | "exponent-separator"
    "decimal-separator" | "grouping-separator" | "infinity" | "minus-sign" | "NaN" | "percent" | "per-mille" | "zero-digit" | "digit" | "pattern-separator" | "exponent-separator"
    [184]   DirAttributeList   ::=   (S (QNameS? "=" S? DirAttributeValue)?)*/* ws: explicit */
    (S (QNameS? "=" S? DirAttributeValue)?)*/* ws: explicit */
    /* ws: explicit */
    [185]   DirAttributeValue   ::=   ('"' (EscapeQuot | QuotAttrValueContent)* '"')
    | ("'" (EscapeApos | AposAttrValueContent)* "'")
    /* ws: explicit */
    ('"' (EscapeQuot | QuotAttrValueContent)* '"')
    | ("'" (EscapeApos | AposAttrValueContent)* "'")
    /* ws: explicit */
    /* ws: explicit */
    [190]   DirCommentConstructor   ::=   "<!--" DirCommentContents "-->"/* ws: explicit */
    "<!--" DirCommentContents "-->"/* ws: explicit */
    /* ws: explicit */
    [191]   DirCommentContents   ::=   ((Char - '-') | ('-' (Char - '-')))*/* ws: explicit */
    ((Char - '-') | ('-' (Char - '-')))*/* ws: explicit */
    /* ws: explicit */
    [182]   DirectConstructor   ::=   DirElemConstructor
    | DirCommentConstructor
    | DirPIConstructor
    DirElemConstructor
    | DirCommentConstructor
    | DirPIConstructor
    [183]   DirElemConstructor   ::=   "<" QNameDirAttributeList ("/>" | (">" DirElemContent* "</" QNameS? ">"))/* ws: explicit */
    "<" QNameDirAttributeList ("/>" | (">" DirElemContent* "</" QNameS? ">"))/* ws: explicit */
    /* ws: explicit */
    [188]   DirElemContent   ::=   DirectConstructor
    | CDataSection
    | CommonContent
    | ElementContentChar
    DirectConstructor
    | CDataSection
    | CommonContent
    | ElementContentChar
    [192]   DirPIConstructor   ::=   "<?" PITarget (SDirPIContents)? "?>"/* ws: explicit */
    "<?" PITarget (SDirPIContents)? "?>"/* ws: explicit */
    /* ws: explicit */
    [193]   DirPIContents   ::=   (Char* - (Char* '?>' Char*))/* ws: explicit */
    (Char* - (Char* '?>' Char*))/* ws: explicit */
    /* ws: explicit */
    [234]   DocumentTest   ::=   "document-node" "(" (ElementTest | SchemaElementTest | NameTestUnion)? ")"
    "document-node" "(" (ElementTest | SchemaElementTest | NameTestUnion)? ")"
    [155]   DynamicFunctionCall   ::=   PostfixExprPositionalArgumentList
    PostfixExprPositionalArgumentList
    [244]   ElementName   ::=   EQName
    EQName
    [241]   ElementTest   ::=   "element" "(" (NameTestUnion ("," TypeName "?"?)?)? ")"
    "element" "(" (NameTestUnion ("," TypeName "?"?)?)? ")"
    [103]   ElseAction   ::=   "else" EnclosedExpr
    "else" EnclosedExpr
    [102]   ElseIfAction   ::=   "else" "if" "(" Expr ")" EnclosedExpr
    "else" "if" "(" Expr ")" EnclosedExpr
    [15]   EmptyOrderDecl   ::=   "declare" "default" "order" "empty" ("greatest" | "least")
    "declare" "default" "order" "empty" ("greatest" | "least")
    [203]   EnclosedContentExpr   ::=   EnclosedExpr
    EnclosedExpr
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"
    [259]   EnumerationType   ::=   "enum" "(" (StringLiteral ++ ",") ")"
    "enum" "(" (StringLiteral ++ ",") ")"
    [265]   EQName   ::=   QName | URIQualifiedName
    QName | URIQualifiedName
    [46]   Expr   ::=   (ExprSingle ++ ",")
    (ExprSingle ++ ",")
    [47]   ExprSingle   ::=   ForExpr
    | LetExpr
    | FLWORExpr
    | QuantifiedExpr
    | SwitchExpr
    | TypeswitchExpr
    | IfExpr
    | TryCatchExpr
    | OrExpr
    ForExpr
    | LetExpr
    | FLWORExpr
    | QuantifiedExpr
    | SwitchExpr
    | TypeswitchExpr
    | IfExpr
    | TryCatchExpr
    | OrExpr
    [43]   ExtendedFieldDeclaration   ::=   FieldDeclaration (":=" ExprSingle)?
    FieldDeclaration (":=" ExprSingle)?
    [258]   ExtensibleFlag   ::=   "," "*"
    "," "*"
    [134]   ExtensionExpr   ::=   Pragma+ "{" Expr? "}"
    Pragma+ "{" Expr? "}"
    [256]   FieldDeclaration   ::=   FieldName "?"? ("as" SequenceType)?
    FieldName "?"? ("as" SequenceType)?
    [257]   FieldName   ::=   NCName | StringLiteral
    NCName | StringLiteral
    [153]   FilterExpr   ::=   PostfixExprPredicate
    PostfixExprPredicate
    [163]   FilterExprAM   ::=   PostfixExpr "?[" Expr "]"
    PostfixExpr "?[" Expr "]"
    [51]   FLWORExpr   ::=   InitialClauseIntermediateClause* ReturnClause
    InitialClauseIntermediateClause* ReturnClause
    [55]   ForBinding   ::=   ForItemBinding | ForMemberBinding | ForEntryBinding
    ForItemBinding | ForMemberBinding | ForEntryBinding
    [54]   ForClause   ::=   "for" (ForBinding ++ ",")
    "for" (ForBinding ++ ",")
    [61]   ForEntryBinding   ::=   ((ForEntryKeyBindingForEntryValueBinding?) | ForEntryValueBinding) PositionalVar? "in" ExprSingle
    ((ForEntryKeyBindingForEntryValueBinding?) | ForEntryValueBinding) PositionalVar? "in" ExprSingle
    [62]   ForEntryKeyBinding   ::=   "key" VarNameAndType
    "key" VarNameAndType
    [63]   ForEntryValueBinding   ::=   "value" VarNameAndType
    "value" VarNameAndType
    [48]   ForExpr   ::=   ForClauseForLetReturn
    ForClauseForLetReturn
    [56]   ForItemBinding   ::=   VarNameAndTypeAllowingEmpty? PositionalVar? "in" ExprSingle
    VarNameAndTypeAllowingEmpty? PositionalVar? "in" ExprSingle
    [49]   ForLetReturn   ::=   ForExpr | LetExpr | ("return" ExprSingle)
    ForExpr | LetExpr | ("return" ExprSingle)
    [59]   ForMemberBinding   ::=   "member" VarNameAndTypePositionalVar? "in" ExprSingle
    "member" VarNameAndTypePositionalVar? "in" ExprSingle
    [143]   ForwardAxis   ::=   ("attribute"
    | "child"
    | "descendant"
    | "descendant-or-self"
    | "following"
    | "following-or-self"
    | "following-sibling"
    | "following-sibling-or-self"
    | "namespace"
    | "self") "::"
    ("attribute"
    | "child"
    | "descendant"
    | "descendant-or-self"
    | "following"
    | "following-or-self"
    | "following-sibling"
    | "following-sibling-or-self"
    | "namespace"
    | "self") "::"
    [142]   ForwardStep   ::=   (ForwardAxisNodeTest) | AbbrevForwardStep
    (ForwardAxisNodeTest) | AbbrevForwardStep
    [39]   FunctionBody   ::=   EnclosedExpr
    EnclosedExpr
    [178]   FunctionCall   ::=   EQNameArgumentList/* xgc: reserved-function-names */
    EQNameArgumentList/* xgc: reserved-function-names */
    /* xgc: reserved-function-names */
    /* gn: parens */
    [34]   FunctionDecl   ::=   "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")/* xgc: reserved-function-names */
    "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")/* xgc: reserved-function-names */
    /* xgc: reserved-function-names */
    [209]   FunctionItemExpr   ::=   NamedFunctionRef | InlineFunctionExpr
    NamedFunctionRef | InlineFunctionExpr
    [35]   FunctionSignature   ::=   "(" ParamList ")" TypeDeclaration?
    "(" ParamList ")" TypeDeclaration?
    [247]   FunctionType   ::=   Annotation* (AnyFunctionType
    | TypedFunctionType)
    Annotation* (AnyFunctionType
    | TypedFunctionType)
    [129]   GeneralComp   ::=   "=" | "!=" | "<" | "<=" | ">" | ">="
    "=" | "!=" | "<" | "<=" | ">" | ">="
    [79]   GroupByClause   ::=   "group" "by" (GroupingSpec ++ ",")
    "group" "by" (GroupingSpec ++ ",")
    [80]   GroupingSpec   ::=   VarName (TypeDeclaration? ":=" ExprSingle)? ("collation" URILiteral)?
    VarName (TypeDeclaration? ":=" ExprSingle)? ("collation" URILiteral)?
    [98]   IfExpr   ::=   "if" "(" Expr ")" (UnbracedActions | BracedActions)
    "if" "(" Expr ")" (UnbracedActions | BracedActions)
    [21]   Import   ::=   SchemaImport | ModuleImport
    SchemaImport | ModuleImport
    [18]   InheritMode   ::=   "inherit" | "no-inherit"
    "inherit" | "no-inherit"
    [52]   InitialClause   ::=   ForClause | LetClause | WindowClause
    ForClause | LetClause | WindowClause
    [211]   InlineFunctionExpr   ::=   Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    [118]   InstanceofExpr   ::=   TreatExpr ( "instance" "of" SequenceType )?
    TreatExpr ( "instance" "of" SequenceType )?
    [53]   IntermediateClause   ::=   InitialClause | WhereClause | WhileClause | GroupByClause | OrderByClause | CountClause
    InitialClause | WhereClause | WhileClause | GroupByClause | OrderByClause | CountClause
    [117]   IntersectExceptExpr   ::=   InstanceofExpr ( ("intersect" | "except") InstanceofExpr )*
    InstanceofExpr ( ("intersect" | "except") InstanceofExpr )*
    [230]   ItemType   ::=   AnyItemTest | TypeName | KindTest | FunctionType | MapType | ArrayType | RecordType | EnumerationType | ChoiceItemType
    AnyItemTest | TypeName | KindTest | FunctionType | MapType | ArrayType | RecordType | EnumerationType | ChoiceItemType
    [41]   ItemTypeDecl   ::=   "type" EQName "as" ItemType
    "type" EQName "as" ItemType
    [166]   KeySpecifier   ::=   NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard
    NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard
    [160]   KeywordArgument   ::=   EQName ":=" Argument
    EQName ":=" Argument
    [159]   KeywordArguments   ::=   (KeywordArgument ++ ",")
    (KeywordArgument ++ ",")
    [232]   KindTest   ::=   DocumentTest
    | ElementTest
    | AttributeTest
    | SchemaElementTest
    | SchemaAttributeTest
    | PITest
    | CommentTest
    | TextTest
    | NamespaceNodeTest
    | AnyKindTest
    DocumentTest
    | ElementTest
    | AttributeTest
    | SchemaElementTest
    | SchemaAttributeTest
    | PITest
    | CommentTest
    | TextTest
    | NamespaceNodeTest
    | AnyKindTest
    [66]   LetBinding   ::=   VarNameAndType ":=" ExprSingle
    VarNameAndType ":=" ExprSingle
    [65]   LetClause   ::=   "let" (LetBinding ++ ",")
    "let" (LetBinding ++ ",")
    [50]   LetExpr   ::=   LetClauseForLetReturn
    LetClauseForLetReturn
    [5]   LibraryModule   ::=   ModuleDeclProlog
    ModuleDeclProlog
    [171]   Literal   ::=   NumericLiteral | StringLiteral
    NumericLiteral | StringLiteral
    [164]   Lookup   ::=   ("?" | "??") (Modifier "::")? KeySpecifier
    ("?" | "??") (Modifier "::")? KeySpecifier
    [128]   LookupArrowTarget   ::=   "=?>" NCNamePositionalArgumentList
    "=?>" NCNamePositionalArgumentList
    [162]   LookupExpr   ::=   PostfixExprLookup
    PostfixExprLookup
    [167]   LookupWildcard   ::=   "*"
    "*"
    [4]   MainModule   ::=   PrologQueryBody
    PrologQueryBody
    [212]   MapConstructor   ::=   "map"? "{" (MapConstructorEntry ** ",") "}"
    "map"? "{" (MapConstructorEntry ** ",") "}"
    [213]   MapConstructorEntry   ::=   MapKeyExpr ":" MapValueExpr
    MapKeyExpr ":" MapValueExpr
    [214]   MapKeyExpr   ::=   ExprSingle
    ExprSingle
    [126]   MappingArrowTarget   ::=   "=!>" ArrowTarget
    "=!>" ArrowTarget
    [250]   MapType   ::=   AnyMapType | TypedMapType
    AnyMapType | TypedMapType
    [215]   MapValueExpr   ::=   ExprSingle
    ExprSingle
    [165]   Modifier   ::=   "pairs" | "keys" | "values" | "items"
    "pairs" | "keys" | "values" | "items"
    [2]   Module   ::=   VersionDecl? (LibraryModule | MainModule)
    VersionDecl? (LibraryModule | MainModule)
    [6]   ModuleDecl   ::=   "module" "namespace" NCName "=" URILiteralSeparator
    "module" "namespace" NCName "=" URILiteralSeparator
    [24]   ModuleImport   ::=   "import" "module" ("namespace" NCName "=")? URILiteral ("at" (URILiteral ++ ","))?
    "import" "module" ("namespace" NCName "=")? URILiteral ("at" (URILiteral ++ ","))?
    [115]   MultiplicativeExpr   ::=   UnionExpr ( ("*" | "×" | "div" | "÷" | "idiv" | "mod") UnionExpr )*
    UnionExpr ( ("*" | "×" | "div" | "÷" | "idiv" | "mod") UnionExpr )*
    [210]   NamedFunctionRef   ::=   EQName "#" IntegerLiteral/* xgc: reserved-function-names */
    EQName "#" IntegerLiteral/* xgc: reserved-function-names */
    /* xgc: reserved-function-names */
    [42]   NamedRecordTypeDecl   ::=   "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    [25]   NamespaceDecl   ::=   "declare" "namespace" NCName "=" URILiteral
    "declare" "namespace" NCName "=" URILiteral
    [237]   NamespaceNodeTest   ::=   "namespace-node" "(" ")"
    "namespace-node" "(" ")"
    [151]   NameTest   ::=   EQName | Wildcard
    EQName | Wildcard
    [107]   NameTestUnion   ::=   (NameTest ++ "|")
    (NameTest ++ "|")
    [75]   NextVar   ::=   "next" VarName
    "next" VarName
    [131]   NodeComp   ::=   "is" | "<<" | ">>"
    "is" | "<<" | ">>"
    [181]   NodeConstructor   ::=   DirectConstructor
    | ComputedConstructor
    DirectConstructor
    | ComputedConstructor
    [148]   NodeTest   ::=   UnionNodeTest | SimpleNodeTest
    UnionNodeTest | SimpleNodeTest
    [172]   NumericLiteral   ::=   IntegerLiteral | HexIntegerLiteral | BinaryIntegerLiteral | DecimalLiteral | DoubleLiteral
    IntegerLiteral | HexIntegerLiteral | BinaryIntegerLiteral | DecimalLiteral | DoubleLiteral
    [229]   OccurrenceIndicator   ::=   "?" | "*" | "+"/* xgc: occurrence-indicators */
    "?" | "*" | "+"/* xgc: occurrence-indicators */
    /* xgc: occurrence-indicators */
    [44]   OptionDecl   ::=   "declare" "option" EQNameStringLiteral
    "declare" "option" EQNameStringLiteral
    [81]   OrderByClause   ::=   "stable"? "order" "by" OrderSpec ("," OrderSpec)*
    "stable"? "order" "by" OrderSpec ("," OrderSpec)*
    [176]   OrderedExpr   ::=   "ordered" EnclosedExpr
    "ordered" EnclosedExpr
    [14]   OrderingModeDecl   ::=   "declare" "ordering" ("ordered" | "unordered")
    "declare" "ordering" ("ordered" | "unordered")
    [83]   OrderModifier   ::=   ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral)?
    ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral)?
    [82]   OrderSpec   ::=   ExprSingleOrderModifier
    ExprSingleOrderModifier
    [108]   OrExpr   ::=   AndExpr ( "or" AndExpr )*
    AndExpr ( "or" AndExpr )*
    [111]   OtherwiseExpr   ::=   StringConcatExpr ( "otherwise" StringConcatExpr )*
    StringConcatExpr ( "otherwise" StringConcatExpr )*
    [38]   ParamList   ::=   (VarNameAndType ** ",")
    (VarNameAndType ** ",")
    [36]   ParamListWithDefaults   ::=   (ParamWithDefault ++ ",")
    (ParamWithDefault ++ ",")
    [37]   ParamWithDefault   ::=   VarNameAndType (":=" ExprSingle)?
    VarNameAndType (":=" ExprSingle)?
    [174]   ParenthesizedExpr   ::=   "(" Expr? ")"
    "(" Expr? ")"
    [138]   PathExpr   ::=   ("/" RelativePathExpr?)
    | ("//" RelativePathExpr)
    | RelativePathExpr
    /* xgc: leading-lone-slash */
    ("/" RelativePathExpr?)
    | ("//" RelativePathExpr)
    | RelativePathExpr
    /* xgc: leading-lone-slash */
    /* xgc: leading-lone-slash */
    [238]   PITest   ::=   "processing-instruction" "(" (NCName | StringLiteral)? ")"
    "processing-instruction" "(" (NCName | StringLiteral)? ")"
    [157]   PositionalArgumentList   ::=   "(" PositionalArguments? ")"
    "(" PositionalArguments? ")"
    [158]   PositionalArguments   ::=   (Argument ++ ",")
    (Argument ++ ",")
    [64]   PositionalVar   ::=   "at" VarName
    "at" VarName
    [154]   PostfixExpr   ::=   PrimaryExpr | FilterExpr | DynamicFunctionCall | LookupExpr | FilterExprAM
    PrimaryExpr | FilterExpr | DynamicFunctionCall | LookupExpr | FilterExprAM
    [135]   Pragma   ::=   "(#" S? EQName (SPragmaContents)? "#)"/* ws: explicit */
    "(#" S? EQName (SPragmaContents)? "#)"/* ws: explicit */
    /* ws: explicit */
    [136]   PragmaContents   ::=   (Char* - (Char* '#)' Char*))
    (Char* - (Char* '#)' Char*))
    [161]   Predicate   ::=   "[" Expr "]"
    "[" Expr "]"
    [17]   PreserveMode   ::=   "preserve" | "no-preserve"
    "preserve" | "no-preserve"
    [74]   PreviousVar   ::=   "previous" VarName
    "previous" VarName
    [170]   PrimaryExpr   ::=   Literal
    | VarRef
    | ParenthesizedExpr
    | ContextValueRef
    | FunctionCall
    | OrderedExpr
    | UnorderedExpr
    | NodeConstructor
    | FunctionItemExpr
    | MapConstructor
    | ArrayConstructor
    | StringTemplate
    | StringConstructor
    | UnaryLookup
    Literal
    | VarRef
    | ParenthesizedExpr
    | ContextValueRef
    | FunctionCall
    | OrderedExpr
    | UnorderedExpr
    | NodeConstructor
    | FunctionItemExpr
    | MapConstructor
    | ArrayConstructor
    | StringTemplate
    | StringConstructor
    | UnaryLookup
    [7]   Prolog   ::=   ((DefaultNamespaceDecl | Setter | NamespaceDecl | Import) Separator)* ((ContextValueDecl | AnnotatedDecl | OptionDecl) Separator)*
    ((DefaultNamespaceDecl | Setter | NamespaceDecl | Import) Separator)* ((ContextValueDecl | AnnotatedDecl | OptionDecl) Separator)*
    [85]   QuantifiedExpr   ::=   ("some" | "every") QuantifierBinding ("," QuantifierBinding)* "satisfies" ExprSingle
    ("some" | "every") QuantifierBinding ("," QuantifierBinding)* "satisfies" ExprSingle
    [86]   QuantifierBinding   ::=   VarNameAndType "in" ExprSingle
    VarNameAndType "in" ExprSingle
    [45]   QueryBody   ::=   Expr
    Expr
    [186]   QuotAttrValueContent   ::=   QuotAttrContentChar
    | CommonContent
    QuotAttrContentChar
    | CommonContent
    [113]   RangeExpr   ::=   AdditiveExpr ( "to" AdditiveExpr )?
    AdditiveExpr ( "to" AdditiveExpr )?
    [253]   RecordType   ::=   AnyRecordType | TypedRecordType
    AnyRecordType | TypedRecordType
    [139]   RelativePathExpr   ::=   StepExpr (("/" | "//") StepExpr)*
    StepExpr (("/" | "//") StepExpr)*
    [84]   ReturnClause   ::=   "return" ExprSingle
    "return" ExprSingle
    [146]   ReverseAxis   ::=   ("ancestor"
    | "ancestor-or-self"
    | "parent"
    | "preceding"
    | "preceding-or-self"
    | "preceding-sibling-or-self") "::"
    ("ancestor"
    | "ancestor-or-self"
    | "parent"
    | "preceding"
    | "preceding-or-self"
    | "preceding-sibling-or-self") "::"
    [145]   ReverseStep   ::=   (ReverseAxisNodeTest) | AbbrevReverseStep
    (ReverseAxisNodeTest) | AbbrevReverseStep
    [240]   SchemaAttributeTest   ::=   "schema-attribute" "(" AttributeName ")"
    "schema-attribute" "(" AttributeName ")"
    [242]   SchemaElementTest   ::=   "schema-element" "(" ElementName ")"
    "schema-element" "(" ElementName ")"
    [22]   SchemaImport   ::=   "import" "schema" SchemaPrefix? URILiteral ("at" (URILiteral ++ ","))?
    "import" "schema" SchemaPrefix? URILiteral ("at" (URILiteral ++ ","))?
    [23]   SchemaPrefix   ::=   ("namespace" NCName "=") | ("fixed"? "default" "element" "namespace")
    ("namespace" NCName "=") | ("fixed"? "default" "element" "namespace")
    [8]   Separator   ::=   ";"
    ";"
    [125]   SequenceArrowTarget   ::=   "=>" ArrowTarget
    "=>" ArrowTarget
    [228]   SequenceType   ::=   ("empty-sequence" "(" ")")
    | (ItemTypeOccurrenceIndicator?)
    ("empty-sequence" "(" ")")
    | (ItemTypeOccurrenceIndicator?)
    [97]   SequenceTypeUnion   ::=   SequenceType ("|" SequenceType)*
    SequenceType ("|" SequenceType)*
    [9]   Setter   ::=   BoundarySpaceDecl | DefaultCollationDecl | BaseURIDecl | ConstructionDecl | OrderingModeDecl | EmptyOrderDecl | CopyNamespacesDecl | DecimalFormatDecl
    BoundarySpaceDecl | DefaultCollationDecl | BaseURIDecl | ConstructionDecl | OrderingModeDecl | EmptyOrderDecl | CopyNamespacesDecl | DecimalFormatDecl
    [137]   SimpleMapExpr   ::=   PathExpr ("!" PathExpr)*
    PathExpr ("!" PathExpr)*
    [150]   SimpleNodeTest   ::=   KindTest | NameTest
    KindTest | NameTest
    [69]   SlidingWindowClause   ::=   "sliding" "window" VarNameAndType "in" ExprSingleWindowStartCondition? WindowEndCondition
    "sliding" "window" VarNameAndType "in" ExprSingleWindowStartCondition? WindowEndCondition
    [217]   SquareArrayConstructor   ::=   "[" (ExprSingle ** ",") "]"
    "[" (ExprSingle ** ",") "]"
    [140]   StepExpr   ::=   PostfixExpr | AxisStep
    PostfixExpr | AxisStep
    [112]   StringConcatExpr   ::=   RangeExpr ( "||" RangeExpr )*
    RangeExpr ( "||" RangeExpr )*
    [222]   StringConstructor   ::=   "``[" StringConstructorContent "]``"/* ws: explicit */
    "``[" StringConstructorContent "]``"/* ws: explicit */
    /* ws: explicit */
    [224]   StringConstructorChars   ::=   (Char* - (Char* ('`{' | ']``') Char*))/* ws: explicit */
    (Char* - (Char* ('`{' | ']``') Char*))/* ws: explicit */
    /* ws: explicit */
    [223]   StringConstructorContent   ::=   StringConstructorChars (StringInterpolationStringConstructorChars)*/* ws: explicit */
    StringConstructorChars (StringInterpolationStringConstructorChars)*/* ws: explicit */
    /* ws: explicit */
    [225]   StringInterpolation   ::=   "`{" Expr? "}`"/* ws: explicit */
    "`{" Expr? "}`"/* ws: explicit */
    /* ws: explicit */
    [219]   StringTemplate   ::=   "`" (StringTemplateFixedPart | StringTemplateVariablePart)* "`"/* ws: explicit */
    "`" (StringTemplateFixedPart | StringTemplateVariablePart)* "`"/* ws: explicit */
    /* ws: explicit */
    [220]   StringTemplateFixedPart   ::=   ((Char - ('{' | '}' | '`')) | "{{" | "}}" | "``")*/* ws: explicit */
    ((Char - ('{' | '}' | '`')) | "{{" | "}}" | "``")*/* ws: explicit */
    /* ws: explicit */
    [221]   StringTemplateVariablePart   ::=   EnclosedExpr/* ws: explicit */
    EnclosedExpr/* ws: explicit */
    /* ws: explicit */
    [91]   SwitchCaseClause   ::=   ("case" SwitchCaseOperand)+ "return" ExprSingle
    ("case" SwitchCaseOperand)+ "return" ExprSingle
    [92]   SwitchCaseOperand   ::=   Expr
    Expr
    [89]   SwitchCases   ::=   SwitchCaseClause+ "default" "return" ExprSingle
    SwitchCaseClause+ "default" "return" ExprSingle
    [88]   SwitchComparand   ::=   "(" Expr? ")"
    "(" Expr? ")"
    [87]   SwitchExpr   ::=   "switch" SwitchComparand (SwitchCases | BracedSwitchCases)
    "switch" SwitchComparand (SwitchCases | BracedSwitchCases)
    [235]   TextTest   ::=   "text" "(" ")"
    "text" "(" ")"
    [101]   ThenAction   ::=   EnclosedExpr
    EnclosedExpr
    [119]   TreatExpr   ::=   CastableExpr ( "treat" "as" SequenceType )?
    CastableExpr ( "treat" "as" SequenceType )?
    [104]   TryCatchExpr   ::=   TryClauseCatchClause+
    TryClauseCatchClause+
    [105]   TryClause   ::=   "try" EnclosedExpr
    "try" EnclosedExpr
    [68]   TumblingWindowClause   ::=   "tumbling" "window" VarNameAndType "in" ExprSingleWindowStartCondition? WindowEndCondition?
    "tumbling" "window" VarNameAndType "in" ExprSingleWindowStartCondition? WindowEndCondition?
    [262]   TypedArrayType   ::=   "array" "(" SequenceType ")"
    "array" "(" SequenceType ")"
    [227]   TypeDeclaration   ::=   "as" SequenceType
    "as" SequenceType
    [249]   TypedFunctionType   ::=   ("function" | "fn") "(" (SequenceType ** ",") ")" "as" SequenceType
    ("function" | "fn") "(" (SequenceType ** ",") ")" "as" SequenceType
    [252]   TypedMapType   ::=   "map" "(" ItemType "," SequenceType ")"
    "map" "(" ItemType "," SequenceType ")"
    [255]   TypedRecordType   ::=   "record" "(" (FieldDeclaration ** ",") ExtensibleFlag? ")"
    "record" "(" (FieldDeclaration ** ",") ExtensibleFlag? ")"
    [246]   TypeName   ::=   EQName
    EQName
    [94]   TypeswitchCases   ::=   CaseClause+ "default" VarName? "return" ExprSingle
    CaseClause+ "default" VarName? "return" ExprSingle
    [93]   TypeswitchExpr   ::=   "typeswitch" "(" Expr ")" (TypeswitchCases | BracedTypeswitchCases)
    "typeswitch" "(" Expr ")" (TypeswitchCases | BracedTypeswitchCases)
    [123]   UnaryExpr   ::=   ("-" | "+")* ValueExpr
    ("-" | "+")* ValueExpr
    [226]   UnaryLookup   ::=   ("?" | "??") (Modifier "::")? KeySpecifier
    ("?" | "??") (Modifier "::")? KeySpecifier
    [99]   UnbracedActions   ::=   "then" ExprSingle "else" ExprSingle
    "then" ExprSingle "else" ExprSingle
    [116]   UnionExpr   ::=   IntersectExceptExpr ( ("union" | "|") IntersectExceptExpr )*
    IntersectExceptExpr ( ("union" | "|") IntersectExceptExpr )*
    [149]   UnionNodeTest   ::=   "(" SimpleNodeTest ("|" SimpleNodeTest)* ")"
    "(" SimpleNodeTest ("|" SimpleNodeTest)* ")"
    [177]   UnorderedExpr   ::=   "unordered" EnclosedExpr
    "unordered" EnclosedExpr
    [201]   UnreservedName   ::=   EQName/* xgc: unreserved-name */
    EQName/* xgc: unreserved-name */
    /* xgc: unreserved-name */
    [202]   UnreservedNCName   ::=   NCName/* xgc: unreserved-name */
    NCName/* xgc: unreserved-name */
    /* xgc: unreserved-name */
    [264]   URILiteral   ::=   StringLiteral
    StringLiteral
    [132]   ValidateExpr   ::=   "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    [133]   ValidationMode   ::=   "lax" | "strict"
    "lax" | "strict"
    [130]   ValueComp   ::=   "eq" | "ne" | "lt" | "le" | "gt" | "ge"
    "eq" | "ne" | "lt" | "le" | "gt" | "ge"
    [124]   ValueExpr   ::=   ValidateExpr | ExtensionExpr | SimpleMapExpr
    ValidateExpr | ExtensionExpr | SimpleMapExpr
    [30]   VarDecl   ::=   "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    [32]   VarDefaultValue   ::=   ExprSingle
    ExprSingle
    [57]   VarName   ::=   "$" EQName
    "$" EQName
    [58]   VarNameAndType   ::=   "$" EQNameTypeDeclaration?
    "$" EQNameTypeDeclaration?
    [173]   VarRef   ::=   "$" EQName
    "$" EQName
    [31]   VarValue   ::=   ExprSingle
    ExprSingle
    [3]   VersionDecl   ::=   "xquery" (("encoding" StringLiteral) | ("version" StringLiteral ("encoding" StringLiteral)?)) Separator
    "xquery" (("encoding" StringLiteral) | ("version" StringLiteral ("encoding" StringLiteral)?)) Separator
    [77]   WhereClause   ::=   "where" ExprSingle
    "where" ExprSingle
    [78]   WhileClause   ::=   "while" ExprSingle
    "while" ExprSingle
    [152]   Wildcard   ::=   "*"
    | (NCName ":*")
    | ("*:" NCName)
    | (BracedURILiteral "*")
    /* ws: explicit */
    "*"
    | (NCName ":*")
    | ("*:" NCName)
    | (BracedURILiteral "*")
    /* ws: explicit */
    /* ws: explicit */
    [67]   WindowClause   ::=   "for" (TumblingWindowClause | SlidingWindowClause)
    "for" (TumblingWindowClause | SlidingWindowClause)
    [71]   WindowEndCondition   ::=   "only"? "end" WindowVars ("when" ExprSingle)?
    "only"? "end" WindowVars ("when" ExprSingle)?
    [70]   WindowStartCondition   ::=   "start" WindowVars ("when" ExprSingle)?
    "start" WindowVars ("when" ExprSingle)?
    [72]   WindowVars   ::=   CurrentVar? PositionalVar? PreviousVar? NextVar?
    CurrentVar? PositionalVar? PreviousVar? NextVar?
    [1]   XPath   ::=   Expr
    Expr

    A.1.1 Notation

    Changes in 4.0  

    1. The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.  [Issue 1366 PR 1498]

    [Definition: Each rule in the grammar defines one symbol, using the following format:

    symbol ::= expression

    ]

    [Definition: A terminal is a symbol or string or pattern that can appear in the right-hand side of a rule, but never appears on the left-hand side in the main grammar, although it may appear on the left-hand side of a rule in the grammar for terminals.] The following constructs are used to match strings of one or more characters in a terminal:

    [a-zA-Z]

    matches any Char with a value in the range(s) indicated (inclusive).

    [abc]

    matches any Char with a value among the characters enumerated.

    [^abc]

    matches any Char with a value not among the characters given.

    "string" or 'string'

    matches the sequence of characters that appear inside the double or single quotation marks.

    [http://www.w3.org/TR/REC-example/#NT-Example]

    matches any string matched by the production defined in the external specification as per the provided reference.

    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, A and B represent (sub-)patterns.

    (A)

    A is treated as a unit and may be combined as described in this list.

    A?

    matches A or nothing; optional A.

    A B

    matches A followed by B. This implicit operator has higher precedence than the choice operator |; thus A B | C D is interpreted as (A B) | (C D).

    A | B

    matches A or B but not both.

    A - B

    matches any string that matches A but does not match B.

    A+

    matches one or more occurrences of A. Concatenation has higher precedence than choice; thus A+ | B+ is identical to (A+) | (B+).

    A*

    matches zero or more occurrences of A. Concatenation has higher precedence than choice; thus A* | B* is identical to (A*) | (B*)

    (A ++ B)

    matches one or more occurrences of A, with one occurrence of B between adjacent occurrences of A. The notation A ++ B is a shorthand for A (B A)*. The construct is always parenthesized to avoid ambiguity, and although in principle B could be any pattern, in practice the notation is used only when it is a simple string literal (typically but not invariably ",").

    For example, (Digit ++ ".") matches 1 or 1.2 or 1.2.3.

    (A ** B)

    matches zero or more occurrences of A, with one occurrence of B between adjacent occurrences of A. The notation A ** B is a shorthand for (A (B A)*)?. The construct is always parenthesized to avoid ambiguity, and although in principle B could be any pattern, in practice the notation is used only when it is a simple string literal (typically but not invariably ",").

    For example, "[" (Digit ** "|") "]" matches [] or [1] or [1|2] or [1|2|3].

    A.1.2 Extra-grammatical Constraints

    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: /* xgc: <id> */.

    Constraint: leading-lone-slash

    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 RelativePathExpr. In some cases, the next terminal after the slash is insufficient to allow a parser to distinguish these two possibilities: a * symbol or a keyword like union could be either an operator or a NameTest. For example, the expression /union/* could be parsed either as (/) union (/*) or as /child::union/child::* (the second interpretation is the one chosen).

    The situation where / is followed by < is a little more complicated. In XPath, this is unambiguous: the < can only indicate one of the operators <, <=, or <<. 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.3 Lexical structure.

    The rule adopted is as follows: if the terminal immediately following a slash can form the start of a RelativePathExpr, then the slash must be the beginning of a PathExpr, not the entirety of it.

    The terminals that can form the start of a RelativePathExpr are: NCName, QName, URIQualifiedName, StringLiteral, NumericLiteral, Wildcard, and StringTemplate; plus @...*$???%([; and in XQuery StringConstructor and DirectConstructor.

    A single slash may be used as the left-hand argument of an operator by parenthesizing it: (/) * 5. The expression 5 * /, on the other hand, is syntactically valid without parentheses.

    Constraint: unreserved-name

    In a computed node constructor of the form element NNN {}, attribute NNN {}, processing-instruction NNN {}, or namespace NNN {}, XQuery 4.0 allows the name NNN to be written as a plain NCName only if it is not a language keyword: more specifically, if it is not one of the literal terminals taking the form of an NCName that are listed in A.3 Lexical structure. If such names (for example div or value) are to be used as element or attribute names in a computed node constructor, they must be written as a string literal in quotation marks.

    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.

    Constraint: xml-version

    The version of XML and XML Names (e.g. [XML 1.0] and [XML Names], or [XML 1.1] and [XML Names 1.1]) is implementation-defined. 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.3.5.1 Default Whitespace Handling. Thus prefix : localname is not a syntactically valid lexical QName 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.

    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 XQuery 1.0XPath 2.0, implementations MAY allow C1 control characters to be used directly.

    Note:

    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.

    Constraint: reserved-function-names

    Unprefixed function names spelled the same way as language keywords could make the language impossible to parse. For instance, element(foo) could be taken either as a FunctionCall or as an ElementTest. Therefore, an unprefixed function name must not be any of the names in A.4 Reserved Function Names.

    A function named if can be called by binding its namespace to a prefix and using the prefixed form: library:if(foo) instead of if(foo).

    Constraint: occurrence-indicators

    As written, the grammar in A XQuery 4.0 and XPath 4.0 Grammar is ambiguous for some forms using the "+", "?" and "*"OccurrenceIndicators. The ambiguity is resolved as follows: these operators are tightly bound to the SequenceType expression, and have higher precedence than other uses of these symbols. Any occurrence of "+", "?" or "*", that follows a sequence type is assumed to be an occurrence indicator, which binds to the last ItemType in the SequenceType.

    Thus, 4 treat as item() + - 5 must be interpreted as (4 treat as item()+) - 5, 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 (4 treat as item()) + -5 surrounds the SequenceType expression with parentheses and leads to the desired interpretation.

    function () as xs:string * is interpreted as function () as (xs:string *), not as (function () as xs:string) *. Parentheses can be used as shown to force the latter interpretation.

    This rule has as a consequence that certain forms which would otherwise be syntactically valid and unambiguous are not recognized: in 4 treat as item() + 5, the "+" is taken as an OccurrenceIndicator, and not as an operator, which means this is not a syntactically valid expression.

    A.1.3 Grammar Notes

    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: /* gn: <id> */.

    Note:

    grammar-note: parens

    Lookahead is required to distinguish a FunctionCall from an EQName or keyword followed by a Pragma or Comment. For example: address (: this may be empty :) may be mistaken for a call to a function named "address" unless this lookahead is employed. Another example is for (: whom the bell :) $tolls in 3 return $tolls, where the keyword "for" must not be mistaken for a function name.

    grammar-note: comments

    Comments are allowed everywhere that ignorable whitespace is allowed, and the Comment symbol does not explicitly appear on the right-hand side of the grammar (except in its own production). See A.3.5.1 Default Whitespace Handling. Note that comments are not allowed in direct constructor content, though they are allowed in nested EnclosedExprs.

    A comment can contain nested comments, as long as all "(:" and ":)" patterns are balanced, no matter where they occur within the outer comment.

    Note:

    Lexical analysis may typically handle nested comments by incrementing a counter for each "(:" pattern, and decrementing the counter for each ":)" pattern. The comment does not terminate until the counter is back to zero.

    Some illustrative examples:

    • (: commenting out a (: comment :) may be confusing, but often helpful :) is a syntactically valid Comment, since balanced nesting of comments is allowed.

    • "this is just a string :)" is a syntactically valid expression. However, (: "this is just a string :)" :) will cause a syntax error. Likewise, "this is another string (:" is a syntactically valid expression, but (: "this is another string (:" :) will cause a syntax error. It is a limitation of nested comments that literal content can cause unbalanced nesting of comments.

    • for (: set up loop :) $i in $x return $i is syntactically valid, ignoring the comment.

    • 5 instance (: strange place for a comment :) of xs:integer is also syntactically valid.

    • <eg (: an example:)>{$i//title}</eg> is not syntactically valid.

    • <eg> (: an example:) </eg> is syntactically valid, but the characters that look like a comment are in fact literal element content.

    A.2 Productions Derived from XML

    Some productions are defined by reference to the XML and XML Names specifications (e.g. [XML 1.0] and [XML Names], or [XML 1.1] and [XML Names 1.1]. A host language may chooseIt is implementation-defined 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).

    A host language may choose whether the lexical rules of [XML 1.0] and [XML Names] are followed, or alternatively, the lexical rules of [XML 1.1] and [XML Names 1.1] are followed.

    It is implementation-defined whether the lexical rules of [XML 1.0] and [XML Names] are followed, or alternatively, the lexical rules of [XML 1.1] and [XML Names 1.1] are followed. Implementations that support the full [XML 1.1] character set SHOULD, for purposes of interoperability, provide a mode that follows only the [XML 1.0] and [XML Names] lexical rules.

    A.3 Lexical structure

    Changes in 4.0  

    1. 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.   [Issue 327 PR 519 30 May 2023]

    This section describes how an XQuery 4.0 and XPath 4.0 text is tokenized prior to parsing.

    All keywords are case sensitive. Keywords are not reserved—that is, any lexical QName may duplicate a keyword except as noted in A.4 Reserved Function Names.

    Tokenizing an input string is a process that follows the following rules:

    • [Definition: An ordinary production rule is a production rule in A.1 EBNF that is not annotated ws:explicit.]

    • [Definition: A literal terminal is a token appearing as a string in quotation marks on the right-hand side of an ordinary production rule.]

      Note:

      Strings that appear in other production rules do not qualify. For example, "]]>" is not a literal terminal, because it appears only in the rule CDataSection, which is not an ordinary production rule; similarly BracedURILiteral does not qualify because it appears only in URIQualifiedName, and "0x" does not qualify because it appears only in HexIntegerLiteral.For example, BracedURILiteral does not quality because it appears only in URIQualifiedName, and "0x" does not qualify because it appears only in HexIntegerLiteral.

      The literal terminals in XQuery 4.0 and XPath 4.0 are: !!=#$%()*+,...///::::=;<<<<===!>=>=?>>>=>>????[@[]{|||}×÷-allowingancestorancestor-or-selfandarrayasascendingatattributebase-uriboundary-spacebycasecastcastablecatchchildcollationcommentconstructioncontextcopy-namespacescountdecimal-formatdecimal-separatordeclaredefaultdescendantdescendant-or-selfdescendingdigitdivdocumentdocument-nodeelementelseemptyempty-sequenceencodingendenumeqeveryexceptexponent-separatorexternalfalsefixedfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selfforfunctiongegreatestgroupgrouping-separatorgtidivifimportininfinityinheritinstanceintersectisitemitemskeykeyslaxleleastletltmapmemberminus-signmodmodulenamespacenamespace-nodeNaNnenextno-inheritno-preservenodeofonlyoptionororderorderedorderingotherwisepairsparentpattern-separatorper-millepercentprecedingpreceding-or-selfpreceding-sibling-or-selfpreservepreviousprocessing-instructionrecordreturnsatisfiesschemaschema-attributeschema-elementselfslidingsomestablestartstrictstripswitchtextthentotreattruetrytumblingtypetypeswitchunionunorderedvalidatevaluevaluesvariableversionwhenwherewhilewindowxqueryzero-digit

    • [Definition: A variable terminal is an instance of a production rule that is not itself an ordinary production rule but that is named (directly) on the right-hand side of an ordinary production rule.]

      The variable terminals in XQuery 4.0 and XPath 4.0 are: BinaryIntegerLiteralCDataSectionDecimalLiteralDirCommentConstructorDirElemConstructorDirPIConstructorDoubleLiteralHexIntegerLiteralIntegerLiteralNCNamePragmaQNameStringConstructorStringLiteralStringTemplateURIQualifiedNameWildcard

    • [Definition: A complex terminal is a variable terminal whose production rule references, directly or indirectly, an ordinary production rule.]

      The complex terminals in XQuery 4.0 and XPath 4.0 are: DirElemConstructorPragmaStringConstructorStringTemplate

      Note:

      The significance of complex terminals is that at one level, a complex terminal is treated as a single token, but internally it may contain arbitrary expressions that must be parsed using the full EBNF grammar.

    • Tokenization is the process of splitting the supplied input string into a sequence of terminals, where each terminal is either a literal terminal or a variable terminal (which may itself be a complex terminal). Tokenization is done by repeating the following steps:

      1. Starting at the current position, skip any whitespace and comments.

      2. If the current position is not the end of the input, then return the longest literal terminal or variable terminal that can be matched starting at the current position, regardless whether this terminal is valid at this point in the grammar. If no such terminal can be identified starting at the current position, or if the terminal that is identified is not a valid continuation of the grammar rules, then a syntax error is reported.

        Note:

        Here are some examples showing the effect of the longest token rule:

        • The expression map{a:b} is a syntax error. Although there is a tokenization of this string that satisfies the grammar (by treating a and b as separate expressions), this tokenization does not satisfy the longest token rule, which requires that a:b is interpreted as a single QName.

        • The expression 10 div3 is a syntax error. The longest token rule requires that this be interpreted as two tokens ("10" and "div3") even though it would be a valid expression if treated as three tokens ("10", "div", and "3").

        • The expression $x-$y is a syntax error. This is interpreted as four tokens, ("$", "x-", "$", and "y").

        Note:

        The lexical production rules for variable terminals have been designed so that there is minimal need for backtracking. For example, if the next terminal starts with "0x", then it can only be either a HexIntegerLiteral or an error; if it starts with "`" (and not with "```") then it can only be a StringTemplate or an error. Direct element constructors in XQuery, however, need special treatment, described below.

        This convention, together with the rules for whitespace separation of tokens (see A.3.2 Terminal Delimitation) means that the longest-token rule does not normally result in any need for backtracking. For example, suppose that a variable terminal has been identified as a StringTemplate by examining its first few characters. If the construct turns out not to be a valid StringTemplate, an error can be reported without first considering whether there is some shorter token that might be returned instead.

    • Tokenization requires special care when the current character is U+003C (LESS-THAN SIGN, <) :

      • If the following character is U+003D (EQUALS SIGN, =) then the token can be identified unambiguously as the operator <=.

      • If the following character is U+003C (LESS-THAN SIGN, <) then the token can be identified unambiguously as the operator <<.

      • If the following character is U+0021 (EXCLAMATION MARK, !) then the token can be identified unambiguously as being a DirCommentConstructor (a CDataSection, which also starts with <! can appear only within a direct element constructor, not as a free-standing token).

      • If the following character is U+003F (QUESTION MARK, ?) , then the token is identified as a DirPIConstructor if and only if a match for the relevant production ("<?" PITarget (S DirPIContents)? "?>") is found. If there is no such match, then the string "<?" is identified as a less-than operator followed by a lookup operator.

      • If the following character is a NameStartChar then the token is identified as a DirElemConstructor if and only if a match for the leading part of a DirElemConstructor is found: specifically if a substring starting at the U+003C (LESS-THAN SIGN, <) character matches one of the following regular expressions:

        ^<\i\c*\s*> (as in <element>...)
        ^<\i\c*\s*/>(as in <element/>)
        ^<\i\c*\s+\i\c*\s*=(as in <element att=...)

        If the content matches one of these regular expressions but further analysis shows that the subsequent content does not satisfy the DirElemConstructor production, then a static error is reported.

        If the content does not match any of these regular expressions then the token is identified as the less-than operator <.

      • If the following character is any other character then the token can be identified unambiguously as the less-than operator <.

      This analysis is done without regard to the syntactic context of the U+003C (LESS-THAN SIGN, <) character. However, a tokenizer may avoid looking for a DirPIConstructor or DirElemConstructor if it knows that such a constructor cannot appear in the current syntactic context.

      Note:

      The rules here are described much more precisely than in XQuery 3.1, and the results in edge cases might be incompatible with some XQuery 3.1 processors.

      Note:

      To avoid potential confusion, simply add whitespace after any less-than operator.

    • Tokenization unambiguously identifies the boundaries of the terminals in the input, and this can be achieved without backtracking or lookahead. However, tokenization does not unambiguously classify each terminal. For example, it might identify the string "div" as a terminal, but it does not resolve whether this is the operator symbol div, or an NCName or QName used as a node test or as a variable or function name. Classification of terminals generally requires information about the grammatical context, and in some cases requires lookahead.

      Note:

      Operationally, classification of terminals may be done either in the tokenizer or the parser, or in some combination of the two. For example, according to the EBNF, the expression "parent::x" is made up of three tokens, "parent", "::", and "x". The name "parent" can be classified as an axis name as soon as the following token "::" is recognized, and this might be done either in the tokenizer or in the parser. (Note that whitespace and comments are allowed both before and after "::".)

    • In the case of a complex terminal, identifying the end of the complex terminal typically involves invoking the parser to process any embedded expressions. Tokenization, as described here, is therefore a recursive process. But other implementations are possible.

    Note:

    Previous versions of this specification included the statement: When tokenizing, the longest possible match that is consistent with the EBNF is used.

    Different processors are known to have interpreted this in different ways. One interpretation, for example, was that the expression 10 div-3 should be split into four tokens (10, div, -, 3) on the grounds that any other tokenization would give a result that was inconsistent with the EBNF grammar. Other processors report a syntax error on this example.

    This rule has therefore been rewritten in version 4.0. Tokenization is now entirely insensitive to the grammatical context; div-3 is recognized as a single token even though this results in a syntax error. For some implementations this may mean that expressions that were accepted in earlier releases are no longer accepted in 4.0.

    A more subtle example is: (. <?b ) cast as xs:integer?> 0) in which <?b ) cast as xs:integer?> is recognized as a single token (a direct processing instruction constructor) even though such a token cannot validly appear in this grammatical context.

    A.3.1 Terminal Symbols

    [266]   IntegerLiteral   ::=   Digits/* ws: explicit */
    Digits/* ws: explicit */
    /* ws: explicit */
    [267]   HexIntegerLiteral   ::=   "0x" HexDigits/* ws: explicit */
    "0x" HexDigits/* ws: explicit */
    /* ws: explicit */
    [268]   BinaryIntegerLiteral   ::=   "0b" BinaryDigits/* ws: explicit */
    "0b" BinaryDigits/* ws: explicit */
    /* ws: explicit */
    [269]   DecimalLiteral   ::=   ("." Digits) | (Digits "." Digits?)/* ws: explicit */
    ("." Digits) | (Digits "." Digits?)/* ws: explicit */
    /* ws: explicit */
    [270]   DoubleLiteral   ::=   (("." Digits) | (Digits ("." Digits?)?)) [eE] [+-]? Digits/* ws: explicit */
    (("." Digits) | (Digits ("." Digits?)?)) [eE] [+-]? Digits/* ws: explicit */
    /* ws: explicit */
    [271]   StringLiteral   ::=   AposStringLiteral | QuotStringLiteral/* ws: explicit */
    AposStringLiteral | QuotStringLiteral/* ws: explicit */
    /* ws: explicit */
    [272]   AposStringLiteral   ::=   "'" (PredefinedEntityRef | CharRef | EscapeApos | [^'&])* "'"/* ws: explicit */
    "'" (PredefinedEntityRef | CharRef | EscapeApos | [^'&])* "'"/* ws: explicit */
    /* ws: explicit */
    [273]   QuotStringLiteral   ::=   '"' (PredefinedEntityRef | CharRef | EscapeQuot | [^"&])* '"'/* ws: explicit */
    '"' (PredefinedEntityRef | CharRef | EscapeQuot | [^"&])* '"'/* ws: explicit */
    /* ws: explicit */
    [274]   URIQualifiedName   ::=   BracedURILiteralNCName/* ws: explicit */
    BracedURILiteralNCName/* ws: explicit */
    /* ws: explicit */
    [275]   BracedURILiteral   ::=   "Q" "{" (PredefinedEntityRef | CharRef | [^&{}])* "}"/* ws: explicit */
    "Q" "{" (PredefinedEntityRef | CharRef | [^&{}])* "}"/* ws: explicit */
    /* ws: explicit */
    [276]   PredefinedEntityRef   ::=   "&" ("lt" | "gt" | "amp" | "quot" | "apos") ";"/* ws: explicit */
    "&" ("lt" | "gt" | "amp" | "quot" | "apos") ";"/* ws: explicit */
    /* ws: explicit */
    [277]   EscapeQuot   ::=   '""'/* ws: explicit */
    '""'/* ws: explicit */
    /* ws: explicit */
    [278]   EscapeApos   ::=   "''"/* ws: explicit */
    "''"/* ws: explicit */
    /* ws: explicit */
    [279]   ElementContentChar   ::=   (Char - [{}<&])
    (Char - [{}<&])
    [280]   QuotAttrContentChar   ::=   (Char - ["{}<&])
    (Char - ["{}<&])
    [281]   AposAttrContentChar   ::=   (Char - ['{}<&])
    (Char - ['{}<&])
    [282]   Comment   ::=   "(:" (CommentContents | Comment)* ":)"/* ws: explicit */
    "(:" (CommentContents | Comment)* ":)"/* ws: explicit */
    /* ws: explicit */
    /* gn: comments */
    [283]   PITarget   ::=   [http://www.w3.org/TR/REC-xml#NT-PITarget]XML/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml#NT-PITarget]XML/* xgc: xml-version */
    /* xgc: xml-version */
    [284]   CharRef   ::=   [http://www.w3.org/TR/REC-xml#NT-CharRef]XML/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml#NT-CharRef]XML/* xgc: xml-version */
    /* xgc: xml-version */
    [285]   QName   ::=   [http://www.w3.org/TR/REC-xml-names/#NT-QName]Names/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml-names/#NT-QName]Names/* xgc: xml-version */
    /* xgc: xml-version */
    [286]   NCName   ::=   [http://www.w3.org/TR/REC-xml-names/#NT-NCName]Names/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml-names/#NT-NCName]Names/* xgc: xml-version */
    /* xgc: xml-version */
    [287]   S   ::=   [http://www.w3.org/TR/REC-xml#NT-S]XML/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml#NT-S]XML/* xgc: xml-version */
    /* xgc: xml-version */
    [288]   Char   ::=   [http://www.w3.org/TR/REC-xml#NT-Char]XML/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml#NT-Char]XML/* xgc: xml-version */
    /* xgc: xml-version */

    The following symbols are used only in the definition of terminal symbols; they are not terminal symbols in the grammar of A.1 EBNF.

    [289]   Digits   ::=   DecDigit ((DecDigit | "_")* DecDigit)?/* ws: explicit */
    DecDigit ((DecDigit | "_")* DecDigit)?/* ws: explicit */
    /* ws: explicit */
    [290]   DecDigit   ::=   [0-9]/* ws: explicit */
    [0-9]/* ws: explicit */
    /* ws: explicit */
    [291]   HexDigits   ::=   HexDigit ((HexDigit | "_")* HexDigit)?/* ws: explicit */
    HexDigit ((HexDigit | "_")* HexDigit)?/* ws: explicit */
    /* ws: explicit */
    [292]   HexDigit   ::=   [0-9a-fA-F]/* ws: explicit */
    [0-9a-fA-F]/* ws: explicit */
    /* ws: explicit */
    [293]   BinaryDigits   ::=   BinaryDigit ((BinaryDigit | "_")* BinaryDigit)?/* ws: explicit */
    BinaryDigit ((BinaryDigit | "_")* BinaryDigit)?/* ws: explicit */
    /* ws: explicit */
    [294]   BinaryDigit   ::=   [01]/* ws: explicit */
    [01]/* ws: explicit */
    /* ws: explicit */
    [295]   CommentContents   ::=   (Char+ - (Char* ('(:' | ':)') Char*))/* ws: explicit */
    (Char+ - (Char* ('(:' | ':)') Char*))/* ws: explicit */
    /* ws: explicit */

    A.3.2 Terminal Delimitation

    XQuery 4.0 and XPath 4.0 expressions consist of terminal symbols and symbol separators.

    Literal and variable terminal symbols are of two kinds: delimiting and non-delimiting.

    [Definition: The delimiting terminal symbols are: !!=#$%()**:,-...::*:::=;<<<===!>=>=?>>>=>>????[@[]```{{{|||}}}×÷AposStringLiteralBracedURILiteral]]><![CDATA[--><!--/></<+#)(#?><?QuotStringLiteralS///]````[}``{StringLiteral ]

    [Definition: The non-delimiting terminal symbols are: allowingancestorancestor-or-selfandarrayasatattributebase-uriboundary-spacebycasecastcastablecatchchildcollationcommentconstructioncontextcopy-namespacescountdecimal-formatdecimal-separatordeclaredefaultdescendantdescendant-or-selfdigitdivdocumentdocument-nodeelementelseemptyempty-sequenceencodingendenumeqeveryexceptexponent-separatorfalsefixedfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selfforfunctiongegroupgrouping-separatorgtidivifimportininfinityinheritinstanceintersectisitemitemskeykeyslaxleletltmapmemberminus-signmodmodulenamespacenamespace-nodeNaNnenextno-inheritno-preservenodeofonlyoptionororderorderedorderingotherwisepairsparentpattern-separatorper-millepercentprecedingpreceding-or-selfpreceding-sibling-or-selfpreservepreviousprocessing-instructionrecordreturnsatisfiesschemaschema-attributeschema-elementselfslidingsomestablestartstrictstripswitchtextthentotreattruetrytumblingtypetypeswitchunionunorderedvalidatevaluevaluesvariableversionwhenwherewhilewindowxqueryzero-digitascendingBinaryIntegerLiteralDecimalLiteraldescendingDoubleLiteralexternalgreatestHexIntegerLiteralIntegerLiteralleastNCNameQNameURIQualifiedName ]

    [Definition: Whitespace and Comments function as symbol separators. For the most part, they are not mentioned in the grammar, and may occur between any two terminal symbols mentioned in the grammar, except where that is forbidden by the /* ws: explicit */ annotation in the EBNF, or by the /* xgc: xml-version */ annotation.]

    As a consequence of the longest token rule (see A.3 Lexical structure), one or more symbol separators are required between two consecutive terminal symbols T and U (where T precedes U) when any of the following is true:

    A.3.3 Less-Than and Greater-Than Characters

    The operator symbols <, <=, >, >=, <<, >>, =>, =!>, and =?> have alternative representations using the characters U+FF1C (FULL-WIDTH LESS-THAN SIGN, ) and U+FF1E (FULL-WIDTH GREATER-THAN SIGN, ) in place of U+003C (LESS-THAN SIGN, <) and U+003E (GREATER-THAN SIGN, >) . The alternative tokens are respectively , <=, , >=, <<, >>, =>, =!>, and =?>. In order to avoid visual confusion these alternatives are not shown explicitly in the grammar.

    This option is provided to improve the readability of XPath expressions embedded in XML-based host languages such as XSLT; it enables these operators to be depicted using characters that do not require escaping as XML entities or character references.

    This rule does not apply to the < and > symbols used to delimit node constructor expressions, which (because they mimic XML syntax) must use U+003C (LESS-THAN SIGN, <) and U+003E (GREATER-THAN SIGN, >) respectively.

    A.3.4 End-of-Line Handling

    The host language must specify whether the XQuery 4.0 and XPath 4.0 processor normalizes all line breaks on input, before parsing, and if it does so, whether it uses the rules of [XML 1.0] or [XML 1.1].

    Note:

    XML-based host languages such as XSLT and XSD do not normalize line breaks at the XPath level, because it will already have been done by the host XML parser. Use of character or entity references suppresses normalization of line breaks, so the string literal &#x0D; written within an XSLT-hosted XPath expression represents a string containing a single U+000D (CARRIAGE RETURN) character.

    Prior to parsing, the XQuery 4.0 and XPath 4.0 processor must normalize all line breaks. The rules for line breaking follow the rules of [XML 1.0] or [XML 1.1]. It is implementation-defined which version is used.

    A.3.4.1 XML 1.0 End-of-Line Handling

    For [XML 1.0] processing, all of the following must be translated to a single U+000A (NEWLINE) :

    1. the two-character sequence U+000D (CARRIAGE RETURN) , U+000A (NEWLINE) ;

    2. any U+000D (CARRIAGE RETURN) character that is not immediately followed by U+000A (NEWLINE) .

    A.3.4.2 XML 1.1 End-of-Line Handling

    For [XML 1.1] processing, all of the following must be translated to a single U+000A (NEWLINE) character:

    1. the two-character sequence U+000D (CARRIAGE RETURN) , U+000A (NEWLINE) ;

    2. the two-character sequence U+000D (CARRIAGE RETURN) , U+0085 (NEXT LINE, NEL) ;

    3. the single character U+0085 (NEXT LINE, NEL) ;

    4. the single character U+2028 (LINE SEPARATOR) ;

    5. any U+000D (CARRIAGE RETURN) character that is not immediately followed by U+000A (NEWLINE) or U+0085 (NEXT LINE, NEL) .

    The characters U+0085 (NEXT LINE, NEL) and U+2028 (LINE SEPARATOR) cannot be reliably recognized and translated until the VersionDecl declaration (if present) has been read.

    A.3.5 Whitespace Rules

    A.3.5.1 Default Whitespace Handling

    [Definition: A whitespace character is any of the characters defined by [http://www.w3.org/TR/REC-xml/#NT-S].]

    [Definition: Ignorable whitespace consists of any whitespace characters that may occur between terminals, unless these characters occur in the context of a production marked with a ws:explicit annotation, in which case they can occur only where explicitly specified (see A.3.5.2 Explicit Whitespace Handling).] Ignorable whitespace characters are not significant to the semantics of an expression. Whitespace is allowed before the first terminal and after the last terminal of a moduleof an XPath expression. Whitespace is allowed between any two terminals. Comments may also act as "whitespace" to prevent two adjacent terminals from being recognized as one. Some illustrative examples are as follows:

    • foo- foo results in a syntax error. "foo-" would be recognized as a QName.

    • foo -foo is syntactically equivalent to foo - foo, two QNames separated by a subtraction operator.

    • foo(: This is a comment :)- foo is syntactically equivalent to foo - foo. This is because the comment prevents the two adjacent terminals from being recognized as one.

    • foo-foo 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.

    • 10div 3 results in a syntax error.

    • 10 div3 also results in a syntax error.

    • 10div3 also results in a syntax error.

    A.3.5.2 Explicit Whitespace Handling

    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.

    ws: explicit

    /* ws: explicit */ means that the EBNF notation explicitly notates, with S or otherwise, where whitespace characters are allowed. In productions with the /* ws: explicit */ annotation, A.3.5.1 Default Whitespace Handling does not apply. Comments are not allowed in these productions except where the Comment non-terminal appears.

    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.

    A.4 Reserved Function Names

    Changes in 4.0  

    1. XQuery and XPath 3.0 included empty-sequence and item as reserved function names, and XQuery and XPath 3.1 added map and array. This was unnecessary since these names never appear followed by a left parenthesis at the start of an expression. They have therefore been removed from the list. New keywords introducing item types, such as record and enum, have not been included in the list.   [Issue 1208 PR 1212 15 May 2024]

    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.

    Names used in KindTests:

    attribute
    comment
    document-node
    element
    namespace-node
    node
    schema-attribute
    schema-element
    processing-instruction
    text

    Names used as syntactic keywords:

    fn
    function
    if
    switch
    typeswitch

    Note:

    Although the keywords switch and typeswitch are not used in XPath, they are considered reserved function names for compatibility with XQuery.

    Note:

    As the language evolves in the future, it may become necessary to reserve additional names. Furthermore, use of common programming terms like return and while 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.

    A.5 Precedence Order (Non-Normative)

    The grammar in A.1 EBNF normatively defines built-in precedence among the operators of XQueryXPath. 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.

    #OperatorAssociativity
    1, (comma)either
    2for,let,FLWOR,some, every, switch,typeswitch,try,ifNA
    3oreither
    4andeither
    5eq, ne, lt, le, gt, ge, =, !=, <, <=, >, >=, is, <<, >>NA
    6otherwiseeither
    7||left-to-right
    8toNA
    9+, - (binary)left-to-right
    10*, div, idiv, modleft-to-right
    11union, |either
    12intersect, exceptleft-to-right
    13instance ofNA
    14treat asNA
    15castable asNA
    16cast asNA
    17=>, =!>, =?>left-to-right
    18-, + (unary)right-to-left
    19!left-to-right
    20/, //left-to-right
    21[ ], ?, ??left-to-right
    22? (unary)NA

    In the "Associativity" column, "either" indicates that all the operators at that level have the associative property (i.e., (A op B) op C is equivalent to A op (B op C)), so their associativity is inconsequential. "NA" (not applicable) indicates that the EBNF does not allow an expression that directly contains multiple operators from that precedence level, so the question of their associativity does not arise.

    Note:

    Parentheses can be used to override the operator precedence in the usual way. Square brackets in an expression such as A[B] 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.

    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.

    B Type Promotion and Operator Mapping

    B.1 Type Promotion

    [Definition: Under certain circumstances, an atomic item can be promoted from one type to another.] Type promotion is used in a number of contexts:

    • It forms part of the process described by the coercion rules, invoked for example when a value of one type is supplied as an argument of a function call where the required type of the corresponding function parameter is declared with a different type.

    • It forms part of the process described in B.2 Operator Mapping, which selects the implementation of a binary operator based on the types of the supplied operands.

    • It is invoked (by explicit reference) in a number of other situations, for example when computing an average of a sequence of numeric values (in the fn:avg function), and in order by clauses (see 4.13.9 Order By Clause).

    In general, type promotion takes a set of one or more atomic items as input, potentially having different types, and selects a single common type to which all the input values can be converted by casting.

    There are three families of atomic types that can be mixed in this way:

    1. Numeric types. This applies when the input contains values of types xs:decimal, xs:float, and xs:double (including types derived from these, such as xs:integer).

      The rules are:

      1. If any of the items is of type xs:double, then all the values are cast to type xs:double.

      2. Otherwise, if any of the items is of type xs:float, then all the values are cast to type xs:float.

      3. Otherwise, no casting takes place: the values remain as xs:decimal.

    2. String types. This applies when the input contains values of types xs:string and xs:anyURI (including types derived from these, such as xs:NCName).

      The rule is that if any of the items is of type xs:string, then all the values are cast to type xs:string.

    3. Binary types. This applies when the input contains values of types xs:hexBinary and xs:base64Binary (including types derived from these).

      The rule is that if any of the items is of type xs:hexBinary, then all the values are cast to type xs:hexBinary.

    B.2 Operator Mapping

    Changes in 4.0  

    1. The operator mapping table has been simplified by removing entries for the operators ne, le, gt, and ge; these are now defined by reference to the rules for the operators eq and lt.

    The operator mapping tables in this section list the combinations of types for which various operators of XQuery 4.0 and XPath 4.0 are defined. The operators covered by this appendix are the value comparison operators eq and lt, and the arithmetic operators +, -, *, div, idiv, and mod.

    Other operators (such as and, or, intersect, union, =, ||, and is) are defined directly in the main body of this document, and do not occur in the operator mapping table.

    The operators ne, le, gt, and ge do not occur in the operator mapping table, but are instead defined by the following equivalences:

    • A ne B is equivalent to not(A eq B)

    • A le B is equivalent to A lt B or A eq B

    • A gt B is equivalent to B lt A

    • A ge B is equivalent to B lt A or B eq A

    [Definition: For each operator and valid combination of operand types, the operator mapping tables specify a result type and an expression that invokes an operator function; the operator function implements the semantics of the operator for the given types.] The definitions of the operator functions are given in [XQuery and XPath Functions and Operators 4.0]. The result of an operator may be the raising of an error by its operator function, as defined in [XQuery and XPath Functions and Operators 4.0]. The operator function fully defines the semantics of a given operator for the case where the operands are single atomic items of the types given in the table. For the definition of each operator (including its behavior for empty sequences or sequences of length greater than one), see the descriptive material in the main part of this document.

    If an operator in the operator mapping tables expects an operand of type ET, that operator can be applied to an operand of type AT if type AT can be converted to type ET by a combination of type promotion and subtype substitution. For example, a table entry indicates that the gt operator may be applied to two xs:date operands, returning xs:boolean. Therefore, the gt operator may also be applied to two (possibly different) subtypes of xs:date, also returning xs:boolean.

    [Definition: When referring to a type, the term numeric denotes the types xs:integer, xs:decimal, xs:float, and xs:double which are all member types of the built-in union type xs:numeric.] An operator whose operands and result are designated as numeric might be thought of as representing four operators, one for each of the numeric types. For example, the numeric + operator might be thought of as representing the following four operators:

    OperatorFirst operand typeSecond operand typeResult type
    +xs:integerxs:integerxs:integer
    +xs:decimalxs:decimalxs:decimal
    +xs:floatxs:floatxs:float
    +xs:doublexs:doublexs:double

    A numeric operator may be validly applied to an operand of type AT if type AT can be converted to any of the four numeric types by a combination of type promotion and subtype substitution. If the result type of an operator is listed as numeric, it means "the first type in the ordered list (xs:integer, xs:decimal, xs:float, xs:double) into which all operands can be converted by subtype substitution and type promotion." As an example, suppose that the type hatsize is derived from xs:integer and the type shoesize is derived from xs:float. Then if the + operator is invoked with operands of type hatsize and shoesize, it returns a result of type xs:float. Similarly, if + is invoked with two operands of type hatsize it returns a result of type xs:integer.

    [Definition: In the operator mapping tables, the term Gregorian refers to the types xs:gYearMonth, xs:gYear, xs:gMonthDay, xs:gDay, and xs:gMonth.] For binary operators that accept two Gregorian-type operands, both operands must have the same type (for example, if one operand is of type xs:gDay, the other operand must be of type xs:gDay.)

    [Definition: In the operator mapping tables, the term binary refers to the types xs:hexBinary and xs:base64Binary.] For operators that accept two binary operands, both operands are promoted to type xs:hexBinary.

    Binary Operators
    OperatorType(A)Type(B)FunctionResult type
    A + Bnumericnumericop:numeric-add(A, B)numeric
    A + Bxs:datexs:yearMonthDurationop:add-yearMonthDuration-to-date(A, B)xs:date
    A + Bxs:yearMonthDurationxs:dateop:add-yearMonthDuration-to-date(B, A)xs:date
    A + Bxs:datexs:dayTimeDurationop:add-dayTimeDuration-to-date(A, B)xs:date
    A + Bxs:dayTimeDurationxs:dateop:add-dayTimeDuration-to-date(B, A)xs:date
    A + Bxs:timexs:dayTimeDurationop:add-dayTimeDuration-to-time(A, B)xs:time
    A + Bxs:dayTimeDurationxs:timeop:add-dayTimeDuration-to-time(B, A)xs:time
    A + Bxs:dateTimexs:yearMonthDurationop:add-yearMonthDuration-to-dateTime(A, B)xs:dateTime
    A + Bxs:yearMonthDurationxs:dateTimeop:add-yearMonthDuration-to-dateTime(B, A)xs:dateTime
    A + Bxs:dateTimexs:dayTimeDurationop:add-dayTimeDuration-to-dateTime(A, B)xs:dateTime
    A + Bxs:dayTimeDurationxs:dateTimeop:add-dayTimeDuration-to-dateTime(B, A)xs:dateTime
    A + Bxs:yearMonthDurationxs:yearMonthDurationop:add-yearMonthDurations(A, B)xs:yearMonthDuration
    A + Bxs:dayTimeDurationxs:dayTimeDurationop:add-dayTimeDurations(A, B)xs:dayTimeDuration
    A - Bnumericnumericop:numeric-subtract(A, B)numeric
    A - Bxs:datexs:dateop:subtract-dates(A, B)xs:dayTimeDuration
    A - Bxs:datexs:yearMonthDurationop:subtract-yearMonthDuration-from-date(A, B)xs:date
    A - Bxs:datexs:dayTimeDurationop:subtract-dayTimeDuration-from-date(A, B)xs:date
    A - Bxs:timexs:timeop:subtract-times(A, B)xs:dayTimeDuration
    A - Bxs:timexs:dayTimeDurationop:subtract-dayTimeDuration-from-time(A, B)xs:time
    A - Bxs:dateTimexs:dateTimeop:subtract-dateTimes(A, B)xs:dayTimeDuration
    A - Bxs:dateTimexs:yearMonthDurationop:subtract-yearMonthDuration-from-dateTime(A, B)xs:dateTime
    A - Bxs:dateTimexs:dayTimeDurationop:subtract-dayTimeDuration-from-dateTime(A, B)xs:dateTime
    A - Bxs:yearMonthDurationxs:yearMonthDurationop:subtract-yearMonthDurations(A, B)xs:yearMonthDuration
    A - Bxs:dayTimeDurationxs:dayTimeDurationop:subtract-dayTimeDurations(A, B)xs:dayTimeDuration
    A * Bnumericnumericop:numeric-multiply(A, B)numeric
    A * Bxs:yearMonthDurationnumericop:multiply-yearMonthDuration(A, B)xs:yearMonthDuration
    A * Bnumericxs:yearMonthDurationop:multiply-yearMonthDuration(B, A)xs:yearMonthDuration
    A * Bxs:dayTimeDurationnumericop:multiply-dayTimeDuration(A, B)xs:dayTimeDuration
    A * Bnumericxs:dayTimeDurationop:multiply-dayTimeDuration(B, A)xs:dayTimeDuration
    A × Bnumericnumericop:numeric-multiply(A, B)numeric
    A × Bxs:yearMonthDurationnumericop:multiply-yearMonthDuration(A, B)xs:yearMonthDuration
    A × Bnumericxs:yearMonthDurationop:multiply-yearMonthDuration(B, A)xs:yearMonthDuration
    A × Bxs:dayTimeDurationnumericop:multiply-dayTimeDuration(A, B)xs:dayTimeDuration
    A × Bnumericxs:dayTimeDurationop:multiply-dayTimeDuration(B, A)xs:dayTimeDuration
    A idiv Bnumericnumericop:numeric-integer-divide(A, B)xs:integer
    A div Bnumericnumericop:numeric-divide(A, B)numeric; but xs:decimal if both operands are xs:integer
    A div Bxs:yearMonthDurationnumericop:divide-yearMonthDuration(A, B)xs:yearMonthDuration
    A div Bxs:dayTimeDurationnumericop:divide-dayTimeDuration(A, B)xs:dayTimeDuration
    A div Bxs:yearMonthDurationxs:yearMonthDurationop:divide-yearMonthDuration-by-yearMonthDuration (A, B)xs:decimal
    A div Bxs:dayTimeDurationxs:dayTimeDurationop:divide-dayTimeDuration-by-dayTimeDuration (A, B)xs:decimal
    A ÷ Bnumericnumericop:numeric-divide(A, B)numeric; but xs:decimal if both operands are xs:integer
    A ÷ Bxs:yearMonthDurationnumericop:divide-yearMonthDuration(A, B)xs:yearMonthDuration
    A ÷ Bxs:dayTimeDurationnumericop:divide-dayTimeDuration(A, B)xs:dayTimeDuration
    A ÷ Bxs:yearMonthDurationxs:yearMonthDurationop:divide-yearMonthDuration-by-yearMonthDuration (A, B)xs:decimal
    A ÷ Bxs:dayTimeDurationxs:dayTimeDurationop:divide-dayTimeDuration-by-dayTimeDuration (A, B)xs:decimal
    A mod Bnumericnumericop:numeric-mod(A, B)numeric
    A eq Bnumericnumericop:numeric-equal(A, B)xs:boolean
    A eq Bxs:booleanxs:booleanop:boolean-equal(A, B)xs:boolean
    A eq Bxs:stringxs:stringop:numeric-equal(fn:compare(A, B), 0)xs:boolean
    A eq Bxs:datexs:dateop:date-equal(A, B)xs:boolean
    A eq Bxs:timexs:timeop:time-equal(A, B)xs:boolean
    A eq Bxs:dateTimexs:dateTimeop:dateTime-equal(A, B)xs:boolean
    A eq Bxs:durationxs:durationop:duration-equal(A, B)xs:boolean
    A eq BGregorianGregorianop:gYear-equal(A, B) etc.xs:boolean
    A eq Bbinarybinaryop:binary-equal(A, B)xs:boolean
    A eq Bxs:QNamexs:QNameop:QName-equal(A, B)xs:boolean
    A eq Bxs:NOTATIONxs:NOTATIONop:NOTATION-equal(A, B)xs:boolean
    A lt Bnumericnumericop:numeric-less-than(A, B)xs:boolean
    A lt Bxs:booleanxs:booleanop:boolean-less-than(A, B)xs:boolean
    A lt Bxs:stringxs:stringop:numeric-less-than(fn:compare(A, B), 0)xs:boolean
    A lt Bxs:datexs:dateop:date-less-than(A, B)xs:boolean
    A lt Bxs:timexs:timeop:time-less-than(A, B)xs:boolean
    A lt Bxs:dateTimexs:dateTimeop:dateTime-less-than(A, B)xs:boolean
    A lt Bxs:yearMonthDurationxs:yearMonthDurationop:yearMonthDuration-less-than(A, B)xs:boolean
    A lt Bxs:dayTimeDurationxs:dayTimeDurationop:dayTimeDuration-less-than(A, B)xs:boolean
    A lt Bbinarybinaryop:binary-less-than(A, B)xs:boolean
    Unary Operators
    OperatorOperand typeFunctionResult type
    + Anumericop:numeric-unary-plus(A)numeric
    - Anumericop:numeric-unary-minus(A)numeric

    C Context Components

    The tables in this section describe how values are assigned to the various components of the static context and dynamic context.

    C.1 Static Context Components

    Changes in 4.0 

    1. 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.   [Issue 1343 ]

    The following table describes the components of the static context. The following aspects of each component are described:

    • Default initial value: This is the initial value of the component if it is not overridden or augmented by the implementation or by a query.

    • Can be overwritten or augmented by implementation: Indicates whether an XQuery implementation is allowed to replace the default initial value of the component by a different, implementation-defined value and/or to augment the default initial value by additional implementation-defined values.

    • Can be overwritten or augmented by prolog: Indicates whether there are prolog declarations that can replace and/or augment the initial value provided by default or by the implementation.

    • Can be overwritten or augmented by expressions: Indicates whether there are expressions that can replace and/or augment the value of the component for their subexpressions.

    • Consistency Rules: Indicates rules that must be observed in assigning values to the component. Additional consistency rules may be found in 2.3.6 Consistency Constraints.

    Static Context Components
    ComponentDefault initial valueCan be overwritten or augmented by implementation?Can be overwritten or augmented by prolog?Can be overwritten or augmented by expressions?Consistency rules
    Statically known namespacesfn, xml, xs, xsi, localoverwriteable and augmentable (except for xml)overwriteable and augmentable by 5.13 Namespace Declarationoverwriteable and augmentable by element constructorOnly one namespace can be assigned to a given prefix per lexical scope.
    Default element/type namespaceno namespaceoverwriteableoverwriteable by 5.14 Default Namespace Declarationoverwriteable by element constructorOnly one default namespace per lexical scope.
    In-scope variablesnoneaugmentableoverwriteable and augmentable by 5.16 Variable Declaration and 4.5.2.5 Inline Function Expressions, augmentable by 5.12 Module Importoverwriteable and augmentable by variable-binding expressionsOnly one definition per variable per lexical scope.
    Context value static typeitem()overwriteableoverwriteable by 5.17 Context Value Declarationoverwriteable by expressions that set the context valueNone.
    Ordering modeorderedoverwriteableoverwriteable by 5.7 Ordering Mode Declarationoverwriteable by expressionValue must be ordered or unordered.
    Default function namespacefnoverwriteable (not recommended)overwriteable by 5.14 Default Namespace DeclarationnoNone.
    In-scope schema typesbuilt-in types in xsaugmentableaugmentable by 5.11 Schema ImportnoOnly one definition per global or local type.
    In-scope element declarationsnoneaugmentableaugmentable by 5.11 Schema ImportnoOnly one definition per global or local element name.
    In-scope attribute declarationsnoneaugmentableaugmentable by 5.11 Schema ImportnoOnly one definition per global or local attribute name.
    Statically known function signaturesthe signatures of the system functionsaugmentableaugmentable by 5.12 Module Import and by 5.18 Function Declarations; augmentable by 5.11 Schema Import (which adds constructor functions for user-defined types)noEach function must have a unique expanded QName and number of arguments.
    Default collationUnicode codepoint collationoverwriteableoverwriteable by 5.4 Default Collation DeclarationnoNone.
    Construction modepreserveoverwriteableoverwriteable by 5.6 Construction DeclarationnoValue must be preserve or strip.
    Default order for empty sequencesimplementation-definedoverwriteableoverwriteable by 5.8 Empty Order DeclarationnoValue must be greatest or least.
    Boundary-space policystripoverwriteableoverwriteable by 5.3 Boundary-space DeclarationnoValue must be preserve or strip.
    Copy-namespaces modeinherit, preserveoverwriteableoverwriteable by 5.9 Copy-Namespaces DeclarationnoValue consists of inherit or no-inherit, and preserve or no-preserve.
    Static Base URISee rules in 5.5 Base URI Declarationoverwriteableoverwriteable by 5.5 Base URI DeclarationnoValue must be a valid lexical representation of the type xs:anyURI.
    Statically known decimal formatsthe default (unnamed) decimal format, which has an implementation-dependent valueaugmentableaugmentable, using decimal format declarationsnoeach QName uniquely identifies a decimal format
    Statically known collationsonly the default collationaugmentablenonoEach URI uniquely identifies a collation.
    XPath 1.0 Compatibility ModefalsenononoMust be false.

    C.2 Dynamic Context Components

    The following table describes the components of the dynamic context. The following aspects of each component are described:

    • Default initial value: This is the initial value of the component if it is not overridden or augmented by the implementation or by a query.

    • Can be overwritten or augmented by implementation: Indicates whether an XQuery implementation is allowed to replace the default initial value of the component by a different implementation-defined value and/or to augment the default initial value by additional implementation-defined values.

    • Can be overwritten or augmented by prolog: Indicates whether there are prolog declarations that can replace and/or augment the initial value provided by default or by the implementation.

    • Can be overwritten or augmented by expressions: Indicates whether there are expressions that can replace and/or augment the value of the component for their subexpressions.

    • Consistency Rules: Indicates rules that must be observed in assigning values to the component. Additional consistency rules may be found in 2.3.6 Consistency Constraints.

    Dynamic Context Components
    ComponentDefault initial valueCan be overwritten or augmented by implementation?Can be overwritten or augmented by prolog?Can be overwritten or augmented by expressions?Consistency rules
    Context valuenoneoverwriteableoverwriteable by a 5.17 Context Value Declaration in the main module overwritten during evaluation of path expressions and predicatesMust be the same in the dynamic context of every module in a query.
    Context positionnoneoverwriteableoverwriteable by a 5.17 Context Value Declaration in the main module overwritten during evaluation of path expressions and predicatesIf context value is defined, context position must be >0 and <= context size; else context position is absentDM31.
    Context sizenone overwriteableoverwriteable by a 5.17 Context Value Declaration in the main module overwritten during evaluation of path expressions and predicatesIf context value is defined, context size must be >0; else context size is absentDM31.
    Variable valuesnoneaugmentableoverwriteable and augmentable by 5.16 Variable Declaration and 4.5.2.5 Inline Function Expressions, augmentable by 5.12 Module Importoverwriteable and augmentable by variable-binding expressionsNames and values must be consistent with in-scope variables.
    Named functionsthe system functionsaugmentableaugmentable by 5.18 Function Declarations, 5.12 Module Import, and 5.11 Schema Import ( (which adds constructor functions for user-defined types)noMust be consistent with statically known function signatures
    Current dateTimenonemust be initialized by implementationnonoMust include a timezone. Remains constant during evaluation of a query.
    Implicit timezonenonemust be initialized by implementationnonoRemains constant during evaluation of a query.
    Available documentsnonemust be initialized by implementationnonoNone
    Available text resourcesnonemust be initialized by implementationnonoNone
    Available collectionsnonemust be initialized by implementationnonoNone
    Default collectionnoneoverwriteablenonoNone
    Available URI collectionsnonemust be initialized by implementationnonoNone
    Default URI collectionnoneoverwriteablenonoNone

    D Context Components

    The tables in this section describe the scope (range of applicability) of the various components in a module's static context and dynamic context.

    D.1 Static Context Components

    The following table describes the components of the static context. For each component, “global” indicates that the value of the component applies throughout an XPath expression, whereas “lexical” indicates that the value of the component applies only within the subexpression in which it is defined.

    Static Context Components
    ComponentScope
    XPath 1.0 Compatibility Modeglobal
    Statically known namespacesglobal
    Default element/type namespaceglobal
    Default function namespaceglobal
    In-scope schema typesglobal
    In-scope element declarationsglobal
    In-scope attribute declarationsglobal
    In-scope variableslexical; for-expressions, let-expressions, and quantified expressions can bind new variables
    Context value static typelexical
    Statically known function signaturesglobal
    Statically known collationsglobal
    Default collationglobal
    Base URIglobal
    Statically known documentsglobal
    Statically known collectionsglobal
    Statically known default collection typeglobal

    D.2 Dynamic Context Components

    The following table describes how values are assigned to the various components of the dynamic context. All these components are initialized by mechanisms defined by the host language. For each component, “global” indicates that the value of the component remains constant throughout evaluation of the XPath expression, whereas “dynamic” indicates that the value of the component can be modified by the evaluation of subexpressions.

    Dynamic Context Components
    ComponentScope
    Context valuedynamic; changes during evaluation of path expressions and predicates
    Context positiondynamic; changes during evaluation of path expressions and predicates
    Context sizedynamic; changes during evaluation of path expressions and predicates
    Variable valuesdynamic; for-expressions, let-expressions, and quantified expressions can bind new variables
    Current date and timeglobal; must be initialized by implementation
    Implicit timezoneglobal; must be initialized by implementation
    Available documentsglobal; must be initialized by implementation
    Available node collectionsglobal; must be initialized by implementation
    Default collectionglobal; overwriteable by implementation
    Available URI collectionsglobal; must be initialized by implementation
    Default URI collectionglobal; overwriteable by implementation

    E Implementation-Defined Items

    The following items in this specification are implementation-defined:

    1. The version of Unicode that is used to construct expressions.

    2. The statically-known collations.

    3. The implicit timezone.

    4. The circumstances in which warnings are raised, and the ways in which warnings are handled.

    5. The method by which errors are reported to the external processing environment.

    6. Which version of XML and XML Names (e.g. [XML 1.0] and [XML Names] or [XML 1.1] and [XML Names 1.1]) and which version of XML Schema (e.g. [XML Schema 1.0] or [XML Schema 1.1]) 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).

    7. How XDM instances are created from sources other than an Infoset or PSVI.

    8. Any components of the static context or dynamic context that are overwritten or augmented by the implementation.

    9. Whether the implementation supports the namespace axis.

    10. The default handling of empty sequences returned by an ordering key (orderspec) in an order by clause (empty least or empty greatest).

    11. The names and semantics of any extension expressions (pragmas) recognized by the implementation.

    12. The names and semantics of any option declarations recognized by the implementation.

    13. 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.

    14. The process by which the specific modules to be imported by a module import are identified, if the Module Feature is supported (includes processing of location hints, if any.)

    15. The means by which serialization is invoked, if the Serialization Feature is supported.

    16. The default values for the byte-order-mark, encoding, html-version, item-separator, media-type, normalization-form, omit-xml-declaration, standalone, and version parameters, if the Serialization Feature is supported.

    17. 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).

    18. Limits on ranges of values for various data types, as enumerated in 6.3 Data Model Conformance.

    19. Syntactic extensions to XQuery, including both their syntax and semantics, as discussed in 6.4 Syntax Extensions.

    20. Whether the type system is based on [XML Schema 1.0] or [XML Schema 1.1]. An implementation that has based its type system on XML Schema 1.0 is not required to support the use of the xs:dateTimeStamp constructor or the use of xs:dateTimeStamp or xs:error as TypeName in any expression.

    21. The signatures of functions provided by the implementation or via an implementation-defined API (see 2.2.1 Static Context).

    22. Any environment variables provided by the implementation.

    23. Any rules used for static typing (see 2.3.3.1 Static Analysis Phase).

    24. Any serialization parameters provided by the implementation (see 2.3.5 Serialization).

    25. The means by which the location hint for a serialization parameter document identifies the corresponding XDM instance (see 2.3.5 Serialization).

    26. What error, if any, is returned if an external function's implementation does not return the declared result type (see 2.3.6 Consistency Constraints).

    27. Any annotations defined by the implementation, and their associated behavior (see 5.15 Annotations).

    28. Any function assertions defined by the implementation.

    29. The effect of function assertions understood by the implementation on 3.3.3 The judgement subtype-assertions(AnnotationsA, AnnotationsB) .

    30. Any implementation-defined variables defined by the implementation. (see 4.2.2 Variable References).

    31. The ordering associated with fn:unordered in the implementation (see 4.15 Ordered and Unordered Expressions).

    32. Any additional information provided for try/catch via the err:additional variable (see 4.20 Try/Catch Expressions).

    33. The default boundary-space policy (see 5.3 Boundary-space Declaration).

    34. The default collation (see 5.4 Default Collation Declaration).

    35. The default base URI (see 5.5 Base URI Declaration).

    F References

    F.1 Normative References

    ISO/IEC 10646
    ISO (International Organization for Standardization). ISO/IEC 10646:2003. Information technology—Universal Multiple-Octet Coded Character Set (UCS), 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 http://www.iso.org for the latest version.)
    RFC2119
    S. Bradner. Key Words for use in RFCs to Indicate Requirement Levels. IETF RFC 2119. See http://www.ietf.org/rfc/rfc2119.txt.
    RFC3986
    T. Berners-Lee, R. Fielding, and L. Masinter. Uniform Resource Identifiers (URI): Generic Syntax. IETF RFC 3986. See http://www.ietf.org/rfc/rfc3986.txt.
    RFC3987
    M. Duerst and M. Suignard. Internationalized Resource Identifiers (IRIs). IETF RFC 3987. See http://www.ietf.org/rfc/rfc3987.txt.
    Unicode
    The Unicode Consortium. The Unicode Standard. Reading, Mass.: Addison-Wesley, 2003, as updated from time to time by the publication of new versions. See http://www.unicode.org/standard/versions/ 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 implementation-defined, but implementations are recommended to use the latest Unicode version.
    XML 1.0
    World Wide Web Consortium. Extensible Markup Language (XML) 1.0. W3C Recommendation. See http://www.w3.org/TR/REC-xml/. The edition of XML 1.0 must be no earlier than the Third Edition; the edition used is implementation-defined, but we recommend that implementations use the latest version.
    XML 1.1
    World Wide Web Consortium. Extensible Markup Language (XML) 1.1. W3C Recommendation. See http://www.w3.org/TR/xml11/
    XML Base
    World Wide Web Consortium. XML Base. W3C Recommendation. See http://www.w3.org/TR/xmlbase/
    XML ID
    World Wide Web Consortium. xml:id Version 1.0. W3C Recommendation. See http://www.w3.org/TR/xml-id/
    XML Names
    World Wide Web Consortium. Namespaces in XML. W3C Recommendation. See http://www.w3.org/TR/REC-xml-names/
    XML Names 1.1
    World Wide Web Consortium. Namespaces in XML 1.1. W3C Recommendation. See http://www.w3.org/TR/xml-names11/
    XML Schema 1.0
    World Wide Web Consortium. XML Schema, Parts 0, 1, and 2 (Second Edition). W3C Recommendation, 28 October 2004. See http://www.w3.org/TR/xmlschema-0/, http://www.w3.org/TR/xmlschema-1/, and http://www.w3.org/TR/xmlschema-2/.
    XML Schema 1.1
    World Wide Web Consortium. XML Schema, Parts 1, and 2. W3C Recommendation 5 April 2012. See http://www.w3.org/TR/xmlschema11-1/, and http://www.w3.org/TR/xmlschema11-2/.
    XPath 4.0
    XML Path Language (XPath) 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
    XQuery and XPath Data Model (XDM) 4.0
    XQuery and XPath Data Model (XDM) 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
    XQuery and XPath Functions and Operators 4.0
    XQuery and XPath Functions and Operators 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
    XSLT and XQuery Serialization 4.0
    XSLT and XQuery Serialization 4.0, XSLT Extensions Community Group, World Wide Web Consortium.

    F.2 Non-normative References

    Document Object Model
    World Wide Web Consortium. Document Object Model (DOM) Level 3 Core Specification. W3C Recommendation, April 7, 2004. See http://www.w3.org/TR/DOM-Level-3-Core/.
    ODMG
    Rick Cattell et al. The Object Database Standard: ODMG-93, Release 1.2. Morgan Kaufmann Publishers, San Francisco, 1996.
    Quilt
    Don Chamberlin, Jonathan Robie, and Daniela Florescu. Quilt: an XML Query Language for Heterogeneous Data Sources. In Lecture Notes in Computer Science, Springer-Verlag, Dec. 2000.
    SQL
    International Organization for Standardization (ISO). Information Technology — Database Language SQL. Standard No. ISO/IEC 9075:2011. (Available from American National Standards Institute, New York, NY 10036, (212) 642-4900.)
    Uniform Resource Locators (URL)
    Internet Engineering Task Force (IETF). Uniform Resource Locators (URL). Request For Comment No. 1738, Dec. 1994. See http://www.ietf.org/rfc/rfc1738.txt.
    XML 1.1 and Schema 1.0
    World Wide Web Consortium. Processing XML 1.1 Documents with XML Schema 1.0 Processors. W3C Working Group Note, 11 May 2005. See http://www.w3.org/TR/xml11schema10/.
    XML Infoset
    World Wide Web Consortium. XML Information Set (Second Edition). W3C Recommendation 4 February 2004. See http://www.w3.org/TR/xml-infoset/
    XML Path Language (XPath) Version 1.0
    XML Path Language (XPath) Version 1.0, 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 latest version is available at http://www.w3.org/TR/xpath.
    XML Path Language (XPath) Version 2.0
    XML Path Language (XPath) 2.0 (Second Edition), Don Chamberlin, Anders Berglund, Scott Boag, et. al., Editors. World Wide Web Consortium, 14 December 2010. This version is https://www.w3.org/TR/2010/REC-xpath20-20101214/. The latest version is available at https://www.w3.org/TR/xpath20/.
    XML Path Language (XPath) Version 3.0
    XML Path Language (XPath) 3.0, 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 latest version is available at https://www.w3.org/TR/xpath-30/.
    XML Path Language (XPath) Version 3.1
    XML Path Language (XPath) 3.1, 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 latest version is available at https://www.w3.org/TR/xpath-31/.
    XML Query Use Cases
    World Wide Web Consortium. XML Query Use Cases. W3C Working Draft, 8 June 2006. See http://www.w3.org/TR/xquery-use-cases/.
    XML-QL
    Alin Deutsch, Mary Fernandez, Daniela Florescu, Alon Levy, and Dan Suciu. A Query Language for XML.
    XPointer
    World Wide Web Consortium. XML Pointer Language (XPointer). W3C Last Call Working Draft 8 January 2001. See http://www.w3.org/TR/WD-xptr
    XQL
    J. Robie, J. Lapp, D. Schach. XML Query Language (XQL). See http://www.w3.org/TandS/QL/QL98/pp/xql.html.
    XQuery 1.0 and XPath 2.0 Formal Semantics
    XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition), Jérôme Siméon, Denise Draper, Peter Frankhauser, et. al., Editors. World Wide Web Consortium, 14 December 2010. This version is https://www.w3.org/TR/2010/REC-xquery-semantics-20101214/. The latest version is available at https://www.w3.org/TR/xquery-semantics/.
    XQuery 3.0 Requirements
    XQuery 3.0 Requirements, 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 latest version is available at https://www.w3.org/TR/xquery-30-requirements/.
    XQuery 3.0: An XML Query Language
    XQuery 3.0: An XML Query Language, 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 latest version is available at https://www.w3.org/TR/xquery-30/.
    XQuery 3.1 Requirements
    XQuery 3.1 Requirements and Use Cases, 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 latest version is available at https://www.w3.org/TR/xquery-31-requirements/.
    XQuery 3.1: An XML Query Language
    XQuery 3.1: An XML Query Language, 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-xquery-31-20170321/. The latest version is available at https://www.w3.org/TR/xquery-31/.
    XSL Transformations (XSLT) Version 4.0
    XSL Transformations (XSLT) Version 4.0, XSLT Extensions Community Group, World Wide Web Consortium.

    F.3 Background Material

    Character Model
    World Wide Web Consortium. Character Model for the World Wide Web. W3C Working Draft. See http://www.w3.org/TR/charmod/.
    Moustache
    mustache - Logic-less templates. See http://mustache.github.io/mustache.5.html.
    Use Case Sample Queries
    Queries from the XQuery 1.0 Use Cases, presented in a single file. See http://www.w3.org/2010/12/xquery-30-use-cases/xquery-30-use-case-queries.txt.
    XQuery Sample Queries
    Queries from this document, presented in a single file. See http://www.w3.org/2013/01/xquery-30-use-cases/xquery-30-example-queries.txt.
    XSL Transformations (XSLT) Version 1.0
    XSL Transformations (XSLT) Version 1.0, James Clark, Editor. World Wide Web Consortium, 16 Nov 1999. This version is http://www.w3.org/TR/1999/REC-xslt-19991116. The latest version is available at http://www.w3.org/TR/xslt.

    G Error Conditions

    err:XPST0001

    It is a static error if analysis of an expression relies on some component of the static context that is absentDM.

    err:XPDY0002

    It is a type error if evaluation of an expression relies on some part of the dynamic context that is absentDM.

    Note:

    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 fn($x) { @code }. The error code is prefixed XPDY rather than XPTY for backwards compatibility reasons.

    err:XPST0003

    It is a static error if an expression is not a valid instance of the grammar defined in A.1 EBNF.

    err:XPTY0004

    It is a type error if, during the static analysis phase, an expression is found to have a static type that is not appropriate for the context in which the expression occurs, or during the dynamic evaluation phase, the dynamic type of a value does not match a required type as specified by the matching rules in 3.1.2 Sequence Type Matching.

    err:XPTY0006

    During the analysis phase, an expression is classified as implausible if the inferred static typeS and the required type R 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.

    err:XPST0008

    It is a static error if an expression refers to an element name, attribute name, schema type name, namespace prefix, or variable name that is not defined in the static context, except for an ElementName in an ElementTest or an AttributeName in an AttributeTest.

    err:XQST0009

    An implementation that does not support the Schema Aware Feature must raise a static error if a Prolog contains a schema import.

    err:XPST0010

    An implementation that does not support the namespace axis must raise a static error if it encounters a reference to the namespace axis and XPath 1.0 compatibility mode is false.

    err:XQST0012

    It is a static error 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 [XML Schema 1.0] or [XML Schema 1.1].

    err:XQST0013

    It is a static error if an implementation recognizes a pragma but determines that its content is invalid.

    err:XQST0016

    An implementation that does not support the Module Feature raises a static error if it encounters a module declaration or a module import.

    err:XPST0017

    It is a static error if the expanded QName and number of arguments in a static function call do not match the name and arity range of a function definition in the static context, 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.

    err:XPTY0018

    It is a type error if the result of a path operator contains both nodes and non-nodes.

    err:XPTY0019

    It is a type error if E1 in a path expression E1/E2 does not evaluate to a sequence of nodes.

    err:XPTY0020

    It is a type error if, in an axis step, the context item is not a node.

    err:XPST0021

    It is a static error if two fields in a record declaration have the same name.

    err:XQST0022

    It is a static error if a namespace declaration attributecontains an EnclosedExpr.

    err:XPST0023

    It is a static error 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.

    err:XQTY0024

    It is a type error if the content sequence in an element constructor contains an attribute node following a node that is not an attribute node.

    err:XQDY0025

    It is a dynamic error 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.

    err:XQDY0026

    It is a dynamic error if the result of the content expression of a computed processing instruction constructor contains the string "?>".

    err:XQDY0027

    In a validate expression, it is a dynamic error if the root element information item in the PSVI resulting from validation does not have the expected validity property: valid if validation mode is strict, or either valid or notKnown if validation mode is lax.

    err:XQTY0030

    It is a type error if the argument of a validate expression does not evaluate to exactly one document or element node.

    err:XQST0031

    It is a static error if the version number specified in a version declaration is not supported by the implementation.

    err:XQST0032

    A static error is raised if a Prolog contains more than one base URI declaration.

    err:XQST0033

    It is a static error if a module contains multiple bindings for the same namespace prefix.

    err:XQST0034

    It is a static error if multiple functions declared or imported by a module have the same expanded QName and overlapping arity ranges (the arity range of a function declaration is M to M+N, where M is the number of required parameters and N is the number of optional parameters).

    err:XQST0035

    It is a static error to import two schema components that both define the same name in the same symbol space and in the same scope.

    err:XQST0038

    It is a static error if a Prolog contains more than one default collation declaration, or the value specified by a default collation declaration is not present in statically known collations.

    err:XQST0039

    It is a static error for a function declaration oran inline function expression to have more than one parameter with the same name.

    err:XQST0040

    It is a static error if the attributes specified by a direct element constructor do not have distinct expanded QNames.

    err:XQDY0041

    It is a dynamic error if the value of the name expression in a computed processing instruction constructor cannot be cast to the type xs:NCName.

    err:XQDY0044

    It is a dynamic error the node-name of a node constructed by a computed attribute constructor has any of the following properties:

    • Its namespace prefix is xmlns.

    • It has no namespace prefix and its local name is xmlns.

    • Its namespace URI is http://www.w3.org/2000/xmlns/.

    • Its namespace prefix is xml and its namespace URI is not http://www.w3.org/XML/1998/namespace.

    • Its namespace prefix is other than xml and its namespace URI is http://www.w3.org/XML/1998/namespace.

    err:XQST0045

    It is a static error if the name of a variable annotation, a function annotation, or the function name in a function declaration is in a reserved namespace.

    err:XQST0046

    An implementation MAYMAY raise a static error if the value of a URILiteral or a BracedURILiteral is of nonzero length and is neither an absolute URI nor a relative URI.

    err:XQST0047

    It is a static error if multiple module imports in the same Prolog specify the same target namespace.

    err:XQST0048

    It is a static error if a function, variable, or item type declared in a library module is not in the target namespace of the library module.

    err:XQST0049

    It is a static error if two or more variables declared or imported by a module have equal expanded QNames (as defined by the eq operator.)

    err:XPDY0050

    It is a dynamic error if the dynamic type of the operand of a treat expression does not match the sequence type designated by the treat expression. This error might also be raised by a path expression beginning with / or // if the context node is not in a tree that is rooted at a document node. This is because a leading / or // in a path expression is an abbreviation for an initial step that includes the clause treat as document-node().

    err:XPST0051

    It is a static error if an expanded QName used as an ItemType in a SequenceType is not defined in the static context either as a named item type in the in-scope named item types, or as a generalized atomic type in the in-scope schema type.

    err:XQST0052

    The type named in a cast or castable expression must be the name of a type defined in the in-scope schema types, and the type must be simple.

    err:XQDY0054

    It is a dynamic error if a cycle is encountered in the definition of a module’s dynamic context components, for example because of a cycle in variable declarations.

    err:XQST0055

    It is a static error if a Prolog contains more than one copy-namespaces declaration.

    err:XQST0057

    It is a static error if a schema import binds a namespace prefix but does not specify a target namespace other than a zero-length string.

    err:XQST0058

    It is a static error if multiple schema imports specify the same target namespace.

    err:XQST0059

    It is a static error if an implementation is unable to process a schema or module import by finding a schema or module with the specified target namespace.

    err:XQST0060

    It is a static error if the name of a function in a function declaration is not in a namespace (expanded QName has a null namespace URI).

    err:XQDY0061

    It is a dynamic error 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.

    err:XQDY0064

    It is a dynamic error if the value of the name expression in a computed processing instruction constructor is equal to XML (in any combination of upper and lower case).

    err:XQST0065

    A static error is raised if a Prolog contains more than one ordering mode declaration.

    err:XQST0066

    A static error is raised if a Prolog contains more than one default element/type namespace declaration, or more than one default function namespace declaration.

    err:XQST0067

    A static error is raised if a Prolog contains more than one construction declaration.

    err:XQST0068

    A static error is raised if a Prolog contains more than one boundary-space declaration.

    err:XQST0069

    A static error is raised if a Prolog contains more than one empty order declaration.

    err:XQST0070

    A static error is raised if one of the predefined prefixes xml or xmlns appears in a namespace declaration or a default namespace declaration, or if any of the following conditions is statically detected in any expression or declaration:

    A static error is raised if any of the following conditions is statically detected in any expression:

    • The prefix xml is bound to some namespace URI other than http://www.w3.org/XML/1998/namespace.

    • A prefix other than xml is bound to the namespace URI http://www.w3.org/XML/1998/namespace.

    • The prefix xmlns is bound to any namespace URI.

    • A prefix other than xmlns is bound to the namespace URI http://www.w3.org/2000/xmlns/.

    err:XQST0071

    A static error is raised if the namespace declaration attributes of a direct element constructor do not have distinct names.

    err:XQDY0072

    It is a dynamic error if the result of the content expression of a computed comment constructor contains two adjacent hyphens or ends with a hyphen.

    err:XQDY0074

    It is a dynamic error if the value of the name expression in a computed element or attribute constructor cannot be converted to an expanded QName (for example, because it contains a namespace prefix not found in statically known namespaces.)

    err:XQST0075

    An implementation that does not support the Schema Aware Feature must raise a static error if it encounters a validate expression.

    err:XQST0076

    It is a static error if a collation subclause in an order byor group by clause of a FLWOR expression does not identify a collation that is present in statically known collations.

    err:XQST0079

    It is a static error if an extension expression contains neither a pragma that is recognized by the implementation nor an expression enclosed in curly braces.

    err:XPST0080

    It is a static error if the target type of a cast or castable expression is xs:NOTATION, xs:anySimpleType, or xs:anyAtomicType.

    err:XPST0081

    It is a static error if a QName used in a queryan expression contains a namespace prefix that cannot be expanded into a namespace URI by using the statically known namespaces.

    err:XQDY0084

    It is a dynamic error if the element validated by a validate statement does not have a top-level element declaration in the in-scope element declarations, if validation mode is strict.

    err:XQST0085

    It is a static error if the namespace URI in a namespace declaration attribute is a zero-length string, and the implementation does not support [XML Names 1.1].

    err:XQTY0086

    It is a type error if the typed value of a copied element or attribute node is namespace-sensitive when construction mode is preserve and copy-namespaces mode is no-preserve.

    err:XQST0087

    It is a static error if the encoding specified in a Version Declaration does not conform to the definition of EncName specified in [XML 1.0].

    err:XQST0088

    It is a static error if the literal that specifies the target namespace in a module import or a module declaration is of zero length.

    err:XQST0089

    It is a static error if a variable bound in a for or window clause of a FLWOR expression, and its associated positional variable, do not have distinct names (expanded QNames).

    err:XQST0089

    It is a static error if a variable bound in a for expression, and its associated positional variable, do not have distinct names (expanded QNames).

    err:XQST0090

    It is a static error if a character reference does not identify a valid character in the version of XML that is in use.

    err:XQDY0091

    An implementation MAY raise a dynamic error if an xml:id error, as defined in [XML ID], is encountered during construction of an attribute named xml:id.

    err:XQDY0092

    An implementation MAY raise a dynamic error if a constructed attribute named xml:space has a value other than preserve or default.

    err:XQST0094

    The name of each grouping variable must be equal (by the eq operator on expanded QNames) to the name of a variable in the input tuple stream.

    err:XQDY0096

    It is a dynamic errorif the node-name of a node constructed by a computed element constructor has any of the following properties:

    • Its namespace prefix is xmlns.

    • Its namespace URI is http://www.w3.org/2000/xmlns/.

    • Its namespace prefix is xml and its namespace URI is not http://www.w3.org/XML/1998/namespace.

    • Its namespace prefix is other than xml and its namespace URI is http://www.w3.org/XML/1998/namespace.

    err:XQST0097

    It is a static error for a decimal-format to specify a value that is not valid for a given property, as described in statically known decimal formats

    err:XQST0098

    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. The following properties represent characters used in a picture string: decimal-separator, exponent-separator, grouping-separator, percent, per-mille, the family of ten decimal digits starting with zero-digit, digit, and pattern-separator.

    err:XQST0099

    No module may contain more than one ContextItemDecl.

    err:XQDY0101

    An error is raised if a computed namespace constructor attempts to do any of the following:

    • Bind the prefix xml to some namespace URI other than http://www.w3.org/XML/1998/namespace.

    • Bind a prefix other than xml to the namespace URI http://www.w3.org/XML/1998/namespace.

    • Bind the prefix xmlns to any namespace URI.

    • Bind a prefix to the namespace URI http://www.w3.org/2000/xmlns/.

    • Bind any prefix (including the empty prefix) to a zero-length namespace URI.

    err:XQDY0102

    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.

    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.

    err:XQST0103

    All variables in a window clause must have distinct names.

    err:XQST0104

    A TypeName that is specified in a validate expression must be found in the in-scope schema definitions

    err:XQTY0105

    It is a type error if the content sequence in an element constructor contains a function .

    err:XQST0106

    It is a static error if a function declaration contains both a %private and a %public annotation.

    err:XQST0108

    It is a static error if an output declaration occurs in a library module.

    err:XQST0109

    It is a static error if the local name of an output declaration in the http://www.w3.org/2010/xslt-xquery-serialization namespace is not one of the serialization parameter names listed in C.1 Static Context Components, or if the name of an output declaration is use-character-maps.

    err:XQST0110

    It is a static error if the same serialization parameter is used more than once in an output declaration.

    err:XQST0111

    It is a static error for a query prolog to contain two decimal formats with the same name, or to contain two default decimal formats.

    err:XQST0113

    Specifying a VarValue or VarDefaultValue for a context item declaration in a library module is a static error.

    err:XQST0114

    It is a static error for a decimal format declaration to define the same property more than once.

    err:XQST0115

    It is a static error if the document specified by the option Q{http://www.w3.org/2010/xslt-xquery-serialization}parameter-document raises a serialization error.

    err:XQST0116

    It is a static errorif a variable declaration contains both a %private and a %public annotation, more than one %private annotation, or more than one %public annotation.

    err:XPTY0117

    When applying the coercion rules, if an item is of type xs:untypedAtomic and the expected type is namespace-sensitive, a type error [err:XPTY0117] is raised.

    err:XQST0118

    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.

    err:XQST0119

    It is a static error if the implementation is not able to process the value of an output:parameter-document declaration to produce an XDM instance.

    err:XQST0125

    It is a static error if an inline function expression is annotated as %public or %private.

    err:XPDY0130

    An implementation-dependent limit has been exceeded.

    err:XQST0134

    The namespace axis is not supported.

    err:XQDY0137

    No two keys in a map may have the same key value.

    err:XQST0140

    It is a static error if a named item type declaration is recursive, unless it satisfies the conditions defined in 3.2.8.3.1 Recursive Record Types.

    err:XPTY0141

    In a forexpressionclause, when the keyword member is present, the value of the binding collection must be a single array; and when either or both of the keywords key and value are present, the value of the binding collection must be a single map.

    err:XPTY0144

    During the analysis phase, an axis step is classified as implausible 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.

    err:XPTY0145

    During the analysis phase, a unary or postfix lookup expression is classified as implausible 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.

    err:XQST0146

    It is a static error if two or more item types declared or imported by a module have equal expanded QNames (as defined by the eq operator.)

    err:XQST0148

    It is a static error if an optional parameter in a function declaration is followed by a parameter that does not have a default value.

    err:XQST0149

    It is a static error if the schemas imported by different modules of a query are not compatible as defined in Section 2.8.1 Schema ConsistencyDM.

    err:XQST0151

    It is a static error if a node name supplied as a string literal in a computed element or attribute constructor does not take the form of an EQName.

    err:XPST0152

    It is a static error if a key type named in a TypedMapType is not a generalized atomic type.

    H The application/xquery Media Type

    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.)

    H.1 Introduction

    This document, found at http://www.w3.org/TR/xquery/, together with its normative references, defines the language XQuery Version 1.0. This Appendix provides information about the application/xquery media type, which is intended to be used for transmitting queries written in the XQuery language.

    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 http://lists.w3.org/Archives/Public/public-qt-comments.

    H.2 Registration of MIME Media Type application/xquery

    MIME media type name: application

    MIME subtype name: xquery

    Required parameters: none

    Optional parameters: none

    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 &#xddd; syntax.

    H.2.2 Applications Using this Media Type

    The public XQuery Web page lists more than two dozen implementations of the XQuery language, both proprietary and open source.

    This media type is registered to allow for deployment of XQuery on the World Wide Web.

    H.2.3 File Extensions

    The most common file extensions in use for XQuery are .xq and .xquery.

    The appropriate Macintosh file type code is TEXT.

    H.2.4 Intended Usage

    The intended usage of this media type is for interchange of XQuery expressions.

    H.2.5 Author/Change Controller

    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.

    H.3 Encoding Considerations

    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.

    An XQuery document may contain an encoding declaration as part of its version declaration:

    xquery version "3.1" encoding "utf-8";

    H.4 Recognizing XQuery Files

    An XQuery file may have the string xquery version "V.V" near the beginning of the document, where "V.V" is a version number. Currently the version number, if present, must be "1.0", "3.0", or "3.1".

    H.5 Charset Default Rules

    XQuery documents use the Unicode character set and, by default, the UTF-8 encoding.

    H.6 Security Considerations

    Queries written in XQuery may cause arbitrary URIs or IRIs to be dereferenced. Therefore, the security issues of [RFC3987] Section 8 should be considered. In addition, the contents of resources identified by file: URIs can in some cases be accessed, processed and returned as results. XQuery expressions can invoke any of the functions defined in [XQuery and XPath Functions and Operators 4.0]. For example, the fn:doc() and fn:doc-available() functions allow local filesystem probes as well as access to any URI-defined resource accessible from the system evaluating the XQuery expression. The fn:transform() 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 fn:transform() function should be sandboxed or disabled if untrusted queries are run.

    XQuery is a full declarative programming language, and supports user-defined functions, external function libraries (modules) referenced by URI, and system-specific “native” functions.

    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.

    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.

    Furthermore, because the XQuery language permits extensions, it is possible that application/xquery may describe content that has security implications beyond those described here.

    I Glossary (Non-Normative)

    anonymous function

    An anonymous function is a function item with no name. Anonymous functions may be created, for example, by evaluating an inline function expression or by partial function application.

    application function

    Application functions are function definitions written in a host language such as XQuery or XSLT whose syntax and semantics are defined in this family of specifications. Their behavior (including the rules determining the static and dynamic context) follows the rules for such functions in the relevant host language specification.

    argument expression

    An argument to a function call is either an argument expression or an ArgumentPlaceholder (?); in both cases it may either be supplied positionally, or identified by a name (called a keyword).

    arity range

    A function definition has an arity range, which is a range of consecutive non-negative integers. If the function definition has M required parameters and N optional parameters, then its arity range is from M to M+N inclusive.

    array

    An array is a function item that associates a set of positions, represented as positive integer keys, with values.

    associated value

    The value associated with a given key is called the associated value of the key.

    atomic item

    An atomic item is a value in the value space of an atomic type, as defined in [XML Schema 1.0] or [XML Schema 1.1].

    atomic type

    An atomic type is a simple schema type whose {variety}XS11-1 is atomic.

    atomization

    Atomization of a sequence is defined as the result of invoking the fn:data function, as defined in Section 2.1.4 fn:dataFO.

    available documents

    Available documents. This is a mapping of strings to document nodes. Each string represents the absolute URI of a resource. The document node is the root of a tree that represents that resource using the data model. The document node is returned by the fn:doc function when applied to that URI.

    available item collections

    Available collections. This is a mapping of strings to sequences of items. Each string represents the absolute URI of a resource. The sequence of items represents the result of the fn:collection function when that URI is supplied as the argument.

    available text resources

    Available text resources. This is a mapping of strings to text resources. Each string represents the absolute URI of a resource. The resource is returned by the fn:unparsed-text function when applied to that URI.

    available uri collections

    Available URI collections. This is a mapping of strings to sequences of URIs. The string represents the absolute URI of a resource which can be interpreted as an aggregation of a number of individual resources each of which has its own URI. The sequence of URIs represents the result of the fn:uri-collection function when that URI is supplied as the argument.

    axis step

    An axis step returns a sequence of nodes that are reachable from a starting node via a specified axis. Such a step has two parts: an axis, which defines the "direction of movement" for the step, and a node test, which selects nodes based on their kind, name, and/or type annotation .

    base URI declaration

    A base URI declaration specifies the Static Base URI property. The Static Base URI property is used when resolving relative URI references.

    binary

    In the operator mapping tables, the term binary refers to the types xs:hexBinary and xs:base64Binary.

    binding collection

    In a for clause, when an expression is preceded by the keyword in, the value of that expression is called a binding collection.

    binding collection

    The result of evaluating the binding expression in a for expression is called the binding collection

    binding sequence

    In a window clause, when an expression is preceded by the keyword in, the value of that expression is called a binding sequence.

    boundary-space declaration

    A boundary-space declaration sets the boundary-space policy in the static context, overriding any implementation-defined default. Boundary-space policy controls whether boundary whitespace is preserved by element constructors during processing of the query.

    boundary-space policy

    Boundary-space policy. This component controls the processing of boundary whitespace by direct element constructors, as described in 4.12.1.4 Boundary Whitespace.

    boundary whitespace

    Boundary whitespace is a sequence of consecutive whitespace characters within the content of a direct element constructor, that is delimited at each end either by the start or end of the content, or by a DirectConstructor, or by an EnclosedExpr. For this purpose, characters generated by character references such as &#x20; or by CDataSections are not considered to be whitespace characters.

    character reference

    A character reference is an XML-style reference to a [Unicode] character, identified by its decimal or hexadecimal codepoint.

    choice item type

    A choice item type defines an item type that is the union of a number of alternatives. For example the type (xs:hexBinary | xs:base64Binary) defines the union of these two primitive atomic types, while the type (map(*) | array(*)) matches any item that is either a map or an array.

    coercion rules

    The coercion rules are rules used to convert a supplied value to a required type, for example when converting an argument of a function call to the declared type of the function parameter.

    collation

    A collation is a specification of the manner in which strings and URIs are compared and, by extension, ordered. For a more complete definition of collation, see Section 5.3 Comparison of stringsFO.

    comma operator

    One way to construct a sequence is by using the comma operator, which evaluates each of its operands and concatenates the resulting sequences, in order, into a single result sequence.

    complex terminal

    A complex terminal is a variable terminal whose production rule references, directly or indirectly, an ordinary production rule.

    computed element constructor

    A computed element constructor creates an element node, allowing both the name and the content of the node to be computed.

    construction declaration

    A construction declaration sets the construction mode in the static context, overriding any implementation-defined default.

    construction mode

    Construction mode. The construction mode governs the behavior of element and document node constructors. If construction mode is preserve, the type of a constructed element node is xs:anyType, and all attribute and element nodes copied during node construction retain their original types. If construction mode is strip, the type of a constructed element node is xs:untyped; all element nodes copied during node construction receive the type xs:untyped, and all attribute nodes copied during node construction receive the type xs:untypedAtomic.

    constructor function

    The constructor function for a given simple type is used to convert instances of other simple types into the given type. The semantics of the constructor function call T($arg) are defined to be equivalent to the expression $arg cast as T?.

    content expression

    In an enclosed expression, the optional expression enclosed in curly brackets is called the content expression.

    context dependent

    A function definition is said to be context dependent if its result depends on the static or dynamic context of its caller. A function definition may be context-dependent for some arities in its arity range, and context-independent for others: for example fn:name#0 is context-dependent while fn:name#1 is context-independent.

    context node

    When the context value is a single item, it can also be referred to as the context item; when it is a single node, it can also be referred to as the context node.

    context position

    The context position is the position of the context value within the series of values currently being processed.

    context size

    The context size is the number of values in the series of values currently being processed.

    context value

    The context value is the value currently being processed.

    copy-namespaces declaration

    A copy-namespaces declaration sets the value of copy-namespaces mode in the static context, overriding any implementation-defined default. Copy-namespaces mode controls the namespace bindings that are assigned when an existing element node is copied by an element constructor or document constructor.

    copy-namespaces mode

    Copy-namespaces mode. This component controls the namespace bindings that are assigned when an existing element node is copied by an element constructor, as described in 4.12.1 Direct Element Constructors. Its value consists of two parts: preserve or no-preserve, and inherit or no-inherit.

    current dateTime

    Current dateTime. This information represents an implementation-dependent point in time during the processing of a queryan expression, and includes an explicit timezone. It can be retrieved by the fn:current-dateTime function. If called multiple times during the execution of a queryan expression, this function always returns the same result.

    data model

    XQuery 4.0 and XPath 4.0 operates on the abstract, logical structure of an XML document or JSON object rather than its surface syntax. This logical structure, known as the data model, is defined in [XQuery and XPath Data Model (XDM) 4.0].

    decimal-format declaration

    A decimal format declaration adds a decimal format to the statically known decimal formats, which define the properties used to format numbers using the fn:format-number() function

    decimal-separator

    decimal-separator(M, R) is used to separate the integer part of the number from the fractional part. The default value for both the marker and the rendition is U+002E (FULL STOP, PERIOD, .) .

    default calendar

    Default calendar. This is the calendar used when formatting dates in human-readable output (for example, by the functions fn:format-date and fn:format-dateTime) if no other calendar is requested. The value is a string.

    default collation

    Default collation. This identifies one of the collations in statically known collations as the collation to be used by functions and operators for comparing and ordering values of type xs:string and xs:anyURI (and types derived from them) when no explicit collation is specified.

    default collation declaration

    A default collation declaration sets the value of the default collation in the static context, overriding any implementation-defined default.

    default collection

    Default collection. This is the sequence of items that would result from calling the fn:collection function with no arguments.

    default function namespace

    Default function namespace. This is either a namespace URI, or absentDM. The namespace URI, if present, is used for any unprefixed QName appearing in a position where a function name is expected.

    default language

    Default language. This is the natural language used when creating human-readable output (for example, by the functions fn:format-date and fn:format-integer) if no other language is requested. The value is a language code as defined by the type xs:language.

    default namespace for elements and types

    Default namespace for elements and types. This is either a namespace URI, or the special value "##any", or absentDM. This indicates how unprefixed QNames are interpreted when they appear in a position where an element name or type name is expected.

    default order for empty sequences

    Default order for empty sequences. This component controls the processing of empty sequences and NaN values as ordering keys in an order by clause in a FLWOR expression, as described in 4.13.9 Order By Clause.

    default place

    Default place. This is a geographical location used to identify the place where events happened (or will happen) when processing dates and times using functions such as fn:format-date, fn:format-dateTime, and fn:civil-timezone, if no other place is specified. It is used when translating timezone offsets to civil timezone names, and when using calendars where the translation from ISO dates/times to a local representation is dependent on geographical location. Possible representations of this information are an ISO country code or an Olson timezone name, but implementations are free to use other representations from which the above information can be derived. The only requirement is that it should uniquely identify a civil timezone, which means that country codes for countries with multiple timezones, such as the United States, are inadequate.

    default URI collection

    Default URI collection. This is the sequence of URIs that would result from calling the fn:uri-collection function with no arguments.

    delimiting terminal symbol

    The delimiting terminal symbols are: !!=#$%()**:,-...::*:::=;<<<===!>=>=?>>>=>>????[@[]```{{{|||}}}×÷AposStringLiteralBracedURILiteral]]><![CDATA[--><!--/></<+#)(#?><?QuotStringLiteralS///]````[}``{StringLiteral

    depends on

    A variable value (or the context value) depends on another variable value (or the context value) if, during the evaluation of the initializing expression of the former, the latter is accessed through the module context.

    derives from

    A schema typeS1 is said to derive fromschema typeS2 if any of the following conditions is true:

    digit

    digit(M) is a character used in the picture string to represent an optional digit; the default value is U+0023 (NUMBER SIGN, #) .

    direct element constructor

    A direct element constructor is a form of element constructor in which the name of the constructed element is a constant.

    document order

    Informally, document order is the order in which nodes appear in the XML serialization of a document.

    dynamically known function definitions

    Dynamically known function definitions. This is a set of function definitions. It includes the statically known function definitions as a subset, but may include other function definitions that are not known statically.

    dynamic context

    The dynamic context of an expression is defined as information that is needed for the dynamic evaluation of an expression, beyond any information that is needed from the static context.

    dynamic error

    A dynamic error is an error that must be detected during the dynamic evaluation phase and may be detected during the static analysis phase.

    dynamic evaluation phase

    The dynamic evaluation phase is the phase during which the value of an expression is computed.

    dynamic function call

    A dynamic function call consists of a base expression that returns the function and a parenthesized list of zero or more arguments (argument expressions or ArgumentPlaceholders).

    dynamic function call

    A dynamic function call is an expression that is evaluated by calling a function item, which is typically obtained dynamically.

    dynamic type

    Every value matches one or more sequence types. A value is said to have a dynamic typeT if it matches (or is an instance of) the sequence type T.

    effective boolean value

    The effective boolean value of a value is defined as the result of applying the fn:boolean function to the value, as defined in Section 7.3.1 fn:booleanFO.

    effective case

    The effective case of a switch expression is the first case clause that matches, using the rules given above, or the default clause if no such case clause exists.

    effective case

    The effective case in a typeswitch expression is the first case clause in which the value of the operand expression matches a SequenceType in the SequenceTypeUnion of the case clause, using the rules of SequenceType matching.

    empty order declaration

    An empty order declaration sets the default order for empty sequences in the static context, overriding any implementation-defined default. This declaration controls the processing of empty sequences and NaN values as ordering keys in an order by clause in a FLWOR expression.

    empty sequence

    A sequence containing zero items is called an empty sequence.

    enclosed expression

    An enclosed expression is an instance of the EnclosedExpr production, which allows an optional expression within curly brackets.

    encoding declaration

    If present, a version declaration may optionally include an encoding declaration. The value of the string literal following the keyword encoding is an encoding name, and must conform to the definition of EncName specified in [XML 1.0] [err:XQST0087]. The purpose of an encoding declaration is to allow the writer of a query to provide a string that indicates how the query is encoded, such as "UTF-8", "UTF-16", or "US-ASCII".

    entry

    Each key / value pair in a map is called an entry.

    enumeration type

    An EnumerationType accepts a fixed set of string values.

    environment variables

    Environment variables. This is a mapping from names to values. Both the names and the values are strings. The names are compared using an implementation-defined collation, and are unique under this collation. The set of environment variables is implementation-defined and may be empty.

    equivalent grouping keys

    Two tuples T1 and T2 have equivalent grouping keys if and only if, for each grouping variable GV, the atomized value of GV in T1 is deep-equal to the atomized value of GV in T2, as defined by applying the function fn:deep-equal using the appropriate collation.

    error value

    In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called error values.

    Executable Base URI

    Executable Base URI. This is an absolute URI used to resolve relative URIs during the evaluation of expressions; it is used, for example, to resolve a relative URI supplied to the fn:doc or fn:unparsed-text functions.

    expanded QName

    An expanded QName is a triple: its components are a prefix, a local name, and a namespace URI. In the case of a name in no namespace, the namespace URI and prefix are both absent. In the case of a name in the default namespace, the prefix is absent.

    exponent-separator

    exponent-separator(M, R) is used to separate the mantissa from the exponent in scientific notation. The default value for both the marker and the rendition is U+0065 (LATIN SMALL LETTER E, e) .

    expression context

    The expression context for a given expression consists of all the information that can affect the result of the expression.

    extension expression

    An extension expression is an expression whose semantics are implementation-defined.

    external function

    External functions can be characterized as functions that are neither part of the processor implementation, nor written in a language whose semantics are under the control of this family of specifications. The semantics of external functions, including any context dependencies, are entirely implementation-defined. In XSLT, external functions are called Section 24.1 Extension Functions XT30.

    filter expression

    A filter expression is an expression in the form E1[E2]: its effect is to return those items from the value of E1 that satisfy the predicate in E2.

    fixed focus

    A fixed focus is a focus for an expression that is evaluated once, rather than being applied to a series of values; in a fixed focus, the context value is set to one specific value, the context position is 1, and the context size is 1.

    focus

    The first three components of the dynamic context (context value, context position, and context size) are called the focus of the expression.

    focus function

    A focus function is an inline function expression in which the function signature is implicit: the function takes a single argument of type item()* (that is, any value), and binds this to the context value when evaluating the function body, which returns a result of type item()*.

    function assertion

    A function assertion is a predicate that restricts the set of functions matched by a FunctionType. It uses the same syntax as 5.15 Annotations.

    function coercion

    Function coercion wraps a function item in a new function whose signature is the same as the expected type. This effectively delays the checking of the argument and return types until the function is called.

    function definition

    A function definition contains information used to evaluate a static function call, including the name, parameters, and return type of the function.

    function item

    A function item is an item that can be called using a dynamic function call.

    generalized atomic type

    A generalized atomic type is an item type whose instances are all atomic items. Generalized atomic types include (a) atomic types, either built-in (for example xs:integer) or imported from a schema, (b) pure union types, either built-in (xs:numeric and xs:error) or imported from a schema, (c) choice item types if their alternatives are all generalized atomic types, and (d) enumeration types.

    Gregorian

    In the operator mapping tables, the term Gregorian refers to the types xs:gYearMonth, xs:gYear, xs:gMonthDay, xs:gDay, and xs:gMonth.

    grouping key

    The atomized value of a grouping variable is called a grouping key.

    grouping-separator

    grouping-separator(M, R) is used to separate groups of digits (for example as a thousands separator). The default value for both the marker and the rendition is U+002C (COMMA, ,) .

    grouping variable

    Each grouping specification specifies one grouping variable, which refers to variable bindings in the pre-grouping tuples. The values of the grouping variables are used to assign pre-grouping tuples to groups.

    guarded

    An expression E is said to be guarded by some governing condition C if evaluation of E is not allowed to fail with a dynamic error except when C applies.

    host language

    A host language for XPath is any environment that provides capabilities for XPath expressions to be defined and evaluated, and that supplies a static and dynamic context for their evaluation.

    ignorable whitespace

    Ignorable whitespace consists of any whitespace characters that may occur between terminals, unless these characters occur in the context of a production marked with a ws:explicit annotation, in which case they can occur only where explicitly specified (see A.3.5.2 Explicit Whitespace Handling).

    implausible

    Certain expressions, while not erroneous, are classified as being implausible, because they achieve no useful effect.

    implementation defined

    Implementation-defined indicates an aspect that may differ between implementations, but must be specified by the implementer for each particular implementation.

    implementation dependent

    Implementation-dependent indicates an aspect that may differ between implementations, is not specified by this or any W3C specification, and is not required to be specified by the implementer for any particular implementation.

    implicit timezone

    Implicit timezone. This is the timezone to be used when a date, time, or dateTime value that does not have a timezone is used in a comparison or arithmetic operation. The implicit timezone is an implementation-defined value of type xs:dayTimeDuration. See Section 3.2.7.3 Timezones XS1-2 or Section 3.3.7 dateTime XS11-2 for the range of valid values of a timezone.

    infinity

    infinity(R) is the string used to represent the double value infinity (INF); the default value is the string "Infinity"

    initial context value

    In the dynamic context of every module in a query, the context value component must have the same setting. If this shared setting is not absentDM, it is referred to as the initial context value.

    initializing expression

    If a variable declaration includes an expression (VarValue or VarDefaultValue), the expression is called an initializing expression. The static context for an initializing expression includes all functions, variables, and namespaces that are declared or imported anywhere in the Prolog.

    inline function expression

    An inline function expression, when evaluated, creates an anonymous function defined directly in the inline function expression.

    in-scope attribute declarations

    In-scope attribute declarations. Each attribute declaration is identified either by an expanded QName (for a top-level attribute declaration) or by an implementation-dependent attribute identifier (for a local attribute declaration). If the Schema Aware Feature is supported, in-scope attribute declarations include all attribute declarations found in imported schemas.

    in-scope element declarations

    In-scope element declarations. Each element declaration is identified either by an expanded QName (for a top-level element declaration) or by an implementation-dependent element identifier (for a local element declaration). If the Schema Aware Feature is supported, in-scope element declarations include all element declarations found in imported schemas.

    in-scope named item types

    In-scope named item types. This is a mapping from expanded QName to named item types.

    in-scope namespaces

    The in-scope namespaces property of an element node is a set of namespace bindings, each of which associates a namespace prefix with a URI.

    in-scope schema definitions

    In-scope schema definitions is a generic term for all the element declarations, attribute declarations, and schema type definitions that are in scope during static analysis of an expression.

    in-scope schema type

    In-scope schema types. Each schema type definition is identified either by an expanded QName (for a named type) or by an implementation-dependent type identifier (for an anonymous type). The in-scope schema types include the predefined schema types described in 3.5 Schema Types. If the Schema Aware Feature is supported, in-scope schema types also include all type definitions found in imported schemas.

    in-scope variables

    In-scope variables. This is a mapping from expanded QName to type. It defines the set of variables that are available for reference within an expression. The expanded QName is the name of the variable, and the type is the static type of the variable.

    item

    An item is either an atomic item, a node, or a function item.

    item type

    An item type is a type that can be expressed using the ItemType syntax, which forms part of the SequenceType syntax. Item types match individual items.

    item type designator

    An item type designator is a syntactic construct conforming to the grammar rule ItemType. An item type designator is said to designate an item type.

    kind test

    An alternative form of a node test called a kind test can select nodes based on their kind, name, and type annotation.

    lexical QName

    A lexical QName is a name that conforms to the syntax of the QName production

    library module

    A module that does not contain a Query Body is called a library module. A library module consists of a module declaration followed by a Prolog.

    literal

    A literal is a direct syntactic representation of an atomic item.

    literal terminal

    A literal terminal is a token appearing as a string in quotation marks on the right-hand side of an ordinary production rule.

    main module

    A main module consists of a Prolog followed by a Query Body.

    map

    A map is a function that associates a set of keys with values, resulting in a collection of key / value pairs.

    mapping arrow operator

    The mapping arrow operator=!> applies a function to each item in a sequence.

    may

    MAY means that an item is truly optional.

    member

    The values of an array are called its members.

    minus-sign

    minus-sign(R) is the string used to mark negative numbers; the default value is U+002D (HYPHEN-MINUS, -) .

    module

    A module is a fragment of XQuery code that conforms to the Module grammar and can independently undergo the static analysis phase described in 2.3.3 Expression Processing. Each module is either a main module or a library module.

    module declaration

    A module declaration serves to identify a module as a library module. A module declaration begins with the keyword module and contains a namespace prefix and a URILiteral.

    module feature

    The Module Feature allows a query Prolog to contain a Module Import and allows library modules to be created.

    module import

    A module import imports the public variable declarations, public function declarations, and public item type declarations from one or more library modules into the statically known function definitions, in-scope variables, or in-scope named item types of the importing module.

    must

    MUST means that the item is an absolute requirement of the specification.

    must not

    MUST NOT means that the item is an absolute prohibition of the specification.

    named function reference

    A named function reference is an expression (written name#arity) which evaluates to a function item, the details of the function item being based on the properties of a function definition in the static context.

    named item type

    A named item type is an ItemType identified by an expanded QName.

    name expression

    When an expression is used to specify the name of a constructed node, that expression is called the name expression of the constructor.

    namespace declaration

    A namespace declaration declares a namespace prefix and associates it with a namespace URI, adding the (prefix, URI) pair to the set of statically known namespaces.

    namespace declaration attribute

    A namespace declaration attribute is used inside a direct element constructor. Its purpose is to bind a namespace prefix (including the zero-length prefix) for the constructed element node, including its attributes.

    namespace-sensitive

    The namespace-sensitive types are xs:QName, xs:NOTATION, types derived by restriction from xs:QName or xs:NOTATION, list types that have a namespace-sensitive item type, and union types with a namespace-sensitive type in their transitive membership.

    name test

    A node test that consists only of an EQName or a Wildcard is called a name test.

    NaN

    NaN(R) is the string used to represent the double value NaN (not a number); the default value is the string "NaN"

    node

    A node is an instance of one of the node kinds defined in Section 5 NodesDM.

    node test

    A node test is a condition on the name, kind (element, attribute, text, document, comment, or processing instruction), and/or type annotation of a node. A node test determines which nodes contained by an axis are selected by a step.

    non-delimiting terminal symbol

    The non-delimiting terminal symbols are: allowingancestorancestor-or-selfandarrayasatattributebase-uriboundary-spacebycasecastcastablecatchchildcollationcommentconstructioncontextcopy-namespacescountdecimal-formatdecimal-separatordeclaredefaultdescendantdescendant-or-selfdigitdivdocumentdocument-nodeelementelseemptyempty-sequenceencodingendenumeqeveryexceptexponent-separatorfalsefixedfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selfforfunctiongegroupgrouping-separatorgtidivifimportininfinityinheritinstanceintersectisitemitemskeykeyslaxleletltmapmemberminus-signmodmodulenamespacenamespace-nodeNaNnenextno-inheritno-preservenodeofonlyoptionororderorderedorderingotherwisepairsparentpattern-separatorper-millepercentprecedingpreceding-or-selfpreceding-sibling-or-selfpreservepreviousprocessing-instructionrecordreturnsatisfiesschemaschema-attributeschema-elementselfslidingsomestablestartstrictstripswitchtextthentotreattruetrytumblingtypetypeswitchunionunorderedvalidatevaluevaluesvariableversionwhenwherewhilewindowxqueryzero-digitascendingBinaryIntegerLiteralDecimalLiteraldescendingDoubleLiteralexternalgreatestHexIntegerLiteralIntegerLiteralleastNCNameQNameURIQualifiedName

    numeric

    When referring to a type, the term numeric denotes the types xs:integer, xs:decimal, xs:float, and xs:double which are all member types of the built-in union type xs:numeric.

    numeric predicate

    A predicate whose predicate expression returns a value of type xs:numeric+ is called a numeric predicate.

    operator function

    For each operator and valid combination of operand types, the operator mapping tables specify a result type and an expression that invokes an operator function; the operator function implements the semantics of the operator for the given types.

    option declaration

    An option declaration declares an option that affects the behavior of a particular implementation. Each option consists of an identifying EQName and a StringLiteral.

    ordinary production rule

    An ordinary production rule is a production rule in A.1 EBNF that is not annotated ws:explicit.

    output declaration

    An output declaration is an option declaration in the namespace http://www.w3.org/2010/xslt-xquery-serialization; it is used to declare serialization parameters.

    partial function application

    A static or dynamic function call is a partial function application if one or more arguments is an ArgumentPlaceholder.

    partially applied function

    A partially applied function is a function created by partial function application.

    path expression

    A path expression consists of a series of one or more steps, separated by / or //, and optionally beginning with / or //. A path expression is typically used to locate nodes within trees.

    pattern-separator

    pattern-separator(M) is a character used to separate positive and negative sub-pictures in a picture string; the default value is U+003B (SEMICOLON, ;) .

    percent

    percent(M, R) is used to indicate that the number is written as a per-hundred fraction; the default value for both the marker and the rendition is U+0025 (PERCENT SIGN, %) .

    per-mille

    per-mille(M, R) is used to indicate that the number is written as a per-thousand fraction; the default value for both the marker and the rendition is U+2030 (PER MILLE SIGN, ) .

    positional variable

    A positional variable is a variable that is preceded by the keyword at.

    pragma

    A pragma is denoted by the delimiters (# and #), and consists of an identifying EQName followed by implementation-defined content.

    predefined entity reference

    A predefined entity reference is a short sequence of characters, beginning with an ampersand, that represents a single character that might otherwise have syntactic significance.

    predicate truth value

    The predicate truth value of a value $V is the result of the expression if ($V instance of xs:numeric+) then ($V = position()) else fn:boolean($V).

    primary expression

    Primary expressions are the basic primitives of the language. They include literals, variable references, context value references, constructors, and function calls. A primary expression may also be created by enclosing any expression in parentheses, which is sometimes helpful in controlling the precedence of operators.

    principal node kind

    Every axis has a principal node kind. If an axis can contain elements, then the principal node kind is element; otherwise, it is the kind of nodes that the axis can contain.

    private function

    A private function is a function with a %private annotation. A private function is hidden from module import, which can not import it into the statically known function definitions of another module.

    private item type

    A private item type is a named item type with a %private annotation. A private item type is hidden from module import, which can not import it into the in-scope named item types of another module.

    private variable

    A private variable is a variable with a %private annotation. A private variable is hidden from module import, which can not import it into the in-scope variables of another module.

    Prolog

    A Prolog is a series of declarations and imports that define the processing environment for the module that contains the Prolog.

    public function

    A public function is a function without a %private annotation. A public function is accessible to module import, which can import it into the statically known function definitions of another module.

    public item type

    A public item type is an item type declaration without a %private annotation. A public item type is accessible to module import, which can import it into the in-scope named item types of another module.

    public variable

    A public variable is a variable without a %private annotation. A public variable is accessible to module import, which can import it into the in-scope variables of another module. Using %public and %private annotations in a main module is not an error, but it does not affect module imports, since a main module cannot be imported. It is a static error [err:XQST0116] if a variable declaration contains both a %private and a %public annotation, more than one %private annotation, or more than one %public annotation.

    pure union type

    A pure union type is a simple type that satisfies the following constraints: (a) {variety}XS11-1 is union, (b) the {facets}XS11-1 property is empty, (c) no type in the transitive membership of the union type has {variety}XS11-1list, and (d) no type in the transitive membership of the union type is a type with {variety}XS11-1union having a non-empty {facets}XS11-1 property

    query

    A query consists of one or more modules.

    query body

    The Query Body, if present, consists of an expression that defines the result of the query.

    reserved namespaces

    A reserved namespace is a namespace that must not be used in the name of a function declaration.

    resolve

    To resolve a relative URI$rel against a base URI $base is to expand it to an absolute URI, as if by calling the function fn:resolve-uri($rel, $base).

    reverse document order

    The node ordering that is the reverse of document order is called reverse document order.

    same key

    Two atomic items K1 and K2 have the same key value if fn:atomic-equal(K1, K2) returns true, as specified in Section 13.2.1 fn:atomic-equalFO

    schema aware feature

    The Schema Aware Feature permits the query Prolog to contain a schema import, and permits a query to contain a validate expression (see 4.24 Validate Expressions).

    schema import

    A schema import imports the element declarations, attribute declarations, and type definitions from a schema into the in-scope schema definitions. For each named user-defined simple type in the schema, schema import also adds a corresponding constructor function.

    schema type

    A schema type is a complex type or simple type as defined in the [XML Schema 1.0] or [XML Schema 1.1] specifications, including built-in types as well as user-defined types.

    sequence

    A sequence is an ordered collection of zero or more items.

    sequence arrow operator

    The sequence arrow operator=> applies a function to a supplied sequence.

    sequence concatenation

    The sequence concatenation of a number of sequences S1, S2, ... Sn is defined to be the sequence formed from the items of S1, followed by the items from S2, and so on, retaining order.

    sequence type

    A sequence type is a type that can be expressed using the SequenceType syntax. Sequence types are used whenever it is necessary to refer to a type in an XQuery 4.0 and XPath 4.0 expression. Since all values are sequences, every value matches one or more sequence types.

    sequence type designator

    A sequence type designator is a syntactic construct conforming to the grammar rule SequenceType. A sequence type designator is said to designate a sequence type.

    SequenceType matching

    SequenceType matching compares a value with an expected sequence type.

    serialization

    Serialization is the process of converting an XDM instance to a sequence of octets (step DM4 in Figure 1.), as described in [XSLT and XQuery Serialization 4.0].

    serialization feature

    The Serialization Feature provides means for serializing the result of a query as specified in 2.3.5 Serialization.

    setter

    Setters are declarations that set the value of some property that affects query processing, such as construction mode or default collation.

    should

    SHOULD means that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.

    singleton

    A sequence containing exactly one item is called a singleton.

    singleton focus

    A singleton focus is a fixed focus in which the context value is a singleton item.

    stable

    Document order is stable, which means that the relative order of two nodes will not change during the processing of a given queryexpression, even if this order is implementation-dependent.

    statically known collations

    Statically known collations. This is an implementation-defined mapping from URI to collation. It defines the names of the collations that are available for use in processing queries and expressions.

    statically known decimal formats

    Statically known decimal formats. This is a mapping from QNames to decimal formats, with one default format that has no visible name, referred to as the unnamed decimal format. Each format is available for use when formatting numbers using the fn:format-number function.

    statically known function definitions

    Statically known function definitions. This is a set of function definitions.

    statically known namespaces

    Statically known namespaces. This is a mapping from prefix to namespace URI that defines all the namespaces that are known during static processing of a given expression.

    static analysis phase

    The static analysis phase depends on the expression itself and on the static context. The static analysis phase does not depend on input data (other than schemas).

    Static Base URI

    Static Base URI. This is an absolute URI, used to resolve relative URIs during static analysis.

    static context

    The static context of an expression is the information that is available during static analysis of the expression, prior to its evaluation.

    static error

    An error that can be detected during the static analysis phase, and is not a type error, is a static error.

    static function call

    A static function call consists of an EQName followed by a parenthesized list of zero or more arguments.

    static type

    The static type of an expression is the best inference that the processor is able to make statically about the type of the result of the expression.

    step

    A step is a part of a path expression that generates a sequence of items and then filters the sequence by zero or more predicates. The value of the step consists of those items that satisfy the predicates, working from left to right. A step may be either an axis step or a postfix expression.

    string constructor

    A String Constructor creates a string from literal text and interpolated expressions.

    string value

    The string value of a node is a string and can be extracted by applying the Section 2.1.3 fn:stringFO function to the node.

    substantively disjoint

    Two sequence types are deemed to be substantively disjoint if (a) neither is a subtype of the other (see 3.3.1 Subtypes of Sequence Types) and (b) the only values that are instances of both types are one or more of the following:

    • The empty sequence, ().

    • The empty map, {}.

    • The empty array, [].

    substitution group

    Substitution groups are defined in Section 2.2.2.2 Element Substitution Group XS1-1 and Section 2.2.2.2 Element Substitution Group XS11-1. Informally, the substitution group headed by a given element (called the head element) consists of the set of elements that can be substituted for the head element without affecting the outcome of schema validation.

    subtype

    Given two sequence types or item types, the rules in this section determine if one is a subtype of the other. If a type A is a subtype of type B, it follows that every value matched by A is also matched by B.

    subtype substitution

    The use of a value that has a dynamic type that is a subtype of the expected type is known as subtype substitution.

    symbol

    Each rule in the grammar defines one symbol, using the following format:

    symbol ::= expression
    symbol separators

    Whitespace and Comments function as symbol separators. For the most part, they are not mentioned in the grammar, and may occur between any two terminal symbols mentioned in the grammar, except where that is forbidden by the /* ws: explicit */ annotation in the EBNF, or by the /* xgc: xml-version */ annotation.

    system function

    System functions include the functions defined in [XQuery and XPath Functions and Operators 4.0], functions defined by the specifications of a host language, constructor functions for atomic types, and any additional functions provided by the implementation. System functions are sometimes called built-in functions.

    target namespace

    The target namespace of a module is the namespace of the objects (such as elements or functions) that it defines.

    terminal

    A terminal is a symbol or string or pattern that can appear in the right-hand side of a rule, but never appears on the left-hand side in the main grammar, although it may appear on the left-hand side of a rule in the grammar for terminals.

    tuple

    A tuple is a set of zero or more named variables, each of which is bound to a value that is an XDM instance.

    tuple stream

    A tuple stream is an ordered sequence of zero or more tuples.

    type annotation

    Each element node and attribute node in an XDM instance has a type annotation (described in Section 2.8 Schema InformationDM). The type annotation of a node is a reference to a schema type.

    typed data feature

    The Typed Data Feature permits an XDM instance to contain element node types other than xs:untyped and attributes node types other than xs:untypedAtomic.

    type declaration

    A variable binding may be accompanied by a type declaration, which consists of the keyword as followed by the static type of the variable, declared using the syntax in 3.1 Sequence Types.

    typed value

    The typed value of a node is a sequence of atomic items and can be extracted by applying the Section 2.1.4 fn:dataFO function to the node.

    type error

    A type error may be raised during the static analysis phase or the dynamic evaluation phase. During the static analysis phase, a type error occurs when the static type of an expression does not match the expected type of the context in which the expression occurs. During the dynamic evaluation phase, a type error occurs when the dynamic type of a value does not match the expected type of the context in which the value occurs.

    type promotion

    Under certain circumstances, an atomic item can be promoted from one type to another.

    URI

    Within this specification, the term URI refers to a Universal Resource Identifier as defined in [RFC3986] and extended in [RFC3987] with the new name IRI.

    user-defined function

    User defined functions are functions that contain a function body, which provides the implementation of the function as a content expression.

    value

    In the data model, a value is always a sequence.

    variable declaration

    A variable declaration in the XQuery prolog defines the name and static type of a variable, and optionally a value for the variable. It adds to the in-scope variables in the static context, and may also add to the variable values in the dynamic context.

    variable reference

    A variable reference is an EQName preceded by a $-sign.

    variable terminal

    A variable terminal is an instance of a production rule that is not itself an ordinary production rule but that is named (directly) on the right-hand side of an ordinary production rule.

    variable values

    Variable values. This is a mapping from expanded QName to value. It contains the same expanded QNames as the in-scope variables in the static context for the expression. The expanded QName is the name of the variable and the value is the dynamic value of the variable, which includes its dynamic type.

    version declaration

    A version declaration can identify the applicable XQuery syntax and semantics for a module, as well as its encoding.

    warning

    In addition to static errors, dynamic errors, and type errors, an XQuery 4.0 and XPath 4.0 implementation may raise warnings, either during the static analysis phase or the dynamic evaluation phase. The circumstances in which warnings are raised, and the ways in which warnings are handled, are implementation-defined.

    whitespace

    A whitespace character is any of the characters defined by [http://www.w3.org/TR/REC-xml/#NT-S].

    wildcard-matches

    In these rules, if MU and NU are NameTestUnions, then MUwildcard-matchesNU is true if every name that matches MU also matches NU.

    window

    A window is a sequence of consecutive items drawn from the binding sequence.

    XDM instance

    The term XDM instance is used, synonymously with the term value, to denote an unconstrained sequence of items.

    XPath 1.0 compatibility mode

    XPath 1.0 compatibility mode.This component must be set by all host languages that include XPath 3.1 as a subset, indicating whether rules for compatibility with XPath 1.0 are in effect. XQuery sets the value of this component to false. This value is true if rules for backward compatibility with XPath Version 1.0 are in effect; otherwise it is false.

    XQuery 1.0 Processor

    An XQuery 1.0 Processor processes a query according to the XQuery 1.0 specification.

    XQuery 3.0 Processor

    An XQuery 3.0 Processor processes a query according to the XQuery 3.0 specification.

    XQuery 3.1 Processor

    An XQuery 3.1 Processor processes a query according to the XQuery 3.1 specification.

    XQuery 4.0 Processor

    An XQuery 4.0 Processor processes a query according to the XQuery 4.0 specification.

    XQuery version number

    An XQuery version number consists of two integers, referred to as the major version number and the minor version number.

    xs:anyAtomicType

    xs:anyAtomicType is an atomic type that includes all atomic items (and no values that are not atomic). Its base type is xs:anySimpleType from which all simple types, including atomic, list, and union types, are derived. All primitive atomic types, such as xs:decimal and xs:string, have xs:anyAtomicType as their base type.

    xs:dayTimeDuration

    xs:dayTimeDuration is derived by restriction from xs:duration. The lexical representation of xs:dayTimeDuration is restricted to contain only day, hour, minute, and second components.

    xs:error

    xs:error is a simple type with no value space. It is defined in Section 3.16.7.3 xs:error XS11-1 and can be used in the 3.1 Sequence Types to raise errors.

    xs:untyped

    xs:untyped is used as the type annotation of an element node that has not been validated, or has been validated in skip mode.

    xs:untypedAtomic

    xs:untypedAtomic is an atomic type that is used to denote untyped atomic data, such as text that has not been assigned a more specific type.

    xs:yearMonthDuration

    xs:yearMonthDuration is derived by restriction from xs:duration. The lexical representation of xs:yearMonthDuration is restricted to contain only year and month components.

    zero-digit

    zero-digit(M) is the character used in the picture string to represent the digit zero; the default value is U+0030 (DIGIT ZERO, 0) . This character must be a digit (category Nd in the Unicode property database), and it must have the numeric value zero. This property implicitly defines the ten Unicode characters that are used to represent the values 0 to 9 in the function output: Unicode is organized so that each set of decimal digits forms a contiguous block of characters in numerical sequence. Within the picture string any of these ten character can be used (interchangeably) as a place-holder for a mandatory digit. Within the final result string, these ten characters are used to represent the digits zero to nine.

    J Atomic Comparisons: An Overview (Non-Normative)

    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.

    J.1 Equality Comparisons

    In XQuery 4.0 and XPath 4.0 there are essentially four ways of comparing two atomic items for equality:

    • $A = $B

      This operator was introduced in XPath 1.0. The semantics were changed slightly in XPath 2.0, but the original semantics remain available when XPath 1.0 compatibility mode is enabled.

      With a general comparison in XPath 2.0 or later (and in XQuery), the following rules are observed:

      • Either operand may be a sequence; the result is true if any pair of items from the two sequences compares equal.

        In consequence, if either operand is an empty sequence, the result is false.

      • If nodes are supplied, they are atomized.

      • 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 "4.0" and "4" are not equal to each other, but both compare equal to the integer value 4.

      • Comparison of certain values is context-sensitive. In particular, comparison of strings uses the default collation from the static context, while comparison of date/time values lacking an explicit timezone takes the timezone from the dynamic context.

      • NaN is not equal to NaN; negative zero is equal to positive zero.

      • xs:hexBinary and xs:base64Binary values are mutually comparable: they are equal if they represent the same sequence of octets.

      • Comparing incompatible values (for example xs:integer and xs:date) raises an error.

    • $A eq $B

      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.

      With a value comparison, the rules are:

      • Each operand must either be a single atomic item, or an empty sequence.

      • If either operand is an empty sequence, the result is an empty sequence; in most contexts this has the same effect as returning false.

      • If nodes are supplied, they are atomized.

      • Untyped atomic items are converted to strings (regardless of the type of the other operand).

      • Numeric values of types xs:integer, xs:decimal, or xs:float are converted to xs:double.

        This can lead to problems with implementations of xs:decimal that support more precision than can be held in an xs:double.

      • As with general comparisons, the default collation and implicit timezone are taken from the context.

      • NaN is not equal to NaN; negative zero is equal to positive zero.

      • xs:hexBinary and xs:base64Binary values are mutually comparable: they are equal if they represent the same sequence of octets.

      • Comparing incompatible values (for example xs:integer and xs:date) raises an error.

    • deep-equal($A, $B)

      As the name implies, the deep-equal 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 deep-equal($A, $B) are also invoked by a wide variety of other functions including distinct-values, all-equal, and all-different; it is also used to underpin grouping constructs in both XQuery 4.0 and XSLT 4.0.

      Some of the relevant rules are:

      • Because deep-equal 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.

      • If nodes are supplied, they are not atomized; they are compared as nodes.

      • 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.

      • Comparisons of dates and times lacking a timezone uses the implicit timezone from the dynamic context.

      • Numeric values are converted to xs:decimal prior to comparison, not to xs:double. This represents a departure in 4.0 from previous versions of the specification. The conversion must use an implementation of xs:decimal that does not cause loss of precision. As a result, the comparison is now truly transitive, which makes it suitable to underpin grouping operations.

      • To ensure that every value is equal to itself, comparing NaN to NaN returns true.

      • xs:hexBinary and xs:base64Binary values are mutually comparable: they are equal if they represent the same sequence of octets.

      • Comparing incompatible values (for example xs:integer and xs:date) returns false; it does not raise an error.

    • atomic-equal($A, $B)

      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:

      • The type signature of the function ensures that it can only be used to compare single items; empty sequences do not arise.

      • If nodes are supplied, they are atomized.

      • Strings are compared codepoint-by-codepoint, without reference to any collation or normalization.

      • 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.

      • As with deep-equal, numeric values are converted to xs:decimal prior to comparison, not to xs:double.

      • Comparing NaN to NaN returns true.

      • xs:hexBinary and xs:base64Binary values are distinct: both can co-exist as distinct keys in a map even if the underlying sequence of octets is the same.

      • Comparing incompatible values (for example xs:integer and xs:date) returns false; it does not raise an error.

    The following table summarizes these differences. 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.

    $A$B$A = $B$A eq $Bdeep-equal(​$A, $B)atomic-equal(​$A, $B)

    ()

    ()

    false

    ()

    true

    error

    12

    ()

    false

    ()

    false

    error

    (1,2)

    (2,3)

    true

    error

    false

    error

    12

    12e0

    true

    true

    true

    true

    0.2

    0.2e0

    true

    true

    false

    false

    NaN

    NaN

    false

    false

    true

    true

    +0e0

    -0e0

    true

    true

    true

    true

    "A"

    "a"

    true

    true

    true

    false

    "A"

    12

    error

    error

    false

    false

    <a>A</a>

    "A"

    true

    true

    false

    true

    <a>12</a>

    12

    true

    error

    false

    false

    xs:time(​'12:00:00Z')

    xs:time(​'13:00:00+01:00')

    true

    true

    true

    true

    xs:time(​'12:00:00Z')

    xs:time(​'13:00:00')

    true

    true

    true

    false

    xs:hexBinary(​"0000")

    xs:base64Binary(​"AAA=")

    true

    true

    true

    false

    J.2 Ordering Comparisons

    In XQuery 4.0 and XPath 4.0 there are essentially three ways of comparing two atomic items for their relative ordering:

    • $A < $B

    • $A lt $B

    • Sorting

    TODO: to be expanded.

    K Backwards Compatibility (Non-Normative)

    K.1 Incompatibilities relative to XQuery and XPath 3.1

    In fn:format-integer, certain formatting pictures using a circumflex as a grouping separator might be interpreted differently in 4.0: for example format-integer(1234, "9^999") would output "1^234" in 3.1, but will output "1621" (1234 in base 9) with 4.0. As a workaround, this can be rewritten as format-integer(1234, "0^000").

    In computed node constructors, the node name must now be written in quotation marks if it matches certain language keywords. For example element div {} must now be written element "div" {}. (Alternatively, element { "div" } {} and element Q{}div {} are permitted by both XQuery 3.1 and XQuery 4.0.) This change is made because {} is now a valid expression representing an empty map, so expressions such as element otherwise {} could (without this rule) be parsed in two different ways.

    In XQuery 4.0 and XPath 4.0, certain expressions are classified as implausible: an example is @code/text(), which will always return an empty sequence. A processor may report a static error when such expressions are encountered; however, processors are required to provide a mode of operation in which such expressions are accepted, thus retaining backwards compatibility.

    In expressions that deliver a function item, notably partial function applications, named function references, and the fn:function-lookup 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 contains(?, 42) 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.

    As explained in 3.4.4 Function Coercion, 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.

    K.2 Incompatibilities relative to XQuery and XPath 3.0

    The following names are now reserved, and cannot appear as function names (see A.4 Reserved Function Names):

    • map

    • array

    K.3 Incompatibilities relative to XQuery and XPath 2.01.0

    The following names are now reserved, and cannot appear as function names (see A.4 Reserved Function Names):

    • function

    • namespace-node

    • switch

    If U is a union type with T as one of its members, and if E is an element with T as its type annotation, the expression E instance of element(*, U) returns true in both XQuery and XPath 3.0 and 3.1. In XPath 2.0XQuery 1.0, it returns false.

    Note:

    This is not an incompatibility with XQuery and XPath 3.0. It should be included in XQuery and XPath 3.0 as an incompatibility with XPath 2.0XQuery 1.0, but it was discovered after publication.

    K.4 Incompatibilities relative to XPath 1.0

    This appendix provides a summary of the areas of incompatibility between XPath 4.0 and [XML Path Language (XPath) Version 1.0]. In each of these cases, an XPath 4.0 processor is compatible with an XPath 2.0, 3.0, or 3.1 processor.

    Three separate cases are considered:

    1. Incompatibilities that exist when source documents have no schema, and when running with XPath 1.0 compatibility mode set to true. This specification has been designed to reduce the number of incompatibilities in this situation to an absolute minimum, but some differences remain and are listed individually.

    2. Incompatibilities that arise when XPath 1.0 compatibility mode is set to false. In this case, the number of expressions where compatibility is lost is rather greater.

    3. Incompatibilities that arise when the source document is processed using a schema (whether or not XPath 1.0 compatibility mode is set to true). Processing the document with a schema changes the way that the values of nodes are interpreted, and this can cause an XPath expression to return different results.

    K.4.1 Incompatibilities when Compatibility Mode is true

    The list below contains all known areas, within the scope of this specification, where an XPath 4.0 processor running with compatibility mode set to true will produce different results from an XPath 1.0 processor evaluating the same expression, assuming that the expression was valid in XPath 1.0, and that the nodes in the source document have no type annotations other than xs:untyped and xs:untypedAtomic.

    Incompatibilities in the behavior of individual functions are not listed here, but are included in an appendix of [XQuery and XPath Functions and Operators 4.0].

    Since both XPath 1.0 and XPath 4.0 leave some aspects of the specification implementation-defined, there may be incompatibilities in the behavior of a particular implementation that are outside the scope of this specification. Equally, some aspects of the behavior of XPath are defined by the host language.

    1. Consecutive comparison operators such as A < B < C were supported in XPath 1.0, but are not permitted by the XPath 4.0 grammar. In most cases such comparisons in XPath 1.0 did not have the intuitive meaning, so it is unlikely that they have been widely used in practice. If such a construct is found, an XPath 4.0 processor will report a syntax error, and the construct can be rewritten as (A < B) < C

    2. When converting strings to numbers (either explicitly when using the number function, or implicitly say on a function call), certain strings that converted to the special value NaN under XPath 1.0 will convert to values other than NaN under XPath 4.0. These include any number written with a leading + sign, any number in exponential floating point notation (for example 1.0e+9), and the strings INF and -INF.

      Furthermore, the strings Infinity and -Infinity, which were accepted by XPath 1.0 as representations of the floating-point values positive and negative infinity, are no longer recognized. They are converted to NaN when running under XPath 4.0 with compatibility mode set to true, and cause a dynamic error when compatibility mode is set to false.

    3. XPath 4.0 does not allow a token starting with a letter to follow immediately after a numeric literal, without intervening whitespace. For example, 10div 3 was permitted in XPath 1.0, but in XPath 4.0 must be written as 10 div 3.

    4. The namespace axis is deprecated as of XPath 2.0. Implementations may support the namespace axis for backward compatibility with XPath 1.0, but they are not required to do so. (XSLT 2.0 requires that if XPath backwards compatibility mode is supported, then the namespace axis must also be supported; but other host languages may define the conformance rules differently.)

    5. In XPath 1.0, the expression -x|y parsed as -(x|y), and returned the negation of the numeric value of the first node in the union of x and y. In XPath 4.0, this expression parses as (-x)|y. When XPath 1.0 Compatibility Mode is true, this will always cause a type error.

    6. The rules for converting numbers to strings have changed. These may affect the way numbers are displayed in the output of a stylesheet. For numbers whose absolute value is in the range 1E-6 to 1E+6, the result should be the same, but outside this range, scientific format is used for non-integral xs:float and xs:double values.

    7. If one operand in a general comparison is a single atomic item of type xs:boolean, the other operand is converted to xs:boolean when XPath 1.0 compatibility mode is set to true. In XPath 1.0, if neither operand of a comparison operation using the <, <=, > or >= operator was a node set, both operands were converted to numbers. The result of the expression true() > number('0.5') is therefore true in XPath 1.0, but is false in XPath 4.0 even when compatibility mode is set to true.

    8. In XPath 4.0, a type error is raised if the PITarget specified in a SequenceType of form processing-instruction(PITarget) is not a valid NCName. In XPath 1.0, this condition was not treated as an error.

    K.4.2 Incompatibilities when Compatibility Mode is false

    Even when the setting of the XPath 1.0 compatibility mode is false, many XPath expressions will still produce the same results under XPath 4.0 as under XPath 1.0. The exceptions are described in this section.

    In all cases it is assumed that the expression in question was valid under XPath 1.0, that XPath 1.0 compatibility mode is false, and that all elements and attributes are annotated with the types xs:untyped and xs:untypedAtomic respectively.

    In the description below, the terms node-set and number are used with their XPath 1.0 meanings, that is, to describe expressions which according to the rules of XPath 1.0 would have generated a node-set or a number respectively.

    1. When a node-set containing more than one node is supplied as an argument to a function or operator that expects a single node or value, the XPath 1.0 rule was that all nodes after the first were discarded. Under XPath 4.0, a type error occurs if there is more than one node. The XPath 1.0 behavior can always be restored by using the predicate [1] to explicitly select the first node in the node-set.

    2. In XPath 1.0, the < and > operators, when applied to two strings, attempted to convert both the strings to numbers and then made a numeric comparison between the results. In XPath 4.0, these operators perform a string comparison using the default collating sequence. (If either value is numeric, however, the results are compatible with XPath 1.0)

    3. When an empty node-set is supplied as an argument to a function or operator that expects a number, the value is no longer converted implicitly to NaN. The XPath 1.0 behavior can always be restored by using the number function to perform an explicit conversion.

    4. More generally, the supplied arguments to a function or operator are no longer implicitly converted to the required type, except in the case where the supplied argument is of type xs:untypedAtomic (which will commonly be the case when a node in a schemaless document is supplied as the argument). For example, the function call substring-before(10 div 3, ".") raises a type error under XPath 4.0, because the arguments to the substring-before function must be strings rather than numbers. The XPath 1.0 behavior can be restored by performing an explicit conversion to the required type using a constructor function or cast.

    5. The rules for comparing a node-set to a boolean have changed. In XPath 1.0, an expression such as $node-set = true() was evaluated by converting the node-set to a boolean and then performing a boolean comparison: so this expression would return true if $node-set was non-empty. In XPath 4.0, this expression is handled in the same way as other comparisons between a sequence and a singleton: it is true if $node-set contains at least one node whose value, after atomization and conversion to a boolean using the casting rules, is true.

      This means that if $node-set is empty, the result under XPath 4.0 will be false regardless of the value of the boolean operand, and regardless of which operator is used. If $node-set is non-empty, then in most cases the comparison with a boolean is likely to fail, giving a dynamic error. But if a node has the value "0", "1", "true", or "false", evaluation of the expression may succeed.

    6. Comparisons of a number to a boolean, a number to a string, or a string to a boolean are not allowed in XPath 4.0: they result in a type error. In XPath 1.0 such comparisons were allowed, and were handled by converting one of the operands to the type of the other. So for example in XPath 1.0 4 = true() returned true; 4 ="+4" returned false (because the string "+4" converts to NaN), and false = "false" returned false (because the string "false" converts to the boolean true). In XPath 3.0 all these comparisons are type errors.

    7. Additional numeric types have been introduced, with the effect that arithmetic may now be done as an integer, decimal, or single- or double-precision floating point calculation where previously it was always performed as double-precision floating point. The result of the div operator when dividing two integers is now a value of type decimal rather than double. The expression 10 div 0 raises an error rather than returning positive infinity.

    8. The rules for converting strings to numbers have changed. The implicit conversion that occurs when passing an xs:untypedAtomic value as an argument to a function that expects a number no longer converts unrecognized strings to the value NaN; instead, it reports a dynamic error. This is in addition to the differences that apply when backwards compatibility mode is set to true.

    9. Many operations in XPath 4.0 produce an empty sequence as their result when one of the arguments or operands is an empty sequence. Where the operation expects a string, an empty sequence is usually considered equivalent to a zero-length string, which is compatible with the XPath 1.0 behavior. Where the operation expects a number, however, the result is not the same. For example, if @width returns an empty sequence, then in XPath 1.0 the result of @width+1 was NaN, while with XPath 4.0 it is (). This has the effect that a filter expression such as item[@width+1 != 2] will select items having no width attribute under XPath 1.0, and will not select them under XPath 4.0.

    10. The typed value of a comment node, processing instruction node, or namespace node under XPath 4.0 is of type xs:string, not xs:untypedAtomic. This means that no implicit conversions are applied if the value is used in a context where a number is expected. If a processing-instruction node is used as an operand of an arithmetic operator, for example, XPath 1.0 would attempt to convert the string value of the node to a number (and deliver NaN if unsuccessful), while XPath 4.0 will report a type error.

    11. In XPath 1.0, it was defined that with an expression of the form A and B, B would not be evaluated if A was false. Similarly in the case of A or B, B would not be evaluated if A was true. This is no longer guaranteed with XPath 4.0: the implementation is free to evaluate the two operands in either order or in parallel. This change has been made to give more scope for optimization in situations where XPath expressions are evaluated against large data collections supported by indexes. Implementations may choose to retain backwards compatibility in this area, but they are not obliged to do so.

    12. In XPath 1.0, the expression -x|y parsed as -(x|y), and returned the negation of the numeric value of the first node in the union of x and y. In XPath 4.0, this expression parses as (-x)|y. When XPath 1.0 Compatibility Mode is false, this will cause a type error, except in the situation where x evaluates to an empty sequence. In that situation, XPath 4.0 will return the value of y, whereas XPath 1.0 returned the negation of the numeric value of y.

    K.4.3 Incompatibilities when using a Schema

    An XPath expression applied to a document that has been processed against a schema will not always give the same results as the same expression applied to the same document in the absence of a schema. Since schema processing had no effect on the result of an XPath 1.0 expression, this may give rise to further incompatibilities. This section gives a few examples of the differences that can arise.

    Suppose that the context node is an element node derived from the following markup: <background color="red green blue"/>. In XPath 1.0, the predicate [@color="blue"] would return false. In XPath 4.0, if the color attribute is defined in a schema to be of type xs:NMTOKENS, the same predicate will return true.

    Similarly, consider the expression @birth < @death applied to the element <person birth="1901-06-06" death="1991-05-09"/>. With XPath 1.0, this expression would return false, because both attributes are converted to numbers, which returns NaN in each case. With XPath 4.0, in the presence of a schema that annotates these attributes as dates, the expression returns true.

    Once schema validation is applied, elements and attributes cannot be used as operands and arguments of expressions that expect a different data type. For example, it is no longer possible to apply the substring function to a date to extract the year component, or to a number to extract the integer part. Similarly, if an attribute is annotated as a boolean then it is not possible to compare it with the strings "true" or "false". All such operations lead to type errors. The remedy when such errors occur is to introduce an explicit conversion, or to do the computation in a different way. For example, substring-after(@temperature, "-") might be rewritten as abs(@temperature).

    In the case of an XPath 4.0 implementation that provides the static typing feature, many further type errors will be reported in respect of expressions that worked under XPath 1.0. For example, an expression such as round(../@price) might lead to a static type error because the processor cannot infer statically that ../@price is guaranteed to be numeric.

    Schema validation will in many cases perform whitespace normalization on the contents of elements (depending on their type). This will change the result of operations such as the string-length function.

    Schema validation augments the data model by adding default values for omitted attributes and empty elements.

    L Change Log (Non-Normative)

    1. Use the arrows to browse significant changes since the 3.1 version of this specification.

      See 1 Introduction

    2. Sections with significant changes are marked Δ in the table of contents.

      See 1 Introduction

    3. Setting the default namespace for elements and types to the special value ##any causes an unprefixed element name to act as a wildcard, matching by local name regardless of namespace.

      See 3.2.7.2 Element Types

    4. The terms FunctionType, ArrayType, MapType, and RecordType replace FunctionTest, ArrayTest, MapTest, and RecordTest, with no change in meaning.

      See 3.2.8.1 Function Types

    5. Record types are added as a new kind of ItemType, constraining the value space of maps.

      See 3.2.8.3 Record Types

    6. Function coercion now allows a function with arity N to be supplied where a function of arity greater than N is expected. For example this allows the function true#0 to be supplied where a predicate function is required.

      See 3.4.4 Function Coercion

    7. The symbols × and ÷ can be used for multiplication and division.

      See 4.8 Arithmetic Expressions

    8. 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.

      See 4.10.1 Value Comparisons

    9. Operators such as < and > can use the full-width forms and to avoid the need for XML escaping.

      See 4.10.2 General Comparisons

    10. The lookup operator ? can now be followed by a string literal, for cases where map keys are strings other than NCNames. It can also be followed by a variable reference.

      See 4.14.3 Lookup Expressions

    11. The arrow operator => is now complemented by a “mapping arrow” operator =!> which applies the supplied function to each item in the input sequence independently.

      See 4.23.2 Mapping Arrow Expressions

    12. All implementations must now predeclare the namespace prefixes math, map, array, and err. In XQuery 3.1 it was permitted but not required to predeclare these namespaces.

      See 5.13 Namespace Declaration

    13. 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).

      See 5.18 Function Declarations

    14. The operator mapping table has been simplified by removing entries for the operators ne, le, gt, and ge; these are now defined by reference to the rules for the operators eq and lt.

      See B.2 Operator Mapping

    15. $err:map contains entries for all values that are bound to the single variables.

      See 4.20 Try/Catch Expressions

    16. $err:stack-trace provides information about the current state of execution.

      See 4.20 Try/Catch Expressions

    17. PR 1023 1128 

      It has been clarified that function coercion applies even when the supplied function item matches the required function type. This is to ensure that arguments supplied when calling the function are checked against the signature of the required function type, which might be stricter than the signature of the supplied function item.

      See 3.4.4 Function Coercion

    18. PR tba 

      Predicates in filter expressions for maps and arrays can now be numeric.

      See 4.14.4 Filter Expressions for Maps and Arrays

    19. The ordered { E } and unordered { E } expressions are retained for backwards compatibility reasons, but in XQuery 4.0 they are deprecated and have no useful effect.

      See 4.15 Ordered and Unordered Expressions

      The ordering mode declaration is retained for backwards compatibility reasons, but in XQuery 4.0 it is deprecated and has no useful effect.

      See 5.7 Ordering Mode Declaration

    20. The static typing feature has been dropped.

      See 6 Conformance

      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.

      See C.1 Static Context Components

    21. The syntax record() is allowed; the only thing it matches is an empty map.

      See 3.2.8.3 Record Types

    22. The context value static type, which was there purely to assist in static typing, has been dropped.

      See 2.2.1 Static Context

    23. Four new axes have been defined: preceding-or-self, preceding-sibling-or-self, following-or-self, and following-sibling-or-self.

      See 4.6.4.1 Axes

    24. The syntax document-node(N), where N is a NameTestUnion, is introduced as an abbreviation for document-node(element(N)). For example, document-node(*) matches any well-formed XML document (as distinct from a document fragment).

      See 3.2.7 Node Types

    25. PR 28 

      Multiple for and let clauses can be combined in an expression without an intervening return keyword.

      See 4.13.11 For Expressions

      See 4.13.12 Let Expressions

    26. PR 159 

      Keyword arguments are allowed on static function calls, as well as positional arguments.

      See 4.5.1.1 Static Function Call Syntax

    27. PR 202 

      The presentation of the rules for the subtype relationship between sequence types and item types has been substantially rewritten to improve clarity; no change to the semantics is intended.

      See 3.3 Subtype Relationships

    28. PR 230 

      The rules for “errors and optimization” have been tightened up to disallow many cases of optimizations that alter error behavior. In particular there are restrictions on reordering the operands of and and or, and of predicates in filter expressions, in a way that might allow the processor to raise dynamic errors that the author intended to prevent.

      See 2.4.5 Guarded Expressions

    29. PR 254 

      The term "function conversion rules" used in 3.1 has been replaced by the term "coercion rules".

      See 3.4 Coercion Rules

      The coercion rules allow “relabeling” of a supplied atomic item where the required type is a derived atomic type: for example, it is now permitted to supply the value 3 when calling a function that expects an instance of xs:positiveInteger.

      See 3.4 Coercion Rules

      The value bound to a variable in a let clause is now converted to the declared type by applying the coercion rules.

      See 4.13.3 Let Clause

      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.

      See 5.16 Variable Declaration

    30. PR 284 

      Alternative syntax for conditional expressions is available: if (condition) { X } else { Y }, with the else part being optional.

      See 4.16 Conditional Expressions

    31. PR 286 

      Element and attribute tests can include alternative names: element(chapter|section), attribute(role|class).

      See 3.2.7 Node Types

      The NodeTest in an AxisStep now allows alternatives: ancestor::(section|appendix)

      See 3.2.7 Node Types

      Element and attribute tests of the form element(N) and attribute(N) now allow N to be any NameTest, including a wildcard.

      See 3.2.7.2 Element Types

      See 3.2.7.3 Attribute Types

    32. PR 324 

      String templates provide a new way of constructing strings: for example `{$greeting}, {$planet}!` is equivalent to $greeting || ', ' || $planet || '!'

      See 4.9.2 String Templates

    33. PR 326 

      Support for higher-order functions is now a mandatory feature (in 3.1 it was optional).

      See 6 Conformance

    34. PR 344 

      A for member clause is added to FLWOR expressions to allow iteration over an array.

      See 4.13.2 For Clause

      See 4.13.11 For Expressions

    35. PR 364 

      Switch expressions now allow a case clause to match multiple atomic items.

      See 4.18 Switch Expressions

    36. PR 368 

      The concept of the context item has been generalized, so it is now a context value. That is, it is no longer constrained to be a single item.

      See 2.2.2 Dynamic Context

      See 5.17 Context Value Declaration

    37. PR 433 

      Numeric literals can now be written in hexadecimal or binary notation; and underscores can be included for readability.

      See 4.2.1.1 Numeric Literals

    38. PR 483 

      The start clause in window expressions has become optional, as well as the when keyword and its associated expression.

      See 4.13.4 Window Clause

    39. PR 493 

      A new variable err:map is available, capturing all error information in one place.

      See 4.20 Try/Catch Expressions

    40. PR 519 

      The rules for tokenization have been largely rewritten. In some cases the revised specification may affect edge cases that were handled in different ways by different 3.1 processors, which could lead to incompatible behavior.

      See A.3 Lexical structure

    41. PR 521 

      New abbreviated syntax is introduced (focus function) for simple inline functions taking a single argument. An example is fn { ../@code }

      See 4.5.2.5 Inline Function Expressions

    42. PR 587 

      Switch and typeswitch expressions can now be written with curly brackets, to improve readability.

      See 4.18 Switch Expressions

      See 4.21.2 Typeswitch

    43. PR 603 

      The rules for reporting type errors during static analysis have been changed so that a processor has more freedom to report errors in respect of constructs that are evidently wrong, such as @price/@value, even though dynamic evaluation is defined to return an empty sequence rather than an error.

      See 2.4.6 Implausible Expressions

      See 4.6.4.3 Implausible Axis Steps

    44. PR 606 

      Element and attribute tests of the form element(A|B) and attribute(A|B) are now allowed.

      See 3.2.7.2 Element Types

      See 3.2.7.3 Attribute Types

    45. PR 635 

      The rules for the consistency of schemas imported by different query modules, and for consistency between imported schemas and those used for validating input documents, have been defined with greater precision. It is now recognized that these schemas will not always be identical, and that validation with respect to different schemas may produce different outcomes, even if the components of one are a subset of the components of the other.

      See 5.11 Schema Import

    46. PR 659 

      In previous versions the interpretation of location hints in import schema declarations was entirely at the discretion of the processor. To improve interoperability, XQuery 4.0 recommends (but does not mandate) a specific strategy for interpreting these hints.

      See 5.11 Schema Import

    47. PR 678 

      The comparand expression in a switch expression can be omitted, allowing the switch cases to be provided as arbitrary boolean expressions.

      See 4.18 Switch Expressions

    48. PR 682 

      The values true() and false() are allowed in function annotations, and negated numeric literals are also allowed.

      See 5.18.4 Function Annotations

    49. PR 691 

      Enumeration types are added as a new kind of ItemType, constraining the value space of strings.

      See 3.2.6 Enumeration Types

    50. PR 728 

      The syntax record(*) is allowed; it matches any map.

      See 3.2.8.3 Record Types

    51. PR 753 

      The default namespace for elements and types can now be declared to be fixed for a query module, meaning it is unaffected by a namespace declaration appearing on a direct element constructor.

      See 4.12.1.2 Namespace Declaration Attributes

      See 5.14 Default Namespace Declaration

    52. PR 815 

      The coercion rules now allow conversion in either direction between xs:hexBinary and xs:base64Binary.

      See 3.4 Coercion Rules

    53. PR 820 

      The value bound to a variable in a for clause is now converted to the declared type by applying the coercion rules.

      See 4.13.2 For Clause

    54. PR 837 

      A deep lookup operator ?? is provided for searching trees of maps and arrays.

      See 4.14.3 Lookup Expressions

    55. PR 911 

      The coercion rules now allow any numeric type to be implicitly converted to any other, for example an xs:double is accepted where the required type is xs:double.

      See 3.4 Coercion Rules

    56. PR 943 

      A FLWOR expression may now include a while clause, which causes early exit from the iteration when a condition is encountered.

      See 4.13.6 While Clause

    57. PR 985 

      With the lookup arrow expression and the =?> operator, a function in a map can be looked up and called with the map as first argument.

      See 4.23.3 Lookup Arrow Expressions

    58. PR 996 

      The value of a predicate in a filter expression can now be a sequence of integers.

      See 4.4 Filter Expressions

    59. PR 1031 

      An otherwise operator is introduced: A otherwise B returns the value of A, unless it is an empty sequence, in which case it returns the value of B.

      See 4.17 Otherwise Expressions

    60. PR 1071 

      In map constructors, the keyword map is now optional, so map { 0: false(), 1: true() } can now be written { 0: false(), 1: true() }, provided it is used in a context where this creates no ambiguity.

      See 4.14.1.1 Map Constructors

    61. PR 1125 

      Lookup expressions can now take a modifier (such as keys, values, or pairs) enabling them to return structured results rather than a flattened sequence.

      See 4.14.3 Lookup Expressions

    62. PR 1131 

      A positional variable can be defined in a for expression.

      See 4.13.11 For Expressions

      The type of a variable used in a for expression can be declared.

      See 4.13.11 For Expressions

      The type of a variable used in a let expression can be declared.

      See 4.13.12 Let Expressions

    63. PR 1132 

      Choice item types (an item type allowing a set of alternative item types) are introduced.

      See 3.2.5 Choice Item Types

    64. PR 1163 

      Filter expressions for maps and arrays are introduced.

      See 4.14.4 Filter Expressions for Maps and Arrays

    65. PR 1181 

      The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.

      See 2.2.1 Static Context

      If the default namespace for elements and types has the special value ##any, then an unprefixed name in a NameTest acts as a wildcard, matching names in any namespace or none.

      See 4.6.4.2 Node Tests

      The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.

      See 5.14 Default Namespace Declaration

    66. PR 1197 

      The keyword fn is allowed as a synonym for function in function types, to align with changes to inline function declarations.

      See 3.2.8.1 Function Types

      In inline function expressions, the keyword function may be abbreviated as fn.

      See 4.5.2.5 Inline Function Expressions

    67. PR 1212 

      XQuery and XPath 3.0 included empty-sequence and item as reserved function names, and XQuery and XPath 3.1 added map and array. This was unnecessary since these names never appear followed by a left parenthesis at the start of an expression. They have therefore been removed from the list. New keywords introducing item types, such as record and enum, have not been included in the list.

      See A.4 Reserved Function Names

    68. PR 1249 

      A for key/value clause is added to FLWOR expressions to allow iteration over a map.

      See 4.13.2 For Clause

      A for key/value clause is added to FLWOR expressions to allow iteration over maps.

      See 4.13.11 For Expressions

    69. PR 1250 

      Several decimal format properties, including minus sign, exponent separator, percent, and per-mille, can now be rendered as arbitrary strings rather than being confined to a single character.

      See 2.2.1.2 Decimal Formats

      See 5.10 Decimal Format Declaration

    70. PR 1254 

      The rules concerning the interpretation of xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes have been tightened up.

      See 4.24 Validate Expressions

    71. PR 1265 

      The rules regarding the document-uri property of nodes returned by the fn:collection function have been relaxed.

      See 2.2.2 Dynamic Context

    72. PR 1344 

      Parts of the static context that were there purely to assist in static typing, such as the statically known documents, were no longer referenced and have therefore been dropped.

      See 2.2.1 Static Context

      The static typing option has been dropped.

      See 2.3 Processing Model

    73. PR 1361 

      The term atomic value has been replaced by atomic item.

      See 2.1.2 Values

    74. PR 1384 

      If a type declaration is present, the supplied values in the input sequence are now coerced to the required type. Type declarations are now permitted in XPath as well as XQuery.

      See 4.19 Quantified Expressions

    75. PR 1432 

      In earlier versions, the static context for the initializing expression excluded the variable being declared. This restriction has been lifted.

      See 5.16 Variable Declaration

    76. PR 1480 

      When the element name matches a language keyword such as div or value, it must now be written in quotes as a string literal. This is a backwards incompatible change.

      See 4.12.3.1 Computed Element Constructors

      When the attribute name matches a language keyword such as by or of, it must now be written in quotes as a string literal. This is a backwards incompatible change.

      See 4.12.3.2 Computed Attribute Constructors

    77. PR 1498 

      The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.

      See 2.1 Terminology

      The EBNF notation has been extended to allow the constructs (A ++ ",") (one or more occurrences of A, comma-separated, and (A ** ",") (zero or more occurrences of A, comma-separated.

      See 2.1.1 Grammar Notation

      The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.

      See A.1 EBNF

      See A.1.1 Notation

    78. PR 1513 

      When the processing instruction name matches a language keyword such as try or validate, it must now be written in quotes as a string literal. This is a backwards incompatible change.

      See 4.12.3.5 Computed Processing Instruction Constructors

      When the namespace prefix matches a language keyword such as as or at, it must now be written in quotes as a string literal. This is a backwards incompatible change.

      See 4.12.3.7 Computed Namespace Constructors

    79. PR 1609 

      Ordered maps are introduced.

      See 4.14.1 Maps

      The order of key-value pairs in the map constructor is now retained in the constructed map.

      See 4.14.1.1 Map Constructors

    \ No newline at end of file +declare option output:parameter-document "file:///home/serialization-parameters.xml";

    An output declaration may appear only in a main module; it is a static error [err:XQST0108] if an output declaration appears in a library module. It is a static error [err:XQST0110] if the same serialization parameter is declared more than once. It is a static error [err:XQST0109] if the local name of an output declaration in the http://www.w3.org/2010/xslt-xquery-serialization namespace is not one of the serialization parameter names listed in C.1 Static Context Components or parameter-document, or if the name of an output declaration is use-character-maps. The default value for the method parameter is "xml". An implementation may define additional implementation-defined serialization parameters in its own namespaces.

    If the local name of an output declaration in the http://www.w3.org/2010/xslt-xquery-serialization namespace is parameter-document, 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 [err:XQST0119] if the implementation is not able to process the value of the output:parameter-document declaration to produce an XDM instance.

    If a processor is performing serialization, the XDM instance identified by an output:parameter-document output declaration specifies the values of serialization parameters in the manner defined by Section 3.1 Setting Serialization Parameters by Means of a Parameter DocumentSE. It is a static error [err:XQST0115] 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 http://www.w3.org/2010/xslt-xquery-serialization namespace with the local name parameter-document declaration.

    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.

    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.

    A processor that is not performing serialization may report errors if any serialization parameters are incorrect, or may ignore such parameters.

    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.

    Note:

    The data model permits an element node to have fewer in-scope namespaces than its parent. Correct serialization of such an element node would require “undeclaration” of namespaces, which is a feature of [XML Names 1.1]. An implementation that does not support [XML Names 1.1] 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.

    5.22.1 Serialization Parameters

    ComponentDefault initial value
    allow-duplicate-namesno
    byte-order-markimplementation-defined
    cdata-section-elementsempty
    doctype-publicnone
    doctype-systemnone
    encodingimplementation-defined choice between "utf-8" and "utf-16"
    escape-solidusyes
    escape-uri-attributesyes
    html-versionimplementation-defined
    include-content-typeyes
    indentno
    item-separatorimplementation-defined
    json-node-output-methodxml
    media-typeimplementation-defined
    methodxml
    normalization-formimplementation-defined
    omit-xml-declarationimplementation-defined
    standaloneimplementation-defined
    suppress-indentationempty
    undeclare-prefixesno
    use-character-mapsempty
    versionimplementation-defined

    6 Conformance

    Changes in 4.0  

    1. Support for higher-order functions is now a mandatory feature (in 3.1 it was optional).   [Issue 205 PR 326 1 February 2023]

    2. The static typing feature has been dropped.   [Issue 1343 ]

    This section defines the conformance criteria for an XQuery 4.0 and XPath 4.0 processor. In this section, the following terms are used to indicate the requirement levels defined in [RFC2119]. [Definition: MUST means that the item is an absolute requirement of the specification.] [Definition: MUST NOT means that the item is an absolute prohibition of the specification.] [Definition: MAY means that an item is truly optional.] [Definition: SHOULD means that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.]

    XPath is intended primarily as a component that can be used by other specifications. Therefore, XPath relies on specifications that use it (such as [XPointer] and [XSL Transformations (XSLT) Version 4.0]) to specify conformance criteria for XPath in their respective environments. Specifications that set conformance criteria for their use of XPath MUST NOT change the syntactic or semantic definitions of XPath as given in this specification, except by subsetting and/or compatible extensions.

    If a language is described as an extension of XPath, then every expression that conforms to the XPath grammar MUST behave as described in this specification.

    An XQuery processor that claims to conform to this specification MUST include a claim of Minimal Conformance as defined in 6.1 Minimal Conformance. In addition to a claim of Minimal Conformance, it MAY claim conformance to one or more optional features defined in 6.2 Optional Features.

    6.1 Minimal Conformance

    An implementation that claims Minimal Conformance to this specification MUST provide all of the following items:

    1. An implementation of everything specified in this document except those features specified in 6.2 Optional Features to be optional. If an implementation does not provide a given optional feature, it MUST implement any requirements specified in 6.2 Optional Features for implementations that do not provide that feature.

    2. A definition of every item specified to be implementation-defined, unless that item is part of an optional feature that is not provided by the implementation. A list of implementation-defined items can be found in E Implementation-Defined Items.

      Note:

      Implementations are not required to define items specified to be implementation-dependent.

    3. An implementation of [XQuery and XPath Data Model (XDM) 4.0], as specified in 6.3 Data Model Conformance, and a definition of every item specified to be implementation-defined, unless that item is part of an optional feature that is not provided by the implementation.

    4. An implementation of all functions defined in [XQuery and XPath Functions and Operators 4.0], and a definition of every item specified to be implementation-defined, unless that function or item is part of an optional feature that is not provided by the implementation.

    6.2 Optional Features

    The features discussed in this section are optional. An implementation MAY claim conformance to one or more of these features.

    The description of each feature mentions any errors that occur if a query relies on a feature that is not present.

    6.2.1 Schema Aware Feature

    [Definition: The Schema Aware Feature permits the query Prolog to contain a schema import, and permits a query to contain a validate expression (see 4.24 Validate Expressions). ]

    If an XQuery implementation does not provide the Schema Aware Feature, it MUST raise a static error [err:XQST0009] if it encounters a schema import, and it MUST raise a static error [err:XQST0075] if it encounters a validate expression.

    If an implementation provides the Schema Aware Feature, it MUST also provide the 6.2.2 Typed Data Feature.

    6.2.2 Typed Data Feature

    [Definition: The Typed Data Feature permits an XDM instance to contain element node types other than xs:untyped and attributes node types other than xs:untypedAtomic.]

    If an XQuery implementation does not provide the Typed Data Feature, it MUST guarantee that:

    1. The XDM has the type xs:untyped for every element node and xs:untypedAtomic for every attribute node, including nodes created by the query.

    2. Elements constructed by the query always have the type xs:untyped; attributes constructed by the query always have the type xs:untypedAtomic. (This is equivalent to using construction mode = strip.)

    6.2.3 Module Feature

    [Definition: The Module Feature allows a query Prolog to contain a Module Import and allows library modules to be created.]

    An implementation that does not provide the Module Feature MUST raise a static error [err:XQST0016] if it encounters a module declaration or a module import. Since a module declaration is required in a library module, the Module Feature is required in order to create a library module.

    Note:

    In the absence of the Module Feature, each query consists of a single main module.

    6.2.4 Serialization Feature

    [Definition: The Serialization Feature provides means for serializing the result of a query as specified in 2.3.5 Serialization.] A conforming XQuery implementation that provides the Serialization Feature MUST conform to 2.3.5 Serialization. An implementation MAY provide other forms of serialization, which do not conform to the Serialization Feature, and are beyond the scope of this specification.

    The means by which serialization is invoked is implementation-defined.

    If an error is raised during the serialization process as specified in [XSLT and XQuery Serialization 4.0], an implementation MUST report the error to the calling environment.

    An implementation that does not provide the Serialization Feature MUST NOT raise errors when reading an output declaration, and MUST implement fn:serialize; it MAY, however, raise an error when fn:serialize is invoked, as specified in Section 14.1.3 fn:serializeFO. An implementation that does not provide the Serialization Feature MAY provide results of a query using a vendor-defined serialization.

    Note:

    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.

    6.3 Data Model Conformance

    All XQuery implementations process data represented in the data model as specified in [XQuery and XPath Data Model (XDM) 4.0]. 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:

    1. Support for normative construction from an infoset. An implementation MAY choose to claim conformance to Section 3.2 Construction from an InfosetDM, which defines a normative way to construct an XDM instance from an XML document that is merely well-formed or is governed by a DTD.

    2. Support for normative construction from a PSVI. An implementation MAY choose to claim conformance to Section 3.3 Construction from a PSVIDM, which defines a normative way to construct an XDM instance from an XML document that is governed by a W3C XML Schema.

    3. Support for versions of XML and XSD. As stated in [XQuery and XPath Data Model (XDM) 4.0], the definitions of primitives such as strings, characters, and names SHOULD 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.

      Note:

      For suggestions on processing XML 1.1 documents with XSD 1.0, see [XML 1.1 and Schema 1.0].

    4. Ranges of data values. In XQuery, the following limits are implementation-defined:

      1. For the xs:decimal type, the maximum number of decimal digits (totalDigits facet) MUST be at least 18. This limit SHOULD be at least 20 digits in order to accommodate the full range of values of built-in subtypes of xs:integer, such as xs:long and xs:unsignedLong.

      2. For the types xs:date, xs:dateTime, xs:gYear, and xs:gYearMonth: the minimum and maximum value of the year component (must be at least 1 to 9999).

        For the types xs:time and xs:dateTime: the maximum number of fractional second digits (must be at least 3).

      3. For the xs:duration type: the maximum absolute values of the years, months, days, hours, minutes, and seconds components.

      4. For the xs:yearMonthDuration type: the maximum absolute value, expressed as an integer number of months.

      5. For the xs:dayTimeDuration type: the maximum absolute value, expressed as a decimal number of seconds.

      6. For the types xs:string, xs:hexBinary, xs:base64Binary, xs:QName, xs:anyURI, xs:NOTATION, and types derived from them: limitations (if any) imposed by the implementation on lengths of values.

      The limits listed above need not be fixed, but MAY depend on environmental factors such as system resources. For example, the length of a value of type xs:string might be limited by available memory.

      Note:

      For discussion of errors due to implementation-dependent limits, see 2.4.1 Kinds of Errors.

    6.4 Syntax Extensions

    Any syntactic extensions to XQuery are implementation-defined. The effect of syntactic extensions, including their error behavior, is implementation-defined. Syntactic extensions MAY be used without restriction to modify the semantics of a XQuery expression.

    A XQuery 4.0 and XPath 4.0 Grammar

    A.1 EBNF

    Changes in 4.0  

    1. The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.  [Issue 1366 PR 1498]

    The grammar of XQuery 4.0 and XPath 4.0 uses the same simple Extended Backus-Naur Form (EBNF) notation as [XML 1.0] with the following differences.

    • The notation XYZ ** "," indicates a sequence of zero or more occurrences of XYZ, with a single comma between adjacent occurrences.

    • The notation XYZ ++ "," indicates a sequence of one or more occurrences of XYZ, with a single comma between adjacent occurrences.

    • All named symbols have a name that begins with an uppercase letter.

    • It adds a notation for referring to productions in external specifications.

    • Comments or extra-grammatical constraints on grammar productions are between '/*' and '*/' symbols.

      • A 'xgc:' prefix is an extra-grammatical constraint, the details of which are explained in A.1.2 Extra-grammatical Constraints

      • A 'ws:' prefix explains the whitespace rules for the production, the details of which are explained in A.3.5 Whitespace Rules

      • A 'gn:' prefix means a 'Grammar Note', and is meant as a clarification for parsing rules, and is explained in A.1.3 Grammar Notes. These notes are not normative.

    The terminal symbols for this grammar include the quoted strings used in the production rules below, and the terminal symbols defined in section A.3.1 Terminal Symbols. The grammar is a little unusual in that parsing and tokenization are somewhat intertwined: for more details see A.3 Lexical structure.

    The EBNF notation is described in more detail in A.1.1 Notation.

    [144]   AbbrevForwardStep   ::=   ("@" NodeTest) | SimpleNodeTest
    ("@" NodeTest) | SimpleNodeTest
    [147]   AbbrevReverseStep   ::=   ".."
    ".."
    [114]   AdditiveExpr   ::=   MultiplicativeExpr ( ("+" | "-") MultiplicativeExpr )*
    MultiplicativeExpr ( ("+" | "-") MultiplicativeExpr )*
    [60]   AllowingEmpty   ::=   "allowing" "empty"
    "allowing" "empty"
    [109]   AndExpr   ::=   ComparisonExpr ( "and" ComparisonExpr )*
    ComparisonExpr ( "and" ComparisonExpr )*
    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [29]   AnnotationValue   ::=   StringLiteral | ("-"? NumericLiteral) | ("true" "(" ")") | ("false" "(" ")")
    StringLiteral | ("-"? NumericLiteral) | ("true" "(" ")") | ("false" "(" ")")
    [261]   AnyArrayType   ::=   "array" "(" "*" ")"
    "array" "(" "*" ")"
    [248]   AnyFunctionType   ::=   ("function" | "fn") "(" "*" ")"
    ("function" | "fn") "(" "*" ")"
    [231]   AnyItemTest   ::=   "item" "(" ")"
    "item" "(" ")"
    [233]   AnyKindTest   ::=   "node" "(" ")"
    "node" "(" ")"
    [251]   AnyMapType   ::=   "map" "(" "*" ")"
    "map" "(" "*" ")"
    [254]   AnyRecordType   ::=   "record" "(" "*" ")"
    "record" "(" "*" ")"
    [187]   AposAttrValueContent   ::=   AposAttrContentChar
    | CommonContent
    AposAttrContentChar
    | CommonContent
    [179]   Argument   ::=   ExprSingle | ArgumentPlaceholder
    ExprSingle | ArgumentPlaceholder
    [156]   ArgumentList   ::=   "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    [180]   ArgumentPlaceholder   ::=   "?"
    "?"
    [216]   ArrayConstructor   ::=   SquareArrayConstructor | CurlyArrayConstructor
    SquareArrayConstructor | CurlyArrayConstructor
    [260]   ArrayType   ::=   AnyArrayType | TypedArrayType
    AnyArrayType | TypedArrayType
    [169]   ArrowDynamicFunction   ::=   VarRef | InlineFunctionExpr | ParenthesizedExpr
    VarRef | InlineFunctionExpr | ParenthesizedExpr
    [122]   ArrowExpr   ::=   UnaryExpr ( (SequenceArrowTarget | MappingArrowTarget | LookupArrowTarget) )*
    UnaryExpr ( (SequenceArrowTarget | MappingArrowTarget | LookupArrowTarget) )*
    [168]   ArrowStaticFunction   ::=   EQName
    EQName
    [127]   ArrowTarget   ::=   (ArrowStaticFunctionArgumentList) | (ArrowDynamicFunctionPositionalArgumentList)
    (ArrowStaticFunctionArgumentList) | (ArrowDynamicFunctionPositionalArgumentList)
    [243]   AttributeName   ::=   EQName
    EQName
    [239]   AttributeTest   ::=   "attribute" "(" (NameTestUnion ("," TypeName)?)? ")"
    "attribute" "(" (NameTestUnion ("," TypeName)?)? ")"
    [141]   AxisStep   ::=   (ReverseStep | ForwardStep) Predicate*
    (ReverseStep | ForwardStep) Predicate*
    [12]   BaseURIDecl   ::=   "declare" "base-uri" URILiteral
    "declare" "base-uri" URILiteral
    [10]   BoundarySpaceDecl   ::=   "declare" "boundary-space" ("preserve" | "strip")
    "declare" "boundary-space" ("preserve" | "strip")
    [100]   BracedActions   ::=   ThenActionElseIfAction* ElseAction?
    ThenActionElseIfAction* ElseAction?
    [90]   BracedSwitchCases   ::=   "{" SwitchCases "}"
    "{" SwitchCases "}"
    [95]   BracedTypeswitchCases   ::=   "{" TypeswitchCases "}"
    "{" TypeswitchCases "}"
    [96]   CaseClause   ::=   "case" (VarName "as")? SequenceTypeUnion "return" ExprSingle
    "case" (VarName "as")? SequenceTypeUnion "return" ExprSingle
    [120]   CastableExpr   ::=   CastExpr ( "castable" "as" CastTarget "?"? )?
    CastExpr ( "castable" "as" CastTarget "?"? )?
    [121]   CastExpr   ::=   ArrowExpr ( "cast" "as" CastTarget "?"? )?
    ArrowExpr ( "cast" "as" CastTarget "?"? )?
    [245]   CastTarget   ::=   TypeName | ChoiceItemType | EnumerationType
    TypeName | ChoiceItemType | EnumerationType
    [106]   CatchClause   ::=   "catch" NameTestUnionEnclosedExpr
    "catch" NameTestUnionEnclosedExpr
    [194]   CDataSection   ::=   "<![CDATA[" CDataSectionContents "]]>"/* ws: explicit */
    "<![CDATA[" CDataSectionContents "]]>"/* ws: explicit */
    /* ws: explicit */
    [195]   CDataSectionContents   ::=   (Char* - (Char* ']]>' Char*))/* ws: explicit */
    (Char* - (Char* ']]>' Char*))/* ws: explicit */
    /* ws: explicit */
    [263]   ChoiceItemType   ::=   "(" (ItemType ++ "|") ")"
    "(" (ItemType ++ "|") ")"
    [236]   CommentTest   ::=   "comment" "(" ")"
    "comment" "(" ")"
    [189]   CommonContent   ::=   PredefinedEntityRef | CharRef | "{{" | "}}" | EnclosedExpr
    PredefinedEntityRef | CharRef | "{{" | "}}" | EnclosedExpr
    [110]   ComparisonExpr   ::=   OtherwiseExpr ( (ValueComp
    | GeneralComp
    | NodeComp) OtherwiseExpr )?
    OtherwiseExpr ( (ValueComp
    | GeneralComp
    | NodeComp) OtherwiseExpr )?
    [204]   CompAttrConstructor   ::=   "attribute" CompNodeNameEnclosedExpr
    "attribute" CompNodeNameEnclosedExpr
    [207]   CompCommentConstructor   ::=   "comment" EnclosedExpr
    "comment" EnclosedExpr
    [197]   CompDocConstructor   ::=   "document" EnclosedExpr
    "document" EnclosedExpr
    [198]   CompElemConstructor   ::=   "element" CompNodeNameEnclosedContentExpr
    "element" CompNodeNameEnclosedContentExpr
    [205]   CompNamespaceConstructor   ::=   "namespace" CompNodeNCNameEnclosedExpr
    "namespace" CompNodeNCNameEnclosedExpr
    [199]   CompNodeName   ::=   StringLiteral | UnreservedName | ("{" Expr "}")
    StringLiteral | UnreservedName | ("{" Expr "}")
    [200]   CompNodeNCName   ::=   StringLiteral | UnreservedNCName | ("{" Expr "}")
    StringLiteral | UnreservedNCName | ("{" Expr "}")
    [208]   CompPIConstructor   ::=   "processing-instruction" CompNodeNCNameEnclosedExpr
    "processing-instruction" CompNodeNCNameEnclosedExpr
    [206]   CompTextConstructor   ::=   "text" EnclosedExpr
    "text" EnclosedExpr
    [196]   ComputedConstructor   ::=   CompDocConstructor
    | CompElemConstructor
    | CompAttrConstructor
    | CompNamespaceConstructor
    | CompTextConstructor
    | CompCommentConstructor
    | CompPIConstructor
    CompDocConstructor
    | CompElemConstructor
    | CompAttrConstructor
    | CompNamespaceConstructor
    | CompTextConstructor
    | CompCommentConstructor
    | CompPIConstructor
    [13]   ConstructionDecl   ::=   "declare" "construction" ("strip" | "preserve")
    "declare" "construction" ("strip" | "preserve")
    [33]   ContextValueDecl   ::=   "declare" "context" (("value" ("as" SequenceType)?) | ("item" ("as" ItemType)?)) ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    "declare" "context" (("value" ("as" SequenceType)?) | ("item" ("as" ItemType)?)) ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    [175]   ContextValueRef   ::=   "."
    "."
    [16]   CopyNamespacesDecl   ::=   "declare" "copy-namespaces" PreserveMode "," InheritMode
    "declare" "copy-namespaces" PreserveMode "," InheritMode
    [76]   CountClause   ::=   "count" VarName
    "count" VarName
    [218]   CurlyArrayConstructor   ::=   "array" EnclosedExpr
    "array" EnclosedExpr
    [73]   CurrentVar   ::=   VarName
    VarName
    [19]   DecimalFormatDecl   ::=   "declare" (("decimal-format" EQName) | ("default" "decimal-format")) (DFPropertyName "=" StringLiteral)*
    "declare" (("decimal-format" EQName) | ("default" "decimal-format")) (DFPropertyName "=" StringLiteral)*
    [11]   DefaultCollationDecl   ::=   "declare" "default" "collation" URILiteral
    "declare" "default" "collation" URILiteral
    [26]   DefaultNamespaceDecl   ::=   "declare" "fixed"? "default" ("element" | "function") "namespace" URILiteral
    "declare" "fixed"? "default" ("element" | "function") "namespace" URILiteral
    [20]   DFPropertyName   ::=   "decimal-separator" | "grouping-separator" | "infinity" | "minus-sign" | "NaN" | "percent" | "per-mille" | "zero-digit" | "digit" | "pattern-separator" | "exponent-separator"
    "decimal-separator" | "grouping-separator" | "infinity" | "minus-sign" | "NaN" | "percent" | "per-mille" | "zero-digit" | "digit" | "pattern-separator" | "exponent-separator"
    [184]   DirAttributeList   ::=   (S (QNameS? "=" S? DirAttributeValue)?)*/* ws: explicit */
    (S (QNameS? "=" S? DirAttributeValue)?)*/* ws: explicit */
    /* ws: explicit */
    [185]   DirAttributeValue   ::=   ('"' (EscapeQuot | QuotAttrValueContent)* '"')
    | ("'" (EscapeApos | AposAttrValueContent)* "'")
    /* ws: explicit */
    ('"' (EscapeQuot | QuotAttrValueContent)* '"')
    | ("'" (EscapeApos | AposAttrValueContent)* "'")
    /* ws: explicit */
    /* ws: explicit */
    [190]   DirCommentConstructor   ::=   "<!--" DirCommentContents "-->"/* ws: explicit */
    "<!--" DirCommentContents "-->"/* ws: explicit */
    /* ws: explicit */
    [191]   DirCommentContents   ::=   ((Char - '-') | ('-' (Char - '-')))*/* ws: explicit */
    ((Char - '-') | ('-' (Char - '-')))*/* ws: explicit */
    /* ws: explicit */
    [182]   DirectConstructor   ::=   DirElemConstructor
    | DirCommentConstructor
    | DirPIConstructor
    DirElemConstructor
    | DirCommentConstructor
    | DirPIConstructor
    [183]   DirElemConstructor   ::=   "<" QNameDirAttributeList ("/>" | (">" DirElemContent* "</" QNameS? ">"))/* ws: explicit */
    "<" QNameDirAttributeList ("/>" | (">" DirElemContent* "</" QNameS? ">"))/* ws: explicit */
    /* ws: explicit */
    [188]   DirElemContent   ::=   DirectConstructor
    | CDataSection
    | CommonContent
    | ElementContentChar
    DirectConstructor
    | CDataSection
    | CommonContent
    | ElementContentChar
    [192]   DirPIConstructor   ::=   "<?" PITarget (SDirPIContents)? "?>"/* ws: explicit */
    "<?" PITarget (SDirPIContents)? "?>"/* ws: explicit */
    /* ws: explicit */
    [193]   DirPIContents   ::=   (Char* - (Char* '?>' Char*))/* ws: explicit */
    (Char* - (Char* '?>' Char*))/* ws: explicit */
    /* ws: explicit */
    [234]   DocumentTest   ::=   "document-node" "(" (ElementTest | SchemaElementTest | NameTestUnion)? ")"
    "document-node" "(" (ElementTest | SchemaElementTest | NameTestUnion)? ")"
    [155]   DynamicFunctionCall   ::=   PostfixExprPositionalArgumentList
    PostfixExprPositionalArgumentList
    [244]   ElementName   ::=   EQName
    EQName
    [241]   ElementTest   ::=   "element" "(" (NameTestUnion ("," TypeName "?"?)?)? ")"
    "element" "(" (NameTestUnion ("," TypeName "?"?)?)? ")"
    [103]   ElseAction   ::=   "else" EnclosedExpr
    "else" EnclosedExpr
    [102]   ElseIfAction   ::=   "else" "if" "(" Expr ")" EnclosedExpr
    "else" "if" "(" Expr ")" EnclosedExpr
    [15]   EmptyOrderDecl   ::=   "declare" "default" "order" "empty" ("greatest" | "least")
    "declare" "default" "order" "empty" ("greatest" | "least")
    [203]   EnclosedContentExpr   ::=   EnclosedExpr
    EnclosedExpr
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"
    [259]   EnumerationType   ::=   "enum" "(" (StringLiteral ++ ",") ")"
    "enum" "(" (StringLiteral ++ ",") ")"
    [265]   EQName   ::=   QName | URIQualifiedName
    QName | URIQualifiedName
    [46]   Expr   ::=   (ExprSingle ++ ",")
    (ExprSingle ++ ",")
    [47]   ExprSingle   ::=   ForExpr
    | LetExpr
    | FLWORExpr
    | QuantifiedExpr
    | SwitchExpr
    | TypeswitchExpr
    | IfExpr
    | TryCatchExpr
    | OrExpr
    ForExpr
    | LetExpr
    | FLWORExpr
    | QuantifiedExpr
    | SwitchExpr
    | TypeswitchExpr
    | IfExpr
    | TryCatchExpr
    | OrExpr
    [43]   ExtendedFieldDeclaration   ::=   FieldDeclaration (":=" ExprSingle)?
    FieldDeclaration (":=" ExprSingle)?
    [258]   ExtensibleFlag   ::=   "," "*"
    "," "*"
    [134]   ExtensionExpr   ::=   Pragma+ "{" Expr? "}"
    Pragma+ "{" Expr? "}"
    [256]   FieldDeclaration   ::=   FieldName "?"? ("as" SequenceType)?
    FieldName "?"? ("as" SequenceType)?
    [257]   FieldName   ::=   NCName | StringLiteral
    NCName | StringLiteral
    [153]   FilterExpr   ::=   PostfixExprPredicate
    PostfixExprPredicate
    [163]   FilterExprAM   ::=   PostfixExpr "?[" Expr "]"
    PostfixExpr "?[" Expr "]"
    [51]   FLWORExpr   ::=   InitialClauseIntermediateClause* ReturnClause
    InitialClauseIntermediateClause* ReturnClause
    [55]   ForBinding   ::=   ForItemBinding | ForMemberBinding | ForEntryBinding
    ForItemBinding | ForMemberBinding | ForEntryBinding
    [54]   ForClause   ::=   "for" (ForBinding ++ ",")
    "for" (ForBinding ++ ",")
    [61]   ForEntryBinding   ::=   ((ForEntryKeyBindingForEntryValueBinding?) | ForEntryValueBinding) PositionalVar? "in" ExprSingle
    ((ForEntryKeyBindingForEntryValueBinding?) | ForEntryValueBinding) PositionalVar? "in" ExprSingle
    [62]   ForEntryKeyBinding   ::=   "key" VarNameAndType
    "key" VarNameAndType
    [63]   ForEntryValueBinding   ::=   "value" VarNameAndType
    "value" VarNameAndType
    [48]   ForExpr   ::=   ForClauseForLetReturn
    ForClauseForLetReturn
    [56]   ForItemBinding   ::=   VarNameAndTypeAllowingEmpty? PositionalVar? "in" ExprSingle
    VarNameAndTypeAllowingEmpty? PositionalVar? "in" ExprSingle
    [49]   ForLetReturn   ::=   ForExpr | LetExpr | ("return" ExprSingle)
    ForExpr | LetExpr | ("return" ExprSingle)
    [59]   ForMemberBinding   ::=   "member" VarNameAndTypePositionalVar? "in" ExprSingle
    "member" VarNameAndTypePositionalVar? "in" ExprSingle
    [143]   ForwardAxis   ::=   ("attribute"
    | "child"
    | "descendant"
    | "descendant-or-self"
    | "following"
    | "following-or-self"
    | "following-sibling"
    | "following-sibling-or-self"
    | "namespace"
    | "self") "::"
    ("attribute"
    | "child"
    | "descendant"
    | "descendant-or-self"
    | "following"
    | "following-or-self"
    | "following-sibling"
    | "following-sibling-or-self"
    | "namespace"
    | "self") "::"
    [142]   ForwardStep   ::=   (ForwardAxisNodeTest) | AbbrevForwardStep
    (ForwardAxisNodeTest) | AbbrevForwardStep
    [39]   FunctionBody   ::=   EnclosedExpr
    EnclosedExpr
    [178]   FunctionCall   ::=   EQNameArgumentList/* xgc: reserved-function-names */
    EQNameArgumentList/* xgc: reserved-function-names */
    /* xgc: reserved-function-names */
    /* gn: parens */
    [34]   FunctionDecl   ::=   "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")/* xgc: reserved-function-names */
    "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")/* xgc: reserved-function-names */
    /* xgc: reserved-function-names */
    [209]   FunctionItemExpr   ::=   NamedFunctionRef | InlineFunctionExpr
    NamedFunctionRef | InlineFunctionExpr
    [35]   FunctionSignature   ::=   "(" ParamList ")" TypeDeclaration?
    "(" ParamList ")" TypeDeclaration?
    [247]   FunctionType   ::=   Annotation* (AnyFunctionType
    | TypedFunctionType)
    Annotation* (AnyFunctionType
    | TypedFunctionType)
    [129]   GeneralComp   ::=   "=" | "!=" | "<" | "<=" | ">" | ">="
    "=" | "!=" | "<" | "<=" | ">" | ">="
    [79]   GroupByClause   ::=   "group" "by" (GroupingSpec ++ ",")
    "group" "by" (GroupingSpec ++ ",")
    [80]   GroupingSpec   ::=   VarName (TypeDeclaration? ":=" ExprSingle)? ("collation" URILiteral)?
    VarName (TypeDeclaration? ":=" ExprSingle)? ("collation" URILiteral)?
    [98]   IfExpr   ::=   "if" "(" Expr ")" (UnbracedActions | BracedActions)
    "if" "(" Expr ")" (UnbracedActions | BracedActions)
    [21]   Import   ::=   SchemaImport | ModuleImport
    SchemaImport | ModuleImport
    [18]   InheritMode   ::=   "inherit" | "no-inherit"
    "inherit" | "no-inherit"
    [52]   InitialClause   ::=   ForClause | LetClause | WindowClause
    ForClause | LetClause | WindowClause
    [211]   InlineFunctionExpr   ::=   Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    [118]   InstanceofExpr   ::=   TreatExpr ( "instance" "of" SequenceType )?
    TreatExpr ( "instance" "of" SequenceType )?
    [53]   IntermediateClause   ::=   InitialClause | WhereClause | WhileClause | GroupByClause | OrderByClause | CountClause
    InitialClause | WhereClause | WhileClause | GroupByClause | OrderByClause | CountClause
    [117]   IntersectExceptExpr   ::=   InstanceofExpr ( ("intersect" | "except") InstanceofExpr )*
    InstanceofExpr ( ("intersect" | "except") InstanceofExpr )*
    [230]   ItemType   ::=   AnyItemTest | TypeName | KindTest | FunctionType | MapType | ArrayType | RecordType | EnumerationType | ChoiceItemType
    AnyItemTest | TypeName | KindTest | FunctionType | MapType | ArrayType | RecordType | EnumerationType | ChoiceItemType
    [41]   ItemTypeDecl   ::=   "type" EQName "as" ItemType
    "type" EQName "as" ItemType
    [166]   KeySpecifier   ::=   NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard
    NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard
    [160]   KeywordArgument   ::=   EQName ":=" Argument
    EQName ":=" Argument
    [159]   KeywordArguments   ::=   (KeywordArgument ++ ",")
    (KeywordArgument ++ ",")
    [232]   KindTest   ::=   DocumentTest
    | ElementTest
    | AttributeTest
    | SchemaElementTest
    | SchemaAttributeTest
    | PITest
    | CommentTest
    | TextTest
    | NamespaceNodeTest
    | AnyKindTest
    DocumentTest
    | ElementTest
    | AttributeTest
    | SchemaElementTest
    | SchemaAttributeTest
    | PITest
    | CommentTest
    | TextTest
    | NamespaceNodeTest
    | AnyKindTest
    [66]   LetBinding   ::=   VarNameAndType ":=" ExprSingle
    VarNameAndType ":=" ExprSingle
    [65]   LetClause   ::=   "let" (LetBinding ++ ",")
    "let" (LetBinding ++ ",")
    [50]   LetExpr   ::=   LetClauseForLetReturn
    LetClauseForLetReturn
    [5]   LibraryModule   ::=   ModuleDeclProlog
    ModuleDeclProlog
    [171]   Literal   ::=   NumericLiteral | StringLiteral
    NumericLiteral | StringLiteral
    [164]   Lookup   ::=   ("?" | "??") (Modifier "::")? KeySpecifier
    ("?" | "??") (Modifier "::")? KeySpecifier
    [128]   LookupArrowTarget   ::=   "=?>" NCNamePositionalArgumentList
    "=?>" NCNamePositionalArgumentList
    [162]   LookupExpr   ::=   PostfixExprLookup
    PostfixExprLookup
    [167]   LookupWildcard   ::=   "*"
    "*"
    [4]   MainModule   ::=   PrologQueryBody
    PrologQueryBody
    [212]   MapConstructor   ::=   "map"? "{" (MapConstructorEntry ** ",") "}"
    "map"? "{" (MapConstructorEntry ** ",") "}"
    [213]   MapConstructorEntry   ::=   MapKeyExpr ":" MapValueExpr
    MapKeyExpr ":" MapValueExpr
    [214]   MapKeyExpr   ::=   ExprSingle
    ExprSingle
    [126]   MappingArrowTarget   ::=   "=!>" ArrowTarget
    "=!>" ArrowTarget
    [250]   MapType   ::=   AnyMapType | TypedMapType
    AnyMapType | TypedMapType
    [215]   MapValueExpr   ::=   ExprSingle
    ExprSingle
    [165]   Modifier   ::=   "pairs" | "keys" | "values" | "items"
    "pairs" | "keys" | "values" | "items"
    [2]   Module   ::=   VersionDecl? (LibraryModule | MainModule)
    VersionDecl? (LibraryModule | MainModule)
    [6]   ModuleDecl   ::=   "module" "namespace" NCName "=" URILiteralSeparator
    "module" "namespace" NCName "=" URILiteralSeparator
    [24]   ModuleImport   ::=   "import" "module" ("namespace" NCName "=")? URILiteral ("at" (URILiteral ++ ","))?
    "import" "module" ("namespace" NCName "=")? URILiteral ("at" (URILiteral ++ ","))?
    [115]   MultiplicativeExpr   ::=   UnionExpr ( ("*" | "×" | "div" | "÷" | "idiv" | "mod") UnionExpr )*
    UnionExpr ( ("*" | "×" | "div" | "÷" | "idiv" | "mod") UnionExpr )*
    [210]   NamedFunctionRef   ::=   EQName "#" IntegerLiteral/* xgc: reserved-function-names */
    EQName "#" IntegerLiteral/* xgc: reserved-function-names */
    /* xgc: reserved-function-names */
    [42]   NamedRecordTypeDecl   ::=   "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    [25]   NamespaceDecl   ::=   "declare" "namespace" NCName "=" URILiteral
    "declare" "namespace" NCName "=" URILiteral
    [237]   NamespaceNodeTest   ::=   "namespace-node" "(" ")"
    "namespace-node" "(" ")"
    [151]   NameTest   ::=   EQName | Wildcard
    EQName | Wildcard
    [107]   NameTestUnion   ::=   (NameTest ++ "|")
    (NameTest ++ "|")
    [75]   NextVar   ::=   "next" VarName
    "next" VarName
    [131]   NodeComp   ::=   "is" | "<<" | ">>"
    "is" | "<<" | ">>"
    [181]   NodeConstructor   ::=   DirectConstructor
    | ComputedConstructor
    DirectConstructor
    | ComputedConstructor
    [148]   NodeTest   ::=   UnionNodeTest | SimpleNodeTest
    UnionNodeTest | SimpleNodeTest
    [172]   NumericLiteral   ::=   IntegerLiteral | HexIntegerLiteral | BinaryIntegerLiteral | DecimalLiteral | DoubleLiteral
    IntegerLiteral | HexIntegerLiteral | BinaryIntegerLiteral | DecimalLiteral | DoubleLiteral
    [229]   OccurrenceIndicator   ::=   "?" | "*" | "+"/* xgc: occurrence-indicators */
    "?" | "*" | "+"/* xgc: occurrence-indicators */
    /* xgc: occurrence-indicators */
    [44]   OptionDecl   ::=   "declare" "option" EQNameStringLiteral
    "declare" "option" EQNameStringLiteral
    [81]   OrderByClause   ::=   "stable"? "order" "by" OrderSpec ("," OrderSpec)*
    "stable"? "order" "by" OrderSpec ("," OrderSpec)*
    [176]   OrderedExpr   ::=   "ordered" EnclosedExpr
    "ordered" EnclosedExpr
    [14]   OrderingModeDecl   ::=   "declare" "ordering" ("ordered" | "unordered")
    "declare" "ordering" ("ordered" | "unordered")
    [83]   OrderModifier   ::=   ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral)?
    ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral)?
    [82]   OrderSpec   ::=   ExprSingleOrderModifier
    ExprSingleOrderModifier
    [108]   OrExpr   ::=   AndExpr ( "or" AndExpr )*
    AndExpr ( "or" AndExpr )*
    [111]   OtherwiseExpr   ::=   StringConcatExpr ( "otherwise" StringConcatExpr )*
    StringConcatExpr ( "otherwise" StringConcatExpr )*
    [38]   ParamList   ::=   (VarNameAndType ** ",")
    (VarNameAndType ** ",")
    [36]   ParamListWithDefaults   ::=   (ParamWithDefault ++ ",")
    (ParamWithDefault ++ ",")
    [37]   ParamWithDefault   ::=   VarNameAndType (":=" ExprSingle)?
    VarNameAndType (":=" ExprSingle)?
    [174]   ParenthesizedExpr   ::=   "(" Expr? ")"
    "(" Expr? ")"
    [138]   PathExpr   ::=   ("/" RelativePathExpr?)
    | ("//" RelativePathExpr)
    | RelativePathExpr
    /* xgc: leading-lone-slash */
    ("/" RelativePathExpr?)
    | ("//" RelativePathExpr)
    | RelativePathExpr
    /* xgc: leading-lone-slash */
    /* xgc: leading-lone-slash */
    [238]   PITest   ::=   "processing-instruction" "(" (NCName | StringLiteral)? ")"
    "processing-instruction" "(" (NCName | StringLiteral)? ")"
    [157]   PositionalArgumentList   ::=   "(" PositionalArguments? ")"
    "(" PositionalArguments? ")"
    [158]   PositionalArguments   ::=   (Argument ++ ",")
    (Argument ++ ",")
    [64]   PositionalVar   ::=   "at" VarName
    "at" VarName
    [154]   PostfixExpr   ::=   PrimaryExpr | FilterExpr | DynamicFunctionCall | LookupExpr | FilterExprAM
    PrimaryExpr | FilterExpr | DynamicFunctionCall | LookupExpr | FilterExprAM
    [135]   Pragma   ::=   "(#" S? EQName (SPragmaContents)? "#)"/* ws: explicit */
    "(#" S? EQName (SPragmaContents)? "#)"/* ws: explicit */
    /* ws: explicit */
    [136]   PragmaContents   ::=   (Char* - (Char* '#)' Char*))
    (Char* - (Char* '#)' Char*))
    [161]   Predicate   ::=   "[" Expr "]"
    "[" Expr "]"
    [17]   PreserveMode   ::=   "preserve" | "no-preserve"
    "preserve" | "no-preserve"
    [74]   PreviousVar   ::=   "previous" VarName
    "previous" VarName
    [170]   PrimaryExpr   ::=   Literal
    | VarRef
    | ParenthesizedExpr
    | ContextValueRef
    | FunctionCall
    | OrderedExpr
    | UnorderedExpr
    | NodeConstructor
    | FunctionItemExpr
    | MapConstructor
    | ArrayConstructor
    | StringTemplate
    | StringConstructor
    | UnaryLookup
    Literal
    | VarRef
    | ParenthesizedExpr
    | ContextValueRef
    | FunctionCall
    | OrderedExpr
    | UnorderedExpr
    | NodeConstructor
    | FunctionItemExpr
    | MapConstructor
    | ArrayConstructor
    | StringTemplate
    | StringConstructor
    | UnaryLookup
    [7]   Prolog   ::=   ((DefaultNamespaceDecl | Setter | NamespaceDecl | Import) Separator)* ((ContextValueDecl | AnnotatedDecl | OptionDecl) Separator)*
    ((DefaultNamespaceDecl | Setter | NamespaceDecl | Import) Separator)* ((ContextValueDecl | AnnotatedDecl | OptionDecl) Separator)*
    [85]   QuantifiedExpr   ::=   ("some" | "every") QuantifierBinding ("," QuantifierBinding)* "satisfies" ExprSingle
    ("some" | "every") QuantifierBinding ("," QuantifierBinding)* "satisfies" ExprSingle
    [86]   QuantifierBinding   ::=   VarNameAndType "in" ExprSingle
    VarNameAndType "in" ExprSingle
    [45]   QueryBody   ::=   Expr
    Expr
    [186]   QuotAttrValueContent   ::=   QuotAttrContentChar
    | CommonContent
    QuotAttrContentChar
    | CommonContent
    [113]   RangeExpr   ::=   AdditiveExpr ( "to" AdditiveExpr )?
    AdditiveExpr ( "to" AdditiveExpr )?
    [253]   RecordType   ::=   AnyRecordType | TypedRecordType
    AnyRecordType | TypedRecordType
    [139]   RelativePathExpr   ::=   StepExpr (("/" | "//") StepExpr)*
    StepExpr (("/" | "//") StepExpr)*
    [84]   ReturnClause   ::=   "return" ExprSingle
    "return" ExprSingle
    [146]   ReverseAxis   ::=   ("ancestor"
    | "ancestor-or-self"
    | "parent"
    | "preceding"
    | "preceding-or-self"
    | "preceding-sibling-or-self") "::"
    ("ancestor"
    | "ancestor-or-self"
    | "parent"
    | "preceding"
    | "preceding-or-self"
    | "preceding-sibling-or-self") "::"
    [145]   ReverseStep   ::=   (ReverseAxisNodeTest) | AbbrevReverseStep
    (ReverseAxisNodeTest) | AbbrevReverseStep
    [240]   SchemaAttributeTest   ::=   "schema-attribute" "(" AttributeName ")"
    "schema-attribute" "(" AttributeName ")"
    [242]   SchemaElementTest   ::=   "schema-element" "(" ElementName ")"
    "schema-element" "(" ElementName ")"
    [22]   SchemaImport   ::=   "import" "schema" SchemaPrefix? URILiteral ("at" (URILiteral ++ ","))?
    "import" "schema" SchemaPrefix? URILiteral ("at" (URILiteral ++ ","))?
    [23]   SchemaPrefix   ::=   ("namespace" NCName "=") | ("fixed"? "default" "element" "namespace")
    ("namespace" NCName "=") | ("fixed"? "default" "element" "namespace")
    [8]   Separator   ::=   ";"
    ";"
    [125]   SequenceArrowTarget   ::=   "=>" ArrowTarget
    "=>" ArrowTarget
    [228]   SequenceType   ::=   ("empty-sequence" "(" ")")
    | (ItemTypeOccurrenceIndicator?)
    ("empty-sequence" "(" ")")
    | (ItemTypeOccurrenceIndicator?)
    [97]   SequenceTypeUnion   ::=   SequenceType ("|" SequenceType)*
    SequenceType ("|" SequenceType)*
    [9]   Setter   ::=   BoundarySpaceDecl | DefaultCollationDecl | BaseURIDecl | ConstructionDecl | OrderingModeDecl | EmptyOrderDecl | CopyNamespacesDecl | DecimalFormatDecl
    BoundarySpaceDecl | DefaultCollationDecl | BaseURIDecl | ConstructionDecl | OrderingModeDecl | EmptyOrderDecl | CopyNamespacesDecl | DecimalFormatDecl
    [137]   SimpleMapExpr   ::=   PathExpr ("!" PathExpr)*
    PathExpr ("!" PathExpr)*
    [150]   SimpleNodeTest   ::=   KindTest | NameTest
    KindTest | NameTest
    [69]   SlidingWindowClause   ::=   "sliding" "window" VarNameAndType "in" ExprSingleWindowStartCondition? WindowEndCondition
    "sliding" "window" VarNameAndType "in" ExprSingleWindowStartCondition? WindowEndCondition
    [217]   SquareArrayConstructor   ::=   "[" (ExprSingle ** ",") "]"
    "[" (ExprSingle ** ",") "]"
    [140]   StepExpr   ::=   PostfixExpr | AxisStep
    PostfixExpr | AxisStep
    [112]   StringConcatExpr   ::=   RangeExpr ( "||" RangeExpr )*
    RangeExpr ( "||" RangeExpr )*
    [222]   StringConstructor   ::=   "``[" StringConstructorContent "]``"/* ws: explicit */
    "``[" StringConstructorContent "]``"/* ws: explicit */
    /* ws: explicit */
    [224]   StringConstructorChars   ::=   (Char* - (Char* ('`{' | ']``') Char*))/* ws: explicit */
    (Char* - (Char* ('`{' | ']``') Char*))/* ws: explicit */
    /* ws: explicit */
    [223]   StringConstructorContent   ::=   StringConstructorChars (StringInterpolationStringConstructorChars)*/* ws: explicit */
    StringConstructorChars (StringInterpolationStringConstructorChars)*/* ws: explicit */
    /* ws: explicit */
    [225]   StringInterpolation   ::=   "`{" Expr? "}`"/* ws: explicit */
    "`{" Expr? "}`"/* ws: explicit */
    /* ws: explicit */
    [219]   StringTemplate   ::=   "`" (StringTemplateFixedPart | StringTemplateVariablePart)* "`"/* ws: explicit */
    "`" (StringTemplateFixedPart | StringTemplateVariablePart)* "`"/* ws: explicit */
    /* ws: explicit */
    [220]   StringTemplateFixedPart   ::=   ((Char - ('{' | '}' | '`')) | "{{" | "}}" | "``")*/* ws: explicit */
    ((Char - ('{' | '}' | '`')) | "{{" | "}}" | "``")*/* ws: explicit */
    /* ws: explicit */
    [221]   StringTemplateVariablePart   ::=   EnclosedExpr/* ws: explicit */
    EnclosedExpr/* ws: explicit */
    /* ws: explicit */
    [91]   SwitchCaseClause   ::=   ("case" SwitchCaseOperand)+ "return" ExprSingle
    ("case" SwitchCaseOperand)+ "return" ExprSingle
    [92]   SwitchCaseOperand   ::=   Expr
    Expr
    [89]   SwitchCases   ::=   SwitchCaseClause+ "default" "return" ExprSingle
    SwitchCaseClause+ "default" "return" ExprSingle
    [88]   SwitchComparand   ::=   "(" Expr? ")"
    "(" Expr? ")"
    [87]   SwitchExpr   ::=   "switch" SwitchComparand (SwitchCases | BracedSwitchCases)
    "switch" SwitchComparand (SwitchCases | BracedSwitchCases)
    [235]   TextTest   ::=   "text" "(" ")"
    "text" "(" ")"
    [101]   ThenAction   ::=   EnclosedExpr
    EnclosedExpr
    [119]   TreatExpr   ::=   CastableExpr ( "treat" "as" SequenceType )?
    CastableExpr ( "treat" "as" SequenceType )?
    [104]   TryCatchExpr   ::=   TryClauseCatchClause+
    TryClauseCatchClause+
    [105]   TryClause   ::=   "try" EnclosedExpr
    "try" EnclosedExpr
    [68]   TumblingWindowClause   ::=   "tumbling" "window" VarNameAndType "in" ExprSingleWindowStartCondition? WindowEndCondition?
    "tumbling" "window" VarNameAndType "in" ExprSingleWindowStartCondition? WindowEndCondition?
    [262]   TypedArrayType   ::=   "array" "(" SequenceType ")"
    "array" "(" SequenceType ")"
    [227]   TypeDeclaration   ::=   "as" SequenceType
    "as" SequenceType
    [249]   TypedFunctionType   ::=   ("function" | "fn") "(" (SequenceType ** ",") ")" "as" SequenceType
    ("function" | "fn") "(" (SequenceType ** ",") ")" "as" SequenceType
    [252]   TypedMapType   ::=   "map" "(" ItemType "," SequenceType ")"
    "map" "(" ItemType "," SequenceType ")"
    [255]   TypedRecordType   ::=   "record" "(" (FieldDeclaration ** ",") ExtensibleFlag? ")"
    "record" "(" (FieldDeclaration ** ",") ExtensibleFlag? ")"
    [246]   TypeName   ::=   EQName
    EQName
    [94]   TypeswitchCases   ::=   CaseClause+ "default" VarName? "return" ExprSingle
    CaseClause+ "default" VarName? "return" ExprSingle
    [93]   TypeswitchExpr   ::=   "typeswitch" "(" Expr ")" (TypeswitchCases | BracedTypeswitchCases)
    "typeswitch" "(" Expr ")" (TypeswitchCases | BracedTypeswitchCases)
    [123]   UnaryExpr   ::=   ("-" | "+")* ValueExpr
    ("-" | "+")* ValueExpr
    [226]   UnaryLookup   ::=   ("?" | "??") (Modifier "::")? KeySpecifier
    ("?" | "??") (Modifier "::")? KeySpecifier
    [99]   UnbracedActions   ::=   "then" ExprSingle "else" ExprSingle
    "then" ExprSingle "else" ExprSingle
    [116]   UnionExpr   ::=   IntersectExceptExpr ( ("union" | "|") IntersectExceptExpr )*
    IntersectExceptExpr ( ("union" | "|") IntersectExceptExpr )*
    [149]   UnionNodeTest   ::=   "(" SimpleNodeTest ("|" SimpleNodeTest)* ")"
    "(" SimpleNodeTest ("|" SimpleNodeTest)* ")"
    [177]   UnorderedExpr   ::=   "unordered" EnclosedExpr
    "unordered" EnclosedExpr
    [201]   UnreservedName   ::=   EQName/* xgc: unreserved-name */
    EQName/* xgc: unreserved-name */
    /* xgc: unreserved-name */
    [202]   UnreservedNCName   ::=   NCName/* xgc: unreserved-name */
    NCName/* xgc: unreserved-name */
    /* xgc: unreserved-name */
    [264]   URILiteral   ::=   StringLiteral
    StringLiteral
    [132]   ValidateExpr   ::=   "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    [133]   ValidationMode   ::=   "lax" | "strict"
    "lax" | "strict"
    [130]   ValueComp   ::=   "eq" | "ne" | "lt" | "le" | "gt" | "ge"
    "eq" | "ne" | "lt" | "le" | "gt" | "ge"
    [124]   ValueExpr   ::=   ValidateExpr | ExtensionExpr | SimpleMapExpr
    ValidateExpr | ExtensionExpr | SimpleMapExpr
    [30]   VarDecl   ::=   "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    [32]   VarDefaultValue   ::=   ExprSingle
    ExprSingle
    [57]   VarName   ::=   "$" EQName
    "$" EQName
    [58]   VarNameAndType   ::=   "$" EQNameTypeDeclaration?
    "$" EQNameTypeDeclaration?
    [173]   VarRef   ::=   "$" EQName
    "$" EQName
    [31]   VarValue   ::=   ExprSingle
    ExprSingle
    [3]   VersionDecl   ::=   "xquery" (("encoding" StringLiteral) | ("version" StringLiteral ("encoding" StringLiteral)?)) Separator
    "xquery" (("encoding" StringLiteral) | ("version" StringLiteral ("encoding" StringLiteral)?)) Separator
    [77]   WhereClause   ::=   "where" ExprSingle
    "where" ExprSingle
    [78]   WhileClause   ::=   "while" ExprSingle
    "while" ExprSingle
    [152]   Wildcard   ::=   "*"
    | (NCName ":*")
    | ("*:" NCName)
    | (BracedURILiteral "*")
    /* ws: explicit */
    "*"
    | (NCName ":*")
    | ("*:" NCName)
    | (BracedURILiteral "*")
    /* ws: explicit */
    /* ws: explicit */
    [67]   WindowClause   ::=   "for" (TumblingWindowClause | SlidingWindowClause)
    "for" (TumblingWindowClause | SlidingWindowClause)
    [71]   WindowEndCondition   ::=   "only"? "end" WindowVars ("when" ExprSingle)?
    "only"? "end" WindowVars ("when" ExprSingle)?
    [70]   WindowStartCondition   ::=   "start" WindowVars ("when" ExprSingle)?
    "start" WindowVars ("when" ExprSingle)?
    [72]   WindowVars   ::=   CurrentVar? PositionalVar? PreviousVar? NextVar?
    CurrentVar? PositionalVar? PreviousVar? NextVar?
    [1]   XPath   ::=   Expr
    Expr

    A.1.1 Notation

    Changes in 4.0  

    1. The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.  [Issue 1366 PR 1498]

    [Definition: Each rule in the grammar defines one symbol, using the following format:

    symbol ::= expression

    ]

    [Definition: A terminal is a symbol or string or pattern that can appear in the right-hand side of a rule, but never appears on the left-hand side in the main grammar, although it may appear on the left-hand side of a rule in the grammar for terminals.] The following constructs are used to match strings of one or more characters in a terminal:

    [a-zA-Z]

    matches any Char with a value in the range(s) indicated (inclusive).

    [abc]

    matches any Char with a value among the characters enumerated.

    [^abc]

    matches any Char with a value not among the characters given.

    "string" or 'string'

    matches the sequence of characters that appear inside the double or single quotation marks.

    [http://www.w3.org/TR/REC-example/#NT-Example]

    matches any string matched by the production defined in the external specification as per the provided reference.

    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, A and B represent (sub-)patterns.

    (A)

    A is treated as a unit and may be combined as described in this list.

    A?

    matches A or nothing; optional A.

    A B

    matches A followed by B. This implicit operator has higher precedence than the choice operator |; thus A B | C D is interpreted as (A B) | (C D).

    A | B

    matches A or B but not both.

    A - B

    matches any string that matches A but does not match B.

    A+

    matches one or more occurrences of A. Concatenation has higher precedence than choice; thus A+ | B+ is identical to (A+) | (B+).

    A*

    matches zero or more occurrences of A. Concatenation has higher precedence than choice; thus A* | B* is identical to (A*) | (B*)

    (A ++ B)

    matches one or more occurrences of A, with one occurrence of B between adjacent occurrences of A. The notation A ++ B is a shorthand for A (B A)*. The construct is always parenthesized to avoid ambiguity, and although in principle B could be any pattern, in practice the notation is used only when it is a simple string literal (typically but not invariably ",").

    For example, (Digit ++ ".") matches 1 or 1.2 or 1.2.3.

    (A ** B)

    matches zero or more occurrences of A, with one occurrence of B between adjacent occurrences of A. The notation A ** B is a shorthand for (A (B A)*)?. The construct is always parenthesized to avoid ambiguity, and although in principle B could be any pattern, in practice the notation is used only when it is a simple string literal (typically but not invariably ",").

    For example, "[" (Digit ** "|") "]" matches [] or [1] or [1|2] or [1|2|3].

    A.1.2 Extra-grammatical Constraints

    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: /* xgc: <id> */.

    Constraint: leading-lone-slash

    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 RelativePathExpr. In some cases, the next terminal after the slash is insufficient to allow a parser to distinguish these two possibilities: a * symbol or a keyword like union could be either an operator or a NameTest. For example, the expression /union/* could be parsed either as (/) union (/*) or as /child::union/child::* (the second interpretation is the one chosen).

    The situation where / is followed by < is a little more complicated. In XPath, this is unambiguous: the < can only indicate one of the operators <, <=, or <<. 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.3 Lexical structure.

    The rule adopted is as follows: if the terminal immediately following a slash can form the start of a RelativePathExpr, then the slash must be the beginning of a PathExpr, not the entirety of it.

    The terminals that can form the start of a RelativePathExpr are: NCName, QName, URIQualifiedName, StringLiteral, NumericLiteral, Wildcard, and StringTemplate; plus @...*$???%([; and in XQuery StringConstructor and DirectConstructor.

    A single slash may be used as the left-hand argument of an operator by parenthesizing it: (/) * 5. The expression 5 * /, on the other hand, is syntactically valid without parentheses.

    Constraint: unreserved-name

    In a computed node constructor of the form element NNN {}, attribute NNN {}, processing-instruction NNN {}, or namespace NNN {}, XQuery 4.0 allows the name NNN to be written as a plain NCName only if it is not a language keyword: more specifically, if it is not one of the literal terminals taking the form of an NCName that are listed in A.3 Lexical structure. If such names (for example div or value) are to be used as element or attribute names in a computed node constructor, they must be written as a string literal in quotation marks.

    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.

    Constraint: xml-version

    The version of XML and XML Names (e.g. [XML 1.0] and [XML Names], or [XML 1.1] and [XML Names 1.1]) is implementation-defined. 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.3.5.1 Default Whitespace Handling. Thus prefix : localname is not a syntactically valid lexical QName 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.

    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 XQuery 1.0XPath 2.0, implementations MAY allow C1 control characters to be used directly.

    Note:

    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.

    Constraint: reserved-function-names

    Unprefixed function names spelled the same way as language keywords could make the language impossible to parse. For instance, element(foo) could be taken either as a FunctionCall or as an ElementTest. Therefore, an unprefixed function name must not be any of the names in A.4 Reserved Function Names.

    A function named if can be called by binding its namespace to a prefix and using the prefixed form: library:if(foo) instead of if(foo).

    Constraint: occurrence-indicators

    As written, the grammar in A XQuery 4.0 and XPath 4.0 Grammar is ambiguous for some forms using the "+", "?" and "*"OccurrenceIndicators. The ambiguity is resolved as follows: these operators are tightly bound to the SequenceType expression, and have higher precedence than other uses of these symbols. Any occurrence of "+", "?" or "*", that follows a sequence type is assumed to be an occurrence indicator, which binds to the last ItemType in the SequenceType.

    Thus, 4 treat as item() + - 5 must be interpreted as (4 treat as item()+) - 5, 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 (4 treat as item()) + -5 surrounds the SequenceType expression with parentheses and leads to the desired interpretation.

    function () as xs:string * is interpreted as function () as (xs:string *), not as (function () as xs:string) *. Parentheses can be used as shown to force the latter interpretation.

    This rule has as a consequence that certain forms which would otherwise be syntactically valid and unambiguous are not recognized: in 4 treat as item() + 5, the "+" is taken as an OccurrenceIndicator, and not as an operator, which means this is not a syntactically valid expression.

    A.1.3 Grammar Notes

    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: /* gn: <id> */.

    Note:

    grammar-note: parens

    Lookahead is required to distinguish a FunctionCall from an EQName or keyword followed by a Pragma or Comment. For example: address (: this may be empty :) may be mistaken for a call to a function named "address" unless this lookahead is employed. Another example is for (: whom the bell :) $tolls in 3 return $tolls, where the keyword "for" must not be mistaken for a function name.

    grammar-note: comments

    Comments are allowed everywhere that ignorable whitespace is allowed, and the Comment symbol does not explicitly appear on the right-hand side of the grammar (except in its own production). See A.3.5.1 Default Whitespace Handling. Note that comments are not allowed in direct constructor content, though they are allowed in nested EnclosedExprs.

    A comment can contain nested comments, as long as all "(:" and ":)" patterns are balanced, no matter where they occur within the outer comment.

    Note:

    Lexical analysis may typically handle nested comments by incrementing a counter for each "(:" pattern, and decrementing the counter for each ":)" pattern. The comment does not terminate until the counter is back to zero.

    Some illustrative examples:

    • (: commenting out a (: comment :) may be confusing, but often helpful :) is a syntactically valid Comment, since balanced nesting of comments is allowed.

    • "this is just a string :)" is a syntactically valid expression. However, (: "this is just a string :)" :) will cause a syntax error. Likewise, "this is another string (:" is a syntactically valid expression, but (: "this is another string (:" :) will cause a syntax error. It is a limitation of nested comments that literal content can cause unbalanced nesting of comments.

    • for (: set up loop :) $i in $x return $i is syntactically valid, ignoring the comment.

    • 5 instance (: strange place for a comment :) of xs:integer is also syntactically valid.

    • <eg (: an example:)>{$i//title}</eg> is not syntactically valid.

    • <eg> (: an example:) </eg> is syntactically valid, but the characters that look like a comment are in fact literal element content.

    A.2 Productions Derived from XML

    Some productions are defined by reference to the XML and XML Names specifications (e.g. [XML 1.0] and [XML Names], or [XML 1.1] and [XML Names 1.1]. A host language may chooseIt is implementation-defined 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).

    A host language may choose whether the lexical rules of [XML 1.0] and [XML Names] are followed, or alternatively, the lexical rules of [XML 1.1] and [XML Names 1.1] are followed.

    It is implementation-defined whether the lexical rules of [XML 1.0] and [XML Names] are followed, or alternatively, the lexical rules of [XML 1.1] and [XML Names 1.1] are followed. Implementations that support the full [XML 1.1] character set SHOULD, for purposes of interoperability, provide a mode that follows only the [XML 1.0] and [XML Names] lexical rules.

    A.3 Lexical structure

    Changes in 4.0  

    1. 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.   [Issue 327 PR 519 30 May 2023]

    This section describes how an XQuery 4.0 and XPath 4.0 text is tokenized prior to parsing.

    All keywords are case sensitive. Keywords are not reserved—that is, any lexical QName may duplicate a keyword except as noted in A.4 Reserved Function Names.

    Tokenizing an input string is a process that follows the following rules:

    • [Definition: An ordinary production rule is a production rule in A.1 EBNF that is not annotated ws:explicit.]

    • [Definition: A literal terminal is a token appearing as a string in quotation marks on the right-hand side of an ordinary production rule.]

      Note:

      Strings that appear in other production rules do not qualify. For example, "]]>" is not a literal terminal, because it appears only in the rule CDataSection, which is not an ordinary production rule; similarly BracedURILiteral does not qualify because it appears only in URIQualifiedName, and "0x" does not qualify because it appears only in HexIntegerLiteral.For example, BracedURILiteral does not quality because it appears only in URIQualifiedName, and "0x" does not qualify because it appears only in HexIntegerLiteral.

      The literal terminals in XQuery 4.0 and XPath 4.0 are: !!=#$%()*+,...///::::=;<<<<===!>=>=?>>>=>>????[@[]{|||}×÷-allowingancestorancestor-or-selfandarrayasascendingatattributebase-uriboundary-spacebycasecastcastablecatchchildcollationcommentconstructioncontextcopy-namespacescountdecimal-formatdecimal-separatordeclaredefaultdescendantdescendant-or-selfdescendingdigitdivdocumentdocument-nodeelementelseemptyempty-sequenceencodingendenumeqeveryexceptexponent-separatorexternalfalsefixedfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selfforfunctiongegreatestgroupgrouping-separatorgtidivifimportininfinityinheritinstanceintersectisitemitemskeykeyslaxleleastletltmapmemberminus-signmodmodulenamespacenamespace-nodeNaNnenextno-inheritno-preservenodeofonlyoptionororderorderedorderingotherwisepairsparentpattern-separatorper-millepercentprecedingpreceding-or-selfpreceding-sibling-or-selfpreservepreviousprocessing-instructionrecordreturnsatisfiesschemaschema-attributeschema-elementselfslidingsomestablestartstrictstripswitchtextthentotreattruetrytumblingtypetypeswitchunionunorderedvalidatevaluevaluesvariableversionwhenwherewhilewindowxqueryzero-digit

    • [Definition: A variable terminal is an instance of a production rule that is not itself an ordinary production rule but that is named (directly) on the right-hand side of an ordinary production rule.]

      The variable terminals in XQuery 4.0 and XPath 4.0 are: BinaryIntegerLiteralCDataSectionDecimalLiteralDirCommentConstructorDirElemConstructorDirPIConstructorDoubleLiteralHexIntegerLiteralIntegerLiteralNCNamePragmaQNameStringConstructorStringLiteralStringTemplateURIQualifiedNameWildcard

    • [Definition: A complex terminal is a variable terminal whose production rule references, directly or indirectly, an ordinary production rule.]

      The complex terminals in XQuery 4.0 and XPath 4.0 are: DirElemConstructorPragmaStringConstructorStringTemplate

      Note:

      The significance of complex terminals is that at one level, a complex terminal is treated as a single token, but internally it may contain arbitrary expressions that must be parsed using the full EBNF grammar.

    • Tokenization is the process of splitting the supplied input string into a sequence of terminals, where each terminal is either a literal terminal or a variable terminal (which may itself be a complex terminal). Tokenization is done by repeating the following steps:

      1. Starting at the current position, skip any whitespace and comments.

      2. If the current position is not the end of the input, then return the longest literal terminal or variable terminal that can be matched starting at the current position, regardless whether this terminal is valid at this point in the grammar. If no such terminal can be identified starting at the current position, or if the terminal that is identified is not a valid continuation of the grammar rules, then a syntax error is reported.

        Note:

        Here are some examples showing the effect of the longest token rule:

        • The expression map{a:b} is a syntax error. Although there is a tokenization of this string that satisfies the grammar (by treating a and b as separate expressions), this tokenization does not satisfy the longest token rule, which requires that a:b is interpreted as a single QName.

        • The expression 10 div3 is a syntax error. The longest token rule requires that this be interpreted as two tokens ("10" and "div3") even though it would be a valid expression if treated as three tokens ("10", "div", and "3").

        • The expression $x-$y is a syntax error. This is interpreted as four tokens, ("$", "x-", "$", and "y").

        Note:

        The lexical production rules for variable terminals have been designed so that there is minimal need for backtracking. For example, if the next terminal starts with "0x", then it can only be either a HexIntegerLiteral or an error; if it starts with "`" (and not with "```") then it can only be a StringTemplate or an error. Direct element constructors in XQuery, however, need special treatment, described below.

        This convention, together with the rules for whitespace separation of tokens (see A.3.2 Terminal Delimitation) means that the longest-token rule does not normally result in any need for backtracking. For example, suppose that a variable terminal has been identified as a StringTemplate by examining its first few characters. If the construct turns out not to be a valid StringTemplate, an error can be reported without first considering whether there is some shorter token that might be returned instead.

    • Tokenization requires special care when the current character is U+003C (LESS-THAN SIGN, <) :

      • If the following character is U+003D (EQUALS SIGN, =) then the token can be identified unambiguously as the operator <=.

      • If the following character is U+003C (LESS-THAN SIGN, <) then the token can be identified unambiguously as the operator <<.

      • If the following character is U+0021 (EXCLAMATION MARK, !) then the token can be identified unambiguously as being a DirCommentConstructor (a CDataSection, which also starts with <! can appear only within a direct element constructor, not as a free-standing token).

      • If the following character is U+003F (QUESTION MARK, ?) , then the token is identified as a DirPIConstructor if and only if a match for the relevant production ("<?" PITarget (S DirPIContents)? "?>") is found. If there is no such match, then the string "<?" is identified as a less-than operator followed by a lookup operator.

      • If the following character is a NameStartChar then the token is identified as a DirElemConstructor if and only if a match for the leading part of a DirElemConstructor is found: specifically if a substring starting at the U+003C (LESS-THAN SIGN, <) character matches one of the following regular expressions:

        ^<\i\c*\s*> (as in <element>...)
        ^<\i\c*\s*/>(as in <element/>)
        ^<\i\c*\s+\i\c*\s*=(as in <element att=...)

        If the content matches one of these regular expressions but further analysis shows that the subsequent content does not satisfy the DirElemConstructor production, then a static error is reported.

        If the content does not match any of these regular expressions then the token is identified as the less-than operator <.

      • If the following character is any other character then the token can be identified unambiguously as the less-than operator <.

      This analysis is done without regard to the syntactic context of the U+003C (LESS-THAN SIGN, <) character. However, a tokenizer may avoid looking for a DirPIConstructor or DirElemConstructor if it knows that such a constructor cannot appear in the current syntactic context.

      Note:

      The rules here are described much more precisely than in XQuery 3.1, and the results in edge cases might be incompatible with some XQuery 3.1 processors.

      Note:

      To avoid potential confusion, simply add whitespace after any less-than operator.

    • Tokenization unambiguously identifies the boundaries of the terminals in the input, and this can be achieved without backtracking or lookahead. However, tokenization does not unambiguously classify each terminal. For example, it might identify the string "div" as a terminal, but it does not resolve whether this is the operator symbol div, or an NCName or QName used as a node test or as a variable or function name. Classification of terminals generally requires information about the grammatical context, and in some cases requires lookahead.

      Note:

      Operationally, classification of terminals may be done either in the tokenizer or the parser, or in some combination of the two. For example, according to the EBNF, the expression "parent::x" is made up of three tokens, "parent", "::", and "x". The name "parent" can be classified as an axis name as soon as the following token "::" is recognized, and this might be done either in the tokenizer or in the parser. (Note that whitespace and comments are allowed both before and after "::".)

    • In the case of a complex terminal, identifying the end of the complex terminal typically involves invoking the parser to process any embedded expressions. Tokenization, as described here, is therefore a recursive process. But other implementations are possible.

    Note:

    Previous versions of this specification included the statement: When tokenizing, the longest possible match that is consistent with the EBNF is used.

    Different processors are known to have interpreted this in different ways. One interpretation, for example, was that the expression 10 div-3 should be split into four tokens (10, div, -, 3) on the grounds that any other tokenization would give a result that was inconsistent with the EBNF grammar. Other processors report a syntax error on this example.

    This rule has therefore been rewritten in version 4.0. Tokenization is now entirely insensitive to the grammatical context; div-3 is recognized as a single token even though this results in a syntax error. For some implementations this may mean that expressions that were accepted in earlier releases are no longer accepted in 4.0.

    A more subtle example is: (. <?b ) cast as xs:integer?> 0) in which <?b ) cast as xs:integer?> is recognized as a single token (a direct processing instruction constructor) even though such a token cannot validly appear in this grammatical context.

    A.3.1 Terminal Symbols

    [266]   IntegerLiteral   ::=   Digits/* ws: explicit */
    Digits/* ws: explicit */
    /* ws: explicit */
    [267]   HexIntegerLiteral   ::=   "0x" HexDigits/* ws: explicit */
    "0x" HexDigits/* ws: explicit */
    /* ws: explicit */
    [268]   BinaryIntegerLiteral   ::=   "0b" BinaryDigits/* ws: explicit */
    "0b" BinaryDigits/* ws: explicit */
    /* ws: explicit */
    [269]   DecimalLiteral   ::=   ("." Digits) | (Digits "." Digits?)/* ws: explicit */
    ("." Digits) | (Digits "." Digits?)/* ws: explicit */
    /* ws: explicit */
    [270]   DoubleLiteral   ::=   (("." Digits) | (Digits ("." Digits?)?)) [eE] [+-]? Digits/* ws: explicit */
    (("." Digits) | (Digits ("." Digits?)?)) [eE] [+-]? Digits/* ws: explicit */
    /* ws: explicit */
    [271]   StringLiteral   ::=   AposStringLiteral | QuotStringLiteral/* ws: explicit */
    AposStringLiteral | QuotStringLiteral/* ws: explicit */
    /* ws: explicit */
    [272]   AposStringLiteral   ::=   "'" (PredefinedEntityRef | CharRef | EscapeApos | [^'&])* "'"/* ws: explicit */
    "'" (PredefinedEntityRef | CharRef | EscapeApos | [^'&])* "'"/* ws: explicit */
    /* ws: explicit */
    [273]   QuotStringLiteral   ::=   '"' (PredefinedEntityRef | CharRef | EscapeQuot | [^"&])* '"'/* ws: explicit */
    '"' (PredefinedEntityRef | CharRef | EscapeQuot | [^"&])* '"'/* ws: explicit */
    /* ws: explicit */
    [274]   URIQualifiedName   ::=   BracedURILiteralNCName/* ws: explicit */
    BracedURILiteralNCName/* ws: explicit */
    /* ws: explicit */
    [275]   BracedURILiteral   ::=   "Q" "{" (PredefinedEntityRef | CharRef | [^&{}])* "}"/* ws: explicit */
    "Q" "{" (PredefinedEntityRef | CharRef | [^&{}])* "}"/* ws: explicit */
    /* ws: explicit */
    [276]   PredefinedEntityRef   ::=   "&" ("lt" | "gt" | "amp" | "quot" | "apos") ";"/* ws: explicit */
    "&" ("lt" | "gt" | "amp" | "quot" | "apos") ";"/* ws: explicit */
    /* ws: explicit */
    [277]   EscapeQuot   ::=   '""'/* ws: explicit */
    '""'/* ws: explicit */
    /* ws: explicit */
    [278]   EscapeApos   ::=   "''"/* ws: explicit */
    "''"/* ws: explicit */
    /* ws: explicit */
    [279]   ElementContentChar   ::=   (Char - [{}<&])
    (Char - [{}<&])
    [280]   QuotAttrContentChar   ::=   (Char - ["{}<&])
    (Char - ["{}<&])
    [281]   AposAttrContentChar   ::=   (Char - ['{}<&])
    (Char - ['{}<&])
    [282]   Comment   ::=   "(:" (CommentContents | Comment)* ":)"/* ws: explicit */
    "(:" (CommentContents | Comment)* ":)"/* ws: explicit */
    /* ws: explicit */
    /* gn: comments */
    [283]   PITarget   ::=   [http://www.w3.org/TR/REC-xml#NT-PITarget]XML/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml#NT-PITarget]XML/* xgc: xml-version */
    /* xgc: xml-version */
    [284]   CharRef   ::=   [http://www.w3.org/TR/REC-xml#NT-CharRef]XML/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml#NT-CharRef]XML/* xgc: xml-version */
    /* xgc: xml-version */
    [285]   QName   ::=   [http://www.w3.org/TR/REC-xml-names/#NT-QName]Names/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml-names/#NT-QName]Names/* xgc: xml-version */
    /* xgc: xml-version */
    [286]   NCName   ::=   [http://www.w3.org/TR/REC-xml-names/#NT-NCName]Names/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml-names/#NT-NCName]Names/* xgc: xml-version */
    /* xgc: xml-version */
    [287]   S   ::=   [http://www.w3.org/TR/REC-xml#NT-S]XML/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml#NT-S]XML/* xgc: xml-version */
    /* xgc: xml-version */
    [288]   Char   ::=   [http://www.w3.org/TR/REC-xml#NT-Char]XML/* xgc: xml-version */
    [http://www.w3.org/TR/REC-xml#NT-Char]XML/* xgc: xml-version */
    /* xgc: xml-version */

    The following symbols are used only in the definition of terminal symbols; they are not terminal symbols in the grammar of A.1 EBNF.

    [289]   Digits   ::=   DecDigit ((DecDigit | "_")* DecDigit)?/* ws: explicit */
    DecDigit ((DecDigit | "_")* DecDigit)?/* ws: explicit */
    /* ws: explicit */
    [290]   DecDigit   ::=   [0-9]/* ws: explicit */
    [0-9]/* ws: explicit */
    /* ws: explicit */
    [291]   HexDigits   ::=   HexDigit ((HexDigit | "_")* HexDigit)?/* ws: explicit */
    HexDigit ((HexDigit | "_")* HexDigit)?/* ws: explicit */
    /* ws: explicit */
    [292]   HexDigit   ::=   [0-9a-fA-F]/* ws: explicit */
    [0-9a-fA-F]/* ws: explicit */
    /* ws: explicit */
    [293]   BinaryDigits   ::=   BinaryDigit ((BinaryDigit | "_")* BinaryDigit)?/* ws: explicit */
    BinaryDigit ((BinaryDigit | "_")* BinaryDigit)?/* ws: explicit */
    /* ws: explicit */
    [294]   BinaryDigit   ::=   [01]/* ws: explicit */
    [01]/* ws: explicit */
    /* ws: explicit */
    [295]   CommentContents   ::=   (Char+ - (Char* ('(:' | ':)') Char*))/* ws: explicit */
    (Char+ - (Char* ('(:' | ':)') Char*))/* ws: explicit */
    /* ws: explicit */

    A.3.2 Terminal Delimitation

    XQuery 4.0 and XPath 4.0 expressions consist of terminal symbols and symbol separators.

    Literal and variable terminal symbols are of two kinds: delimiting and non-delimiting.

    [Definition: The delimiting terminal symbols are: !!=#$%()**:,-...::*:::=;<<<===!>=>=?>>>=>>????[@[]```{{{|||}}}×÷AposStringLiteralBracedURILiteral]]><![CDATA[--><!--/></<+#)(#?><?QuotStringLiteralS///]````[}``{StringLiteral ]

    [Definition: The non-delimiting terminal symbols are: allowingancestorancestor-or-selfandarrayasatattributebase-uriboundary-spacebycasecastcastablecatchchildcollationcommentconstructioncontextcopy-namespacescountdecimal-formatdecimal-separatordeclaredefaultdescendantdescendant-or-selfdigitdivdocumentdocument-nodeelementelseemptyempty-sequenceencodingendenumeqeveryexceptexponent-separatorfalsefixedfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selfforfunctiongegroupgrouping-separatorgtidivifimportininfinityinheritinstanceintersectisitemitemskeykeyslaxleletltmapmemberminus-signmodmodulenamespacenamespace-nodeNaNnenextno-inheritno-preservenodeofonlyoptionororderorderedorderingotherwisepairsparentpattern-separatorper-millepercentprecedingpreceding-or-selfpreceding-sibling-or-selfpreservepreviousprocessing-instructionrecordreturnsatisfiesschemaschema-attributeschema-elementselfslidingsomestablestartstrictstripswitchtextthentotreattruetrytumblingtypetypeswitchunionunorderedvalidatevaluevaluesvariableversionwhenwherewhilewindowxqueryzero-digitascendingBinaryIntegerLiteralDecimalLiteraldescendingDoubleLiteralexternalgreatestHexIntegerLiteralIntegerLiteralleastNCNameQNameURIQualifiedName ]

    [Definition: Whitespace and Comments function as symbol separators. For the most part, they are not mentioned in the grammar, and may occur between any two terminal symbols mentioned in the grammar, except where that is forbidden by the /* ws: explicit */ annotation in the EBNF, or by the /* xgc: xml-version */ annotation.]

    As a consequence of the longest token rule (see A.3 Lexical structure), one or more symbol separators are required between two consecutive terminal symbols T and U (where T precedes U) when any of the following is true:

    A.3.3 Less-Than and Greater-Than Characters

    The operator symbols <, <=, >, >=, <<, >>, =>, =!>, and =?> have alternative representations using the characters U+FF1C (FULL-WIDTH LESS-THAN SIGN, ) and U+FF1E (FULL-WIDTH GREATER-THAN SIGN, ) in place of U+003C (LESS-THAN SIGN, <) and U+003E (GREATER-THAN SIGN, >) . The alternative tokens are respectively , <=, , >=, <<, >>, =>, =!>, and =?>. In order to avoid visual confusion these alternatives are not shown explicitly in the grammar.

    This option is provided to improve the readability of XPath expressions embedded in XML-based host languages such as XSLT; it enables these operators to be depicted using characters that do not require escaping as XML entities or character references.

    This rule does not apply to the < and > symbols used to delimit node constructor expressions, which (because they mimic XML syntax) must use U+003C (LESS-THAN SIGN, <) and U+003E (GREATER-THAN SIGN, >) respectively.

    A.3.4 End-of-Line Handling

    The host language must specify whether the XQuery 4.0 and XPath 4.0 processor normalizes all line breaks on input, before parsing, and if it does so, whether it uses the rules of [XML 1.0] or [XML 1.1].

    Note:

    XML-based host languages such as XSLT and XSD do not normalize line breaks at the XPath level, because it will already have been done by the host XML parser. Use of character or entity references suppresses normalization of line breaks, so the string literal &#x0D; written within an XSLT-hosted XPath expression represents a string containing a single U+000D (CARRIAGE RETURN) character.

    Prior to parsing, the XQuery 4.0 and XPath 4.0 processor must normalize all line breaks. The rules for line breaking follow the rules of [XML 1.0] or [XML 1.1]. It is implementation-defined which version is used.

    A.3.4.1 XML 1.0 End-of-Line Handling

    For [XML 1.0] processing, all of the following must be translated to a single U+000A (NEWLINE) :

    1. the two-character sequence U+000D (CARRIAGE RETURN) , U+000A (NEWLINE) ;

    2. any U+000D (CARRIAGE RETURN) character that is not immediately followed by U+000A (NEWLINE) .

    A.3.4.2 XML 1.1 End-of-Line Handling

    For [XML 1.1] processing, all of the following must be translated to a single U+000A (NEWLINE) character:

    1. the two-character sequence U+000D (CARRIAGE RETURN) , U+000A (NEWLINE) ;

    2. the two-character sequence U+000D (CARRIAGE RETURN) , U+0085 (NEXT LINE, NEL) ;

    3. the single character U+0085 (NEXT LINE, NEL) ;

    4. the single character U+2028 (LINE SEPARATOR) ;

    5. any U+000D (CARRIAGE RETURN) character that is not immediately followed by U+000A (NEWLINE) or U+0085 (NEXT LINE, NEL) .

    The characters U+0085 (NEXT LINE, NEL) and U+2028 (LINE SEPARATOR) cannot be reliably recognized and translated until the VersionDecl declaration (if present) has been read.

    A.3.5 Whitespace Rules

    A.3.5.1 Default Whitespace Handling

    [Definition: A whitespace character is any of the characters defined by [http://www.w3.org/TR/REC-xml/#NT-S].]

    [Definition: Ignorable whitespace consists of any whitespace characters that may occur between terminals, unless these characters occur in the context of a production marked with a ws:explicit annotation, in which case they can occur only where explicitly specified (see A.3.5.2 Explicit Whitespace Handling).] Ignorable whitespace characters are not significant to the semantics of an expression. Whitespace is allowed before the first terminal and after the last terminal of a moduleof an XPath expression. Whitespace is allowed between any two terminals. Comments may also act as "whitespace" to prevent two adjacent terminals from being recognized as one. Some illustrative examples are as follows:

    • foo- foo results in a syntax error. "foo-" would be recognized as a QName.

    • foo -foo is syntactically equivalent to foo - foo, two QNames separated by a subtraction operator.

    • foo(: This is a comment :)- foo is syntactically equivalent to foo - foo. This is because the comment prevents the two adjacent terminals from being recognized as one.

    • foo-foo 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.

    • 10div 3 results in a syntax error.

    • 10 div3 also results in a syntax error.

    • 10div3 also results in a syntax error.

    A.3.5.2 Explicit Whitespace Handling

    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.

    ws: explicit

    /* ws: explicit */ means that the EBNF notation explicitly notates, with S or otherwise, where whitespace characters are allowed. In productions with the /* ws: explicit */ annotation, A.3.5.1 Default Whitespace Handling does not apply. Comments are not allowed in these productions except where the Comment non-terminal appears.

    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.

    A.4 Reserved Function Names

    Changes in 4.0  

    1. XQuery and XPath 3.0 included empty-sequence and item as reserved function names, and XQuery and XPath 3.1 added map and array. This was unnecessary since these names never appear followed by a left parenthesis at the start of an expression. They have therefore been removed from the list. New keywords introducing item types, such as record and enum, have not been included in the list.   [Issue 1208 PR 1212 15 May 2024]

    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.

    Names used in KindTests:

    attribute
    comment
    document-node
    element
    namespace-node
    node
    schema-attribute
    schema-element
    processing-instruction
    text

    Names used as syntactic keywords:

    fn
    function
    if
    switch
    typeswitch

    Note:

    Although the keywords switch and typeswitch are not used in XPath, they are considered reserved function names for compatibility with XQuery.

    Note:

    As the language evolves in the future, it may become necessary to reserve additional names. Furthermore, use of common programming terms like return and while 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.

    A.5 Precedence Order (Non-Normative)

    The grammar in A.1 EBNF normatively defines built-in precedence among the operators of XQueryXPath. 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.

    #OperatorAssociativity
    1, (comma)either
    2for,let,FLWOR,some, every, switch,typeswitch,try,ifNA
    3oreither
    4andeither
    5eq, ne, lt, le, gt, ge, =, !=, <, <=, >, >=, is, <<, >>NA
    6otherwiseeither
    7||left-to-right
    8toNA
    9+, - (binary)left-to-right
    10*, div, idiv, modleft-to-right
    11union, |either
    12intersect, exceptleft-to-right
    13instance ofNA
    14treat asNA
    15castable asNA
    16cast asNA
    17=>, =!>, =?>left-to-right
    18-, + (unary)right-to-left
    19!left-to-right
    20/, //left-to-right
    21[ ], ?, ??left-to-right
    22? (unary)NA

    In the "Associativity" column, "either" indicates that all the operators at that level have the associative property (i.e., (A op B) op C is equivalent to A op (B op C)), so their associativity is inconsequential. "NA" (not applicable) indicates that the EBNF does not allow an expression that directly contains multiple operators from that precedence level, so the question of their associativity does not arise.

    Note:

    Parentheses can be used to override the operator precedence in the usual way. Square brackets in an expression such as A[B] 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.

    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.

    B Type Promotion and Operator Mapping

    B.1 Type Promotion

    [Definition: Under certain circumstances, an atomic item can be promoted from one type to another.] Type promotion is used in a number of contexts:

    • It forms part of the process described by the coercion rules, invoked for example when a value of one type is supplied as an argument of a function call where the required type of the corresponding function parameter is declared with a different type.

    • It forms part of the process described in B.2 Operator Mapping, which selects the implementation of a binary operator based on the types of the supplied operands.

    • It is invoked (by explicit reference) in a number of other situations, for example when computing an average of a sequence of numeric values (in the fn:avg function), and in order by clauses (see 4.13.9 Order By Clause).

    In general, type promotion takes a set of one or more atomic items as input, potentially having different types, and selects a single common type to which all the input values can be converted by casting.

    There are three families of atomic types that can be mixed in this way:

    1. Numeric types. This applies when the input contains values of types xs:decimal, xs:float, and xs:double (including types derived from these, such as xs:integer).

      The rules are:

      1. If any of the items is of type xs:double, then all the values are cast to type xs:double.

      2. Otherwise, if any of the items is of type xs:float, then all the values are cast to type xs:float.

      3. Otherwise, no casting takes place: the values remain as xs:decimal.

    2. String types. This applies when the input contains values of types xs:string and xs:anyURI (including types derived from these, such as xs:NCName).

      The rule is that if any of the items is of type xs:string, then all the values are cast to type xs:string.

    3. Binary types. This applies when the input contains values of types xs:hexBinary and xs:base64Binary (including types derived from these).

      The rule is that if any of the items is of type xs:hexBinary, then all the values are cast to type xs:hexBinary.

    B.2 Operator Mapping

    Changes in 4.0  

    1. The operator mapping table has been simplified by removing entries for the operators ne, le, gt, and ge; these are now defined by reference to the rules for the operators eq and lt.

    The operator mapping tables in this section list the combinations of types for which various operators of XQuery 4.0 and XPath 4.0 are defined. The operators covered by this appendix are the value comparison operators eq and lt, and the arithmetic operators +, -, *, div, idiv, and mod.

    Other operators (such as and, or, intersect, union, =, ||, and is) are defined directly in the main body of this document, and do not occur in the operator mapping table.

    The operators ne, le, gt, and ge do not occur in the operator mapping table, but are instead defined by the following equivalences:

    • A ne B is equivalent to not(A eq B)

    • A le B is equivalent to A lt B or A eq B

    • A gt B is equivalent to B lt A

    • A ge B is equivalent to B lt A or B eq A

    [Definition: For each operator and valid combination of operand types, the operator mapping tables specify a result type and an expression that invokes an operator function; the operator function implements the semantics of the operator for the given types.] The definitions of the operator functions are given in [XQuery and XPath Functions and Operators 4.0]. The result of an operator may be the raising of an error by its operator function, as defined in [XQuery and XPath Functions and Operators 4.0]. The operator function fully defines the semantics of a given operator for the case where the operands are single atomic items of the types given in the table. For the definition of each operator (including its behavior for empty sequences or sequences of length greater than one), see the descriptive material in the main part of this document.

    If an operator in the operator mapping tables expects an operand of type ET, that operator can be applied to an operand of type AT if type AT can be converted to type ET by a combination of type promotion and subtype substitution. For example, a table entry indicates that the gt operator may be applied to two xs:date operands, returning xs:boolean. Therefore, the gt operator may also be applied to two (possibly different) subtypes of xs:date, also returning xs:boolean.

    [Definition: When referring to a type, the term numeric denotes the types xs:integer, xs:decimal, xs:float, and xs:double which are all member types of the built-in union type xs:numeric.] An operator whose operands and result are designated as numeric might be thought of as representing four operators, one for each of the numeric types. For example, the numeric + operator might be thought of as representing the following four operators:

    OperatorFirst operand typeSecond operand typeResult type
    +xs:integerxs:integerxs:integer
    +xs:decimalxs:decimalxs:decimal
    +xs:floatxs:floatxs:float
    +xs:doublexs:doublexs:double

    A numeric operator may be validly applied to an operand of type AT if type AT can be converted to any of the four numeric types by a combination of type promotion and subtype substitution. If the result type of an operator is listed as numeric, it means "the first type in the ordered list (xs:integer, xs:decimal, xs:float, xs:double) into which all operands can be converted by subtype substitution and type promotion." As an example, suppose that the type hatsize is derived from xs:integer and the type shoesize is derived from xs:float. Then if the + operator is invoked with operands of type hatsize and shoesize, it returns a result of type xs:float. Similarly, if + is invoked with two operands of type hatsize it returns a result of type xs:integer.

    [Definition: In the operator mapping tables, the term Gregorian refers to the types xs:gYearMonth, xs:gYear, xs:gMonthDay, xs:gDay, and xs:gMonth.] For binary operators that accept two Gregorian-type operands, both operands must have the same type (for example, if one operand is of type xs:gDay, the other operand must be of type xs:gDay.)

    [Definition: In the operator mapping tables, the term binary refers to the types xs:hexBinary and xs:base64Binary.] For operators that accept two binary operands, both operands are promoted to type xs:hexBinary.

    Binary Operators
    OperatorType(A)Type(B)FunctionResult type
    A + Bnumericnumericop:numeric-add(A, B)numeric
    A + Bxs:datexs:yearMonthDurationop:add-yearMonthDuration-to-date(A, B)xs:date
    A + Bxs:yearMonthDurationxs:dateop:add-yearMonthDuration-to-date(B, A)xs:date
    A + Bxs:datexs:dayTimeDurationop:add-dayTimeDuration-to-date(A, B)xs:date
    A + Bxs:dayTimeDurationxs:dateop:add-dayTimeDuration-to-date(B, A)xs:date
    A + Bxs:timexs:dayTimeDurationop:add-dayTimeDuration-to-time(A, B)xs:time
    A + Bxs:dayTimeDurationxs:timeop:add-dayTimeDuration-to-time(B, A)xs:time
    A + Bxs:dateTimexs:yearMonthDurationop:add-yearMonthDuration-to-dateTime(A, B)xs:dateTime
    A + Bxs:yearMonthDurationxs:dateTimeop:add-yearMonthDuration-to-dateTime(B, A)xs:dateTime
    A + Bxs:dateTimexs:dayTimeDurationop:add-dayTimeDuration-to-dateTime(A, B)xs:dateTime
    A + Bxs:dayTimeDurationxs:dateTimeop:add-dayTimeDuration-to-dateTime(B, A)xs:dateTime
    A + Bxs:yearMonthDurationxs:yearMonthDurationop:add-yearMonthDurations(A, B)xs:yearMonthDuration
    A + Bxs:dayTimeDurationxs:dayTimeDurationop:add-dayTimeDurations(A, B)xs:dayTimeDuration
    A - Bnumericnumericop:numeric-subtract(A, B)numeric
    A - Bxs:datexs:dateop:subtract-dates(A, B)xs:dayTimeDuration
    A - Bxs:datexs:yearMonthDurationop:subtract-yearMonthDuration-from-date(A, B)xs:date
    A - Bxs:datexs:dayTimeDurationop:subtract-dayTimeDuration-from-date(A, B)xs:date
    A - Bxs:timexs:timeop:subtract-times(A, B)xs:dayTimeDuration
    A - Bxs:timexs:dayTimeDurationop:subtract-dayTimeDuration-from-time(A, B)xs:time
    A - Bxs:dateTimexs:dateTimeop:subtract-dateTimes(A, B)xs:dayTimeDuration
    A - Bxs:dateTimexs:yearMonthDurationop:subtract-yearMonthDuration-from-dateTime(A, B)xs:dateTime
    A - Bxs:dateTimexs:dayTimeDurationop:subtract-dayTimeDuration-from-dateTime(A, B)xs:dateTime
    A - Bxs:yearMonthDurationxs:yearMonthDurationop:subtract-yearMonthDurations(A, B)xs:yearMonthDuration
    A - Bxs:dayTimeDurationxs:dayTimeDurationop:subtract-dayTimeDurations(A, B)xs:dayTimeDuration
    A * Bnumericnumericop:numeric-multiply(A, B)numeric
    A * Bxs:yearMonthDurationnumericop:multiply-yearMonthDuration(A, B)xs:yearMonthDuration
    A * Bnumericxs:yearMonthDurationop:multiply-yearMonthDuration(B, A)xs:yearMonthDuration
    A * Bxs:dayTimeDurationnumericop:multiply-dayTimeDuration(A, B)xs:dayTimeDuration
    A * Bnumericxs:dayTimeDurationop:multiply-dayTimeDuration(B, A)xs:dayTimeDuration
    A × Bnumericnumericop:numeric-multiply(A, B)numeric
    A × Bxs:yearMonthDurationnumericop:multiply-yearMonthDuration(A, B)xs:yearMonthDuration
    A × Bnumericxs:yearMonthDurationop:multiply-yearMonthDuration(B, A)xs:yearMonthDuration
    A × Bxs:dayTimeDurationnumericop:multiply-dayTimeDuration(A, B)xs:dayTimeDuration
    A × Bnumericxs:dayTimeDurationop:multiply-dayTimeDuration(B, A)xs:dayTimeDuration
    A idiv Bnumericnumericop:numeric-integer-divide(A, B)xs:integer
    A div Bnumericnumericop:numeric-divide(A, B)numeric; but xs:decimal if both operands are xs:integer
    A div Bxs:yearMonthDurationnumericop:divide-yearMonthDuration(A, B)xs:yearMonthDuration
    A div Bxs:dayTimeDurationnumericop:divide-dayTimeDuration(A, B)xs:dayTimeDuration
    A div Bxs:yearMonthDurationxs:yearMonthDurationop:divide-yearMonthDuration-by-yearMonthDuration (A, B)xs:decimal
    A div Bxs:dayTimeDurationxs:dayTimeDurationop:divide-dayTimeDuration-by-dayTimeDuration (A, B)xs:decimal
    A ÷ Bnumericnumericop:numeric-divide(A, B)numeric; but xs:decimal if both operands are xs:integer
    A ÷ Bxs:yearMonthDurationnumericop:divide-yearMonthDuration(A, B)xs:yearMonthDuration
    A ÷ Bxs:dayTimeDurationnumericop:divide-dayTimeDuration(A, B)xs:dayTimeDuration
    A ÷ Bxs:yearMonthDurationxs:yearMonthDurationop:divide-yearMonthDuration-by-yearMonthDuration (A, B)xs:decimal
    A ÷ Bxs:dayTimeDurationxs:dayTimeDurationop:divide-dayTimeDuration-by-dayTimeDuration (A, B)xs:decimal
    A mod Bnumericnumericop:numeric-mod(A, B)numeric
    A eq Bnumericnumericop:numeric-equal(A, B)xs:boolean
    A eq Bxs:booleanxs:booleanop:boolean-equal(A, B)xs:boolean
    A eq Bxs:stringxs:stringop:numeric-equal(fn:compare(A, B), 0)xs:boolean
    A eq Bxs:datexs:dateop:date-equal(A, B)xs:boolean
    A eq Bxs:timexs:timeop:time-equal(A, B)xs:boolean
    A eq Bxs:dateTimexs:dateTimeop:dateTime-equal(A, B)xs:boolean
    A eq Bxs:durationxs:durationop:duration-equal(A, B)xs:boolean
    A eq BGregorianGregorianop:gYear-equal(A, B) etc.xs:boolean
    A eq Bbinarybinaryop:binary-equal(A, B)xs:boolean
    A eq Bxs:QNamexs:QNameop:QName-equal(A, B)xs:boolean
    A eq Bxs:NOTATIONxs:NOTATIONop:NOTATION-equal(A, B)xs:boolean
    A lt Bnumericnumericop:numeric-less-than(A, B)xs:boolean
    A lt Bxs:booleanxs:booleanop:boolean-less-than(A, B)xs:boolean
    A lt Bxs:stringxs:stringop:numeric-less-than(fn:compare(A, B), 0)xs:boolean
    A lt Bxs:datexs:dateop:date-less-than(A, B)xs:boolean
    A lt Bxs:timexs:timeop:time-less-than(A, B)xs:boolean
    A lt Bxs:dateTimexs:dateTimeop:dateTime-less-than(A, B)xs:boolean
    A lt Bxs:yearMonthDurationxs:yearMonthDurationop:yearMonthDuration-less-than(A, B)xs:boolean
    A lt Bxs:dayTimeDurationxs:dayTimeDurationop:dayTimeDuration-less-than(A, B)xs:boolean
    A lt Bbinarybinaryop:binary-less-than(A, B)xs:boolean
    Unary Operators
    OperatorOperand typeFunctionResult type
    + Anumericop:numeric-unary-plus(A)numeric
    - Anumericop:numeric-unary-minus(A)numeric

    C Context Components

    The tables in this section describe how values are assigned to the various components of the static context and dynamic context.

    C.1 Static Context Components

    Changes in 4.0 

    1. 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.   [Issue 1343 ]

    The following table describes the components of the static context. The following aspects of each component are described:

    • Default initial value: This is the initial value of the component if it is not overridden or augmented by the implementation or by a query.

    • Can be overwritten or augmented by implementation: Indicates whether an XQuery implementation is allowed to replace the default initial value of the component by a different, implementation-defined value and/or to augment the default initial value by additional implementation-defined values.

    • Can be overwritten or augmented by prolog: Indicates whether there are prolog declarations that can replace and/or augment the initial value provided by default or by the implementation.

    • Can be overwritten or augmented by expressions: Indicates whether there are expressions that can replace and/or augment the value of the component for their subexpressions.

    • Consistency Rules: Indicates rules that must be observed in assigning values to the component. Additional consistency rules may be found in 2.3.6 Consistency Constraints.

    Static Context Components
    ComponentDefault initial valueCan be overwritten or augmented by implementation?Can be overwritten or augmented by prolog?Can be overwritten or augmented by expressions?Consistency rules
    Statically known namespacesfn, xml, xs, xsi, localoverwriteable and augmentable (except for xml)overwriteable and augmentable by 5.13 Namespace Declarationoverwriteable and augmentable by element constructorOnly one namespace can be assigned to a given prefix per lexical scope.
    Default element/type namespaceno namespaceoverwriteableoverwriteable by 5.14 Default Namespace Declarationoverwriteable by element constructorOnly one default namespace per lexical scope.
    In-scope variablesnoneaugmentableoverwriteable and augmentable by 5.16 Variable Declaration and 4.5.2.5 Inline Function Expressions, augmentable by 5.12 Module Importoverwriteable and augmentable by variable-binding expressionsOnly one definition per variable per lexical scope.
    Context value static typeitem()overwriteableoverwriteable by 5.17 Context Value Declarationoverwriteable by expressions that set the context valueNone.
    Ordering modeorderedoverwriteableoverwriteable by 5.7 Ordering Mode Declarationoverwriteable by expressionValue must be ordered or unordered.
    Default function namespacefnoverwriteable (not recommended)overwriteable by 5.14 Default Namespace DeclarationnoNone.
    In-scope schema typesbuilt-in types in xsaugmentableaugmentable by 5.11 Schema ImportnoOnly one definition per global or local type.
    In-scope element declarationsnoneaugmentableaugmentable by 5.11 Schema ImportnoOnly one definition per global or local element name.
    In-scope attribute declarationsnoneaugmentableaugmentable by 5.11 Schema ImportnoOnly one definition per global or local attribute name.
    Statically known function signaturesthe signatures of the system functionsaugmentableaugmentable by 5.12 Module Import and by 5.18 Function Declarations; augmentable by 5.11 Schema Import (which adds constructor functions for user-defined types)noEach function must have a unique expanded QName and number of arguments.
    Default collationUnicode codepoint collationoverwriteableoverwriteable by 5.4 Default Collation DeclarationnoNone.
    Construction modepreserveoverwriteableoverwriteable by 5.6 Construction DeclarationnoValue must be preserve or strip.
    Default order for empty sequencesimplementation-definedoverwriteableoverwriteable by 5.8 Empty Order DeclarationnoValue must be greatest or least.
    Boundary-space policystripoverwriteableoverwriteable by 5.3 Boundary-space DeclarationnoValue must be preserve or strip.
    Copy-namespaces modeinherit, preserveoverwriteableoverwriteable by 5.9 Copy-Namespaces DeclarationnoValue consists of inherit or no-inherit, and preserve or no-preserve.
    Static Base URISee rules in 5.5 Base URI Declarationoverwriteableoverwriteable by 5.5 Base URI DeclarationnoValue must be a valid lexical representation of the type xs:anyURI.
    Statically known decimal formatsthe default (unnamed) decimal format, which has an implementation-dependent valueaugmentableaugmentable, using decimal format declarationsnoeach QName uniquely identifies a decimal format
    Statically known collationsonly the default collationaugmentablenonoEach URI uniquely identifies a collation.
    XPath 1.0 Compatibility ModefalsenononoMust be false.

    C.2 Dynamic Context Components

    The following table describes the components of the dynamic context. The following aspects of each component are described:

    • Default initial value: This is the initial value of the component if it is not overridden or augmented by the implementation or by a query.

    • Can be overwritten or augmented by implementation: Indicates whether an XQuery implementation is allowed to replace the default initial value of the component by a different implementation-defined value and/or to augment the default initial value by additional implementation-defined values.

    • Can be overwritten or augmented by prolog: Indicates whether there are prolog declarations that can replace and/or augment the initial value provided by default or by the implementation.

    • Can be overwritten or augmented by expressions: Indicates whether there are expressions that can replace and/or augment the value of the component for their subexpressions.

    • Consistency Rules: Indicates rules that must be observed in assigning values to the component. Additional consistency rules may be found in 2.3.6 Consistency Constraints.

    Dynamic Context Components
    ComponentDefault initial valueCan be overwritten or augmented by implementation?Can be overwritten or augmented by prolog?Can be overwritten or augmented by expressions?Consistency rules
    Context valuenoneoverwriteableoverwriteable by a 5.17 Context Value Declaration in the main module overwritten during evaluation of path expressions and predicatesMust be the same in the dynamic context of every module in a query.
    Context positionnoneoverwriteableoverwriteable by a 5.17 Context Value Declaration in the main module overwritten during evaluation of path expressions and predicatesIf context value is defined, context position must be >0 and <= context size; else context position is absentDM31.
    Context sizenone overwriteableoverwriteable by a 5.17 Context Value Declaration in the main module overwritten during evaluation of path expressions and predicatesIf context value is defined, context size must be >0; else context size is absentDM31.
    Variable valuesnoneaugmentableoverwriteable and augmentable by 5.16 Variable Declaration and 4.5.2.5 Inline Function Expressions, augmentable by 5.12 Module Importoverwriteable and augmentable by variable-binding expressionsNames and values must be consistent with in-scope variables.
    Named functionsthe system functionsaugmentableaugmentable by 5.18 Function Declarations, 5.12 Module Import, and 5.11 Schema Import ( (which adds constructor functions for user-defined types)noMust be consistent with statically known function signatures
    Current dateTimenonemust be initialized by implementationnonoMust include a timezone. Remains constant during evaluation of a query.
    Implicit timezonenonemust be initialized by implementationnonoRemains constant during evaluation of a query.
    Available documentsnonemust be initialized by implementationnonoNone
    Available text resourcesnonemust be initialized by implementationnonoNone
    Available collectionsnonemust be initialized by implementationnonoNone
    Default collectionnoneoverwriteablenonoNone
    Available URI collectionsnonemust be initialized by implementationnonoNone
    Default URI collectionnoneoverwriteablenonoNone

    D Context Components

    The tables in this section describe the scope (range of applicability) of the various components in a module's static context and dynamic context.

    D.1 Static Context Components

    The following table describes the components of the static context. For each component, “global” indicates that the value of the component applies throughout an XPath expression, whereas “lexical” indicates that the value of the component applies only within the subexpression in which it is defined.

    Static Context Components
    ComponentScope
    XPath 1.0 Compatibility Modeglobal
    Statically known namespacesglobal
    Default element/type namespaceglobal
    Default function namespaceglobal
    In-scope schema typesglobal
    In-scope element declarationsglobal
    In-scope attribute declarationsglobal
    In-scope variableslexical; for-expressions, let-expressions, and quantified expressions can bind new variables
    Context value static typelexical
    Statically known function signaturesglobal
    Statically known collationsglobal
    Default collationglobal
    Base URIglobal
    Statically known documentsglobal
    Statically known collectionsglobal
    Statically known default collection typeglobal

    D.2 Dynamic Context Components

    The following table describes how values are assigned to the various components of the dynamic context. All these components are initialized by mechanisms defined by the host language. For each component, “global” indicates that the value of the component remains constant throughout evaluation of the XPath expression, whereas “dynamic” indicates that the value of the component can be modified by the evaluation of subexpressions.

    Dynamic Context Components
    ComponentScope
    Context valuedynamic; changes during evaluation of path expressions and predicates
    Context positiondynamic; changes during evaluation of path expressions and predicates
    Context sizedynamic; changes during evaluation of path expressions and predicates
    Variable valuesdynamic; for-expressions, let-expressions, and quantified expressions can bind new variables
    Current date and timeglobal; must be initialized by implementation
    Implicit timezoneglobal; must be initialized by implementation
    Available documentsglobal; must be initialized by implementation
    Available node collectionsglobal; must be initialized by implementation
    Default collectionglobal; overwriteable by implementation
    Available URI collectionsglobal; must be initialized by implementation
    Default URI collectionglobal; overwriteable by implementation

    E Implementation-Defined Items

    The following items in this specification are implementation-defined:

    1. The version of Unicode that is used to construct expressions.

    2. The statically-known collations.

    3. The implicit timezone.

    4. The circumstances in which warnings are raised, and the ways in which warnings are handled.

    5. The method by which errors are reported to the external processing environment.

    6. Which version of XML and XML Names (e.g. [XML 1.0] and [XML Names] or [XML 1.1] and [XML Names 1.1]) and which version of XML Schema (e.g. [XML Schema 1.0] or [XML Schema 1.1]) 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).

    7. How XDM instances are created from sources other than an Infoset or PSVI.

    8. Any components of the static context or dynamic context that are overwritten or augmented by the implementation.

    9. Whether the implementation supports the namespace axis.

    10. The default handling of empty sequences returned by an ordering key (orderspec) in an order by clause (empty least or empty greatest).

    11. The names and semantics of any extension expressions (pragmas) recognized by the implementation.

    12. The names and semantics of any option declarations recognized by the implementation.

    13. 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.

    14. The process by which the specific modules to be imported by a module import are identified, if the Module Feature is supported (includes processing of location hints, if any.)

    15. The means by which serialization is invoked, if the Serialization Feature is supported.

    16. The default values for the byte-order-mark, encoding, html-version, item-separator, media-type, normalization-form, omit-xml-declaration, standalone, and version parameters, if the Serialization Feature is supported.

    17. 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).

    18. Limits on ranges of values for various data types, as enumerated in 6.3 Data Model Conformance.

    19. Syntactic extensions to XQuery, including both their syntax and semantics, as discussed in 6.4 Syntax Extensions.

    20. Whether the type system is based on [XML Schema 1.0] or [XML Schema 1.1]. An implementation that has based its type system on XML Schema 1.0 is not required to support the use of the xs:dateTimeStamp constructor or the use of xs:dateTimeStamp or xs:error as TypeName in any expression.

    21. The signatures of functions provided by the implementation or via an implementation-defined API (see 2.2.1 Static Context).

    22. Any environment variables provided by the implementation.

    23. Any rules used for static typing (see 2.3.3.1 Static Analysis Phase).

    24. Any serialization parameters provided by the implementation (see 2.3.5 Serialization).

    25. The means by which the location hint for a serialization parameter document identifies the corresponding XDM instance (see 2.3.5 Serialization).

    26. What error, if any, is returned if an external function's implementation does not return the declared result type (see 2.3.6 Consistency Constraints).

    27. Any annotations defined by the implementation, and their associated behavior (see 5.15 Annotations).

    28. Any function assertions defined by the implementation.

    29. The effect of function assertions understood by the implementation on 3.3.3 The judgement subtype-assertions(AnnotationsA, AnnotationsB) .

    30. Any implementation-defined variables defined by the implementation. (see 4.2.2 Variable References).

    31. The ordering associated with fn:unordered in the implementation (see 4.15 Ordered and Unordered Expressions).

    32. Any additional information provided for try/catch via the err:additional variable (see 4.20 Try/Catch Expressions).

    33. The default boundary-space policy (see 5.3 Boundary-space Declaration).

    34. The default collation (see 5.4 Default Collation Declaration).

    35. The default base URI (see 5.5 Base URI Declaration).

    F References

    F.1 Normative References

    ISO/IEC 10646
    ISO (International Organization for Standardization). ISO/IEC 10646:2003. Information technology—Universal Multiple-Octet Coded Character Set (UCS), 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 http://www.iso.org for the latest version.)
    RFC2119
    S. Bradner. Key Words for use in RFCs to Indicate Requirement Levels. IETF RFC 2119. See http://www.ietf.org/rfc/rfc2119.txt.
    RFC3986
    T. Berners-Lee, R. Fielding, and L. Masinter. Uniform Resource Identifiers (URI): Generic Syntax. IETF RFC 3986. See http://www.ietf.org/rfc/rfc3986.txt.
    RFC3987
    M. Duerst and M. Suignard. Internationalized Resource Identifiers (IRIs). IETF RFC 3987. See http://www.ietf.org/rfc/rfc3987.txt.
    Unicode
    The Unicode Consortium. The Unicode Standard. Reading, Mass.: Addison-Wesley, 2003, as updated from time to time by the publication of new versions. See http://www.unicode.org/standard/versions/ 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 implementation-defined, but implementations are recommended to use the latest Unicode version.
    XML 1.0
    World Wide Web Consortium. Extensible Markup Language (XML) 1.0. W3C Recommendation. See http://www.w3.org/TR/REC-xml/. The edition of XML 1.0 must be no earlier than the Third Edition; the edition used is implementation-defined, but we recommend that implementations use the latest version.
    XML 1.1
    World Wide Web Consortium. Extensible Markup Language (XML) 1.1. W3C Recommendation. See http://www.w3.org/TR/xml11/
    XML Base
    World Wide Web Consortium. XML Base. W3C Recommendation. See http://www.w3.org/TR/xmlbase/
    XML ID
    World Wide Web Consortium. xml:id Version 1.0. W3C Recommendation. See http://www.w3.org/TR/xml-id/
    XML Names
    World Wide Web Consortium. Namespaces in XML. W3C Recommendation. See http://www.w3.org/TR/REC-xml-names/
    XML Names 1.1
    World Wide Web Consortium. Namespaces in XML 1.1. W3C Recommendation. See http://www.w3.org/TR/xml-names11/
    XML Schema 1.0
    World Wide Web Consortium. XML Schema, Parts 0, 1, and 2 (Second Edition). W3C Recommendation, 28 October 2004. See http://www.w3.org/TR/xmlschema-0/, http://www.w3.org/TR/xmlschema-1/, and http://www.w3.org/TR/xmlschema-2/.
    XML Schema 1.1
    World Wide Web Consortium. XML Schema, Parts 1, and 2. W3C Recommendation 5 April 2012. See http://www.w3.org/TR/xmlschema11-1/, and http://www.w3.org/TR/xmlschema11-2/.
    XPath 4.0
    XML Path Language (XPath) 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
    XQuery and XPath Data Model (XDM) 4.0
    XQuery and XPath Data Model (XDM) 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
    XQuery and XPath Functions and Operators 4.0
    XQuery and XPath Functions and Operators 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
    XSLT and XQuery Serialization 4.0
    XSLT and XQuery Serialization 4.0, XSLT Extensions Community Group, World Wide Web Consortium.

    F.2 Non-normative References

    Document Object Model
    World Wide Web Consortium. Document Object Model (DOM) Level 3 Core Specification. W3C Recommendation, April 7, 2004. See http://www.w3.org/TR/DOM-Level-3-Core/.
    ODMG
    Rick Cattell et al. The Object Database Standard: ODMG-93, Release 1.2. Morgan Kaufmann Publishers, San Francisco, 1996.
    Quilt
    Don Chamberlin, Jonathan Robie, and Daniela Florescu. Quilt: an XML Query Language for Heterogeneous Data Sources. In Lecture Notes in Computer Science, Springer-Verlag, Dec. 2000.
    SQL
    International Organization for Standardization (ISO). Information Technology — Database Language SQL. Standard No. ISO/IEC 9075:2011. (Available from American National Standards Institute, New York, NY 10036, (212) 642-4900.)
    Uniform Resource Locators (URL)
    Internet Engineering Task Force (IETF). Uniform Resource Locators (URL). Request For Comment No. 1738, Dec. 1994. See http://www.ietf.org/rfc/rfc1738.txt.
    XML 1.1 and Schema 1.0
    World Wide Web Consortium. Processing XML 1.1 Documents with XML Schema 1.0 Processors. W3C Working Group Note, 11 May 2005. See http://www.w3.org/TR/xml11schema10/.
    XML Infoset
    World Wide Web Consortium. XML Information Set (Second Edition). W3C Recommendation 4 February 2004. See http://www.w3.org/TR/xml-infoset/
    XML Path Language (XPath) Version 1.0
    XML Path Language (XPath) Version 1.0, 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 latest version is available at http://www.w3.org/TR/xpath.
    XML Path Language (XPath) Version 2.0
    XML Path Language (XPath) 2.0 (Second Edition), Don Chamberlin, Anders Berglund, Scott Boag, et. al., Editors. World Wide Web Consortium, 14 December 2010. This version is https://www.w3.org/TR/2010/REC-xpath20-20101214/. The latest version is available at https://www.w3.org/TR/xpath20/.
    XML Path Language (XPath) Version 3.0
    XML Path Language (XPath) 3.0, 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 latest version is available at https://www.w3.org/TR/xpath-30/.
    XML Path Language (XPath) Version 3.1
    XML Path Language (XPath) 3.1, 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 latest version is available at https://www.w3.org/TR/xpath-31/.
    XML Query Use Cases
    World Wide Web Consortium. XML Query Use Cases. W3C Working Draft, 8 June 2006. See http://www.w3.org/TR/xquery-use-cases/.
    XML-QL
    Alin Deutsch, Mary Fernandez, Daniela Florescu, Alon Levy, and Dan Suciu. A Query Language for XML.
    XPointer
    World Wide Web Consortium. XML Pointer Language (XPointer). W3C Last Call Working Draft 8 January 2001. See http://www.w3.org/TR/WD-xptr
    XQL
    J. Robie, J. Lapp, D. Schach. XML Query Language (XQL). See http://www.w3.org/TandS/QL/QL98/pp/xql.html.
    XQuery 1.0 and XPath 2.0 Formal Semantics
    XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition), Jérôme Siméon, Denise Draper, Peter Frankhauser, et. al., Editors. World Wide Web Consortium, 14 December 2010. This version is https://www.w3.org/TR/2010/REC-xquery-semantics-20101214/. The latest version is available at https://www.w3.org/TR/xquery-semantics/.
    XQuery 3.0 Requirements
    XQuery 3.0 Requirements, 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 latest version is available at https://www.w3.org/TR/xquery-30-requirements/.
    XQuery 3.0: An XML Query Language
    XQuery 3.0: An XML Query Language, 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 latest version is available at https://www.w3.org/TR/xquery-30/.
    XQuery 3.1 Requirements
    XQuery 3.1 Requirements and Use Cases, 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 latest version is available at https://www.w3.org/TR/xquery-31-requirements/.
    XQuery 3.1: An XML Query Language
    XQuery 3.1: An XML Query Language, 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-xquery-31-20170321/. The latest version is available at https://www.w3.org/TR/xquery-31/.
    XSL Transformations (XSLT) Version 4.0
    XSL Transformations (XSLT) Version 4.0, XSLT Extensions Community Group, World Wide Web Consortium.

    F.3 Background Material

    Character Model
    World Wide Web Consortium. Character Model for the World Wide Web. W3C Working Draft. See http://www.w3.org/TR/charmod/.
    Moustache
    mustache - Logic-less templates. See http://mustache.github.io/mustache.5.html.
    Use Case Sample Queries
    Queries from the XQuery 1.0 Use Cases, presented in a single file. See http://www.w3.org/2010/12/xquery-30-use-cases/xquery-30-use-case-queries.txt.
    XQuery Sample Queries
    Queries from this document, presented in a single file. See http://www.w3.org/2013/01/xquery-30-use-cases/xquery-30-example-queries.txt.
    XSL Transformations (XSLT) Version 1.0
    XSL Transformations (XSLT) Version 1.0, James Clark, Editor. World Wide Web Consortium, 16 Nov 1999. This version is http://www.w3.org/TR/1999/REC-xslt-19991116. The latest version is available at http://www.w3.org/TR/xslt.

    G Error Conditions

    err:XPST0001

    It is a static error if analysis of an expression relies on some component of the static context that is absentDM.

    err:XPDY0002

    It is a type error if evaluation of an expression relies on some part of the dynamic context that is absentDM.

    Note:

    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 fn($x) { @code }. The error code is prefixed XPDY rather than XPTY for backwards compatibility reasons.

    err:XPST0003

    It is a static error if an expression is not a valid instance of the grammar defined in A.1 EBNF.

    err:XPTY0004

    It is a type error if, during the static analysis phase, an expression is found to have a static type that is not appropriate for the context in which the expression occurs, or during the dynamic evaluation phase, the dynamic type of a value does not match a required type as specified by the matching rules in 3.1.2 Sequence Type Matching.

    err:XPTY0006

    During the analysis phase, an expression is classified as implausible if the inferred static typeS and the required type R 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.

    err:XPST0008

    It is a static error if an expression refers to an element name, attribute name, schema type name, namespace prefix, or variable name that is not defined in the static context, except for an ElementName in an ElementTest or an AttributeName in an AttributeTest.

    err:XQST0009

    An implementation that does not support the Schema Aware Feature must raise a static error if a Prolog contains a schema import.

    err:XPST0010

    An implementation that does not support the namespace axis must raise a static error if it encounters a reference to the namespace axis and XPath 1.0 compatibility mode is false.

    err:XQST0012

    It is a static error 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 [XML Schema 1.0] or [XML Schema 1.1].

    err:XQST0013

    It is a static error if an implementation recognizes a pragma but determines that its content is invalid.

    err:XQST0016

    An implementation that does not support the Module Feature raises a static error if it encounters a module declaration or a module import.

    err:XPST0017

    It is a static error if the expanded QName and number of arguments in a static function call do not match the name and arity range of a function definition in the static context, 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.

    err:XPTY0018

    It is a type error if the result of a path operator contains both nodes and non-nodes.

    err:XPTY0019

    It is a type error if E1 in a path expression E1/E2 does not evaluate to a sequence of nodes.

    err:XPTY0020

    It is a type error if, in an axis step, the context item is not a node.

    err:XPST0021

    It is a static error if two fields in a record declaration have the same name.

    err:XQST0022

    It is a static error if a namespace declaration attributecontains an EnclosedExpr.

    err:XPST0023

    It is a static error 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.

    err:XQTY0024

    It is a type error if the content sequence in an element constructor contains an attribute node following a node that is not an attribute node.

    err:XQDY0025

    It is a dynamic error 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.

    err:XQDY0026

    It is a dynamic error if the result of the content expression of a computed processing instruction constructor contains the string "?>".

    err:XQDY0027

    In a validate expression, it is a dynamic error if the root element information item in the PSVI resulting from validation does not have the expected validity property: valid if validation mode is strict, or either valid or notKnown if validation mode is lax.

    err:XQTY0030

    It is a type error if the argument of a validate expression does not evaluate to exactly one document or element node.

    err:XQST0031

    It is a static error if the version number specified in a version declaration is not supported by the implementation.

    err:XQST0032

    A static error is raised if a Prolog contains more than one base URI declaration.

    err:XQST0033

    It is a static error if a module contains multiple bindings for the same namespace prefix.

    err:XQST0034

    It is a static error if multiple functions declared or imported by a module have the same expanded QName and overlapping arity ranges (the arity range of a function declaration is M to M+N, where M is the number of required parameters and N is the number of optional parameters).

    err:XQST0035

    It is a static error to import two schema components that both define the same name in the same symbol space and in the same scope.

    err:XQST0038

    It is a static error if a Prolog contains more than one default collation declaration, or the value specified by a default collation declaration is not present in statically known collations.

    err:XQST0039

    It is a static error for a function declaration oran inline function expression to have more than one parameter with the same name.

    err:XQST0040

    It is a static error if the attributes specified by a direct element constructor do not have distinct expanded QNames.

    err:XQDY0041

    It is a dynamic error if the value of the name expression in a computed processing instruction constructor cannot be cast to the type xs:NCName.

    err:XQDY0044

    It is a dynamic error the node-name of a node constructed by a computed attribute constructor has any of the following properties:

    • Its namespace prefix is xmlns.

    • It has no namespace prefix and its local name is xmlns.

    • Its namespace URI is http://www.w3.org/2000/xmlns/.

    • Its namespace prefix is xml and its namespace URI is not http://www.w3.org/XML/1998/namespace.

    • Its namespace prefix is other than xml and its namespace URI is http://www.w3.org/XML/1998/namespace.

    err:XQST0045

    It is a static error if the name of a variable annotation, a function annotation, or the function name in a function declaration is in a reserved namespace.

    err:XQST0046

    An implementation MAYMAY raise a static error if the value of a URILiteral or a BracedURILiteral is of nonzero length and is neither an absolute URI nor a relative URI.

    err:XQST0047

    It is a static error if multiple module imports in the same Prolog specify the same target namespace.

    err:XQST0048

    It is a static error if a function, variable, or item type declared in a library module is not in the target namespace of the library module.

    err:XQST0049

    It is a static error if two or more variables declared or imported by a module have equal expanded QNames (as defined by the eq operator.)

    err:XPDY0050

    It is a dynamic error if the dynamic type of the operand of a treat expression does not match the sequence type designated by the treat expression. This error might also be raised by a path expression beginning with / or // if the context node is not in a tree that is rooted at a document node. This is because a leading / or // in a path expression is an abbreviation for an initial step that includes the clause treat as document-node().

    err:XPST0051

    It is a static error if an expanded QName used as an ItemType in a SequenceType is not defined in the static context either as a named item type in the in-scope named item types, or as a generalized atomic type in the in-scope schema type.

    err:XQST0052

    The type named in a cast or castable expression must be the name of a type defined in the in-scope schema types, and the type must be simple.

    err:XQDY0054

    It is a dynamic error if a cycle is encountered in the definition of a module’s dynamic context components, for example because of a cycle in variable declarations.

    err:XQST0055

    It is a static error if a Prolog contains more than one copy-namespaces declaration.

    err:XQST0057

    It is a static error if a schema import binds a namespace prefix but does not specify a target namespace other than a zero-length string.

    err:XQST0058

    It is a static error if multiple schema imports specify the same target namespace.

    err:XQST0059

    It is a static error if an implementation is unable to process a schema or module import by finding a schema or module with the specified target namespace.

    err:XQST0060

    It is a static error if the name of a function in a function declaration is not in a namespace (expanded QName has a null namespace URI).

    err:XQDY0061

    It is a dynamic error 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.

    err:XQDY0064

    It is a dynamic error if the value of the name expression in a computed processing instruction constructor is equal to XML (in any combination of upper and lower case).

    err:XQST0065

    A static error is raised if a Prolog contains more than one ordering mode declaration.

    err:XQST0066

    A static error is raised if a Prolog contains more than one default element/type namespace declaration, or more than one default function namespace declaration.

    err:XQST0067

    A static error is raised if a Prolog contains more than one construction declaration.

    err:XQST0068

    A static error is raised if a Prolog contains more than one boundary-space declaration.

    err:XQST0069

    A static error is raised if a Prolog contains more than one empty order declaration.

    err:XQST0070

    A static error is raised if one of the predefined prefixes xml or xmlns appears in a namespace declaration or a default namespace declaration, or if any of the following conditions is statically detected in any expression or declaration:

    A static error is raised if any of the following conditions is statically detected in any expression:

    • The prefix xml is bound to some namespace URI other than http://www.w3.org/XML/1998/namespace.

    • A prefix other than xml is bound to the namespace URI http://www.w3.org/XML/1998/namespace.

    • The prefix xmlns is bound to any namespace URI.

    • A prefix other than xmlns is bound to the namespace URI http://www.w3.org/2000/xmlns/.

    err:XQST0071

    A static error is raised if the namespace declaration attributes of a direct element constructor do not have distinct names.

    err:XQDY0072

    It is a dynamic error if the result of the content expression of a computed comment constructor contains two adjacent hyphens or ends with a hyphen.

    err:XQDY0074

    It is a dynamic error if the value of the name expression in a computed element or attribute constructor cannot be converted to an expanded QName (for example, because it contains a namespace prefix not found in statically known namespaces.)

    err:XQST0075

    An implementation that does not support the Schema Aware Feature must raise a static error if it encounters a validate expression.

    err:XQST0076

    It is a static error if a collation subclause in an order byor group by clause of a FLWOR expression does not identify a collation that is present in statically known collations.

    err:XQST0079

    It is a static error if an extension expression contains neither a pragma that is recognized by the implementation nor an expression enclosed in curly braces.

    err:XPST0080

    It is a static error if the target type of a cast or castable expression is xs:NOTATION, xs:anySimpleType, or xs:anyAtomicType.

    err:XPST0081

    It is a static error if a QName used in a queryan expression contains a namespace prefix that cannot be expanded into a namespace URI by using the statically known namespaces.

    err:XQDY0084

    It is a dynamic error if the element validated by a validate statement does not have a top-level element declaration in the in-scope element declarations, if validation mode is strict.

    err:XQST0085

    It is a static error if the namespace URI in a namespace declaration attribute is a zero-length string, and the implementation does not support [XML Names 1.1].

    err:XQTY0086

    It is a type error if the typed value of a copied element or attribute node is namespace-sensitive when construction mode is preserve and copy-namespaces mode is no-preserve.

    err:XQST0087

    It is a static error if the encoding specified in a Version Declaration does not conform to the definition of EncName specified in [XML 1.0].

    err:XQST0088

    It is a static error if the literal that specifies the target namespace in a module import or a module declaration is of zero length.

    err:XQST0089

    It is a static error if a variable bound in a for or window clause of a FLWOR expression, and its associated positional variable, do not have distinct names (expanded QNames).

    err:XQST0089

    It is a static error if a variable bound in a for expression, and its associated positional variable, do not have distinct names (expanded QNames).

    err:XQST0090

    It is a static error if a character reference does not identify a valid character in the version of XML that is in use.

    err:XQDY0091

    An implementation MAY raise a dynamic error if an xml:id error, as defined in [XML ID], is encountered during construction of an attribute named xml:id.

    err:XQDY0092

    An implementation MAY raise a dynamic error if a constructed attribute named xml:space has a value other than preserve or default.

    err:XQST0094

    The name of each grouping variable must be equal (by the eq operator on expanded QNames) to the name of a variable in the input tuple stream.

    err:XQDY0096

    It is a dynamic errorif the node-name of a node constructed by a computed element constructor has any of the following properties:

    • Its namespace prefix is xmlns.

    • Its namespace URI is http://www.w3.org/2000/xmlns/.

    • Its namespace prefix is xml and its namespace URI is not http://www.w3.org/XML/1998/namespace.

    • Its namespace prefix is other than xml and its namespace URI is http://www.w3.org/XML/1998/namespace.

    err:XQST0097

    It is a static error for a decimal-format to specify a value that is not valid for a given property, as described in statically known decimal formats

    err:XQST0098

    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. The following properties represent characters used in a picture string: decimal-separator, exponent-separator, grouping-separator, percent, per-mille, the family of ten decimal digits starting with zero-digit, digit, and pattern-separator.

    err:XQST0099

    No module may contain more than one ContextItemDecl.

    err:XQDY0101

    An error is raised if a computed namespace constructor attempts to do any of the following:

    • Bind the prefix xml to some namespace URI other than http://www.w3.org/XML/1998/namespace.

    • Bind a prefix other than xml to the namespace URI http://www.w3.org/XML/1998/namespace.

    • Bind the prefix xmlns to any namespace URI.

    • Bind a prefix to the namespace URI http://www.w3.org/2000/xmlns/.

    • Bind any prefix (including the empty prefix) to a zero-length namespace URI.

    err:XQDY0102

    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.

    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.

    err:XQST0103

    All variables in a window clause must have distinct names.

    err:XQST0104

    A TypeName that is specified in a validate expression must be found in the in-scope schema definitions

    err:XQTY0105

    It is a type error if the content sequence in an element constructor contains a function .

    err:XQST0106

    It is a static error if a function declaration contains both a %private and a %public annotation.

    err:XQST0108

    It is a static error if an output declaration occurs in a library module.

    err:XQST0109

    It is a static error if the local name of an output declaration in the http://www.w3.org/2010/xslt-xquery-serialization namespace is not one of the serialization parameter names listed in C.1 Static Context Components, or if the name of an output declaration is use-character-maps.

    err:XQST0110

    It is a static error if the same serialization parameter is used more than once in an output declaration.

    err:XQST0111

    It is a static error for a query prolog to contain two decimal formats with the same name, or to contain two default decimal formats.

    err:XQST0113

    Specifying a VarValue or VarDefaultValue for a context item declaration in a library module is a static error.

    err:XQST0114

    It is a static error for a decimal format declaration to define the same property more than once.

    err:XQST0115

    It is a static error if the document specified by the option Q{http://www.w3.org/2010/xslt-xquery-serialization}parameter-document raises a serialization error.

    err:XQST0116

    It is a static errorif a variable declaration contains both a %private and a %public annotation, more than one %private annotation, or more than one %public annotation.

    err:XPTY0117

    When applying the coercion rules, if an item is of type xs:untypedAtomic and the expected type is namespace-sensitive, a type error [err:XPTY0117] is raised.

    err:XQST0118

    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.

    err:XQST0119

    It is a static error if the implementation is not able to process the value of an output:parameter-document declaration to produce an XDM instance.

    err:XQST0125

    It is a static error if an inline function expression is annotated as %public or %private.

    err:XPDY0130

    An implementation-dependent limit has been exceeded.

    err:XQST0134

    The namespace axis is not supported.

    err:XQDY0137

    No two keys in a map may have the same key value.

    err:XQST0140

    It is a static error if a named item type declaration is recursive, unless it satisfies the conditions defined in 3.2.8.3.1 Recursive Record Types.

    err:XPTY0141

    In a forexpressionclause, when the keyword member is present, the value of the binding collection must be a single array; and when either or both of the keywords key and value are present, the value of the binding collection must be a single map.

    err:XPTY0144

    During the analysis phase, an axis step is classified as implausible 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.

    err:XPTY0145

    During the analysis phase, a unary or postfix lookup expression is classified as implausible 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.

    err:XQST0146

    It is a static error if two or more item types declared or imported by a module have equal expanded QNames (as defined by the eq operator.)

    err:XQST0148

    It is a static error if an optional parameter in a function declaration is followed by a parameter that does not have a default value.

    err:XQST0149

    It is a static error if the schemas imported by different modules of a query are not compatible as defined in Section 2.8.1 Schema ConsistencyDM.

    err:XQST0151

    It is a static error if a node name supplied as a string literal in a computed element or attribute constructor does not take the form of an EQName.

    err:XPST0152

    It is a static error if a key type named in a TypedMapType is not a generalized atomic type.

    H The application/xquery Media Type

    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.)

    H.1 Introduction

    This document, found at http://www.w3.org/TR/xquery/, together with its normative references, defines the language XQuery Version 1.0. This Appendix provides information about the application/xquery media type, which is intended to be used for transmitting queries written in the XQuery language.

    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 http://lists.w3.org/Archives/Public/public-qt-comments.

    H.2 Registration of MIME Media Type application/xquery

    MIME media type name: application

    MIME subtype name: xquery

    Required parameters: none

    Optional parameters: none

    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 &#xddd; syntax.

    H.2.2 Applications Using this Media Type

    The public XQuery Web page lists more than two dozen implementations of the XQuery language, both proprietary and open source.

    This media type is registered to allow for deployment of XQuery on the World Wide Web.

    H.2.3 File Extensions

    The most common file extensions in use for XQuery are .xq and .xquery.

    The appropriate Macintosh file type code is TEXT.

    H.2.4 Intended Usage

    The intended usage of this media type is for interchange of XQuery expressions.

    H.2.5 Author/Change Controller

    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.

    H.3 Encoding Considerations

    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.

    An XQuery document may contain an encoding declaration as part of its version declaration:

    xquery version "3.1" encoding "utf-8";

    H.4 Recognizing XQuery Files

    An XQuery file may have the string xquery version "V.V" near the beginning of the document, where "V.V" is a version number. Currently the version number, if present, must be "1.0", "3.0", or "3.1".

    H.5 Charset Default Rules

    XQuery documents use the Unicode character set and, by default, the UTF-8 encoding.

    H.6 Security Considerations

    Queries written in XQuery may cause arbitrary URIs or IRIs to be dereferenced. Therefore, the security issues of [RFC3987] Section 8 should be considered. In addition, the contents of resources identified by file: URIs can in some cases be accessed, processed and returned as results. XQuery expressions can invoke any of the functions defined in [XQuery and XPath Functions and Operators 4.0]. For example, the fn:doc() and fn:doc-available() functions allow local filesystem probes as well as access to any URI-defined resource accessible from the system evaluating the XQuery expression. The fn:transform() 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 fn:transform() function should be sandboxed or disabled if untrusted queries are run.

    XQuery is a full declarative programming language, and supports user-defined functions, external function libraries (modules) referenced by URI, and system-specific “native” functions.

    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.

    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.

    Furthermore, because the XQuery language permits extensions, it is possible that application/xquery may describe content that has security implications beyond those described here.

    I Glossary (Non-Normative)

    anonymous function

    An anonymous function is a function item with no name. Anonymous functions may be created, for example, by evaluating an inline function expression or by partial function application.

    application function

    Application functions are function definitions written in a host language such as XQuery or XSLT whose syntax and semantics are defined in this family of specifications. Their behavior (including the rules determining the static and dynamic context) follows the rules for such functions in the relevant host language specification.

    argument expression

    An argument to a function call is either an argument expression or an ArgumentPlaceholder (?); in both cases it may either be supplied positionally, or identified by a name (called a keyword).

    arity range

    A function definition has an arity range, which is a range of consecutive non-negative integers. If the function definition has M required parameters and N optional parameters, then its arity range is from M to M+N inclusive.

    array

    An array is a function item that associates a set of positions, represented as positive integer keys, with values.

    associated value

    The value associated with a given key is called the associated value of the key.

    atomic item

    An atomic item is a value in the value space of an atomic type, as defined in [XML Schema 1.0] or [XML Schema 1.1].

    atomic type

    An atomic type is a simple schema type whose {variety}XS11-1 is atomic.

    atomization

    Atomization of a sequence is defined as the result of invoking the fn:data function, as defined in Section 2.1.4 fn:dataFO.

    available documents

    Available documents. This is a mapping of strings to document nodes. Each string represents the absolute URI of a resource. The document node is the root of a tree that represents that resource using the data model. The document node is returned by the fn:doc function when applied to that URI.

    available item collections

    Available collections. This is a mapping of strings to sequences of items. Each string represents the absolute URI of a resource. The sequence of items represents the result of the fn:collection function when that URI is supplied as the argument.

    available text resources

    Available text resources. This is a mapping of strings to text resources. Each string represents the absolute URI of a resource. The resource is returned by the fn:unparsed-text function when applied to that URI.

    available uri collections

    Available URI collections. This is a mapping of strings to sequences of URIs. The string represents the absolute URI of a resource which can be interpreted as an aggregation of a number of individual resources each of which has its own URI. The sequence of URIs represents the result of the fn:uri-collection function when that URI is supplied as the argument.

    axis step

    An axis step returns a sequence of nodes that are reachable from a starting node via a specified axis. Such a step has two parts: an axis, which defines the "direction of movement" for the step, and a node test, which selects nodes based on their kind, name, and/or type annotation .

    base URI declaration

    A base URI declaration specifies the Static Base URI property. The Static Base URI property is used when resolving relative URI references.

    binary

    In the operator mapping tables, the term binary refers to the types xs:hexBinary and xs:base64Binary.

    binding collection

    In a for clause, when an expression is preceded by the keyword in, the value of that expression is called a binding collection.

    binding collection

    The result of evaluating the binding expression in a for expression is called the binding collection

    binding sequence

    In a window clause, when an expression is preceded by the keyword in, the value of that expression is called a binding sequence.

    boundary-space declaration

    A boundary-space declaration sets the boundary-space policy in the static context, overriding any implementation-defined default. Boundary-space policy controls whether boundary whitespace is preserved by element constructors during processing of the query.

    boundary-space policy

    Boundary-space policy. This component controls the processing of boundary whitespace by direct element constructors, as described in 4.12.1.4 Boundary Whitespace.

    boundary whitespace

    Boundary whitespace is a sequence of consecutive whitespace characters within the content of a direct element constructor, that is delimited at each end either by the start or end of the content, or by a DirectConstructor, or by an EnclosedExpr. For this purpose, characters generated by character references such as &#x20; or by CDataSections are not considered to be whitespace characters.

    character reference

    A character reference is an XML-style reference to a [Unicode] character, identified by its decimal or hexadecimal codepoint.

    choice item type

    A choice item type defines an item type that is the union of a number of alternatives. For example the type (xs:hexBinary | xs:base64Binary) defines the union of these two primitive atomic types, while the type (map(*) | array(*)) matches any item that is either a map or an array.

    coercion rules

    The coercion rules are rules used to convert a supplied value to a required type, for example when converting an argument of a function call to the declared type of the function parameter.

    collation

    A collation is a specification of the manner in which strings and URIs are compared and, by extension, ordered. For a more complete definition of collation, see Section 5.3 Comparison of stringsFO.

    comma operator

    One way to construct a sequence is by using the comma operator, which evaluates each of its operands and concatenates the resulting sequences, in order, into a single result sequence.

    complex terminal

    A complex terminal is a variable terminal whose production rule references, directly or indirectly, an ordinary production rule.

    computed element constructor

    A computed element constructor creates an element node, allowing both the name and the content of the node to be computed.

    construction declaration

    A construction declaration sets the construction mode in the static context, overriding any implementation-defined default.

    construction mode

    Construction mode. The construction mode governs the behavior of element and document node constructors. If construction mode is preserve, the type of a constructed element node is xs:anyType, and all attribute and element nodes copied during node construction retain their original types. If construction mode is strip, the type of a constructed element node is xs:untyped; all element nodes copied during node construction receive the type xs:untyped, and all attribute nodes copied during node construction receive the type xs:untypedAtomic.

    constructor function

    The constructor function for a given simple type is used to convert instances of other simple types into the given type. The semantics of the constructor function call T($arg) are defined to be equivalent to the expression $arg cast as T?.

    content expression

    In an enclosed expression, the optional expression enclosed in curly brackets is called the content expression.

    context dependent

    A function definition is said to be context dependent if its result depends on the static or dynamic context of its caller. A function definition may be context-dependent for some arities in its arity range, and context-independent for others: for example fn:name#0 is context-dependent while fn:name#1 is context-independent.

    context node

    When the context value is a single item, it can also be referred to as the context item; when it is a single node, it can also be referred to as the context node.

    context position

    The context position is the position of the context value within the series of values currently being processed.

    context size

    The context size is the number of values in the series of values currently being processed.

    context value

    The context value is the value currently being processed.

    copy-namespaces declaration

    A copy-namespaces declaration sets the value of copy-namespaces mode in the static context, overriding any implementation-defined default. Copy-namespaces mode controls the namespace bindings that are assigned when an existing element node is copied by an element constructor or document constructor.

    copy-namespaces mode

    Copy-namespaces mode. This component controls the namespace bindings that are assigned when an existing element node is copied by an element constructor, as described in 4.12.1 Direct Element Constructors. Its value consists of two parts: preserve or no-preserve, and inherit or no-inherit.

    current dateTime

    Current dateTime. This information represents an implementation-dependent point in time during the processing of a queryan expression, and includes an explicit timezone. It can be retrieved by the fn:current-dateTime function. If called multiple times during the execution of a queryan expression, this function always returns the same result.

    data model

    XQuery 4.0 and XPath 4.0 operates on the abstract, logical structure of an XML document or JSON object rather than its surface syntax. This logical structure, known as the data model, is defined in [XQuery and XPath Data Model (XDM) 4.0].

    decimal-format declaration

    A decimal format declaration adds a decimal format to the statically known decimal formats, which define the properties used to format numbers using the fn:format-number() function

    decimal-separator

    decimal-separator(M, R) is used to separate the integer part of the number from the fractional part. The default value for both the marker and the rendition is U+002E (FULL STOP, PERIOD, .) .

    default calendar

    Default calendar. This is the calendar used when formatting dates in human-readable output (for example, by the functions fn:format-date and fn:format-dateTime) if no other calendar is requested. The value is a string.

    default collation

    Default collation. This identifies one of the collations in statically known collations as the collation to be used by functions and operators for comparing and ordering values of type xs:string and xs:anyURI (and types derived from them) when no explicit collation is specified.

    default collation declaration

    A default collation declaration sets the value of the default collation in the static context, overriding any implementation-defined default.

    default collection

    Default collection. This is the sequence of items that would result from calling the fn:collection function with no arguments.

    default function namespace

    Default function namespace. This is either a namespace URI, or absentDM. The namespace URI, if present, is used for any unprefixed QName appearing in a position where a function name is expected.

    default language

    Default language. This is the natural language used when creating human-readable output (for example, by the functions fn:format-date and fn:format-integer) if no other language is requested. The value is a language code as defined by the type xs:language.

    default namespace for elements and types

    Default namespace for elements and types. This is either a namespace URI, or the special value "##any", or absentDM. This indicates how unprefixed QNames are interpreted when they appear in a position where an element name or type name is expected.

    default order for empty sequences

    Default order for empty sequences. This component controls the processing of empty sequences and NaN values as ordering keys in an order by clause in a FLWOR expression, as described in 4.13.9 Order By Clause.

    default place

    Default place. This is a geographical location used to identify the place where events happened (or will happen) when processing dates and times using functions such as fn:format-date, fn:format-dateTime, and fn:civil-timezone, if no other place is specified. It is used when translating timezone offsets to civil timezone names, and when using calendars where the translation from ISO dates/times to a local representation is dependent on geographical location. Possible representations of this information are an ISO country code or an Olson timezone name, but implementations are free to use other representations from which the above information can be derived. The only requirement is that it should uniquely identify a civil timezone, which means that country codes for countries with multiple timezones, such as the United States, are inadequate.

    default URI collection

    Default URI collection. This is the sequence of URIs that would result from calling the fn:uri-collection function with no arguments.

    delimiting terminal symbol

    The delimiting terminal symbols are: !!=#$%()**:,-...::*:::=;<<<===!>=>=?>>>=>>????[@[]```{{{|||}}}×÷AposStringLiteralBracedURILiteral]]><![CDATA[--><!--/></<+#)(#?><?QuotStringLiteralS///]````[}``{StringLiteral

    depends on

    A variable value (or the context value) depends on another variable value (or the context value) if, during the evaluation of the initializing expression of the former, the latter is accessed through the module context.

    derives from

    A schema typeS1 is said to derive fromschema typeS2 if any of the following conditions is true:

    digit

    digit(M) is a character used in the picture string to represent an optional digit; the default value is U+0023 (NUMBER SIGN, #) .

    direct element constructor

    A direct element constructor is a form of element constructor in which the name of the constructed element is a constant.

    document order

    Informally, document order is the order in which nodes appear in the XML serialization of a document.

    dynamically known function definitions

    Dynamically known function definitions. This is a set of function definitions. It includes the statically known function definitions as a subset, but may include other function definitions that are not known statically.

    dynamic context

    The dynamic context of an expression is defined as information that is needed for the dynamic evaluation of an expression, beyond any information that is needed from the static context.

    dynamic error

    A dynamic error is an error that must be detected during the dynamic evaluation phase and may be detected during the static analysis phase.

    dynamic evaluation phase

    The dynamic evaluation phase is the phase during which the value of an expression is computed.

    dynamic function call

    A dynamic function call consists of a base expression that returns the function and a parenthesized list of zero or more arguments (argument expressions or ArgumentPlaceholders).

    dynamic function call

    A dynamic function call is an expression that is evaluated by calling a function item, which is typically obtained dynamically.

    dynamic type

    Every value matches one or more sequence types. A value is said to have a dynamic typeT if it matches (or is an instance of) the sequence type T.

    effective boolean value

    The effective boolean value of a value is defined as the result of applying the fn:boolean function to the value, as defined in Section 7.3.1 fn:booleanFO.

    effective case

    The effective case of a switch expression is the first case clause that matches, using the rules given above, or the default clause if no such case clause exists.

    effective case

    The effective case in a typeswitch expression is the first case clause in which the value of the operand expression matches a SequenceType in the SequenceTypeUnion of the case clause, using the rules of SequenceType matching.

    empty order declaration

    An empty order declaration sets the default order for empty sequences in the static context, overriding any implementation-defined default. This declaration controls the processing of empty sequences and NaN values as ordering keys in an order by clause in a FLWOR expression.

    empty sequence

    A sequence containing zero items is called an empty sequence.

    enclosed expression

    An enclosed expression is an instance of the EnclosedExpr production, which allows an optional expression within curly brackets.

    encoding declaration

    If present, a version declaration may optionally include an encoding declaration. The value of the string literal following the keyword encoding is an encoding name, and must conform to the definition of EncName specified in [XML 1.0] [err:XQST0087]. The purpose of an encoding declaration is to allow the writer of a query to provide a string that indicates how the query is encoded, such as "UTF-8", "UTF-16", or "US-ASCII".

    entry

    Each key / value pair in a map is called an entry.

    enumeration type

    An EnumerationType accepts a fixed set of string values.

    environment variables

    Environment variables. This is a mapping from names to values. Both the names and the values are strings. The names are compared using an implementation-defined collation, and are unique under this collation. The set of environment variables is implementation-defined and may be empty.

    equivalent grouping keys

    Two tuples T1 and T2 have equivalent grouping keys if and only if, for each grouping variable GV, the atomized value of GV in T1 is deep-equal to the atomized value of GV in T2, as defined by applying the function fn:deep-equal using the appropriate collation.

    error value

    In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called error values.

    Executable Base URI

    Executable Base URI. This is an absolute URI used to resolve relative URIs during the evaluation of expressions; it is used, for example, to resolve a relative URI supplied to the fn:doc or fn:unparsed-text functions.

    expanded QName

    An expanded QName is a triple: its components are a prefix, a local name, and a namespace URI. In the case of a name in no namespace, the namespace URI and prefix are both absent. In the case of a name in the default namespace, the prefix is absent.

    exponent-separator

    exponent-separator(M, R) is used to separate the mantissa from the exponent in scientific notation. The default value for both the marker and the rendition is U+0065 (LATIN SMALL LETTER E, e) .

    expression context

    The expression context for a given expression consists of all the information that can affect the result of the expression.

    extension expression

    An extension expression is an expression whose semantics are implementation-defined.

    external function

    External functions can be characterized as functions that are neither part of the processor implementation, nor written in a language whose semantics are under the control of this family of specifications. The semantics of external functions, including any context dependencies, are entirely implementation-defined. In XSLT, external functions are called Section 24.1 Extension Functions XT30.

    filter expression

    A filter expression is an expression in the form E1[E2]: its effect is to return those items from the value of E1 that satisfy the predicate in E2.

    fixed focus

    A fixed focus is a focus for an expression that is evaluated once, rather than being applied to a series of values; in a fixed focus, the context value is set to one specific value, the context position is 1, and the context size is 1.

    focus

    The first three components of the dynamic context (context value, context position, and context size) are called the focus of the expression.

    focus function

    A focus function is an inline function expression in which the function signature is implicit: the function takes a single argument of type item()* (that is, any value), and binds this to the context value when evaluating the function body, which returns a result of type item()*.

    function assertion

    A function assertion is a predicate that restricts the set of functions matched by a FunctionType. It uses the same syntax as 5.15 Annotations.

    function coercion

    Function coercion wraps a function item in a new function whose signature is the same as the expected type. This effectively delays the checking of the argument and return types until the function is called.

    function definition

    A function definition contains information used to evaluate a static function call, including the name, parameters, and return type of the function.

    function item

    A function item is an item that can be called using a dynamic function call.

    generalized atomic type

    A generalized atomic type is an item type whose instances are all atomic items. Generalized atomic types include (a) atomic types, either built-in (for example xs:integer) or imported from a schema, (b) pure union types, either built-in (xs:numeric and xs:error) or imported from a schema, (c) choice item types if their alternatives are all generalized atomic types, and (d) enumeration types.

    Gregorian

    In the operator mapping tables, the term Gregorian refers to the types xs:gYearMonth, xs:gYear, xs:gMonthDay, xs:gDay, and xs:gMonth.

    grouping key

    The atomized value of a grouping variable is called a grouping key.

    grouping-separator

    grouping-separator(M, R) is used to separate groups of digits (for example as a thousands separator). The default value for both the marker and the rendition is U+002C (COMMA, ,) .

    grouping variable

    Each grouping specification specifies one grouping variable, which refers to variable bindings in the pre-grouping tuples. The values of the grouping variables are used to assign pre-grouping tuples to groups.

    guarded

    An expression E is said to be guarded by some governing condition C if evaluation of E is not allowed to fail with a dynamic error except when C applies.

    host language

    A host language for XPath is any environment that provides capabilities for XPath expressions to be defined and evaluated, and that supplies a static and dynamic context for their evaluation.

    ignorable whitespace

    Ignorable whitespace consists of any whitespace characters that may occur between terminals, unless these characters occur in the context of a production marked with a ws:explicit annotation, in which case they can occur only where explicitly specified (see A.3.5.2 Explicit Whitespace Handling).

    implausible

    Certain expressions, while not erroneous, are classified as being implausible, because they achieve no useful effect.

    implementation defined

    Implementation-defined indicates an aspect that may differ between implementations, but must be specified by the implementer for each particular implementation.

    implementation dependent

    Implementation-dependent indicates an aspect that may differ between implementations, is not specified by this or any W3C specification, and is not required to be specified by the implementer for any particular implementation.

    implicit timezone

    Implicit timezone. This is the timezone to be used when a date, time, or dateTime value that does not have a timezone is used in a comparison or arithmetic operation. The implicit timezone is an implementation-defined value of type xs:dayTimeDuration. See Section 3.2.7.3 Timezones XS1-2 or Section 3.3.7 dateTime XS11-2 for the range of valid values of a timezone.

    infinity

    infinity(R) is the string used to represent the double value infinity (INF); the default value is the string "Infinity"

    initial context value

    In the dynamic context of every module in a query, the context value component must have the same setting. If this shared setting is not absentDM, it is referred to as the initial context value.

    initializing expression

    If a variable declaration includes an expression (VarValue or VarDefaultValue), the expression is called an initializing expression. The static context for an initializing expression includes all functions, variables, and namespaces that are declared or imported anywhere in the Prolog.

    inline function expression

    An inline function expression, when evaluated, creates an anonymous function defined directly in the inline function expression.

    in-scope attribute declarations

    In-scope attribute declarations. Each attribute declaration is identified either by an expanded QName (for a top-level attribute declaration) or by an implementation-dependent attribute identifier (for a local attribute declaration). If the Schema Aware Feature is supported, in-scope attribute declarations include all attribute declarations found in imported schemas.

    in-scope element declarations

    In-scope element declarations. Each element declaration is identified either by an expanded QName (for a top-level element declaration) or by an implementation-dependent element identifier (for a local element declaration). If the Schema Aware Feature is supported, in-scope element declarations include all element declarations found in imported schemas.

    in-scope named item types

    In-scope named item types. This is a mapping from expanded QName to named item types.

    in-scope namespaces

    The in-scope namespaces property of an element node is a set of namespace bindings, each of which associates a namespace prefix with a URI.

    in-scope schema definitions

    In-scope schema definitions is a generic term for all the element declarations, attribute declarations, and schema type definitions that are in scope during static analysis of an expression.

    in-scope schema type

    In-scope schema types. Each schema type definition is identified either by an expanded QName (for a named type) or by an implementation-dependent type identifier (for an anonymous type). The in-scope schema types include the predefined schema types described in 3.5 Schema Types. If the Schema Aware Feature is supported, in-scope schema types also include all type definitions found in imported schemas.

    in-scope variables

    In-scope variables. This is a mapping from expanded QName to type. It defines the set of variables that are available for reference within an expression. The expanded QName is the name of the variable, and the type is the static type of the variable.

    item

    An item is either an atomic item, a node, or a function item.

    item type

    An item type is a type that can be expressed using the ItemType syntax, which forms part of the SequenceType syntax. Item types match individual items.

    item type designator

    An item type designator is a syntactic construct conforming to the grammar rule ItemType. An item type designator is said to designate an item type.

    kind test

    An alternative form of a node test called a kind test can select nodes based on their kind, name, and type annotation.

    lexical QName

    A lexical QName is a name that conforms to the syntax of the QName production

    library module

    A module that does not contain a Query Body is called a library module. A library module consists of a module declaration followed by a Prolog.

    literal

    A literal is a direct syntactic representation of an atomic item.

    literal terminal

    A literal terminal is a token appearing as a string in quotation marks on the right-hand side of an ordinary production rule.

    main module

    A main module consists of a Prolog followed by a Query Body.

    map

    A map is a function that associates a set of keys with values, resulting in a collection of key / value pairs.

    mapping arrow operator

    The mapping arrow operator=!> applies a function to each item in a sequence.

    may

    MAY means that an item is truly optional.

    member

    The values of an array are called its members.

    minus-sign

    minus-sign(R) is the string used to mark negative numbers; the default value is U+002D (HYPHEN-MINUS, -) .

    module

    A module is a fragment of XQuery code that conforms to the Module grammar and can independently undergo the static analysis phase described in 2.3.3 Expression Processing. Each module is either a main module or a library module.

    module declaration

    A module declaration serves to identify a module as a library module. A module declaration begins with the keyword module and contains a namespace prefix and a URILiteral.

    module feature

    The Module Feature allows a query Prolog to contain a Module Import and allows library modules to be created.

    module import

    A module import imports the public variable declarations, public function declarations, and public item type declarations from one or more library modules into the statically known function definitions, in-scope variables, or in-scope named item types of the importing module.

    must

    MUST means that the item is an absolute requirement of the specification.

    must not

    MUST NOT means that the item is an absolute prohibition of the specification.

    named function reference

    A named function reference is an expression (written name#arity) which evaluates to a function item, the details of the function item being based on the properties of a function definition in the static context.

    named item type

    A named item type is an ItemType identified by an expanded QName.

    name expression

    When an expression is used to specify the name of a constructed node, that expression is called the name expression of the constructor.

    namespace declaration

    A namespace declaration declares a namespace prefix and associates it with a namespace URI, adding the (prefix, URI) pair to the set of statically known namespaces.

    namespace declaration attribute

    A namespace declaration attribute is used inside a direct element constructor. Its purpose is to bind a namespace prefix (including the zero-length prefix) for the constructed element node, including its attributes.

    namespace-sensitive

    The namespace-sensitive types are xs:QName, xs:NOTATION, types derived by restriction from xs:QName or xs:NOTATION, list types that have a namespace-sensitive item type, and union types with a namespace-sensitive type in their transitive membership.

    name test

    A node test that consists only of an EQName or a Wildcard is called a name test.

    NaN

    NaN(R) is the string used to represent the double value NaN (not a number); the default value is the string "NaN"

    node

    A node is an instance of one of the node kinds defined in Section 5 NodesDM.

    node test

    A node test is a condition on the name, kind (element, attribute, text, document, comment, or processing instruction), and/or type annotation of a node. A node test determines which nodes contained by an axis are selected by a step.

    non-delimiting terminal symbol

    The non-delimiting terminal symbols are: allowingancestorancestor-or-selfandarrayasatattributebase-uriboundary-spacebycasecastcastablecatchchildcollationcommentconstructioncontextcopy-namespacescountdecimal-formatdecimal-separatordeclaredefaultdescendantdescendant-or-selfdigitdivdocumentdocument-nodeelementelseemptyempty-sequenceencodingendenumeqeveryexceptexponent-separatorfalsefixedfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selfforfunctiongegroupgrouping-separatorgtidivifimportininfinityinheritinstanceintersectisitemitemskeykeyslaxleletltmapmemberminus-signmodmodulenamespacenamespace-nodeNaNnenextno-inheritno-preservenodeofonlyoptionororderorderedorderingotherwisepairsparentpattern-separatorper-millepercentprecedingpreceding-or-selfpreceding-sibling-or-selfpreservepreviousprocessing-instructionrecordreturnsatisfiesschemaschema-attributeschema-elementselfslidingsomestablestartstrictstripswitchtextthentotreattruetrytumblingtypetypeswitchunionunorderedvalidatevaluevaluesvariableversionwhenwherewhilewindowxqueryzero-digitascendingBinaryIntegerLiteralDecimalLiteraldescendingDoubleLiteralexternalgreatestHexIntegerLiteralIntegerLiteralleastNCNameQNameURIQualifiedName

    numeric

    When referring to a type, the term numeric denotes the types xs:integer, xs:decimal, xs:float, and xs:double which are all member types of the built-in union type xs:numeric.

    numeric predicate

    A predicate whose predicate expression returns a value of type xs:numeric+ is called a numeric predicate.

    operator function

    For each operator and valid combination of operand types, the operator mapping tables specify a result type and an expression that invokes an operator function; the operator function implements the semantics of the operator for the given types.

    option declaration

    An option declaration declares an option that affects the behavior of a particular implementation. Each option consists of an identifying EQName and a StringLiteral.

    ordinary production rule

    An ordinary production rule is a production rule in A.1 EBNF that is not annotated ws:explicit.

    output declaration

    An output declaration is an option declaration in the namespace http://www.w3.org/2010/xslt-xquery-serialization; it is used to declare serialization parameters.

    partial function application

    A static or dynamic function call is a partial function application if one or more arguments is an ArgumentPlaceholder.

    partially applied function

    A partially applied function is a function created by partial function application.

    path expression

    A path expression consists of a series of one or more steps, separated by / or //, and optionally beginning with / or //. A path expression is typically used to locate nodes within trees.

    pattern-separator

    pattern-separator(M) is a character used to separate positive and negative sub-pictures in a picture string; the default value is U+003B (SEMICOLON, ;) .

    percent

    percent(M, R) is used to indicate that the number is written as a per-hundred fraction; the default value for both the marker and the rendition is U+0025 (PERCENT SIGN, %) .

    per-mille

    per-mille(M, R) is used to indicate that the number is written as a per-thousand fraction; the default value for both the marker and the rendition is U+2030 (PER MILLE SIGN, ) .

    positional variable

    A positional variable is a variable that is preceded by the keyword at.

    pragma

    A pragma is denoted by the delimiters (# and #), and consists of an identifying EQName followed by implementation-defined content.

    predefined entity reference

    A predefined entity reference is a short sequence of characters, beginning with an ampersand, that represents a single character that might otherwise have syntactic significance.

    predicate truth value

    The predicate truth value of a value $V is the result of the expression if ($V instance of xs:numeric+) then ($V = position()) else fn:boolean($V).

    primary expression

    Primary expressions are the basic primitives of the language. They include literals, variable references, context value references, constructors, and function calls. A primary expression may also be created by enclosing any expression in parentheses, which is sometimes helpful in controlling the precedence of operators.

    principal node kind

    Every axis has a principal node kind. If an axis can contain elements, then the principal node kind is element; otherwise, it is the kind of nodes that the axis can contain.

    private function

    A private function is a function with a %private annotation. A private function is hidden from module import, which can not import it into the statically known function definitions of another module.

    private item type

    A private item type is a named item type with a %private annotation. A private item type is hidden from module import, which can not import it into the in-scope named item types of another module.

    private variable

    A private variable is a variable with a %private annotation. A private variable is hidden from module import, which can not import it into the in-scope variables of another module.

    Prolog

    A Prolog is a series of declarations and imports that define the processing environment for the module that contains the Prolog.

    public function

    A public function is a function without a %private annotation. A public function is accessible to module import, which can import it into the statically known function definitions of another module.

    public item type

    A public item type is an item type declaration without a %private annotation. A public item type is accessible to module import, which can import it into the in-scope named item types of another module.

    public variable

    A public variable is a variable without a %private annotation. A public variable is accessible to module import, which can import it into the in-scope variables of another module. Using %public and %private annotations in a main module is not an error, but it does not affect module imports, since a main module cannot be imported. It is a static error [err:XQST0116] if a variable declaration contains both a %private and a %public annotation, more than one %private annotation, or more than one %public annotation.

    pure union type

    A pure union type is a simple type that satisfies the following constraints: (a) {variety}XS11-1 is union, (b) the {facets}XS11-1 property is empty, (c) no type in the transitive membership of the union type has {variety}XS11-1list, and (d) no type in the transitive membership of the union type is a type with {variety}XS11-1union having a non-empty {facets}XS11-1 property

    query

    A query consists of one or more modules.

    query body

    The Query Body, if present, consists of an expression that defines the result of the query.

    reserved namespaces

    A reserved namespace is a namespace that must not be used in the name of a function declaration.

    resolve

    To resolve a relative URI$rel against a base URI $base is to expand it to an absolute URI, as if by calling the function fn:resolve-uri($rel, $base).

    reverse document order

    The node ordering that is the reverse of document order is called reverse document order.

    same key

    Two atomic items K1 and K2 have the same key value if fn:atomic-equal(K1, K2) returns true, as specified in Section 13.2.1 fn:atomic-equalFO

    schema aware feature

    The Schema Aware Feature permits the query Prolog to contain a schema import, and permits a query to contain a validate expression (see 4.24 Validate Expressions).

    schema import

    A schema import imports the element declarations, attribute declarations, and type definitions from a schema into the in-scope schema definitions. For each named user-defined simple type in the schema, schema import also adds a corresponding constructor function.

    schema type

    A schema type is a complex type or simple type as defined in the [XML Schema 1.0] or [XML Schema 1.1] specifications, including built-in types as well as user-defined types.

    sequence

    A sequence is an ordered collection of zero or more items.

    sequence arrow operator

    The sequence arrow operator=> applies a function to a supplied sequence.

    sequence concatenation

    The sequence concatenation of a number of sequences S1, S2, ... Sn is defined to be the sequence formed from the items of S1, followed by the items from S2, and so on, retaining order.

    sequence type

    A sequence type is a type that can be expressed using the SequenceType syntax. Sequence types are used whenever it is necessary to refer to a type in an XQuery 4.0 and XPath 4.0 expression. Since all values are sequences, every value matches one or more sequence types.

    sequence type designator

    A sequence type designator is a syntactic construct conforming to the grammar rule SequenceType. A sequence type designator is said to designate a sequence type.

    SequenceType matching

    SequenceType matching compares a value with an expected sequence type.

    serialization

    Serialization is the process of converting an XDM instance to a sequence of octets (step DM4 in Figure 1.), as described in [XSLT and XQuery Serialization 4.0].

    serialization feature

    The Serialization Feature provides means for serializing the result of a query as specified in 2.3.5 Serialization.

    setter

    Setters are declarations that set the value of some property that affects query processing, such as construction mode or default collation.

    should

    SHOULD means that there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course.

    singleton

    A sequence containing exactly one item is called a singleton.

    singleton focus

    A singleton focus is a fixed focus in which the context value is a singleton item.

    stable

    Document order is stable, which means that the relative order of two nodes will not change during the processing of a given queryexpression, even if this order is implementation-dependent.

    statically known collations

    Statically known collations. This is an implementation-defined mapping from URI to collation. It defines the names of the collations that are available for use in processing queries and expressions.

    statically known decimal formats

    Statically known decimal formats. This is a mapping from QNames to decimal formats, with one default format that has no visible name, referred to as the unnamed decimal format. Each format is available for use when formatting numbers using the fn:format-number function.

    statically known function definitions

    Statically known function definitions. This is a set of function definitions.

    statically known namespaces

    Statically known namespaces. This is a mapping from prefix to namespace URI that defines all the namespaces that are known during static processing of a given expression.

    static analysis phase

    The static analysis phase depends on the expression itself and on the static context. The static analysis phase does not depend on input data (other than schemas).

    Static Base URI

    Static Base URI. This is an absolute URI, used to resolve relative URIs during static analysis.

    static context

    The static context of an expression is the information that is available during static analysis of the expression, prior to its evaluation.

    static error

    An error that can be detected during the static analysis phase, and is not a type error, is a static error.

    static function call

    A static function call consists of an EQName followed by a parenthesized list of zero or more arguments.

    static type

    The static type of an expression is the best inference that the processor is able to make statically about the type of the result of the expression.

    step

    A step is a part of a path expression that generates a sequence of items and then filters the sequence by zero or more predicates. The value of the step consists of those items that satisfy the predicates, working from left to right. A step may be either an axis step or a postfix expression.

    string constructor

    A String Constructor creates a string from literal text and interpolated expressions.

    string value

    The string value of a node is a string and can be extracted by applying the Section 2.1.3 fn:stringFO function to the node.

    substantively disjoint

    Two sequence types are deemed to be substantively disjoint if (a) neither is a subtype of the other (see 3.3.1 Subtypes of Sequence Types) and (b) the only values that are instances of both types are one or more of the following:

    • The empty sequence, ().

    • The empty map, {}.

    • The empty array, [].

    substitution group

    Substitution groups are defined in Section 2.2.2.2 Element Substitution Group XS1-1 and Section 2.2.2.2 Element Substitution Group XS11-1. Informally, the substitution group headed by a given element (called the head element) consists of the set of elements that can be substituted for the head element without affecting the outcome of schema validation.

    subtype

    Given two sequence types or item types, the rules in this section determine if one is a subtype of the other. If a type A is a subtype of type B, it follows that every value matched by A is also matched by B.

    subtype substitution

    The use of a value that has a dynamic type that is a subtype of the expected type is known as subtype substitution.

    symbol

    Each rule in the grammar defines one symbol, using the following format:

    symbol ::= expression
    symbol separators

    Whitespace and Comments function as symbol separators. For the most part, they are not mentioned in the grammar, and may occur between any two terminal symbols mentioned in the grammar, except where that is forbidden by the /* ws: explicit */ annotation in the EBNF, or by the /* xgc: xml-version */ annotation.

    system function

    System functions include the functions defined in [XQuery and XPath Functions and Operators 4.0], functions defined by the specifications of a host language, constructor functions for atomic types, and any additional functions provided by the implementation. System functions are sometimes called built-in functions.

    target namespace

    The target namespace of a module is the namespace of the objects (such as elements or functions) that it defines.

    terminal

    A terminal is a symbol or string or pattern that can appear in the right-hand side of a rule, but never appears on the left-hand side in the main grammar, although it may appear on the left-hand side of a rule in the grammar for terminals.

    tuple

    A tuple is a set of zero or more named variables, each of which is bound to a value that is an XDM instance.

    tuple stream

    A tuple stream is an ordered sequence of zero or more tuples.

    type annotation

    Each element node and attribute node in an XDM instance has a type annotation (described in Section 2.8 Schema InformationDM). The type annotation of a node is a reference to a schema type.

    typed data feature

    The Typed Data Feature permits an XDM instance to contain element node types other than xs:untyped and attributes node types other than xs:untypedAtomic.

    type declaration

    A variable binding may be accompanied by a type declaration, which consists of the keyword as followed by the static type of the variable, declared using the syntax in 3.1 Sequence Types.

    typed value

    The typed value of a node is a sequence of atomic items and can be extracted by applying the Section 2.1.4 fn:dataFO function to the node.

    type error

    A type error may be raised during the static analysis phase or the dynamic evaluation phase. During the static analysis phase, a type error occurs when the static type of an expression does not match the expected type of the context in which the expression occurs. During the dynamic evaluation phase, a type error occurs when the dynamic type of a value does not match the expected type of the context in which the value occurs.

    type promotion

    Under certain circumstances, an atomic item can be promoted from one type to another.

    URI

    Within this specification, the term URI refers to a Universal Resource Identifier as defined in [RFC3986] and extended in [RFC3987] with the new name IRI.

    user-defined function

    User defined functions are functions that contain a function body, which provides the implementation of the function as a content expression.

    value

    In the data model, a value is always a sequence.

    variable declaration

    A variable declaration in the XQuery prolog defines the name and static type of a variable, and optionally a value for the variable. It adds to the in-scope variables in the static context, and may also add to the variable values in the dynamic context.

    variable reference

    A variable reference is an EQName preceded by a $-sign.

    variable terminal

    A variable terminal is an instance of a production rule that is not itself an ordinary production rule but that is named (directly) on the right-hand side of an ordinary production rule.

    variable values

    Variable values. This is a mapping from expanded QName to value. It contains the same expanded QNames as the in-scope variables in the static context for the expression. The expanded QName is the name of the variable and the value is the dynamic value of the variable, which includes its dynamic type.

    version declaration

    A version declaration can identify the applicable XQuery syntax and semantics for a module, as well as its encoding.

    warning

    In addition to static errors, dynamic errors, and type errors, an XQuery 4.0 and XPath 4.0 implementation may raise warnings, either during the static analysis phase or the dynamic evaluation phase. The circumstances in which warnings are raised, and the ways in which warnings are handled, are implementation-defined.

    whitespace

    A whitespace character is any of the characters defined by [http://www.w3.org/TR/REC-xml/#NT-S].

    wildcard-matches

    In these rules, if MU and NU are NameTestUnions, then MUwildcard-matchesNU is true if every name that matches MU also matches NU.

    window

    A window is a sequence of consecutive items drawn from the binding sequence.

    XDM instance

    The term XDM instance is used, synonymously with the term value, to denote an unconstrained sequence of items.

    XPath 1.0 compatibility mode

    XPath 1.0 compatibility mode.This component must be set by all host languages that include XPath 3.1 as a subset, indicating whether rules for compatibility with XPath 1.0 are in effect. XQuery sets the value of this component to false. This value is true if rules for backward compatibility with XPath Version 1.0 are in effect; otherwise it is false.

    XQuery 1.0 Processor

    An XQuery 1.0 Processor processes a query according to the XQuery 1.0 specification.

    XQuery 3.0 Processor

    An XQuery 3.0 Processor processes a query according to the XQuery 3.0 specification.

    XQuery 3.1 Processor

    An XQuery 3.1 Processor processes a query according to the XQuery 3.1 specification.

    XQuery 4.0 Processor

    An XQuery 4.0 Processor processes a query according to the XQuery 4.0 specification.

    XQuery version number

    An XQuery version number consists of two integers, referred to as the major version number and the minor version number.

    xs:anyAtomicType

    xs:anyAtomicType is an atomic type that includes all atomic items (and no values that are not atomic). Its base type is xs:anySimpleType from which all simple types, including atomic, list, and union types, are derived. All primitive atomic types, such as xs:decimal and xs:string, have xs:anyAtomicType as their base type.

    xs:dayTimeDuration

    xs:dayTimeDuration is derived by restriction from xs:duration. The lexical representation of xs:dayTimeDuration is restricted to contain only day, hour, minute, and second components.

    xs:error

    xs:error is a simple type with no value space. It is defined in Section 3.16.7.3 xs:error XS11-1 and can be used in the 3.1 Sequence Types to raise errors.

    xs:untyped

    xs:untyped is used as the type annotation of an element node that has not been validated, or has been validated in skip mode.

    xs:untypedAtomic

    xs:untypedAtomic is an atomic type that is used to denote untyped atomic data, such as text that has not been assigned a more specific type.

    xs:yearMonthDuration

    xs:yearMonthDuration is derived by restriction from xs:duration. The lexical representation of xs:yearMonthDuration is restricted to contain only year and month components.

    zero-digit

    zero-digit(M) is the character used in the picture string to represent the digit zero; the default value is U+0030 (DIGIT ZERO, 0) . This character must be a digit (category Nd in the Unicode property database), and it must have the numeric value zero. This property implicitly defines the ten Unicode characters that are used to represent the values 0 to 9 in the function output: Unicode is organized so that each set of decimal digits forms a contiguous block of characters in numerical sequence. Within the picture string any of these ten character can be used (interchangeably) as a place-holder for a mandatory digit. Within the final result string, these ten characters are used to represent the digits zero to nine.

    J Atomic Comparisons: An Overview (Non-Normative)

    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.

    J.1 Equality Comparisons

    In XQuery 4.0 and XPath 4.0 there are essentially four ways of comparing two atomic items for equality:

    • $A = $B

      This operator was introduced in XPath 1.0. The semantics were changed slightly in XPath 2.0, but the original semantics remain available when XPath 1.0 compatibility mode is enabled.

      With a general comparison in XPath 2.0 or later (and in XQuery), the following rules are observed:

      • Either operand may be a sequence; the result is true if any pair of items from the two sequences compares equal.

        In consequence, if either operand is an empty sequence, the result is false.

      • If nodes are supplied, they are atomized.

      • 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 "4.0" and "4" are not equal to each other, but both compare equal to the integer value 4.

      • Comparison of certain values is context-sensitive. In particular, comparison of strings uses the default collation from the static context, while comparison of date/time values lacking an explicit timezone takes the timezone from the dynamic context.

      • NaN is not equal to NaN; negative zero is equal to positive zero.

      • xs:hexBinary and xs:base64Binary values are mutually comparable: they are equal if they represent the same sequence of octets.

      • Comparing incompatible values (for example xs:integer and xs:date) raises an error.

    • $A eq $B

      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.

      With a value comparison, the rules are:

      • Each operand must either be a single atomic item, or an empty sequence.

      • If either operand is an empty sequence, the result is an empty sequence; in most contexts this has the same effect as returning false.

      • If nodes are supplied, they are atomized.

      • Untyped atomic items are converted to strings (regardless of the type of the other operand).

      • Numeric values of types xs:integer, xs:decimal, or xs:float are converted to xs:double.

        This can lead to problems with implementations of xs:decimal that support more precision than can be held in an xs:double.

      • As with general comparisons, the default collation and implicit timezone are taken from the context.

      • NaN is not equal to NaN; negative zero is equal to positive zero.

      • xs:hexBinary and xs:base64Binary values are mutually comparable: they are equal if they represent the same sequence of octets.

      • Comparing incompatible values (for example xs:integer and xs:date) raises an error.

    • deep-equal($A, $B)

      As the name implies, the deep-equal 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 deep-equal($A, $B) are also invoked by a wide variety of other functions including distinct-values, all-equal, and all-different; it is also used to underpin grouping constructs in both XQuery 4.0 and XSLT 4.0.

      Some of the relevant rules are:

      • Because deep-equal 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.

      • If nodes are supplied, they are not atomized; they are compared as nodes.

      • 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.

      • Comparisons of dates and times lacking a timezone uses the implicit timezone from the dynamic context.

      • Numeric values are converted to xs:decimal prior to comparison, not to xs:double. This represents a departure in 4.0 from previous versions of the specification. The conversion must use an implementation of xs:decimal that does not cause loss of precision. As a result, the comparison is now truly transitive, which makes it suitable to underpin grouping operations.

      • To ensure that every value is equal to itself, comparing NaN to NaN returns true.

      • xs:hexBinary and xs:base64Binary values are mutually comparable: they are equal if they represent the same sequence of octets.

      • Comparing incompatible values (for example xs:integer and xs:date) returns false; it does not raise an error.

    • atomic-equal($A, $B)

      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:

      • The type signature of the function ensures that it can only be used to compare single items; empty sequences do not arise.

      • If nodes are supplied, they are atomized.

      • Strings are compared codepoint-by-codepoint, without reference to any collation or normalization.

      • 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.

      • As with deep-equal, numeric values are converted to xs:decimal prior to comparison, not to xs:double.

      • Comparing NaN to NaN returns true.

      • xs:hexBinary and xs:base64Binary values are distinct: both can co-exist as distinct keys in a map even if the underlying sequence of octets is the same.

      • Comparing incompatible values (for example xs:integer and xs:date) returns false; it does not raise an error.

    The following table summarizes these differences. 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.

    $A$B$A = $B$A eq $Bdeep-equal(​$A, $B)atomic-equal(​$A, $B)

    ()

    ()

    false

    ()

    true

    error

    12

    ()

    false

    ()

    false

    error

    (1,2)

    (2,3)

    true

    error

    false

    error

    12

    12e0

    true

    true

    true

    true

    0.2

    0.2e0

    true

    true

    false

    false

    NaN

    NaN

    false

    false

    true

    true

    +0e0

    -0e0

    true

    true

    true

    true

    "A"

    "a"

    true

    true

    true

    false

    "A"

    12

    error

    error

    false

    false

    <a>A</a>

    "A"

    true

    true

    false

    true

    <a>12</a>

    12

    true

    error

    false

    false

    xs:time(​'12:00:00Z')

    xs:time(​'13:00:00+01:00')

    true

    true

    true

    true

    xs:time(​'12:00:00Z')

    xs:time(​'13:00:00')

    true

    true

    true

    false

    xs:hexBinary(​"0000")

    xs:base64Binary(​"AAA=")

    true

    true

    true

    false

    J.2 Ordering Comparisons

    In XQuery 4.0 and XPath 4.0 there are essentially three ways of comparing two atomic items for their relative ordering:

    • $A < $B

    • $A lt $B

    • Sorting

    TODO: to be expanded.

    K Backwards Compatibility (Non-Normative)

    K.1 Incompatibilities relative to XQuery and XPath 3.1

    In fn:format-integer, certain formatting pictures using a circumflex as a grouping separator might be interpreted differently in 4.0: for example format-integer(1234, "9^999") would output "1^234" in 3.1, but will output "1621" (1234 in base 9) with 4.0. As a workaround, this can be rewritten as format-integer(1234, "0^000").

    In computed node constructors, the node name must now be written in quotation marks if it matches certain language keywords. For example element div {} must now be written element "div" {}. (Alternatively, element { "div" } {} and element Q{}div {} are permitted by both XQuery 3.1 and XQuery 4.0.) This change is made because {} is now a valid expression representing an empty map, so expressions such as element otherwise {} could (without this rule) be parsed in two different ways.

    In XQuery 4.0 and XPath 4.0, certain expressions are classified as implausible: an example is @code/text(), which will always return an empty sequence. A processor may report a static error when such expressions are encountered; however, processors are required to provide a mode of operation in which such expressions are accepted, thus retaining backwards compatibility.

    In expressions that deliver a function item, notably partial function applications, named function references, and the fn:function-lookup 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 contains(?, 42) 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.

    As explained in 3.4.4 Function Coercion, 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.

    K.2 Incompatibilities relative to XQuery and XPath 3.0

    The following names are now reserved, and cannot appear as function names (see A.4 Reserved Function Names):

    • map

    • array

    K.3 Incompatibilities relative to XQuery and XPath 2.01.0

    The following names are now reserved, and cannot appear as function names (see A.4 Reserved Function Names):

    • function

    • namespace-node

    • switch

    If U is a union type with T as one of its members, and if E is an element with T as its type annotation, the expression E instance of element(*, U) returns true in both XQuery and XPath 3.0 and 3.1. In XPath 2.0XQuery 1.0, it returns false.

    Note:

    This is not an incompatibility with XQuery and XPath 3.0. It should be included in XQuery and XPath 3.0 as an incompatibility with XPath 2.0XQuery 1.0, but it was discovered after publication.

    K.4 Incompatibilities relative to XPath 1.0

    This appendix provides a summary of the areas of incompatibility between XPath 4.0 and [XML Path Language (XPath) Version 1.0]. In each of these cases, an XPath 4.0 processor is compatible with an XPath 2.0, 3.0, or 3.1 processor.

    Three separate cases are considered:

    1. Incompatibilities that exist when source documents have no schema, and when running with XPath 1.0 compatibility mode set to true. This specification has been designed to reduce the number of incompatibilities in this situation to an absolute minimum, but some differences remain and are listed individually.

    2. Incompatibilities that arise when XPath 1.0 compatibility mode is set to false. In this case, the number of expressions where compatibility is lost is rather greater.

    3. Incompatibilities that arise when the source document is processed using a schema (whether or not XPath 1.0 compatibility mode is set to true). Processing the document with a schema changes the way that the values of nodes are interpreted, and this can cause an XPath expression to return different results.

    K.4.1 Incompatibilities when Compatibility Mode is true

    The list below contains all known areas, within the scope of this specification, where an XPath 4.0 processor running with compatibility mode set to true will produce different results from an XPath 1.0 processor evaluating the same expression, assuming that the expression was valid in XPath 1.0, and that the nodes in the source document have no type annotations other than xs:untyped and xs:untypedAtomic.

    Incompatibilities in the behavior of individual functions are not listed here, but are included in an appendix of [XQuery and XPath Functions and Operators 4.0].

    Since both XPath 1.0 and XPath 4.0 leave some aspects of the specification implementation-defined, there may be incompatibilities in the behavior of a particular implementation that are outside the scope of this specification. Equally, some aspects of the behavior of XPath are defined by the host language.

    1. Consecutive comparison operators such as A < B < C were supported in XPath 1.0, but are not permitted by the XPath 4.0 grammar. In most cases such comparisons in XPath 1.0 did not have the intuitive meaning, so it is unlikely that they have been widely used in practice. If such a construct is found, an XPath 4.0 processor will report a syntax error, and the construct can be rewritten as (A < B) < C

    2. When converting strings to numbers (either explicitly when using the number function, or implicitly say on a function call), certain strings that converted to the special value NaN under XPath 1.0 will convert to values other than NaN under XPath 4.0. These include any number written with a leading + sign, any number in exponential floating point notation (for example 1.0e+9), and the strings INF and -INF.

      Furthermore, the strings Infinity and -Infinity, which were accepted by XPath 1.0 as representations of the floating-point values positive and negative infinity, are no longer recognized. They are converted to NaN when running under XPath 4.0 with compatibility mode set to true, and cause a dynamic error when compatibility mode is set to false.

    3. XPath 4.0 does not allow a token starting with a letter to follow immediately after a numeric literal, without intervening whitespace. For example, 10div 3 was permitted in XPath 1.0, but in XPath 4.0 must be written as 10 div 3.

    4. The namespace axis is deprecated as of XPath 2.0. Implementations may support the namespace axis for backward compatibility with XPath 1.0, but they are not required to do so. (XSLT 2.0 requires that if XPath backwards compatibility mode is supported, then the namespace axis must also be supported; but other host languages may define the conformance rules differently.)

    5. In XPath 1.0, the expression -x|y parsed as -(x|y), and returned the negation of the numeric value of the first node in the union of x and y. In XPath 4.0, this expression parses as (-x)|y. When XPath 1.0 Compatibility Mode is true, this will always cause a type error.

    6. The rules for converting numbers to strings have changed. These may affect the way numbers are displayed in the output of a stylesheet. For numbers whose absolute value is in the range 1E-6 to 1E+6, the result should be the same, but outside this range, scientific format is used for non-integral xs:float and xs:double values.

    7. If one operand in a general comparison is a single atomic item of type xs:boolean, the other operand is converted to xs:boolean when XPath 1.0 compatibility mode is set to true. In XPath 1.0, if neither operand of a comparison operation using the <, <=, > or >= operator was a node set, both operands were converted to numbers. The result of the expression true() > number('0.5') is therefore true in XPath 1.0, but is false in XPath 4.0 even when compatibility mode is set to true.

    8. In XPath 4.0, a type error is raised if the PITarget specified in a SequenceType of form processing-instruction(PITarget) is not a valid NCName. In XPath 1.0, this condition was not treated as an error.

    K.4.2 Incompatibilities when Compatibility Mode is false

    Even when the setting of the XPath 1.0 compatibility mode is false, many XPath expressions will still produce the same results under XPath 4.0 as under XPath 1.0. The exceptions are described in this section.

    In all cases it is assumed that the expression in question was valid under XPath 1.0, that XPath 1.0 compatibility mode is false, and that all elements and attributes are annotated with the types xs:untyped and xs:untypedAtomic respectively.

    In the description below, the terms node-set and number are used with their XPath 1.0 meanings, that is, to describe expressions which according to the rules of XPath 1.0 would have generated a node-set or a number respectively.

    1. When a node-set containing more than one node is supplied as an argument to a function or operator that expects a single node or value, the XPath 1.0 rule was that all nodes after the first were discarded. Under XPath 4.0, a type error occurs if there is more than one node. The XPath 1.0 behavior can always be restored by using the predicate [1] to explicitly select the first node in the node-set.

    2. In XPath 1.0, the < and > operators, when applied to two strings, attempted to convert both the strings to numbers and then made a numeric comparison between the results. In XPath 4.0, these operators perform a string comparison using the default collating sequence. (If either value is numeric, however, the results are compatible with XPath 1.0)

    3. When an empty node-set is supplied as an argument to a function or operator that expects a number, the value is no longer converted implicitly to NaN. The XPath 1.0 behavior can always be restored by using the number function to perform an explicit conversion.

    4. More generally, the supplied arguments to a function or operator are no longer implicitly converted to the required type, except in the case where the supplied argument is of type xs:untypedAtomic (which will commonly be the case when a node in a schemaless document is supplied as the argument). For example, the function call substring-before(10 div 3, ".") raises a type error under XPath 4.0, because the arguments to the substring-before function must be strings rather than numbers. The XPath 1.0 behavior can be restored by performing an explicit conversion to the required type using a constructor function or cast.

    5. The rules for comparing a node-set to a boolean have changed. In XPath 1.0, an expression such as $node-set = true() was evaluated by converting the node-set to a boolean and then performing a boolean comparison: so this expression would return true if $node-set was non-empty. In XPath 4.0, this expression is handled in the same way as other comparisons between a sequence and a singleton: it is true if $node-set contains at least one node whose value, after atomization and conversion to a boolean using the casting rules, is true.

      This means that if $node-set is empty, the result under XPath 4.0 will be false regardless of the value of the boolean operand, and regardless of which operator is used. If $node-set is non-empty, then in most cases the comparison with a boolean is likely to fail, giving a dynamic error. But if a node has the value "0", "1", "true", or "false", evaluation of the expression may succeed.

    6. Comparisons of a number to a boolean, a number to a string, or a string to a boolean are not allowed in XPath 4.0: they result in a type error. In XPath 1.0 such comparisons were allowed, and were handled by converting one of the operands to the type of the other. So for example in XPath 1.0 4 = true() returned true; 4 ="+4" returned false (because the string "+4" converts to NaN), and false = "false" returned false (because the string "false" converts to the boolean true). In XPath 3.0 all these comparisons are type errors.

    7. Additional numeric types have been introduced, with the effect that arithmetic may now be done as an integer, decimal, or single- or double-precision floating point calculation where previously it was always performed as double-precision floating point. The result of the div operator when dividing two integers is now a value of type decimal rather than double. The expression 10 div 0 raises an error rather than returning positive infinity.

    8. The rules for converting strings to numbers have changed. The implicit conversion that occurs when passing an xs:untypedAtomic value as an argument to a function that expects a number no longer converts unrecognized strings to the value NaN; instead, it reports a dynamic error. This is in addition to the differences that apply when backwards compatibility mode is set to true.

    9. Many operations in XPath 4.0 produce an empty sequence as their result when one of the arguments or operands is an empty sequence. Where the operation expects a string, an empty sequence is usually considered equivalent to a zero-length string, which is compatible with the XPath 1.0 behavior. Where the operation expects a number, however, the result is not the same. For example, if @width returns an empty sequence, then in XPath 1.0 the result of @width+1 was NaN, while with XPath 4.0 it is (). This has the effect that a filter expression such as item[@width+1 != 2] will select items having no width attribute under XPath 1.0, and will not select them under XPath 4.0.

    10. The typed value of a comment node, processing instruction node, or namespace node under XPath 4.0 is of type xs:string, not xs:untypedAtomic. This means that no implicit conversions are applied if the value is used in a context where a number is expected. If a processing-instruction node is used as an operand of an arithmetic operator, for example, XPath 1.0 would attempt to convert the string value of the node to a number (and deliver NaN if unsuccessful), while XPath 4.0 will report a type error.

    11. In XPath 1.0, it was defined that with an expression of the form A and B, B would not be evaluated if A was false. Similarly in the case of A or B, B would not be evaluated if A was true. This is no longer guaranteed with XPath 4.0: the implementation is free to evaluate the two operands in either order or in parallel. This change has been made to give more scope for optimization in situations where XPath expressions are evaluated against large data collections supported by indexes. Implementations may choose to retain backwards compatibility in this area, but they are not obliged to do so.

    12. In XPath 1.0, the expression -x|y parsed as -(x|y), and returned the negation of the numeric value of the first node in the union of x and y. In XPath 4.0, this expression parses as (-x)|y. When XPath 1.0 Compatibility Mode is false, this will cause a type error, except in the situation where x evaluates to an empty sequence. In that situation, XPath 4.0 will return the value of y, whereas XPath 1.0 returned the negation of the numeric value of y.

    K.4.3 Incompatibilities when using a Schema

    An XPath expression applied to a document that has been processed against a schema will not always give the same results as the same expression applied to the same document in the absence of a schema. Since schema processing had no effect on the result of an XPath 1.0 expression, this may give rise to further incompatibilities. This section gives a few examples of the differences that can arise.

    Suppose that the context node is an element node derived from the following markup: <background color="red green blue"/>. In XPath 1.0, the predicate [@color="blue"] would return false. In XPath 4.0, if the color attribute is defined in a schema to be of type xs:NMTOKENS, the same predicate will return true.

    Similarly, consider the expression @birth < @death applied to the element <person birth="1901-06-06" death="1991-05-09"/>. With XPath 1.0, this expression would return false, because both attributes are converted to numbers, which returns NaN in each case. With XPath 4.0, in the presence of a schema that annotates these attributes as dates, the expression returns true.

    Once schema validation is applied, elements and attributes cannot be used as operands and arguments of expressions that expect a different data type. For example, it is no longer possible to apply the substring function to a date to extract the year component, or to a number to extract the integer part. Similarly, if an attribute is annotated as a boolean then it is not possible to compare it with the strings "true" or "false". All such operations lead to type errors. The remedy when such errors occur is to introduce an explicit conversion, or to do the computation in a different way. For example, substring-after(@temperature, "-") might be rewritten as abs(@temperature).

    In the case of an XPath 4.0 implementation that provides the static typing feature, many further type errors will be reported in respect of expressions that worked under XPath 1.0. For example, an expression such as round(../@price) might lead to a static type error because the processor cannot infer statically that ../@price is guaranteed to be numeric.

    Schema validation will in many cases perform whitespace normalization on the contents of elements (depending on their type). This will change the result of operations such as the string-length function.

    Schema validation augments the data model by adding default values for omitted attributes and empty elements.

    L Change Log (Non-Normative)

    1. Use the arrows to browse significant changes since the 3.1 version of this specification.

      See 1 Introduction

    2. Sections with significant changes are marked Δ in the table of contents.

      See 1 Introduction

    3. Setting the default namespace for elements and types to the special value ##any causes an unprefixed element name to act as a wildcard, matching by local name regardless of namespace.

      See 3.2.7.2 Element Types

    4. The terms FunctionType, ArrayType, MapType, and RecordType replace FunctionTest, ArrayTest, MapTest, and RecordTest, with no change in meaning.

      See 3.2.8.1 Function Types

    5. Record types are added as a new kind of ItemType, constraining the value space of maps.

      See 3.2.8.3 Record Types

    6. Function coercion now allows a function with arity N to be supplied where a function of arity greater than N is expected. For example this allows the function true#0 to be supplied where a predicate function is required.

      See 3.4.4 Function Coercion

    7. The symbols × and ÷ can be used for multiplication and division.

      See 4.8 Arithmetic Expressions

    8. 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.

      See 4.10.1 Value Comparisons

    9. Operators such as < and > can use the full-width forms and to avoid the need for XML escaping.

      See 4.10.2 General Comparisons

    10. The lookup operator ? can now be followed by a string literal, for cases where map keys are strings other than NCNames. It can also be followed by a variable reference.

      See 4.14.3 Lookup Expressions

    11. The arrow operator => is now complemented by a “mapping arrow” operator =!> which applies the supplied function to each item in the input sequence independently.

      See 4.23.2 Mapping Arrow Expressions

    12. All implementations must now predeclare the namespace prefixes math, map, array, and err. In XQuery 3.1 it was permitted but not required to predeclare these namespaces.

      See 5.13 Namespace Declaration

    13. 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).

      See 5.18 Function Declarations

    14. The operator mapping table has been simplified by removing entries for the operators ne, le, gt, and ge; these are now defined by reference to the rules for the operators eq and lt.

      See B.2 Operator Mapping

    15. $err:map contains entries for all values that are bound to the single variables.

      See 4.20 Try/Catch Expressions

    16. $err:stack-trace provides information about the current state of execution.

      See 4.20 Try/Catch Expressions

    17. PR 1023 1128 

      It has been clarified that function coercion applies even when the supplied function item matches the required function type. This is to ensure that arguments supplied when calling the function are checked against the signature of the required function type, which might be stricter than the signature of the supplied function item.

      See 3.4.4 Function Coercion

    18. PR tba 

      Predicates in filter expressions for maps and arrays can now be numeric.

      See 4.14.4 Filter Expressions for Maps and Arrays

    19. The ordered { E } and unordered { E } expressions are retained for backwards compatibility reasons, but in XQuery 4.0 they are deprecated and have no useful effect.

      See 4.15 Ordered and Unordered Expressions

      The ordering mode declaration is retained for backwards compatibility reasons, but in XQuery 4.0 it is deprecated and has no useful effect.

      See 5.7 Ordering Mode Declaration

    20. The static typing feature has been dropped.

      See 6 Conformance

      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.

      See C.1 Static Context Components

    21. The syntax record() is allowed; the only thing it matches is an empty map.

      See 3.2.8.3 Record Types

    22. The context value static type, which was there purely to assist in static typing, has been dropped.

      See 2.2.1 Static Context

    23. Four new axes have been defined: preceding-or-self, preceding-sibling-or-self, following-or-self, and following-sibling-or-self.

      See 4.6.4.1 Axes

    24. The syntax document-node(N), where N is a NameTestUnion, is introduced as an abbreviation for document-node(element(N)). For example, document-node(*) matches any well-formed XML document (as distinct from a document fragment).

      See 3.2.7 Node Types

    25. PR 28 

      Multiple for and let clauses can be combined in an expression without an intervening return keyword.

      See 4.13.11 For Expressions

      See 4.13.12 Let Expressions

    26. PR 159 

      Keyword arguments are allowed on static function calls, as well as positional arguments.

      See 4.5.1.1 Static Function Call Syntax

    27. PR 202 

      The presentation of the rules for the subtype relationship between sequence types and item types has been substantially rewritten to improve clarity; no change to the semantics is intended.

      See 3.3 Subtype Relationships

    28. PR 230 

      The rules for “errors and optimization” have been tightened up to disallow many cases of optimizations that alter error behavior. In particular there are restrictions on reordering the operands of and and or, and of predicates in filter expressions, in a way that might allow the processor to raise dynamic errors that the author intended to prevent.

      See 2.4.5 Guarded Expressions

    29. PR 254 

      The term "function conversion rules" used in 3.1 has been replaced by the term "coercion rules".

      See 3.4 Coercion Rules

      The coercion rules allow “relabeling” of a supplied atomic item where the required type is a derived atomic type: for example, it is now permitted to supply the value 3 when calling a function that expects an instance of xs:positiveInteger.

      See 3.4 Coercion Rules

      The value bound to a variable in a let clause is now converted to the declared type by applying the coercion rules.

      See 4.13.3 Let Clause

      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.

      See 5.16 Variable Declaration

    30. PR 284 

      Alternative syntax for conditional expressions is available: if (condition) { X } else { Y }, with the else part being optional.

      See 4.16 Conditional Expressions

    31. PR 286 

      Element and attribute tests can include alternative names: element(chapter|section), attribute(role|class).

      See 3.2.7 Node Types

      The NodeTest in an AxisStep now allows alternatives: ancestor::(section|appendix)

      See 3.2.7 Node Types

      Element and attribute tests of the form element(N) and attribute(N) now allow N to be any NameTest, including a wildcard.

      See 3.2.7.2 Element Types

      See 3.2.7.3 Attribute Types

    32. PR 324 

      String templates provide a new way of constructing strings: for example `{$greeting}, {$planet}!` is equivalent to $greeting || ', ' || $planet || '!'

      See 4.9.2 String Templates

    33. PR 326 

      Support for higher-order functions is now a mandatory feature (in 3.1 it was optional).

      See 6 Conformance

    34. PR 344 

      A for member clause is added to FLWOR expressions to allow iteration over an array.

      See 4.13.2 For Clause

      See 4.13.11 For Expressions

    35. PR 364 

      Switch expressions now allow a case clause to match multiple atomic items.

      See 4.18 Switch Expressions

    36. PR 368 

      The concept of the context item has been generalized, so it is now a context value. That is, it is no longer constrained to be a single item.

      See 2.2.2 Dynamic Context

      See 5.17 Context Value Declaration

    37. PR 433 

      Numeric literals can now be written in hexadecimal or binary notation; and underscores can be included for readability.

      See 4.2.1.1 Numeric Literals

    38. PR 483 

      The start clause in window expressions has become optional, as well as the when keyword and its associated expression.

      See 4.13.4 Window Clause

    39. PR 493 

      A new variable err:map is available, capturing all error information in one place.

      See 4.20 Try/Catch Expressions

    40. PR 519 

      The rules for tokenization have been largely rewritten. In some cases the revised specification may affect edge cases that were handled in different ways by different 3.1 processors, which could lead to incompatible behavior.

      See A.3 Lexical structure

    41. PR 521 

      New abbreviated syntax is introduced (focus function) for simple inline functions taking a single argument. An example is fn { ../@code }

      See 4.5.2.5 Inline Function Expressions

    42. PR 587 

      Switch and typeswitch expressions can now be written with curly brackets, to improve readability.

      See 4.18 Switch Expressions

      See 4.21.2 Typeswitch

    43. PR 603 

      The rules for reporting type errors during static analysis have been changed so that a processor has more freedom to report errors in respect of constructs that are evidently wrong, such as @price/@value, even though dynamic evaluation is defined to return an empty sequence rather than an error.

      See 2.4.6 Implausible Expressions

      See 4.6.4.3 Implausible Axis Steps

    44. PR 606 

      Element and attribute tests of the form element(A|B) and attribute(A|B) are now allowed.

      See 3.2.7.2 Element Types

      See 3.2.7.3 Attribute Types

    45. PR 635 

      The rules for the consistency of schemas imported by different query modules, and for consistency between imported schemas and those used for validating input documents, have been defined with greater precision. It is now recognized that these schemas will not always be identical, and that validation with respect to different schemas may produce different outcomes, even if the components of one are a subset of the components of the other.

      See 5.11 Schema Import

    46. PR 659 

      In previous versions the interpretation of location hints in import schema declarations was entirely at the discretion of the processor. To improve interoperability, XQuery 4.0 recommends (but does not mandate) a specific strategy for interpreting these hints.

      See 5.11 Schema Import

    47. PR 678 

      The comparand expression in a switch expression can be omitted, allowing the switch cases to be provided as arbitrary boolean expressions.

      See 4.18 Switch Expressions

    48. PR 682 

      The values true() and false() are allowed in function annotations, and negated numeric literals are also allowed.

      See 5.18.4 Function Annotations

    49. PR 691 

      Enumeration types are added as a new kind of ItemType, constraining the value space of strings.

      See 3.2.6 Enumeration Types

    50. PR 728 

      The syntax record(*) is allowed; it matches any map.

      See 3.2.8.3 Record Types

    51. PR 753 

      The default namespace for elements and types can now be declared to be fixed for a query module, meaning it is unaffected by a namespace declaration appearing on a direct element constructor.

      See 4.12.1.2 Namespace Declaration Attributes

      See 5.14 Default Namespace Declaration

    52. PR 815 

      The coercion rules now allow conversion in either direction between xs:hexBinary and xs:base64Binary.

      See 3.4 Coercion Rules

    53. PR 820 

      The value bound to a variable in a for clause is now converted to the declared type by applying the coercion rules.

      See 4.13.2 For Clause

    54. PR 837 

      A deep lookup operator ?? is provided for searching trees of maps and arrays.

      See 4.14.3 Lookup Expressions

    55. PR 911 

      The coercion rules now allow any numeric type to be implicitly converted to any other, for example an xs:double is accepted where the required type is xs:double.

      See 3.4 Coercion Rules

    56. PR 943 

      A FLWOR expression may now include a while clause, which causes early exit from the iteration when a condition is encountered.

      See 4.13.6 While Clause

    57. PR 985 

      With the lookup arrow expression and the =?> operator, a function in a map can be looked up and called with the map as first argument.

      See 4.23.3 Lookup Arrow Expressions

    58. PR 996 

      The value of a predicate in a filter expression can now be a sequence of integers.

      See 4.4 Filter Expressions

    59. PR 1031 

      An otherwise operator is introduced: A otherwise B returns the value of A, unless it is an empty sequence, in which case it returns the value of B.

      See 4.17 Otherwise Expressions

    60. PR 1071 

      In map constructors, the keyword map is now optional, so map { 0: false(), 1: true() } can now be written { 0: false(), 1: true() }, provided it is used in a context where this creates no ambiguity.

      See 4.14.1.1 Map Constructors

    61. PR 1125 

      Lookup expressions can now take a modifier (such as keys, values, or pairs) enabling them to return structured results rather than a flattened sequence.

      See 4.14.3 Lookup Expressions

    62. PR 1131 

      A positional variable can be defined in a for expression.

      See 4.13.11 For Expressions

      The type of a variable used in a for expression can be declared.

      See 4.13.11 For Expressions

      The type of a variable used in a let expression can be declared.

      See 4.13.12 Let Expressions

    63. PR 1132 

      Choice item types (an item type allowing a set of alternative item types) are introduced.

      See 3.2.5 Choice Item Types

    64. PR 1163 

      Filter expressions for maps and arrays are introduced.

      See 4.14.4 Filter Expressions for Maps and Arrays

    65. PR 1181 

      The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.

      See 2.2.1 Static Context

      If the default namespace for elements and types has the special value ##any, then an unprefixed name in a NameTest acts as a wildcard, matching names in any namespace or none.

      See 4.6.4.2 Node Tests

      The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.

      See 5.14 Default Namespace Declaration

    66. PR 1197 

      The keyword fn is allowed as a synonym for function in function types, to align with changes to inline function declarations.

      See 3.2.8.1 Function Types

      In inline function expressions, the keyword function may be abbreviated as fn.

      See 4.5.2.5 Inline Function Expressions

    67. PR 1212 

      XQuery and XPath 3.0 included empty-sequence and item as reserved function names, and XQuery and XPath 3.1 added map and array. This was unnecessary since these names never appear followed by a left parenthesis at the start of an expression. They have therefore been removed from the list. New keywords introducing item types, such as record and enum, have not been included in the list.

      See A.4 Reserved Function Names

    68. PR 1249 

      A for key/value clause is added to FLWOR expressions to allow iteration over a map.

      See 4.13.2 For Clause

      A for key/value clause is added to FLWOR expressions to allow iteration over maps.

      See 4.13.11 For Expressions

    69. PR 1250 

      Several decimal format properties, including minus sign, exponent separator, percent, and per-mille, can now be rendered as arbitrary strings rather than being confined to a single character.

      See 2.2.1.2 Decimal Formats

      See 5.10 Decimal Format Declaration

    70. PR 1254 

      The rules concerning the interpretation of xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes have been tightened up.

      See 4.24 Validate Expressions

    71. PR 1265 

      The rules regarding the document-uri property of nodes returned by the fn:collection function have been relaxed.

      See 2.2.2 Dynamic Context

    72. PR 1344 

      Parts of the static context that were there purely to assist in static typing, such as the statically known documents, were no longer referenced and have therefore been dropped.

      See 2.2.1 Static Context

      The static typing option has been dropped.

      See 2.3 Processing Model

    73. PR 1361 

      The term atomic value has been replaced by atomic item.

      See 2.1.2 Values

    74. PR 1384 

      If a type declaration is present, the supplied values in the input sequence are now coerced to the required type. Type declarations are now permitted in XPath as well as XQuery.

      See 4.19 Quantified Expressions

    75. PR 1432 

      In earlier versions, the static context for the initializing expression excluded the variable being declared. This restriction has been lifted.

      See 5.16 Variable Declaration

    76. PR 1480 

      When the element name matches a language keyword such as div or value, it must now be written in quotes as a string literal. This is a backwards incompatible change.

      See 4.12.3.1 Computed Element Constructors

      When the attribute name matches a language keyword such as by or of, it must now be written in quotes as a string literal. This is a backwards incompatible change.

      See 4.12.3.2 Computed Attribute Constructors

    77. PR 1498 

      The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.

      See 2.1 Terminology

      The EBNF notation has been extended to allow the constructs (A ++ ",") (one or more occurrences of A, comma-separated, and (A ** ",") (zero or more occurrences of A, comma-separated.

      See 2.1.1 Grammar Notation

      The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.

      See A.1 EBNF

      See A.1.1 Notation

    78. PR 1513 

      When the processing instruction name matches a language keyword such as try or validate, it must now be written in quotes as a string literal. This is a backwards incompatible change.

      See 4.12.3.5 Computed Processing Instruction Constructors

      When the namespace prefix matches a language keyword such as as or at, it must now be written in quotes as a string literal. This is a backwards incompatible change.

      See 4.12.3.7 Computed Namespace Constructors

    79. PR 1703 

      Ordered maps are introduced.

      See 4.14.1 Maps

      The order of key-value pairs in the map constructor is now retained in the constructed map.

      See 4.14.1.1 Map Constructors

    \ No newline at end of file diff --git a/pr/1703/xquery-40/shared-40-diff.html b/pr/1703/xquery-40/shared-40-diff.html index 7c3167777..68d7c7d2f 100644 --- a/pr/1703/xquery-40/shared-40-diff.html +++ b/pr/1703/xquery-40/shared-40-diff.html @@ -22,7 +22,7 @@

    XQuery 4.0 and XPath 4.0 WG Review Draft

    -

    W3C Editor's Draft 14 January 2025

    +

    W3C Editor's Draft 15 January 2025

    This version:
    @@ -22942,7 +22942,7 @@

    4.14.1

    Changes in 4.0  

    1. -

      Ordered maps are introduced.  [Issue 564 PR 1609 25 November 2024]

      +

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

    @@ -22962,22 +22962,11 @@

    4.14.1 see Section 17 MapsFO.

    Note:

    -

    Maps in XQuery 4.0 and XPath 4.0 have a property called [TERMDEF dt-map-ordered IN DM40], - which takes the value true or false; a map - is accordingly said to be ordered or unordered. +

    Maps in XQuery 4.0 and XPath 4.0 are ordered. The effect of this property is explained - in Section 2.9.5 Map ItemsDM. In summary:

    -
      -
    • -

      In an unordered map, the order of entries - in the map is implementation dependent; it may, for example, - be the result of a randomized hashing algorithm.

      -
    • -
    • -

      In an ordered map, the order of entries is predictable + in Section 2.9.5 Map ItemsDM. + In an ordered map, the order of entries is predictable and depends on the order in which they were added to the map.

      -
    • -
    @@ -22994,7 +22983,7 @@
    4.14.1.1
  • The order of key-value - pairs in the map constructor is now retained in the constructed map.  [Issue 564 PR 1609 25 November 2024]

    + pairs in the map constructor is now retained in the constructed map.  [Issue 1651 PR 1703 14 January 2025]

  • @@ -23150,7 +23139,7 @@

    4.14.1.1
    -
    Example: Constructing a fixed map
    +
    Example: Constructing a fixed map

    The following expression constructs a map with seven entries:

     {
    @@ -23167,7 +23156,7 @@ 
    4.14.1.1  

    -
    Example: Constructing nested maps
    +
    Example: Constructing nested maps

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

     
    @@ -24060,7 +24049,7 @@ 
    4.14.3.2 - [165]    + [165]    Modifier    ::=    "pairs" | "keys" | "values" | "items" @@ -24071,7 +24060,7 @@
    4.14.3.2 - [166]    + [166]    KeySpecifier    ::=    @@ -24086,7 +24075,7 @@
    4.14.3.2 - [167]    + [167]    LookupWildcard    ::=    "*" @@ -24440,7 +24429,7 @@
    4.14.3.3 -
    Example: Comparison with JSONPath
    +
    Example: Comparison with JSONPath

    This example provides XPath equivalents to some examples given in the JSONPath specification. [TODO: add a reference].

    The examples query the result of parsing the following JSON value, representing @@ -24766,15 +24755,14 @@

    4.14.4 entry orderDM), and the context size is the number of entries in the map. The result of the expression is a map containing those entries of the input map for which the predicate truth value of the FILTER expression is true. - The ordered property of the result is the same as the ordered - property of the input map, and in the case of an ordered map, the relative order of - entries in the result retains the relative order of entries in the input. + The relative order of entries in the result retains the relative order of entries in the input.

    For example, the following expression:

    @@ -24942,7 +24928,7 @@

    4.15 - [40]    + [40]    EnclosedExpr    ::=    "{" Expr? "}" @@ -25070,7 +25056,7 @@

    4.16 - [40]    + [40]    EnclosedExpr    ::=    "{" Expr? "}" @@ -25544,7 +25530,7 @@

    4.19 - [227]    + [227]    TypeDeclaration    ::=    "as" SequenceType @@ -25792,7 +25778,7 @@

    4.20 - [107]    + [107]    NameTestUnion    ::=    (NameTest ++ "|") @@ -25803,7 +25789,7 @@

    4.20 - [151]    + [151]    NameTest    ::=    @@ -25818,7 +25804,7 @@

    4.20 - [40]    + [40]    EnclosedExpr    ::=    "{" Expr? "}" @@ -26394,7 +26380,7 @@

    4.21.3 - [263]    + [263]    ChoiceItemType    ::=    "(" (ItemType ++ "|") ")" @@ -26405,7 +26391,7 @@

    4.21.3 - [259]    + [259]    EnumerationType    ::=    "enum" "(" (StringLiteral ++ ",") ")" @@ -26547,7 +26533,7 @@

    4.21.4 - [245]    + [245]    CastTarget    ::=    @@ -26562,7 +26548,7 @@

    4.21.4 - [263]    + [263]    ChoiceItemType    ::=    "(" (ItemType ++ "|") ")" @@ -26573,7 +26559,7 @@

    4.21.4 - [259]    + [259]    EnumerationType    ::=    "enum" "(" (StringLiteral ++ ",") ")" @@ -27075,7 +27061,7 @@

    4.23 - [211]    + [211]    InlineFunctionExpr    ::=    @@ -27090,7 +27076,7 @@

    4.23 - [156]    + [156]    ArgumentList    ::=    "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")" @@ -27101,7 +27087,7 @@

    4.23 - [157]    + [157]    PositionalArgumentList    ::=    "(" PositionalArguments? ")" @@ -27421,7 +27407,7 @@

    4.24 - [40]    + [40]    EnclosedExpr    ::=    "{" Expr? "}" @@ -28851,7 +28837,7 @@

    5.12 -
    Example: Schema Information and Module Import
    +
    Example: Schema Information and Module Import

    A module import does not import schema definitions from the imported module. In the following query, the type geometry:triangle is not defined, even if it is known in the imported module, so the variable declaration raises an error [err:XPST0051]:

    @@ -29209,7 +29195,7 @@

    5.15 - [211]    + [211]    InlineFunctionExpr    ::=    @@ -29349,7 +29335,7 @@

    5.16 - [27]    + [27]    AnnotatedDecl    ::=    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl) @@ -29360,7 +29346,7 @@

    5.16 - [28]    + [28]    Annotation    ::=    "%" EQName ("(" (AnnotationValue ++ ",") ")")? @@ -29382,7 +29368,7 @@

    5.16 - [58]    + [58]    VarNameAndType    ::=    "$" EQName @@ -29395,7 +29381,7 @@

    5.16 - [57]    + [57]    VarName    ::=    "$" EQName @@ -29408,7 +29394,7 @@

    5.16 - [227]    + [227]    TypeDeclaration    ::=    "as" SequenceType @@ -29832,7 +29818,7 @@

    5.18 - [27]    + [27]    AnnotatedDecl    ::=    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl) @@ -29843,7 +29829,7 @@

    5.18 - [28]    + [28]    Annotation    ::=    "%" EQName ("(" (AnnotationValue ++ ",") ")")? @@ -29917,7 +29903,7 @@

    5.18 - [227]    + [227]    TypeDeclaration    ::=    "as" SequenceType @@ -29930,7 +29916,7 @@

    5.18 - [40]    + [40]    EnclosedExpr    ::=    "{" Expr? "}" @@ -29950,7 +29936,7 @@

    5.18 -
    Example: Using a function, prepare a summary of employees that are located in Denver.
    +
    Example: Using a function, prepare a summary of employees that are located in Denver.
    declare function local:summary($emps as element(employee)*) as element(dept)* { 
    @@ -30227,7 +30213,7 @@ 

    5.18.6 -
    Example: A recursive function to compute the maximum depth of a document
    +
    Example: A recursive function to compute the maximum depth of a document

    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 @@ -30264,7 +30250,7 @@

    5.19 - [27]    + [27]    AnnotatedDecl    ::=    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl) @@ -30275,7 +30261,7 @@

    5.19 - [28]    + [28]    Annotation    ::=    "%" EQName ("(" (AnnotationValue ++ ",") ")")? @@ -30416,7 +30402,7 @@

    5.20 - [27]    + [27]    AnnotatedDecl    ::=    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl) @@ -30427,7 +30413,7 @@

    5.20 - [28]    + [28]    Annotation    ::=    "%" EQName ("(" (AnnotationValue ++ ",") ")")? @@ -30462,7 +30448,7 @@

    5.20 - [256]    + [256]    FieldDeclaration    ::=    @@ -30475,7 +30461,7 @@

    5.20 - [257]    + [257]    FieldName    ::=    @@ -44058,7 +44044,7 @@

    L 4.12.3.7 Computed Namespace Constructors

  • -

    PR 1609 

    +

    PR 1703 

    Ordered maps are introduced.

    See 4.14.1 Maps

    The order of key-value diff --git a/pr/1703/xquery-40/shared-40.html b/pr/1703/xquery-40/shared-40.html index 42ee9ff90..a741aac58 100644 --- a/pr/1703/xquery-40/shared-40.html +++ b/pr/1703/xquery-40/shared-40.html @@ -14,7 +14,7 @@

    XQuery 4.0 and XPath 4.0 WG Review Draft

    -

    W3C Editor's Draft 14 January 2025

    +

    W3C Editor's Draft 15 January 2025

    This version:
    @@ -22589,7 +22589,7 @@

    4.14.1

    Changes in 4.0  

    1. -

      Ordered maps are introduced.  [Issue 564 PR 1609 25 November 2024]

      +

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

  • @@ -22609,22 +22609,11 @@

    4.14.1 see Section 17 MapsFO.

    Note:

    -

    Maps in XQuery 4.0 and XPath 4.0 have a property called [TERMDEF dt-map-ordered IN DM40], - which takes the value true or false; a map - is accordingly said to be ordered or unordered. +

    Maps in XQuery 4.0 and XPath 4.0 are ordered. The effect of this property is explained - in Section 2.9.5 Map ItemsDM. In summary:

    -
      -
    • -

      In an unordered map, the order of entries - in the map is implementation dependent; it may, for example, - be the result of a randomized hashing algorithm.

      -
    • -
    • -

      In an ordered map, the order of entries is predictable + in Section 2.9.5 Map ItemsDM. + In an ordered map, the order of entries is predictable and depends on the order in which they were added to the map.

      -
    • -
    @@ -22641,7 +22630,7 @@
    4.14.1.1
  • The order of key-value - pairs in the map constructor is now retained in the constructed map.  [Issue 564 PR 1609 25 November 2024]

    + pairs in the map constructor is now retained in the constructed map.  [Issue 1651 PR 1703 14 January 2025]

  • @@ -22797,7 +22786,7 @@

    4.14.1.1
    -
    Example: Constructing a fixed map
    +
    Example: Constructing a fixed map

    The following expression constructs a map with seven entries:

     {
    @@ -22814,7 +22803,7 @@ 
    4.14.1.1  

    -
    Example: Constructing nested maps
    +
    Example: Constructing nested maps

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

     
    @@ -23703,7 +23692,7 @@ 
    4.14.3.2 - [165]    + [165]    Modifier    ::=    "pairs" | "keys" | "values" | "items" @@ -23714,7 +23703,7 @@
    4.14.3.2 - [166]    + [166]    KeySpecifier    ::=    @@ -23729,7 +23718,7 @@
    4.14.3.2 - [167]    + [167]    LookupWildcard    ::=    "*" @@ -24082,7 +24071,7 @@
    4.14.3.3 -
    Example: Comparison with JSONPath
    +
    Example: Comparison with JSONPath

    This example provides XPath equivalents to some examples given in the JSONPath specification. [TODO: add a reference].

    The examples query the result of parsing the following JSON value, representing @@ -24405,15 +24394,14 @@

    4.14.4 entry orderDM), and the context size is the number of entries in the map. The result of the expression is a map containing those entries of the input map for which the predicate truth value of the FILTER expression is true. - The ordered property of the result is the same as the ordered - property of the input map, and in the case of an ordered map, the relative order of - entries in the result retains the relative order of entries in the input. + The relative order of entries in the result retains the relative order of entries in the input.

    For example, the following expression:

    @@ -24581,7 +24567,7 @@

    4.15 - [40]    + [40]    EnclosedExpr    ::=    "{" Expr? "}" @@ -24706,7 +24692,7 @@

    4.16 - [40]    + [40]    EnclosedExpr    ::=    "{" Expr? "}" @@ -25139,7 +25125,7 @@

    4.19 - [227]    + [227]    TypeDeclaration    ::=    "as" SequenceType @@ -25383,7 +25369,7 @@

    4.20 - [107]    + [107]    NameTestUnion    ::=    (NameTest ++ "|") @@ -25394,7 +25380,7 @@

    4.20 - [151]    + [151]    NameTest    ::=    @@ -25409,7 +25395,7 @@

    4.20 - [40]    + [40]    EnclosedExpr    ::=    "{" Expr? "}" @@ -25981,7 +25967,7 @@

    4.21.3 - [263]    + [263]    ChoiceItemType    ::=    "(" (ItemType ++ "|") ")" @@ -25992,7 +25978,7 @@

    4.21.3 - [259]    + [259]    EnumerationType    ::=    "enum" "(" (StringLiteral ++ ",") ")" @@ -26132,7 +26118,7 @@

    4.21.4 - [245]    + [245]    CastTarget    ::=    @@ -26147,7 +26133,7 @@

    4.21.4 - [263]    + [263]    ChoiceItemType    ::=    "(" (ItemType ++ "|") ")" @@ -26158,7 +26144,7 @@

    4.21.4 - [259]    + [259]    EnumerationType    ::=    "enum" "(" (StringLiteral ++ ",") ")" @@ -26654,7 +26640,7 @@

    4.23 - [211]    + [211]    InlineFunctionExpr    ::=    @@ -26669,7 +26655,7 @@

    4.23 - [156]    + [156]    ArgumentList    ::=    "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")" @@ -26680,7 +26666,7 @@

    4.23 - [157]    + [157]    PositionalArgumentList    ::=    "(" PositionalArguments? ")" @@ -26964,7 +26950,7 @@

    4.24 - [40]    + [40]    EnclosedExpr    ::=    "{" Expr? "}" @@ -28373,7 +28359,7 @@

    5.12 -
    Example: Schema Information and Module Import
    +
    Example: Schema Information and Module Import

    A module import does not import schema definitions from the imported module. In the following query, the type geometry:triangle is not defined, even if it is known in the imported module, so the variable declaration raises an error [err:XPST0051]:

    @@ -28727,7 +28713,7 @@

    5.15 - [211]    + [211]    InlineFunctionExpr    ::=    @@ -28861,7 +28847,7 @@

    5.16 - [27]    + [27]    AnnotatedDecl    ::=    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl) @@ -28872,7 +28858,7 @@

    5.16 - [28]    + [28]    Annotation    ::=    "%" EQName ("(" (AnnotationValue ++ ",") ")")? @@ -28894,7 +28880,7 @@

    5.16 - [58]    + [58]    VarNameAndType    ::=    "$" EQName @@ -28907,7 +28893,7 @@

    5.16 - [57]    + [57]    VarName    ::=    "$" EQName @@ -28920,7 +28906,7 @@

    5.16 - [227]    + [227]    TypeDeclaration    ::=    "as" SequenceType @@ -29337,7 +29323,7 @@

    5.18 - [27]    + [27]    AnnotatedDecl    ::=    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl) @@ -29348,7 +29334,7 @@

    5.18 - [28]    + [28]    Annotation    ::=    "%" EQName ("(" (AnnotationValue ++ ",") ")")? @@ -29422,7 +29408,7 @@

    5.18 - [227]    + [227]    TypeDeclaration    ::=    "as" SequenceType @@ -29435,7 +29421,7 @@

    5.18 - [40]    + [40]    EnclosedExpr    ::=    "{" Expr? "}" @@ -29454,7 +29440,7 @@

    5.18 -
    Example: Using a function, prepare a summary of employees that are located in Denver.
    +
    Example: Using a function, prepare a summary of employees that are located in Denver.
    declare function local:summary($emps as element(employee)*) as element(dept)* { 
    @@ -29715,7 +29701,7 @@ 

    5.18.6 -
    Example: A recursive function to compute the maximum depth of a document
    +
    Example: A recursive function to compute the maximum depth of a document

    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 @@ -29749,7 +29735,7 @@

    5.19 - [27]    + [27]    AnnotatedDecl    ::=    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl) @@ -29760,7 +29746,7 @@

    5.19 - [28]    + [28]    Annotation    ::=    "%" EQName ("(" (AnnotationValue ++ ",") ")")? @@ -29898,7 +29884,7 @@

    5.20 - [27]    + [27]    AnnotatedDecl    ::=    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl) @@ -29909,7 +29895,7 @@

    5.20 - [28]    + [28]    Annotation    ::=    "%" EQName ("(" (AnnotationValue ++ ",") ")")? @@ -29944,7 +29930,7 @@

    5.20 - [256]    + [256]    FieldDeclaration    ::=    @@ -29957,7 +29943,7 @@

    5.20 - [257]    + [257]    FieldName    ::=    @@ -43459,7 +43445,7 @@

    L 4.12.3.7 Computed Namespace Constructors

  • -

    PR 1609 

    +

    PR 1703 

    Ordered maps are introduced.

    See 4.14.1 Maps

    The order of key-value diff --git a/pr/1703/xquery-40/shared-40.xml b/pr/1703/xquery-40/shared-40.xml index 93d3d8b43..6a44621b8 100644 --- a/pr/1703/xquery-40/shared-40.xml +++ b/pr/1703/xquery-40/shared-40.xml @@ -1,6 +1,6 @@ XQuery 4.0 and XPath 4.0 WG Review Draft

    W3C

    XQuery 4.0 and XPath 4.0 WG Review Draft

    -

    W3C Editor's Draft 14 January 2025

    This version:
    +

    W3C Editor's Draft 15 January 2025

    This version:
    http://www.w3.org/TR/2000/WD-shared-40-20000101/
    Most recent version of XQuery and XPath:
    http://www.w3.org/TR/shared/ @@ -9113,7 +9113,7 @@ item, and can appear as an item in a sequence.

    -

    4.14.1 Maps

    Changes in 4.0  

    1. Ordered maps are introduced.  [Issue 564 PR 1609 25 November 2024]

    +

    4.14.1 Maps

    Changes in 4.0  

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

    [Definition: A map is a function that associates a set of keys with values, resulting in a collection of key / value pairs.] @@ -9125,20 +9125,17 @@ item, and can appear as an item in a sequence.

    Section 2.9.5 Map ItemsDM. For an overview of the functions available for processing maps, - see Section 17 MapsFO.

    Note:

    Maps in XQuery 4.0 and XPath 4.0 have a property called [TERMDEF dt-map-ordered IN DM40], - which takes the value true or false; a map - is accordingly said to be ordered or unordered. + see Section 17 MapsFO.

    Note:

    Maps in XQuery 4.0 and XPath 4.0 are ordered. The effect of this property is explained - in Section 2.9.5 Map ItemsDM. In summary:

    • In an unordered map, the order of entries - in the map is implementation dependent; it may, for example, - be the result of a randomized hashing algorithm.

    • In an ordered map, the order of entries is predictable - and depends on the order in which they were added to the map.

    + in Section 2.9.5 Map ItemsDM. + In an ordered map, the order of entries is predictable + and depends on the order in which they were added to the map.

    4.14.1.1 Map Constructors

    Changes in 4.0  

    1. In map constructors, the keyword map is now optional, so map { 0: false(), 1: true() } can now be written { 0: false(), 1: true() }, provided it is used in a context where this creates no ambiguity.   [Issue 1070 PR 1071 26 March 2024]

    2. The order of key-value - pairs in the map constructor is now retained in the constructed map.  [Issue 564 PR 1609 25 November 2024]

    A map can be created using a MapConstructor.

    [212]   MapConstructor   ::=   "map"? "{" (MapConstructorEntry ** ",") "}"
    "map"? "{" (MapConstructorEntry ** ",") "}"
    [213]   MapConstructorEntry   ::=    + pairs in the map constructor is now retained in the constructed map.  [Issue 1651 PR 1703 14 January 2025]

    A map can be created using a MapConstructor.

    [212]   MapConstructor   ::=   "map"? "{" (MapConstructorEntry ** ",") "}"
    "map"? "{" (MapConstructorEntry ** ",") "}"
    [213]   MapConstructorEntry   ::=    MapKeyExpr ":" MapValueExpr
    MapKeyExpr ":" MapValueExpr @@ -9222,7 +9219,7 @@ item, and can appear as an item in a sequence.

    MapConstructorEntry entries in the input.

    [167]   LookupWildcard   ::=   "*"
    "*"

    Unary lookup is most commonly used in predicates (for example, $map[?name = 'Mike']) or with the simple map operator (for example, avg($maps ! (?price - ?discount))).

    The unary lookup expression ?modifier::KS is defined to be equivalent to the postfix lookup expression .?modifier::KS which has the context value (.) as the implicit first operand. See 4.14.3.1 Postfix Lookup Expressions for the postfix lookup operator.

    Examples:

    "ordered" EnclosedExpr
    [177]   UnorderedExpr   ::=   "unordered" EnclosedExpr
    "unordered" EnclosedExpr -
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    This syntax is retained from earlier versions of XQuery; in XQuery 4.0 it is deprecated and has + [40]   EnclosedExpr   ::=   "{" Expr? "}""{" Expr? "}"

    This syntax is retained from earlier versions of XQuery; in XQuery 4.0 it is deprecated and has no effect.

    The constructs ordered { E } and unordered { E } both return the result of evaluating the expression E.

    Note:

    In addition to ordered and unordered expressions, XQuery provides a function named fn:unordered that operates on any sequence @@ -9982,7 +9977,7 @@ return $map?[?key ge 2]

  • returns:

    "else"  "if"  "("  Expr  ")"  EnclosedExpr
                       [103]   ElseAction   ::=   "else"  EnclosedExpr
                       "else"  EnclosedExpr
    -                  [40]   EnclosedExpr   ::=   "{"  Expr?  "}""{"  Expr?  "}"

    There are two formats with essentially the same semantics.

    4.21.4 Castable

    [120]   CastableExpr   ::=    CastExpr ( "castable" "as" CastTarget "?"? )?
    - CastExpr ( "castable" "as" CastTarget "?"? )?
    [245]   CastTarget   ::=    + CastExpr ( "castable" "as" CastTarget "?"? )?
    [245]   CastTarget   ::=    TypeName | ChoiceItemType | EnumerationType
    TypeName | ChoiceItemType | EnumerationType -
    [263]   ChoiceItemType   ::=   "(" (ItemType ++ "|") ")"
    "(" (ItemType ++ "|") ")"
    [259]   EnumerationType   ::=   "enum" "(" (StringLiteral ++ ",") ")"
    "enum" "(" (StringLiteral ++ ",") ")"

    XQuery 4.0 and XPath 4.0 + [263]   ChoiceItemType   ::=   "(" (ItemType ++ "|") ")""(" (ItemType ++ "|") ")"[259]   EnumerationType   ::=   "enum" "(" (StringLiteral ++ ",") ")""enum" "(" (StringLiteral ++ ",") ")"

    XQuery 4.0 and XPath 4.0 provides an expression that tests whether a given value is castable into a given target type. @@ -10716,11 +10711,11 @@ raised [err:XPDY0050].

    < VarRef | InlineFunctionExpr | ParenthesizedExpr VarRef | InlineFunctionExpr | ParenthesizedExpr - [211]   InlineFunctionExpr   ::=    + [211]   InlineFunctionExpr   ::=    Annotation* ("function" | "fn") FunctionSignature? FunctionBody Annotation* ("function" | "fn") FunctionSignature? FunctionBody - [156]   ArgumentList   ::=   "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")""(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"[157]   PositionalArgumentList   ::=   "(" PositionalArguments? ")""(" PositionalArguments? ")"

    The arrow syntax is particularly helpful when applying multiple + [156]   ArgumentList   ::=   "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")""(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"[157]   PositionalArgumentList   ::=   "(" PositionalArguments? ")""(" PositionalArguments? ")"

    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:

    tokenize((normalize-unicode(upper-case($string))),"\s+")

    In the following reformulation, it is easier to see that the parentheses are balanced:

    $string => upper-case() => normalize-unicode() => tokenize("\s+")

    When the operator is written as =!>, the function @@ -10808,7 +10803,7 @@ return $rectangle =?> area()

    returns the value 240

    4.24 Validate Expressions

    Changes in 4.0  

    1. The rules concerning the interpretation of xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes have been tightened up. -   [Issue 729 PR 1254 8 June 2024]

    [132]   ValidateExpr   ::=   "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    [133]   ValidationMode   ::=   "lax" | "strict"
    "lax" | "strict"
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    A validate expression can be used to validate a +   [Issue 729 PR 1254 8 June 2024]

    [132]   ValidateExpr   ::=   "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    "validate" (ValidationMode | ("type" TypeName))? "{" Expr "}"
    [133]   ValidationMode   ::=   "lax" | "strict"
    "lax" | "strict"
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    A validate expression can be used to validate a document node or an element node with respect to the in-scope schema definitions, using the schema validation process defined in [XML Schema 1.0] or [XML Schema 1.1]. If the operand of a validate expression does not evaluate to @@ -11425,7 +11420,7 @@ return ( module B, and module B imports module C, module A does not have access to the functions and variables declared in module C.

    The keyword "fixed" has no effect when declaring a default function namespace, since there is no mechanism to change the default function namespace within a query module.

    Unprefixed attribute names and variable names are in no namespace.

    -

    5.15 Annotations

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [211]   InlineFunctionExpr   ::=    +

    5.15 Annotations

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [211]   InlineFunctionExpr   ::=    Annotation* ("function" | "fn") FunctionSignature? FunctionBody
    Annotation* ("function" | "fn") FunctionSignature? FunctionBody @@ -11645,11 +11640,11 @@ return $node/xx:bing

    Although the namespace prefixes x   [Issue 189 PR 254 29 November 2022]

  • In earlier versions, the static context for the initializing expression excluded the variable being declared. This restriction has been lifted. -   [Issue 1379 PR 1432 12 September 2024]

  • [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [30]   VarDecl   ::=   "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    [58]   VarNameAndType   ::=   "$" EQName +   [Issue 1379 PR 1432 12 September 2024]

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [30]   VarDecl   ::=   "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    "variable" VarNameAndType ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
    [58]   VarNameAndType   ::=   "$" EQName TypeDeclaration?
    "$" EQName - TypeDeclaration?
    [57]   VarName   ::=   "$" EQName + TypeDeclaration?
    [57]   VarName   ::=   "$" EQName
    "$" EQName -
    [227]   TypeDeclaration   ::=   "as" SequenceType +
    [227]   TypeDeclaration   ::=   "as" SequenceType
    "as" SequenceType
    [31]   VarValue   ::=    ExprSingle @@ -11821,7 +11816,7 @@ declare context value as document-node()* := collection($uri); added to the statically known function definitions of the static context. The associated functions also become available in the dynamically known function definitions - of the dynamic context.

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [34]   FunctionDecl   ::=   "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")/* + of the dynamic context.

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [34]   FunctionDecl   ::=   "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")/* xgc: reserved-function-names */
    "function" EQName "(" ParamListWithDefaults? ")" TypeDeclaration? (FunctionBody | "external")/* xgc: reserved-function-names @@ -11833,15 +11828,15 @@ declare context value as document-node()* := collection($uri); EnclosedExpr
    EnclosedExpr -
    [227]   TypeDeclaration   ::=   "as" SequenceType +
    [227]   TypeDeclaration   ::=   "as" SequenceType
    "as" SequenceType -
    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    A function declaration specifies whether the implementation of the function +

    [40]   EnclosedExpr   ::=   "{" Expr? "}"
    "{" Expr? "}"

    A function declaration specifies whether the implementation of the function is user-defined or external.

    In addition to user-defined functions and external functions, XQuery 4.0 and XPath 4.0 allows anonymous functions to be declared in the body of a query using inline function expressions.

    The following example illustrates the declaration and use of a local function that accepts a sequence of employee elements, summarizes them by department, and returns a sequence of dept elements.

    5.19 Item Type Declarations

    An item type declaration defines a name for an item type. Defining a name for an item type allows it to be referenced by name rather than repeating - the item type designator in full.

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [41]   ItemTypeDecl   ::=   "type" EQName "as" ItemType + the item type designator in full.

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [41]   ItemTypeDecl   ::=   "type" EQName "as" ItemType
    "type" EQName "as" ItemType

    An item type declaration adds a named item type to the in-scope named item types of the containing module. This enables the item type to be referred to using a simple name.

    For example, given the declaration:

    declare type app:invoice as map("xs:string", element(inv:paid-invoice));

    It becomes possible to declare a variable containing a sequence of such items as:

    declare variable $invoices as app:invoice*;

    The definition can also be used within another item type declaration:

    declare type app:overdue-invoices as map("xs:date", app:invoice*);

    If the name of the item type being declared is written as an (unprefixed) NCName, then @@ -12032,11 +12027,11 @@ local:depth(doc("partlist.xml"))

    [TODO: add an example of a used to give names to record types as well as any other item type, named record types as described in this section provide a more concise syntax, plus additional functionality. In particular:

    • Named record types can be recursive.

    • Named record types implicitly create a constructor function that can be used to create instances of the record type.

    • A field in a named record type can be a function that has implicit access to - the record on which it is defined, rather like methods in object-oriented languages.

    The syntax is as follows:

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [42]   NamedRecordTypeDecl   ::=   "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    [43]   ExtendedFieldDeclaration   ::=    + the record on which it is defined, rather like methods in object-oriented languages.

    The syntax is as follows:

    [27]   AnnotatedDecl   ::=   "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    "declare" Annotation* (VarDecl | FunctionDecl | ItemTypeDecl | NamedRecordTypeDecl)
    [28]   Annotation   ::=   "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    "%" EQName ("(" (AnnotationValue ++ ",") ")")?
    [42]   NamedRecordTypeDecl   ::=   "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    "record" EQName "(" (ExtendedFieldDeclaration ** ",") ExtensibleFlag? ")"
    [43]   ExtendedFieldDeclaration   ::=    FieldDeclaration (":=" ExprSingle)?
    - FieldDeclaration (":=" ExprSingle)?
    [256]   FieldDeclaration   ::=    + FieldDeclaration (":=" ExprSingle)?
    [256]   FieldDeclaration   ::=    FieldName "?"? ("as" SequenceType)?
    - FieldName "?"? ("as" SequenceType)?
    [257]   FieldName   ::=    + FieldName "?"? ("as" SequenceType)?
    [257]   FieldName   ::=    NCName | StringLiteral
    NCName | StringLiteral @@ -17418,5 +17413,5 @@ consecutive items drawn from the

    See 4.12.3.5 Computed Processing Instruction Constructors

    When the namespace prefix matches a language keyword such as as or at, it must now be written in quotes as a string literal. This is a backwards incompatible change. -

    See 4.12.3.7 Computed Namespace Constructors

  • PR 1609 

    Ordered maps are introduced.

    See 4.14.1 Maps

    The order of key-value +

    See 4.12.3.7 Computed Namespace Constructors

  • PR 1703 

    Ordered maps are introduced.

    See 4.14.1 Maps

    The order of key-value pairs in the map constructor is now retained in the constructed map.

    See 4.14.1.1 Map Constructors

  • \ No newline at end of file +return $rectangle =?> area()

    returns the value 240.

    An expression such as M =?> N(A, B, C) is evaluated as follows:

    1. The left-hand expression M is evaluated. If the value is an empty sequence, then the result of the expression is an empty sequence. If it is non-empty then it must be a single map: call it $m.

    2. The lookup expression $m?N is evaluated. The result must be a single function item: call it $f.

    3. The dynamic function call $f($m, A, B, C) is evaluated, and the result is returned.

    Any of the above steps can lead to errors:

    1. A type error [err:XPTY0004] is raised if the value of the left hand expression does not match the type map(*)?.

    2. A type error [err:XPTY0004] is raised if the value of the lookup expression $m?N does not match the type function(*), or if the arity of the function is not equal to the number of arguments in the argument list plus one.

    3. An error may occur in evaluating the dynamic function call, for example if the function does not expect a map to be supplied as the first argument.

    5 Conformance

    Changes in 4.0  

    1. Support for higher-order functions is now a mandatory feature (in 3.1 it was optional).   [Issue 205 PR 326 1 February 2023]

    2. The static typing feature has been dropped.   [Issue 1343 ]

    This section defines the conformance criteria for an XPath 4.0 processor. In this section, the following terms are used to indicate the requirement levels defined in [RFC2119]. [Definition: MUST means that the item is an absolute requirement of the specification.] [Definition: MUST NOT means that the item is an absolute prohibition of the specification.] [Definition: MAY means that an item is truly optional.]

    XPath is intended primarily as a component that can be used by other specifications. Therefore, XPath relies on specifications that use it (such as [XPointer] and [XSL Transformations (XSLT) Version 4.0]) to specify conformance criteria for XPath in their respective environments. Specifications that set conformance criteria for their use of XPath MUST NOT change the syntactic or semantic definitions of XPath as given in this specification, except by subsetting and/or compatible extensions.

    If a language is described as an extension of XPath, then every expression that conforms to the XPath grammar MUST behave as described in this specification.

    A XPath 4.0 Grammar

    A.1 EBNF

    Changes in 4.0  

    1. The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.  [Issue 1366 PR 1498]

    The grammar of XPath 4.0 uses the same simple Extended Backus-Naur Form (EBNF) notation as [XML 1.0] with the following differences.

    • The notation XYZ ** "," indicates a sequence of zero or more occurrences of XYZ, with a single comma between adjacent occurrences.

    • The notation XYZ ++ "," indicates a sequence of one or more occurrences of XYZ, with a single comma between adjacent occurrences.

    • All named symbols have a name that begins with an uppercase letter.

    • It adds a notation for referring to productions in external specifications.

    • Comments or extra-grammatical constraints on grammar productions are between '/*' and '*/' symbols.

      • A 'xgc:' prefix is an extra-grammatical constraint, the details of which are explained in A.1.2 Extra-grammatical Constraints

      • A 'ws:' prefix explains the whitespace rules for the production, the details of which are explained in A.3.5 Whitespace Rules

      • A 'gn:' prefix means a 'Grammar Note', and is meant as a clarification for parsing rules, and is explained in A.1.3 Grammar Notes. These notes are not normative.

    The terminal symbols for this grammar include the quoted strings used in the production rules below, and the terminal symbols defined in section A.3.1 Terminal Symbols. The grammar is a little unusual in that parsing and tokenization are somewhat intertwined: for more details see A.3 Lexical structure.

    The EBNF notation is described in more detail in A.1.1 Notation.

    AbbrevForwardStep::=("@" NodeTest) | SimpleNodeTest
    AbbrevReverseStep::=".."
    AdditiveExpr::=MultiplicativeExpr ( ("+" | "-") MultiplicativeExpr )*
    AndExpr::=ComparisonExpr ( "and" ComparisonExpr )*
    AnyArrayType::="array" "(" "*" ")"
    AnyFunctionType::=("function" | "fn") "(" "*" ")"
    AnyItemTest::="item" "(" ")"
    AnyKindTest::="node" "(" ")"
    AnyMapType::="map" "(" "*" ")"
    AnyRecordType::="record" "(" "*" ")"
    Argument::=ExprSingle | ArgumentPlaceholder
    ArgumentList::="(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    ArgumentPlaceholder::="?"
    ArrayConstructor::=SquareArrayConstructor | CurlyArrayConstructor
    ArrayType::=AnyArrayType | TypedArrayType
    ArrowDynamicFunction::=VarRef | InlineFunctionExpr | ParenthesizedExpr
    ArrowExpr::=UnaryExpr ( (SequenceArrowTarget | MappingArrowTarget | LookupArrowTarget) )*
    ArrowStaticFunction::=EQName
    ArrowTarget::=(ArrowStaticFunctionArgumentList) | (ArrowDynamicFunctionPositionalArgumentList)
    AttributeName::=EQName
    AttributeTest::="attribute" "(" (NameTestUnion ("," TypeName)?)? ")"
    AxisStep::=(ReverseStep | ForwardStep) Predicate*
    BracedActions::=ThenActionElseIfAction* ElseAction?
    CastableExpr::=CastExpr ( "castable" "as" CastTarget "?"? )?
    CastExpr::=ArrowExpr ( "cast" "as" CastTarget "?"? )?
    CastTarget::=TypeName | ChoiceItemType | EnumerationType
    ChoiceItemType::="(" (ItemType ++ "|") ")"
    CommentTest::="comment" "(" ")"
    ComparisonExpr::=OtherwiseExpr ( (ValueComp
    | GeneralComp
    | NodeComp) OtherwiseExpr )?
    ContextValueRef::="."
    CurlyArrayConstructor::="array" EnclosedExpr
    DocumentTest::="document-node" "(" (ElementTest | SchemaElementTest | NameTestUnion)? ")"
    DynamicFunctionCall::=PostfixExprPositionalArgumentList
    ElementName::=EQName
    ElementTest::="element" "(" (NameTestUnion ("," TypeName "?"?)?)? ")"
    ElseAction::="else" EnclosedExpr
    ElseIfAction::="else" "if" "(" Expr ")" EnclosedExpr
    EnclosedExpr::="{" Expr? "}"
    EnumerationType::="enum" "(" (StringLiteral ++ ",") ")"
    EQName::=QName | URIQualifiedName
    Expr::=(ExprSingle ++ ",")
    ExprSingle::=ForExpr
    | LetExpr
    | QuantifiedExpr
    | IfExpr
    | OrExpr
    ExtensibleFlag::="," "*"
    FieldDeclaration::=FieldName "?"? ("as" SequenceType)?
    FieldName::=NCName | StringLiteral
    FilterExpr::=PostfixExprPredicate
    FilterExprAM::=PostfixExpr "?[" Expr "]"
    ForBinding::=ForItemBinding | ForMemberBinding | ForEntryBinding
    ForClause::="for" (ForBinding ++ ",")
    ForEntryBinding::=((ForEntryKeyBindingForEntryValueBinding?) | ForEntryValueBinding) PositionalVar? "in" ExprSingle
    ForEntryKeyBinding::="key" VarNameAndType
    ForEntryValueBinding::="value" VarNameAndType
    ForExpr::=ForClauseForLetReturn
    ForItemBinding::=VarNameAndTypePositionalVar? "in" ExprSingle
    ForLetReturn::=ForExpr | LetExpr | ("return" ExprSingle)
    ForMemberBinding::="member" VarNameAndTypePositionalVar? "in" ExprSingle
    ForwardAxis::=("attribute"
    | "child"
    | "descendant"
    | "descendant-or-self"
    | "following"
    | "following-or-self"
    | "following-sibling"
    | "following-sibling-or-self"
    | "namespace"
    | "self") "::"
    ForwardStep::=(ForwardAxisNodeTest) | AbbrevForwardStep
    FunctionBody::=EnclosedExpr
    FunctionCall::=EQNameArgumentList
    /* xgc: reserved-function-names */
    /* gn: parens */
    FunctionItemExpr::=NamedFunctionRef | InlineFunctionExpr
    FunctionSignature::="(" ParamList ")" TypeDeclaration?
    FunctionType::=AnyFunctionType
    | TypedFunctionType
    GeneralComp::="=" | "!=" | "<" | "<=" | ">" | ">="
    IfExpr::="if" "(" Expr ")" (UnbracedActions | BracedActions)
    InlineFunctionExpr::=("function" | "fn") FunctionSignature? FunctionBody
    InstanceofExpr::=TreatExpr ( "instance" "of" SequenceType )?
    IntersectExceptExpr::=InstanceofExpr ( ("intersect" | "except") InstanceofExpr )*
    ItemType::=AnyItemTest | TypeName | KindTest | FunctionType | MapType | ArrayType | RecordType | EnumerationType | ChoiceItemType
    KeySpecifier::=NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard
    KeywordArgument::=EQName ":=" Argument
    KeywordArguments::=(KeywordArgument ++ ",")
    KindTest::=DocumentTest
    | ElementTest
    | AttributeTest
    | SchemaElementTest
    | SchemaAttributeTest
    | PITest
    | CommentTest
    | TextTest
    | NamespaceNodeTest
    | AnyKindTest
    LetBinding::=VarNameAndType ":=" ExprSingle
    LetClause::="let" (LetBinding ++ ",")
    LetExpr::=LetClauseForLetReturn
    Literal::=NumericLiteral | StringLiteral
    Lookup::=("?" | "??") (Modifier "::")? KeySpecifier
    LookupArrowTarget::="=?>" NCNamePositionalArgumentList
    LookupExpr::=PostfixExprLookup
    LookupWildcard::="*"
    MapConstructor::="map"? "{" (MapConstructorEntry ** ",") "}"
    MapConstructorEntry::=MapKeyExpr ":" MapValueExpr
    MapKeyExpr::=ExprSingle
    MappingArrowTarget::="=!>" ArrowTarget
    MapType::=AnyMapType | TypedMapType
    MapValueExpr::=ExprSingle
    Modifier::="pairs" | "keys" | "values" | "items"
    MultiplicativeExpr::=UnionExpr ( ("*" | "×" | "div" | "÷" | "idiv" | "mod") UnionExpr )*
    NamedFunctionRef::=EQName "#" IntegerLiteral
    /* xgc: reserved-function-names */
    NamespaceNodeTest::="namespace-node" "(" ")"
    NameTest::=EQName | Wildcard
    NameTestUnion::=(NameTest ++ "|")
    NodeComp::="is" | "<<" | ">>"
    NodeTest::=UnionNodeTest | SimpleNodeTest
    NumericLiteral::=IntegerLiteral | HexIntegerLiteral | BinaryIntegerLiteral | DecimalLiteral | DoubleLiteral
    OccurrenceIndicator::="?" | "*" | "+"
    /* xgc: occurrence-indicators */
    OrExpr::=AndExpr ( "or" AndExpr )*
    OtherwiseExpr::=StringConcatExpr ( "otherwise" StringConcatExpr )*
    ParamList::=(VarNameAndType ** ",")
    ParenthesizedExpr::="(" Expr? ")"
    PathExpr::=("/" RelativePathExpr?)
    | ("//" RelativePathExpr)
    | RelativePathExpr
    /* xgc: leading-lone-slash */
    PITest::="processing-instruction" "(" (NCName | StringLiteral)? ")"
    PositionalArgumentList::="(" PositionalArguments? ")"
    PositionalArguments::=(Argument ++ ",")
    PositionalVar::="at" VarName
    PostfixExpr::=PrimaryExpr | FilterExpr | DynamicFunctionCall | LookupExpr | FilterExprAM
    Predicate::="[" Expr "]"
    PrimaryExpr::=Literal
    | VarRef
    | ParenthesizedExpr
    | ContextValueRef
    | FunctionCall
    | FunctionItemExpr
    | MapConstructor
    | ArrayConstructor
    | StringTemplate
    | UnaryLookup
    QuantifiedExpr::=("some" | "every") QuantifierBinding ("," QuantifierBinding)* "satisfies" ExprSingle
    QuantifierBinding::=VarNameAndType "in" ExprSingle
    RangeExpr::=AdditiveExpr ( "to" AdditiveExpr )?
    RecordType::=AnyRecordType | TypedRecordType
    RelativePathExpr::=StepExpr (("/" | "//") StepExpr)*
    ReverseAxis::=("ancestor"
    | "ancestor-or-self"
    | "parent"
    | "preceding"
    | "preceding-or-self"
    | "preceding-sibling-or-self") "::"
    ReverseStep::=(ReverseAxisNodeTest) | AbbrevReverseStep
    SchemaAttributeTest::="schema-attribute" "(" AttributeName ")"
    SchemaElementTest::="schema-element" "(" ElementName ")"
    SequenceArrowTarget::="=>" ArrowTarget
    SequenceType::=("empty-sequence" "(" ")")
    | (ItemTypeOccurrenceIndicator?)
    SimpleMapExpr::=PathExpr ("!" PathExpr)*
    SimpleNodeTest::=KindTest | NameTest
    SquareArrayConstructor::="[" (ExprSingle ** ",") "]"
    StepExpr::=PostfixExpr | AxisStep
    StringConcatExpr::=RangeExpr ( "||" RangeExpr )*
    StringTemplate::="`" (StringTemplateFixedPart | StringTemplateVariablePart)* "`"
    /* ws: explicit */
    StringTemplateFixedPart::=((Char - ('{' | '}' | '`')) | "{{" | "}}" | "``")*
    /* ws: explicit */
    StringTemplateVariablePart::=EnclosedExpr
    /* ws: explicit */
    TextTest::="text" "(" ")"
    ThenAction::=EnclosedExpr
    TreatExpr::=CastableExpr ( "treat" "as" SequenceType )?
    TypedArrayType::="array" "(" SequenceType ")"
    TypeDeclaration::="as" SequenceType
    TypedFunctionType::=("function" | "fn") "(" (SequenceType ** ",") ")" "as" SequenceType
    TypedMapType::="map" "(" ItemType "," SequenceType ")"
    TypedRecordType::="record" "(" (FieldDeclaration ** ",") ExtensibleFlag? ")"
    TypeName::=EQName
    UnaryExpr::=("-" | "+")* ValueExpr
    UnaryLookup::=("?" | "??") (Modifier "::")? KeySpecifier
    UnbracedActions::="then" ExprSingle "else" ExprSingle
    UnionExpr::=IntersectExceptExpr ( ("union" | "|") IntersectExceptExpr )*
    UnionNodeTest::="(" SimpleNodeTest ("|" SimpleNodeTest)* ")"
    ValueComp::="eq" | "ne" | "lt" | "le" | "gt" | "ge"
    ValueExpr::=SimpleMapExpr
    VarName::="$" EQName
    VarNameAndType::="$" EQNameTypeDeclaration?
    VarRef::="$" EQName
    Wildcard::="*"
    | (NCName ":*")
    | ("*:" NCName)
    | (BracedURILiteral "*")
    /* ws: explicit */
    XPath::=Expr

    A.1.1 Notation

    Changes in 4.0  

    1. The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.  [Issue 1366 PR 1498]

    [Definition: Each rule in the grammar defines one symbol, using the following format:

    symbol ::= expression

    ]

    [Definition: A terminal is a symbol or string or pattern that can appear in the right-hand side of a rule, but never appears on the left-hand side in the main grammar, although it may appear on the left-hand side of a rule in the grammar for terminals.] The following constructs are used to match strings of one or more characters in a terminal:

    [a-zA-Z]

    matches any Char with a value in the range(s) indicated (inclusive).

    [abc]

    matches any Char with a value among the characters enumerated.

    [^abc]

    matches any Char with a value not among the characters given.

    "string" or 'string'

    matches the sequence of characters that appear inside the double or single quotation marks.

    [http://www.w3.org/TR/REC-example/#NT-Example]

    matches any string matched by the production defined in the external specification as per the provided reference.

    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, A and B represent (sub-)patterns.

    (A)

    A is treated as a unit and may be combined as described in this list.

    A?

    matches A or nothing; optional A.

    A B

    matches A followed by B. This implicit operator has higher precedence than the choice operator |; thus A B | C D is interpreted as (A B) | (C D).

    A | B

    matches A or B but not both.

    A - B

    matches any string that matches A but does not match B.

    A+

    matches one or more occurrences of A. Concatenation has higher precedence than choice; thus A+ | B+ is identical to (A+) | (B+).

    A*

    matches zero or more occurrences of A. Concatenation has higher precedence than choice; thus A* | B* is identical to (A*) | (B*)

    (A ++ B)

    matches one or more occurrences of A, with one occurrence of B between adjacent occurrences of A. The notation A ++ B is a shorthand for A (B A)*. The construct is always parenthesized to avoid ambiguity, and although in principle B could be any pattern, in practice the notation is used only when it is a simple string literal (typically but not invariably ",").

    For example, (Digit ++ ".") matches 1 or 1.2 or 1.2.3.

    (A ** B)

    matches zero or more occurrences of A, with one occurrence of B between adjacent occurrences of A. The notation A ** B is a shorthand for (A (B A)*)?. The construct is always parenthesized to avoid ambiguity, and although in principle B could be any pattern, in practice the notation is used only when it is a simple string literal (typically but not invariably ",").

    For example, "[" (Digit ** "|") "]" matches [] or [1] or [1|2] or [1|2|3].

    A.1.2 Extra-grammatical Constraints

    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: /* xgc: <id> */.

    Constraint: leading-lone-slash

    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 RelativePathExpr. In some cases, the next terminal after the slash is insufficient to allow a parser to distinguish these two possibilities: a * symbol or a keyword like union could be either an operator or a NameTest. For example, the expression /union/* could be parsed either as (/) union (/*) or as /child::union/child::* (the second interpretation is the one chosen).

    The situation where / is followed by < is a little more complicated. In XPath, this is unambiguous: the < can only indicate one of the operators <, <=, or <<. 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.3 Lexical structure.

    The rule adopted is as follows: if the terminal immediately following a slash can form the start of a RelativePathExpr, then the slash must be the beginning of a PathExpr, not the entirety of it.

    The terminals that can form the start of a RelativePathExpr are: NCName, QName, URIQualifiedName, StringLiteral, NumericLiteral, Wildcard, and StringTemplate; plus @...*$???%([; and in XQuery StringConstructor and DirectConstructor.

    A single slash may be used as the left-hand argument of an operator by parenthesizing it: (/) * 5. The expression 5 * /, on the other hand, is syntactically valid without parentheses.

    Constraint: xml-version

    The version of XML and XML Names (e.g. [XML 1.0] and [XML Names], or [XML 1.1] and [XML Names 1.1]) is implementation-defined. 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.3.5.1 Default Whitespace Handling. Thus prefix : localname is not a syntactically valid lexical QName 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.

    Constraint: reserved-function-names

    Unprefixed function names spelled the same way as language keywords could make the language impossible to parse. For instance, element(foo) could be taken either as a FunctionCall or as an ElementTest. Therefore, an unprefixed function name must not be any of the names in A.4 Reserved Function Names.

    A function named if can be called by binding its namespace to a prefix and using the prefixed form: library:if(foo) instead of if(foo).

    Constraint: occurrence-indicators

    As written, the grammar in A XPath 4.0 Grammar is ambiguous for some forms using the "+", "?" and "*"OccurrenceIndicators. The ambiguity is resolved as follows: these operators are tightly bound to the SequenceType expression, and have higher precedence than other uses of these symbols. Any occurrence of "+", "?" or "*", that follows a sequence type is assumed to be an occurrence indicator, which binds to the last ItemType in the SequenceType.

    Thus, 4 treat as item() + - 5 must be interpreted as (4 treat as item()+) - 5, 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 (4 treat as item()) + -5 surrounds the SequenceType expression with parentheses and leads to the desired interpretation.

    function () as xs:string * is interpreted as function () as (xs:string *), not as (function () as xs:string) *. Parentheses can be used as shown to force the latter interpretation.

    This rule has as a consequence that certain forms which would otherwise be syntactically valid and unambiguous are not recognized: in 4 treat as item() + 5, the "+" is taken as an OccurrenceIndicator, and not as an operator, which means this is not a syntactically valid expression.

    A.1.3 Grammar Notes

    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: /* gn: <id> */.

    Note:

    grammar-note: parens

    Lookahead is required to distinguish a FunctionCall from an EQName or keyword followed by a Comment. For example: address (: this may be empty :) may be mistaken for a call to a function named "address" unless this lookahead is employed. Another example is for (: whom the bell :) $tolls in 3 return $tolls, where the keyword "for" must not be mistaken for a function name.

    grammar-note: comments

    Comments are allowed everywhere that ignorable whitespace is allowed, and the Comment symbol does not explicitly appear on the right-hand side of the grammar (except in its own production). See A.3.5.1 Default Whitespace Handling.

    A comment can contain nested comments, as long as all "(:" and ":)" patterns are balanced, no matter where they occur within the outer comment.

    Note:

    Lexical analysis may typically handle nested comments by incrementing a counter for each "(:" pattern, and decrementing the counter for each ":)" pattern. The comment does not terminate until the counter is back to zero.

    Some illustrative examples:

    • (: commenting out a (: comment :) may be confusing, but often helpful :) is a syntactically valid Comment, since balanced nesting of comments is allowed.

    • "this is just a string :)" is a syntactically valid expression. However, (: "this is just a string :)" :) will cause a syntax error. Likewise, "this is another string (:" is a syntactically valid expression, but (: "this is another string (:" :) will cause a syntax error. It is a limitation of nested comments that literal content can cause unbalanced nesting of comments.

    • for (: set up loop :) $i in $x return $i is syntactically valid, ignoring the comment.

    • 5 instance (: strange place for a comment :) of xs:integer is also syntactically valid.

    A.2 Productions Derived from XML

    Some productions are defined by reference to the XML and XML Names specifications (e.g. [XML 1.0] and [XML Names], or [XML 1.1] and [XML Names 1.1]. A host language may choose 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).

    A host language may choose whether the lexical rules of [XML 1.0] and [XML Names] are followed, or alternatively, the lexical rules of [XML 1.1] and [XML Names 1.1] are followed.

    A.3 Lexical structure

    Changes in 4.0  

    1. 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.   [Issue 327 PR 519 30 May 2023]

    This section describes how an XPath 4.0 text is tokenized prior to parsing.

    All keywords are case sensitive. Keywords are not reserved—that is, any lexical QName may duplicate a keyword except as noted in A.4 Reserved Function Names.

    Tokenizing an input string is a process that follows the following rules:

    • [Definition: An ordinary production rule is a production rule in A.1 EBNF that is not annotated ws:explicit.]

    • [Definition: A literal terminal is a token appearing as a string in quotation marks on the right-hand side of an ordinary production rule.]

      Note:

      Strings that appear in other production rules do not qualify. For example, BracedURILiteral does not quality because it appears only in URIQualifiedName, and "0x" does not qualify because it appears only in HexIntegerLiteral.

      The literal terminals in XPath 4.0 are: !!=#$()*+,...///::::=<<<<===!>=>=?>>>=>>????[@[]{|||}×÷-ancestorancestor-or-selfandarrayasatattributecastcastablechildcommentdescendantdescendant-or-selfdivdocument-nodeelementelseempty-sequenceenumeqeveryexceptfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selfforfunctiongegtidivifininstanceintersectisitemitemskeykeysleletltmapmembermodnamespacenamespace-nodenenodeoforotherwisepairsparentprecedingpreceding-or-selfpreceding-sibling-or-selfprocessing-instructionrecordreturnsatisfiesschema-attributeschema-elementselfsometextthentotreatunionvaluevalues

    • [Definition: A variable terminal is an instance of a production rule that is not itself an ordinary production rule but that is named (directly) on the right-hand side of an ordinary production rule.]

      The variable terminals in XPath 4.0 are: BinaryIntegerLiteralDecimalLiteralDoubleLiteralHexIntegerLiteralIntegerLiteralNCNameQNameStringLiteralStringTemplateURIQualifiedNameWildcard

    • [Definition: A complex terminal is a variable terminal whose production rule references, directly or indirectly, an ordinary production rule.]

      The complex terminals in XPath 4.0 are: StringTemplate

      Note:

      The significance of complex terminals is that at one level, a complex terminal is treated as a single token, but internally it may contain arbitrary expressions that must be parsed using the full EBNF grammar.

    • Tokenization is the process of splitting the supplied input string into a sequence of terminals, where each terminal is either a literal terminal or a variable terminal (which may itself be a complex terminal). Tokenization is done by repeating the following steps:

      1. Starting at the current position, skip any whitespace and comments.

      2. If the current position is not the end of the input, then return the longest literal terminal or variable terminal that can be matched starting at the current position, regardless whether this terminal is valid at this point in the grammar. If no such terminal can be identified starting at the current position, or if the terminal that is identified is not a valid continuation of the grammar rules, then a syntax error is reported.

        Note:

        Here are some examples showing the effect of the longest token rule:

        • The expression map{a:b} is a syntax error. Although there is a tokenization of this string that satisfies the grammar (by treating a and b as separate expressions), this tokenization does not satisfy the longest token rule, which requires that a:b is interpreted as a single QName.

        • The expression 10 div3 is a syntax error. The longest token rule requires that this be interpreted as two tokens ("10" and "div3") even though it would be a valid expression if treated as three tokens ("10", "div", and "3").

        • The expression $x-$y is a syntax error. This is interpreted as four tokens, ("$", "x-", "$", and "y").

        Note:

        The lexical production rules for variable terminals have been designed so that there is minimal need for backtracking. For example, if the next terminal starts with "0x", then it can only be either a HexIntegerLiteral or an error; if it starts with "`" (and not with "```") then it can only be a StringTemplate or an error.

        This convention, together with the rules for whitespace separation of tokens (see A.3.2 Terminal Delimitation) means that the longest-token rule does not normally result in any need for backtracking. For example, suppose that a variable terminal has been identified as a StringTemplate by examining its first few characters. If the construct turns out not to be a valid StringTemplate, an error can be reported without first considering whether there is some shorter token that might be returned instead.

    • Tokenization unambiguously identifies the boundaries of the terminals in the input, and this can be achieved without backtracking or lookahead. However, tokenization does not unambiguously classify each terminal. For example, it might identify the string "div" as a terminal, but it does not resolve whether this is the operator symbol div, or an NCName or QName used as a node test or as a variable or function name. Classification of terminals generally requires information about the grammatical context, and in some cases requires lookahead.

      Note:

      Operationally, classification of terminals may be done either in the tokenizer or the parser, or in some combination of the two. For example, according to the EBNF, the expression "parent::x" is made up of three tokens, "parent", "::", and "x". The name "parent" can be classified as an axis name as soon as the following token "::" is recognized, and this might be done either in the tokenizer or in the parser. (Note that whitespace and comments are allowed both before and after "::".)

    • In the case of a complex terminal, identifying the end of the complex terminal typically involves invoking the parser to process any embedded expressions. Tokenization, as described here, is therefore a recursive process. But other implementations are possible.

    Note:

    Previous versions of this specification included the statement: When tokenizing, the longest possible match that is consistent with the EBNF is used.

    Different processors are known to have interpreted this in different ways. One interpretation, for example, was that the expression 10 div-3 should be split into four tokens (10, div, -, 3) on the grounds that any other tokenization would give a result that was inconsistent with the EBNF grammar. Other processors report a syntax error on this example.

    This rule has therefore been rewritten in version 4.0. Tokenization is now entirely insensitive to the grammatical context; div-3 is recognized as a single token even though this results in a syntax error. For some implementations this may mean that expressions that were accepted in earlier releases are no longer accepted in 4.0.

    A.3.1 Terminal Symbols

    IntegerLiteral::=Digits
    /* ws: explicit */
    HexIntegerLiteral::="0x" HexDigits
    /* ws: explicit */
    BinaryIntegerLiteral::="0b" BinaryDigits
    /* ws: explicit */
    DecimalLiteral::=("." Digits) | (Digits "." Digits?)
    /* ws: explicit */
    DoubleLiteral::=(("." Digits) | (Digits ("." Digits?)?)) [eE] [+-]? Digits
    /* ws: explicit */
    StringLiteral::=AposStringLiteral | QuotStringLiteral
    /* ws: explicit */
    AposStringLiteral::="'" (EscapeApos | [^'])* "'"
    /* ws: explicit */
    QuotStringLiteral::='"' (EscapeQuot | [^"])* '"'
    /* ws: explicit */
    URIQualifiedName::=BracedURILiteralNCName
    /* ws: explicit */
    BracedURILiteral::="Q" "{" [^{}]* "}"
    /* ws: explicit */
    PredefinedEntityRef::="&" ("lt" | "gt" | "amp" | "quot" | "apos") ";"
    /* ws: explicit */
    EscapeQuot::='""'
    /* ws: explicit */
    EscapeApos::="''"
    /* ws: explicit */
    Comment::="(:" (CommentContents | Comment)* ":)"
    /* ws: explicit */
    /* gn: comments */
    CharRef::=[http://www.w3.org/TR/REC-xml#NT-CharRef]XML
    /* xgc: xml-version */
    QName::=[http://www.w3.org/TR/REC-xml-names/#NT-QName]Names
    /* xgc: xml-version */
    NCName::=[http://www.w3.org/TR/REC-xml-names/#NT-NCName]Names
    /* xgc: xml-version */
    Char::=[http://www.w3.org/TR/REC-xml#NT-Char]XML
    /* xgc: xml-version */

    The following symbols are used only in the definition of terminal symbols; they are not terminal symbols in the grammar of A.1 EBNF.

    Digits::=DecDigit ((DecDigit | "_")* DecDigit)?
    /* ws: explicit */
    DecDigit::=[0-9]
    /* ws: explicit */
    HexDigits::=HexDigit ((HexDigit | "_")* HexDigit)?
    /* ws: explicit */
    HexDigit::=[0-9a-fA-F]
    /* ws: explicit */
    BinaryDigits::=BinaryDigit ((BinaryDigit | "_")* BinaryDigit)?
    /* ws: explicit */
    BinaryDigit::=[01]
    /* ws: explicit */
    CommentContents::=(Char+ - (Char* ('(:' | ':)') Char*))
    /* ws: explicit */

    A.3.2 Terminal Delimitation

    XPath 4.0 expressions consist of terminal symbols and symbol separators.

    Literal and variable terminal symbols are of two kinds: delimiting and non-delimiting.

    [Definition: The delimiting terminal symbols are: !!=#$()**:,...::*:::=<<<===!>=>=?>>>=>>????[@[]```{{|||}}×÷AposStringLiteralBracedURILiteral{<-+QuotStringLiteral}///StringLiteral ]

    [Definition: The non-delimiting terminal symbols are: ancestorancestor-or-selfandarrayasatattributecastcastablechildcommentdescendantdescendant-or-selfdivdocument-nodeelementelseempty-sequenceenumeqeveryexceptfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selfforfunctiongegtidivifininstanceintersectisitemitemskeykeysleletltmapmembermodnamespacenamespace-nodenenodeoforotherwisepairsparentprecedingpreceding-or-selfpreceding-sibling-or-selfprocessing-instructionrecordreturnsatisfiesschema-attributeschema-elementselfsometextthentotreatunionvaluevaluesBinaryIntegerLiteralDecimalLiteralDoubleLiteralHexIntegerLiteralIntegerLiteralNCNameQNameURIQualifiedName ]

    [Definition: Whitespace and Comments function as symbol separators. For the most part, they are not mentioned in the grammar, and may occur between any two terminal symbols mentioned in the grammar, except where that is forbidden by the /* ws: explicit */ annotation in the EBNF, or by the /* xgc: xml-version */ annotation.]

    As a consequence of the longest token rule (see A.3 Lexical structure), one or more symbol separators are required between two consecutive terminal symbols T and U (where T precedes U) when any of the following is true:

    A.3.3 Less-Than and Greater-Than Characters

    The operator symbols <, <=, >, >=, <<, >>, =>, =!>, and =?> have alternative representations using the characters U+FF1C (FULL-WIDTH LESS-THAN SIGN, ) and U+FF1E (FULL-WIDTH GREATER-THAN SIGN, ) in place of U+003C (LESS-THAN SIGN, <) and U+003E (GREATER-THAN SIGN, >) . The alternative tokens are respectively , <=, , >=, <<, >>, =>, =!>, and =?>. In order to avoid visual confusion these alternatives are not shown explicitly in the grammar.

    This option is provided to improve the readability of XPath expressions embedded in XML-based host languages such as XSLT; it enables these operators to be depicted using characters that do not require escaping as XML entities or character references.

    A.3.4 End-of-Line Handling

    The host language must specify whether the XPath 4.0 processor normalizes all line breaks on input, before parsing, and if it does so, whether it uses the rules of [XML 1.0] or [XML 1.1].

    Note:

    XML-based host languages such as XSLT and XSD do not normalize line breaks at the XPath level, because it will already have been done by the host XML parser. Use of character or entity references suppresses normalization of line breaks, so the string literal &#x0D; written within an XSLT-hosted XPath expression represents a string containing a single U+000D (CARRIAGE RETURN) character.

    A.3.4.1 XML 1.0 End-of-Line Handling

    For [XML 1.0] processing, all of the following must be translated to a single U+000A (NEWLINE) :

    1. the two-character sequence U+000D (CARRIAGE RETURN) , U+000A (NEWLINE) ;

    2. any U+000D (CARRIAGE RETURN) character that is not immediately followed by U+000A (NEWLINE) .

    A.3.4.2 XML 1.1 End-of-Line Handling

    For [XML 1.1] processing, all of the following must be translated to a single U+000A (NEWLINE) character:

    1. the two-character sequence U+000D (CARRIAGE RETURN) , U+000A (NEWLINE) ;

    2. the two-character sequence U+000D (CARRIAGE RETURN) , U+0085 (NEXT LINE, NEL) ;

    3. the single character U+0085 (NEXT LINE, NEL) ;

    4. the single character U+2028 (LINE SEPARATOR) ;

    5. any U+000D (CARRIAGE RETURN) character that is not immediately followed by U+000A (NEWLINE) or U+0085 (NEXT LINE, NEL) .

    A.3.5 Whitespace Rules

    A.3.5.1 Default Whitespace Handling

    [Definition: A whitespace character is any of the characters defined by [http://www.w3.org/TR/REC-xml/#NT-S].]

    [Definition: Ignorable whitespace consists of any whitespace characters that may occur between terminals, unless these characters occur in the context of a production marked with a ws:explicit annotation, in which case they can occur only where explicitly specified (see A.3.5.2 Explicit Whitespace Handling).] Ignorable whitespace characters are not significant to the semantics of an expression. Whitespace is allowed before the first terminal and after the last terminal of an XPath expression. Whitespace is allowed between any two terminals. Comments may also act as "whitespace" to prevent two adjacent terminals from being recognized as one. Some illustrative examples are as follows:

    • foo- foo results in a syntax error. "foo-" would be recognized as a QName.

    • foo -foo is syntactically equivalent to foo - foo, two QNames separated by a subtraction operator.

    • foo(: This is a comment :)- foo is syntactically equivalent to foo - foo. This is because the comment prevents the two adjacent terminals from being recognized as one.

    • foo-foo 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.

    • 10div 3 results in a syntax error.

    • 10 div3 also results in a syntax error.

    • 10div3 also results in a syntax error.

    A.3.5.2 Explicit Whitespace Handling

    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.

    ws: explicit

    /* ws: explicit */ means that the EBNF notation explicitly notates, with S or otherwise, where whitespace characters are allowed. In productions with the /* ws: explicit */ annotation, A.3.5.1 Default Whitespace Handling does not apply. Comments are not allowed in these productions except where the Comment non-terminal appears.

    A.4 Reserved Function Names

    Changes in 4.0  

    1. XPath 3.0 included empty-sequence and item as reserved function names, and XPath 3.1 added map and array. This was unnecessary since these names never appear followed by a left parenthesis at the start of an expression. They have therefore been removed from the list. New keywords introducing item types, such as record and enum, have not been included in the list.   [Issue 1208 PR 1212 15 May 2024]

    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.

    Names used in KindTests:

    attribute
    comment
    document-node
    element
    namespace-node
    node
    schema-attribute
    schema-element
    processing-instruction
    text

    Names used as syntactic keywords:

    fn
    function
    if
    switch
    typeswitch

    Note:

    Although the keywords switch and typeswitch are not used in XPath, they are considered reserved function names for compatibility with XQuery.

    Note:

    As the language evolves in the future, it may become necessary to reserve additional names. Furthermore, use of common programming terms like return and while 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.

    A.5 Precedence Order (Non-Normative)

    The grammar in A.1 EBNF normatively defines built-in precedence among the operators of XPath. 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.

    #OperatorAssociativity
    1, (comma)either
    2for,let,some, every, ifNA
    3oreither
    4andeither
    5eq, ne, lt, le, gt, ge, =, !=, <, <=, >, >=, is, <<, >>NA
    6otherwiseeither
    7||left-to-right
    8toNA
    9+, - (binary)left-to-right
    10*, div, idiv, modleft-to-right
    11union, |either
    12intersect, exceptleft-to-right
    13instance ofNA
    14treat asNA
    15castable asNA
    16cast asNA
    17=>, =!>, =?>left-to-right
    18-, + (unary)right-to-left
    19!left-to-right
    20/, //left-to-right
    21[ ], ?, ??left-to-right
    22? (unary)NA

    In the "Associativity" column, "either" indicates that all the operators at that level have the associative property (i.e., (A op B) op C is equivalent to A op (B op C)), so their associativity is inconsequential. "NA" (not applicable) indicates that the EBNF does not allow an expression that directly contains multiple operators from that precedence level, so the question of their associativity does not arise.

    Note:

    Parentheses can be used to override the operator precedence in the usual way. Square brackets in an expression such as A[B] 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.

    B Type Promotion and Operator Mapping

    B.1 Type Promotion

    [Definition: Under certain circumstances, an atomic item can be promoted from one type to another.] Type promotion is used in a number of contexts:

    • It forms part of the process described by the coercion rules, invoked for example when a value of one type is supplied as an argument of a function call where the required type of the corresponding function parameter is declared with a different type.

    • It forms part of the process described in B.2 Operator Mapping, which selects the implementation of a binary operator based on the types of the supplied operands.

    • It is invoked (by explicit reference) in a number of other situations, for example when computing an average of a sequence of numeric values (in the fn:avg function).

    In general, type promotion takes a set of one or more atomic items as input, potentially having different types, and selects a single common type to which all the input values can be converted by casting.

    There are three families of atomic types that can be mixed in this way:

    1. Numeric types. This applies when the input contains values of types xs:decimal, xs:float, and xs:double (including types derived from these, such as xs:integer).

      The rules are:

      1. If any of the items is of type xs:double, then all the values are cast to type xs:double.

      2. Otherwise, if any of the items is of type xs:float, then all the values are cast to type xs:float.

      3. Otherwise, no casting takes place: the values remain as xs:decimal.

    2. String types. This applies when the input contains values of types xs:string and xs:anyURI (including types derived from these, such as xs:NCName).

      The rule is that if any of the items is of type xs:string, then all the values are cast to type xs:string.

    3. Binary types. This applies when the input contains values of types xs:hexBinary and xs:base64Binary (including types derived from these).

      The rule is that if any of the items is of type xs:hexBinary, then all the values are cast to type xs:hexBinary.

    B.2 Operator Mapping

    Changes in 4.0 

    1. The operator mapping table has been simplified by removing entries for the operators ne, le, gt, and ge; these are now defined by reference to the rules for the operators eq and lt.

    The operator mapping tables in this section list the combinations of types for which various operators of XPath 4.0 are defined. The operators covered by this appendix are the value comparison operators eq and lt, and the arithmetic operators +, -, *, div, idiv, and mod.

    Other operators (such as and, or, intersect, union, =, ||, and is) are defined directly in the main body of this document, and do not occur in the operator mapping table.

    The operators ne, le, gt, and ge do not occur in the operator mapping table, but are instead defined by the following equivalences:

    • A ne B is equivalent to not(A eq B)

    • A le B is equivalent to A lt B or A eq B

    • A gt B is equivalent to B lt A

    • A ge B is equivalent to B lt A or B eq A

    [Definition: For each operator and valid combination of operand types, the operator mapping tables specify a result type and an expression that invokes an operator function; the operator function implements the semantics of the operator for the given types.] The definitions of the operator functions are given in [XQuery and XPath Functions and Operators 4.0]. The result of an operator may be the raising of an error by its operator function, as defined in [XQuery and XPath Functions and Operators 4.0]. The operator function fully defines the semantics of a given operator for the case where the operands are single atomic items of the types given in the table. For the definition of each operator (including its behavior for empty sequences or sequences of length greater than one), see the descriptive material in the main part of this document.

    If an operator in the operator mapping tables expects an operand of type ET, that operator can be applied to an operand of type AT if type AT can be converted to type ET by a combination of type promotion and subtype substitution. For example, a table entry indicates that the gt operator may be applied to two xs:date operands, returning xs:boolean. Therefore, the gt operator may also be applied to two (possibly different) subtypes of xs:date, also returning xs:boolean.

    [Definition: When referring to a type, the term numeric denotes the types xs:integer, xs:decimal, xs:float, and xs:double which are all member types of the built-in union type xs:numeric.] An operator whose operands and result are designated as numeric might be thought of as representing four operators, one for each of the numeric types. For example, the numeric + operator might be thought of as representing the following four operators:

    OperatorFirst operand typeSecond operand typeResult type
    +xs:integerxs:integerxs:integer
    +xs:decimalxs:decimalxs:decimal
    +xs:floatxs:floatxs:float
    +xs:doublexs:doublexs:double

    A numeric operator may be validly applied to an operand of type AT if type AT can be converted to any of the four numeric types by a combination of type promotion and subtype substitution. If the result type of an operator is listed as numeric, it means "the first type in the ordered list (xs:integer, xs:decimal, xs:float, xs:double) into which all operands can be converted by subtype substitution and type promotion." As an example, suppose that the type hatsize is derived from xs:integer and the type shoesize is derived from xs:float. Then if the + operator is invoked with operands of type hatsize and shoesize, it returns a result of type xs:float. Similarly, if + is invoked with two operands of type hatsize it returns a result of type xs:integer.

    [Definition: In the operator mapping tables, the term Gregorian refers to the types xs:gYearMonth, xs:gYear, xs:gMonthDay, xs:gDay, and xs:gMonth.] For binary operators that accept two Gregorian-type operands, both operands must have the same type (for example, if one operand is of type xs:gDay, the other operand must be of type xs:gDay.)

    [Definition: In the operator mapping tables, the term binary refers to the types xs:hexBinary and xs:base64Binary.] For operators that accept two binary operands, both operands are promoted to type xs:hexBinary.

    Binary Operators
    OperatorType(A)Type(B)FunctionResult type
    A + Bnumericnumericop:numeric-add(A, B)numeric
    A + Bxs:datexs:yearMonthDurationop:add-yearMonthDuration-to-date(A, B)xs:date
    A + Bxs:yearMonthDurationxs:dateop:add-yearMonthDuration-to-date(B, A)xs:date
    A + Bxs:datexs:dayTimeDurationop:add-dayTimeDuration-to-date(A, B)xs:date
    A + Bxs:dayTimeDurationxs:dateop:add-dayTimeDuration-to-date(B, A)xs:date
    A + Bxs:timexs:dayTimeDurationop:add-dayTimeDuration-to-time(A, B)xs:time
    A + Bxs:dayTimeDurationxs:timeop:add-dayTimeDuration-to-time(B, A)xs:time
    A + Bxs:dateTimexs:yearMonthDurationop:add-yearMonthDuration-to-dateTime(A, B)xs:dateTime
    A + Bxs:yearMonthDurationxs:dateTimeop:add-yearMonthDuration-to-dateTime(B, A)xs:dateTime
    A + Bxs:dateTimexs:dayTimeDurationop:add-dayTimeDuration-to-dateTime(A, B)xs:dateTime
    A + Bxs:dayTimeDurationxs:dateTimeop:add-dayTimeDuration-to-dateTime(B, A)xs:dateTime
    A + Bxs:yearMonthDurationxs:yearMonthDurationop:add-yearMonthDurations(A, B)xs:yearMonthDuration
    A + Bxs:dayTimeDurationxs:dayTimeDurationop:add-dayTimeDurations(A, B)xs:dayTimeDuration
    A - Bnumericnumericop:numeric-subtract(A, B)numeric
    A - Bxs:datexs:dateop:subtract-dates(A, B)xs:dayTimeDuration
    A - Bxs:datexs:yearMonthDurationop:subtract-yearMonthDuration-from-date(A, B)xs:date
    A - Bxs:datexs:dayTimeDurationop:subtract-dayTimeDuration-from-date(A, B)xs:date
    A - Bxs:timexs:timeop:subtract-times(A, B)xs:dayTimeDuration
    A - Bxs:timexs:dayTimeDurationop:subtract-dayTimeDuration-from-time(A, B)xs:time
    A - Bxs:dateTimexs:dateTimeop:subtract-dateTimes(A, B)xs:dayTimeDuration
    A - Bxs:dateTimexs:yearMonthDurationop:subtract-yearMonthDuration-from-dateTime(A, B)xs:dateTime
    A - Bxs:dateTimexs:dayTimeDurationop:subtract-dayTimeDuration-from-dateTime(A, B)xs:dateTime
    A - Bxs:yearMonthDurationxs:yearMonthDurationop:subtract-yearMonthDurations(A, B)xs:yearMonthDuration
    A - Bxs:dayTimeDurationxs:dayTimeDurationop:subtract-dayTimeDurations(A, B)xs:dayTimeDuration
    A * Bnumericnumericop:numeric-multiply(A, B)numeric
    A * Bxs:yearMonthDurationnumericop:multiply-yearMonthDuration(A, B)xs:yearMonthDuration
    A * Bnumericxs:yearMonthDurationop:multiply-yearMonthDuration(B, A)xs:yearMonthDuration
    A * Bxs:dayTimeDurationnumericop:multiply-dayTimeDuration(A, B)xs:dayTimeDuration
    A * Bnumericxs:dayTimeDurationop:multiply-dayTimeDuration(B, A)xs:dayTimeDuration
    A × Bnumericnumericop:numeric-multiply(A, B)numeric
    A × Bxs:yearMonthDurationnumericop:multiply-yearMonthDuration(A, B)xs:yearMonthDuration
    A × Bnumericxs:yearMonthDurationop:multiply-yearMonthDuration(B, A)xs:yearMonthDuration
    A × Bxs:dayTimeDurationnumericop:multiply-dayTimeDuration(A, B)xs:dayTimeDuration
    A × Bnumericxs:dayTimeDurationop:multiply-dayTimeDuration(B, A)xs:dayTimeDuration
    A idiv Bnumericnumericop:numeric-integer-divide(A, B)xs:integer
    A div Bnumericnumericop:numeric-divide(A, B)numeric; but xs:decimal if both operands are xs:integer
    A div Bxs:yearMonthDurationnumericop:divide-yearMonthDuration(A, B)xs:yearMonthDuration
    A div Bxs:dayTimeDurationnumericop:divide-dayTimeDuration(A, B)xs:dayTimeDuration
    A div Bxs:yearMonthDurationxs:yearMonthDurationop:divide-yearMonthDuration-by-yearMonthDuration (A, B)xs:decimal
    A div Bxs:dayTimeDurationxs:dayTimeDurationop:divide-dayTimeDuration-by-dayTimeDuration (A, B)xs:decimal
    A ÷ Bnumericnumericop:numeric-divide(A, B)numeric; but xs:decimal if both operands are xs:integer
    A ÷ Bxs:yearMonthDurationnumericop:divide-yearMonthDuration(A, B)xs:yearMonthDuration
    A ÷ Bxs:dayTimeDurationnumericop:divide-dayTimeDuration(A, B)xs:dayTimeDuration
    A ÷ Bxs:yearMonthDurationxs:yearMonthDurationop:divide-yearMonthDuration-by-yearMonthDuration (A, B)xs:decimal
    A ÷ Bxs:dayTimeDurationxs:dayTimeDurationop:divide-dayTimeDuration-by-dayTimeDuration (A, B)xs:decimal
    A mod Bnumericnumericop:numeric-mod(A, B)numeric
    A eq Bnumericnumericop:numeric-equal(A, B)xs:boolean
    A eq Bxs:booleanxs:booleanop:boolean-equal(A, B)xs:boolean
    A eq Bxs:stringxs:stringop:numeric-equal(fn:compare(A, B), 0)xs:boolean
    A eq Bxs:datexs:dateop:date-equal(A, B)xs:boolean
    A eq Bxs:timexs:timeop:time-equal(A, B)xs:boolean
    A eq Bxs:dateTimexs:dateTimeop:dateTime-equal(A, B)xs:boolean
    A eq Bxs:durationxs:durationop:duration-equal(A, B)xs:boolean
    A eq BGregorianGregorianop:gYear-equal(A, B) etc.xs:boolean
    A eq Bbinarybinaryop:binary-equal(A, B)xs:boolean
    A eq Bxs:QNamexs:QNameop:QName-equal(A, B)xs:boolean
    A eq Bxs:NOTATIONxs:NOTATIONop:NOTATION-equal(A, B)xs:boolean
    A lt Bnumericnumericop:numeric-less-than(A, B)xs:boolean
    A lt Bxs:booleanxs:booleanop:boolean-less-than(A, B)xs:boolean
    A lt Bxs:stringxs:stringop:numeric-less-than(fn:compare(A, B), 0)xs:boolean
    A lt Bxs:datexs:dateop:date-less-than(A, B)xs:boolean
    A lt Bxs:timexs:timeop:time-less-than(A, B)xs:boolean
    A lt Bxs:dateTimexs:dateTimeop:dateTime-less-than(A, B)xs:boolean
    A lt Bxs:yearMonthDurationxs:yearMonthDurationop:yearMonthDuration-less-than(A, B)xs:boolean
    A lt Bxs:dayTimeDurationxs:dayTimeDurationop:dayTimeDuration-less-than(A, B)xs:boolean
    A lt Bbinarybinaryop:binary-less-than(A, B)xs:boolean
    Unary Operators
    OperatorOperand typeFunctionResult type
    + Anumericop:numeric-unary-plus(A)numeric
    - Anumericop:numeric-unary-minus(A)numeric

    C Context Components

    The tables in this section describe the scope (range of applicability) of the various components in a module's static context and dynamic context.

    C.1 Static Context Components

    The following table describes the components of the static context. For each component, “global” indicates that the value of the component applies throughout an XPath expression, whereas “lexical” indicates that the value of the component applies only within the subexpression in which it is defined.

    Static Context Components
    ComponentScope
    XPath 1.0 Compatibility Modeglobal
    Statically known namespacesglobal
    Default element/type namespaceglobal
    Default function namespaceglobal
    In-scope schema typesglobal
    In-scope element declarationsglobal
    In-scope attribute declarationsglobal
    In-scope variableslexical; for-expressions, let-expressions, and quantified expressions can bind new variables
    Context value static typelexical
    Statically known function signaturesglobal
    Statically known collationsglobal
    Default collationglobal
    Base URIglobal
    Statically known documentsglobal
    Statically known collectionsglobal
    Statically known default collection typeglobal

    C.2 Dynamic Context Components

    The following table describes how values are assigned to the various components of the dynamic context. All these components are initialized by mechanisms defined by the host language. For each component, “global” indicates that the value of the component remains constant throughout evaluation of the XPath expression, whereas “dynamic” indicates that the value of the component can be modified by the evaluation of subexpressions.

    Dynamic Context Components
    ComponentScope
    Context valuedynamic; changes during evaluation of path expressions and predicates
    Context positiondynamic; changes during evaluation of path expressions and predicates
    Context sizedynamic; changes during evaluation of path expressions and predicates
    Variable valuesdynamic; for-expressions, let-expressions, and quantified expressions can bind new variables
    Current date and timeglobal; must be initialized
    Implicit timezoneglobal; must be initialized
    Available documentsglobal; must be initialized
    Available node collectionsglobal; must be initialized
    Default collectionglobal; overwriteable by implementation
    Available URI collectionsglobal; must be initialized
    Default URI collectionglobal; overwriteable by implementation

    D Implementation-Defined Items

    The following items in this specification are implementation-defined:

    1. The version of Unicode that is used to construct expressions.

    2. The statically-known collations.

    3. The implicit timezone.

    4. The circumstances in which warnings are raised, and the ways in which warnings are handled.

    5. The method by which errors are reported to the external processing environment.

    6. Which version of XML and XML Names (e.g. [XML 1.0] and [XML Names] or [XML 1.1] and [XML Names 1.1]) and which version of XML Schema (e.g. [XML Schema 1.0] or [XML Schema 1.1]) 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).

    7. How XDM instances are created from sources other than an Infoset or PSVI.

    8. Whether the implementation supports the namespace axis.

    9. Whether the type system is based on [XML Schema 1.0] or [XML Schema 1.1]. An implementation that has based its type system on XML Schema 1.0 is not required to support the use of the xs:dateTimeStamp constructor or the use of xs:dateTimeStamp or xs:error as TypeName in any expression.

    10. The signatures of functions provided by the implementation or via an implementation-defined API (see 2.2.1 Static Context).

    11. Any environment variables provided by the implementation.

    12. Any rules used for static typing (see 2.3.3.1 Static Analysis Phase).

    13. Any serialization parameters provided by the implementation

    14. What error, if any, is returned if an external function's implementation does not return the declared result type (see 2.3.6 Consistency Constraints).

    E References

    E.1 Normative References

    RFC2119
    S. Bradner. Key Words for use in RFCs to Indicate Requirement Levels. IETF RFC 2119. See http://www.ietf.org/rfc/rfc2119.txt.
    RFC3986
    T. Berners-Lee, R. Fielding, and L. Masinter. Uniform Resource Identifiers (URI): Generic Syntax. IETF RFC 3986. See http://www.ietf.org/rfc/rfc3986.txt.
    RFC3987
    M. Duerst and M. Suignard. Internationalized Resource Identifiers (IRIs). IETF RFC 3987. See http://www.ietf.org/rfc/rfc3987.txt.
    ISO/IEC 10646
    ISO (International Organization for Standardization). ISO/IEC 10646:2003. Information technology—Universal Multiple-Octet Coded Character Set (UCS), 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 http://www.iso.org for the latest version.)
    Unicode
    The Unicode Consortium. The Unicode Standard. Reading, Mass.: Addison-Wesley, 2003, as updated from time to time by the publication of new versions. See http://www.unicode.org/standard/versions/ 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 implementation-defined, but implementations are recommended to use the latest Unicode version.
    XML 1.0
    World Wide Web Consortium. Extensible Markup Language (XML) 1.0. W3C Recommendation. See http://www.w3.org/TR/REC-xml/. The edition of XML 1.0 must be no earlier than the Third Edition; the edition used is implementation-defined, but we recommend that implementations use the latest version.
    XML 1.1
    World Wide Web Consortium. Extensible Markup Language (XML) 1.1. W3C Recommendation. See http://www.w3.org/TR/xml11/
    XML Base
    World Wide Web Consortium. XML Base. W3C Recommendation. See http://www.w3.org/TR/xmlbase/
    XML Names
    World Wide Web Consortium. Namespaces in XML. W3C Recommendation. See http://www.w3.org/TR/REC-xml-names/
    XML Names 1.1
    World Wide Web Consortium. Namespaces in XML 1.1. W3C Recommendation. See http://www.w3.org/TR/xml-names11/
    XML ID
    World Wide Web Consortium. xml:id Version 1.0. W3C Recommendation. See http://www.w3.org/TR/xml-id/
    XML Schema 1.0
    World Wide Web Consortium. XML Schema, Parts 0, 1, and 2 (Second Edition). W3C Recommendation, 28 October 2004. See http://www.w3.org/TR/xmlschema-0/, http://www.w3.org/TR/xmlschema-1/, and http://www.w3.org/TR/xmlschema-2/.
    XML Schema 1.1
    World Wide Web Consortium. XML Schema, Parts 1, and 2. W3C Recommendation 5 April 2012. See http://www.w3.org/TR/xmlschema11-1/, and http://www.w3.org/TR/xmlschema11-2/.
    XQuery and XPath Data Model (XDM) 4.0
    XQuery and XPath Data Model (XDM) 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
    XQuery and XPath Functions and Operators 4.0
    XQuery and XPath Functions and Operators 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
    XPath 4.0
    XML Path Language (XPath) 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
    XSLT and XQuery Serialization 4.0
    XSLT and XQuery Serialization 4.0, XSLT Extensions Community Group, World Wide Web Consortium.

    E.2 Non-normative References

    XQuery 3.1: An XML Query Language
    XQuery 3.1: An XML Query Language, 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-xquery-31-20170321/. The latest version is available at https://www.w3.org/TR/xquery-31/.
    XQuery 1.0 and XPath 2.0 Formal Semantics
    XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition), Jérôme Siméon, Denise Draper, Peter Frankhauser, et. al., Editors. World Wide Web Consortium, 14 December 2010. This version is https://www.w3.org/TR/2010/REC-xquery-semantics-20101214/. The latest version is available at https://www.w3.org/TR/xquery-semantics/.
    XSL Transformations (XSLT) Version 4.0
    XSL Transformations (XSLT) Version 4.0, XSLT Extensions Community Group, World Wide Web Consortium.
    XML Infoset
    World Wide Web Consortium. XML Information Set (Second Edition). W3C Recommendation 4 February 2004. See http://www.w3.org/TR/xml-infoset/
    XML Path Language (XPath) Version 1.0
    XML Path Language (XPath) Version 1.0, 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 latest version is available at http://www.w3.org/TR/xpath.
    XML Path Language (XPath) Version 2.0
    XML Path Language (XPath) 2.0 (Second Edition), Don Chamberlin, Anders Berglund, Scott Boag, et. al., Editors. World Wide Web Consortium, 14 December 2010. This version is https://www.w3.org/TR/2010/REC-xpath20-20101214/. The latest version is available at https://www.w3.org/TR/xpath20/.
    XML Path Language (XPath) Version 3.0
    XML Path Language (XPath) 3.0, 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 latest version is available at https://www.w3.org/TR/xpath-30/.
    XPointer
    World Wide Web Consortium. XML Pointer Language (XPointer). W3C Last Call Working Draft 8 January 2001. See http://www.w3.org/TR/WD-xptr

    E.3 Background Material

    Character Model
    World Wide Web Consortium. Character Model for the World Wide Web. W3C Working Draft. See http://www.w3.org/TR/charmod/.
    XSL Transformations (XSLT) Version 1.0
    XSL Transformations (XSLT) Version 1.0, James Clark, Editor. World Wide Web Consortium, 16 Nov 1999. This version is http://www.w3.org/TR/1999/REC-xslt-19991116. The latest version is available at http://www.w3.org/TR/xslt.

    F Error Conditions

    err:XPST0001

    It is a static error if analysis of an expression relies on some component of the static context that is absentDM.

    err:XPDY0002

    It is a type error if evaluation of an expression relies on some part of the dynamic context that is absentDM.

    Note:

    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 fn($x) { @code }. The error code is prefixed XPDY rather than XPTY for backwards compatibility reasons.

    err:XPST0003

    It is a static error if an expression is not a valid instance of the grammar defined in A.1 EBNF.

    err:XPTY0004

    It is a type error if, during the static analysis phase, an expression is found to have a static type that is not appropriate for the context in which the expression occurs, or during the dynamic evaluation phase, the dynamic type of a value does not match a required type as specified by the matching rules in 3.1.2 Sequence Type Matching.

    err:XPTY0006

    During the analysis phase, an expression is classified as implausible if the inferred static typeS and the required type R 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.

    err:XPST0008

    It is a static error if an expression refers to an element name, attribute name, schema type name, namespace prefix, or variable name that is not defined in the static context, except for an ElementName in an ElementTest or an AttributeName in an AttributeTest.

    err:XPST0010

    An implementation that does not support the namespace axis must raise a static error if it encounters a reference to the namespace axis and XPath 1.0 compatibility mode is false.

    err:XPST0017

    It is a static error if the expanded QName and number of arguments in a static function call do not match the name and arity range of a function definition in the static context, 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.

    err:XPTY0018

    It is a type error if the result of a path operator contains both nodes and non-nodes.

    err:XPTY0019

    It is a type error if E1 in a path expression E1/E2 does not evaluate to a sequence of nodes.

    err:XPTY0020

    It is a type error if, in an axis step, the context item is not a node.

    err:XPST0021

    It is a static error if two fields in a record declaration have the same name.

    err:XPST0023

    It is a static error 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.

    err:XQST0039

    It is a static error for an inline function expression to have more than one parameter with the same name.

    err:XQST0046

    An implementation MAY raise a static error if the value of a BracedURILiteral is of nonzero length and is neither an absolute URI nor a relative URI.

    err:XPDY0050

    It is a dynamic error if the dynamic type of the operand of a treat expression does not match the sequence type designated by the treat expression. This error might also be raised by a path expression beginning with / or // if the context node is not in a tree that is rooted at a document node. This is because a leading / or // in a path expression is an abbreviation for an initial step that includes the clause treat as document-node().

    err:XPST0051

    It is a static error if an expanded QName used as an ItemType in a SequenceType is not defined in the static context either as a named item type in the in-scope named item types, or as a generalized atomic type in the in-scope schema type.

    err:XQST0052

    The type named in a cast or castable expression must be the name of a type defined in the in-scope schema types, and the type must be simple.

    err:XQST0070

    A static error is raised if any of the following conditions is statically detected in any expression:

    • The prefix xml is bound to some namespace URI other than http://www.w3.org/XML/1998/namespace.

    • A prefix other than xml is bound to the namespace URI http://www.w3.org/XML/1998/namespace.

    • The prefix xmlns is bound to any namespace URI.

    • A prefix other than xmlns is bound to the namespace URI http://www.w3.org/2000/xmlns/.

    err:XPST0080

    It is a static error if the target type of a cast or castable expression is xs:NOTATION, xs:anySimpleType, or xs:anyAtomicType.

    err:XPST0081

    It is a static error if a QName used in an expression contains a namespace prefix that cannot be expanded into a namespace URI by using the statically known namespaces.

    err:XQST0089

    It is a static error if a variable bound in a for expression, and its associated positional variable, do not have distinct names (expanded QNames).

    err:XPTY0117

    When applying the coercion rules, if an item is of type xs:untypedAtomic and the expected type is namespace-sensitive, a type error [err:XPTY0117] is raised.

    err:XPDY0130

    An implementation-dependent limit has been exceeded.

    err:XQST0134

    The namespace axis is not supported.

    err:XQDY0137

    No two keys in a map may have the same key value.

    err:XQST0140

    It is a static error if a named item type declaration is recursive, unless it satisfies the conditions defined in 3.2.8.3.1 Recursive Record Types.

    err:XPTY0141

    In a forexpression, when the keyword member is present, the value of the binding collection must be a single array; and when either or both of the keywords key and value are present, the value of the binding collection must be a single map.

    err:XPTY0144

    During the analysis phase, an axis step is classified as implausible 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.

    err:XPTY0145

    During the analysis phase, a unary or postfix lookup expression is classified as implausible 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.

    err:XPST0152

    It is a static error if a key type named in a TypedMapType is not a generalized atomic type.

    G Glossary (Non-Normative)

    anonymous function

    An anonymous function is a function item with no name. Anonymous functions may be created, for example, by evaluating an inline function expression or by partial function application.

    application function

    Application functions are function definitions written in a host language such as XQuery or XSLT whose syntax and semantics are defined in this family of specifications. Their behavior (including the rules determining the static and dynamic context) follows the rules for such functions in the relevant host language specification.

    argument expression

    An argument to a function call is either an argument expression or an ArgumentPlaceholder (?); in both cases it may either be supplied positionally, or identified by a name (called a keyword).

    arity range

    A function definition has an arity range, which is a range of consecutive non-negative integers. If the function definition has M required parameters and N optional parameters, then its arity range is from M to M+N inclusive.

    array

    An array is a function item that associates a set of positions, represented as positive integer keys, with values.

    associated value

    The value associated with a given key is called the associated value of the key.

    atomic item

    An atomic item is a value in the value space of an atomic type, as defined in [XML Schema 1.0] or [XML Schema 1.1].

    atomic type

    An atomic type is a simple schema type whose {variety}XS11-1 is atomic.

    atomization

    Atomization of a sequence is defined as the result of invoking the fn:data function, as defined in Section 2.1.4 fn:dataFO.

    available documents

    Available documents. This is a mapping of strings to document nodes. Each string represents the absolute URI of a resource. The document node is the root of a tree that represents that resource using the data model. The document node is returned by the fn:doc function when applied to that URI.

    available item collections

    Available collections. This is a mapping of strings to sequences of items. Each string represents the absolute URI of a resource. The sequence of items represents the result of the fn:collection function when that URI is supplied as the argument.

    available text resources

    Available text resources. This is a mapping of strings to text resources. Each string represents the absolute URI of a resource. The resource is returned by the fn:unparsed-text function when applied to that URI.

    available uri collections

    Available URI collections. This is a mapping of strings to sequences of URIs. The string represents the absolute URI of a resource which can be interpreted as an aggregation of a number of individual resources each of which has its own URI. The sequence of URIs represents the result of the fn:uri-collection function when that URI is supplied as the argument.

    axis step

    An axis step returns a sequence of nodes that are reachable from a starting node via a specified axis. Such a step has two parts: an axis, which defines the "direction of movement" for the step, and a node test, which selects nodes based on their kind, name, and/or type annotation .

    binary

    In the operator mapping tables, the term binary refers to the types xs:hexBinary and xs:base64Binary.

    binding collection

    The result of evaluating the binding expression in a for expression is called the binding collection

    choice item type

    A choice item type defines an item type that is the union of a number of alternatives. For example the type (xs:hexBinary | xs:base64Binary) defines the union of these two primitive atomic types, while the type (map(*) | array(*)) matches any item that is either a map or an array.

    coercion rules

    The coercion rules are rules used to convert a supplied value to a required type, for example when converting an argument of a function call to the declared type of the function parameter.

    collation

    A collation is a specification of the manner in which strings and URIs are compared and, by extension, ordered. For a more complete definition of collation, see Section 5.3 Comparison of stringsFO.

    comma operator

    One way to construct a sequence is by using the comma operator, which evaluates each of its operands and concatenates the resulting sequences, in order, into a single result sequence.

    complex terminal

    A complex terminal is a variable terminal whose production rule references, directly or indirectly, an ordinary production rule.

    constructor function

    The constructor function for a given simple type is used to convert instances of other simple types into the given type. The semantics of the constructor function call T($arg) are defined to be equivalent to the expression $arg cast as T?.

    content expression

    In an enclosed expression, the optional expression enclosed in curly brackets is called the content expression.

    context dependent

    A function definition is said to be context dependent if its result depends on the static or dynamic context of its caller. A function definition may be context-dependent for some arities in its arity range, and context-independent for others: for example fn:name#0 is context-dependent while fn:name#1 is context-independent.

    context node

    When the context value is a single item, it can also be referred to as the context item; when it is a single node, it can also be referred to as the context node.

    context position

    The context position is the position of the context value within the series of values currently being processed.

    context size

    The context size is the number of values in the series of values currently being processed.

    context value

    The context value is the value currently being processed.

    current dateTime

    Current dateTime. This information represents an implementation-dependent point in time during the processing of an expression, and includes an explicit timezone. It can be retrieved by the fn:current-dateTime function. If called multiple times during the execution of an expression, this function always returns the same result.

    data model

    XPath 4.0 operates on the abstract, logical structure of an XML document or JSON object rather than its surface syntax. This logical structure, known as the data model, is defined in [XQuery and XPath Data Model (XDM) 4.0].

    decimal-separator

    decimal-separator(M, R) is used to separate the integer part of the number from the fractional part. The default value for both the marker and the rendition is U+002E (FULL STOP, PERIOD, .) .

    default calendar

    Default calendar. This is the calendar used when formatting dates in human-readable output (for example, by the functions fn:format-date and fn:format-dateTime) if no other calendar is requested. The value is a string.

    default collation

    Default collation. This identifies one of the collations in statically known collations as the collation to be used by functions and operators for comparing and ordering values of type xs:string and xs:anyURI (and types derived from them) when no explicit collation is specified.

    default collection

    Default collection. This is the sequence of items that would result from calling the fn:collection function with no arguments.

    default function namespace

    Default function namespace. This is either a namespace URI, or absentDM. The namespace URI, if present, is used for any unprefixed QName appearing in a position where a function name is expected.

    default language

    Default language. This is the natural language used when creating human-readable output (for example, by the functions fn:format-date and fn:format-integer) if no other language is requested. The value is a language code as defined by the type xs:language.

    default namespace for elements and types

    Default namespace for elements and types. This is either a namespace URI, or the special value "##any", or absentDM. This indicates how unprefixed QNames are interpreted when they appear in a position where an element name or type name is expected.

    default place

    Default place. This is a geographical location used to identify the place where events happened (or will happen) when processing dates and times using functions such as fn:format-date, fn:format-dateTime, and fn:civil-timezone, if no other place is specified. It is used when translating timezone offsets to civil timezone names, and when using calendars where the translation from ISO dates/times to a local representation is dependent on geographical location. Possible representations of this information are an ISO country code or an Olson timezone name, but implementations are free to use other representations from which the above information can be derived. The only requirement is that it should uniquely identify a civil timezone, which means that country codes for countries with multiple timezones, such as the United States, are inadequate.

    default URI collection

    Default URI collection. This is the sequence of URIs that would result from calling the fn:uri-collection function with no arguments.

    delimiting terminal symbol

    The delimiting terminal symbols are: !!=#$()**:,...::*:::=<<<===!>=>=?>>>=>>????[@[]```{{|||}}×÷AposStringLiteralBracedURILiteral{<-+QuotStringLiteral}///StringLiteral

    derives from

    A schema typeS1 is said to derive fromschema typeS2 if any of the following conditions is true:

    digit

    digit(M) is a character used in the picture string to represent an optional digit; the default value is U+0023 (NUMBER SIGN, #) .

    document order

    Informally, document order is the order in which nodes appear in the XML serialization of a document.

    dynamically known function definitions

    Dynamically known function definitions. This is a set of function definitions. It includes the statically known function definitions as a subset, but may include other function definitions that are not known statically.

    dynamic context

    The dynamic context of an expression is defined as information that is needed for the dynamic evaluation of an expression, beyond any information that is needed from the static context.

    dynamic error

    A dynamic error is an error that must be detected during the dynamic evaluation phase and may be detected during the static analysis phase.

    dynamic evaluation phase

    The dynamic evaluation phase is the phase during which the value of an expression is computed.

    dynamic function call

    A dynamic function call consists of a base expression that returns the function and a parenthesized list of zero or more arguments (argument expressions or ArgumentPlaceholders).

    dynamic function call

    A dynamic function call is an expression that is evaluated by calling a function item, which is typically obtained dynamically.

    dynamic type

    Every value matches one or more sequence types. A value is said to have a dynamic typeT if it matches (or is an instance of) the sequence type T.

    effective boolean value

    The effective boolean value of a value is defined as the result of applying the fn:boolean function to the value, as defined in Section 7.3.1 fn:booleanFO.

    empty sequence

    A sequence containing zero items is called an empty sequence.

    enclosed expression

    An enclosed expression is an instance of the EnclosedExpr production, which allows an optional expression within curly brackets.

    entry

    Each key / value pair in a map is called an entry.

    enumeration type

    An EnumerationType accepts a fixed set of string values.

    environment variables

    Environment variables. This is a mapping from names to values. Both the names and the values are strings. The names are compared using an implementation-defined collation, and are unique under this collation. The set of environment variables is implementation-defined and may be empty.

    error value

    In addition to its identifying QName, a dynamic error may also carry a descriptive string and one or more additional values called error values.

    Executable Base URI

    Executable Base URI. This is an absolute URI used to resolve relative URIs during the evaluation of expressions; it is used, for example, to resolve a relative URI supplied to the fn:doc or fn:unparsed-text functions.

    expanded QName

    An expanded QName is a triple: its components are a prefix, a local name, and a namespace URI. In the case of a name in no namespace, the namespace URI and prefix are both absent. In the case of a name in the default namespace, the prefix is absent.

    exponent-separator

    exponent-separator(M, R) is used to separate the mantissa from the exponent in scientific notation. The default value for both the marker and the rendition is U+0065 (LATIN SMALL LETTER E, e) .

    expression context

    The expression context for a given expression consists of all the information that can affect the result of the expression.

    external function

    External functions can be characterized as functions that are neither part of the processor implementation, nor written in a language whose semantics are under the control of this family of specifications. The semantics of external functions, including any context dependencies, are entirely implementation-defined. In XSLT, external functions are called Section 24.1 Extension Functions XT30.

    filter expression

    A filter expression is an expression in the form E1[E2]: its effect is to return those items from the value of E1 that satisfy the predicate in E2.

    fixed focus

    A fixed focus is a focus for an expression that is evaluated once, rather than being applied to a series of values; in a fixed focus, the context value is set to one specific value, the context position is 1, and the context size is 1.

    focus

    The first three components of the dynamic context (context value, context position, and context size) are called the focus of the expression.

    focus function

    A focus function is an inline function expression in which the function signature is implicit: the function takes a single argument of type item()* (that is, any value), and binds this to the context value when evaluating the function body, which returns a result of type item()*.

    function coercion

    Function coercion wraps a function item in a new function whose signature is the same as the expected type. This effectively delays the checking of the argument and return types until the function is called.

    function definition

    A function definition contains information used to evaluate a static function call, including the name, parameters, and return type of the function.

    function item

    A function item is an item that can be called using a dynamic function call.

    generalized atomic type

    A generalized atomic type is an item type whose instances are all atomic items. Generalized atomic types include (a) atomic types, either built-in (for example xs:integer) or imported from a schema, (b) pure union types, either built-in (xs:numeric and xs:error) or imported from a schema, (c) choice item types if their alternatives are all generalized atomic types, and (d) enumeration types.

    Gregorian

    In the operator mapping tables, the term Gregorian refers to the types xs:gYearMonth, xs:gYear, xs:gMonthDay, xs:gDay, and xs:gMonth.

    grouping-separator

    grouping-separator(M, R) is used to separate groups of digits (for example as a thousands separator). The default value for both the marker and the rendition is U+002C (COMMA, ,) .

    guarded

    An expression E is said to be guarded by some governing condition C if evaluation of E is not allowed to fail with a dynamic error except when C applies.

    host language

    A host language for XPath is any environment that provides capabilities for XPath expressions to be defined and evaluated, and that supplies a static and dynamic context for their evaluation.

    ignorable whitespace

    Ignorable whitespace consists of any whitespace characters that may occur between terminals, unless these characters occur in the context of a production marked with a ws:explicit annotation, in which case they can occur only where explicitly specified (see A.3.5.2 Explicit Whitespace Handling).

    implausible

    Certain expressions, while not erroneous, are classified as being implausible, because they achieve no useful effect.

    implementation defined

    Implementation-defined indicates an aspect that may differ between implementations, but must be specified by the implementer for each particular implementation.

    implementation dependent

    Implementation-dependent indicates an aspect that may differ between implementations, is not specified by this or any W3C specification, and is not required to be specified by the implementer for any particular implementation.

    implicit timezone

    Implicit timezone. This is the timezone to be used when a date, time, or dateTime value that does not have a timezone is used in a comparison or arithmetic operation. The implicit timezone is an implementation-defined value of type xs:dayTimeDuration. See Section 3.2.7.3 Timezones XS1-2 or Section 3.3.7 dateTime XS11-2 for the range of valid values of a timezone.

    infinity

    infinity(R) is the string used to represent the double value infinity (INF); the default value is the string "Infinity"

    inline function expression

    An inline function expression, when evaluated, creates an anonymous function defined directly in the inline function expression.

    in-scope attribute declarations

    In-scope attribute declarations. Each attribute declaration is identified either by an expanded QName (for a top-level attribute declaration) or by an implementation-dependent attribute identifier (for a local attribute declaration).

    in-scope element declarations

    In-scope element declarations. Each element declaration is identified either by an expanded QName (for a top-level element declaration) or by an implementation-dependent element identifier (for a local element declaration).

    in-scope named item types

    In-scope named item types. This is a mapping from expanded QName to named item types.

    in-scope namespaces

    The in-scope namespaces property of an element node is a set of namespace bindings, each of which associates a namespace prefix with a URI.

    in-scope schema definitions

    In-scope schema definitions is a generic term for all the element declarations, attribute declarations, and schema type definitions that are in scope during static analysis of an expression.

    in-scope schema type

    In-scope schema types. Each schema type definition is identified either by an expanded QName (for a named type) or by an implementation-dependent type identifier (for an anonymous type). The in-scope schema types include the predefined schema types described in 3.5 Schema Types.

    in-scope variables

    In-scope variables. This is a mapping from expanded QName to type. It defines the set of variables that are available for reference within an expression. The expanded QName is the name of the variable, and the type is the static type of the variable.

    item

    An item is either an atomic item, a node, or a function item.

    item type

    An item type is a type that can be expressed using the ItemType syntax, which forms part of the SequenceType syntax. Item types match individual items.

    item type designator

    An item type designator is a syntactic construct conforming to the grammar rule ItemType. An item type designator is said to designate an item type.

    kind test

    An alternative form of a node test called a kind test can select nodes based on their kind, name, and type annotation.

    lexical QName

    A lexical QName is a name that conforms to the syntax of the QName production

    literal

    A literal is a direct syntactic representation of an atomic item.

    literal terminal

    A literal terminal is a token appearing as a string in quotation marks on the right-hand side of an ordinary production rule.

    map

    A map is a function that associates a set of keys with values, resulting in a collection of key / value pairs.

    mapping arrow operator

    The mapping arrow operator=!> applies a function to each item in a sequence.

    may

    MAY means that an item is truly optional.

    member

    The values of an array are called its members.

    minus-sign

    minus-sign(R) is the string used to mark negative numbers; the default value is U+002D (HYPHEN-MINUS, -) .

    must

    MUST means that the item is an absolute requirement of the specification.

    must not

    MUST NOT means that the item is an absolute prohibition of the specification.

    named function reference

    A named function reference is an expression (written name#arity) which evaluates to a function item, the details of the function item being based on the properties of a function definition in the static context.

    named item type

    A named item type is an ItemType identified by an expanded QName.

    namespace-sensitive

    The namespace-sensitive types are xs:QName, xs:NOTATION, types derived by restriction from xs:QName or xs:NOTATION, list types that have a namespace-sensitive item type, and union types with a namespace-sensitive type in their transitive membership.

    name test

    A node test that consists only of an EQName or a Wildcard is called a name test.

    NaN

    NaN(R) is the string used to represent the double value NaN (not a number); the default value is the string "NaN"

    node

    A node is an instance of one of the node kinds defined in Section 5 NodesDM.

    node test

    A node test is a condition on the name, kind (element, attribute, text, document, comment, or processing instruction), and/or type annotation of a node. A node test determines which nodes contained by an axis are selected by a step.

    non-delimiting terminal symbol

    The non-delimiting terminal symbols are: ancestorancestor-or-selfandarrayasatattributecastcastablechildcommentdescendantdescendant-or-selfdivdocument-nodeelementelseempty-sequenceenumeqeveryexceptfnfollowingfollowing-or-selffollowing-siblingfollowing-sibling-or-selfforfunctiongegtidivifininstanceintersectisitemitemskeykeysleletltmapmembermodnamespacenamespace-nodenenodeoforotherwisepairsparentprecedingpreceding-or-selfpreceding-sibling-or-selfprocessing-instructionrecordreturnsatisfiesschema-attributeschema-elementselfsometextthentotreatunionvaluevaluesBinaryIntegerLiteralDecimalLiteralDoubleLiteralHexIntegerLiteralIntegerLiteralNCNameQNameURIQualifiedName

    numeric

    When referring to a type, the term numeric denotes the types xs:integer, xs:decimal, xs:float, and xs:double which are all member types of the built-in union type xs:numeric.

    operator function

    For each operator and valid combination of operand types, the operator mapping tables specify a result type and an expression that invokes an operator function; the operator function implements the semantics of the operator for the given types.

    ordinary production rule

    An ordinary production rule is a production rule in A.1 EBNF that is not annotated ws:explicit.

    partial function application

    A static or dynamic function call is a partial function application if one or more arguments is an ArgumentPlaceholder.

    partially applied function

    A partially applied function is a function created by partial function application.

    path expression

    A path expression consists of a series of one or more steps, separated by / or //, and optionally beginning with / or //. A path expression is typically used to locate nodes within trees.

    pattern-separator

    pattern-separator(M) is a character used to separate positive and negative sub-pictures in a picture string; the default value is U+003B (SEMICOLON, ;) .

    percent

    percent(M, R) is used to indicate that the number is written as a per-hundred fraction; the default value for both the marker and the rendition is U+0025 (PERCENT SIGN, %) .

    per-mille

    per-mille(M, R) is used to indicate that the number is written as a per-thousand fraction; the default value for both the marker and the rendition is U+2030 (PER MILLE SIGN, ) .

    predicate truth value

    The predicate truth value of a value $V is the result of the expression if ($V instance of xs:numeric+) then ($V = position()) else fn:boolean($V).

    primary expression

    Primary expressions are the basic primitives of the language. They include literals, variable references, context value references, 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.

    principal node kind

    Every axis has a principal node kind. If an axis can contain elements, then the principal node kind is element; otherwise, it is the kind of nodes that the axis can contain.

    pure union type

    A pure union type is a simple type that satisfies the following constraints: (a) {variety}XS11-1 is union, (b) the {facets}XS11-1 property is empty, (c) no type in the transitive membership of the union type has {variety}XS11-1list, and (d) no type in the transitive membership of the union type is a type with {variety}XS11-1union having a non-empty {facets}XS11-1 property

    resolve

    To resolve a relative URI$rel against a base URI $base is to expand it to an absolute URI, as if by calling the function fn:resolve-uri($rel, $base).

    reverse document order

    The node ordering that is the reverse of document order is called reverse document order.

    same key

    Two atomic items K1 and K2 have the same key value if fn:atomic-equal(K1, K2) returns true, as specified in Section 13.2.1 fn:atomic-equalFO

    schema type

    A schema type is a complex type or simple type as defined in the [XML Schema 1.0] or [XML Schema 1.1] specifications, including built-in types as well as user-defined types.

    sequence

    A sequence is an ordered collection of zero or more items.

    sequence arrow operator

    The sequence arrow operator=> applies a function to a supplied sequence.

    sequence concatenation

    The sequence concatenation of a number of sequences S1, S2, ... Sn is defined to be the sequence formed from the items of S1, followed by the items from S2, and so on, retaining order.

    sequence type

    A sequence type is a type that can be expressed using the SequenceType syntax. Sequence types are used whenever it is necessary to refer to a type in an XPath 4.0 expression. Since all values are sequences, every value matches one or more sequence types.

    sequence type designator

    A sequence type designator is a syntactic construct conforming to the grammar rule SequenceType. A sequence type designator is said to designate a sequence type.

    SequenceType matching

    SequenceType matching compares a value with an expected sequence type.

    serialization

    Serialization is the process of converting an XDM instance to a sequence of octets (step DM4 in Figure 1.), as described in [XSLT and XQuery Serialization 4.0].

    singleton

    A sequence containing exactly one item is called a singleton.

    singleton focus

    A singleton focus is a fixed focus in which the context value is a singleton item.

    stable

    Document order is stable, which means that the relative order of two nodes will not change during the processing of a given expression, even if this order is implementation-dependent.

    statically known collations

    Statically known collations. This is an implementation-defined mapping from URI to collation. It defines the names of the collations that are available for use in processing expressions.

    statically known decimal formats

    Statically known decimal formats. This is a mapping from QNames to decimal formats, with one default format that has no visible name, referred to as the unnamed decimal format. Each format is available for use when formatting numbers using the fn:format-number function.

    statically known function definitions

    Statically known function definitions. This is a set of function definitions.

    statically known namespaces

    Statically known namespaces. This is a mapping from prefix to namespace URI that defines all the namespaces that are known during static processing of a given expression.

    static analysis phase

    The static analysis phase depends on the expression itself and on the static context. The static analysis phase does not depend on input data (other than schemas).

    Static Base URI

    Static Base URI. This is an absolute URI, used to resolve relative URIs during static analysis.

    static context

    The static context of an expression is the information that is available during static analysis of the expression, prior to its evaluation.

    static error

    An error that can be detected during the static analysis phase, and is not a type error, is a static error.

    static function call

    A static function call consists of an EQName followed by a parenthesized list of zero or more arguments.

    static type

    The static type of an expression is the best inference that the processor is able to make statically about the type of the result of the expression.

    step

    A step is a part of a path expression that generates a sequence of items and then filters the sequence by zero or more predicates. The value of the step consists of those items that satisfy the predicates, working from left to right. A step may be either an axis step or a postfix expression.

    string value

    The string value of a node is a string and can be extracted by applying the Section 2.1.3 fn:stringFO function to the node.

    substantively disjoint

    Two sequence types are deemed to be substantively disjoint if (a) neither is a subtype of the other (see 3.3.1 Subtypes of Sequence Types) and (b) the only values that are instances of both types are one or more of the following:

    • The empty sequence, ().

    • The empty map, {}.

    • The empty array, [].

    substitution group

    Substitution groups are defined in Section 2.2.2.2 Element Substitution Group XS1-1 and Section 2.2.2.2 Element Substitution Group XS11-1. Informally, the substitution group headed by a given element (called the head element) consists of the set of elements that can be substituted for the head element without affecting the outcome of schema validation.

    subtype

    Given two sequence types or item types, the rules in this section determine if one is a subtype of the other. If a type A is a subtype of type B, it follows that every value matched by A is also matched by B.

    subtype substitution

    The use of a value that has a dynamic type that is a subtype of the expected type is known as subtype substitution.

    symbol

    Each rule in the grammar defines one symbol, using the following format:

    symbol ::= expression
    symbol separators

    Whitespace and Comments function as symbol separators. For the most part, they are not mentioned in the grammar, and may occur between any two terminal symbols mentioned in the grammar, except where that is forbidden by the /* ws: explicit */ annotation in the EBNF, or by the /* xgc: xml-version */ annotation.

    system function

    System functions include the functions defined in [XQuery and XPath Functions and Operators 4.0], functions defined by the specifications of a host language, constructor functions for atomic types, and any additional functions provided by the implementation. System functions are sometimes called built-in functions.

    terminal

    A terminal is a symbol or string or pattern that can appear in the right-hand side of a rule, but never appears on the left-hand side in the main grammar, although it may appear on the left-hand side of a rule in the grammar for terminals.

    type annotation

    Each element node and attribute node in an XDM instance has a type annotation (described in Section 2.8 Schema InformationDM). The type annotation of a node is a reference to a schema type.

    typed value

    The typed value of a node is a sequence of atomic items and can be extracted by applying the Section 2.1.4 fn:dataFO function to the node.

    type error

    A type error may be raised during the static analysis phase or the dynamic evaluation phase. During the static analysis phase, a type error occurs when the static type of an expression does not match the expected type of the context in which the expression occurs. During the dynamic evaluation phase, a type error occurs when the dynamic type of a value does not match the expected type of the context in which the value occurs.

    type promotion

    Under certain circumstances, an atomic item can be promoted from one type to another.

    URI

    Within this specification, the term URI refers to a Universal Resource Identifier as defined in [RFC3986] and extended in [RFC3987] with the new name IRI.

    value

    In the data model, a value is always a sequence.

    variable reference

    A variable reference is an EQName preceded by a $-sign.

    variable terminal

    A variable terminal is an instance of a production rule that is not itself an ordinary production rule but that is named (directly) on the right-hand side of an ordinary production rule.

    variable values

    Variable values. This is a mapping from expanded QName to value. It contains the same expanded QNames as the in-scope variables in the static context for the expression. The expanded QName is the name of the variable and the value is the dynamic value of the variable, which includes its dynamic type.

    warning

    In addition to static errors, dynamic errors, and type errors, an XPath 4.0 implementation may raise warnings, either during the static analysis phase or the dynamic evaluation phase. The circumstances in which warnings are raised, and the ways in which warnings are handled, are implementation-defined.

    whitespace

    A whitespace character is any of the characters defined by [http://www.w3.org/TR/REC-xml/#NT-S].

    wildcard-matches

    In these rules, if MU and NU are NameTestUnions, then MUwildcard-matchesNU is true if every name that matches MU also matches NU.

    XDM instance

    The term XDM instance is used, synonymously with the term value, to denote an unconstrained sequence of items.

    XPath 1.0 compatibility mode

    XPath 1.0 compatibility mode.This value is true if rules for backward compatibility with XPath Version 1.0 are in effect; otherwise it is false.

    xs:anyAtomicType

    xs:anyAtomicType is an atomic type that includes all atomic items (and no values that are not atomic). Its base type is xs:anySimpleType from which all simple types, including atomic, list, and union types, are derived. All primitive atomic types, such as xs:decimal and xs:string, have xs:anyAtomicType as their base type.

    xs:dayTimeDuration

    xs:dayTimeDuration is derived by restriction from xs:duration. The lexical representation of xs:dayTimeDuration is restricted to contain only day, hour, minute, and second components.

    xs:error

    xs:error is a simple type with no value space. It is defined in Section 3.16.7.3 xs:error XS11-1 and can be used in the 3.1 Sequence Types to raise errors.

    xs:untyped

    xs:untyped is used as the type annotation of an element node that has not been validated, or has been validated in skip mode.

    xs:untypedAtomic

    xs:untypedAtomic is an atomic type that is used to denote untyped atomic data, such as text that has not been assigned a more specific type.

    xs:yearMonthDuration

    xs:yearMonthDuration is derived by restriction from xs:duration. The lexical representation of xs:yearMonthDuration is restricted to contain only year and month components.

    zero-digit

    zero-digit(M) is the character used in the picture string to represent the digit zero; the default value is U+0030 (DIGIT ZERO, 0) . This character must be a digit (category Nd in the Unicode property database), and it must have the numeric value zero. This property implicitly defines the ten Unicode characters that are used to represent the values 0 to 9 in the function output: Unicode is organized so that each set of decimal digits forms a contiguous block of characters in numerical sequence. Within the picture string any of these ten character can be used (interchangeably) as a place-holder for a mandatory digit. Within the final result string, these ten characters are used to represent the digits zero to nine.

    H Atomic Comparisons: An Overview (Non-Normative)

    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.

    H.1 Equality Comparisons

    In XPath 4.0 there are essentially four ways of comparing two atomic items for equality:

    • $A = $B

      This operator was introduced in XPath 1.0. The semantics were changed slightly in XPath 2.0, but the original semantics remain available when XPath 1.0 compatibility mode is enabled.

      With a general comparison in XPath 2.0 or later (and in XQuery), the following rules are observed:

      • Either operand may be a sequence; the result is true if any pair of items from the two sequences compares equal.

        In consequence, if either operand is an empty sequence, the result is false.

      • If nodes are supplied, they are atomized.

      • 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 "4.0" and "4" are not equal to each other, but both compare equal to the integer value 4.

      • Comparison of certain values is context-sensitive. In particular, comparison of strings uses the default collation from the static context, while comparison of date/time values lacking an explicit timezone takes the timezone from the dynamic context.

      • NaN is not equal to NaN; negative zero is equal to positive zero.

      • xs:hexBinary and xs:base64Binary values are mutually comparable: they are equal if they represent the same sequence of octets.

      • Comparing incompatible values (for example xs:integer and xs:date) raises an error.

    • $A eq $B

      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.

      With a value comparison, the rules are:

      • Each operand must either be a single atomic item, or an empty sequence.

      • If either operand is an empty sequence, the result is an empty sequence; in most contexts this has the same effect as returning false.

      • If nodes are supplied, they are atomized.

      • Untyped atomic items are converted to strings (regardless of the type of the other operand).

      • Numeric values of types xs:integer, xs:decimal, or xs:float are converted to xs:double.

        This can lead to problems with implementations of xs:decimal that support more precision than can be held in an xs:double.

      • As with general comparisons, the default collation and implicit timezone are taken from the context.

      • NaN is not equal to NaN; negative zero is equal to positive zero.

      • xs:hexBinary and xs:base64Binary values are mutually comparable: they are equal if they represent the same sequence of octets.

      • Comparing incompatible values (for example xs:integer and xs:date) raises an error.

    • deep-equal($A, $B)

      As the name implies, the deep-equal 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 deep-equal($A, $B) are also invoked by a wide variety of other functions including distinct-values, all-equal, and all-different; it is also used to underpin grouping constructs in both XQuery 4.0 and XSLT 4.0.

      Some of the relevant rules are:

      • Because deep-equal 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.

      • If nodes are supplied, they are not atomized; they are compared as nodes.

      • 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.

      • Comparisons of dates and times lacking a timezone uses the implicit timezone from the dynamic context.

      • Numeric values are converted to xs:decimal prior to comparison, not to xs:double. This represents a departure in 4.0 from previous versions of the specification. The conversion must use an implementation of xs:decimal that does not cause loss of precision. As a result, the comparison is now truly transitive, which makes it suitable to underpin grouping operations.

      • To ensure that every value is equal to itself, comparing NaN to NaN returns true.

      • xs:hexBinary and xs:base64Binary values are mutually comparable: they are equal if they represent the same sequence of octets.

      • Comparing incompatible values (for example xs:integer and xs:date) returns false; it does not raise an error.

    • atomic-equal($A, $B)

      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:

      • The type signature of the function ensures that it can only be used to compare single items; empty sequences do not arise.

      • If nodes are supplied, they are atomized.

      • Strings are compared codepoint-by-codepoint, without reference to any collation or normalization.

      • 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.

      • As with deep-equal, numeric values are converted to xs:decimal prior to comparison, not to xs:double.

      • Comparing NaN to NaN returns true.

      • xs:hexBinary and xs:base64Binary values are distinct: both can co-exist as distinct keys in a map even if the underlying sequence of octets is the same.

      • Comparing incompatible values (for example xs:integer and xs:date) returns false; it does not raise an error.

    The following table summarizes these differences. 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.

    $A$B$A = $B$A eq $Bdeep-equal(​$A, $B)atomic-equal(​$A, $B)

    ()

    ()

    false

    ()

    true

    error

    12

    ()

    false

    ()

    false

    error

    (1,2)

    (2,3)

    true

    error

    false

    error

    12

    12e0

    true

    true

    true

    true

    0.2

    0.2e0

    true

    true

    false

    false

    NaN

    NaN

    false

    false

    true

    true

    +0e0

    -0e0

    true

    true

    true

    true

    "A"

    "a"

    true

    true

    true

    false

    "A"

    12

    error

    error

    false

    false

    <a>A</a>

    "A"

    true

    true

    false

    true

    <a>12</a>

    12

    true

    error

    false

    false

    xs:time(​'12:00:00Z')

    xs:time(​'13:00:00+01:00')

    true

    true

    true

    true

    xs:time(​'12:00:00Z')

    xs:time(​'13:00:00')

    true

    true

    true

    false

    xs:hexBinary(​"0000")

    xs:base64Binary(​"AAA=")

    true

    true

    true

    false

    H.2 Ordering Comparisons

    In XPath 4.0 there are essentially three ways of comparing two atomic items for their relative ordering:

    • $A < $B

    • $A lt $B

    • Sorting

    TODO: to be expanded.

    I Backwards Compatibility (Non-Normative)

    I.1 Incompatibilities relative to XPath 3.1

    In fn:format-integer, certain formatting pictures using a circumflex as a grouping separator might be interpreted differently in 4.0: for example format-integer(1234, "9^999") would output "1^234" in 3.1, but will output "1621" (1234 in base 9) with 4.0. As a workaround, this can be rewritten as format-integer(1234, "0^000").

    In XPath 4.0, certain expressions are classified as implausible: an example is @code/text(), which will always return an empty sequence. A processor may report a static error when such expressions are encountered; however, processors are required to provide a mode of operation in which such expressions are accepted, thus retaining backwards compatibility.

    In expressions that deliver a function item, notably partial function applications, named function references, and the fn:function-lookup 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 contains(?, 42) 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.

    As explained in 3.4.4 Function Coercion, 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.

    I.2 Incompatibilities relative to XPath 3.0

    The following names are now reserved, and cannot appear as function names (see A.4 Reserved Function Names):

    • map

    • array

    I.3 Incompatibilities relative to XPath 2.0

    The following names are now reserved, and cannot appear as function names (see A.4 Reserved Function Names):

    • function

    • namespace-node

    • switch

    If U is a union type with T as one of its members, and if E is an element with T as its type annotation, the expression E instance of element(*, U) returns true in both XPath 3.0 and 3.1. In XPath 2.0, it returns false.

    Note:

    This is not an incompatibility with XPath 3.0. It should be included in XPath 3.0 as an incompatibility with XPath 2.0, but it was discovered after publication.

    I.4 Incompatibilities relative to XPath 1.0

    This appendix provides a summary of the areas of incompatibility between XPath 4.0 and [XML Path Language (XPath) Version 1.0]. In each of these cases, an XPath 4.0 processor is compatible with an XPath 2.0, 3.0, or 3.1 processor.

    Three separate cases are considered:

    1. Incompatibilities that exist when source documents have no schema, and when running with XPath 1.0 compatibility mode set to true. This specification has been designed to reduce the number of incompatibilities in this situation to an absolute minimum, but some differences remain and are listed individually.

    2. Incompatibilities that arise when XPath 1.0 compatibility mode is set to false. In this case, the number of expressions where compatibility is lost is rather greater.

    3. Incompatibilities that arise when the source document is processed using a schema (whether or not XPath 1.0 compatibility mode is set to true). Processing the document with a schema changes the way that the values of nodes are interpreted, and this can cause an XPath expression to return different results.

    I.4.1 Incompatibilities when Compatibility Mode is true

    The list below contains all known areas, within the scope of this specification, where an XPath 4.0 processor running with compatibility mode set to true will produce different results from an XPath 1.0 processor evaluating the same expression, assuming that the expression was valid in XPath 1.0, and that the nodes in the source document have no type annotations other than xs:untyped and xs:untypedAtomic.

    Incompatibilities in the behavior of individual functions are not listed here, but are included in an appendix of [XQuery and XPath Functions and Operators 4.0].

    Since both XPath 1.0 and XPath 4.0 leave some aspects of the specification implementation-defined, there may be incompatibilities in the behavior of a particular implementation that are outside the scope of this specification. Equally, some aspects of the behavior of XPath are defined by the host language.

    1. Consecutive comparison operators such as A < B < C were supported in XPath 1.0, but are not permitted by the XPath 4.0 grammar. In most cases such comparisons in XPath 1.0 did not have the intuitive meaning, so it is unlikely that they have been widely used in practice. If such a construct is found, an XPath 4.0 processor will report a syntax error, and the construct can be rewritten as (A < B) < C

    2. When converting strings to numbers (either explicitly when using the number function, or implicitly say on a function call), certain strings that converted to the special value NaN under XPath 1.0 will convert to values other than NaN under XPath 4.0. These include any number written with a leading + sign, any number in exponential floating point notation (for example 1.0e+9), and the strings INF and -INF.

      Furthermore, the strings Infinity and -Infinity, which were accepted by XPath 1.0 as representations of the floating-point values positive and negative infinity, are no longer recognized. They are converted to NaN when running under XPath 4.0 with compatibility mode set to true, and cause a dynamic error when compatibility mode is set to false.

    3. XPath 4.0 does not allow a token starting with a letter to follow immediately after a numeric literal, without intervening whitespace. For example, 10div 3 was permitted in XPath 1.0, but in XPath 4.0 must be written as 10 div 3.

    4. The namespace axis is deprecated as of XPath 2.0. Implementations may support the namespace axis for backward compatibility with XPath 1.0, but they are not required to do so. (XSLT 2.0 requires that if XPath backwards compatibility mode is supported, then the namespace axis must also be supported; but other host languages may define the conformance rules differently.)

    5. In XPath 1.0, the expression -x|y parsed as -(x|y), and returned the negation of the numeric value of the first node in the union of x and y. In XPath 4.0, this expression parses as (-x)|y. When XPath 1.0 Compatibility Mode is true, this will always cause a type error.

    6. The rules for converting numbers to strings have changed. These may affect the way numbers are displayed in the output of a stylesheet. For numbers whose absolute value is in the range 1E-6 to 1E+6, the result should be the same, but outside this range, scientific format is used for non-integral xs:float and xs:double values.

    7. If one operand in a general comparison is a single atomic item of type xs:boolean, the other operand is converted to xs:boolean when XPath 1.0 compatibility mode is set to true. In XPath 1.0, if neither operand of a comparison operation using the <, <=, > or >= operator was a node set, both operands were converted to numbers. The result of the expression true() > number('0.5') is therefore true in XPath 1.0, but is false in XPath 4.0 even when compatibility mode is set to true.

    8. In XPath 4.0, a type error is raised if the PITarget specified in a SequenceType of form processing-instruction(PITarget) is not a valid NCName. In XPath 1.0, this condition was not treated as an error.

    I.4.2 Incompatibilities when Compatibility Mode is false

    Even when the setting of the XPath 1.0 compatibility mode is false, many XPath expressions will still produce the same results under XPath 4.0 as under XPath 1.0. The exceptions are described in this section.

    In all cases it is assumed that the expression in question was valid under XPath 1.0, that XPath 1.0 compatibility mode is false, and that all elements and attributes are annotated with the types xs:untyped and xs:untypedAtomic respectively.

    In the description below, the terms node-set and number are used with their XPath 1.0 meanings, that is, to describe expressions which according to the rules of XPath 1.0 would have generated a node-set or a number respectively.

    1. When a node-set containing more than one node is supplied as an argument to a function or operator that expects a single node or value, the XPath 1.0 rule was that all nodes after the first were discarded. Under XPath 4.0, a type error occurs if there is more than one node. The XPath 1.0 behavior can always be restored by using the predicate [1] to explicitly select the first node in the node-set.

    2. In XPath 1.0, the < and > operators, when applied to two strings, attempted to convert both the strings to numbers and then made a numeric comparison between the results. In XPath 4.0, these operators perform a string comparison using the default collating sequence. (If either value is numeric, however, the results are compatible with XPath 1.0)

    3. When an empty node-set is supplied as an argument to a function or operator that expects a number, the value is no longer converted implicitly to NaN. The XPath 1.0 behavior can always be restored by using the number function to perform an explicit conversion.

    4. More generally, the supplied arguments to a function or operator are no longer implicitly converted to the required type, except in the case where the supplied argument is of type xs:untypedAtomic (which will commonly be the case when a node in a schemaless document is supplied as the argument). For example, the function call substring-before(10 div 3, ".") raises a type error under XPath 4.0, because the arguments to the substring-before function must be strings rather than numbers. The XPath 1.0 behavior can be restored by performing an explicit conversion to the required type using a constructor function or cast.

    5. The rules for comparing a node-set to a boolean have changed. In XPath 1.0, an expression such as $node-set = true() was evaluated by converting the node-set to a boolean and then performing a boolean comparison: so this expression would return true if $node-set was non-empty. In XPath 4.0, this expression is handled in the same way as other comparisons between a sequence and a singleton: it is true if $node-set contains at least one node whose value, after atomization and conversion to a boolean using the casting rules, is true.

      This means that if $node-set is empty, the result under XPath 4.0 will be false regardless of the value of the boolean operand, and regardless of which operator is used. If $node-set is non-empty, then in most cases the comparison with a boolean is likely to fail, giving a dynamic error. But if a node has the value "0", "1", "true", or "false", evaluation of the expression may succeed.

    6. Comparisons of a number to a boolean, a number to a string, or a string to a boolean are not allowed in XPath 4.0: they result in a type error. In XPath 1.0 such comparisons were allowed, and were handled by converting one of the operands to the type of the other. So for example in XPath 1.0 4 = true() returned true; 4 ="+4" returned false (because the string "+4" converts to NaN), and false = "false" returned false (because the string "false" converts to the boolean true). In XPath 3.0 all these comparisons are type errors.

    7. Additional numeric types have been introduced, with the effect that arithmetic may now be done as an integer, decimal, or single- or double-precision floating point calculation where previously it was always performed as double-precision floating point. The result of the div operator when dividing two integers is now a value of type decimal rather than double. The expression 10 div 0 raises an error rather than returning positive infinity.

    8. The rules for converting strings to numbers have changed. The implicit conversion that occurs when passing an xs:untypedAtomic value as an argument to a function that expects a number no longer converts unrecognized strings to the value NaN; instead, it reports a dynamic error. This is in addition to the differences that apply when backwards compatibility mode is set to true.

    9. Many operations in XPath 4.0 produce an empty sequence as their result when one of the arguments or operands is an empty sequence. Where the operation expects a string, an empty sequence is usually considered equivalent to a zero-length string, which is compatible with the XPath 1.0 behavior. Where the operation expects a number, however, the result is not the same. For example, if @width returns an empty sequence, then in XPath 1.0 the result of @width+1 was NaN, while with XPath 4.0 it is (). This has the effect that a filter expression such as item[@width+1 != 2] will select items having no width attribute under XPath 1.0, and will not select them under XPath 4.0.

    10. The typed value of a comment node, processing instruction node, or namespace node under XPath 4.0 is of type xs:string, not xs:untypedAtomic. This means that no implicit conversions are applied if the value is used in a context where a number is expected. If a processing-instruction node is used as an operand of an arithmetic operator, for example, XPath 1.0 would attempt to convert the string value of the node to a number (and deliver NaN if unsuccessful), while XPath 4.0 will report a type error.

    11. In XPath 1.0, it was defined that with an expression of the form A and B, B would not be evaluated if A was false. Similarly in the case of A or B, B would not be evaluated if A was true. This is no longer guaranteed with XPath 4.0: the implementation is free to evaluate the two operands in either order or in parallel. This change has been made to give more scope for optimization in situations where XPath expressions are evaluated against large data collections supported by indexes. Implementations may choose to retain backwards compatibility in this area, but they are not obliged to do so.

    12. In XPath 1.0, the expression -x|y parsed as -(x|y), and returned the negation of the numeric value of the first node in the union of x and y. In XPath 4.0, this expression parses as (-x)|y. When XPath 1.0 Compatibility Mode is false, this will cause a type error, except in the situation where x evaluates to an empty sequence. In that situation, XPath 4.0 will return the value of y, whereas XPath 1.0 returned the negation of the numeric value of y.

    I.4.3 Incompatibilities when using a Schema

    An XPath expression applied to a document that has been processed against a schema will not always give the same results as the same expression applied to the same document in the absence of a schema. Since schema processing had no effect on the result of an XPath 1.0 expression, this may give rise to further incompatibilities. This section gives a few examples of the differences that can arise.

    Suppose that the context node is an element node derived from the following markup: <background color="red green blue"/>. In XPath 1.0, the predicate [@color="blue"] would return false. In XPath 4.0, if the color attribute is defined in a schema to be of type xs:NMTOKENS, the same predicate will return true.

    Similarly, consider the expression @birth < @death applied to the element <person birth="1901-06-06" death="1991-05-09"/>. With XPath 1.0, this expression would return false, because both attributes are converted to numbers, which returns NaN in each case. With XPath 4.0, in the presence of a schema that annotates these attributes as dates, the expression returns true.

    Once schema validation is applied, elements and attributes cannot be used as operands and arguments of expressions that expect a different data type. For example, it is no longer possible to apply the substring function to a date to extract the year component, or to a number to extract the integer part. Similarly, if an attribute is annotated as a boolean then it is not possible to compare it with the strings "true" or "false". All such operations lead to type errors. The remedy when such errors occur is to introduce an explicit conversion, or to do the computation in a different way. For example, substring-after(@temperature, "-") might be rewritten as abs(@temperature).

    In the case of an XPath 4.0 implementation that provides the static typing feature, many further type errors will be reported in respect of expressions that worked under XPath 1.0. For example, an expression such as round(../@price) might lead to a static type error because the processor cannot infer statically that ../@price is guaranteed to be numeric.

    Schema validation will in many cases perform whitespace normalization on the contents of elements (depending on their type). This will change the result of operations such as the string-length function.

    Schema validation augments the data model by adding default values for omitted attributes and empty elements.

    J Change Log (Non-Normative)

    1. Use the arrows to browse significant changes since the 3.1 version of this specification.

      See 1 Introduction

    2. Sections with significant changes are marked Δ in the table of contents.

      See 1 Introduction

    3. Setting the default namespace for elements and types to the special value ##any causes an unprefixed element name to act as a wildcard, matching by local name regardless of namespace.

      See 3.2.7.2 Element Types

    4. The terms FunctionType, ArrayType, MapType, and RecordType replace FunctionTest, ArrayTest, MapTest, and RecordTest, with no change in meaning.

      See 3.2.8.1 Function Types

    5. Record types are added as a new kind of ItemType, constraining the value space of maps.

      See 3.2.8.3 Record Types

    6. Function coercion now allows a function with arity N to be supplied where a function of arity greater than N is expected. For example this allows the function true#0 to be supplied where a predicate function is required.

      See 3.4.4 Function Coercion

    7. The symbols × and ÷ can be used for multiplication and division.

      See 4.8 Arithmetic Expressions

    8. 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.

      See 4.10.1 Value Comparisons

    9. Operators such as < and > can use the full-width forms and to avoid the need for XML escaping.

      See 4.10.2 General Comparisons

    10. The lookup operator ? can now be followed by a string literal, for cases where map keys are strings other than NCNames. It can also be followed by a variable reference.

      See 4.13.3 Lookup Expressions

    11. The arrow operator => is now complemented by a “mapping arrow” operator =!> which applies the supplied function to each item in the input sequence independently.

      See 4.19.2 Mapping Arrow Expressions

    12. The operator mapping table has been simplified by removing entries for the operators ne, le, gt, and ge; these are now defined by reference to the rules for the operators eq and lt.

      See B.2 Operator Mapping

    13. PR 1023 1128 

      It has been clarified that function coercion applies even when the supplied function item matches the required function type. This is to ensure that arguments supplied when calling the function are checked against the signature of the required function type, which might be stricter than the signature of the supplied function item.

      See 3.4.4 Function Coercion

    14. PR tba 

      Predicates in filter expressions for maps and arrays can now be numeric.

      See 4.13.4 Filter Expressions for Maps and Arrays

    15. The static typing feature has been dropped.

      See 5 Conformance

    16. The syntax record() is allowed; the only thing it matches is an empty map.

      See 3.2.8.3 Record Types

    17. The context value static type, which was there purely to assist in static typing, has been dropped.

      See 2.2.1 Static Context

    18. Four new axes have been defined: preceding-or-self, preceding-sibling-or-self, following-or-self, and following-sibling-or-self.

      See 4.6.4.1 Axes

    19. The syntax document-node(N), where N is a NameTestUnion, is introduced as an abbreviation for document-node(element(N)). For example, document-node(*) matches any well-formed XML document (as distinct from a document fragment).

      See 3.2.7 Node Types

    20. PR 28 

      Multiple for and let clauses can be combined in an expression without an intervening return keyword.

      See 4.12.1 For Expressions

      See 4.12.2 Let Expressions

    21. PR 159 

      Keyword arguments are allowed on static function calls, as well as positional arguments.

      See 4.5.1.1 Static Function Call Syntax

    22. PR 202 

      The presentation of the rules for the subtype relationship between sequence types and item types has been substantially rewritten to improve clarity; no change to the semantics is intended.

      See 3.3 Subtype Relationships

    23. PR 230 

      The rules for “errors and optimization” have been tightened up to disallow many cases of optimizations that alter error behavior. In particular there are restrictions on reordering the operands of and and or, and of predicates in filter expressions, in a way that might allow the processor to raise dynamic errors that the author intended to prevent.

      See 2.4.5 Guarded Expressions

    24. PR 254 

      The term "function conversion rules" used in 3.1 has been replaced by the term "coercion rules".

      See 3.4 Coercion Rules

      The coercion rules allow “relabeling” of a supplied atomic item where the required type is a derived atomic type: for example, it is now permitted to supply the value 3 when calling a function that expects an instance of xs:positiveInteger.

      See 3.4 Coercion Rules

    25. PR 284 

      Alternative syntax for conditional expressions is available: if (condition) { X } else { Y }, with the else part being optional.

      See 4.14 Conditional Expressions

    26. PR 286 

      Element and attribute tests can include alternative names: element(chapter|section), attribute(role|class).

      See 3.2.7 Node Types

      The NodeTest in an AxisStep now allows alternatives: ancestor::(section|appendix)

      See 3.2.7 Node Types

      Element and attribute tests of the form element(N) and attribute(N) now allow N to be any NameTest, including a wildcard.

      See 3.2.7.2 Element Types

      See 3.2.7.3 Attribute Types

    27. PR 324 

      String templates provide a new way of constructing strings: for example `{$greeting}, {$planet}!` is equivalent to $greeting || ', ' || $planet || '!'

      See 4.9.2 String Templates

    28. PR 326 

      Support for higher-order functions is now a mandatory feature (in 3.1 it was optional).

      See 5 Conformance

    29. PR 344 

      A for member clause is added to FLWOR expressions to allow iteration over an array.

      See 4.12.1 For Expressions

    30. PR 368 

      The concept of the context item has been generalized, so it is now a context value. That is, it is no longer constrained to be a single item.

      See 2.2.2 Dynamic Context

    31. PR 433 

      Numeric literals can now be written in hexadecimal or binary notation; and underscores can be included for readability.

      See 4.2.1.1 Numeric Literals

    32. PR 519 

      The rules for tokenization have been largely rewritten. In some cases the revised specification may affect edge cases that were handled in different ways by different 3.1 processors, which could lead to incompatible behavior.

      See A.3 Lexical structure

    33. PR 521 

      New abbreviated syntax is introduced (focus function) for simple inline functions taking a single argument. An example is fn { ../@code }

      See 4.5.2.5 Inline Function Expressions

    34. PR 603 

      The rules for reporting type errors during static analysis have been changed so that a processor has more freedom to report errors in respect of constructs that are evidently wrong, such as @price/@value, even though dynamic evaluation is defined to return an empty sequence rather than an error.

      See 2.4.6 Implausible Expressions

      See 4.6.4.3 Implausible Axis Steps

    35. PR 606 

      Element and attribute tests of the form element(A|B) and attribute(A|B) are now allowed.

      See 3.2.7.2 Element Types

      See 3.2.7.3 Attribute Types

    36. PR 691 

      Enumeration types are added as a new kind of ItemType, constraining the value space of strings.

      See 3.2.6 Enumeration Types

    37. PR 728 

      The syntax record(*) is allowed; it matches any map.

      See 3.2.8.3 Record Types

    38. PR 815 

      The coercion rules now allow conversion in either direction between xs:hexBinary and xs:base64Binary.

      See 3.4 Coercion Rules

    39. PR 837 

      A deep lookup operator ?? is provided for searching trees of maps and arrays.

      See 4.13.3 Lookup Expressions

    40. PR 911 

      The coercion rules now allow any numeric type to be implicitly converted to any other, for example an xs:double is accepted where the required type is xs:double.

      See 3.4 Coercion Rules

    41. PR 985 

      With the lookup arrow expression and the =?> operator, a function in a map can be looked up and called with the map as first argument.

      See 4.19.3 Lookup Arrow Expressions

    42. PR 996 

      The value of a predicate in a filter expression can now be a sequence of integers.

      See 4.4 Filter Expressions

    43. PR 1031 

      An otherwise operator is introduced: A otherwise B returns the value of A, unless it is an empty sequence, in which case it returns the value of B.

      See 4.15 Otherwise Expressions

    44. PR 1071 

      In map constructors, the keyword map is now optional, so map { 0: false(), 1: true() } can now be written { 0: false(), 1: true() }, provided it is used in a context where this creates no ambiguity.

      See 4.13.1.1 Map Constructors

    45. PR 1125 

      Lookup expressions can now take a modifier (such as keys, values, or pairs) enabling them to return structured results rather than a flattened sequence.

      See 4.13.3 Lookup Expressions

    46. PR 1131 

      A positional variable can be defined in a for expression.

      See 4.12.1 For Expressions

      The type of a variable used in a for expression can be declared.

      See 4.12.1 For Expressions

      The type of a variable used in a let expression can be declared.

      See 4.12.2 Let Expressions

    47. PR 1132 

      Choice item types (an item type allowing a set of alternative item types) are introduced.

      See 3.2.5 Choice Item Types

    48. PR 1163 

      Filter expressions for maps and arrays are introduced.

      See 4.13.4 Filter Expressions for Maps and Arrays

    49. PR 1181 

      The default namespace for elements and types can be set to the value ##any, allowing unprefixed names in axis steps to match elements with a given local name in any namespace.

      See 2.2.1 Static Context

      If the default namespace for elements and types has the special value ##any, then an unprefixed name in a NameTest acts as a wildcard, matching names in any namespace or none.

      See 4.6.4.2 Node Tests

    50. PR 1197 

      The keyword fn is allowed as a synonym for function in function types, to align with changes to inline function declarations.

      See 3.2.8.1 Function Types

      In inline function expressions, the keyword function may be abbreviated as fn.

      See 4.5.2.5 Inline Function Expressions

    51. PR 1212 

      XPath 3.0 included empty-sequence and item as reserved function names, and XPath 3.1 added map and array. This was unnecessary since these names never appear followed by a left parenthesis at the start of an expression. They have therefore been removed from the list. New keywords introducing item types, such as record and enum, have not been included in the list.

      See A.4 Reserved Function Names

    52. PR 1249 

      A for key/value clause is added to FLWOR expressions to allow iteration over maps.

      See 4.12.1 For Expressions

    53. PR 1250 

      Several decimal format properties, including minus sign, exponent separator, percent, and per-mille, can now be rendered as arbitrary strings rather than being confined to a single character.

      See 2.2.1.2 Decimal Formats

    54. PR 1265 

      The rules regarding the document-uri property of nodes returned by the fn:collection function have been relaxed.

      See 2.2.2 Dynamic Context

    55. PR 1344 

      Parts of the static context that were there purely to assist in static typing, such as the statically known documents, were no longer referenced and have therefore been dropped.

      See 2.2.1 Static Context

      The static typing option has been dropped.

      See 2.3 Processing Model

    56. PR 1361 

      The term atomic value has been replaced by atomic item.

      See 2.1.2 Values

    57. PR 1384 

      If a type declaration is present, the supplied values in the input sequence are now coerced to the required type. Type declarations are now permitted in XPath as well as XQuery.

      See 4.16 Quantified Expressions

    58. PR 1498 

      The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.

      See 2.1 Terminology

      The EBNF notation has been extended to allow the constructs (A ++ ",") (one or more occurrences of A, comma-separated, and (A ** ",") (zero or more occurrences of A, comma-separated.

      See 2.1.1 Grammar Notation

      The EBNF operators ++ and ** have been introduced, for more concise representation of sequences using a character such as "," as a separator. The notation is borrowed from Invisible XML.

      See A.1 EBNF

      See A.1.1 Notation

    59. PR 1703 

      Ordered maps are introduced.

      See 4.13.1 Maps

      The order of key-value pairs in the map constructor is now retained in the constructed map.

      See 4.13.1.1 Map Constructors

    \ No newline at end of file diff --git a/pr/1703/xquery-40/xpath-40-diff.html b/pr/1703/xquery-40/xpath-40-diff.html index d3811bc3c..35a4cea91 100644 --- a/pr/1703/xquery-40/xpath-40-diff.html +++ b/pr/1703/xquery-40/xpath-40-diff.html @@ -22,7 +22,7 @@

    XML Path Language (XPath) 4.0 WG Review Draft

    -

    W3C Editor's Draft 14 January 2025

    +

    W3C Editor's Draft 15 January 2025

    This version:
    https://qt4cg.org/pr/1703/xpath-40/
    @@ -14894,7 +14894,7 @@

    4.13.1

    Changes in 4.0  

    1. -

      Ordered maps are introduced.  [Issue 564 PR 1609 25 November 2024]

      +

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

    @@ -14914,22 +14914,11 @@

    4.13.1 see Section 17 MapsFO.

    Note:

    -

    Maps in XPath 4.0 have a property called [TERMDEF dt-map-ordered IN DM40], - which takes the value true or false; a map - is accordingly said to be ordered or unordered. +

    Maps in XPath 4.0 are ordered. The effect of this property is explained - in Section 2.9.5 Map ItemsDM. In summary:

    -
      -
    • -

      In an unordered map, the order of entries - in the map is implementation dependent; it may, for example, - be the result of a randomized hashing algorithm.

      -
    • -
    • -

      In an ordered map, the order of entries is predictable + in Section 2.9.5 Map ItemsDM. + In an ordered map, the order of entries is predictable and depends on the order in which they were added to the map.

      -
    • -
    @@ -14946,12 +14935,12 @@
    4.13.1.1
  • The order of key-value - pairs in the map constructor is now retained in the constructed map.  [Issue 564 PR 1609 25 November 2024]

    + pairs in the map constructor is now retained in the constructed map.  [Issue 1651 PR 1703 14 January 2025]

  • A map can be created using a MapConstructor.

    - +
    @@ -15080,7 +15069,7 @@
    4.13.1.1
    -
    Example: Constructing a fixed map
    +
    Example: Constructing a fixed map

    The following expression constructs a map with seven entries:

     {
    @@ -15097,7 +15086,7 @@ 
    4.13.1.1  

    -
    Example: Constructing nested maps
    +
    Example: Constructing nested maps

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

     
    @@ -15251,7 +15240,7 @@ 
    4.13.2.1 Atomization).

    An array is created using an ArrayConstructor.

    -
    MapConstructor
    +
    @@ -15439,7 +15428,7 @@

    4.13.3
    4.13.3.1 Postfix Lookup Expressions
    -

    ArrayConstructor
    +
    @@ -15932,7 +15921,7 @@
    4.13.3.1
    4.13.3.2 Unary Lookup
    -
    LookupExpr
    +
    @@ -15943,14 +15932,14 @@
    4.13.3.2 -
    + - + + @@ -16300,7 +16289,7 @@
    4.13.3.3 -
    Example: Comparison with JSONPath
    +
    Example: Comparison with JSONPath

    This example provides XPath equivalents to some examples given in the JSONPath specification. [TODO: add a reference].

    The examples query the result of parsing the following JSON value, representing @@ -16554,7 +16543,7 @@

    4.13.4

    UnaryLookupModifierModifier ::= "pairs" | "keys" | "values" | "items"
    KeySpecifierKeySpecifier ::= NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard @@ -15959,7 +15948,7 @@
    4.13.3.2 -
    LookupWildcardLookupWildcard ::= "*"
    +
    @@ -16619,15 +16608,14 @@

    4.13.4 entry orderDM), and the context size is the number of entries in the map. The result of the expression is a map containing those entries of the input map for which the predicate truth value of the FILTER expression is true. - The ordered property of the result is the same as the ordered - property of the input map, and in the case of an ordered map, the relative order of - entries in the result retains the relative order of entries in the input. + The relative order of entries in the result retains the relative order of entries in the input.

    For example, the following expression:

    @@ -16768,7 +16754,7 @@

    4.14 -

    FilterExprAM
    +
    @@ -16820,7 +16806,7 @@

    4.14 -

    + @@ -16979,7 +16965,7 @@

    4.15

    IfExprEnclosedExprEnclosedExpr ::= "{" Expr? "}"
    +
    @@ -17023,7 +17009,7 @@

    4.16

    OtherwiseExpr
    +
    @@ -17043,7 +17029,7 @@

    4.16 -

    + @@ -17204,7 +17190,7 @@

    4.17

    4.17.1 Instance Of

    -

    QuantifiedExprTypeDeclarationTypeDeclaration ::= "as" SequenceType
    +
    @@ -17265,7 +17251,7 @@

    4.17.1

    4.17.2 Cast

    -

    InstanceofExpr
    +
    @@ -17285,14 +17271,14 @@

    4.17.2

    - + - + @@ -17414,7 +17400,7 @@

    4.17.2

    4.17.3 Castable

    -

    CastExpr
    ChoiceItemTypeChoiceItemType ::= "(" (ItemType ++ "|") ")"
    EnumerationTypeEnumerationType ::= "enum" "(" (StringLiteral ++ ",") ")"
    +
    @@ -17425,7 +17411,7 @@

    4.17.3 -

    + + - + @@ -17595,7 +17581,7 @@

    4.17.4

    4.17.5 Treat

    -

    CastableExprCastTargetCastTarget ::= TypeName | ChoiceItemType | EnumerationType @@ -17434,14 +17420,14 @@

    4.17.3 -

    ChoiceItemTypeChoiceItemType ::= "(" (ItemType ++ "|") ")"
    EnumerationTypeEnumerationType ::= "enum" "(" (StringLiteral ++ ",") ")"
    +
    @@ -17691,7 +17677,7 @@

    4.17.5

    4.18 Simple map operator (!)

    -

    TreatExpr
    +
    @@ -17809,7 +17795,7 @@

    4.18 4.19 Arrow Expressions

    Arrow expressions apply a function to a value, using the value of the left-hand expression as the first argument to the function.

    -
    SimpleMapExpr
    +
    @@ -17872,7 +17858,7 @@

    4.19 -

    + @@ -17880,14 +17866,14 @@

    4.19 -

    + - + @@ -19821,7 +19807,7 @@

    A.3

    A.3.1 Terminal Symbols

    -

    ArrowExprInlineFunctionExprInlineFunctionExpr ::= ("function" | "fn") FunctionSignature? FunctionBody ArgumentListArgumentList ::= "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    PositionalArgumentListPositionalArgumentList ::= "(" PositionalArguments? ")"
    +
    @@ -20102,7 +20088,7 @@

    A.3.1 A.1 EBNF.

    -

    IntegerLiteral
    +
    @@ -25413,7 +25399,7 @@

    J A.1.1 Notation

  • -

    PR 1609 

    +

    PR 1703 

    Ordered maps are introduced.

    See 4.13.1 Maps

    The order of key-value diff --git a/pr/1703/xquery-40/xpath-40.html b/pr/1703/xquery-40/xpath-40.html index a0ea5b1f2..087d6fc09 100644 --- a/pr/1703/xquery-40/xpath-40.html +++ b/pr/1703/xquery-40/xpath-40.html @@ -14,7 +14,7 @@

    XML Path Language (XPath) 4.0 WG Review Draft

    -

    W3C Editor's Draft 14 January 2025

    +

    W3C Editor's Draft 15 January 2025

    This version:
    https://qt4cg.org/pr/1703/xpath-40/
    @@ -14581,7 +14581,7 @@

    4.13.1

    Changes in 4.0  

    1. -

      Ordered maps are introduced.  [Issue 564 PR 1609 25 November 2024]

      +

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

    @@ -14601,22 +14601,11 @@

    4.13.1 see Section 17 MapsFO.

    Note:

    -

    Maps in XPath 4.0 have a property called [TERMDEF dt-map-ordered IN DM40], - which takes the value true or false; a map - is accordingly said to be ordered or unordered. +

    Maps in XPath 4.0 are ordered. The effect of this property is explained - in Section 2.9.5 Map ItemsDM. In summary:

    -
      -
    • -

      In an unordered map, the order of entries - in the map is implementation dependent; it may, for example, - be the result of a randomized hashing algorithm.

      -
    • -
    • -

      In an ordered map, the order of entries is predictable + in Section 2.9.5 Map ItemsDM. + In an ordered map, the order of entries is predictable and depends on the order in which they were added to the map.

      -
    • -
    @@ -14633,12 +14622,12 @@
    4.13.1.1
  • The order of key-value - pairs in the map constructor is now retained in the constructed map.  [Issue 564 PR 1609 25 November 2024]

    + pairs in the map constructor is now retained in the constructed map.  [Issue 1651 PR 1703 14 January 2025]

  • A map can be created using a MapConstructor.

    -

  • Digits
    +
    @@ -14767,7 +14756,7 @@
    4.13.1.1
    -
    Example: Constructing a fixed map
    +
    Example: Constructing a fixed map

    The following expression constructs a map with seven entries:

     {
    @@ -14784,7 +14773,7 @@ 
    4.13.1.1  

    -
    Example: Constructing nested maps
    +
    Example: Constructing nested maps

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

     
    @@ -14938,7 +14927,7 @@ 
    4.13.2.1 Atomization).

    An array is created using an ArrayConstructor.

    -
    MapConstructor
    +
    @@ -15124,7 +15113,7 @@

    4.13.3
    4.13.3.1 Postfix Lookup Expressions
    -

    ArrayConstructor
    +
    @@ -15615,7 +15604,7 @@
    4.13.3.1
    4.13.3.2 Unary Lookup
    -
    LookupExpr
    +
    @@ -15626,14 +15615,14 @@
    4.13.3.2 -
    + - + + @@ -15982,7 +15971,7 @@
    4.13.3.3 -
    Example: Comparison with JSONPath
    +
    Example: Comparison with JSONPath

    This example provides XPath equivalents to some examples given in the JSONPath specification. [TODO: add a reference].

    The examples query the result of parsing the following JSON value, representing @@ -16233,7 +16222,7 @@

    4.13.4

    UnaryLookupModifierModifier ::= "pairs" | "keys" | "values" | "items"
    KeySpecifierKeySpecifier ::= NCName | IntegerLiteral | StringLiteral | VarRef | ParenthesizedExpr | LookupWildcard @@ -15642,7 +15631,7 @@
    4.13.3.2 -
    LookupWildcardLookupWildcard ::= "*"
    +
    @@ -16298,15 +16287,14 @@

    4.13.4 entry orderDM), and the context size is the number of entries in the map. The result of the expression is a map containing those entries of the input map for which the predicate truth value of the FILTER expression is true. - The ordered property of the result is the same as the ordered - property of the input map, and in the case of an ordered map, the relative order of - entries in the result retains the relative order of entries in the input. + The relative order of entries in the result retains the relative order of entries in the input.

    For example, the following expression:

    @@ -16444,7 +16430,7 @@

    4.14

    FilterExprAM
    +
    @@ -16496,7 +16482,7 @@

    4.14 -

    + @@ -16629,7 +16615,7 @@

    4.15

    IfExprEnclosedExprEnclosedExpr ::= "{" Expr? "}"
    +
    @@ -16672,7 +16658,7 @@

    4.16

    OtherwiseExpr
    +
    @@ -16692,7 +16678,7 @@

    4.16 -

    + @@ -16849,7 +16835,7 @@

    4.17

    4.17.1 Instance Of

    -

    QuantifiedExprTypeDeclarationTypeDeclaration ::= "as" SequenceType
    +
    @@ -16910,7 +16896,7 @@

    4.17.1

    4.17.2 Cast

    -

    InstanceofExpr
    +
    @@ -16930,14 +16916,14 @@

    4.17.2

    - + - + @@ -17057,7 +17043,7 @@

    4.17.2

    4.17.3 Castable

    -

    CastExpr
    ChoiceItemTypeChoiceItemType ::= "(" (ItemType ++ "|") ")"
    EnumerationTypeEnumerationType ::= "enum" "(" (StringLiteral ++ ",") ")"
    +
    @@ -17068,7 +17054,7 @@

    4.17.3 -

    + + - + @@ -17232,7 +17218,7 @@

    4.17.4

    4.17.5 Treat

    -

    CastableExprCastTargetCastTarget ::= TypeName | ChoiceItemType | EnumerationType @@ -17077,14 +17063,14 @@

    4.17.3 -

    ChoiceItemTypeChoiceItemType ::= "(" (ItemType ++ "|") ")"
    EnumerationTypeEnumerationType ::= "enum" "(" (StringLiteral ++ ",") ")"
    +
    @@ -17328,7 +17314,7 @@

    4.17.5

    4.18 Simple map operator (!)

    -

    TreatExpr
    +
    @@ -17446,7 +17432,7 @@

    4.18 4.19 Arrow Expressions

    Arrow expressions apply a function to a value, using the value of the left-hand expression as the first argument to the function.

    -
    SimpleMapExpr
    +
    @@ -17509,7 +17495,7 @@

    4.19 -

    + @@ -17517,14 +17503,14 @@

    4.19 -

    + - + @@ -19414,7 +19400,7 @@

    A.3

    A.3.1 Terminal Symbols

    -

    ArrowExprInlineFunctionExprInlineFunctionExpr ::= ("function" | "fn") FunctionSignature? FunctionBody ArgumentListArgumentList ::= "(" ((PositionalArguments ("," KeywordArguments)?) | KeywordArguments)? ")"
    PositionalArgumentListPositionalArgumentList ::= "(" PositionalArguments? ")"
    +
    @@ -19695,7 +19681,7 @@

    A.3.1 A.1 EBNF.

    -

    IntegerLiteral
    +
    @@ -24989,7 +24975,7 @@

    J A.1.1 Notation

  • -

    PR 1609 

    +

    PR 1703 

    Ordered maps are introduced.

    See 4.13.1 Maps

    The order of key-value diff --git a/pr/1703/xquery-40/xpath-40.xml b/pr/1703/xquery-40/xpath-40.xml index 8b992a620..3110a3229 100644 --- a/pr/1703/xquery-40/xpath-40.xml +++ b/pr/1703/xquery-40/xpath-40.xml @@ -1,6 +1,6 @@ XML Path Language (XPath) 4.0 WG Review Draft

    W3C

    XML Path Language (XPath) 4.0 WG Review Draft

    -

    W3C Editor's Draft 14 January 2025

    This version:
    https://qt4cg.org/pr/1703/xpath-40/
    Most recent version of XPath:
    +

    W3C Editor's Draft 15 January 2025

    This version:
    https://qt4cg.org/pr/1703/xpath-40/
    Most recent version of XPath:
    https://qt4cg.org/specifications/xpath-40/
    Most recent Recommendation of XPath:
    https://www.w3.org/TR/2017/REC-xpath-31-20170321/ @@ -6460,7 +6460,7 @@ item, and can appear as an item in a sequence.

    -

    4.13.1 Maps

    Changes in 4.0  

    1. Ordered maps are introduced.  [Issue 564 PR 1609 25 November 2024]

    +

    4.13.1 Maps

    Changes in 4.0  

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

    [Definition: A map is a function that associates a set of keys with values, resulting in a collection of key / value pairs.] @@ -6472,21 +6472,18 @@ item, and can appear as an item in a sequence.

    Section 2.9.5 Map ItemsDM. For an overview of the functions available for processing maps, - see Section 17 MapsFO.

    Note:

    Maps in XPath 4.0 have a property called [TERMDEF dt-map-ordered IN DM40], - which takes the value true or false; a map - is accordingly said to be ordered or unordered. + see Section 17 MapsFO.

    Note:

    Maps in XPath 4.0 are ordered. The effect of this property is explained - in Section 2.9.5 Map ItemsDM. In summary:

    • In an unordered map, the order of entries - in the map is implementation dependent; it may, for example, - be the result of a randomized hashing algorithm.

    • In an ordered map, the order of entries is predictable - and depends on the order in which they were added to the map.

    + in Section 2.9.5 Map ItemsDM. + In an ordered map, the order of entries is predictable + and depends on the order in which they were added to the map.

    4.13.1.1 Map Constructors

    Changes in 4.0  

    1. In map constructors, the keyword map is now optional, so map { 0: false(), 1: true() } can now be written { 0: false(), 1: true() }, provided it is used in a context where this creates no ambiguity.   [Issue 1070 PR 1071 26 March 2024]

    2. The order of key-value - pairs in the map constructor is now retained in the constructed map.  [Issue 564 PR 1609 25 November 2024]

    A map can be created using a MapConstructor.

    -
  • Digits
    MapConstructor::="map"? "{" (MapConstructorEntry ** ",") "}"
    MapConstructorEntry::= + pairs in the map constructor is now retained in the constructed map.  [Issue 1651 PR 1703 14 January 2025]

    A map can be created using a MapConstructor.

    +
    MapConstructor::="map"? "{" (MapConstructorEntry ** ",") "}"
    MapConstructorEntry::= MapKeyExpr ":" MapValueExpr
    MapKeyExpr::= ExprSingle @@ -6564,7 +6561,7 @@ item, and can appear as an item in a sequence.

    MapConstructorEntry entries in the input.

    -

    The following expression constructs a map with seven entries:

    +

    The following expression constructs a map with seven entries:

     

    -

    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:

    +

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

     
     {
       "book": {
    @@ -6648,7 +6645,7 @@ item, and can appear as an item in a sequence.

    Atomization).

    An array is created using an ArrayConstructor.

    -
    ArrayConstructor::= +
    ArrayConstructor::= SquareArrayConstructor | CurlyArrayConstructor
    SquareArrayConstructor::="[" (ExprSingle ** ",") "]"
    CurlyArrayConstructor::="array" EnclosedExpr

    @@ -6721,7 +6718,7 @@ item, and can appear as an item in a sequence.

    4.13.3.3 Deep Lookup.

    4.13.3.1 Postfix Lookup Expressions
    -
    LookupExpr::= +
    LookupExpr::= PostfixExpr Lookup
    Lookup::=("?" | "??") (Modifier "::")? KeySpecifier @@ -6885,10 +6882,10 @@ item, and can appear as an item in a sequence.

    raises a dynamic error [err:FOAY0001]FO40

     

    -

    This example provides XPath equivalents to some examples given in the +

    This example provides XPath equivalents to some examples given in the JSONPath specification. [TODO: add a reference].

    The examples query the result of parsing the following JSON value, representing a store whose stock consists of four books and a bicycle:

    {
       "store": {
    @@ -7170,7 +7167,7 @@ declare function recursive-content($item as item()) as record(key, value)* {
                      [Issue 1159 PR 1163 20 April 2024]

  • Predicates in filter expressions for maps and arrays can now be numeric.   [Issue 1207 PR tba 15 May 2024]

  • -
    FilterExprAM::= +
    FilterExprAM::= PostfixExpr "?[" Expr "]"

    Maps and arrays can be filtered using the construct INPUT?[FILTER]. For example, $array?[count(.)=1] filters an array to retain only those members that @@ -7207,20 +7204,18 @@ return $array?[count(.) ge 2]

    returns:

    entry orderDM), and the context size is the number of entries in the map. The result of the expression is a map containing those entries of the input map for which the predicate truth value of the FILTER expression is true. - The ordered property of the result is the same as the ordered - property of the input map, and in the case of an ordered map, the relative order of - entries in the result retains the relative order of entries in the input. + The relative order of entries in the result retains the relative order of entries in the input.

    For example, the following expression:

    let map := { 1: "alpha", 2: "beta", 3: "gamma" }
    -return $map?[?key ge 2]

    returns:

    { 2: "beta", 3: "gamma" }

    Note:

    Filtering of maps based on numeric positions is not generally useful when - the map is unordered, because the order of entries is unpredictable; but it is available - in the interests of orthogonality.

    With an ordered map, a filter expression such as $map?[last()-1, last()] - might be used to return the last two entries.

    +return $map?[?key ge 2]

    returns:

    { 2: "beta", 3: "gamma" }

    Note:

    A filter expression such as $map?[last()-1, last()] + might be used to return the last two entries of a map in + entry orderDM.

    4.13.5 Pinned Maps and Arrays

    Unlike navigation within node trees derived from XML, navigation within a tree of maps and arrays derived from JSON is normally “downwards only”: there is no equivalent of the parent or ancestor axis. This means, for example, that having selected leav nodes in the tree @@ -7282,14 +7277,14 @@ return $map?[?key ge 2]

    returns:

    if (condition) { X } else { Y },
                    with the else part being optional.
                   [Issue 234 PR 284 23 January 2023]

    XPath 4.0 allows conditional expressions to be written in several different ways.

    -
    IfExpr::="if" "(" Expr ")" (UnbracedActions | BracedActions)
    UnbracedActions::="then" ExprSingle "else" ExprSingle +
    IfExpr::="if" "(" Expr ")" (UnbracedActions | BracedActions)
    UnbracedActions::="then" ExprSingle "else" ExprSingle
    BracedActions::= ThenAction ElseIfAction* ElseAction?
    ThenAction::= EnclosedExpr
    ElseIfAction::="else" "if" "(" Expr ")" EnclosedExpr
    ElseAction::="else" EnclosedExpr -
    EnclosedExpr::="{" Expr? "}"

    There are two formats with essentially the same semantics.

    • The unbraced expression if (C) then T else E is equivalent to +

    EnclosedExpr::="{" Expr? "}"

    There are two formats with essentially the same semantics.