ConceptioArchiveW3C TR
W3C TRopen access

xquery semantics

W3C · w3c_tr
W3C TR · Standards · License: Open Access
Open Source ↗
w3c, standard

XQuery 1.0 and XPath 2.0 Formal Semantics (Second Edition) /**/ code { font-family: monospace; }

div.constraint, div.issue, div.note, div.notice { margin-left: 2em; }

div.issue p.title { margin-left: -2em; }

ol.enumar { list-style-type: decimal; } ol.enumla { list-style-type: lower-alpha; } ol.enumlr { list-style-type: lower-roman; } ol.enumua { list-style-type: upper-alpha; } ol.enumur { list-style-type: upper-roman; }

li p { margin-top: 0.3em; margin-bottom: 0.3em; }

sup small { font-style: italic; color: #8F8F8F; } div.exampleInner pre { margin-left: 1em; margin-top: 0em; margin-bottom: 0em} div.exampleOuter {border: 4px double gray; margin: 0em; padding: 0em} div.exampleInner { background-color: #d5dee3; border-top-width: 4px; border-top-style: double; border-top-color: #d3d3d3; border-bottom-width: 4px; border-bottom-style: double; border-bottom-color: #d3d3d3; padding: 4px; margin: 0em } div.exampleWrapper { margin: 4px } div.exampleHeader { font-weight: bold; margin: 4px}

div.issue { border-bottom-color: black; border-bottom-style: solid; border-bottom-width: 1pt; margin-bottom: 20pt; }

th.issue-toc-head { border-bottom-color: black; border-bottom-style: solid; border-bottom-width: 1pt; }

table.small { font-size: x-small; }

a.judgment:visited, a.judgment:link { font-family: sans-serif; color: black; text-decoration: none } a.processing:visited, a.processing:link { color: black; text-decoration: none } a.env:visited, a.env:link { color: black; text-decoration: none } /**/ This version: http://www.w3.org/TR/2010/REC-xquery-semantics-20101214/ Latest version: http://www.w3.org/TR/xquery-semantics/ Previous versions: http://www.w3.org/TR/2009/PER-xquery-semantics-20090421/, http://www.w3.org/TR/2007/REC-xquery-semantics-20070123/ Editors: Denise Draper, Microsoft <[email protected]> Michael Dyck (XML Query WG) <[email protected]> Peter Fankhauser (XML Query WG), Infonyte GmbH <[email protected]> Mary Fernández (XML Query WG), AT&T Labs - Research <[email protected]> Ashok Malhotra (XML Query and XSL WGs), Oracle Corporation <[email protected]> Kristoffer Rose (XSL WG), IBM T.J. Watson Research Center <[email protected]> Michael Rys (XML Query WG), Microsoft <[email protected]> Jérôme Siméon (XML Query WG), IBM T.J. Watson Research Center <[email protected]> Philip Wadler (XML Query WG), University of Edinburgh <[email protected]> Please refer to the errata See also translations This document is also available in these non-normative formats: XML Change markings relative to first edition Copyright W3C ® MIT ERCIM Keio liability trademark document use Note: This paragraph is informative. This document defines formally the semantics of XQuery 1.0 [XQuery 1.0: An XML Query Language (Second Edition)] and XPath 2.0 [XML Path Language (XPath) 2.0 (Second Edition)] This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index This is one document in a set of eight documents that are being progressed to Edited Recommendation together (XPath 2.0, XQuery 1.0, XQueryX 1.0, XSLT 2.0, Data Model (XDM), Functions and Operators, Formal Semantics, Serialization). This document, published on 14 December 2010, is an Edited Recommendation Proposed Edited Recommendation XML Query Working Group XSL Working Group XML Activity This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web. This document incorporates changes made against the Recommendation [G Changes since the First Edition] first edition This specification is designed to be referenced normatively from other specifications defining a host language for it; it is not intended to be implemented outside a host language. The implementability of this specification has been tested in the context of its normative inclusion in host languages defined by the XQuery 1.0 XSLT 2.0 XQuery 1.0 implementation report XSLT 2.0 implementation report This document was produced by groups operating under the 5 February 2004 W3C Patent Policy public list of any patent disclosures public list of any patent disclosures Essential Claim(s) section 6 of the W3C Patent Policy 1 Introduction Normative and Informative Sections Preliminaries Introduction to the Formal Semantics Notations from grammar productions Notations for judgments Notations for environments Notations for inference rules Putting it together URIs, Namespaces, and Prefixes XML Values Formal values Examples of values The [XPath/XQuery] Type System XML Schema and the [XPath/XQuery] Type System Item types Content models Top level definitions Example of a complete Schema Functions and operators Basics Expression Context Static Context Resolving QNames to Expanded QNames Dynamic Context Processing Model Processing model Normalization mapping rules Static typing judgment Dynamic evaluation judgment Error Handling Concepts Document Order Atomization Effective Boolean Value Input Sources URI Literals Types Predefined Schema Types Typed Value and String Value SequenceType Syntax SequenceType Matching Comments XML-defined Terminals Expressions Primary Expressions Literals Variable References Parenthesized Expressions Context Item Expression Function Calls Path Expressions Steps Axes Node Tests Predicates Unabbreviated Syntax Abbreviated Syntax Sequence Expressions Constructing Sequences Filter Expressions Combining Node Sequences Arithmetic Expressions Comparison Expressions Value Comparisons General Comparisons Node Comparisons Logical Expressions Constructors Direct Element Constructors Attributes Namespace Declaration Attributes Content Boundary Whitespace Other Direct Constructors Computed Constructors Computed Element Constructors Computed Attribute Constructors Document Node Constructors Text Node Constructors Computed Processing Instruction Constructors Computed Comment Constructors In-scope Namespaces of a Constructed Element [For/FLWOR] Expressions FLWOR expressions For expression Let Expression Order By and Return Clauses Ordered and Unordered Expressions Conditional Expressions Quantified Expressions Expressions on SequenceTypes Instance Of Typeswitch Cast Castable Constructor Functions Treat Validate Expressions Validating an Element Node Validating a Document Node Extension Expressions Modules and Prologs Version Declaration Module Declaration Boundary-space Declaration Default Collation Declaration Base URI Declaration Construction Declaration Ordering Mode Declaration Empty Order Declaration Copy-Namespaces Declaration Schema Import Module Import Namespace Declaration Default Namespace Declaration Variable Declaration Function Declaration Option Declaration Conformance Static Typing Feature Static Typing Extensions Additional Semantics of Functions Formal Semantics Functions The fs:convert-operand function The fs:convert-simple-operand function The fs:distinct-doc-order function The fs:distinct-doc-order-or-atomic-sequence function The fs:item-sequence-to-node-sequence function The fs:item-sequence-to-string function The fs:item-sequence-to-untypedAtomic-PI function The fs:item-sequence-to-untypedAtomic-text function The fs:item-sequence-to-untypedAtomic-comment function The fs:apply-ordering-mode function The fs:to function The fs:node-sequence function The fs:item-at function Standard functions with specific static typing rules The fn:last context function The fn:position context function The fn:abs, fn:ceiling, fn:floor, fn:round, and fn:round-half-to-even functions The fn:boolean and fn:not functions The fn:collection and fn:doc functions The fn:data function The fn:distinct-values function The fn:unordered function The fn:error function The fn:min, fn:max, fn:avg, and fn:sum functions The fn:remove function The fn:reverse function The fn:subsequence function The op:union, op:intersect, and op:except operators The fn:insert-before function The fn:zero-or-one, fn:one-or-more, and fn:exactly-one functions Auxiliary Judgments Judgments for accessing types Derives from Substitutes for Element and attribute name lookup (Dynamic) Element and attribute type lookup (Static) Extension Mixed content Type adjustment Builtin attributes Type expansion Union interpretation of derived types Judgments for step expressions and filtering Principal Node Kind Auxiliary judgments for axes Static semantics of axes Inference rules for all axes Inference rules for the self axis Inference rules for the child axis Inference rules for the attribute axis Inference rules for the parent axis Inference rules for the namespace axis Inference rules for the descendant axis Inference rules for the descendant-or-self axis Inference rules for the ancestor axis Inference rules for the ancestor-or-self axis Dynamic semantics of axes Auxiliary judgments for node tests Static semantics of node tests Name Tests Kind Tests Dynamic semantics of node tests Name Tests Kind Tests Judgments for type matching Matches Subtyping (<:) Judgments for FLWOR and other expressions on sequences Judgments for function calls Type promotion Judgments for validation modes and contexts Elements in validation mode A Normalized core and formal grammars Core BNF Formal BNF Index of judgments Functions and Operators Functions and Operators used in the Formal Semantics Mapping of Overloaded Internal Functions Importing Schemas Introduction Features Organization Main mapping rules Special attributes use, default, and fixed minOccurs, maxOccurs, minLength, maxLength, and length mixed nillable substitutionGroup Anonymous type names Schemas as a whole Schema Include Redefine Import Attribute Declarations Global attributes declarations Local attribute declarations Element Declarations Global element declarations Local element declarations Complex Type Definitions Global complex type Local complex type Complex type with simple content Complex type with complex content Attribute Uses Attribute Group Definitions Attribute group definitions Attribute group reference Model Group Definitions Model Groups All groups Choice groups Sequence groups Particles Element reference Group reference Wildcards Attribute wildcards Element wildcards Identity-constraint Definitions Notation Declarations Annotation Simple Type Definitions Global simple type definition Local simple type definition Simple type content References Normative References Non-normative References Background References Auxiliary Judgments for Validation Judgments for the validate expression Type resolution Interleaving Attribute filtering Erasure Simply erases Erases Annotate Simply annotate Nil-annotate Annotate Changes since the First Edition This document defines the formal semantics of XQuery 1.0 and XPath 2.0. The present document is part of a set of documents that together define the XQuery 1.0 and XPath 2.0 languages: [XQuery 1.0: An XML Query Language (Second Edition)] [XML Path Language (XPath) 2.0 (Second Edition)] [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] [XSLT 2.0 and XQuery 1.0 Serialization (Second Edition)] The scope and goals for the [XPath/XQuery] language are discussed in the charter of the W3C [XSL/XML Query] Working Group and in the [XPath/XQuery] requirements [XML Query 1.0 Requirements] This document defines the semantics of [XPath/XQuery] by giving a precise formal meaning to each of the expressions of the [XPath/XQuery] specification in terms of the [XPath/XQuery] data model. This document assumes that the reader is already familiar with the [XPath/XQuery] language. This document defines the formal semantics for XPath 2.0 only when the XPath 1.0 backward compatibility rules are not in effect. Two important design aspects of [XPath/XQuery] are that it is functional typed [XPath/XQuery] is a functional language [XPath/XQuery] is a typed language static type analysis [Schema Part 1] This document is organized as follows. [2 Preliminaries] [3 Basics] [4 Expressions] [5 Modules and Prologs] [XQuery 1.0: An XML Query Language (Second Edition)] [XML Path Language (XPath) 2.0 (Second Edition)] [3 Basics] [4 Expressions] [5 Modules and Prologs] [7 Additional Semantics of Functions] [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [8 Auxiliary Judgments] [D Importing Schemas] [8 Auxiliary Judgments] [4 Expressions] [D Importing Schemas] Certain aspects of language processing are described in this specification as implementation-defined implementation-dependent [ Definition Implementation-defined [ Definition Implementation-dependent A language aspect described in this specification as implementation-defined implementation dependent This document contains the normative static semantics of [XPath/XQuery]. The static semantics rules in [3 Basics] [4 Expressions] [5 Modules and Prologs] [7 Additional Semantics of Functions] [3.1.1 Static Context] [8 Auxiliary Judgments] The dynamic semantics of [XPath/XQuery] are normatively defined in [XQuery 1.0: An XML Query Language (Second Edition)] [XML Path Language (XPath) 2.0 (Second Edition)] [3 Basics] [4 Expressions] [5 Modules and Prologs] The mapping rules from XML Schema to the XQuery type system provided in [D Importing Schemas] [F Auxiliary Judgments for Validation] This section provides the background necessary to understand the Formal Semantics, introduces the notations that are used, and explains its relationship to other documents. Why a Formal Semantics? [XQuery 1.0: An XML Query Language (Second Edition)] [XML Path Language (XPath) 2.0 (Second Edition)] A rigorous formal semantics clarifies the intended meaning of the English specification, ensures that no corner cases are left out, and provides a reference for implementation. Why use formal notations? The Formal Semantics uses several kinds of formal notations to define the relationships between [XPath/XQuery] expressions, XML values, and XML Schema types. This section introduces the notations for judgments, inference rules, and mapping rules as well as the notation for environments, which implement the dynamic and static contexts. The reader already familiar with these notations can skip this section and continue with [2.3 XML Values] Grammar productions are used to describe "objects" (values, types, [XPath/XQuery] expressions, etc.) manipulated by the Formal Semantics. The Formal Semantics makes use of several kinds of grammar productions: productions from the [XPath/XQuery] grammar itself, productions for a subset of the [XPath/XQuery] language called the XQuery Core which is used throughout this document, and other productions used for formal specification only such as for the XQuery type system. XQuery grammar productions describe the XQuery language and expressions. XQuery productions are identified by a number, which corresponds to their number in the [XQuery 1.0: An XML Query Language (Second Edition)] 33 (XQuery) FLWORExpr XQ ::= ( ForClause LetClause WhereClause OrderByClause ExprSingle For the purpose of this document, the differences between the XQuery 1.0 and the XPath 2.0 grammars are mostly irrelevant. By default, this document uses XQuery 1.0 grammar productions. Whenever the grammar for XPath 2.0 differs from the one for XQuery 1.0, the corresponding XPath 2.0 productions are also given. XPath productions are identified by a number, which corresponds to their number in [XML Path Language (XPath) 2.0 (Second Edition)] 4 (XPath) ForExpr XP ::= SimpleForClause XQuery Core grammar productions describe the XQuery Core. The Core grammar is given in [A Normalized core and formal grammars] [A Normalized core and formal grammars] 24 (Core) FLWORExpr ::= ( ForClause LetClause ExprSingle The Formal Semantics manipulates "objects" (values, types, expressions, etc.) for which there is no existing grammar production in the [XQuery 1.0: An XML Query Language (Second Edition)] [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] 39 (Formal) Definition ::= ("define" "element" ElementName OptSubstitution OptNillable TypeReference AttributeName TypeReference TypeName TypeDerivation Note that grammar productions that are specific to the Formal Semantics (i.e., marked with "(Formal)") are not part of [XPath/XQuery]. They are not accessible to the user and are only used in the course of defining the languages' semantics. Grammar non-terminals are used extensively in this document to represent objects in judgments (see the next section). As a convenience, non-terminals used in judgments link to the appropriate grammar production. The basic building block of the formal specification is called a judgment For example: Notation The judgment Object is a positive integer holds if the object Object A judgment may hold (if it is true) or not hold (if it is false). For instance '1 is a positive integer is a positive integer Notation Here are two other example judgments. The judgment Expr => Value holds if the expression Expr Value The judgment Expr : Type holds if the expression Expr Type Most other judgments used in this document are short English sentences intended to reflect their meaning. For instance, the judgment Axis has principal PrincipalNodeKind holds if PrincipalNodeKind Axis A judgment can contain symbols patterns Symbols are purely syntactic and are used to write the judgment itself. Symbols are chosen to reflect a judgment's meaning, and are written in bold fonts. For example, ' is a positive integer => : Patterns are used to represent objects, constructed from a given grammar production. In patterns, italicized words usually correspond to non-terminals in the grammar. The name of those non-terminals is significant, and may be instantiated only to an "object" (a value, a type, an expression, etc.) that can be substituted legally for that non-terminal. For example, ' Expr Expr 1 Expr 2 Value Non-terminals in a pattern may appear with subscripts (e.g. Expr 1 Expr 2 BaseTypeName TypeName TypeName 2 When instantiating => => Expr => Value => => In some cases, inference rules may need to use the fact that a certain judgment does not not Judgment Judgment In some cases, a pattern may be instantiated to a value within a finite set of pre-determined values. We may write that set of possible values using the in Color in blue green holds if the pattern Color blue green In some cases, a judgment may use the "=" sign to indicate that a given value is equal to another value, or that a pattern is equal to a given value. For instance, the judgment Color blue holds if the pattern Color blue An index to all the judgments used in this specification is provided in [B Index of judgments] An environment component is a dictionary that maps a symbol (e.g., a function name or a variable name) to an "object" (e.g., a function body, a type, a value). One can access information in an environment component or update it. If "envComp" is an environment component, then "envComp( symbol symbol symbol symbol This document uses environments symbol symbol The two main environments used in the Formal Semantics are: a dynamic environment ( dynEnv statEnv [3.1 Expression Context] For example, dynEnv varValue dynEnv varValue Variable Variable Environments are used in a judgment to capture some of the context in which the judgment is computed, and most judgments are computed assuming that some environment is given. This assumption For instance, the judgment dynEnv |- Expr => Value is read as: Assuming the dynamic environment dynEnv Expr Value Environments can be updated "env + envComp( symbol object env envComp symbol object symbol object symbol object In case the environment component contains only a constant value (e.g., the ordering mode which can only be either ordered or unordered), the following notation is used to set its value. "env + envComp( object The following shorthand is also allowed: "env + envComp( symbol 1 object 1 symbol n object n This notation is equivalent to nested updates, as in " (env + envComp( symbol 1 object 1 symbol n object n Updating an environment creates a copy of the original environment and overrides any previous binding that might exist for the same name and the same component in that environment. Updating the environment is used to capture the scope let $x := 1 return let $x := $x + 2 return $x - 3 each let expression changes the dynamic context by binding a new variable to a new value. Each different context is represented by a different environment. The original environment, in which the expression 1 $x $x 1 $x + 2 $x 3 $x - 3 Also, note that there are no operations to remove entries from environments. This is never necessary as updating an environment effectively creates a new extended copy of the original environment, leaving the original environment accessible wherever it is in scope along with the updated copy. Inference rules are used to specify how to infer whether a given judgment holds or not. Inference rules express the logical relation between judgments and describe how complex judgments can be concluded from simpler premise judgments. A logical inference rule is written as a collection of premise conclusion premise 1 premise n conclusion All premises and the conclusion are judgments. From a logical point of view, an inference rule is a deduction that if the premises hold, then the conclusion holds as well. In that sense, the previous inference rule has a similar meaning as the following logical statement. IF premise 1 AND ... AND premise n THEN conclusion Here is a simple example of inference rule, which uses specific instances of the example judgment ' Expr => Value $x => => $x + 3 => This inference rule expresses the following property: if and then An inference rule may have no premises above the line, which means that the expression below the line always holds. For instance: 3 => This inference rule expresses the following property: evaluating the literal expression '3' always yields the value '3'. The two above rules are expressed in terms of specific expressions and values, but usually rules are more abstract. That is, the judgments are not fully instantiated. Here is a rule that says that for any variable $ VarName Integer $ VarName => Integer $ VarName => Integer Each occurrence of a given pattern in a particular inference rule must be instantiated to the same "object" within the entire rule. This means that, in the context of a particular instantiation of a rule, one can talk about "the value of $ VarName VarName Here is an example of a rule occurring later in this document. statEnv |- Expr 1 : Type 1 statEnv |- Expr 2 : Type 2 statEnv |- Expr 1 Expr 2 : Type 1 Type 2 This rule is read as follows: if two expressions Expr 1 Expr 2 Type 1 Type 2 Expr 1 Expr 2 Type 1 Type 2 Type 1 Type 2 The following rule defines the static semantics of a "let" expression. The binding of the new variable is captured by an update to the varType component of the original static environment. statEnv |- VarName of var expands to expanded-QName statEnv |- Expr 1 : Type 1 statEnv varType expanded-QName Type 1 |- Expr 2 : Type 2 statEnv |- let $ VarName Expr 1 return Expr 2 : Type 2 This rule is read as follows: First, because the variable is a QName, it is first expanded into an expanded QName. Second, the type Type 1 Expr 1 expanded-QName Type 1 statEnv Type 2 Expr 2 In some cases, ellipses may be used in inference rules to handle an arbitrary number of judgments. In those cases, some of the patterns may have indices as subscript. If the same index is used several times within the same rule, the number of judgment in each case must be the same. For instance, the following rule holds for any number of expressions, from Expr 1 Expr n Type 1 Type n statEnv |- QName of func expands to expanded-QName statEnv |- Expr 1 : Type 1 ... statEnv |- Expr n : Type n statEnv |- expanded-QName Type 1 Type n : Type statEnv |- QName Expr 1 Expr n : Type This inference rule is equivalent to having an unbounded number of rules, the first of which has 1 judgment, the second of which has 2 judgments, etc. For instance, the above rule holds if and only if one of the following rules hold. statEnv |- QName of func expands to expanded-QName statEnv |- Expr 1 : Type 1 statEnv |- expanded-QName Type 1 : Type statEnv |- QName Expr 1 : Type or statEnv |- QName of func expands to expanded-QName statEnv |- Expr 1 : Type 1 statEnv |- Expr 2 : Type 2 statEnv |- expanded-QName Type 1 Type 2 : Type statEnv |- QName Expr 1 Expr 2 : Type etc. When ellipses are used, the value for the index always ranges from 1 to an arbitrary number n. In isolation, each inference rule describes a fragment of the semantics for a given judgment. Put together, inference rules describe possible inferences that can be used to decide whether a particular judgment holds. For a given judgment, if that judgment can be inferred to be true by applying any sequence of inferences based on premises which are known to be true, the inference succeeds. In most cases, the inference will proceed by proving intermediate judgments, following the consequences from one judgment to the next by applying successive inference rules. Such inference is a mechanism which can be used to describe both static type analysis and dynamic evaluation. More specifically, performing static typing consists in proving that the following judgment holds for a given expression Expr statEnv |- Expr : Type If the judgment holds for a given type Type Consider the following expression. fn:count((1,2,3)) Using the static typing rules given for expressions in the rest of this document, one can deduce that the expression is of type xs:integer statEnv |- 1 : xs:integer (from typing of literals) statEnv |- 2 : xs:integer (from typing of literals) --------------------------------------------------- (sequence) statEnv |- 1,2 : xs:integer, xs:integer statEnv |- 3 : xs:integer ----------------------------------------------------- (sequence) statEnv |- 1,2,3 : xs:integer, xs:integer, xs:integer

declare function fn:count($x as item()*) as xs:integer statEnv |- xs:integer,xs:integer,xs:integer <: item()* ---------------------------------------------------------- (function call) statEnv |- fn:count((1,2,3)) : xs:integer Conversly, consider the following expression. fn:nilled((1,2,3)) Using the static typing rules given for expressions in the rest of this document, one can apply inference rules up to the following point. .... ----------------------------------------------------- (sequence) statEnv |- 1,2,3 : xs:integer, xs:integer, xs:integer However, there is no rule that can infer the type of fn:nilled((1,2,3)) (xs:integer,xs:integer,xs:integer) fn:nilled Note that in some cases, the inference can only proceed through the appropriate changes to the environment. For instance, consider the following expression. let $x := 1 return ($x,$x) Using the static typing rules given for expressions in the rest of this document, one can deduce that the expression is of type (xs:integer,xs:integer) statEnv0.varType = ()

-------------------------- (literal) statEnv0 |- 1 : xs:integer

statEnv1 = statEnv0 + varType($x => xs:integer)

statEnv1.varType($x) = xs:integer --------------------------------- (variable reference) statEnv1 |- $x : xs:integer

statEnv1.varType($x) = xs:integer --------------------------------- (variable reference) statEnv1 |- $x : xs:integer

------------------------------------------- (sequence) statEnv1 |- ($x,$x) : xs:integer,xs:integer

-------------------------------------------------------------- (let) statEnv0 |- let $x := 1 return ($x,$x) : xs:integer,xs:integer This example illustrates how each rule is applied to individual sub-expressions, and how the environment is used to maintain the relevant context information. The Formal Semantics does not formally specify the adjustment of relative URIs according to a base URI. All URIs used in this document are assumed to be absolute URIs. The Formal Semantics uses the following namespace prefixes. fn: [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] xs: These prefixes are assumed to be bound to the appropriate URIs. In addition, the Formal Semantics uses the following special prefixes for specification purposes. dm: [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] op: [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] fs: These prefixes are always italicized to emphasize that the corresponding functions, variables, and types are abstract: they are not and cannot be made accessible in [XPath/XQuery]. None of these special prefixes are given an explicit URI, but they behave as if they had one for the purposes of namespace resolution. The [XPath/XQuery] language is defined over values of the [XPath/XQuery] data model. The [XPath/XQuery] data model is defined normatively in [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] This section gives the grammar for formal values, along with a summary of the corresponding data model properties. In the context of this document, all constraints on values that are specified in [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] A value is a sequence of zero or more items. An item is either an atomic value or a node. An atomic value is a value in the value space of an atomic type, labeled with the name of that atomic type. An atomic type is either a primitive or derived atomic type according to XML Schema [Schema Part 2] xs:untypedAtomic xs:anyAtomicType A node is either an element, an attribute, a document, a text, a comment, or a processing-instruction node. Element nodes have a type annotation XQ type annotation XQ xs:untypedAtomic A simple value is a sequence of atomic values. A complex value is a sequence of attribute nodes followed by a sequence of element, text, comment, or processing-instruction nodes. A type annotation XQ QName fs: fs: 0 fs: 1 Formal values are defined by the following grammar. 7 (Formal) Value ::= Item Value Value 21 (Formal) Item ::= NodeValue AtomicValue 22 (Formal) AtomicValue ::= AtomicValueContent TypeAnnotation 1 (Formal) AtomicValueContent ::= String 2 (Formal) TypeAnnotation ::= "of" "type" TypeName 9 (Formal) ElementValue ::= "element" ElementName TypeAnnotation Value NamespaceBindings 10 (Formal) AttributeValue ::= "attribute" AttributeName TypeAnnotation SimpleValue 8 (Formal) SimpleValue ::= AtomicValue SimpleValue SimpleValue 11 (Formal) DocumentValue ::= "document" "{" Value 13 (Formal) CommentValue ::= "comment" "{" String "}" 14 (Formal) ProcessingInstructionValue ::= "processing-instruction" NCName 12 (Formal) TextValue ::= "text" "{" String "}" 20 (Formal) NodeValue ::= ElementValue AttributeValue DocumentValue TextValue CommentValue ProcessingInstructionValue 3 (Formal) ElementName ::= QName 6 (Formal) AttributeName ::= QName 23 (Formal) TypeName ::= QName 15 (Formal) NamespaceBindings ::= NamespaceBinding NamespaceBinding 17 (Formal) NamespaceBinding ::= "namespace" NCName Notation In the production for AtomicValueContent String xs:string Boolean xs:boolean expanded-QName xs:QName String "" "a" "John" xs:string StringLiteral Element (resp. attributes) without type annotations, are assumed to have the type annotation xs:anyType xs:anySimpleType "Hello, World!" "Hello, World!" of type xs:string Untyped elements (e.g., from well-formed documents) have the type annotation XQ xs:untyped type annotation XQ xs:untypedAtomic type annotation XQ xs:untypedAtomic An element has an optional "nilled" marker. This marker is present only if the element has been validated against an element type in the schema which is "nillable", and the element has no content and an attribute xsi:nil "true" An element also has a sequence of namespace bindings, which are the set of in-scope namespaces for that element. Each namespace binding is a prefix, URI pair. Elements without namespace bindings are assumed to have an empty set of in-scope namespaces. Note: In [XPath] namespace nodes namespace axis [XML Path Language (XPath) 2.0 (Second Edition)] A well-formed document <fact>The cat weighs <weight units="lbs">12</weight> pounds.</fact> In the absence of a Schema, this document is represented as element fact of type xs:untyped { text { "The cat weighs " }, element weight of type xs:untyped { attribute units of type xs:untypedAtomic { "lbs" of type xs:untypedAtomic }, text { "12" } }, text { " pounds." } } A document before and after validation. <weight xsi:type="xs:integer">42</weight> The formal model for values can represent values before and after validation. Before validation, this element is represented as: element weight of type xs:untyped { attribute xsi:type of type xs:untypedAtomic { "xs:integer" of type xs:untypedAtomic }, text { "42" } } After validation, this element is represented as: element weight of type xs:integer { attribute xsi:type of type xs:QName { "xs:integer" of type xs:QName }, 42 of type xs:integer } An element with a list type <sizes>1 2 3</sizes> Before validation, this element is represented as: element sizes of type xs:untyped { text { "1 2 3" } } Assume the following Schema. <xs:element name="sizes" type="sizesType"/> <xs:simpleType name="sizesType"> <xs:list itemType="sizeType"/> </xs:simpleType> <xs:simpleType name="sizeType"> <xs:restriction base="xs:integer"/> </xs:simpleType> After validation against this Schema, the element is represented as: element sizes of type sizesType { 1 of type sizeType, 2 of type sizeType, 3 of type sizeType } An element with an anonymous type <sizes>1 2 3</sizes> Before validation, this element is represented as: element sizes of type xs:untyped { text { "1 2 3" } } Assume the following Schema. <xs:element name="sizes"> <xs:simpleType> <xs:list itemType="xs:integer"/> </xs:simpleType> </xs:element> After validation, this element is represented as: element sizes of type fs:anon1 { 1 of type xs:integer, 2 of type xs:integer, 3 of type xs:integer } where fs: 1 sizes A nillable element with xsi:type set to true <sizes xsi:nil="true"/> Before validation, this element is represented as: element sizes of type xs:untyped { attribute xsi:nil of type xs:untypedAtomic { "true" of type xs:untypedAtomic } } Assume the following Schema. <xs:element name="sizes" type="sizesType" nillable="true"/> After validation against this Schema, the element is represented as: element sizes nilled of type sizesType { attribute xsi:nil of type xs:boolean { true of type xs:boolean } } An element with a union type <sizes>1 two 3 four</sizes> Before validation, this element is represented as: element sizes of type xs:untyped { text { "1 two 3 four" } } Assume the following Schema: <xs:element name="sizes" type="sizesType"/> <xs:simpleType name="sizesType"> <xs:list itemType="sizeType"/> </xs:simpleType> <xs:simpleType name="sizeType"> <xs:union memberType="xs:integer xs:string"/> </xs:simpleType> After validation against this Schema, the element is represented as: element sizes of type sizesType { 1 of type xs:integer, "two" of type xs:string, 3 of type xs:integer, "four" of type xs:string } The [XPath/XQuery] type system is used in the specification of the dynamic and of the static semantics of [XPath/XQuery]. This section introduces formal notations for describing types. The [XPath/XQuery] type system is based on [Schema Part 1] [Schema Part 2] [Schema Part 1] [Schema Part 2] Representation of content models. + * ? | All groups & Representation of anonymous types. Representation of XML Schema simple type facets and identity constraints. This document describes types in the [XPath/XQuery] types system, as well as the operations and properties over those types which are used to define the [XPath/XQuery] static typing feature. The two most important properties are whether a data instance matches a type, and whether a type is a subtype of another. Those properties are described in [8.3 Judgments for type matching] The mapping from XML Schema into the [XPath/XQuery] type system is given in [D Importing Schemas] [2.4.2 Item types] [2.4.3 Content models] [2.4.4 Top level definitions] An item type is either an atomic type, an element type, an attribute type, a document node type, a text node type, a comment node type, or a processing instruction type. We distinguish between document nodes, attribute nodes, and nodes that can occur in element content (elements, comments, processing instructions, and text nodes), as we need to refer to element content types later in the formal semantics. 25 (Formal) FormalItemType ::= AtomicTypeName NodeType 28 (Formal) AtomicTypeName ::= TypeName 26 (Formal) NodeType ::= DocumentType AttributeType ElementContentType 27 (Formal) ElementContentType ::= ElementType ProcessingInstructionType 29 (Formal) ElementType ::= "element" ElementNameOrWildcard OptTypeSpecifier 4 (Formal) ElementNameOrWildcard ::= QName 5 (Formal) AttributeNameOrWildcard ::= QName 77 (Formal) OptTypeSpecifier ::= TypeSpecifier 30 (Formal) TypeSpecifier ::= OptNillable TypeReference 31 (Formal) AttributeType ::= "attribute" AttributeNameOrWildcard OptTypeReference 75 (Formal) OptNillable ::= Nillable 32 (Formal) Nillable ::= "nillable" 78 (Formal) OptTypeReference ::= TypeReference 36 (Formal) TypeReference ::= "of" "type" TypeName 93 (Formal) ProcessingInstructionType ::= "processing-instruction" PITargetOrWildcard 94 (Formal) PITargetOrWildcard ::= NCName 45 (Formal) DocumentType ::= "document" ("{" Type An element or attribute type has a name or wildcard, and an optional type reference. A name alone corresponds to a reference to a global element or attribute declaration. A name with a type reference corresponds to a local element or attribute declaration. "element *" or "attribute *" alone refers to the wildcard types for any element or any attribute. In addition, an element type has an optional nillable flag that indicates whether the element can be nilled or not. A document type has an optional content type. If no content type is given, then the type is treated as being the wildcard type for documents, i.e., a sequence of text and element nodes. For consistency with element nodes, PIs and comments are not indicated in that wildcard type, but may occur in instances. Note Generic node types (e.g., node() [3.5.4 SequenceType Matching] Examples The following is a text node type text The following is a type for all elements element * of type xs:anyType The following is a type for all elements of type string element * of type xs:string The following is a type for a nillable element of type string and with name size element size nillable of type xs:string The following is a reference to a global attribute declaration attribute sizes The following is a type for elements with anonymous type fs: 1 element sizes of type fs:anon1 Following XML Schema, types in [XPath/XQuery] are composed from item types by optional, one or more, zero or more, all group sequence choice empty none The type empty none none Type none Type none [7.2.9 The fn:error function] 24 (Formal) Type ::= FormalItemType Type OccurrenceIndicator Type Type Type Type Type Type Type The [XPath/XQuery] type system includes three binary operators on types: ",", "|" and "&", corresponding respectively to sequence, choice and all groups The "&" operator builds the "interleaved product" of two types. The type Type 1 Type 2 Value 1 Value 2 Value 1 Type 1 Value 2 Type 2 Value 1 Value 2 Value 0 Value 0 Value 1 Value 2 all groups All groups For example, consider the types Type 1 xs:integer xs:integer xs:integer Type 2 xs:string xs:string Value 1 = (1,2,3) Type 1 Value 2 = ("a","b") Type 2 Value 0 Value 1 Value 2 Type 1 Type 2 Value0 = (1,2,3,"a","b") Value0 = (1,2,"a",3,"b") Value0 = (1,2,"a","b",3) Value0 = (1,"a",2,3,"b") Value0 = (1,"a",2,"b",3) Value0 = (1,"a","b",2,3) Value0 = ("a",1,2,3,"b") Value0 = ("a",1,2,"b",3) Value0 = ("a",1,"b",2,3) Value0 = ("a","b",1,2,3) Types precedence order # Operator 1 | (choice) 2 & (interleaving) 3 , (sequence) 4 *, +, ? (occurrence) Parenthesis can be used to enforce precedence. For instance xs:string | xs:integer, xs:float* is equivalent to xs:string | (xs:integer, (xs:float*)) and a different precedence can be obtained by writing ((xs:string | xs:integer), xs:float)* Examples A sequence of elements The "," operator builds the "sequence" of two types. For example, element title of type xs:string, element year of type xs:integer is a sequence of an element title of type string followed by an element year of type integer. The union of two element types The "|" operator builds the "union" of two types. For example, element editor of type xs:string | element bib:author means either an element editor of type string, or a reference to the global element bib:author An all group of two elements The "&" operator builds the "interleaved product" of two types. For example, (element a & element b) = element a, element b | element b, element a which specifies that the a b An empty type The following type matches the empty sequence. empty A sequence of zero or more elements The following type matches zero or more elements each of which can be a surgeon plumber (element surgeon | element plumber)* Notation The grammar for Type 42 (Formal) AttributeModel ::= AttributeType AttributeType AttributeModel AttributeModel 43 (Formal) ElementModel ::= ElementType ElementType ElementModel ElementModel Top level definitions correspond to global element declarations, global attribute declarations and type definitions in XML Schema. 40 (Formal) Definitions ::= ( Definition Separator Definitions 39 (Formal) Definition ::= ("define" "element" ElementName OptSubstitution OptNillable TypeReference AttributeName TypeReference TypeName TypeDerivation 76 (Formal) OptSubstitution ::= Substitution 41 (Formal) Substitution ::= "substitutes" "for" ElementName 33 (Formal) TypeDerivation ::= ComplexTypeDerivation AtomicTypeDerivation 34 (Formal) ComplexTypeDerivation ::= OptDerivation OptMixed Type 35 (Formal) AtomicTypeDerivation ::= "restricts" AtomicTypeName 95 (Formal) OptDerivation ::= Derivation 37 (Formal) Derivation ::= ("restricts" TypeName TypeName 74 (Formal) OptMixed ::= Mixed 38 (Formal) Mixed ::= "mixed" A type definition has a name (possibly anonymous) and a type derivation. In the case of a complex type, the derivation indicates whether it is derived by extension or restriction, its base type, and its content model, with an optional flag indicating if it has mixed content. Note the type system allows recursive types, following the rules defined in [Schema Part 1] Example For instance, the following complex type <complexType name="UKAddress"> <complexContent> <extension base="ipo:Address"> <sequence> <element name="postcode" type="ipo:UKPostcode"/> </sequence> <attribute name="exportCode" type="positiveInteger" fixed="1"/> </extension> </complexContent> </complexType> is represented as follows define type UKAddress extends ipo:Address { attribute exportCode of type positiveInteger, element postcode of type ipo:UKPostcode }; Example In the case of simple types derived by union or list, the derivation is always a restriction from the base type xs:anySimpleType <xsd:simpleType name="listOfMyIntType"> <xsd:list itemType="myInteger"/> </xsd:simpleType>

<xsd:simpleType name="zipUnion"> <xsd:union memberTypes="USState FrenchRegion"/> </xsd:simpleType> are represented as follows define type listOfMyIntType restricts xs:anySimpleType { myInteger* };

define type zipUnion restricts xs:anySimpleType { USState | FrenchRegion }; Example In the case of an atomic type, it just indicates its base type. For instance, the following type definition <xsd:simpleType name="SKU"> <xsd:restriction base="xsd:string"> <xsd:pattern value="\d{3}-[A-Z]{2}"/> </xsd:restriction> </xsd:simpleType> is represented as follows define type SKU restricts xsd:string; Example When the type derivation is omitted, the type derives by restriction from xs:anyType define type Bib { element book* }; define type Bib restricts xs:anyType { element book* }; Example Empty content can be indicated with the explicit empty sequence, or omitted, as in: define type Bib { }; define type Bib { empty }; Global element and attribute declarations always have a name and a reference to a (possibly anonymous) type. A global element declaration also may declare a substitution group for the element and whether the element is nillable. Example A type declaration with one element name xs:string street xs:string define type Address { element name of type xs:string, element street of type xs:string+ } Example A type declaration with complex content derived by extension define type USAddress extends Address { element zip of type xs:integer } Example A type declaration with mixed content define type Section mixed { (element h1 of type xs:string | element p of type xs:string | element div of type Section)* } Example A type declaration with simple content derived by restriction define type SKU restricts xs:string Example An element declaration define element address of type Address Example An element declaration with a substitution group define element usaddress substitutes for address of type USAddress Example An element declaration which is nillable define element zip nillable of type xs:integer Here is a schema describing purchase orders from [XML Schema Part 0] <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:annotation> <xsd:documentation xml:lang="en"> Purchase order schema for Example.com. Copyright 2000 Example.com. All rights reserved. </xsd:documentation> </xsd:annotation> <xsd:element name="purchaseOrder" type="PurchaseOrderType"/> <xsd:element name="comment" type="xsd:string"/> <xsd:complexType name="PurchaseOrderType"> <xsd:sequence> <xsd:element name="shipTo" type="USAddress"/> <xsd:element name="billTo" type="USAddress"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="items" type="Items"/> </xsd:sequence> <xsd:attribute name="orderDate" type="xsd:date"/> </xsd:complexType> <xsd:complexType name="USAddress"> <xsd:sequence> <xsd:element name="name" type="xsd:string"/> <xsd:element name="street" type="xsd:string"/> <xsd:element name="city" type="xsd:string"/> <xsd:element name="state" type="xsd:string"/> <xsd:element name="zip" type="xsd:decimal"/> </xsd:sequence> <xsd:attribute name="country" type="xsd:NMTOKEN" fixed="US"/> </xsd:complexType> <xsd:complexType name="Items"> <xsd:sequence> <xsd:element name="item" minOccurs="0" maxOccurs="unbounded"> <xsd:complexType> <xsd:sequence> <xsd:element name="productName" type="xsd:string"/> <xsd:element name="quantity"> <xsd:simpleType> <xsd:restriction base="xsd:positiveInteger"> <xsd:maxExclusive value="100"/> </xsd:restriction> </xsd:simpleType> </xsd:element> <xsd:element name="USPrice" type="xsd:decimal"/> <xsd:element ref="comment" minOccurs="0"/> <xsd:element name="shipDate" type="xsd:date" minOccurs="0"/> </xsd:sequence> <xsd:attribute name="partNum" type="SKU" use="required"/> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> <!-- Stock Keeping Unit, a code for identifying products --> <xsd:simpleType name="SKU"> <xsd:restriction base="xsd:string"> <xsd:pattern value="\d{3}-[A-Z]{2}"/> </xsd:restriction> </xsd:simpleType> </xsd:schema> Here is the mapping of the above schema into the [XPath/XQuery] type system. declare namespace xsd = "http://www.w3.org/2001/XMLSchema";

define element purchaseOrder of type PurchaseOrderType; define element comment of type xsd:string; define type PurchaseOrderType { attribute orderDate of type xsd:date?, element shipTo of type USAddress, element billTo of type USAddress, element comment?, element items of type Items };

define type USAddress { attribute country of type xsd:NMTOKEN, element name of type xsd:string, element street of type xsd:string, element city of type xsd:string, element state of type xsd:string, element zip of type xsd:decimal };

define type Items { attribute partNum of type SKU, element item of type fs:anon1* };

define type fs:anon1 { element productName of type xsd:string, element quantity of type fs:anon2, element USPrice of type xsd:decimal, element comment?, element shipDate of type xsd:date? };

define type fs:anon2 restricts xsd:positiveInteger;

define type SKU restrict xsd:string; Note that the two anonymous types in the item fs: 1 fs: 2 The following additional definitions illustrate how more advanced XML Schema features (a complex type derived by extension, an anonymous simple type derived by restriction, and substitution groups) are represented in the [XPath/XQuery] type system. <complexType name="NYCAddress"> <complexContent> <extension base="USAddress"> <sequence> <element ref="apt"/> </sequence> </extension> </complexContent> </complexType>

<element name="apt"> <xsd:simpleType> <xsd:restriction base="xsd:positiveInteger"> <xsd:maxExclusive value="10000"/> </xsd:restriction> </xsd:simpleType> </element>

<element name="usaddress" substitutionGroup="address" type="USAddress"/> <element name="nycaddress" substitutionGroup="usaddress" type="NYCAddress"/> The above definitions are mapped into the [XPath/XQuery] type system as follows: define type NYCAddress extends USAddress { element apt };

define element apt of type fs:anon3;

define type fs:anon3 restricts xsd:positiveInteger;

define element usaddress substitutes for address of type USAddress; define element nycaddress substitutes for usaddress of type NYCAddress; The [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [C.1 Functions and Operators used in the Formal Semantics] Many functions in the [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] generic fn:unordered fn:unordered fn:unordered($sourceSeq as item()*) as item()* As defined, this signature provides little useful type information. For such functions, better type information can often be obtained by having the output type depend on the type of input parameters. For instance, if the function fn:unordered a a In order to provide better static typing for those functions, specific static typing rules are given in [7 Additional Semantics of Functions] The organization of this section parallels the organization of Section 2 Basics XQ Introduction 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 the static context dynamic context Notation We introduce the following auxiliary grammar production to describe function signatures. 85 (Formal) FunctionSig ::= "declare" "function" expanded-QName "(" TypeList Type 86 (Formal) TypeList ::= Type Type In the static (and dynamic) context, each function is uniquely identified by its expanded QName and its arity (number of parameters). We introduce the auxilliary symbol FunctionKey 92 (Formal) FunctionKey ::= expanded-QName "," Arity ( Arity statEnv If analysis of an expression relies on some component of the static context that has not been assigned a value, a static error is raised. The following environment components are part of the static environment: statEnv xpath1.0_compatibility The statEnv xpath1.0_compatibility XPath 1.0 compatibility flag statEnv namespace The statEnv namespace statically known namespaces The statEnv namespace NCName namespace kind AnyURI passive active [XML Names 1.1] statEnv default_elem_namespace The statEnv default_elem_namespace default element/type namespace The statEnv default_elem_namespace AnyURI statEnv default_function_namespace The statEnv default_function_namespace default function namespace The statEnv default_function_namespace AnyURI statEnv typeDefn The statEnv typeDefn in-scope schema types The statEnv typeDefn TypeName Definition statEnv elemDecl The statEnv elemDecl in-scope element declarations The statEnv elemDecl ElementName Definition statEnv attrDecl The statEnv attrDecl in-scope attribute declarations The statEnv attrDecl AttributeName Definition statEnv varType The statEnv varType in-scope variables The statEnv varType VarName Type The context item static type $ fs: dot statEnv varType statEnv funcType The statEnv funcType function signatures The statEnv funcType FunctionKey QName FunctionSig statEnv collations The statEnv collations statically known collations The statEnv collations AnyURI statEnv defaultCollation The statEnv defaultCollation default collation The statEnv defaultCollation statEnv collations statEnv constructionMode The statEnv constructionMode construction mode The statEnv constructionMode preserve strip statEnv orderingMode The statEnv orderingMode ordering mode The statEnv orderingMode ordered unordered statEnv defaultEmptySequenceOrder The statEnv defaultEmptySequenceOrder default order for empty sequences The statEnv defaultEmptySequenceOrder order by greatest least statEnv boundarySpace The statEnv boundarySpace boundary-space policy The statEnv boundarySpace preserve strip statEnv copyNamespacesMode The statEnv copyNamespacesMode copy-namespaces mode The statEnv copyNamespacesMode preserve no-preserve inherit no-inherit statEnv baseURI The statEnv baseURI base URI The statEnv baseURI AnyURI statEnv docType The statEnv docType statically known documents fn:doc The statEnv docType AnyURI Type statEnv collectionType The statEnv collectionType statically known collections fn:collection The statEnv collectionType AnyURI Type statEnv defaultCollectionType The statEnv defaultCollectionType statically known default collection type fn:collection The statEnv defaultCollectionType Type Note that the boundary-space behavior is not formally specified in this document. An initial environment is set up when [expression/query] processing begins, containing, for example, the function signatures of all built-in functions. The initial values for the static context are defined in Section C Context Components XQ Section C Context Components XP statEnvDefault Here is an example that shows how the static environment is modified in response to a namespace definition. dynEnv |- URILiteral has atomic value AnyURI statEnv namespace NCName AnyURI |- Expr : Type statEnv |- declare namespace NCName URILiteral Expr : Type This rule reads as follows: "the phrase on the bottom (a namespace declaration in the query prolog followed by an expression) is well-typed (accepted by the static typing rules) within an environment statEnv if statEnv The helper function fs: active_ns statEnv For each attribute and element node in Value expanded-QName AnyURI fs: get_static_ns_from_items statEnv Value AnyURI statEnv namespace AnyURI A common use of the static environment is to expand a QName statEnv namespace expanded-QName DM #NULL-NAMESPACE The auxiliary judgments below expand an element, type, attribute, variable, or function QName statEnv namespace Notation The judgment statEnv |- QName of elem/type expands to expanded-QName holds when the element or type QName expands to the given expanded QName. The judgment statEnv |- QName of attr expands to expanded-QName holds when the attribute QName expands to the given expanded QName. We use Variable The judgment statEnv |- QName of var expands to Variable holds when the variable QName expands to the given expanded QName. The judgment statEnv |- QName of func expands to expanded-QName holds when the function QName expands to the given expanded QName. Semantics Note that none of the inference rules can infer a resolved name in the case a given namespace prefix is bound to the (#UNDECLARED) value. As a result, namespace resolution will fail if the implementation supports [XML Names 1.1] An element or type QName consisting of a prefix NCName and a local part NCName expands to the URI (or the null namespace) corresponding to that prefix and the local part. statEnv namespace NCName 1 NamespaceKind AnyURI-or-#NULL-NAMESPACE statEnv |- NCName 1 NCName 2 of elem/type expands to AnyURI-or-#NULL-NAMESPACE NCName 2 An element or type QName consisting only of a local part NCName expands to the default element/type namespace and the local part. statEnv default_elem_namespace AnyURI-or-#NULL-NAMESPACE statEnv |- NCName of elem/type expands to AnyURI-or-#NULL-NAMESPACE NCName An attribute QName consisting of a prefix NCName and a local part NCName expands to the URI (or the null namespace) corresponding to the prefix and the local part. statEnv namespace NCName 1 NamespaceKind AnyURI-or-#NULL-NAMESPACE statEnv |- NCName 1 NCName 2 of attr expands to AnyURI-or-#NULL-NAMESPACE NCName 2 An attribute QName consisting only of a local part NCName expands to the null namespace and the local part. statEnv |- NCName of attr expands to NCName A variable QName consisting of a prefix NCName and a local part NCName expands to the URI that corresponds to the prefix and the local part. statEnv namespace NCName 1 NamespaceKind AnyURI statEnv |- NCName 1 NCName 2 of var expands to AnyURI NCName 2 A variable QName consisting only of a local part NCName expands to the null namespace and the local part. statEnv |- NCName of var expands to NCName A function QName consisting of a prefix NCName and a local part NCName expands to the URI that corresponds to the prefix and the local part. statEnv namespace NCName 1 NamespaceKind AnyURI statEnv |- NCName 1 NCName 2 of func expands to AnyURI NCName 2 A function QName consisting only of a local part NCName expands to the default function namespace URI and the local part. statEnv default_function_namespace AnyURI statEnv |- NCName of func expands to AnyURI NCName dynEnv If evaluation of an expression relies on some component of the dynamic context that has not been assigned a value, a dynamic error is raised. The following environment components are part of the dynamic environment: dynEnv varValue The dynEnv varValue variable values context item context position context size The dynamic value environment component maps an expanded variable name (expanded VarName Value #IMPORTED AnyURI AnyURI dynEnv funcDefn The dynEnv funcDefn function implementations The dynEnv funcDefn FunctionKey [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] #BUILT-IN #EXTERNAL AnyURI #IMPORTED AnyURI Expr Variable 1 Variable n Expr Variable 1 Variable n The initial function environment component ( dynEnvDefault [C.2 Mapping of Overloaded Internal Functions] [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] #BUILT-IN dynEnv dateTime The dynEnv dateTime current dateTime dynEnv timezone The dynEnv timezone implicit timezone [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] dynEnv docValue The dynEnv docValue available documents fn:doc The dynEnv docValue AnyURI DocumentValue dynEnv collectionValue The dynEnv collectionValue available collections fn:collection The dynEnv collectionValue AnyURI dynEnv defaultCollectionValue The dynEnv defaultCollectionValue default collection fn:collection The dynEnv defaultCollectionValue The initial values for the dynamic context are defined in Section C Context Components XQ Section C Context Components XP dynEnvDefault The following Formal Semantics variables represent the context item context position context size Built-in Variable Represents: $ fs: dot context item $ fs: position context position $ fs: last context size Within this document, variables with the "fs" prefix are reserved for use in the formal specification. Values of $ fs: position $ fs: last fn:position fn:last $ fs: position $ fs: last xs:integer $ fs: dot This section reviews the processing model for [XPath/XQuery]. The [XPath/XQuery] processing model is defined normatively in Section 2.2 Processing Model XQ The following figure depicts the [XPath/XQuery] processing model Figure 1: Processing Model Overview This processing model is not intended to describe an actual implementation, although a naive implementation might be based upon it. It does not prescribe an implementation technique, but any implementation should produce the same results as obtained by following this processing model and applying the rest of the Formal Semantics specification. Query processing consists of two phases: a static analysis phase and a dynamic evaluation phase. Static analysis is further divided into four sub-phases. Typically, each phase consumes the result of the previous phase and generates output for the next phase. When processing query prologs, these phases may be mutually dependent (See [5 Modules and Prologs] [ Definition static analysis phase static analysis phase The purpose of the static analysis phase is to detect errors, e.g., syntax errors or type errors, at compile time rather than at run-time. If no error occurs, the result of static analysis could be some compiled form of [expression/query], suitable for execution by a compiled-[expression/query] processor. Static analysis consists of the following sub-phases: Parsing. [XQuery 1.0: An XML Query Language (Second Edition)] Static Context Processing. [5 Modules and Prologs] statEnv Normalization. for for Core language [A Normalized core and formal grammars] During the normalization phase, each [XPath/XQuery] [expression/query] is mapped into its equivalent [expression/query] in the Core. (Note that this has nothing to do with Unicode Normalization, which works on character strings.) Normalization works by recursive application of the normalization rules over a given expression. Specifically the normalization phase is defined in terms of the static part of the context ( statEnv Expr [3.2.2 Normalization mapping rules] After normalization, the full semantics is obtained by giving a semantics to the normalized Core [expression/query]. This is done during the last two phases. Static type analysis. Static type analysis checks whether each [expression/query] is well-typed, and if so, determines its static type. Static type analysis is defined only for Core [expression/query]. Static type analysis works by recursive application of the static typing rules over a given expression. If the [expression/query] is not well-typed, static type analysis yields a type error More precisely, the static analysis phase is defined in terms of the static context ( statEnv CoreExpr [3.2.3 Static typing judgment] Static typing does not imply that the content of XML documents must be rigidly fixed or even known in advance. The [XPath/XQuery] type system accommodates "flexible" types, such as elements that can contain any content. Schema-less documents are handled in [XPath/XQuery] by associating a standard type with the document, such that it may include any legal XML content. If the static analysis phase succeeds, the dynamic evaluation phase (sometimes also called "execution") evaluates a query on input document(s). Dynamic Context Processing. [5 Modules and Prologs] dynEnv Dynamic Evaluation. The dynamic evaluation phase is defined in terms of the static context ( statEnv dynEnv CoreExpr [3.2.4 Dynamic evaluation judgment] Static type analysis catches only certain classes of errors. For instance, it can detect a comparison operation applied between incompatible types (e.g., xs:int xs:date xs:int While implementations are free to implement different processing models, the [XPath/XQuery] static semantics relies on the existence of a static type analysis phase that precedes any access to the input data. The above processing phases are all internal to the [XPath/XQuery] processor. They do not deal with how the [XPath/XQuery] processor interacts with the outside world, notably how it accesses actual documents and types. A typical [expression/query] engine would support at least three other important processing phases: Schema Import Processing. [D Importing Schemas] Data Model Generation. [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] Serialization. [XSLT 2.0 and XQuery 1.0 Serialization (Second Edition)] The parsing phase is not specified formally; the formal semantics does not define a formal model for the syntax trees, but uses the [XPath/XQuery] concrete syntax directly. More details about parsing for XQuery 1.0 can be found in the [XQuery 1.0: An XML Query Language (Second Edition)] [XML Path Language (XPath) 2.0 (Second Edition)] Normalization is specified using mapping [D Importing Schemas] Notation Mapping rules are written using a square bracket notation, as follows: [ ] Subscript premises == Mapped Object The original "object", and an optional list of premises, is written above the = = [ Expr ] FunctionArgument( Type [4.1.5 Function Calls] Since normalization is always applied in the presence of a static context, the above rule is a shorthand for: statEnv |- statEnv |- [ ] Subscript Most normalization rules have no premises, so they are omitted. The static environment is used in certain normalization rules (e.g. for normalization of function calls). To keep the notation simpler, the static environment is not written in the normalization rules, but it is assumed to be available. The normalization rule that is used to map "top-level" expressions in the [XPath/XQuery] syntax into expressions in the [XPath/XQuery] Core is: [ Expr ] Expr == CoreExpr which indicates that the expression Expr CoreExpr statEnv Expr Expr 1 [ ] Expr == 1 To simplify the specification in some cases, some further normalization may be used on the right-hand side of a normalization rule. For instance, the following normalization rules for the / [ ] Expr == [ fn:root ] Expr Example For instance, the following [expression/query] for $i in (1, 2), $j in (3, 4) return element pair { ($i,$j) } is normalized to the Core expression for $i in (1, 2) return for $j in (3, 4) return element pair { ($i,$j) } {} in which the "FWLR" expression is mapped into a composition of two simpler "for" expressions. The static semantics is specified using static typing rules Notation The judgment statEnv |- Expr : Type holds when, in the static environment statEnv Expr Type Example The result of static type inference is to associate a static type with every [expression/query], such that any evaluation of that [expression/query] is guaranteed to yield a value that belongs to that type. For instance, the following expression. let $v := 3 return $v+5 has type xs:integer Note The type of an expression is computed by inference. Static typing rules define for each kind of expression how to compute the type of the expression given the types of its sub-expressions. Here is a simple example: statEnv |- Expr 1 : xs:boolean statEnv |- Expr 2 : Type 2 statEnv |- Expr 3 : Type 3 statEnv |- if Expr 1 then Expr 2 else Expr 3 : Type 2 Type 3 This rule states that if the conditional expression of an "if" expression has type boolean, then the type of the entire expression is one of the two types of its "then" and "else" clauses. Note that the resulting type is represented as a union: '( Type 2 Type 3 The part after the |- : below Expr 1 Expr 2 Expr 3 above The dynamic, or operational, semantics is specified using dynamic evaluation rules Notation The judgment statEnv dynEnv |- Expr => Value holds when, in the static environment statEnv dynEnv Expr Value The static environment is used in certain cases (e.g. for type matching) during evaluation. To keep the notation simpler, the static environment is not written in the dynamic evaluation rules, but it is assumed to be available. The inference rules used for dynamic evaluation, like those for static typing, follow a recursive structure, computing the value of expressions from the values of their sub-expressions. Expressions can raise errors during static analysis or dynamic evaluation. The [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [XQuery 1.0: An XML Query Language (Second Edition)] [XML Path Language (XPath) 2.0 (Second Edition)] fn:error This document does not describe formally the conditions under which dynamic errors are raised. Notably, it does not specify the error codes or the rules about errors and optimization, as described in [XQuery 1.0: An XML Query Language (Second Edition)] type error XQ [XPath/XQuery] is most generally used to process documents [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] Document order is defined in [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] Atomization converts an item sequence into a sequence of atomic values and is implemented by the fn:data If a sequence of items is encountered where a boolean value is expected, the item sequence's effective boolean value is used. The fn:boolean [XPath/XQuery] has several functions that provide access to input data, described in Section 2.4.4 Input Sources XQ [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] In certain places in the XQuery grammar, a statically known valid absolute URI is required. These places are denoted by the grammatical symbol URILiteral [XQuery 1.0: An XML Query Language (Second Edition)] All the built-in types of XML Schema are recognized by [XPath/XQuery]. In addition, [XPath/XQuery] recognizes the predefined types xs:anyAtomicType xs:untypedAtomic xs:untyped xs:yearMonthDuration xs:dayTimeDuration [ Definition xs:anyType define type xs:anyType restricts xs:anyType { ( attribute * of type xs:anySimpleType )*, ( xs:anyAtomicType* | ( element * of type xs:anyType | text | comment | processing-instruction * )* ) } [ Definition xs:anySimpleType define type xs:anySimpleType restricts xs:anyType { xs:anyAtomicType* } The name of the Ur simple type is xs:anySimpleType xs:anyType [ Definition The following type definition of xs:anyAtomicType xs:anyAtomicType define type xs:anyAtomicType restricts xs:anySimpleType { ( xs:string | xs:boolean | xs:decimal | xs:float | xs:double | xs:duration | xs:dateTime | xs:time | xs:date | xs:gYearMonth | xs:gYear | xs:gMonthDay | xs:gDay | xs:gMonth | xs:hexBinary | xs:base64Binary | xs:anyURI | xs:QName | xs:NOTATION | xs:untypedAtomic ) } [ Definition the XML Schema primitive types define type xs:string restricts xs:anyAtomicType; define type xs:boolean restricts xs:anyAtomicType; define type xs:decimal restricts xs:anyAtomicType; define type xs:float restricts xs:anyAtomicType; define type xs:double restricts xs:anyAtomicType; define type xs:duration restricts xs:anyAtomicType; define type xs:dateTime restricts xs:anyAtomicType; define type xs:time restricts xs:anyAtomicType; define type xs:date restricts xs:anyAtomicType; define type xs:gYearMonth restricts xs:anyAtomicType; define type xs:gYear restricts xs:anyAtomicType; define type xs:gMonthDay restricts xs:anyAtomicType; define type xs:gDay restricts xs:anyAtomicType; define type xs:gMonth restricts xs:anyAtomicType; define type xs:hexBinary restricts xs:anyAtomicType; define type xs:base64Binary restricts xs:anyAtomicType; define type xs:anyURI restricts xs:anyAtomicType; define type xs:QName restricts xs:anyAtomicType; define type xs:NOTATION restricts xs:anyAtomicType; All of those primitive types derive from xs:anyAtomicType xs:string [Schema Part 2] [ Definition xs:untypedAtomic define type xs:untypedAtomic restricts xs:anyAtomicType Note that this rule does not indicate the value space of xs:untypedAtomic xs:untypedAtomic xs:string The following example shows two atomic values. The first one is a value of type string containing "Database". The second one is an untyped atomic value containing "Database". "Databases" of type xs:string "Databases" of type xs:untypedAtomic [ Definition xs:untyped define type xs:untyped restricts xs:anyType { attribute * of type xs:untypedAtomic*, ( element * of type xs:untyped | text | comment | processing-instruction * )* } [ Definition XML Schema derived types define type xs:normalizedString restricts xs:string; define type xs:token restricts xs:normalizedString; define type xs:language restricts xs:token; define type xs:NMTOKEN restricts xs:token; define type xs:Name restricts xs:token; define type xs:NCName restricts xs:Name; define type xs:ID restricts xs:NCName; define type xs:IDREF restricts xs:NCName; define type xs:ENTITY restricts xs:NCName; define type xs:integer restricts xs:decimal; define type xs:nonPositiveInteger restricts xs:integer; define type xs:negativeInteger restricts xs:nonPositiveInteger; define type xs:long restricts xs:integer; define type xs:int restricts xs:long; define type xs:short restricts xs:int; define type xs:byte restricts xs:short; define type xs:nonNegativeInteger restricts xs:integer; define type xs:unsignedLong restricts xs:nonNegativeInteger; define type xs:unsignedInt restricts xs:unsignedLong; define type xs:unsignedShort restricts xs:unsignedInt; define type xs:unsignedByte restricts xs:unsignedShort; define type xs:positiveInteger restricts xs:nonNegativeInteger; Three XML Schema built-in derived types are derived by list, as follows. Note that those derive directly from xs:anySimpleType define type xs:NMTOKENS restricts xs:anySimpleType { xs:NMTOKEN+ }; define type xs:IDREFS restricts xs:anySimpleType { xs:IDREF+ }; define type xs:ENTITIES restricts xs:anySimpleType { xs:ENTITY+ }; For example, here is an element whose content is of type xs:IDREFS element a of type xs:IDREFS { "id1" of type xs:IDREF, "id2" of type xs:IDREF, "id3" of type xs:IDREF } Note that the type name xs:IDREFS xs:anySimpleType xs:IDREF a f1 f2 f3 declare function f1($x as element(*,xs:anySimpleType)) { $x } declare function f2($x as element(*,xs:IDREFS)) { $x } declare function f3($x as element(*,xs:IDREF)) { $x } [ Definition The totally ordered duration types xs:yearMonthDuration xs:dayTimeDuration xs:duration define type xs:yearMonthDuration restricts xs:duration; define type xs:dayTimeDuration restricts xs:duration; [ Definition fs: numeric define type fs:numeric restricts xs:anyAtomicType { xs:decimal | xs:float | xs:double } The typed value of a node is computed by the fn:data fn:string [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] Introduction Sequence types can be used in [XPath/XQuery] to refer to an XML Schema type. Sequence types are used to declare the types of function parameters and in several [XPath/XQuery] expressions. The syntax of sequence types is described by the following grammar productions. 119 (XQuery) SequenceType XQ ::= ("empty-sequence" "(" ")") ItemType OccurrenceIndicator 121 (XQuery) ItemType XQ ::= KindTest AtomicType 120 (XQuery) OccurrenceIndicator XQ ::= "?" | "*" | "+" 122 (XQuery) AtomicType XQ ::= QName 123 (XQuery) KindTest XQ ::= DocumentTest ElementTest AttributeTest SchemaElementTest SchemaAttributeTest PITest CommentTest TextTest AnyKindTest 125 (XQuery) DocumentTest XQ ::= "document-node" "(" ( ElementTest SchemaElementTest 133 (XQuery) ElementTest XQ ::= "element" "(" ( ElementNameOrWildcard TypeName 135 (XQuery) SchemaElementTest XQ ::= "schema-element" "(" ElementDeclaration 136 (XQuery) ElementDeclaration XQ ::= ElementName 129 (XQuery) AttributeTest XQ ::= "attribute" "(" ( AttribNameOrWildcard TypeName 131 (XQuery) SchemaAttributeTest XQ ::= "schema-attribute" "(" AttributeDeclaration 132 (XQuery) AttributeDeclaration XQ ::= AttributeName 134 (XQuery) ElementNameOrWildcard XQ ::= ElementName 138 (XQuery) ElementName XQ ::= QName 130 (XQuery) AttribNameOrWildcard XQ ::= AttributeName 137 (XQuery) AttributeName XQ ::= QName 139 (XQuery) TypeName XQ ::= QName 128 (XQuery) PITest XQ ::= "processing-instruction" "(" ( NCName StringLiteral 127 (XQuery) CommentTest XQ ::= "comment" "(" ")" 126 (XQuery) TextTest XQ ::= "text" "(" ")" 124 (XQuery) AnyKindTest XQ ::= "node" "(" ")" Core Grammar The Core grammar productions for sequence types are: 76 (Core) SequenceType ::= ("empty-sequence" "(" ")") ItemType OccurrenceIndicator 78 (Core) ItemType ::= KindTest AtomicType 77 (Core) OccurrenceIndicator ::= "?" | "*" | "+" 79 (Core) AtomicType ::= QName 80 (Core) KindTest ::= DocumentTest ElementTest AttributeTest SchemaElementTest SchemaAttributeTest PITest CommentTest TextTest AnyKindTest 82 (Core) DocumentTest ::= "document-node" "(" ( ElementTest SchemaElementTest 90 (Core) ElementTest ::= "element" "(" ( ElementNameOrWildcard TypeName 92 (Core) SchemaElementTest ::= "schema-element" "(" ElementDeclaration 93 (Core) ElementDeclaration ::= ElementName 86 (Core) AttributeTest ::= "attribute" "(" ( AttribNameOrWildcard TypeName 88 (Core) SchemaAttributeTest ::= "schema-attribute" "(" AttributeDeclaration 89 (Core) AttributeDeclaration ::= AttributeName 91 (Core) ElementNameOrWildcard ::= ElementName 95 (Core) ElementName ::= QName 87 (Core) AttribNameOrWildcard ::= AttributeName 94 (Core) AttributeName ::= QName 96 (Core) TypeName ::= QName 85 (Core) PITest ::= "processing-instruction" "(" ( NCName StringLiteral 84 (Core) CommentTest ::= "comment" "(" ")" 83 (Core) TextTest ::= "text" "(" ")" 81 (Core) AnyKindTest ::= "node" "(" ")" The semantics of SequenceTypes is defined by means of normalization rules from SequenceTypes into types in the [XPath/XQuery] type system (See [2.4 The [XPath/XQuery] Type System] However, the [XPath/XQuery] type system not being part of the [XPath/XQuery] syntax, the SequenceType syntax is still part of the [XPath/XQuery] Core. Normalization from SequenceTypes to types is not applied during the normalization phase but whenever a dynamic evaluation or static typing rule requires it. Introduction During processing of a query, it is sometimes necessary to determine whether a given value matches a type that was declared using the SequenceType syntax. This process is known as SequenceType matching, and is formally specified in [8.3 Judgments for type matching] Notation To define normalization of SequenceTypes to the [XPath/XQuery] type system, the following auxiliary mapping rule is used. [ SequenceType ] sequencetype == Type specifies that SequenceType Type Normalization OccurenceIndicators are left unchanged when normalizing SequenceTypes into [XPath/XQuery] types. Each kind of SequenceType component is normalized separately into the [XPath/XQuery] type system. [ ItemType OccurrenceIndicator ] sequencetype == [ ItemType ] sequencetype OccurrenceIndicator The "empty-sequence()" sequence type is mapped to the empty type. [ ] sequencetype == empty An atomic type is normalized to itself in the [XPath/XQuery] type system. [ AtomicType ] sequencetype == AtomicType An "element" SequenceType without content or with a wildcard and no type name is normalized into a wildcard element type. [ ] sequencetype == element * of type xs:anyType [ ] sequencetype == element * of type xs:anyType An "element" SequenceType with a wildcard and a type name is normalized into a wildcard element type with a corresponding type name. The presence of a "?" after the type name indicates a nillable element. [ TypeName ] sequencetype == element * of type TypeName [ TypeName ] sequencetype == element * nillable of type TypeName An "element" SequenceType with a name and a type name is normalized into an element type with a corresponding type name. The presence of a "?" after the type name indicates a nillable element. [ ElementName TypeName ] sequencetype == element ElementName TypeName [ ElementName TypeName ] sequencetype == element ElementName TypeName An "element" SequenceType with only a name is normalized into a nillable [ ElementName ] sequencetype == element ElementName xs:anyType A "schema-element" SequenceType with an element declaration is normalized into a reference to the corresponding global element declaration. [ ElementName ] sequencetype == element ElementName An "attribute" SequenceType without content or with a wildcard and no type name is normalized into a wildcard attribute type. [ ] sequencetype == attribute * of type xs:anySimpleType [ ] sequencetype == attribute * of type xs:anySimpleType An "attribute" SequenceType with a wildcard and a type name is normalized into a wildcard attribute type with a corresponding type name. [ TypeName ] sequencetype == attribute * of type TypeName An "attribute" SequenceType with a name and a type name is normalized into an attribute type with a corresponding type name. [ AttributeName TypeName ] sequencetype == attribute AttributeName TypeName A "schema-attribute" SequenceType with an attribute declaration is normalized into a reference to the corresponding global attribute declaration. [ AttributeName ] sequencetype == attribute AttributeName A "document-node()" sequence types is normalized into the corresponding document type. [ ] sequencetype == document { (element * of type xs:anyType A "document-node" sequence type with an element test (resp. a schema element test) is normalized into the corresponding document type, whose content is the normalization of the element test (resp. schema element test), interleaved with an arbitrary sequence of processing instruction, comment, and text nodes. [ ElementTest ] sequencetype == document { [ ElementTest ] sequencetype [ SchemaElementTest ] sequencetype == document { [ SchemaElementTest ] sequencetype A "processing-instruction()" SequenceType is normalized into the corresponding processing-instruction type. [ ] sequencetype == processing-instruction * [ NCName ] sequencetype == processing-instruction NCName For backward compatibility with XPath 1.0, the PITarget of a PITest may also be expressed as a string literal. The following rule handles that case. StringLiteral has atomic value String xs:NCName String NCName [ StringLiteral ] sequencetype NCName A "comment()" SequenceType is normalized into the corresponding comment type. [ ] sequencetype == comment A "text()" SequenceType is normalized into the corresponding text type. [ ] sequencetype == text The "node()" SequenceType denotes any node. It is normalized into a choice between the corresponding wildcard types for each kind of node. [ ] sequencetype == (element * of type xs:anyType xs:anySimpleType xs:anyType The "item()" SequenceType denotes any node or atomic value. It is normalized into a choice between the corresponding wildcard types for each kind of nodes or atomic values. [ ] sequencetype == (element * of type xs:anyType xs:anySimpleType xs:anyType xs:anyAtomicType 151 (XQuery) Comment XQ ::= "(:" ( CommentContents Comment 159 (XQuery) CommentContents XQ ::= ( Char Comments are lexical constructs only, and have no effect on the meaning of the query, and therefore do not have any formal semantics. The following terminals are defined by XML. 152 (XQuery) PITarget XQ ::= [http://www.w3.org/TR/REC-xml#NT-PITarget] XML 153 (XQuery) CharRef XQ ::= [http://www.w3.org/TR/REC-xml#NT-CharRef] XML 154 (XQuery) QName XQ ::= [http://www.w3.org/TR/REC-xml-names/#NT-QName] Names 155 (XQuery) NCName XQ ::= [http://www.w3.org/TR/REC-xml-names/#NT-NCName] Names 156 (XQuery) S XQ ::= [http://www.w3.org/TR/REC-xml#NT-S] XML 157 (XQuery) Char XQ ::= [http://www.w3.org/TR/REC-xml#NT-Char] XML This section gives the semantics of all the [XPath/XQuery] expressions. The organization of this section parallels the organization of Section 3 Expressions XQ 31 (XQuery) Expr XQ ::= ExprSingle ExprSingle 32 (XQuery) ExprSingle XQ ::= FLWORExpr QuantifiedExpr TypeswitchExpr IfExpr OrExpr 1 (XPath) XPath XP ::= Expr For each expression, a short description and the relevant grammar productions are given. The semantics of an expression includes the normalization, static analysis, and dynamic evaluation phases. Recall that normalization rules translate [XPath/XQuery] syntax into Core syntax. In the sections that contain normalization rules, the Core grammar productions into which the expression is normalized are also provided. After normalization, sections on static type inference and dynamic evaluation define the static type and dynamic value for the Core expression. Core Grammar The Core grammar productions for expressions are: 22 (Core) Expr ::= ExprSingle ExprSingle 23 (Core) ExprSingle ::= FLWORExpr QuantifiedExpr TypeswitchExpr IfExpr OrExpr Static Type Analysis During static analysis, it is a type error for an expression to have the empty type, except for the following expressions and function calls: Empty parentheses () The fn:data fs () Any function which returns the empty type. The reason for these exceptions is that they are typically part of the result of normalizing a larger user-level expression and are used to capture the semantics of the user-level expression when applied to the empty sequence. The rule below enforces the above constraints. It is a static type error, if the following conditions hold for a given expression Expr statEnv |- Expr : Type statEnv |- Type <: empty not Expr fn:data fs A static type error is raised for expression Expr In general, static type errors are raised whenever there are no static typing rules which can compute the type of a given expression. This is the reason for the absence of a formal conclusion in this rule. There is indeed a rule that infers the type for expression Expr Example The above rule is useful in catching common mistakes, such as the misspelling of an element or attribute name or referencing of an element or attribute that does not exist. For instance, the following path expression $x/title raises a static type error if the type of variable $x title Primary expressions 84 (XQuery) PrimaryExpr XQ ::= Literal VarRef ParenthesizedExpr ContextItemExpr FunctionCall OrderedExpr UnorderedExpr Constructor Core Grammar The Core grammar production for primary expressions is: 55 (Core) PrimaryExpr ::= Literal VarRef ParenthesizedExpr FunctionCall OrderedExpr UnorderedExpr Constructor Introduction A literal 85 (XQuery) Literal XQ ::= NumericLiteral StringLiteral 86 (XQuery) NumericLiteral XQ ::= IntegerLiteral DecimalLiteral DoubleLiteral 141 (XQuery) IntegerLiteral XQ ::= Digits 142 (XQuery) DecimalLiteral XQ ::= ("." Digits Digits 143 (XQuery) DoubleLiteral XQ ::= (("." Digits Digits Digits 144 (XQuery) StringLiteral XQ ::= ('"' ( PredefinedEntityRef CharRef EscapeQuot PredefinedEntityRef CharRef EscapeApos 140 (XQuery) URILiteral XQ ::= StringLiteral 145 (XQuery) PredefinedEntityRef XQ ::= "&" ("lt" | "gt" | "amp" | "quot" | "apos") ";" 158 (XQuery) Digits XQ ::= [0-9]+ Core Grammar The Core grammar productions for literals are: 56 (Core) Literal ::= NumericLiteral StringLiteral 57 (Core) NumericLiteral ::= IntegerLiteral DecimalLiteral DoubleLiteral 99 (Core) IntegerLiteral ::= Digits 100 (Core) DecimalLiteral ::= ("." Digits Digits 101 (Core) DoubleLiteral ::= (("." Digits Digits Digits 102 (Core) StringLiteral ::= ('"' ( EscapeQuot EscapeApos 97 (Core) URILiteral ::= StringLiteral 113 (Core) Digits ::= [0-9]+ Notation To define the dynamic semantics of literals, we introduce the following auxiliary judgments. The judgment dynEnv |- Literal has atomic value AtomicValue holds if the literal expression Literal AtomicValue [XQuery 1.0: An XML Query Language (Second Edition)] Normalization Literals are left unchanged through normalization. [ IntegerLiteral ] Expr == IntegerLiteral [ DecimalLiteral ] Expr == DecimalLiteral [ DoubleLiteral ] Expr == DoubleLiteral [ StringLiteral ] Expr == StringLiteral Static Type Analysis The static type of a literal expression is its corresponding atomic type. statEnv |- IntegerLiteral : statEnv |- DecimalLiteral : statEnv |- DoubleLiteral : statEnv |- StringLiteral : Dynamic Evaluation In the dynamic semantics, a literal is evaluated by constructing an atomic value in the data model, using the has atomic value dynEnv |- Literal has atomic value AtomicValue dynEnv |- Literal => AtomicValue Introduction A variable dynamic context 87 (XQuery) VarRef XQ ::= "$" VarName 88 (XQuery) VarName XQ ::= QName Core Grammar The Core grammar productions for variable references are: 58 (Core) VarRef ::= "$" VarName 59 (Core) VarName ::= QName Normalization Variable references are left unchanged through normalization. [ VarRef ] Expr == VarRef Static Type Analysis In the static semantics, the type of a variable is simply its type in the static environment statEnv varType statEnv |- VarName of var expands to Variable statEnv varType Variable Type statEnv |- VarName : Type If the variable is not bound in the static environment, a static type error is raised. Dynamic Evaluation In the dynamic semantics, a locally declared variable is evaluated by "looking up" its value in dynEnv varValue statEnv |- VarName of var expands to Variable dynEnv varValue Variable Value dynEnv |- VarName => Value In the dynamic semantics, a reference to a variable imported from a module is evaluated by accessing the dynamic context of the module in which the variable is declared. The notation AnyURI => module_dynEnv dynEnv 1 [5.2 Module Declaration] statEnv |- VarName of var expands to Variable dynEnv varValue Variable #IMPORTED AnyURI AnyURI => module_dynEnv dynEnv 1 dynEnv 1 varValue Variable Value dynEnv |- VarName => Value 89 (XQuery) ParenthesizedExpr XQ ::= "(" Expr Core Grammar The Core grammar production for parenthesized expressions is: 60 (Core) ParenthesizedExpr ::= "(" Expr Empty parentheses () () [4 Expressions] Static Type Analysis statEnv |- : empty statEnv |- Expr : Type statEnv |- Expr : Type Dynamic Evaluation Empty parentheses () dynEnv |- => dynEnv |- Expr => Value dynEnv |- Expr => Value 90 (XQuery) ContextItemExpr XQ ::= "." Introduction A context item expression Normalization A context item expression is normalized to the built-in variable $ fs: dot [ ] Expr == $ fs: dot Introduction A function call consists of a QName followed by a parenthesized list of zero or more expressions. In [XPath/XQuery], the actual argument to a function is called an argument parameter 93 (XQuery) FunctionCall XQ ::= QName ExprSingle ExprSingle Because [XPath/XQuery] implicitly converts the values of function arguments, a normalization step is required. Core Grammar The Core grammar production for function calls is: 63 (Core) FunctionCall ::= QName ExprSingle ExprSingle Notation Normalization of function calls uses an auxiliary mapping [ ] FunctionArgument( Type Type [ Expr ] FunctionArgument( Type == [ [ [ Expr ] Expr ] AtomizeAtomic( Type ] Convert( Type where [ Expr ] AtomizeAtomic( Type If Type <: xs:anyAtomicType Then fn:data Expr Else Expr which specifies that if the function expects atomic parameters, then fn:data [ Expr ] Convert( Type If Type <: xs:anyAtomicType Then fs: convert-simple-operand Expr PrototypicalValue Else Expr where PrototypicalValue 1.0 xs:decimal Note The fs: convert-simple-operand PrototypicalValue xs:double Normalization Each argument expression in a function call is normalized to its corresponding Core expression by applying [ ] FunctionArgument( Type Type statEnv |- QName of func expands to expanded-QName statEnv |- not expanded-QName denotes a constructor function statEnv funcType expanded-QName expanded-QName Type 1 Type n Type statEnv |- [ QName Expr 1 Expr n ] Expr QName [ Expr 1 ] FunctionArgument( Type 1 [ Expr n ] FunctionArgument( Type n Note that this normalization rule depends on the function signature (found in statEnv funcType Type 1 Type n Static Type Analysis Different sets of static typing rules are used to type check function calls depending on which of the following categories they belong to: overloaded internal functions, built-in functions with a specific static typing rule, and other built-in and user-defined functions. The following two rules factor out the step (common to all those categories) of translating a type-inference judgment on syntactic objects ( QName Expr i expanded-QName Type i statEnv |- QName of func expands to expanded-QName statEnv |- expanded-QName : Type statEnv |- QName : Type statEnv |- QName of func expands to expanded-QName statEnv |- Expr 1 : Type 1 ... statEnv |- Expr n : Type n statEnv |- expanded-QName Type 1 Type n : Type statEnv |- QName Expr 1 Expr n : Type The following depends on the kind of function call. If the expanded QName for the function corresponds to one of the overloaded internal fs: [C.2 Mapping of Overloaded Internal Functions] [C.2 Mapping of Overloaded Internal Functions] If the expanded QName for the function corresponds to one of the built-in functions with a specialized static typing rule, listed in [7 Additional Semantics of Functions] [7 Additional Semantics of Functions] Otherwise, the following general static typing rules are applied. Recall that statEnv funcType statEnv funcType expanded-QName expanded-QName Type statEnv |- expanded-QName : Type statEnv funcType expanded-QName expanded-QName Type 1 Type n Type statEnv |- Type 1 can be promoted to Type 1 ... statEnv |- Type n can be promoted to Type n statEnv |- expanded-QName Type 1 Type n : Type The function body itself is not analyzed for each invocation: static typing of the function definition itself guarantees that the function body always returns a value of the declared return type. Notation The following auxiliary judgment dynEnv |- function expanded-QName with types on values yields Value holds when applying the function with expanded QName expanded-QName Value dynEnv |- function expanded-QName with types Type 1 Type n on values Value 1 Value n yields Value holds when applying the function with expanded QName expanded-QName Type 1 Type n Value 1 Value n Value That judgment is defined below for each kind of function (user-defined, built-in, external, and imported functions). Dynamic Evaluation The following rules apply to all the different kinds of functions using the previously defined judgment. statEnv |- QName of func expands to expanded-QName statEnv funcType expanded-QName FunctionSig FunctionSig expanded-QName Type dynEnv |- function expanded-QName with types on values yields Value statEnv |- Value against Type promotes to Value dynEnv |- QName => Value dynEnv |- Expr 1 => Value 1 ... dynEnv |- Expr n => Value n statEnv |- QName of func expands to expanded-QName statEnv funcType expanded-QName FunctionSig FunctionSig expanded-QName Type 1 Type n Type statEnv |- Value 1 against Type 1 promotes to Value 1 ... statEnv |- Value n against Type n promotes to Value n dynEnv |- function expanded-QName with types Type 1 Type n on values Value 1 Value n yields Value statEnv |- Value against Type promotes to Value dynEnv |- QName Expr 1 Expr n => Value First the function name is expanded, and the expanded name is used to retrieve the function signature from the static environment. Then, the rule evaluates each function argument expression, and the resulting values are promoted according to the expected type for the function. The result of evaluating the function is obtained through the auxiliary judgment previously defined, and the resulting value is promoted according to the expected return type. In case the function is a user defined function in a main module, the expression body is retrieved from the dynamic environment and used to compute the value of the function. The rule extends dynEnv varValue The notation AnyURI => module_dynEnv dynEnv 1 [5.2 Module Declaration] dynEnv funcDefn expanded-QName Expr #MAIN => module_dynEnv dynEnv 1 dynEnv 1 |- Expr => Value dynEnv |- function expanded-QName with types on values yields Value dynEnv funcDefn expanded-QName Expr Variable 1 Variable n #MAIN => module_dynEnv dynEnv 1 dynEnv 1 varValue Variable 1 Value 1 Variable n Value n |- Expr => Value dynEnv |- function expanded-QName with types Type 1 Type n on values Value 1 Value n yields Value Note that the function body is evaluated in the dynamic environment containing the main module declarations. The rule for evaluating a function imported from a module is similar to that for evaluating a user-defined function in a main module, except that the function call is evaluated in the dynamic context of the module in which it is declared, and that the appropriate additional type matching must be performed. dynEnv funcDefn expanded-QName #IMPORTED AnyURI AnyURI => module_statEnv statEnv 1 AnyURI => module_dynEnv dynEnv 1 statEnv 1 funcType expanded-QName FunctionSig FunctionSig expanded-QName Type dynEnv 1 funcDefn expanded-QName Expr dynEnv 1 |- Expr => Value statEnv |- Value matches Type dynEnv |- function expanded-QName with types on values yields Value dynEnv funcDefn expanded-QName #IMPORTED AnyURI AnyURI => module_statEnv statEnv 1 AnyURI => module_dynEnv dynEnv 1 statEnv 1 funcType expanded-QName FunctionSig FunctionSig expanded-QName Type 1 Type n Type statEnv |- Value 1 matches Type 1 ... statEnv |- Value n matches Type n dynEnv 1 funcDefn expanded-QName Expr Variable 1 Variable n dynEnv 1 varValue Variable 1 Value 1 Variable n Value n |- Expr => Value statEnv |- Value matches Type dynEnv |- function expanded-QName with types Type 1 Type n on values Value 1 Value n yields Value If the function is a built-in function (resp. special formal semantics function), the value returned by the function is the one specified in [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [7.1 Formal Semantics Functions] [C.2 Mapping of Overloaded Internal Functions] dynEnv funcDefn expanded-QName #BUILT-IN The built-in function expanded-QName [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [7.1 Formal Semantics Functions] [C.2 Mapping of Overloaded Internal Functions] Value dynEnv |- function expanded-QName with types on values yields Value dynEnv funcDefn expanded-QName #BUILT-IN The built-in function expanded-QName [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [7.1 Formal Semantics Functions] [C.2 Mapping of Overloaded Internal Functions] Value 1 Value n Value dynEnv |- function expanded-QName with types Type 1 Type n on values Value 1 Value n yields Value If the function is an external function, the value returned by the function is implementation-defined. dynEnv funcDefn expanded-QName #EXTERNAL The external function expanded-QName Value dynEnv |- function expanded-QName with types on values yields Value dynEnv funcDefn expanded-QName #EXTERNAL The external function expanded-QName Value 1 Value n Value dynEnv |- function expanded-QName with types Type 1 Type n on values Value 1 Value n yields Value Introduction Path expressions are used to locate nodes within a tree. There are two kinds of path expressions, absolute path expressions and relative path expressions. An absolute path expression is a rooted relative path expression. A relative path expression is composed of a sequence of steps. 68 (XQuery) PathExpr XQ ::= ("/" RelativePathExpr RelativePathExpr RelativePathExpr 69 (XQuery) RelativePathExpr XQ ::= StepExpr StepExpr Core Grammar PathExpr and RelativePathExpr are fully normalized, therefore they have no corresponding productions in the Core. The grammar for path expressions in the Core starts with the StepExpr production. Normalization Absolute path expressions are path expressions starting with the / // fn:root $ fs: dot [ ] Expr == [ fn:root ] Expr [ RelativePathExpr ] Expr == [ fn:root RelativePathExpr ] Expr [ RelativePathExpr ] Expr == [ fn:root descendant-or-self::node() RelativePathExpr ] Expr [ RelativePathExpr StepExpr ] Expr == [ RelativePathExpr StepExpr ] Expr A composite relative path expression (using / for fs: distinct-doc-order $ fs: dot $ fs: sequence $ fs: position $ fs: last Note that sorting by document order enforces the restriction that input and output sequences contains only nodes, and that the last step in a path expression may actually return atomic values. [ RelativePathExpr StepExpr ] Expr == fs: apply-ordering-mode fs: distinct-doc-order-or-atomic-sequence let $ fs: sequence fs: node-sequence [ RelativePathExpr ] Expr let $ fs: last $ fs: sequence for $ fs: dot $ fs: position $ fs: sequence [ StepExpr ] Expr )) Note that this section uses some auxiliary judgments which are defined in [8.2 Judgments for step expressions and filtering] Introduction 70 (XQuery) StepExpr XQ ::= FilterExpr AxisStep 71 (XQuery) AxisStep XQ ::= ( ReverseStep ForwardStep PredicateList 72 (XQuery) ForwardStep XQ ::= ( ForwardAxis NodeTest AbbrevForwardStep 75 (XQuery) ReverseStep XQ ::= ( ReverseAxis NodeTest AbbrevReverseStep 82 (XQuery) PredicateList XQ ::= Predicate Core Grammar The Core grammar productions for XPath steps are: 46 (Core) StepExpr ::= PrimaryExpr AxisStep 47 (Core) AxisStep ::= ReverseStep ForwardStep 48 (Core) ForwardStep ::= ForwardAxis NodeTest 50 (Core) ReverseStep ::= ReverseAxis NodeTest Note Step expressions can be followed by predicates. Normalization of predicates uses the following auxiliary mapping rule: [ ] Predicates [4.2.2 Predicates] [ ] Axis [4.2.1.1 Axes] Normalization Normalization of predicates need to distinguish between forward steps, reverse steps, and primary expressions. As explained in the [XPath/XQuery] document, applying a step in XPath changes the focus (or context). The change of focus is made explicit by the normalization rule below, which binds the variable $ fs: dot $ fs: position There are two sets of normalization rules for Predicates. The first set of rules apply when the predicate is a numeric literal or the expression last() last() When the predicate expression is a numeric literal or the fn:last [ ForwardStep PredicateList NumericLiteral ] Expr == let $ fs: sequence fs: apply-ordering-mode fs: distinct-doc-order [ ForwardStep PredicateList ] Expr fs: item-at $ fs: sequence NumericLiteral [ ForwardStep PredicateList fn:last ] Expr == let $ fs: sequence fs: apply-ordering-mode fs: distinct-doc-order [ ForwardStep PredicateList ] Expr let $ fs: last fn:count $ fs: sequence fs: item-at $ fs: sequence $ fs: last When predicates are applied on a reverse step, the position variable is bound in reverse document order. [ ReverseStep PredicateList NumericLiteral ] Expr == let $ fs: sequence fs: apply-ordering-mode fs: distinct-doc-order [ ReverseStep PredicateList ] Expr let $ fs: last $ fs: sequence let $ fs: position fs: plus fs: minus $ fs: last NumericLiteral fs: item-at $ fs: sequence $ fs: position When the step is a reverse axis, then the last item in the context sequence is the first in document order. [ ReverseStep PredicateList fn:last ] Expr == let $ fs: sequence fs: apply-ordering-mode fs: distinct-doc-order [ ReverseStep PredicateList ] Expr fs: item-at $ fs: sequence The normalization rules above all use the function fs: item-at [7.1.13 The fs:item-at function] When predicates are applied on a forward step, the input sequence is first sorted in document order and duplicates are removed. The context is changed by binding the $ fs: dot [ ForwardStep PredicateList Expr ] Expr == let $ fs: sequence fs: apply-ordering-mode fs: distinct-doc-order [ ForwardStep PredicateList ] Expr let $ fs: last $ fs: sequence for $ fs: dot $ fs: position $ fs: sequence if ( [ Expr ] Predicates $ fs: dot When predicates are applied on a reverse step, the input sequence is first sorted in document order and duplicates are removed. The context is changed by binding the $ fs: dot [ ReverseStep PredicateList Expr ] Expr == let $ fs: sequence fs: apply-ordering-mode fs: distinct-doc-order [ ReverseStep PredicateList ] Expr let $ fs: last $ fs: sequence for $ fs: dot fs: $ fs: sequence let $ fs: position fs: plus fs: minus $ fs: last fs: if ( [ Expr ] Predicates $ fs: dot Finally, a stand-alone forward or reverse step is normalized by the auxiliary normalization rule for Axis [ ForwardStep ] Expr == fs: apply-ordering-mode [ ForwardStep ] Axis [ ReverseStep ] Expr == fs: apply-ordering-mode [ ReverseStep ] Axis Static Type Analysis The static semantics of an Axis NodeTest Axis NodeTest PrincipalNodeKind statEnv varType FS-URI dot Type 1 statEnv |- Type 1 <: [ ] sequencetype statEnv |- axis Axis of Type 1 : Type 2 Axis has principal PrincipalNodeKind statEnv |- test NodeTest with PrincipalNodeKind of Type 2 : Type 3 statEnv |- Axis NodeTest : Type 3 Note Note that the second judgment in the rule requires that the context item be a node, guaranteeing that a type error is raised when the context item is an atomic value. Dynamic Evaluation The dynamic semantics of an Axis NodeTest Axis NodeTest of has principal test dynEnv varValue FS-URI dot Value 1 statEnv |- Value 1 matches [ ] sequencetype dynEnv |- axis Axis of Value 1 => Value 2 Axis has principal PrincipalNodeKind dynEnv |- test NodeTest with PrincipalNodeKind of Value 2 => Value 3 dynEnv |- Axis NodeTest => fs: distinct-doc-order Value 3 Note Note that the second judgment in the rule guarantees that the context item is bound to a node. Introduction The XQuery grammar for forward and reverse axis is as follows. 73 (XQuery) ForwardAxis XQ ::= ("child" "::") 76 (XQuery) ReverseAxis XQ ::= ("parent" "::") In the case of XPath, forward axis also contain the namespace:: 30 (XPath) ForwardAxis XP ::= ("child" "::") Core Grammar The Core grammar productions for XPath axis are: 49 (Core) ForwardAxis ::= ("child" "::") 51 (Core) ReverseAxis ::= ("parent" "::") Notation We introduce the following auxiliary grammar production to describe all axis. 90 (Formal) Axis ::= ForwardAxis ReverseAxis Notation The normalization of axes uses the following auxiliary mapping rule: [ ] Axis Normalization The normalization for all axes is specified as follows. The semantics of the following(-sibling) and preceding(-sibling) axes are expressed by mapping them to Core expressions. All other axes are part of the Core and therefore are left unchanged through normalization. [ following-sibling:: NodeTest ] Axis == [ let $e := . where fn:not($e/self::attribute()) return $e/parent::node()/child:: NodeTest ] Expr [ following:: NodeTest ] Axis == [ let $e := . return fn:root() / descendant:: NodeTest except $e / descendant::node() ] Expr All other forward axes are part of the Core [XPath/XQuery] and handled by the normalization rules below: [ child:: NodeTest ] Axis == child:: NodeTest [ attribute:: NodeTest ] Axis == attribute:: NodeTest [ self:: NodeTest ] Axis == self:: NodeTest [ descendant:: NodeTest ] Axis == descendant:: NodeTest [ descendant-or-self:: NodeTest ] Axis == descendant-or-self:: NodeTest [ namespace:: NodeTest ] Axis == namespace:: NodeTest Reverse axes: [ preceding-sibling:: NodeTest ] Axis == [ NodeTest ] Expr [ preceding:: NodeTest ] Axis == [ ancestor-or-self::node()/preceding-sibling::node()/descendant-or-self:: NodeTest ] Expr All other reverse axes are part of the Core [XPath/XQuery] and handled by the normalization rules below: [ parent:: NodeTest ] Axis == parent:: NodeTest [ ancestor:: NodeTest ] Axis == ancestor:: NodeTest [ ancestor-or-self:: NodeTest ] Axis == ancestor-or-self:: NodeTest Introduction A node test is a condition applied on the nodes selected by an axis step. Node tests are described by the following grammar productions. 78 (XQuery) NodeTest XQ ::= KindTest NameTest 79 (XQuery) NameTest XQ ::= QName Wildcard 80 (XQuery) Wildcard XQ ::= "*" NCName NCName Core Grammar The Core grammar productions for node tests are: 52 (Core) NodeTest ::= KindTest NameTest 53 (Core) NameTest ::= QName Wildcard 54 (Core) Wildcard ::= "*" NCName NCName Notation For convenience, we will use the grammar non-terminals Prefix LocalPart NCName 18 (Formal) Prefix ::= NCName 19 (Formal) LocalPart ::= NCName Introduction A predicate consists of an expression, called a predicate expression 83 (XQuery) Predicate XQ ::= "[" Expr Notation Normalization of predicates uses the following auxiliary mapping rule: [ ] Predicates Normalization Predicates in path expressions are normalized with a special mapping rule: [ Expr ] Predicates == typeswitch ( [ Expr ] Expr case $v as fs: numeric op: $ fs: position default $v return fn:boolean Note that the semantics of predicates whose input expression returns a numeric value also work if that value is not an integer. In those cases the op:numeric-equal //a[3.4] The corresponding Section in the [XPath/XQuery] document just contains examples. 74 (XQuery) AbbrevForwardStep XQ ::= "@"? NodeTest 77 (XQuery) AbbrevReverseStep XQ ::= ".." Normalization Here are normalization rules for the abbreviated syntax. [ ] Axis == parent::node() [ NodeTest ] Axis == attribute:: NodeTest [ NodeTest ] Axis == child:: NodeTest Introduction [XPath/XQuery] supports operators to construct and combine sequences. A sequence item 31 (XQuery) Expr XQ ::= ExprSingle ExprSingle 49 (XQuery) RangeExpr XQ ::= AdditiveExpr AdditiveExpr Core Grammar The Core grammar production for sequence expressions is: 22 (Core) Expr ::= ExprSingle ExprSingle Normalization A sequence expression is normalized into a sequence of normalized single expressions: [ Expr 1 Expr 2 ] Expr == [ Expr 1 ] Expr [ Expr 2 ] Expr Static Type Analysis The type of the sequence expression is the sequence over the types of the individual expressions. statEnv |- Expr 1 : Type 1 statEnv |- Expr 2 : Type 2 statEnv |- Expr 1 Expr 2 : Type 1 Type 2 Dynamic Evaluation Each expression in the sequence is evaluated and the resulting values are concatenated into one sequence. dynEnv |- Expr 1 => Value 1 dynEnv |- Expr 2 => Value 2 dynEnv |- Expr 1 Expr 2 => Value 1 Value 2 Normalization The range operator is normalized to the fs: to [ Expr 1 to Expr 2 ] Expr == fs: to [ Expr 1 ] Expr [ Expr 2 ] Expr Static Type Analysis The static semantics of the fs: to [7.1.11 The fs:to function] Dynamic Evaluation The dynamic semantics of the fs: to [7.1.11 The fs:to function] Introduction 81 (XQuery) FilterExpr XQ ::= PrimaryExpr PredicateList Core Grammar There are no Core grammar productions for filter expressions as they are normalized to other Core expressions. Normalization When a predicate with a numeric literal or the last() fs: item-at [ PrimaryExpr PredicateList NumericLiteral ] Expr == let $ fs: sequence [ PrimaryExpr PredicateList ] Expr fs: item-at $ fs: sequence NumericLiteral [ PrimaryExpr PredicateList ] Expr == let $ fs: sequence [ PrimaryExpr PredicateList ] Expr let $ fs: last $ fs: sequence fs: item-at $ fs: sequence $ fs: last In the general case, when a predicate is applied on a primary expression, it is normalized to a FLWOR expression as follows. The input sequence is processed in sequence order and the context item is bound to each item in the input sequence. [ PrimaryExpr PredicateList Expr ] Expr == let $ fs: sequence [ PrimaryExpr PredicateList ] Expr let $ fs: last $ fs: sequence for $ fs: dot $ fs: position $ fs: sequence if ( [ Expr ] Predicates $ fs: dot Static Type Analysis There are no additional static typing rules for filter expressions. Dynamic Evaluation There are no additional dynamic evaluation rules for filter expressions. [XPath/XQuery] provides several operators for combining sequences of nodes. 52 (XQuery) UnionExpr XQ ::= IntersectExceptExpr IntersectExceptExpr 53 (XQuery) IntersectExceptExpr XQ ::= InstanceofExpr InstanceofExpr Notation The union, intersect, and except expressions are normalized into function calls to the appropriate functions. The mapping function [ ] SequenceOp SequenceOp [ SequenceOp ] SequenceOp "union" op: "|" op: "intersect" op: "except" op: Normalization Operators for combining node sequences are normalized as follows. [ Expr 1 SequenceOp Expr 2 ] Expr == fs: apply-ordering-mode [ SequenceOp ] SequenceOp [ Expr 1 ] Expr [ Expr 2 ] Expr Static Type Analysis The static semantics of the operators that combine sequences are defined in [7.2.14 The op:union, op:intersect, and op:except operators] Dynamic Evaluation The dynamic semantics for function calls is given in [4.1.5 Function Calls] [XPath/XQuery] provides arithmetic operators for addition, subtraction, multiplication, division, and modulus, in their usual binary and unary forms. 50 (XQuery) AdditiveExpr XQ ::= MultiplicativeExpr MultiplicativeExpr 51 (XQuery) MultiplicativeExpr XQ ::= UnionExpr UnionExpr 58 (XQuery) UnaryExpr XQ ::= ("-" | "+")* ValueExpr 59 (XQuery) ValueExpr XQ ::= ValidateExpr PathExpr ExtensionExpr Core Grammar The Core grammar production for arithmetic expressions is: 40 (Core) ValueExpr ::= ValidateExpr StepExpr ExtensionExpr Notation The mapping function [ ] ArithOp ArithOp [ ArithOp ] ArithOp "+" fs: plus "-" fs: minus "*" fs: times "div" fs: div "mod" fs: mod Core Grammar There are no Core grammar productions for arithmetic expressions as they are normalized to other Core expressions. Normalization The normalization rules for all the arithmetic operators except idiv fn:data fs: convert-operand xs:untypedAtomic [C.2 Mapping of Overloaded Internal Functions] [ Expr 1 ArithOp Expr 2 ] Expr == [ ArithOp ] ArithOp fs: convert-operand fn:data [ Expr 1 ] Expr fs: convert-operand fn:data [ Expr 2 ] Expr The normalization rules for the idiv xs:untypedAtomic xs:double xs:integer [ Expr 1 idiv Expr 2 ] Expr == fs: idiv fs: convert-operand fn:data [ Expr 1 ] Expr fs: convert-operand fn:data [ Expr 2 ] Expr The unary operators are mapped similarly. [ + Expr ] Expr == fs: unary-plus fs: convert-operand fn:data [ Expr ] Expr [ - Expr ] Expr == fs: unary-minus fs: convert-operand fn:data [ Expr ] Expr Static Type Analysis The static semantics for function calls is given in [4.1.5 Function Calls] [C.2 Mapping of Overloaded Internal Functions] Dynamic Evaluation The dynamic semantics for function calls is given in [4.1.5 Function Calls] [C.2 Mapping of Overloaded Internal Functions] Introduction Comparison expressions allow two values to be compared. [XPath/XQuery] provides three kinds of comparison expressions, called value comparisons, general comparisons, and node comparisons. 48 (XQuery) ComparisonExpr XQ ::= RangeExpr ValueComp GeneralComp NodeComp RangeExpr 61 (XQuery) ValueComp XQ ::= "eq" | "ne" | "lt" | "le" | "gt" | "ge" 60 (XQuery) GeneralComp XQ ::= "=" | "!=" | "<" | "<=" | ">" | ">=" 62 (XQuery) NodeComp XQ ::= "is" | "<<" | ">>" Notation The mapping function [ ] ValueComp ValueComp [ ] ValueComp " eq fs: " ne fs: " lt fs: " le fs: " gt fs: " ge fs: Core Grammar There are no Core grammar productions for value comparisons as they are normalized to other Core expressions. Normalization The normalization rules for the value comparison operators first atomize each argument by applying fn:data fs: convert-operand [7.1.1 The fs:convert-operand function] xs:untypedAtomic [C.2 Mapping of Overloaded Internal Functions] [ Expr 1 ValueComp Expr 2 ] Expr == [ ValueComp ] ValueComp fs: convert-operand fn:data [ Expr 1 ] Expr fs: convert-operand fn:data [ Expr 2 ] Expr Static Type Analysis The static semantics for function calls is given in [4.1.5 Function Calls] xs:boolean [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] Dynamic Evaluation The dynamic semantics for function calls is given in [4.1.5 Function Calls] Introduction General comparisons are defined by adding existential semantics to value comparisons. The operands of a general comparison may be sequences of any length. The result of a general comparison is always true false Notation The function [ ] GeneralComp GeneralComp [ GeneralComp ] GeneralComp " = fs: " != fs: " < fs: " <= fs: " > fs: " >= fs: Core Grammar There are no Core grammar productions for general comparisons as they are normalized to existentially quantified Core expressions. Normalization The normalization rule for a general comparison expression first atomizes each argument by applying fn:data some fs: convert-operand xs:untypedAtomic [ Expr 1 GeneralComp Expr 2 ] Expr == some $v1 in fn:data [ Expr 1 ] Expr some $v2 in fn:data [ Expr 2 ] Expr let $u1 := fs: convert-operand let $u2 := fs: convert-operand [ GeneralComp ] GeneralComp Core Grammar There are no Core grammar productions for node comparisons as they are normalized to other Core expressions. Normalization The normalization rules for node comparisons map each argument expression and then apply the internal function corresponding to the node comparison operator. The internal function are defined in [C.2 Mapping of Overloaded Internal Functions] [ Expr 1 is Expr 2 ] Expr == fs: is-same-node [ Expr 1 ] Expr [ Expr 2 ] Expr [ Expr 1 Expr 2 ] Expr == fs: node-before [ Expr 1 ] Expr [ Expr 2 ] Expr [ Expr 1 Expr 2 ] Expr == fs: node-after [ Expr 1 ] Expr [ Expr 2 ] Expr Static Type Analysis The static semantics for the internal functions are defined in [C.2 Mapping of Overloaded Internal Functions] Dynamic Evaluation The dynamic semantics for internal function is defined in [C.2 Mapping of Overloaded Internal Functions] Introduction A logical expression and-expression or-expression true false 46 (XQuery) OrExpr XQ ::= AndExpr AndExpr 47 (XQuery) AndExpr XQ ::= ComparisonExpr ComparisonExpr Core Grammar The Core grammar productions for logical expressions are: 36 (Core) OrExpr ::= AndExpr AndExpr 37 (Core) AndExpr ::= CastableExpr CastableExpr Normalization The normalization rules for " and or [ Expr 1 and Expr 2 ] Expr == fn:boolean [ Expr 1 ] Expr and fn:boolean [ Expr 2 ] Expr [ Expr 1 or Expr 2 ] Expr == fn:boolean [ Expr 1 ] Expr or fn:boolean [ Expr 2 ] Expr Static Type Analysis The logical expressions require that each subexpression have type xs:boolean xs:boolean statEnv |- Expr 1 : xs:boolean statEnv |- Expr n : xs:boolean statEnv |- Expr 1 and Expr 2 : xs:boolean statEnv |- Expr 1 : xs:boolean statEnv |- Expr n : xs:boolean statEnv |- Expr 1 or Expr 2 : xs:boolean Dynamic Evaluation The dynamic semantics of logical expressions is non-deterministic. This non-determinism permits implementations to use short-circuit evaluation strategies when evaluating logical expressions. In the expression, Expr 1 and Expr 2 Expr 1 or Expr 2 dynEnv |- Expr i => i in dynEnv |- Expr 1 and Expr 2 => dynEnv |- Expr 1 => dynEnv |- Expr 2 => dynEnv |- Expr 1 and Expr 2 => dynEnv |- Expr i => i in dynEnv |- Expr 1 or Expr 2 => dynEnv |- Expr 1 => dynEnv |- Expr 2 => dynEnv |- Expr 1 or Expr 2 => [XPath/XQuery] supports two forms of constructors. Direct constructors Computed constructors 94 (XQuery) Constructor XQ ::= DirectConstructor ComputedConstructor 95 (XQuery) DirectConstructor XQ ::= DirElemConstructor DirCommentConstructor DirPIConstructor 96 (XQuery) DirElemConstructor XQ ::= "<" QName DirAttributeList DirElemContent QName S 101 (XQuery) DirElemContent XQ ::= DirectConstructor CDataSection CommonContent ElementContentChar 148 (XQuery) ElementContentChar XQ ::= Char 102 (XQuery) CommonContent XQ ::= PredefinedEntityRef CharRef EnclosedExpr 107 (XQuery) CDataSection XQ ::= "<![CDATA[" CDataSectionContents 108 (XQuery) CDataSectionContents XQ ::= ( Char 97 (XQuery) DirAttributeList XQ ::= ( S QName S S DirAttributeValue 98 (XQuery) DirAttributeValue XQ ::= ('"' ( EscapeQuot QuotAttrValueContent EscapeApos AposAttrValueContent 99 (XQuery) QuotAttrValueContent XQ ::= QuotAttrContentChar CommonContent 100 (XQuery) AposAttrValueContent XQ ::= AposAttrContentChar CommonContent 149 (XQuery) QuotAttrContentChar XQ ::= Char 150 (XQuery) AposAttrContentChar XQ ::= Char 146 (XQuery) EscapeQuot XQ ::= '""' 147 (XQuery) EscapeApos XQ ::= "''" 29 (XQuery) EnclosedExpr XQ ::= "{" Expr Core Grammar The Core grammar productions for constructors are: 64 (Core) Constructor ::= ComputedConstructor 65 (Core) ComputedConstructor ::= CompDocConstructor CompElemConstructor CompAttrConstructor CompTextConstructor CompCommentConstructor CompPIConstructor 21 (Core) EnclosedExpr ::= "{" Expr There are no Core grammar productions for direct XML element or attribute constructors as they are normalized to computed constructors. Introduction The static and dynamic semantics of the direct forms of element and attribute constructors are specified in terms of the equivalent computed element and attribute constructors. Notation The auxiliary mapping rules [ ] ElementContent [ ] ElementContentUnit [ ] PartitionIntoUnits [ ] DirCharsUnit Notation An element-content unit is either a DirCharsUnit 83 (Formal) ElementContentUnit ::= DirectConstructor EnclosedExpr DirCharsUnit 84 (Formal) DirCharsUnit ::= ( CDataSection PredefinedEntityRef CharRef ElementContentChar We use the auxiliary normalization rule [ DirElemContent ] PartitionIntoUnits DirElemContent Here are three direct element constructors, each of which contains one element-content unit: <date>{ xs:date("2003-03-18") }</date>

<name>Dizzy Gillespie</name>

<comment><!-- Just a comment --></comment> The first contains one enclosed expression, the second contains one contiguous sequence of characters, and the third contains one XML comment. After boundary whitespace is stripped, the next example contains six element-content units: <address> <!-- Dizzy's address --> { 123 }-0A <street>Roosevelt Ave.</street> Flushing, NY { 11368 } </address> It contains an XML comment, followed by an enclosed expression that contains the integer 123, a contiguous sequence of characters ("-0A "), a direct XML element constructor, a contiguous sequence of characters (" Flushing, NY "), and an enclosed expression that contains the integer 11368. Evaluation of that constructor will result in the following element. <address><!-- Dizzy's address -->123-0A <street>Roosevelt Ave.</street> Flushing, NY 11368</address> Normalization We start by giving the rules for the two forms of direct XML element constructors. Note that the direct attribute constructors are normalized twice: the [ ] NamespaceAttrs [ ] Attribute [ QName DirAttributeList DirElemContent QName ] Expr == element QName [ DirAttributeList ] Attribute [ [ DirElemContent ] PartitionIntoUnits ] ElementContent [ DirAttributeList ] NamespaceAttrs [ QName DirAttributeList ] Expr == element QName [ DirAttributeList ] Attribute [ DirAttributeList ] NamespaceAttrs We can now give the rules for normalizing a direct element constructor's content. Adjacent element-content units permit arbitrary interleaving of text and atomic data. During evaluation, atomic values are converted to text nodes containing the string representations of the atomic values, and then adjacent text nodes are concatenated together. In the example at the beginning of this section, the integer 123 is converted to a string and concatenated with "-0A" and the result is a single text node containing "123-0A". Below are two examples of normalization for element constructors. <date>{ xs:date("2003-03-18") }</date> = element date { fs:item-sequence-to-node-sequence( xs:date("2003-03-18") ) } {}

<address> <!-- Dizzy's address --> { 123 }-0A <street>Roosevelt Ave.</street> Flushing, NY { 11368 } </address> = element address { fs:item-sequence-to-node-sequence( comment { " Dizzy's address "}, 123, text { "-0A "}, element street {"Roosevelt Ave."} {}, text { " Flushing, NY " }, 11368 ) } {} We normalize each unit individually and construct a sequence of the normalized results. [ ElementContentUnit 1 ElementContentUnit n ] ElementContent == [ ElementContentUnit 1 ] ElementContentUnit [ ElementContentUnit n ] ElementContentUnit (Note that this rule should be understood to cover the degenerate cases of n=0 and n=1, where the element constructor's content consists of zero or one element-content units.) Next, we give the normalization rules for each element-content unit. The normalization rule for a contiguous sequence of characters assumes that the significant whitespace characters in element constructors have been preserved, as described in [4.7.1.4 Boundary Whitespace] The following normalization rule takes a maximal contiguous sequence of individual characters that include literal characters, CDataSections, escaped curly braces, character references, and predefined entity references and normalizes the character sequence as a text node containing the string of characters. [ DirCharsUnit ] ElementContentUnit == text { [ DirCharsUnit ] DirCharsUnit The application of [ ] DirCharsUnit DirCharsUnit DirCharsUnit Section 3.7.1.4 Boundary Whitespace XQ Section 3.7.1.3 Content XQ XML processing instructions and comments in element content are normalized by applying the standard normalization rules for expressions, which appear in [4.7.2 Other Direct Constructors] [ DirPIConstructor ] ElementContentUnit == [ DirPIConstructor ] Expr [ DirCommentConstructor ] ElementContentUnit == [ DirCommentConstructor ] Expr A direct element constructor is normalized using the normalization rule for expressions. [ DirElemConstructor ] ElementContentUnit == [ DirElemConstructor ] Expr An enclosed expression in element content is normalized into a call to the function fs: item-sequence-to-node-sequence [ Expr ] ElementContentUnit == fs: item-sequence-to-node-sequence [ Expr ] Expr Static Type Analysis There are no additional static typing rules for direct XML element or attribute constructors. Dynamic Evaluation There are no additional dynamic evaluation rules for direct XML element or attribute constructors. Like direct element constructors, direct attribute constructors are normalized to computed attribute constructors. Notation The auxiliary mapping rules [ ] Attribute [ ] DirAttributeValue [ ] AttributeContent [ ] AttributeContentUnit [ ] AttributeCharsUnit We use the following grammar productions to represent AttributeContentUnit 87 (Formal) AttributeContentUnits ::= AttributeContentUnit 88 (Formal) AttributeContentUnit ::= AttributeCharsUnit EnclosedExpr 91 (Formal) AttributeCharsUnit ::= ( QuotAttrContentChar AposAttrContentChar EscapeQuot EscapeApos PredefinedEntityRef CharRef An AttributeCharsUnit AttributeContentUnits AttributeCharsUnit Normalization Direct attributes may contain namespace-declaration attributes. The normalization rules in this section ignore namespace-declaration attributes -- they are handled by the normalization rules in [4.7.1.2 Namespace Declaration Attributes] A DirAttributeList [ QName 1 DirAttributeValue 1 ... QName n DirAttributeValue n ] Attribute == ( [ QName 1 DirAttributeValue 1 ] Attribute ..., [ QName n DirAttributeValue n ] Attribute Namespace-declaration attributes, i.e., those attributes whose prefix is xmlns [ Prefix LocalPart DirAttributeValue ] Attribute ( Prefix xmlns == () All attributes that are not namespace-declaration attributes are mapped to computed attribute constructors. [ Prefix LocalPart DirAttributeValue ] Attribute not Prefix xmlns == attribute Prefix LocalPart [ [ DirAttributeValue ] DirAttributeValue ] AttributeContent The effect of [ DirAttributeValue ] DirAttributeValue DirAttributeValue AttributeContentUnit EnclosedExpr AttributeCharsUnit [ ] AttributeContent To apply [ ] AttributeContent fn:string-join [ AttributeContentUnit 1 AttributeContentUnit n ] AttributeContent == fn:string-join (( [ AttributeContentUnit 1 ] AttributeContentUnit [ AttributeContentUnit n ] AttributeContentUnit (Note that this rule should be understood to cover the degenerate cases of n=0 and n=1, where the attribute constructor's content consists of zero or one attribute-content units.) The next two rules specify the normalization of each attribute-content unit via [ ] AttributeContentUnit We normalize an AttributeCharsUnit [ AttributeCharsUnit ] AttributeContentUnit == [ AttributeCharsUnit ] AttributeCharsUnit The effect of [ AttributeCharsUnit ] AttributeCharsUnit Section 3.7.1.1 Attributes XQ We normalize an enclosed expression into a call to the function fs: item-sequence-to-string [ Expr ] AttributeContentUnit == fs: item-sequence-to-string [ Expr ] Expr Notation The auxiliary mapping rules [ ] NamespaceAttr [ ] NamespaceAttrs Normalization Some direct attributes may be namespace-declaration attributes. The normalization rules for namespace-declaration attributes ignore all non-namespace attributes -- they are handled by the normalization rules in [4.7.1.1 Attributes] A DirAttributeList [ QName 1 DirAttributeValue 1 ... QName n DirAttributeValue n ] NamespaceAttrs == ( [ QName 1 DirAttributeValue 1 ] NamespaceAttr ..., [ QName n DirAttributeValue n ] NamespaceAttr Attributes whose prefix is not xmlns [ Prefix LocalPart DirAttributeValue ] NamespaceAttr not Prefix xmlns == () Namespace-declaration attributes are normalized to local namespace declarations ( LocalNamespaceDecl [ Prefix LocalPart URILiteral ] NamespaceAttr ( Prefix xmlns == namespace LocalPart URILiteral The rules for normalizing element content are given above in [4.7.1 Direct Element Constructors] Section 3.7.1.4 Boundary Whitespace XQ boundary-space [ ] DirCharsUnit 105 (XQuery) DirPIConstructor XQ ::= "<?" PITarget S DirPIContents 106 (XQuery) DirPIContents XQ ::= ( Char 103 (XQuery) DirCommentConstructor XQ ::= "<!--" DirCommentContents 104 (XQuery) DirCommentContents XQ ::= (( Char Char Notation The auxiliary mapping rule [ ] Characters [ Char ] Characters StringLiteral Normalization A literal XML processing instruction is normalized into a computed processing-instruction constructor; its character content is converted to a string using the auxiliary mapping rule [ ] Characters [ NCName DirPIContents ] Expr == [ NCName [ DirPIContents ] Characters ] Expr A literal XML comment is normalized into a computed comment constructor; its character content is converted to a string using the auxiliary mapping rule [ ] Characters [ DirCommentContents ] Expr == [ [ DirCommentContents ] Characters ] Expr Static Type Analysis There are no additional static typing rules for direct processing-instruction or comment constructors. Dynamic Evaluation There are no additional dynamic evaluation rules for direct processing-instruction or comment constructors. 109 (XQuery) ComputedConstructor XQ ::= CompDocConstructor CompElemConstructor CompAttrConstructor CompTextConstructor CompCommentConstructor CompPIConstructor Introduction This section describes the semantics of computed element constructors. Remember that direct element constructors are normalized into computed element constructors. This document does not formally specify how namespaces are copied. The semantics of namespaces copying in element constructors can be found in [XQuery 1.0: An XML Query Language (Second Edition)] 111 (XQuery) CompElemConstructor XQ ::= "element" ( QName Expr ContentExpr 112 (XQuery) ContentExpr XQ ::= Expr Core Grammar The Core grammar productions for computed element constructors are: 67 (Core) CompElemConstructor ::= "element" ( QName Expr ContentExpr LocalNamespaceDecls 69 (Core) ContentExpr ::= Expr 98 (Core) LocalNamespaceDecls ::= LocalNamespaceDecl 68 (Core) LocalNamespaceDecl ::= "namespace" NCName URILiteral Normalization If the content expression is missing, the computed element constructor is normalized as if its content expression was the empty sequence. [ QName ] Expr == [ QName ] Expr Computed element constructors are normalized using the fs: item-sequence-to-node-sequence [ QName Expr ] Expr == element QName fs: item-sequence-to-node-sequence [ Expr ] Expr When the name of the element is also computed, the normalization rule applies atomization to the name expression. [ Expr 1 Expr 2 ] Expr == element { fn:data [ Expr 1 ] Expr fs: item-sequence-to-node-sequence [ Expr 2 ] Expr Notation The following auxiliary judgment adds a sequence of namespace bindings to the static context. add namespace bindings LocalNamespaceDecls to statEnv 1 yields statEnv 2 This judgment is defined as follows. statEnv |- add namespace bindings to statEnv 0 yields statEnv 0 LocalNamespaceDecl 1 LocalPart 1 URILiteral 1 ... LocalNamespaceDecl n LocalPart n URILiteral n dynEnvDefault |- URILiteral 1 has atomic value AnyURI ... dynEnvDefault |- URILiteral 1 has atomic value AnyURI statEnv 1 namespace statEnv 0 namespace LocalPart 1 AnyURI 1 ... statEnv n namespace statEnv n-1 namespace LocalPart n AnyURI n statEnv |- add namespace bindings LocalNamespaceDecl 1 LocalNamespaceDecl n to statEnv 0 yields statEnv n Static Type Analysis The normalization rules of direct element and attribute constructors leave us with only the computed forms of constructors. The static semantics for constructors is defined on all the computed forms. The computed element constructor itself has two forms: one in which the element name is a literal QName A computed element constructor creates a new element with either the type annotation XQ xs:untyped type annotation XQ xs:anyType statEnv constructionMode add namespace bindings LocalNamespaceDecls to statEnv 1 yields statEnv 2 statEnv 2 |- Expr : Type statEnv 2 |- Type <: statEnv 1 |- QName Expr LocalNamespaceDecls : QName xs:anyType statEnv constructionMode add namespace bindings LocalNamespaceDecls to statEnv 1 yields statEnv 2 statEnv 2 |- Expr : Type statEnv 2 |- Type <: statEnv 1 |- QName Expr LocalNamespaceDecls : QName xs:untyped In case the element name is computed as well, the name expression must be of type xs:QName xs:string xs:untypedAtomic statEnv constructionMode add namespace bindings LocalNamespaceDecls to statEnv 1 yields statEnv 2 statEnv 2 |- Expr 1 : Type 1 statEnv 2 |- Type 1 <: xs:QName xs:string xs:untypedAtomic statEnv 2 |- Expr 2 : Type 2 statEnv 2 |- Type 2 <: statEnv 1 |- Expr 1 Expr 2 LocalNamespaceDecls : xs:anyType statEnv constructionMode add namespace bindings LocalNamespaceDecls to statEnv 1 yields statEnv 2 statEnv 2 |- Expr 1 : Type 1 statEnv 2 |- Type 1 <: xs:QName xs:string xs:untypedAtomic statEnv 2 |- Expr 2 : Type 2 statEnv 2 |- Type 2 <: statEnv 1 |- Expr 1 Expr 2 LocalNamespaceDecls : xs:untyped Notation The following auxiliary judgment is used in the dynamic semantics of node constructors. Value 0 with text nodes processed is Value 1 This judgment is informally defined to hold when Value 1 Value 0 Adjacent text nodes in Value 0 After concatenation, any text node whose content is a zero-length string is deleted from the sequence. Dynamic Evaluation The following rules take a computed element constructor expression and construct an element node. The dynamic semantics for computed element constructors is the most complex of all expressions in XQuery. Here is how to read the rule below. First, the constructor's local namespace declarations are evaluated, yielding a sequence of namespace bindings. The static environment is extended to include the new namespace bindings, which are all active Section 3.7.1.2 Namespace Declaration Attributes XQ Second, the expression is evaluated, and its value's text nodes are processed. The resulting sequence must match zero-or-more attributes followed by zero-or-more element, text, processing-instruction or comment nodes. Third, the namespace bindings are concatenated with the list of active namespaces in the namespace environment statEnv namespace Expr Expr 0 statEnv n dynEnv |- Expr 0 => Value 0 Value 0 with text nodes processed is Value 1 statEnv |- Value 1 matches statEnv dynEnv |- QName Expr => QName xs:anyType Value 1 Expr Expr 0 LocalNamespaceDecls LocalNamespaceDecl 1 LocalNamespaceDecl n LocalNamespaceDecl 1 NCName 1 URILiteral 1 ... LocalNamespaceDecl n NCName n URILiteral n dynEnvDefault |- URILiteral 1 has atomic value AnyURI 1 ... dynEnvDefault |- URILiteral n has atomic value AnyURI n NamespaceBinding 1 NCName 1 AnyURI 1 ... NamespaceBinding n NCName n AnyURI n statEnv 1 statEnv namespace NCName 1 AnyURI 1 ... statEnv n statEnv n-1 namespace NCName n AnyURI n statEnv n dynEnv |- Expr 0 => Value 0 Value 0 with text nodes processed is Value 1 statEnv |- Value 1 matches NamespaceBindings NamespaceBinding 1 NamespaceBinding n fs: active_ns statEnv fs: get_static_ns_from_items statEnv Value 1 statEnv dynEnv |- QName Expr LocalNamespaceDecls => QName xs:anyType Value 1 NamespaceBindings The dynamic evaluation of an element constructor with a computed name is similar. There is one additional rule that checks that the value of the element's name expression matches xs:QName dynEnv |- Expr 1 => Value 0 statEnv |- Value 0 matches xs:QName QName fn:prefix-from-QName Value 0 : fn:local-name-from-QName Value 0 dynEnv |- QName Expr 2 LocalNamespaceDecls => Value dynEnv |- Expr 1 Expr 2 LocalNamespaceDecls => Value 113 (XQuery) CompAttrConstructor XQ ::= "attribute" ( QName Expr Expr Core Grammar The Core grammar production for computed attribute constructors is: 70 (Core) CompAttrConstructor ::= "attribute" ( QName Expr Expr Normalization Computed attribute constructors are normalized by mapping their name and content expression in a similar way as computed element constructors. The normalization rule uses the fs: item-sequence-to-string [ QName ] Expr == [ QName ] Expr [ QName Expr ] Expr == attribute QName fs: item-sequence-to-string [ Expr ] Expr [ Expr 1 Expr 2 ] Expr == attribute { fn:data [ Expr 1 ] Expr fs: item-sequence-to-string [ Expr 2 ] Expr Static Type Analysis The normalization rules for direct attribute constructors leave us with only the computed form of the attribute constructors. Like in a computed element constructor, a computed attribute constructor has two forms: one in which the attribute name is a literal QName In the case of attribute constructors, the type annotation XQ xs:untypedAtomic statEnv |- Expr : Type statEnv |- Type <: xs:string statEnv |- QName Expr : QName xs:untypedAtomic statEnv |- Expr 1 : Type 1 statEnv |- Type 1 <: xs:QName xs:string xs:untypedAtomic statEnv |- Expr 2 : Type 2 statEnv |- Type 2 <: xs:string statEnv |- Expr 1 Expr 2 : xs:untypedAtomic Dynamic Evaluation The following rules take a computed attribute constructor expression and construct an attribute node. The rules are similar to those rules for element constructors. First, the attribute's name is expanded into a qualified name. Second, the content expression is evaluated in the dynamic environment. dynEnv |- Expr => AtomicValue dynEnv |- QName Expr => QName xs:untypedAtomic AtomicValue dynEnv |- Expr 1 => Value 1 statEnv |- Value 1 matches xs:QName QName 1 fn:prefix-from-QName Value 1 : fn:local-name-from-QName Value 1 dynEnv |- Expr 2 => AtomicValue 2 dynEnv |- Expr 1 Expr 2 => QName 1 xs:untypedAtomic AtomicValue 2 110 (XQuery) CompDocConstructor XQ ::= "document" "{" Expr Core Grammar The Core grammar production for a computed document constructor is: 66 (Core) CompDocConstructor ::= "document" "{" Expr Normalization A document node constructor contains an expression, which must evaluate to a sequence of element, text, comment, or processing-instruction nodes. Section 3.7.3.3 Document Node Constructors XQ fs: item-sequence-to-node-sequence [ Expr ] Expr == document { fs: item-sequence-to-node-sequence [ Expr ] Expr Static Type Analysis The type of the entire expression is the most general document type annotation XQ statEnv |- Expr : Type statEnv |- Type <: statEnv |- Expr : Type Dynamic Evaluation The dynamic semantics checks that the argument expression evaluates to a value that is a sequence of element, text, processing-instruction, or comment nodes. The entire expression evaluates to a new document node value. If the construction mode is set to strip type annotation XQ statEnv constructionMode dynEnv |- Expr => Value 1 Value 1 with text nodes processed is Value 2 statEnv |- Value 2 matches dynEnv |- Expr => Value 2 statEnv constructionMode dynEnv |- Expr => Value 1 Value 1 erases to Value 2 Value 2 with text nodes processed is Value 3 statEnv |- Value 3 matches dynEnv |- Expr => Value 3 114 (XQuery) CompTextConstructor XQ ::= "text" "{" Expr Core Grammar The Core grammar production for a computed text constructor is: 71 (Core) CompTextConstructor ::= "text" "{" Expr Normalization A text node constructor contains an expression, which must evaluate to an xs:string Section 3.7.3.4 Text Node Constructors XQ fs: item-sequence-to-untypedAtomic-text [ Expr ] Expr == text { ( fs: item-sequence-to-untypedAtomic-text fn:data [ Expr ] Expr xs:string Static Type Analysis The static semantics checks that the argument expression has type xs:string empty statEnv |- Expr : xs:string statEnv |- Expr : Dynamic Evaluation If the argument expression returns the empty sequence, the text node constructor returns the empty sequence. dynEnv |- Expr => () dynEnv |- Expr => () If the argument expression returns a value of type xs:string dynEnv |- Expr => Value statEnv |- Value matches xs:string dynEnv |- Expr => Value 116 (XQuery) CompPIConstructor XQ ::= "processing-instruction" ( NCName Expr Expr Core Grammar The Core grammar production for computed processing-instruction constructors is: 73 (Core) CompPIConstructor ::= "processing-instruction" ( NCName Expr Expr Normalization Computed processing-instruction constructors are normalized by mapping their name and content expression in the same way that computed element and attribute constructors are normalized. [ NCName ] Expr == [ NCName ] Expr [ NCName Expr ] Expr == processing-instruction NCName fs: item-sequence-to-untypedAtomic-PI [ Expr ] Expr [ Expr 1 Expr 2 ] Expr == processing-instruction { fn:data [ Expr 1 ] Expr fs: item-sequence-to-untypedAtomic-PI [ Expr 2 ] Expr Static Type Analysis The static typing rules for processing-instruction constructors are straightforward. statEnv |- Expr : xs:untypedAtomic statEnv |- NCName Expr : NCName statEnv |- Expr 1 : xs:NCName xs:string xs:untypedAtomic statEnv |- Expr 2 : xs:untypedAtomic statEnv |- Expr 1 Expr 2 : Dynamic Evaluation The dynamic evaluation rules for computed processing-instructions are straightforward. dynEnv |- Expr => Value statEnv |- Value matches xs:untypedAtomic dynEnv |- NCName Expr => NCName Value dynEnv |- Expr 1 => Value 1 statEnv |- Value 1 matches xs:NCName xs:untypedAtomic xs:string xs:NCName Value 1 NCName 1 dynEnv |- Expr 2 => Value 2 statEnv |- Value 2 matches xs:untypedAtomic dynEnv |- Expr 1 Expr 2 => NCName 1 Value 2 115 (XQuery) CompCommentConstructor XQ ::= "comment" "{" Expr Core Grammar The Core grammar production for computed comment constructors is: 72 (Core) CompCommentConstructor ::= "comment" "{" Expr Normalization Computed comment constructors are normalized by mapping their content expression. [ Expr ] Expr == comment { ( fs: item-sequence-to-untypedAtomic-comment [ Expr ] Expr xs:string Static Type Analysis The static typing rule for computed comment constructors is straightforward. statEnv |- Expr : xs:string statEnv |- Expr : Dynamic Evaluation The dynamic evaluation rule for computed comment constructors is straightforward. dynEnv |- Expr => Value statEnv |- Value matches xs:string dynEnv |- Expr => Value The effect of in-scope namespaces on constructed elements is specified in [4.7.1 Direct Element Constructors] [4.7.3.1 Computed Element Constructors] Introduction [XPath/XQuery] provides [For/FLWOR] expressions for iteration, for binding variables to intermediate results, and filtering bound variables according to a predicate. A FLWORExpr ForClause LetClause WhereClause OrderByClause The dynamic semantics of the ordering mode in FLWOR expressions is not specified formally, as it would require the introduction of tuples, which are not supported in the [XPath/XQuery] data model. 33 (XQuery) FLWORExpr XQ ::= ( ForClause LetClause WhereClause OrderByClause ExprSingle 34 (XQuery) ForClause XQ ::= "for" "$" VarName TypeDeclaration PositionalVar ExprSingle VarName TypeDeclaration PositionalVar ExprSingle 36 (XQuery) LetClause XQ ::= "let" "$" VarName TypeDeclaration ExprSingle VarName TypeDeclaration ExprSingle 118 (XQuery) TypeDeclaration XQ ::= "as" SequenceType 35 (XQuery) PositionalVar XQ ::= "at" "$" VarName 37 (XQuery) WhereClause XQ ::= "where" ExprSingle 38 (XQuery) OrderByClause XQ ::= (("order" "by") | ("stable" "order" "by")) OrderSpecList 39 (XQuery) OrderSpecList XQ ::= OrderSpec OrderSpec 40 (XQuery) OrderSpec XQ ::= ExprSingle OrderModifier 41 (XQuery) OrderModifier XQ ::= ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral 4 (XPath) ForExpr XP ::= SimpleForClause 5 (XPath) SimpleForClause XP ::= "for" "$" VarName "in" ExprSingle ("," "$" VarName "in" ExprSingle)* Core Grammar The Core grammar productions for FLWOR expressions are: 24 (Core) FLWORExpr ::= ( ForClause LetClause ExprSingle 25 (Core) ForClause ::= "for" "$" VarName TypeDeclaration PositionalVar ExprSingle 27 (Core) LetClause ::= "let" "$" VarName TypeDeclaration ExprSingle 26 (Core) PositionalVar ::= "at" "$" VarName 75 (Core) TypeDeclaration ::= "as" SequenceType 28 (Core) OrderByClause ::= (("order" "by") | ("stable" "order" "by")) OrderSpecList 29 (Core) OrderSpecList ::= OrderSpec OrderSpec 30 (Core) OrderSpec ::= ExprSingle OrderModifier 31 (Core) OrderModifier ::= ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral Notation For convenience, we introduce the following auxiliary grammar productions to represent optional type declarations and positional variables in For and Let clauses. 79 (Formal) OptTypeDeclaration ::= TypeDeclaration 80 (Formal) OptPositionalVar ::= PositionalVar Notation To facilitate the specification of normalization, we also introduce the following auxiliary grammar productions as an alternative grammar for FLWOR expressions. 65 (Formal) FormalFLWORClause ::= ForClause LetClause WhereClause OrderByClause 66 (Formal) FormalReturnClause ::= FormalFLWORExpr Expr 67 (Formal) FormalFLWORExpr ::= FormalFLWORClause FormalReturnClause Normalization Full FLWOR expressions are normalized to nested Core FLWOR expressions with a single for or let clause. Note that some of the normalization rules below accept ungrammatical FLWOR expressions such as "where Expr 1 Expr 2 Normalized FLWOR expressions restrict a For and Let clause to bind only one variable. Otherwise, the Core FLWOR expression is the same as the XQuery FLWOR expression. The first normalization rule is applied on a full [For/FLWOR] expression, splitting it at the clause level, then applying further normalization on each separate clause. [ for $ VarName 1 OptTypeDeclaration 1 OptPositionalVar 1 Expr 1 ···, $ VarName n OptTypeDeclaration n OptPositionalVar n Expr n FormalReturnClause ] Expr == for $ VarName 1 OptTypeDeclaration 1 OptPositionalVar 1 [ Expr 1 ] Expr ··· for $ VarName n OptTypeDeclaration n OptPositionalVar n [ Expr n ] Expr [ FormalReturnClause ] Expr Likewise, a LetClause [ let $ VarName 1 OptTypeDeclaration 1 Expr 1 ···, $ VarName n OptTypeDeclaration n Expr n FormalReturnClause ] Expr == let $ VarName 1 OptTypeDeclaration 1 [ Expr 1 ] Expr ··· let $ VarName n OptTypeDeclaration n [ Expr n ] Expr [ FormalReturnClause ] Expr A WhereClause IfExpr [ Expr 1 FormalReturnClause ] Expr == if ( fn:boolean(( [ Expr 1 ] Expr [ FormalReturnClause ] Expr The order by clause is normalized using the auxiliary mapping rule [ ] OrderSpecList [4.8.4 Order By and Return Clauses] [ OrderSpecList FormalReturnClause ] Expr == [ OrderSpecList ] OrderSpecList [ FormalReturnClause ] Expr Finally, a stand-alone return clause is normalized into the corresponding expression. Recall that return [ Expr ] Expr == [ Expr ] Expr Example The following simple example illustrates how a FLWORExpr for $i $j let $k where 5 for $i as xs:integer in (1, 2), $j in (3, 4) let $k := $i + $j where $k >= 5 return <tuple> <i> { $i } </i> <j> { $j } </j> </tuple> By the first set of rules, this is normalized to (except for the operators and element constructor which are not treated here): for $i as xs:integer in (1, 2) return for $j in (3, 4) return let $k := $i + $j return if ($k >= 5) then <tuple> <i> { $i } </i> <j> { $j } </j> </tuple> else () For each binding of $i (1 , 2) for (3 , 4) (<tuple> <i>1</i> <j>4</j> </tuple>, <tuple> <i>2</i> <j>3</j> </tuple>, <tuple> <i>2</i> <j>4</j> </tuple>) Static Type Analysis A single for Type 1 Expr 1 prime type Type 1 prime Type 1 Type 1 [8.4 Judgments for FLWOR and other expressions on sequences] statEnv VarName 1 prime Type 1 Type 2 Expr 2 for Expr 1 Type 2 Type 1 ? * + quantifier Type 1 Type 2 · quantifier Type 1 [8.4 Judgments for FLWOR and other expressions on sequences] statEnv |- Expr 1 : Type 1 statEnv |- VarName 1 of var expands to Variable 1 statEnv varType Variable 1 prime Type 1 |- Expr 2 : Type 2 statEnv |- VarName 1 Expr 1 Expr 2 : Type 2 · quantifier Type 1 When a positional variable Variable pos xs:integer statEnv |- Expr 1 : Type 1 statEnv |- VarName 1 of var expands to Variable 1 statEnv |- VarName pos of var expands to Variable pos statEnv varType Variable 1 prime Type 1 Variable pos xs:integer |- Expr 2 : Type 2 statEnv |- VarName 1 VarName pos Expr 1 Expr 2 : Type 2 · quantifier Type 1 When a type declaration is present, the static semantics also checks that the type of the input expression is a subtype of the declared type and extends the static environment by typing $ VarName 1 Type 0 statEnv |- Expr 1 : Type 1 Type 0 [ SequenceType ] sequencetype statEnv |- prime Type 1 <: Type 0 statEnv |- VarName 1 of var expands to Variable 1 statEnv varType Variable 1 Type 0 |- Expr 2 : Type 2 statEnv |- VarName 1 SequenceType Expr 1 Expr 2 : Type 2 · quantifier Type 1 The last rule handles For expressions that contain a type declaration and a positional variable. When the positional variable is present, the static environment is also extended with the positional variable typed as an integer. statEnv |- Expr 1 : Type 1 Type 0 [ SequenceType ] sequencetype statEnv |- prime Type 1 <: Type 0 statEnv |- VarName 1 of var expands to Variable 1 statEnv |- VarName pos of var expands to Variable pos statEnv varType Variable 1 Type 0 Variable pos xs:integer |- Expr 2 : Type 2 statEnv |- VarName 1 SequenceType VarName pos Expr 1 Expr 2 : Type 2 · quantifier Type 1 Example For example, if $example 10.0, 1.0E1, 10 xs:decimal, xs:float, xs:integer for $s in $example return $s * 2 is typed as follows: (1) prime(xs:decimal, xs:float, xs:integer) = xs:decimal | xs:float | xs:integer (2) quantifier(xs:decimal, xs:float, xs:integer) = + (3) $s : xs:decimal | xs:float | xs:integer (4) $s * 2 : xs:decimal | xs:float | xs:integer (5) result-type : ( xs:decimal | xs:float | xs:integer ) + This result-type is not the most specific type possible. It does not take into account the order of elements in the input type, and it ignores the individual and overall number of elements in the input type. The most specific type possible is: xs:decimal, xs:float, xs:integer Dynamic Evaluation The evaluation of a for Expr 1 dynEnv |- Expr 1 => dynEnv |- VarName 1 OptTypeDeclaration OptPositionalVar Expr 1 Expr 2 => Otherwise, the iteration expression Expr 1 Item 1 Item n Item i for Expr 2 dynEnv VarName 1 Item i Value i Value n dynEnv |- Expr 1 => Item 1 Item n statEnv |- VarName of var expands to Variable dynEnv varValue Variable Item 1 |- Expr 2 => Value 1 ··· dynEnv varValue Variable Item n |- Expr 2 => Value n dynEnv |- VarName Expr 1 Expr 2 => Value 1 Value n The following rule is the same as the rule above, but includes the optional positional variable $ VarName pos VarName pos i dynEnv |- Expr 1 => Item 1 Item n statEnv |- VarName of var expands to Variable statEnv |- VarName pos of var expands to Variable pos dynEnv varValue Variable Item 1 Variable pos |- Expr 2 => Value 1 ··· dynEnv varValue Variable Item n Variable pos |- Expr 2 => Value n dynEnv |- VarName VarName pos Expr 1 Expr 2 => Value 1 Value n When a type declaration is present, the dynamic semantics also checks that each item in the result of evaluating Expr 1 dynEnv |- Expr 1 => Item 1 Item n Type 0 [ SequenceType ] sequencetype statEnv |- Item 1 matches Type 0 ··· statEnv |- Item n matches Type 0 statEnv |- VarName of var expands to Variable dynEnv varValue Variable Item 1 |- Expr 2 => Value 1 ··· dynEnv varValue Variable Item n |- Expr 2 => Value n dynEnv |- VarName SequenceType Expr 1 Expr 2 => Value 1 Value n The last rule covers a for dynEnv |- Expr 1 => Item 1 Item n Type 0 [ SequenceType ] sequencetype statEnv |- Item 1 matches Type 0 ··· statEnv |- Item n matches Type 0 statEnv |- VarName of var expands to Variable statEnv |- VarName pos of var expands to Variable pos dynEnv varValue Variable Item 1 Variable pos |- Expr 2 => Value 1 ··· dynEnv varValue Variable Item n Variable pos |- Expr 2 => Value n dynEnv |- VarName SequenceType VarName pos Expr 1 Expr 2 => Value 1 Value n Note that this definition allows non-deterministic Example Note that if the expression in the return for $i in (1,2) return (<i> {$i} </i>, <negi> {-$i} </negi>) each iteration in the for (<i>1</i>, <negi>-1</negi>, <i>2</i>, <negi>-2</negi>) Static Type Analysis A let statEnv Variable 1 Type 1 Expr 1 Expr 2 Type 2 statEnv |- Expr 1 : Type 1 statEnv |- VarName of var expands to Variable statEnv varType Variable Type 1 |- Expr 2 : Type 2 statEnv |- VarName Expr 1 Expr 2 : Type 2 When a type declaration is present, the static semantics also checks that the type of the input expression is a subtype of the declared type and extends the static environment by typing Variable 1 Type 0 statEnv |- Expr 1 : Type 1 Type 0 [ SequenceType ] sequencetype statEnv |- Type 1 <: Type 0 statEnv |- VarName of var expands to Variable statEnv varType Variable 1 Type 0 |- Expr 2 : Type 2 statEnv |- VarName 1 SequenceType Expr 1 Expr 2 : Type 2 Dynamic Evaluation A let dynEnv Variable Value 1 Expr 1 Expr 2 Value 2 dynEnv |- Expr 1 => Value 1 statEnv |- VarName of var expands to Variable dynEnv varValue Variable 1 Value 1 |- Expr 2 => Value 2 dynEnv |- VarName 1 Expr 1 Expr 2 => Value 2 When a type declaration is present, the dynamic semantics also checks that the result of evaluating Expr 1 dynEnv |- Expr 1 => Value 1 Type 0 [ SequenceType ] sequencetype statEnv |- Value 1 matches Type 0 statEnv |- VarName of var expands to Variable dynEnv varValue Variable 1 Value 1 |- Expr 2 => Value 2 dynEnv |- VarName 1 SequenceType Expr 1 Expr 2 => Value 2 Example Note the use of the environments to define the scope of each variable. For instance, in the following nested let let $k := 5 return let $k := $k + 1 return $k+1 the outermost let $k 5 $k+1 6 $k 7 Introduction The dynamic semantics of the OrderByClause Section 3.8.3 Order By and Return Clauses XQ Although an OrderByClause FLWORExpr FLWORExpr OrderByClause FLWORExpr OrderByClause gt OrderSpec Notation To define normalization of OrderBy, the following auxiliary mapping rule is used. [ OrderSpecList ] OrderSpecList == LetClause LetClause This rules specifies that OrderSpecList LetClause Normalization Proper static typing for FLWOR expressions with an OrderByClause OrderByClause OrderByClause gt Each OrderSpec [ OrderSpec 1 OrderSpec n ] OrderSpecList == [ OrderSpec 1 ] OrderSpecList [ OrderSpec n ] OrderSpecList [ Expr OrderModifier ] OrderSpecList == let $ fs: 0 let $ fs: 1 [ Expr ] Expr for $ fs: 2 fs: 1 for $ fs: 3 fs: 1 [ fs: 2 fs: 3 ] Expr [ OrderSpecList ] OrderSpecList Introduction The purpose of ordered unordered ordered unordered 91 (XQuery) OrderedExpr XQ ::= "ordered" "{" Expr 92 (XQuery) UnorderedExpr XQ ::= "unordered" "{" Expr Core Grammar The Core grammar productions for ordered/unordered expressions are: 61 (Core) OrderedExpr ::= "ordered" "{" Expr 62 (Core) UnorderedExpr ::= "unordered" "{" Expr Normalization OrderedExpr UnorderedExpr OrderedExpr UnorderedExpr [ Expr ] Expr == ordered { [ Expr ] Expr [ Expr ] Expr == unordered { [ Expr ] Expr Static Type Analysis OrderedExpr UnorderedExpr ordered unordered statEnv 1 statEnv orderingMode ordered statEnv 1 |- Expr : Type statEnv |- Expr : Type statEnv 1 statEnv orderingMode unordered statEnv 1 |- Expr : Type statEnv |- Expr : Type Dynamic Evaluation OrderedExpr UnorderedExpr fs: apply-ordering-mode union intersect except order by dynEnv |- Expr => Value dynEnv |- Expr => Value dynEnv |- Expr => Value dynEnv |- Expr => Value Introduction A conditional expression supports conditional evaluation of one of two expressions. 45 (XQuery) IfExpr XQ ::= "if" "(" Expr ExprSingle ExprSingle Core Grammar The Core grammar production for the conditional expression is: 35 (Core) IfExpr ::= "if" "(" Expr ExprSingle ExprSingle Normalization Conditional expressions are normalized as follows. [ Expr 1 Expr 2 Expr 3 ] Expr == if ( fn:boolean [ Expr 1 ] Expr [ Expr 2 ] Expr [ Expr 3 ] Expr Static Type Analysis statEnv |- Expr 1 : xs:boolean statEnv |- Expr 2 : Type 2 statEnv |- Expr 3 : Type 3 statEnv |- if Expr 1 then Expr 2 else Expr 3 : Type 2 Type 3 Dynamic Evaluation If the conditional's boolean expression Expr 1 Expr 2 Expr 3 dynEnv |- Expr 1 => dynEnv |- Expr 2 => Value 2 dynEnv |- Expr 1 Expr 2 Expr 3 => Value 2 dynEnv |- Expr 1 => dynEnv |- Expr 3 => Value 3 dynEnv |- Expr 1 Expr 2 Expr 3 => Value 3 Introduction [XPath/XQuery] defines two quantification expressions: 42 (XQuery) QuantifiedExpr XQ ::= ("some" | "every") "$" VarName TypeDeclaration ExprSingle VarName TypeDeclaration ExprSingle ExprSingle 6 (XPath) QuantifiedExpr XP ::= ("some" | "every") "$" VarName "in" ExprSingle ("," "$" VarName "in" ExprSingle)* "satisfies" ExprSingle Core Grammar The Core grammar production for quantified expressions is: 32 (Core) QuantifiedExpr ::= ("some" | "every") "$" VarName TypeDeclaration ExprSingle VarName TypeDeclaration ExprSingle ExprSingle Normalization The quantified expressions are normalized into nested Core quantified expressions, each of which binds one variable. [ VarName 1 Expr 1 VarName n Expr n Expr ] Expr == some $ VarName 1 [ Expr 1 ] Expr some $ VarName 2 [ Expr 2 ] Expr ... some $ VarName n [ Expr n ] Expr fn:boolean [ Expr ] Expr [ VarName 1 Expr 1 VarName n Expr n Expr ] Expr == every $ VarName 1 [ Expr 1 ] Expr every $ VarName 2 [ Expr 2 ] Expr ... every $ VarName n [ Expr n ] Expr fn:boolean [ Expr ] Expr Static Type Analysis The static semantics of the quantified expressions uses the notion of prime type for [4.8.2 For expression] statEnv |- Expr 1 : Type 1 statEnv |- VarName 1 of var expands to Variable 1 statEnv varType Variable 1 prime Type 1 |- Expr 2 : xs:boolean statEnv |- VarName 1 Expr 1 Expr 2 : xs:boolean The next rule is for SomeExpr statEnv |- Expr 1 : Type 1 Type 0 [ SequenceType ] sequencetype statEnv |- prime Type 1 <: Type 0 statEnv |- VarName 1 of var expands to Variable 1 statEnv varType Variable 1 Type 0 |- Expr 2 : xs:boolean statEnv |- VarName 1 SequenceType Expr 1 Expr 2 : xs:boolean The next rule is for EveryExpr statEnv |- Expr 1 : Type 1 statEnv |- VarName 1 of var expands to Variable 1 statEnv varType Variable 1 prime Type 1 |- Expr 2 : xs:boolean statEnv |- VarName 1 Expr 1 Expr 2 : xs:boolean The next rule is for EveryExpr statEnv |- Expr 1 : Type 1 Type 0 [ SequenceType ] sequencetype statEnv |- prime Type 1 <: Type 0 statEnv |- VarName 1 of var expands to Variable 1 statEnv varType Variable 1 Type 0 |- Expr 2 : xs:boolean statEnv |- VarName 1 SequenceType Expr 1 Expr 2 : xs:boolean Dynamic Evaluation If its input expression returns the empty sequence, the SomeExpr dynEnv |- Expr 1 => dynEnv |- VarName 1 OptTypeDeclaration Expr 1 Expr 2 => The SomeExpr SomeExpr dynEnv |- Expr 1 => Item 1 Item n statEnv |- VarName 1 of var expands to Variable 1 dynEnv varValue Variable 1 Item i |- Expr 2 => i in dynEnv |- VarName 1 Expr 1 Expr 2 => The next rule is for SomeExpr dynEnv |- Expr 1 => Item 1 Item n Type 0 [ SequenceType ] sequencetype statEnv |- Item i matches Type 0 i in statEnv |- VarName 1 of var expands to Variable 1 dynEnv varValue Variable 1 Item i |- Expr 2 => dynEnv |- VarName 1 SequenceType Expr 1 Expr 2 => The next rule is for SomeExpr dynEnv |- Expr 1 => Item 1 Item n statEnv |- VarName 1 of var expands to Variable 1 dynEnv varValue Variable 1 Item 1 |- Expr 2 => ... dynEnv varValue Variable 1 Item n |- Expr 2 => dynEnv |- VarName 1 Expr 1 Expr 2 => The next rule is for SomeExpr dynEnv |- Expr 1 => Item 1 Item n Type 0 [ SequenceType ] sequencetype statEnv |- VarName 1 of var expands to Variable 1 dynEnv varValue Variable 1 Item 1 |- Expr 2 => statEnv |- Item 1 matches Type 0 ... dynEnv varValue Variable 1 Item n |- Expr 2 => statEnv |- Item n matches Type 0 dynEnv |- VarName 1 SequenceType Expr 1 Expr 2 => If its input expression returns the empty sequence, the EveryExpr dynEnv |- Expr 1 => dynEnv |- VarName 1 OptTypeDeclaration Expr 1 Expr 2 => The EveryExpr EveryExpr dynEnv |- Expr 1 => Item 1 Item n statEnv |- VarName 1 of var expands to Variable 1 dynEnv varValue Variable 1 Item i |- Expr 2 => i in dynEnv |- VarName 1 Expr 1 Expr 2 => The next rule is for EveryExpr dynEnv |- Expr 1 => Item 1 Item n Type 0 [ SequenceType ] sequencetype statEnv |- Item i matches Type 0 statEnv |- VarName 1 of var expands to Variable 1 dynEnv varValue Variable 1 Item i |- Expr 2 => i in dynEnv |- VarName 1 SequenceType Expr 1 Expr 2 => The next rule is for EveryExpr dynEnv |- Expr 1 => Item 1 Item n statEnv |- VarName 1 of var expands to Variable 1 dynEnv varValue Variable 1 Item 1 |- Expr 2 => ... dynEnv varValue Variable 1 Item n |- Expr 2 => dynEnv |- VarName 1 Expr 1 Expr 2 => The next rule is for EveryExpr dynEnv |- Expr 1 => Item 1 Item n Type 0 [ SequenceType ] sequencetype statEnv |- VarName 1 of var expands to Variable 1 dynEnv varValue Variable 1 Item 1 |- Expr 2 => statEnv |- Item 1 matches Type 0 ... dynEnv varValue Variable 1 Item n |- Expr 2 => statEnv |- Item n matches Type 0 dynEnv |- VarName 1 SequenceType Expr 1 Expr 2 => Introduction Some of the expressions relying on the SequenceTypes syntax are called expressions on SequenceTypes. The syntax of SequenceTypes is described in [3.5.3 SequenceType Syntax] 54 (XQuery) InstanceofExpr XQ ::= TreatExpr SequenceType Introduction The SequenceType expression " Expr SequenceType Expr SequenceType Normalization An InstanceofExpr TypeswitchExpr fs: [ Expr SequenceType ] Expr == typeswitch ( [ Expr ] Expr case $ fs: SequenceType fn:true default $ fs: fn:false 43 (XQuery) TypeswitchExpr XQ ::= "typeswitch" "(" Expr CaseClause VarName ExprSingle 44 (XQuery) CaseClause XQ ::= "case" ("$" VarName SequenceType ExprSingle Introduction The typeswitch Each branch of a typeswitch expression may have an optional $ VarName Core Grammar The Core grammar productions for typeswitch 33 (Core) TypeswitchExpr ::= "typeswitch" "(" Expr CaseClause VarName ExprSingle 34 (Core) CaseClause ::= "case" "$" VarName SequenceType ExprSingle Notation For convenience, we introduce the following auxiliary grammar production. 81 (Formal) OptVarName ::= ("$" VarName Notation To define normalization of case clauses to the [XPath/XQuery] Core, the following auxiliary mapping rules are used. [ CaseClause ] Case == CaseClause specifies that CaseClause CaseClause Normalization Normalization of a typeswitch expression guarantees that every branch has an associated $ VarName [ SequenceType Expr ] Case == case $ fs: 1 SequenceType [ Expr ] Expr [ VarName SequenceType Expr ] Case == case $ VarName SequenceType [ Expr ] Expr [ Expr ] Case == default $ fs: 1 [ Expr ] Expr [ VarName Expr ] Case == default $ VarName [ Expr ] Expr [ typeswitch ( Expr 0 CaseClause 1 ··· CaseClause n default OptVarName Expr n+1 ] Expr == typeswitch ( [ Expr 0 ] Expr [ CaseClause 1 ] Case ··· [ CaseClause n ] Case [ OptVarName Expr n+1 ] Case Notation For convenience, we use the following auxiliary grammar productions to denote case clauses in a typeswitch. 68 (Formal) FormalCaseClauses ::= ( FormalCaseClause FormalCaseClauses FormalDefaultCaseClause 69 (Formal) FormalCaseClause ::= "case" "$" VarName SequenceType Expr 70 (Formal) FormalDefaultCaseClause ::= "default" "$" VarName Expr The following judgments statEnv |- Type 1 case FormalCaseClause : Type statEnv |- Type 1 case FormalDefaultCaseClause : Type is used in the static semantics of typeswitch. It indicates that under the static environment statEnv Type 1 Type The following judgment dynEnv |- Value 1 against FormalCaseClauses => Value 2 is used in the dynamic semantics of typeswitch. It indicates that under the dynamic environment dynEnv Value 1 Value 2 Static Type Analysis The static typing rules for the typeswitch expression are simple. Each case clause and the default clause of the typeswitch is typed independently. The type of the entire typeswitch expression is the union of the types of all the clauses. statEnv |- Expr 0 : Type 0 statEnv |- Type 0 case VarName 1 SequenceType 1 Expr 1 : Type 1 ··· statEnv |- Type 0 case VarName n SequenceType n Expr n : Type n statEnv |- Type 0 case VarName n+1 Expr n : Type n+1 statEnv |- (typeswitch ( Expr 0 case $ VarName 1 SequenceType 1 Expr 1 ··· case $ VarName n SequenceType n Expr n default $ VarName n+1 Expr n+1 : Type 1 Type n+1 To type one case clause, the case variable is assigned the type of the case clause Case Type Case Type [ SequenceType ] sequencetype statEnv |- VarName of var expands to Variable statEnv varType Variable Case Type |- Expr : Type statEnv |- Type 0 case VarName SequenceType Expr : Type To type the default clause, the variable is assigned the type of the input expression and the body of the default clause is typed in the extended environment. statEnv |- VarName of var expands to Variable statEnv varType Variable Type 0 |- Expr : Type statEnv |- Type 0 case VarName Expr : Type Dynamic Evaluation The evaluation of a typeswitch proceeds as follows. First, the input expression is evaluated, yielding an input value. The effective case case case return return dynEnv |- Expr => Value 0 dynEnv |- Value 0 against FormalCaseClauses => Value 1 dynEnv |- Expr FormalCaseClauses => Value 1 If the value matches the sequence type, the following rule applies: It extends the dynamic environment by binding the variable Variable Value 0 return Case Type [ SequenceType ] sequencetype statEnv |- Value 0 matches Case Type statEnv |- VarName of var expands to Variable dynEnv varValue Variable Value 0 |- Expr => Value 1 dynEnv |- Value 0 against VarName SequenceType Expr FormalCaseClauses => Value 1 If the value does not match the sequence type, the current case is not evaluated, and the remaining case clauses are evaluated in order by applying the inference rule recursively. Case Type [ SequenceType ] sequencetype statEnv |- not Value 0 matches Case Type dynEnv |- Value 0 against FormalCaseClauses => Value 1 dynEnv |- Value 0 against VarName SequenceType Expr FormalCaseClauses => Value 1 The last rule states that the default return statEnv |- VarName of var expands to Variable dynEnv varValue Variable Value 0 |- Expr => Value 1 dynEnv |- Value 0 against VarName Expr => Value 1 Introduction The cast 57 (XQuery) CastExpr XQ ::= UnaryExpr SingleType 117 (XQuery) SingleType XQ ::= AtomicType Core Grammar The Core grammar productions for cast 39 (Core) CastExpr ::= ValueExpr SingleType 74 (Core) SingleType ::= AtomicType Normalization The normalization of cast applies atomization to its argument. The type declaration asserts that the result is a single atomic value. The second normalization rule applies when the target type is optional. [ Expr AtomicType ] Expr == let $v as xs:anyAtomicType fn:data [ Expr ] Expr $v cast as AtomicType [ Expr AtomicType ] Expr == let $v as xs:anyAtomicType fn:data [ Expr ] Expr typeswitch ($v) case $ fs: default $ fs: AtomicType Static Type Analysis The static typing rule of cast cast cast statEnv |- Expr AtomicType : AtomicType Notation The dynamic semantics of cast Section 17 Casting FO casting table Section 17 Casting FO Section 17 Casting FO The judgment AtomicValue 1 cast value to type AtomicType => AtomicValue 2 holds if AtomicValue 1 AtomicType AtomicValue 2 Section 17 Casting FO Dynamic Evaluation dynEnv |- Expr => AtomicValue 1 AtomicValue 1 cast value to type AtomicType => AtomicValue 2 dynEnv |- Expr AtomicType => AtomicValue 2 56 (XQuery) CastableExpr XQ ::= CastExpr SingleType Castable expressions check whether a value can be cast to a given type. Core Grammar The Core grammar production for castable is: 38 (Core) CastableExpr ::= CastExpr SingleType Normalization The normalization of castable simply maps its expression argument. [ Expr SingleType ] Expr == ( [ Expr ] Expr SingleType Static Type Analysis The type of a Core castable statEnv |- Expr AtomicType : xs:boolean Notation The auxiliary judgment: Value can be cast to SingleType holds when Value SingleType cast value to type () can be cast to AtomicType Value can be cast to AtomicType Value can be cast to AtomicType fn:data( Value AtomicValue 1 AtomicValue 1 cast value to type AtomicType => AtomicValue 2 Value can be cast to AtomicType Dynamic Evaluation If the value of the operand expression can be cast to the given type, then the castable dynEnv |- Expr => Value Value can be cast to SingleType dynEnv |- Expr SingleType => Otherwise, 'castable as' evaluates to false. dynEnv |- Expr => Value not Value can be cast to SingleType dynEnv |- Expr SingleType => Constructor functions provide an alternative syntax for casting. Notation Calls to constructor functions are normalized differently from other function calls, so we introduce an auxiliary judgment to detect whether the function being called is a constructor function. statEnv |- expanded-QName denotes a constructor function This judgment holds when the expanded function name maps to an atomic type in the in-scope schema types. statEnv typeDefn expanded-QName QName AtomicTypeDerivation statEnv |- expanded-QName denotes a constructor function Normalization Constructor functions for atomic types are normalized to explicit cast as statEnv |- QName of func expands to expanded-QName statEnv |- expanded-QName denotes a constructor function statEnv |- [ QName ExprSingle 1 ] Expr [ ExprSingle 1 QName ] Expr 55 (XQuery) TreatExpr XQ ::= CastableExpr SequenceType Introduction The expression " Expr SequenceType Normalization Treat as expressions are normalized to typeswitch expressions. Note that the following normalization rule uses a variable $ fs: [ Expr SequenceType ] Expr == typeswitch ( [ Expr ] Expr case $ fs: SequenceType fs: default $ fs: fn:error 63 (XQuery) ValidateExpr XQ ::= "validate" ValidationMode Expr 64 (XQuery) ValidationMode XQ ::= "lax" | "strict" Core Grammar The Core grammar productions for validate are: 41 (Core) ValidateExpr ::= "validate" ValidationMode Expr 42 (Core) ValidationMode ::= "lax" | "strict" A validate in-scope schema definitions [Schema Part 1] type annotation XQ Normalization A validate expression with no validation mode is normalized into a validate expression with the validation mode set to strict. [ Expr ] Expr == validate strict { [ Expr ] Expr [ ValidationMode Expr ] Expr == validate ValidationMode [ Expr ] Expr Static Type Analysis Static typing of the validate operation begins with the following rule. We infer the type of the argument expression, and ensure that it is consistent with a run-time argument that is either an element or a well-formed document node (i.e., with only one root element and no text nodes). Then we hand off the type and the validation mode to the validate statEnv |- Expr : Type statEnv |- Type <: statEnv |- validate ValidationMode Type : Type U statEnv |- ValidationMode Expr : Type U Because the type of the argument expression may be a union of multiple element and document types, the judgment: statEnv |- validate ValidationMode Type : Type U extracts the prime type of the argument type, applies the validate item type prime Type FormalItemType 1 FormalItemType n statEnv |- validate ValidationMode item type FormalItemType 1 : Type 1 ... statEnv |- validate ValidationMode item type FormalItemType n : Type n Type 1 Type n Type U statEnv |- validate ValidationMode Type : Type U The judgement statEnv |- validate ValidationMode item type FormalItemType : Type does a case analysis on the different item types that it can encounter. DocumentType Type statEnv |- validate ValidationMode Type : Type U statEnv |- validate ValidationMode item type DocumentType : Type U ElementType ElementNameOrWildcard OptTypeSpecifier statEnv |- ElementNameOrWildcard with mode ValidationMode resolves to ElementType statEnv |- validate ValidationMode item type ElementType : ElementType statEnv |- validate ValidationMode item type ProcessingInstructionType : statEnv |- validate ValidationMode item type : Dynamic Evaluation The normative dynamic semantics of validation is specified in Section 3.13 Validate Expressions XQ serialization of the data model, as described in [XSLT 2.0 and XQuery 1.0 Serialization (Second Edition)] validation of the serialized value into a Post-Schema Validated Infoset, as described in [Schema Part 1] construction of a new data model value, as described in [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] The above steps are expressed formally by the "erasure" and "annotation" judgments. Formally, validation removes existing type annotations from nodes ("erasure"), and it re-validates the corresponding data model instance, possibly adding new type annotations to nodes ("annotation"). Both erasure and annotation are described formally in [F Auxiliary Judgments for Validation] validate In the first premise below, the expression to validate is evaluated. The resulting value must be an element or document node. The second premise constructs a new value in which all existing type annotations have been erased. The third premise determines the element type that corresponds to the element node's name in the given validation mode. The last premise validates erased element node with the type against which it is validated, using the annotate as statEnv dynEnv |- Expr => ElementValue 1 ElementValue 1 erases to ElementValue 2 ElementValue 2 ElementName 2 TypeName 2 Value statEnv |- ElementName 2 with mode ValidationMode resolves to ElementType 2 statEnv |- annotate as ElementType 2 ElementValue 2 => ElementValue 3 dynEnv |- ValidationMode Expr => ElementValue 3 The rule for validating a document node is similar to that for validating an element node. Dynamic Evaluation statEnv dynEnv |- Expr => ElementValue 1 document { ElementValue 1 erases to ElementValue 2 ElementValue 2 ElementName 2 TypeName 2 Value statEnv |- ElementName 2 with mode ValidationMode resolves to ElementType 2 statEnv |- annotate as ElementType 2 ElementValue 2 => ElementValue 3 dynEnv |- ValidationMode Expr => ElementValue 3 Introduction An extension expression is an expression whose semantics are implementation-defined. An extension expression consists of one or more pragmas, followed by an expression enclosed in curly braces. 65 (XQuery) ExtensionExpr XQ ::= Pragma Expr 66 (XQuery) Pragma XQ ::= "(#" S QName S PragmaContents 67 (XQuery) PragmaContents XQ ::= ( Char Core Grammar The Core grammar productions for ExtensionExpr are: 43 (Core) ExtensionExpr ::= Pragma Expr 44 (Core) Pragma ::= "(#" S QName S PragmaContents 45 (Core) PragmaContents ::= ( Char Normalization Extension expressions are normalized as extension expressions in the [XPath/XQuery] Core. [ Pragma Expr ] Expr == Pragma [ Expr ] Expr If the extension expression does not contain any expression, this is normalized into an extension expression with a call to the fn:error [ Pragma ] Expr == Pragma fn:error Static Type Analysis If at least one of the pragmas is recognized, the static semantics are implementation-defined. If none of the pragmas is recognized, the static semantics are the same as for the input expression. In both cases, the static typing must be applied on the input expression, possibly raising the corresponding type errors. statEnv |- Expr : Type 1 statEnv |- Pragma Type 2 statEnv |- Pragma Expr : Type 2 statEnv |- Expr : Type 1 statEnv |- Pragma statEnv |- Pragma Expr : Type 1 Dynamic Evaluation The QName of a pragma must resolve to a namespace URI and local name, using the statically known namespaces. If at least one of the pragmas is recognized, the dynamic semantics is implementation-defined. dynEnv |- Pragma Value dynEnv |- Pragma Expr => Value If none of the pragmas is recognized, the dynamic semantics of an ExtensionExpr No Pragma dynEnv |- Expr => Value dynEnv |- Pragma Expr => Value The organization of this section parallels the organization of Section 4 Modules and Prologs XQ Introduction XQuery supports modules as defined in Section 4 Modules and Prologs XQ main module XQ Prolog XQ query body XQ query body XQ library module XQ Prolog XQ The Prolog is a sequence of declarations that affect query processing. The Prolog can be used, for example, to declare namespace prefixes, import types from XML Schemas, and declare functions and variables. Namespace declarations and schema imports always precede function and variable declarations, as specified by the following grammar productions. 1 (XQuery) Module XQ ::= VersionDecl LibraryModule MainModule 3 (XQuery) MainModule XQ ::= Prolog QueryBody 4 (XQuery) LibraryModule XQ ::= ModuleDecl Prolog 6 (XQuery) Prolog XQ ::= (( DefaultNamespaceDecl Setter NamespaceDecl Import Separator VarDecl FunctionDecl OptionDecl Separator 7 (XQuery) Setter XQ ::= BoundarySpaceDecl DefaultCollationDecl BaseURIDecl ConstructionDecl OrderingModeDecl EmptyOrderDecl CopyNamespacesDecl 8 (XQuery) Import XQ ::= SchemaImport ModuleImport 9 (XQuery) Separator XQ ::= ";" 30 (XQuery) QueryBody XQ ::= Expr Function declarations are globally scoped, that is, the use of a function name in a function call may precede declaration of the function. Variable declarations are lexically scoped, i.e., variable declarations must precede variable uses. Core Grammar The module declarations and prolog are processed as part of the static and dynamic context processing. In addition, normalization of prolog declarations is performed into a simplified formal grammar given below. As a result, the XQuery core does not need to include the prolog and module declarations. The entry point for the core grammar is the Expr [4 Expressions] Notation Modules are identified and can be imported using a target namespace (a URI). In [XPath/XQuery], the process by which a module is obtained from a given target namespace is implementation defined. In this specification, we use the following auxiliary judgment to model that implementation defined process. The judgment: AnyURI is target namespace of modules Module 1 Module n holds if Module 1 Module n AnyURI Module i [XQuery 1.0: An XML Query Language (Second Edition)] Notation The XQuery Prolog requires that declarations appear in a particular order. In the Formal Semantics, it is simpler to assume the declarations can appear in any order, as it does not change their semantics -- we simply assume that an XQuery parser has enforced the required order. The Prolog contains a variety of declarations that specify the initial static and dynamic context of the query. The following formal grammar productions represent any Prolog declaration. 71 (Formal) PrologDeclList ::= ( PrologDecl Separator PrologDeclList 72 (Formal) PrologDecl ::= DefaultCollationDecl BaseURIDecl ConstructionDecl OrderingModeDecl EmptyOrderDecl CopyNamespacesDecl SchemaImport ModuleImport NamespaceDecl DefaultNamespaceDecl VarDecl FunctionDecl OptionDecl The function [ ] PrologDecl [ PrologDecl 1 ] PrologDecl == PrologDecl 2 The following auxiliary judgments are applied when statically processing the declarations in the prolog. The effect of the judgment is to process each prolog declaration in order, constructing a new static environment from the static environment constructed from previous prolog declarations. The judgment: AnyURI statEnv 1 |- PrologDeclList => stat statEnv 2 with PrologDeclList 1 holds if for the given module with namespace AnyURI statEnv 1 PrologDeclList statEnv 2 The judgment: statEnv 1 |- PrologDecl => stat statEnv 2 holds if under the static environment statEnv 1 PrologDecl statEnv 2 Notation Because functions can be mutually referential, function signatures must be defined in the static environment before static type analysis is applied to the function bodies. The following judgment is used to extend the static environment with the appropriate function signatures. That judgment is used when computing the static context for a given module before applying static context processing. The judgment: statEnv 1 |- PrologDeclList => sigs statEnv 2 holds if extending the static environment statEnv 1 PrologDeclList statEnv 2 This judgment is defined as follows. In case there is no declaration, the static environment is returned unchanged. statEnv |- => sigs statEnv If the case of a namespace declaration, the static context is extended with the corresponding namespace binding. PrologDecl NamespaceDecl PrologDecl DefaultNamespaceDecl statEnv |- PrologDecl => stat statEnv 1 statEnv 1 |- PrologDeclList => sigs statEnv 2 statEnv |- PrologDecl PrologDeclList => sigs statEnv 2 If the case of a function declaration, the static context is extended with the corresponding signature. PrologDecl FunctionDecl statEnv |- PrologDecl => sigs statEnv 1 statEnv 1 |- PrologDeclList => sigs statEnv 2 statEnv |- PrologDecl PrologDeclList => sigs statEnv 2 FunctionDecl QName VarName 1 SequenceType 1 VarName n SequenceType n SequenceType r EnclosedExpr statEnv |- QName of func expands to expanded-QName [ SequenceType 1 ] sequencetype Type 1 ... [ SequenceType n ] sequencetype Type n [ SequenceType r ] sequencetype Type r FunctionSig expanded-QName Type 1 Type n Type r statEnv 1 statEnv funcType expanded-QName FunctionSig statEnv |- FunctionDecl => sigs statEnv 1 For all other kinds of declarations, the static context is left unchanged. not PrologDecl FunctionDecl not PrologDecl NamespaceDecl not PrologDecl DefaultNamespaceDecl statEnv |- PrologDecl PrologDeclList => sigs statEnv In case of a function declaration, the static context is extended with the corresponding function signature. Static Context Processing Prolog declarations are processed in the order they are encountered. The normalization of a prolog declaration PrologDecl PrologDecl PrologDecl The following inference rules express this dependency. The first rule specifies that for an empty sequence of prolog declarations, the initial static environment is left unchanged. AnyURI statEnv |- => stat statEnv with The next two rules interleaves normalization and static context processing. The result of static context processing and normalization is a static context and the normalized prolog declarations. In case the declaration is a module import, the URI for the current module is passed to the static context processing rule. This allows to avoid self-import, which is handled globally (See rules for building the context for module declarations in [5.2 Module Declaration] not PrologDecl ModuleImport [ PrologDecl ] PrologDecl PrologDecl 1 statEnv |- PrologDecl 1 => stat statEnv 1 AnyURI statEnv 1 |- PrologDeclList => stat statEnv 2 with PrologDeclList 1 AnyURI statEnv |- PrologDecl PrologDeclList => stat statEnv 2 with PrologDecl 1 PrologDeclList 1 PrologDecl ModuleImport [ PrologDecl ] PrologDecl PrologDecl 1 AnyURI statEnv |- PrologDecl 1 => stat statEnv 1 AnyURI statEnv 1 |- PrologDeclList => stat statEnv 2 with PrologDeclList 1 AnyURI statEnv |- PrologDecl PrologDeclList => stat statEnv 2 with PrologDecl 1 PrologDeclList 1 Static Type Analysis Static typing of a main module follows context processing and normalization. Context processing and normalization of a main module applies the rules above to the prolog, then using the resulting static environment statEnv AnyURI statEnvDefault |- PrologDeclList => stat statEnv with PrologDeclList 1 statEnv |- [ QueryBody ] Expr Expr 2 statEnv |- Expr 2 : Type PrologDeclList QueryBody : Type Notation Similarly, the judgment: dynEnv 1 |- PrologDeclList => dyn dynEnv 2 holds if under the dynamic environment dynEnv 1 PrologDeclList dynEnv 2 The judgment: dynEnv |- PrologDecl => dyn dynEnv 1 holds if under the dynamic environment dynEnv PrologDecl dynEnv 1 Dynamic Context Processing The rules for initializing the dynamic context are as follows. The first rule specifies that for an empty sequence of prolog declarations, the dynamic environment is left unchanged. dynEnv |- => dyn dynEnv The second rule simply computes the dynamic environment by processing the prolog declarations in order. dynEnv |- PrologDecl => dyn dynEnv 1 dynEnv 1 |- PrologDeclList => dyn dynEnv 2 dynEnv |- PrologDecl PrologDeclList => dyn dynEnv 2 Dynamic Evaluation Dynamic evaluation of a main module applies the rules for dynamic-context processing to the prolog declarations, then using the resulting dynamic environment dynEnv #MAIN ; statEnvDefault |- PrologDeclList => stat statEnv with PrologDeclList 1 statEnv |- [ QueryBody ] Expr Expr 2 dynEnvDefault |- PrologDeclList 1 => dyn dynEnv dynEnv |- Expr 2 => Value PrologDeclList QueryBody => Value Notation We define a new judgment that maps a module's target namespace (or a main module) to the corresponding module's static environment: ( AnyURI => module_statEnv statEnv We also define a new judgment that maps a module's target namespace (or a main module) to the corresponding module's dynamic environment: ( AnyURI => module_dynEnv dynEnv For a main module, those judgments are defined as follows. statEnvDefault |- PrologDeclList => stat statEnv #MAIN => module_statEnv statEnv dynEnvDefault |- PrologDeclList => dyn dynEnv #MAIN => module_dynEnv dynEnv For a library module, those judgments are defined in [5.11 Module Import] 2 (XQuery) VersionDecl XQ ::= "xquery" "version" StringLiteral StringLiteral Separator Introduction A version declaration specifies the applicable XQuery syntax and semantics for a module. An XQuery implementation must raise a static error when processing a query labeled with a version that the implementation does not support. This document applies to XQuery 1.0 only and does not specify this static error formally. Verifying whether the proper version declaration is used is not formally specified. Introduction 5 (XQuery) ModuleDecl XQ ::= "module" "namespace" NCName URILiteral Separator We assume that the static-context processing and dynamic-context processing described in [5 Modules and Prologs] before Core Grammar The core grammar production for module declarations is: 1 (Core) ModuleDecl ::= "module" "namespace" NCName URILiteral Separator 2 (Core) Separator ::= ";" Normalization Module declarations are left unchanged through normalization. [ ModuleDecl ] PrologDecl == ModuleDecl Static Context Processing The effect of a module declaration is to apply the static context processing rules defined in [5 Modules and Prologs] The module declaration extends the prolog with a namespace declaration that binds the module's prefix to its target namespace (a URI), then computes the static context for the complete module. AnyURI is target namespace of modules Module 1 Module n Module 1 NCName 1 URILiteral PrologDeclList 1 ... Module 1 NCName 1 URILiteral PrologDeclList n dynEnv |- URILiteral has atomic value AnyURI statEnvDefault |- PrologDeclList 1 PrologDeclList n => sigs statEnv 0 AnyURI statEnv 0 |- NCName URILiteral PrologDeclList 1 => stat statEnv 1 with PrologDeclList ... AnyURI statEnv n-1 |- NCName URILiteral PrologDeclList n => stat statEnv n with PrologDeclList AnyURI => module_statEnv statEnv n Note that the rule above and the rules for static context processing of an "import module" declaration in [5.11 Module Import] Dynamic Context Processing The dynamic context processing of a module declaration is similar to that of static processing. The module declaration extends the prolog with a namespace declaration that binds the module's prefix to its target namespace (a URI), then computes the dynamic context for the complete module. AnyURI is target namespace of modules Module 1 Module n Module 1 NCName URILiteral PrologDeclList 1 ... Module n NCName URILiteral PrologDeclList n dynEnv |- URILiteral has atomic value AnyURI dynEnvDefault |- NCName URILiteral PrologDeclList 1 => dyn dynEnv 1 ... dynEnv n-1 |- NCName URILiteral PrologDeclList n => dyn dynEnv n AnyURI => module_dynEnv dynEnv n Note that the rule above and the rules for dynamic context processing of an "import module" declaration in [5.11 Module Import] 11 (XQuery) BoundarySpaceDecl XQ ::= "declare" "boundary-space" ("preserve" | "strip") The semantics of a boundary-space declaration is not specified formally. 19 (XQuery) DefaultCollationDecl XQ ::= "declare" "default" "collation" URILiteral Core Grammar The core grammar production for default collation declarations is: 11 (Core) DefaultCollationDecl ::= "declare" "default" "collation" URILiteral Normalization Default collation declarations are left unchanged through normalization. [ DefaultCollationDecl ] PrologDecl == DefaultCollationDecl Static Context Processing The default collation declaration updates the collations environment component within the static environment. The collations environment component is used by several functions in [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] dynEnv |- URILiteral has atomic value AnyURI statEnv collations AnyURI Collation statEnv 1 statEnv defaultCollation Collation statEnv |- URILiteral => stat statEnv 1 Dynamic Context Processing The default collation declaration does not affect the dynamic context. dynEnv |- URILiteral => dyn dynEnv 20 (XQuery) BaseURIDecl XQ ::= "declare" "base-uri" URILiteral Core Grammar The core grammar production for base uri declarations is: 12 (Core) BaseURIDecl ::= "declare" "base-uri" URILiteral Normalization Base URI declarations are left unchanged through normalization. [ BaseURIDecl ] PrologDecl == BaseURIDecl Static Context Processing A base URI declaration specifies the base URI property of the static context, which is used when resolving relative URIs within a module. dynEnv |- URILiteral has atomic value AnyURI statEnv 1 statEnv baseURI AnyURI statEnv |- URILiteral => stat statEnv 1 Dynamic Context Processing The base URI declaration does not affect the dynamic context. dynEnv |- URILiteral => dyn dynEnv 25 (XQuery) ConstructionDecl XQ ::= "declare" "construction" ("strip" | "preserve") Core Grammar The core grammar production for construction declarations is: 17 (Core) ConstructionDecl ::= "declare" "construction" ("strip" | "preserve") Notation For convenience, we introduce the following auxiliary grammar production. 89 (Formal) ConstructionMode ::= "preserve" | "strip" Normalization Construction declarations are left unchanged through normalization. [ ConstructionDecl ] PrologDecl == ConstructionDecl Static Context Processing The construction declaration modifies the construction mode in the static context. statEnv 1 statEnv constructionMode ConstructionMode statEnv |- ConstructionMode => stat statEnv 1 Dynamic Context Processing The construction declaration does not have any effect on the dynamic context. dynEnv |- ConstructionMode => stat dynEnv 14 (XQuery) OrderingModeDecl XQ ::= "declare" "ordering" ("ordered" | "unordered") Core Grammar The core grammar production for ordering mode declarations is: 6 (Core) OrderingModeDecl ::= "declare" "ordering" ("ordered" | "unordered") Normalization Ordering mode declarations are left unchanged through normalization. [ OrderingModeDecl ] PrologDecl == OrderingModeDecl Static Context Processing The ordering mode declaration does not have any effect on the static context. statEnv |- OrderingModeDecl => stat statEnv Dynamic Context Processing The ordering mode declaration does not have any effect on the dynamic context. dynEnv |- OrderingModeDecl => dyn dynEnv 15 (XQuery) EmptyOrderDecl XQ ::= "declare" "default" "order" "empty" ("greatest" | "least") Core Grammar The core grammar production for empty order declarations is: 7 (Core) EmptyOrderDecl ::= "declare" "default" "order" "empty" ("greatest" | "least") Normalization Empty order declarations are left unchanged through normalization. [ EmptyOrderDecl ] PrologDecl == EmptyOrderDecl Static Context Processing The empty order declaration does not have any effect on the static context. statEnv |- EmptyOrderDecl => stat statEnv Dynamic Context Processing The empty order declaration does not have any effect on the dynamic context. dynEnv |- EmptyOrderDecl => dyn dynEnv 16 (XQuery) CopyNamespacesDecl XQ ::= "declare" "copy-namespaces" PreserveMode InheritMode 17 (XQuery) PreserveMode XQ ::= "preserve" | "no-preserve" 18 (XQuery) InheritMode XQ ::= "inherit" | "no-inherit" Core Grammar The core grammar productions for copy-namespaces declarations are: 8 (Core) CopyNamespacesDecl ::= "declare" "copy-namespaces" PreserveMode InheritMode 9 (Core) PreserveMode ::= "preserve" | "no-preserve" 10 (Core) InheritMode ::= "inherit" | "no-inherit" Normalization Copy-namespace declarations are left unchanged through normalization. [ CopyNamespacesDecl ] PrologDecl == CopyNamespacesDecl Static Context Processing The copy-namespace declaration does not have any effect on the static context. statEnv |- CopyNamespacesDecl => stat statEnv Dynamic Context Processing The copy-namespace declaration does not have any effect on the dynamic context. dynEnv |- CopyNamespacesDecl => dyn dynEnv 21 (XQuery) SchemaImport XQ ::= "import" "schema" SchemaPrefix URILiteral URILiteral URILiteral 22 (XQuery) SchemaPrefix XQ ::= ("namespace" NCName The semantics of Schema Import is described in terms of the [XPath/XQuery] type system. The process of converting an XML Schema into a sequence of type declarations is described in Section [D Importing Schemas] Core Grammar The Core grammar productions for schema imports are: 13 (Core) SchemaImport ::= "import" "schema" SchemaPrefix URILiteral URILiteral URILiteral 14 (Core) SchemaPrefix ::= ("namespace" NCName Normalization Schema imports are left unchanged through normalization. [ SchemaImport ] PrologDecl == SchemaImport Notation For convenience, we introduce the following auxiliary grammar productions. 16 (Formal) LocationHints ::= "at" URILiteral URILiteral 82 (Formal) OptLocationHints ::= LocationHints Notation The following auxiliary judgments are used when processing schema imports. The judgment: statEnv 1 |- Definitions => type statEnv 2 holds if under the static environment statEnv 1 Definitions statEnv 2 The judgment: statEnv 1 |- Definition => type statEnv 2 holds if under the static environment statEnv 1 Definition statEnv 2 Static Context Processing A schema imported into a query is first mapped into the [XPath/XQuery] type system, which yields a sequence of XQuery type definitions. The rules for mapping the imported schema begin in [D.2 Schemas as a whole] Definitions [ URILiteral OptLocationHints ] Schema statEnv |- Definitions => type statEnv 1 statEnv |- URILiteral OptLocationHints => stat statEnv 1 The schema import declaration may also assign an element/type namespace prefix to the URI of the imported schema, or assign the default element namespace to the URI of the imported schema. Definitions [ URILiteral OptLocationHints ] Schema statEnv |- Definitions => type statEnv 1 dynEnv |- URILiteral has atomic value AnyURI statEnv 2 statEnv 1 namespace NCName AnyURI statEnv |- NCName URILiteral OptLocationHints => stat statEnv 2 Definitions [ URILiteral OptLocationHints ] Schema statEnv |- Definitions => type statEnv 1 dynEnv |- URILiteral has atomic value AnyURI statEnv 2 statEnv 1 default_elem_namespace AnyURI statEnv |- URILiteral OptLocationHints => stat statEnv 2 An empty sequence of type definitions yields the input environment. statEnv |- => type statEnv Each type definition is added into the static environment. statEnv |- Definitions => type statEnv 1 statEnv 1 |- Definition 1 => type statEnv 2 statEnv |- Definition 1 Definitions => type statEnv 2 Each type, element, or attribute declaration is added respectively to the type, element and attribute declarations components of the static environment. statEnv |- TypeName of elem/type expands to expanded-QName statEnv 1 statEnv typeDefn expanded-QName TypeName TypeDerivation statEnv |- TypeName TypeDerivation => type statEnv 1 statEnv |- ElementName of elem/type expands to expanded-QName statEnv 1 statEnv elemDecl expanded-QName ElementName OptSubstitution OptNillable TypeReference statEnv |- ElementName OptSubstitution OptNillable TypeReference => type statEnv 1 statEnv |- AttributeName of attr expands to expanded-QName statEnv 1 statEnv attrDecl expanded-QName AttributeName TypeReference statEnv |- AttributeName TypeReference => type statEnv 1 Note that it is a static error to import two schemas that both define the same name in the same symbol space and in the same scope. That is multiple top-level definitions of the same type, element, or attribute name raises a static error. For instance, a query may not import two schemas that include top-level element declarations for two elements with the same expanded name. Dynamic Context Processing The schema import declarations do not affect the dynamic context. dynEnv |- SchemaImport => dyn dynEnv 23 (XQuery) ModuleImport XQ ::= "import" "module" ("namespace" NCName URILiteral URILiteral URILiteral Introduction The effect of an "import module" declaration is to extend the importing module's dynamic (and static) context with the global variables (and their types) and the functions (and their signatures) of the imported module. Module import is not transitive, only the global variables and functions declared explicitly in the imported module are available in the importing module. Also, module import does not import schemas, therefore the importing module must explicitly import any schemas on which the imported global variables or functions depend. Core Grammar The core grammar production for module imports is: 15 (Core) ModuleImport ::= "import" "module" ("namespace" NCName URILiteral URILiteral URILiteral Normalization Module imports are left unchanged through normalization. [ ModuleImport ] PrologDecl == ModuleImport Notation The rules below depend on the following auxiliary functions which are used to import the proper fragment of the static context. The function fs: local-variables statEnv AnyURI expanded-QName Type statEnv varType The function fs: local-functions statEnv AnyURI FunctionKey FunctionSig statEnv funcType Notation The following auxiliary judgments is used to extend a given static environment with the static environment from an imported module. The judgment statEnv 1 extended with static environment statEnv 2 yields statEnv 3 for uri AnyURI 1 holds if extending the environment statEnv 1 statEnv 2 statEnv 3 AnyURI This judgment is defined as follows. fs: local-variables statEnv 2 AnyURI Variable 1 Type 1 Variable m Type m statEnv 3 statEnv 1 varType Variable 1 Type 1 Variable m Type m fs: local-functions statEnv 2 AnyURI FunctionKey 1 FunctionSig 1 FunctionKey n FunctionSig n statEnv 4 statEnv 3 funcType FunctionKey 1 FunctionSig 1 FunctionKey n FunctionSig n statEnv 1 extended with static environment statEnv 2 yields statEnv 4 for uri AnyURI 1 Notation The rules below depend on the following auxiliary judgments. The following rules add each variable explicitly declared in the imported module to the importing module's dynamic variable environment. dynEnv 1 AnyURI |- => import_variables dynEnv 1 dynEnv 2 dynEnv 1 varValue expanded-QName 1 #IMPORTED AnyURI dynEnv 2 AnyURI |- expanded-QName 2 Type 2 expanded-QName n Type n => import_variables dynEnv 3 dynEnv 1 AnyURI |- expanded-QName 1 Type 1 expanded-QName n Type n => import_variables dynEnv 3 The following rules add each function explicitly declared in the imported module to the importing module's dynamic function environment. dynEnv 1 AnyURI |- => import_functions dynEnv 1 dynEnv 2 dynEnv 1 funcDefn FunctionKey 1 #IMPORTED AnyURI dynEnv 2 AnyURI |- FunctionKey 2 FunctionSig 2 FunctionKey n FunctionSig n => import_functions dynEnv 3 dynEnv 1 AnyURI |- FunctionKey 1 FunctionSig 1 FunctionKey n FunctionSig n => import_functions dynEnv 3 Notation The following auxiliary judgments is used to extend a given dynamic environment with the dynamic environment from an imported module. The judgment dynEnv 1 extended with dynamic environment dynEnv 2 yields dynEnv 3 for uri AnyURI holds if extending the dynamic environment dynEnv 1 dynEnv 2 dynEnv 3 AnyURI This judgment is defined as follows. dynEnv 1 AnyURI |- fs: local-variables statEnv 2 AnyURI => import_variables dynEnv 3 dynEnv 1 AnyURI |- fs: local-variables statEnv 2 AnyURI => import_variables dynEnv 3 dynEnv 3 AnyURI |- fs: local-functions statEnv 2 AnyURI => import_functions dynEnv 4 dynEnv 1 extended with dynamic environment dynEnv 2 yields dynEnv 4 for uri AnyURI Static Context Processing The first set of premises below "look up" the static contexts of all the imported modules, as defined in [5.2 Module Declaration] not AnyURI 1 AnyURI AnyURI 1 => module_statEnv statEnv 1 statEnv extended with static environment statEnv 1 yields statEnv 2 for uri AnyURI 1 AnyURI statEnv |- AnyURI 1 LocationHints => stat statEnv 2 AnyURI 1 AnyURI AnyURI statEnv |- AnyURI 1 LocationHints => stat statEnv 1 not AnyURI 1 AnyURI dynEnv |- URILiteral 1 has atomic value AnyURI 1 AnyURI 1 => module_statEnv statEnv 1 statEnv extended with static environment statEnv 1 yields statEnv 2 for uri AnyURI 1 statEnv 3 statEnv 2 namespace NCName AnyURI statEnv |- NCName URILiteral 1 LocationHints => stat statEnv 3 AnyURI 1 AnyURI dynEnv |- URILiteral 1 has atomic value AnyURI 1 statEnv 2 statEnv 1 namespace NCName AnyURI statEnv |- NCName URILiteral 1 LocationHints => stat statEnv 2 Note that the rules above and the rules for processing a library module in [5.2 Module Declaration] Dynamic Context Processing During dynamic context processing, each variable and function name is mapped to the special value #IMPORTED AnyURI The first set of premises below "look up" the dynamic contexts of all the imported modules, as defined in [5.2 Module Declaration] dynEnv |- URILiteral has atomic value AnyURI AnyURI => module_dynEnv dynEnv 1 ... AnyURI => module_dynEnv dynEnv n dynEnv extended with dynamic environment dynEnv 1 yields dynEnv 1 for uri AnyURI ... dynEnv n-1 extended with dynamic environment dynEnv n yields dynEnv n for uri AnyURI dynEnv 1 |- NCName URILiteral LocationHints => dyn dynEnv n Note that the rule above and the rules for processing a library module in [5.2 Module Declaration] 10 (XQuery) NamespaceDecl XQ ::= "declare" "namespace" NCName URILiteral Core Grammar The core grammar production for namespace declarations is: 3 (Core) NamespaceDecl ::= "declare" "namespace" NCName URILiteral Normalization Namespace declarations are left unchanged through normalization. [ NamespaceDecl ] PrologDecl == NamespaceDecl Static Context Processing A namespace declaration adds a new (prefix,uri) binding in the namespace component of the static environment. All namespace declarations in the prolog are passive active dynEnv |- URILiteral has atomic value AnyURI statEnv 1 statEnv namespace NCName AnyURI statEnv |- NCName URILiteral => stat statEnv 1 In case the URILiteral statEnv 1 statEnv namespace NCName statEnv |- NCName => stat statEnv 1 Dynamic Context Processing The namespace declaration does not affect the dynamic context. dynEnv |- NCName URILiteral => dyn dynEnv 12 (XQuery) DefaultNamespaceDecl XQ ::= "declare" "default" ("element" | "function") "namespace" URILiteral Core Grammar The core grammar production for default namespace declarations is: 4 (Core) DefaultNamespaceDecl ::= "declare" "default" ("element" | "function") "namespace" URILiteral Normalization Default namespace declarations are left unchanged through normalization. [ DefaultNamespaceDecl ] PrologDecl == DefaultNamespaceDecl Static Context Processing A default element namespace declaration changes the default element namespace component of the static environment. If the URI literal is the zero-length string, the default element namespace is set to the null namespace. statEnv 1 statEnv default_elem_namespace statEnv |- => stat statEnv 1 not URILiteral dynEnv |- URILiteral has atomic value AnyURI statEnv 1 statEnv default_elem_namespace AnyURI statEnv |- URILiteral => stat statEnv 1 A default function namespace declaration changes the default function namespace component of the static environment. If the URI literal is the zero-length string, the default function namespace is set to the null namespace. statEnv 1 statEnv default_function_namespace statEnv |- => stat statEnv 1 not URILiteral dynEnv |- URILiteral has atomic value AnyURI statEnv 1 statEnv default_function_namespace AnyURI statEnv |- URILiteral => stat statEnv 1 Note that multiple declarations of the same namespace prefix in the Prolog result in a static error. However, a declaration of a namespace in the Prolog can override a prefix that has been predeclared in the static context. Dynamic Context Processing Default namespace declarations do not affect the dynamic context. dynEnv |- DefaultNamespaceDecl => dyn dynEnv 24 (XQuery) VarDecl XQ ::= "declare" "variable" "$" QName TypeDeclaration ExprSingle Core Grammar The core grammar production for variable declarations is: 16 (Core) VarDecl ::= "declare" "variable" "$" QName TypeDeclaration ExprSingle Normalization Normalization of a variable declaration normalizes its initializing expression, if it is present. [ VarName SequenceType Expr ] PrologDecl == declare variable $ VarName SequenceType [ Expr ] Expr [ VarName Expr ] PrologDecl == declare variable $ VarName [ Expr ] Expr If an external variable declaration does not have a type declaration it is treated as if the type declaration was item()* [ VarName ] PrologDecl == declare variable $ VarName [ VarName SequenceType ] PrologDecl == declare variable $ VarName SequenceType Static Context Processing A variable declaration updates the variable component of the static context by associating the given variable with a static type. If a variable declaration has an associated expression but does not have a type declaration, the static type of the variable is the static type of the expression. statEnv |- VarName of var expands to Variable statEnv |- Expr : Type statEnv 1 statEnv varType Variable Type statEnv |- VarName Expr => stat statEnv 1 If the variable declaration has an associated expression and has a type declaration, the static type of the variable is the specified type. The type of the expression must be a subtype of the declared type. statEnv |- VarName of var expands to Variable Type [ SequenceType ] sequencetype statEnv |- Expr : Type 2 statEnv |- Type 2 <: Type statEnv 1 statEnv varType Variable Type statEnv |- VarName SequenceType Expr => stat statEnv 1 If the variable declaration is external and has a type declaration, the static type of the variable is the specified type. statEnv |- VarName of var expands to Variable Type [ SequenceType ] sequencetype statEnv 1 statEnv varType Variable Type statEnv |- VarName SequenceType => stat statEnv 1 Dynamic Context Processing To evaluate a variable declaration, its associated expression is evaluated, and the dynamic context is updated with the variable bound to the resulting value. dynEnv |- Expr => Value statEnv |- VarName of var expands to Variable dynEnv 1 dynEnv varValue Variable Value dynEnv |- VarName Expr => dyn dynEnv 1 dynEnv |- Expr => Value Type [ SequenceType ] sequencetype statEnv |- Value matches Type statEnv |- VarName of var expands to Variable dynEnv 1 dynEnv varValue Variable Value dynEnv |- VarName SequenceType Expr => dyn dynEnv 1 Dynamic evaluation does not apply to externally defined variables. The dynamic environment must provide the values of external variables in the initial dynamic context ( dynEnvDefault dynEnv |- VarName SequenceType => dyn dynEnv Introduction User-defined functions specify the name of the function, the names and types of the parameters, and the type of the result. The function body 26 (XQuery) FunctionDecl XQ ::= "declare" "function" QName ParamList SequenceType EnclosedExpr 27 (XQuery) ParamList XQ ::= Param Param 28 (XQuery) Param XQ ::= "$" QName TypeDeclaration Core Grammar The core grammar productions for function declarations are: 18 (Core) FunctionDecl ::= "declare" "function" QName ParamList SequenceType EnclosedExpr 19 (Core) ParamList ::= Param Param 20 (Core) Param ::= "$" QName TypeDeclaration Notation The following auxiliary mapping rule is used for the normalization of parameters in function declarations: [ ] Param Parameters without a declared type are given the item()* sequence type. [ VarName ] Param == $ VarName [ VarName SequenceType ] Param == $ VarName SequenceType An empty parameter list is left unchanged. [ ] Param == A parameter list is normalized by applying the normalization rule to each parameter. [ Param 1 Param n ] Param == [ Param 1 ] Param [ Param n ] Param Normalization The parameter list and body of a user-defined function are all normalized into Core expressions. statEnv |- QName of func expands to expanded-QName Type [ SequenceType ] sequencetype statEnv |- [ QName ParamList SequenceType Expr ] PrologDecl QName [ ParamList ] Param SequenceType [ Expr ] FunctionArgument( Type If the return type of the function is not provided, it is given the item()* [ QName ParamList Expr ] PrologDecl == [ QName ParamList Expr ] PrologDecl Externally defined functions are normalized similarly. [ QName ParamList SequenceType ] PrologDecl == declare function QName [ ParamList ] Param SequenceType [ QName ParamList ] PrologDecl == [ QName ParamList ] PrologDecl Notation We use the following auxiliary judgment during static context processing and static type analysis of function declarations. The judgment: statEnv |- function declaration FunctionDecl with signature FunctionSig : Type holds if the function declaration FunctionDecl FunctionSig Type Static Context Processing Static context processing accesses the function signature from the static context, and checks that the function declaration corresponds to the declared type. statEnv funcType expanded-QName FunctionSig statEnv |- function declaration FunctionDecl with signature FunctionSig : Type r statEnv |- FunctionDecl => stat statEnv 1 Note that the static context processing is performing type checking of the function, as defined below. Note also that the type checking is done in the new environment in which the function declaration has been added which ensures that recursive calls are type-checked properly. Static Type Analysis The static typing rules for function bodies follow normalization and processing of the static context. The static typing rules below construct a new environment in which each parameter has the given expected type, then the static type of the function's body is computed under the new environment. The function body's type must be a subtype of the expected return type. If static typing fails, a static type error is raised. Otherwise, static typing of the function has no other effect, as function signatures are already inside the static environment. statEnv varType |- Expr : Type statEnv |- Type <: Type r statEnv |- function declaration QName SequenceType r Expr with signature expanded-QName Type r : Type r statEnv |- VarName 1 of var expands to Variable 1 ... statEnv |- VarName n of var expands to Variable n statEnv varType Variable 1 Type 1 Variable n Type n |- Expr : Type statEnv |- Type can be promoted to Type r statEnv |- function declaration QName VarName 1 SequenceType 1 VarName n SequenceType n SequenceType r Expr with signature expanded-QName Type 1 Type n Type r : Type r The bodies of external functions are not available and therefore cannot by type checked. To ensure type soundness, the implementation must guarantee that the value returned by the external function matches the expected return type. statEnv |- function declaration QName SequenceType r with signature expanded-QName Type r : Type r statEnv |- VarName 1 of var expands to Variable 1 ... statEnv |- VarName n of var expands to Variable n statEnv |- function declaration QName VarName 1 SequenceType 1 VarName n SequenceType n SequenceType r with signature expanded-QName Type 1 Type n Type r : Type r Dynamic Context Processing A function declaration updates the dynamic context. The function name with arity N is associated with the given function body. The number of arguments is required, because XQuery permits overloading of function names as long as each function signature has a different number of arguments. statEnv |- QName of func expands to expanded-QName dynEnv 1 dynEnv funcDefn expanded-QName Expr dynEnv |- QName SequenceType r Expr => dyn dynEnv 1 statEnv |- QName of func expands to expanded-QName statEnv |- VarName 1 of var expands to Variable 1 ··· statEnv |- VarName n of var expands to Variable n dynEnv 1 dynEnv funcDefn expanded-QName Expr Variable 1 Variable n dynEnv |- QName VarName 1 SequenceType 1 VarName n SequenceType n SequenceType r Expr => dyn dynEnv 1 An external function declaration does not affect the dynamic environment. The implementation must support the declared external functions. dynEnv |- QName VarName 1 SequenceType 1 VarName n SequenceType n SequenceType r => dyn dynEnv The dynamic semantics of a function body are applied when the function is called, as described in [4.1.5 Function Calls] 13 (XQuery) OptionDecl XQ ::= "declare" "option" QName StringLiteral Core Grammar The core grammar production for option declarations is: 5 (Core) OptionDecl ::= "declare" "option" QName StringLiteral Normalization Option declarations are left unchanged through normalization. [ OptionDecl ] PrologDecl == OptionDecl Static Context Processing An option declaration does not have any effect on the static context. statEnv |- OptionDecl => stat statEnv Dynamic Context Processing An option declaration does not have any effect on the dynamic context. dynEnv |- OptionDecl => dyn dynEnv The XQuery Formal Semantics is intended primarily as a component that can be used by [XQuery 1.0: An XML Query Language (Second Edition)] [XML Path Language (XPath) 2.0 (Second Edition)] This specification normatively defines the static typing feature which can be used in [XQuery 1.0: An XML Query Language (Second Edition)] [XML Path Language (XPath) 2.0 (Second Edition)] [3.2.3 Static typing judgment] In some cases, the static typing rules are not very precise (see, for example, the type inference rules for the ancestor axes—parent, ancestor, and ancestor-or-self—and for the function fn:root This constraint is formally expressed as follows. A static typing extension Expr : ext Type Expr statEnv |- Expr : Type statEnv |- Type <: Type statEnv |- Expr : ext Type Note: It is not recommended for a static typing extension to change the static typing behavior of expressions that specify a type explicitly ( treat as cast as typeswitch This section defines the auxiliary functions required to define the formal semantics of [XPath/XQuery], and gives special normalization and static typing rules for some functions in [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] Remember from [4.1.5 Function Calls] FN-URI [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] OP-URI [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] FS-URI Introduction This section gives the definition and semantics of functions that are used in the formal semantics but are not in [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] The fs: convert-operand fs:convert-operand $actual as xs:anyAtomicType? $expected as xs:anyAtomicType as xs:anyAtomicType ? The formal-semantics function fs: convert-operand If $actual If $actual xs:untypedAtomic if $expected xs:untypedAtomic xs:string $actual xs:string if $expected $actual xs:double otherwise returns $actual $expected Otherwise, returns $actual Static Type Analysis To analyze a call to fs: convert-operand convert_operand statEnv |- Type A <: xs:anyAtomicType statEnv |- Type E <: xs:anyAtomicType prime Type A AtomicTypeName A1 AtomicTypeName Am prime Type E AtomicTypeName E1 AtomicTypeName En statEnv |- convert_operand AtomicTypeName A1 against AtomicTypeName E1 is AtomicTypeName 1,1 ... statEnv |- convert_operand AtomicTypeName A1 against AtomicTypeName En is AtomicTypeName 1,n ... statEnv |- convert_operand AtomicTypeName Am against AtomicTypeName E1 is AtomicTypeName m,1 ... statEnv |- convert_operand AtomicTypeName Am against AtomicTypeName En is AtomicTypeName m,n AtomicTypeName 1,1 AtomicTypeName m,n Type R statEnv |- ( FS-URI convert-operand Type A Type E : Type R quantifier Type A The auxiliary judgment: statEnv |- convert_operand AtomicTypeName A against AtomicTypeName E is AtomicTypeName R is the static analog of the fs: convert-operand No conversion is needed if the first argument isn't an instance of type xs:untypedAtomic statEnv |- not AtomicTypeName A <: xs:untypedAtomic statEnv |- convert_operand AtomicTypeName A against AtomicTypeName E is AtomicTypeName A The remaining rules cover the cases when the first argument is xs:untypedAtomic If the second argument is of type xs:untypedAtomic xs:string statEnv |- AtomicTypeName A <: xs:untypedAtomic statEnv |- AtomicTypeName E <: xs:untypedAtomic xs:string statEnv |- convert_operand AtomicTypeName A against AtomicTypeName E is xs:string If the second argument is numeric, the first is converted to xs:double statEnv |- AtomicTypeName A <: xs:untypedAtomic statEnv |- AtomicTypeName E <: fs: numeric statEnv |- convert_operand AtomicTypeName A against AtomicTypeName E is xs:double Otherwise, the first argument is converted to the type of the second argument. statEnv |- AtomicTypeName A <: xs:untypedAtomic statEnv |- not AtomicTypeName E <: xs:untypedAtomic xs:string fs: numeric statEnv |- convert_operand AtomicTypeName A against AtomicTypeName E is AtomicTypeName E The fs: convert-simple-operand fs:convert-simple-operand $actual as xs:anyAtomicType * $expected as xs:anyAtomicType as xs:anyAtomicType * The formal-semantics function fs: convert-simple-operand $actual $expected The dynamic semantics of this function are as follows: For each item in $actual $expected Static Type Analysis The following static typing rules correspond to the dynamic semantics rules given above. statEnv |- Type 2 <: xs:anyAtomicType Type 3 convert_untypedAtomic prime Type 1 Type 2 statEnv |- ( FS-URI convert-simple-operand Type 1 Type 2 : Type 3 · quantifier Type 1 The fs: distinct-doc-order fs:distinct-doc-order $nodes as node * as node * The fs: distinct-doc-order Static Type Analysis The fs: distinct-doc-order prime quantifier [8.4 Judgments for FLWOR and other expressions on sequences] statEnv |- Type <: statEnv |- ( FS-URI distinct-doc-order Type : prime Type · quantifier Type The fs: distinct-doc-order-or-atomic-sequence fs:distinct-doc-order-or-atomic-sequence $item as item()* as item()* The fs: distinct-doc-order-or-atomic-sequence Static Type Analysis The fs: distinct-doc-order prime quantifier [8.4 Judgments for FLWOR and other expressions on sequences] statEnv |- Type <: [ ] sequencetype statEnv |- ( FS-URI distinct-doc-order-or-atomic-sequence Type : prime Type · quantifier Type statEnv |- Type <: xs:anyAtomicType statEnv |- ( FS-URI distinct-doc-order-or-atomic-sequence Type : Type The fs: item-sequence-to-node-sequence fs:item-sequence-to-node-sequence $items as item()* as node()* The fs: item-sequence-to-node-sequence 1e 2 Section 3.7.1.3 Content XQ $items If the input sequence contains any attribute nodes, they must precede any other items. Static Type Analysis statEnv |- Type <: statEnv |- ( FS-URI item-sequence-to-node-sequence Type : statEnv |- Type <: xs:anyAtomicType statEnv |- ( FS-URI item-sequence-to-node-sequence Type : statEnv |- Type <: xs:anyAtomicType statEnv |- ( FS-URI item-sequence-to-node-sequence Type : The fs: item-sequence-to-string Introduction fs:item-sequence-to-string $items as item()* as xs:string The fs: item-sequence-to-string Section 3.7.3.2 Computed Attribute Constructors XQ Dynamic Evaluation If the input of the fs: item-sequence-to-string Static Type Analysis There are no special static typing rules for this function. Static type analysis for this function should be performed as for a built-in function declared with the given signature. The fs: item-sequence-to-untypedAtomic-PI Introduction fs:item-sequence-to-untypedAtomic-PI $items as item()* as xs:untypedAtomic The fs: item-sequence-to-untypedAtomic-PI xs:untypedAtomic Section 3.7.3.5 Computed Processing Instruction Constructors XQ Dynamic Evaluation If the input is an empty sequence, the fs: item-sequence-to-untypedAtomic-PI Static Type Analysis There are no special static typing rules for this function. Static type analysis for this function should be performed as for a built-in function declared with the given signature. The fs: item-sequence-to-untypedAtomic-text Introduction fs:item-sequence-to-untypedAtomic-text $items as item()* as xs:untypedAtomic? The fs: item-sequence-to-untypedAtomic-text xs:untypedAtomic Section 3.7.3.4 Text Node Constructors XQ Dynamic Evaluation If the input is the empty sequence, the fs: item-sequence-to-untypedAtomic-text Static Type Analysis There are no special static typing rules for this function. Static type analysis for this function should be performed as for a built-in function declared with the given signature. The fs: item-sequence-to-untypedAtomic-comment Introduction fs:item-sequence-to-untypedAtomic-comment $items as item()* as xs:untypedAtomic The fs: item-sequence-to-untypedAtomic-comment xs:untypedAtomic Section 3.7.3.6 Computed Comment Constructors XQ Dynamic Evaluation If the input is the empty sequence, the fs: item-sequence-to-untypedAtomic-comment Static Type Analysis There are no special static typing rules for this function. Static type analysis for this function should be performed as for a built-in function declared with the given signature. The fs: apply-ordering-mode fs:apply-ordering-mode $items as item()* as item()* Dynamic Evaluation If the statEnv orderingMode fs: apply-ordering-mode statEnv orderingMode ordered dynEnv |- Expr => Value dynEnv |- fs: apply-ordering-mode Expr => Value If the statEnv orderingMode fs: apply-ordering-mode fn:unordered statEnv orderingMode unordered dynEnv |- fn:unordered Expr => Value dynEnv |- fs: apply-ordering-mode Expr => Value Static Type Analysis If the ordering context is set to ordered fs: apply-ordering-mode statEnv orderingMode ordered statEnv |- ( FS-URI apply-ordering-mode Type : Type If the ordering context is set to unordered fs: apply-ordering-mode prime quantifier fn:unordered statEnv orderingMode unordered statEnv |- ( FS-URI apply-ordering-mode Type : prime Type · quantifier Type fs: to fs:to $firstval as xs:integer? $lastval as xs:integer? as xs:integer* The formal semantics function fs: to op:to Dynamic Evaluation If one of the input parameters for fs: to op:to declare function fs:to($firstval as xs:integer?, $lastval as xs:integer?) as xs:integer* { if (fn:empty($firstval) or fn:empty($lastval) then () else op:to($firstval,$lastval) }; Static Type Analysis The static type of fs: to The fs: node-sequence fs:node-sequence $nodes as node()* as node()* If the input is a (possibly empty) sequence of nodes, fs: node-sequence Static Type Analysis The static type of a call to fs: node-sequence node()* statEnv |- Type <: [ ] sequencetype statEnv |- ( FS-URI node-sequence Type : Type The fs: item-at fs:item-at $sourceSeq as item()* $loc as xs:double as item()? The fs: item-at Dynamic Evaluation If $loc $sourceSeq $sourceSeq $loc n n $sourceSeq Otherwise, the empty sequence is returned. The function is roughly equivalent to the following user-defined function. declare function fs:item-at( $sourceSeq as item()*, $loc as xs:double) as item()? { if ($loc mod 1 eq 0) then fn:subsequence($sourceSeq,$loc,1) else () }; Static Type Analysis The static typing rules for invocations of fs: item-at statEnv |- QName of func expands to ( FS-URI item-at statEnv |- Expr 1 : Type 1 quantifier Type 1 in statEnv |- QName Expr 1 : prime Type 1 Otherwise, the following less precise rule is used. statEnv |- QName of func expands to ( FS-URI item-at statEnv |- Expr 1 : Type 1 statEnv |- QName Expr 1 Expr 2 : prime Type 1 (Since invocations of fs: item-at Expr2 $fs:last $fs:position Introduction This section gives special normalization and static typing rules for functions in [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] [4.1.5 Function Calls] fn:last As explained in [3.1.2 Dynamic Context] fn:last() $ fs: last Static Type Analysis statEnv varType FS-URI last Type statEnv |- FN-URI last : Type Dynamic Evaluation dynEnv varValue FS-URI last Value dynEnv |- function FN-URI last with types on values yields Value fn:position As explained in [3.1.2 Dynamic Context] fn:position() $ fs: position Static Type Analysis statEnv varType FS-URI position Type statEnv |- FN-URI position : Type Dynamic Evaluation dynEnv varValue FS-URI position Value dynEnv |- function FN-URI position with types on values yields Value The fn:abs fn:ceiling fn:floor fn:round fn:round-half-to-even Notation The auxiliary judgment has base atomic type [7.2.10 The fn:min, fn:max, fn:avg, and fn:sum functions] statEnv |- AtomicTypeName 1 has base atomic type AtomicTypeName 2 To a first approximation, this judgment holds when AtomicTypeName 1 AtomicTypeName 2 xs:integer xs:decimal xs:yearMonthDuration xs:dayTimeDuration xs:duration If AtomicTypeName 1 xs:decimal xs:duration statEnv |- AtomicTypeName 1 <: AtomicTypeName 2 AtomicTypeName 2 not AtomicTypeName 2 in xs:decimal xs:duration statEnv |- AtomicTypeName 1 has base atomic type AtomicTypeName 2 Similarly for xs:integer xs:yearMonthDuration xs:dayTimeDuration statEnv |- AtomicTypeName 1 <: AtomicTypeName 2 AtomicTypeName 2 in xs:integer xs:yearMonthDuration xs:dayTimeDuration statEnv |- AtomicTypeName 1 has base atomic type AtomicTypeName 2 For xs:decimal xs:integer statEnv |- AtomicTypeName 1 <: xs:decimal statEnv |- not AtomicTypeName 1 <: xs:integer statEnv |- AtomicTypeName 1 has base atomic type xs:decimal And finally, for xs:duration xs:yearMonthDuration xs:dayTimeDuration statEnv |- AtomicTypeName 1 <: xs:duration statEnv |- not AtomicTypeName 1 <: xs:yearMonthDuration statEnv |- not AtomicTypeName 1 <: xs:dayTimeDuration statEnv |- AtomicTypeName 1 has base atomic type xs:duration Static Type Analysis Note that, in the declarations for the built-in functions fn:abs fn:ceiling fn:floor fn:round fn:round-half-to-even numeric? [4.1.5 Function Calls] fn:data fs: convert-simple-operand xs:double xs:anyAtomicType xs:untypedAtomic In the static typing rule for these functions, we check that the argument type is numeric, extract its prime type (which must be a choice of atomic types), find the base atomic type for each, and then form the choice of those results. expanded-QName in FN-URI abs FN-URI ceiling FN-URI floor FN-URI round FN-URI round-half-to-even statEnv |- Type 1 <: fs: numeric prime Type 1 AtomicTypeName 1 AtomicTypeName n statEnv |- AtomicTypeName 1 has base atomic type AtomicTypeName 1 ... statEnv |- AtomicTypeName n has base atomic type AtomicTypeName n Type 3 AtomicTypeName 1 AtomicTypeName n statEnv |- expanded-QName Type 1 : Type 3 quantifier Type 1 The fn:round-half-to-even statEnv |- Type 2 <: xs:integer statEnv |- expanded-QName Type 1 : Type 3 statEnv |- FN-URI round-half-to-even Type 1 Type 2 : Type 3 The fn:boolean fn:not Static Type Analysis The fn:boolean [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] xs:boolean xs:string xs:anyURI xs:untypedAtomic fn:boolean The fn:not fn:boolean fn:boolean expanded-QName in FN-URI boolean FN-URI not statEnv |- Type <: [ ] sequencetype xs:boolean xs:string xs:untypedAtomic fs: numeric xs:anyURI statEnv |- expanded-QName Type : xs:boolean The fn:collection fn:doc Introduction The static typing rules for fn:collection fn:doc Static Type Analysis The fn:collection [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] If the fn:collection statEnv |- QName of func expands to FN-URI collection statEnv |- Type statEnv |- QName : Type If the argument to fn:collection URILiteral statEnv collectionType URILiteral statEnv collectionType statEnv |- QName of func expands to FN-URI collection statEnv collectionType URILiteral Type statEnv |- QName URILiteral : Type Otherwise, if the argument is a URI literal but is not defined in statEnv collectionType statEnv |- QName of func expands to FN-URI collection statEnv collectionType URILiteral statEnv |- QName URILiteral : statEnv |- QName of func expands to FN-URI collection Expr URILiteral statEnv |- QName Expr : The fn:doc statEnv |- QName of func expands to FN-URI doc statEnv docType URILiteral Type statEnv |- Type <: statEnv |- QName URILiteral : Type Otherwise, if the argument is a URI literal not defined in the domain of statEnv docType statEnv |- QName of func expands to FN-URI doc statEnv docType URILiteral statEnv |- QName URILiteral : statEnv |- QName of func expands to FN-URI doc Expr URILiteral statEnv |- QName Expr : fn:data Introduction The fn:data Notation Inferring the type for the fn:data data on statEnv |- data on Type 1 : Type 2 Static Type Analysis The general rule for fn:data data on statEnv |- data on prime Type : Type 1 statEnv |- FN-URI data Type : Type 1 · quantifier Type When applied to none, data on statEnv |- data on none : none When applied to empty, data on statEnv |- data on empty : empty When applied to the union of two types, data on prime quantifier [8.4 Judgments for FLWOR and other expressions on sequences] data on statEnv |- data on Type 1 : Type 1 statEnv |- data on Type 2 : Type 2 statEnv |- data on Type 1 Type 2 : prime Type 1 Type 2 · quantifier Type 1 Type 2 When applied to an atomic type, data on statEnv |- Type <: xs:anyAtomicType statEnv |- data on Type : Type When applied to comment or processing instruction node types, data on xs:string statEnv |- Type <: statEnv |- data on Type : xs:string When applied to text or document node types, data on xs:untypedAtomic statEnv |- Type <: statEnv |- data on Type : xs:untypedAtomic When applied to element node types with type annotation XQ xs:untyped data on xs:untypedAtomic statEnv |- ElementType type lookup xs:untyped statEnv |- data on ElementType : xs:untypedAtomic When applied to an attribute node type, the data on statEnv |- AttributeType type lookup TypeName statEnv |- TypeName expands to Type statEnv |- data on AttributeType : Type When applied to an element type whose type annotation XQ data on statEnv |- ElementType type lookup TypeReference statEnv |- TypeReference expands to Type statEnv |- Type <: Type 1 statEnv |- Type 1 <: xs:anyAtomicType statEnv |- data on ElementType : Type 1 For any element node whose type annotation XQ fn:data data on type annotation XQ data on Because we can derive complex types with element-only mixed xs:anyType data on type annotation XQ xs:untyped data on Example Consider the following variable and its corresponding static type. $x : (element price { attribute currency { xs:string }, xs:decimal } | element price_code { xs:integer }) Applying the fn:data fn:data($x) : (xs:decimal | xs:integer) Because the input type is a choice, applying the data on fn:data The fn:distinct-values Static Type Analysis The fn:distinct-values [8.4 Judgments for FLWOR and other expressions on sequences] statEnv |- Type <: xs:anyAtomicType statEnv |- FN-URI distinct-values Type : prime Type · quantifier Type The fn:unordered Static Type Analysis The static semantics for fn:unordered prime quantifier [8.4 Judgments for FLWOR and other expressions on sequences] prime quantifier statEnv |- FN-URI unordered Type 1 : prime Type 1 · quantifier Type 1 The fn:error Static Type Analysis The fn:error function always has the none statEnv |- FN-URI error : none statEnv |- Type <: xs:QName statEnv |- FN-URI error Type : none statEnv |- Type 1 <: xs:QName statEnv |- Type 2 <: xs:string statEnv |- FN-URI error Type 1 Type 2 : none statEnv |- Type 1 <: xs:QName statEnv |- Type 2 <: xs:string statEnv |- FN-URI error Type 1 Type 2 Type 3 : none The fn:min fn:max fn:avg fn:sum Introduction The semantics of aggregate functions convert any item of type xs:untypedAtomic xs:double The fn:sum xs:integer Static Type Analysis statEnv |- FN-URI sum Type 1 xs:integer : Type 2 statEnv |- FN-URI sum Type 1 : Type 2 Notation The type function convert_untypedAtomic xs:untypedAtomic convert_untypedAtomic xs:untypedAtomic Type = Type if not( FormalItemType xs:untypedAtomic convert_untypedAtomic FormalItemType Type = FormalItemType convert_untypedAtomic empty Type = empty convert_untypedAtomic none Type = none convert_untypedAtomic Type 1 Type 2 Type = convert_untypedAtomic Type 1 Type convert_untypedAtomic Type 2 Type Notation The function aggregate_quantifier aggregate_quantifier ? = ? aggregate_quantifier * = ? aggregate_quantifier 1 = 1 aggregate_quantifier + = 1 Static Type Analysis Now we can define the static typing rules for the aggregate functions. Note that the normalization rules of [4.1.5 Function Calls] fn:data fs: convert-simple-operand xs:double xs:anyAtomicType xs:untypedAtomic First, we can quickly deal with fn:avg fn:avg($arg) fs:div( fn:sum($arg,()), fn:count($arg) ) statEnv |- FN-URI sum Type 1 : Type 2 statEnv |- FS-URI div Type 2 xs:integer : Type 3 statEnv |- FN-URI avg Type 1 : Type 3 For the remaining aggregate functions ( fn:min fn:max fn:sum fn:min fn:max fn:sum For fn:min fn:max expanded-QName in FN-URI min FN-URI max Type statEnv |- expanded-QName Type : expanded-QName in FN-URI min FN-URI max statEnv |- Type 1 <: Type 3 Type 3 in fs: numeric xs:anyURI xs:string xs:yearMonthDuration xs:dayTimeDuration xs:date xs:time xs:dateTime xs:boolean prime Type 1 AtomicTypeName 1 AtomicTypeName n statEnv |- AtomicTypeName 1 has base atomic type AtomicTypeName 1 ... statEnv |- AtomicTypeName n has base atomic type AtomicTypeName n AtomicTypeName 1 AtomicTypeName n Type 4 statEnv |- expanded-QName Type 1 : Type 4 aggregate_quantifier quantifier Type 1 For fn:sum Type 1 statEnv |- Type 2 <: xs:anyAtomicType statEnv |- FN-URI sum Type 1 Type 2 : Type 2 statEnv |- Type 1 <: Type 3 Type 3 in fs: numeric xs:yearMonthDuration xs:dayTimeDuration statEnv |- Type 2 <: xs:anyAtomicType prime Type 1 AtomicTypeName 1 AtomicTypeName n statEnv |- AtomicTypeName 1 has base atomic type AtomicTypeName 1 ... statEnv |- AtomicTypeName n has base atomic type AtomicTypeName n AtomicTypeName 1 AtomicTypeName n Type 4 statEnv |- second argument contribution for sum with Type 1 and Type 2 is Type 2 statEnv |- FN-URI sum Type 1 Type 2 : Type 4 Type 2 The second argument's contribution (if any) to the above result type is determined as follows. If the first argument could be the empty sequence, we add the type of the second argument to the result type. Otherwise, the type of the second argument is ignored. statEnv |- <: Type 1 statEnv |- second argument contribution for sum with Type 1 and Type 2 is Type 2 statEnv |- not <: Type 1 statEnv |- second argument contribution for sum with Type 1 and Type 2 is The fn:remove Static Type Analysis The static type for the fn:remove prime quantifier [8.4 Judgments for FLWOR and other expressions on sequences] statEnv |- Type 1 <: xs:integer statEnv |- FN-URI remove Type Type 1 : prime Type · quantifier Type · The fn:reverse Static Type Analysis The static type for the fn:reverse prime quantifier [8.4 Judgments for FLWOR and other expressions on sequences] statEnv |- FN-URI reverse Type : prime Type · quantifier Type The fn:subsequence Static Type Analysis The static type of a call to fn:subsequence prime quantifier [8.4 Judgments for FLWOR and other expressions on sequences] statEnv |- Type 2 <: fs: numeric statEnv |- Type 3 <: fs: numeric statEnv |- FN-URI subsequence Type 1 Type 2 Type 3 : prime Type 1 · quantifier Type 1 · The op:union op:intersect op:except Static Type Analysis The static semantics for op:union prime quantifier [8.4 Judgments for FLWOR and other expressions on sequences] prime quantifier Type 1 Type 2 statEnv |- OP-URI union Type 1 Type 2 : prime Type 1 Type 2 · quantifier Type 1 Type 2 The static semantics of op:intersect op:union statEnv |- OP-URI intersect Type 1 Type 2 : prime Type 1 Type 2 · quantifier Type 1 Type 2 · The static semantics of op:except op:intersect op:except statEnv |- OP-URI except Type 1 Type 2 : prime Type 1 · quantifier Type 1 · The fn:insert-before Static Type Analysis The static type for the fn:insert-before prime quantifier [8.4 Judgments for FLWOR and other expressions on sequences] statEnv |- Type 2 <: xs:integer Type 4 Type 1 Type 3 statEnv |- FN-URI insert-before Type 1 Type 2 Type 3 : prime Type 4 · quantifier Type 4 The fn:zero-or-one fn:one-or-more fn:exactly-one The functions fn:zero-or-one fn:one-or-more fn:exactly-one For example, in the following query, the user may know that all ISBN numbers are unique and therefore that the function always returns at most one book element. However, the static typing feature cannot infer a precise enough type and will raise a type error during static type analysis. declare function book_with_isbn($isbn as xs:string) as schema-element(book)? { //book[@isbn=$isbn] } In that query, the fn:zero-or-one declare function book_with_isbn($isbn as xs:string) as schema-element(book)? { fn:zero-or-one(//book[@isbn=$isbn]) } Static Type Analysis The static typing rules for those functions always infer a type with the cardinality indicated by that function. statEnv |- FN-URI zero-or-one Type : prime Type statEnv |- FN-URI one-or-more Type : prime Type statEnv |- FN-URI exactly-one Type : prime Type This section defines auxiliary judgments used in defining the formal semantics. Many auxiliary judgments are used in both static typing and dynamic evaluation rules. Those auxiliary judgments that are used in only the static or dynamic semantics are labeled as such. Introduction This section defines several auxiliary judgments to access components of the [XPath/XQuery] type system. The first two judgments ( derives from substitutes for name lookup type lookup extended by adjusts to expands to [8.3 Judgments for type matching] [F.1 Judgments for the validate expression] [8.2 Judgments for step expressions and filtering] Notation The judgment statEnv |- TypeName 1 derives from TypeName 2 holds when TypeName 1 TypeName 2 derives-from Section 2.5.4 SequenceType Matching XQ Example For example, assuming the extended XML Schema given in section [2.4.5 Example of a complete Schema] USAddress derives from xs:anyType NYCAddress derives from USAddress NYCAddress derives from xs:anyType xsd:positiveInteger derives from xsd:integer xsd:integer derives from xs:anySimpleType fs:anon3 derives from xsd:positiveInteger fs:anon3 derives from xsd:integer fs:anon3 derives from xs:anySimpleType fs:anon3 derives from xs:anyType Note Derivation is a partial order. It is reflexive and transitive by the definition below. Semantics This judgment is specified by the following rules. Every type name derives from itself. statEnv |- TypeName derives from TypeName Every type name derives from the type it is declared to derive from by extension or restriction. statEnv |- TypeName of elem/type expands to expanded-QName statEnv typeDefn expanded-QName TypeName BaseTypeName OptMixed Type statEnv |- TypeName derives from BaseTypeName statEnv |- TypeName of elem/type expands to expanded-QName statEnv typeDefn expanded-QName TypeName BaseTypeName OptMixed Type statEnv |- TypeName derives from BaseTypeName The above rules all require that the type names be defined in the static context, but [XPath/XQuery] permits references to "unknown" type names, i.e., type names that are not defined in the static context. An unknown type name might be encountered, if a module in which the given type name occurs does not import the schema in which the given type name is defined. In this case, an implementation is allowed (but is not required) to provide an implementation-dependent mechanism for determining whether the unknown type name is the same as or derived by restriction from the expected type name. The following rule formalizes this implementation dependent mechanism. "The implementation is able to determine that TypeName 1 TypeName 2 statEnv |- TypeName 1 derives from TypeName 2 The derivation relation is transitive. statEnv |- TypeName 1 derives from TypeName 2 statEnv |- TypeName 2 derives from TypeName 3 statEnv |- TypeName 1 derives from TypeName 3 The substitutes judgment is used to know whether an element name is in the substitution group of another element name. Notation The judgment statEnv |- ElementName 1 substitutes for ElementName 2 holds when ElementName 1 ElementName 2 Example For example, assuming the extended XML Schema given in section [2.4.5 Example of a complete Schema] usaddress substitutes for address nyaddress substitutes for usaddress nyaddress substitutes for address Note Substitution is a partial order. It is reflexive and transitive by the definition below. It is asymmetric because no cycles are allowed in substitution groups. Semantics The substitutes judgment for element names is specified by the following rules. Every element name substitutes for itself. statEnv |- ElementName substitutes for ElementName Every element name substitutes for the element it is declared to substitute for. statEnv |- ElementName of elem/type expands to expanded-QName statEnv elemDecl expanded-QName ElementName BaseElementName OptNillable TypeReference statEnv |- ElementName substitutes for BaseElementName Substitution is transitive. statEnv |- ElementName 1 substitutes for ElementName 2 statEnv |- ElementName 1 substitutes for ElementName 3 statEnv |- ElementName 1 substitutes for ElementName 3 The name lookup matches name lookup matches The name lookup Notation The judgment statEnv |- ElementName name lookup ElementType yields OptNillable TypeReference holds when the given element name matches the given element type and requires that the element be nillable as indicated and have the given type reference. Example For example, assuming the extended XML Schema given in section [2.4.5 Example of a complete Schema] comment name lookup element comment yields of type xsd:string size name lookup element size nillable of type xs:integer yields nillable of type xsd:string apt name lookup element apt yields of type fs:anon3 nycaddress name lookup element address yields of type NYCAddress Note that when the element name is in a substitution group, the name lookup returns the type name corresponding to the original element name (here the type NYCAddress nycaddress Address address Semantics This judgment is specified by the following rules. If the element type is a reference to a global element, then name lookup yields the type reference in the element declaration for the given element name. The given element name must be in the substitution group of the global element. statEnv |- ElementName 1 substitutes for ElementName 2 statEnv |- ElementName 1 of elem/type expands to expanded-QName 1 statEnv elemDecl expanded-QName 1 ElementName 1 OptSubstitution OptNillable TypeReference statEnv |- ElementName 1 name lookup ElementName 2 yields OptNillable TypeReference If the given element name matches the element name in the element type, and the element type contains a type reference, then name lookup yields that type reference. statEnv |- ElementName name lookup ElementName OptNillable TypeReference yields OptNillable TypeReference If the element type has no element name but contains a type reference, then name lookup yields the type reference. statEnv |- ElementName name lookup TypeReference yields TypeReference If the element type has no element name and no type reference, then name lookup yields xs:anyType statEnv |- ElementName name lookup yields xs:anyType Notation The judgment statEnv |- AttributeName name lookup AttributeType yields TypeReference holds when matching an attribute with the given attribute name against the given attribute type matches the type reference. Example For example, assuming the extended XML Schema given in section [2.4.5 Example of a complete Schema] orderDate name lookup attribute orderDate of type xsd:date yields of type xsd:date? orderDate name lookup attribute of type xsd:date yields of type xsd:date? Semantics This judgment is specified by the following rules. If the attribute type is a reference to a global attribute, then name lookup yields the type reference in the attribute declaration for the given attribute name. statEnv |- AttributeName of attr expands to expanded-QName statEnv attrDecl expanded-QName AttributeName TypeReference statEnv |- AttributeName name lookup AttributeName yields TypeReference If the given attribute name matches the attribute name in the attribute type, and the attribute type contains a type reference, then name lookup yields that type reference. statEnv |- AttributeName name lookup AttributeName TypeReference yields TypeReference If the attribute type has no attribute name but contains a type reference, then name lookup yields the type reference. statEnv |- AttributeName name lookup TypeReference yields TypeReference If the attribute type has no attribute name and no type reference, then name lookup yields xs:anySimpleType statEnv |- AttributeName name lookup yields xs:anySimpleType The type lookup judgments are used to obtain the appropriate type reference for an attribute or element. Notation The judgment statEnv |- ElementType type lookup OptNillable TypeReference holds when the element type is optionally nillable and has the given type reference. Semantics The element type lookup judgments are specified by the following rules. A reference to a global element yields the type reference in the global element declaration with the given element name. statEnv |- ElementName of elem/type expands to expanded-QName statEnv elemDecl expanded-QName ElementName OptSubstitution OptNillable TypeReference statEnv |- ElementName type lookup OptNillable TypeReference In the case of a local element type, type lookup yields the corresponding type reference. statEnv |- ElementName OptNillable TypeReference type lookup OptNillable TypeReference If the element type has no element name but contains a type reference, then type lookup yields that type reference. statEnv |- OptNillable TypeReference type lookup TypeReference If the element type has no element name and no type reference, then lookup yields xs:anyType statEnv |- type lookup xs:anyType Notation The judgment statEnv |- AttributeType type lookup TypeReference holds when the attribute type has the given type reference. Semantics This judgment is specified by the following rules. A reference to a global attribute yields the type reference in the global attribute declaration with the given attribute name. statEnv |- AttributeName of attr expands to expanded-QName statEnv attrDecl expanded-QName AttributeName TypeReference statEnv |- AttributeName type lookup TypeReference If the attribute name is not defined, i.e., it is not declared in the in-scope schema definitions, then the attribute's default type is xs:untypedAtomic statEnv |- AttributeName of attr expands to expanded-QName statEnv attrDecl expanded-QName statEnv |- AttributeName type lookup xs:untypedAtomic In the case of a local attribute type, type lookup yields the corresponding type reference. statEnv |- AttributeName TypeReference type lookup TypeReference If the attribute type has no attribute name but contains a type reference, then type lookup yields the type reference. statEnv |- TypeReference type lookup TypeReference If the attribute type has no attribute name and no type reference, then type lookup yields xs:anySimpleType statEnv |- type lookup xs:anySimpleType Notation The judgment statEnv |- Type 1 extended by Type 2 is Type holds when the result of extending Type 1 Type 2 Type [8.1.9 Type expansion] Semantics This judgment is specified by the following rules. statEnv |- Type 1 AttributeModel 1 ElementModel 1 statEnv |- Type 2 AttributeModel 2 ElementModel 2 statEnv |- Type 1 extended by Type 2 is AttributeModel 1 AttributeModel 2 ElementModel 1 ElementModel 2 Notation The judgment statEnv |- Type 1 mixes to Type 2 holds when the result of creating a mixed content from Type 1 Type 2 Semantics This judgment is specified by the following rule, which interleaves the element content with a sequence of text nodes and adds a union of xs:anyAtomicType xs:anyAtomicType statEnv |- Type AttributeModel ElementModel statEnv |- Type mixes to AttributeModel ElementModel xs:anyAtomicType In the [XPath/XQuery] type system, a complex-type declaration does not include the implicit attributes and nodes that may be included in the type. Type adjustment takes a complex type and adjusts it to include implicit attributes and nodes. In particular, type adjustment: adds the four (optional) built-in attributes xsi:type, xsi:nil, xsi:schemaLocation, or xsi:noNamespaceSchemaLocation, interleaves the type with a sequence of comments and processing-instructions, and if the complex type is mixed, interleaves the type with a sequence of text nodes and xs:anyAtomicType Notation The judgment statEnv |- OptMixed Type 1 adjusts to Type 2 holds when the second type is the same as the first after the first has been adjusted as described above. Semantics This judgment is specified by the following rules. If the type is flagged as mixed, then mix the type and extend it by the built-in attributes. statEnv |- Type 1 mixes to Type 2 statEnv |- Type 2 extended by BuiltInAttributes is Type 3 statEnv |- Type 4 Type 3 processing-instruction** comment* statEnv |- Type 1 adjusts to Type 4 Otherwise, just extend the type by the built-in attributes. statEnv |- Type 1 extended by BuiltInAttributes is Type 2 statEnv |- Type 3 Type 2 processing-instruction** comment* statEnv |- Type 1 adjusts to Type 3 Schema defines four built-in attributes that can appear on any element in the document without being explicitly declared in the schema. Those four attributes need to be added inside content models when doing matching. The four built-in attributes of Schema are declared as follows. define attribute xsi:type of type xs:QName; define attribute xsi:nil of type xs:boolean; define attribute xsi:schemaLocation of type fs:anon; define type fs:anon1 { xs:anyURI* }; define attribute xsi:noNamespaceSchemaLocation of type xs:anyURI; For convenience, a type that is an all group of the four built-in XML Schema attributes is defined. BuiltInAttributes = attribute xsi:type ? & attribute xsi:nil ? & attribute xsi:schemaLocation ? & attribute xsi:noNamespaceSchemaLocation ? The expands to [8.2.2.1 Static semantics of axes] The judgment takes a type name and computes the union of all types derived from the given type. If the type is nillable, it also makes sure the content model allows the empty sequence. If the type is mixed, it also adjusts the type to include the mixed content model. The judgment depends on the union interpretation of Notation The judgment statEnv |- TypeSpecifier expands to Type holds when expanding the type specifier results in the given type. Semantics This judgment is specified by the following rules. If the type is nillable, then it expands into an optional type. statEnv |- TypeReference expands to Type statEnv |- TypeReference expands to Type The type definition for the type reference is contained in its expansion. statEnv |- TypeName of elem/type expands to expanded-QName statEnv.typeDefn( expanded-QName Definition statEnv |- union interpretation of Definition is Type U statEnv |- Type U adjusts to Type 3 statEnv |- TypeName expands to Type 3 In case the type is xs:untyped [3.5.1 Predefined Schema Types] statEnv |- xs:untyped of elem/type expands to expanded-QName statEnv typeDefn expanded-QName xs:untyped xs:anyType Type 1 statEnv |- xs:untyped expands to Type 1 Notation The judgment statEnv |- union interpretation of Definition is Type U holds when the type Type U Definition Semantics This judgment is specified by the following rules. statEnv |- Definition TypeName OptDerivation OptMixed Type statEnv |- inheritance due to OptDerivation is Type I statEnv |- OptMixed Type I Type opt-mixes to Type M statEnv |- type definitions derived from TypeName are Definition 1 Definition n statEnv |- union interpretation of Definition 1 is Type 1 ... statEnv |- union interpretation of Definition n is Type n Type M Type 1 Type n Type U statEnv |- union interpretation of Definition is Type U The auxilliary judgment statEnv |- inheritance due to OptDerivation is Type looks "up" the type hierarchy to find out what OptDerivation statEnv |- TypeName of elem/type expands to expanded-QName statEnv.typeDefn( expanded-QName TypeName OptDerivation OptMixed Type statEnv |- inheritance due to OptDerivation is Type I statEnv |- inheritance due to TypeName is Type I Type statEnv |- inheritance due to TypeName is statEnv |- inheritance due to is The auxiliary judgment: statEnv |- OptMixed Type 1 opt-mixes to Type 2 holds when Type 2 Type 1 OptMixed statEnv |- Type 1 mixes to Type 2 statEnv |- Type 1 opt-mixes to Type 2 statEnv |- Type 1 opt-mixes to Type 1 Finally, the auxiliary judgment: statEnv |- type definitions derived from TypeName are Definition 1 Definition n is defined informally: all type definitions in statEnv.typeDefn that involve "restricts TypeName TypeName Definition Examples Note that this expansion does not enforce the unique particule attribution T1 define type T1 { element a } define type T2 extends T1 { element b }

union interpretation of define type T1 { element a } is (element a | element a, element b) An implementation might want to infer the equivalent content model that verifies the unique particule attribution union interpretation of define type T1 { element a } is (element a, (() | element b)) Introduction Step expressions are one of the elementary operations in [XPath/XQuery]. Steps select nodes reachable from the root of an XML tree. Defining the semantics of step expressions requires a detailed analysis of all the possible cases of axis and node tests. This section introduces auxiliary judgments used to define the semantics of step expressions. The has principal [8.2.1 Principal Node Kind] principal node kind [8.2.2 Auxiliary judgments for axes] [8.2.3 Auxiliary judgments for node tests] filter [F Auxiliary Judgments for Validation] Notation The following auxiliary grammar production describes principal node kinds (See [XML Path Language (XPath) 2.0 (Second Edition)] 64 (Formal) PrincipalNodeKind ::= "element" | "attribute" | "namespace" Notation The judgment Axis has principal PrincipalNodeKind holds when PrincipalNodeKind Axis Example For example, the following judgments hold. child:: principal element descendant:: principal element preceding:: principal element attribute:: principal attribute namespace:: principal namespace Semantics This judgment is specified by the following rules. The principal node type for the attribute axis is attribute. attribute:: has principal The principal node type for the namespace axis is namespace. namespace:: has principal The principal node type for all other axis is element. Axis attribute:: Axis namespace:: Axis has principal Notation The following judgment statEnv |- axis Axis of Type 1 : Type 2 holds when applying the axis Axis Type 1 Type 2 The following two judgments are used in the definition of axis statEnv |- Type 1 has node content Type 2 only applies to a type that is a valid element content type and holds when Type 1 Type 2 The judgment statEnv |- Type 1 has attribute content Type 2 only applies to a type that is a valid element content type and holds when Type 1 Type 2 Example For example, the following judgments hold. axis child:: of element of type xs:string : text axis child:: of element items of type Items : element item of type fs:anon1*

axis child:: of element purchaseOrder : element shipTo of type USAddress, element billTo of type USAddress, element ipo:comment?, element items of type Items

axis attribute:: of element of type xs:string : empty

attribute partNum of type SKU, element item of type fs:anon1* has-node-content element item of type fs:anon1*

attribute partNum of type SKU, element item of type fs:anon1* has-attribute-content attribute partNum of type SKU

(attribute partNum of type SKU, element item of type fs:anon1*) | (attribute orderDate of type xs:date?, element shipTo of type USAddress, element billTo of type USAddress, element comment?, element items of type Items) has-node-content (element item of type fs:anon1*) | (element shipTo of type USAddress, element billTo of type USAddress, element comment?, element items of type Items)

(attribute partNum of type SKU, element item of type fs:anon1*) | (attribute orderDate of type xs:date?, element shipTo of type USAddress, element billTo of type USAddress, element comment?, element items of type Items) has-attribute-content (attribute partNum of type SKU) | (attribute orderDate of type xs:date?) Semantics The following rules compute the type of the axis expression when applied to each item type in the content model. statEnv |- axis Axis of Type 1 : Type 2 statEnv |- axis Axis of Type 1 OccurrenceIndicator : Type 2 OccurrenceIndicator statEnv |- axis Axis of Type 1 : Type 3 statEnv |- axis Axis of Type 2 : Type 4 statEnv |- axis Axis of Type 1 Type 2 : Type 3 Type 4 statEnv |- axis Axis of Type 1 : Type 3 statEnv |- axis Axis of Type 2 : Type 4 statEnv |- axis Axis of Type 1 Type 2 : Type 3 Type 4 statEnv |- axis Axis of Type 1 : Type 3 statEnv |- axis Axis of Type 2 : Type 4 statEnv |- axis Axis of Type 1 Type 2 : Type 3 Type 4 statEnv |- axis Axis of : statEnv |- axis Axis of empty : empty The rules in the following subsections specify how to compute the type of each axis applied to an item type. self Semantics Applying the self axis to a node type results in the same node type. statEnv |- axis self:: of NodeType : NodeType child Semantics In the case of an element type, the static type of the child axis is obtained by type lookup and expansion of the resulting type. Note that the expands to all expands to union After type expansion, the judgment has node content statEnv |- ElementType type lookup OptNillable TypeReference statEnv |- OptNillable TypeReference expands to Type 1 Type n statEnv |- Type 1 has node content Type 1 · · · statEnv |- Type n has node content Type n statEnv |- axis child:: of ElementType : Type 1 Type n If the type is a sequence of attributes, then the content type is empty statEnv |- Type <: statEnv |- Type has node content empty If the type is attributes followed by a simple type, the content type is zero-or-one text nodes. The resulting type is optional since an expression returning the empty sequence results in no text node being constructed. Type Type 1 Type 2 statEnv |- Type 1 <: statEnv |- Type 2 <: xs:anyAtomicType statEnv |- Type has node content In the case of an element type with complex content type, the content type is simply the non-attribute part of the complex content type. Type Type 1 Type 2 statEnv |- Type 1 <: statEnv |- Type 2 <: ElementModel statEnv |- Type has node content Type 2 In the case of an attribute type, the static type of the child axis is empty. statEnv |- axis child:: of AttributeType : empty In the case of a text node type, the static type of the child axis is empty. statEnv |- axis child:: of : empty In the case of a comment node type, the static type of the child axis is empty. statEnv |- axis child:: of : empty In the case of a processing-instruction node type, the static type of the child axis is empty. statEnv |- axis child:: of : empty In case of a document node type, the static type of the child axis is the type of the document node content, interleaved with a sequence of comments and processing-instructions. statEnv |- axis child:: of Type : Type attribute Semantics The static type for the attribute axis is computed in a similar way as the static type for the child axis. As above, the expands to has attribute content statEnv |- ElementType type lookup OptNillable TypeReference statEnv |- OptNillable TypeReference expands to Type 1 Type n statEnv |- Type 1 has attribute content Type 1 · · · statEnv |- Type n has attribute content Type n statEnv |- axis attribute:: of ElementType : Type 1 Type n When applied to an element type, has attribute content Type Type 1 Type 2 statEnv |- Type 1 <: statEnv |- Type 2 <: ElementModel xs:anyAtomicType statEnv |- Type has attribute content Type 1 In case of an attribute type, the static type of the attribute axis is empty. statEnv |- axis attribute:: of AttributeType : empty In case of a text node type, the static type of the attribute axis is empty. statEnv |- axis attribute:: of : empty In case of a comment node type, the static type of the attribute axis is empty. statEnv |- axis attribute:: of : empty In case of a processing-instruction node type, the static type of the attribute axis is empty. statEnv |- axis attribute:: of : empty In case of a document node type, the static type of the attribute axis is the empty. statEnv |- axis attribute:: of Type : empty parent Semantics The type for the parent of an element type, a text node type, a PI node type, or a comment node type is either an element, a document, or empty. statEnv |- axis parent:: of : statEnv |- axis parent:: of : statEnv |- axis parent:: of : statEnv |- axis parent:: of : The type for the parent of an attribute node is an element or empty. statEnv |- axis parent:: of AttributeType : The type for the parent of a document node type is always empty. statEnv |- axis parent:: of DocumentType : empty namespace Semantics This document does not specify inference rules for the namespace axis (which is allowed, though deprecated, in XPath 2.0, and is not allowed in XQuery 1.0). Implementations choosing to support the namespace axis will need to define an additional node kind for namespace nodes in the type hierarchy, and to add the appropriate inference rules. descendant Semantics The types for the descendant axis is obtained as the closure of the type of the child axis. This is expressed by the following inference rule. statEnv |- axis child:: of Type : Type 1 statEnv |- axis child:: of prime Type 1 : Type 2 ... statEnv |- axis child:: of prime Type n : Type n+1 statEnv |- prime Type n+1 <: prime Type 1 prime Type n statEnv |- axis descendant:: of Type : prime Type 1 prime Type n Note Note that the last premise in the above rule terminates the recursion. The rule computes the n-th type Type n descendant-or-self Semantics The type for the descendant-or-self axis is the union of the type for the self axis and for the descendant axis. statEnv |- axis descendant:: of Type 1 : Type 2 statEnv |- axis descendant-or-self:: of Type 1 : prime Type 1 prime Type 2 ancestor Semantics The type for the ancestor axis is computed similarly as for the descendant axis. statEnv |- axis ancestor:: of NodeType : Note that this rule will always result in the type (element * | document)* statEnv |- axis parent:: of Type : Type 1 statEnv |- axis parent:: of prime Type 1 : Type 2 ... statEnv |- axis parent:: of prime Type n : Type n+1 statEnv |- prime Type n+1 <: prime Type 1 prime Type n statEnv |- axis ancestor:: of Type : prime Type 1 prime Type n ancestor-or-self Semantics The type for the ancestor-or-self axis is the union of the type for the self axis and for the ancestor axis. statEnv |- axis ancestor:: of Type 1 : Type 2 statEnv |- axis ancestor-or-self:: of Type 1 : prime Type 1 prime Type 2 Notation The following judgment dynEnv |- axis Axis of Value 1 => Value 2 holds when applying the axis Axis Value 1 Value 2 Example For example, the following judgments hold. axis child:: of element sizes { text { "1 2 3" } } => text { "1 2 3" }

axis attribute:: of element weight of type xs:integer { attribute xsi:type of type xs:QName { "xs:integer" of type xs:QName }, 42 of type xs:integer } => attribute xsi:type of type xs:QName { "xs:integer" of type xs:QName } Semantics This judgment is specified by the following rules. The first set of rules are used to process the axis judgment on each individual item in the input sequence. dynEnv |- axis Axis of => dynEnv |- axis Axis of Value 1 => Value 3 dynEnv |- axis Axis of Value 2 => Value 4 dynEnv |- axis Axis of Value 1 Value 2 => Value 3 Value 4 The following rules specifies how the value filter judgment is applied on each Axis. The self axis just returns the context node. dynEnv |- axis self:: of NodeValue => NodeValue The child, parent, attribute and namespace axis are specified as follows. dynEnv |- axis child:: of ElementName AttributeValue ElementValue => ElementValue dynEnv |- axis attribute:: of ElementName AttributeValue ElementValue => AttributeValue dynEnv |- axis parent:: of NodeValue => dm: NodeValue The descendant, descendant-or-self, ancestor, and ancestor-or-self axis are implemented through recursive application of the children and parent filters. dynEnv |- axis child:: of NodeValue => Value 1 dynEnv |- axis descendant:: of Value 1 => Value 2 dynEnv |- axis descendant:: of NodeValue => Value 1 Value 2 dynEnv |- axis self:: of NodeValue => Value 1 dynEnv |- axis descendant:: of Value 1 => Value 2 dynEnv |- axis descendant-or-self:: of NodeValue => Value 1 Value 2 dynEnv |- axis parent:: of NodeValue => Value 1 dynEnv |- axis ancestor:: of Value 1 => Value 2 dynEnv |- axis ancestor:: of NodeValue => Value 1 Value 2 dynEnv |- axis self:: of NodeValue => Value 1 dynEnv |- axis ancestor:: of Value 1 => Value 2 dynEnv |- axis ancestor-or-self:: of NodeValue => Value 1 Value 2 In all the other cases, the axis application results in an empty sequence, and the following judgment holds. Otherwise dynEnv |- axis Axis of NodeValue => A node test may be a name test or a kind test. In the static and dynamic semantics, we begin with name tests, followed by kind tests. Notation The following judgment statEnv |- test NodeTest with PrincipalNodeKind of Type 1 : Type 2 holds when applying the node test NodeTest Type 1 Type 2 Example For example, assuming the extended XML Schema given in section [2.4.5 Example of a complete Schema] test shipTo with element of element shipTo of type USAddress, element billTo of type USAddress, element ipo:comment?, element items of type Items : element shipTo of type USAddress Semantics This judgment is specified by the following rules. The first set of rules is similar to that for axes, and are used to process the content each individual item type in the input content model. statEnv |- test NodeTest with PrincipalNodeKind of Type 1 : Type 2 statEnv |- test NodeTest with PrincipalNodeKind of Type 1 OccurrenceIndicator : Type 2 OccurrenceIndicator statEnv |- test NodeTest with PrincipalNodeKind of Type 1 : Type 3 statEnv |- test NodeTest with PrincipalNodeKind of Type 2 : Type 4 statEnv |- test NodeTest with PrincipalNodeKind of Type 1 Type 2 : Type 3 Type 4 statEnv |- test NodeTest with PrincipalNodeKind of Type 1 : Type 3 statEnv |- test NodeTest with PrincipalNodeKind of Type 2 : Type 4 statEnv |- test NodeTest with PrincipalNodeKind of Type 1 Type 2 : Type 3 Type 4 statEnv |- test NodeTest with PrincipalNodeKind of Type 1 : Type 3 statEnv |- test NodeTest with PrincipalNodeKind of Type 2 : Type 4 statEnv |- test NodeTest with PrincipalNodeKind of Type 1 Type 2 : Type 3 Type 4 statEnv |- test NodeTest with PrincipalNodeKind of : statEnv |- test NodeTest with PrincipalNodeKind of : The following rules specify how the test judgment apply to node tests in the context of a principal node kind. We start with name tests followed by kind tests. Name tests on elements and attributes always compute the most specific type possible. For example, if $v $v element $v/self::foo element foo of type xs:anyType foo statEnv |- QName 1 of elem/type expands to expanded-QName statEnv |- QName 2 of elem/type expands to expanded-QName statEnv |- test QName 2 with of QName 1 OptTypeSpecifier : QName 1 OptTypeSpecifier statEnv |- QName 1 of elem/type expands to expanded-QName 1 statEnv |- QName 2 of elem/type expands to expanded-QName 2 not expanded-QName 1 expanded-QName 2 statEnv |- test QName 2 with of QName 1 OptTypeSpecifier 1 : statEnv |- test QName 2 with of * OptTypeSpecifier : QName 2 OptTypeSpecifier statEnv |- QName 1 of elem/type expands to expanded-QName 1 LocalPart 2 fn:local-name-from-QName expanded-QName 1 statEnv |- test *: LocalPart 2 with of QName 1 OptTypeSpecifier : QName 1 OptTypeSpecifier statEnv |- QName 1 of elem/type expands to expanded-QName 1 fn:local-name-from-QName expanded-QName 1 LocalPart 1 not LocalPart 1 LocalPart 2 statEnv |- test LocalPart 2 with of QName 1 OptTypeSpecifier 1 : statEnv |- test *: LocalPart 2 with of OptTypeSpecifier : OptTypeSpecifier statEnv |- QName 1 of elem/type expands to expanded-QName 1 statEnv namespace Prefix 2 NamespaceKind AnyURI fn:namespace-uri-from-QName expanded-QName 1 AnyURI statEnv |- test Prefix 2 with of QName 1 OptTypeSpecifier : QName 1 OptTypeSpecifier statEnv |- QName 1 of elem/type expands to expanded-QName 1 fn:namespace-uri-from-QName expanded-QName 1 AnyURI 1 statEnv namespace Prefix 2 NamespaceKind AnyURI 2 not AnyURI 1 AnyURI 2 statEnv |- test Prefix 2 with of QName 1 OptTypeSpecifier 1 : statEnv |- test Prefix 2 :* with of OptTypeSpecifier : OptTypeSpecifier statEnv |- test * with of ElementType : ElementType not Type statEnv |- test NameTest with of Type : Similar static typing rules apply to the attribute name tests: statEnv |- QName 1 of attr expands to expanded-QName statEnv |- QName 2 of attr expands to expanded-QName statEnv |- test QName 2 with of QName 1 OptTypeReference : QName 1 OptTypeReference statEnv |- QName 1 of attr expands to expanded-QName 1 statEnv |- QName 2 of attr expands to expanded-QName 2 not expanded-QName 1 expanded-QName 2 statEnv |- test QName 2 with of QName 1 OptTypeReference : statEnv |- test QName 2 with of * OptTypeReference : QName 2 OptTypeReference statEnv |- QName 1 of attr expands to expanded-QName 1 fn:local-name-from-QName expanded-QName 1 LocalPart 2 statEnv |- test *: LocalPart 2 with of QName 1 OptTypeReference : QName 1 OptTypeReference statEnv |- QName 1 of attr expands to expanded-QName 1 fn:local-name-from-QName expanded-QName 1 LocalPart 1 not LocalPart 1 LocalPart 2 statEnv |- test LocalPart 2 with of QName 1 OptTypeReference : statEnv |- test *: LocalPart 2 with of OptTypeReference : OptTypeReference statEnv namespace Prefix 2 NamespaceKind AnyURI statEnv |- QName 1 of attr expands to expanded-QName 1 fn:namespace-uri-from-QName expanded-QName 1 AnyURI statEnv |- test Prefix 2 :* with of QName 1 OptTypeReference : QName 1 OptTypeReference statEnv |- QName 1 of attr expands to expanded-QName 1 fn:namespace-uri-from-QName expanded-QName 1 AnyURI 1 statEnv namespace Prefix 2 NamespaceKind AnyURI 2 not AnyURI 1 AnyURI 2 statEnv |- test Prefix 2 with of QName 1 OptTypeReference : statEnv |- test Prefix 2 :* with of OptTypeReference : OptTypeReference statEnv |- test * with of AttributeType : AttributeType not Type statEnv |- test NameTest with of Type : All the rules for typing the document, element, and attribute kind tests are similar. First, the document, element, or attribute test is normalized to the equivalent document, element, or attribute type by applying the [ ] sequencetype After normalization of the kind test as an XQuery type, that type is compared to the expression's inferred type. If the latter is a subtype of the former other, then the kind test yields the smaller type. Document kind test Semantics If the type of the expression is a subtype of the document kind test, then we are guaranteed that during evaluation, the expression's value will always match the document kind test, and therefore the type of the entire expression is the type of the input expression. [ DocumentTest ] sequencetype DocumentType statEnv |- Type 1 <: DocumentType statEnv |- test DocumentTest with of Type 1 : Type 1 Conversely, if the type of the document kind test is a subtype of the expression, then during evaluation, the expression's value may or may not match the document kind test, and therefore the type of the entire expression is zero-or-one of the type of the document kind test. [ DocumentTest ] sequencetype DocumentType statEnv |- DocumentType <: Type 1 statEnv |- test DocumentTest with of Type 1 : DocumentType If the types of the expression and document kind test are unrelated, then we apply the kind test rule recursively on the element types, which may yield a non-empty type. [ ElementTest ] sequencetype DocumentType statEnv |- not Type 1 <: DocumentType statEnv |- not DocumentType <: Type 1 statEnv |- test ElementTest with of Type 1 : Type 2 statEnv |- not Type 2 <: empty statEnv |- test ElementTest with of Type 1 : Type 2 If there is no non-empty type, then the kind test yields the empty type. [ ElementTest ] sequencetype DocumentType statEnv |- not Type 1 <: DocumentType statEnv |- not DocumentType <: Type 1 statEnv |- test ElementTest with of Type 1 : Type 2 statEnv |- Type 2 <: empty statEnv |- test ElementTest with of Type 1 : Element kind test Semantics The rules for the element kind test are similar to those for the document kind test. If the type of the expression is a subtype of the element kind test, then we are guaranteed that during evaluation, the expression's element value will always match the element kind test, and therefore the type of the entire expression is the type of the input expression. [ ElementTest ] sequencetype ElementType statEnv |- Type 1 <: ElementType statEnv |- test ElementTest with of Type 1 : Type 1 Conversely, if the type of the element kind test is a subtype of the expression, then during evaluation, the expression's element value may or may not match the element kind test, and therefore the type of the entire expression is zero-or-one of the type of the element kind test. [ ElementTest ] sequencetype ElementType statEnv |- ElementType <: Type 1 statEnv |- test ElementTest with of Type 1 : ElementType If the types of the expression and element kind test are unrelated (i.e., neither type is a subtype of the other), then we must compare the structure of the type of the element test with the type of the element expression, as an element type or test may contain wildcards. In the first case, the element kind test contains an element name and a type name and the input expression's type contains only a type name. If the input expression's content type is a subtype of the element kind test's content type, then the type of the entire expression is zero-or-one of an element with the given name and the input expression's content type. [ ElementTest ] sequencetype ElementName 1 TypeSpecifier 1 statEnv |- TypeSpecifier 1 expands to Type 1 statEnv |- TypeSpecifier 2 expands to Type 2 statEnv |- Type 2 <: Type 1 statEnv |- test ElementTest with of TypeSpecifier 2 : ElementName 1 TypeSpecifier 2 In the second case, the structure of the input types is reversed: The input expression's type contains an element name and a type name and the element kind test's type contains only a type name. If the element kind test's content type is a subtype of the input expression's content type, then the type of the entire expression is zero-or-one of an element with the given name and the element kind test's content type. [ ElementTest ] sequencetype TypeSpecifier 1 statEnv |- TypeSpecifier 1 expands to Type 1 statEnv |- TypeSpecifier 2 expands to Type 2 statEnv |- Type 1 <: Type 2 statEnv |- test ElementTest with of ElementName 2 TypeSpecifier 2 : ElementName 2 TypeSpecifier 1 Lastly, if none of the above rules holds, then the type of the input expression is empty. [ ElementTest ] sequencetype ElementNameOrWildcard 1 TypeSpecifier 1 statEnv |- not ElementNameOrWildcard 1 TypeSpecifier 1 <: ElementNameOrWildcard 2 TypeSpecifier 2 statEnv |- not ElementNameOrWildcard 2 TypeSpecifier 2 <: ElementNameOrWildcard 1 TypeSpecifier 1 statEnv |- TypeSpecifier 1 expands to Type 1 statEnv |- TypeSpecifier 2 expands to Type 2 statEnv |- not Type 1 <: Type 2 statEnv |- not Type 2 <: Type 1 statEnv |- test ElementTest with of ElementNameOrWildcard 2 TypeSpecifier 2 : Attribute kind test Semantics The rules for the attribute kind test are isomorphic to those for element kind test. If the type of the expression is a subtype of the attribute kind test, then we are guaranteed that during evaluation, the expression's attribute value will always match the attribute kind test, and therefore the type of the entire expression is the type of the input expression. [ AttributeTest ] sequencetype AttributeType statEnv |- Type 1 <: AttributeType statEnv |- test AttributeTest with of Type 1 : Type 1 Conversely, if the type of the attribute kind test is a subtype of the expression, then during evaluation, the expression's attribute value may or may not match the attribute kind test, and therefore the type of the entire expression is zero-or-one of the type of the attribute kind test. [ AttributeTest ] sequencetype AttributeType statEnv |- AttributeType <: Type 1 statEnv |- test AttributeTest with of Type 1 : AttributeType If the types of the expression and attribute kind test are unrelated (i.e., neither type is a subtype of the other), then we must compare the structure of the type of the attribute test with the type of the attribute expression, as an attribute type or test may contain wildcards. In the first case, the attribute kind test contains an attribute name and a type name and the input expression's type contains only a type name. If the input expression's content type is a subtype of the attribute kind test's content type, then the type of the entire expression is zero-or-one of an attribute with the given name and the input expression's content type. [ AttributeTest ] sequencetype AttributeName 1 TypeReference 1 statEnv |- TypeReference 1 expands to Type 1 statEnv |- TypeReference 2 expands to Type 2 statEnv |- Type 2 <: Type 1 statEnv |- test AttributeTest with of TypeReference 2 : AttributeName 1 TypeReference 2 In the second case, the structure of the input types is reversed: The input expression's type contains an attribute name and a type name and the attribute kind test's type contains only a type name. If the attribute kind test's content type is a subtype of the input expression's content type, then the type of the entire expression is zero-or-one of an attribute with the given name and the attribute kind test's content type. [ AttributeTest ] sequencetype TypeReference 1 statEnv |- TypeReference 1 expands to Type 1 statEnv |- TypeReference 2 expands to Type 2 statEnv |- Type 1 <: Type 2 statEnv |- test AttributeTest with of AttributeName 2 TypeReference 2 : AttributeName 2 TypeReference 1 Lastly, if none of the above rules holds, then the type of the input expression is empty. [ AttributeTest ] sequencetype AttributeName 1 TypeReference 1 statEnv |- not AttributeName 1 TypeReference 1 <: AttributeName 2 TypeReference 2 statEnv |- not AttributeName 2 TypeReference 2 <: AttributeName 1 TypeReference 1 statEnv |- TypeReference 1 expands to Type 1 statEnv |- TypeReference 2 expands to Type 2 statEnv |- not Type 1 <: Type 2 statEnv |- not Type 2 <: Type 1 statEnv |- test AttributeTest with of AttributeName 2 TypeReference 2 : Processing instruction, comment, and text kind tests Semantics [ PITest ] sequencetype statEnv |- test PITest with PrincipalNodeKind of ProcessingInstructionType : ProcessingInstructionType A processing-instruction node test with a string literal or NCName matches a processing instruction whose target has the given name. [ PITest ] sequencetype NCName statEnv |- test PITest with PrincipalNodeKind of NCName : NCName [ PITest ] sequencetype NCName statEnv |- test PITest with PrincipalNodeKind of : NCName statEnv |- test comment() with PrincipalNodeKind of : statEnv |- test text() with PrincipalNodeKind of : statEnv |- test node() with PrincipalNodeKind of NodeType : NodeType If none of the above rules applies then the node test returns the empty sequence, and the following dynamic rule is applied: Otherwise statEnv |- test NodeTest with PrincipalNodeKind of NodeType : empty Notation The following judgment dynEnv |- test NodeTest with PrincipalNodeKind of Value 1 => Value 2 holds when applying the node test NodeTest Value 1 PrincipalNodeKind Value 2 Example For example, the following judgments hold. test node() with element of text { "1 2 3" } => text { "1 2 3" } test size with element of text { "1 2 3" } => ()

test foo:* with element of (element foo:a of type xs:int { 1 }, element foo:a of type xs:int { 2 }, element bar:b of type xs:int { 3 }, element bar:c of type xs:int { 4 }, element foo:d of type xs:int { 5 }) => (element foo:a of type xs:int { 1 }, element foo:a of type xs:int { 2 }, (), (), element foo:d of type xs:int { 5 }) Note The last example illustrates how a test judgment operates on a sequence of nodes, applying the test on each node in the sequence individually, while preserving the structure of the sequence. Semantics This judgment is specified by the following rules. The first set of rules are similar to those for axes, and are used to process the test judgment on each individual item in the input sequence. dynEnv |- test NodeTest with PrincipalNodeKind of => dynEnv |- test NodeTest with PrincipalNodeKind of Value 1 => Value 3 dynEnv |- test NodeTest with PrincipalNodeKind of Value 2 => Value 4 dynEnv |- test NodeTest with PrincipalNodeKind of Value 1 Value 2 => Value 3 Value 4 The following rules specify how the value filter judgment is applied on a name test in the context of a principal node kind. Semantics dm: node-kind NodeValue PrincipalNodeKind fn:node-name NodeValue expanded-QName statEnv namespace Prefix NamespaceKind AnyURI fn:namespace-uri-from-QName expanded-QName AnyURI fn:local-name-from-QName expanded-QName LocalPart dynEnv |- test Prefix LocalPart with PrincipalNodeKind of NodeValue => NodeValue dm: node-kind NodeValue PrincipalNodeKind dynEnv |- test * with PrincipalNodeKind of NodeValue => NodeValue dm: node-kind NodeValue PrincipalNodeKind fn:node-name NodeValue expanded-QName statEnv namespace Prefix NamespaceKind AnyURI fn:namespace-uri-from-QName expanded-QName AnyURI dynEnv |- test Prefix :* with PrincipalNodeKind of NodeValue => NodeValue dm: node-kind NodeValue PrincipalNodeKind fn:node-name NodeValue expanded-QName fn:local-name-from-QName expanded-QName LocalPart dynEnv |- test *: LocalPart with PrincipalNodeKind of NodeValue => NodeValue All the rules for evaluating the document, element, and attribute kind tests are similar. First, the document, element, or attribute test is normalized to the equivalent document, element, or attribute type by applying the [ ] sequencetype [3.5.3 SequenceType Syntax] After normalization of the SequenceType to an XQuery type, the document, element, or attribute value is simply matched against the XQuery type. If the value matches the type, then the judgment yields the value, otherwise the judgment yields the empty sequence. Document kind test Semantics [ DocumentTest ] sequencetype DocumentType statEnv |- DocumentValue matches DocumentType dynEnv |- test DocumentTest with of DocumentValue => DocumentValue [ DocumentTest ] sequencetype DocumentType statEnv |- not DocumentValue matches DocumentType dynEnv |- test DocumentTest with of DocumentValue => Element kind test Semantics [ ElementTest ] sequencetype ElementType statEnv |- ElementValue matches ElementType dynEnv |- test ElementTest with of ElementValue => ElementValue [ ElementTest ] sequencetype ElementType statEnv |- not ElementValue matches ElementType dynEnv |- test ElementTest with of ElementValue => Attribute kind test Semantics [ AttributeTest ] sequencetype AttributeType statEnv |- AttributeValue matches AttributeType dynEnv |- test AttributeTest with of AttributeValue => AttributeValue [ AttributeTest ] sequencetype AttributeType statEnv |- not AttributeValue matches AttributeType dynEnv |- test AttributeTest with of AttributeValue => Processing instruction, comment, and text kind tests Semantics dm: node-kind NodeValue dynEnv |- test processing-instruction() with PrincipalNodeKind of NodeValue => NodeValue dm: node-kind NodeValue fn:node-name NodeValue expanded-QName dynEnv |- StringLiteral has atomic value String fn:local-name-from-QName expanded-QName String dynEnv |- test processing-instruction( StringLiteral ) with PrincipalNodeKind of NodeValue => NodeValue not dm: node-kind NodeValue dynEnv |- test processing-instruction() with PrincipalNodeKind of NodeValue => dm: node-kind NodeValue dynEnv |- test comment() with PrincipalNodeKind of NodeValue => NodeValue not dm: node-kind NodeValue dynEnv |- test comment() with PrincipalNodeKind of NodeValue => dm: node-kind NodeValue dynEnv |- test text() with PrincipalNodeKind of NodeValue => NodeValue not dm: node-kind NodeValue dynEnv |- test text() with PrincipalNodeKind of NodeValue => The node() dynEnv |- test node() with PrincipalNodeKind of NodeValue => NodeValue If none of the above rules applies then the node test returns the empty sequence, and the following dynamic rule is applied: Otherwise dynEnv |- test NodeTest with PrincipalNodeKind of NodeValue => Introduction XQuery supports type declarations on variable bindings, and several operations on types ( typeswitch instance of The "match" judgment specifies formally type matching. It takes as input a value and a type and either succeeds or fails. It is used in matching parameters against function signatures, type declarations, and matching values against cases in "typeswitch". An informal description of type matching is given in Section 2.5.4 SequenceType Matching XQ The "subtyping" judgment takes two types and succeeds if all values matching the first type also match the second. It is used to define the static semantics of operations using type matching. Notation The judgment statEnv |- Value matches Type holds when the given value matches the given type. Example For example, assuming the extended XML Schema given in section [2.4.5 Example of a complete Schema] element comment of type xsd:string { "This is not important" } matches element comment of type xsd:string

(element apt of type fs:anon3 { 2510 }, element apt of type fs:anon3 { 2511 }) matches element apt+

() matches element usaddress?

element usaddress of type USAddress { element name of type xsd:string { "The Archive" }, element street of type xsd:string { "Christopher Street" }, element city of type xsd:string { "New York" }, element state of type xsd:string { "NY" }, element zip of type xsd:decimal { 10210 } } matches element usaddress? Semantics We start by giving the inference rules for matching an item value with an item type. An atomic value matches an atomic type if its type annotation XQ statEnv |- AtomicTypeName 1 derives from AtomicTypeName 2 statEnv |- AtomicValueContent AtomicTypeName 1 matches AtomicTypeName 2 A text node matches text. statEnv |- String matches A comment node matches comment. statEnv |- String matches A processing-instruction node matches the general processing-instruction type, and also the particular processing-instruction type that shares its PITarget. statEnv |- NCName String matches statEnv |- NCName String matches NCName A document node matches a document type if the node's content matches the document type's corresponding content type. statEnv |- Value matches Type statEnv |- Value matches Type The rules for matching an element value with an element type are more complicated. When an element value is not nilled, the element matches an element type if the element name and the element type resolve to some type name, and the element value's type annotation XQ type annotation XQ statEnv |- ElementName name lookup ElementType yields OptNillable BaseTypeName statEnv |- TypeName derives from BaseTypeName Value 1 filter => SimpleValue SimpleValue in statEnv |- ElementName TypeName Value matches ElementType Note Type matching uses the name lookup judgment defined in [8.1.3 Element and attribute name lookup (Dynamic)] In the case the element has been nilled, that is there exists and xsi:nil attribute set to true in the element value, the following rule checks that the type is nillable. statEnv |- ElementName name lookup ElementType yields BaseTypeName statEnv |- TypeName derives from BaseTypeName Value filter => statEnv |- ElementName TypeName Value matches ElementType The rule for attributes is similar, but does not require the check for the xsi:nil attribute. statEnv |- AttributeName name lookup AttributeType yields BaseTypeName statEnv |- TypeName derives from BaseTypeName statEnv |- AttributeName TypeName SimpleValue matches AttributeType A type can also be a sequence of items, in that case the matching rules also need to check whether the constraints described by the type as a regular expression hold. This is specified by the following rules. The empty sequence matches the empty sequence type. statEnv |- matches empty If two values match two types, then their sequence matches the corresponding sequence type. statEnv |- Value 1 matches Type 1 statEnv |- Value 2 matches Type 2 statEnv |- Value 1 Value 2 matches Type 1 Type 2 If a value matches a type, then it also matches a choice type where that type is one of the choices. statEnv |- Value matches Type 1 statEnv |- Value matches Type 1 Type 2 statEnv |- Value matches Type 2 statEnv |- Value matches Type 1 Type 2 If two values match two types, then their interleaving matches the corresponding all group. statEnv |- Value 1 matches Type 1 statEnv |- Value 2 matches Type 2 statEnv |- Value 1 interleave Value 2 yields Value statEnv |- Value matches Type 1 Type 2 An optional type matches a value of that type or the empty sequence. statEnv |- Value matches Type statEnv |- Value matches Type The following rules are used to match a value against a sequence of zero (or one) or more types. statEnv |- matches Type statEnv |- Value 1 matches Type statEnv |- Value 2 matches Type statEnv |- Value 1 Value 2 matches Type statEnv |- Value 1 matches Type statEnv |- Value 2 matches Type statEnv |- Value 1 Value 2 matches Type Note The above definition of type matching, although complete and precise, does not give a simple means to compute The structural component of the [XPath/XQuery] type system can be modeled by regular expressions. Regular expressions can be implemented by means of finite state automata. Computing type matching then is equivalent to check if a given sequence of items is recognized [Languages] [TATA] Introduction This section defines the semantics of subtyping in [XPath/XQuery]. Subtyping is used during static type analysis, in typeswitch, treat and assert expressions, and to check the correctness of function applications. Note that intuitive relationships between types. For instance, that ( Type Type Notation The judgment statEnv |- Type 1 <: Type 2 holds if the first type is a subtype of the second. Semantics This judgment is true if and only if, for every value Value Value matches Type 1 Value matches Type 2 Note It is easy to see that the subtype relation <: reflexive statEnv |- Type <: Type and it is transitive statEnv |- Type 1 <: Type 2 and, statEnv |- Type 2 <: Type 3 then, statEnv |- Type 1 <: Type 3 Finally, two types are equal if each is a subtype of the other, that is: statEnv |- Type 1 <: Type 2 and, statEnv |- Type 2 <: Type 1 then, statEnv |- Type 1 Type 2 Note The above definition, although complete and precise, does not give a simple means to compute The structural component of the [XPath/XQuery] type system can be modeled by regular expressions. Regular expressions can be implemented by means of finite state automata. Computing subtyping between two types can then be done by computing if inclusion Finite state automata and how to compute operations on those automata, such as inclusion, emptiness or intersection, have been extensively studied and documented in the literature. The interested reader can consult the relevant literature on tree grammars, for instance [Languages] [TATA] Introduction Some [XPath/XQuery] operations work on sequences of items. For instance, [For/FLWOR] expressions iterate over a sequence of items and the fn:unordered Static typing for those operations needs to infer a type acceptable for all Example Assume the variable $shipTo <shipTo country="US"> <name>Alice Smith</name> <street>123 Maple Street</street> <city>Mill Valley</city> <state>CA</state> <zip>90952</zip> </shipTo> and has type element shipTo of type USAddress The following query orders all children of the shipTo element by alphabetical order of their content. for $x in $shipTo/* order by $x/text() return $x resulting in the sequence (<street>123 Maple Street</street>, <zip>90952</zip>, <name>Alice Smith</name>, <state>CA</state>, <city>Mill Valley</city>) This operation iterates over the elements in the input sequence returned by the expression $shipTo/* (element name of type xsd:string, element street of type xsd:string, element city of type xsd:string, element state of type xsd:string, element zip of type xsd:decimal) During static typing, one must give a type to the variable $x $x (element name of type xsd:string | element street of type xsd:string | element city of type xsd:string | element state of type xsd:string | element zip of type xsd:decimal) This type indicates that the type of the variable can be of any of the item types in the input sequence. The static inference also needs to approximate the number of occurrences of items in the sequence. In this example, there is at least one item and more than one, so the closest occurrence indicator is + The static inference for this example finally results in the following type. (element name of type xsd:string | element street of type xsd:string | element city of type xsd:string | element state of type xsd:string | element zip of type xsd:decimal)+ [ Definition prime type Notation A choice of item types is called a prime type 44 (Formal) PrimeType ::= FormalItemType PrimeType PrimeType Notation The type function prime Type Type The function quantifier Type Type ?, +, * For interim results, the auxiliary occurrence indicator 1 Semantics The prime prime FormalItemType = FormalItemType prime empty = none prime none = none prime Type 1 Type 2 = prime Type 1 prime Type 2 prime Type 1 Type 2 = prime Type 1 prime Type 2 prime Type 1 Type 2 = prime Type 1 prime Type 2 prime Type = prime Type prime Type = prime Type prime Type = prime Type Note This function is typically used in judgments of the form: prime Type FormalItemType 1 FormalItemType n In cases where prime Type none FormalItemType 1 none n 1 none FormalItemType n 0 Semantics The quantifier quantifier FormalItemType = 1 quantifier empty = ? quantifier none = 1 quantifier Type 1 Type 2 = quantifier Type 1 quantifier Type 2 quantifier Type 1 Type 2 = quantifier Type 1 quantifier Type 2 quantifier Type 1 Type 2 = quantifier Type 1 quantifier Type 2 quantifier Type = quantifier Type · quantifier Type = quantifier Type · quantifier Type = quantifier Type · This definition uses the sum ( OccurrenceIndicator 1 OccurrenceIndicator 2 OccurrenceIndicator 1 OccurrenceIndicator 2 OccurrenceIndicator 1 · OccurrenceIndicator 2 OccurrenceIndicator 1 OccurrenceIndicator 2 , 1 ? + * 1 + + + + ? + * + * + + + + + * + * + * | 1 ? + * 1 1 ? + * ? ? ? * * + + * + * * * * * * · 1 ? + * 1 1 ? + * ? ? ? * * + + * + * * * * * * Examples For example, here are the result of applying prime quantifier prime(element a+) = element a prime(element a | empty) = element a prime(element a?,element b?) = element a | element b prime(element a | element b+, element c*) = element a | element b | element c

quantifier(element a+) = + quantifier(element a | empty) = ? quantifier(element a?,element b?) = * quantifier(element a | element b+, element d*) = + Note that the last occurrence indicator should be '+', since the regular expression is such that there must be at least one element in the sequence (this element being an 'a' element or a 'b' element). Note Note that prime Type quantifier Type Type Type <: prime Type quantifier Type Semantics Finally, a type Type Type · = Type Type · = Type Type · = Type Type · = Type Introduction Function calls can perform type promotion between atomic types. This section introduces judgments which describe type promotion for the purpose of the dynamic and static semantics. These promotion rules include promoting xs:untypedAtomic Notation The judgment statEnv |- Type 1 can be promoted to Type 2 holds if type Type 1 Type 2 Example For example, the following judgments hold: xs:integer can be promoted to xs:integer xs:decimal can be promoted to xs:float xs:integer can be promoted to xs:float xs:float can be promoted to xs:double Semantics This judgment is specified by the following rules. xs:decimal xs:float statEnv |- xs:decimal can be promoted to xs:float xs:float xs:double statEnv |- xs:float can be promoted to xs:double xs:anyURI xs:string statEnv |- xs:anyURI can be promoted to xs:string xs:untypedAtomic statEnv |- Type <: xs:anyAtomicType statEnv |- xs:untypedAtomic can be promoted to Type A type can be promoted to itself or to any type of which it is a subtype: statEnv |- Type can be promoted to Type statEnv |- Type <: Type 1 statEnv |- Type can be promoted to Type 1 Type promotion is transitive: statEnv |- Type 1 can be promoted to Type 2 statEnv |- Type 2 can be promoted to Type 3 statEnv |- Type 1 can be promoted to Type 3 Finally, type promotion distributes over occurrence and union constructors. statEnv |- prime Type 1 can be promoted to prime Type 2 quantifier Type 1 quantifier Type 2 statEnv |- Type 1 can be promoted to Type 2 statEnv |- Type 1 can be promoted to Type statEnv |- Type 2 can be promoted to Type statEnv |- Type 1 Type 2 can be promoted to Type where the "<=" operator for occurrence indicators denotes set inclusion of the subsets of the allowed occurrences. Notation The judgment statEnv |- Value 1 against Type 2 promotes to Value 2 holds if value Value 1 Value 2 Type 2 Example For example, the following judgments hold 1 of type xs:integer against xs:integer promotes to 1 of type xs:integer 1 of type xs:integer against xs:decimal promotes to 1 of type xs:integer 1 of type xs:integer against xs:float promotes to 1.0e0 of type xs:float 1.0e0 of type xs:float against xs:double promotes to 1.0e0 of type xs:double Note that type promotion changes the value, and only occurs if the input value does not match the target type. Semantics This judgment is specified by the following rules. If the value matches the target type, then it is promoted to itself statEnv |- Value matches Type statEnv |- Value against Type promotes to Value If the value does not match the target type, but is an atomic value and it matches a type which can be promoted to the target type, then the value is cast to the target type. statEnv |- AtomicValue 1 matches AtomicType 1 statEnv |- AtomicType 1 can be promoted to AtomicType 2 AtomicType 1 AtomicType 2 AtomicValue 1 cast value to type AtomicType 2 => AtomicValue 2 statEnv |- AtomicValue 1 against AtomicType 2 promotes to AtomicValue 2 Notation A validation mode may occur explicitly in a validate expression [4.13 Validate Expressions] with mode The judgment statEnv |- ElementNameOrWildcard with mode ValidationMode resolves to Type holds when the possibly optional element name resolves to the given type in the given validation mode. Semantics We start with the rules for the global validation context. If no element name is present, the global validation context resolves to the union of all element types that are globally declared. statEnv |- ElementName 1 of elem/type expands to expanded-QName 1 ... statEnv |- ElementName n of elem/type expands to expanded-QName n statEnv elemDecl expanded-QName 1 ElementName 1 OptSubstitution 1 OptNillable 1 TypeReference 1 ... statEnv elemDecl expanded-QName n ElementName n OptSubstitution n OptNillable n TypeReference n statEnv |- with mode ValidationMode resolves to ElementName 1 ElementName n If the element name is globally declared in the schema, it resolves to the element type of the corresponding global element declaration, independently of the validation mode. statEnv |- ElementName of elem/type expands to expanded-QName statEnv elemDecl expanded-QName ElementName OptSubstitution OptNillable TypeReference statEnv |- ElementName with mode ValidationMode resolves to ElementName If an element name is not globally defined and the validation mode is lax, then the element name resolves to the element type with the given element name with any content type. statEnv |- ElementName of elem/type expands to expanded-QName statEnv elemDecl expanded-QName statEnv |- ElementName with mode resolves to ElementName xs:anyType This section contains the set of productions for the of [XPath/XQuery] grammar after it has been normalized, sometimes referred to as the "core" grammar, and for the formal grammar productions. The following grammar uses the same Basic EBNF notation as [XML] 99 IntegerLiteral ::= Digits 100 DecimalLiteral ::= ("." Digits Digits 101 DoubleLiteral ::= (("." Digits Digits Digits 102 StringLiteral ::= ('"' ( EscapeQuot EscapeApos 103 EscapeQuot ::= '""' 104 EscapeApos ::= "''" 105 ElementContentChar ::= Char 106 QuotAttrContentChar ::= Char 107 AposAttrContentChar ::= Char 108 PITarget ::= [http://www.w3.org/TR/REC-xml#NT-PITarget] XML 109 QName ::= [http://www.w3.org/TR/REC-xml-names/#NT-QName] Names 110 NCName ::= [http://www.w3.org/TR/REC-xml-names/#NT-NCName] Names 111 S ::= [http://www.w3.org/TR/REC-xml#NT-S] XML 112 Char ::= [http://www.w3.org/TR/REC-xml#NT-Char] XML 1 ModuleDecl ::= "module" "namespace" NCName URILiteral Separator 2 Separator ::= ";" 3 NamespaceDecl ::= "declare" "namespace" NCName URILiteral 4 DefaultNamespaceDecl ::= "declare" "default" ("element" | "function") "namespace" URILiteral 5 OptionDecl ::= "declare" "option" QName StringLiteral 6 OrderingModeDecl ::= "declare" "ordering" ("ordered" | "unordered") 7 EmptyOrderDecl ::= "declare" "default" "order" "empty" ("greatest" | "least") 8 CopyNamespacesDecl ::= "declare" "copy-namespaces" PreserveMode InheritMode 9 PreserveMode ::= "preserve" | "no-preserve" 10 InheritMode ::= "inherit" | "no-inherit" 11 DefaultCollationDecl ::= "declare" "default" "collation" URILiteral 12 BaseURIDecl ::= "declare" "base-uri" URILiteral 13 SchemaImport ::= "import" "schema" SchemaPrefix URILiteral URILiteral URILiteral 14 SchemaPrefix ::= ("namespace" NCName 15 ModuleImport ::= "import" "module" ("namespace" NCName URILiteral URILiteral URILiteral 16 VarDecl ::= "declare" "variable" "$" QName TypeDeclaration ExprSingle 17 ConstructionDecl ::= "declare" "construction" ("strip" | "preserve") 18 FunctionDecl ::= "declare" "function" QName ParamList SequenceType EnclosedExpr 19 ParamList ::= Param Param 20 Param ::= "$" QName TypeDeclaration 21 EnclosedExpr ::= "{" Expr 22 Expr ::= ExprSingle ExprSingle 23 ExprSingle ::= FLWORExpr QuantifiedExpr TypeswitchExpr IfExpr OrExpr 24 FLWORExpr ::= ( ForClause LetClause ExprSingle 25 ForClause ::= "for" "$" VarName TypeDeclaration PositionalVar ExprSingle 26 PositionalVar ::= "at" "$" VarName 27 LetClause ::= "let" "$" VarName TypeDeclaration ExprSingle 28 OrderByClause ::= (("order" "by") | ("stable" "order" "by")) OrderSpecList 29 OrderSpecList ::= OrderSpec OrderSpec 30 OrderSpec ::= ExprSingle OrderModifier 31 OrderModifier ::= ("ascending" | "descending")? ("empty" ("greatest" | "least"))? ("collation" URILiteral 32 QuantifiedExpr ::= ("some" | "every") "$" VarName TypeDeclaration ExprSingle VarName TypeDeclaration ExprSingle ExprSingle 33 TypeswitchExpr ::= "typeswitch" "(" Expr CaseClause VarName ExprSingle 34 CaseClause ::= "case" "$" VarName SequenceType ExprSingle 35 IfExpr ::= "if" "(" Expr ExprSingle ExprSingle 36 OrExpr ::= AndExpr AndExpr 37 AndExpr ::= CastableExpr CastableExpr 38 CastableExpr ::= CastExpr SingleType 39 CastExpr ::= ValueExpr SingleType 40 ValueExpr ::= ValidateExpr StepExpr ExtensionExpr 41 ValidateExpr ::= "validate" ValidationMode Expr 42 ValidationMode ::= "lax" | "strict" 43 ExtensionExpr ::= Pragma Expr 44 Pragma ::= "(#" S QName S PragmaContents 45 PragmaContents ::= ( Char 46 StepExpr ::= PrimaryExpr AxisStep 47 AxisStep ::= ReverseStep ForwardStep 48 ForwardStep ::= ForwardAxis NodeTest 49 ForwardAxis ::= ("child" "::") 50 ReverseStep ::= ReverseAxis NodeTest 51 ReverseAxis ::= ("parent" "::") 52 NodeTest ::= KindTest NameTest 53 NameTest ::= QName Wildcard 54 Wildcard ::= "*" NCName NCName 55 PrimaryExpr ::= Literal VarRef ParenthesizedExpr FunctionCall OrderedExpr UnorderedExpr Constructor 56 Literal ::= NumericLiteral StringLiteral 57 NumericLiteral ::= IntegerLiteral DecimalLiteral DoubleLiteral 58 VarRef ::= "$" VarName 59 VarName ::= QName 60 ParenthesizedExpr ::= "(" Expr 61 OrderedExpr ::= "ordered" "{" Expr 62 UnorderedExpr ::= "unordered" "{" Expr 63 FunctionCall ::= QName ExprSingle ExprSingle 64 Constructor ::= ComputedConstructor 65 ComputedConstructor ::= CompDocConstructor CompElemConstructor CompAttrConstructor CompTextConstructor CompCommentConstructor CompPIConstructor 66 CompDocConstructor ::= "document" "{" Expr 67 CompElemConstructor ::= "element" ( QName Expr ContentExpr LocalNamespaceDecls 68 LocalNamespaceDecl ::= "namespace" NCName URILiteral 69 ContentExpr ::= Expr 70 CompAttrConstructor ::= "attribute" ( QName Expr Expr 71 CompTextConstructor ::= "text" "{" Expr 72 CompCommentConstructor ::= "comment" "{" Expr 73 CompPIConstructor ::= "processing-instruction" ( NCName Expr Expr 74 SingleType ::= AtomicType 75 TypeDeclaration ::= "as" SequenceType 76 SequenceType ::= ("empty-sequence" "(" ")") ItemType OccurrenceIndicator 77 OccurrenceIndicator ::= "?" | "*" | "+" 78 ItemType ::= KindTest AtomicType 79 AtomicType ::= QName 80 KindTest ::= DocumentTest ElementTest AttributeTest SchemaElementTest SchemaAttributeTest PITest CommentTest TextTest AnyKindTest 81 AnyKindTest ::= "node" "(" ")" 82 DocumentTest ::= "document-node" "(" ( ElementTest SchemaElementTest 83 TextTest ::= "text" "(" ")" 84 CommentTest ::= "comment" "(" ")" 85 PITest ::= "processing-instruction" "(" ( NCName StringLiteral 86 AttributeTest ::= "attribute" "(" ( AttribNameOrWildcard TypeName 87 AttribNameOrWildcard ::= AttributeName 88 SchemaAttributeTest ::= "schema-attribute" "(" AttributeDeclaration 89 AttributeDeclaration ::= AttributeName 90 ElementTest ::= "element" "(" ( ElementNameOrWildcard TypeName 91 ElementNameOrWildcard ::= ElementName 92 SchemaElementTest ::= "schema-element" "(" ElementDeclaration 93 ElementDeclaration ::= ElementName 94 AttributeName ::= QName 95 ElementName ::= QName 96 TypeName ::= QName 97 URILiteral ::= StringLiteral 98 LocalNamespaceDecls ::= LocalNamespaceDecl 113 Digits ::= [0-9]+ The following grammar uses the same Basic EBNF notation as [XML] 96 HexDigits ::= [0-9a-fA-F]+ 97 CharRef ::= "&#" ( Digits HexDigits 98 Char ::= #x0009#x000D#x000A#x0020-#xFFFD 1 AtomicValueContent ::= String 2 TypeAnnotation ::= "of" "type" TypeName 3 ElementName ::= QName 4 ElementNameOrWildcard ::= QName 5 AttributeNameOrWildcard ::= QName 6 AttributeName ::= QName 7 Value ::= Item Value Value 8 SimpleValue ::= AtomicValue SimpleValue SimpleValue 9 ElementValue ::= "element" ElementName TypeAnnotation Value NamespaceBindings 10 AttributeValue ::= "attribute" AttributeName TypeAnnotation SimpleValue 11 DocumentValue ::= "document" "{" Value 12 TextValue ::= "text" "{" String "}" 13 CommentValue ::= "comment" "{" String "}" 14 ProcessingInstructionValue ::= "processing-instruction" NCName 15 NamespaceBindings ::= NamespaceBinding NamespaceBinding 16 LocationHints ::= "at" URILiteral URILiteral 17 NamespaceBinding ::= "namespace" NCName 18 Prefix ::= NCName 19 LocalPart ::= NCName 20 NodeValue ::= ElementValue AttributeValue DocumentValue TextValue CommentValue ProcessingInstructionValue 21 Item ::= NodeValue AtomicValue 22 AtomicValue ::= AtomicValueContent TypeAnnotation 23 TypeName ::= QName 24 Type ::= FormalItemType Type OccurrenceIndicator Type Type Type Type Type Type Type 25 FormalItemType ::= AtomicTypeName NodeType 26 NodeType ::= DocumentType AttributeType ElementContentType 27 ElementContentType ::= ElementType ProcessingInstructionType 28 AtomicTypeName ::= TypeName 29 ElementType ::= "element" ElementNameOrWildcard OptTypeSpecifier 30 TypeSpecifier ::= OptNillable TypeReference 31 AttributeType ::= "attribute" AttributeNameOrWildcard OptTypeReference 32 Nillable ::= "nillable" 33 TypeDerivation ::= ComplexTypeDerivation AtomicTypeDerivation 34 ComplexTypeDerivation ::= OptDerivation OptMixed Type 35 AtomicTypeDerivation ::= "restricts" AtomicTypeName 36 TypeReference ::= "of" "type" TypeName 37 Derivation ::= ("restricts" TypeName TypeName 38 Mixed ::= "mixed" 39 Definition ::= ("define" "element" ElementName OptSubstitution OptNillable TypeReference AttributeName TypeReference TypeName TypeDerivation 40 Definitions ::= ( Definition Separator Definitions 41 Substitution ::= "substitutes" "for" ElementName 42 AttributeModel ::= AttributeType AttributeType AttributeModel AttributeModel 43 ElementModel ::= ElementType ElementType ElementModel ElementModel 44 PrimeType ::= FormalItemType PrimeType PrimeType 45 DocumentType ::= "document" ("{" Type 46 SPragma ::= ("include" | "import" | "redefine" | "annotation")* 47 Content ::= (("simpleType" | "complexType" | "element" | "attribute" | "attributeGroup" | "group" | "notation") "annotation"*)* 48 MixedAttribute ::= "mixed" "=" Boolean 49 NillableAttribute ::= "nillable" "=" Boolean 50 substitutionGroupAttribute ::= "substitutionGroup" "=" QName 51 maxLength ::= "maxLength" "=" "nonNegativeInteger" 52 minLength ::= "minLength" "=" "nonNegativeInteger" 53 length ::= "length" "=" "nonNegativeInteger" 54 maxOccurs ::= "maxOccurs" "=" ("nonNegativeInteger" | "unbounded") 55 minOccurs ::= "minOccurs" "=" "nonNegativeInteger" 56 OccursAttributes ::= maxOccurs minOccurs maxLength minLength length 57 ComplexTypeContent ::= "annotation"? ("simpleContent" | "complexContent" | ( ChildrenContent AttributeContent 58 ChildrenContent ::= ("group" | "all" | "choice" | "sequence")? 59 GroupComponent ::= "element" | "group" | "choice" | "sequence" | "any" 60 AttributeContent ::= ("attribute" | "attributeGroup")* "anyAttribute"? 61 UseAttribute ::= "use" "=" ("optional" | "prohibited" | "required") 62 DefaultAttribute ::= "default" "=" String 63 FixedAttribute ::= "fixed" "=" String 64 PrincipalNodeKind ::= "element" | "attribute" | "namespace" 65 FormalFLWORClause ::= ForClause LetClause WhereClause OrderByClause 66 FormalReturnClause ::= FormalFLWORExpr Expr 67 FormalFLWORExpr ::= FormalFLWORClause FormalReturnClause 68 FormalCaseClauses ::= ( FormalCaseClause FormalCaseClauses FormalDefaultCaseClause 69 FormalCaseClause ::= "case" "$" VarName SequenceType Expr 70 FormalDefaultCaseClause ::= "default" "$" VarName Expr 71 PrologDeclList ::= ( PrologDecl Separator PrologDeclList 72 PrologDecl ::= DefaultCollationDecl BaseURIDecl ConstructionDecl OrderingModeDecl EmptyOrderDecl CopyNamespacesDecl SchemaImport ModuleImport NamespaceDecl DefaultNamespaceDecl VarDecl FunctionDecl OptionDecl 73 OptAtomicType ::= AtomicTypeName AtomicTypeName 74 OptMixed ::= Mixed 75 OptNillable ::= Nillable 76 OptSubstitution ::= Substitution 77 OptTypeSpecifier ::= TypeSpecifier 78 OptTypeReference ::= TypeReference 79 OptTypeDeclaration ::= TypeDeclaration 80 OptPositionalVar ::= PositionalVar 81 OptVarName ::= ("$" VarName 82 OptLocationHints ::= LocationHints 83 ElementContentUnit ::= DirectConstructor EnclosedExpr DirCharsUnit 84 DirCharsUnit ::= ( CDataSection PredefinedEntityRef CharRef ElementContentChar 85 FunctionSig ::= "declare" "function" expanded-QName "(" TypeList Type 86 TypeList ::= Type Type 87 AttributeContentUnits ::= AttributeContentUnit 88 AttributeContentUnit ::= AttributeCharsUnit EnclosedExpr 89 ConstructionMode ::= "preserve" | "strip" 90 Axis ::= ForwardAxis ReverseAxis 91 AttributeCharsUnit ::= ( QuotAttrContentChar AposAttrContentChar EscapeQuot EscapeApos PredefinedEntityRef CharRef 92 FunctionKey ::= expanded-QName "," Arity 93 ProcessingInstructionType ::= "processing-instruction" PITargetOrWildcard 94 PITargetOrWildcard ::= NCName 95 OptDerivation ::= Derivation Here is the list of the judgments defined in this specification. Main judgments: statEnv |- Expr : Type statEnv |- Expr : ext Type statEnv dynEnv |- Expr => Value Auxiliary judgments: statEnv |- Type 1 <: Type 2 statEnv |- AnyURI => module_statEnv statEnv statEnv |- AnyURI => module_dynEnv dynEnv statEnv 1 |- PrologDeclList => stat statEnv 2 with PrologDeclList 1 dynEnv 1 |- PrologDeclList => dyn dynEnv 2 statEnv 1 |- Definitions => type statEnv 2 dynEnv 1 AnyURI |- FunctionKey 1 FunctionSig 1 FunctionKey n FunctionSig n => import_functions dynEnv 2 dynEnv 1 AnyURI |- expanded-QName 1 Type 1 expanded-QName n Type n => import_variables dynEnv 2 statEnv |- OptMixed Type 1 adjusts to Type 2 statEnv |- Value 1 against Type 2 promotes to Value 2 dynEnv |- Value 1 against FormalCaseClauses => Value 2 statEnv |- annotate as Type Value 1 => Value 2 statEnv |- axis Axis of Type 1 : Type 2 dynEnv |- axis Axis of Value 1 => Value 2 statEnv |- Type 1 case FormalCaseClause : Type dynEnv |- Value can be cast to SingleType statEnv |- Type 1 can be promoted to Type 2 AtomicValue 1 cast value to type AtomicType => AtomicValue 2 statEnv |- data on Type 1 : Type 2 statEnv |- expanded-QName denotes a constructor function statEnv |- Value 1 erases to Value 2 statEnv |- TypeSpecifier expands to Type statEnv |- Type 1 extended by Type 2 is Type dynEnv 1 extended with dynamic environment dynEnv 2 yields dynEnv 3 for uri AnyURI statEnv 1 extended with static environment statEnv 2 yields statEnv 3 for uri AnyURI Value filter QName => absent statEnv |- function declaration FunctionDecl with signature FunctionSig : Type r dynEnv |- function expanded-QName with types Type 1 Type n on values Value 1 Value n yields Value dynEnv |- LiteralExpr has atomic value AtomicValue statEnv |- Type 1 has attribute content Type 2 AtomicTypeName 1 has base atomic type AtomicTypeName 2 statEnv |- Type 1 has node content Type 2 Axis has principal PrincipalNodeKind statEnv |- inheritance due to OptDerivation is Type statEnv |- Value 1 interleave Value 2 yields Value 3 AnyURI is target namespace of modules Module 1 Module n statEnv |- Value matches Type statEnv |- Type 1 mixes to Type 2 statEnv |- ElementName name lookup ElementType yields OptNillable TypeReference statEnv |- AttributeName name lookup AttributeType yields TypeReference statEnv |- nil-annotate as Nillable Type Value 1 => Value 2 statEnv |- QName of attr expands to expanded-QName statEnv |- QName of elem/type expands to expanded-QName statEnv |- QName of func expands to expanded-QName statEnv |- QName of var expands to Variable expanded-QName operator type for AtomicType 1 and AtomicType 2 is AtomicType 3 statEnv |- OptMixed Type 1 opt-mixes to Type 2 statEnv |- TypeReference resolves to TypeName Type second argument contribution for sum with Type 1 and Type 2 is Type 3 statEnv |- simply annotate as SimpleType SimpleValue => SimpleValue 2 statEnv |- SimpleValue simply erases to String statEnv |- ElementName 1 substitutes for ElementName 2 statEnv |- AttributeType type lookup TypeReference statEnv |- ElementType type lookup OptNillable TypeReference statEnv |- test NodeTest with PrincipalNodeKind of Type 1 : Type 2 dynEnv |- test NodeTest with PrincipalNodeKind of Value 1 => Value 2 statEnv |- type definitions derived from TypeName are Definition 1 Definition n statEnv |- union interpretation of Definition is Type U statEnv |- ElementNameOrWildcard with mode ValidationMode resolves to Type Value 0 with text nodes processed is Value 1 Here is the list of functions from the [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] Section 10.6.6 op:add-dayTimeDurations FO Section 10.8.5 op:add-dayTimeDuration-to-dateTime FO Section 10.8.9 op:add-dayTimeDuration-to-date FO Section 10.8.12 op:add-dayTimeDuration-to-time FO Section 10.6.1 op:add-yearMonthDurations FO Section 10.8.4 op:add-yearMonthDuration-to-dateTime FO Section 10.8.8 op:add-yearMonthDuration-to-date FO Section 9.2.1 op:boolean-equal FO Section 9.2.3 op:boolean-greater-than FO Section 9.2.2 op:boolean-less-than FO Section 15.1.1 fn:boolean FO Section 7.3.2 fn:compare FO Section 15.1.2 op:concatenate FO Section 15.4.1 fn:count FO Section 10.4.6 op:dateTime-equal FO Section 10.4.8 op:dateTime-greater-than FO Section 10.4.7 op:dateTime-less-than FO Section 10.4.4 op:dayTimeDuration-greater-than FO Section 10.4.3 op:dayTimeDuration-less-than FO Section 10.6.9 op:divide-dayTimeDuration FO Section 10.6.4 op:divide-yearMonthDuration FO Section 2.4 fn:data FO Section 15.1.4 fn:empty FO Section 3 The Error Function FO Section 15.3.4 op:except FO Section 9.1.2 fn:false FO Section 15.3.3 op:intersect FO Section 14.6 op:is-same-node FO Section 16.2 fn:last FO Section 10.6.8 op:multiply-dayTimeDuration FO Section 10.6.3 op:multiply-yearMonthDuration FO Section 14.8 op:node-after FO Section 14.7 op:node-before FO Section 13.1.1 op:NOTATION-equal FO Section 9.3.1 fn:not FO Section 6.2.1 op:numeric-add FO Section 6.2.4 op:numeric-divide FO Section 6.3.1 op:numeric-equal FO Section 6.3.3 op:numeric-greater-than FO Section 6.3.2 op:numeric-less-than FO Section 6.2.6 op:numeric-mod FO Section 6.2.3 op:numeric-multiply FO Section 6.2.2 op:numeric-subtract FO Section 6.2.8 op:numeric-unary-minus FO Section 6.2.7 op:numeric-unary-plus FO Section 16.1 fn:position FO Section 11.2.1 op:QName-equal FO Section 14.9 fn:root FO Section 6.4.4 fn:round FO Section 7.4.2 fn:string-join FO Section 10.8.7 op:subtract-dayTimeDuration-from-dateTime FO Section 10.8.11 op:subtract-dayTimeDuration-from-date FO Section 10.8.13 op:subtract-dayTimeDuration-from-time FO Section 10.6.7 op:subtract-dayTimeDurations FO Section 10.8.6 op:subtract-yearMonthDuration-from-dateTime FO Section 10.8.10 op:subtract-yearMonthDuration-from-date FO Section 10.6.2 op:subtract-yearMonthDurations FO Section 15.5.1 op:to FO Section 9.1.1 fn:true FO Section 15.3.2 op:union FO Section 10.4.2 op:yearMonthDuration-greater-than FO Section 10.4.1 op:yearMonthDuration-less-than FO This section gives the semantics specific to overloaded internal functions (with prefix fs: op: [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] Notation The following auxiliary grammar production describe optional atomic types. 73 (Formal) OptAtomicType ::= AtomicTypeName AtomicTypeName Static Type Analysis The following static typing rules apply generically to all the fs: [4.1.5 Function Calls] First, if the static type of one or several of the expressions passed as argument is a union of atomic types, the function call is type checked once separately for each atomic type in that union. The static type of the entire function call expression is then the union of the types computed in each case. Type 1 OptAtomicType 1 ,1 OptAtomicType m ,1 ... Type n OptAtomicType 1 ,n OptAtomicType m ,n statEnv |- expanded-QName OptAtomicType 1 ,1 OptAtomicType 1 ,n : OptAtomicType 1 ... statEnv |- expanded-QName OptAtomicType m ,1 OptAtomicType m ,n : OptAtomicType r statEnv |- expanded-QName Type 1 Type n : OptAtomicType 1 OptAtomicType r Note Note that this approach can be used since the type declared for a function parameter is never itself be a union. The following rules deal with optional arguments. In the case of binary operators, if either one of the types of the operands is empty, the resulting type is empty. Type 1 statEnv |- expanded-QName Type 1 Type 2 : Type 2 statEnv |- expanded-QName Type 1 Type 2 : If either one of the types of the operands is optional, the type obtained by propagating the optional occurrence indicator. Type 1 AtomicType 1 Type 2 AtomicType 2 statEnv |- expanded-QName AtomicType 1 AtomicType 2 : AtomicType 3 statEnv |- expanded-QName Type 1 Type 2 : AtomicType 3 Type 1 AtomicType 1 Type 2 AtomicType 2 statEnv |- expanded-QName AtomicType 1 AtomicType 2 : AtomicType 3 statEnv |- expanded-QName Type 1 Type 2 : AtomicType 3 Type 1 AtomicType 1 Type 2 AtomicType 2 statEnv |- expanded-QName AtomicType 1 AtomicType 2 : AtomicType 3 statEnv |- expanded-QName Type 1 Type 2 : AtomicType 3 In the case of unary operators, if the type of the operand is empty, the resulting type is empty. Type 1 statEnv |- expanded-QName Type 1 : Finally, the resulting type is obtained by performing type promotion and accessing the operators mapping table (using the operator type for statEnv |- AtomicType 1 can be promoted to AtomicType 1 statEnv |- AtomicType 2 can be promoted to AtomicType 2 expanded-QName operator type for AtomicType 1 and AtomicType 2 is AtomicType 3 statEnv |- expanded-QName AtomicType 1 AtomicType 2 : AtomicType 3 statEnv |- AtomicType 1 can be promoted to AtomicType 1 expanded-QName operator type for AtomicType 1 is AtomicType 3 statEnv |- expanded-QName AtomicType 1 : AtomicType 3 Dynamic Evaluation Each fs: op: [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] The dynamic semantics of the fs: declare function fs:opname ($x1 as xs:anyAtomicType?, $x2 as xs:anyAtomicType?) as xs:anyAtomicType? { if (fn:empty($x1) or fn:empty($x2)) then () else [ fs:opname($x1,$x2) ] OverloadedOp }; Where [ fs:opname() ] OverloadedOp [XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition)] Notation The operators mapping table is given below. The table is used to define the following auxiliary mapping rules and judgments. The mapping rule for binary and unary operators [ fs:opname1 Expr 1 Expr 2 ] OverloadedOp op:opname2 Expr 1 Expr 2 and [ fs:opname1 Expr 1 ] OverloadedOp op:opname2 Expr 1 where the operator depends on the type of each value returned by Expr 1 Expr 2 The judgments for binary and unary operators expanded-QName operator type for AtomicType 1 and AtomicType 2 is AtomicType 3 and expanded-QName operator type for AtomicType 1 is AtomicType 3 hold when the operator table indicates that the operator expanded-QName AtomicType 3 AtomicType 1 AtomicType 2 Note that in the following table, all numeric functions are applied to operands with the same type. Values are promoted to compatible types using the function call semantics given in [4.1.5 Function Calls] Gregorian xs:gYearMonth xs:gYear xs:gMonthDay xs:gDay xs:gMonth xs:gDay xs:gDay Binary Operators Internal Function AtomicType 1 AtomicType 2 Denotes AtomicType 3 fs: plus xs:integer xs:integer op:numeric-add(A, B) xs:integer fs: plus xs:decimal xs:decimal op:numeric-add(A, B) xs:decimal fs: plus xs:float xs:float op:numeric-add(A, B) xs:float fs: plus xs:double xs:double op:numeric-add(A, B) xs:double fs: plus xs:date xs:yearMonthDuration op:add-yearMonthDuration-to-date(A, B) xs:date fs: plus xs:yearMonthDuration xs:date op:add-yearMonthDuration-to-date(B, A) xs:date fs: plus xs:date xs:dayTimeDuration op:add-dayTimeDuration-to-date(A, B) xs:date fs: plus xs:dayTimeDuration xs:date op:add-dayTimeDuration-to-date(B, A) xs:date fs: plus xs:time xs:dayTimeDuration op:add-dayTimeDuration-to-time(A, B) xs:time fs: plus xs:dayTimeDuration xs:time op:add-dayTimeDuration-to-time(B, A) xs:time fs: plus xs:dateTime xs:yearMonthDuration op:add-yearMonthDuration-to-dateTime(A, B) xs:dateTime fs: plus xs:yearMonthDuration xs:dateTime op:add-yearMonthDuration-to-dateTime(B, A) xs:dateTime fs: plus xs:dateTime xs:dayTimeDuration op:add-dayTimeDuration-to-dateTime(A, B) xs:dateTime fs: plus xs:dayTimeDuration xs:dateTime op:add-dayTimeDuration-to-dateTime(B, A) xs:dateTime fs: plus xs:yearMonthDuration xs:yearMonthDuration op:add-yearMonthDurations(A, B) xs:yearMonthDuration fs: plus xs:dayTimeDuration xs:dayTimeDuration op:add-dayTimeDurations(A, B) xs:dayTimeDuration fs: minus xs:integer xs:integer op:numeric-subtract(A, B) xs:integer fs: minus xs:decimal xs:decimal op:numeric-subtract(A, B) xs:decimal fs: minus xs:float xs:float op:numeric-subtract(A, B) xs:float fs: minus xs:double xs:double op:numeric-subtract(A, B) xs:double fs: minus xs:date xs:date op:subtract-dates(A, B) xs:dayTimeDuration fs: minus xs:date xs:yearMonthDuration op:subtract-yearMonthDuration-from-date(A, B) xs:date fs: minus xs:date xs:dayTimeDuration op:subtract-dayTimeDuration-from-date(A, B) xs:date fs: minus xs:time xs:time op:subtract-times(A, B) xs:dayTimeDuration fs: minus xs:time xs:dayTimeDuration op:subtract-dayTimeDuration-from-time(A, B) xs:time fs: minus xs:dateTime xs:dateTime op:subtract-dateTimes(A, B) xs:dayTimeDuration fs: minus xs:dateTime xs:yearMonthDuration op:subtract-yearMonthDuration-from-dateTime(A, B) xs:dateTime fs: minus xs:dateTime xs:dayTimeDuration op:subtract-dayTimeDuration-from-dateTime(A, B) xs:dateTime fs: minus xs:yearMonthDuration xs:yearMonthDuration op:subtract-yearMonthDurations(A, B) xs:yearMonthDuration fs: minus xs:dayTimeDuration xs:dayTimeDuration op:subtract-dayTimeDurations(A, B) xs:dayTimeDuration fs: times xs:integer xs:integer op:numeric-multiply(A, B) xs:integer fs: times xs:decimal xs:decimal op:numeric-multiply(A, B) xs:decimal fs: times xs:float xs:float op:numeric-multiply(A, B) xs:float fs: times xs:double xs:double op:numeric-multiply(A, B) xs:double fs: times xs:yearMonthDuration xs:double op:multiply-yearMonthDuration(A, B) xs:yearMonthDuration fs: times xs:double xs:yearMonthDuration op:multiply-yearMonthDuration(B, A) xs:yearMonthDuration fs: times xs:dayTimeDuration xs:double op:multiply-dayTimeDuration(A, B) xs:dayTimeDuration fs: times xs:double xs:dayTimeDuration op:multiply-dayTimeDuration(B, A) xs:dayTimeDuration fs: idiv xs:integer xs:integer op:numeric-integer-divide(A, B) xs:integer fs: idiv xs:decimal xs:decimal op:numeric-integer-divide(A, B) xs:integer fs: idiv xs:float xs:float op:numeric-integer-divide(A, B) xs:integer fs: idiv xs:double xs:double op:numeric-integer-divide(A, B) xs:integer fs: div xs:integer xs:integer op:numeric-divide(A, B) xs:decimal fs: div xs:decimal xs:decimal op:numeric-divide(A, B) xs:decimal fs: div xs:float xs:float op:numeric-divide(A, B) xs:float fs: div xs:double xs:double op:numeric-divide(A, B) xs:double fs: div xs:yearMonthDuration xs:double op:divide-yearMonthDuration(A, B) xs:yearMonthDuration fs: div xs:dayTimeDuration xs:double op:divide-dayTimeDuration(A, B) xs:dayTimeDuration fs: div xs:yearMonthDuration xs:yearMonthDuration op:divide-yearMonthDuration-by-yearMonthDuration(A, B) xs:decimal fs: div xs:dayTimeDuration xs:dayTimeDuration op:divide-dayTimeDuration-by-dayTimeDuration(A, B) xs:decimal fs: mod xs:integer xs:integer op:numeric-mod(A, B) xs:integer fs: mod xs:decimal xs:decimal op:numeric-mod(A, B) xs:decimal fs: mod xs:float xs:float op:numeric-mod(A, B) xs:float fs: mod xs:double xs:double op:numeric-mod(A, B) xs:double fs: eq xs:integer xs:integer op:numeric-equal(A, B) xs:boolean fs: eq xs:decimal xs:decimal op:numeric-equal(A, B) xs:boolean fs: eq xs:float xs:float op:numeric-equal(A, B) xs:boolean fs: eq xs:double xs:double op:numeric-equal(A, B) xs:boolean fs: eq xs:boolean xs:boolean op:boolean-equal(A, B) xs:boolean fs: eq xs:string xs:string op:numeric-equal(fn:compare(A, B), 0) xs:boolean fs: eq xs:date xs:date op:date-equal(A, B) xs:boolean fs: eq xs:time xs:time op:time-equal(A, B) xs:boolean fs: eq xs:dateTime xs:dateTime op:dateTime-equal(A, B) xs:boolean fs: eq xs:duration xs:duration op:duration-equal(A, B) xs:boolean fs: eq Gregorian Gregorian op:gYear-equal(A, B) etc. xs:boolean fs: eq xs:hexBinary xs:hexBinary op:hexBinary-equal(A, B) xs:boolean fs: eq xs:base64Binary xs:base64Binary op:base64Binary-equal(A, B) xs:boolean fs: eq xs:anyURI xs:anyURI op:numeric-equal(fn:compare(A, B), 0) xs:boolean fs: eq xs:QName xs:QName op:QName-equal(A, B) xs:boolean fs: eq xs:NOTATION xs:NOTATION op:NOTATION-equal(A, B) xs:boolean fs: ne xs:integer xs:integer fn:not xs:boolean fs: ne xs:decimal xs:decimal fn:not xs:boolean fs: ne xs:float xs:float fn:not xs:boolean fs: ne xs:double xs:double fn:not xs:boolean fs: ne xs:boolean xs:boolean fn:not xs:boolean fs: ne xs:string xs:string fn:not xs:boolean fs: ne xs:date xs:date fn:not xs:boolean fs: ne xs:time xs:time fn:not xs:boolean fs: ne xs:dateTime xs:dateTime fn:not xs:boolean fs: ne xs:duration xs:duration fn:not xs:boolean fs: ne Gregorian Gregorian fn:not xs:boolean fs: ne xs:hexBinary xs:hexBinary fn:not xs:boolean fs: ne xs:base64Binary xs:base64Binary fn:not xs:boolean fs: ne xs:anyURI xs:anyURI fn:not xs:boolean fs: ne xs:QName xs:QName fn:not xs:boolean fs: ne xs:NOTATION xs:NOTATION fn:not xs:boolean fs: gt xs:integer xs:integer op:numeric-greater-than(A, B) xs:boolean fs: gt xs:decimal xs:decimal op:numeric-greater-than(A, B) xs:boolean fs: gt xs:float xs:float op:numeric-greater-than(A, B) xs:boolean fs: gt xs:double xs:double op:numeric-greater-than(A, B) xs:boolean fs: gt xs:boolean xs:boolean op:boolean-greater-than(A, B) xs:boolean fs: gt xs:string xs:string op:numeric-greater-than( fn:compare xs:boolean fs: gt xs:date xs:date op:date-greater-than(A, B) xs:boolean fs: gt xs:time xs:time op:time-greater-than(A, B) xs:boolean fs: gt xs:dateTime xs:dateTime op:dateTime-greater-than(A, B) xs:boolean fs: gt xs:yearMonthDuration xs:yearMonthDuration op:yearMonthDuration-greater-than(A, B) xs:boolean fs: gt xs:dayTimeDuration xs:dayTimeDuration op:dayTimeDuration-greater-than(A, B) xs:boolean fs: lt xs:integer xs:integer op:numeric-less-than(A, B) xs:boolean fs: lt xs:decimal xs:decimal op:numeric-less-than(A, B) xs:boolean fs: lt xs:float xs:float op:numeric-less-than(A, B) xs:boolean fs: lt xs:double xs:double op:numeric-less-than(A, B) xs:boolean fs: lt xs:boolean xs:boolean op:boolean-less-than(A, B) xs:boolean fs: lt xs:string xs:string op:numeric-less-than( fn:compare xs:boolean fs: lt xs:date xs:date op:date-less-than(A, B) xs:boolean fs: lt xs:time xs:time op:time-less-than(A, B) xs:boolean fs: lt xs:dateTime xs:dateTime op:dateTime-less-than(A, B) xs:boolean fs: lt xs:yearMonthDuration xs:yearMonthDuration op:yearMonthDuration-less-than(A, B) xs:boolean fs: lt xs:dayTimeDuration xs:dayTimeDuration op:dayTimeDuration-less-than(A, B) xs:boolean fs: ge xs:integer xs:integer op:numeric-greater-than(A, B) or op:numeric-equal(A,B) xs:boolean fs: ge xs:decimal xs:decimal op:numeric-greater-than(A, B) or op:numeric-equal(A,B) xs:boolean fs: ge xs:float xs:float op:numeric-greater-than(A, B) or op:numeric-equal(A,B) xs:boolean fs: ge xs:double xs:double op:numeric-greater-than(A, B) or op:numeric-equal(A,B) xs:boolean fs: ge xs:boolean xs:boolean op:numeric-greater-than(A, B) or op:numeric-equal(A,B) xs:boolean fs: ge xs:string xs:string op:numeric-greater-than( fn:compare xs:boolean fs: ge xs:date xs:date op:date-less-than(B, A) xs:boolean fs: ge xs:time xs:time op:time-less-than(B, A) xs:boolean fs: ge xs:dateTime xs:dateTime op:dateTime-less-than(B, A) xs:boolean fs: ge xs:yearMonthDuration xs:yearMonthDuration op:yearMonthDuration-less-than(B, A) xs:boolean fs: ge xs:dayTimeDuration xs:dayTimeDuration op:dayTimeDuration-less-than(B, A) xs:boolean fs: le xs:integer xs:integer op:numeric-less-than(A, B) or op:numeric-equal(A,B) xs:boolean fs: le xs:decimal xs:decimal op:numeric-less-than(A, B) or op:numeric-equal(A,B) xs:boolean fs: le xs:float xs:float op:numeric-less-than(A, B) or op:numeric-equal(A,B) xs:boolean fs: le xs:double xs:double op:numeric-less-than(A, B) or op:numeric-equal(A,B) xs:boolean fs: le xs:boolean xs:boolean op:numeric-less-than(A, B) or op:numeric-equal(A,B) xs:boolean fs: le xs:string xs:string op:numeric-less-than( fn:compare xs:boolean fs: le xs:date xs:date op:date-greater-than(B, A) xs:boolean fs: le xs:time xs:time op:time-greater-than(B, A) xs:boolean fs: le xs:dateTime xs:dateTime op:dateTime-greater-than(B, A) xs:boolean fs: le xs:yearMonthDuration xs:yearMonthDuration op:yearMonthDuration-greater-than(B, A) xs:boolean fs: le xs:dayTimeDuration xs:dayTimeDuration op:dayTimeDuration-greater-than(B, A) xs:boolean fs: is-same-node node() node() op:is-same-node xs:boolean fs: node-before node() node() op:node-before xs:boolean fs: node-after node() node() op:node-after xs:boolean Unary Operators Internal Function AtomicType 1 Denotes AtomicType 3 fs: unary-plus xs:integer op:numeric-unary-plus(A) xs:integer fs: unary-plus xs:decimal op:numeric-unary-plus(A) xs:decimal fs: unary-plus xs:float op:numeric-unary-plus(A) xs:float fs: unary-plus xs:double op:numeric-unary-plus(A) xs:double fs: unary-minus xs:integer op:numeric-unary-minus(A) xs:integer fs: unary-minus xs:decimal op:numeric-unary-minus(A) xs:decimal fs: unary-minus xs:float op:numeric-unary-minus(A) xs:float fs: unary-minus xs:double op:numeric-unary-minus(A) xs:double This section describes how XML Schema declarations, as specified by XML Schema are imported into the [XPath/XQuery] type system. During schema import processing, the [XPath/XQuery] environment imports XML Schema declarations and loads them as declarations in the [XPath/XQuery] type system. The semantics of that loading process is defined by normalization rules that map XML Schema descriptions into the [XPath/XQuery] type system. Here is summarized the XML Schema features which are covered by the formal semantics, and handled by the import mapping described in this section. For each feature, the following indications are used. Handled Not in v1.0 mapping only Not handled Ignored Here is the exhaustive list of XML Schema features and their status in this document. Feature: Supported Primitive Simple types Handled Simple type derivation by restriction Handled Derivation by list and union Handled Facets on simple types Not handled ID and IDREF constraints Ignored Attribute Declarations default,fixed,use Not in v1.0 Element Declarations default, fixed (value constraint) Not in v1.0 nillable Handled substitution group affiliation Handled substitution group exclusions Ignored disallowed substitutions Ignored abstract Not in v1.0 Complex Type Definitions derivation by restriction Handled derivation by extension Handled final Ignored abstract Not in v1.0 AttributeUses required Not in v1.0, mapping only default, fixed (value constraint) Not in v1.0 Attribute Group Definitions Not in v1.0, mapping only Model Group Definitions Not in v1.0, mapping only Model Groups Handled Particles Handled Wildcards process contents strict, skip, lax Ignored namespace wild cards. Ignored Identity-constraint Definitions Ignored Notation Declarations Ignored Annotations Ignored Note that the schema import feature specified here assumes it is given a legal schema as input. As a result, it is not necessary to check for 'block' or 'abstract' attributes. The presentation of the schema mapping is done according to the following organization. Schema component First each schema component is summarized using the same notation used in the XML Representation Summary sections in XML Schema. For instance, here is the XML Representation Summary for complex types. <complexType [ ignored ] [ ignored ] [ ignored ] [ ignored ] mixed = boolean : false name = NCName [ ignored ] Content: (annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, ((schemaAttribute | schemaAttributeGroup)*, anySchemaAttribute?)))) </complexType> Attributes indicated as [ ignored ] Attributes indicated as [ not handled ] Note that in order to simplify the mapping, it is assumed that the default values for all attributes in the XML Representation of Schema are filled in. For instance in the above complex type, if the mixed "false" Schema mapping XML Schema import is specified by means of mapping rules. All mapping rules have the structure below. [ SchemaComponent ] Subscript == TypeComponent The SchemaComponent TypeComponent Notation Whenever necessary for the mapping rules, specific grammar productions which describe fragments of XML Schema may be introduced. For instance, here are grammar productions used to describes fragments of the XML Representation Summary for the complexType Element Information Item. 57 (Formal) ComplexTypeContent ::= "annotation"? ("simpleContent" | "complexContent" | ( ChildrenContent AttributeContent 60 (Formal) AttributeContent ::= ("attribute" | "attributeGroup")* "anyAttribute"? 58 (Formal) ChildrenContent ::= ("group" | "all" | "choice" | "sequence")? As in the rest of this document, some mapping rules may use fragments of the XML Representation corresponding to the syntactic categories defined by those grammar productions. For instance, the following complex type fragment uses the syntactic categories: TypeName ComplexTypeContent AttributeContent ChildrenContent MixedAttribute <complexType name = TypeName MixedAttribute ChildrenContent AttributeContent </complexType> Notation The normalization rule [ Schema ] Schema == Definitions maps a complete schema into a set of Definitions The normalization rule [ SchemaComponent ] definition( target NCName == Definition maps a top level schema component into a Definition target AnyURI The normalization rule [ SchemaComponent ] content( target NCName == TypeComponent maps a schema component not directly under the schema element, into a TypeComponent target AnyURI The XML Schema attributes: use, default, fixed, minOccurs, maxOccurs, mixed, nillable, and substitutionGroup, require specific mapping rules. The "use", "default", and "fixed" attributes are used to describe the occurrence and default behavior of a given attribute. Notation The following auxiliary grammar productions are used to describe the "use", "default", and "fixed" attributes. 61 (Formal) UseAttribute ::= "use" "=" ("optional" | "prohibited" | "required") 62 (Formal) DefaultAttribute ::= "default" "=" String 63 (Formal) FixedAttribute ::= "fixed" "=" String The normalization rule [ UseAttribute DefaultAttribute FixedAttribute ] use == OccurrenceIndicator maps a combination of a use attribute UseAttribute OccurrenceIndicator Schema mapping Use attributes are mapped to the type system in the following way. In case there is a default or fixed attribute, the attribute is always present in the PSVI and the use attribute is ignored. UseAttribute DefaultAttribute use == 1 UseAttribute FixedAttribute use == 1 use = "optional" use == ? use = "required" use == 1 Editorial note Issue: how derivation of attribute declaration and the "prohibited" use attributes are mapped in the [XPath/XQuery] type system is still an open issue. Notation The following auxiliary grammar productions are used to describe occurrence attributes and the length facets. 56 (Formal) OccursAttributes ::= maxOccurs minOccurs maxLength minLength length 54 (Formal) maxOccurs ::= "maxOccurs" "=" ("nonNegativeInteger" | "unbounded") 55 (Formal) minOccurs ::= "minOccurs" "=" "nonNegativeInteger" 51 (Formal) maxLength ::= "maxLength" "=" "nonNegativeInteger" 52 (Formal) minLength ::= "minLength" "=" "nonNegativeInteger" 53 (Formal) length ::= "length" "=" "nonNegativeInteger" The normalization rule [ OccursAttributes ] occurs == OccurrenceIndicator maps the occurrence attributes and facets OccursAttributes OccurrenceIndicator Schema mapping Occurrence attributes are mapped to the type system in the following way. [ ] occurs == ? [ ] occurs == [ ] occurs == * [ ] occurs == + where n > 1. [ ] occurs == + where m >= n > 1 [ ] occurs == ? [ ] occurs == [ ] occurs == * [ ] occurs == + where n > 1. [ ] occurs == + where m >= n > 1 [ ] occurs == [ ] occurs == + where n > 1 Notation The following auxiliary grammar productions are used to describe the "mixed" attribute. 48 (Formal) MixedAttribute ::= "mixed" "=" Boolean The normalization rule [ MixedAttribute ] mixed == Mixed maps the mixed attribute MixedAttribute Mixed Schema mapping If the mixed attribute is true it is mapped to a mixed notation in the [XPath/XQuery] type system. [ ] mixed == mixed If the mixed attribute is false it is mapped to empty in the [XPath/XQuery] type system. [ ] mixed == Notation The following auxiliary grammar productions are used to describe the "nillable" attribute. 49 (Formal) NillableAttribute ::= "nillable" "=" Boolean The normalization rule [ NillableAttribute ] nillable == Nillable maps the nillable attribute NillableAttribute Nillable Schema mapping If the nillable attribute is true it is mapped to a nillable notation in the [XPath/XQuery] type system. [ ] nillable == nillable If the nillable attribute is false it is mapped to empty in the [XPath/XQuery] type system. [ ] nillable == Notation The substitution group declaration indicates the element that a given element can be substituted for. The following auxiliary grammar productions are used to describe the "substitutionGroup" attribute. 50 (Formal) substitutionGroupAttribute ::= "substitutionGroup" "=" QName The normalization rule [ substitutionGroupAttribute ] substitution == Substitution maps the substitutionGroup attribute substitutionGroupAttribute Substitution Schema mapping If the substitutionGroup attribute is present, it is mapped to a substitutionGroup notation in the [XPath/XQuery] type system. [ QName ] substitution == substitutes for QName Otherwise, it is mapped to empty. Notation As explained in [2.4 The [XPath/XQuery] Type System] Schema component A schema is represented in XML by the following structure. <schema [ not handled ] [ ignored ] [ not handled ] [ ignored ] [ ignored ] targetNamespace = anyURI [ ignored ] [ ignored ] [ ignored ] Content: ((include | import | redefine | annotation)*, (((simpleType | complexType | group | attributeGroup) | element | attribute | notation), annotation*)*) </schema> Notation The following auxiliary grammar productions are used. 46 (Formal) SPragma ::= ("include" | "import" | "redefine" | "annotation")* 47 (Formal) Content ::= (("simpleType" | "complexType" | "element" | "attribute" | "attributeGroup" | "group" | "notation") "annotation"*)* The auxiliary normalization rule [ Pragma ] pragma( target AnyURI == Definitions maps the a schema pragma into a set of definitions in the [XPath/XQuery] type system. Schema mapping Schemas are imported by the "schema" declaration in the preamble of a query. To import a schema, the document referred to by the given URI is opened and the schema declarations contained in the document are translated into the corresponding in-line type definitions. The mechanism for finding a schema document, possibly using the optional schema location hint, is not specified formally. [ StringLiteral StringLiteral ] Schema == [ StringLiteral StringLiteral ] Schema [ <schema targetNamespace = target AnyURI Pragma Content </schema> ] Schema == [ Pragma ] pragma( target AnyURI [ Content ] definition( target NCName Schema component A schema include is represented in XML by the following structure. <include [ ignored ] schemaLocation = anyURI [ ignored ] Content: (annotation?) </include> Schema mapping A schema include is not specified here, and is assumed to be handled by the XML Schema processor. Schema component A schema redefinition is represented in XML by the following structure. <redefine [ ignored ] schemaLocation = anyURI [ ignored ] Content: (annotation | (simpleType | complexType | group | attributeGroup))* </redefine> Schema mapping A schema redefine is not specified here, and is assumed to be handled by the XML Schema processor. Schema component A schema import is represented in XML by the following structure. <import [ ignored ] namespace = anyURI schemaLocation = anyURI [ ignored ] Content: (annotation?) </import> Schema mapping A schema import is not specified here, and is assumed to be handled by the XML Schema processor. Schema component The following structure describes attribute declarations in XML Schema. <attribute [ not handled ] [ not handled ] [ not handled ] [ ignored ] name = NCName ref = QName type = QName use = (optional | prohibited | required) : optional [ ignored ] Content: (annotation?, (simpleType?)) </attribute> Schema import distinguishes between global attribute declarations and local attribute declarations. Schema mapping Global attribute declarations are mapped like local attribute declarations, but are prefixed by a "define" keyword in the [XPath/XQuery] type system. [ AttributeDecl ] definition( target NCName == define [ AttributeDecl ] content( target NCName Schema mapping Local attributes whose type is given by a reference to a global type name are mapped in the type system as follows. [ <attribute name = NCName type = QName UseAttribute ] content( target NCName == ( attribute target NCName NCName QName [ UseAttribute ] use References to a global attribute are mapped in the type system as follows. [ <attribute ref = QName UseAttribute ] content( target NCName == ( attribute QName [ UseAttribute ] use A local attribute with a local content is mapped to the [XPath/XQuery] type system as follows. Let fs: k [ <attribute name = NCName UseAttribute simpleType </attribute> ] content( target NCName == ( attribute target NCName NCName fs: k [ UseAttribute ] use with define type fs: k [ simpleType ] content( target NCName Schema component The following structure describes attribute declarations in XML Schema. <element [ ignored ] [ ignored ] [ not handled ] [ ignored ] [ not handled ] [ not handled ] [ ignored ] maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 name = NCName nillable = boolean : false ref = QName substitutionGroup = QName type = QName [ ignored ] Content: (annotation?, ((simpleType | complexType)?, (unique | key | keyref)*)) </element> Schema import distinguishes between global element declarations and local element declarations. Schema mapping Global element declarations are mapped like local element declarations, but are prefixed by a "define" keyword in the [XPath/XQuery] type system. [ <element name = NCName NillableAttribute substitutionGroupAttribute type = QName ] definition( target NCName == define element target NCName NCName [ substitutionGroupAttribute ] substitution [ NillableAttribute ] nillable QName [ <element name = NCName NillableAttribute substitutionGroupAttribute ElementModel </element> ] definition( target NCName == define element target NCName NCName [ substitutionGroupAttribute ] substitution [ NillableAttribute ] nillable [ ElementModel ] content( target NCName Schema mapping Local element declarations, but mapped into corresponding notations in the [XPath/XQuery] type system. Note that substitution group cannot be declared on local elements. [ <element OccursAttributes name = NCName NillableAttribute type = QName ] content( target NCName == ( element target NCName NCName [ NillableAttribute ] nillable QName [ OccursAttributes ] occurs [ <element OccursAttributes ref = QName ] content( target NCName == ( element QName [ OccursAttributes ] occurs Let fs: k [ <element OccursAttributes name = NCName NillableAttribute ElementModel </element> ] definition( target NCName == ( element target NCName NCName [ NillableAttribute ] nillable fs: k [ OccursAttributes ] occurs with define type fs: k [ ElementModel ] content( target NCName Schema component A complex type definition is represented in XML by the following structure. <complexType [ ignored ] [ ignored ] [ ignored ] [ ignored ] mixed = boolean : false name = NCName [ ignored ] Content: (annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)))) </complexType> Notation The following auxiliary grammar productions are used to describe the content of a complex type definition. 57 (Formal) ComplexTypeContent ::= "annotation"? ("simpleContent" | "complexContent" | ( ChildrenContent AttributeContent 60 (Formal) AttributeContent ::= ("attribute" | "attributeGroup")* "anyAttribute"? 58 (Formal) ChildrenContent ::= ("group" | "all" | "choice" | "sequence")? Schema import distinguishes between global complex types (which are mapped to sort declarations) and local complex types (which are mapped to type definitions). Schema mapping In the case of global complex types, the mapping rule which applies is denoted by [ ] definition( target NCName [ <complexType MixedAttribute name = NCName ComplexTypeContent </complexType> ] definition( target NCName == define type target NCName NCName [ MixedAttribute ComplexTypeContent ] mixed_content( target NCName Note that the mixed Schema mapping In the case of a local complex types, there must not be a name attribute and the mapping rule which applies is denoted by [ ] content( target NCName [ <complexType MixedAttribute ComplexTypeContent </complexType> ] content( target NCName == [ MixedAttribute ComplexTypeContent ] mixed_content( target NCName Note that the mixed Schema component A complex type can be of simple content. A simple content is represented in XML by the following structure. <simpleContent [ ignored ] [ ignored ] Content: (annotation?, (restriction | extension)) </simpleContent> Derivation by restriction inside a simple content is represented in XML by the following structure. <restriction base = QName [ ignored ] [ ignored ] Content: (annotation?, (simpleType?, (minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits | fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)*)?, ((attribute | attributeGroup)*, anyAttribute?)) </restriction> Derivation by extension inside a simple content is represented in XML by the following structure. <extension base [ ignored ] [ ignored ] Content: (annotation?, ((attribute | attributeGroup)*, anyAttribute?)) </extension> Notation The normalization rule [ MixedAttribute ComplexTypeContent ] mixed_content( target NCName == TypeDerivation maps a pair of mixed attribute and complex type content to a type derivation. Schema mapping A complex types with simple content must not have a mixed If the simple content is derived by restriction, it is mapped into a simple type restriction in the [XPath/XQuery] type system. Only the name of the base atomic type and attributes are mapped, while the actual simple type restriction is ignored. (Remember that facets are not captured in the [XPath/XQuery] type system.) [ mixed = "false" <simpleContent> <restriction base = QName simpleContentRestriction AttributeContent </restriction> </simpleContent> ] mixed_content( target NCName == restricts QName [ AttributeContent ] content( target NCName QName If the simple type is derived by extension, it is mapped into an extended type specifier into the [XPath/XQuery] type system. [ mixed = "false" <simpleContent> <extension base = QName AttributeContent </extension> </simpleContent> ] mixed_content( target NCName == extends QName [ AttributeContent ] content( target NCName Schema component A complex type can be of complex content. A complex content is represented in XML by the following structure. <complexContent [ ignored ] mixed = boolean : false [ ignored ] Content: (annotation?, (restriction | extension)) </complexContent> Derivation by restriction inside a complex content is represented in XML by the following structure. <restriction base = QName [ ignored ] [ ignored ] Content: (annotation?, (group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?)) </restriction> Derivation by extension inside a complex content is represented in XML by the following structure. <extension base [ ignored ] [ ignored ] Content: (annotation?, ((group | all | choice | sequence)?, ((attribute | attributeGroup)*, anyAttribute?))) </extension> Schema mapping If the complex content is derived by restriction, it is mapped into a type restriction in the [XPath/XQuery] type system, and the [ MixedAttribute <complexContent> <restriction base = QName annotation ChildrenContent AttributeContent </restriction> </complexContent> ] mixed_content( target NCName == restricts QName [ MixedAttribute ] mixed [ AttributeContent ] content( target NCName [ ChildrenContent ] content( target NCName If the complex content is derived by extension, it is mapped into an extended type specifier into the [XPath/XQuery] type system. [ MixedAttribute <complexContent> <extension base = QName annotation ChildrenContent AttributeContent </extension> </complexContent> ] mixed_content( target NCName == extends QName [ MixedAttribute ] mixed [ AttributeContent ] content( target NCName [ ChildrenContent ] content( target NCName Mapping for attribute uses is given in [D.1.4 Special attributes] Schema component Model group definitions are represented in XML by the following structure. <attributeGroup [ ignored ] name = NCame ref = QName [ ignored ] Content: (annotation?, ((attribute | attributeGroup)*, anyAttribute?)) </attributeGroup> Schema mapping Attribute group definitions are not currently handled by the mapping. See Issue 501 (FS-Issue-0158). Schema mapping Attribute group references are not currently handled by the mapping. See Issue 501 (FS-Issue-0158). Schema component Model group definitions are represented in XML by the following structure. <group name Content: (annotation?, (all | choice | sequence)) </group> Schema mapping Model group definitions are not currently handled by the mapping. See Issue 501 (FS-Issue-0158). Model groups are either "all", "sequence" or "choice". One can also refer to a model group definition. Schema component All groups are represented in XML by the following structure. <all [ ignored ] maxOccurs = 1 : 1 minOccurs = (0 | 1) : 1 [ ignored ] Content: (annotation?, element*) </all> Schema mapping All groups are mapped into the "&" operation in the [XPath/XQuery] type system. [ <all OccursAttributes Element 1 Element n </all> ] content( target NCName == ( [ Element 1 ] content( target NCName [ Element n ] content( target NCName [ OccursAttributes ] occurs Schema component Choice groups are represented in XML by the following structure. <choice [ ignored ] maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 [ ignored ] Content: (annotation?, (element | group | choice | sequence | any)*) </choice> Notation The following auxiliary grammar productions are used to describe group components. 59 (Formal) GroupComponent ::= "element" | "group" | "choice" | "sequence" | "any" Schema mapping Choice groups are mapped into the "|" operation in the [XPath/XQuery] type system. [ <choice OccursAttributes GroupComponent 1 GroupComponent n </choice> ] content( target NCName == ( [ GroupComponent 1 ] content( target NCName [ GroupComponent n ] content( target NCName [ OccursAttributes ] occurs Schema component Sequence groups are represented in XML by the following structure. <sequence [ ignored ] maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 [ ignored ] Content: (annotation?, (element | group | choice | sequence | any)*) </sequence> Schema mapping Sequence groups are mapped into the "," operation in the [XPath/XQuery] type system. [ <sequence OccursAttributes GroupComponent 1 GroupComponent n </sequence> ] content( target NCName == ( [ GroupComponent 1 ] content( target NCName [ GroupComponent n ] content( target NCName [ OccursAttributes ] occurs Particles contribute to the definition of content models. A particle can be either an element reference, a group reference or a wildcard. Schema component Element reference particles are represented in XML by the following structure. <element ref = QName maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 [ ignored ] Schema mapping Element references are mapped into element references in the [XPath/XQuery] type system. [ <element ref = QName OccursAttributes ] content( target NCName == element QName [ OccursAttributes ] occurs Schema component Group reference particles are represented in XML by the following structure. <group ref = QName maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 [ ignored ] Schema mapping Model group references are not currently handled by the mapping. Schema component Attribute wildcards are represented in XML by the following structure. <anyAttribute [ ignored ] [ not handled ] processContents = (lax | skip | strict) : strict [ ignored ] Content: (annotation?) </anyAttribute> Schema mapping An attribute wildcard with a "skip" process content is mapped as an attribute wildcard in the [XPath/XQuery] type system. [ <anyAttribute processContents = "skip" > annotation </anyAttribute> ] content( target NCName == (attribute (*, xs:untypedAtomic [ <anyAttribute processContents = "lax" > annotation </anyAttribute> ] content( target NCName == attribute * [ <anyAttribute processContents = "strict" > annotation </anyAttribute> ] content( target NCName == attribute * Editorial note Namespace wildcards are not handled by the mapping. Schema component Element wildcards are represented in XML by the following structure. <any [ ignored ] maxOccurs = (nonNegativeInteger | unbounded) : 1 minOccurs = nonNegativeInteger : 1 [ not handled ] processContents = (lax | skip | strict) : strict [ ignored ] Content: (annotation?) </any> Schema mapping An element wildcard with a "skip" process content is mapped as an element wildcard in the [XPath/XQuery] type system. [ <any OccursAttributes processContents = "skip" > annotation </any> ] content( target NCName == ( element (*, xs:untyped [ OccursAttributes ] occurs [ <any OccursAttributes processContents = "lax" > annotation </any> ] content( target NCName == ( element (*, xs:anyType [ OccursAttributes ] occurs Editorial note Element wildcards with a "lax" or "strict" process content are not handled by the mapping. Editorial note Namespace wildcards are not handled by the mapping. All identity-constraints definitions are ignored when mapping into the [XPath/XQuery] type system. All notation declarations are ignored when mapping into the [XPath/XQuery] type system. All annotation are ignored when mapping into the [XPath/XQuery] type system. Schema component A simple type is represented in XML by the following structure. <simpleType [ ignored ] [ ignored ] name = NCName [ ignored ] name = NCName </simpleType> Derivation by restriction inside a simple type is represented in XML by the following structure. <restriction base = QName [ ignored ] [ ignored ] Content: (annotation?, (simpleType?, (minExclusive | minInclusive | maxExclusive | maxInclusive | totalDigits | fractionDigits | length | minLength | maxLength | enumeration | whiteSpace | pattern)*)?) </restriction> Derivation by list inside a simple type is represented in XML by the following structure. <list [ ignored ] itemType = QName [ ignored ] Content: (annotation?, (simpleType?)) </list> Derivation by union inside a simple type is represented in XML by the following structure. <union [ ignored ] memberTypes = List of QName [ ignored ] Content: (annotation?, (simpleType*)) </union> Schema import distinguishes between global simple types (which are mapped to sort declarations) and local simple types (which are mapped to type definitions). Schema mapping In the case of global simple types, the mapping rule which applies is denoted by [ ] definition( target NCName [ <simpleType name = NCName SimpleTypeContent </simpleType> ] definition( target NCName == define type target NCName NCName [ SimpleTypeContent ] simple_content( target NCName Schema mapping In the case of global simple types, the mapping rule which applies is denoted by [ ] content( target NCName [ <simpleType> SimpleTypeContent </simpleType> ] content( target NCName == [ SimpleTypeContent ] simple_content( target NCName Notation The normalization rule [ ] simple_content( target NCName Schema mapping If the simple type is derived by restriction, it is mapped into a simple type restriction in the [XPath/XQuery] type system. The name of the base atomic type and attributes are mapped. Only the minLength, maxLength, and length facets in the simple type restriction are handled. All other properties of the simple-type restriction are ignored. [ <restriction base = QName simpleContentRestriction </restriction> ] simple_content( target NCName == restricts QName QName [ simpleContentRestriction ] occurs If the simple type is derived by list, and its content type does not constrain the length of the list, it is mapped into a zero-or-more repetition type into the [XPath/XQuery] type system. [ <list> SimpleType </list> ] simple_content( target NCName Type [ SimpleType ] content( target NCName == { Type If the simple type is derived by list, and its content type does constrain the length of the list, then it is mapped into a zero-or-more repetition type into the [XPath/XQuery] type system. [ <list> SimpleType </list> ] simple_content( target NCName Type · OccurrenceIndicator [ SimpleType ] content( target NCName == { Type · OccurrenceIndicator [ <list itemType = QName ] simple_content( target NCName == { QName If the simple type is derived by union, it is mapped into a union type into the [XPath/XQuery] type system. [ <union> SimpleType 1 SimpleType n </union> ] simple_content( target NCName == { ( [ SimpleType ] content( target NCName [ SimpleType n ] content( target NCName [ <union memberTypes = QName 1 QName n ] simple_content( target NCName == { QName 1 QName n Extensible Markup Language (XML) 1.0 (Fifth Edition) et. al. latest version World Wide Web Consortium. Namespaces in XML 1.1. http://www.w3.org/TR/xml-names11/ XML Schema Part 1: Structures Second Edition latest version XML Schema Part 2: Datatypes Second Edition latest version XQuery 1.0 and XPath 2.0 Data Model (XDM) (Second Edition) latest version XSLT 2.0 and XQuery 1.0 Serialization (Second Edition) latest version XQuery 1.0: An XML Query Language (Second Edition) et. al. latest version XML Path Language (XPath) 2.0 (Second Edition) et. al. latest version XQuery 1.0 and XPath 2.0 Functions and Operators (Second Edition) latest version XML Schema Part 0: Primer Second Edition latest version XML Query (XQuery) Requirements latest version Handbook of Formal Languages. G. Rozenberg and A. Salomaa, editors. Springer-Verlag Tree Automata Techniques and Applications. H. Comon and M. Dauchet and R. Gilleron and F. Jacquemard and D. Lugiez and S. Tison and M. Tommasi. See http://tata.gforge.inria.fr/ XQuery supports XML Schema validation using the validate expression. This section gives a non-normative formal semantics of XML Schema validation, solely for the purpose of specifying its usage in XQuery. Specifying XML Schema validation requires a fairly large number of auxiliary judgments. There are two main judgments used to describe the semantics of validation. The "erase" judgment takes a value and removes all type information from it. This operation is necessary since, in XQuery, validation can occur both on well-formed or already validated documents. The "annotate" operation takes an untyped value and a type and either fails or succeeds by returning a new -validated- value. Before defining these two judgments, we first introduce the auxiliary judgments used to describe specific parts of XML Schema's semantics. Notation The judgments statEnv |- TypeReference resolves to TypeName Type and statEnv |- TypeDerivation resolves to TypeName Type hold when a type reference (resp. a type derivation) resolves to the given type name and type content. Semantics Those judgments are specified by the following rules. If the type is omitted, it is resolved as the empty sequence type. statEnv |- OptDerivation OptMixed resolves to TypeName Type statEnv |- OptDerivation OptMixed resolves to TypeName Type In case of a type reference, then the type name is the name of that type, and the type is taken by resolving the type declaration of the global type. statEnv |- TypeName of elem/type expands to expanded-QName statEnv typeDefn expanded-QName TypeName TypeDerivation statEnv |- TypeDerivation resolves to BaseTypeName Type statEnv |- TypeName resolves to TypeName Type In the above inference rule, note that BaseTypeName TypeName resolves to If the type derivation is a restriction, then the type name is the name of the base type, and the type is taken from the type derivation. statEnv |- OptMixed Type adjusts to Adjusted Type statEnv |- TypeName OptMixed Type resolves to TypeName Adjusted Type If the type derivation is an extension, then the type name is the name of the base type, and the type is the base type extended by the type in the type derivation. statEnv |- TypeName of elem/type expands to expanded-QName statEnv typeDefn expanded-QName TypeName OptDerivation BaseOptMixed Base Type statEnv |- Base Type extended by Type is Extended Type statEnv |- OptMixed Extended Type adjusts to Adjusted Type statEnv |- TypeName OptMixed Type resolves to TypeName Adjusted Type Notation The judgment statEnv |- Value 1 interleave Value 2 yields Value 3 holds if some interleaving of Value 1 Value 2 Value 3 Semantics This judgment is specified by the following rules. Interleaving two empty sequences yields the empty sequence. statEnv |- interleave yields Otherwise, pick an item from the head of one of the sequences, and recursively interleave the remainder. statEnv |- Value 1 interleave Value 2 yields Value 3 statEnv |- Item Value 1 interleave Value 2 yields Item Value 3 statEnv |- Value 1 interleave Value 2 yields Value 3 statEnv |- Value 1 interleave Item Value 2 yields Item Value 3 Introduction Finally, we introduce an auxiliary judgment which extracts the value of a given attribute if it exists. This judgment is not used in the semantics of step expressions, but in [8.3 Judgments for type matching] Notation The judgment Value filter QName => absent holds if there are no occurrences of the attribute QName Value Value filter QName => SimpleValue holds if there is one occurrence of the attribute QName Value SimpleValue Semantics The filter dynEnv |- axis of Value 1 => Value 2 dynEnv |- test QName with of Value 2 => Value 1 filter QName => absent dynEnv |- axis of Value 1 => Value 2 dynEnv |- test QName with of Value 2 => Value 3 Value 3 QName SimpleValue Value 1 filter QName => SimpleValue Notation To define erasure, an auxiliary judgment is needed. The judgment SimpleValue simply erases to String holds when SimpleValue String Semantics This judgment is specified by the following rules. The empty sequence erases to the empty string. () simply erases to The concatenation of two non-empty sequences of values erases to the concatenation of their erasures with a separating space. SimpleValue 1 simply erases to String 1 SimpleValue 1 SimpleValue 2 simply erases to String 2 SimpleValue 2 SimpleValue 1 SimpleValue 2 simply erases to fn:concat String 1 String 2 An atomic value erases to its string representation as an instance of xs:untypedAtomic AtomicValueContent AtomicTypeName simply erases to dm: string-value AtomicValueContent Notation The erases to Section 3.13 Validate Expressions XQ serialization of the data model, as described in [XSLT 2.0 and XQuery 1.0 Serialization (Second Edition)] validation of the serialized value into a Post-Schema Validated Infoset, as described in [Schema Part 1] construction of a new data model value, as described in [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] Erasure is the formal equivalent of serialization followed by construction of a new data model value in which all element nodes are labeled with xs:untyped xs:untypedAtomic The judgment Value 1 erases to Value 2 holds when the erasure of Value 1 Value 2 Semantics This judgment is specified by the following rules. The empty sequence erases to itself. () erases to The erasure of the concatenation of two values is the concatenation of their erasure, so long as neither of the two original values is simple. Value 1 erases to Value 1 statEnv |- Value 1 Value 2 erases to Value 2 Value 2 Value 1 Value 2 erases to Value 1 Value 2 The erasure of an element is an element that has the same name and the type xs:untyped Value 1 erases to Value 2 element ElementName TypeName Value 1 erases to ElementName xs:untyped Value 2 The erasure of an attribute is an attribute that has the same name and the type xs:untypedAtomic xs:untypedAtomic SimpleValue simply erases to String attribute AttributeName TypeName SimpleValue erases to AttributeName xs:untypedAtomic String xs:untypedAtomic The erasure of a document is a document with the erasure of the original content. Value 1 erases to Value 2 document { Value 1 erases to Value 2 The erasure of a text or comment or processing-instruction node is itself. text { String erases to String comment { String erases to String processing-instruction NCName String erases to NCName String The erasure of a simple value is the corresponding text node. SimpleValue simply erases to String SimpleValue erases to String The annotate as Section 3.13 Validate Expressions XQ serialization of the data model, as described in [XSLT 2.0 and XQuery 1.0 Serialization (Second Edition)] parsing of the serialized value into the Infoset validation of the Infoset into a Post-Schema Validated Infoset, as described in [Schema Part 1] construction of a new data model value, as described in [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] Annotation is the formal equivalent of schema validation of an Infoset value into the PSVI followed by construction of a new data model value. Because the Formal Semantics is defined on data model values, not the Infoset, annotation is applied to data model values in which all element nodes are labeled with xs:untyped xs:untypedAtomic Notation The judgment statEnv |- simply annotate as SimpleType SimpleValue => SimpleValue 2 holds if the result of casting the SimpleValue 1 SimpleType SimpleValue 2 Semantics This judgment is specified by the following rules. Simply annotating a simple value to a union type yields the result of simply annotating the simple value to either the first or second type in the union. Note that simply annotating to the second type is attempted only if simply annotating to the first type fails statEnv |- simply annotate as SimpleType 1 SimpleValue 1 => SimpleValue 2 statEnv |- simply annotate as SimpleType 1 SimpleType 2 SimpleValue 1 => SimpleValue 2 statEnv |- not simply annotate as SimpleType 1 SimpleValue 1 => SimpleValue 2 statEnv |- simply annotate as SimpleType 2 SimpleValue 1 => SimpleValue 2 statEnv |- simply annotate as SimpleType 1 SimpleType 2 SimpleValue 1 => SimpleValue 2 The simple annotation rules for ?, +, * are similar. statEnv |- simply annotate as SimpleType => statEnv |- simply annotate as SimpleType SimpleValue 1 => SimpleValue 2 statEnv |- simply annotate as SimpleType SimpleValue 1 => SimpleValue 2 statEnv |- simply annotate as SimpleType => statEnv |- simply annotate as SimpleType SimpleValue 1 => SimpleValue 1 statEnv |- simply annotate as SimpleType SimpleValue 2 => SimpleValue 2 statEnv |- simply annotate as SimpleType SimpleValue 1 SimpleValue 2 => SimpleValue 1 SimpleValue 2 statEnv |- simply annotate as SimpleType SimpleValue 1 => SimpleValue 1 statEnv |- simply annotate as SimpleType SimpleValue 2 => SimpleValue 2 statEnv |- simply annotate as SimpleType SimpleValue 1 SimpleValue 2 => SimpleValue 1 SimpleValue 2 Simply annotating an atomic value to xs:string statEnv |- simply annotate as xs:string AtomicValue => dm: AtomicValue Simply annotating an atomic value to xs:decimal statEnv |- simply annotate as xs:decimal AtomicValue => xs:decimal dm: string-value AtomicValue Similar rules are assumed for the rest of the 19 XML Schema primitive types. Notation The judgment statEnv |- nil-annotate as OptNillable Type Value 1 => Value 2 holds if it is possible to annotate value Value 1 Type Value 2 Semantics This judgment is specified by the following rules. If the type is not nillable, then the xsi:nil attribute must not appear in the value, and it must be possible to annotate value Value Type Value 1 filter => absent statEnv |- annotate as Type Value 1 => Value 2 statEnv |- nil-annotate as Type Value 1 => Value 2 If the type is nillable, and the xsi:nil attribute does not appear or is false, then it must be possible to annotate value Value 1 Type Value 1 filter => SimpleValue SimpleValue in statEnv |- annotate as Type Value 1 => Value 2 statEnv |- nil-annotate as Type Value 1 => Value 2 If the type is nillable, and the xsi:nil attribute is true, then it must be possible to annotate value Value 1 Value 1 filter => statEnv |- annotate as AttributeModel Value 1 => Value 2 statEnv |- nil-annotate as AttributeModel ElementModel Value 1 => Value 2 The annotate as Section 3.13 Validate Expressions XQ serialization of the data model, as described in [XSLT 2.0 and XQuery 1.0 Serialization (Second Edition)] parsing of the serialized value into the Infoset validation of the Infoset into a Post-Schema Validated Infoset, as described in [Schema Part 1] construction of a new data model value, as described in [XQuery 1.0 and XPath 2.0 Data Model (Second Edition)] Erasure is the formal equivalent of serialization followed by construction of a new data model value in which all element nodes are labeled with xs:untyped xs:untypedAtomic Notation The judgment statEnv |- annotate as Type Value 1 => Value 2 holds if it is possible to annotate value Value 1 Type Value 2 Note Assume an XML Infoset instance X1 is validated against an XML Schema S, yielding PSVI instance X2. Then if X1 corresponds to Value 1 Type Value 2 annotate as Type Value 1 => Value 2 Semantics This judgment is specified by the following rules. Annotating the empty sequence as the empty type yields the empty sequence. statEnv |- annotate as => Annotating a concatenation of values as a concatenation of types yields the concatenation of the annotated values. statEnv |- annotate as Type 1 Value 1 => Value 1 statEnv |- annotate as Type 2 Value 2 => Value 2 statEnv |- annotate as Type 1 Type 2 Value 1 Value 2 => Value 1 Value 2 Annotating a value as a choice type yields the result of annotating the value as either the first or second type in the choice. statEnv |- annotate as Type 1 Value 1 => Value 2 statEnv |- annotate as Type 1 Type 2 Value 1 => Value 2 statEnv |- annotate as Type 2 Value 1 => Value 2 statEnv |- annotate as Type 1 Type 2 Value 1 => Value 2 Annotating a value as an all group uses interleaving to decompose the original value and recompose the annotated value. Editorial note Jerome and Phil: Note that this may reorder the original sequence. Perhaps we should disallow such reordering. Specifying that formally is not as easy as we would like. statEnv |- annotate as Type 1 Value 1 => Value 1 statEnv |- annotate as Type 2 Value 2 => Value 2 statEnv |- Value 1 interleave Value 2 yields Value statEnv |- Value 1 interleave Value 2 yields Value statEnv |- annotate as Type 1 Type 2 Value => Value The annotation rules for ?, +, * are similar. statEnv |- annotate as Type Value 1 => Value 2 statEnv |- annotate as Type Value 1 => Value 2 statEnv |- annotate as Type Value 1 => Value 1 statEnv |- annotate as Type Value 2 => Value 2 statEnv |- annotate as Type Value 1 Value 2 => Value 1 Value 2 statEnv |- annotate as Type => statEnv |- annotate as Type Value 1 => Value 1 statEnv |- annotate as Type Value 2 => Value 2 statEnv |- annotate as Type Value 1 Value 2 => Value 1 Value 2 To annotate an element with no xsi:type attribute, first look up the element type, next resolve the resulting type reference, then annotate the value against the resolved type, and finally return a new element with the name of the original element, the resolved type name, and the annotated value. Value filter => statEnv |- ElementName name lookup ElementType yields OptNillable TypeReference statEnv |- TypeReference resolves to TypeName Type statEnv |- nil-annotate as OptNillable Type Value => Value statEnv |- annotate as ElementType ElementName xs:anyType Value => ElementName TypeName Value To annotate an element with an xsi:type attribute, define a type reference corresponding to the xsi:type. Look up the element type, yielding a type reference, and check that the xsi:type reference derives from this type reference. Resolve the xsi:type reference, then annotate the value against the resolved type, and finally return a new element with the name of the original element, the resolved type name, and the annotated value. Value filter => TypeName Xsi TypeReference TypeName statEnv |- ElementName name lookup ElementType yields OptNillable BaseTypeName statEnv |- TypeName derives from BaseTypeName statEnv |- Xsi TypeReference resolves to TypeName Type statEnv |- nil-annotate as OptNillable Type Value => Value statEnv |- annotate as ElementType ElementName xs:anyType Value => ElementName TypeName Value The rule for attributes is similar to the first rule for elements. statEnv |- AttributeName name lookup AttributeType yields TypeReference statEnv |- TypeReference resolves to TypeName Type statEnv |- nil-annotate as OptNillable Type SimpleValue 1 => SimpleValue 2 statEnv |- annotate as AttributeType AttributeName xs:anySimpleType SimpleValue 1 => AttributeName TypeName SimpleValue 2 Annotating a document node yields a document with the annotation of its contents. statEnv |- annotate as Type Value => Value statEnv |- annotate as Type Value => Value Annotating a text node as text yields itself. statEnv |- annotate as String => String Annotating a text nodes as a simple type is identical to casting. statEnv |- simply annotate as SimpleType String => SimpleValue statEnv |- annotate as SimpleType String => SimpleValue Annotating a simple value as a simple type is identical to casting. statEnv |- simply annotate as SimpleType SimpleValue => SimpleValue statEnv |- annotate as SimpleType SimpleValue => SimpleValue The changes made to this document are described in detail in the Errata Erratum Bugzilla Category Description E001 1641 3896 editorial Make normalization of DirAttributeValue more explicit. E002 3864 editorial Both Core and Formal grammars had symbols 'NamespaceBinding' and 'NamespaceBindings'. To avoid confusion, we rename the Core symbols 'NamespaceBinding[s]' as 'LocalNamespaceDecl[s]', changing all occurrences of the former to the latter. At the same time, we introduce a production for LocalNamespaceDecls (currently assumed). E003 1647 editorial Complete the changes entailed by adding a local-namespaces component to the Core CompElemConstructor. E004 1746 editorial Fix typo in function signature. E005 1660 editorial (superseded) E006 3875 3184 3885 3194 1715 editorial Fix problems involving the domains of statEnv.funcType and dynEnv.funcDefn: Although section 3.1.1 declares the domain of statEnv.funcType to be (expanded-QName, arity), some inference rules neglect the arity. And although section 3.1.2 declares the domain of dynEnv.funcDefn to be expanded-QName(Type1, ..., Typen), this leads to misunderstandings and mistakes; dynEnv.funcDefn should have the same domain as statEnv.funcType. To simplify some of these changes, we introduce the Formal symbol FunctionKey to represent the common domain. E007 1694 editorial Fix miscellaneous small errors in section 5. E008 1680 editorial Fix a bug in the normalization of function calls. E009 3142 editorial Fix some errors in the productions for FunctionSig and TypeList. E010 3670 editorial Clean up due to the removal of op:anyURI-equal from the F+O spec. E011 3758 3760 editorial Correct/simplify/complete the Normalization rules defining []ElementContent and []AttributeContent, and simplify the corresponding Dynamic Evaluation rules. E012 3771 editorial Static Type Analysis must allow for empty text nodes introduced during normalization of direct element constructors. E013 1754 editorial Fix small errors in sections 7.2.1 and 7.2.2. E014 1756 editorial (superseded) E015 1783 editorial Fix some small errors in section 8.4. E016 3847 substantive For internal function fs:idiv, correct the operand types and supporting op: function given in the Binary Operators table. E017 4371 editorial Update the "Processing Model" diagram. E018 4242 4261 4512 4581 5129 3269 substantive Correct various errors in section 8.2.3.1.1. E019 4578 substantive Correct a normalization error in section 4.3.2 Filter Expressions. E020 4766 editorial Correct errors in examples in section 2.4.4. E021 3818 substantive Avoid loss of type information in normalized path expressions. E022 3946 substantive Make the static typing of processing-instructions consistent with their dynamic typing. E023 3269 editorial ElementNameOrWildcard and AttributeNameOrWildcard do not derive empty. E024 4841 editorial Introduce fs:item-at() function. E025 5601 substantive For internal function fs:div, correct the result type in the Binary Operators table. E026 1757 editorial Fix small errors in section 7.2.4 [The fn:boolean function]. E027 5651 substantive Provide (non-default) static typing for fn:not(). E028 5670 substantive Call fn:boolean() in normalization of Where clause E029 3655 3771 4869 substantive Don't use the "interleave with empty text nodes" technique for element constructors. E030 5986 editorial Fix cross-reference in 4.7.3.4. E031 3771 substantive Don't use the "interleave with empty text nodes" technique for attribute constructors. E032 5747 substantive Rework the rules for CastableExpr to avoid raising type errors (and fix various other problems). E033 5459 5460 substantive Fix the static typing for numeric and aggregate functions. E034 1776 editorial Adjust the formatting of a rule in 8.2.2.2 [Dynamic semantics of axes]. E035 3193 editorial Fix typo in 5.14 [Variable Declaration]. E036 3268 editorial Introduce Formal symbol OptDerivation. E037 3861 editorial Fix typo in 2.1.4 [Notations for inference rules]. E038 3864 editorial Fix typos in 2.3.1 [Formal values]. E039 3865 editorial Fix typo in 2.3.2 [Examples of values]. E040 3866 editorial Fix typos in 2.4.1 [XML Schema and the [XPath/XQuery] Type System]. E041 3868 editorial Fix typos in 2.4.3 [Content models]. E042 3871 editorial In the production for Definitions, add a semicolon after each Definition. Adjust the rest of the spec accordingly. E043 3871 editorial Fix typos in 2.4.4 [Top level definitions]. E044 3873 editorial Fix typo in 2.5 [Functions and operators]. E045 3876 editorial Fix typo in 3.2.2 [Normalization mapping rules]. E046 3879 editorial Fix typos in 4 [Expressions]. E047 3882 editorial Change some wording in 4.1.5 [Function Calls] / Normalization. E048 3883 editorial Change some wording in 4.1.5 [Function Calls] / Static Type Analysis. E049 3885 editorial Minor changes in 4.1.5 [Function Calls] / Dynamic Evaluation. E050 3886 editorial Fix typo in 4.2.1 [Steps]. E051 6005 markup Correctly render metavariables in mapping subscripts. E052 3895 editorial Change some wording in 4.7.1 [Direct Element Constructors]. E053 4447 editorial Fix incorrect references to standard functions/operators. E054 4593 editorial Fix typo in 8.4 [Judgments for FLWOR and other expressions on sequences]. E055 4601 editorial Change wording re fs:convert-operand in 4.5.2 [General Comparisons]. E056 6007 markup Fix italicization in C.2 [Mapping of Overloaded Internal Functions]. E057 6160 substantive Fix the static typing for fs:convert-operand(). E058 5254 substantive Fix the static typing for ValidateExpr. E059 4189 substantive Fix various bugs in the 'union interpretation' rules. E060 6538 substantive Fix behaviour of following-sibling axis re attribute nodes. E061 4273 substantive Fix unsoundness of 'data on' judgment. E062 5452 substantive Don't define the static type of the namespace axis.

Related documents

Record · ID 153191 · SHA-256 55b2e1ef622435f3
Conceptio Open Knowledge Archive — every document is proof-bundled with source, license, and retrieval metadata.