From 0d5231d82e57446fb7240fa9da8ab16334dcc70c Mon Sep 17 00:00:00 2001 From: Andy Bunce Date: Tue, 12 Sep 2023 16:18:30 +0100 Subject: [PATCH 1/8] [mod] rework xqlint caching --- .vscode/settings.json | 3 +- CHANGELOG.md | 8 +- README.md | 2 +- docs/xquery/xquery-errors.md | 8 + package.json | 49 +- src/common/channel-basex.ts | 2 +- .../child-process.ts | 0 src/common/configuration.ts | 6 + src/common/create-document-selector.ts | 10 - src/common/document-selectors.ts | 20 + src/common/index.ts | 2 +- src/common/native-commands.ts | 10 +- src/common/xqlint.ts | 50 +- src/constants.ts | 7 +- src/extension.ts | 24 +- src/linting/index.ts | 1 - src/linting/report.ts | 79 +- src/linting/xquery-linter.ts | 38 - src/providers/completion.ts | 5 +- src/providers/documentlink.ts | 9 +- src/providers/hover.ts | 5 +- src/providers/symbols.ts | 7 +- src/test/test-data/issue-194.formatted.xml | 1 + src/test/test-xml/fos.xsd | 382 + src/test/test-xml/function-catalog.xml | 27813 ++++++++++++++++ src/test/{test-data => test-xml}/xslt-3.0.xsd | 0 src/xqdiagnostics.ts | 131 +- .../commands => xquery-cmds}/executeXQuery.ts | 12 +- src/xquery-cmds/index.ts | 2 + src/xquery-cmds/xqcmds.ts | 48 + src/xquery-execution/commands/index.ts | 1 - src/xquery-execution/index.ts | 1 - tsconfig.json | 3 +- 33 files changed, 28504 insertions(+), 235 deletions(-) create mode 100644 docs/xquery/xquery-errors.md rename src/{xquery-execution => common}/child-process.ts (100%) delete mode 100644 src/common/create-document-selector.ts create mode 100644 src/common/document-selectors.ts delete mode 100644 src/linting/xquery-linter.ts create mode 100644 src/test/test-xml/fos.xsd create mode 100644 src/test/test-xml/function-catalog.xml rename src/test/{test-data => test-xml}/xslt-3.0.xsd (100%) rename src/{xquery-execution/commands => xquery-cmds}/executeXQuery.ts (81%) create mode 100644 src/xquery-cmds/index.ts create mode 100644 src/xquery-cmds/xqcmds.ts delete mode 100644 src/xquery-execution/commands/index.ts delete mode 100644 src/xquery-execution/index.ts diff --git a/.vscode/settings.json b/.vscode/settings.json index 05e3e5d..64a972f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -8,5 +8,6 @@ }, "yaml.schemas": { "https://json.schemastore.org/mkdocs-1.0.json": "file:///c%3A/Users/mrwhe/git/vscode-basex/mkdocs.yml" - } + }, + "basexTools.xquery.processor": "basex-9" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 5fc3b5d..2515a23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,8 @@ - +# 0.1.16 (2023-09-10) +* [mod] virtual docs updates +# 0.1.15 (2023-09-09) +* [ADD] set processor and selectDeclaration commands +* [mod] rework event handlers # 0.1.14 (2023-08-26) * [mod] Use xqlint 0.3.3 * [mod] rewrite event subscriptions @@ -23,7 +27,7 @@ * Add XQuery icon # 0.1.4 (2023-03-18) -* [fix] use xqlint 0.2.1, was using 0.2.0 +* [fix] use xqlint 0.2.1, was using 0.2.0 in error # 0.1.3 (2023-02-27) * Rename setting `platform` to `processor` diff --git a/README.md b/README.md index 90f451c..ba5b01d 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ See the [documentation](https://quodatum.github.io/vscode-basex/) for more detai # Requirements -* VS Code `1.73.0` or higher +* VS Code `1.76.0` or higher # Release Notes Detailed release notes are available [here](https://github.com/Quodatum/vscode-basex/releases). diff --git a/docs/xquery/xquery-errors.md b/docs/xquery/xquery-errors.md new file mode 100644 index 0000000..0612338 --- /dev/null +++ b/docs/xquery/xquery-errors.md @@ -0,0 +1,8 @@ +--- +title: XQuery errors +summary: Error markers generated by XQlint. +authors: + - Andy Bunce +date: 2023-09-11 +--- +TODO diff --git a/package.json b/package.json index 114bed7..3982873 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "vscode-basex", "displayName": "BaseX tools", "description": "BaseX tools: XQuery, XML, XPath Tools for Visual Studio Code", - "version": "0.1.14", + "version": "0.1.16", "preview": true, "publisher": "quodatum", "author": "Andy Bunce (https://github.com/Quodatum)", @@ -37,6 +37,11 @@ ], "contributes": { "commands": [ + { + "command": "basexTools.processor", + "title": "BaseX Tools: get/set XQuery processor", + "shortTitle": "XQuery processor" + }, { "command": "basexTools.xqParse", "title": "BaseX Tools: Parse of XQuery source (xml)", @@ -52,14 +57,34 @@ "enablement": "editorLangId == xquery" }, { - "command": "basexTools.evaluateXPath", - "title": "BaseX Tools: Evaluate XPath long title", - "shortTitle": "BaseX Tools: Evaluate XPath" + "command": "basexTools.xqLintReport", + "title": "BaseX Tools: Analysis of current location in Xquery source", + "shortTitle": "Posinfo" + }, + { + "command": "basexTools.clearDiagnostics", + "title": "BaseX Tools: Clear the XQuery Diagnostics collection" }, { "command": "basexTools.executeXQuery", - "title": "BaseX Tools: Execute XQuery using standalone BaseX " + "title": "BaseX Tools: Execute XQuery using standalone BaseX" + }, + { + "command": "basexTools.selectDeclaration", + "title": "BaseX Tools: Select current declaration", + "enablement": "editorLangId == xquery" + }, + + { + "command": "basexTools.getCurrentXPath", + "title": "BaseX Tools: Get Current XPath" }, + { + "command": "basexTools.evaluateXPath", + "title": "BaseX Tools: Evaluate XPath ", + "shortTitle": "BaseX Tools: Evaluate XPath" + }, + { "command": "basexTools.formatAsXml", "title": "BaseX Tools: Format as XML" @@ -72,22 +97,10 @@ "command": "basexTools.xmlToText", "title": "BaseX Tools: Convert XML to text (<> -> <>)" }, - { - "command": "basexTools.getCurrentXPath", - "title": "BaseX Tools: Get Current XPath" - }, + { "command": "basexTools.minifyXml", "title": "BaseX Tools: Minify XML" - }, - { - "command": "basexTools.xqLintReport", - "title": "BaseX Tools: Analysis of current location in Xquery source", - "shortTitle": "Posinfo" - }, - { - "command": "basexTools.clearDiagnostics", - "title": "BaseX Tools: Clear the XQuery Diagnostics collection" } ], "configuration": [ diff --git a/src/common/channel-basex.ts b/src/common/channel-basex.ts index b97afb2..eb78ad8 100644 --- a/src/common/channel-basex.ts +++ b/src/common/channel-basex.ts @@ -46,5 +46,5 @@ export class channel { _channel.appendLine(`${ action}: ${uri.fsPath}`) } } -channel.log(`Activate vscode-basex(${ version }) ***************** XQLint(${ verXQlint })`); +channel.log(`Activate vscode-basex(${ version.version }) ***************** XQLint(${ verXQlint })`); _channel.show \ No newline at end of file diff --git a/src/xquery-execution/child-process.ts b/src/common/child-process.ts similarity index 100% rename from src/xquery-execution/child-process.ts rename to src/common/child-process.ts diff --git a/src/common/configuration.ts b/src/common/configuration.ts index 9ce6c4b..ee19c2d 100644 --- a/src/common/configuration.ts +++ b/src/common/configuration.ts @@ -42,6 +42,9 @@ export class Configuration { static get xqueryProcessor(): string { return this._getForWindow("xquery.processor"); } + static set xqueryProcessor(value: string) { + this._setForWindow("xquery.processor",value); + } static xqueryShowHovers(): boolean { return this._getForWindow("xquery.showHovers"); } @@ -69,4 +72,7 @@ export class Configuration { private static _getForWindow(section: string): T { return workspace.getConfiguration(ExtensionTopLevelSection).get(section); } + private static _setForWindow(section: string,value:string) { + workspace.getConfiguration(ExtensionTopLevelSection).update(section,value); + } } diff --git a/src/common/create-document-selector.ts b/src/common/create-document-selector.ts deleted file mode 100644 index 3d9bd3e..0000000 --- a/src/common/create-document-selector.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { DocumentFilter } from "vscode"; - -import * as constants from "../constants"; - -export function createDocumentSelector(language: string): DocumentFilter[] { - return [ - { language, scheme: constants.uriSchemes.file }, - { language, scheme: constants.uriSchemes.untitled }, - ]; -} diff --git a/src/common/document-selectors.ts b/src/common/document-selectors.ts new file mode 100644 index 0000000..58b8983 --- /dev/null +++ b/src/common/document-selectors.ts @@ -0,0 +1,20 @@ +import { DocumentFilter, Uri, TextDocument } from "vscode"; + +import * as constants from "../constants"; + +export function createDocumentSelector(language: string): DocumentFilter[] { + return [ + { language, scheme: constants.uriSchemes.file }, + { language, scheme: constants.uriSchemes.untitled }, + ]; +} +export function isNotXQDoc(doc: TextDocument): boolean { + if (!doc || doc.languageId !== constants.languageIds.xquery) return true; + return unsupportedScheme(doc.uri) +} +// only supported schemes +export function unsupportedScheme(uri: Uri): boolean { + const supportedSchemes = [constants.uriSchemes.file, constants.uriSchemes.untitled]; + return supportedSchemes.indexOf(uri.scheme) === -1; +} + diff --git a/src/common/index.ts b/src/common/index.ts index d9ee748..65e5abb 100644 --- a/src/common/index.ts +++ b/src/common/index.ts @@ -1,6 +1,6 @@ export * from "./configuration"; export * from "./xqlint"; -export * from "./create-document-selector"; +export * from "./document-selectors"; export * from "./extension-state"; export * from "./native-commands"; export * from "./xml-traverser"; diff --git a/src/common/native-commands.ts b/src/common/native-commands.ts index 7703cbc..2fb6234 100644 --- a/src/common/native-commands.ts +++ b/src/common/native-commands.ts @@ -1,5 +1,13 @@ -import { commands } from "vscode"; +import { Uri, Tab, TabInputText, window, commands } from "vscode"; +//https://stackoverflow.com/questions/44733028/how-to-close-textdocument-in-vs-code/75192905#75192905 +export async function closeFileIfOpen(file: Uri): Promise { + const tabs: Tab[] = window.tabGroups.all.map(tg => tg.tabs).flat(); + const index = tabs.findIndex(tab => tab.input instanceof TabInputText && tab.input.uri.path === file.path); + if (index !== -1) { + await window.tabGroups.close(tabs[index]); + } +} export class NativeCommands { static async cursorMove(to: string, by: string): Promise { await commands.executeCommand("cursorMove", { diff --git a/src/common/xqlint.ts b/src/common/xqlint.ts index 5c40b42..e1e3f23 100644 --- a/src/common/xqlint.ts +++ b/src/common/xqlint.ts @@ -1,42 +1,8 @@ -import * as ext from "@quodatum/xqlint"; -import { TextDocument, Range, Uri } from "vscode"; - -import { Configuration } from "."; -import { channel } from "./channel-basex"; - -// map of seen documents -const xlints: MapType = {}; -type MapType = { - [id: string]: ext.XQLint; -} - -export class XQLintFactory { - - // return xqlint for document - - static XQLint(document: TextDocument, refresh = true): ext.XQLint { - return XQLintFactory.XQLint2(document.uri, document.getText(), refresh = true) - } - -// - static XQLint2(uri: Uri, document: string, refresh = true): ext.XQLint { - const key = uri.toString(); - let xqlint = xlints[key]; - const isNew = typeof xqlint === "undefined"; - channel.log((isNew ? "🆕" : "") + (refresh ? "♻️": "") + " XQLint@ " + key); - if (isNew || refresh) { - const processor = Configuration.xqueryProcessor; - const opts={ "processor": processor, "fileName": uri.fsPath }; - xqlint = new ext.XQLint(document, opts); - xlints[key] = xqlint; - } - return xqlint; - } -} - - -export function importRange(lintRange: ext.LintRange): Range { - return lintRange? - new Range(lintRange.sl, lintRange.sc, lintRange.el, lintRange.ec) - :new Range(0,0,0,0); -} \ No newline at end of file +import { LintRange } from "@quodatum/xqlint"; +import { Range } from "vscode"; + +export function importRange(lintRange: LintRange): Range { + return lintRange? + new Range(lintRange.sl, lintRange.sc, lintRange.el, lintRange.ec) + :new Range(0,0,0,0); + } \ No newline at end of file diff --git a/src/constants.ts b/src/constants.ts index 69c1c52..f04d407 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -1,11 +1,12 @@ /* eslint-disable @typescript-eslint/no-namespace */ export namespace commands { - export const executeXQuery = "basexTools.executeXQuery"; + export const xqExecute = "basexTools.executeXQuery"; export const xqDoc = "basexTools.xqDoc"; // used as url scheme export const xqParse = "basexTools.xqParse"; // used as url scheme - + export const xqProcessor = "basexTools.processor"; + export const xqSelectDeclaration = "basexTools.selectDeclaration"; export const xqLintReport = "basexTools.xqLintReport"; - export const clearDiagnostics ="basexTools.clearDiagnostics" + export const xqClearDiagnostics ="basexTools.clearDiagnostics" export const getCurrentXPath = "basexTools.getCurrentXPath"; export const evaluateXPath = "basexTools.evaluateXPath"; diff --git a/src/extension.ts b/src/extension.ts index 11a11c5..56de534 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -12,7 +12,8 @@ import { formatAsXml, minifyXml, xmlToText, textToXml } from "./formatting/comma import { xqLintReport, activateVirtualDocs } from "./linting"; import { XmlTreeDataProvider } from "./tree-view"; import { evaluateXPath, getCurrentXPath } from "./xpath/commands"; -import { executeXQuery } from "./xquery-execution/commands"; + +import { setProcessor, selectDeclaration, executeXQuery } from "./xquery-cmds"; import * as constants from "./constants"; import * as formatter from "./providers/formatting"; @@ -21,12 +22,15 @@ import * as hover from './providers/hover'; import * as completion from './providers/completion'; import * as documentLink from './providers/documentlink'; -let diagnosticCollectionXQuery: XQueryDiagnostics; +export const diagnosticCollectionXQuery=new XQueryDiagnostics(); export function activate(context: ExtensionContext) { channel.log("Extension activate"); ExtensionState.configure(context); + /* Linting Features */ + subscribeToDocumentChanges(context, diagnosticCollectionXQuery); + /* activate XQuery handlers */ symbols.activate(context); hover.activate(context); @@ -36,9 +40,7 @@ export function activate(context: ExtensionContext) { activateVirtualDocs(context); - /* Linting Features */ - diagnosticCollectionXQuery = new XQueryDiagnostics(); - subscribeToDocumentChanges(context, diagnosticCollectionXQuery); + /* XML Formatting Features */ @@ -81,18 +83,20 @@ export function activate(context: ExtensionContext) { /* XQuery Features */ context.subscriptions.push( - commands.registerTextEditorCommand(constants.commands.executeXQuery, executeXQuery), - commands.registerTextEditorCommand(constants.commands.clearDiagnostics, diagnosticCollectionXQuery.clear), + commands.registerTextEditorCommand(constants.commands.xqExecute, executeXQuery), + commands.registerTextEditorCommand(constants.commands.xqSelectDeclaration, selectDeclaration), + commands.registerCommand(constants.commands.xqProcessor, setProcessor), + commands.registerCommand(constants.commands.xqClearDiagnostics, diagnosticCollectionXQuery.clear), ); - // if processor changed clear diagnostics - // + + // if changes to processor then clear diagnostics workspace.onDidChangeConfiguration(event => { if (event.affectsConfiguration("basexTools.xquery.processor")) { diagnosticCollectionXQuery.clear(); window.showInformationMessage("Processor now: " + Configuration.xqueryProcessor); } }) - + window.showInformationMessage("XQuery processor: " + Configuration.xqueryProcessor); } export function deactivate() { diff --git a/src/linting/index.ts b/src/linting/index.ts index 987ea77..b25cb5d 100644 --- a/src/linting/index.ts +++ b/src/linting/index.ts @@ -1,2 +1 @@ -export * from "./xquery-linter"; export * from "./report"; diff --git a/src/linting/report.ts b/src/linting/report.ts index 18bd84f..0127f77 100644 --- a/src/linting/report.ts +++ b/src/linting/report.ts @@ -1,10 +1,9 @@ // todo // see https://github.com/microsoft/vscode-extension-samples/tree/main/contentprovider-sample -import * as vscode from "vscode"; -import { languageIds,commands } from "../constants"; -import { channel, dump } from "../common/channel-basex"; -import { XQLintFactory } from "../common/xqlint"; - +import * as vscode from "vscode"; +import { commands } from "../constants"; +import { channel, dump,closeFileIfOpen, unsupportedScheme } from "../common"; +import { diagnosticCollectionXQuery } from "../extension"; export function activateVirtualDocs({ subscriptions }: vscode.ExtensionContext) { @@ -12,17 +11,10 @@ export function activateVirtualDocs({ subscriptions }: vscode.ExtensionContext) const parseScheme =commands.xqParse; const parseProvider = new class implements vscode.TextDocumentContentProvider { - - // emitter and its event - onDidChangeEmitter = new vscode.EventEmitter(); - onDidChange = this.onDidChangeEmitter.event; - provideTextDocumentContent(uri: vscode.Uri): string { - // simply invoke cowsay, use uri-path as text - const document = xqueryDoc(); - if (!document) return; - const linter = XQLintFactory.XQLint2(document.uri,document.getText()) - return linter.printAST(); + const orig=sourceUri(uri); + if(unsupportedScheme(orig)) return; + return diagnosticCollectionXQuery.xqlint(orig).printAST(); } }; subscriptions.push(vscode.workspace.registerTextDocumentContentProvider(parseScheme, parseProvider)); @@ -32,22 +24,28 @@ export function activateVirtualDocs({ subscriptions }: vscode.ExtensionContext) const uri = vscode.Uri.parse(`${parseScheme}:${editor.document.uri}.xml`); const doc = await vscode.workspace.openTextDocument(uri); // calls back into the provider vscode.languages.setTextDocumentLanguage(doc, "xml"); + /* const onDidChangeDisposable = vscode.workspace.onDidChangeTextDocument((event: vscode.TextDocumentChangeEvent)=>{ + if (event.document === editor.document){ + console.log('Watched doc changed: '+ editor.document.uri); + } + }); + const onDidCloseDisposable = vscode.workspace.onDidCloseTextDocument((closedDoc: vscode.TextDocument)=>{ + if (closedDoc === editor.document){ + console.log('Watched doc was closed: '+onDidCloseDisposable); + closeFileIfOpen(closedDoc.uri); + } + }); + subscriptions.push(onDidChangeDisposable,onDidCloseDisposable); */ await vscode.window.showTextDocument(doc, editor.viewColumn! + 1); })); const xqdocScheme = commands.xqDoc; const xqdocProvider = new class implements vscode.TextDocumentContentProvider { - - // emitter and its event - onDidChangeEmitter = new vscode.EventEmitter(); - onDidChange = this.onDidChangeEmitter.event; - provideTextDocumentContent(uri: vscode.Uri): string { - const document = xqueryDoc(); - if (!document) return; - const linter = XQLintFactory.XQLint2(document.uri,document.getText()); - const xqdoc= linter.getXQDoc(); + const orig=sourceUri(uri); + if(unsupportedScheme(orig)) return; + const xqdoc=diagnosticCollectionXQuery.xqlint(orig).getXQDoc(); return JSON.stringify(xqdoc,undefined," ") ; } }; @@ -57,16 +55,35 @@ export function activateVirtualDocs({ subscriptions }: vscode.ExtensionContext) const uri = vscode.Uri.parse(`${xqdocScheme}:${editor.document.uri}.json`); const doc = await vscode.workspace.openTextDocument(uri); // calls back into the provider vscode.languages.setTextDocumentLanguage(doc, "json"); + + const onDidChangeDisposable = vscode.workspace.onDidChangeTextDocument((event: vscode.TextDocumentChangeEvent)=>{ + if (event.document === editor.document){ + console.log('Watched doc changed: '+ editor.document.uri); + } + }); + const onDidCloseDisposable = vscode.workspace.onDidCloseTextDocument((closedDoc: vscode.TextDocument)=>{ + if (closedDoc === editor.document){ + console.log('Watched doc was closed: '+onDidCloseDisposable); + closeFileIfOpen(closedDoc.uri); + } + }); + subscriptions.push(onDidChangeDisposable,onDidCloseDisposable); + await vscode.window.showTextDocument(doc, editor.viewColumn! + 1); })); + +} +// convert custom scheme back to source uri + function sourceUri(uri: vscode.Uri): vscode.Uri { + const p=uri.path; + return vscode.Uri.parse(p.substring(0, p.lastIndexOf('.'))); + } // dump node to console export function xqLintReport(textEditor: vscode.TextEditor): void { - const linter = XQLintFactory.XQLint(textEditor.document); - - + const linter = diagnosticCollectionXQuery.xqlint(textEditor.document.uri); textEditor.edit(textEdit => { const selections = textEditor.selections; selections.forEach(selection => { @@ -79,11 +96,3 @@ export function xqLintReport(textEditor: vscode.TextEditor): void { }); } -// the active xquery doc or null -function xqueryDoc(): vscode.TextDocument { - if (!vscode.window.activeTextEditor) { - return null; // no editor - } - const { document } = vscode.window.activeTextEditor; - return (document.languageId === languageIds.xquery) ? document : null; -} \ No newline at end of file diff --git a/src/linting/xquery-linter.ts b/src/linting/xquery-linter.ts deleted file mode 100644 index 3506d01..0000000 --- a/src/linting/xquery-linter.ts +++ /dev/null @@ -1,38 +0,0 @@ -// convert xqlint markers -import { Diagnostic, DiagnosticSeverity, TextDocument } from "vscode"; -import { Marker } from "@quodatum/xqlint"; -import { Configuration } from "../common"; -import {XQLintFactory,importRange} from "../common/xqlint"; - -export class XQueryLinter { - - lint(document: TextDocument): Diagnostic[] { - const linter = XQLintFactory.XQLint(document,true); //refresh because changed - const diagnostics = new Array(); - - linter.getErrors().forEach((error: Marker) => { - diagnostics.push(new Diagnostic( - importRange( error.pos ), - error.message, - isSuppressed(error.message) ? DiagnosticSeverity.Information : DiagnosticSeverity.Error - )); - }); - - linter.getWarnings().forEach((warning: Marker) => { - diagnostics.push(new Diagnostic( - importRange(warning.pos ), - warning.message, - DiagnosticSeverity.Warning - )); - }); - return diagnostics; - - } -} -// [XQST0059] module "http://www.rave-tech.com/bloomsbury/config" not found -// [XPST0008] "list-details#0": undeclared function -function isSuppressed(msg: string): boolean { - const errs = Configuration.xquerySuppressErrors; - return errs.some((x) => msg.includes(x)); -} - diff --git a/src/providers/completion.ts b/src/providers/completion.ts index c968e8d..5c5f981 100644 --- a/src/providers/completion.ts +++ b/src/providers/completion.ts @@ -2,8 +2,9 @@ import { CompletionItem, CompletionItemKind, CompletionItemProvider, Position, TextDocument, ExtensionContext, languages } from "vscode"; -import { XQLintFactory } from "../common/xqlint"; + import { languageIds } from "../constants"; +import { diagnosticCollectionXQuery } from "../extension"; export function activate(context: ExtensionContext) { context.subscriptions.push(languages.registerCompletionItemProvider( @@ -15,7 +16,7 @@ class XQueryCompletionItemProvider implements CompletionItemProvider { provideCompletionItems(document: TextDocument, position: Position): CompletionItem[] { const completionItems = new Array(); - const linter = XQLintFactory.XQLint(document); + const linter = diagnosticCollectionXQuery.xqlint(document.uri); linter.getCompletions(position).forEach((x: any) => { completionItems.push(this._getCompletionItem(x)); diff --git a/src/providers/documentlink.ts b/src/providers/documentlink.ts index 54e22a1..f1921f8 100644 --- a/src/providers/documentlink.ts +++ b/src/providers/documentlink.ts @@ -10,8 +10,8 @@ import { ExtensionContext, languages, TextDocument, CancellationToken, DocumentLink, DocumentLinkProvider,Uri } from 'vscode'; -import { channel } from "../common/channel-basex"; -import { XQLintFactory, importRange } from "../common/xqlint"; +import { channel,importRange } from "../common"; +import { diagnosticCollectionXQuery } from "../extension"; import { languageIds } from "../constants"; @@ -21,9 +21,10 @@ export function activate(context: ExtensionContext) { ); } class XQueryDocumentLinks implements DocumentLinkProvider { - provideDocumentLinks = async (doc: TextDocument, token: CancellationToken): Promise => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + provideDocumentLinks = async (doc: TextDocument, _token: CancellationToken): Promise => { channel.start("Doclinks" , doc.uri); - const linter = XQLintFactory.XQLint(doc); + const linter = diagnosticCollectionXQuery.xqlint(doc.uri); const dlinks = linter.getDocLinks(); const links: DocumentLink[] = []; diff --git a/src/providers/hover.ts b/src/providers/hover.ts index 039f4ee..2427eae 100644 --- a/src/providers/hover.ts +++ b/src/providers/hover.ts @@ -1,9 +1,10 @@ // xquery hover import * as vscode from "vscode"; -import { XQLintFactory } from "../common/xqlint"; + import { Configuration } from "../common"; import { languageIds } from "../constants"; +import { diagnosticCollectionXQuery } from "../extension"; export function activate(context: vscode.ExtensionContext) { context.subscriptions.push(vscode.languages.registerHoverProvider( @@ -20,8 +21,8 @@ class XQueryHoverProvider implements vscode.HoverProvider { const range = document.getWordRangeAtPosition(position); if (!range) return null const word = document.getText(range); + const linter = diagnosticCollectionXQuery.xqlint(document.uri); - const linter = XQLintFactory.XQLint(document); const node = linter.getAST(position); if (node.name === 'WS') return null; diff --git a/src/providers/symbols.ts b/src/providers/symbols.ts index d466d46..6e8e344 100644 --- a/src/providers/symbols.ts +++ b/src/providers/symbols.ts @@ -5,9 +5,9 @@ import { Position, Location,Uri,TextDocument, CancellationToken, ExtensionContext, languages, SymbolInformation } from 'vscode'; -import { channel } from "../common/channel-basex"; -import { XQLintFactory, importRange } from "../common/xqlint"; +import { channel,importRange } from "../common"; import { languageIds } from "../constants"; +import { diagnosticCollectionXQuery } from "../extension"; // // This class handles XQuery Symbols // @@ -46,7 +46,8 @@ export class DocumentSymbols implements DocumentSymbolProvider { channel.log("DocumentSymbols: " + document.uri); const symbols: DocumentSymbol[] = []; - const linter = XQLintFactory.XQLint(document); + + const linter = diagnosticCollectionXQuery.xqlint(document.uri); const xqdoc = linter.getXQDoc(true); channel.log("got xqdoc"); diff --git a/src/test/test-data/issue-194.formatted.xml b/src/test/test-data/issue-194.formatted.xml index fb6e5a3..89c7490 100644 --- a/src/test/test-data/issue-194.formatted.xml +++ b/src/test/test-data/issue-194.formatted.xml @@ -1,4 +1,5 @@ + This is ok diff --git a/src/test/test-xml/fos.xsd b/src/test/test-xml/fos.xsd new file mode 100644 index 0000000..6157d54 --- /dev/null +++ b/src/test/test-xml/fos.xsd @@ -0,0 +1,382 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + A reference to a fos:type definition, typically a record type definition. + + + + + + + + + + + + + + + A reference to a fos:type definition, typically a record type definition. + + + + + + + + Used by XSLT for streamability analysis. + + + + + + + An example of a valid value for the argument: used for test data generation. If omitted, + a generic instance of the required data type is used. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/test-xml/function-catalog.xml b/src/test/test-xml/function-catalog.xml new file mode 100644 index 0000000..32fceb1 --- /dev/null +++ b/src/test/test-xml/function-catalog.xml @@ -0,0 +1,27813 @@ + + + + <PurchaseOrder> <line-item> + <description>Large widget</description> <price>8.95</price> + <quantity>5.0</quantity> </line-item> <line-item> + <description>Small widget</description> <price>3.99</price> + <quantity>2.0</quantity> </line-item> <line-item> + <description>Tiny widget</description> <price>1.49</price>a + <quantity>805</quantity> </line-item> + </PurchaseOrder> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the name of a node, as an xs:QName.

+
+ +

If the argument is omitted, it defaults to the context item (.). The + behavior of the function if the argument is omitted is exactly the same as if the + context item had been passed as the argument.

+

If $node is the empty sequence, the empty sequence is returned.

+

Otherwise, the function returns the result of the dm:node-name accessor as + defined in (see ).

+
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+ +
+ +

For element and attribute nodes, the name of the node is returned as an + xs:QName, retaining the prefix, namespace URI, and local part.

+

For processing instructions, the name of the node is returned as an + xs:QName in which the prefix and namespace URI are absent.

+

For a namespace node, the function returns an empty sequence if the node represents the + default namespace; otherwise it returns an xs:QName in which prefix and + namespace URI are absent and the local + part is the namespace prefix being bound.

+

For all other kinds of node, the function returns the empty sequence.

+
+
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + + +

Returns true for an element that is nilled.

+
+ +

If the argument is omitted, it defaults to the context item (.). The + behavior of the function if the argument is omitted is exactly the same as if the + context item had been passed as the argument.

+

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

+

Otherwise the function returns the result of the dm:nilled accessor as + defined in (see ).

+
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+ +
+ +

If $node is not an element node, the function returns the empty + sequence.

+

If $node is an untyped element node, the function returns false.

+

In practice, the function returns true only for an element node that has + the attribute xsi:nil="true" and that is successfully validated against a + schema that defines the element to be nillable; the detailed rules, however, are defined + in .

+
+
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the value of $value represented as an xs:string.

+
+ +

In the zero-argument version of the function, $value defaults to the context + item. That is, calling fn:string() is equivalent to calling + fn:string(.).

+

If $value is the empty sequence, the function returns the zero-length + string.

+ +

If $value is a node, the function returns the string value of the node, as obtained using the + dm:string-value accessor defined in (see ).

+ +

If $value is an atomic value, the function returns the result of the expression $value cast + as xs:string (see ).

+ +

In all other cases, a dynamic error occurs (see below).

+ + +
+ +

A dynamic error is raised by + the zero-argument version of the function if the context item is absent.

+

A type error is raised if + $value is a function item (this includes maps and arrays).

+
+ +

Every node has a string value, even an element with element-only + content (which has no typed value). Moreover, casting an atomic value to a string always + succeeds. Functions, maps, and arrays have no string value, so these are the + only arguments that satisfy the type signature but cause failure.

+
+ + + + string(23) + "23" + + + string(false()) + "false" + + + string("Paris") + "Paris" + + + string((1, 2, 3)) + + + + string([[1, 2], [3, 4]]) + + + + string(abs#1) + + + + In a hole in the ground there lived a hobbit.]]> + + + + string($para) + "In a hole in the ground there lived a hobbit." + + + +
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the result of atomizing a sequence. This process flattens arrays, and replaces + nodes by their typed values.

+
+ +

If the argument is omitted, it defaults to the context item (.). The + behavior of the function if the argument is omitted is exactly the same as if the + context item had been passed as the argument.

+

The result of fn:data is the sequence of atomic values produced by + applying the following rules to each item in $input:

+ + +

If the item is an atomic value, it is appended to the result sequence.

+
+ +

If the item is a node, the typed value of the node is appended to the result + sequence. The typed value is a sequence of zero or more atomic values: + specifically, the result of the dm:typed-value accessor as defined in + (See ).

+
+ +

If the item is an array, the result of applying fn:data to + each member of the array, in order, is appended to the result sequence.

+
+
+
+ +

A type error is raised if an item in the + sequence $input is a node that does not have a typed value.

+

A type error is raised if an item in + the sequence $input is a function item other than + an array.

+ +

A dynamic error is raised if $input is omitted and the context item is + absent.

+ + +
+ +

The process of applying the fn:data function to a sequence is referred to + as atomization. In many cases an explicit call on fn:data is + not required, because atomization is invoked implicitly when a node or sequence of nodes + is supplied in a context where an atomic value or sequence of atomic values is + required.

+

The result of atomizing an empty sequence is an empty sequence.

+

The result of atomizing an empty array is an empty sequence.

+
+ + + + data(123) + 123 + + + data((123, 456)) + 123, 456 + + + data([[1,2],[3,4]]) + 1, 2, 3, 4 + + + + In a hole in the ground there lived a hobbit.]]> + + + + data($para) + xs:untypedAtomic("In a hole in the ground there lived a hobbit.") + + + data($para/term/@author) + xs:untypedAtomic("Tolkien") + + + data(abs#1) + + + + +
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the base URI of a node.

+
+ + +

The zero-argument version of the function returns the base URI of the context node: it + is equivalent to calling fn:base-uri(.).

+

The single-argument version of the function behaves as follows:

+ +

If $node is the empty sequence, the function returns the empty + sequence.

+ +

Otherwise, the function returns the value of the dm:base-uri accessor + applied to the node $node. This accessor is defined, for each kind of + node, in the XDM specification (See ).

+
+

As explained in XDM, document, element and processing-instruction nodes have a + base-uri property which may be empty. The base-uri property for all other node kinds is + the empty sequence. The dm:base-uri accessor returns the base-uri property of a node if + it exists and is non-empty; otherwise it returns the result of applying the dm:base-uri + accessor to its parent, recursively. If the node does not have a parent, or if the + recursive ascent up the ancestor chain encounters a parentless node whose base-uri + property is empty, the empty sequence is returned. In the case of namespace nodes, + however, the result is always an empty sequence — it does not depend on the base URI of + the parent element.

+ + +

See also fn:static-base-uri.

+
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+
+
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the URI of a resource where a document can be found, if available.

+
+ +

If the argument is omitted, it defaults to the context item (.). The + behavior of the function if the argument is omitted is exactly the same as if the + context item had been passed as the argument.

+

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

+

If $node is not a document node, the function returns the empty + sequence.

+

Otherwise, the function returns the value of the document-uri accessor + applied to $node, as defined in (See + ).

+
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+ +
+ +

In the case of a document node $D returned by the fn:doc + function, or a document node at the root of a tree containing a node returned by the + fn:collection function, it will always be true that either + fn:document-uri($D) returns the empty sequence, or that the following + expression is true: fn:doc(fn:document-uri($D)) is $D. It is + implementation-defined whether this guarantee also holds for + document nodes obtained by other means, for example a document node passed as the + initial context node of a query or transformation.

+

A consequence of these rules is that it is not possible (within the + execution scope of a transformation) for two different documents to have the same + value for their document-uri property. This means that in situations where + URI stability is not guaranteed (for example, with streamed input documents in XSLT, + or for documents returned by fn:collection if document stability has been + disabled), the document-uri property should be absent, and + fn:document-uri should return an empty sequence.

+
+
+ + + + + + + + + + nondeterministic + context-independent + focus-independent + + +

Calling the fn:error function raises an application-defined error.

+
+ +

This function never returns a value. Instead it always raises an error. The effect of + the error is identical to the effect of dynamic errors raised implicitly, for example + when an incorrect argument is supplied to a function.

+

The parameters to the fn:error function supply information that is + associated with the error condition and that is made available to a caller that asks for + information about the error. The error may be caught either by the host language (using + a try/catch construct in XSLT or XQuery, for example), or by the calling application or + external processing environment. The way in which error information is returned to the + external processing environment is implementation-dependent.

+ +

There are three pieces of information that may be associated with an error.

+ + +

The $code is an error code that distinguishes this error from others. + It is an xs:QName; the namespace URI conventionally identifies the + component, subsystem, or authority responsible for defining the meaning of the + error code, while the local part identifies the specific error condition. The + namespace URI http://www.w3.org/2005/xqt-errors is used for errors + defined in this specification; other namespace URIs may be used for errors defined + by the application.

+

If the external processing environment expects the error code to be returned as a + URI or a string rather than as an xs:QName, then an error code with + namespace URI NS and local part LP will be returned in + the form NS#LP. The namespace URI part of the error code should + therefore not include a fragment identifier.

+

If no value is supplied for the $code argument, or if the value supplied + is an empty sequence, + the effective value of the error code is fn:QName('http://www.w3.org/2005/xqt-errors', 'err:FOER0000').

+
+ +

The $description is a natural-language description of the error + condition.

+

If no value is supplied for the $description + argument, or if the value supplied + is an empty sequence, then the + effective value of the description is implementation-dependent.

+
+ +

The $value is an arbitrary value used to convey additional + information about the error, and may be used in any way the application + chooses.

+

If no value is supplied for the $value + argument or if the value supplied + is an empty sequence,, then the + effective value of the error object is implementation-dependent.

+
+
+ + + +
+ +

This function always raises a dynamic error. By default, it raises

+
+ +

The value of the $description parameter may need to be localized.

+

The type none is a special type defined in and is not available to the user. It indicates that the function never returns and + ensures that it has the correct static type.

+

Any QName may be used as an error code; there are no reserved names or namespaces. The + error is always classified as a dynamic error, even if the error code used is one that + is normally used for static errors or type errors.

+
+ + + + error() + + This returns the URI + http://www.w3.org/2005/xqt-errors#FOER0000 (or the corresponding + xs:QName) to the external processing environment, unless the error + is caught using a try/catch construct in the host language. + + + + + error( + QName( + 'http://www.example.com/HR', + 'myerr:toohighsal' + ), + 'Salary is too high' +) + + This returns http://www.example.com/HR#toohighsal and the + xs:string + "Salary is too high" (or the corresponding + xs:QName) to the external processing environment, unless the error + is caught using a try/catch construct in the host language. + + + + + All three arguments are now optional, and each argument can be set + to an empty sequence. Previously if $description was supplied, it could not be empty. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Provides an execution trace intended to be used in debugging queries.

+
+ +

The function returns $input, unchanged.

+

In addition, the values of $input, typically serialized and converted + to an xs:string, and $label (if supplied + and non-empty) may + be output to an destination.

+

The serialization of the trace output must not raise an error. + This can be achieved (for example) by using a serialization method that can handle + arbitrary input, such as the adaptive output method (see + ).

+

The format of the trace output and its order are + . Therefore, the order in which the output + appears is not predictable. This also means that if dynamic errors occur + (whether or not they are caught using try/catch), it may be unpredictable whether + any output is logged before the error occurs.

+
+ +

If the trace information is unrelated to a specific value, + fn:log can be used instead.

+
+ + +

Consider a situation in which a user wants to investigate the actual value passed to + a function. Assume that in a particular execution, $v is an + xs:decimal with value 124.84. + Writing fn:trace($v, 'the value of $v is:') will output the strings + "124.84" and "the value of $v is:" + in an implementation-dependent order.

+
+
+ + The $label argument can now be set + to an empty sequence. Previously if $label was supplied, it could not be empty. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Outputs trace information and discards the result.

+
+ +

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

+

In contrast to fn:trace, the function returns an empty sequence.

+

The serialization of the log output must not raise an error. + This can e.g. be achieved by using a serialization method that can handle arbitrary + input, such as the .

+

The format of the trace output and its order are + . Therefore, the order in which the output + appears is not predictable. This also means that if dynamic errors occur + (whether or not they are caught using try/catch), it may be unpredictable whether + any output is logged before the error occurs.

+
+ +

The function can be used for debugging. It can also be helpful in productive + environments, e.g. to store dynamic input and evaluations to log files.

+
+ + New function. + +
+ + + + + + + + + Defines the semantics of the + operator when + applied to two numeric values + +

Returns the arithmetic sum of its operands: ($arg1 + $arg2).

+
+ +

General rules: see .

+
+ +

For xs:float or xs:double values, if one of the operands is a + zero or a finite number and the other is INF or -INF, + INF or -INF is returned. If both operands are + INF, INF is returned. If both operands are + -INF, -INF is returned. If one of the operands is + INF and the other is -INF, NaN is + returned.

+
+
+ + + + + + + + Defines the semantics of the - operator when + applied to two numeric values. + +

Returns the arithmetic difference of its operands: ($arg1 - $arg2).

+
+ +

General rules: see .

+
+ +

For xs:float or xs:double values, if one of the operands is a + zero or a finite number and the other is INF or -INF, an + infinity of the appropriate sign is returned. If both operands are INF or + -INF, NaN is returned. If one of the operands is + INF and the other is -INF, an infinity of the appropriate + sign is returned.

+
+
+ + + + + + + + Defines the semantics of the * operator when + applied to two numeric values. + +

Returns the arithmetic product of its operands: ($arg1 * $arg2).

+
+ +

General rules: see .

+
+ +

For xs:float or xs:double values, if one of the operands is a + zero and the other is an infinity, NaN is returned. If one of the operands + is a non-zero number and the other is an infinity, an infinity with the appropriate sign + is returned.

+
+
+ + + + + + + + Defines the semantics of the div operator when + applied to two numeric values. + +

Returns the arithmetic quotient of its operands: ($arg1 div $arg2).

+
+ +

General rules: see .

+

As a special case, if the types of both $arg1 and $arg2 are + xs:integer, then the return type is xs:decimal.

+ +
+ +

A dynamic error is raised for xs:decimal + and xs:integer operands, if the divisor is (positive or negative) zero.

+
+ +

For xs:float and xs:double operands, floating point division + is performed as specified in . A positive number divided by + positive zero returns INF. A negative number divided by positive zero + returns -INF. Division by negative zero returns -INF and + INF, respectively. Positive or negative zero divided by positive or + negative zero returns NaN. Also, INF or -INF + divided by INF or -INF returns NaN.

+
+ +
+ + + + + + + + Defines the semantics of the idiv operator when + applied to two numeric values. + +

Performs an integer division.

+
+ +

General rules: see .

+ +

If $arg2 is INF or -INF, and $arg1 + is not INF or -INF, then the result is zero.

+ +

Otherwise, subject to limits of precision and overflow/underflow conditions, the result + is the largest (furthest from zero) xs:integer value $N such + that the following expression is true:

+ + abs($N * $arg2) le abs($arg1) + and compare($N * $arg2, 0) eq compare($arg1, 0). + +

The second term in this condition ensures that the result has the correct sign.

+
+

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

+
+ +

A dynamic error is raised if the divisor is (positive + or negative) zero.

+

A dynamic error is raised if either operand is + NaN or if $arg1 is INF or + -INF.

+
+ +

Except in situations involving errors, loss of precision, or overflow/underflow, the + result of $a idiv $b is the same as ($a div $b) cast as + xs:integer.

+

The semantics of this function are different from integer division as defined in + programming languages such as Java and C++.

+
+ + + + op:numeric-integer-divide(10,3) + 3 + + + + + op:numeric-integer-divide(3,-2) + -1 + + + + + op:numeric-integer-divide(-3,2) + -1 + + + + + op:numeric-integer-divide(-3,-2) + 1 + + + + + op:numeric-integer-divide(9.0,3) + 3 + + + + + op:numeric-integer-divide(-3.5,3) + -1 + + + + + op:numeric-integer-divide(3.0,4) + 0 + + + + + op:numeric-integer-divide(3.1E1,6) + 5 + + + + + op:numeric-integer-divide(3.1E1,7) + 4 + + + +
+ + + + + + + + Defines the semantics of the mod operator when + applied to two numeric values. + +

Returns the remainder resulting from dividing $arg1, the dividend, by + $arg2, the divisor.

+
+ +

General rules: see .

+

The operation a mod b for operands that are xs:integer or + xs:decimal, or types derived from them, produces a result such that + (a idiv b)*b+(a mod b) is equal to a and the magnitude of + the result is always less than the magnitude of b. This identity holds even + in the special case that the dividend is the negative integer of largest possible + magnitude for its type and the divisor is -1 (the remainder is 0). It follows from this + rule that the sign of the result is the sign of the dividend.

+ +

For xs:float and xs:double operands the following rules + apply:

+ + +

If either operand is NaN, the result is NaN.

+
+ +

If the dividend is positive or negative infinity, or the divisor is positive or + negative zero (0), or both, the result is NaN.

+
+ +

If the dividend is finite and the divisor is an infinity, the result equals the + dividend.

+
+ +

If the dividend is positive or negative zero and the divisor is finite, the result + is the same as the dividend.

+
+ +

In the remaining cases, where neither positive or negative infinity, nor positive + or negative zero, nor NaN is involved, the result obeys (a idiv + b)*b+(a mod b) = a. + + Division is truncating division, analogous to integer division, not rounding division i.e. additional digits are truncated, + not rounded to the required precision.

+
+
+
+ +

A dynamic error is raised for xs:integer + and xs:decimal operands, if $arg2 is zero.

+
+ + + + op:numeric-mod(10,3) + 1 + + + + + op:numeric-mod(6,-2) + 0 + + + + + op:numeric-mod(4.5,1.2) + 0.9 + + + + + op:numeric-mod(1.23E2, 0.6E1) + 3.0E0 + + + +
+ + + + + + + Defines the semantics of the unary + operator + applied to a numeric value. + +

Returns its operand with the sign unchanged: (+ $arg).

+
+ +

General rules: see .

+

The returned value is equal to $arg, and is an instance of + xs:integer, xs:decimal, xs:double, or + xs:float depending on the type of $arg.

+
+ +

Because function conversion rules are applied in the normal way, the unary + + operator can be used to force conversion of an untyped node to a + number: the result of +@price is the same as xs:double(@price) + if the type of @price is xs:untypedAtomic.

+
+
+ + + + + + + Defines the semantics of the unary - operator when + applied to a numeric value. + +

Returns its operand with the sign reversed: (- $arg).

+
+ +

General rules: see .

+

The returned value is an instance of xs:integer, xs:decimal, + xs:double, or xs:float depending on the type of + $arg.

+

For xs:integer and xs:decimal arguments, 0 and + 0.0 return 0 and 0.0, respectively. For + xs:float and xs:double arguments, NaN returns + NaN, 0.0E0 returns -0.0E0 and vice versa. + INF returns -INF. -INF returns + INF.

+
+
+ + + + + + + + Defines the semantics of + the eq operator when applied to two numeric values, and is also used in defining the + semantics of ne, le and ge. + +

Returns true if and only if the value of $arg1 is equal to the value of + $arg2.

+
+ +

General rules: see and .

+
+ +

For xs:float and xs:double values, positive zero and negative + zero compare equal. INF equals INF and -INF + equals -INF. If $arg1 or $arg2 is + NaN, the function returns false.

+
+
+ + + + + + + + Defines the semantics of the + lt operator when applied to two numeric values, and is also used in defining the + semantics of le, gt, and ge. + +

Returns true if and only if $arg1 is numerically less than + $arg2.

+
+ +

General rules: see and .

+
+ +

For xs:float and xs:double values, positive infinity is + greater than all other non-NaN values; negative infinity is less than all + other non-NaN values. Positive and negative zero compare equal. + If $arg1 or $arg2 is + NaN, the function returns false.

+
+
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the absolute value of $value.

+
+ +

General rules: see .

+

If $value is negative the function returns -$value, otherwise it + returns $value.

+

For the four types xs:float, + xs:double, xs:decimal and xs:integer, it is + guaranteed that if the type of $value is an instance of type T then + the result will also be an instance of T. The result may + also be an instance of a type derived from one of these four by restriction. For example, if + $value is an instance of xs:positiveInteger then the value of + $value + may be returned unchanged.

+

For xs:float and xs:double arguments, if the argument is + positive zero or negative zero, then positive zero is returned. If the argument is + positive or negative infinity, positive infinity is returned.

+
+ + + + abs(10.5) + 10.5 + + + + + abs(-10.5) + 10.5 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Rounds $value upwards to a whole number.

+
+ +

General rules: see .

+

The function returns the smallest (closest to negative infinity) number with no + fractional part that is not less than $value.

+

For the four types xs:float, + xs:double, xs:decimal and xs:integer, it is + guaranteed that if the type of $value is an instance of type T then + the result will also be an instance of T. The result may + also be an instance of a type derived from one of these four by restriction. For example, if + $value is an instance of xs:decimal then the result may + be an instance of xs:integer.

+

For xs:float and xs:double arguments, if the argument is + positive zero, then positive zero is returned. If the argument is negative zero, then + negative zero is returned. If the argument is less than zero and greater than -1, + negative zero is returned.

+
+ + + + ceiling(10.5) + 11 + + + + + ceiling(-10.5) + -10 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Rounds $value downwards to a whole number.

+
+ +

General rules: see .

+

The function returns the largest (closest to positive infinity) number with no + fractional part that is not greater than $value.

+

For the four types xs:float, + xs:double, xs:decimal and xs:integer, it is + guaranteed that if the type of $value is an instance of type T then + the result will also be an instance of T. The result may + also be an instance of a type derived from one of these four by restriction. For example, if + $value is an instance of xs:decimal then the result may + be an instance of xs:integer.

+

For xs:float and xs:double arguments, if the argument is + positive zero, then positive zero is returned. If the argument is negative zero, then + negative zero is returned.

+ +
+ + + + floor(10.5) + 10 + + + + + floor(-10.5) + -11 + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Rounds a value to a specified number of decimal places, rounding upwards if two such + values are equally near.

+
+ +

General rules: see .

+

The function returns the nearest (that is, numerically closest) value to + $value that is a multiple of ten to the power of minus + $precision. If two such values are equally near (for example, if the + fractional part in $value is exactly .5), the function returns the one that + is closest to positive infinity.

+

For the four types xs:float, + xs:double, xs:decimal and xs:integer, it is + guaranteed that if the type of $value is an instance of type T then + the result will also be an instance of T. The result may + also be an instance of a type derived from one of these four by restriction. For example, if + $value is an instance of xs:decimal and $precision is + less than one, then the result may + be an instance of xs:integer.

+

The single-argument version of this function produces the same result as the + two-argument version with $precision=0 (that is, it rounds to a whole + number).

+

When $value is of type xs:float and xs:double:

+ + +

If $value is NaN, positive or negative zero, or positive or negative + infinity, then the result is the same as the argument.

+
+ +

For other values, the argument is cast to xs:decimal using an + implementation of xs:decimal that imposes no limits on the number of + digits that can be represented. The function is applied to this + xs:decimal value, and the resulting xs:decimal is + cast back to xs:float or xs:double as appropriate to + form the function result. If the resulting xs:decimal value is zero, + then positive or negative zero is returned according to the sign of + $value.

+
+
+ +
+ +

This function is typically used with a non-zero $precision in financial + applications where the argument is of type xs:decimal. For arguments of + type xs:float and xs:double the results may be + counter-intuitive. For example, consider round(35.425e0, 2). The result is + not 35.43, as might be expected, but 35.42. + This is because the xs:double written as 35.425e0 + has an exact value equal to 35.42499999999..., which is closer to + 35.42 than to 35.43.

+
+ + + + round(2.5) + 3.0 + + + + + round(2.4999) + 2.0 + + + + + round(-2.5) + -2.0 + Not the possible alternative, -3 + + + + + round(1.125, 2) + 1.13 + + + + + round(8452, -2) + 8500 + + + + + round(3.1415e0, 2) + 3.14e0 + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Rounds a value to a specified number of decimal places, rounding to make the last digit + even if two such values are equally near.

+
+ +

General rules: see .

+

The function returns the nearest (that is, numerically closest) value to + $value that is a multiple of ten to the power of minus + $precision. If two such values are equally near (e.g. if the fractional + part in $value is exactly .500...), the function returns the one whose least + significant digit is even.

+

For the four types xs:float, + xs:double, xs:decimal and xs:integer, it is + guaranteed that if the type of $value is an instance of type T then + the result will also be an instance of T. The result may + also be an instance of a type derived from one of these four by restriction. For example, if + $value is an instance of xs:decimal and $precision + is less than one, then the result may + be an instance of xs:integer.

+

The one-argument form of this function produces the same result as the two-argument form + with $precision=0.

+

For arguments of type xs:float and xs:double:

+ + +

If the argument is NaN, positive or negative zero, or positive or + negative infinity, then the result is the same as the argument.

+
+ +

In all other cases, the argument is cast to xs:decimal using an + implementation of xs:decimal that imposes no limits on the number of digits that + can be represented. The function is applied to this xs:decimal value, + and the resulting xs:decimal is cast back to xs:float or + xs:double as appropriate to form the function result. If the + resulting xs:decimal value is zero, then positive or negative zero is + returned according to the sign of the original argument.

+
+
+ +
+ +

This function is typically used in financial applications where the argument is of type + xs:decimal. For arguments of type xs:float and + xs:double the results may be counter-intuitive. For example, consider + round-half-to-even(xs:float(150.015), 2). + The result is not 150.02 as might be expected, but 150.01. + This is because the conversion of the + xs:float value represented by the literal 150.015 to an + xs:decimal produces the xs:decimal + value 150.014999389..., which is closer to + 150.01 than to 150.02.

+
+ + + + round-half-to-even(0.5) + 0.0 + + + + + round-half-to-even(1.5) + 2.0 + + + + + round-half-to-even(2.5) + 2.0 + + + + + round-half-to-even(3.567812e+3, 2) + 3567.81e0 + + + + + round-half-to-even(4.7564e-3, 2) + 0.0e0 + + + + + round-half-to-even(35612.25, -2) + 35600 + + + +
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-independent + focus-independent + + +

Formats an integer according to a given picture string, using the conventions of a given + natural language if specified.

+
+ +

If $value is an empty sequence, the function returns a zero-length + string.

+

In all other cases, the $picture argument describes the format in which + $value is output.

+

The rules that follow describe how non-negative numbers are output. If the value of + $value is negative, the rules below are applied to the absolute value of + $value, and a minus sign is prepended to the result.

+ +

The value of $picture consists of the following, in order:

+ +

An optional radix, which is an integer in the range 2 to 36, written using ASCII + digits (0-9) without any leading zero;

+

A circumflex (^), which is present if the radix is present, and absent otherwise.

+

A circumflex is recognized as marking the presence of a radix only + if (a) it is immediately preceded by an integer + in the range 2 to 36, and (b) it is + followed (somewhere within the primary format token) by an "X" + or "x". In other cases, the circumflex is treated as a grouping separator. + For example, the picture 9^000 outputs the number + 2345 as "2^345", whereas 9^XXX outputs "4451". + This rule is to ensure backwards compatibility.

+
+

A primary format token. This is always present and + must not be zero-length.

+

An optional format modifier.

+

If the string contains one or more + semicolons then the last semicolon is taken as terminating the primary + format token, and everything that follows is taken as the format modifier; if the string + contains no semicolon then + the format modifier is taken to be absent (which is equivalent to supplying a + zero-length string).

+
+ + +

If a radix is present, then the primary format token must follow the + rules for a digit-pattern.

+ + +

The primary format token is classified as one of the following:

+ + +

A digit-pattern made up of optional-digit-signs, + mandatory-digit-signs, and grouping-separator-signs.

+ + + +

The optional-digit-sign is the character #.

+
+ +

If the radix is absent, then + a mandatory-digit-sign is a character in Unicode category Nd. All + mandatory-digit-signs within the format token + must be from the same digit family, where a digit + family is a sequence of ten consecutive characters in Unicode category Nd, + having digit values 0 through 0. + Within the format token, these digits are + interchangeable: a three-digit number may thus be indicated equivalently by + 000, 001, or 999.

+

If the primary format token contains at least one Unicode digit, + then the primary format token is taken + as a decimal digit pattern, and in this case it must match the + regular expression ^((\p{Nd}|#|[^\p{N}\p{L}])+?)$. If it contains a + digit but does not match this pattern, a dynamic error is raised .

+
+ +

If the radix (call it R) is + present (including the case where an explicit radix of 10 is used), then + the character used as the mandatory-digit-sign is either "x" + or "X". If any mandatory-digit-sign is upper-case "X", then all + mandatory-digit-signs must be upper-case "X". The digit family + used in the output comprises the first R characters of the + alphabet 0123456789abcdefghijklmnopqrstuvwxyz, but using upper-case + letters in place of lower-case if an upper-case "X" is used + as the mandatory-digit-sign.

+

In this case the primary format token must match the + regular expression ^(([Xx#]|[^\p{N}\p{L}])+?)$

+
+ +

a grouping-separator-sign is a non-alphanumeric character, that + is a character whose Unicode category is + other than Nd, Nl, No, Lu, Ll, + Lt, Lm or Lo.

+
+
+ + + + +

If a semicolon is to be used as a grouping separator, then the primary format + token as a whole must be followed by another semicolon, to ensure that the + grouping separator is not mistaken as a separator between the primary format + token and the format modifier.

+
+ + +

There must be at least one mandatory-digit-sign. + There may be zero or more optional-digit-signs, and (if present) these + must precede all mandatory-digit-signs. There may + be zero or more grouping-separator-signs. A + grouping-separator-sign + must not appear at the start or end of the + digit-pattern, nor adjacent to another + grouping-separator-sign.

+ +

The corresponding output is a number in the specified radix, using this digit family, with + at least as many digits as there are mandatory-digit-signs in the + format token. Thus:

+ +

A format token 1 generates the sequence 0 1 + 2 ... 10 11 12 ...

+

A format token 01 (or equivalently, + 00 or 99) generates the sequence 00 01 02 ... + 09 10 11 12 ... 99 100 101

+

A format token of &#x661; + (Arabic-Indic digit one) generates the sequence ١ then ٢ + then ٣ ...

+

A format token of 16^xx generates the sequence 00 01 02 03 + ... 08 09 0a 0b 0c 0d 0e 0f 10 11 ...

+

A format token of 16^X generates the sequence 0 1 2 3 + ... 8 9 A B C D E F 10 11 ...

+
+ +

The grouping-separator-signs are handled as follows:

+ + + +

The position of + grouping separators within the format token, counting backwards from the last + digit, indicates the position of grouping separators to appear within the + formatted number, and the character used as the grouping-separator-sign + within the format token indicates the character to be used as the corresponding + grouping separator in the formatted number. +

+
+ +

More specifically, the position of a grouping separator is + the number of optional-digit-signs and mandatory-digit-signs appearing + between the grouping separator and the right-hand end of the primary format token.

+
+ +

Grouping separators are defined to be regular if the following conditions apply:

+ + +

There is at least one grouping separator.

+
+ +

Every grouping separator is the same character (call it C).

+
+ +

There is a positive integer G (the grouping size) such that:

+ + +

The position of every grouping separator is an integer multiple of G, and

+
+ +

Every positive integer multiple of G that is less than the number of + optional-digit-signs and mandatory-digit-signs in the primary format token + is the position of a grouping separator.

+
+
+
+
+
+ +

The grouping separator template is a (possibly infinite) set of (position, character) pairs.

+
+ +

If grouping separators are regular, then the grouping separator template contains one pair of the form (n×G, C) + for every positive integer n where G is the grouping size and C is the grouping character.

+
+ +

Otherwise (when grouping separators are not regular), the grouping separator template contains one pair of the form + (P, C) for every grouping separator found in the primary formatting token, where C is the grouping + separator character and P is its position.

+
+ + +

If there are no grouping separators, then the grouping separator template is an empty set.

+
+
+
+ + +

The number is formatted as follows:

+ + + +

Let S/1 be the result of formatting the supplied number + in the appropriate radix: + for radix 10 this will be the value obtained by casting + it to xs:string.

+
+ +

Let S/2 be the result of padding S/1 on the left with as many leading zeroes + as are needed to ensure that it contains at least as many digits as the number of mandatory-digit-signs + in the primary format token.

+
+ +

Let S/3 be the result of replacing all decimal digits (0-9) in S/2 with the corresponding + digits from the selected digit family. (This has no effect when the selected digit family uses ASCII digits (0-9), + which will always be the case if a radix is specified.)

+
+ +

Let S/4 be the result of inserting grouping separators into S/3: for every (position + P, character C) pair in the grouping separator template where P is less than the number + of digits in S/3, insert character C into S/3 at position P, counting from + the right-hand end.

+
+ +

Let S/5 be the result of converting S/4 into ordinal form, if an ordinal modifier + is present, as described below.

+
+ +

The result of the function is then S/5.

+
+
+ + +
+ + + + + +

The format token A, which generates the sequence A B C ... Z AA + AB AC....

+
+ +

The format token a, which generates the sequence a b c ... z aa + ab ac....

+
+ +

The format token i, which generates the sequence i ii iii iv v + vi vii viii ix x ....

+
+ +

The format token I, which generates the sequence I II III IV V + VI VII VIII IX X ....

+
+ +

The format token w, which generates numbers written as lower-case + words, for example in English, one two three four ... +

+
+ +

The format token W, which generates numbers written as upper-case + words, for example in English, ONE TWO THREE FOUR ... +

+
+ +

The format token Ww, which generates numbers written as title-case + words, for example in English, One Two Three Four ... +

+
+ +

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

+ +

In some traditional numbering sequences additional signs are added to denote + that the letters should be interpreted as numbers; these are not included in + the format token. An example (see also the example below) is classical Greek + where a dexia keraia + (x0374, ʹ) and sometimes an + aristeri keraia + (x0375, ͵) is added.

+
+
+
+

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

+

The above expansions of numbering sequences for format tokens such as a and + i are indicative but not prescriptive. There are various conventions in + use for how alphabetic sequences continue when the alphabet is exhausted, and differing + conventions for how roman numerals are written (for example, IV versus + IIII as the representation of the number 4). Sometimes alphabetic + sequences are used that omit letters such as i and o. This + specification does not prescribe the detail of any sequence other than those sequences + consisting entirely of decimal digits.

+

Many numbering sequences are language-sensitive. This applies especially to the sequence + selected by the tokens w, W and Ww. It also + applies to other sequences, for example different languages using the Cyrillic alphabet + use different sequences of characters, each starting with the letter #x410 (Cyrillic + capital letter A). In such cases, the $language argument specifies which + language conventions are to be used. If the argument is specified, the value + should be either an empty sequence or a value that would be valid + for the xml:lang attribute (see ). Note that this + permits the identification of sublanguages based on country codes (from ISO 3166-1) as + well as identification of dialects and regions within a country.

+

The set of languages for which numbering is supported is implementation-defined. If the $language argument is absent, or is + set to an empty sequence, or is invalid, or is not a language supported by the + implementation, then the number is formatted using the default language from the dynamic + context.

+

The format modifier must be a string that matches the regular + expression ^([co](\(.+\))?)?[at]?$. That is, if it is present it must + consist of one or more of the following, in order:

+ + +

either c or o, optionally followed by a sequence of + characters enclosed between parentheses, to indicate cardinal or ordinal numbering + respectively, the default being cardinal numbering

+
+ +

either a or t, to indicate alphabetic or traditional + numbering respectively, the default being implementation-defined.

+
+
+

If the o modifier is present, this indicates a request to output ordinal + numbers rather than cardinal numbers. For example, in English, when used with the format + token 1, this outputs the sequence 1st 2nd 3rd 4th ..., and + when used with the format token w outputs the sequence first second + third fourth ....

+

The string of characters between the parentheses, if present, is used to select between + other possible variations of cardinal or ordinal numbering sequences. The interpretation + of this string is implementation-defined. No error occurs if the implementation does not + define any interpretation for the defined string.

+ + +

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

+ +

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

+
+ +

A dynamic error is raised if the format token is + invalid, that is, if it violates any mandatory rules (indicated by an emphasized + must or required keyword in the above rules). + For example, the error is raised if the primary format token contains a digit but does + not match the required regular expression.

+
+ + + +

Note the careful distinction between conditions that are errors and conditions where + fallback occurs. The principle is that an error in the syntax of the format picture will + be reported by all processors, while a construct that is recognized by some + implementations but not others will never result in an error, but will instead cause a + fallback representation of the integer to be used.

+
+ +

The following notes apply when a digit-pattern is used:

+ + +

If grouping-separator-signs + appear at regular intervals within the format token, then the sequence is extrapolated to + the left, so grouping separators will be used in the formatted number at every + multiple of N. For example, if the format token is 0'000 + then the number one million will be formatted as 1'000'000, while the + number fifteen will be formatted as 0'015.

+
+ +

The only purpose of optional-digit-signs is to mark the position of + grouping-separator-signs. For example, if the format token is + #'##0 then the number one million will be formatted as + 1'000'000, while the number fifteen will be formatted as + 15. A grouping separator is included in the formatted number only + if there is a digit to its left, which will only be the case if either (a) the + number is large enough to require that digit, or (b) the number of + mandatory-digit-signs in the format token requires insignificant + leading zeros to be present.

+
+ +

Grouping separators are not designed for effects such as + formatting a US telephone number as (365)123-9876. In general they are not + suitable for such purposes because (a) only single characters are allowed, and (b) they + cannot appear at the beginning or end of the number.

+
+ +

Numbers will never be truncated. Given the digit-pattern + 01, the number three hundred will be output as 300, + despite the absence of any optional-digit-sign.

+
+ +
+
+ +

The following notes apply when ordinal numbering is selected using the o modifier.

+

In some languages, the form of numbers (especially ordinal numbers) varies depending + on the grammatical context: they may have different genders and may decline with the + noun that they qualify. In such cases the string appearing in parentheses after the + letter c or o may be used to indicate the variation of the + cardinal or ordinal number required.

+ +

The way in which the variation is indicated will depend on the conventions of the language.

+ +

For inflected languages that vary the ending of the word, the approach recommended + in the previous version of this specification was to indicate the required ending, + preceded by a hyphen: for example in German, appropriate values might be + o(-e), o(-er), o(-es), o(-en). +

+

Another approach, which might usefully be adopted by an implementation based on the + open-source ICU localization library , or any other library making use of the + Unicode Common Locale Data Repository , is to allow the value in parentheses + to be the name of a registered numbering rule set for the language in question, + conventionally prefixed with a percent sign: for example, + o(%spellout-ordinal-masculine), or c(%spellout-cardinal-year). +

+ +
+ +
+ + +
+ + + + format-integer(123, '0000') + "0123" + + + +

format-integer(123, 'w') might return "one hundred and + twenty-three"

+
+ +

Ordinal numbering in Italian: The specification "1;o(-º)" with $language equal to + it, if supported, should produce the sequence:

+ 1º 2º 3º 4º ... +

The specification "Ww;o" with $language equal to + it, if supported, should produce the sequence:

+ Primo Secondo Terzo Quarto Quinto ... +
+ + + format-integer(21, '1;o', 'en') + "21st" + + + +

format-integer(14, 'Ww;o(-e)', 'de') might return + "Vierzehnte"

+
+ + + format-integer(7, 'a') + "g" + + + + + format-integer(57, 'I') + "LVII" + + + + + format-integer(1234, '#;##0;') + "1;234" + + + + + format-integer(1234, '16^xxxx') + "04d2" + + + + + format-integer(1234, '16^X') + "4D2" + + + + + format-integer(12345678, '16^xxxx_xxxx') + "00bc_614e" + + + + + format-integer(12345678, '16^#_xxxx') + "bc_614e" + + + + + format-integer(255, '2^xxxx xxxx') + "1111 1111" + + + + + format-integer(1023, '32^XXXX') + "00VV" + + + + + format-integer(1023, '10^XXXX') + "1023" + + + + + format-integer(1023, '10^00') + "10^23" + + +
+
+ + + + + + + + + + deterministic + context-independent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns a string containing a number formatted according to a given picture string, + taking account of decimal formats specified in the static context.

+
+ +

The effect of the two-argument form of the function is equivalent to calling the + three-argument form with an empty sequence as the value of the third argument.

+

The function formats $value as a string using the picture string specified by the + $picture argument and the decimal-format named by the + $decimal-format-name argument, or the unnamed decimal-format, if there + is no $decimal-format-name argument. The syntax of the picture string is + described in .

+

The $value argument may be of any numeric data type + (xs:double, xs:float, xs:decimal, or their + subtypes including xs:integer). Note that if an xs:decimal is + supplied, it is not automatically promoted to an xs:double, as such + promotion can involve a loss of precision.

+

If the supplied value of the $value argument is an empty sequence, the + function behaves as if the supplied value were the xs:double value + NaN.

+

The value of $decimal-format-name, if present and non-empty, + must be either an xs:QName, + or a string which after removal of leading and trailing + whitespace is in the form of an EQName as defined in the XPath 4.0 + grammar, that is one of the following:

+ + + +

A lexical QName, which is expanded using the statically known namespaces. The + default namespace is not used (no prefix means no namespace).

+
+ +

A URIQualifiedName using the syntax Q{uri}local, where + the URI can be zero-length to indicate a name in no namespace.

+
+
+ + +

The decimal format that is used is the decimal format in the static context whose name + matches $decimal-format-name if supplied, or the unnamed decimal format in + the static context otherwise.

+ +

The evaluation of the fn:format-number function takes place in two + phases, an analysis phase described in and a + formatting phase described in .

+ +

The analysis phase takes as its inputs the picture + string and the variables derived from the relevant decimal format in the + static context, and produces as its output a number of variables with defined values. + The formatting phase takes as its inputs the number to be formatted and the variables + produced by the analysis phase, and produces as its output a string containing a + formatted representation of the number.

+ +

The result of the function is the formatted string representation of the supplied + number.

+ +
+ +

A dynamic error is raised + if + the $decimal-format-name argument is supplied as an xs:string + that is neither a valid lexical QName nor a + valid URIQualifiedName, or if it uses a prefix that is not found in the + statically known namespaces, or if the static context does not contain a declaration of + a decimal-format with a matching expanded QName. If the processor is able to detect the + error statically (for example, when the argument is supplied as a string literal), then + the processor may optionally signal this as a static error.

+
+ +

A string is an ordered sequence of characters, and this specification + uses terms such as “left” and “right”, “preceding” and “following” in relation to this ordering, + irrespective of the position of the characters when visually rendered on some output medium. + Both in the picture string and in the result string, digits with higher significance (that is, + representing higher powers of ten) always precede digits with lower significance, even when + the rendered text flow is from right to left.

+
+ + +

The following examples assume a default decimal format in which the chosen digits are + the ASCII digits 0-9, the decimal separator is ., the grouping separator is ,, + the minus-sign is -, and the percent-sign is %.

+ + format-number(12345.6, '#,###.00') + "12,345.60" + + + format-number(12345678.9, '9,999.99') + "12,345,678.90" + + + format-number(123.9, '9999') + "0124" + + + format-number(0.14, '01%') + "14%" + + + format-number(-6, '000') + "-006" + +

The following example assumes the existence of a decimal format named ch in which + the grouping separator is ʹ and the decimal separator is + ·:

+ + format-number( + 1234.5678, + '#ʹ##0·00', + 'ch' +) + "1ʹ234·57" + +

The following examples assume that the exponent separator is + in decimal format fortran is E:

+ + format-number(1234.5678, '00.000E0', 'fortran') + "12.346E2" + + + format-number(0.234, '0.0E0', 'fortran') + "2.3E-1" + + + format-number(0.234, '#.00E0', 'fortran') + "0.23E0" + + + format-number(0.234, '.00E0', 'fortran') + ".23E0" + +
+
+ + The decimal format name can now be supplied as a value of type xs:QName, + as an alternative to supplying a lexical QName as an instance of xs:string. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Converts a string to an integer, recognizing any radix in the range 2 to 36.

+
+ + +

The supplied $radix must be in the range 2 to 36 inclusive.

+

The string $value is preprocessed by stripping all whitespace characters (including internal whitespace) + and underscore characters.

+

After this process, the supplied value + must consist of an optional sign (+ or -) + followed by a sequence of one or more generalized digits drawn from the first $radix characters + in the alphabet 0123456789abcdefghijklmnopqrstuvwxyz; upper case alphabetics + A-Z may be used in place of their lower-case equivalents.

+

The value of a generalized digit corresponds to its position in this alphabet. + More formally, in non-error cases the result of the function is given by the XQuery expression:

+ +
+ +

A dynamic error is raised + if $radix is not in the range 2 to 36.

+

A dynamic error is raised + if after stripping whitespace and underscores and the optional leading sign + $value is a zero-length string, + or if it contains a character + that is not among the first $radix characters in the + alphabet 0123456789abcdefghijklmnopqrstuvwxyz, or the + upper-case equivalent of such a character.

+

A dynamic error is raised + if the value of the resulting integer exceeds the implementation-dependent + limit on the size of an xs:integer.

+ +
+ +

When $radix takes its default value of 10, + the function delivers the same result as casting $value + (after removal of whitespace and underscores) to xs:integer.

+

If underscores or whitespace in the input need to be rejected, then + the string should first be validated, perhaps using fn:matches.

+

If other characters may legitimately appear in the input, for example + a leading 0x, then this must first be removed by pre-processing the input.

+

If the input uses a different family of digits, then the value should first + be converted to the required digits using fn:translate.

+

A string in the lexical space of xs:hexBinary will always + be an acceptable input, provided it is not too long. So, for example, the expression + "1DE=" => xs:base64Binary() => xs:hexBinary() => xs:string() => parse-integer(16) + can be used to convert the Base 64 value 1DE= to the integer 54321, via the + hexadecimal string D431.

+
+ + + + parse-integer(" 200 ") + 200 + + + parse-integer("-20") + -20 + + + parse-integer(" +100") + 100 + + + parse-integer("ff", 16) + 255 + + + parse-integer("FFFF FFFF", 16) + 4294967295 + + + parse-integer("-FFFF_FFFF", 16) + -4294967295 + + + parse-integer("377", 8) + 255 + + + parse-integer("101", 2) + 5 + + + parse-integer("vv", 32) + 1023 + +

Alphabetic base-26 numbering systems (hexavigesimal) can be parsed via translation. + Note, enumerating systems that do not assign a symbol to zero (e.g., spreadsheet + columns) must be preprocessed in a different fashion.

+ + lower-case("AAB") +=> translate("abcdefghijklmnopqrstuvwxyz", "0123456789abcdefghijklmnop") +=> parse-integer(26) + 1 + +

Digit-based numeration systems comparable to the Arabic numbers 0 through 9 can be + parsed via translation.

+ + translate('٢٠٢٣', '٠١٢٣٤٥٦٧٨٩', '0123456789') +=> parse-integer() + 2023 + +
+
+
+ + + + + + deterministic + context-independent + focus-independent + + +

Returns an approximation to the mathematical constant π.

+
+ +

This function returns the xs:double value whose lexical representation is + 3.141592653589793e0

+
+ + + + 2*math:pi() + 6.283185307179586e0 + + + +

The expression 60 * (math:pi() div 180) converts an angle of 60 degrees + to radians.

+
+
+
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the value of ex where x is the argument value.

+
+ +

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

+

Otherwise the result is the mathematical constant e raised to the power of + $value, as defined in the specification of + the exp function applied to 64-bit binary floating point values.

+
+ +

The treatment of overflow and underflow is defined in .

+
+ + + + math:exp(()) + () + + + math:exp(0) + 1.0e0 + + + math:exp(1) + 2.7182818284590455e0 + + + math:exp(2) + 7.38905609893065e0 + + + math:exp(-1) + 0.36787944117144233e0 + + + math:exp(math:pi()) + 23.140692632779267e0 + + + math:exp(xs:double('NaN')) + xs:double('NaN') + + + math:exp(xs:double('INF')) + xs:double('INF') + + + math:exp(xs:double('-INF')) + 0.0e0 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the value of 10x, where x is the supplied argument value.

+
+ +

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

+

Otherwise the result is ten raised to the power of $value, as defined in the + specification of the exp10 function applied + to 64-bit binary floating point values.

+
+ +

The treatment of overflow and underflow is defined in .

+
+ + + + math:exp10(()) + () + + + math:exp10(0) + 1.0e0 + + + math:exp10(1) + 1.0e1 + + + math:exp10(0.5) + 3.1622776601683795e0 + + + math:exp10(-1) + 1.0e-1 + + + math:exp10(xs:double('NaN')) + xs:double('NaN') + + + math:exp10(xs:double('INF')) + xs:double('INF') + + + math:exp10(xs:double('-INF')) + 0.0e0 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the natural logarithm of the argument.

+
+ +

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

+

Otherwise the result is the natural logarithm of $value, as defined in the + specification of the log function applied + to 64-bit binary floating point values.

+
+ +

The treatment of divideByZero and invalidOperation exceptions + is defined in . The effect is that if the argument is + zero, the result is -INF, and if it is negative, the result is NaN.

+
+ + + + math:log(()) + () + + + math:log(0) + xs:double('-INF') + + + math:log(math:exp(1)) + 1.0e0 + + + math:log(1.0e-3) + -6.907755278982137e0 + + + math:log(2) + 0.6931471805599453e0 + + + math:log(-1) + xs:double('NaN') + + + math:log(xs:double('NaN')) + xs:double('NaN') + + + math:log(xs:double('INF')) + xs:double('INF') + + + math:log(xs:double('-INF')) + xs:double('NaN') + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the base-ten logarithm of the argument.

+
+ +

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

+

Otherwise the result is the base-10 logarithm of $value, as defined in the + specification of the log10 function applied + to 64-bit binary floating point values.

+
+ +

The treatment of divideByZero and invalidOperation exceptions + is defined in . The effect is that if the argument is + zero, the result is -INF, and if it is negative, the result is NaN.

+
+ + + + math:log10(()) + () + + + math:log10(0) + xs:double('-INF') + + + math:log10(1.0e3) + 3.0e0 + + + math:log10(1.0e-3) + -3.0e0 + + + math:log10(2) + 0.3010299956639812e0 + + + math:log10(-1) + xs:double('NaN') + + + math:log10(xs:double('NaN')) + xs:double('NaN') + + + math:log10(xs:double('INF')) + xs:double('INF') + + + math:log10(xs:double('-INF')) + xs:double('NaN') + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the non-negative square root of the argument.

+
+ +

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

+

Otherwise the result is the mathematical non-negative square root of $value + as defined in the specification of the + squareRoot function applied to 64-bit binary floating point values.

+
+ + +

The treatment of the invalidOperation exception is defined in . The effect is that if the argument is less than zero, the result + is NaN.

+ +

If $value is positive or negative zero, positive infinity, or + NaN, then the result is $value. (Negative zero is the only + case where the result can have negative sign)

+
+ + + + math:sqrt(()) + () + + + math:sqrt(0.0e0) + 0.0e0 + + + math:sqrt(-0.0e0) + -0.0e0 + + + math:sqrt(1.0e6) + 1.0e3 + + + math:sqrt(2.0e0) + 1.4142135623730951e0 + + + math:sqrt(-2.0e0) + xs:double('NaN') + + + math:sqrt(xs:double('NaN')) + xs:double('NaN') + + + math:sqrt(xs:double('INF')) + xs:double('INF') + + + math:sqrt(xs:double('-INF')) + xs:double('NaN') + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the result of raising the first argument to the power of the second.

+
+ +

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

+

If $y is an instance of xs:integer, the result is + $x raised to the power of $y as defined in the specification of the pown function applied to a + 64-bit binary floating point value and an integer.

+

Otherwise $y is converted to an xs:double by numeric + promotion, and the result is $x raised to the power of + $y as defined in the specification of the + pow function applied to two 64-bit binary floating point values.

+
+ + +

The treatment of the divideByZero and invalidOperation + exceptions is defined in . Some of the consequences are + illustrated in the examples below.

+ +
+ + + + math:pow((), 93.7) + () + + + math:pow(2, 3) + 8.0e0 + + + math:pow(-2, 3) + -8.0e0 + + + math:pow(2, -3) + 0.125e0 + + + math:pow(-2, -3) + -0.125e0 + + + math:pow(2, 0) + 1.0e0 + + + math:pow(0, 0) + 1.0e0 + + + math:pow(xs:double('INF'), 0) + 1.0e0 + + + math:pow(xs:double('NaN'), 0) + 1.0e0 + + + math:pow(-math:pi(), 0) + 1.0e0 + + + math:pow(0e0, 3) + 0.0e0 + + + math:pow(0e0, 4) + 0.0e0 + + + math:pow(-0e0, 3) + -0.0e0 + + + math:pow(0, 4) + 0.0e0 + + + math:pow(0e0, -3) + xs:double('INF') + + + math:pow(0e0, -4) + xs:double('INF') + + + math:pow(-0e0, -3) + xs:double('-INF') + + + math:pow(0, -4) + xs:double('INF') + + + math:pow(16, 0.5e0) + 4.0e0 + + + math:pow(16, 0.25e0) + 2.0e0 + + + math:pow(0e0, -3.0e0) + xs:double('INF') + + + math:pow(-0e0, -3.0e0) + xs:double('-INF') + Odd-valued whole numbers are treated specially + + + math:pow(0e0, -3.1e0) + xs:double('INF') + + + math:pow(-0e0, -3.1e0) + xs:double('INF') + + + math:pow(0e0, 3.0e0) + 0.0e0 + + + math:pow(-0e0, 3.0e0) + -0.0e0 + Odd-valued whole numbers are treated specially + + + math:pow(0e0, 3.1e0) + 0.0e0 + + + math:pow(-0e0, 3.1e0) + 0.0e0 + + + math:pow(-1, xs:double('INF')) + 1.0e0 + + + math:pow(-1, xs:double('-INF')) + 1.0e0 + + + math:pow(1, xs:double('INF')) + 1.0e0 + + + math:pow(1, xs:double('-INF')) + 1.0e0 + + + math:pow(1, xs:double('NaN')) + 1.0e0 + + + math:pow(-2.5e0, 2.0e0) + 6.25e0 + + + math:pow(-2.5e0, 2.00000001e0) + xs:double('NaN') + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the sine of the argument. The argument is an angle in radians.

+
+ +

If $radians is the empty sequence, the function returns the empty + sequence.

+ +

Otherwise the result is the sine of $radians (which is treated as an angle in + radians) as defined in the specification of the + sin function applied to 64-bit binary floating point values.

+ +
+ +

The treatment of the invalidOperation and underflow exceptions + is defined in .

+

If $radians is positive or negative zero, the result is + $radians.

+

If $radians is positive or negative infinity, or NaN, + then the result is NaN.

+

Otherwise the result is always in the range -1.0e0 to +1.0e0

+
+ + + + math:sin(()) + () + + + math:sin(0) + 0.0e0 + + + math:sin(-0.0e0) + -0.0e0 + + + math:sin(math:pi() div 2) + 1.0e0 + + + math:sin(-math:pi() div 2) + -1.0e0 + + + math:sin(math:pi()) + 0.0e0 + + + math:sin(xs:double('NaN')) + xs:double('NaN') + + + math:sin(xs:double('INF')) + xs:double('NaN') + + + math:sin(xs:double('-INF')) + xs:double('NaN') + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the cosine of the argument. The argument is an angle in radians.

+
+ +

If $radians is the empty sequence, the function returns the empty + sequence.

+

If $radians is positive or negative infinity, or NaN, + then the result is NaN.

+

Otherwise the result is the cosine of $θ (which is treated as an angle in + radians) as defined in the specification of the + cos function applied to 64-bit binary floating point values.

+
+ +

The treatment of the invalidOperation exception is defined in .

+

If $radians is positive or negative zero, the result is + $radians.

+

If $radiansis positive or negative infinity, or NaN, + then the result is NaN.

+

Otherwise the result is always in the range -1.0e0 to +1.0e0

+
+ + + + math:cos(()) + () + + + math:cos(0) + 1.0e0 + + + math:cos(-0.0e0) + 1.0e0 + + + math:cos(math:pi() div 2) + 0.0e0 + + + math:cos(-math:pi() div 2) + 0.0e0 + + + math:cos(math:pi()) + -1.0e0 + + + math:cos(xs:double('NaN')) + xs:double('NaN') + + + math:cos(xs:double('INF')) + xs:double('NaN') + + + math:cos(xs:double('-INF')) + xs:double('NaN') + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the tangent of the argument. The argument is an angle in radians.

+
+ +

If $radians is the empty sequence, the function returns the empty + sequence.

+

Otherwise the result is the tangent of $radians (which is treated as an angle + in radians) as defined in the specification of the + tan function applied to 64-bit binary floating point values.

+ +
+ +

The treatment of the invalidOperation and underflow exceptions + is defined in .

+

If $radians is positive or negative infinity, or NaN, + then the result is NaN.

+
+ + + + math:tan(()) + () + + + math:tan(0) + 0.0e0 + + + math:tan(-0.0e0) + -0.0e0 + + + math:tan(math:pi() div 4) + 1.0e0 + + + math:tan(-math:pi() div 4) + -1.0e0 + + + 1 div math:tan(math:pi() div 2) + 0.0e0 + Mathematically, tan(π/2) is positive infinity. But because math:pi() div 2 + returns an approximation, the result of math:tan(math:pi() div 2) will be a large + but finite number. + + + 1 div math:tan(-math:pi() div 2) + -0.0e0 + Mathematically, tan(-π/2) is negative infinity. But because -math:pi() div 2 + returns an approximation, the result of math:tan(-math:pi() div 2) will be a large + but finite negative number. + + + math:tan(math:pi()) + 0.0e0 + + + math:tan(xs:double('NaN')) + xs:double('NaN') + + + math:tan(xs:double('INF')) + xs:double('NaN') + + + math:tan(xs:double('-INF')) + xs:double('NaN') + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the arc sine of the argument.

+
+ +

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

+

Otherwise the result is the arc sine of $value as defined in the specification of the + asin function applied to 64-bit binary floating point values. + The result is in the range -π/2 to +π/2 radians.

+
+ +

The treatment of the invalidOperation and underflow exceptions + is defined in .

+

If $value is positive or negative zero, the result is $value.

+

If $value is NaN, or if its absolute value is greater than one, + then the result is NaN.

+

In other cases the result is an xs:double value representing an angle + θ in radians in the range -π/2 <= + θ <= +π/2.

+
+ + + + math:asin(()) + () + + + math:asin(0) + 0.0e0 + + + math:asin(-0.0e0) + -0.0e0 + + + math:asin(1.0e0) + 1.5707963267948966e0 + + + math:asin(-1.0e0) + -1.5707963267948966e0 + + + math:asin(2.0e0) + xs:double('NaN') + + + math:asin(xs:double('NaN')) + xs:double('NaN') + + + math:asin(xs:double('INF')) + xs:double('NaN') + + + math:asin(xs:double('-INF')) + xs:double('NaN') + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the arc cosine of the argument.

+
+ +

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

+

Otherwise the result is the arc cosine of $value, as defined in the specification of the + acos function applied to 64-bit binary floating point values. + The result is in the range zero to +π radians.

+
+ +

The treatment of the invalidOperation exception is defined in .

+

If $value is NaN, or if its absolute value is greater than one, + then the result is NaN.

+

In other cases the result is an xs:double value representing an angle + θ in radians in the range 0 <= θ <= + +π.

+
+ + + + math:acos(()) + () + + + math:acos(0) + 1.5707963267948966e0 + + + math:acos(-0.0e0) + 1.5707963267948966e0 + + + math:acos(1.0e0) + 0.0e0 + + + math:acos(-1.0e0) + 3.141592653589793e0 + + + math:acos(2.0e0) + xs:double('NaN') + + + math:acos(xs:double('NaN')) + xs:double('NaN') + + + math:acos(xs:double('INF')) + xs:double('NaN') + + + math:acos(xs:double('-INF')) + xs:double('NaN') + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the arc tangent of the argument.

+
+ +

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

+

Otherwise the result is the arc tangent of $value, as defined + in the specification of the + atan function applied to 64-bit binary floating point values. + The result is in the range -π/2 + to +π/2 radians.

+
+ +

The treatment of the underflow exception is defined in .

+

If $value is positive or negative zero, the result is $value.

+

If $value is NaN then the result is NaN.

+

In other cases the result is an xs:double value representing an angle + θ in radians in the range -π/2 <= + θ <= +π/2.

+
+ + + + math:atan(()) + () + + + math:atan(0) + 0.0e0 + + + math:atan(-0.0e0) + -0.0e0 + + + math:atan(1.0e0) + 0.7853981633974483e0 + + + math:atan(-1.0e0) + -0.7853981633974483e0 + + + math:atan(xs:double('NaN')) + xs:double('NaN') + + + math:atan(xs:double('INF')) + 1.5707963267948966e0 + + + math:atan(xs:double('-INF')) + -1.5707963267948966e0 + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the angle in radians subtended at the origin by the point on a plane with + coordinates (x, y) and the positive x-axis.

+
+ +

The result is the value of atan2(y, x) as defined in the specification of the atan2 function applied to + 64-bit binary floating point values. The result is in the range -π + to +π radians.

+
+ +

The treatment of the underflow exception is defined in . The following rules apply when the values are finite and non-zero, + (subject to rules for overflow, underflow and approximation).

+

If either argument is NaN then the result is NaN.

+

If $x is positive, then the value of atan2($y, + $x) is atan($y div $x).

+

If $x is negative, then:

+ +

If $y is positive, then the value of atan2($y, $x) is + atan($y div $x) + π.

+

If $y is negative, then the value of atan2($y, $x) is + atan($y div $x) - π.

+
+

Some results for special values of the arguments are shown in the examples below.

+ +
+ + + + + + math:atan2(+0.0e0, 0.0e0) + 0.0e0 + + + math:atan2(-0.0e0, 0.0e0) + -0.0e0 + + + math:atan2(+0.0e0, -0.0e0) + 3.141592653589793e0 + + + math:atan2(-0.0e0, -0.0e0) + -3.141592653589793e0 + + + math:atan2(-1, 0.0e0) + -1.5707963267948966e0 + + + math:atan2(+1, 0.0e0) + 1.5707963267948966e0 + + + math:atan2(-0.0e0, -1) + -3.141592653589793e0 + + + math:atan2(+0.0e0, -1) + 3.141592653589793e0 + + + math:atan2(-0.0e0, +1) + -0.0e0 + + + math:atan2(+0.0e0, +1) + +0.0e0 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an xs:string whose characters have supplied codepoints.

+
+ +

The function returns the string made up from the characters whose Unicode codepoints are + supplied in $values. This will be the zero-length string if $values + is the empty sequence.

+ +
+ +

A dynamic error is raised if any of the codepoints in + $values is not a + permitted character.

+
+ + + + codepoints-to-string((66, 65, 67, 72)) + "BACH" + + + codepoints-to-string((2309, 2358, 2378, 2325)) + "अशॊक" + + + codepoints-to-string(()) + "" + + + codepoints-to-string(0) + + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the sequence of codepoints that constitute an + xs:string value.

+
+ +

The function returns a sequence of integers, each integer being the Unicode codepoint of the corresponding character in $value.

+

If $value is a zero-length string or the empty sequence, the function returns + the empty sequence.

+
+ + + + string-to-codepoints("Thérèse") + (84, 104, 233, 114, 232, 115, 101) + + + +
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns -1, 0, or 1, + depending on whether $value1 collates before, + equal to, or after $value2 according to the rules of a selected + collation.

+
+ +

Returns -1, 0, or 1, + depending on whether $value1 is + respectively less than, equal to, or greater than $value2, + according to the rules of the collation that is used.

+

The collation used by this function is determined according to the rules in .

+

If either $value1 or $value2 is the empty sequence, + the function returns the empty sequence.

+

This function, when used with the default collation, defines the semantics of the eq, ne, + gt, lt, le and ge operators on xs:string values.

+
+ + + + compare('abc', 'abc') + 0 + + + + + compare('Strasse', 'Straße') + 0 + Assuming the default collation includes provisions that equate + ss and the (German) character ß + (sharp-s). Otherwise, the returned value depends on the + semantics of the default collation. + + + + + compare( + 'Strasse', + 'Straße', + 'http://www.w3.org/2013/collation/UCA?lang=de;strength=primary' +) + 0 + The specified collation equates + ss and the (German) character ß + (sharp-s). + + + + + compare('Strassen', 'Straße') + 1 + Assuming the default collation includes provisions that treat + differences between ss and the (German) character ß + (sharp-s) with less strength than the differences between the + base characters, such as the final n. + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns true if two strings are equal, considered codepoint-by-codepoint.

+
+ +

If either argument is the empty sequence, the function returns the empty sequence.

+

Otherwise, the function returns true or false depending on + whether $value1 is equal to + $value2, according to the Unicode codepoint collation + (http://www.w3.org/2005/xpath-functions/collation/codepoint).

+ +
+ +

This function allows xs:anyURI values to be compared without having to + specify the Unicode codepoint collation.

+
+ + + + codepoint-equal("abcd", "abcd") + true() + + + codepoint-equal("abcd", "abcd ") + false() + + + codepoint-equal("", "") + true() + + + codepoint-equal("", ()) + () + + + codepoint-equal((), ()) + () + + + +
+ + + + + + + + + The two-argument form of + this function defines the semantics of the || operator. + + deterministic + context-independent + focus-independent + + +

Returns the concatenation of the string values of the arguments.

+
+ +

This function accepts two or more xs:anyAtomicType arguments and casts each + one to xs:string. The function returns the xs:string that is + the concatenation of the values of its arguments after conversion. If any argument is + the empty sequence, that argument is treated as the zero-length string.

+

The fn:concat function is specified to allow two or more arguments, which + are concatenated together. This is the only function specified in this document that + allows a variable number of arguments. This capability is retained for compatibility + with .

+
+ +

As mentioned in Unicode normalization is not automatically + applied to the result of fn:concat. If a normalized result is required, + fn:normalize-unicode can be applied to the xs:string + returned by fn:concat. The following XQuery:

+ +let $v1 := "I plan to go to Mu" +let $v2 := "?nchen in September" +return concat($v1, $v2) +

where the ? represents either the actual Unicode character COMBINING DIARESIS + (Unicode codepoint U+0308) or &#x0308;, will return:

+

"I plan to go to Mu?nchen in September"

+

where the ? represents either the actual Unicode character COMBINING DIARESIS + (Unicode codepoint U+0308) or &#x0308;. + It is worth noting that the returned value is not normalized in NFC; however, it is normalized in NFD.

+

However, the following XQuery:

+ +let $v1 := "I plan to go to Mu" +let $v2 := "?nchen in September" +return normalize-unicode(concat($v1, $v2)) +

where ? represents either the actual Unicode character COMBINING DIARESIS + (Unicode codepoint U+0308) or &#x0308;, will return:

+

"I plan to go to München in September"

+

This returned result is normalized in NFC.

+
+ + + + concat('un', 'grateful') + "ungrateful" + + + + + concat( + 'Thy ', (), 'old ', "groans", "", ' ring', + ' yet', ' in', ' my', ' ancient',' ears.' +) + "Thy old groans ring yet in my ancient ears." + + + + + concat('Ciao!',()) + "Ciao!" + + + + + concat('Ingratitude, ', 'thou ', + 'marble-hearted', ' fiend!') + "Ingratitude, thou marble-hearted fiend!" + + + + + concat(01, 02, 03, 04, true()) + "1234true" + + + + + 10 || '/' || 6 + "10/6" + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a string created by concatenating the items in a sequence, with a defined + separator between adjacent items.

+
+ +

The effect of calling the single-argument version of this function is the same as + calling the two-argument version with $separator set to a zero-length + string.

+

The function returns an xs:string created by casting each item + in the sequence $values to an xs:string, + and then concatenating the result strings in order, + using the value of $separator as a + separator between adjacent strings. If $separator is the zero-length + string, then the items in $values are concatenated without a separator.

+ +
+ +

If $values is the empty sequence, the function returns the + zero-length string.

+
+ + + + string-join(1 to 9) + "123456789" + + + + + string-join(('Now', 'is', 'the', 'time', '...'), ' ') + "Now is the time ..." + + + + + string-join( + ('Blow, ', 'blow, ', 'thou ', 'winter ', 'wind!'), + '' +) + "Blow, blow, thou winter wind!" + + + + + string-join((), 'separator') + "" + + + + + string-join(1 to 5, ', ') + "1, 2, 3, 4, 5" + + + + <doc> + <chap> + <section xml:id="xyz"/> + </chap> +</doc> + + + $doc//@xml:id +! string-join((node-name(), '="', ., '"')) + 'xml:id="xyz"' + + + + + $doc//section +! string-join(ancestor-or-self::*/name(), '/') + "doc/chap/section" + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the part of $value beginning at the position + indicated by $start and continuing for the number of characters indicated by $length.

+
+ +

If $value is the empty sequence, the function returns + the zero-length string.

+

Otherwise, the function returns a string comprising those characters of $value whose index position (counting + from one) is greater than or equal to $start (rounded to an + integer), and (if $length is specified + and non-empty) less than the sum of + $start and $length (both rounded to integers).

+

The characters returned do not extend beyond $value. If + $start is zero or negative, only those characters in positions greater + than zero are returned.

+

More specifically, the three argument version of the function returns the characters in + $value whose position $p satisfies:

+

+ fn:round($start) <= $p and $p < fn:round($start) + fn:round($length) +

+

The two argument version of the function assumes that $length is infinite + and thus returns the characters in + $value whose position $p satisfies:

+

+ fn:round($start) <= $p +

+

In the above computations, the rules for op:numeric-less-than and + op:numeric-greater-than apply.

+
+ +

The first character of a string is located at position 1, not position 0.

+

The second and third arguments allow xs:double values (rather than + requiring xs:integer) in order to achieve compatibility with XPath 1.0.

+

A surrogate pair counts as one character, not two.

+

The consequences of supplying values such as NaN or positive or negative + infinity for the $start or $length arguments follow from the + above rules, and are not always intuitive.

+
+ + + + substring("motor car", 6) + " car" + Characters starting at position 6 to the end of + $sourceString are selected. + +

+ + + + substring("metadata", 4, 3) + "ada" + Characters at positions greater than or equal to 4 and less than 7 are + selected. + + + + + substring("12345", 1.5, 2.6) + "234" + Characters at positions greater than or equal to 2 and less than 5 are + selected. + + + + + substring("12345", 0, 3) + "12" + Characters at positions greater than or equal to 0 and less than 3 are + selected. Since the first position is 1, these are the characters at positions 1 + and 2. + + + + + substring("12345", 5, -3) + "" + Characters at positions greater than or equal to 5 and less than 2 are + selected. + + + + + substring("12345", -3, 5) + "1" + Characters at positions greater than or equal to -3 and less than 2 + are selected. Since the first position is 1, this is the character at position + 1. + + + + + substring("12345", 0 div 0E0, 3) + "" + Since 0 div 0E0 returns NaN, and + NaN compared to any other number returns false, no + characters are selected. + + + + + substring("12345", 1, 0 div 0E0) + "" + As above. + + + + + substring((), 1, 3) + "" + + + + + substring("12345", -42, 1 div 0E0) + "12345" + Characters at positions greater than or equal to -42 and less than + INF are selected. + + + + + substring("12345", -1 div 0E0, 1 div 0E0) + "" + Since the value of -INF + INF is NaN, no + characters are selected. + + + + + The third argument can now be supplied as an empty sequence. + + + + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the number of characters in a string.

+ + +

The function returns an xs:integer equal to the length in characters of $value.

+

Calling the zero-argument version of the function is equivalent to calling + fn:string-length(fn:string(.)).

+

If $value is the empty sequence, the function returns the + xs:integer value 0.

+
+ +

If $value is not specified and the context item is absent, a dynamic error is raised: .

+
+ +

Unlike some programming languages, a codepoint + greater than 65535 counts as one character, not two.

+

There are situations where fn:string-length() has a different effect + from fn:string-length(.). For example, if the context item + is an attribute node typed as an xs:integer with the string value 000001, + then fn:string-length() returns 6 + (the length of the string value of the node), while + fn:string-length(.) raises a type error (because the result of atomization + is not an xs:string).

+
+ + + + string-length( + "Harp not on that string, madam; that is past." +) + 45 + + + + + string-length(()) + 0 + + + +
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns $value with leading and trailing whitespace removed, and + sequences of internal whitespace reduced to a single space character.

+
+ +

If $value is the empty sequence, the function returns the + zero-length string.

+

The function returns a string constructed by stripping leading and trailing whitespace + from $value, and replacing sequences of one or more adjacent + whitespace characters with a single space, #x20.

+

The whitespace characters are defined in the metasymbol S (Production 3) of .

+ +

If no argument is supplied, then $value defaults to the string value + (calculated using fn:string) of the context item (.).

+
+ +

If no argument is supplied and the context item is absent then a dynamic error is raised: .

+
+ +

The definition of whitespace is unchanged in . It is repeated here + for convenience:

+

+ S ::= (#x20 | #x9 | #xD | #xA)+ +

+
+ + + + normalize-space(" The wealthy curled darlings + of our nation. ") + "The wealthy curled darlings of our nation." + + + + + normalize-space(()) + "" + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns $value after applying Unicode normalization.

+
+ +

If $value is the empty sequence, the function returns the + zero-length string.

+

If the single-argument version of the function is used, the result is the same as + calling the two-argument version with $form set to the string + "NFC".

+

Otherwise, the function returns $value normalized according to + the rules of the normalization form identified by the value of + $form.

+

The effective value of $form is the value of the expression + fn:upper-case(fn:normalize-space($form)).

+ + + +

If the effective value of $form is NFC, + then the function returns $value converted to Unicode + Normalization Form C (NFC).

+
+ +

If the effective value of $form is NFD, + then the function returns $value converted to Unicode + Normalization Form D (NFD).

+
+ +

If the effective value of $form is NFKC, + then the function returns $value in Unicode Normalization + Form KC (NFKC).

+
+ +

If the effective value of $form is NFKD, + then the function returns $value converted to Unicode + Normalization Form KD (NFKD).

+
+ +

If the effective value of $form is + FULLY-NORMALIZED, then the function returns + $value converted to fully normalized form.

+
+ +

If the effective value of $form is the zero-length + string, no normalization is performed and $value is returned.

+
+
+

Normalization forms NFC, NFD, NFKC, and NFKD, and the algorithms to be used for + converting a string to each of these forms, are defined in .

+

The motivation for normalization form FULLY-NORMALIZED is explained in . However, as that specification did not progress beyond + working draft status, the normative specification is as follows:

+ + +

A string is fully-normalized if (a) it is in normalization form NFC + as defined in , and (b) it does not start + with a composing character.

+
+ +

A composing character is a character that is one or both of the following:

+ + +

the second character in the canonical decomposition mapping of some + character that is not listed in the Composition Exclusion Table defined in + ;

+
+ +

of non-zero canonical combining class (as defined in ).

+
+ +
+
+ +

A string is converted to FULLY-NORMALIZED form as follows:

+ + +

if the first character in the string is a composing character, prepend a + single space (x20);

+
+ +

convert the resulting string to normalization form NFC.

+
+
+
+
+ +

Conforming implementations must support normalization form NFC and + may support normalization forms NFD, NFKC, NFKD, and + FULLY-NORMALIZED. They may also support other normalization forms + with implementation-defined semantics.

+

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

+
+ +

A dynamic error is raised if the + effective value of the $form argument is not one of the values + supported by the implementation.

+
+
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Converts a string to upper case.

+
+ +

If $value is the empty sequence, the zero-length string is + returned.

+

Otherwise, the function returns $value after translating every + character to its upper-case correspondent as + defined in the appropriate case mappings section in the Unicode standard . For versions of Unicode beginning with the 2.1.8 update, only + locale-insensitive case mappings should be applied. Beginning with version 3.2.0 (and + likely future versions) of Unicode, precise mappings are described in default case + operations, which are full case mappings in the absence of tailoring for particular + languages and environments. Every lower-case character that does not have an upper-case + correspondent, as well as every upper-case character, is included in the returned value + in its original form.

+
+ +

Case mappings may change the length of a string. In general, the + fn:upper-case and fn:lower-case functions are not inverses + of each other: fn:lower-case(fn:upper-case($s)) is not guaranteed to + return $s, nor is fn:upper-case(fn:lower-case($s)). The + Latin small letter dotless i (ı, U+0131, used in Turkish) is perhaps the most prominent + lower-case letter which will not round-trip. The Latin capital letter i with dot above (İ, U+0130) + is the most prominent upper-case letter which will not round trip; there are others, + such as Latin capital letter sharp S (ẞ, U+1E9E), which was introduced in Unicode 5.1.

+

These functions may not always be linguistically appropriate (e.g. Turkish i without + dot) or appropriate for the application (e.g. titlecase). In cases such as Turkish, a + simple translation should be used first.

+

Because the function is not sensitive to locale, results will not always match user + expectations. In Quebec, for example, the standard uppercase equivalent of è is È, + while in metropolitan France it is more commonly E; only one of these is supported by + the functions as defined.

+

Many characters of class Ll lack uppercase equivalents in the Unicode case mapping + tables; many characters of class Lu lack lowercase equivalents.

+
+ + + + upper-case("abCd0") + "ABCD0" + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Converts a string to lower case.

+
+ +

If t$value is the empty sequence, the zero-length string is + returned.

+

Otherwise, the function returns $value after translating every + character to its lower-case correspondent as + defined in the appropriate case mappings section in the Unicode standard . For versions of Unicode beginning with the 2.1.8 update, only + locale-insensitive case mappings should be applied. Beginning with version 3.2.0 (and + likely future versions) of Unicode, precise mappings are described in default case + operations, which are full case mappings in the absence of tailoring for particular + languages and environments. Every upper-case character that does not have a lower-case + correspondent, as well as every lower-case character, is included in the returned value + in its original form.

+
+ +

Case mappings may change the length of a string. In general, the + fn:upper-case and fn:lower-case functions are not inverses + of each other: fn:lower-case(fn:upper-case($s)) is not guaranteed to + return $s, nor is fn:upper-case(fn:lower-case($s)). The + Latin small letter dotless i (ı, U+0131, used in Turkish) is perhaps the most prominent + lower-case letter which will not round-trip. The Latin capital letter i with dot above (İ, U+0130) + is the most prominent upper-case letter which will not round trip; there are others, + such as Latin capital letter sharp S (ẞ, U+1E9E), which was introduced in Unicode 5.1.

+

These functions may not always be linguistically appropriate (e.g. Turkish i without + dot) or appropriate for the application (e.g. titlecase). In cases such as Turkish, a + simple translation should be used first.

+

Because the function is not sensitive to locale, results will not always match user + expectations. In Quebec, for example, the standard uppercase equivalent of è is È, + while in metropolitan France it is more commonly E; only one of these is supported by + the functions as defined.

+

Many characters of class Ll lack uppercase equivalents in the Unicode case mapping + tables; many characters of class Lu lack lowercase equivalents.

+
+ + + + lower-case("ABc!D") + "abc!d" + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns $value modified by replacing or removing individual + characters.

+
+ +

If $value is the empty sequence, the function returns the + zero-length string.

+

Otherwise, the function returns a result string constructed by processing each character in $value, in order, + according to the following rules:

+ + +

If the character does not appear in $replace then it + is added to the result string unchanged.

+
+ +

If the character first appears in $replace at some + position M, where the value of $with is + M or more characters in length, then the character at position + M in $with is added to the result string.

+
+ +

If the character first appears in $replace at some + position M, where $with is less than + M characters in length, then the character is omitted from the + result string.

+
+
+
+ +

If $replace is the zero-length string then the function returns + $value unchanged.

+

If a character occurs more than once in $replace, then the first + occurrence determines the action taken.

+

If $with is longer than $replace, the excess + characters are ignored.

+
+ + + + translate("bar","abc","ABC") + "BAr" + + + + + translate("--aaa--","abc-","ABC") + "AAA" + + + + + translate("abcdabc", "abc", "AB") + "ABdAB" + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Encodes reserved characters in a string that is intended to be used in the path segment + of a URI.

+
+ +

If $value is the empty sequence, the function returns the zero-length + string.

+

This function applies the URI escaping rules defined in section 2 of to the xs:string supplied as $value. The + effect of the function is to escape reserved characters. Each such character in the + string is replaced with its percent-encoded form as described in .

+

Since recommends that, for consistency, URI producers and + normalizers should use uppercase hexadecimal digits for all percent-encodings, this + function must always generate hexadecimal values using the upper-case letters A-F.

+
+ +

All characters are escaped except those identified as “unreserved” by , that is the upper- and lower-case letters A to Z, + the digits 0 to 9, HYPHEN-MINUS (-), + LOW LINE (_), FULL STOP (.), and TILDE (~).

+

This function escapes URI delimiters and therefore cannot be used indiscriminately to + encode “invalid” characters in a path segment.

+

This function is invertible but not idempotent. This is because a string containing a + percent character will be modified by applying the function: for example + 100% becomes 100%25, while 100%25 becomes + 100%2525.

+
+ + + + encode-for-uri( + "http://www.example.com/00/Weather/CA/Los%20Angeles#ocean" +) + "http%3A%2F%2Fwww.example.com%2F00%2FWeather%2FCA%2FLos%2520Angeles%23ocean" + This is probably not what the user intended because all of the + delimiters have been encoded. + + + + + concat( + "http://www.example.com/", + encode-for-uri("~bébé") +) + "http://www.example.com/~b%C3%A9b%C3%A9" + + + + + concat( + "http://www.example.com/", + encode-for-uri("100% organic") +) + "http://www.example.com/100%25%20organic" + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Converts a string containing an IRI into a URI according to the rules of .

+
+ +

If $value is the empty sequence, the function returns the zero-length + string.

+

Otherwise, the function converts $value into a URI according to + the rules given in Section 3.1 of by percent-encoding characters + that are allowed in an IRI but not in a URI. If $value contains a character + that is invalid in an IRI, such as the space character (see note below), the invalid + character is replaced by its percent-encoded form as described in before the conversion is performed.

+

Since recommends that, for consistency, URI producers and + normalizers should use uppercase hexadecimal digits for all percent-encodings, this + function must always generate hexadecimal values using the upper-case letters A-F.

+
+ +

The function is idempotent but not invertible. Both the inputs My Documents + and My%20Documents will be converted to the output + My%20Documents.

+

This function does not check whether $iri is a valid IRI. It treats it as + an string and operates on the characters in the string.

+ +

The following printable ASCII characters are invalid in an IRI: <, >, + ", , {, }, |, + \, ^, and `. Since these + characters should not appear in an IRI, if they do appear in $iri they will + be percent-encoded. In addition, characters outside the range x20-x7E will be + percent-encoded because they are invalid in a URI.

+ +

Since this function does not escape the PERCENT SIGN % and this character is not + allowed in data within a URI, users wishing to convert character strings (such as file + names) that include % to a URI should manually escape % + by replacing it with %25. +

+
+ + + + iri-to-uri( + "http://www.example.com/00/Weather/CA/Los%20Angeles#ocean" +) + "http://www.example.com/00/Weather/CA/Los%20Angeles#ocean" + + + + + iri-to-uri("http://www.example.com/~bébé") + "http://www.example.com/~b%C3%A9b%C3%A9" + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Escapes a URI in the same way that HTML user agents handle attribute values expected to + contain URIs.

+
+ +

If $value is the empty sequence, the function returns the zero-length + string.

+

Otherwise, the function escapes all characters except + printable characters of the US-ASCII coded character set, specifically the codepoints between 32 and 126 (decimal) inclusive. Each + character in $uri to be escaped is replaced by an escape sequence, which is + formed by encoding the character as a sequence of octets in UTF-8, and then representing + each of these octets in the form %HH, where HH is the hexadecimal representation of the + octet. This function must always generate hexadecimal values using the upper-case + letters A-F.

+
+ +

The behavior of this function corresponds to the recommended handling of non-ASCII + characters in URI attribute values as described in Appendix + B.2.1.

+
+ + + + escape-html-uri( + "http://www.example.com/00/Weather/CA/Los Angeles#ocean" +) + "http://www.example.com/00/Weather/CA/Los Angeles#ocean" + + + + + escape-html-uri( + "javascript:if (navigator.browserLanguage == 'fr') window.open('http://www.example.com/~bébé');" +) + "javascript:if (navigator.browserLanguage == 'fr') window.open('http://www.example.com/~b%C3%A9b%C3%A9');" + + + +
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns true if the string $value contains $substring as a + substring, taking collations into account.

+
+ +

If $value or $substring is the empty sequence, or + contains only ignorable collation units, it is interpreted as the zero-length + string.

+

If $substring is the zero-length string, then the function returns + true.

+

If $value is the zero-length string, the function returns + false.

+

The collation used by this function is determined according to the rules in .

+

The function returns an xs:boolean indicating whether or not + $value contains (at the beginning, at the end, or anywhere within) at + least one sequence of collation units that provides a minimal match to the + collation units in $substring, according to the collation that is + used.

+ +

Minimal match is defined in .

+
+ +
+ +

A dynamic error may be raised if the specified collation does not support collation units.

+
+ + +

The collation used in these examples, http://example.com/CollationA is a + collation in which both - and * are ignorable collation units.

+

“Ignorable collation unit” is equivalent to “ignorable collation element” in .

+
+ + + contains("tattoo", "t") + true() + + + + + contains("tattoo", "ttt") + false() + + + + + contains("", ()) + true() + The first rule is applied, followed by the second + rule. + + + + + contains( + "abcdefghi", + "-d-e-f-", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + + + + + contains( + "a*b*c*d*e*f*g*h*i*", + "d-ef-", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + + + + + contains( + "abcd***e---f*--*ghi", + "def", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + + + + + contains( + (), + "--***-*---", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + The second argument contains only ignorable collation units and is + equivalent to the zero-length string. + + +
+
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns true if the string $value contains $substring as a leading + substring, taking collations into account.

+
+ +

If $value or $substring is the empty sequence, or + contains only ignorable collation units, it is interpreted as the zero-length + string.

+

If $substring is the zero-length string, then the function returns + true. If $value is the zero-length string and + $substring is not the zero-length string, then the function returns + false.

+

The collation used by this function is determined according to the rules in .

+

The function returns an xs:boolean indicating whether or not + $value starts with a sequence of collation units that provides a + match to the collation units of $substring according to the + collation that is used.

+ +

Match is defined in .

+
+ +
+ +

A dynamic error may be raised if the specified collation does not support collation units.

+
+ + +

The collation used in these examples, http://example.com/CollationA is a + collation in which both - and * are ignorable collation units.

+

“Ignorable collation unit” is equivalent to “ignorable collation element” in .

+
+ + + starts-with("tattoo", "tat") + true() + + + + + starts-with("tattoo", "att") + false() + + + + + starts-with((), ()) + true() + + + + + starts-with( + "abcdefghi", + "-a-b-c-", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + + + + + starts-with( + "a*b*c*d*e*f*g*h*i*", + "a-bc-", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + + + + + starts-with( + "abcd***e---f*--*ghi", + "abcdef", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + + + + + starts-with( + (), + "--***-*---", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + The second argument contains only ignorable collation units and is + equivalent to the zero-length string. + + + + + starts-with( + "-abcdefghi", + "-abc", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + + +
+
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns true if the string $value contains $substring as a trailing + substring, taking collations into account.

+
+ +

If $value or $substring is the empty sequence, or + contains only ignorable collation units, it is interpreted as the zero-length + string.

+

If $substring is the zero-length string, then the function returns + true. If $value is the zero-length string and + the value of $substring is not the zero-length string, then the function returns + false.

+

The collation used by this function is determined according to the rules in .

+

The function returns an xs:boolean indicating whether or not + $value ends with a sequence of collation units that provides a + match to the collation units of $substring according to the + collation that is used.

+ +

+ Match is defined in .

+
+ +
+ +

A dynamic error may be raised if the specified collation does not support collation units.

+
+ + +

The collation used in these examples, http://example.com/CollationA is a + collation in which both - and * are ignorable collation units.

+

“Ignorable collation unit” is equivalent to “ignorable collation element” in .

+
+ + + ends-with("tattoo", "tattoo") + true() + + + + + ends-with("tattoo", "atto") + false() + + + + + ends-with((), ()) + true() + + + + + ends-with( + "abcdefghi", + "-g-h-i-", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + + + + + ends-with( + "abcd***e---f*--*ghi", + "defghi", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + + + + + ends-with( + "abcd***e---f*--*ghi", + "defghi", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + + + + + ends-with( + (), + "--***-*---", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + The second argument contains only ignorable collation units and is + equivalent to the zero-length string. + + + + + ends-with( + "abcdefghi", + "ghi-", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + true() + + +
+
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns the part of $value that precedes the first occurrence of + $substring, taking collations into account.

+
+ +

If $value or $substring is the empty sequence, or + contains only ignorable collation units, it is interpreted as the zero-length + string.

+

If $substring is the zero-length string, then the function returns + the zero-length string.

+

If $value does not contain a string that is equal to + $substring, then the function returns the zero-length string.

+

The collation used by this function is determined according to the rules in .

+

The function returns the substring of $value that precedes in + $value the first occurrence of a sequence of collation units + that provides a minimal match to the collation units of $substring + according to the collation that is used.

+ +

Minimal match is defined in .

+
+ +
+ +

A dynamic error may be raised if the specified collation does not support collation units.

+
+ + +

The collation used in these examples, http://example.com/CollationA is a + collation in which both - and * are ignorable collation units.

+

“Ignorable collation unit” is equivalent to “ignorable collation element” in .

+
+ + + substring-before("tattoo", "attoo") + "t" + + + + + substring-before("tattoo", "tatto") + "" + + + + + substring-before((), ()) + "" + + + + + substring-before( + "abcdefghi", + "--d-e-", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + "abc" + + + + + substring-before( + "abc--d-e-fghi", + "--d-e-", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + "abc--" + + + + + substring-before( + "a*b*c*d*e*f*g*h*i*", + "***cde", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + "a*b*" + + + + + substring-before( + "Eureka!", + "--***-*---", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + "" + The second argument contains only ignorable collation units and is + equivalent to the zero-length string. + + +
+
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns the part of $value that follows the first occurrence of + $substring, taking collations into account.

+
+ +

If $value or $substring is the empty sequence, or + contains only ignorable collation units, it is interpreted as the zero-length + string.

+

If $substring is the zero-length string, then the function returns + the value of $value.

+

If $value does not contain a string that is equal to + $substring, then the function returns the zero-length string.

+

The collation used by this function is determined according to the rules in .

+

The function returns the substring of $value that follows in + $value the first occurrence of a sequence of collation units + that provides a minimal match to the collation units of $substring + according to the collation that is used.

+ +

Minimal match is defined in .

+
+ +
+ +

A dynamic error may be raised if + the specified collation does not support collation units.

+
+ + +

The collation used in these examples, http://example.com/CollationA is a + collation in which both - and * are ignorable collation units.

+

“Ignorable collation unit” is equivalent to “ignorable collation element” in .

+
+ + + substring-after("tattoo", "tat") + "too" + + + + + substring-after("tattoo", "tattoo") + "" + + + + + substring-after((), ()) + "" + + + + + substring-after( + "abcdefghi", + "--d-e-", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + "fghi" + + + + + substring-after( + "abc--d-e-fghi", + "--d-e-", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + "-fghi" + + + + + substring-after( + "a*b*c*d*e*f*g*h*i*", + "***cde***", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + "*f*g*h*i*" + + + + + substring-after( + "Eureka!", + "--***-*---", + "http://www.w3.org/2013/collation/UCA?lang=en;alternate=blanked;strength=primary" +) + "Eureka!" + The second argument contains only ignorable collation units and is + equivalent to the zero-length string. + + +
+
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns true if the supplied string matches a given regular expression.

+
+ +

If $value is the empty sequence, it is interpreted as the zero-length + string.

+

If the $flags argument is omitted or if it is an empty sequence, + the effect is the same as setting $flags to a zero-length string. + Flags are defined in .

+

The function returns true if $value or some substring of + $value matches the regular expression supplied as $pattern, + and the associated $flags. Otherwise, the function returns false.

+
+ +

A dynamic error is raised if + $pattern is invalid according to the rules described in .

+

A dynamic error is raised if + $flags is invalid according to the rules described in .

+
+ +

Unless the metacharacters ^ and $ are used as anchors, the + string is considered to match the pattern if any substring matches the pattern. But if + anchors are used, the anchors must match the start/end of the string (in string mode), + or the start/end of a line (in multi-line mode).

+

This is different from the behavior of patterns in , where + regular expressions are implicitly anchored.

+

Regular expression matching is defined on the basis of Unicode code points; it takes no + account of collations.

+
+ + + + matches("abracadabra", "bra") + true() + + + + + matches("abracadabra", "^a.*a$") + true() + + + + + matches("abracadabra", "^bra") + false() + + + +

Given the source document:

+
+ +Kaum hat dies der Hahn gesehen, +Fängt er auch schon an zu krähen: +Kikeriki! Kikikerikih!! +Tak, tak, tak! - da kommen sie. +]]> + +

the following function calls produce the following results, with the + poem element as the context node:

+
+ + + matches($poem, "Kaum.*krähen") + false() + + + + + matches($poem, "Kaum.*krähen", "s") + true() + + + + + matches($poem, "^Kaum.*gesehen,$", "m") + true() + + + + + matches($poem, "^Kaum.*gesehen,$") + false() + + + + + matches($poem, "kiki", "i") + true() + + +
+
+ + + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a string produced from the input string by replacing any substrings that match a + given regular expression with a supplied replacement string, + provided either literally, or by invoking a supplied function.

+
+ +

If $value is the empty sequence, it is interpreted as the zero-length + string.

+

The replacement string is determined by the values of the + $replacement and/or $action arguments:

+ +

If the $action argument is present and is not an empty sequence, + the string is obtained by calling the $action function.

+

The first argument to the $action function is the string to be replaced, + provided as xs:untypedAtomic.

+

The second argument to the $action function provides the captured + substrings as an xs:untypedAtomic sequence. + The Nth item in this sequence is the substring captured by + the Nth parenthesized sub-expression. If the + Nth parenthesized sub-expression was not matched, the Nth item + will be the zero-length string.

+

Note that the rules for function coercion mean that the function actually + supplied for the $action parameter may be an arity-1 function: the + second argument does not need to be declared if it is not used.

+

The replacement string is obtained by invoking fn:string + for the result of the function call.

+
+

Otherwise, if the $replacement argument is present and is not + an empty sequence, the replacement string is the value of $replacement.

+

Otherwise, the replacement string is the zero-length string.

+
+

If the $flags argument is omitted or if it is an empty sequence, + the effect is the same as setting $flags to a zero-length string. + Flags are defined in .

+

The function returns the xs:string that is obtained by replacing each + non-overlapping substring of $value that matches the given + $pattern with a replacement string.

+

If two overlapping substrings of $value both match the + $pattern, then only the first one (that is, the one whose first character comes first in the $value string) is + replaced.

+

If the q flag is present, or if the replacement string was obtained + by calling the $action function, then the replacement string is used + as is.

+

Otherwise, within the replacement string, a variable $N may + be used to refer to the substring captured by the Nth parenthesized sub-expression in + the regular expression. For each match of the pattern, these variables are assigned the + value of the content matched by the relevant sub-expression, and the modified + replacement string is then substituted for the characters in $value that matched the pattern. + $0 refers to the substring captured by the regular expression as a + whole.

+

More specifically, the rules are as follows, where S is the number of + parenthesized sub-expressions in the regular expression, and N is the + decimal number formed by taking all the digits that consecutively follow the + $ character:

+ + + +

If N=0, then the variable is replaced by the substring + matched by the regular expression as a whole.

+
+ +

If 1<=N<=S, then the variable is + replaced by the substring captured by the Nth parenthesized sub-expression. If the + Nth parenthesized sub-expression was not matched, then the + variable is replaced by the zero-length string.

+
+ +

If S<N<=9, then the variable is + replaced by the zero-length string.

+
+ +

Otherwise (if N>S and + N>9), the last digit of N is taken to + be a literal character to be included “as is” in the replacement string, and the + rules are reapplied using the number N formed by stripping off this + last digit.

+
+
+ +

For example, if the replacement string is + "$23" + and there are 5 substrings, the result contains the value of the substring that + matches the second sub-expression, followed by the digit + 3.

+

Unless the q flag is used, a literal $ character within the + replacement string must be written as \$, and a literal \ + character must be written as \\.

+ +

If two alternatives within the pattern both match at the same position in the + $input, then the match that is chosen is the one matched by the first + alternative. For example:

+ replace("abcd", "(ab)|(a)", "[1=$1][2=$2]") returns "[1=ab][2=]cd" + +
+ +

A dynamic error is raised if the value of + $pattern is invalid according to the rules described in section .

+

A dynamic error is raised if the value of + $flags is invalid according to the rules described in section .

+

A dynamic error is raised if the pattern matches a + zero-length string, that is, if the expression fn:matches("", $pattern, + $flags) returns true. It is not an error, however, if a captured + substring is zero-length.

+

In the absence of the q flag, + a dynamic error is raised if the value of + $replacement contains a dollar sign ($) character that is not + immediately followed by a digit 0-9 and not immediately preceded by a + backslash (\).

+

In the absence of the q flag, + a dynamic error is raised if the value of + $replacement contains a backslash (\) character that is not part of a + \\ pair, unless it is immediately followed by a dollar sign ($) + character.

+

A dynamic error is raised if both the $replacement + and $action arguments are supplied, and neither is an empty sequence.

+
+ +

If the input string contains no substring that matches the regular + expression, the result of the function is a single string identical to the input + string.

+
+ + + + replace("abracadabra", "bra", "*") + "a*cada*" + + + replace("abracadabra", "a.*a", "*") + "*" + + + replace("abracadabra", "a.*?a", "*") + "*c*bra" + + + replace("abracadabra", "a", "") + "brcdbr" + + + replace("abracadabra", "a(.)", "a$1$1") + "abbraccaddabbra" + + + replace("AAAA", "A+", "b") + "b" + + + replace("AAAA", "A+?", "b") + "bbbb" + + + replace("darted", "^(.*?)d(.*)$", "$1c$2") + "carted" + The first d is replaced. + + + replace( + "abracadabra", + "bra", + action := function { "*" } +) + "a*cada*" + + + replace( + "abracadabra", + "bra", + action := upper-case#1 +) + aBRAcadaBRA + + + replace( + "Chapter 9", + "[0-9]+", + action := function { string(number(.) + 1) } +) + "Chapter 10" + + + replace( + "LHR to LAX", + "[A-Z]{3}", + action := map {'LAX': 'Los Angeles', 'LHR': 'London' } +) + "London to Los Angeles" + + + replace( + "57°43′30″", + "([0-9]+)°([0-9]+)′([0-9]+)″", + action := function($s, $groups) { + string(number($groups[1]) + number($groups[2]) ÷ 60 + number($groups[3]) ÷ 3600) || '°' + } +) + "57.725°" + + + +

The expression fn:replace("abracadabra", ".*?", "$1") raises an error, + because the pattern matches the zero-length string

+
+
+ + The addition of the $action argument as proposed here has + not been reviewed by the working group. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a sequence of strings constructed by splitting the input wherever a separator is + found; the separator is any substring that matches a given regular expression.

+
+ +

The following rules apply when the $pattern argument is omitted, + or is set to an empty sequence:

+ +

The function splits the supplied string at whitespace boundaries.

+

More specifically, calling fn:tokenize($value) or fn:tokenize($value, ()) + is equivalent to calling fn:tokenize(fn:normalize-space($value), ' ')) where the second argument + is a single space character (x20).

+

The $flags argument is ignored.

+
+

The following rules apply when the $pattern argument is supplied as a single string:

+ +

If the $flags argument is omitted or if it is an empty sequence, + the effect is the same as setting $flags to a zero-length string. + Flags are defined in .

+

If $value is the empty sequence, or if $value is the + zero-length string, the function returns the empty sequence.

+ +

The function returns a sequence of strings formed by breaking the $value + string into a sequence of strings, treating any substring that matches + $pattern as a separator. The separators themselves are not returned.

+
+ +

If a separator occurs at the start of the $value string, the result + sequence will start with a zero-length string. Similarly, zero-length strings will also occur in + the result sequence if a separator occurs at the end of the $value string, + or if two adjacent substrings match the supplied $pattern.

+
+ +

If two alternatives within the supplied $pattern both match at the same + position in the $value string, then the match that is chosen is the first. + For example:

+ tokenize("abracadabra", "(ab)|(a)") returns ("", "r", "c", "d", "r", "") +
+
+ +
+ +

A dynamic error is raised if the value of + $pattern is invalid according to the rules described in section .

+

A dynamic error is raised if the value of + $flags is invalid according to the rules described in section .

+

A dynamic error is raised if the supplied + $pattern matches a zero-length string, that is, if fn:matches("", + $pattern, $flags) returns true.

+ +
+ +

If the input string is not zero length, and no separators are found in + the input string, the result of the function is a single string identical to the input + string.

+

The one-argument form of the function has a similar effect to + the two-argument form with \s+ as the separator pattern, except that the one-argument + form strips leading and trailing whitespace, whereas the two-argument form delivers an extra + zero-length token if leading or trailing whitespace is present.

+

The function returns no information about the separators that were found + in the string. If this information is required, the fn:analyze-string function + can be used instead.

+

The separator used by the one-argument form of the function is any sequence + of tab (x09), newline (x0A), carriage return + (x0D) or space (x20) characters. This is the same as the + separator recognized by list-valued attributes as defined in XSD. + It is not the same as the separator recognized by list-valued attributes in HTML5, + which also treats form-feed (x0C) as whitespace. If it is necessary + to treat form-feed as a separator, an explicit separator pattern should be used.

+
+ + + + tokenize(" red green blue ") + ("red", "green", "blue") + + + + + tokenize("The cat sat on the mat", "\s+") + ("The", "cat", "sat", "on", "the", "mat") + + + + + tokenize(" red green blue ", "\s+") + ("", "red", "green", "blue", "") + + + + + tokenize("1, 15, 24, 50", ",\s*") + ("1", "15", "24", "50") + + + + + tokenize("1,15,,24,50,", ",") + ("1", "15", "", "24", "50", "") + + + +

fn:tokenize("abba", ".?") raises the dynamic error .

+
+ + + tokenize( + "Some unparsed <br> HTML <BR> text", + "\s*<br>\s*", "i" +) + ("Some unparsed", "HTML", "text") + + +
+ + Changed for 4.0: allow the second argument to be an empty sequence. + +
+ + + + + + + + + + nondeterministic + context-independent + focus-independent + + +

Analyzes a string using a regular expression, returning an XML structure that identifies + which parts of the input string matched or failed to match the regular expression, and + in the case of matched substrings, which substrings matched each capturing group in the + regular expression.

+
+ +

If the $flags argument is omitted or if it is an empty sequence, + the effect is the same as setting $flags to a zero-length string. + Flags are defined in .

+

If $value is the empty sequence the function behaves as if + $value were the zero-length string. In this situation the result will be + an element node with no children.

+

The function returns an element node whose local name is + analyze-string-result. This element and all its descendant elements have + the namespace URI http://www.w3.org/2005/xpath-functions. The namespace + prefix is implementation-dependent. The children of this element are a + sequence of fn:match and fn:non-match elements. This sequence + is formed by breaking the $value string into a sequence of strings, + returning any substring that matches $pattern as the content of a + match element, and any intervening substring as the content of a + non-match element.

+

More specifically, the function starts at the beginning of the input string and attempts + to find the first substring that matches the regular expression. If there are several + matches, the first match is defined to be the one whose starting position comes first in + the string. If several alternatives within the regular expression both match at the same + position in the input string, then the match that is chosen is the first alternative + that matches. For example, if the input string is The quick brown fox jumps + and the regular expression is jump|jumps, then the match that is chosen is + jump.

+ +

Having found the first match, the instruction proceeds to find the second and subsequent + matches by repeating the search, starting at the first character that was not included in the previous match.

+ +

The input string is thus partitioned into a sequence of substrings, some of which match + the regular expression, others which do not match it. Each substring will contain at + least one character. This sequence is represented in the result by the sequence of + fn:match and fn:non-match children of the returned element + node; the string value of the fn:match or fn:non-match element + will be the corresponding substring of $input, and the string value of the + returned element node will therefore be the same as $input.

+ +

The content of an fn:non-match element is always a single text node.

+ +

The content of a fn:match element, however, is in general a sequence of + text nodes and fn:group element children. An fn:group element + with a nr attribute having the integer value N identifies the + substring captured by the Nth parenthesized sub-expression in the regular + expression. For each capturing subexpression there will be at most one corresponding + fn:group element in each fn:match element in the + result.

+ +

If the function is called twice with the same arguments, it is implementation-dependent whether the two calls return the same element node + or distinct (but deep equal) element nodes. In this respect it is non-deterministic with respect to node identity.

+ +

The base URI of the element nodes in the result is implementation-dependent.

+ +

A schema is defined for the structure of the returned element: see .

+ +

The result of the function will always be such that validation against this schema would succeed. + However, it is implementation-defined whether the result is typed or untyped, + that is, whether the elements and attributes in the returned tree have type annotations that reflect + the result of validating against this schema.

+ + +
+ +

A dynamic error is raised if the value of + $pattern is invalid according to the rules described in section .

+

A dynamic error is raised if the value of + $flags is invalid according to the rules described in section .

+

A dynamic error is raised if the supplied + $pattern matches a zero-length string, that is, if fn:matches("", + $pattern, $flags) returns true.

+
+ +

It is recommended that a processor that implements schema awareness should return typed nodes. + The concept of “schema awareness”, however, is a matter for host languages to define and is outside + the scope of the function library specification.

+

The declarations and definitions in the schema are not automatically available in + the static context of the fn:analyze-string call (or of any other + expression). The contents of the static context are host-language defined, and in some + host languages are implementation-defined.

+

The schema defines the outermost element, analyze-string-result, in such + a way that mixed content is permitted. In fact the element will only have element nodes (match + and non-match) as its children, never text nodes. Although this might have originally been an + oversight, defining the analyze-string-result element with mixed="true" allows it + to be atomized, which is potentially useful (the atomized value will be the original input string), + and the capability has therefore been retained for compatibility with the 3.0 version of this + specification.

+
+ + +

In the following examples, the result document is shown in serialized form, with + whitespace between the element nodes. This whitespace is not actually present in the + result.

+
+ + + analyze-string("The cat sat on the mat.", "\w+") + + The + + cat + + sat + + on + + the + + mat + . +]]> + + + + + analyze-string( + "2008-12-03", + "^(\d+)\-(\d+)\-(\d+)$" +) + + 2008-12-03 +]]> + + + + + analyze-string( + "A1,C15,,D24, X50,", + "([A-Z])([0-9]+)" +) + + A1 + , + C15 + ,, + D24 + , + X50 + , +]]> + + +
+
+ + + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Determines whether or not any of the supplied strings, when tokenized at whitespace boundaries, contains the supplied token, + under the rules of the supplied collation.

+
+ +

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

+

Leading and trailing whitespace is trimmed from $token. + If the trimmed value of $token + is a zero-length string, the function returns false.

+

The collation used by this function is determined according to the rules in .

+

The function returns true if and only if there is string in $value which, + after tokenizing at whitespace boundaries, contains a token + that is equal to the trimmed value of $token under + the rules of the selected collation.

+

That is, the function returns the value of the expression:

+ +
+ +

Interior whitespace within $token will cause the function to return false, + unless such whitespace is ignored by the selected collation.

+

This function can be used for processing space-separated attribute values + (for example, the XHTML and DITA class attribute), + where one often needs to test for the presence + of a single token in a space-separated list. The function is designed to work + both when the attribute has been validated against an XSD list type, and when it + appears as a single untyped string. It differs from the + HTML 5 definition in that HTML 5 recognizes form feed (x0C) as a separator. + To reproduce the HTML token matching behavior, the HTML ASCII case-insensitive collation + should be used: see .

+
+ + + + contains-token("red green blue ", "red") + true() + + + contains-token(("red", "green", "blue"), " red ") + true() + + + contains-token("red, green, blue", "red") + false() + + + contains-token( + "red green blue", + "RED", + "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive" +) + true() + + + +
+ + + + + + + + + deterministic + context-dependent + focus-independent + + +

Resolves a relative IRI reference against an absolute IRI.

+
+ + + +

The function is defined to operate on IRI references as defined in , and the implementation must permit all arguments that are valid + according to that specification. In addition, the implementation may + accept some or all strings that conform to the rules for (absolute or relative) Legacy + Extended IRI references as defined in . For the purposes of this + section, the terms IRI and IRI reference include these extensions, insofar as the + implementation chooses to support them.

+ +

The following rules apply in order:

+ + + +

If $href is the empty sequence, the function returns the empty + sequence.

+
+ +

If $href is an absolute IRI (as defined above), then it is returned + unchanged.

+
+ +

If the $base argument is not supplied, + or is supplied as an empty sequence then:

+ + +

If the static base URI in the static context is not absent, it is used as the effective + value of $base.

+
+ +

Otherwise, a dynamic error is raised: .

+
+
+
+ +

The function resolves the relative IRI reference $href + against the base IRI $base using the algorithm defined in , adapted by treating any character + that would not be valid in an RFC3986 URI or relative reference in the same way that + RFC3986 treats unreserved characters. No percent-encoding takes place.

+
+
+
+ +

The first form of this function resolves $href against the value of the + base-uri property from the static context. A dynamic error is raised if the base-uri property is not initialized in the static + context.

+

A dynamic error is raised if $href + is not a valid IRI according to the rules of RFC3987, extended with an + implementation-defined subset of the extensions permitted in LEIRI, or if it is not a + suitable relative reference to use as input to the RFC3986 resolution algorithm extended + to handle additional unreserved characters.

+

A dynamic error is raised if $base is + not a valid IRI according to the rules of RFC3987, extended with an + implementation-defined subset of the extensions permitted in LEIRI, or if it is not a + suitable IRI to use as input to the chosen resolution algorithm (for example, if it is a + relative IRI reference or, if it is a non-hierarchic URI, or if it contains a fragment + identifier). In XPath 4.0, attempting + to resolve against an absolute URI that includes a fragment identifier is no longer + an error, the fragment identifier is simply ignored. A narrow reading of RFC 3986 + might seem to forbid this, but in practice the interpretation is non-controversial + and the practice is widely supported.

+

A dynamic error is raised if the chosen resolution + algorithm fails for any other reason.

+
+ +

Resolving a URI does not dereference it. This is merely a syntactic operation on two + strings.

+

The algorithms in the cited RFCs include some variations that are optional or + recommended rather than mandatory; they also describe some common practices that are not + recommended, but which are permitted for backwards compatibility. Where the cited RFCs + permit variations in behavior, so does this specification.

+

Throughout this family of specifications, the phrase "resolving a relative URI (or IRI) + reference" should be understood as using the rules of this function, unless otherwise + stated.

+

RFC3986 defines an algorithm for resolving relative references + in the context of the URI syntax defined in that RFC. RFC3987 describes a modification + to that algorithm to make it applicable to IRIs (specifically: additional characters + permitted in an IRI are handled the same way that RFC3986 handles unreserved characters). + The LEIRI specification does not explicitly define a resolution algorithm, but suggests + that it should not be done by converting the LEIRI to a URI, and + should not involve percent-encoding. This specification fills this gap + by defining resolution for LEIRIs in the same way that RFC3987 defines resolution for IRIs, + that is by specifying that additional characters are handled as unreserved characters.

+
+ + The optional second argument can now be supplied as an empty sequence. + +
+ + + + + + deterministic + context-independent + focus-independent + + +

Returns the xs:boolean value true.

+
+ +

The result is equivalent to xs:boolean("1").

+
+ + + + true() + xs:boolean(1) + + + +
+ + + + + + deterministic + context-independent + focus-independent + + +

Returns the xs:boolean value false.

+
+ +

The result is equivalent to xs:boolean("0").

+
+ + + + false() + xs:boolean(0) + + + +
+ + + + + + + + Defines the semantics of the eq + operator when applied to two xs:boolean values. + +

Returns true if the two arguments are the same boolean value.

+
+ +

The function returns true if both arguments are true or if + both arguments are false. It returns false if one of the + arguments is true and the other argument is false.

+
+
+ + + + + + + + Defines the + semantics of the lt operator when applied to two xs:boolean values. Also + used in the definition of the ge operator. + +

Returns true if the first argument is false and the second is true.

+
+ +

The function returns true if $arg1 is false and + $arg2 is true. Otherwise, it returns + false.

+
+
+ + + + + + + + +

Computes the effective boolean value of the sequence $input.

+
+ +

The function computes the effective boolean value of a sequence, defined according to + the following rules. See also .

+ + +

If $input is the empty sequence, fn:boolean returns + false.

+
+ +

If $input is a sequence whose first item is a node, + fn:boolean returns true.

+
+ +

If $input is a singleton value of type xs:boolean or a + derived from xs:boolean, fn:boolean returns + $input.

+
+ +

If $input is a singleton value of type xs:string or a type + derived from xs:string, xs:anyURI or a type derived from + xs:anyURI, or xs:untypedAtomic, + fn:boolean returns false if the operand value has + zero length; otherwise it returns true.

+
+ +

If $input is a singleton value of any numeric type or a type derived + from a numeric type, fn:boolean returns false if the + operand value is NaN or is numerically equal to zero; otherwise it + returns true.

+
+
+
+ +

In all cases other than those listed above, fn:boolean raises a type error .

+
+ +

The result of this function is not necessarily the same as $input cast as + xs:boolean. For example, fn:boolean("false") returns the value + true whereas "false" cast as xs:boolean (which can also be + written xs:boolean("false")) returns false.

+
+ + + + + boolean($abc[1]) + true() + + + + + boolean($abc[0]) + false() + + + + + boolean($abc[3]) + false() + + + +

fn:boolean($abc) raises a type error .

+
+ +

fn:boolean([]) raises a type error .

+
+
+
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns true if the effective boolean value of $input is + false, or false if it is true.

+
+ +

The value of $input is first reduced to an effective boolean value by + applying the fn:boolean() function. The function returns true + if the effective boolean value is false, or false if the + effective boolean value is true.

+
+ + + + not(true()) + false() + + + + + not(()) + true() + + + + + not("false") + false() + + + +

fn:not(1 to 10) raises a type error .

+
+
+
+ + + + + + + + + Defines + the semantics of the lt operator when applied to two xs:yearMonthDuration + values. Also used in the definition of the ge operator. + +

Returns true if $arg1 is a shorter duration than $arg2.

+
+ +

If the number of months in $arg1 is numerically less than the + number of months in $arg2, the function returns true.

+

Otherwise, the function returns false.

+
+ +

Either or both durations may be negative.

+
+
+ + + + + + + + + Defines the + semantics of the lt operator when applied to two xs:dayTimeDuration values. + Also used in the definition of the ge operator. + +

Returns true if $arg1 is a shorter duration than $arg2.

+
+ +

If the number of seconds in $arg1 is numerically less than the + number of seconds in $arg2, the function returns true.

+

Otherwise, the function returns false.

+
+ +

Either or both durations may be negative

+
+
+ + + + + + + + + Defines the + semantics of the eq operators when applied to two xs:duration values. Also + used in the definition of the ne operator. + +

Returns true if $arg1 and $arg2 are durations of the same + length.

+
+ +

If the xs:yearMonthDuration components of $arg1 and + $arg2 are equal and the xs:dayTimeDuration components of + $arg1 and $arg2 are equal, the function returns + true.

+

Otherwise, the function returns false.

+

The semantics of this function are:

+ +xs:yearMonthDuration($arg1) div xs:yearMonthDuration('P1M') eq +xs:yearMonthDuration($arg2) div xs:yearMonthDuration('P1M') + and +xs:dayTimeDuration($arg1) div xs:dayTimeDuration('PT1S') eq +xs:dayTimeDuration($arg2) div xs:dayTimeDuration('PT1S') + +

that is, the function returns true if the months and seconds values of the + two durations are equal.

+
+ +

Note that this function, like any other, may be applied to arguments that are derived + from the types given in the function signature, including the two subtypes + xs:dayTimeDuration and xs:yearMonthDuration. With the + exception of the zero-length duration, no instance of xs:dayTimeDuration + can ever be equal to an instance of xs:yearMonthDuration.

+
+ + + + op:duration-equal( + xs:duration("P1Y"), + xs:duration("P12M") +) + true() + + + + + op:duration-equal( + xs:duration("PT24H"), + xs:duration("P1D") +) + true() + + + + + op:duration-equal( + xs:duration("P1Y"), + xs:duration("P365D") +) + false() + + + + + op:duration-equal( + xs:yearMonthDuration("P0Y"), + xs:dayTimeDuration("P0D") +) + true() + + + + + op:duration-equal( + xs:yearMonthDuration("P1Y"), + xs:dayTimeDuration("P365D") +) + false() + + + + + op:duration-equal( + xs:yearMonthDuration("P2Y"), + xs:yearMonthDuration("P24M") +) + true() + + + + + op:duration-equal( + xs:dayTimeDuration("P10D"), + xs:dayTimeDuration("PT240H") +) + true() + + + + + op:duration-equal( + xs:duration("P2Y0M0DT0H0M0S"), + xs:yearMonthDuration("P24M") +) + true() + + + + + op:duration-equal( + xs:duration("P0Y0M10D"), + xs:dayTimeDuration("PT240H") +) + true() + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the number of years in a duration.

+
+ +

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

+

Otherwise, the function returns an xs:integer representing the years + component in $value. Given that a duration + is a ($months, $seconds) tuple, the result is the value of ($months idiv 12).

+

If $value is a negative duration then the result will be negative.

+

If $value is an xs:dayTimeDuration the function + returns 0.

+
+ + + + years-from-duration( + xs:yearMonthDuration("P20Y15M") +) + 21 + + + + + years-from-duration( + xs:yearMonthDuration("-P15M") +) + -1 + + + + + years-from-duration( + xs:dayTimeDuration("-P2DT15H") +) + 0 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the number of months in a duration.

+
+ +

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

+

Otherwise, the function returns an xs:integer representing the months + component in $value. Given that a duration + is a ($months, $seconds) tuple, the result is the value of ($months mod 12).

+

If $value is a negative duration then the result will be negative.

+

If $value is an xs:dayTimeDuration the function + returns 0.

+
+ + + + months-from-duration( + xs:yearMonthDuration("P20Y15M") +) + 3 + + + + + months-from-duration( + xs:yearMonthDuration("-P20Y18M") +) + -6 + + + + + months-from-duration( + xs:dayTimeDuration("-P2DT15H0M0S") +) + 0 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the number of days in a duration.

+
+ +

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

+

Otherwise, the function returns an xs:integer representing the days + component in $value. Given that a duration + is a ($months, $seconds) tuple, the result is ($seconds idiv 86400).

+

If $value is a negative duration then the result will be negative.

+

If $value is an xs:yearMonthDuration the function returns 0.

+
+ + + + days-from-duration( + xs:dayTimeDuration("P3DT10H") +) + 3 + + + + + days-from-duration( + xs:dayTimeDuration("P3DT55H") +) + 5 + + + + + days-from-duration( + xs:yearMonthDuration("P3Y5M") +) + 0 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the number of hours in a duration.

+
+ +

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

+

Otherwise, the function returns an xs:integer representing the hours + component in $value. Given that a duration + is a ($months, $seconds) tuple, the result is the value of ($seconds mod 86400) idiv 3600.

+

If $value is a negative duration then the result will be negative.

+

If $value is an xs:yearMonthDuration the function returns 0.

+
+ + + + hours-from-duration( + xs:dayTimeDuration("P3DT10H") +) + 10 + + + + + hours-from-duration( + xs:dayTimeDuration("P3DT12H32M12S") +) + 12 + + + + + hours-from-duration( + xs:dayTimeDuration("PT123H") +) + 3 + + + + + hours-from-duration( + xs:dayTimeDuration("-P3DT10H") +) + -10 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the number of minutes in a duration.

+
+ +

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

+

Otherwise, the function returns an xs:integer representing the minutes + component in $value. Given that a duration + is a ($months, $seconds) tuple, the result is the value of ($seconds mod 3600) idiv 60.

+

If $value is a negative duration then the result will be negative.

+

If $value is an xs:yearMonthDuration the function returns 0.

+
+ + + + minutes-from-duration( + xs:dayTimeDuration("P3DT10H") +) + 0 + + + + + minutes-from-duration( + xs:dayTimeDuration("-P5DT12H30M") +) + -30 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the number of seconds in a duration.

+
+ +

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

+

Otherwise, the function returns an xs:decimal representing the seconds + component in $value. Given that a duration + is a ($months, $seconds) tuple, the result is the value of ($seconds mod 60) + as an xs:decimal.

+

If $value is a negative duration then the result will be negative.

+

If $value is an xs:yearMonthDuration the function returns 0.

+
+ + + + seconds-from-duration( + xs:dayTimeDuration("P3DT10H12.5S") +) + 12.5 + + + + + seconds-from-duration( + xs:dayTimeDuration("-PT256S") +) + -16.0 + + + +
+ + + + + + + + Defines the semantics of the + + operator when applied to two xs:yearMonthDuration values. + +

Returns the result of adding two xs:yearMonthDuration values.

+
+ +

The function returns the result of adding $arg1 to $arg2. + The result will be an xs:yearMonthDuration whose + length in months is equal to the length in months of $arg1 plus the length + in months of $arg2.

+

For handling of overflow, see .

+
+ +

Either duration (and therefore the result) may be negative.

+
+ + + + op:add-yearMonthDurations( + xs:yearMonthDuration("P2Y11M"), + xs:yearMonthDuration("P3Y3M") +) + xs:yearMonthDuration("P6Y2M") + + + +
+ + + + + + + + Defines the semantics of the + - operator when applied to two xs:yearMonthDuration values. + +

Returns the result of subtracting one xs:yearMonthDuration value from + another.

+
+ +

The function returns the result of subtracting $arg2 from + $arg1. The result will be an xs:yearMonthDuration + whose length in months is equal to the length in months of $arg1 minus the + length in months of $arg2.

+

For handling of overflow, see .

+
+ +

Either duration (and therefore the result) may be negative.

+
+ + + + op:subtract-yearMonthDurations( + xs:yearMonthDuration("P2Y11M"), + xs:yearMonthDuration("P3Y3M") +) + xs:yearMonthDuration("-P4M") + + + +
+ + + + + + + + Defines the semantics of the + * operator when applied to an xs:yearMonthDuration and a numeric + value. + +

Returns the result of multiplying $arg1 by $arg2. + The result is rounded to the nearest month.

+
+ +

The result is the xs:yearMonthDuration whose length in months is equal to + the result of applying the fn:round function to the value obtained by + multiplying the length in months of $arg1 by the value of + $arg2.

+

If $arg2 is positive or negative zero, the result is a zero-length + duration. If $arg2 is positive or negative infinity, the result overflows + and is handled as described in .

+

For handling of overflow and underflow, see .

+
+ +

A dynamic error is raised if $arg2 is + NaN.

+
+ +

Either duration (and therefore the result) may be negative.

+
+ + + + op:multiply-yearMonthDuration( + xs:yearMonthDuration("P2Y11M"), + 2.3 +) + xs:yearMonthDuration("P6Y9M") + + + +
+ + + + + + + + Defines the semantics of the + div operator when applied to an xs:yearMonthDuration and a numeric + value. + +

Returns the result of dividing $arg1 by $arg2. + The result is rounded to the nearest month.

+
+ +

The result is the xs:yearMonthDuration whose length in months is equal to + the result of applying the fn:round function to the value obtained by + dividing the length in months of $arg1 by the value of + $arg2.

+

If $arg2 is positive or negative infinity, the result is a zero-length + duration. If $arg2 is positive or negative zero, the result overflows and + is handled as described in .

+

For handling of overflow and underflow, see .

+
+ +

A dynamic error is raised if $arg2 is + NaN.

+
+ +

Either operand (and therefore the result) may be negative.

+
+ + + + op:divide-yearMonthDuration( + xs:yearMonthDuration("P2Y11M"), + 1.5 +) + xs:yearMonthDuration("P1Y11M") + + + +
+ + + + + + + + Defines the semantics of the + div operator when applied to two xs:yearMonthDuration values. + +

Returns the ratio of two xs:yearMonthDuration values.

+
+ +

The function returns the result of dividing the length in months of $arg1 + by the length in months of $arg2, according to the rules of the + op:numeric-divide function for integer operands.

+

For handling of overflow and underflow, see .

+
+ +

Either duration (and therefore the result) may be negative.

+
+ + + + op:divide-yearMonthDuration-by-yearMonthDuration( + xs:yearMonthDuration("P3Y4M"), + xs:yearMonthDuration("-P1Y4M") +) + -2.5 + + + +

The following example demonstrates how to calculate the length of an + xs:yearMonthDuration value in months:

+ + op:divide-yearMonthDuration-by-yearMonthDuration( + xs:yearMonthDuration("P3Y4M"), + xs:yearMonthDuration("P1M") +) + 40 + +
+
+
+ + + + + + + + Defines the semantics of the + + operator when applied to two xs:dayTimeDuration values. + +

Returns the sum of two xs:dayTimeDuration values.

+
+ +

The function returns the result of adding $arg1 to + $arg2. The result is the xs:dayTimeDuration whose length in + seconds is equal to the sum of the length in seconds of the two input durations.

+

For handling of overflow, see .

+
+ +

Either duration (and therefore the result) may be negative.

+
+ + + + op:add-dayTimeDurations( + xs:dayTimeDuration("P2DT12H5M"), + xs:dayTimeDuration("P5DT12H") +) + xs:dayTimeDuration('P8DT5M') + + + +
+ + + + + + + + Defines the semantics of the - + operator when applied to two xs:dayTimeDuration values. + +

Returns the result of subtracting one xs:dayTimeDuration from another.

+
+ +

The function returns the result of subtracting $arg2 from + $arg1. The result is the xs:dayTimeDuration whose + length in seconds is equal to the length in seconds of $arg1 minus the + length in seconds of $arg2.

+

For handling of overflow, see .

+
+ +

Either duration (and therefore the result) may be negative.

+
+ + + + op:subtract-dayTimeDurations( + xs:dayTimeDuration("P2DT12H"), + xs:dayTimeDuration("P1DT10H30M") +) + xs:dayTimeDuration('P1DT1H30M') + + + +
+ + + + + + + + Defines the semantics of the * + operator when applied to an xs:dayTimeDuration and a numeric + value. + +

Returns the result of multiplying a xs:dayTimeDuration by a number.

+
+ +

The function returns the result of multiplying $arg1 by + $arg2. The result is the xs:dayTimeDuration whose length in + seconds is equal to the length in seconds of $arg1 multiplied by the + numeric value $arg2.

+ +

If $arg2 is positive or negative zero, the result is a zero-length + duration. If $arg2 is positive or negative infinity, the result overflows + and is handled as described in .

+

For handling of overflow and underflow, see .

+
+ +

A dynamic error is raised if $arg2 is + NaN.

+
+ +

Either operand (and therefore the result) may be negative.

+
+ + + + op:multiply-dayTimeDuration( + xs:dayTimeDuration("PT2H10M"), + 2.1 +) + xs:dayTimeDuration('PT4H33M') + + + +
+ + + + + + + + Defines the semantics of the + div operator when applied to two xs:dayTimeDuration values. + +

Returns the result of multiplying a xs:dayTimeDuration by a number.

+
+ +

The function returns the result of dividing $arg1 by + $arg2. The result is the xs:dayTimeDuration whose length in + seconds is equal to the length in seconds of $arg1 divided by the numeric + value $arg2.

+

If $arg2 is positive or negative infinity, the result is a zero-length + duration. If $arg2 is positive or negative zero, the result overflows and + is handled as described in .

+ +

For handling of overflow and underflow, see .

+
+ +

A dynamic error is raised if $arg2 is + NaN.

+
+ +

Either operand (and therefore the result) may be negative.

+
+ + + + op:divide-dayTimeDuration( + xs:dayTimeDuration("P1DT2H30M10.5S"), + 1.5 +) + xs:duration("PT17H40M7S") + + + +
+ + + + + + + + Defines the semantics of the + div operator when applied to two xs:dayTimeDuration values. + +

Returns the ratio of two xs:dayTimeDuration values, as a decimal + number.

+
+ +

The function returns the result of dividing $arg1 by + $arg2. The result is the xs:dayTimeDuration whose length in + seconds is equal to the length in seconds of $arg1 divided by the length in + seconds of $arg2. The calculation is performed by applying + op:numeric-divide to the two xs:decimal operands.

+

For handling of overflow and underflow, see .

+
+ +

Either operand (and therefore the result) may be negative.

+
+ + + + round-half-to-even( + op:divide-dayTimeDuration-by-dayTimeDuration( + xs:dayTimeDuration("P2DT53M11S"), xs:dayTimeDuration("P1DT10H") + ), + 4 +) + 1.4378 + + + +

This examples shows how to determine the number of seconds in a duration.

+ + op:divide-dayTimeDuration-by-dayTimeDuration( + xs:dayTimeDuration("P2DT53M11S"), + xs:dayTimeDuration("PT1S") +) + 175991.0 + +
+
+
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an xs:dateTime value created by combining an xs:date + and an xs:time.

+
+ +

If either $date or $time is the empty sequence the function + returns the empty sequence.

+

Otherwise, the function returns an xs:dateTime whose date component is + equal to $date and whose time component is equal to $time.

+

The timezone of the result is computed as follows:

+ + +

If neither argument has a timezone, the result has no timezone.

+
+ +

If exactly one of the arguments has a timezone, or if both arguments have the same + timezone, the result has this timezone.

+
+
+
+ +

A dynamic error is raised if the two arguments both + have timezones and the timezones are different.

+
+ + + + dateTime( + xs:date("1999-12-31"), + xs:time("12:00:00") +) + xs:dateTime("1999-12-31T12:00:00") + + + + + dateTime( + xs:date("1999-12-31"), + xs:time("24:00:00") +) + xs:dateTime("1999-12-31T00:00:00") + This is because "24:00:00" is an alternate lexical form + for "00:00:00" + + + +
+ + + + + + + + Defines the + semantics of the eq operator when applied to two xs:dateTime values. Also + used in the definition of the ne, le and ge operators. + + deterministic + context-dependent + focus-independent + + +

Returns true if the two supplied xs:dateTime values refer to the same + instant in time.

+
+ +

If either $arg1 or $arg2 has no timezone component, the + effective value of the argument is obtained by substituting the implicit timezone from + the dynamic evaluation context.

+

The function then returns true if and only if the effective value of + $arg1 is equal to the effective value of $arg2 according to + the algorithm defined in section 3.2.7.4 of + Order relation on dateTime for xs:dateTime values with + timezones. Otherwise the function returns false.

+
+ + +

Assume that the dynamic context provides an implicit timezone value of + -05:00

+
+ + + op:dateTime-equal( + xs:dateTime("2002-04-02T12:00:00-01:00"), + xs:dateTime("2002-04-02T17:00:00+04:00") +) + true() + + + + + op:dateTime-equal( + xs:dateTime("2002-04-02T12:00:00"), + xs:dateTime("2002-04-02T23:00:00+06:00") +) + true() + + + + + op:dateTime-equal( + xs:dateTime("2002-04-02T12:00:00"), + xs:dateTime("2002-04-02T17:00:00") +) + false() + + + + + op:dateTime-equal( + xs:dateTime("2002-04-02T12:00:00"), + xs:dateTime("2002-04-02T12:00:00") +) + true() + + + + + op:dateTime-equal( + xs:dateTime("2002-04-02T23:00:00-04:00"), + xs:dateTime("2002-04-03T02:00:00-01:00") +) + true() + + + + + op:dateTime-equal( + xs:dateTime("1999-12-31T24:00:00"), + xs:dateTime("2000-01-01T00:00:00") +) + true() + + + + + op:dateTime-equal( + xs:dateTime("2005-04-04T24:00:00"), + xs:dateTime("2005-04-04T00:00:00") +) + false() + + +
+
+ + + + + + + + + Defines the + semantics of the lt operator when applied to two xs:dateTime values. Also + used in the definition of the ge operator. + + deterministic + context-dependent + focus-independent + + +

Returns true if the first argument represents an earlier instant in time + than the second argument.

+
+ +

If either $arg1 or $arg2 has no timezone component, the + effective value of the argument is obtained by substituting the implicit timezone from + the dynamic evaluation context.

+

The function then returns true if and only if the effective value of + $arg1 is less than the effective value of $arg2 according + to the algorithm defined in section 3.2.7.4 of + Order relation on dateTime for xs:dateTime values with + timezones. Otherwise the function returns false.

+
+
+ + + + + + + + + + Defines the + semantics of the eq operator when applied to two xs:date values. Also used + in the definition of the ne, le and ge operators. + + deterministic + context-dependent + focus-independent + + +

Returns true if and only if the starting instants of the two supplied + xs:date values are the same.

+
+ +

The starting instant of an xs:date is the xs:dateTime at time + 00:00:00 on that date.

+

The function returns the result of the expression:

+ op:dateTime-equal(xs:dateTime($arg1), xs:dateTime($arg2)) +
+ + + + op:date-equal( + xs:date("2004-12-25Z"), + xs:date("2004-12-25+07:00") +) + false() + The starting instants are + xs:dateTime("2004-12-25T00:00:00Z") and + xs:dateTime("2004-12-25T00:00:00+07:00"). These are normalized to + xs:dateTime("2004-12-25T00:00:00Z") and + xs:dateTime("2004-12-24T17:00:00Z"). + + + + + op:date-equal( + xs:date("2004-12-25-12:00"), + xs:date("2004-12-26+12:00") +) + true() + + + +
+ + + + + + + + Defines the semantics + of the lt operator when applied to two xs:date values. Also used in the + definition of the ge operator. + +

Returns true if and only if the starting instant of $arg1 is + less than the starting instant of $arg2. Returns false + otherwise.

+
+ +

The starting instant of an xs:date is the xs:dateTime at time + 00:00:00 on that date.

+

The function returns the result of the expression:

+ op:dateTime-less-than(xs:dateTime($arg1), xs:dateTime($arg2)) +
+ + + + op:date-less-than( + xs:date("2004-12-25Z"), + xs:date("2004-12-25-05:00") +) + true() + + + + + op:date-less-than( + xs:date("2004-12-25-12:00"), + xs:date("2004-12-26+12:00") +) + false() + + + +
+ + + + + + + + + Defines the + semantics of the eq operator when applied to two xs:time values. Also used + in the definition of the ne, le and ge operators. + + deterministic + context-dependent + focus-independent + + +

Returns true if the two xs:time values represent the same + instant in time, when treated as being times on the same date, before adjusting the + timezone.

+
+ +

Each of the supplied xs:time values is expanded to an + xs:dateTime value by associating the time with an arbitrary date. The + function returns the result of comparing these two xs:dateTime values using + op:dateTime-equal.

+

The result of the function is thus the same as the value of the expression:

+ op:dateTime-equal( + dateTime(xs:date('1972-12-31'), $arg1), + dateTime(xs:date('1972-12-31'), $arg2)) +
+ + +

Assume that the date components from the reference xs:dateTime + correspond to 1972-12-31.

+
+ + + op:time-equal( + xs:time("08:00:00+09:00"), + xs:time("17:00:00-06:00") +) + false() + The xs:dateTimes calculated using the reference date + components are 1972-12-31T08:00:00+09:00 and + 1972-12-31T17:00:00-06:00. These normalize to + 1972-12-30T23:00:00Z and 1972-12-31T23:00:00Z. + + + + + + op:time-equal( + xs:time("21:30:00+10:30"), + xs:time("06:00:00-05:00") +) + true() + + + + + op:time-equal( + xs:time("24:00:00+01:00"), + xs:time("00:00:00+01:00") +) + true() + This not the result one might expect. For xs:dateTime + values, a time of 24:00:00 is equivalent to 00:00:00 on + the following day. For xs:time, the normalization from + 24:00:00 to 00:00:00 happens before the + xs:time is converted into an xs:dateTime for the + purpose of the equality comparison. For xs:time, any operation on + 24:00:00 produces the same result as the same operation on + 00:00:00 because these are two different lexical representations + of the same value. + + +
+
+ + + + + + + + Defines the semantics + of the lt operator when applied to two xs:time values. Also used in the + definition of the ge operator. + + deterministic + context-dependent + focus-independent + + +

Returns true if the first xs:time value represents an earlier + instant in time than the second, when both are treated as being times on the same date, + before adjusting the timezone.

+
+ +

Each of the supplied xs:time values is expanded to an + xs:dateTime value by associating the time with an arbitrary date. The + function returns the result of comparing these two xs:dateTime values using + op:dateTime-less-than.

+

The result of the function is thus the same as the value of the expression:

+ op:dateTime-less-than( + dateTime(xs:date('1972-12-31'), $arg1), + dateTime(xs:date('1972-12-31'), $arg2)) +
+ + +

Assume that the dynamic context provides an implicit timezone value of + -05:00.

+
+ + + op:time-less-than( + xs:time("12:00:00"), + xs:time("23:00:00+06:00") +) + false() + + + + + op:time-less-than( + xs:time("11:00:00"), + xs:time("17:00:00Z") +) + true() + + + + + op:time-less-than( + xs:time("23:59:59"), + xs:time("24:00:00") +) + false() + + +
+
+ + + + + + + + + Defines the + semantics of the eq operator when applied to two xs:gYearMonth values. Also + used in the definition of the ne operator. + + deterministic + context-dependent + focus-independent + + +

Returns true if the two xs:gYearMonth values have the same starting + instant.

+
+ +

The starting instants of $arg1 and $arg2 are calculated by + supplying the missing components of $arg1 and $arg2 from the + xs:dateTime template xxxx-xx-01T00:00:00. The function + returns the result of comparing these two starting instants using + op:dateTime-equal.

+
+ + +

Assume that the dynamic context provides an implicit timezone value of + -05:00.

+
+ +

op:gYearMonth-equal(xs:gYearMonth("1986-02"), xs:gYearMonth("1986-03")) + returns false(). The starting instants are + 1986-02-01T00:00:00-05:00 and 1986-03-01T00:00:00, + respectively.

+
+ +

op:gYearMonth-equal(xs:gYearMonth("1978-03"), xs:gYearMonth("1986-03Z")) + returns false(). The starting instants are + 1978-03-01T00:00:00-05:00 and 1986-03-01T00:00:00Z, + respectively.

+
+
+
+ + + + + + + + + Defines the semantics + of the eq operator when applied to two xs:gYear values. Also used in the + definition of the ne operator. + + deterministic + context-dependent + focus-independent + + +

Returns true if the two xs:gYear values have the same starting instant.

+
+ +

The starting instants of $arg1 and $arg2 are calculated by + supplying the missing components of $arg1 and $arg2 from the + xs:dateTime template xxxx-01-01T00:00:00. The function + returns the result of comparing these two starting instants using + op:dateTime-equal.

+
+ + +

Assume that the dynamic context provides an implicit timezone value of + -05:00. Assume, also, that the xs:dateTime template is + xxxx-01-01T00:00:00.

+
+ +

op:gYear-equal(xs:gYear("2005-12:00"), xs:gYear("2005+12:00")) returns + false(). The starting instants are + 2005-01-01T00:00:00-12:00 and 2005-01-01T00:00:00+12:00, + respectively, and normalize to 2005-01-01T12:00:00Z and + 2004-12-31T12:00:00Z.

+
+ + + op:gYear-equal( + xs:gYear("1976-05:00"), + xs:gYear("1976") +) + true() + + +
+
+ + + + + + + + + Defines the + semantics of the eq operator when applied to two xs:gMonthDay values. Also + used in the definition of the ne operator. + + deterministic + context-dependent + focus-independent + + +

Returns true if the two xs:gMonthDay values have the same starting instant, + when considered as days in the same year.

+
+ +

The starting instants of $arg1 and $arg2 are calculated by + supplying the missing components of $arg1 and $arg2 from the + xs:dateTime template 1972-xx-xxT00:00:00 or an equivalent. + The function returns the result of comparing these two starting instants using + op:dateTime-equal.

+
+ + +

Assume that the dynamic context provides an implicit timezone value of + -05:00. Assume for the purposes of illustration that the + xs:dateTime template used is 1972-xx-xxT00:00:00 (this + does not affect the result).

+
+ + + op:gMonthDay-equal( + xs:gMonthDay("--12-25-14:00"), + xs:gMonthDay("--12-26+10:00") +) + true() + The starting instants are 1972-12-25T00:00:00-14:00 and + 1972-12-26T00:00:00+10:00, respectively, and normalize to + 1972-12-25T14:00:00Z and 1972-12-25T14:00:00Z. + + + + + + op:gMonthDay-equal( + xs:gMonthDay("--12-25"), + xs:gMonthDay("--12-26Z") +) + false() + + +
+
+ + + + + + + + Defines the + semantics of the eq operator when applied to two xs:gMonth values. Also used + in the definition of the ne operator. + + deterministic + context-dependent + focus-independent + + +

Returns true if the two xs:gMonth values have the same starting instant, + when considered as months in the same year.

+
+ +

The starting instants of $arg1 and $arg2 are calculated by + supplying the missing components of $arg1 and $arg2 from the + xs:dateTime template 1972-xx-01T00:00:00 or an equivalent. + The function returns the result of comparing these two starting instants using + op:dateTime-equal.

+
+ + +

Assume that the dynamic context provides an implicit timezone value of + -05:00. Assume, also, that the xs:dateTime template + chosen is 1972-xx-01T00:00:00.

+
+ + + op:gMonth-equal( + xs:gMonth("--12-14:00"), + xs:gMonth("--12+10:00") +) + false() + The starting instants are 1972-12-01T00:00:00-14:00 and + 1972-12-01T00:00:00+10:00, respectively, and normalize to + 1972-11-30T14:00:00Z and 1972-12-01T14:00:00Z. + + + + + + op:gMonth-equal( + xs:gMonth("--12"), + xs:gMonth("--12Z") +) + false() + + +
+
+ + + + + + + + Defines the semantics + of the eq operator when applied to two xs:gDay values. Also used in the + definition of the ne operator. + + deterministic + context-dependent + focus-independent + + +

Returns true if the two xs:gDay values have the same starting instant, when + considered as days in the same month of the same year.

+
+ +

The starting instants of $arg1 and $arg2 are calculated by + supplying the missing components of $arg1 and $arg2 from the + xs:dateTime template 1972-12-xxT00:00:00 or an equivalent. + The function returns the result of comparing these two starting instants using + op:dateTime-equal.

+
+ + +

Assume that the dynamic context provides an implicit timezone value of + -05:00. Assume, also, that the xs:dateTime template is + 1972-12-xxT00:00:00.

+
+ + + op:gDay-equal( + xs:gDay("---25-14:00"), + xs:gDay("---25+10:00") +) + false() + The starting instants are 1972-12-25T00:00:00-14:00 and + 1972-12-25T00:00:00+10:00, respectively, and normalize to + 1972-12-25T14:00:00Z and 1972-12-24T14:00:00Z. + + + + + + op:gDay-equal(xs:gDay("---12"), xs:gDay("---12Z")) + false() + + +
+
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the year component of an xs:dateTime.

+
+ +

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

+

Otherwise, the function returns an xs:integer representing the year + component in the local value of $value. The result may be negative.

+
+ +

Ignoring complications that arise with midnight on the last day + of the year, the year returned is the same numeric value that appears in the lexical + representation, which for negative years means the meaning may vary depending on whether + XSD 1.0 or XSD 1.1 conventions are in use.

+
+ + + + year-from-dateTime( + xs:dateTime("1999-05-31T13:20:00-05:00") +) + 1999 + + + + + year-from-dateTime( + xs:dateTime("1999-05-31T21:30:00-05:00") +) + 1999 + + + + + year-from-dateTime( + xs:dateTime("1999-12-31T19:20:00") +) + 1999 + + + + + year-from-dateTime( + xs:dateTime("1999-12-31T24:00:00") +) + 2000 + + + + + year-from-dateTime( + xs:dateTime("-0002-06-06T00:00:00") +) + -2 + The result is the same whether XSD 1.0 or 1.1 is in use, despite + the absence of a year 0 in the XSD 1.0 value space. + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the month component of an xs:dateTime.

+
+ +

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

+

Otherwise, the function returns an xs:integer between 1 and + 12, both inclusive, representing the month component in the + local value of $value.

+
+ + + + month-from-dateTime( + xs:dateTime("1999-05-31T13:20:00-05:00") +) + 5 + + + + + month-from-dateTime( + xs:dateTime("1999-12-31T19:20:00-05:00") +) + 12 + + + + + month-from-dateTime( + adjust-dateTime-to-timezone( + xs:dateTime("1999-12-31T19:20:00-05:00"), + xs:dayTimeDuration("PT0S") + ) +) + 1 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the day component of an xs:dateTime.

+
+ +

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

+

Otherwise, the function returns an xs:integer between 1 and + 31, both inclusive, representing the day component in the + local value of $value.

+
+ + + + day-from-dateTime( + xs:dateTime("1999-05-31T13:20:00-05:00") +) + 31 + + + + + day-from-dateTime( + xs:dateTime("1999-12-31T20:00:00-05:00") +) + 31 + + + + + day-from-dateTime( + adjust-dateTime-to-timezone( + xs:dateTime("1999-12-31T19:20:00-05:00"), + xs:dayTimeDuration("PT0S") + ) +) + 1 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the hours component of an xs:dateTime.

+
+ +

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

+

Otherwise, the function returns an xs:integer between 0 and + 23, both inclusive, representing the hours component in the local value + of $value.

+
+ + + + hours-from-dateTime( + xs:dateTime("1999-05-31T08:20:00-05:00") +) + 8 + + + + + hours-from-dateTime( + xs:dateTime("1999-12-31T21:20:00-05:00") +) + 21 + + + + + hours-from-dateTime( + adjust-dateTime-to-timezone( + xs:dateTime("1999-12-31T21:20:00-05:00"), + xs:dayTimeDuration("PT0S") + ) +) + 2 + + + + + hours-from-dateTime( + xs:dateTime("1999-12-31T12:00:00") +) + 12 + + + + + hours-from-dateTime( + xs:dateTime("1999-12-31T24:00:00") +) + 0 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the minute component of an xs:dateTime.

+
+ +

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

+

Otherwise, the function returns an xs:integer value between 0 + and 59, both inclusive, representing the minute component in the local value of + $value.

+
+ + + + minutes-from-dateTime( + xs:dateTime("1999-05-31T13:20:00-05:00") +) + 20 + + + + + minutes-from-dateTime( + xs:dateTime("1999-05-31T13:30:00+05:30") +) + 30 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the seconds component of an xs:dateTime.

+
+ +

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

+

Otherwise, the function returns an xs:decimal value greater than or equal + to zero and less than 60, representing the seconds and fractional seconds in the local + value of $value.

+
+ + + + seconds-from-dateTime( + xs:dateTime("1999-05-31T13:20:00-05:00") +) + 0 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the timezone component of an xs:dateTime.

+
+ +

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

+

Otherwise, the function returns the timezone component of $value, if any. If + $value has a timezone component, then the result is an + xs:dayTimeDuration that indicates deviation from UTC; its value may + range from +14:00 to -14:00 hours, both inclusive. If $value has no timezone + component, the result is the empty sequence.

+
+ + + + timezone-from-dateTime( + xs:dateTime("1999-05-31T13:20:00-05:00") +) + xs:dayTimeDuration("-PT5H") + + + + + timezone-from-dateTime( + xs:dateTime("2000-06-12T13:20:00Z") +) + xs:dayTimeDuration("PT0S") + + + + + timezone-from-dateTime( + xs:dateTime("2004-08-27T00:00:00") +) + () + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the year component of an xs:date.

+
+ +

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

+

Otherwise, the function returns an xs:integer representing the year in the + local value of $value. The value may be negative.

+
+ +

The year returned is the same numeric value that appears in the lexical + representation, which for negative years means the meaning may vary depending on whether + XSD 1.0 or XSD 1.1 conventions are in use.

+
+ + + + year-from-date( + xs:date("1999-05-31") +) + 1999 + + + + + year-from-date( + xs:date("2000-01-01+05:00") +) + 2000 + + + + + year-from-date( + xs:date("-0002-06-01") +) + -2 + The result is the same whether XSD 1.0 or 1.1 is in use, despite + the absence of a year 0 in the XSD 1.0 value space. + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the month component of an xs:date.

+
+ +

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

+

Otherwise, the function returns an xs:integer between + 1 and 12, both + inclusive, representing the month component in the local value of $value. +

+
+ + + + month-from-date( + xs:date("1999-05-31-05:00") +) + 5 + + + + + month-from-date( + xs:date("2000-01-01+05:00") +) + 1 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the day component of an xs:date.

+
+ +

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

+

Otherwise, the function returns an xs:integer between + 1 and 31, both + inclusive, representing the day component in the localized value of + $value.

+
+ + + + day-from-date( + xs:date("1999-05-31-05:00") +) + 31 + + + + + day-from-date( + xs:date("2000-01-01+05:00") +) + 1 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the timezone component of an xs:date.

+
+ +

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

+

Otherwise, the function returns the timezone component of $value, if any. If + $value has a timezone component, then the result is an + xs:dayTimeDuration that indicates deviation from UTC; its value may + range from +14:00 to -14:00 hours, both inclusive. If $value has no timezone + component, the result is the empty sequence.

+
+ + + + timezone-from-date( + xs:date("1999-05-31-05:00") +) + xs:dayTimeDuration("-PT5H") + + + + + timezone-from-date( + xs:date("2000-06-12Z") +) + xs:dayTimeDuration("PT0S") + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the hours component of an xs:time.

+
+ +

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

+

Otherwise, the function returns an xs:integer between + 0 and 23, both + inclusive, representing the value of the hours component in the local value of + $value.

+
+ + +

Assume that the dynamic context provides an implicit timezone value of + -05:00.

+
+ + + hours-from-time(xs:time("11:23:00")) + 11 + + + + + hours-from-time(xs:time("21:23:00")) + 21 + + + + + hours-from-time(xs:time("01:23:00+05:00")) + 1 + + + + + hours-from-time( + adjust-time-to-timezone( + xs:time("01:23:00+05:00"), + xs:dayTimeDuration("PT0S") + ) +) + 20 + + + + + hours-from-time(xs:time("24:00:00")) + 0 + + +
+
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the minutes component of an xs:time.

+
+ +

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

+

Otherwise, the function returns an xs:integer value between 0 + and 59, both inclusive, representing the value of the minutes component + in the local value of $value.

+
+ + + + minutes-from-time(xs:time("13:00:00Z")) + 0 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the seconds component of an xs:time.

+
+ +

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

+

Otherwise, the function returns an xs:decimal value greater than or equal + to zero and less than 60, representing the seconds and fractional seconds in the local + value of $value.

+
+ + + + seconds-from-time(xs:time("13:20:10.5")) + 10.5 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the timezone component of an xs:time.

+
+ +

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

+

Otherwise, the function returns the timezone component of $value, if any. If + $value has a timezone component, then the result is an + xs:dayTimeDuration that indicates deviation from UTC; its value may + range from +14:00 to -14:00 hours, both inclusive. If $value has no timezone + component, the result is the empty sequence.

+
+ + + + timezone-from-time(xs:time("13:20:00-05:00")) + xs:dayTimeDuration("-PT5H") + + + + + timezone-from-time(xs:time("13:20:00")) + () + + + +
+ + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-independent + focus-independent + + +

Adjusts an xs:dateTime value to a specific timezone, or to no timezone at + all.

+
+ +

If $timezone is not specified, then the effective value of + $timezone is the value of the implicit timezone in the dynamic + context.

+

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

+

If $value does not have a timezone component and $timezone is + the empty sequence, then the result is $value.

+

If $value does not have a timezone component and $timezone is + not the empty sequence, then the result is $value with $timezone + as the timezone component.

+

If $value has a timezone component and $timezone is the empty + sequence, then the result is the local value of $value without its timezone + component.

+

If $value has a timezone component and $timezone is not the + empty sequence, then the result is the xs:dateTime value that is equal to + $value and that has a timezone component equal to + $timezone.

+
+ +

A dynamic error is raised if $timezone + is less than -PT14H or greater than PT14H or is not an + integral number of minutes.

+
+ + +

Assume the dynamic context provides an implicit timezone of -05:00 + (-PT5H0M).

+
+ + + + adjust-dateTime-to-timezone( + xs:dateTime('2002-03-07T10:00:00') +) + xs:dateTime('2002-03-07T10:00:00-05:00') + + + + + adjust-dateTime-to-timezone( + xs:dateTime('2002-03-07T10:00:00-07:00') +) + xs:dateTime('2002-03-07T12:00:00-05:00') + + + + + adjust-dateTime-to-timezone( + xs:dateTime('2002-03-07T10:00:00'), + $tz-10 +) + xs:dateTime('2002-03-07T10:00:00-10:00') + + + + + adjust-dateTime-to-timezone( + xs:dateTime('2002-03-07T10:00:00-07:00'), + $tz-10 +) + xs:dateTime('2002-03-07T07:00:00-10:00') + + + + + adjust-dateTime-to-timezone( + xs:dateTime('2002-03-07T10:00:00-07:00'), + xs:dayTimeDuration("PT10H") +) + xs:dateTime('2002-03-08T03:00:00+10:00') + + + + + adjust-dateTime-to-timezone( + xs:dateTime('2002-03-07T00:00:00+01:00'), + xs:dayTimeDuration("-PT8H") +) + xs:dateTime('2002-03-06T15:00:00-08:00') + + + + + adjust-dateTime-to-timezone( + xs:dateTime('2002-03-07T10:00:00'), + () +) + xs:dateTime('2002-03-07T10:00:00') + + + + + adjust-dateTime-to-timezone( + xs:dateTime('2002-03-07T10:00:00-07:00'), + () +) + xs:dateTime('2002-03-07T10:00:00') + + +
+
+ + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-independent + focus-independent + + +

Adjusts an xs:date value to a specific timezone, or to no timezone at all; + the result is the date in the target timezone that contains the starting instant of the + supplied date.

+
+ +

If $timezone is not specified, then the effective value of + $timezone is the value of the implicit timezone in the dynamic + context.

+

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

+

If $value does not have a timezone component and $timezone is + the empty sequence, then the result is $value.

+

If $value does not have a timezone component and $timezone is + not the empty sequence, then the result is $value with $timezone + as the timezone component.

+

If $value has a timezone component and $timezone is the empty + sequence, then the result is the local value of $value without its timezone + component.

+

If $value has a timezone component and $timezone is not the + empty sequence, then the function returns the value of the expression:

+ + +

Let $dt be the value of fn:dateTime($arg, + xs:time('00:00:00')).

+
+ +

Let $adt be the value of fn:adjust-dateTime-to-timezone($dt, + $timezone)

+
+ +

The function returns the value of xs:date($adt)

+
+
+
+ +

A dynamic error is raised if $timezone + is less than -PT14H or greater than PT14H or is not an + integral number of minutes.

+
+ + +

Assume the dynamic context provides an implicit timezone of -05:00 + (-PT5H0M).

+
+ + + + adjust-date-to-timezone( + xs:date("2002-03-07") +) + xs:date("2002-03-07-05:00") + + + + + adjust-date-to-timezone( + xs:date("2002-03-07-07:00") +) + xs:date("2002-03-07-05:00") + $value is converted to + xs:dateTime("2002-03-07T00:00:00-07:00"). This is adjusted to the + implicit timezone, giving "2002-03-07T02:00:00-05:00". + + + + + + adjust-date-to-timezone( + xs:date("2002-03-07"), + $tz-10 +) + xs:date("2002-03-07-10:00") + + + + + adjust-date-to-timezone( + xs:date("2002-03-07-07:00"), + $tz-10 +) + xs:date("2002-03-06-10:00") + $value is converted to + xs:dateTime("2002-03-07T00:00:00-07:00"). + This is adjusted to the given timezone, + giving "2002-03-06T21:00:00-10:00". + + + + + adjust-date-to-timezone( + xs:date("2002-03-07"), + () +) + xs:date("2002-03-07") + + + + + adjust-date-to-timezone( + xs:date("2002-03-07-07:00"), + () +) + xs:date("2002-03-07") + + +
+
+ + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-independent + focus-independent + + +

Adjusts an xs:time value to a specific timezone, or to no timezone at + all.

+
+ +

If $timezone is not specified, then the effective value of + $timezone is the value of the implicit timezone in the dynamic + context.

+

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

+

If $value does not have a timezone component and $timezone is + the empty sequence, then the result is $value.

+

If $value does not have a timezone component and $timezone is + not the empty sequence, then the result is $value with $timezone + as the timezone component.

+

If $value has a timezone component and $timezone is the empty + sequence, then the result is the localized value of $value without its + timezone component.

+

If $value has a timezone component and $timezone is not the + empty sequence, then:

+ + +

Let $dt be the xs:dateTime value + fn:dateTime(xs:date('1972-12-31'), $value).

+
+ +

Let $adt be the value of fn:adjust-dateTime-to-timezone($dt, + $timezone) +

+
+ +

The function returns the xs:time value + xs:time($adt).

+
+
+
+ +

A dynamic error is raised if $timezone + is less than -PT14H or greater than PT14H or if does not + contain an integral number of minutes.

+
+ + +

Assume the dynamic context provides an implicit timezone of -05:00 + (-PT5H0M).

+
+ + + + adjust-time-to-timezone( + xs:time("10:00:00") +) + xs:time("10:00:00-05:00") + + + + + adjust-time-to-timezone( + xs:time("10:00:00-07:00") +) + xs:time("12:00:00-05:00") + + + + + adjust-time-to-timezone( + xs:time("10:00:00"), + $tz-10 +) + xs:time("10:00:00-10:00") + + + + + adjust-time-to-timezone( + xs:time("10:00:00-07:00"), + $tz-10 +) + xs:time("07:00:00-10:00") + + + + + adjust-time-to-timezone( + xs:time("10:00:00"), + () +) + xs:time("10:00:00") + + + + + adjust-time-to-timezone( + xs:time("10:00:00-07:00"), + () +) + xs:time("10:00:00") + + + + + adjust-time-to-timezone( + xs:time("10:00:00-07:00"), + xs:dayTimeDuration("PT10H") +) + xs:time("03:00:00+10:00") + + +
+
+ + + + + + + + + Defines the semantics of the - + operator when applied to two xs:dateTime values. + + deterministic + context-dependent + focus-independent + + +

Returns an xs:dayTimeDuration representing the amount of elapsed time + between the instants arg2 and arg1.

+
+ +

If either $arg1 or $arg2 do not contain an explicit timezone + then, for the purpose of the operation, the implicit timezone provided by the dynamic + context (See .) is + assumed to be present as part of the value.

+

The function returns the elapsed time between the date/time instant arg2 + and the date/time instant arg1, computed according to the algorithm given + in Appendix E of , and expressed as a + xs:dayTimeDuration.

+

If the normalized value of $arg1 precedes in time the normalized value of + $arg2, then the returned value is a negative duration.

+
+ + +

Assume that the dynamic context provides an implicit timezone value of + -05:00.

+
+ + + op:subtract-dateTimes( + xs:dateTime("2000-10-30T06:12:00"), + xs:dateTime("1999-11-28T09:00:00Z") +) + xs:dayTimeDuration("P337DT2H12M") + + +
+
+ + + + + + + + Defines the semantics of the - operator + when applied to two xs:date values. + + deterministic + context-dependent + focus-independent + + +

Returns the xs:dayTimeDuration that corresponds to the elapsed time between + the starting instant of $arg2 and the starting instant of + $arg2.

+
+ +

If either $arg1 or $arg2 do not contain an explicit timezone + then, for the purpose of the operation, the implicit timezone provided by the dynamic + context (See .) is + assumed to be present as part of the value.

+

The starting instant of an xs:date is the xs:dateTime at + 00:00:00 on that date.

+

The function returns the result of subtracting the two starting instants using + op:subtract-dateTimes.

+

If the starting instant of $arg1 precedes in time the starting instant of + $arg2, then the returned value is a negative duration.

+
+ + +

Assume that the dynamic context provides an implicit timezone value of + Z.

+
+ + + op:subtract-dates( + xs:date("2000-10-30"), + xs:date("1999-11-28") +) + xs:dayTimeDuration("P337D") + The normalized values of the two starting instants are {2000, + 10, 30, 0, 0, 0, PT0S} and {1999, 11, 28, 0, 0, 0, + PT0S}. + + + +

Now assume that the dynamic context provides an implicit timezone value of + +05:00.

+
+ + + op:subtract-dates( + xs:date("2000-10-30"), + xs:date("1999-11-28Z") +) + xs:dayTimeDuration("P336DT19H") + The normalized values of the two starting instants are {2000, + 10, 29, 19, 0, 0, PT0S} and {1999, 11, 28, 0, 0, 0, + PT0S}. + + + + + op:subtract-dates( + xs:date("2000-10-15-05:00"), + xs:date("2000-10-10+02:00") +) + xs:dayTimeDuration("P5DT7H") + + +
+
+ + + + + + + + Defines the semantics of the - operator + when applied to two xs:time values. + + deterministic + context-dependent + focus-independent + + +

Returns the xs:dayTimeDuration that corresponds to the elapsed time between + the values of $arg2 and $arg1 treated as times on the same + date.

+
+ +

The function returns the result of the expression:

+ op-subtract-dateTimes( + dateTime(xs:date('1972-12-31'), $arg1), + dateTime(xs:date('1972-12-31'), $arg2)) +
+ +

Any other reference date would work equally well.

+
+ + +

Assume that the dynamic context provides an implicit timezone value of + -05:00. Assume, also, that the date components of the reference + xs:dateTime correspond to "1972-12-31".

+
+ + + op:subtract-times( + xs:time("11:12:00Z"), + xs:time("04:00:00") +) + xs:dayTimeDuration("PT2H12M") + This is obtained by subtracting from the xs:dateTime + value {1972, 12, 31, 11, 12, 0, PT0S} the xs:dateTime + value {1972, 12, 31, 9, 0, 0, PT0S}. + + + + + op:subtract-times( + xs:time("11:00:00-05:00"), + xs:time("21:30:00+05:30") +) + xs:dayTimeDuration("PT0S") + The two xs:dateTime values are {1972, 12, 31, 11, + 0, 0, -PT5H} and {1972, 12, 31, 21, 30, 0, PT5H30M}. These + normalize to {1972, 12, 31, 16, 0, 0, PT0S} and {1972, 12, 31, + 16, 0, 0, PT0S}. + + + + + op:subtract-times( + xs:time("17:00:00-06:00"), + xs:time("08:00:00+09:00") +) + xs:dayTimeDuration("P1D") + The two normalized xs:dateTime values are {1972, + 12, 31, 23, 0, 0, PT0S} and {1972, 12, 30, 23, 0, 0, + PT0S}. + + + + + op:subtract-times( + xs:time("24:00:00"), + xs:time("23:59:59") +) + xs:dayTimeDuration("-PT23H59M59S") + The two normalized xs:dateTime values are {1972, + 12, 31, 0, 0, 0, ()} and {1972, 12, 31, 23, 59, 59.0, + ()}. + + +
+
+ + + + + + + + Defines the + semantics of the + operator when applied to an xs:dateTime and an + xs:yearMonthDuration value. + + deterministic + context-independent + focus-independent + + +

Returns the xs:dateTime that is a given duration after a specified + xs:dateTime (or before, if the duration is negative).

+
+ +

The function returns the result of adding $arg2 to the value of + $arg1 using the algorithm described in Appendix E of , disregarding the rule about leap seconds. If $arg2 + is negative, then the result xs:dateTime precedes $arg1.

+

The result has the same timezone as $arg1. If $arg1 has no + timezone, the result has no timezone.

+
+ + + + op:add-yearMonthDuration-to-dateTime( + xs:dateTime("2000-10-30T11:12:00"), + xs:yearMonthDuration("P1Y2M") +) + xs:dateTime("2001-12-30T11:12:00") + + + +
+ + + + + + + + Defines the semantics + of the + operator when applied to an xs:dateTime and an + xs:dayTimeDuration value. + + deterministic + context-independent + focus-independent + + +

Returns the xs:dateTime that is a given duration after a specified + xs:dateTime (or before, if the duration is negative).

+
+ +

The function returns the result of adding $arg2 to the value of + $arg1 using the algorithm described in Appendix E of , disregarding the rule about leap seconds. If $arg2 + is negative, then the result xs:dateTime precedes $arg1.

+

The result has the same timezone as $arg1. If $arg1 has no + timezone, the result has no timezone.

+
+ + + + op:add-dayTimeDuration-to-dateTime( + xs:dateTime("2000-10-30T11:12:00"), + xs:dayTimeDuration("P3DT1H15M") +) + xs:dateTime("2000-11-02T12:27:00") + + + +
+ + + + + + + + Defines the + semantics of the - operator when applied to an xs:dateTime and an + xs:yearMonthDuration value. + + deterministic + context-independent + focus-independent + + +

Returns the xs:dateTime that is a given duration before a specified + xs:dateTime (or after, if the duration is negative).

+
+ +

The function returns the xs:dateTime computed by negating + $arg2 and adding the result to $arg1 using the + function op:add-yearMonthDuration-to-dateTime.

+
+ + + + op:subtract-yearMonthDuration-from-dateTime( + xs:dateTime("2000-10-30T11:12:00"), + xs:yearMonthDuration("P1Y2M") +) + xs:dateTime("1999-08-30T11:12:00") + + + +
+ + + + + + + + Defines the semantics + of the - operator when applied to an xs:dateTime an and + xs:dayTimeDuration values + +

Returns the xs:dateTime that is a given duration before a specified + xs:dateTime (or after, if the duration is negative).

+
+ +

The function returns the xs:dateTime computed by negating + $arg2 and adding the result to $arg1 using the + function op:add-dayTimeDuration-to-dateTime.

+
+ + + + op:subtract-dayTimeDuration-from-dateTime( + xs:dateTime("2000-10-30T11:12:00"), + xs:dayTimeDuration("P3DT1H15M") +) + xs:dateTime("2000-10-27T09:57:00") + + + +
+ + + + + + + + Defines the semantics + of the + operator when applied to an xs:date and an + xs:yearMonthDuration value. + + deterministic + context-independent + focus-independent + + +

Returns the xs:date that is a given duration after a specified + xs:date (or before, if the duration is negative).

+
+ +

The function returns the result of casting $arg1 to an + xs:dateTime, adding $arg2 using the function + op:add-yearMonthDuration-to-dateTime, and casting the result back to an + xs:date.

+
+ + + + op:add-yearMonthDuration-to-date( + xs:date("2000-10-30"), + xs:yearMonthDuration("P1Y2M") +) + xs:date("2001-12-30") + + + +
+ + + + + + + + Defines the semantics of + the + operator when applied to an xs:date and an + xs:dayTimeDuration value. + + deterministic + context-independent + focus-independent + + +

Returns the xs:date that is a given duration after a specified + xs:date (or before, if the duration is negative).

+
+ +

The function returns the result of casting $arg1 to an + xs:dateTime, adding $arg2 using the function + op:add-dayTimeDuration-to-dateTime, and casting the result back to an + xs:date.

+
+ + + + op:add-dayTimeDuration-to-date( + xs:date("2004-10-30Z"), + xs:dayTimeDuration("P2DT2H30M0S") +) + xs:date("2004-11-01Z") + The starting instant of the first argument is the + xs:dateTime value {2004, 10, 30, 0, 0, 0, PT0S}. + Adding the second argument to this gives the xs:dateTime value + {2004, 11, 1, 2, 30, 0, PT0S}. The time components are then + discarded. + + + +
+ + + + + + + + Defines the semantics + of the - operator when applied to an xs:date and an + xs:yearMonthDuration value. + + deterministic + context-independent + focus-independent + + +

Returns the xs:date that is a given duration before a specified + xs:date (or after, if the duration is negative).

+
+ +

Returns the xs:date computed by negating $arg2 and adding the + result to $arg1 using the function + op:add-yearMonthDuration-to-date.

+
+ + + + op:subtract-yearMonthDuration-from-date( + xs:date("2000-10-30"), + xs:yearMonthDuration("P1Y2M") +) + xs:date("1999-08-30") + + + + + op:subtract-yearMonthDuration-from-date( + xs:date("2000-02-29Z"), + xs:yearMonthDuration("P1Y") +) + xs:date("1999-02-28Z") + + + + + op:subtract-yearMonthDuration-from-date( + xs:date("2000-10-31-05:00"), + xs:yearMonthDuration("P1Y1M") +) + xs:date("1999-09-30-05:00") + + + +
+ + + + + + + + Defines the semantics of + the - operator when applied to an xs:date and an + xs:dayTimeDuration. + + deterministic + context-independent + focus-independent + + +

Returns the xs:date that is a given duration before a specified + xs:date (or after, if the duration is negative).

+
+ +

Returns the xs:date computed by negating $arg2 and adding the + result to $arg1 using the function + op:add-dayTimeDuration-to-date.

+
+ + + + op:subtract-dayTimeDuration-from-date( + xs:date("2000-10-30"), + xs:dayTimeDuration("P3DT1H15M") +) + xs:date("2000-10-26") + + + +
+ + + + + + + + Defines the semantics of + the + operator when applied to an xs:time and an + xs:dayTimeDuration value. + +

Returns the xs:time value that is a given duration after a specified + xs:time (or before, if the duration is negative or causes wrap-around + past midnight)

+
+ +

First, the days component in the canonical lexical representation of $arg2 + is set to zero (0) and the value of the resulting xs:dayTimeDuration is + calculated. Alternatively, the value of $arg2 modulus 86,400 is used as the + second argument. This value is added to the value of $arg1 converted to an + xs:dateTime using a reference date such as 1972-12-31, and + the time component of the result is returned. Note that the xs:time + returned may occur in a following or preceding day and may be less than + $arg1.

+

The result has the same timezone as $arg1. If $arg1 has no + timezone, the result has no timezone.

+
+ + + + op:add-dayTimeDuration-to-time( + xs:time("11:12:00"), + xs:dayTimeDuration("P3DT1H15M") +) + xs:time("12:27:00") + + + + + op:add-dayTimeDuration-to-time( + xs:time("23:12:00+03:00"), + xs:dayTimeDuration("P1DT3H15M") +) + xs:time("02:27:00+03:00") + That is, {0, 0, 0, 2, 27, 0, PT3H} + + + +
+ + + + + + + + Defines the semantics of + the - operator when applied to an xs:time and an + xs:dayTimeDuration value. + + deterministic + context-independent + focus-independent + + +

Returns the xs:time value that is a given duration before a specified + xs:time (or after, if the duration is negative or causes wrap-around + past midnight)

+
+ +

The function returns the result of negating $arg2 and adding the result to + $arg1 using the function op:add-dayTimeDuration-to-time.

+
+ + + + op:subtract-dayTimeDuration-from-time( + xs:time("11:12:00"), + xs:dayTimeDuration("P3DT1H15M") +) + xs:time("09:57:00") + + + + + op:subtract-dayTimeDuration-from-time( + xs:time("08:20:00-05:00"), + xs:dayTimeDuration("P23DT10H10M") +) + xs:time("22:10:00-05:00") + + + +
+ + + + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns a string containing an xs:dateTime value formatted for display.

+
+ +

See .

+
+ + The 3rd, 4th, and 5th arguments are now optional; previously the function required either 2 or 5 arguments. + +
+ + + + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns a string containing an xs:date value formatted for display.

+
+ +

See .

+
+ + The 3rd, 4th, and 5th arguments are now optional; previously the function required either 2 or 5 arguments. + +
+ + + + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns a string containing an xs:time value formatted for display.

+
+ +

See .

+
+ + The 3rd, 4th, and 5th arguments are now optional; previously the function required either 2 or 5 arguments. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + + +

Parses a string containing the date and time in IETF format, returning the corresponding + xs:dateTime value.

+
+ +

The function accepts a string matching the production input in the + following grammar:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ input + + ::= + + S? (dayname ","? S)? ((datespec S time) | asctime) S? +
+ dayname + + ::= + + "Mon" | "Tue" | "Wed" | "Thu" | "Fri" | "Sat" | "Sun" | "Monday | "Tuesday" + | "Wednesday" | "Thursday" | "Friday" | "Saturday" | "Sunday" +
+ datespec + + ::= + + daynum dsep monthname dsep year +
+ asctime + + ::= + + monthname dsep daynum S time S year +
+ dsep + + ::= + + S | (S? "-" S?) +
+ daynum + + ::= + + digit digit? +
+ year + + ::= + + digit digit (digit digit)? +
+ digit + + ::= + + [0-9] +
+ monthname + + ::= + + "Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun" | "Jul" | "Aug" | "Sep" | + "Oct" | "Nov" | "Dec" +
+ time + + ::= + + hours ":" minutes (":" seconds)? (S? timezone)? +
+ hours + + ::= + + digit digit? +
+ minutes + + ::= + + digit digit +
+ seconds + + ::= + + digit digit ("." digit+)? +
+ timezone + + ::= + + tzname | tzoffset (S? "(" S? tzname S? ")")? +
+ tzname + + ::= + + "UT" | "UTC" | "GMT" | "EST" | "EDT" | "CST" | "CDT" | "MST" | "MDT" | "PST" + | "PDT" +
+ tzoffset + + ::= + + ("+"|"-") hours ":"? minutes? +
+ S + + ::= + + (x09 | x0A | x0D | x20)+ +
+ +

The input is case-insensitive: upper-case and lower-case distinctions in the above + grammar show the conventional usage, but otherwise have no significance.

+

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

+

The dayname, if present, is ignored.

+

The daynum, monthname, and year supply the day, + month, and year of the resulting xs:dateTime value. A two-digit year + must have 1900 added to it. A year such as 0070 is to be treated + as given; negative years are not permitted.

+

The hours, minutes, and seconds (including + fractional seconds) values supply the corresponding components of the resulting + xs:dateTime value; if the seconds value + or the fractional seconds value is absent then zero + is assumed.

+

If both a tzoffset and a tzname are supplied then the + tzname is ignored.

+

If a tzoffset is supplied then this defines the hours and minutes parts of the timezone offset:

+ + +

If it contains a colon, this separates the hours part from the minutes part.

+
+ +

Otherwise, the grammar allows a sequence of from one to four digits. These are interpreted + as H, HH, HMM, or HHMM respectively, where H + or HH is the hours part, and MM (if present) is the minutes part.

+
+

If the minutes part is absent it defaults to 00.

+
+ +

If a tzname is supplied with no tzoffset then it is translated + to a timezone offset as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
tznameOffset
UT, UTC, GMT00:00
EST-05:00
EDT-04:00
CST-06:00
CDT-05:00
MST-07:00
MDT-06:00
PST-08:00
PDT-07:00
+

If neither a tzoffset nor tzname is supplied, a timezone + offset of 00:00 is assumed.

+
+ +

A dynamic error is raised if the input does + not match the grammar, or if the resulting date/time value is invalid + (for example, "31 February").

+
+ +

The parse-ietf-date function attempts to interpret its input as a date + in any of the three formats specified by HTTP .

+ +

These formats are used widely on the Internet to represent timestamps, and were + specified in:

+ +

(electronic mail), extended in to allow four-digit years;

+

(Usenet Messages), obsoleted by ;

+

POSIX asctime() format

+
+

(HTTP) officially uses a subset of those three formats restricted to GMT.

+ +

The grammar for this function is slightly more liberal than the RFCs (reflecting the internet tradition of being liberal in what is accepted). + For example the function:

+ + + +

Accepts a single-digit value where appropriate in place of a two-digit value with a leading zero (so + "Wed 1 Jun" is acceptable in place of "Wed 01 Jun", + and the timezone offset "-5:00" is equivalent to "-05:00")

+
+ +

Accepts one or more whitespace characters (x20, x09, x0A, x0D) wherever a single + space is required, and allows whitespace to be omitted where it is not required + for parsing

+
+ +

Accepts and ignores whitespace characters (x20, x09, x0A, x0D) at the start or end + of the string.

+
+
+ +

In new protocols IETF recommends the format of which is based on a profile of + ISO 8601 similar to that already used in XPath and XSD, but the “approximate” + format described here is very widely used.

+ +

An date can be generated approximately using fn:format-dateTime with a picture + string of "[FNn3], [D01] [MNn3] [Y04] [H01]:[m01]:[s01] [Z0000]".

+
+ + + + parse-ietf-date("Wed, 06 Jun 1994 07:29:35 GMT") + xs:dateTime("1994-06-06T07:29:35Z") + + + parse-ietf-date("Wed, 6 Jun 94 07:29:35 GMT") + xs:dateTime("1994-06-06T07:29:35Z") + + + parse-ietf-date("Wed Jun 06 11:54:45 EST 2013") + xs:dateTime("2013-06-06T11:54:45-05:00") + + + parse-ietf-date("Sunday, 06-Nov-94 08:49:37 GMT") + xs:dateTime("1994-11-06T08:49:37Z") + + + parse-ietf-date("Wed, 6 Jun 94 07:29:35 +0500") + xs:dateTime("1994-06-06T07:29:35+05:00") + + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an xs:QName value (that is, an expanded-QName) by taking an + xs:string that has the lexical form of an xs:QName (a + string in the form "prefix:local-name" or "local-name") + and resolving it using the in-scope namespaces for a given element.

+
+ + +

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

+

More specifically, the function searches the namespace bindings of $element + for a binding whose name matches the prefix of $value, or the zero-length + string if it has no prefix, and returns an expanded-QName whose local name is taken + from the supplied $value, and whose namespace URI is taken from the string + value of the namespace binding.

+ +

If the $value has no prefix, and there is no namespace binding for + $element corresponding to the default (unnamed) namespace, then the + resulting expanded-QName has no namespace part.

+

The prefix (or absence of a prefix) in the supplied $value argument is + retained in the returned expanded-QName, as described in .

+ +
+ +

A dynamic error is raised if $value does + not have the correct lexical form for an instance of xs:QName.

+

A dynamic error is raised if $value has + a prefix and there is no namespace binding for $element that matches this + prefix.

+
+ +

Sometimes the requirement is to construct an xs:QName without using the + default namespace. This can be achieved by writing:

+ if (contains($value, ":")) then resolve-QName($value, $element) else + QName("", $value) +

If the requirement is to construct an xs:QName using the namespaces in the + static context, then the xs:QName constructor should be used.

+
+ + +

Assume that the element bound to $element has a single namespace binding + bound to the prefix eg.

+
+ + +

+ fn:resolve-QName("hello", $element) returns a QName with local name + "hello" that is in no namespace.

+
+ +

+ fn:resolve-QName("eg:myFunc", $element) returns an xs:QName + whose namespace URI is specified by the namespace binding corresponding to the prefix + "eg" and whose local name is "myFunc".

+
+
+
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an xs:QName value formed using a supplied namespace URI and lexical QName.

+
+ + +

The namespace URI in the returned QName is taken from $uri. If + $uri is the zero-length string or the empty sequence, it represents + “no namespace”.

+

The prefix (or absence of a prefix) in $qname is retained in the + returned xs:QName value.

+

The local name in the result is taken from the local part of + $qname.

+ +
+ + +

A dynamic error is raised if $qname + does not have the correct lexical form for an instance of xs:QName.

+

A dynamic error is raised if $uri + is the zero-length string or the empty sequence, and the value of + $qname contains a colon (:).

+

A dynamic error may be raised if + $uri is not a valid URI (XML Namespaces 1.0) or IRI (XML Namespaces + 1.1).

+ +
+ + + + +

+ fn:QName("http://www.example.com/example", "person") returns an + xs:QName with namespace URI "http://www.example.com/example", + local name "person" and prefix "".

+

+ fn:QName("http://www.example.com/example", "ht:person") returns an + xs:QName with namespace URI "http://www.example.com/example", + local name "person" and prefix "ht".

+ +
+ +
+ +
+ + + + + + + + deterministic + context-dependent + focus-independent + + +

Returns an xs:QName value formed by parsing an EQName.

+
+ + +

Leading and trailing whitespace in $value is stripped.

+

If the resulting $value is castable to xs:NCName, + the result is fn:QName("", $value): that is, a QName in no namespace.

+

Otherwise, if the resulting $value is in the lexical space of xs:QName + (that is, if it is in the form prefix:local), the result is xs:QName($value). + Note that this result depends on the in-scope prefixes in the static context, and may result in + various error conditions.

+

Otherwise, if the resulting $value takes the form of an + XPath BracedURILiteral + (that is, Q{uri}local, where the uri part may be zero-length), + then the result is fn:QName(uri, local).

+

The rules used for parsing a within a + URIQualifiedName are the XPath rules, + not the XQuery rules (the XQuery rules require special characters such as < + and & to be escaped).

+ +
+ + +

A dynamic error is raised + if the supplied value of $value, after whitespace normalization, + does not match the XPath production EQName

+

A dynamic error is raised if + the supplied value of $value, after whitespace normalization, + is in the form prefix:local (with a non-absent prefix), and + the prefix cannot be resolved to a namespace URI using the in-scope namespace + bindings from the static context.

+
+ + + +

+ fn:parse-QName("Q{http://www.example.com/example}person") returns an + xs:QName with namespace URI "http://www.example.com/example", + local name "person" and prefix "".

+

+ fn:parse-QName("person") returns an + xs:QName with absent namespace URI, local + name "person" and prefix "".

+

+ fn:parse-QName("Q{}person") returns an + xs:QName with absent namespace URI, local + name "person" and prefix "".

+

+ fn:parse-QName("p:person") returns an + xs:QName with namespace URI obtained from the static context, local + name "person" and prefix "p" + (The result is the same as xs:QName("p:person")).

+
+ +
+ + New function, accepted 2022-11-18 + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a string representation of an xs:QName in the format Q{uri}local.

+
+ +

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

+

The result is a string in the format Q{uri}local, where:

+ +

uri + is the result of fn:string(fn:namespace-uri-from-QName($value)) + (which will be a zero-length string if the QName is in no namespace), and

+

local is the result of + fn:local-name-from-QName($value).

+
+

There is no escaping of special characters in the namespace URI. If the namespace URI + contains curly braces, the resulting string will not be a valid + BracedURILiteral.

+
+ + + + + + QName("http:/example.com", "person") +=> expanded-QName() + "Q{http://example.com}person" + + + QName("", "person") +=> expanded-QName() + "Q{}person" + + + + + New function, accepted 2022-11-15. + +
+ + + + + + + + Defines the semantics + of the eq and ne operators when applied to two values of type xs:QName. + + deterministic + context-independent + focus-independent + + +

Returns true if two supplied QNames have the same namespace URI and the + same local part.

+
+ +

The function returns true if the namespace URIs of $arg1 and + $arg2 are equal and the local names of $arg1 and + $arg2 are equal.

+

Otherwise, the function returns false.

+

The namespace URI parts are considered equal if they are both absent, or if they are both present and equal under the rules + of the fn:codepoint-equal function.

+

The local parts are also compared under the rules of the fn:codepoint-equal + function.

+
+ +

The prefix parts of $arg1 and $arg2, if any, are ignored.

+
+
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the prefix component of the supplied QName.

+
+ +

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

+

If $value has no prefix component the function returns the empty + sequence.

+

Otherwise, the function returns an xs:NCName representing the prefix + component of $value.

+
+
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the local part of the supplied QName.

+
+ +

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

+

Otherwise, the function returns an xs:NCName representing the local part of + $value.

+
+ + + + local-name-from-QName( + QName("http://www.example.com/example", "person") +) + "person" + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the namespace URI part of the supplied QName.

+
+ +

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

+

Otherwise, the function returns an xs:anyURI representing the namespace URI + part of $value.

+

If $value is in no namespace, the function returns the zero-length + xs:anyURI.

+
+ + + + namespace-uri-from-QName( + QName("http://www.example.com/example", "person") +) + xs:anyURI("http://www.example.com/example") + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the namespace URI of one of the in-scope namespaces for $element, + identified by its namespace prefix.

+
+ +

The function returns the result of the expression map:get(fn:in-scope-namespaces($element), string($value)).

+
+ + + +]]> + + + namespace-uri-for-prefix("z", $e) + "http://example.org/two" + + + namespace-uri-for-prefix("", $e) + "http://example.org/one" + + + namespace-uri-for-prefix((), $e) + "http://example.org/one" + + + namespace-uri-for-prefix("xml", $e) + "http://www.w3.org/XML/1998/namespace" + + + + + + Reformulated in 4.0, so it is now defined in terms of the new + fn:in-scope-namespaces function; the semantics are unchanged. + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the in-scope namespaces of an element node, as a map.

+
+ +

The function returns a map representing the prefixes of the in-scope + namespaces for $element. The map contains one entry + for each in-scope namespace: the key of the entry is the namespace + prefix or a zero-length string, and the corresponding value is the namespace URI.

+ +

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

+ + + +
+ +

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

+
+ + + +]]> + + + in-scope-namespaces($e) + map{"": "http://example.org/one", "z": "http://example.org/two", + "xml": "http://www.w3.org/XML/1998/namespace"} + + + + + New in 4.0. Accepted 2022-09-20. Note that the function signature uses notation + that is not yet accepted. + +
+ + + + + + + + nondeterministic-wrt-ordering + context-independent + focus-independent + + +

Returns the prefixes of the in-scope namespaces for an element node.

+
+ +

The function returns the result of the expression + map:keys(fn:in-scope-namespaces($element)) (but in no defined order).

+ +
+ +

The XML namespace is in scope for every element, so the result will always include the string "xml".

+
+ + Reformulated in 4.0, so it is now defined in terms of the new + fn:in-scope-namespaces function; the semantics are unchanged. + +
+ + + + + + + + Defines the semantics of + the eq and ne operators when applied to two xs:hexBinary + values. + +

Returns true if two xs:hexBinary values contain the same octet + sequence.

+
+ +

The function returns true if $value1 and $value2 + are of the same length, measured in binary octets, and contain the same octets in the + same order. Otherwise, it returns false.

+
+
+ + + + + + + + Defines the semantics of + the lt operator when applied to two xs:hexBinary values. Also used in the + definition of the ge operator. + +

Returns true if the first argument is less than the second.

+
+ +

The function returns true if any of the following conditions is true:

+ + +

$arg1 is zero-length (contains no octets) and $arg2 is + not zero-length.

+
+ +

Neither argument is zero-length, and the first octet of $arg1 is less + than the first octet of $arg2, treating the value of the octet as an + unsigned integer in the range 0 to 255.

+
+ +

Neither argument is zero-length, the first octet of $arg1 is equal to + the first octet of $arg2, and the xs:hexBinary value + formed by taking all octets of arg1 after the first is less than the + xs:hexBinary value formed by taking all octets of + arg2 after the first.

+
+
+ +

Otherwise, the function returns false.

+
+
+ + + + + + + + + Defines the semantics + of the eq and ne operators when applied to two xs:base64Binary + values. + +

Returns true if two xs:base64Binary values contain the same octet + sequence.

+
+ +

The function returns true if $value1 and $value2 + are of the same length, measured in binary octets, and contain the same octets in the + same order. Otherwise, it returns false.

+
+
+ + + + + + + + Defines the semantics + of the lt operator when applied to two xs:base64Binary values. Also used in + the definition of the ge operator. + +

Returns true if the first argument is less than the second.

+
+ +

The function returns true if any of the following conditions is true:

+ + +

$arg1 is zero-length (contains no octets) and $arg2 is + not zero-length.

+
+ +

Neither argument is zero-length, and the first octet of $arg1 is less + than the first octet of $arg2, treating the value of the octet as an + unsigned integer in the range 0 to 255.

+
+ +

Neither argument is zero-length, the first octet of $arg1 is equal to + the first octet of $arg2, and the xs:base64Binary value + formed by taking all octets of arg1 after the first is less than the + xs:base64Binary value formed by taking all octets of + arg2 after the first.

+
+
+ +

Otherwise, the function returns false.

+
+
+ + + + + + + + + Defines the + semantics of the eq and ne operators when applied to two values of type + xs:NOTATION. + +

Returns true if the two xs:NOTATION values have the same + namespace URI and the same local part.

+
+ +

The function returns true if the namespace URIs of $arg1 and + $arg2 are equal and the local names of $arg1 and + $arg2 are equal.

+

Otherwise, the function returns false.

+

The namespace URI parts are considered equal if they are both absent, or if they are both present and equal under the rules + of the fn:codepoint-equal function.

+

The local parts are also compared under the rules of the fn:codepoint-equal + function.

+
+ +

The prefix parts of $arg1 and $arg2, if any, are ignored.

+
+
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the name of a node, as an xs:string that is either the zero-length + string, or has the lexical form of an xs:QName.

+
+ +

If the argument is omitted, it defaults to the context item (.). The + behavior of the function if the argument is omitted is exactly the same as if the + context item had been passed as the argument.

+

If the argument is supplied and is the empty sequence, the function returns the + zero-length string.

+

If the node identified by $node has no name (that is, if it is a document + node, a comment, a text node, or a namespace node having no name), the function returns + the zero-length string.

+

Otherwise, the function returns the value of the expression + fn:string(fn:node-name($node)).

+
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+ +
+ +

Because the result depends on the choice of namespace prefixes in the source document, + it is not good practice to use the result of this function for anything other than display + purposes. For example, the test name(.) = 'my:profile' will fail if the source + document uses an unexpected namespace prefix. Such a test (assuming it relates to an element node) + is better written as boolean(self::my:profile).

+
+
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the local part of the name of $node as an xs:string + that is either the zero-length string, or has the lexical form of an + xs:NCName.

+
+ +

If the argument is omitted, it defaults to the context item (.). The + behavior of the function if the argument is omitted is exactly the same as if the + context item had been passed as the argument.

+

If the argument is supplied and is the empty sequence, the function returns the + zero-length string.

+

If the node identified by $node has no name (that is, if it is a document + node, a comment, a text node, or a namespace node having no name), the function returns + the zero-length string.

+

Otherwise, the function returns the local part of the expanded-QName of the node + identified by $node, as determined by the dm:node-name accessor + defined in ). This will be an + xs:string whose lexical form is an xs:NCName.

+
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+ +
+
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the namespace URI part of the name of $node, as an + xs:anyURI value.

+
+ +

If the argument is omitted, it defaults to the context node (.). The + behavior of the function if the argument is omitted is exactly the same as if the + context item had been passed as the argument.

+

If the node identified by $node is neither an element nor an attribute node, + or if it is an element or attribute node whose expanded-QName (as determined by the + dm:node-name accessor in the ) + is in no namespace, then the function returns the zero-length xs:anyURI + value.

+

Otherwise, the result will be the namespace URI part of the expanded-QName of the node + identified by $node, as determined by the dm:node-name accessor + defined in ), returned as an + xs:anyURI value.

+
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+
+
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the value indicated by $value or, if $value is not + specified, the context item after atomization, converted to an xs:double. +

+
+ +

Calling the zero-argument version of the function is defined to give the same result as + calling the single-argument version with the context item (.). That is, + fn:number() is equivalent to fn:number(.), as defined by + the rules that follow.

+

If $value is the empty sequence or if $value cannot be converted + to an xs:double, the xs:double value NaN is + returned.

+

Otherwise, $value is converted to an xs:double following the + rules of . If the conversion to xs:double + fails, the xs:double value NaN is returned.

+
+ +

A dynamic error is raised + if $value is omitted and the context item is absent.

+

As a consequence of the rules given above, a type error occurs if the context item + cannot be atomized, or if the result of atomizing the context item is a sequence + containing more than one atomic value.

+ +
+ +

XSD 1.1 allows the string +INF as a representation of positive infinity; + XSD 1.0 does not. It is implementation-defined whether XSD 1.1 is + supported.

+

Generally fn:number returns NaN rather than raising a dynamic + error if the argument cannot be converted to xs:double. However, a type + error is raised in the usual way if the supplied argument cannot be atomized or if the + result of atomization does not match the required argument type.

+
+ + + + number($item1/quantity) + 5.0e0 + + + + + number($item2/description) + xs:double('NaN') + + + +

Assume that the context item is the xs:string value "15". + Then fn:number() returns 1.5e1.

+
+
+ +
+ + + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

This function tests whether the language of $node, or the context item if + the second argument is omitted, as specified by xml:lang attributes is the + same as, or is a sublanguage of, the language specified by $language.

+
+ +

The behavior of the function if the second argument is omitted is exactly the same as if + the context item (.) had been passed as the second argument.

+

The language of the argument $node, or the context item if the second + argument is omitted, is determined by the value of the xml:lang attribute + on the node, or, if the node has no such attribute, by the value of the + xml:lang attribute on the nearest ancestor of the node that has an + xml:lang attribute. If there is no such ancestor, then the function + returns false.

+ +

If $language is the empty sequence it is interpreted as the zero-length + string.

+

The relevant xml:lang attribute is determined by the value of the XPath + expression:

+ (ancestor-or-self::*/@xml:lang)[last()] +

If this expression returns an empty sequence, the function returns false.

+

Otherwise, the function returns true if and only if, based on a caseless + default match as specified in section 3.13 of , either:

+ + +

+ $language is equal to the string-value of the relevant + xml:lang attribute, or

+
+ +

+ $language is equal to some substring of the string-value of the + relevant xml:lang attribute that starts at the start of the + string-value and ends immediately before a hyphen, - + (HYPHEN-MINUS, #x002D).

+
+
+
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+
+ + +

The expression fn:lang("en") would return true if the + context node were any of the following four elements:

+ + +

+ <para xml:lang="en"/> +

+
+ +

+ <div xml:lang="en"><para>And now, and + forever!</para></div> +

+
+ +

+ <para xml:lang="EN"/> +

+
+ +

+ <para xml:lang="en-us"/> +

+
+
+
+ +

The expression fn:lang("fr") would return false if the + context node were <para xml:lang="EN"/> +

+
+
+
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns a path expression that can be used to select the supplied node relative to the + root of its containing document.

+
+ +

The behavior of the function if the argument is omitted is exactly the same as if the + context item (.) had been passed as the argument.

+

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

+

If $node is a document node, the function returns the string + "/".

+

Otherwise, the function returns a string that consists of a sequence of steps, one + for each ancestor-or-self of $node other than the root node. This string is + prefixed by "Q{http://www.w3.org/2005/xpath-functions}root()" if the root + node is not a document node. Each step consists of the character "/" + followed by a string whose form depends on the kind of node selected by that step, as + follows:

+ + + +

For an element node, + Q{uri}local[position], + where uri is the namespace URI of the node name or the + empty string if the node is in no namespace, local is + the local part of the node name, and position is an + integer representing the position of the selected node among its like-named + siblings.

+
+ +

For an attribute node:

+ + +

if the node is in no namespace, @local, where + local is the local part of the node name

+
+ +

otherwise, @Q{uri}local, where + uri is the namespace URI of the node name, + and local is the local part of the node name

+
+
+
+ +

For a text node: text()[position] where + position is an integer representing the position + of the selected node among its text node siblings

+
+ +

For a comment node: comment()[position] where + position is an integer representing the position + of the selected node among its comment node siblings

+
+ +

For a processing-instruction node: + processing-instruction(local)[position] + where local is the name of the processing instruction + node and position is an integer representing the + position of the selected node among its like-named processing-instruction node + siblings

+
+ +

For a namespace node:

+ + +

If the namespace node has a name: + namespace::prefix, where + prefix is the local part of the name of the + namespace node (which represents the namespace prefix).

+
+ +

If the namespace node has no name (that is, it represents the default + namespace): + namespace::*[Q{http://www.w3.org/2005/xpath-functions}local-name()=""]

+
+
+
+
+ +
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+
+ + +Freude, schöner Götterfunken,
+Tochter aus Elysium,
+Wir betreten feuertrunken,
+Himmlische, dein Heiligtum.

}]]> +
+ + + path($e) + '/' + + + path($e/*:p) + '/Q{http://example.com/one}p[1]' + + + path($e/*:p/@xml:lang) + '/Q{http://example.com/one}p[1]/@Q{http://www.w3.org/XML/1998/namespace}lang' + + + path($e/*:p/@author) + '/Q{http://example.com/one}p[1]/@author' + + + path($e/*:p/*:br[2]) + '/Q{http://example.com/one}p[1]/Q{http://example.com/one}br[2]' + + + path( + $e//text()[ + starts-with(normalize-space(), 'Tochter') + ] +) + '/Q{http://example.com/one}p[1]/text()[2]' + + + + E21256 + John + Brown + ]]> + + + + path($emp) + 'Q{http://www.w3.org/2005/xpath-functions}root()' + + + path($emp/@xml:id) + 'Q{http://www.w3.org/2005/xpath-functions}root()/@Q{http://www.w3.org/XML/1998/namespace}id' + + + path($emp/empnr) + 'Q{http://www.w3.org/2005/xpath-functions}root()/Q{}empnr[1]' + + +
+
+ + + + + + + + deterministic + context-dependent + focus-dependent + special-streaming-rules + + + deterministic + context-independent + focus-independent + special-streaming-rules + + +

Returns the root of the tree to which $node belongs. This will usually, but + not necessarily, be a document node.

+
+ +

If the function is called without an argument, the context item (.) is used + as the default argument. The behavior of the function if the argument is omitted is + exactly the same as if the context item had been passed as the argument.

+ +

The function returns the value of the expression + ($arg/ancestor-or-self::node())[1].

+
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+
+ + +

These examples use some variables which could be defined in + as:

+
+ + let $i := <tool>wrench</tool> +let $o := <order> {$i} <quantity>5</quantity> </order> +let $odoc := document {$o} +let $newi := $o/tool + + +

Or they could be defined in as:

+
+ + <xsl:variable name="i" as="element()"> + <tool>wrench</tool> +</xsl:variable> + +<xsl:variable name="o" as="element()"> + <order> + <xsl:copy-of select="$i"/> + <quantity>5</quantity> + </order> +</xsl:variable> + +<xsl:variable name="odoc"> + <xsl:copy-of select="$o"/> +</xsl:variable> + +<xsl:variable name="newi" select="$o/tool"/> + + +

fn:root($i) returns the element node $i +

+
+ +

fn:root($o/quantity) returns the element node $o +

+
+ +

fn:root($odoc//quantity) returns the document node $odoc +

+
+ +

fn:root($newi) returns the element node $o +

+
+ +

The final three examples could be made type-safe by wrapping their operands with + fn:exactly-one().

+
+
+
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns true if the supplied node has one or more child nodes (of any kind).

+
+ +

If the argument is omitted, it defaults to the context item (.). The + behavior of the function if the argument is omitted is exactly the same as if the + context item had been passed as the argument.

+

Provided that the supplied argument $node matches the expected type + node()?, the result of the function call + fn:has-children($node) is defined to be the same as the result of the + expression fn:exists($node/child::node()).

+
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+ +
+ +

If $node is an empty sequence the result is false.

+

The motivation for this function is to support streamed evaluation. According to the + streaming rules in , the following construct is not + streamable:

+ + + + + + + +]]> +

This is because it makes two downward selections to read the child row + elements. The use of fn:has-children in the xsl:if conditional + is intended to circumvent this restriction.

+

Although the function was introduced to support streaming use cases, it has general + utility as a convenience function.

+
+ +
+ + + + + + + + deterministic + context-independent + focus-independent + special-streaming-rules + + +

Returns every node within the input sequence that is not an ancestor of another member + of the input sequence; the nodes are returned in document order with duplicates + eliminated.

+
+ +

The effect of the function call fn:innermost($nodes) is defined to be + equivalent to the result of the expression:

+ $nodes except $nodes/ancestor::node() +

That is, the function takes as input a sequence of nodes, and returns every node within + the sequence that is not an ancestor of another node within the sequence; the nodes are + returned in document order with duplicates eliminated.

+
+ + +

If the source document contains nested sections represented by div + elements, the expression innermost(//div) returns those div + elements that do not contain further div elements.

+
+
+
+ + + + + + + + deterministic + context-independent + focus-independent + special-streaming-rules + + +

Returns every node within the input sequence that has no ancestor that is itself a + member of the input sequence; the nodes are returned in document order with duplicates + eliminated.

+
+ +

The effect of the function call fn:outermost($nodes) is defined to be + equivalent to the result of the expression:

+ $nodes[not(ancestor::node() intersect $nodes)]/. + +

That is, the function takes as input a sequence of nodes, and returns every node within + the sequence that does not have another node within the sequence as an ancestor; the + nodes are returned in document order with duplicates eliminated.

+
+ +

The formulation $nodes except $nodes/descendant::node() might appear to be + simpler, but does not correctly account for attribute nodes, as these are not + descendants of their parent element.

+

The motivation for the function was based on XSLT streaming use cases. There are cases + where the streaming rules allow the construct + outermost(//section) but do not allow //section; the + function can therefore be useful in cases where it is known that sections will not be + nested, as well as cases where the application actually wishes to process all sections + except those that are nested within another.

+
+ + +

If the source document contains nested sections represented by div + elements, the expression outermost(//div) returns those div + elements that are not contained within further div elements.

+
+
+
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns a sequence of positive integers giving the positions within the sequence + $input of items that are equal to $search.

+
+ +

The function returns a sequence of positive integers giving the positions within the + sequence $input of items that are equal to $search.

+

The collation used by this function is determined according to the rules in . This collation is used when string comparison is + required.

+

The items in the sequence $input are compared with $search under + the rules for the eq operator. Values of type xs:untypedAtomic + are compared as if they were of type xs:string. Values that cannot be + compared, because the eq operator is not defined for their types, are + considered to be distinct. If an item compares equal, then the position of that item in + the sequence $input is included in the result.

+

The first item in a sequence is at position 1, not position 0.

+

The result sequence is in ascending numeric order.

+
+ +

If $input is the empty sequence, or if no item in + $input matches $search, then the function returns the empty + sequence.

+

No error occurs if non-comparable values are encountered. So when comparing two atomic + values, the effective boolean value of fn:index-of($a, $b) is true if + $a and $b are equal, false if they are not equal or not + comparable.

+
+ + + + index-of((10, 20, 30, 40), 35) + () + + + + + index-of((10, 20, 30, 30, 20, 10), 20) + (2, 5) + + + + + index-of( + ("a", "sport", "and", "a", "pastime"), + "a" +) + (1, 4) + + + + + index-of(current-date(), 23) + () + + + + + index-of([1, [5, 6], [6, 7]], 6) + (3, 4) + The array is atomized to a sequence of five integers + + + +

If @a is an attribute of type xs:NMTOKENS whose string + value is "red green blue", and whose typed value is therefore + ("red", "green", "blue"), then fn:index-of(@a, "blue") + returns 3. This is because the function calling mechanism atomizes the + attribute node to produce a sequence of three xs:NMTOKEN values.

+
+
+
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns true if the argument is the empty sequence.

+
+ +

If $input is the empty sequence, the function returns + true; otherwise, the function returns false.

+
+ + + + empty((1,2,3)[10]) + true() + + + + + empty(remove(("hello", "world"), 1)) + false() + + + + + empty([]) + false() + + + + + empty(map{}) + false() + + + + + empty("") + false() + + + +

Assuming $in is an element with no children:

+ +let $break := <br/> +return empty($break) + +

The result is false().

+
+
+
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns true if the argument is a non-empty sequence.

+
+ +

If $input is a non-empty sequence, the function returns + true; otherwise, the function returns false.

+
+ + + + exists(remove(("hello"), 1)) + false() + + + + + exists(remove(("hello", "world"), 1)) + true() + + + + + exists([]) + true() + + + + + exists(map{}) + true() + + + + + exists("") + true() + + + +

Assuming $in is an element with no children:

+ +let $break := <br/> +return exists($break) + +

The result is true().

+
+
+
+ + + + + + + + + nondeterministic-wrt-ordering + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns the values that appear in a sequence, with duplicates eliminated.

+
+ +

The function returns the sequence that results from removing from $values all + but one of a set of values that are considered equal to one another. + Two items $J and $K in the input sequence + (after atomization, as required by the function signature) + are considered equal if fn:deep-equal($J, $K, $coll) is true, + where $coll is the collation selected according to the rules in . This collation is used when string comparison is + required.

+ + +

The order in which the sequence of values is returned is implementation-dependent.

+ +

Which value of a set of values that compare equal is returned is implementation-dependent.

+

If the input sequence contains values of different numeric types that differ from each + other by small amounts, then the eq operator is not transitive, because of rounding + effects occurring during type promotion. In the situation where the input contains three + values A, B, and C such that A eq B, + B eq C, but A ne C, then the number of items in the result + of the function (as well as the choice of which items are returned) is implementation-dependent, subject only to the constraints that (a) no two + items in the result sequence compare equal to each other, and (b) every input item that + does not appear in the result sequence compares equal to some item that does appear in + the result sequence.

+ +

For example, this arises when computing:

+ + + +

because the values of type xs:float and xs:double both compare + equal to the value of type xs:decimal but not equal to each other.

+
+ +

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

+ +

Values of type xs:untypedAtomic are compared as if they were of type + xs:string.

+

Values that cannot be compared, because the eq operator is not defined for + their types, are considered to be distinct.

+ +

For xs:float and xs:double values, positive zero is equal to + negative zero and, although NaN does not equal itself, if $values + contains multiple NaN values a single NaN is returned.

+

If xs:dateTime, xs:date or xs:time values do not + have a timezone, they are considered to have the implicit timezone provided by the + dynamic context for the purpose of comparison. Note that xs:dateTime, + xs:date or xs:time values can compare equal even if their + timezones are different.

+
+ + + + distinct-values((1, 2.0, 3, 2)) + (1, 3, 2.0) + The result may include either the xs:integer 2 or the xs:decimal 2.0 + + + + + distinct-values(( + xs:untypedAtomic("cherry"), + xs:untypedAtomic("plum"), + xs:untypedAtomic("plum") +)) + (xs:untypedAtomic("cherry"), + xs:untypedAtomic("plum")) + + + +
+ + + + + + + + + + nondeterministic-wrt-ordering + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns the values that appear in a sequence more than once.

+
+ +

The items of $values are compared against each other, according to the + rules of fn:distinct-values and with $coll as the collation + selected according to the rules in .

+

From each resulting set of values that are considered equal, one value will be + returned if the set contains more than one value.

+

The order in which the sequence of values is returned is implementation-dependent.

+

Which value of a set of values that compare equal is returned is implementation-dependent.

+
+ + +

The effect of the function is equivalent to the following XSLT expression:

+ + + +]]> +

The following XQuery expression is equivalent if no collation is specified +(group by requires collation URIs to be static):

+ +for $group in $values +group by $value := $group +where count($group) > 1 +return $value + +
+ + + + duplicate-values((1, 2, 3, 1.0, 1e0)) + 1 + The result may be the xs:integer, xs:decimal + or xs:decimal value of the input sequence. + + + + + duplicate-values(1 to 100) + () + + + + + 1, '2', 2))]]> + "1" + The string "1" and the untyped value of the + element node are considered equal, whereas the string "2" + and the integer are considered unequal. + + + +

Raise an error for duplicates in an ID sequence:

+ let $ids := duplicate-values(//@id) +where exists($ids) +return error((), 'Duplicate IDs found: ' || string-join($ids, ', ')) +
+
+
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns its argument value.

+
+ +

The function returns $input.

+
+ +

The function is useful in contexts where a function must be supplied, but no processing is required.

+
+ + + + identity(0) + (0) + + + + + identity(1 to 10) + (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + + + + + ') ! (identity(/) is /)]]> + true() + If the argument is a node, the function returns the identical node, not a copy + + + + + identity(()) + () + + + + + New in 4.0. Accepted 2022-09-20. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a sequence constructed by inserting an item or a sequence of items at a given + position within an existing sequence.

+
+ +

The value returned by the function consists of all items of $input whose + 1-based position is less than $position, followed by all items of + $insert, followed by the remaining elements of $input, in + that order.

+
+ +

If $input is the empty sequence, $insert is returned. If + $insert is the empty sequence, $input is returned.

+

If $position is less than one (1), the first position, the effective value + of $position is one (1). If $position is greater than the + number of items in $input, then the effective value of + $position is equal to the number of items in $input plus + 1.

+

The value of $input is not affected by the sequence construction.

+
+ + + + + insert-before($abc, 0, "z") + ("z", "a", "b", "c") + + + + + insert-before($abc, 1, "z") + ("z", "a", "b", "c") + + + + + insert-before($abc, 2, "z") + ("a", "z", "b", "c") + + + + + insert-before($abc, 3, "z") + ("a", "b", "z", "c") + + + + + insert-before($abc, 4, "z") + ("a", "b", "c", "z") + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a new sequence containing all the items of $input except those + at specified positions.

+
+ +

The function returns a sequence consisting of all items of $input whose + 1-based position is not equal to any of the integers in $positions.

+

More formally, the function returns the result of the expression $input[not(position() = $positions)].

+
+ +

Any integer in $positions that is less than 1 or greater than the number of items in + $input is effectively ignored.

+

If $input is the empty sequence, the empty sequence is returned.

+

If $positions is an empty sequence, the input sequence $input is returned unchanged.

+
+ + + + + remove($abc, 0) + ("a", "b", "c") + + + + + remove($abc, 1) + ("b", "c") + + + + + remove($abc, 6) + ("a", "b", "c") + + + + + remove((), 3) + () + + + + + remove($abc, 2 to 3) + "a" + + + + + remove($abc, ()) + ("a", "b", "c") + + + + + Changed in 4.0: the second argument can now be a sequence of integers. + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the first item in a sequence.

+
+ +

The function returns the value of the expression $input[1]

+
+ +

If $input is the empty sequence, the empty sequence is returned. Otherwise + the first item in the sequence is returned.

+
+ + + + head(1 to 5) + 1 + + + + + head(("a", "b", "c")) + "a" + + + + + head(()) + () + + + + + head([1,2,3]) + [1,2,3] + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns all but the first item in a sequence.

+
+ +

The function returns the value of the expression subsequence($input, 2)

+
+ +

If $input is the empty sequence, or a sequence containing a single item, then + the empty sequence is returned.

+
+ + + + tail(1 to 5) + (2, 3, 4, 5) + + + + + tail(("a", "b", "c")) + ("b", "c") + + + + + tail("a") + () + + + + + tail(()) + () + + + + + tail([1,2,3]) + () + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns all but the last item in a sequence.

+
+ +

The function returns the value of the expression fn:remove($input, count($input))

+
+ +

If $input is the empty sequence, or a sequence containing a single item, then + the empty sequence is returned.

+
+ + + + trunk(1 to 5) + (1, 2, 3, 4) + + + + + trunk(("a", "b", "c")) + ("a", "b") + + + + + trunk("a") + () + + + + + trunk(()) + () + + + + + trunk([1,2,3]) + () + + + + + New in 4.0. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Produces multiple copies of a sequence.

+
+ +

The function returns the value of (1 to $count) ! $input.

+
+ +

If $input is the empty sequence, the empty sequence is returned.

+

The $count argument is declared as xs:nonNegativeInteger, + which means that a type error occurs if it is called with a negative value.

+

If the input sequence contains nodes, these are not copied: instead, the result sequence contains + multiple references to the same node. So, for example, fn:count(fn:replicate(/, 6)|()) + returns 1, because the fn:replicate call creates duplicates, and the + union operation eliminates them.

+

[TODO: the use of type xs:nonNegativeInteger for the second argument + assumes we will accept the proposal to allow downcasting in the coercion rules for + function arguments. MHK 2022-10-04.]

+
+ + + + replicate(0, 6) + (0, 0, 0, 0, 0, 0) + + + + + replicate(("A", "B", "C"), 3) + ("A", "B", "C", "A", "B", "C", "A", "B", "C") + + + + + replicate((), 5) + () + + + + + replicate(("A", "B", "C"), 1) + ("A", "B", "C") + + + + + replicate(("A", "B", "C"), 0) + () + + + + + New in 4.0. Accepted 2022-10-04. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Inserts a separator between adjacent items in a sequence.

+
+ +

The function returns the value of head($input), tail($input) ! ($separator, .).

+
+ +

If $input contains less than two items then it is returned unchanged.

+

If $separator is the empty sequence then $input is returned unchanged.

+

For example, in XQuery, fn:intersperse(para, <hr/>) would insert + an empty hr element between adjacent paragraphs.

+
+ + + + intersperse(1 to 5, "|") + (1, "|", 2, "|" , 3, "|", 4, "|", 5) + + + intersperse((), "|") + () + + + intersperse("A", "|") + "A" + + + intersperse(1 to 5, ()) + (1, 2, 3, 4, 5) + + + intersperse(1 to 5, ("⅓", "⅔")) + (1, "⅓", "⅔", 2, "⅓", "⅔", 3, "⅓", "⅔", 4, "⅓", "⅔", 5) + + + + + New in 4.0. Accepted 2022-09-27. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the last item in a sequence.

+
+ +

The function returns the value of the expression $input[position() = last()]

+
+ +

If $input is the empty sequence the empty sequence is returned.

+
+ + + + foot(1 to 5) + (5) + + + foot(()) + () + + + + + New in 4.0. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + special-streaming-rules + + +

Reverses the order of items in a sequence.

+
+ +

The function returns a sequence containing the items in $input in reverse + order.

+
+ +

If $input is the empty sequence, the empty sequence is returned.

+
+ + + + + reverse($abc) + ("c", "b", "a") + + + + + reverse(("hello")) + ("hello") + + + + + reverse(()) + () + + + + + reverse([1,2,3]) + [1,2,3] + The input is a sequence containing a single item (the array) + + + + + reverse(([1,2,3],[4,5,6])) + ([4,5,6],[1,2,3]) + + + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the contiguous sequence of items in $input + beginning at the position indicated by $start and + continuing for the number of items indicated by $length.

+
+ +

In the two-argument case (or where the + third argument is an empty sequence), the function returns:

+ $input[round($start) le position()] +

In the three-argument case, the function returns:

+ $input[round($start) le position() + and position() lt round($start) + round($length)] + +
+ +

The first item of a sequence is located at position 1, not position 0.

+

If $input is the empty sequence, the empty sequence is returned.

+ +

In the two-argument case, the function returns a sequence comprising those items of + $input whose 1-based position + is greater than or equal to $start (rounded to an integer). + No error occurs if $start is zero or negative.

+ +

In the three-argument case, The function returns a sequence comprising those items of + $input whose 1-based position + is greater than or equal to $start (rounded to an integer), and + less than the sum of $start and $length (both rounded to integers). + No error occurs if $start is zero or negative, or if $start + plus $length exceeds the number of items in the sequence, or if + $length is negative.

+ + +

As a consequence of the general rules, if $start is + -INF and $length is +INF, then + fn:round($start) + fn:round($length) is NaN; since + position() lt NaN always returns false, the result is an empty sequence.

+ +

The reason the function accepts arguments of type xs:double is that many + computations on untyped data return an xs:double result; and the reason for + the rounding rules is to compensate for any imprecision in these floating-point + computations.

+
+ + + + + + subsequence($seq, 4) + ("item4", "item5") + + + + + subsequence($seq, 3, 2) + ("item3", "item4") + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a sequence containing the items from $input + at positions defined by $at, in the order specified.

+
+ +

Returns the value of $at ! fn:subsequence($input, ., 1)

+
+ +

The effect of the function is to return those items from $items + at the positions given by the integers in $at, in the order + represented by the integers in $at.

+

In the simplest case where $at is a single integer, + fn:items-at($input, 3) returns the same result as $input[3].

+

Compared with a simple positional filter expression, the function is useful because:

+ +

It can select items at multiple positions, and unlike fn:subsequence, + these do not need to be contiguous.

+

The $at expression can depend on the focus.

+

The order of the returned items can differ from their order in the $input sequence.

+
+

If any integer in $at is outside the range 1 to count($input), that integer + is effectively ignored: no error occurs.

+

If either of the arguments is an empty sequence, the result is an empty sequence.

+
+ + + + + items-at(11 to 20, 4) + 14 + + + items-at(11 to 20, 4 to 6) + 14, 15, 16 + + + items-at(11 to 20, (7, 3)) + 17, 13 + + + items-at(11 to 20, index-of(("a", "b", "c"), "b")) + 12 + + + items-at(characters("quintessential"), (4, 8, 3)) + ("n", "s", "i") + + + items-at((), 832) + () + + + items-at((), ()) + () + + + + + New in 4.0 (see issue 213) + +
+ + + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a sequence containing selected items from a supplied input sequence based on their position.

+
+ +

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

+

Let $S be the first of the following that applies:

+ +

If $start is absent, empty, or zero, then 1.

+

If $start is negative, then fn:count($input) + $start + 1.

+

Otherwise, $start.

+
+

Let $E be the first of the following that applies:

+ +

If $end is absent, empty, or zero, then fn:count($input).

+

If $end is negative, then fn:count($input) + $end + 1.

+

Otherwise, $end.

+
+

Let $STEP be the first of the following that applies:

+ +

If $step is absent, empty, or zero, then:

+ +

If $E ge $S, then +1

+

Otherwise -1

+
+
+

Otherwise, $step.

+
+

If $STEP is negative, the function returns + $input => fn:reverse() => fn:slice(-$S, -$E, -$STEP).

+ +

Otherwise the function returns the result of the expression:

+ $input[position() ge $S and position() le $E and (position() - $S) mod $STEP eq 0] + +
+ +

The function is inspired by the slice operators in Javascript and Python, but it differs + in detail to accommodate the tradition of 1-based addressing in XPath. The end position is + inclusive rather than exclusive, so that in the simple case where $start and + $end are positive and $end > $start, + fn:slice($in, $start, $end) + returns the same result as $in[position() = $start to $end].

+
+ + + + + + slice($in, start := 2, end := 4) + ("b", "c", "d") + + + slice($in, start := 2) + ("b", "c", "d", "e") + + + slice($in, end := 2) + ("a", "b") + + + slice($in, start := 3, end := 3) + ("c") + + + slice($in, start := 4, end := 3) + ("d", "c") + + + slice($in, start := 2, end := 5, step := 2) + ("b", "d") + + + slice($in, start := 5, end := 2, step := -2) + ("e", "c") + + + slice($in, start := 2, end := 5, step := -2) + () + + + slice($in, start := 5, end := 2, step := 2) + () + + + slice($in) + ("a", "b", "c", "d", "e") + + + slice($in, start := -1) + ("e") + + + slice($in, start := -3) + ("c", "d", "e") + + + slice($in, end := -2) + ("a", "b", "c", "d") + + + slice($in, start := 2, end := -2) + ("b", "c", "d") + + + slice($in, start := -2, end := 2) + ("d", "c", "b") + + + slice($in, start := -4, end := -2) + ("b", "c", "d") + + + slice($in, start := -2, end := -4) + ("d", "c", "b") + + + slice($in, start := -4, end := -2, step := 2) + ("b", "d") + + + slice($in, start := -2, end := -4, step := -2) + ("d", "b") + + + slice(("a", "b", "c", "d"), 0) + ("a", "b", "c", "d") + + + + + Proposed for 4.0; not yet reviewed. + +
+ + + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-independent + focus-independent + + +

Determines whether one sequence starts with another, using a supplied callback function to compare items.

+
+ +

Informally, the function returns true if $input starts with $subsequence, + when items are compared using the supplied (or default) $compare function.

+

More formally, the function returns the value of the expression:

+ +
+ +

There is no requirement that the $compare function should have the traditional qualities + of equality comparison. The result is well-defined, for example, even if $compare is not transitive + or not symmetric.

+
+ + + + + starts-with-sequence((), ()) + true() + + + starts-with-sequence(1 to 10, 1 to 5) + true() + + + starts-with-sequence(1 to 10, ()) + true() + + + starts-with-sequence(1 to 10, 1 to 10) + true() + + + starts-with-sequence(1 to 10, 1) + true() + + + starts-with-sequence( + 1 to 10, + 101 to 105, + function($x, $y) { $x mod 100 = $y mod 100 } +) + true() + + + starts-with-sequence( + ("A", "B", "C"), + ("a", "b"), + function($x, $y) { + compare( + $x, + $y, + "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive" + ) eq 0 + } +) + true() + + +

")//p[2] +return starts-with-sequence( + $p/ancestor::*[1], + $p/parent::*, + op("is") +)]]> + true() + + + starts-with-sequence(10 to 20, 1 to 5, op("gt")) + true() + + + starts-with-sequence( + ("Alpha", "Beta", "Gamma"), + ("A", "B"), + starts-with#2 +) + true() + + + starts-with-sequence( + ("Alpha", "Beta", "Gamma", "Delta"), + 1 to 3, + function($x, $y) { ends-with($x, 'a' ) } +) + true() + True because the first three items in the input sequence end with "a". + + + + + New in 4.0. Accepted 2022-11-01 + + + + + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-independent + focus-independent + + +

Determines whether one sequence ends with another, using a supplied callback function to compare items.

+ + +

Informally, the function returns true if $input ends with $subsequence, + when items are compared using the supplied (or default) $compare function.

+

More formally, the function returns the value of the expression:

+ +
+ +

There is no requirement that the $compare function should have the traditional qualities + of equality comparison. The result is well-defined, for example, even if $compare is not transitive + or not symmetric.

+
+ + + + + ends-with-sequence((), ()) + true() + + + ends-with-sequence(1 to 10, 5 to 10) + true() + + + ends-with-sequence(1 to 10, ()) + true() + + + ends-with-sequence(1 to 10, 1 to 10) + true() + + + ends-with-sequence(1 to 10, 10) + true() + + + ends-with-sequence( + 1 to 10, + 108 to 110, + function($x, $y) { $x mod 100 = $y mod 100 } +) + true() + + + ends-with-sequence( + ("A", "B", "C"), + ("b", "c"), + function($x, $y) { + compare( + $x, + $y, + "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive" + ) eq 0 + } +) + true() + + +

")//p[2] +return ends-with-sequence( + $p/ancestor::node()[last()], + $p/root(), + op("is") +)]]> + true() + + + ends-with-sequence(10 to 20, 1 to 5, op("gt")) + true() + + + ends-with-sequence( + ("Alpha", "Beta", "Gamma"), + ("B", "G"), + starts-with#2 +) + true() + + + ends-with-sequence( + ("Alpha", "Beta", "Gamma", "Delta"), + 1 to 2, + function($x, $y) { string-length($x) eq 5 } +) + true() + True because the last two items in the input sequence have a string length of 5. + + + + + New in 4.0. Accepted 2022-11-01 + + + + + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-independent + focus-independent + + +

Determines whether one sequence contains another as a contiguous subsequence, using a supplied callback function to compare items.

+ + +

Informally, the function returns true if $input contains a consecutive subsequence matching $subsequence, + when items are compared using the supplied (or default) $compare function.

+

More formally, the function returns the value of the expression:

+ +
+ +

There is no requirement that the $compare function should have the traditional qualities + of equality comparison. The result is well-defined, for example, even if $compare is not transitive + or not symmetric.

+
+ + + + + contains-sequence((), ()) + true() + + + contains-sequence(1 to 10, 3 to 6) + true() + + + contains-sequence(1 to 10, (2, 4, 6)) + false() + + + contains-sequence(1 to 10, ()) + true() + + + contains-sequence(1 to 10, 1 to 10) + true() + + + contains-sequence(1 to 10, 5) + true() + + + contains-sequence( + 1 to 10, + 103 to 105, + function($x, $y) { $x mod 100 = $y mod 100 } +) + true() + + + contains-sequence( + ("A", "B", "C", "D"), + ("b", "c"), + function($x, $y) { + compare( + $x, + $y, + "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive" + ) eq 0 + } +) + true() + + +

")//chap +return contains-sequence( + $chap ! child::*, + $chap ! child::p, + op("is") +)]]> + true() + True because the p children of the chap element form a contiguous subsequence. + + + contains-sequence(10 to 20, (5, 3, 1), op("gt")) + true() + + + contains-sequence( + ("Alpha", "Beta", "Gamma", "Delta"), ("B", "G"), + starts-with#2 +) + true() + + + contains-sequence( + ("Zero", "Alpha", "Beta", "Gamma", "Delta", "Epsilon"), + 1 to 4, + function($x, $y) { ends-with($x, 'a') } +) + true() + True because there is a run of 4 consecutive items ending in "a". + + + + + New in 4.0. Accepted 2022-11-01 + + + + + + + + + + + nondeterministic-wrt-ordering + context-independent + focus-independent + + +

Returns the items of $input in an implementation-dependent order.

+ + +

The function returns the items of $input in an implementation-dependent order.

+
+ +

Query optimizers may be able to do a better job if the order of the output sequence is + not specified. For example, when retrieving prices from a purchase order, if an index + exists on prices, it may be more efficient to return the prices in index order rather + than in document order.

+
+ + + + unordered((1, 2, 3, 4, 5)) + (1, 2, 3, 4, 5) + + + + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Absorbs the argument.

+
+ +

The function absorbs the supplied $input argument and + returns an empty sequence.

+
+ +

The function can be used to discard unneeded output of expressions + (functions, third-party libraries, etc.).

+

It can also be used to discard results during development.

+

The function is utilized by built-in functions such as map:get + to return an empty sequence for arbitrary input.

+

It is implementation-dependent + whether the supplied argument is evaluated or ignored. An implementation may decide to + evaluate nondeterministic expressions and + ignore deterministic ones.

+
+ + + + void(1 to 1000000) + () + + + array:get(array { 1, 2, 3 }, 4, void#1) + () + Without the third argument, an error would be raised + + + for $f in (identity#1, void#1) return $f(123) + 123 + + + + + New in 4.0. Approved. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns input if it contains zero or one items. Otherwise, raises an + error.

+
+ +

Except in error cases, the function returns $input unchanged.

+
+ +

A dynamic error is raised if $input + contains more than one item.

+
+
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns $input if it contains one or more items. Otherwise, raises an error. +

+
+ +

Except in error cases, the function returns $input unchanged.

+ +
+ +

A dynamic error is raised if $input is an + empty sequence.

+
+
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns $input if it contains exactly one item. Otherwise, raises an error. +

+
+ +

Except in error cases, the function returns $input unchanged.

+
+ +

A dynamic error is raised if $input is an + empty sequence or a sequence containing more than one item.

+
+
+ + + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

This function assesses whether two sequences are deep-equal to each other. To be + deep-equal, they must contain items that are pairwise deep-equal; and for two items to + be deep-equal, they must either be atomic values that compare equal, or nodes of the + same kind, with the same name, whose children are deep-equal, + or maps with matching entries, or arrays with matching members.

+
+ +

The $collation argument identifies a collation which is used at all levels + of recursion when strings are compared (but not when names are compared), according to + the rules in . If the argument is not supplied, + or if it is empty, then the default collation from the + dynamic context of the caller is used.

+

The $options argument, if present, defines additional parameters controlling + how the comparison is done. The option parameter conventions apply.

+

If the two sequences are both empty, the function returns true.

+

If the two sequences are of different lengths, the function returns + false.

+

If the two sequences are of the same length, the function returns true if + and only if every item in the sequence $input1 is deep-equal to the + item at the same position in the sequence $input2. The rules for + deciding whether two items are deep-equal appear below.

+ + +

The entries that may appear in the $options map are as follows. The detailed rules + for the interpretation of each option appear later.

+ + + + Determines whether the base-uri of a node is significant. + + xs:boolean + false + + + Determines whether comments are significant. + + xs:boolean + false + + + Requests diagnostics in the case where the function returns false. + When this option is set and the two inputs are found to be not equal, the implementation + should output messages (in an implementation-dependent format and to + an implementation-dependent destination) indicating the nature of the differences that + were found. + + xs:boolean + false + + + If true, then in the event of a dynamic error occurring in the course of + the comparison, the function will return false rather than throwing the error. (This option does + not affect the handling of errors in the supplied values of the $collation + and $options arguments.) + + xs:boolean + false + + + Determines whether the id property of elements and attributes is significant. + + xs:boolean + false + + + Determines whether the idrefs property of elements and attributes is significant. + + xs:boolean + false + + + Determines whether the in-scope namespaces of elements are significant. + + xs:boolean + false + + + Determines whether namespace prefixes in xs:QName values (particularly + the names of elements and attributes) are significant. + + xs:boolean + false + + + Determines whether the nilled property of elements and attributes is significant. + + xs:boolean + false + + + If present, indicates that text and attributes are converted to the specified + Unicode normalization form prior to comparison. The value is as for the corresponding + argument of fn:normalize-unicode. + + xs:string? + () + + + Determines whether processing instructions are significant. + + xs:boolean + false + + + Determines whether timezones in date/time values are significant. + + xs:boolean + false + + + Determines whether type annotations are significant. + + xs:boolean + false + + + Determines whether the variety of the type annotation of an element + (whether it has complex content or simple content) is significant. + + xs:boolean + true + + + Determines whether nodes are compared using their typed values rather than + their string values. + + xs:boolean + true + + + A list of QNames of elements considered to be unordered: that is, their child + elements may appear in any order. + + xs:QName* + () + + + Determines the extent to which whitespace + is treated as significant. The value + preserve retains all whitespace. The value strip ignores text nodes + consisting entirely of whitespace. + The value normalize ignores whitespace text nodes in the same way as + the strip option, and additionally compares text and attribute nodes after + normalizing whitespace in accordance with the rules of the fn:normalize-space + function. The detailed rules, given below, also take into account type annotations and + xml:space attributes. + + + enum("preserve", "strip", "normalize") + preserve + + + +

As a general rule for boolean options (but not invariably), the value true indicates + that the comparison is more strict.

+ +

In the following rules, where a recursive call on fn:deep-equal is made, this is assumed + to use the same values of $collation and $options as the original call.

+ +

The rules reference a function equal-strings which compares two strings as follows:

+ + +

If the whitespace option is set to normalize, then each string is processed + by calling the fn:normalize-space function.

+

If the normalization-form option is present, each string is then normalized + by calling the fn:normalize-unicode function, supplying the specified normalization + form.

+

The two strings are then compared for equality under the requested $collation.

+
+ +

More formally, the equal-strings function can be expressed as follows:

+ + + +

The rules for deciding whether two items $i1 and $i2 are deep-equal + are as follows. The two items are deep-equal + if one or more of the following conditions are true:

+ + +

All of the following conditions are true:

+ + +

$i1 is an atomic value.

+ +

$i2 is an atomic value.

+ +

Either the type-annotations option is false, or both atomic values have + the same type annotation.

+
+ +

One of the following conditions is true:

+ +

If both $i1 and $i2 are instances of + xs:string or xs:untypedAtomic, + equal-strings($i1, $i2, $collation, $options) + returns true. +

+

If both $i1 and $i2 are instances of + xs:date, xs:time or xs:dateTime, + $i1 eq $i2 + returns true. +

+

Otherwise, fn:atomic-equal($i1, $i2) + returns true. +

+
+

If $i1 and $i2 are not comparable, that is, + if the expression ($i1 eq $i2) would raise an error, then the function + returns false; it does not report an error.

+
+ + +

One of the following conditions is true:

+ +

Option namespace-prefixes is false.

+

Neither $i1 nor $i2 is of type + xs:QName or xs:NOTATION.

+

$i1 and $i2 are qualified names with the same namespace prefix.

+
+
+ +

One of the following conditions is true:

+ +

Option timezones is false.

+

Neither $i1 nor $i2 is of type + xs:date, xs:time, xs:dateTime, + xs:gYear, xs:gYearMonth, xs:gMonth, + xs:gMonthDay, or xs:gDay.

+

Neither $i1 nor $i2 has a timezone component.

+

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

+
+
+
+
+ +

All of the following conditions are true:

+ + +

$i1 is a map.

+
+ +

$i2 is a map.

+
+ +

Both maps have the same number of entries.

+
+ +

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

+ + +

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

+
+ +

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

+
+
+
+
+
+ +

All the following conditions are true:

+ +

$i1 is an array.

+

$i2 is an array.

+ +

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

+
+ +

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

+
+
+
+ +

All the following conditions are true:

+ +

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

+

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

+

$i1 and $i2 have the same function identity. + The concept of function identity is explained in .

+
+
+ +

All the following conditions are true:

+ +

$i1 is a node.

+

$i2 is a node.

+

Both nodes have the same node kind.

+

Either the base-uri option is false, or both nodes have the same value + for their base URI property, or both nodes have an absent base URI.

+

Let significant-children($parent) be the sequence of nodes obtained by applying the following + steps to the children of $parent, in turn:

+ +

Comment nodes are discarded if the option comments is false.

+

Processing instruction nodes are discarded if the option processing-instructions is false.

+

Adjacent text nodes are merged.

+

Whitespace-only text nodes are discarded if both the following conditions are true:

+ + +

Either:

+ + +

The option whitespace is set to strip + or normalize; or

+
+ +

$parent is a schema-validated element node whose type annotation + is a complex type with an element-only or empty content model.

+
+
+
+

The text node is not within the scope + of an element that has the attribute xml:space="preserve".

+
+
+
+ +
+ +

One of the following conditions is true.

+ + +

Both nodes are document nodes, and the sequence significant-children($i1) + is deep-equal to the sequence significant-children($i2).

+
+ +

Both nodes are element nodes, and all the following conditions are true:

+ + +

The two nodes have the same name, that is (node-name($i1) eq + node-name($i2)).

+
+ +

Either the option namespace-prefixes is false, or both element + names have the same prefix.

+
+ +

Either the option in-scope-namespaces is false, or both element + nodes have the same in-scope namespace bindings.

+
+ +

Either the option type-annotations is false, or both + element nodes have the same type annotation.

+
+ +

Either the option id-property is false, or both element + nodes have the same value for their is-id property.

+
+ +

Either the option idrefs-property is false, or both element + nodes have the same value for their is-idrefs property.

+
+ +

Either the option nilled-property is false, or both element + nodes have the same value for their nilled property.

+
+ +

One of the following conditions is true:

+ +

The option type-variety is false.

+

Both nodes are annotated as having simple content. + For this purpose simple content + means either a simple type or a complex type with simple content.

+

Both nodes are annotated as having complex content. For this purpose + complex content means a complex type whose variety is mixed, element-only, or + empty.

+
+ +

It is a consequence of this rule that, by default, validating a document D + against a schema will usually (but not necessarily) result in a document + that is not deep-equal to D. The exception is when the schema + allows all elements to have mixed content.

+
+ +
+ +

The two nodes have the same number of attributes, and for every attribute + $a1 in $i1/@* there exists an attribute + $a2 in $i2/@* such that $a1 and + $a2 are deep-equal.

+
+ +

One of the following conditions holds:

+ + +

Both element nodes are annotated as having simple content (as defined + above), the typed-values option is true, + and the typed value of $i1 is deep-equal + to the typed value of $i2.

+

The typed value of an element node is used only when the element + has simple content, which means that no error can occur as a result + of atomizing a node with no typed value.

+
+ +

Both element nodes are annotated as having simple content (as defined + above), the typed-values option is false, + and the equal-strings function returns true when + applied to the string value of $i1 + and the string value of $i2.

+
+ +

Both element nodes have a type annotation that is a complex type with + element-only, mixed, or empty content, + the (common) element name is not present in the unordered-elements option, + and the sequence significant-children($i1) is + deep-equal to the sequence significant-children($i2).

+
+ +

Both element nodes have a type annotation that is a complex type with + element-only, mixed, or empty content, + the (common) element name is present in the unordered-elements option, + and the sequence significant-children($i1) is + deep-equal to some permutation of the sequence significant-children($i2).

+ +

Elements annotated as xs:untyped fall into this category.

+

Including an element name in the unordered-elements list is unlikely + to be useful except when the relevant elements have element-only content, but + this is not a requirement: the rules apply equally to elements with mixed content, + or even (trivially) to elements with empty content.

+
+
+
+
+
+
+ + +

Both nodes are attribute nodes, and all the following conditions are true:

+ + + +

The two attribute nodes have the same name, that is (node-name($i1) eq + node-name($i2)).

+
+ +

Either the option namespace-prefixes is false, or both + attribute names have the same prefix.

+
+ +

Either the option type-annotations is false, or both + attribute nodes have the same type annotation.

+
+ +

Either the option id-property is false, or both attribute nodes + have the same value for their is-id property.

+
+ +

Either the option idrefs-property is false, or both attribute nodes + have the same value for their is-idrefs property.

+
+ +

Either the option typed-value is false, or + the typed value of $i1 is deep-equal to the typed value of + $i2.

+
+ +

Either the option typed-value is true, or + the equal-strings function returns true + when applied to the string value of $i1 + and the string value of $i2.

+
+ +
+
+ + +

Both nodes are processing instruction nodes, and all the following conditions are true:

+ + +

The two nodes have the same name, that is (node-name($i1) eq + node-name($i2)).

+
+ +

The equal-strings function returns true when applied to + the string value of $i1 + and the string value of $i2.

+
+
+
+ +

Both nodes are namespace nodes, and all the following conditions are true:

+ + +

The two nodes either have the same name or are both nameless, that is + fn:deep-equal(node-name($i1), node-name($i2)).

+
+ +

The string value of $i1 is equal to the string value of + $i2 when compared using the Unicode codepoint collation.

+
+
+

Namespace nodes are not considered directly unless they appear in the top-level sequences + passed explicitly to the fn:deep-equal function.

+
+ +

Both nodes are comment nodes, and the equal-strings function + returns true when applied to their string values.

+
+ +

Both nodes are text nodes, and the equal-strings function + returns true when applied to their string values.

+ +
+
+
+ +
+
+
+

In all other cases the result is false.

+
+ +

A type error is raised if either input + sequence contains a function item that is not a map or + array.

+

However, the above error is not raised if the false-on-error option is + true; in this case, the function returns false rather than raising an error.

+

A type error is raised if the value of + $options includes an entry whose key is defined + in this specification, and whose value is not of the permitted type for that key.

+

A dynamic error is raised if the value of + $options includes an entry whose key is defined + in this specification, and whose value is not a permitted value for that key.

+
+ +

By default, whitespace in text nodes and attribute is considered significant. There are various ways + whitespace differences can be ignored:

+ +

If nodes have been schema-validated, setting the typed-values + option to true causes the typed values rather + than the string values to be compared. This will typically cause whitespace to be ignored + except where the type of the value is xs:string.

+

Setting the whitespace option to normalize causes all + text and attribute nodes to have leading and trailing whitespace removed, and intermediate + whitespace reduced to a single character.

+
+

By default, two nodes are not required to have the same type annotation, and they are not + required to have the same in-scope namespaces. They may also differ in their parent, + their base URI, and the values returned by the is-id and + is-idrefs accessors (see and + ). The order of children is significant, + but the order of attributes is insignificant.

+

By default, the contents of comments and processing instructions are significant only if these nodes + appear directly as items in the two sequences being compared. The content of a comment + or processing instruction that appears as a descendant of an item in one of the + sequences being compared does not affect the result. However, the presence of a comment + or processing instruction, if it causes a text node to be split into two text nodes, may + affect the result.

+

Comparing items of different kind (for example, comparing an atomic + value to a node, or a map to an array, or an integer to an xs:date) returns false, + it does not return an error. So + the result of fn:deep-equal(1, current-dateTime()) is false.

+

Comparing a function (other than a map or array) to any other value raises a type error, + unless the error is suppressed using the false-on-error option.

+
+ + + + + +]]> + + + deep-equal($at, $at/*) + false() + + + + + deep-equal($at/name[1], $at/name[2]) + false() + + + + + deep-equal($at/name[1], $at/name[3]) + true() + + + + + deep-equal($at/name[1], 'Peter Parker') + false() + + + + + deep-equal(map{1:'a', 2:'b'}, map{2:'b', 1:'a'}) + true() + + + + + deep-equal([1, 2, 3], [1, 2, 3]) + true() + + + + + deep-equal((1, 2, 3), [1, 2, 3]) + false() + + + + + "), + parse-xml(""))]]> + true() + By default, namespace prefixes are ignored + + + + + "), + parse-xml(""), + options := map{'namespace-prefixes':true()})]]> + false() + False because the namespace prefixes differ + + + + + "), + parse-xml(""), + options := map{'in-scope-namespaces':true()})]]> + false() + False because the in-scope namespace bindings differ + + + + + "), + parse-xml(""))]]> + false() + By default, order of elements is significant + + + + + "), + parse-xml(""), + options := map{'unordered-elements': parse-QName('a')})]]> + true() + The unordered-elements option means that the ordering of the children + of a is ignored. + + + + + x"), + parse-xml( + " x"))]]> + false() + By default, both the leading whitespace in the style attribute + and the whitespace text node preceding the span element are significant. + + + + + x"), + parse-xml( + " x"), + options := map{'whitespace': 'normalize'})]]> + false() + The whitespace option causes both the leading space + in the attribute value and the whitespace preceding the + span element to be ignored. + + + + + + Options parameter added. Approved in principle on 2023-01-31, subject + to further review. + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the number of items in a sequence.

+
+ +

The function returns the number of items in $input.

+
+ +

returns 0.if $input is the empty sequence.

+
+ + + + + + + count($seq1) + 2 + + + + + count($seq3) + 0 + + + + + count($seq2) + 3 + + + + + count($seq2[. > 100]) + 0 + + + + + count([]) + 1 + + + + + count([1,2,3]) + 1 + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the average of the values in the input sequence $values, that is, the + sum of the values divided by the number of values.

+
+ +

If $values is the empty sequence, the empty sequence is returned.

+

If $values contains values of type xs:untypedAtomic they are cast + to xs:double.

+

Duration values must either all be xs:yearMonthDuration values or must all + be xs:dayTimeDuration values. For numeric values, the numeric promotion + rules defined in are used to promote all values to a single + common type. After these operations, $values must satisfy the following condition:

+

There must be a type T such that:

+ +

every item in $values is an instance of T.

+

T is one of xs:double, xs:float, + xs:decimal, xs:yearMonthDuration, or + xs:dayTimeDuration.

+
+ + +

The function returns the average of the values as sum($values) div + count($values); but the implementation may use an otherwise equivalent algorithm + that avoids arithmetic overflow.

+ +
+ +

A type error is raised if the input sequence contains + items of incompatible types, as described above.

+
+ + + + + + + avg($seq3) + 4.0 + The result is of type xs:decimal. + + + + + avg(($d1, $d2)) + xs:yearMonthDuration("P10Y5M") + + + + + avg(()) + () + + + + + avg((xs:float('INF'), xs:float('-INF'))) + xs:float('NaN') + + + + + avg(($seq3, xs:float('NaN'))) + xs:float('NaN') + + + +

fn:avg(($d1, $seq3)) raises a type error .

+
+
+
+ + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns a value that is equal to the highest value appearing in the input sequence.

+
+ +

The following conversions are applied to the input sequence $values, in order:

+ + +

Values of type xs:untypedAtomic in $values are cast to + xs:double.

+
+ +

If the resulting sequence contains values that are instances of more than one primitive type + (meaning the 19 primitive types defined in ), then: +

+ + +

If each value is an instance of one of the types xs:string or xs:anyURI, + then all the values are cast to type xs:string.

+
+ +

If each value is an instance of one of the types xs:decimal or xs:float, + then all the values are cast to type xs:float.

+
+ +

If each value is an instance of one of the types xs:decimal, xs:float, + or xs:double, then all the values are cast to type xs:double.

+
+ +

Otherwise, a type error is raised .

+
+
+ +

The primitive type of an xs:integer value for this purpose is xs:decimal.

+
+
+ +
+

The items in the resulting sequence may be reordered in an arbitrary order. The + resulting sequence is referred to below as the converted sequence. The function returns + an item from the converted sequence rather than the input sequence.

+

If the converted sequence is empty, the function returns the empty sequence.

+

All items in the converted sequence must be derived from a single base type for which + the le operator is defined. In addition, the values in the sequence must + have a total order. If date/time values do not have a timezone, they are considered to + have the implicit timezone provided by the dynamic context for the purpose of + comparison. Duration values must either all be xs:yearMonthDuration values + or must all be xs:dayTimeDuration values.

+

If the converted sequence contains the value NaN, the value + NaN is returned + (as an xs:float or xs:double as appropriate).

+

If the items in the converted sequence are of type xs:string or types + derived by restriction from xs:string, then the determination of the item + with the smallest value is made according to the collation that is used. If the type of + the items in the converted sequence is not xs:string and + $collation is specified, the collation is ignored.

+

The collation used by this function is determined according to the rules in .

+

The function returns the result of the expression:

+ + if (every $v in $c satisfies $c[1] ge $v) + then $c[1] + else max(tail($c)) +

evaluated with $collation as the default collation if specified, and with + $c as the converted sequence.

+ +
+ +

A type error is raised if the input sequence contains + items of incompatible types, as described above.

+
+ +

Because the rules allow the sequence to be reordered, if there are two or more items that are + “equal highest”, the specific item whose value is returned is implementation-dependent. This can arise for example if two different strings + compare equal under the selected collation, or if two different xs:dateTime + values compare equal despite being in different timezones.

+

If the converted sequence contains exactly one value then that value is returned.

+

The default type when the fn:max function is applied to + xs:untypedAtomic values is xs:double. This differs from the + default type for operators such as gt, and for sorting in XQuery and XSLT, + which is xs:string.

+

The rules for the dynamic type of the result are stricter in version 3.1 of the specification than + in earlier versions. For example, if all the values in the input sequence belong to types derived from + xs:integer, version 3.0 required only that the result be an instance + of the least common supertype of the types present in the input sequence; Version 3.1 + requires that the returned value retains its original type. This does not apply, however, where type promotion + is needed to convert all the values to a common primitive type.

+
+ + + + max((3,4,5)) + 5 + + + + + max([3,4,5]) + 5 + Arrays are atomized + + + + + max((xs:integer(5), xs:float(5.0), xs:double(0))) + xs:double(5.0e0) + + + + + max((current-date(), xs:date("2100-01-01"))) + xs:date("2100-01-01") + Assuming that the current date is during the 21st + century. + + + + + max(("a", "b", "c")) + "c" + Assuming a typical default collation. + + + +

fn:max((3,4,"Zero")) raises a type error .

+
+
+
+ + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + +

Returns a value that is equal to the lowest value appearing in the input sequence.

+
+ +

The following rules are applied to the input sequence:

+ + +

Values of type xs:untypedAtomic in $values are cast to + xs:double.

+
+ +

If the resulting sequence contains values that are instances of more than one primitive type + (meaning the 19 primitive types defined in ), then: +

+ + +

If each value is an instance of one of the types xs:string or xs:anyURI, + then all the values are cast to type xs:string.

+
+ +

If each value is an instance of one of the types xs:decimal or xs:float, + then all the values are cast to type xs:float.

+
+ +

If each value is an instance of one of the types xs:decimal, xs:float, + or xs:double, then all the values are cast to type xs:double.

+
+ +

Otherwise, a type error is raised .

+
+
+ +

The primitive type of an xs:integer value for this purpose is xs:decimal.

+
+
+
+

The items in the resulting sequence may be reordered in an arbitrary order. The + resulting sequence is referred to below as the converted sequence. The function returns + an item from the converted sequence rather than the input sequence.

+

If the converted sequence is empty, the empty sequence is returned.

+

All items in the converted sequence must be derived from a single base type for which + the le operator is defined. In addition, the values in the sequence must + have a total order. If date/time values do not have a timezone, they are considered to + have the implicit timezone provided by the dynamic context for the purpose of + comparison. Duration values must either all be xs:yearMonthDuration values + or must all be xs:dayTimeDuration values.

+

If the converted sequence contains the value NaN, the value + NaN is returned + (as an xs:float or xs:double as appropriate).

+

If the items in the converted sequence are of type xs:string or types + derived by restriction from xs:string, then the determination of the item + with the smallest value is made according to the collation that is used. If the type of + the items in the converted sequence is not xs:string and + $collation is specified, the collation is ignored.

+

The collation used by this function is determined according to the rules in .

+

The function returns the result of the expression:

+ + if (every $v in $c satisfies $c[1] le $v) + then $c[1] + else min(tail($c)) +

evaluated with $collation as the default collation if specified, and with + $c as the converted sequence.

+ +
+ +

A type error is raised if the input sequence contains + items of incompatible types, as described above.

+
+ +

Because the rules allow the sequence to be reordered, if there are two or items that are + “equal lowest”, the specific item whose value is returned is implementation-dependent. This can arise for example if two different strings + compare equal under the selected collation, or if two different xs:dateTime + values compare equal despite being in different timezones.

+

If the converted sequence contains exactly one value then that value is returned.

+

The default type when the fn:min function is applied to + xs:untypedAtomic values is xs:double. This differs from the + default type for operators such as lt, and for sorting in XQuery and XSLT, + which is xs:string.

+

The rules for the dynamic type of the result are stricter in version 3.1 of the specification than + in earlier versions. For example, if all the values in the input sequence belong to types derived from + xs:integer, version 3.0 required only that the result be an instance + of the least common supertype of the types present in the input sequence; Version 3.1 + requires that the returned value retains its original type. This does not apply, however, where type promotion + is needed to convert all the values to a common primitive type.

+ +
+ + + + min((3,4,5)) + 3 + + + + + min([3,4,5]) + 3 + Arrays are atomized + + + + + min((xs:integer(5), xs:float(5), xs:double(10))) + xs:double(5.0e0) + + + +

fn:min((xs:float(0.0E0), xs:float(-0.0E0))) can return either positive + or negative zero. The two items are equal, so it is implementation-dependent which is returned.

+
+ + + min((current-date(), xs:date("1900-01-01"))) + xs:date("1900-01-01") + Assuming that the current date is set to a reasonable + value. + + + + + min(("a", "b", "c")) + "a" + Assuming a typical default collation. + + + +

fn:min((3,4,"Zero")) raises a type error .

+
+
+
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a value obtained by adding together the values in $values.

+
+ +

Any values of type xs:untypedAtomic in $values are cast to + xs:double. The items in the resulting sequence may be reordered in an + arbitrary order. The resulting sequence is referred to below as the converted + sequence.

+

If the converted sequence is empty, then the function returns + the value of the argument $zero, which defaults to + the xs:integer value 0.

+

If the converted sequence contains the value NaN, NaN is + returned.

+

All items in $values must be numeric or derived from a single base type. In + addition, the type must support addition. Duration values must either all be + xs:yearMonthDuration values or must all be + xs:dayTimeDuration values. For numeric values, the numeric promotion + rules defined in are used to promote all values to a single + common type. The sum of a sequence of integers will therefore be an integer, while the + sum of a numeric sequence that includes at least one xs:double will be an + xs:double.

+

The result of the function is the value of the + expression:

+ +if (count($c) eq 0) then + $zero +else if (count($c) eq 1) then + $c[1] +else + $c[1] + sum(subsequence($c, 2)) +

where $c is the converted sequence.

+

The result of the function when a single argument is supplied is the result of the expression: + fn:sum($arg, 0).

+ +
+ +

A type error is raised if the input sequence contains + items of incompatible types, as described above.

+ +
+ +

The second argument allows an appropriate value to be defined to represent the sum of an + empty sequence. For example, when summing a sequence of durations it would be + appropriate to return a zero-length duration of the appropriate type. This argument is + necessary because a system that does dynamic typing cannot distinguish “an empty + sequence of integers", for example, from “an empty sequence of durations”.

+

The explicit or implicit value of + the $zero argument is used only when the input sequence is empty, not + when a non-empty sequence sums to zero. For example, sum((-1, +1), xs:double('NaN')) + returns the xs:integer value 0, not NaN.

+

If the converted sequence contains exactly one value then that value is returned.

+
+ + + + + + + + sum(($d1, $d2)) + xs:yearMonthDuration("P20Y10M") + + + + + sum( + $seq1[. lt xs:yearMonthDuration('P3M')], + xs:yearMonthDuration('P0M') +) + xs:yearMonthDuration("P0M") + + + + + sum($seq3) + 12 + + + + + sum(()) + 0 + + + + + sum((),()) + () + + + + + sum((1 to 100)[. lt 0], 0) + 0 + + + + + sum(($d1, $d2), "ein Augenblick") + xs:yearMonthDuration("P20Y10M") + There is no requirement that the $zero value should be + the same type as the items in $value, or even that it should belong to + a type that supports addition. + + + + + sum([1, 2, 3]) + 6 + Atomizing an array returns the sequence obtained by atomizing its members. + + + + + sum([[1, 2], [3, 4]]) + 10 + Atomizing an array returns the sequence obtained by atomizing its members. + + + +

fn:sum(($d1, 9E1)) raises a type error .

+
+
+
+ + + + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the sequence of element nodes that have an ID value matching the + value of one or more of the IDREF values supplied in $values.

+
+ +

The function returns a sequence, in document order with duplicates eliminated, + containing every element node E that satisfies all the following + conditions:

+ + +

+ E is in the target document. The target document is the document + containing $node, or the document containing the context item + (.) if the second argument is omitted. The behavior of the + function if $node is omitted is exactly the same as if the context + item had been passed as $node.

+
+ +

E has an ID value equal to one of the candidate + IDREF values, where:

+ + +

An element has an ID value equal to V if either + or both of the following conditions are true:

+ + +

The is-id property (See .) of the element node is true, and the typed value + of the element node is equal to V under the rules of the + eq operator using the Unicode codepoint collation + (http://www.w3.org/2005/xpath-functions/collation/codepoint).

+
+ +

The element has an attribute node whose is-id property + (See .) is true and whose typed + value is equal to V under the rules of the + eq operator using the Unicode code point collation + (http://www.w3.org/2005/xpath-functions/collation/codepoint).

+
+
+
+ +

Each xs:string in $values is parsed as if it were of + type IDREFS, that is, each xs:string in + $values is treated as a whitespace-separated sequence of + tokens, each acting as an IDREF. These tokens are then included + in the list of candidate IDREFs. If any of the tokens is not a + lexically valid IDREF (that is, if it is not lexically an + xs:NCName), it is ignored. Formally, the candidate + IDREF values are the strings in the sequence given by the + expression:

+ for $s in $values return + tokenize(normalize-space($s), ' ')[. castable as xs:IDREF] + +
+
+
+ +

If several elements have the same ID value, then E is + the one that is first in document order.

+
+
+
+ +

A dynamic error is raised if + $node, or the context item if the second argument is absent, is a node + in a tree whose root is not a document node.

+

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+ +
+ +

The effect of this function is anomalous in respect of element nodes with the + is-id property. For legacy reasons, this function returns the element + that has the is-id property, whereas it would be more appropriate to return + its parent, that being the element that is uniquely identified by the ID. A new function + fn:element-with-id has been introduced with the desired + behavior.

+ +

If the data model is constructed from an Infoset, an attribute will have the + is-id property if the corresponding attribute in the Infoset had an + attribute type of ID: typically this means the attribute was declared as an + ID in a DTD.

+ +

If the data model is constructed from a PSVI, an element or attribute will have the + is-id property if its typed value is a single atomic value of type + xs:ID or a type derived by restriction from xs:ID.

+ +

No error is raised in respect of a candidate IDREF value that does not + match the ID of any element in the document. If no candidate + IDREF value matches the ID value of any element, the + function returns the empty sequence.

+

It is not necessary that the supplied argument should have type xs:IDREF + or xs:IDREFS, or that it should be derived from a node with the + is-idrefs property.

+

An element may have more than one ID value. This can occur with synthetic + data models or with data models constructed from a PSVI where the element and one of its + attributes are both typed as xs:ID.

+

If the source document is well-formed but not valid, it is possible for two or more + elements to have the same ID value. In this situation, the function will + select the first such element.

+

It is also possible in a well-formed but invalid document to have an element or + attribute that has the is-id property but whose value does not conform to + the lexical rules for the xs:ID type. Such a node will never be selected by + this function.

+
+ + + E21256 + John + Brown + + } + }]]> + + + + $emp/id('ID21256')/name() + "employee" + The xml:id attribute has the is-id property, + so the employee element is selected. + + + + + $emp/id('E21256')/name() + "empnr" + Assuming the empnr element is given the type + xs:ID as a result of schema validation, the element will have the + is-id property and is therefore selected. Note the difference from + the behavior of fn:element-with-id. + + + +
+ + + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the sequence of element nodes that have an ID value matching the + value of one or more of the IDREF values supplied in $values.

+
+ + + +

The effect of this function is identical to fn:id in respect of + elements that have an attribute with the is-id property. However, it + behaves differently in respect of element nodes with the is-id property. + Whereas the fn:id function, for legacy reasons, returns the element that has the + is-id property, this function returns the element identified by the ID, + which is the parent of the element having the is-id property.

+
+

The function returns a sequence, in document order with duplicates eliminated, + containing every element node E that satisfies all the following + conditions:

+ + +

+ E is in the target document. The target document is the document + containing $node, or the document containing the context item + (.) if the second argument is omitted. The behavior of the + function if $node is omitted is exactly the same as if the context + item had been passed as $node.

+
+ +

E has an ID value equal to one of the candidate + IDREF values, where:

+ + +

An element has an ID value equal to V if either + or both of the following conditions are true:

+ + +

The element has an child element node whose is-id + property (See .) is true and + whose typed value is equal to V under the rules of the + eq operator using the Unicode code point collation + (http://www.w3.org/2005/xpath-functions/collation/codepoint).

+
+ +

The element has an attribute node whose is-id property + (See .) is true and whose typed + value is equal to V under the rules of the + eq operator using the Unicode code point collation + (http://www.w3.org/2005/xpath-functions/collation/codepoint).

+
+
+
+ +

Each xs:string in $values is parsed as if it were of + type IDREFS, that is, each xs:string in + $values is treated as a whitespace-separated sequence of + tokens, each acting as an IDREF. These tokens are then included + in the list of candidate IDREFs. If any of the tokens is not a + lexically valid IDREF (that is, if it is not lexically an + xs:NCName), it is ignored. Formally, the candidate + IDREF values are the strings in the sequence given by the + expression:

+ for $s in $arg return + tokenize(normalize-space($s), ' ')[. castable as xs:IDREF] +
+
+
+ +

If several elements have the same ID value, then E is + the one that is first in document order.

+
+
+
+ +

A dynamic error is raised if $node, or the context item if the second argument is omitted, is a node + in a tree whose root is not a document node.

+

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+ +
+ +

This function is equivalent to the fn:id function except when dealing with + ID-valued element nodes. Whereas the fn:id function selects the element + containing the identifier, this function selects its parent.

+

If the data model is constructed from an Infoset, an attribute will have the + is-id property if the corresponding attribute in the Infoset had an + attribute type of ID: typically this means the attribute was declared as an + ID in a DTD.

+ +

If the data model is constructed from a PSVI, an element or attribute will have the + is-id property if its typed value is a single atomic value of type + xs:ID or a type derived by restriction from xs:ID.

+ +

No error is raised in respect of a candidate IDREF value that does not + match the ID of any element in the document. If no candidate + IDREF value matches the ID value of any element, the + function returns the empty sequence.

+

It is not necessary that the supplied argument should have type xs:IDREF + or xs:IDREFS, or that it should be derived from a node with the + is-idrefs property.

+

An element may have more than one ID value. This can occur with synthetic + data models or with data models constructed from a PSVI where the element and one of its + attributes are both typed as xs:ID.

+

If the source document is well-formed but not valid, it is possible for two or more + elements to have the same ID value. In this situation, the function will + select the first such element.

+

It is also possible in a well-formed but invalid document to have an element or + attribute that has the is-id property but whose value does not conform to + the lexical rules for the xs:ID type. Such a node will never be selected by + this function.

+
+ + + E21256 + John + Brown + + } + }]]> + + + + $emp/element-with-id('ID21256')/name() + "employee" + The xml:id attribute has the is-id property, + so the employee element is selected. + + + + + $emp/element-with-id('E21256')/name() + "employee" + Assuming the empnr element is given the type + xs:ID as a result of schema validation, the element will have the + is-id property and is therefore its parent is selected. Note the + difference from the behavior of fn:id. + + + +
+ + + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

Returns the sequence of element or attribute nodes with an IDREF value + matching the value of one or more of the ID values supplied in + $values.

+
+ +

The function returns a sequence, in document order with duplicates eliminated, + containing every element or attribute node $N that satisfies all the + following conditions:

+ + +

$N is in the target document. The target document is the document + containing $node or the document containing the context item + (.) if the second argument is omitted. The behavior of the + function if $node is omitted is exactly the same as if the context + item had been passed as $node.

+
+ +

$N has an IDREF value equal to one of the candidate + ID values, where:

+ + +

A node $N has an IDREF value equal to + V if both of the following conditions are true:

+ + +

The is-idrefs property (see ) of $N is true.

+
+ +

The sequence

+ tokenize(normalize-space(string($N)), ' ') + +

contains a string that is + equal to V under the rules of the eq + operator using the Unicode code point collation + (http://www.w3.org/2005/xpath-functions/collation/codepoint).

+
+
+
+ +

Each xs:string in $values is parsed as if it were of + lexically of type xs:ID. These xs:strings are then + included in the list of candidate xs:IDs. If any of the strings + in $values is not a lexically valid xs:ID (that is, + if it is not lexically an xs:NCName), it is ignored. More + formally, the candidate ID values are the strings in the + sequence:

+ $values[. castable as xs:NCName] +
+
+
+
+
+ +

A dynamic error is raised if + $node, or the context item if the second argument is omitted, is a node + in a tree whose root is not a document node.

+

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+ +
+ +

An element or attribute typically acquires the is-idrefs property by being + validated against the schema type xs:IDREF or xs:IDREFS, or + (for attributes only) by being described as of type IDREF or + IDREFS in a DTD.

+

Because the function is sensitive to the way in which the data model + is constructed, calls on this function are not always interoperable.

+

No error is raised in respect of a candidate ID value that does not match + the IDREF value of any element or attribute in the document. If no + candidate ID value matches the IDREF value of any element or + attribute, the function returns the empty sequence.

+

It is possible for two or more nodes to have an IDREF value that matches a + given candidate ID value. In this situation, the function will return all + such nodes. However, each matching node will be returned at most once, regardless how + many candidate ID values it matches.

+

It is possible in a well-formed but invalid document to have a node whose + is-idrefs property is true but that does not conform to the lexical + rules for the xs:IDREF type. The effect of the above rules is that + ill-formed candidate ID values and ill-formed IDREF values are + ignored.

+

If the data model is constructed from a PSVI, the typed value of a node that has the + is-idrefs property will contain at least one atomic value of type + xs:IDREF (or a type derived by restriction from xs:IDREF). + It may also contain atomic values of other types. These atomic values are treated as + candidate ID values if two conditions are met: their lexical form must be valid as an + xs:NCName, and there must be at least one instance of xs:IDREF + in the typed value of the node. If these conditions are not satisfied, such values are ignored.

+ +
+ + + + E21256 + Anil + Singh + E30561 + + + E30561 + John + Brown + ID21256 + + + } + }]]> + + + + $emp/( + element-with-id('ID21256')/@xml:id => idref() +)/ancestor::employee/last +=> string() + "Brown" + Assuming that manager has the is-idref property, the call on fn:idref selects + the manager element. If, instead, the manager had a ref + attribute with the is-idref property, the call on fn:idref would select the attribute node. + + + + + $emp/( + element-with-id('E30561')/empnr => idref() +)/ancestor::employee/last +=> string() + "Singh" + Assuming that employee/deputy has the is-idref property, the call on fn:idref selects + the deputy element. + + + +
+ + + + + + + + deterministic + context-dependent + focus-independent + + +

Retrieves a document using a URI supplied as an xs:string, and returns the + corresponding document node.

+
+ +

If $href is the empty sequence, the result is an empty sequence.

+

If $href is a relative URI reference, it is resolved relative to the value + of the static base URI property from the static context. The resulting absolute URI is + promoted to an xs:string.

+

If the available documents described in provides a mapping from this string to a document node, the + function returns that document node.

+

The URI may include a fragment identifier.

+

By default, this function is deterministic. Two + calls on this function return the same document node if the same URI Reference (after + resolution to an absolute URI Reference) is supplied to both calls. Thus, the following + expression (if it does not raise an error) will always return true:

+ doc("foo.xml") is doc("foo.xml") +

However, for performance reasons, implementations may provide a user option to evaluate + the function without a guarantee of determinism. The manner in which any such option is + provided is implementation-defined. If the user has not selected such an option, a call + of the function must either return a deterministic result or must raise a dynamic error + .

+ + +

If $href is read from a source document, it is generally appropriate to + resolve it relative to the base URI property of the relevant node in the source + document. This can be achieved by calling the fn:resolve-uri function, + and passing the resulting absolute URI as an argument to the fn:doc + function.

+
+

If two calls to this function supply different absolute URI References as arguments, the + same document node may be returned if the implementation can determine that the two + arguments refer to the same resource.

+

By defining the semantics of this function in terms of a string-to-document-node + mapping in the dynamic context, the specification is acknowledging that the results of + this function are outside the purview of the language specification itself, and depend + entirely on the run-time environment in which the expression is evaluated. This run-time + environment includes not only an unpredictable collection of resources (“the web”), but + configurable machinery for locating resources and turning their contents into document + nodes within the XPath data model. Both the set of resources that are reachable, and the + mechanisms by which those resources are parsed and validated, are implementation-dependent.

+

One possible processing model for this function is as follows. The resource identified + by the URI Reference is retrieved. If the resource cannot be retrieved, a dynamic error + is raised . The data resulting from the retrieval + action is then parsed as an XML document and a tree is constructed in accordance with + the . If the top-level media type is known and is + "text", the content is parsed in the same way as if the media type were text/xml; + otherwise, it is parsed in the same way as if the media type were application/xml. If + the contents cannot be parsed successfully, a dynamic error is raised . Otherwise, the result of the function is the document node + at the root of the resulting tree. This tree is then optionally validated against a + schema.

+

Various aspects of this processing are implementation-defined. + Implementations may provide external configuration options that allow any aspect of the + processing to be controlled by the user. In particular:

+ + +

The set of URI schemes that the implementation recognizes is + implementation-defined. Implementations may allow the mapping of URIs to resources + to be configured by the user, using mechanisms such as catalogs or user-written + URI handlers.

+
+ +

The handling of non-XML media types is implementation-defined. Implementations may + allow instances of the data model to be constructed from non-XML resources, under + user control.

+
+ +

It is implementation-defined whether DTD validation and/or schema + validation is applied to the source document.

+
+ +

Implementations may provide user-defined error handling options that allow + processing to continue following an error in retrieving a resource, or in parsing + and validating its content. When errors have been handled in this way, the + function may return either an empty sequence, or a fallback document provided by + the error handler.

+
+ +

Implementations may provide user options that relax the requirement for the + function to return deterministic results.

+
+ +

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

+
+
+
+ +

A dynamic error may be raised if + $href is not a valid URI reference.

+

A dynamic error is raised if a relative URI reference + is supplied, and the base-URI property in the static context is absent.

+

A dynamic error is raised if the available + documents provides no mapping for the absolutized URI.

+

A dynamic error is raised if the resource cannot be + retrieved or cannot be parsed successfully as XML.

+

A dynamic error is raised if the implementation is + not able to guarantee that the result of the function will be deterministic, and the + user has not indicated that an unstable result is acceptable.

+
+
+ + + + + + + + deterministic + context-dependent + focus-independent + + +

The function returns true if and only if the function call fn:doc($href) + would return a document node.

+
+ +

If $href is an empty sequence, this function returns false.

+

If a call on fn:doc($href) would return a document node, this function + returns true.

+

In all other cases this function returns false. This + includes the case where an invalid URI is supplied, and also the case where + a valid relative URI reference is supplied, and cannot be resolved, + for example because the static base URI is absent.

+

If this function returns true, then calling fn:doc($href) + within the same must return a document node. However, + if nondeterministic processing has been selected for the fn:doc function, + this guarantee is lost.

+
+
+ + + + + + + + deterministic + context-dependent + focus-independent + + +

Returns a sequence of items identified by a + collection URI; or a default collection if no URI is supplied.

+
+ +

This function takes an xs:string as argument and returns a sequence of + items obtained by interpreting $uri as an xs:anyURI and + resolving it according to the mapping specified in available + collections described in .

+

If available collections provides a mapping from this string to a + sequence of items, the function returns that sequence. If available + collections maps the string to an empty sequence, then the function returns an + empty sequence.

+

If $uri is not specified, the function returns the sequence of items in + the default collection in the dynamic context. See .

+

If $uri is a relative xs:anyURI, it is resolved + against the value of the base-URI property from the static context.

+

If $uri is the empty sequence, the function behaves as if it had been + called without an argument. See above.

+

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

+

There is no requirement that any nodes in the result should be in document order, nor is + there a requirement that the result should contain no duplicates.

+ + +
+ +

A dynamic error is raised if no URI is supplied and + the value of the default collection is absent.

+

A dynamic error is raised if a relative URI reference + is supplied, and the base-URI property in the static context is absent.

+

A dynamic error is raised if available node + collections provides no mapping for the absolutized URI.

+

A dynamic error may be raised if $uri is not + a valid xs:anyURI.

+
+ +

In earlier versions of this specification, the primary use for the fn:collection function + was to retrieve a collection of XML documents, perhaps held as lexical XML in operating + system filestore, or perhaps held in an XML database. In this release the concept has + been generalised to allow other resources to be retrieved: for example JSON documents might + be returned as arrays or maps, non-XML text files might be returned as strings, and binary + files might be returned as instances of xs:base64Binary.

+

The abstract concept of a collection might be realized in different ways by different + implementations, and the ways in which URIs map to collections can be equally variable. + Specifying resources using URIs is + useful because URIs are dynamic, can be parameterized, and do not rely on an external + environment.

+
+
+ + + + + + + + deterministic + context-dependent + focus-independent + + +

Returns a sequence of xs:anyURI values representing the URIs in a URI + collection.

+
+ +

The zero-argument form of the function returns the URIs in the default URI + collection described in .

+

If $uri is a relative xs:anyURI, it is resolved + against the value of the base-URI property from the static context.

+

If $uri is the empty sequence, the function behaves as if it had been + called without an argument. See above.

+

The single-argument form of the function returns the sequence of URIs corresponding to + the supplied URI in the available URI collections described in + .

+

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

+

There is no requirement that the URIs returned by this function should all be distinct, + and no assumptions can be made about the order of URIs in the sequence, unless the + implementation defines otherwise.

+
+ +

A dynamic error is raised if no URI is supplied (that + is, if the function is called with no arguments, or with a single argument that + evaluates to an empty sequence), and the value of the default resource collection is + absent.

+

A dynamic error is raised if a relative URI reference + is supplied, and the base-URI property in the static context is absent.

+

A dynamic error is raised if available resource + collections provides no mapping for the absolutized URI.

+

A dynamic error may be raised if $uri is not + a valid xs:anyURI.

+
+ +

In some implementations, there might be a close relationship between collections (as retrieved + by the fn:collection function), and URI collections (as retrieved by this function). + For example, a collection might return XML documents, and the corresponding URI collection might return + the URIs of those documents. However, this specification does not impose such a close relationship. For example, there + may be collection URIs accepted by one of the two functions and not by the other; a collection might contain + items that do not have any URI; or a URI collection might contain URIs that cannot be dereferenced to return any + resource.

+ +

Thus, some implementations might ensure that calling fn:uri-collection and then + applying fn:doc to each of the returned URIs delivers the same result as + calling fn:collection with the same argument; however, this is not + guaranteed.

+ +

In the case where fn:uri-collection returns the URIs of resources that + could also be retrieved directly using fn:collection, there are several reasons why it + might be appropriate to use this function in preference + to the fn:collection function. For example:

+ + + +

It allows different URIs for different kinds of resource to be dereferenced in + different ways: for + example, the returned URIs might be referenced using the + fn:unparsed-text function rather than the fn:doc + function.

+
+ +

In XSLT 3.0 it allows the documents in a collection to be processed in streaming mode using the + xsl:stream instruction.

+
+ +

It allows recovery from failures to read, parse, or validate individual documents, + by calling the fn:doc (or other dereferencing) function within the scope of try/catch.

+
+ +

It allows selection of which documents to read based on their URI, for example + they can be filtered to select those whose URIs end in .xml, or those + that use the https scheme.

+
+ +

An application might choose to limit the number of URIs processed in a single run, + for example it might process only the first 50 URIs in the collection; or it might + present the URIs to the user and allow the user to select which of them need to be + further processed.

+
+ +

It allows the URIs to be modified before they are dereferenced, for example by + adding or removing query parameters, or by redirecting the request to a local + cache or to a mirror site.

+
+
+ +

For some of these use cases, this assumes that the cost of calling + fn:collection might be significant (for example, it might involving + retrieving all the documents in the collection over the network and parsing them). This + will not necessarily be true of all implementations.

+ + + + + + +
+
+ + + + + + + + + deterministic + context-dependent + focus-independent + + +

The fn:unparsed-text function reads an external resource (for example, a + file) and returns a string representation of the resource.

+
+ +

The $href argument must be a string in the form of a URI + reference, which must contain no fragment identifier, and + must identify a resource for which a string representation is + available. If the URI is a relative URI reference, then it is resolved relative to the + static base URI property from the static context.

+

The mapping of URIs to the string representation of a resource is the mapping defined in + the available text + resources component of the dynamic context.

+

If the $href argument is an empty sequence, the function + returns an empty sequence.

+

The $encoding argument, if present + and non-empty, is the name of an encoding. The values + for this attribute follow the same rules as for the encoding attribute in + an XML declaration. The only values which every + implementation is required to recognize are + utf-8 and utf-16.

+

The encoding of the external resource is determined as follows:

+ + +

external encoding information is used if available, otherwise

+
+ +

if the media type of the resource is text/xml or + application/xml (see ), or if it matches + the conventions text/*+xml or application/*+xml (see + and/or its successors), then the encoding is recognized + as specified in , otherwise

+
+ +

the $encoding argument is used if present, otherwise

+
+ +

the processor may use implementation-defined heuristics to determine the likely encoding, + otherwise

+
+ +

UTF-8 is assumed.

+
+
+

The result of the function is a string containing the string representation of the + resource retrieved using the URI.

+
+ +

A dynamic error is raised if the $href argument + contains a fragment identifier, or if it cannot be resolved + to an absolute URI (for example, because the base-URI property in the static context is absent), + or if it cannot be used to retrieve the string + representation of a resource.

+

A dynamic error is raised if the value of the + $encoding argument is not a valid encoding name, if the + processor does not support the specified encoding, if + the string representation of the retrieved resource contains octets that cannot be + decoded into Unicode characters using the specified + encoding, or if the resulting characters are not + permitted character.

+

A dynamic error is raised if $encoding + is absent and the processor cannot infer the + encoding using external information and the encoding is not UTF-8.

+
+ + +

If it is appropriate to use a base URI other than the dynamic base URI (for example, + when resolving a relative URI reference read from a source document) then it is + advisable to resolve the relative URI reference using the fn:resolve-uri + function before passing it to the fn:unparsed-text function.

+

There is no essential relationship between the sets of URIs accepted by the two + functions fn:unparsed-text and fn:doc (a URI accepted by one + may or may not be accepted by the other), and if a URI is accepted by both there is no + essential relationship between the results (different resource representations are + permitted by the architecture of the web).

+

There are no constraints on the MIME type of the resource.

+ + +

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

+ + +

The set of URI schemes that the implementation recognizes is + implementation-defined. Implementations may allow the mapping of URIs to resources + to be configured by the user, using mechanisms such as catalogs or user-written + URI handlers.

+
+ +

The handling of media types is implementation-defined.

+
+ + +

Implementations may provide user-defined error handling options that allow + processing to continue following an error in retrieving a resource, or in reading + its content. When errors have been handled in this way, the function may return a + fallback document provided by the error handler.

+
+ +

Implementations may provide user options that relax the requirement for the + function to return deterministic results.

+
+
+ +

The rules for determining the encoding are chosen for consistency with . Files with an XML media type are treated specially because there + are use cases for this function where the retrieved text is to be included as unparsed + XML within a CDATA section of a containing document, and because processors are likely + to be able to reuse the code that performs encoding detection for XML external + entities.

+

If the text file contains characters such as < and &, + these will typically be output as &lt; and &amp; if + the string is serialized as XML or HTML. If these characters actually represent markup + (for example, if the text file contains HTML), then an XSLT stylesheet can attempt to + write them as markup to the output file using the disable-output-escaping + attribute of the xsl:value-of instruction. Note, however, that XSLT + implementations are not required to support this feature.

+
+ + + + + + + +

This XSLT example attempts to read a file containing “boilerplate” HTML and copy it + directly to the serialized output file:

+ + + + + + + +]]> +
+
+ +
+ + + + + + + + + deterministic + context-dependent + focus-independent + + +

The fn:unparsed-text-lines function reads an external resource (for + example, a file) and returns its contents as a sequence of strings, one for each line of + text in the string representation of the resource.

+
+ +

The unparsed-text-lines function reads an external resource (for example, a + file) and returns its string representation as a sequence of strings, separated at + newline boundaries.

+

The result of the single-argument function is the same as the result of the expression + fn:tokenize(fn:unparsed-text($href), '\r\n|\r|\n')[not(position()=last() and + .='')]. The result of the two-argument function is the same as the result of + the expression fn:tokenize(fn:unparsed-text($href, $encoding), + '\r\n|\r|\n')[not(position()=last() and .='')].

+

The result is thus a sequence of strings containing the text of the resource retrieved + using the URI, each string representing one line of text. Lines are separated by one of + the sequences x0A, x0D, or x0Dx0A. The characters representing the newline are not + included in the returned strings. If there are two adjacent newline sequences, a + zero-length string will be returned to represent the empty line; but if the external + resource ends with the sequence x0A, x0D, or x0Dx0A, the result will be as if this final + line ending were not present.

+
+ +

Error conditions are the same as for the fn:unparsed-text function.

+ +
+ + +

See the notes for fn:unparsed-text.

+
+
+ + + + + + + + + deterministic + context-dependent + focus-independent + + +

Because errors in evaluating the fn:unparsed-text function are + non-recoverable, these two functions are provided to allow an application to determine + whether a call with particular arguments would succeed.

+
+ +

The fn:unparsed-text-available function determines whether a call + on the fn:unparsed-text function with identical arguments would + return a string.

+

If the first argument is an empty sequence, the function returns false.

+

In other cases, the function returns true if a call on + fn:unparsed-text with the same arguments would succeed, and + false if a call on fn:unparsed-text with the same arguments would + fail with a non-recoverable dynamic error.

+

The functions fn:unparsed-text and + fn:unparsed-text-available have the same requirement for + determinism as the functions + fn:doc and fn:doc-available. This means that unless the + user has explicitly stated a requirement for a reduced level of determinism, either of + these functions if called twice with the same arguments during the course of a + transformation must return the same results each time; moreover, the + results of a call on fn:unparsed-text-available + must be consistent with the results of a subsequent call on + unparsed-text with the same arguments.

+
+ +

This requires that the fn:unparsed-text-available function should + actually attempt to read the resource identified by the URI, and check that it is + correctly encoded and contains no characters that are invalid in XML. Implementations + may avoid the cost of repeating these checks for example by caching the validated + contents of the resource, to anticipate a subsequent call on the + fn:unparsed-text or fn:unparsed-text-lines + function. Alternatively, implementations may be able to rewrite an expression such as + if (unparsed-text-available(A)) then unparsed-text(A) else ... to + generate a single call internally.

+

Since the function fn:unparsed-text-lines succeeds or fails under + exactly the same circumstances as fn:unparsed-text, the + fn:unparsed-text-available function may equally be used to test + whether a call on fn:unparsed-text-lines would succeed.

+ +
+ +
+ + + + + + + + deterministic + context-dependent + focus-independent + + +

Returns the value of a system environment variable, if it exists.

+
+ +

The set of available environment + variables is a set of (name, value) pairs forming part of the dynamic + context, in which the name is unique within the set of pairs. The name and value are + arbitrary strings.

+

If the $name argument matches the name of one of these pairs, the function + returns the corresponding value.

+

If there is no environment variable with a matching name, the function returns the empty + sequence.

+

The collation used for matching names is implementation-defined, but + must be the same as the collation used to ensure that the names of all environment + variables are unique.

+

The function is deterministic, which means + that if it is called several times within the same execution scope, with the same arguments, it must return the same + result.

+
+ +

On many platforms, the term “environment variable” has a natural meaning in terms of + facilities provided by the operating system. This interpretation of the concept does not + exclude other interpretations, such as a mapping to a set of configuration parameters in + a database system.

+

Environment variable names are usually case sensitive. Names are usually of the form + (letter|_) (letter|_|digit)*, but this varies by platform.

+

On some platforms, there may sometimes be multiple environment variables with the same + name; in this case, it is implementation-dependent as to which is returned; see for + example (Chapter 8, Environment Variables). Implementations + may use prefixes or other naming conventions to disambiguate the + names.

+

The requirement to ensure that the function is deterministic means in practice that the + implementation must make a snapshot of the environment variables at some time during + execution, and return values obtained from this snapshot, rather than using live values + that are subject to change at any time.

+

Operating system environment variables may be associated with a particular process, + while queries and stylesheets may execute across multiple processes (or multiple + machines). In such circumstances implementations may choose to + provide access to the environment variables associated with the process in which the + query or stylesheet processing was initiated.

+

Security advice: Queries from untrusted sources should not be permitted unrestricted + access to environment variables. For example, the name of the account under which the + query is running may be useful information to a would-be intruder. An implementation may + therefore choose to restrict access to the environment, or may provide a facility to + make fn:environment-variable always return the empty sequence.

+ +
+
+ + + + + + deterministic + context-dependent + focus-independent + + +

Returns a list of environment variable names that are suitable for passing to + fn:environment-variable, as a (possibly empty) sequence of strings.

+
+ +

The function returns a sequence of strings, being the names of the environment variables + in the dynamic context in some implementation-dependent order.

+

The function is deterministic: that is, the + set of available environment variables does not vary during evaluation.

+
+ +

The function returns a list of strings, containing no duplicates.

+

It is intended that the strings in this list should be suitable for passing to + fn:environment-variable.

+ +

See also the note on security under the definition of the + fn:environment-variable function. If access to environment variables has + been disabled, fn:available-environment-variables always returns the empty + sequence.

+
+
+ + + + + + + + deterministic + context-dependent + focus-dependent + + + deterministic + context-independent + focus-independent + + +

This function returns a string that uniquely identifies a given node.

+
+ +

If the argument is omitted, it defaults to the context item (.). The + behavior of the function if the argument is omitted is exactly the same as if the + context item had been passed as the argument.

+

If the argument is the empty sequence, the result is the zero-length string.

+

In other cases, the function returns a string that uniquely identifies a given node. + More formally, it is guaranteed that within a single + execution scope, + fn:codepoint-equal(fn:generate-id($N), fn:generate-id($M)) returns true + if and only if ($M is $N) returns true.

+ +

The returned identifier must consist of ASCII alphanumeric characters + and must start with an alphabetic character. Thus, the string is + syntactically an XML name.

+ +
+ +

The following errors may be raised when $node is omitted:

+ + +

If the context item is absent, + dynamic error

+
+ +

If the context item is not a node, type error .

+
+
+ +
+ +

An implementation is free to generate an identifier in any convenient way provided that + it always generates the same identifier for the same node and that different identifiers + are always generated from different nodes. An implementation is under no obligation to + generate the same identifiers each time a document is transformed or queried.

+

There is no guarantee that a generated unique identifier will be distinct from any + unique IDs specified in the source document.

+

There is no inverse to this function; it is not directly possible to find the node with + a given generated ID. Of course, it is possible to search a given sequence of nodes + using an expression such as $nodes[generate-id()=$id].

+

It is advisable, but not required, for implementations to generate IDs that are distinct + even when compared using a case-blind collation.

+ +
+ + +

The primary use case for this function is to generate hyperlinks. For example, when + generating HTML, an anchor for a given section $sect can be generated by + writing (in either XSLT or XQuery):

+

+ ]]> +

+

and a link to that section can then be produced with code such as:

+

+ here]]> +

+

Note that anchors generated in this way will not necessarily be the same each time a + document is republished.

+ +
+ +

Since the keys in a map must be atomic values, it is possible to use generated IDs + as surrogates for nodes when constructing a map. For example, in some implementations, + testing whether a node $N is a member of a large node-set $S + using the expression fn:exists($N intersect $S) may be expensive; there + may then be performance benefits in creating a map:

+

+ let $SMap := map:merge($S!map{fn:generate-id(.) : .}) +

+

and then testing for membership of the node-set using:

+

+ map:contains($SMap, generate-id($N)) +

+
+
+
+ + + + + + + + + + + nondeterministic + context-dependent + focus-independent + + +

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

+
+ +

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

+

The precise process used to construct the XDM instance is implementation-defined. In particular, it is implementation-defined whether + DTD and/or schema validation is invoked, and it is implementation-defined whether an XML + 1.0 or XML 1.1 parser is used.

+

The static base URI property from the static context of the fn:parse-xml + function call is used both as the base URI used by the XML parser to resolve relative + entity references within the document, and as the base URI of the document node that is + returned.

+

The document URI of the returned node is absent.

+

The function is not + deterministic: that is, if the function is called + twice with the same arguments, it is implementation-dependent whether the same node is returned on both + occasions.

+
+ +

A dynamic error is raised if the content of + $value is not a well-formed and namespace-well-formed XML document.

+

A dynamic error is raised if DTD-based validation is + carried out and the content of $value is not valid against its DTD.

+
+ +

Since the XML document is presented to the parser as a string, rather than as a sequence + of octets, the encoding specified within the XML declaration has no meaning. If the XML + parser accepts input only in the form of a sequence of octets, then the processor must + ensure that the string is encoded as octets in a way that is consistent with rules used + by the XML parser to detect the encoding.

+

The primary use case for this function is to handle input documents that contain nested + XML documents embedded within CDATA sections. Since the content of the CDATA section are + exposed as text, the receiving query or stylesheet may pass this text to the + fn:parse-xml function to create a tree representation of the nested + document.

+

Similarly, nested XML within comments is sometimes encountered, and lexical XML is + sometimes returned by extension functions, for example, functions that access web + services or read from databases.

+

A use case arises in XSLT where there is a need to preprocess an input document before + parsing. For example, an application might wish to edit the document to remove its + DOCTYPE declaration. This can be done by reading the raw text using the + fn:unparsed-text function, editing the resulting string, and then + passing it to the fn:parse-xml function.

+
+ + +

The expression fn:parse-xml("<alpha>abcd</alpha>") returns a newly + created document node, having an alpha element as its only child; the + alpha element in turn is the parent of a text node whose string value + is "abcd".

+
+
+
+ + + + + + + + nondeterministic + context-dependent + focus-independent + + +

This function takes as input an XML external entity represented as a string, and returns + the document node at the root of an XDM tree representing the parsed document + fragment.

+
+ +

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

+

The input must be a namespace-well-formed external general parsed entity. More + specifically, it must be a string conforming to the production rule extParsedEnt in , it must contain + no entity references other than references to predefined entities, and it must satisfy + all the rules of for namespace-well-formed documents with + the exception that the rule requiring it to be a well-formed document is replaced by the + rule requiring it to be a well-formed external general parsed entity.

+

The string is parsed to form a sequence of nodes which become children of the new + document node, in the same way as the content of any element is converted into a + sequence of children for the resulting element node.

+

Schema validation is not invoked, which means that the nodes in the + returned document will all be untyped.

+

The precise process used to construct the XDM instance is implementation-defined. In particular, it is implementation-defined whether + an XML 1.0 or XML 1.1 parser is used.

+

The static base URI from the static context of the fn:parse-xml-fragment + function call is used as the base URI of the document node that is returned.

+

The document URI of the returned node is absent.

+

The function is not + deterministic: that is, if the function is called + twice with the same arguments, it is implementation-dependent whether the same node is returned on both + occasions.

+
+ +

A dynamic error is raised if the content of + $value is not a well-formed external general parsed entity, if it contains + entity references other than references to predefined entities, or if a document that + incorporates this well-formed parsed entity would not be namespace-well-formed.

+
+ +

See also the notes for the fn:parse-xml function.

+

The main differences between fn:parse-xml and + fn:parse-xml-fragment are that for fn:parse-xml, the + children of the resulting document node must contain exactly one element node and no + text nodes, wheras for fn:parse-xml-fragment, the resulting document node + can have any number (including zero) of element and text nodes among its children. An + additional difference is that the text declaration at the start of an + external entity has slightly different syntax from the XML declaration at + the start of a well-formed document.

+

Note that all whitespace outside the text declaration is significant, + including whitespace that precedes the first element node.

+

One use case for this function is to handle XML fragments stored in databases, which + frequently allow zero-or-more top level element nodes. Another use case is to parse the + contents of a CDATA section embedded within another XML document.

+
+ + +

The expression + fn:parse-xml-fragment("<alpha>abcd</alpha><beta>abcd</beta>") + returns a newly created document node, having two elements named alpha + and beta as its children; each of these elements in turn is the parent + of a text node.

+

The expression fn:parse-xml-fragment("He was <i>so</i> kind") + returns a newly created document node having three children: a text node whose string + value is "He was ", an element node named i having a child + text node with string value "so", and a text node whose string value is + " kind".

+

The expression fn:parse-xml-fragment("") returns a document node having + no children.

+

The expression fn:parse-xml-fragment(" ") returns a document node whose + children comprise a single text node whose string value is a single space.

+

The expression fn:parse-xml-fragment('<?xml version="1.0" encoding="utf8" + standalone="yes"?><a/>') results in a dynamic error because the standalone keyword is not permitted in the text + declaration that appears at the start of an external general parsed entity. (Thus, it + is not the case that any input accepted by the fn:parse-xml function + will also be accepted by fn:parse-xml-fragment.)

+
+
+
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

This function serializes the supplied input sequence $input as described in + , returning the serialized representation + of the sequence as a string.

+
+ +

The value of the first argument $input acts as the input sequence to the serialization process, + which starts with sequence normalization.

+ +

The second argument $options, if present, provides serialization parameters. These may be supplied in either + of two forms:

+ + + +

As an output:serialization-parameters + element, having the format described in . In this case the type of the supplied + argument must match the required type element(output:serialization-parameters).

+
+ +

As a map. In this case the type of the supplied argument must match the required type map(*)

+
+
+ +

The single-argument version of this function has the same effect as the two-argument + version called with $options set to an empty sequence. This in turn is the + same as the effect of passing an output:serialization-parameters element + with no child elements.

+ +

The final stage of serialization, that is, encoding, is skipped. If the serializer does + not allow this phase to be skipped, then the sequence of octets returned by the + serializer is decoded into a string by reversing the character encoding performed in the + final stage.

+ +

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

+ +

If the second argument is supplied as a map, then the option parameter conventions + apply. In this case:

+ + + +

Each entry in the map defines one serialization parameter.

+
+ +

The key of the entry is an xs:string value in the cases of parameter names defined in these specifications, or an + xs:QName (with non-absent namespace) in the case of implementation-defined serialization parameters.

+
+ +

The required type of each parameter, and its default value, are defined by the following table. The default + value is used when the map contains no entry for the parameter in question, and also when an entry is present, with the + empty sequence as its value. The table also indicates how the value of the map entry is to be interpreted in cases + where further explanation is needed.

+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ParameterRequired typeInterpretationDefault Value
+ allow-duplicate-names + + xs:boolean? + true() means "yes", false() means "no" + no +
+ byte-order-mark + + xs:boolean? + true() means "yes", false() means "no" + no +
+ cdata-section-elements + + xs:QName* + + + () +
+ doctype-public + + xs:string? + Zero-length string and () both represent "absent"absent
+ doctype-system + + xs:string? + Zero-length string and () both represent "absent"absent
+ encoding + + xs:string? + + + utf-8 +
+ escape-solidus + + xs:boolean? + true() means "yes", false() means "no" + yes +
+ escape-uri-attributes + + xs:boolean? + true() means "yes", false() means "no" + yes +
+ html-version + + xs:decimal? + + + 5 +
+ include-content-type + + xs:boolean? + true() means "yes", false() means "no" + yes +
+ indent + + xs:boolean? + true() means "yes", false() means "no" + no +
+ item-separator + + xs:string? + + absent
+ json-node-output-method + + union(xs:string, xs:QName)? + See Notes 1, 2 + xml +
+ media-type + + xs:string? + + (a media type suitable for the chosen method)
+ method + + union(xs:string, xs:QName)? + See Notes 1, 2 + xml +
+ normalization-form + + xs:string? + + + none +
+ omit-xml-declaration + + xs:boolean? + true() means "yes", false() means "no" + yes +
+ standalone + + xs:boolean? + true() means "yes", false() means "no", () means "omit" + omit +
+ suppress-indentation + + xs:QName* + + + () +
+ undeclare-prefixes + + xs:boolean? + true() means "yes", false() means "no" + no +
+ use-character-maps + + map(xs:string, xs:string)? + See Note 3 + map{} +
+ version + + xs:string? + + + 1.0 +
+ +

Notes to the table:

+ + + +

The notation union(A, B) is used to represent a union type whose member types are A + and B.

+
+ +

If an xs:QName is supplied for the method or json-node-output-method + options, then it must have a non-absent namespace URI. This + means that system-defined serialization methods such as xml and json + are defined as strings, not as xs:QName values.

+
+ +

For the use-character-maps option, the value is a map, whose keys + are the characters to be mapped (as xs:string instances), + and whose corresponding values are the strings to be substituted for these characters. +

+
+
+ +
+ +

A type error occurs if the $options argument + is present and does not match either of the types element(output:serialization-parameters)? + or map(*).

+ +

This is defined as a type error so that it can be enforced via the function signature by implementations + that generalize the type system in a suitable way.

+
+

If the host language makes serialization an optional feature and the implementation does + not support serialization, then a dynamic error is + raised.

+

When the second argument is supplied as a map, + and the supplied value is of the wrong type for the particular parameter, for example if the value of indent + is a string rather than a boolean, then as defined by the option parameter conventions, + a type error is raised. + If the value is of the correct type, but does not satisfy the rules for that + parameter defined in , then a dynamic error + is raised. (For example, this occurs if the map supplied to + use-character-maps includes a key that is a string whose length is not one (1)).

+

If any serialization error occurs, including the detection of an invalid value for a + serialization parameter as described above, this results in the fn:serialize call failing with + a dynamic error.

+
+ +

One use case for this function arises when there is a need to construct an XML document + containing nested XML documents within a CDATA section (or on occasions within a + comment). See fn:parse-xml for further details.

+

Another use case arises when there is a need to call an extension function that expects + a lexical XML document as input.

+

Another use case for this function is serializing instances of the data model into a human + readable format for the purposes of debugging. Using the by specifying it as the output method defined in the second argument via + output:serialization-parameters, allows for serializing any valid + XDM instance without raising a serialization error.

+

There are also use cases where the application wants to post-process the output of a + query or transformation, for example by adding an internal DTD subset, or by inserting + proprietary markup delimiters such as the <% ... %> used by some + templating languages.

+

The ability to specify the serialization parameters in an output:serialization-parameters + element provides backwards compatibility with the 3.0 version of this specification; the ability to + use a map takes advantage of new features in the 3.1 version. The default parameter values are + implementation-defined when an output:serialization-parameters + element is used (or when the argument is omitted), but are fixed by this specification in the + case where a map (including an empty map) is supplied for the argument.

+
+ + +

Given the variables:

+
+ + +]]> + + ]]> + + +

The following call might produce the output shown:

+
+ + + + ']]> + + + +

The following call would also produce the output shown (though the second argument could equally well be supplied + as an empty map (map{}), since both parameters are given their default values):

+
+ + + + ']]> + + + +

The expression fn:serialize(map{"a":"AB", "b": "BC"}, map{"method":"adaptive"}) returns "map{"a":"AB","b":"BC"}"

+

The expression fn:serialize(array{"a",3, attribute test {"true"}}, map{"method":"adaptive"}) returns "["a",3,test="true"]"

+
+
+
+ + + + + + + + + nondeterministic + context-independent + focus-independent + + +

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

+
+ +

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

+

The method key of $options specifies the parsing algorithm, + application, or library to use to construct the XDM nodes from the parsed HTML document.

+

If the type of $html is an xs:string, the encoding is determined + in a way consistent with section 13.2.3.1, Parsing with a + known character encoding. The specific character encoding is + .

+ +

The HTML specification uses this for when the encoding of the input byte stream is + known for certain, such as when the byte stream has already been decoded.

+

This means that an implementation should set the encoding to the encoding of the + underlying string representation. For example, a Java program could specify the + encoding as UTF-16. If the implementation supports passing native string values + then that can be used instead of using a byte stream and encoding.

+

Be aware that the WHATWG Encoding specification defines the ISO 8859-1 (latin1) + and ASCII encodings as aliases of the windows-1252 encoding.

+
+

If the type of $html is a sequence of octets (xs:hexBinary or + xs:base64Binary), the encoding is determined in a way consistent with + section 13.2.3.2, Determining the character encoding. + The encoding key of $options is used in step 2 as the user + instructing the user agent to override the document’s character encoding with the + specified encoding.

+

For any given method key of $options the implementation must + use a parser and validator consistent with the html-version key of + $options.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Valid method and html version combinations
methodhtml-versionDescription
html3, 3.2, 4, 4.01An parsing algorithm, tree construction, + and validation consistent with the specified HTML version.
html5, 5.0, 5.1, 5.2An HTML5 conformant parsing algorithm, tree construction, and validation consistent + with the specified HTML version. An implementation may choose to use LS + for all these HTML versions.
htmlLSA parsing algorithm, tree construction, and validation consistent with the + .
xhtml1.0, 1.1 +

An implementation may choose to use an XML parser to directly construct the + XDM nodes, and then use an validation + mechanism (such as DTD or XMLSchema) to validate the XHTML DOM tree.

+

An implementation may also choose to use for all these + XHTML versions, or some other HTML parser capable of processing XHTML + documents.

+
** +

An parsing algorithm, tree construction, + and validation consistent with the specified HTML version.

+ +

This allows an implementation to provide their own method, html-version + combinations. For example, an implementation could use the values + "whatwg" and "2023-01-28" for an implementation of the WHATWG HTML Living + Standard at a given date.

+
+
+

The section defines a mapping between the constructed HTML DOM + tree and an XDM tree. It is how this mapping + occurs.

+

The function is not deterministic: + that is, if the function is called twice with the same arguments, it is + whether the same node is returned on both + occasions.

+
+ +

A dynamic error is raised if the content of + $html is not a well-formed HTML document.

+

A dynamic error is raised if the method + key of $options is not supported by the implementation.

+

A dynamic error is raised if a key passed to + $options, or the value of that key, is not supported by the implementation.

+
+ +

If the HTML parser accepts a string as the input then that may be used directly when + $html is an xs:string instead of converting the string to + a sequence of octets in an encoding. The HTML + parser must not perform character encoding processing on that input, treating the HTML + string as being in a known character encoding that matches the encoding of the string.

+

The mapping from the HTML document to the XDM nodes can be done in several ways:

+ + +

An implementation could construct the XDM nodes directly in the HTML tree construction + step of the HTML parsing algorithm.

+
+ +

An implementation could take the DOM tree and interfaces generated by the HTML parser + and adapt those to the XDM accessors. The section defines this + for the specification.

+
+ +

An implementation could traverse the HTML document returned by the parsing algorithm + and create the corresponding XDM nodes.

+
+
+
+ + +

The expression parse-html(()) returns ().

+

The expression parse-html("<p>Hello</p>") returns an XDM + document node for a HTML document with a single paragraph within the body element.

+

The expression parse-html("<p>Hi</p>", method:="html") + is equivalent to parse-html("<p>Hi</p>").

+

The expression parse-html($html, method:="tidy") could use + the tidy application or library to parse $html if supported + by the implementation. Otherwise an error is raised.

+

The expression parse-html($html, method:="tagsoup", nons:=true()) + could use the tagsoup application to parse $html if supported + by the implementation, passing the --nons argument to the application.

+

[TODO: The examples depend on keyword arguments.]

+
+
+ + New in 4.0. Accepted 2023-01-10. + +
+ + + + + + deterministic + context-dependent + focus-dependent + special-streaming-rules + + +

Returns the context position from the dynamic context.

+
+ +

Returns the context position from the dynamic context. (See .)

+
+ +

A dynamic error is raised if + the context item is absent.

+
+
+ + + + + + deterministic + context-dependent + focus-dependent + special-streaming-rules + + +

Returns the context size from the dynamic context.

+
+ +

Returns the context size from the dynamic context. (See .)

+
+ +

A dynamic error is raised if + the context size is absent.

+
+ +

Under most circumstances, the context size is absent only if the context item is absent. However, XSLT 3.0 with + streaming defines situations in which the context item and context position are known, but the context size is unknown.

+
+ + + + (1 to 20)[last() - 1] + 19 + + + +
+ + + + + + deterministic + context-dependent + focus-independent + + +

Returns the current date and time (with timezone).

+
+ +

Returns the current dateTime (with timezone) from the dynamic context. (See .) This is an + xs:dateTime that is current at some time during the evaluation of a + query or transformation in which fn:current-dateTime is executed.

+

This function is . The precise instant during the query + or transformation represented by the value of fn:current-dateTime() is + implementation-dependent.

+

If the implementation supports data types from XSD 1.1 then the returned value will be + an instance of xs:dateTimeStamp. Otherwise, the only guarantees are that it + will be an instance of xs:dateTime and will have a timezone component.

+
+ +

The returned xs:dateTime will always have an associated timezone, which + will always be the same as the implicit timezone in the dynamic context

+
+ + +

fn:current-dateTime() returns an xs:dateTimeStamp + corresponding to the current date and time. For example, a call of + fn:current-dateTime() might return + 2004-05-12T18:17:15.125Z corresponding to the current time on May 12, + 2004 in timezone Z.

+
+
+
+ + + + + + deterministic + context-dependent + focus-independent + + +

Returns the current date.

+
+ +

Returns xs:date(fn:current-dateTime()). This is an xs:date + (with timezone) that is current at some time during the evaluation of a query or + transformation in which fn:current-date is executed.

+

This function is . The precise instant during the query + or transformation represented by the value of fn:current-date is implementation-dependent.

+
+ +

The returned date will always have an associated timezone, which will always be the same + as the implicit timezone in the dynamic context

+
+ + +

fn:current-date() returns an xs:date corresponding to the + current date. For example, a call of fn:current-date() might return + 2004-05-12+01:00.

+
+
+
+ + + + + + deterministic + context-dependent + focus-independent + + +

Returns the current time.

+
+ +

Returns xs:time(fn:current-dateTime()). This is an xs:time + (with timezone) that is current at some time during the evaluation of a query or + transformation in which fn:current-time is executed.

+

This function is . The precise instant during the query + or transformation represented by the value of fn:current-time() is implementation-dependent.

+
+ +

The returned time will always have an associated timezone, which will always be the same + as the implicit timezone in the dynamic context

+
+ + +

fn:current-time() returns an xs:time corresponding to the + current time. For example, a call of fn:current-time() might return + 23:17:00.000-05:00.

+
+
+
+ + + + + + deterministic + context-dependent + focus-independent + + +

Returns the value of the implicit timezone property from the dynamic context.

+
+ +

Returns the value of the implicit timezone property from the dynamic context. Components + of the dynamic context are described in .

+
+
+ + + + + + deterministic + context-dependent + focus-independent + + +

Returns the value of the default collation property from the dynamic context.

+
+ +

Returns the value of the default collation property from the + dynamic context context. Components + of the dynamic context are described in .

+
+ +

The default collation property can never be absent. If it is not explicitly defined, a + system defined default can be invoked. If this is not provided, the Unicode codepoint + collation (http://www.w3.org/2005/xpath-functions/collation/codepoint) is + used.

+

In most cases, the default collation is known statically, + and a call on this function can therefore be pre-evaluated during static analysis. The only + notable exception is when a call on default-collation() is used to define + the default value of a parameter to a user-defined function. In this case it is interpreted + as a reference to the default collation in the context of the relevant function call, + which may differ from the default collation of the function definition.

+
+
+ + + + + + deterministic + context-dependent + focus-independent + + +

Returns the value of the default language property from the dynamic context.

+
+ +

Returns the value of the default language property from the dynamic context. Components + of the dynamic context are described in .

+
+ +

The default language property can never be absent. The functions fn:format-integer, + fn:format-date, fn:format-time, and fn:format-dateTime + are defined to use the default language if no explicit language is supplied. The default language + may play a role in selection of a default collation, but this is not a requirement.

+
+
+ + + + + + deterministic + context-dependent + focus-independent + + +

This function returns the value of the executable base URI property from the dynamic + context.

+
+ +

The function (despite its name) + returns the value of the executable base URI property from the dynamic context. + If the property is absent, the empty sequence is returned.

+

Components of the dynamic context are described in .

+
+ +

The executable base URI will in many cases be the same as the static base URI in the static context. + However, XQuery and XSLT give an implementation freedom to use different base URIs during + the static analysis phase and the dynamic evaluation phase, that is, for retrieval of compile-time + and run-time resources respectively. This is appropriate when the implementation allows + the output of static analysis (a “compiled” query or stylesheet) to be deployed for execution + to a different location from the one where static analysis took place. In this situation, the + fn:static-base-uri function should return a URI suitable for locating + resources needed during dynamic evaluation.

+

If a call on the fn:static-base-uri function appears within the expression used + to define the value of an optional parameter to a user-defined function, then the value supplied + to the function (if the argument is omitted) will be the executable base URI from the dynamic + context of the function caller. This allows such a function to resolve relative URIs supplied + in other parameters to the same function.

+
+
+ + + + + + + + + deterministic + context-dependent + focus-dependent + + special-streaming-rules + + +

Returns a function item having a given name and arity, if there is one.

+
+ +

A call to fn:function-lookup starts by looking for a + function definition + in the named functions component of the dynamic context + (specifically, the dynamic context of the call to fn:function-lookup), + using the expanded QName supplied as $name and the arity supplied as + $arity. There can be at most one such function definition.

+ +

If no function definition can be identified (by name and arity), then an empty sequence + is returned.

+ +

If a function definition is identified, then a function item is obtained from the function + definition using the same rules as for evaluation of a named function reference + (see ). The captured context of + the returned function item (if it is context dependent) is the static and dynamic context of + the call on fn:function-lookup.

+ + +

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

+ + + +
+ + +

This function can be useful where there is a need to make a dynamic decision on which of + several statically known functions to call. It can thus be used as a substitute for + polymorphism, in the case where the application has been designed so several functions + implement the same interface.

+

The function can also be useful in cases where a query or stylesheet module is written + to work with alternative versions of a library module. In such cases the author of the + main module might wish to test whether an imported library module contains or does not + contain a particular function, and to call a function in that module only if it is + available in the version that was imported. A static call would cause a static error if + the function is not available, whereas getting the function using + fn:function-lookup allows the caller to take fallback action in this + situation.

+

If the function that is retrieved by fn:function-lookup is context-dependent, that is, if it has + dependencies on the static or dynamic context of its caller, the context that applies is + the static and/or dynamic context of the call to the fn:function-lookup + function itself. The context thus effectively forms part of the closure of the returned + function. In practice this applies only where the target of + fn:function-lookup is a built-in function, because user-defined + functions never depend on the static or dynamic context of the function call. The rule + applies recursively, since fn:function-lookup is itself a context-dependent + built-in function.

+

However, the static and dynamic context of the call to fn:function-lookup + may play a role even when the selected function definition is not itself context dependent, + if the expressions used to establish default parameter values are context dependent.

+

The function identity is determined in the same way as for + a named function reference. Specifically, if there is no context dependency, two calls + on fn:function-lookup with the same name and arity must return the same function.

+

These specifications do not define any circumstances in which the dynamic context will + contain functions that are not present in the static context, but neither do they rule + this out. For example an API may provide the ability to add functions + to the dynamic context. Equally, these specifications do not define any mechanism for + creating context-dependent functions other than the built-in context-dependent + functions, but neither do they rule out the existence of such functions.

+ +

The mere fact that a function exists and has a name does not of itself mean that the + function is present in the dynamic context. For example, functions obtained through + use of the fn:load-xquery-module function are not added to the dynamic context.

+
+ + + + function-lookup(xs:QName('fn:substring'), 2)('abcd', 2) + 'bcd' + + + +

The expression (fn:function-lookup(xs:QName('xs:dateTimeStamp'), 1), + xs:dateTime#1)[1] ('2011-11-11T11:11:11Z') returns an + xs:dateTime value set to the specified date, time, and timezone; if + the implementation supports XSD 1.1 then the result will be an instance of the + derived type xs:dateTimeStamp. The query is written to ensure that no + failure occurs when the implementation does not recognize the type + xs:dateTimeStamp.

+
+ +

The expression + let $f := function-lookup(xs:QName('zip:binary-entry'), 2) +return if (exists($f)) then $f($href, $entry) else () +returns the result of + calling zip:binary-entry($href, $entry) if the function is available, or + an empty sequence otherwise.

+
+
+
+ + + + + + + + deterministic + context-independent + focus-independent + + + +

Returns the name of the function identified by a function item.

+
+ +

If $function refers to a named function, fn:function-name($func) + returns the name of that function.

+

Otherwise ($function refers to an anonymous function), + fn:function-name($function) returns an empty sequence.

+

The prefix part of the returned QName is implementation-dependent.

+
+ + + + function-name(substring#2) + QName("http://www.w3.org/2005/xpath-functions", "fn:substring") + The namespace prefix of the returned QName is not predictable. + + + + + function-name(function($node) { count($node/*) }) + () + + + + +
+ + + + + + + + deterministic + context-independent + focus-independent + + + +

Returns the arity of the function identified by a function item.

+
+ +

The fn:function-arity function returns the arity (number of arguments) of + the function identified by $function.

+
+ + + + function-arity(substring#2) + 2 + + + + + function-arity(function($node) { name($node) }) + 1 + + + + + let $initial := substring(?, 1, 1) +return function-arity($initial) + 1 + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + + +

Applies the function item $action to every item from the sequence $input + in turn, returning the concatenation of the resulting sequences in order.

+
+ +

The effect of the function is equivalent to the following implementation in XQuery:

+ +

or its equivalent in XSLT:

+ + + + + + +]]> + +
+ +

The function call fn:for-each($SEQ, $F) is equivalent to the expression + for $i in $SEQ return $F($i), assuming that ordering mode is + ordered.

+

See also array:build, which provides similar functionality for the + case where the input is a sequence rather than an array.

+
+ + + + for-each(1 to 5, function($a) { $a * $a }) + (1, 4, 9, 16, 25) + + + + + for-each( + ("john", "jane"), + string-to-codepoints#1 +) + (106, 111, 104, 110, 106, 97, 110, 101) + + + + + for-each(("23", "29"), xs:int#1) + (23, 29) + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + + +

Returns those items from the sequence $input for which the supplied function + $predicate returns true.

+
+ +

The effect of the function is equivalent to the following implementation in XQuery:

+ +

or its equivalent in XSLT:

+ + + + + + +]]> + +
+ +

As a consequence of the function signature and the function calling rules, a type error + occurs if the supplied function $predicate returns anything other than a single + xs:boolean item; there is no conversion to an effective boolean + value.

+
+ +

The function call fn:filter($SEQ, $F) has a very similar effect to the + expression $SEQ[$F(.)]. There are some differences, however. In the case of + fn:filter, the function $F is required to return a boolean; + there is no special treatment for numeric predicate values, and no conversion to an + effective boolean value. Also, with a filter expression $SEQ[$F(.)], the + focus within the predicate is different from that outside; this means that the use of a + context-sensitive function such as fn:lang#1 will give different results in + the two cases.

+
+ + + + filter(1 to 10, function($a) {$a mod 2 = 0}) + (2, 4, 6, 8, 10) + + + + + filter((), lang("en", ?)) + () + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Processes the supplied sequence from left to right, applying the supplied function + repeatedly to each item in turn, together with an accumulated result value.

+
+ +

The effect of the function is equivalent to the following implementation in XQuery:

+ +

or its equivalent in XSLT:

+ + + + + + + + + + + + +]]> + +
+ +

As a consequence of the function signature and the function calling rules, a type error + occurs if the supplied function $action cannot be applied to two arguments, where + the first argument is either the value of $zero or the result of a previous + application of $action, and the second + is any single item from the sequence $input.

+
+ +

This operation is often referred to in the functional programming literature as + “folding” or “reducing” a sequence. It takes a function that operates on a pair of + values, and applies it repeatedly, with an accumulated result as the first argument, and + the next item in the sequence as the second argument. The accumulated result is + initially set to the value of the $zero argument, which is conventionally a + value (such as zero in the case of addition, one in the case of multiplication, or a + zero-length string in the case of string concatenation) that causes the function to + return the value of the other argument unchanged.

+
+ + + + fold-left( + 1 to 5, + 0, + function($a, $b) { $a + $b } +) + 15 + This returns the sum of the items in the sequence + + + + + fold-left( + (2,3,5,7), + 1, + function($a, $b) { $a * $b } +) + 210 + This returns the product of the items in the sequence + + + + + fold-left( + (true(), false(), false()), + false(), + function($a, $b) { $a or $b } +) + true() + This returns true if any item in the sequence has an effective boolean + value of true + + + + + fold-left( + (true(), false(), false()), + false(), + function($a, $b) { $a and $b } +) + false() + This returns true only if every item in the sequence has an effective + boolean value of true + + + + + fold-left( + 1 to 5, + (), + function($a, $b) { $b, $a } +) + (5,4,3,2,1) + This reverses the order of the items in a sequence + + + + + fold-left( + 1 to 5, + "", + concat(?, ".", ?) +) + ".1.2.3.4.5" + + + + + fold-left( + 1 to 5, + "$zero", + concat("$f(", ?, ", ", ?, ")") +) + "$f($f($f($f($f($zero, 1), 2), 3), 4), 5)" + + + + + fold-left( + 1 to 5, + map { }, + function($map, $n) { map:put($map, $n, $n * 2) } +) + map{1:2, 2:4, 3:6, 4:8, 5:10} + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + special-streaming-rules + + +

Processes the supplied sequence from right to left, applying the supplied function + repeatedly to each item in turn, together with an accumulated result value.

+
+ +

The effect of the function is equivalent to the following implementation in XQuery:

+ +

or its equivalent in XSLT:

+ + + + + + + + + + + + +]]> + +
+ +

As a consequence of the function signature and the function calling rules, a type error + occurs if the supplied function $action cannot be applied to two arguments, where + the first argument is any item in the sequence $input, and the second is either + the value of $zero or the result of a previous application of + $action.

+ +
+ +

This operation is often referred to in the functional programming literature as + “folding” or “reducing” a sequence. It takes a function that operates on a pair of + values, and applies it repeatedly, with the next item in the sequence as the first + argument, and the result of processing the remainder of the sequence as the second + argument. The accumulated result is initially set to the value of the $zero + argument, which is conventionally a value (such as zero in the case of addition, one in + the case of multiplication, or a zero-length string in the case of string concatenation) + that causes the function to return the value of the other argument unchanged.

+

In cases where the function performs an associative operation on its two arguments (such + as addition or multiplication), fn:fold-right produces the same result as + fn:fold-left.

+
+ + + + fold-right( + 1 to 5, + 0, + function($a, $b) { $a + $b } +) + 15 + This returns the sum of the items in the sequence + + + + + fold-right( + 1 to 5, + "", + concat(?, ".", ?) +) + "1.2.3.4.5." + + + + + fold-right( + 1 to 5, + "$zero", + concat("$f(", ?, ", ", ?, ")") +) + "$f(1, $f(2, $f(3, $f(4, $f(5, $zero)))))" + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Processes a supplied value repeatedly, continuing while some condition remains true, + and returning the first value that does not satisfy the condition.

+
+ +

Informally, the function behaves as follows:

+ + +

The supplied $input value is tested against the supplied + $predicate.

+
+ +

If the result of the predicate is true, $action($input) + is evaluated, the resulting value is used as a new $input, and the + process repeats from step 1.

+
+ +

If the result of the predicate is false, the function returns the + value of $input.

+
+
+

More formally, the function is equivalent to the following implementation in XQuery:

+ +
+ +

While-loops are very common in procedural programming languages, and this function + provides a way to write functionally clean and interruptible iterations without + side-effects. An initial value is tested and replaced by new values until it matches + a given condition. Depending on the use case, the value can be a simple atomic item + or an arbitrarily complex data structure.

+

Note that, just as when writing recursive functions, it is easy to construct infinite + loops.

+
+ + + + + 256 + + + + + + 5 + This returns the first positive number missing in a sequence. + + + + + + (5, 6, 7, 8, 9) + The first number of a sequence is removed as long as it is smaller than 5. + + + + + = 0.0000000001 }, + function($guess) { ($guess + $input div $guess) div 2 } +) => round(5)]]> + 1984 + This computes the square root of a number. + + + +

The following example generates random doubles. It is interrupted once a number + exceeds a given limit:

+ +
+
+ + New in 4.0. Approved. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Applies the function item $action to successive pairs of items taken one from + $input1 and one from $input2, returning the concatenation of the + resulting sequences in order.

+
+ +

The effect of the function is equivalent to the following implementation in XQuery:

+ +

or its equivalent in XSLT:

+ + + + + + + + +]]> + +
+ +

If one sequence is longer than the other, excess items in the longer sequence are ignored.

+
+ + + + for-each-pair( + ("a", "b", "c"), + ("x", "y", "z"), + concat#2 +) + ("ax", "by", "cz") + + + + + + for-each-pair( + 1 to 5, + 1 to 5, + function($a, $b) { 10 * $a + $b } +) + (11, 22, 33, 44, 55) + + + + + let $s := 1 to 8 +return for-each-pair($s, tail($s), function($a, $b) { $a * $b }) + (2, 6, 12, 20, 30, 42, 56) + + + +
+ + + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + + + + +

Sorts a supplied sequence, based on the value of a sort key supplied as a function.

+
+ +

Calling the single-argument version of the function is equivalent to calling the two-argument form + with default-collation() as the second argument: that is, it sorts a sequence of items according + to the typed value of the items, using the default collation to compare strings.

+ +

Calling the two-argument version of the function is equivalent to calling the three-argument form + with fn:data#1 as the third argument: that is, it sorts a sequence of items according + to the typed value of the items, using a specified collation to compare strings.

+ +

In the case of both fn:sort#2 and fn:sort#3, supplying an empty + sequence as the second argument is equivalent to supplying fn:default-collation(). For more + information on collations see .

+ +

The result of the function is obtained as follows:

+ + +

For each item in the sequence $input, the function supplied as $key + is evaluated with that item as its argument. + The resulting values are the sort keys of the items in the input sequence. +

+
+ +

The result sequence contains the same items as the input sequence $input, but generally in a different order.

+
+ +

Let $C be the selected collation, or the default collation where applicable.

+
+ +

The order of items in the result is such that, given two items $A and $B:

+ +

Let $REL be the result of evaluating op:lexicographic-compare($key($A), $key($B), $C) + where op:lexicographic-compare($a, $b, $C) is defined as follows:

+ if (empty($a) and empty($b)) then 0 +else if (empty($a)) then -1 +else if (empty($b)) then +1 +else let $rel = op:simple-compare(head($a), head($b), $C) + return if ($rel eq 0) + then op:lexicographic-compare(tail($a), tail($b), $C) + else $rel +
+

Here op:simple-compare($k1, $k2) is defined as follows:

+ if ($k1 instance of union(xs:string, xs:anyURI, xs:untypedAtomic) + and $k2 instance of union(xs:string, xs:anyURI, xs:untypedAtomic)) + then compare($k1, $k2, $C) + else if ($k1 eq $k2 or (is-NaN($k1) and is-NaN($k2))) then 0 + else if (is-NaN($k1) or $k2 lt $k2) then -1 + else +1 +

This raises an error if two keys are not comparable, for example + if one is a string and the other is a number, or if both belong to a non-ordered + type such as xs:QName.

+
+ +
+
+ +

If $REL eq 0, then the relative order of $A and $B + in the output is the same as their relative order in the input (that is, the sort is stable) +

+
+ +

Otherwise, if $REL lt 0, then $A precedes $B in the output. +

+
+
+
+ +

If the set of computed sort keys contains values that are not comparable using the lt operator then the sort + operation will fail with a type error (). +

+
+ +

XSLT and XQuery both provide native sorting capability, but previous releases of XPath provided no sorting functionality + for use in standalone environments.

+

In addition there are cases where this function may be more flexible than the built-in sorting capability for XQuery or XSLT, + for example when the sort key or collation is chosen dynamically, or when the sort key is a sequence of items rather than a single + item.

+

The results are compatible with the results of XSLT sorting (using xsl:sort) in the case where the sort key evaluates to a sequence of + length zero or one, given the options stable="yes" and order="ascending".

+

The results are compatible with the results of XQuery sorting (using the order by clause) in the case where the sort key evaluates to a sequence of + length zero or one, given the options stable, ascending, and empty least.

+
+ + + + sort((1, 4, 6, 5, 3)) + (1, 3, 4, 5, 6) + + + sort((1, -2, 5, 10, -10, 10, 8), (), abs#1) + (1, -2, 5, 8, 10, -10, 10) + + + +

To sort a set of strings $in using Swedish collation:

+ +let $SWEDISH := "http://www.w3.org/2013/collation/UCA?lang=se" +return sort($in, $SWEDISH) + +
+ +

To sort a sequence of employees by last name as the major sort key and first name as the minor sort key, + using the default collation: +

+ sort($employees, (), function($emp) {$emp/name ! (last, first)}) +
+
+
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Given a function F that navigates from one node to other nodes, + returns a function that applies F repeatedly.

+
+ + +

The argument is a function $step that takes a single node as input, and returns a set of nodes as its result. + The result of the fn:transitive-closure function is a function TC that takes a + single node N as input, and returns all nodes that can be reached from + N by applying $step repeatedly between $min and $max times (inclusive).

+ +

Although $step may return any sequence of nodes, the result is treated as a set: the order of nodes + in the sequence is ignored, and duplicates are ignored. The result of calling TC will always be + a sequence of nodes in document order with no duplicates.

+ +

The default value of $min, if the argument is not supplied or is set to an empty sequence, + is 1 (one). If $min is zero, the result of calling TC will include the argument node + N. If $min is greater than zero, the result will include N only if + N is reachable by a cyclic path involving between $min and $max steps.

+ +

The default value of $max, if the argument is not supplied or is set to an empty sequence, + is unbounded. In this situation the function TC continues execution until no further nodes + are added to the result set. Note that if the $step function constructs new nodes, this + can lead to non-termination. Specifying an explicit value for $max guarantees termination.

+ + + +
+ +

Cycles in the data are not a problem, even if $max is unbounded; + the function stops searching when it finds no new nodes.

+
+ + + + + + + + + + + +}]]> + + + + + + let $tc := transitive-closure($direct-reports) +return $tc($data//person[@id="2"])/string(@id) + ("3", "4", "6", "7", "8") + + + let $tc := transitive-closure($direct-reports, min:=0) +return $tc($data//person[@id="2"])/string(@id) + ("2", "3", "4", "6", "7", "8") + + + let $tc := transitive-closure($direct-reports, max:=2) +return $tc($data//person[@id="2"])/string(@id) + ("3", "4", "6") + + + let $tc := transitive-closure(function { child::* }) +return $tc($data)/@id/string() + ("0", "1", "2", "3", "4", "5", "6", "7","8") + The transitive closure of the child axis is the ancestor axis + if min=1, or the ancestor-or-self axis if min=0. + + + +

The following example, given $root as the root of an XSLT stylesheet module, returns the URIs + of all stylesheet modules reachable using xsl:import and xsl:include declarations:

+ let $tc := transitive-closure(function { document(//(xsl:import|xsl:include)/@href) }) +return $tc($root) =!> document-uri() +

This example uses the XSLT-defined document() function.

+
+ +

The following example, given $doc as the root of a document consisting of nested sections with paths + such as article/section/section/section, returns the headings of all level-2 and level-3 sections:

+ let $tc := transitive-closure(function { child::section }, min:=2, max:=3) +return $tc($doc/article)/head +
+
+
+ + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Makes a dynamic call on a function with an argument list supplied in the form of an array.

+
+ +

The result of the function is obtained by invoking the supplied function $function with arguments + taken from the members of the supplied array $arguments. The first argument of the function call is the first + member of $arguments, the second argument is the second member of $array, and so on.

+

The arity of the supplied function $function must be the same as the size of the array $array.

+

The effect of calling fn:apply($f, [$a, $b, $c, ...]) is the same as the effect of the dynamic function call + $f($a, $b, $c, ....). For example, the function conversion rules are applied to the supplied arguments + in the usual way.

+
+ +

A dynamic error is raised if the arity of the function $function is not the same as the size of the + array $array (). +

+
+ +

The function is useful where the arity of a function item is not known statically.

+
+ + + + apply(concat#3, ["a", "b", "c"]) + "abc" + + + +

The expression apply($f, array:subarray(["a", "b", "c", "d", "e", "f"], 1, function-arity($f))) + calls the supplied function $f supplying the number of arguments required by its arity.

+
+
+
+ + + + + + + + + deterministic + context-independent + focus-independent + + + +

Returns a function whose effect is to apply a supplied binary operator to two arguments.

+
+ +

The supplied operator must be one of:

+

",", "and", "or", "+", + "-", "*", "div", "idiv", + "mod", "=", "<", "<=", + ">", ">=", "!=", "eq", + "lt", "le", "gt", "ge", + "ne", "<<", ">>", + "is", "||", "|", "union", + "except", "intersect", "to", + "otherwise"

+

The result of calling fn:op("⊙"), where is one of the above operators, is + the function represented by the XPath expression:

+

function($x, $y) { $x ⊙ $y }

+

For example, op("+") returns function($x, $y) { $x + $y }.

+
+ +

A dynamic error is raised if the supplied argument is not one of the supported operators ([TODO: error code]). +

+
+ +

The function is useful in contexts where an arity-2 callback function needs to be supplied, and + a standard operator meets the requirement.

+

For example, the XSLT xsl:map instruction + has an on-duplicates attribute that expects such a function. Specifying + on-duplicates="op(',')" is equivalent to specifying + on-duplicates="function($x, $y) { $x, $y }

+

The function is also useful in cases where the choice of operator to apply is + made dynamically.

+
+ + + + for-each-pair(21 to 25, 1 to 5, op("+")) + 22, 24, 26, 28, 30 + + + + + for-each-pair(21 to 25, 1 to 5, op("-")) + 20, 20, 20, 20, 20 + + + + + New in 4.0. Accepted 2022-10-11. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Determines whether two atomic values are equal, under the rules used for comparing keys in a map.

+
+ +

The function fn:atomic-equal is used to compare two atomic values for equality. This function + has the following properties (which do not all apply to the eq operator):

+ +

Any two atomic values can be compared, regardless of their type.

+

No dynamic error is ever raised (the result is either true or false).

+

The result of the comparison never depends on the static or dynamic context.

+

Every value (including NaN) is equal to itself.

+

The comparison is symmetric: if A equals B, then B equals A.

+

The comparison is transitive: if A equals B and B equals C, + then A equals C.

+
+ +

The function returns true if and only if one of the following conditions is true:

+ + + +

All of the following conditions are true:

+ + +

$value1 is an instance of xs:string, xs:anyURI, or xs:untypedAtomic

+
+ +

$value2 is an instance of xs:string, xs:anyURI, or xs:untypedAtomic

+
+ +

+ fn:codepoint-equal($value1, $value2) +

+
+
+ +

Strings are compared without any dependency on collations.

+
+
+ +

All of the following conditions are true:

+ + +

$value1 is an instance of xs:decimal, xs:double, or xs:float

+
+ +

$value2 is an instance of xs:decimal, xs:double, or xs:float

+
+ +

One of the following conditions is true:

+ + +

Both $value1 and $value2 are NaN

+ +

xs:double('NaN') is the same key as xs:float('NaN')

+
+
+ +

Both $value1 and $value2 are positive infinity

+ +

xs:double('INF') is the same key as xs:float('INF')

+
+
+ +

Both $value1 and $value2 are negative infinity

+ +

xs:double('-INF') is the same key as xs:float('-INF')

+
+
+ +

$value1 and $value2 when converted to decimal numbers with no rounding or loss of precision + are mathematically equal.

+ +

Every instance of xs:double, xs:float, and xs:decimal can be represented + exactly as a decimal number provided enough digits are available both before and after the decimal point. Unlike the eq + relation, which converts both operands to xs:double values, possibly losing precision in the process, this + comparison is transitive.

+
+ +

Positive and negative zero compare equal.

+
+
+
+
+
+ +
+ + +

All of the following conditions are true:

+ + +

$value1 is an instance of xs:date, xs:time, xs:dateTime, + xs:gYear, xs:gYearMonth, xs:gMonth, xs:gMonthDay, or xs:gDay

+
+ +

$value2 is an instance of xs:date, xs:time, xs:dateTime, + xs:gYear, xs:gYearMonth, xs:gMonth, xs:gMonthDay, or xs:gDay

+
+ +

One of the following conditions is true:

+ + +

Both $value1 and $value2 have a timezone

+
+ +

Neither $value1 nor $value2 has a timezone

+
+
+
+ +

+ fn:deep-equal($value1, $value2) +

+ +

The use of deep-equal rather than eq ensures that comparing values of different + types yields false rather than an error.

+
+
+ +
+ +
+ + +

All of the following conditions are true:

+ + +

$value1 is an instance of xs:boolean, xs:hexBinary, xs:base64Binary, + xs:duration, xs:QName, or xs:NOTATION

+
+ +

$value2 is an instance of xs:boolean, xs:hexBinary, xs:base64Binary, + xs:duration, xs:QName, or xs:NOTATION

+
+ +

+ fn:deep-equal($value1, $value2) +

+ +

The use of deep-equal rather than eq ensures that comparing values of different + types yields false rather than an error.

+
+
+
+
+
+ +
+ + +

The internal function op:same-key was introduced in an earlier version of this specification + for comparing keys within a map. + In this version of the specification, the functionality is unchanged, but the function is exposed so that it + is available directly to applications.

+ +

The function is used to assess whether two atomic + values are considered to be duplicates when used as keys in a map. A map cannot + contain two separate entries whose keys are the same as defined by this function. + The function is also used when matching keys in functions such as map:get + and map:remove.

+ +

The rules for comparing keys in a map are chosen to ensure that the comparison is:

+ + +

Context-free: there is no dependency on the static or dynamic context

+
+ +

Error-free: any two atomic values can be compared, and the result is either true or false, never an error

+
+ +

Transitive: if A is the same key as B, and B is the same key as C, + then A is the same key as C.

+
+
+

Two atomic values may be distinguishable even though they are equal under this comparison. For example: they may have + different type annotations; dates and times may have different timezones; xs:QName values may have different + prefixes.

+

As always, any algorithm that delivers the right result is acceptable. For example, when testing whether an xs:double + value D is the same key as an xs:decimal value that has N significant digits, it is not + necessary to know all the digits in the decimal expansion of D to establish the result: computing the first N+1 + significant digits (or indeed, simply knowing that there are more than N significant digits) is sufficient.

+
+ + + + atomic-equal(3, 3) + true() + + + atomic-equal(3, 3e0) + true() + + + atomic-equal(xs:double('NaN'), xs:float('NaN')) + true() + + + atomic-equal("a", "a") + true() + + + atomic-equal("a", "A") + false() + + + atomic-equal("a", xs:untypedAtomic("a")) + true() + + + atomic-equal( + "https://www.w3.org/", + xs:anyURI("https://www.w3.org/") +) + true() + + + atomic-equal(12, "12") + false() + + + + + Proposed for 4.0; the function is identical to the internal op:same-key + function in 3.1 + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a map that combines the entries from a number of existing maps.

+
+ +

The function map:merge + returns a map that + is formed by combining the contents of the maps supplied in the $maps + argument.

+ + +

Informally, the supplied maps are combined as follows:

+ + + +

There is one entry in the returned map for each distinct key present in the union + of the input maps, where two keys are distinct if they are not the same key.

+
+ +

If there are duplicate keys, that is, if two or more maps contain entries having the + same key, then the way this is handled is + controlled by the second ($options) argument.

+
+
+ + +

The definitive specification is as follows.

+ + + +

The effect of calling the single-argument function is the same as the effect of + calling the two-argument function with an empty map as the value of $options.

+
+ +

The $options argument can be used to control the way in which duplicate keys are handled. + The option parameter conventions apply. +

+
+ +

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

+ + + + Determines the policy for handling duplicate keys: specifically, the action to be + taken if two maps in the input sequence $maps contain entries with key values + K1 and K2 where K1 and K2 are the + same key. + + xs:string + use-first + + + An error is raised if duplicate keys are encountered. + + + If duplicate keys are present, all but the first of a set of duplicates are ignored, + where the ordering is based on the order of maps in the $maps argument. + + + If duplicate keys are present, all but the last of a set of duplicates are ignored, + where the ordering is based on the order of maps in the $maps argument. + + + If duplicate keys are present, all but one of a set of duplicates are ignored, + and it is implementation-dependent + which one is retained. + + + If duplicate keys are present, the result map includes an entry for the key whose + associated value is the sequence-concatenation of all the values associated with the key, + retaining order based on the order of maps in the $maps argument. + The key value in the result map that corresponds to such a set of duplicates must + be the same key as each of the duplicates, but it is + otherwise unconstrained: for example if the duplicate keys are xs:byte(1) + and xs:short(1), the key in the result could legitimately be xs:long(1). + + + + + + +
+
+

The result of the function call map:merge($MAPS, $OPTIONS) + is defined to be consistent with the result of the expression:

+ + + + +

By way of explanation, $combine-maps is a function that combines + two maps by iterating over the keys of the second map, adding each key and its corresponding + value to the first map as it proceeds. The second call of fn:fold-left + in the return clause then iterates over the maps supplied in the call + to map:merge, accumulating a single map that absorbs successive maps + in the input sequence by calling $combine-maps.

+ + +

This algorithm processes the supplied maps in a defined order, but processes the keys within + each map in implementation-dependent order.

+ +

The use of fn:random-number-generator represents one possible conformant + implementation for "duplicates":"use-any", but it is not the only conformant + implementation and is not intended to be a realistic implementation. The purpose of this + option is to allow the implementation to use whatever strategy is most efficient; for example, + if the input maps are processed in parallel, then specifying "duplicates":"use-any" + means that the implementation does not need to keep track of the original order of the sequence of input + maps.

+ +
+ + +
+ +

An error is raised if the value of + $options indicates that duplicates are to be rejected, and a duplicate key is encountered.

+

An error is raised if the value of + $options includes an entry whose key is defined + in this specification, and whose value is not a permitted value for that key.

+
+ + +

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

+

If the input is a sequence of length one, the result map is + indistinguishable from the supplied map.

+

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

+
+ + + + + map:merge(()) + map{} + Returns an empty map + + + map:merge(( + map:entry(0, "no"), + map:entry(1, "yes") +)) + map{0:"no", 1:"yes"} + Returns a map with two entries + + + map:merge(( + ($week, map { 7: "Unbekannt" }) +) + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", + 5:"Freitag", 6:"Samstag", 7:"Unbekannt"} + The value of the existing map is unchanged; the returned map + contains all the entries from $week, supplemented with an additional + entry. + + + map:merge( + ($week, map { 6: "Sonnabend" }), + map { "duplicates": "use-last" } +) + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", + 5:"Freitag", 6:"Sonnabend"} + The value of the existing map is unchanged; the returned map + contains all the entries from $week, with one entry replaced by a + new entry. Both input maps contain an entry with the key 6; the + one used in the result is the one that comes last in the input + sequence. + + + map:merge( + ($week, map { 6: "Sonnabend" }), + map { "duplicates": "use-first" } +) + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", + 5:"Freitag", 6:"Samstag"} + The value of the existing map is unchanged; the returned map + contains all the entries from $week, with one entry replaced by a + new entry. Both input maps contain an entry with the key 6; the + one used in the result is the one that comes first in the input + sequence. + + + map:merge( + ($week, map { 6: "Sonnabend" }), + map { "duplicates": "combine" } +) + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", + 5:"Freitag", 6:("Samstag", "Sonnabend")} + The value of the existing map is unchanged; the returned map + contains all the entries from $week, with one entry replaced by a + new entry. Both input maps contain an entry with the key 6; the + entry that appears in the result is the sequence-concatenation of the entries + in the input maps, retaining order. + + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a map that combines data from a sequence of + key-value pair maps.

+
+ + +

The function map:of-pairs + returns a map that + is formed by combining key-value pair maps supplied in the + $key-value-pairs + argument.

+ +

The optional $combine argument can be used to define how + duplicate keys should be handled. The default is to form the sequence concatenation + of the corresponding values, retaining their order in the input sequence.

+ +

The effect of the function is equivalent to the expression:

+ map:build($key-value-pairs, fn($kvp) { $kvp?key }, fn($kvp) { $kvp?value }, $combine) + + +
+ +

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

+
+ + +

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

+

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

+
+ + + + + map:of-pairs(()) + map{} + Returns an empty map + + + map:of-pairs(map:pairs($week)) + $week + The function map:of-pairs is the inverse of + map:pairs. + + + + map{0:"no", 1:"yes"} + Returns a map with two entries + + + map:of-pairs(( + map:pairs($week), + map { "key": 7, "value": "Unbekannt" } +)) + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", + 5:"Freitag", 6:"Samstag", 7:"Unbekannt"} + The value of the existing map is unchanged; the returned map + contains all the entries from $week, supplemented with an additional + entry. + + + map:of-pairs(( + map:pairs($week), + map { "key": 6, "value": "Sonnabend" } +)) + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", + 5:"Freitag", 6:("Samstag", "Sonnabend")} + The value of the existing map is unchanged; the returned map + contains all the entries from $week, with one entry replaced by a + new entry. Both input maps contain an entry with the key 6; the + one used in the result combines the two supplied values into a single sequence. + + + map:of-pairs( + (map:pairs($week), + map { "key": 6, "value": "Sonnabend" }), + function($old, $new) { $new } +) + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", + 5:"Freitag", 6:"Sonnabend"} + The value of the existing map is unchanged; the returned map + contains all the entries from $week, with one entry replaced by a + new entry. Both input maps contain an entry with the key 6; the + supplied $combine function ensures that the one used in the result + is the one that comes last in the input sequence. + + + map:of-pairs( + (map:pairs($week), + map { "key": 6, "value": "Sonnabend" }), + function($old, $new) { `{$old}|{$new}` } +) + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", + 5:"Freitag", 6:"Samstag|Sonnabend"} + In the result map, the value for key 6 is obtained by concatenating the values + from the two input maps, with a separator character. + + + + + +
+ + + + + + + + + + nondeterministic-wrt-ordering + context-independent + focus-independent + + +

Returns a sequence containing keys present in a map

+
+ +

The function map:keys takes any map + as its $map argument. The $predicate function, if + supplied, takes the value of the corresponding map entry as an argument, and the + result is a sequence containing the keys of those entries for which the function + returns true in implementation-dependent order.

+

The function is non-deterministic with respect to ordering + (see ). This means that two calls with the same argument + are not guaranteed to produce the results in the same order.

+

More formally, the function returns the result of the following expression:

+ +map:for-each( + $map, + function($key, $value) { + if($predicate($value)) { $key } + } +) + +
+ + + + map:keys(map{1:"yes", 2:"no"}) + (1,2) + The result is in implementation-dependent order. + + + + + +let $numbers := map { + 0: 'zero', + 1: 'one', + 2: 'two', + 3: 'three' +} +return map:keys($numbers, function { . = ('two', 'three') }) + + (2, 3) + + + + + +let $square := map:merge( + (1 to 5) ! map:entry(., . * .) +) +return map:keys($square, function { . > 5 and . < 20 }) + + (3, 4) + + + + + +let $birthdays := map { + 'jack': xs:date('1980-12-31'), + 'joel': xs:date('1969-11-10'), + 'john': xs:date('2001-05-05') +} +return map:keys($birthdays, function($date) { + year-from-date($date) = 1969 +}) + + "joel" + + + +
+ + + + + + + + + nondeterministic-wrt-ordering + context-independent + focus-independent + + +

Returns a sequence containing all the values present in a map, in unpredictable order.

+
+ +

The function map:values takes any map + as its $map argument and returns the values that are present in the map as + a sequence, in implementation-dependent order.

+

The function is non-deterministic with respect to ordering + (see ). This means that two calls with the same argument + are not guaranteed to produce the results in the same order.

+

The effect of the function is equivalent to map:for-each($map, fn($k, $v) { $v }).

+
+ + + + map:values( + map{ 1: "yes", 2: "no" } +) + ("yes", "no") + The result is in implementation-dependent order. + + + map:values( + map { + 1: ("red", "green"), + 2: ("blue", "yellow"), + 3:() + } +) + ("red", "green", "blue", "yellow") + The result is in implementation-dependent order. + + + +
+ + + + + + + + + nondeterministic-wrt-ordering + context-independent + focus-independent + + +

Returns a sequence containing all the key-value pairs present in a map, each represented + as a .

+
+ +

The function map:entries takes any map + as its $map argument and returns the key-value pairs that are present in the map as + a sequence of singleton maps, in implementation-dependent order.

+ +

The function is non-deterministic with respect to ordering + (see ). This means that two calls with the same argument + are not guaranteed to produce the results in the same order.

+

The effect of the function is equivalent to the expression:

+ map:for-each($map, fn($k, $v) { map { $k: $v } }) +
+ + + + map:entries( + map { 1: "yes", 2: "no" } +) + (map{1:"yes"}, map{2:"no"}) + The result sequence is in implementation-dependent order. + + + +
+ + + + + + + + + nondeterministic-wrt-ordering + context-independent + focus-independent + + +

Returns a sequence containing all the key-value pairs present in a map, each represented + as a .

+
+ +

The function map:pairs takes any map + as its $map argument and returns the keys that are present in the map as + a sequence of key-value pair maps, in implementation-dependent order.

+

A key-value pair map is an instance of type record(key as xs:anyAtomicType, value as item()*): + that is a map with two entries, one (with key "key") holding the key, + and the other (with key "value") holding the value.

+

The function is non-deterministic with respect to ordering + (see ). This means that two calls with the same argument + are not guaranteed to produce the results in the same order.

+

The effect of the function is equivalent to the expression:

+ map:for-each($map, fn($k, $v) { map { "key": $k, "value": $v } }) +
+ + + + map:pairs( + map { 1: "yes", 2: "no" } +) + (map{"key":1, "value":"yes"}, map{"key":2, "value":"no"}) + The result is in implementation-dependent order. + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Tests whether a supplied map contains an entry for a given key

+
+ +

The function map:contains returns true if the map supplied as $map contains an entry with the same key as $key; otherwise it returns false.

+
+ + + + + + map:contains($week, 2) + true() + + + map:contains($week, 9) + false() + + + map:contains(map{}, "xyz") + false() + + + map:contains(map{"xyz":23}, "xyz") + true() + + + map:contains(map{"abc":23, "xyz":()}, "xyz") + true() + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the value associated with a supplied key in a given map.

+
+ +

The function map:get attempts to find an entry within the map supplied as $map that has + the same key as $key. If there is such an entry, it returns the associated value; + if not, it invokes the supplied $fallback function, supplying + the requested $key value as the argument, and returns the result of this call. + The default $fallback function always returns an empty sequence.

+ +
+ +

A return value of () from map:get could indicate that + the key is present in the map with an associated value of (), or it could + indicate that the key is not present in the map. The two cases can be distinguished by + calling map:contains, or by using + a $fallback function to return a value known never to appear in the map.

+ +

The $fallback function can be used in a number of ways:

+ + +

It might return a conventional value such as NaN to indicate that no matching + key was found.

+

It might raise a dynamic error, by means of a call on fn:error.

+

It might compute a result algorithmically. For example, if the map holds a table of + abbreviations, such as map{'CA':'Canada', 'UK':'United Kingdom', 'US':'United States'}, + then specifying fallback := fn:identity#1 has the effect that the key value is returned + unchanged if it is not found in the map.

+
+ +

Invoking the map as a function item has the same effect + as calling get with no $fallback + function: that is, when $map is a map, the expression + $map($K) is equivalent to map:get($map, $K). Similarly, the + expression map:get(map:get(map:get($map, 'employee'), 'name'), 'first') can + be written as $map('employee')('name')('first').

+ +
+ + + + + map:get($week, 4) + "Donnerstag" + + + map:get($week, 9) + () + When the key is not present, the function returns an empty + sequence. + + + map:get(map:entry(7,()), 7) + () + An empty sequence as the result can also signify that the key is + present and the associated value is an empty sequence. + + + map { 1: "single", 2: "double", 3: "triple" } +=> map:get(10, function { . || "-fold" }) + "10-fold" + The map holds special cases; the fallback function handles other cases. + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

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

+
+ +

The function map:find searches the sequence supplied as $input + looking for map entries whose key is the same key + as $key. The associated value in any such map entry (each being in general a sequence) + is returned as a member of the result array.

+ +

The search processes the $input sequence using the following recursively defined rules + (any equivalent algorithm may be used provided it delivers + the same result, respecting those rules that constrain the order of the result):

+ + + +

To process a sequence, process each of its items in order.

+
+ +

To process an item that is an array, process each of its members in order + (each member is, in general, a sequence).

+
+ +

To process an item that is a map, then for each key-value entry (K, V) + in the map (in implementation-dependent order) + perform both of the following steps, in order:

+ + +

If K is the same key as $key, + then add V as a new member to the end of the result array.

+
+ +

Process V (which is, in general, a sequence).

+
+
+
+ +

To process an item that is neither a map nor an array, do nothing. (Such items are ignored).

+
+
+ +
+ +

If $input is an empty sequence, map, or array, or if the requested $key is not found, + the result will be a zero-length array.

+ +
+ + + + + map:find($responses, 0) + ['no', 'non', 'nein'] + + + map:find($responses, 1) + ['yes', 'oui', ('ja', 'doch')] + + + map:find($responses, 2) + [] + + + + + + + map:find($inventory, "parts") + [[map{"name":"engine", "id":"YW678", "parts":[]}], []] + + + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + +

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

+
+ +

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

+ +

The effect of the function call map:put($MAP, $KEY, $VALUE) is equivalent + to the result of the following steps:

+ + + +

+ let $MAP2 := map:remove($MAP, $KEY) +

+

This returns a map in which all entries with the same key as $KEY have been removed.

+
+ +

Construct and return a map containing:

+ + +

All the entries (key/value pairs) in $MAP2, and

+
+ +

The entry map:entry($KEY, $VALUE)

+
+
+
+
+ +
+ + +

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

+ +
+ + + + + + map:put($week, 6, "Sonnabend") + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", + 5:"Freitag", 6:"Sonnabend"} + + + map:put($week, -1, "Unbekannt") + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", + 5:"Freitag", 6:"Samstag", -1:"Unbekannt"} + + + +
+ + + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a that + represents a single key-value pair.

+
+ +

The function map:entry returns a map which contains a single + entry. The key of the entry in the new map is + $key, and its associated value is $value.

+ + +
+ +

The function call map:entry(K, V) produces the same result as the + expression map{K : V}.

+

The function map:entry is intended primarily for use in conjunction with + the function map:merge. For example, a map containing seven entries may be + constructed like this:

+ + +

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

+ +
+ + + + map:entry("M", "Monday") + map{"M":"Monday"} + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a that + represents a single key-value pair.

+
+ +

The function map:pair returns a map which contains two entries, one (with the key "key") + containing $key and the other (with the key "value") + containing $value.

+
+ +

The function call map:pair(K, V) produces the same result as the + expression map { "key": K, "value": V }.

+

The function map:pair is intended primarily for use in conjunction with + the function map:of-pairs. A map may be constructed like this:

+ + +

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

+ +
+ + + + map:pair("M", "Monday") + map { "key": "M", "value": "Monday" } + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

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

+
+ +

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

+

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

+

The effect of the function call map:remove($MAP, $KEY) can be described more formally as the result of the expression below:

+ + +
+ + + + + + map:remove($week, 4) + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 5:"Freitag", + 6:"Samstag"} + + + map:remove($week, 23) + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", + 5:"Freitag", 6:"Samstag"} + + + map:remove($week, (0, 6 to 7)) + map{1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", 5:"Freitag"} + + + map:remove($week, ()) + map{0:"Sonntag", 1:"Montag", 2:"Dienstag", 3:"Mittwoch", 4:"Donnerstag", 5:"Freitag", + 6:"Samstag"} + + + +
+ + + + + + + + + nondeterministic-wrt-ordering + context-independent + focus-independent + + + +

Applies a supplied function to every entry in a map, returning the concatenation of the + results.

+
+ +

The function map:for-each takes any map as its $map argument and applies the supplied function + to each entry in the map, in implementation-dependent order; the result is the sequence obtained by + concatenating the results of these function calls.

+

The function is non-deterministic with respect to ordering + (see ). This means that two calls with the same arguments + are not guaranteed to process the map entries in the same order.

+

The function supplied as $action takes two arguments. It is called + supplying the key of the map entry as the first argument, and the associated value as + the second argument.

+
+ + + + map:for-each( + map { 1: "yes", 2: "no" }, + function($k, $v) { $k } +) + (1,2) + This function call is equivalent to calling map:keys. The + result is in implementation-dependent order. + + + distinct-values( + map:for-each( + map { 1: "yes", 2: "no" }, + function($k, $v) { $v } + ) +) + ("yes", "no") + This function call returns the distinct values present in the map, in + implementation-dependent order. + + + map:merge( + map:for-each( + map { "a": 1, "b": 2 }, + function($k, $v) { map:entry($k, $v + 1) } + ) +) + map{"a":2, "b":3} + This function call returns a map with the same keys as the input map, + with the value of each entry increased by one. + + + + +

This XQuery example converts the entries in a map to attributes on a newly constructed + element node:

+ + { + map:for-each($dimensions, function($k, $v) { attribute { $k } { $v } }) +}]]> + +

The result is the element <box height="3" width="4" + depth="5"/>.

+
+
+
+ + + + + + + + + + context-independent + focus-independent + + + +

Selects entries from a map, returning a new map.

+
+ +

The function map:filter takes any map as its $map argument and applies the supplied function + to each entry in the map; the result is a new map containing those entries for which + the function returns true.

+ +

The function supplied as $predicate takes two arguments. It is called + supplying the key of the map entry as the first argument, and the associated value as + the second argument.

+
+ + + + map:filter( + map { 1: "Sunday", 2: "Monday", + 3: "Tuesday", 4:"Wednesday", + 5: "Thursday", 6: "Friday", + 7: "Saturday" }, + function($k, $v) { $k = (1, 7) } +) + map{1:"Sunday", 7:"Saturday"} + + + map:filter( + map { 1: "Sunday", 2: "Monday", + 3: "Tuesday", 4: "Wednesday", + 5: "Thursday", 6:"Friday", + 7:"Saturday" }, + function($k, $v) { $v = ("Saturday", "Sunday") } +) + map{1:"Sunday", 7:"Saturday"} + + + + + + + Proposed for 4.0. + Discussed 2022-09-20; decided to defer acceptance pending ideas for alignment with array:filter. + +
+ + + + + + + + + + + context-independent + focus-independent + + + +

Returns a map based on the contents of an existing map, computing a new value to be associated + with a supplied key.

+
+ +

If the supplied $map contains an existing entry for the supplied $key, + then the returned map contains an entry for that $key whose value is obtained by applying + the supplied $action to the existing value associated with that key.

+

Otherwise, the returned map contains an entry for the supplied $key whose value is + obtained by applying the supplied $action to an empty sequence.

+ + +

The effect of the function call map:replace($MAP, $KEY, $VALUE) is equivalent + to the result of the expression:

+ + if (map:contains($MAP, $KEY)) +then map:put($MAP, $KEY, $ACTION(map:get($MAP, $KEY))) +else map:put($MAP, $KEY, $ACTION(()) + + +
+ + + + map:replace(map{1:"alpha", 2:"beta"}, 1, upper-case#1) + map { 1: "ALPHA", 2: "beta" } + + + map:replace(map{1:"alpha", 2:"beta"}, 3, upper-case#1) + map { 1: "alpha", 2: "beta" 3: "" } + + + fold-left( + ("a", "b", "c", "a"), + map { }, + function($map, $key) { + map:replace($map, $key, function($val) { + ($val otherwise 0) + 1 + }) + } +) + map{"a":2, "b":1, "c":1} + + + + +
+ + + + + + + + + + context-independent + focus-independent + + + +

Applies a supplied function to every entry in a map, returning a map whose entries + have the same keys as the input, but (potentially) different associated values.

+
+ +

The function map:substitute takes any map as its $map argument and applies the supplied function + to each entry in the map; the result is a map that associates the original set of key + values with the results of these function calls.

+

The function supplied as $action takes two arguments. It is called + supplying the key of the map entry as the first argument, and the associated value as + the second argument.

+
+ +

The function call map:substitute($m, $f) returns the same result as + map:merge(map:for-each($m, fn($k, $v) { map:entry($k, $f($k, $v)) })).

+
+ + + + map:substitute( + map { 1: true(), 2: false() }, + function($k, $v) { not($v) } +) + map{1:false(), 2:true()} + + + map:substitute( + map { 1: "yes", 2: "no" }, + function($k, $v) { $v || ' (' || $k || ')' } +) + map{1:"yes (1)", 2:"no (2)"} + + + + +
+ + + + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Returns a map that typically contains one entry for each item in a supplied input sequence.

+
+ +

Informally, the function processes each item in $input in order. It calls the $key function on + that item to obtain a key value, and the $value function to obtain an associated value. + If the key is non-empty, then:

+ +

If the key is not already present in the target map, the processor adds a new key-value pair to the map, with that key + and that value.

+

If the key is already present, the processor calls the $combine function to combine the existing value + for the key with the new value, and replaces the entry with this combined value.

+
+ +

More formally, the result of the function is the result of the following expression:

+ + +fold-left($input, map{}, fn($map, $next) { + let $nextKey := $key($next) + let $nextValue := $value($next) + return + if (fn:exists($nextKey)) + then + if (map:contains($map, $nextKey)) + then map:put($map, $nextKey, $combine($map($nextKey), $nextValue)) + else map:put($map, $nextKey, $nextValue) + else + $map +}) + +
+ + +

Although defined to process the input sequence in order, this is only relevant when combining the entries + for duplicate keys.

+

The default function for both $key and $value is the identity function. + Although it is permitted to default both, this serves little purpose: usually at least one of these arguments + will be supplied.

+

The default action for combining entries with duplicate keys is to perform a sequence-concatenation of the corresponding values, + equivalent to the duplicates: combine option on map:merge. Other potentially useful + functions for combining duplicates include:

+ +

fn($a, $b) { $a } Use the first value and discard the remainder

+

fn($a, $b) { $b } Use the last value and discard the remainder

+

fn:concat(?, ",", ?) Form the string-concatenation of the values, comma-separated

+

fn:op('+') Compute the sum of the values

+
+
+ + + + map:build((), string#1) + map{} + + + map:build(1 to 10, function { . mod 3 }) + map{0: (3, 6, 9), 1: (1, 4, 7, 10), 2: (2, 5, 8)} + Returns a map with one entry for each distinct value of . mod 3. The + function to compute the value is the identity function, and duplicates are combined by + sequence concatenation. + + + map:build( + 1 to 5, + value := format-integer(?, "w") +) + map{1: "one", 2: "two", 3: "three", 4: "four", 5: "five"} + Returns a map with five entries. The function to compute the key is an identity function, the + function to compute the value invokes fn:format-integer. + + + map:build( + ("January", "February", "March", "April", + "May", "June", "July", "August", "September", + "October", "November", "December"), + substring(?, 1, 1) +) + map{"A": ("April", "August"), "D": ("December"), "F": ("February"), "J": ("January", "June", "July"), + "M": ("March", "May"), "N": ("November"), "O": ("October"), "S": ("September")} + + + map:build( + ("apple", "apricot", "banana", + "blueberry", "cherry"), + substring(?, 1, 1), + string-length#1, + op("+") +) + map{"a": 12, "b": 15, "c": 6} + Constructs a map where the key is the first character of an input item, and where the corresponding value + is the total string-length of the items starting with that character. + + + + + +

The following expression creates a map whose keys are employee @ssn values, and whose + corresponding values are the employee nodes:

+ map:build(//employee, fn { @ssn }) +
+ +

The following expression creates a map whose keys are employee @location values, and whose + corresponding values represent the number of employees at each distinct location. Any employees that + lack an @location attribute will be excluded from the result.

+ map:build(//employee, fn { @location }, fn { 1 }, op("+")) +
+ +

The following expression creates a map whose keys are employee @location values, and whose + corresponding values contain the employee node for the highest-paid employee at each distinct location:

+ map:build(//employee, function { @location }, + combine := fn($a, $b) { highest(($a, $b), fn { xs:decimal(@salary) }) }) +
+ +

The following expression creates a map allowing efficient access to every element in a document by means + of its fn:generate-id value:

+ map:build(//*, generate-id#1) +
+
+ + Accepted for version 4.0 2022-10-18 + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the number of entries in the supplied map.

+
+ +

The function map:size takes any map + as its $map argument and returns the number of entries that are present + in the map.

+
+ + + + map:size(map{}) + 0 + + + map:size(map{"true":1, "false":0}) + 2 + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + + + + deterministic + context-dependent + focus-independent + + +

Given a string value and a collation, generates an internal value called a collation key, with the property that + the matching and ordering of collation keys reflects the matching and ordering of strings under the specified collation.

+
+ +

Calling the one-argument version of this function is equivalent to calling the + two-argument version supplying the default collation as the second argument.

+

The function returns an implementation-dependent + value with the property that, + for any two strings $K1 and $K2:

+ + +

collation-key($K1, $C) eq collation-key($K2, $C) if and only if + compare($K1, $K2, $C) eq 0

+
+ +

collation-key($K1, $C) lt collation-key($K2, $C) if and only if + compare($K1, $K2, $C) lt 0

+
+
+ +

The collation used by this function is determined according to the rules in . Collation keys are defined as xs:base64Binary values + to ensure unambiguous and context-free comparison semantics.

+

An implementation is free to generate a collation key in any convenient way provided + that it always generates the same collation key for two strings that are equal under the + collation, and different collation keys for strings that are not equal. This holds only + within a single execution scope; + an implementation is under no obligation to generate the same collation keys during a + subsequent unrelated query or transformation.

+

It is possible to define collations that do not have the ability to generate collation + keys. Supplying such a collation will cause the function to fail. The ability to + generate collation keys is an implementation-defined property of the + collation.

+
+ +

An error is raised if the specified + collation does not support the generation of collation keys.

+
+ +

The function is provided primarily for use with maps. If a map is required where + codepoint equality is inappropriate for comparing keys, then a common technique is to + normalize the key so that equality matching becomes feasible. There are many ways + keys can be normalized, for example by use of functions such as + fn:upper-case, fn:lower-case, + fn:normalize-space, or fn:normalize-unicode, but this + function provides a way of normalizing them according to the rules of a specified + collation. For example, if the collation ignores accents, then the function will + generate the same collation key for two input strings that differ only in their use of + accents.

+

The result of the function is defined to be an xs:base64Binary value. Binary values + are chosen because they have unambiguous and context-free comparison semantics, because the value space + is unbounded, and because the ordering rules are such that between any two values in the ordered value space, an + arbitrary number of further values can be interpolated. The choice between xs:base64Binary + and xs:hexBinary is arbitrary; the only operation that behaves differently between the two binary + data types is conversion to/from a string, and this operation is not one that is normally required for + effective use of collation keys. +

+

For collations based on the Unicode Collation Algorithm, an algorithm for computing + collation keys is provided in . Implementations are + not required to use this algorithm.

+ +

The fact that collation keys are ordered can be exploited in XQuery, whose order by + clause does not allow the collation to be selected dynamically. This restriction can be circumvented + by rewriting the clause order by $e/@key collation "URI" as order by fn:collation-key($e/@key, $collation), + where $collation allows the collation to be chosen dynamically.

+

Note that xs:base64Binary becomes an ordered type + in XPath 3.1, making binary collation keys possible.

+ +
+ + + + + map:merge( + (map { collation-key("A", $C): 1 }, + map { collation-key("a", $C): 2 }), + map { "duplicates": "use-last" } +)(collation-key("A", $C)) + 2 + Given that the keys of the two entries are equal under the rules of + the chosen collation, only one of the entries can appear in the result; the one + that is chosen is the one from the last map in the input sequence. + + + + + let $M := map { + collation-key("A", $C): 1, + collation-key("B", $C): 2 +} +return $M(collation-key("a", $C)) + 1 + The strings "A" and "a" have the same collation key under this + collation. + + + +

As the above examples illustrate, it is important that when the + collation-key function is used to add entries to a map, then it must + also be used when retrieving entries from the map. This process can be made less + error-prone by encapsulating the map within a function: function($k) + {$M(collation-key($k, $collation)}.

+
+
+
+ + + + + + + + + + nondeterministic + context-dependent + focus-independent + + +

Parses a string supplied in the form of a JSON text, returning the results in the form + of an XML document node.

+
+ +

The effect of the one-argument form of this function is the same as calling the + two-argument form with an empty map as the value of the $options + argument.

+ +

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

+ +

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

+ +

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

+ +

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

+ + + + Determines whether deviations from the syntax of RFC7159 are permitted. + xs:boolean + false + + + The input must consist of an optional byte order mark (which is ignored) followed by a string + that conforms to the grammar of JSON-text in . An error must be raised + (see below) if the input does not conform to the grammar. + + + The input may contain deviations from the grammar of , + which are handled in an implementation-defined way. (Note: some popular + extensions include allowing quotes on keys to be omitted, allowing a comma + to appear after the last item in an array, allowing leading zeroes in numbers, and allowing control characters such as + tab and newline to be present in unescaped form.) Since the extensions accepted + are implementation-defined, an error may be raised + (see below) if the input does not conform to the grammar. + + + + + Determines the policy for handling duplicate keys in a JSON object. + To determine whether keys are duplicates, they are compared using the Unicode codepoint collation, after expanding escape + sequences, unless the escape option is set to true, in which + case keys are compared in escaped form. + + xs:string + If validate is true then reject, otherwise retain. + + + An error is raised if duplicate keys are encountered. + + + If duplicate keys are present in a JSON object, all but the first of a set of duplicates are ignored. + + + If duplicate keys are present in a JSON object, the XML result of the function will also contain duplicates (making + it invalid against the schema). This value is therefore incompatible with the option validate=true + + + + + + + Determines whether the generated XML tree is schema-validated. + xs:boolean + Implementation-defined. + + + Indicates that the resulting XDM instance must be typed; that is, the element + and attribute nodes must carry the type annotations that result from validation + against the schema given at , or against an + implementation-defined schema + if the liberal option has the value true. + + + Indicates that the resulting XDM instance must be untyped. + + + + + + Determines whether special characters are represented in the XDM output + in backslash-escaped form. + xs:boolean + false + + + All characters in the input that are valid + in the version of XML supported by the implementation, whether or not they are represented + in the input by means of an escape sequence, are represented as unescaped characters in the result. Any + characters or codepoints that are not valid XML characters + (for example, unpaired surrogates) are passed to the fallback function + as described below; in the absence of a fallback function, they are replaced by + the Unicode REPLACEMENT CHARACTER (xFFFD). + The attributes escaped and escaped-key will not be present in the XDM output. + + + JSON escape sequences are used in the result to represent special characters in the JSON input, as defined below, + whether or not they were represented using JSON escape sequences in the input. + The characters that are considered “special” for this purpose are: + +

all codepoints in the range x00 to x1F + or x7F to x9F;

+

all codepoints that do not represent characters that are valid in the version of XML supported by the processor, + including codepoints representing unpaired surrogates;

+

the backslash character itself (x5C).

+
+ + Such characters are represented using a two-character + escape sequence where available (for example, \t), or a six-character escape sequence otherwise + (for example \uDEAD). Characters other than these will not be escaped in the result, + even if they were escaped in the input. In the result: + + +

Any string element whose string value contains a + backslash character must have the attribute value escaped="true".

+

Any element that contains a key attribute whose string value + contains a backslash character must have the attribute + escaped-key="true".

+

The values of the escaped and + escaped-key attributes are immaterial when there is no backslash + present, and it is never necessary to include either attribute when its value + is false.

+
+
+
+
+ + + + Provides a function which is called when the input contains an escape sequence + that represents a character that is not valid in the version of XML + supported by the implementation. + + It is an error to supply the fallback option if the escape option is present + with the value true. + + function(xs:string) as xs:string + The default is effectively the function function($s) { "&#xFFFD;" }: that is, + a function that replaces the escape sequence with the Unicode REPLACEMENT CHARACTER. + + + The function is called when the JSON input contains an escape sequence that is valid according to the JSON + grammar, but which does not represent a character that is valid in the version of XML supported + by the processor. In the case of surrogates, the function is called once for any six-character escape sequence + that is not properly paired with another surrogate. The string supplied + as the argument will always be a two- or six- character escape + sequence, starting with a backslash, that conforms to the rules in the JSON grammar (as extended by the + implementation if liberal:true() is specified): for example + \b or \uFFFF or \uDEAD. The function is not + called for an escape sequence that is invalid against the grammar (for example \x0A). + The function returns a string + which is inserted into the result in place of the invalid character. The + function also has the option of raising a dynamic error by calling fn:error. + + + +
+ +

The various structures that can occur in JSON are transformed recursively to XDM values + according to the rules given in .

+ +

The function returns a document node, whose only child + is the element node representing the outermost construct in the JSON + text.

+ +

The function is non-deterministic with respect to node identity: that is, if the function is called twice with the same + arguments, it is implementation-dependent whether the same node is returned on both + occasions.

+ +

The base URI of the returned document node is taken from the static base URI of the + function call.

+ +

The choice of namespace prefix (or absence of a prefix) in the names of constructed + nodes is implementation-dependent.

+ +

The XDM tree returned by the function does not contain any + unnecessary (albeit valid) nodes such as whitespace text nodes, comments, or processing instructions. + It does not include any whitespace in the value of number or boolean + element nodes, or in the value of escaped or escaped-key + attribute nodes.

+ + +

If the result is typed, every element named string will have an attribute named + escaped whose value is either true or false, and every element having + an attribute named key will also have an attribute named escaped-key whose value is either + true or false. +

+

If the result is untyped, the attributes escaped and escaped-key will + either be present with the value true, or will be absent. They will never be present with the value false.

+ +
+ + +

An error is raised if the value of + $value does not conform to the JSON grammar as defined + by , unless the option "liberal":true() is present and + the processor chooses to accept the deviation.

+ +

An error is raised if the value of + the validate option is true and the processor does not support + schema validation or typed data.

+ +

An error is raised if the value of + $options includes an entry whose key is defined in this specification, + and whose value is not a permitted value for that key.

+ + +
+ +

To read a JSON file, this function can be used in conjunction with the + fn:unparsed-text function.

+

Many JSON implementations allow commas to be used after the last item in an object or + array, although the specification does not permit it. The option + spec="liberal" is provided to allow such deviations from the + specification to be accepted. Some JSON implementations also allow constructors such as + new Date("2000-12-13") to appear as values: specifying + spec="liberal" allows such extensions to be accepted, but does not + guarantee it. If such extensions are accepted, the resulting value is + implementation-defined, and will not necessarily conform to the schema at .

+

If the input starts with a byte order mark, this function ignores it. The byte order mark may have been added + to the data stream in order to facilitate decoding of an octet stream to a character string, but since this function + takes a character string as input, the byte order mark serves no useful purpose.

+

The possibility of the input containing characters that are not valid in XML (for example, unpaired surrogates) + arises only when such characters are expressed using JSON escape sequences. The is because the input to the function + is an instance of xs:string, which by definition can only contain characters that are valid in XML.

+ +
+ + + + json-to-xml( + '{"x": 1, "y": [3,4,5]}', + map { "validate": false() } +) + + 1 + + 3 + 4 + 5 + +]]> + + + json-to-xml( + '"abcd"', + map { 'liberal': false() } +) + abcd]]> + + + json-to-xml( + '{"x": "\\", "y": "\u0025"}', + map { "validate": false() } +) + + \ + % +]]> + + + json-to-xml( + '{"x": "\\", "y": "\u0025"}', + map { 'escape': true(), "validate": false() } +) + + \\ + % +]]> + But see the detailed rules for alternative values of the escaped attribute + on the second string element. + + + +

The following example illustrates use of the fallback function to + handle characters that are invalid in XML.

+ +
+
+
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Converts an XML tree, whose format corresponds to the XML representation of JSON defined + in this specification, into a string conforming to the JSON grammar.

+
+ +

The effect of the one-argument form of this function is the same as calling the + two-argument form with an empty map as the value of the $options + argument.

+ +

The first argument $node is a node; the subtree rooted at this node will typically be + the XML representation of a JSON document as defined in .

+ +

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

+ +

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

+ +

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

+ + + + Determines whether additional whitespace should be added to the output to improve readability. + xs:boolean + false + + + The processor must not insert any insignificant whitespace between JSON tokens. + + + The processor may insert whitespace between JSON tokens in order to improve readability. + The specification imposes no constraints on how this is done. + + + + + Determines how numeric values should be formatted. + (function(xs:string) as xs:string)? + () + + + The supplied function is called to process the string value of all fn:number + elements in the input. For example, setting the value to fn:identity#1 + causes the value to be output unchanged. There is no requirement that the result should + be valid JSON. + + + If no function is supplied, numbers are formatted by converting the string value of + the fn:number element to an xs:double, and then converting + the result to a string using the casting rules. Note that this will result in exponential + notation being used for values outside the range + 1e-6 to 1e+6. A dynamic error occurs for values + such as infinity and NaN where the resulting JSON would be invalid. + + + + + + + +

The node supplied as $node must be one of the following:

+ + + +

An element node whose name matches the name of a global element declaration in the schema given in + (“the schema”) and that is valid as defined below:

+ + +

If the type annotation of the element matches the type of the relevant element declaration + in the schema (indicating that the element has been validated against the schema), then the element + is considered valid. +

+
+ +

Otherwise, the processor may attempt to validate the element against + the schema, in which case it is treated as valid if and only if the outcome of validation is + valid. +

+
+ +

Otherwise (if the processor does not attempt validation using the schema), + the processor must ensure that the content of the element, + after stripping all attributes (at any depth) in namespaces other than + http://www.w3.org/2005/xpath-functions, is such that validation + against the schema would have an outcome of valid. +

+ +

The process described here is not precisely equivalent to schema validation. + For example, schema validation will fail if there is an invalid xsi:type + or xsi:nil attribute, whereas this process will ignore such attributes. +

+
+
+
+ +
+ + +

An element node E having a key attribute and/or an escaped-key attribute + provided that E would satisfy one of the above + conditions if the key and/or escaped-key attributes were removed.

+ +
+ + +

A document node having exactly one element child and no text node children, + where the element child satisfies one of the conditions above.

+
+
+ + + +

Furthermore, $node must satisfy the following constraint + (which cannot be conveniently expressed in the schema). Every element M that is a descendant-or-self of + $node and has local name map and namespace URI http://www.w3.org/2005/xpath-functions + must satisfy the following rule: there must not be two distinct children of M (say C/1 and C/2) + such that the normalized key of C/1 is equal to the normalized key of C/2. The normalized key + of an element C is as follows:

+ + + +

If C has the attribute value escaped-key="true", then the value of the + key attribute of C, with all JSON escape sequences replaced by the corresponding Unicode characters + according to the JSON escaping rules. +

+
+ +

Otherwise (the escaped-key attribute of C is absent or set to false), + the value of the key attribute of C.

+
+
+ +

Nodes in the input tree are handled by applying the following rules, recursively. In these rules the term + “an element named N” means "an element node whose local name is N and whose namespace URI is + http://www.w3.org/2005/xpath-functions".

+ + + +

A document node having a single element node child is processed by processing that child.

+
+ +

An element named null results in the output null.

+
+ +

An element $E named boolean results in the output true or false + depending on the result of xs:boolean(fn:string($E)).

+
+ +

An element $E named number is processed as follows:

+ +

If the number-formatter option is present and non-empty, + the supplied function is called, with the string value of $E as its argument, + and the result is output (whether or not it is valid JSON).

+

Otherwise, the result of the expression xs:string(xs:double(fn:string($E))) + is output.

+
+

The default formatting results in exponential format being used for numbers whose + absolute value is outside the range 1e-6 to 1e+6; + although this is valid according to the JSON specification, some receiving + applications may be unable to process it. Possible reasons for using + a number-formatter might be:

+ +

To avoid use of exponential notation in the output.

+

To avoid loss of precision when the numbers to be output have + greater precision than an xs:double.

+

To improve the human readability of the output, for example by calling fn:format-number + to limit the number of decimal places in the result.

+

To avoid errors when dealing with values that JSON cannot handle, such as Infinity and NaN + (for example, by emitting these as strings within quotation marks).

+
+
+
+ +

An element named string results in the output of the string value of the element, enclosed in + quotation marks, with any special characters in the string escaped as described below.

+
+ +

An element named array results in the output of the children of the array element, + each processed by applying these rules recursively: the items in the resulting list are enclosed between square brackets, + and separated by commas.

+
+ +

An element named map results in the output of a sequence of map entries corresponding to + the children of the map element, enclosed between curly braces and separated by commas. + Each entry comprises the value of the key attribute of the child element, enclosed in quotation marks + and escaped as described below, followed by a colon, followed by the result of processing the child element + by applying these rules recursively.

+
+ +

Comments, processing instructions, and whitespace text node children of map and array + are ignored.

+
+ +
+ +

Strings are escaped as follows:

+ + + +

If the attribute escaped="true" is present for a string value, or escaped-key="true" for a key value, then:

+ + + +

any valid JSON escape sequence present in the string is copied unchanged to the output;

+
+ + +

any invalid JSON escape sequence results in a dynamic error ;

+
+ + +

any unescaped occurrence of quotation mark, backspace, form-feed, newline, carriage return, tab, or solidus is replaced by + \", \b, \f, \n, \r, \t, or \/ respectively;

+
+ + +

any other codepoint in the range 1-31 or 127-159 is replaced by an escape in the form \uHHHH where HHHH + is the upper-case hexadecimal representation of the codepoint value.

+
+
+
+ +

Otherwise (that is, in the absence of the attribute escaped="true" for a string value, + or escaped-key="true" for a key value):

+ + + +

any occurrence of backslash is replaced by \\

+
+ + +

any occurrence of quotation mark, backspace, form-feed, newline, carriage return, or tab is + replaced by \", \b, \f, \n, \r, or \t respectively;

+
+ + +

any other codepoint in the range 1-31 or 127-159 is replaced by an escape in + the form \uHHHH where HHHH is the upper-case hexadecimal representation of the codepoint value.

+
+
+
+
+ +
+ + +

A dynamic error is raised if the value of + $options includes an entry whose key is defined in this specification, + and whose value is not a permitted value for that key.

+ +

A dynamic error is raised if the value of + $node is not a document or element node or is not valid according to the schema for the XML representation of + JSON, or if a map element has two children whose normalized key values are the same.

+ +

A dynamic error is raised if the value of + $node includes a string labeled with escaped="true", or + a key labeled with escaped-key="true", where the content of the string or key + contains an invalid JSON escape sequence: specifically, where it contains a backslash (\) that is not followed by one + of the characters ", \, /, b, f, n, + r, t, or u, or where it contains the characters \u + not followed by four hexadecimal digits (that is [0-9A-Fa-f]{4}). +

+ +
+ +

The rule requiring schema validity has a number of consequences, including the following:

+ + +

The input cannot contain no-namespace attributes, or attributes in the namespace http://www.w3.org/2005/xpath-functions, + except where explicitly allowed by the schema. Attributes in other namespaces, however, are ignored.

+
+ +

Nodes that do not affect schema validity, such as comments, processing instructions, namespace nodes, and whitespace text node + children of map and array, are ignored.

+
+ +

Numeric values are restricted to those that are valid in JSON: + the schema disallows positive and negative infinity and NaN.

+
+ +

Duplicate key values are not permitted. Most cases of duplicate keys are prevented by the rules in the schema; + additional cases (where the keys are equal only after expanding JSON escape sequences) are prevented by the prose rules + of this function. For example, the key values \n and \u000A are treated as duplicates even though + the rules in the schema do not treat them as such.

+
+
+

The rule allowing the top-level element to have a key attribute (which is ignored) + allows any element in the output of the fn:json-to-xml function + to be processed: for example, it is possible to take a JSON document, convert it to XML, select + a subtree based on the value of a key attribute, and then convert this subtree + back to JSON, perhaps after a transformation. The rule means that an element with the appropriate name will be + accepted if it has been validated against one of the + types mapWithinMapType, arrayWithinMapType, stringWithinMapType, + numberWithinMapType, booleanWithinMapType, or nullWithinMapType.

+
+ + +

The input 1is1]]> + produces the result [1,"is",true].

+
+ +

The input 12]]> + produces the result {"Sunday":1,"Monday":2}.

+
+
+
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Parses CSV data supplied as a string, returning the results in the form of a sequence of arrays of strings.

+
+ +

The effect of the one-argument form of this function is the same as calling the + two-argument form with an empty map as the value of the $options + argument.

+ +

The first argument is CSV data, as defined in , in the form of a + sequence of xs:string values. The function parses this sequence to return + an XDM value.

+ +

If $csv is the empty sequence, implementations must + return the empty sequence as the value of the body field of the returned + map.

+ +

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

+ +

Implementations must treat any of CRLF, CR, or LF as a single line + separator, as with fn:unparsed-text-lines.

+ +

Fields are regarded as simple xs:string values. Implementations + must leave whitespace within a field untouched, without + normalizing or otherwise altering it, unless whitespace trimming is explicitly requested + by the user using the trim-whitespace option.

+ +

When whitespace trimming is requested, implementations must only + strip leading and trailing whitespace, this is not equivalent to calling + fn:normalize-space().

+ +

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

+ + + + The character used to delimit fields within a record. An instance of + xs:string whose length is exactly one. + xs:string + "," + + + The characters used to delimit records within the CSV string, if the + default use of line separator as record separator is to be overridden. + xs:string + () + + + The character used to quote fields within the CSV string. An instance of + xs:string whose length is exactly one. + xs:string + '"' + + + Determines whether fields should have leading and trailing whitespace + removed before being returned. + xs:boolean + false + + Fields will be returned with any leading or trailing + whitespace intact. Implementations must preserve whitespace + as it occurred in the CSV string. + + Fields will be returned with leading or trailing + whitespace removed, and all non-leading or -trailing whitespace preserved. + + + + + +

The result of the function is a sequence of arrays-of-strings + array(xs:string)*.

+

A blank row is represented as an empty array.

+

An empty field is represented by the empty string.

+
+ +

A dynamic error occurs if the value of + $csv does not conform to the grammar for quoted + fields.

+

A dynamic error occurs if one or more of the values + for field-separator, record-separator, + quote-character are specified and are not a single character.

+

A dynamic error occurs if any of the values for + field-separator, record-separator, + quote-character are equal.

+
+ +

All fields are returned as xs:string values.

+

Quoted fields in the input are returned without the quotes.

+

For more discussion of the returned data, see .

+
+ + + + + +

Handling any of the default record separators:

+ + parse-csv(`name,city{$crlf}Bob,Berlin{$crlf}Alice,Aachen{$crlf}`) + ( + ["name", "city"] + ["Bob", "Berlin"], + ["Alice", "Aachen"] +) + + + parse-csv(`name,city{$cr}Bob,Berlin{$cr}Alice,Aachen{$cr}`) + ( + ["name", "city"] + ["Bob", "Berlin"], + ["Alice", "Aachen"] +) + + + parse-csv(`name,city{$lf}Bob,Berlin{$lf}Alice,Aachen{$lf}`) + ( + ["name", "city"] + ["Bob", "Berlin"], + ["Alice", "Aachen"] +) + +
+ +

Quote handling:

+ + parse-csv(`"name","city"${crlf}"Bob","Berlin"${crlf}"Alice","Aachen"${crlf}`) + ( + ["name", "city"] + ["Bob", "Berlin"], + ["Alice", "Aachen"] +) + + + parse-csv(`"name","city"${crlf}"Bob ""The Exemplar"" Mustermann","Berlin"${crlf}`) + ( + ["name", "city"] + ['Bob "The Exemplar" Mustermann', "Berlin"], + ["Alice", "Aachen"] +) + +
+ +

Non-default record- and field-separators:

+ + parse-csv("name;city§Bob;Berlin§Alice;Aachen", map{"record-separator": "§", "field-separator": ";"}) + ( + ["name", "city"] + ["Bob", "Berlin"], + ["Alice", "Aachen"] +) + +
+ +

Non-default quote character:

+ + parse-csv(`|name|,|city|${crlf}|Bob|,|Berlin|${crlf}`, map{"quote-character": "|"}) + ( + ["name", "city"] + ["Bob", "Berlin"], + ["Alice", "Aachen"] +) + +
+ +

Trimming whitespace in fields:

+ + parse-csv(`name ,city ${crlf}Bob ,Berlin${crlf}Alice ,Aachen${crlf}`, map{"trim-whitespace: true()}) + ( + ["name", "city"] + ["Bob", "Berlin"], + ["Alice", "Aachen"] +) + +
+
+
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Parses CSV data supplied as a string, returning the results in the form of a + parsed-csv-structure-record record containing information about the + column structure of the data, as well as the data itself as a sequence of + csv-row-record records.

+
+ +

The effect of the one-argument form of this function is the same as calling the + two-argument form with an empty map as the value of the $options + argument.

+ +

The first argument is CSV data, as defined in , in the form of a + sequence of xs:string values. The function parses this sequence using + fn:parse-csv, and then processes its result to return an XDM value.

+ +

If $csv is the empty sequence, implementations must + return a parsed-csv-structure-record whose rows entry is the empty sequence.

+ +

If $csv is the empty sequence, but column name extraction has been + requested, or explicit column names have been supplied, then the + parsed-csv-structure-record returned by implementations + must have a rows entry whose value is the empty + sequence.

+ +

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

+ +

Handling of delimiters, and whitespace trimming, are handled using + fn:parse-csv, and the options controlling their use are defined + there.

+ +

If the headers option is true, implementations must + exclude the first record from the returned map’s body key, and return it as + the value of the returned map’s headers-record key.

+ +

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

+ + + The character used to delimit fields within a record. An instance of + xs:string whose length is exactly one. + xs:string + "," + + + The characters used to delimit records within the CSV string, if the + default use of line separator as record separator is to be overridden. + xs:string + () + + + The character used to quote fields within the CSV string. An instance of + xs:string whose length is exactly one. + xs:string + '"' + + + Determines whether fields should have leading and trailing whitespace + removed before being returned. + xs:boolean + false + + Fields will be returned with any leading or trailing + whitespace intact. Implementations must preserve whitespace + as it occurred in the CSV string. + + Fields will be returned with leading or trailing + whitespace removed, and all non-leading or -trailing whitespace preserved. + + + + + Determines whether the first row of the CSV should be treated as a list + of column names and returned as a csv-columns-record in the + columns entry of the returned map. + union(xs:boolean, map(xs:string, xs:integer)) + false + + A csv-columns-record is constructed using the + first row of the CSV data and returned as the header entry of the + parsed-csv-structure-record. The row’s fields are transformed + into a map of the form { "Column name": column-number } for the + names entry of the csv-columns-record, and the + fields of the row are returned as a sequence of strings + (xs:string*) for the fields entry. Implmentations + must exclude the first row from the rows + entry of the returned parsed-csv-structure-record. + Implementations must return an empty + csv-columns-record, equivalent to the literal map map { + names: map {}, fields: () }, in the columns entry of + the returned parsed-csv-structure-record. Implementations + must not exclude the first row from the rows + entry of the parsed-csv-structure-record. + A csv-columns-record is + constructed using the supplied map and returned as the header + entry of the parsed-csv-structure-record. The supplied map is used + as the names entry, and a sequence of strings for the + fields is constructed, filling in blank columns with the empty + string. and the fields of the row are returned as the fields + entry. Implementations must not exclude the first row from + the rows entry of the parsed-csv-structure-record. + + + + + Specifies how many columns to return. + union(enum("all", "first-row"), xs:integer) + "all" + + All fields from all rows + must be returned, without being padded or truncated, + regardless of whether rows have varying numbers of fields, or of how many + fields they have. + The number of fields in the first row is counted, + and processing proceeds as if that integer had been supplied as the value for + this option. + The number of columns is set to this value. Rows + with more fields than the supplied value are truncated by discarding the extra + fields. as if calling fn:subsequence(R, 1, I), given the row’s + sequence of fields in R, and the supplied value in I. If + a row has fewer fields than the supplied value it is padded by appending empty + string values until it contains the specified number of fields. + + + + +

If column names were extracted from the first row of the CSV, when there are duplicate + column names, implementations must include only the first occurrence + in the names entry of the csv-columns-record, ignoring + subsequent entries. Any fields in the first record whose value is the empty string + must also be omitted.

+ +

The result of the function is a parsed-csv-structure-record, a map with + string keys containing two entries, columns, and rows.

+ + +

The entry with key "columns" holds a csv-columns-record + record. If column names have been extracted, or supplied, then the record will + have a names entry whose value is a map of column-name to + column-number, map(xs:integer, xs:string). The record’s + fields entry will contains the column names as a sequence of + strings, xs:string*, replicating the row they were taken from.

+ +

If column names were not extracted or supplied, then the + csv-columns-record will contain a names entry whose + value is an empty map, and a fields entry whose value is the empty + sequence.

+
+ +

The entry with key "rows" holds the records of the CSV as a sequence + of row records, csv-row-record*. If there is no data in the CSV, this + will be the empty sequence.

+ +

Each record in the rows sequence contains a fields + entry, containing the row’s fields as a sequence of strings, + xs:string*, and a field entry containing an arity-one + function. The function takes a string or integer key K as input, and + returns the field in fields that corresponds to the position + K, if K is an xs:integer, or the position + obtained by looking up K in the names map if K + is an xs:string.

+ +

The properties of this function are as follows:

+ + +

name: absent

+
+ +

parameter names: ($key)

+
+ +

signature: (union(xs:integer, xs:string)) => xs:string?

+
+ +

non-local variable bindings: none

+
+ +

implementation: implementation-dependent

+
+ +

errors: A dynamic error occurs if the + supplied $key is a string and does not occur in the map of column + names.

+
+
+ +

This function behaves identically to fn:csv-fetch-field-by-column + would had the header entry of the containing + parsed-csv-structure-record and the fields entry of + this csv-row-record been supplied as its first two arguments, and + $key as its last. See the definition of + fn:csv-fetch-field-by-column for more details

+
+
+
+ +

A dynamic error occurs if the value of + $csv does not conform to the grammar for quoted + fields.

+

A dynamic error occurs if one or more of the values + for field-separator, record-separator, + quote-character are specified and are not a single character.

+

A dynamic error occurs if any of the values for + field-separator, record-separator, + quote-character are equal.

+
+ +

All fields are returned as xs:string values.

+

Quoted fields in the input are returned without the quotes.

+

For more discussion of the returned data, see .

+
+ + + `name,city{$crlf}Bob,Berlin{$crlf}Alice,Aachen{$crlf}` + map { "record-separator": "§", "field-separator": ";", "quote-character": "|" } + `|name|;|city|§|Bob|;|Berlin|§|Alice|;|Aachen|` + map { "trim-whitespace": true() } + +

With defaults for delimiters and quotes, and default column extraction (false):

+ + map:keys(csv-to-xdm($csv-string)) + ("header", "rows") + + + csv-to-xdm($csv-string)?columns + map { + "names": map {}, + "fields": (), +} + + + count(csv-to-xdm($csv-string)?rows) + 3 + + + csv-to-xdm($csv-string)?rows[1]?field("name") + + + + csv-to-xdm($csv-string)?rows[1]?field(2) + "city" + +

With defaults for delimiters and quotes, and columns: true() set:

+ + csv-to-xdm($csv-string, map {"columns": true()})?columns + map { + "names": map { "name": 1, "city": 2 }, + "fields": ("name", "city"), +} + + + count(csv-to-xdm($csv-string, map {"columns": true()})?rows) + 2 + + + csv-to-xdm($csv-string), map {"columns": true()}?rows[1]?fields + ("Bob", "Berlin") + + + csv-to-xdm($csv-string, map {"columns": true()})?rows[1]?field("name") + "Bob" + + + csv-to-xdm($csv-string, map {"columns": true()})?rows[1]?field(2) + "Berlin" + +
+ +

Non-default record- and field-delimiters, non-default quotes:

+ + map:keys(csv-to-xdm($non-std-csv, $options)) + ("header", "rows") + + + csv-to-xdm($non-std-csv, $options)?columns + map { + "names": map {}, + "fields": (), + } + + + count(csv-to-xdm($non-std-csv, $options)?rows) + 3 + + + csv-to-xdm($non-std-csv, $options)?rows[3]?field(1) + "Alice" + +
+ +

Trimming whitespace in fields:

+ + csv-to-xdm(`name ,city ${crlf}Bob ,Berlin${crlf}Alice ,Aachen${crlf}`, $trim-opts)?rows?fields + ("name", "city", "Bob", "Berlin", "Alice", "Aachen") + +
+ `date,name,city,amount,currency,original amount,note{$crlf}2023-07-19,Bob,Berlin,10.00,USD,13.99{$crlf}2023-07-20,Alice,Aachen,15.00{$crlf}2023-07-20,Charlie,Celle,15.00,GBP,11.99,cake,not a lie{$crlf}` + +

Filtering columns

+ + csv-to-xdm($csv-uneven-cols, map { "columns": true(), "filter-columns": (2,1,4) })?columns?fields + ("name","date","amount") + + + for $r in csv-to-xdm($csv-uneven-cols, map { "columns": true(), "filter-columns": (2,1,4) })?rows return array { $r?fields } + ( + ["Bob","2023-07-19","10.00"], + ["Alice","2023-07-20","15.00"], + ["Charlie","2023-07-20","15.00"] +) + +
+ +

Specifying the number of columns, using "all" (the default)

+ + csv-to-xdm($csv-uneven-cols, map { "columns": true(), "number-of-columns": "all" })?columns?fields + ("date","name","city","amount","currency","original amount","note") + + + for $r in csv-to-xdm($csv-uneven-cols, map { "columns": true(), "number-of-columns": "all" })?rows return array { $r?fields } + ( + ["2023-07-19","Bob","Berlin","10.00","USD","13.99"], + ["2023-07-20","Alice","Aachen","15.00"], + ["2023-07-20","Charlie","Celle","15.00","GBP","11.99","cake","not a lie"] +) + +
+ +

Specifying the number of columns using "first-row"

+ + csv-to-xdm($csv-uneven-cols, map { "columns": true(), "number-of-columns": "first-row" })?columns?fields + ("date","name","city","amount","currency","original amount","note") + + + for $r in csv-to-xdm($csv-uneven-cols, map { "columns": true(), "number-of-columns": "first-row" })?rows return array { $r?fields } + ( + ["2023-07-19","Bob","Berlin","10.00","USD","13.99",""], + ["2023-07-20","Alice","Aachen","15.00","","",""], + ["2023-07-20","Charlie","Celle","15.00","GBP","11.99","cake"] +) + +
+ +

Specifying the number of columns with a number

+ + csv-to-xdm($csv-uneven-cols, map { "columns": true(), "number-of-columns": 6 })?columns?fields + ("date","name","city","amount","currency","original amount") + + + for $r in csv-to-xdm($csv-uneven-cols, map { "columns": true(), "number-of-columns": 6 })?rows return array { $r?fields } + ( + ["2023-07-19","Bob","Berlin","10.00","USD","13.99"], + ["2023-07-20","Alice","Aachen","15.00","",""], + ["2023-07-20","Charlie","Celle","15.00","GBP","11.99"] +) + +
+
+
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + +

Parses CSV data supplied as a string, returning the results as an XML document, as described by + .

+
+ +

The effect of the one-argument form of this function is the same as calling the + two-argument form with an empty map as the value of the $options + argument.

+ +

The first argument is CSV data, as defined in , in the form of a + sequence of xs:string values. The function parses this sequence using + fn:parse-csv, and then processes its result to return an XML document.

+ +

If $csv is the empty sequence, implementations must + return a ]]> whose ]]> element + is empty.

+ +

If $csv is the empty sequence, but column name extraction has been + requested, but explicit column names have not been supplied, then the implementation + must return a ]]> element whose + ]]> element is empty.

+ +

If $csv is the empty sequence, but explicit column names have been + supplied, then the implementation must return a + ]]> element whose ]]> + element contains the appropriate ]]> elements.

+ +

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

+ +

Handling of delimiters, and whitespace trimming, are handled using + fn:parse-csv, and the options controlling their use are defined + there.

+ +

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

+ + + + The character used to delimit fields within a record. An instance of + xs:string whose length is exactly one. + xs:string + "," + + + The characters used to delimit records within the CSV string, if the + default use of line separator as record separator is to be overridden. + xs:string + () + + + The character used to quote fields within the CSV string. An instance of + xs:string whose length is exactly one. + xs:string + '"' + + + Determines whether fields should have leading and trailing whitespace + removed before being returned. + xs:boolean + false + + Fields will be returned with any leading or trailing + whitespace intact. Implementations must preserve whitespace + as it occurred in the CSV string. + + Fields will be returned with leading or trailing + whitespace removed, and all non-leading or -trailing whitespace preserved. + + + + + Determines whether the first row of the CSV should be treated as a list + of column headers and returned as a csv-columns-record in the + header entry of the returned map. + union(xs:boolean, map(xs:integer, xs:string)) + false + + The ]]> element is populated + with ]]> elements constructed using the values + from the first row of the CSV data. Implmentations must + exclude the first row from the ]]> + element. + Implementations must not include a + ]]> element in the output. + The supplied map is used to + construct a sequence of ]]> elements to populate + the ]]> element. The xs:integer + denotes the column number, and the xs:string the column name. Gaps + in the integer sequence of column numbers are filled with empty + ]]> elements. Implementations must + not exclude the first row from the ]]> + element. + + + + A sequence indicating which fields to return and in which order. If this + option is missing or the empty sequence, all fields are returned in their natural + order. Items in the sequence are treated as the index of the column to return. In + the returned data, only fields from the specified columnms are returned, and in + the order specified. + xs:integer* + () + + + Specifies how many columns to return. + union(enum("all", "first-row"), xs:integer) + "all" + + All fields from all rows + must be returned, without being padded or truncated, + regardless of whether rows have varying numbers of fields, or of how many + fields they have. + The number of fields in the first row is counted, + and processing proceeds as if that integer had been supplied as the value for + this option. + The number of columns is set to this value. Rows + with more fields than the supplied value are truncated by discarding the extra + fields. as if calling fn:subsequence(R, 1, I), given the row’s + sequence of fields in R, and the supplied value in I. If + a row has fewer fields than the supplied value it is padded by appending empty + string values until it contains the specified number of fields. + + + +
+ +

A dynamic error occurs if the value of + $csv does not conform to the grammar for quoted + fields.

+

A dynamic error occurs if one or more of the values + for field-separator, record-separator, + quote-character are specified and are not a single character.

+

A dynamic error occurs if any of the values for + field-separator, record-separator, + quote-character are equal.

+
+ + + `name,city{$crlf}Bob,Berlin{$crlf}Alice,Aachen{$crlf}` + +

An empty CSV with default column extraction (false):

+ + csv-to-xml("") + + + +]]> + +
+ +

An empty CSV with column extraction:

+ + csv-to-xml("", map { "columns": true() }) + + + + +]]> + +
+ +

An empty CSV with explicit column names:

+ + csv-to-xml("", map { "columns": map { "name": 1, "city": 3 }) + + + name + + city + + + +]]> + +
+ +

With defaults for delimiters and quotes, and column extraction:

+ + csv-to-xml($csv-string, map { "columns": true() }) + + + name + city + + + + Bob + Berlin + + + Alice + Aachen + + + +]]> + +
+ +

With defaults for delimiters and quotes, and column extraction:

+ + csv-to-xml($csv-string, map { "columns": true() }) + + + name + city + + + + Bob + Berlin + + + Alice + Aachen + + + +]]> + +
+ `date,name,city,amount,currency,original amount,note{$crlf}2023-07-19,Bob,Berlin,10.00,USD,13.99{$crlf}2023-07-20,Alice,Aachen,15.00{$crlf}2023-07-20,Charlie,Celle,15.00,GBP,11.99,cake,not a lie{$crlf}` + +

Filtering columns

+ + csv-to-xml($csv-string, map { "columns": true(), "filter-columns": (2,1,4) }) + + + name + date + amount + + + + Bob + 2023-07-19 + 10.00 + + + Alice + 2023-07-20 + 15.00 + + + Charlie + 2023-07-20 + 15.00 + + + +]]> + +
+ +

Specifying the number of columns, using "all" (the default)

+ + csv-to-xml($csv-uneven-cols, map { "columns": true(), "number-of-columns": "all" }) + + + date + name + city + amount + currency + original amount + note + + + + 2023-07-19 + Bob + Berlin + 10.00 + USD + 13.99 + + + 2023-07-20 + Alice + Aachen + 15.00 + + + 2023-07-20 + Charlie + Celle + 15.00 + GBP + 11.99 + cake + not a lie + + + +]]> + +
+ +

Specifying the number of columns using "first-row"

+ + csv-to-xml($csv-uneven-cols, map { "columns": true(), "number-of-columns": "first-row" }) + + + date + name + city + amount + currency + original amount + note + + + + 2023-07-19 + Bob + Berlin + 10.00 + USD + 13.99 + + + + 2023-07-20 + Alice + Aachen + 15.00 + + + + + + 2023-07-20 + Charlie + Celle + 15.00 + GBP + 11.99 + cake + + + +]]> + +
+ +

Specifying the number of columns with a number

+ + csv-to-xml($csv-uneven-cols, map { "columns": true(), "number-of-columns": 6 }) + + + date + name + city + amount + currency + original amount + + + + 2023-07-19 + Bob + Berlin + 10.00 + USD + 13.99 + + + 2023-07-20 + Alice + Aachen + 15.00 + + + + + 2023-07-20 + Charlie + Celle + 15.00 + GBP + 11.99 + + + +]]> + +
+
+
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Fetches a field from a parsed CSV row by name or position.

+
+ +

The first argument is a csv-columns-record, as provided in the + header entry of the parsed-csv-structure-record returned by + fn:csv-to-xdm.

+ +

The second argument is the row whose fields are being fetched, represented as a sequence + of strings as would be provided by the fields entry of a + csv-row-record returned by fn:csv-to-xdm.

+ +

The final argument is the key to use for the lookup, supplied as either an + xs:string (the column name) or xs:integer (the column + position).

+ +

When the argument is a string, if the string is missing from the keys of the map + contained in the names entry of the $columns argument’s + csv-columns-record, then implementations must raise + an .

+ +

When the argument is an integer, if the integer position is outside the bounds of the + $fields sequence (i.e. is greater than the size of the sequence), then + implementations must return the empty string.

+ +

The function returns the field in the sequence $fields at the position in + the sequence either explicitly provided (when $key is an + xs:integer), or looked up from the map of name to position in the + csv-columns-record provided in $columns.

+
+ +

A dynamic error occurs if the value of + $key is an xs:string but is not a member of the keys of the + map contained in the names entry of the csv-columns-record in + $header. fields.

+
+ + map { + "names": map { "name": 1, "city": 2 }, + "fields: ("name", "city") +} + ("Bob", "Berlin") + +

With a string key:

+ + csv-fetch-field-by-column($columns, $fields, "name") + "Bob" + + + csv-fetch-field-by-column($columns, $fields, "amount") + + +
+ +

With an integer key

+ + csv-fetch-field-by-column($columns, $fields, 2) + "Berlin" + + + csv-fetch-field-by-column($columns, $fields, 3) + "" + +
+
+
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

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

+
+ +

The effect of the one-argument form of this function is the same as calling the + two-argument form with an empty map as the value of the $options + argument.

+ +

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

+ +

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

+ + +

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

+
+ +

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

+ +

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

+ + + + Determines whether deviations from the syntax of RFC7159 are permitted. + xs:boolean + false + + + The input must consist of an optional byte order mark (which is ignored) followed by a string + that conforms to the grammar of JSON-text in . An error must be raised + if the input does not conform to the grammar. + + + The input may contain deviations from the grammar of , + which are handled in an implementation-defined way. (Note: some popular + extensions include allowing quotes on keys to be omitted, allowing a comma + to appear after the last item in an array, allowing leading zeroes in numbers, and allowing control characters such as + tab and newline to be present in unescaped form.) Since the extensions accepted + are implementation-defined, an error may be raised + if the input does not conform to the grammar. + + + + + Determines the policy for handling duplicate keys in a JSON object. + To determine whether keys are duplicates, they are compared using the Unicode codepoint collation, after expanding escape + sequences, unless the escape option is set to true, in which + case keys are compared in escaped form. + + xs:string + use-first + + + An error is raised if duplicate keys are encountered. + + + If duplicate keys are present in a JSON object, all but the first of a set of duplicates are ignored. + + + If duplicate keys are present in a JSON object, all but the last of a set of duplicates are ignored. + + + + + + Determines whether special characters are represented in the XDM output in backslash-escaped form. + xs:boolean + true + + + All characters in the input that are valid + in the version of XML supported by the implementation, whether or not they are represented + in the input by means of an escape sequence, are represented as unescaped characters in the result. Any + characters or codepoints that are not valid XML characters + (for example, unpaired surrogates) are passed to the fallback function + as described below; in the absence of a fallback function, they are replaced by + the Unicode REPLACEMENT CHARACTER (xFFFD). + + + JSON escape sequences are used in the result to represent special characters in the JSON input, as defined below, + whether or not they were represented using JSON escape sequences in the input. + The characters that are considered “special” for this purpose are: + +

all codepoints in the range x00 to x1F + or x7F to x9F;

+

all codepoints that do not represent characters that are valid in the version of XML supported by the processor, + including codepoints representing unpaired surrogates;

+

the backslash character itself (x5C).

+
+ + Such characters are represented using a two-character + escape sequence where available (for example, \t), or a six-character escape sequence otherwise + (for example \uDEAD). Characters other than these are not escaped in the result, even if they + were escaped in the input. +
+
+
+ + + Provides a function which is called when the input contains an escape sequence + that represents a character that is not valid in the version of XML + supported by the implementation. + + It is an error to supply the fallback option if the escape option is present + with the value true. + + function(xs:string) as xs:string + The default is effectively the function function($s) { "&#xFFFD;" }: that is, + a function that replaces the escape sequence with the Unicode REPLACEMENT CHARACTER. + + + The function is called when the JSON input contains a special character (as defined under + the escape option) that is valid according to the JSON + grammar, whether the special character is represented in the input directly or as an escape sequence. + The function is called once for any surrogate + that is not properly paired with another surrogate. The string supplied as the argument will always be a two- or six- character escape + sequence, starting with a backslash, that conforms to the rules in the JSON grammar (as extended by the + implementation if liberal:true() is specified): for example + \b or \uFFFF or \uDEAD. The function is not + called for an escape sequence that is invalid against the grammar (for example \x0A). The function returns a string + which is inserted into the result in place of the invalid character. The + function also has the option of raising a dynamic error by calling fn:error. + + + + + Determines how numeric values should be processed. + (function(xs:string) as xs:anyAtomicType)? + () + + + The supplied function is called to process the string value of any JSON number + in the input. By default, numbers are processed by + converting to xs:double using the XPath casting rules. + Supplying the value xs:decimal#1 will instead convert to xs:decimal + (which potentially retains more precision, but disallows exponential notation), while + supplying a function that casts to union(xs:decimal, xs:double) will treat + the value as xs:decimal if there is no exponent, or as xs:double + otherwise. Supplying the value fn:identity#1 causes the value to be retained + unchanged as an xs:string. Before calling the supplied number-parser, + the value is first checked to ensure that it conforms to the JSON grammar (for example, + a leading plus sign and redundant leading zeroes are not allowed); these checks are disabled + if the liberal option is set to true. + + + If no function is supplied, numbers are processed by casting the supplied value to + xs:double. + + + +
+ + + +

The various structures that can occur in JSON are transformed recursively to XDM values + as follows:

+ + + +

A JSON object is converted to a map. + The entries in the map correspond to the key/value + pairs in the JSON object. The key is always of type xs:string; the + associated value may be of any type, and is the result of converting the JSON + value by recursive application of these rules. For example, the JSON text + {"x":2, "y":5} is transformed to the value + map{"x":2, "y":5}.

+

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

+
+ +

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

+
+ +

A JSON string is converted to an xs:string value. + The handling of special characters depends on the + escape and fallback options, as described in the table above.

+
+ +

A JSON number is processed using the function supplied + in the number-parser option; by default it is converted to an xs:double value using + the rules for casting from xs:string to xs:double.

+
+ +

The JSON boolean values true and false are + converted to the corresponding xs:boolean values.

+
+ +

The JSON value null is converted to the empty sequence.

+
+
+ + +
+ +

A dynamic error occurs if the value of + $value does not conform to the JSON grammar, unless the option + "liberal":true() is present and the processor chooses to accept the deviation.

+ +

A dynamic error occurs if the option + "duplicates":"reject" is present and the value of + $value contains a JSON object with duplicate keys.

+ +

A dynamic error occurs if the $options + map contains an entry whose key is defined in this specification and whose value is not valid for that key, + or if it contains an entry with the key fallback when the option "escape":true() + is also present.

+
+ +

The result of the function will be an instance of one of the following types. An + instance of test (or in XQuery, typeswitch) can be used to + distinguish them:

+ + +

map(xs:string, item()?) for a JSON object

+
+ +

array(item()?) for a JSON array

+
+ +

xs:string for a JSON string

+
+ +

xs:double for a JSON number

+
+ +

xs:boolean for a JSON boolean

+
+ +

empty-sequence() for a JSON null (or for empty input)

+
+
+

If the input starts with a byte order mark, this function ignores it. The byte order mark may have been added + to the data stream in order to facilitate decoding of an octet stream to a character string, but since this function + takes a character string as input, the byte order mark serves no useful purpose.

+ +

The possibility of the input containing characters that are not valid in XML (for example, unpaired surrogates) + arises only when such characters are expressed using JSON escape sequences. The is because the input to the function + is an instance of xs:string, which by definition can only contain characters that are valid in XML.

+
+ + + + parse-json('{"x":1, "y":[3,4,5]}') + map{"x":1e0,"y":[3e0,4e0,5e0]} + + + parse-json('"abcd"') + "abcd" + + + parse-json('{"x":"\\", "y":"\u0025"}') + map{"x":"\","y":"%"} + + + parse-json( + '{"x":"\\", "y":"\u0025"}', + map { 'escape': true() } +) + map{"x":"\\","y":"%"} + + + parse-json( + '{"x":"\\", "y":"\u0000"}' +) + map{"x":"\","y":codepoints-to-string(65533)} + + + parse-json( + '{"x":"\\", "y":"\u0000"}', + map { 'escape': true() } +) + map{"x":"\\","y":"\u0000"} + + + parse-json( + '{"x":"\\", "y":"\u0000"}', + map { + 'fallback': function($s) { '['||$s||']' } + } +) + map{"x":"\","y":"[\u0000]"} + + + +
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + +

Reads an external resource containing JSON, and returns the result of parsing the resource as JSON.

+
+ +

The effect of the single-argument call fn:json-doc($H) is the same as the effect of the two-argument call + fn:json-doc($H, map{}) where an empty map is supplied as the second argument.

+

The effect of the two-argument function call fn:json-doc($H, $M)is equivalent to the function composition + fn:unparsed-text($H) => fn:parse-json($M); except that:

+ + + +

The function may accept a resource in any encoding. requires + UTF-8, UTF-16, or UTF-32 to be accepted, but it is not an error if a different encoding is used. + Unless external encoding information is available, the function must + assume that the encoding is one of UTF-8, UTF-16, or UTF-32, and must distinguish these cases by examination + of the initial octets of the resource.

+
+ +

If the resource contains characters that are not + permitted characters, + then rather than raising an error as fn:unparsed-text#1 does, the function replaces such characters by the equivalent + JSON escape sequence prior to parsing.

+ +

Equivalently, the implementation can use some other internal representation of strings that allows non-XML characters to + be manipulated.

+
+
+
+ +

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

+ + + +
+ +

The function may raise any error defined for the fn:unparsed-text or fn:parse-json + functions.

+
+ +

If the input cannot be decoded (that is, converted into a sequence of Unicode codepoints, which may or may not represent characters), + then a dynamic error occurs as with the fn:unparsed-text function.

+

If the input can be decoded, + then the possibility still arises that the resulting sequence of codepoints includes codepoints that do not represent characters that are valid in the + version of XML that the processor supports. Such codepoints are translated into JSON escape sequences (for example, \uFFFF), + and the JSON escape sequence is then passed to the fallback function specified in the $options argument, which in turn + defaults to a function that returns the Unicode REPLACEMENT CHARACTER (xFFFD).

+
+
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Creates a JSON representation of an arbitrary XDM value.

+
+ +

This function returns a string, in JSON format, containing a representation of the + supplied input $input. The function is error-free (it accepts any input sequence + whatsoever), but it is not lossless: there are cases when two different XDM values will + have the same JSON representation. For example, the sequence (1, 2) + and the array [1, 2] are both output as [1,2].

+ +

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

+ + + + Determines whether additional whitespace should be added to the output to improve readability. + xs:boolean + false + + + The processor must not insert any insignificant whitespace between JSON tokens. + + + The processor may insert whitespace between JSON tokens in order to improve readability. + The specification imposes no constraints on how this is done. + + + + + Determines whether elements whose children are element nodes with distinct + names should be treated specially. + xs:boolean + true + + + The processor treats such elements in the same way as any other element. + + + The processor generates a JSON object in which the child element names are used + as JSON property names. + + + + + + +

An input sequence is handled as follows:

+ +

An empty sequence is output as the JSON value null.

+

A singleton sequence is output following the rules for processing items, below.

+

A sequence of two or more items results in a JSON array, whose members are constructed + from the items by applying the rules below.

+
+ +

Items are processed as follows:

+ + + +

Atomic values

+ +

An xs:boolean value is output as the JSON value true or false.

+

A numeric value, other than INF, -INF, or NaN, + is output as a JSON number.

+

Any other atomic value is cast to xs:string, and the result is output as a JSON string, + escaped as described below.

+
+
+ +

Nodes

+ + +

Document nodes

+

A document node is output as a JSON object with two properties, in order:

+ +

A property #document set to the value of the base URI of the document + if available, or an empty string otherwise..

+

A property #content whose value follows the rules for + outputting the content of an element node, given below.

+
+
+ +

Element nodes

+

An element node is output as a JSON object with the following properties, in order:

+ + +

#element set to the local name of the element.

+
+ +

If the element name has a prefix, #prefix, set to the value of the prefix.

+
+ + +

If the element name is in a namespace, #namespace, set to the value of the + namespace URI.

+
+ +

For each attribute of the element, in arbitrary order, a property whose + name is derived from the attribute name as follows:

+ +

If the attribute name is in no namespace, then "@" followed + by the local name.

+

If the attribute name is in the XML namespace, then "@xml:" followed + by the local name.

+

Otherwise "@Q{uri}local" where uri is the namespace + URI and local is the local name.

+
+ +

The property value is the result of atomizing the attribute node and applying the + fn:json function to the result. (For untyped attributes, the result + will always be a single string.)

+ + +
+ +

The children of the element are processed as follows:

+ + +

If there are no children, nothing is output.

+
+ +

If the element has a type annotation that is a simple type, or if its content + comprises a single text node, then a property #value set to the result + of atomizing the element node and applying the fn:json function + to the result.

+
+ +

If (a) the children consist exclusively of elements and whitespace-only + text nodes, and (b) the child element nodes are all in the same namespace, or all in no + namespace, and (c) each child element has a local name that is distinct from the local + name of any other child, and (d) the element-map option is not + present in $options with the value false(), + then a property #content whose value is a JSON + object having one property for each child element node. The name of this property + is the local name of the element, and the value of the property is obtained by applying + these rules recursively, except that for an empty element, the value is represented + as JSON null.

+
+

Otherwise, a property #content whose value is an array, with + one member for each child node (including whitespace-only text nodes), obtained + by applying the fn:json function to that child node.

+
+
+
+
+ +

Text nodes

+

A JSON object with a single property #text whose value is the + string value of the text node.

+
+ +

Comment nodes

+

A JSON object with a single property #comment whose value is the + string value of the comment.

+
+ +

Processing instruction nodes

+

A JSON object with a two properties (in order): #processing-instruction set to the + name of the processing instruction, and #data set to the + string value of the processing instruction node.

+
+ +

Attribute nodes

+

Attribute nodes that are reached via an element node are output as described + under “element nodes”, above.

+

Free-standing attribute nodes are output as JSON objects with properties + #attribute set to the local name of the attribute, #prefix + (if non-empty) set to the prefix of the attribute’s name, #namespace + (if non-empty) set to the namespace URI, and #value set to + the result of atomizing the attribute value and applying the + fn:json function to the result.

+
+

Namespace nodes

+

Namespace nodes that are reached via an element node result in no output.

+

Free-standing namespace nodes are output as JSON objects with properties + #namespace set to the namespace prefix ("" for the default + namespace) and #uri set to the namespace URI.

+
+
+ +

Maps

+

An XDM map is output as a JSON object with one property for each entry in the map.

+

The property name is derived from the key value by converting the value to a string + and applying escaping rules. If the property name thus generated is the same as a previously output + property name, then it is made unique by appending "(N)" where N is the smallest + positive integer that makes the resulting value unique.

+

The property value is derived by applying the fn:json function to the value in the map entry.

+ +

Conflicts between property names can arise because the XDM model allows keys of different types, + for example the xs:date value 2020-12-31 and the string value + "2020-12-31" can co-exist. The map map{xs:duration('PT1D'):20, "PT1D":30} + is converted to the JSON string {"PT1D":20,"PT1D(1)":30} or + {"PT1D":30,"PT1D(1)":20}, depending on the (unpredictable) order in which the + entries in the map are processed.

+

Because the order of entries in a map is unpredictable, the order in which the + properties are listed in the JSON output is also unpredictable.

+
+ +

Arrays

+

An XDM array is output as a JSON array. Each member of the XDM array generates one entry in the + JSON array, in order, obtained by applying the fn:json function to the XDM array member.

+
+ +

Functions

+

An XDM function, other than a map or array, is output as a JSON object with the following + properties:

+ +

#function, set to the local name of the function + if it has a name, or the empty string otherwise.

+

#namespace, set to the namespace URI of the function. The property + is omitted for an anonymous function.

+

#arity, set to the arity of the function as a JSON number.

+

#arguments whose value is an array + of strings, which identify the names and types of the function arguments, + in the format $Q{uri}local as SequenceType: for example + ["$x as double", "$y as string"]. Namespace prefixes must not be used: + unprefixed element names and variable names are taken to be in no namespace, and unprefixed + type names are taken to be in the namespace http://www.w3.org/2001/XMLSchema. +

+

#result whose value is a string + identifying the type of the function result, using the same conventions as for #arguments.

+

Optionally at implementer discretion, #implementation whose value is a string + representing the function’s implementation in implementation-defined format.

+
+

Strings are escaped as follows:

+ + +

Any occurrence of backslash is replaced by \\

+
+ + +

Any occurrence of quotation mark, backspace, form-feed, newline, carriage return, or tab is + replaced by \", \b, \f, \n, \r, or \t respectively;

+
+ + +

Any other codepoint in the range 1-31 or 127-159 is replaced by an escape in + the form \uHHHH where HHHH is the upper-case hexadecimal representation of the codepoint value.

+
+
+
+
+
+ +

In the JSON output, names of properties defined in this specification are prefixed with #; + names not so prefixed are derived from names appearing in the input.

+

Namespace information may be lost (specifically, namespaces that are declared but not used are + not retained in the output).

+

The distinction between sequences and arrays is lost.

+

The distinction between different atomic types is lost, except for the boolean / number / string + distinction present in JSON.

+

In elements whose children are elements with distinct names, whitespace text nodes are lost, + and the namespace URIs and prefixes of the child elements are lost.

+
+ + + + json(()) + 'null' + + + json(12) + '12' + + + json((12, "December")) + '[12,"December"]' + + + json(true()) + 'true' + + + json(map{"a":1,"b":number('NaN'),"c":(1,2,3)}) + '{"a":1,"b":"NaN","c":[1,2,3]}' + (or some permutation thereof) + + + banana)]]> + '{"#element":"a","@x":"2","#value":"banana"}' + + + 2)]]> + '{"#element":"a","#content":{"b":null,"c":"2"}}' + + + )]]> + '{"#name":"a","#content":[{"#name":"b"},{"#name":"b"},{"#name":"c}]}' + + + A nice one!)]]> + '{"#name":"a","#content":["A ",{"#name":"i", "#value":"nice"}," one!"]}' + + + + + Proposed for 4.0; not yet reviewed. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the number of members in the supplied array.

+
+ +

Informally, the function returns the number of members in the array.

+

More formally, the function returns the value of fn:count(array:members($array)).

+
+ +

Note that because an array is an item, the fn:count function + when applied to an array always returns 1.

+
+ + + + array:size(["a", "b", "c"]) + 3 + + + array:size(["a", ["b", "c"]]) + 2 + + + array:size([ ]) + 0 + + + array:size([[ ]]) + 1 + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns true if the supplied array contains no members.

+
+ +

The function returns true if and only if $array contains no members, that is, + if array:size($array) eq 0.

+
+ +

The test for emptiness is not the same as the test used by the + xsl:on-empty instruction in XSLT. For example, an array + is not considered empty by this function if it contains a single + member that is itself an empty array.

+
+ + + + array:empty(["a", "b", "c"]) + false() + + + array:empty([]) + true() + + + array:empty([[]]) + false() + + + array:empty([()]) + false() + + + + + Proposed for 4.0, see issue 229 + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns true if the supplied array contains one or more members.

+
+ +

The function returns true if and only if $array contains one or more members, that is, + if array:size($array) gt 0.

+
+ +

The function name is chosen by analogy with fn:exists. Note that the function tests whether + any array members exist, not whether the array itself exists. A function such as:

+ function($a as array(*)?) as xs:boolean { return array:exists($a) } +

will raise a type error (rather than returning false) if the argument $a is + an empty sequence, because array:exists does not allow the argument to be + an empty sequence.

+
+ + + + array:exists(["a", "b", "c"]) + true() + + + array:exists([]) + false() + + + array:exists([[]]) + true() + + + array:exists([()]) + true() + + + + + Proposed for 4.0, see issue 229 + +
+ + + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the value at the specified position in the supplied array + (counting from 1).

+
+ +

Informally, the function returns the member at a specified position in the array. + If $position is less than one or greater than array:size($array), + then the $fallback function is called, supplying the value of $position + as the argument value; and the result of this call is returned.

+

The default $fallback function raises a dynamic error. The call on fn:error + shown as the default is for illustrative purposes only; apart from the error code (err:FOAY0001) + the details of the error (such as the error message) are implementation-dependent.

+

More formally, the function returns the value of:

+ if ($position = (1 to array:size($array))) +then array:members($array)[$position]?value +else $fallback($position) +
+ +

In the absence of a $fallback function, + a dynamic error occurs if $position is not in the range 1 to + array:size($array) inclusive.

+
+ + + + ["a", "b", "c"] => array:get(2) + "b" + + + ["a", ["b", "c"]] => array:get(2) + ["b", "c"] + + + ["a"] => array:get(1, void#1) + "a" + + + [] => array:get(1, void#1) + () + + + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an array containing all the members of a supplied array, except for one member which is replaced with a new value.

+
+ +

Informally, the result is an array whose size is array:size($array), in which all + members in positions other than $position are the same as the members in the corresponding position + of $array, and the member in position $position is $member.

+

More formally, the result is the value of the expression + $array => array:remove($position) => array:insert-before($position, $member).

+ +
+ +

A dynamic error occurs if $position is not in the range 1 to + array:size($array) inclusive.

+

This error will always occur if $array is empty.

+
+ + + + array:put(["a", "b", "c"], 2, "d") + ["a", "d", "c"] + + + array:put(["a", "b", "c"], 2, ("d", "e")) + ["a", ("d", "e"), "c"] + + + array:put(["a"], 1, ["d", "e"]) + [["d", "e"]] + + + + + First introduced in 3.1. + Unchanged in 4.0. + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an array containing all the members of a supplied array, except for one member which is replaced with a new value, + the new value being computed from the previous value.

+
+ +

Informally, the result is an array whose size is array:size($array), in which all + members in positions other than $position are the same as the members in the corresponding position + of $array, and the member in position $position is the result of applying + the $action function to the original value in that position.

+

More formally, the result is the value of the expression + $array => array:remove($position) => array:insert-before($position, $action($array($position))).

+ +
+ +

A dynamic error occurs + if $position is not in the range 1 to + array:size($array) inclusive.

+

This error will always occur if $array is empty.

+
+ + + + array:replace([10, 11, 12], 2, function { . + 10 }) + [10, 21, 12] + + + array:replace(["a", "b", "c"], 2, concat(?, "x")) + ["a", "bx", "c"] + + + array:replace([("a", "b"), ("c", "d")], 2, reverse#1) + [("a", "b"), ("d", "c")] + + + + + First introduced in 4.0. + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an array containing all the members of a supplied array, plus one additional member at the end.

+
+ +

Informally, the result is an array whose size is array:size($array) + 1, in which all + members in positions 1 to array:size($array) are the same as the members in the corresponding position + of $array, and the member in position array:size($array) + 1 is $member.

+

More formally, the result is the value of the expression + array:of-members((array:members($array), map{'value':$member})).

+ +
+ + + + array:append(["a", "b", "c"], "d") + ["a", "b", "c", "d"] + + + array:append(["a", "b", "c"], ("d", "e")) + ["a", "b", "c", ("d", "e")] + + + array:append(["a", "b", "c"], ["d", "e"]) + ["a", "b", "c", ["d", "e"]] + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Concatenates the contents of several arrays into a single array.

+
+ +

Informally, the function concatenates the members of several arrays into a single array.

+

More formally, the function returns the result of + array:of-members($arrays ! array:members(.)).

+
+ + + + array:join(()) + [ ] + + + array:join([1, 2, 3]) + [1, 2, 3] + + + array:join((["a", "b"], ["c", "d"])) + ["a", "b", "c", "d"] + + + array:join((["a", "b"], ["c", "d"], [ ])) + ["a", "b", "c", "d"] + + + array:join((["a", "b"], ["c", "d"], [["e", "f"]])) + ["a", "b", "c", "d", ["e", "f"]] + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an array containing all members from a supplied array starting at a supplied + position, up to a specified length.

+
+ +

Except in error cases, + the two-argument version of the function returns the same result as the three-argument + version when called with $length equal to the value of array:size($array) - + $start + 1.

+

Setting the third argument to the empty sequence has the same effect as omitting the argument.

+

Except in error cases, the result of the three-argument version of the function is the + value of the expression + array:of-members(array:members($array) => fn:subsequence($start, $length)).

+
+ +

A dynamic error is raised if $start is less than one + or greater than array:size($array) + 1.

+

For the three-argument version of the function:

+ + +

A dynamic error is raised + if $length is less than zero.

+
+ +

A dynamic error is raised + if $start + $length is greater than array:size($array) + 1.

+
+
+
+ +

The value of $start can be equal to array:size($array) + 1 provided that $length + is either equal to zero or omitted. In this case the result will be an empty array.

+
+ + + + array:subarray(["a", "b", "c", "d"], 2) + ["b", "c", "d"] + + + array:subarray(["a", "b", "c", "d"], 5) + [ ] + + + array:subarray(["a", "b", "c", "d"], 2, 0) + [ ] + + + array:subarray(["a", "b", "c", "d"], 2, 1) + ["b"] + + + array:subarray(["a", "b", "c", "d"], 2, 2) + ["b", "c"] + + + array:subarray(["a", "b", "c", "d"], 5, 0) + [ ] + + + array:subarray([ ], 1, 0) + [ ] + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the position in an input array of members that match a supplied predicate.

+
+ + +

The result of the function is a sequence of integers, in monotonic ascending order, representing + the 1-based positions in the input array of those members for which the supplied predicate function + returns true.

+

More formally, the function returns the result of the expression:

+ index-of(array:for-each($input, $predicate)?*, true()) +
+ + + + + array:index-where([], boolean#1) + () + + + array:index-where([0, (), 4, 9], boolean#1) + (3, 4) + + + array:index-where( + array { 1 to 10 }, + function {. mod 2 = 0 } +) + (2, 4, 6, 8, 10) + + + array:index-where( + [ "January", "February", "March", "April", + "May", "June", "July", "August", "September", + "October", "November", "December" ], + contains(?, "r") +) + (1, 2, 3, 4, 9, 10, 11, 12) + + + array:index-where( + [(1, 2, 3), (4, 5, 6), (7, 8)], + function($m) { count($m) = 3 } +) + (1, 2) + + + + + Approved 2022-12-13 for inclusion in 4.0 - issue #114 + +
+ + + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an array containing selected members of a supplied input array based on their position.

+
+ +

Returns the value of array:of-members(array:members($array) => fn:slice($start, $end, $step))

+
+ +

The function is formally defined by converting the array to a sequence, applying + fn:slice to this sequence, and then converting the resulting sequence + back to an array.

+

Note that unlike other operations on arrays, there are no out-of-bounds errors for inappropriate + values of $start, $end, or $step.

+
+ + + + + + array:slice($in, start := 2, end := 4) + ["b", "c", "d"] + + + array:slice($in, start := 2) + ["b", "c", "d", "e"] + + + array:slice($in, end := 2) + ["a", "b"] + + + array:slice($in, start := 3, end := 3) + ["c"] + + + array:slice($in, start := 4, end := 3) + ["d", "c"] + + + array:slice($in, start := 2, end := 5, step := 2) + ["b", "d"] + + + array:slice($in, start := 5, end := 2, step := -2) + ["e", "c"] + + + array:slice($in, start := 2, end := 5, step := -2) + [] + + + array:slice($in, start := 5, end := 2, step := 2) + [] + + + array:slice($in) + ["a", "b", "c", "d", "e"] + + + array:slice($in, start := -1) + ["e"] + + + array:slice($in, start := -3) + ["c", "d", "e"] + + + array:slice($in, end := -2) + ["a", "b", "c", "d"] + + + array:slice($in, start := 2, end := -2) + ["b", "c", "d"] + + + array:slice($in, start := -2, end := 2) + ["d", "c", "b"] + + + array:slice($in, start := -4, end := -2) + ["b", "c", "d"] + + + array:slice($in, start := -2, end := -4) + ["d", "c", "b"] + + + array:slice($in, start := -4, end := -2, step := 2) + ["b", "d"] + + + array:slice($in, start := -2, end := -4, step := -2) + ["d", "b"] + + + array:slice(["a", "b", "c", "d"], 0) + ["a", "b", "c", "d"] + + + + + Proposed for 4.0; not yet reviewed?. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an array containing all the members of the supplied array, except for the + members at specified positions.

+
+ +

Informally, the function returns an array of size array:size($array) - fn:count(fn:distinct-values($positions)) + containing all members from $array + except the members whose position (counting from 1) is present in the sequence $positions. + The order of the remaining members is preserved.

+

More formally, the result of the function, except in error cases, is given by the expression + array:of-members(array:members($array) => fn:remove($positions)). +

+
+ +

A dynamic error is raised if any integer in $positions is not in the range 1 to + array:size($array) inclusive. By implication, an error occurs if $array is empty, unless $positions + is also empty.

+
+ + + + array:remove(["a", "b", "c", "d"], 1) + ["b", "c", "d"] + + + array:remove(["a", "b", "c", "d"], 2) + ["a", "c", "d" ] + + + array:remove(["a"], 1) + [ ] + + + array:remove(["a", "b", "c", "d"], 1 to 3) + ["d"] + + + array:remove(["a", "b", "c", "d"], ()) + ["a", "b", "c", "d"] + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an array containing all the members of the supplied array, with one additional member at a specified position.

+
+ +

Informally, the function returns an array of size array:size($array) + 1 + containing all members from $array + whose position is less than $position, then a new member given by $member, and + then all members from $array whose position is greater than or equal to $position. + Positions are counted from 1.

+

More formally, except in error cases, the result is the value of the expression + array:of-members(array:members($array) => fn:insert-before($position, map{'value':$member})).

+
+ +

A dynamic error occurs if $position is not in the range 1 to + array:size($array) + 1 inclusive.

+
+ +

Setting $position to 1 has the effect of prepending the new member at the start of the array. Setting $position + to the value array:size($array) + 1 delivers the same result as array:append($array, $member).

+
+ + + + array:insert-before( + ["a", "b", "c", "d"], + 3, + ("x", "y") +) + ["a", "b", ("x", "y"), "c", "d"] + + + array:insert-before( + ["a", "b", "c", "d"], + 5, + ("x", "y") +) + ["a", "b", "c", "d", ("x", "y")] + + + array:insert-before( + ["a", "b", "c", "d"], + 3, + ["x", "y"] +) + ["a", "b", ["x", "y"], "c", "d"] + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the first member of an array, that is $array(1).

+
+ +

The function returns first member of $array, + that is the value of array:get($array, 1).

+
+ +

A dynamic error occurs if $array is empty.

+
+ + + + array:head([5, 6, 7, 8]) + 5 + + + array:head([["a", "b"], ["c", "d"]]) + ["a", "b"] + + + array:head([("a", "b"), ("c", "d")]) + "a", "b" + + + + + First introduced in 3.1. + Unchanged in 4.0. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the last member of an array, that is $array(array:size($array)).

+
+ +

The function returns last member of $array, that is the value of array:get($array, array:size($array)).

+
+ +

A dynamic error occurs if $array is empty.

+
+ + + + array:foot([5, 6, 7, 8]) + 8 + + + array:foot([["a", "b"], ["c", "d"]]) + ["c", "d"] + + + array:foot([("a", "b"), ("c", "d")]) + "c", "d" + + + + + Proposed and accepted for 4.0, see issue 97 + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an array containing all members except the first from a supplied array.

+
+ +

The function returns an array containing all members of the supplied array except the first, + that is array:remove($array, 1).

+
+ +

A dynamic error occurs if $array is empty.

+
+ +

If the supplied array contains exactly one member, the result will be an empty array.

+
+ + + + array:tail([5, 6, 7, 8]) + [6, 7, 8] + + + array:tail([5]) + [ ] + + + + + First introduced in 3.1. + Unchanged in 4.0. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an array containing all members except the last from a supplied array.

+
+ +

The function returns an array containing all members of the supplied array except the last, + that is array:remove($array, array:size($array)).

+
+ +

A dynamic error occurs if $array is empty.

+
+ +

If the supplied array contains exactly one member, the result will be an empty array.

+
+ + + + array:trunk([5, 6, 7, 8]) + [5, 6, 7] + + + array:trunk([5]) + [ ] + + + + + Proposed and accepted for 4.0, see issue 97 + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns an array containing all the members of a supplied array, but in reverse order.

+
+ +

The function returns the result of the expression: + array:of-members(array:members($array) => fn:reverse())

+
+ + + + array:reverse(["a", "b", "c", "d"]) + ["d", "c", "b", "a"] + + + array:reverse([("a", "b"), ("c", "d")]) + [("c", "d"), ("a", "b")] + + + array:reverse([(1 to 5)]) + [(1, 2, 3, 4, 5)] + + + array:reverse([]) + [] + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Returns an array whose size is the same as array:size($array), in which + each member is computed by applying $function to the corresponding member of + $array.

+
+ +

Informally, the function returns an array whose members are obtained by applying + the supplied $function to each member of the input array in turn.

+

More formally, the function returns the result of the expression + array:of-members(array:members($array) ! map { 'value': $action(?value) }.

+
+ + + + array:for-each( + [ "A", "B", 1, 2 ], + function($z) { $z instance of xs:integer } +) + [false(), false(), true(), true()] + + + array:for-each( + [ "the cat", "sat", "on the mat" ], + tokenize#1 +) + [("the", "cat"), "sat", ("on", "the", "mat")] + + + array:for-each( + [ [ "the", "cat" ], [ "sat" ], [ "on", "the", "mat" ] ], + array:flatten#1 +) + [("the", "cat"), "sat", ("on", "the", "mat")] + + + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Returns an array containing those members of the $array for which + $predicate returns true.

+
+ +

Informally, the function returns an array containing those members of the input + array that satisfy the supplied predicate.

+

More formally, the function returns the result of the expression + array:of-members(array:members($array) => fn:filter(function($m) { $predicate($m?value) }).

+ +
+ +

As a consequence of the function signature and the function calling rules, a type error occurs if the supplied + function $function returns anything other than a single xs:boolean item; there is no conversion + to an effective boolean value.

+
+ + + + array:filter( + ["A", "B", 1, 2], + function($x) { $x instance of xs:integer } +) + [1, 2] + + + array:filter( + ["the cat", "sat", "on the mat"], + function { count(tokenize(.)) > 1 } +) + ["the cat", "on the mat"] + + + array:filter(["A", "B", "", 0, 1], boolean#1) + ["A", "B", 1] + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Evaluates the supplied function cumulatively on successive members of the supplied + array.

+
+ +

The result of the function is the value of the expression + array:members($array) => fn:fold-left($zero, function($a, $b) { $action($a, $b?value })

+ +
+ +

If the supplied array is empty, the function returns $zero.

+

If the supplied array contains a single member $m, the function returns $zero => $action($m).

+

If the supplied array contains two members $m and $n, the function returns + $zero => $action($m) => $action($n); and similarly for an input array with more than two members.

+
+ + + + array:fold-left( + [true(), true(), false()], + true(), + function($x, $y) { $x and $y } +) + false() + Returns true if every member of the input array has an effective boolean value of true(). + + + array:fold-left( + [true(), true(), false()], + false(), + function($x, $y) { $x or $y } +) + true() + Returns true if at least one member of the input array has an effective boolean value of true(). + + + array:fold-left( + [ 1, 2, 3 ], + [], + function($x, $y) { [ $x, $y ] } +) + [[[[], 1], 2], 3] + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Evaluates the supplied function cumulatively on successive values of the supplied + array.

+
+ +

The result of the function is the value of the expression + array:members($array) => fn:fold-right($zero, function($a, $b) { $action($a, $b?value })

+ +
+ +

If the supplied array is empty, the function returns $zero.

+

If the supplied array contains a single member $m, the function returns $action($m, $zero).

+

If the supplied array contains two members $m and $n, the function returns + $action($m, $action($n, $zero)); and similarly for an input array with more than two members.

+
+ + + + array:fold-right( + [true(), true(), false()], + true(), + function($x, $y) { $x and $y } +) + false() + Returns true if every member of the input array has an effective boolean value of true(). + + + array:fold-right( + [true(), true(), false()], + false(), + function($x, $y) { $x or $y } +) + true() + Returns true if at least one member of the input array has an effective boolean value of true(). + + + array:fold-right( + [ 1, 2, 3 ], + [], + function($x, $y) { [ $x, $y ] } +) + [1, [2, [3, []]]] + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Returns an array obtained by evaluating the supplied function once for each pair of members at the same position in + the two supplied arrays.

+
+ +

The function returns the result of the expression:

+ array:of-members( + for-each-pair(array:members($array1), + array:members($array2), + function($m, $n) {map{'value': $action($m?value, $n?value)}})) + + +
+ +

If the arrays have different size, excess members in the longer array are ignored.

+
+ + + + array:for-each-pair( + ["A", "B", "C"], + [1, 2, 3], + function($x, $y) { array { $x, $y }} +) + [["A", 1], ["B", 2], ["C", 3]] + + + let $array := ["A", "B", "C", "D"] +return array:for-each-pair( + $array, + array:tail($array), + concat#2 +) + ["AB", "BC", "CD"] + + + + + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Returns an array obtained by evaluating the supplied function once for each item in the input sequence.

+
+ +

If the function is called with one argument, the effect is the same as calling the two-argument + function with fn:identity#1 as the second argument.

+

Informally, array:build#2 applies the supplied function to each item + in the input sequence, and the resulting sequence becomes one member of the returned array.

+

More formally, array:build#2 returns the result of the expression:

+ array:of-members($input ! map{'value':$action(.)}) +
+ +

The single-argument function array:build($input) is equivalent to the XPath + expression array{$input}, but it is useful to have this available as a function.

+

The two-argument form facilitates the construction of arrays whose members are arbitrary + sequences.

+

See also array:for-each, which provides similar functionality for the + case where the input is an array rather than a sequence.

+
+ + + + array:build(1 to 5) + [1, 2, 3, 4, 5] + + + array:build( + 1 to 5, + function { 2 * . } +) + [2, 4, 6, 8, 10] + + + array:build( + 1 to 5, + function { 1 to . } +) + [1, (1,2), (1,2,3), (1,2,3,4), (1,2,3,4,5)] + + + array:build( + ("red", "green", "blue"), + characters#1 +) + [("r", "e", "d"), ("g", "r", "e", "e", "n"), ("b", "l", "u", "e")] + + + array:build( + 1 to 5, + function { array { 1 to . } } +) + [[1], [1,2], [1,2,3], [1,2,3,4], [1,2,3,4,5]] + + + + + Proposed for 4.0. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Delivers the contents of an array as a sequence of value records.

+
+ +

The members of the array are delivered as a sequence of value records. + A value record is an item that encapsulates an arbitrary sequence $S: specifically + it is a map comprising a single entry whose key is the xs:string value + "value" and whose corresponding value is $S. The content encapsulated + by a value record $V can be obtained using the expression $V?value.

+ + +
+ +

This function is the inverse of array:of-members.

+
+ + + + + array:members([]) + () + + + array:members([1 to 5])?value + (1, 2, 3, 4, 5) + + + array:members([(1,1), (2,4), (3,9), (4,16), (5,25)]) +! sum(?value) + (2, 6, 12, 20, 30) + + + let $array := [ "any array" ] +return deep-equal( + $array, + array:of-members(array:members($array)) +) + true() + + + + + Proposed for 4.0, see issues 29, 113, 314. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Delivers the contents of an array as a sequence of singleton arrays.

+
+ +

The members of the array are delivered as a sequence of arrays. + Each returned array encapsulates the value of a single array member.

+
+ +

The function call array:split($array) produces the same result as the + expression for member $m in $array return [ $m ].

+

This function is the inverse of array:join.

+
+ + + + + array:split([]) + () + + + array:split([ () ]) + [ () ] + + + array:split([ 1 to 5 ]) + [ (1, 2, 3, 4, 5) ] + + + array:split( + array { 1 to 5 } +) + [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ] + + + array:split( + [ (1,1), (2,4), (3,9), (4,16), (5,25) ] +) ! sum(.) + 2, 6, 12, 20, 30 + + + let $array := [ "any array" ] +return deep-equal( + $array, + array:join(array:split($array)) +) + true() + + + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Constructs an array from the contents of a sequence of value records.

+
+ +

The input items must be value records. A value record is an item that encapsulates + an arbitrary sequence $S: specifically + it is a map comprising a single entry whose key is the xs:string value + "value" and whose corresponding value is $S. The content encapsulated + by a value record $V can be obtained using the expression $V?value.

+ + +
+ +

This function is the inverse of array:members.

+ + +
+ + + + array:of-members(()) + [] + + + array:of-members(map { 'value': (1 to 5) }) + [(1, 2, 3, 4, 5)] + + + array:of-members((1 to 5) ! map { 'value': . }) + [1, 2, 3, 4, 5] + + + array:of-members((1 to 5) ! map { 'value': (., .*.) }) + [(1,1), (2,4), (3,9), (4,16), (5,25)] + + + + + Proposed for 4.0, see issues 29, 113, 314. + +
+ + + + + + + + + + + deterministic + context-dependent + focus-independent + + + deterministic + context-dependent + focus-independent + + + deterministic + context-independent + focus-independent + + + +

Returns an array containing all the members of the supplied array, sorted + according to the value of a sort key supplied as a function.

+
+ +

Calling the single-argument version of the function is equivalent to calling the two-argument form + with default-collation() as the second argument: that is, it sorts the members of an array according + to the typed value of the items, using the default collation to compare strings.

+ +

Calling the two-argument version of the function is equivalent to calling the three-argument form + with fn:data#1 as the third argument: that is, it sorts the members of an array according + to the typed value of the items, using a specified collation to compare strings.

+ +

In the case of both array:sort#2 and array:sort#3, supplying an empty + sequence as the second argument is equivalent to supplying fn:default-collation(). For more + information on collations see .

+ +

The result of array:sort#3 is the value of the expression + array:of-members(array:members($array) => sort($collation, function($x) { $key($x?value) }))

+
+ +

If the set of computed sort keys contains values that are not comparable using the le operator then the sort + operation will fail with a dynamic error. +

+
+ + + + array:sort([1, 4, 6, 5, 3]) + [1, 3, 4, 5, 6] + + + array:sort([1, -2, 5, 10, -10, 10, 8], (), abs#1) + [1, -2, 5, 8, 10, -10, 10] + + + array:sort([(1,0), (1,1), (0,1), (0,0)]) + [(0,0), (0,1), (1,0), (1,1)] + + + +

To sort an array of strings $in using Swedish collation:

+ +let $SWEDISH := "http://www.w3.org/2013/collation/UCA?lang=se" +return array:sort($in, $SWEDISH) + +
+ +

To sort an array of maps representing employees, using last name as the major sort key and first name as the minor sort key, + with the default collation: +

+ array:sort($employees, (), function($emp) {$emp?name?last, $emp?name?first}) +
+
+ + First introduced in 3.1. + Functionality unchanged in 4.0, but the specification has been formalized. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Replaces any array appearing in a supplied sequence with the members of the array, recursively.

+
+ +

The function processes the items in the supplied sequence $input as follows:

+ + +

An item that is an array is replaced by its members, retaining order.

+
+ +

Any other item is retained unchanged.

+
+
+

The process is then repeated so long as the sequence contains an array among its items.

+

The function is equivalent to the following XQuery implementation (assuming static typing is not in force):

+ declare function flatten ($S as item()*) { + for $s in $S return ( + typeswitch($s) + case $a as array(*) return flatten($a?*) + default return $s +)} + +
+ +

The argument to the function will often be a single array item, but this is not essential.

+

Unlike atomization, this function retains any nodes contained in the array.

+
+ + + + array:flatten([1, 4, 6, 5, 3]) + (1, 4, 6, 5, 3) + + + array:flatten(([1, 2, 5], [[10, 11], 12], [], 13)) + (1, 2, 5, 10, 11, 12, 13) + + + array:flatten([(1,0), (1,1), (0,1), (0,0)]) + (1, 0, 1, 1, 0, 1, 0, 0) + + + + + First introduced in 3.1. + Retained unchanged. + +
+ + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a sequence with the members of an array.

+
+ +

The function concatenates the members of $array and returns them as + a sequence. The values are returned in their original order. + Arrays contained within members are returned unchanged.

+

The effect of the function is equivalent to $array?*.

+
+ + + + array:values(array { "one", "two", "three" }) + ("one", "two", "three") + + + array:values([ (), 1, (2 to 4), [ 5 ] ]) + (1, 2, 3, 4, [ 5 ]) + + + +
+ + + + + + + + + + deterministic + context-dependent + focus-dependent + + + +

Provides access to the public functions and global variables of a dynamically loaded XQuery library module.

+
+ +

The function loads an implementation-defined set of modules having the target namespace $module-uri.

+

Calling the one-argument version of the function has the same effect as calling the two-argument version with an empty map + as the second argument.

+

The $options argument can be used to control the way in which the function operates. + The option parameter conventions apply.

+ + + + + The minimum level of the XQuery language that the + processor must support. + xs:decimal + The version given in the prolog of the library module; or + implementation-defined if this is absent. + + + A sequence of URIs (in the form of xs:string values) which may be used or ignored in an + implementation-defined way. + xs:string* + Empty sequence + + + The item to be used as the initial context item when evaluating global variables in the library module. Supplying + an empty sequence is equivalent to omitting the entry from the map, and indicates the absence of a context item. + If the library module specifies a required type for the context item, then the supplied value must conform to + this type, without conversion. + item()? + Absent + + + Values for external variables defined in the library module. Values must be supplied + for external variables that have no default value, and may be supplied for external variables + that do have a default value. The supplied value must conform to the required type of the variable, without conversion. + The map contains one entry for each external variable: the key is the variable’s name, and the associated value is + the variable’s value. The option parameter conventions do not apply + to this contained map. + map(xs:QName, item()*) + An empty map + + + Values for vendor-defined configuration options for the XQuery processor used to process the request. The key is the + name of an option, expressed as a QName: the namespace URI of the QName should be a URI controlled + by the vendor of the XQuery processor. The meaning of the associated value is implementation-defined. + Implementations should ignore options whose names are in an unrecognized namespace. + The option parameter conventions do not apply + to this contained map. + map(xs:QName, item()*) + An empty map + + + + +

The result of the function is a map R with two entries:

+ + +

There is an entry whose key is the xs:string value "variables" and whose associated value + is a map V. This map (V) contains one entry for each public global variable declared in the library module. + The key of the + entry is the name of the variable, as an xs:QName value; the associated value is the value of the variable.

+
+ +

There is an entry whose key is the xs:string value "functions" and whose associated value + is a map F. This map (F) contains one entry for each distinct QName Q that represents the + name of a public and non-external function declared in the library module. The key of the + entry is Q, as an xs:QName value; the associated value is a map A. + This map (A) contains one entry for each arity N within the arity range of any of the function declarations + with the given name; its key is N, + as an xs:integer value, and its associated value is a function item obtained as if by evaluating + a named function reference Q#N, using the static and dynamic context of the call on + fn:load-xquery-module. The function item + can be invoked using the rules for dynamic function invocation. +

+ +
+
+ +

The static and dynamic context of the library module are established according to the rules in + .

+ +

It is implementation-defined whether constructs in the library module + are evaluated in the same execution scope as the calling module.

+ +

The library module that is loaded may import other modules using an import module declaration. The result of + fn:load-xquery-module does not include global variables or functions declared in such a transitively imported module. + However, the options map supplied in the function call may + (and if no default is defined, must) + supply values for external variables declared in transitively loaded library modules.

+ +

The library module that is loaded may import schema declarations using an import schema declaration. It is + implementation-defined whether schema components in the in-scope + schema definitions of the calling module + are automatically added to the in-scope schema definitions of the dynamically loaded module. The in-scope schema definitions + of the calling and called modules must be consistent, according to the rules defined in + .

+ +

Where nodes are passed to or from the dynamically loaded module, for example as an argument or result of a function, + they should if possible retain their node identity, their base URI, their type annotations, and their relationships to all other nodes + in the containing tree (including ancestors and siblings). If this is not possible, for example because the only way of passing nodes + to the chosen XQuery implementation is by serializing and re-parsing, then a node may be passed in the form of a deep + copy, which may lose information about the identity of the node, about its ancestors and siblings, about its base URI, about its type annotations, and about its + relationships to other nodes passed across the interface.

+ + +
+ +

If $module-uri is a zero length string, a dynamic error is raised .

+

If the implementation is not able to find a library module with the specified target namespace, + an error is raised .

+

If a static error (including a statically detected type error) is encountered when processing the library module, + a dynamic error is raised .

+ +

If a value is supplied for the initial context item or for an external variable and the value does not conform to the required + type declared in the dynamically loaded module, a dynamic error is raised .

+

If no suitable XQuery processor is available, a dynamic error is raised . + This includes (but is not limited to) the following cases:

+ + +

No XQuery processor is available;

+
+ +

Use of the function has been disabled;

+
+ +

No XQuery processor supporting the requested version of XQuery is available;

+
+ +

No XQuery processor supporting the optional Module Feature is available.

+
+
+ +

If a dynamic error (including a dynamically detected type error) is encountered when processing the module + (for example, when evaluating its global variables), the dynamic error is returned as is.

+
+ + + +

If a function declaration F in the loaded module declares (say) four parameters of which one is optional, + its arity range will be from 3 to 4, so the result will include two function items corresponding to F#3 + and F#4. In the lower-arity function item, F#3, the fourth parameter will take its + default value. If the expression that initializes the default value is context sensitive, the static and dynamic + context for its evaluation are the static and dynamic contexts of the fn:load-xquery-module + function call itself. +

+ +

As with all other functions in this specification, conformance requirements depend on the host language. + For example, a host language might specify that provision of this function is optional, or that it is excluded entirely, + or that implementations are required to support XQuery modules using a specified version of XQuery.

+ +

Even where support for this function is mandatory, it is recommended for security reasons that implementations + should provide a user option to disable its use, or to disable aspects of its functionality.

+ + +
+ +
+ + + + + + + + + nondeterministic + context-dependent + focus-independent + + +

Invokes a transformation using a dynamically loaded XSLT stylesheet.

+
+ +

This function loads an XSLT stylesheet and invokes it to perform a transformation.

+

The inputs to the transformation are supplied in the form of a map. + The option parameter conventions apply + to this map; they do not apply to any nested map unless otherwise specified.

+ +

The function first identifies the requested XSLT version, as follows:

+ + + +

If the xslt-version + option is present, the requested XSLT version is the value of that option.

+
+ +

Otherwise, the requested XSLT version + is the value of the [xsl:]version attribute of the outermost element in the supplied stylesheet or package.

+
+
+ +

The function then attempts to locate an XSLT processor that implements the requested XSLT version.

+ + + +

If a processor that implements the requested XSLT version is available, then it is used.

+
+ +

Otherwise, if a processor that implements a version later than the requested version is available, then it is used.

+
+ +

Otherwise, the function fails indicating that no suitable XSLT processor is available.

+
+
+ + +

The phrase locate an XSLT processor includes the possibility of locating a software product and + configuring it to act as an XSLT processor that implements the requested XSLT version.

+
+ +

If more than one XSLT processor is available under the above rules, then the one that is chosen may be selected according to + the availability of requested features: see below.

+ +

Once an XSLT processor has been selected that implements a given version of XSLT, the processor + follows the rules of that version of the XSLT specification. This includes any decision to operate in backwards or forwards + compatibility mode. For example, if an XSLT 2.0 processor is selected, and the stylesheet specifies version="1.0", + then the processor will operate in backwards compatibility mode; if the same processor is selected and the stylesheet + specifies version="3.0", the processor will operate in forwards compatibility mode.

+ +

The combinations of options that are relevant to each version of XSLT, other than xslt-version + itself, are listed below. This is followed by a table giving the meaning of each option.

+ + + + + +

For invocation of an XSLT 1.0 processor (see ), + the supplied options must include all of the following (if anything else is present, it is ignored):

+ + +

The stylesheet, provided by supplying exactly one of the following:

+ + + stylesheet-location + + + stylesheet-node + + + stylesheet-text + + +
+ +

The source tree, provided as the value of the source-node option.

+
+ +

Zero or more of the following additional options:

+ + + stylesheet-base-uri + + stylesheet-params (defaults to an empty map) + initial-mode (defaults to the stylesheet’s default mode) + delivery-format (defaults to document) + serialization-params (defaults to an empty map) + enable-messages (default is implementation-defined) + requested-properties (default is an empty map) + vendor-options (defaults to an empty map) + cache (default is implementation-defined) + +
+
+
+ +

For invocation of an XSLT 2.0 processor (see ), + the supplied options must include all of the following (if anything else is present, it is ignored):

+ + +

The stylesheet, provided by supplying exactly one of the following:

+ + + stylesheet-location + + + stylesheet-node + + + stylesheet-text + + +
+ +

Invocation details, as exactly one of the following:

+ + +

For apply-templates invocation, all of the following:

+

+ source-node +

+

Optionally, initial-mode (defaults to the stylesheet’s default mode)

+
+ +

For call-template invocation, all of the following:

+

+ initial-template +

+

Optionally, source-node

+
+
+
+ +

Zero or more of the following additional options:

+ + + stylesheet-base-uri + + stylesheet-params (defaults to an empty map) + base-output-uri (defaults to absent) + delivery-format (defaults to document) + serialization-params (defaults to an empty map) + enable-messages (default is implementation-defined) + enable-trace (default is implementation-defined) + requested-properties (default is an empty map) + vendor-options (defaults to an empty map) + cache (default is implementation-defined) + +
+
+
+ +

For invocation of an XSLT 3.0 processor (see ), + the supplied options must include all of the following (if anything else is present, it is ignored):

+ + +

The stylesheet, provided either by supplying exactly one of the following:

+ + + stylesheet-location + + + stylesheet-node + + + stylesheet-text + + + +

Or by supplying exactly one of the following:

+ + + package-location + + + package-node + + + package-text + + package-name plus optionally package-version + +
+ +

Invocation details, as exactly one of the following combinations:

+ + +

For apply-templates invocation, all of the following:

+

Exactly one of source-node or initial-match-selection

+

Optionally, initial-mode

+

Optionally, template-params

+

Optionally, tunnel-params

+
+ +

For call-template invocation using an explicit template name, all of the following:

+

+ initial-template +

+

Optionally, template-params

+

Optionally, tunnel-params

+

Optionally, source-node

+
+ +

For call-template invocation using the defaulted template name xsl:initial-template, all of the following:

+

Optionally, template-params

+

Optionally, tunnel-params

+ +

If the source-node option is present and initial-template is absent, + then apply-templates invocation will be used. To use call-template invocation on the template + named xsl:initial-template while also supplying a context item for use when evaluating + global variables, either (a) supply the context item using the global-context-item option, + or (b) supply source-node, and set the initial-template option explicitly to the + QName xsl:initial-template

+
+
+ +

For call-function invocation, all of the following:

+

+ initial-function +

+

+ function-params +

+
+
+ +

The invocation method can be determined as the first of the following which applies:

+ + +

If initial-function is present, then call-function invocation.

+
+ +

If initial-template is present, then call-template invocation.

+
+ +

If source-node or initial-match-selection + is present, then apply-templates invocation.

+
+ +

Otherwise, call-template invocation using + the default entry point xsl:initial-template.

+
+
+
+
+ +

Zero or more of the following additional options:

+ + + stylesheet-base-uri + + static-params (defaults to an empty map) + stylesheet-params (defaults to an empty map) + global-context-item (defaults to absent) + base-output-uri (defaults to absent) + + delivery-format + + serialization-params (defaults to an empty map) + enable-assertions (default is false) + enable-messages (default is implementation-defined) + enable-trace (default is implementation-defined) + requested-properties (default is an empty map) + vendor-options (defaults to an empty map) + cache (default is implementation-defined) + +
+
+
+
+ +

The meanings of each option are defined in the table below.

+ + + + + 1.0, 2.0, 3.0 + The URI of the principal result document; also used as the base URI for + resolving relative URIs of secondary result documents. If the value is a relative + reference, it is resolved against the static base URI of the fn:transform + function call. + + xs:string + The effect of not + supplying a base output URI is defined by the XSLT specification; the implementation + may supply a default, for example the directory containing the + stylesheet, or the current working directory. + + + 1.0, 2.0, 3.0 + This option has no effect on the result of the transformation but may affect + efficiency. The value true indicates an expectation that the same + stylesheet is likely to be used for more than one transformation; the value + false indicates an expectation that the stylesheet will be used once + only. + xs:boolean + true() + + + 1.0, 2.0, 3.0 + The manner in which the transformation results should be delivered. Applies both to the + principal result document and to secondary result documents created using + xsl:result-document. + xs:string + document, unless the relevant + xsl:output or xsl:result-document element specifies + build-tree="no" (applies to XSLT 3.0 only), in which case the default + is raw. + + The result is delivered as a + document node. + The result is delivered as + a string, representing the results of serialization. Note that (as with the + fn:serialize function) the final encoding stage of + serialization (which turns a sequence of characters into a sequence of + octets) is either skipped, or reversed by decoding the octet stream back + into a character stream. + The result of the initial + template or function is returned as an arbitrary XDM value (after conversion + to the declared type, but without wrapping in a document node, and without + serialization): when this option is chosen, the returned map contains the + raw result. + + + + + 3.0 + Indicates whether any xsl:assert instructions in the stylesheet + are to be evaluated. + xs:boolean + false() + + + 1.0, 2.0, 3.0 + Indicates whether any xsl:message instructions in the stylesheet + are to be evaluated. The destination and formatting of any such messages is + implementation-defined. + xs:boolean + Implementation-defined + + + 2.0, 3.0 + Indicates whether any fn:trace functions in the stylesheet are to + generate diagnostic messages. The destination and formatting of any such messages is + implementation-defined. + xs:boolean + Implementation-defined + + + 3.0 + An array of values to be used as the arguments to the initial function call. + The value is converted to the required type of the declared parameter using the function + conversion rules. + array(item()*) + Empty array + + + 3.0 + The value of the global context item, as defined in XSLT 3.0 + item() + The value of source-node + + + 3.0 + The name of the initial function to be called for call-function invocation. The + arity of the function is inferred from the length of + function-params. + xs:QName + n/a + + + 3.0 + The value of the initial match selection, as defined in XSLT 3.0 + item()* + The value of source-node + + + 1.0, 2.0, 3.0 + The name of the initial processing mode. + xs:QName + + + + 2.0, 3.0 + The name of a named template in the stylesheet to act as the initial entry + point. + xs:QName + xsl:initial-template + + + 3.0 + The name of the top-level stylesheet package to be invoked (an absolute + URI) + xs:string + n/a + + + 3.0 + The location of the top-level stylesheet package, as a relative or absolute + URI + xs:string + n/a + + + 3.0 + A document or element node containing the top-level stylesheet + package + node() + n/a + + + 3.0 + The top-level stylesheet package in the form of unparsed lexical + XML. + xs:string + n/a + + + + 3.0 + The version of the top-level stylesheet package to be invoked. + xs:string + "*" (any version) + + + 1.0 2.0 3.0 + A function that is used to post-process each result document of + the transformation (both the principal result and secondary results), in whatever + form it would otherwise be delivered (document, serialized, or raw). The first + argument of the function is the key used to identify the result in the map return + by the fn:transform function (for example, this will be the supplied + base output URI in the case of the principal result, or the string “output” if no + base output URI was supplied). The second argument is the + actual value. The value that is returned in the result of the fn:transform + function is the result of applying this post-processing. + + +

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

+

If the primary purpose of the post-processing function is achieved by + means of such side-effects, and if the actual results are not needed by + the caller of the fn:transform function, then it does not matter what + the post-processing function actually returns (it could be an empty + sequence, for example).

+

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

+
+ function(xs:string, item()*) as item()* + function($a, $b) { $b } +
+ + 1.0, 2.0, 3.0 + The keys in the map are QNames that could legitimately be supplied in a call to + the XSLT system-property function; the values in the map are the requested + settings of the corresponding property. The boolean values true() and + false() are equivalent to the string values yes and + no. As a special case, setting a value for xsl:version has + no effect, because of the potential for conflict with other options. For example: +

Setting xsl:product-name to a particular value requests a + particular XSLT software product.

+

Setting xsl:product-version requests a specific version of + that product.

+

Setting xsl:is-schema-aware to true() requests a + schema-aware processor.

+

Setting xsl:xsd-version to "1.1" requests a + processor that supports XML Schema version 1.1.

+
Setting a boolean property such as xsl:supports-dynamic-evaluation + to false() is interpreted as an explicit request for a processor in which + the value of the property is false. The effect if the requests cannot be precisely met + is implementation-defined. In some cases it may be appropriate to ignore the request or + to provide an alternative (for example, a later version of the product than the one + requested); in other cases it may be more appropriate to raise an error indicating that no suitable XSLT processor + is available.
+ map(xs:QName, xs:anyAtomicType) + Empty map +
+ + 1.0, 2.0, 3.0 + Serialization parameters for the principal result document. The supplied map + follows the same rules that apply to a map supplied as the second argument of + fn:serialize. +

When a parameter is supplied, the corresponding value overrides or augments + the value specified in the unnamed xsl:output declaration (or + its default), following the same rules as when one xsl:output + declaration overrides another with lower import precedence.

+

When a parameter is supplied and the corresponding value is an empty + sequence (for example, map{"standalone":()}), any value + specified in the unnamed xsl:output declaration is overridden + by the default value.

+

When a parameter is not supplied in serialization-params (that + is, when the key is absent) the value that applies is the value appearing in + the unnamed xsl:output declaration, or its default.

+
+ map(xs:anyAtomicType, item()*) + Empty map +
+ + 1.0, 2.0, 3.0 + When source-node is supplied then the + global-context-item (the context item for evaluating global variables) + is the root of the tree containing the supplied node. In addition, for apply-templates + invocation, the source-node acts as the + initial-match-selection, that is, stylesheet execution starts by + applying templates to this node. + node() + n/a + + + + 3.0 + The values of static parameters defined in the stylesheet; the keys are the + names of the parameters, and the associated values are their values. The value is + converted to the required type of the declared parameter using the function conversion + rules. + map(xs:QName, item()*) + Empty map + + + 1.0, 2.0, 3.0 + A string intended to be used as the static base URI of the principal stylesheet + module. This value must be used if no other static base URI is + available. If the supplied stylesheet already has a base URI (which will generally be + the case if the stylesheet is supplied using stylesheet-node or + stylesheet-location) then it is implementation-defined whether this + parameter has any effect. If the value is a relative reference, it is resolved against + the static base URI of the fn:transform function call. + xs:string + n/a + + + 1.0, 2.0, 3.0 + URI that can be used to locate the principal stylesheet module. If relative, it + is resolved against the static base URI of the fn:transform function call. + The value also acts as the default for stylesheet-base-uri. + xs:string + n/a + + + 1.0, 2.0, 3.0 + Root of the tree containing the principal stylesheet module, as a document or + element node. The base URI of the node acts as the default for + stylesheet-base-uri. + node() + n/a + + + 1.0, 2.0, 3.0 + A map holding values to be supplied for stylesheet parameters. The keys are the + parameter names; the values are the corresponding parameter values. The values are + converted if necessary to the required type using the function conversion rules. The + default is an empty map. + map(xs:QName, item()*) + Empty map + + + + 1.0, 2.0, 3.0 + The principal stylesheet module in the form of unparsed lexical + XML. + xs:string + n/a + + + 3.0 + The values of non-tunnel parameters to be supplied to the initial template, + used with both apply-templates and call-template invocation. Each value is converted to + the required type of the declared parameter using the function conversion + rules. + map(xs:QName, item()*) + + + + 3.0 + The values of tunnel parameters to be supplied to the initial template, used + with both apply-templates and call-template invocation. Each value is converted to the + required type of the declared parameter using the function conversion + rules. + map(xs:QName, item()*) + Empty map + + + + 1.0, 2.0, 3.0 + Values for vendor-defined configuration options for the XSLT processor used to + process the request. The key is the name of an option, expressed as a QName: the + namespace URI of the QName should be a URI controlled by the vendor + of the XSLT processor. The meaning of the associated value is implementation-defined. Implementations + should ignore options whose names are in an unrecognized + namespace. Default is an empty map. + map{xs:QName, item()*} + Empty map + + + + 1.0, 2.0, 3.0 + The minimum level of the XSLT language that the processor must support. + xs:decimal + The [xsl:]version attribute at the outermost level of the + stylesheet. + + +
+ + + + +

The result of the transformation is returned as a map. There is one entry in the map for the principal result document, and one + for each secondary result document. The key is a URI in the form of an xs:string value. The key for the principal + result document is the base output URI if specified, or the string "output" otherwise. The key for secondary + result documents is the URI of the document, as an absolute URI. The associated value in each entry depends on the requested + delivery format. If the delivery format is document, the value is a document node. If the delivery format is + serialized, the value is a string containing the serialized result.

+ +

Where nodes are passed to or from the transformation, for example as the value of a stylesheet parameter or the result of a function, + they should if possible retain their node identity, their base URI, their type annotations, and their relationships to all other nodes + in the containing tree (including ancestors and siblings). If this is not possible, for example because the only way of passing nodes + to the chosen XSLT implementation is by serializing and re-parsing, then a node may be passed in the form of a deep + copy, which may lose information about the identity of the node, about its ancestors and siblings, about its base URI, about its type annotation, and about its + relationships to other nodes passed across the interface.

+ +

It is implementation-defined whether the XSLT transformation is executed + within the same execution scope as the calling code.

+ +

The function is nondeterministic in that it is + implementation-dependent whether running the function twice against the same + inputs produces identical results. The results of two invocations may differ in the identity of any returned nodes; they may also + differ in other respects, for example because the value of fn:current-dateTime is different for the two invocations, + or because the contents of external documents accessed using fn:doc or xsl:source-document change between + one invocation and the next.

+ + + + +
+ +

A dynamic error is raised if the transformation cannot be invoked + because no suitable XSLT processor is available. This includes (but is not limited to) the following cases:

+ + +

No XSLT processor is available;

+
+ +

No XSLT processor supporting the requested version of XSLT is available;

+
+ +

The XSLT processor API does not support some requested feature (for example, the ability to supply tunnel parameters externally);

+
+
+

A dynamic error is raised if an error is detected in the supplied + parameters (for example if two mutually exclusive parameters are supplied).

+

If a static or dynamic error is reported by the XSLT processor, this function fails with a dynamic error, retaining the XSLT error code.

+

A dynamic error is raised if the XSLT transformation invoked by a call on + fn:transform fails with a static or dynamic error, and no more specific error code is available.

+ +

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

+
+

A dynamic error is raised if the use of this function (or of selected options) + has been externally disabled, for example for security reasons.

+

A dynamic error is raised if the transformation produces output containing + characters available only in XML 1.1, and the calling processor cannot handle such characters.

+

Recursive use of the fn:transform function may lead to catastrophic failures such as + non-termination or stack overflow. No error code is assigned to such conditions, since they cannot necessarily + be detected by the processor.

+ +
+ + +

As with all other functions in this specification, conformance requirements depend on the host language. + For example, a host language might specify that provision of this function is optional, or that it is excluded entirely, + or that implementations are required to support a particular set of values for the xslt-version + parameter.

+ +

Even where support for this function is mandatory, it is recommended for security reasons that implementations + should provide a user option to disable its use, or to disable aspects of its functionality such as + the ability to write to persistent resources.

+ + +
+ + +

The following example loads a stylesheet from the location render.xsl, + applies it to a document loaded from test.xml, and uses an XPath expression + to examine the result:

+ +
+
+ +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Returns a random number generator, which can be used to generate sequences of random numbers.

+
+ +

The function returns a random number generator. A random number generator is represented as a value of type + random-number-generator-record, defined as follows:

+ + + +

This type is self-referential in a way that the + current syntax for record type declarations does not allow. The + use of the type #random-number-generator-record as the return type of the next + function is purely for expository purposes; an approximation allowed by the grammar would be + next as (function() as record(number, next, permute, *)).

+ +

That is, the result of the function is a map containing three entries. + The keys of each entry are strings:

+ + +

The entry with key "number" holds a random number; it is an xs:double greater than or equal + to zero (0.0e0), and less than one (1.0e0).

+
+ +

The entry with key "next" is a zero-arity function that can be called to return another random number + generator.

+

The properties of this function are as follows:

+ + +

name: absent

+
+ +

parameter names: ()

+
+ +

signature: () => map(xs:string, item())

+
+ +

non-local variable bindings: none

+
+ +

implementation: implementation-dependent

+
+
+
+ +

The entry with key "permute" is a function with arity 1 (one), which takes an arbitrary sequence + as its argument, and returns a random permutation of that sequence.

+

The properties of this function are as follows:

+ + +

name: absent

+
+ +

parameter names: "arg"

+
+ +

signature: (item()*) => item()*

+
+ +

non-local variable bindings: none

+
+ +

implementation: implementation-dependent

+
+
+
+
+

Calling the fn:random-number-generator function with no arguments is equivalent to calling the single-argument + form of the function with an implementation-dependent seed.

+

Calling the fn:random-number-generator function with an empty sequence as $seed + is equivalent to calling the single-argument form of the function with an implementation-dependent seed.

+

If a $seed is supplied, it may be an atomic value of any type.

+

Both forms of the function are : calling the function twice with the same arguments, within a single + execution scope, produces the same results.

+ + +

The value of the number entry should be such that all eligible xs:double + values are equally likely to be chosen the distribution of numbers is uniform: for example, the probability of the + number being in the range 0.1e0 to 0.2e0 is the same as the probability of its being in the range 0.8e0 to 0.9e0.

+ +

The function returned in the permute entry should be such that all permutations + of the supplied sequence are equally likely to be chosen.

+ +

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

+
+ +

It is not meaningful to ask whether the functions returned in the next and permute + functions resulting from two separate calls with the same seed are “the same function”, but the functions must be equivalent in the sense + that calling them produces the same sequence of random numbers.

+

The repeatability of the results of function calls in different execution scopes is outside the scope of this + specification. It is recommended that when the same seed is provided explicitly, the same random number sequence + should be delivered even in different execution scopes; while if no seed is provided, the processor should choose a seed + that is likely to be different from one execution scope to another. (The same effect can be achieved explicitly by using + fn:current-dateTime() as a seed.)

+

The specification does not place strong conformance requirements on the actual randomness of the result; this is left to + the implementation. It is desirable, for example, when generating a sequence + of random numbers that the sequence should not get into a repeating loop; but the specification does not attempt to dictate this.

+
+ + +

The following example returns a random permutation of the integers in the range + 1 to 100: + fn:random-number-generator()?permute(1 to 100) +

+

The following example returns a 10% sample of the items in an input sequence $seq, chosen at random: + fn:random-number-generator()?permute($seq)[position() = 1 to (count($seq) idiv 10)] +

+

The following code defines a function that can be called to produce a random sequence of xs:double + values in the range zero to one, of specified length:

+ +declare %public function r:random-sequence($length as xs:integer) as xs:double* { + r:random-sequence($length, random-number-generator()) +}; + +declare %private function r:random-sequence($length as xs:integer, + $G as record(number as xs:double, next as function(*), *)) { + if ($length eq 0) + then () + else ($G?number, r:random-sequence($length - 1, $G?next())) +}; + +r:random-sequence(200); + + + + +
+
+
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns true if all items in the input sequence match a supplied predicate.

+
+ +

The effect of the function is equivalent to the following implementation in XQuery:

+ +

or its equivalent in XSLT:

+ + + + +]]> + +
+ +

If the second argument is omitted, the first argument must be a sequence of + xs:boolean values.

+

The implementation may deliver a result as soon as one item is found for which the predicate + returns false; it is not required to evaluate the predicate for every item.

+
+ + + + all(()) + true() + + + all((1=1, 2=2, 3=4)) + false() + + + all((), boolean#1) + true() + + + all((1, 3, 7), function { . mod 2 = 1 }) + true() + + + all(-5 to +5, function { . ge 0 }) + false() + + + all( + ("January", "February", "March", "April", + "September", "October", "November", "December"), + contains(?, "r") +) + true() + + + all( + ("January", "February", "March", "April", + "September", "October", "November", "December") + =!> contains("r") +) + true() + + + + + New in 4.0. Accepted 2022-09-13. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns a string containing a named character or glyph.

+
+ +

The function returns a string, generally containing a single character or glyph, identified by $value.

+

For example, fn:char("nbsp") returns a string containing the + non-breaking space character, xA0.

+

The supplied value of $value must be one of the following:

+ +

An HTML5 character reference name (often referred to as an entity name) as defined + at [https://html.spec.whatwg.org/multipage/named-characters.html]. The name is + written with no leading ampersand and no trailing semicolon. + For example fn:char("pi") represents the character + π (x3C0).

+

A processor may recognize additional character reference names defined in + other versions of HTML. Character reference names are case-sensitive.

+

In the event that the HTML5 character reference name identifies a string + comprising multiple codepoints, that string is returned.

+

[TODO: add a proper bibliographic reference.]

+

A backslash-escape sequence from the set \n (newline, x0A), + \r (carriage return, 0xD), + or \t (tab, 0x09).

+

A decimal codepoint value in the form #[0-9]+, for example + fn:char("#10") represents a newline character. Leading zeroes are optional.

+

A hexadecimal codepoint value in the form #x[0-9a-fA-F]+, for example + fn:char("#x0A") represents a newline character. Leading zeroes are optional, and the + letters A-F may be in either upper or lower case.

+ +
+

The result must consist of + permitted characters. + For example fn:char("#xDEAD") is invalid because it is in the surrogate range.

+
+ +

The function fails with a dynamic error if $value is not a valid + representation of a valid character or sequence of characters. +

+
+ +

Although all Unicode characters can appear in string literals (the delimiting quotation marks can be + escaped by doubling them), some characters are not visually distinctive, so representing them by name + may make code more readable. In addition, there may be contexts where it is necessary or prudent to + write XPath expressions using ASCII characters only, for example where an expression is used in the query + part of a URI.

+

A few HTML5 character reference names identify glyphs whose Unicode + representation uses multiple codepoints. For example, the name + NotEqualTilde refers to the glyph ≂̸ which is expressed + using the two codepoints #x2242 #x0338. In such cases the string length of + the result of the function will exceed one.

+
+ + + + char("#32") + " " + + + char("#x20") + " " + + + char("\t") + codepoints-to-string(9) + The character tab + + + char("#x1D1CA") + "𝇊" + The character Tempus Imperfectum Cum Prolatione Perfecta + + + char("aacute") + "á" + + + char("eth") + "ð" + + + char("NotEqualTilde") + codepoints-to-string((8770, 824)) + This HTML5 character reference name expands to multiple codepoints. + + + + + + Accepted for 4.0 on 2023-01-10; with actions on the editor for revision. See issue #121. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Splits the supplied string into a sequence of single-character strings.

+
+ +

The function returns a sequence of strings, each string having length 1, containing + the corresponding character in $value.

+

If $value is a zero-length string or the empty sequence, the function returns + the empty sequence.

+

More formally, the function returns the result of the expression fn:string-to-codepoints($value) ! fn:codepoints-to-string(.)

+
+ + + + characters("Thérèse") + ("T", "h", "é", "r", "è", "s", "e") + + + characters("") + () + + + characters(()) + () + + + characters("Banana") => index-of("a") + (2, 4, 6) + + + characters("stretch") => string-join("-") + "s-t-r-e-t-c-h" + + + "Banana" +=> characters() +=> reverse() +=> string-join() + "ananaB" + + + + + New in 4.0. Accepted 2022-09-20, subject to improving the description. + +
+ + + + + + + + + + + + + deterministic + context-dependent + focus-independent + + + + +

Returns those items from a supplied sequence that have the highest value of a sort key, where + the sort key can be computed using a caller-supplied function.

+
+ +

The second argument, $collation, defaults to ().

+

Supplying an empty + sequence as $collation is equivalent to supplying + fn:default-collation(). For more + information on collations see .

+ +

The third argument defaults to the function data#1.

+ +

Let $modified-key be the function:

+ +function($item) { + $key($item) => data() ! ( + if (. instance of xs:untypedAtomic) + then xs:double(.) + else .) +} + +

That is, the supplied function for computing key values is wrapped in a function that + converts any xs:untypedAtomic values in its result to xs:double. This makes + the function consistent with the behavior of fn:min and fn:max, + but inconsistent with fn:sort, which treats untyped values as strings.

+ +

The result of the function is obtained as follows:

+ + +

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

+
+ +

The input sequence is sorted, by applying the function + fn:sort($input, $collation, $modified-key).

+
+ +

Let $C be the selected collation, or the default collation where applicable.

+
+ +

Let $B be the last item in the sorted sequence.

+
+ +

The function returns those items $A from the input sequence such that + (fn:deep-equal($key($A), $key($B), $C), retaining their order. +

+
+ +
+
+ +

If the set of computed keys contains xs:untypedAtomic values that are not + castable to xs:double then + operation will fail with a dynamic error (). +

+

If the set of computed keys contains values that are not comparable using + the lt operator then the sort + operation will fail with a type error (). +

+
+ + ]]> + + + highest($e/@*) ! name() + ("x") + By default, untyped values are compared as numbers. + + + highest($e/@*, (), string#1) ! name() + ("y") + Here, the attribute values are compared as strings. + + + highest(("red", "green", "blue"), (), string-length#1) + ("green") + + + highest( + ("red", "green", "blue"), + (), + map { + "red" : xs:hexBinary('FF0000'), + "green": xs:hexBinary('008000'), + "blue" : xs:hexBinary('0000FF') + } +) + ("red") + + + highest( + ("red", "orange", "yellow", "green", + "blue", "indigo", "violet"), + (), + string-length#1 +) + ("orange", "yellow", "indigo", "violet") + + + highest(1 to 25, (), function { . idiv 10 }) + (20, 21, 22, 23, 24, 25) + + + +

To find employees having the highest salary: +

+ highest($employees, (), function { xs:decimal(salary) }) +
+
+ + New in 4.0. Accepted 2022-09-20. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the position in an input sequence of items that match a supplied predicate.

+
+ + +

The result of the function is a sequence of integers, in monotonic ascending order, representing + the 1-based positions in the input sequence of those items for which the supplied predicate function + returns true.

+

More formally, the function returns the result of the expression:

+ index-of($input!$predicate(.), true()) +
+ + + + + index-where((), boolean#1) + () + + + index-where((0, 4, 9), boolean#1) + (2, 3) + + + index-where(1 to 10, function { . mod 2 = 0 }) + (2, 4, 6, 8, 10) + + + index-where( + ("January", "February", "March", "April", + "May", "June", "July", "August", "September", + "October", "November", "December"), + contains(?, "r") +) + (1, 2, 3, 4, 9, 10, 11, 12) + + + + + New in 4.0. Accepted 2022-09-20. + +
+ + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns true if the argument is the xs:float or xs:double value NaN.

+
+ + +

The function returns true if the argument is the xs:float or xs:double value NaN; + otherwise it returns false.

+ +
+ + + + + + + is-NaN(23) + false() + + + is-NaN("NaN") + false() + + + is-NaN(number("twenty-three")) + true() + + + is-NaN(math:sqrt(-1)) + true() + + + + + + New in 4.0. Accepted 2022-09-20. + +
+ + + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the items from the input sequence that follow the first item to match a supplied predicate.

+
+ +

The supplied $predicate function is called for each item in the input sequence $input, + to return a boolean value. Let $P be the 1-based position of the first item to match the predicate, + or -1 if no item matches the predicate.

+

The function then returns if ($P lt 0) then () else fn:subsequence($input, $P + 1).

+
+ +

To retain the first matching item, use fn:items-starting-where.

+
+ + + + + + items-after(10 to 20, function { . gt 12 }) + (14, 15, 16, 17, 18, 19, 20) + + + items-after( + ("January", "February", "March", "April", "May"), + starts-with(?, "A") +) + ("May") + + + items-after(10 to 20, function { . gt 100 }) + () + + + items-after((), boolean#1) + () + + +

")//doc/* +=> items-after(function { boolean(self::h2) })]]> + ]]> + + + + + + New in 4.0. Accepted 2022-10-25. + + + + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the items from the input sequence that precede the first item to match a supplied predicate.

+
+ +

The supplied $predicate function is called for each item in the input sequence $input, + to return a boolean value. Let $P be the 1-based position of the first item to match the predicate, + or -1 if no item matches the predicate.

+

The function then returns if ($P lt 0) then $seq else fn:subsequence($input, 1, $P - 1).

+
+ +

To retain the first matching item, use fn:items-ending-where.

+
+ + + + + + + items-before(10 to 20, function { . gt 12 }) + (10, 11, 12) + + + items-before( + ("January", "February", "March", "April", "May"), + starts-with(?, "A") +) + ("January", "February", "March") + + + items-before(10 to 20, function { . gt 100 }) + (10 to 20) + + + items-before((), boolean#1) + () + + +

")//doc/* +=> items-before(function { boolean(self::img) }) +=!> name()]]> + "p", "p", "h2" + + + ("Aardvark", "Antelope", "Bison", + "Buffalo", "Camel", "Dingo") +=> items-starting-where(starts-with(?, "B")) +=> items-before(starts-with(?, "D")) + "Bison", "Buffalo", "Camel" + + + + + + New in 4.0. Accepted 2022-10-25. + + + + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the items from the input sequence starting from the first item to match a supplied predicate.

+
+ +

The supplied $predicate function is called for each item in the input sequence $input, + to return a boolean value. Let $P be the 1-based position of the first item to match the predicate, + or -1 if no item matches the predicate.

+

The function then returns if ($P lt 0) then () else fn:subsequence($input, $P).

+
+ +

To exclude the first item, use fn:items-after.

+
+ + + + + + + items-starting-where(10 to 20, function { . gt 12 }) + (13, 14, 15, 16, 17, 18, 19, 20) + + + items-starting-where( + ("January", "February", "March", "April", "May"), + starts-with(?, "A") +) + ("April", "May") + + + items-starting-where(10 to 20, function { . gt 100 }) + () + + + items-starting-where((), boolean#1) + () + + +

")//doc/* +=> items-starting-where(function { boolean(self::h2) }) +=!> name()]]> + "h2", "img" + + + + + + New in 4.0. Accepted 2022-10-25. + + + + + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns the items from the input sequence ending with the first item to match a supplied predicate.

+
+ +

The supplied $predicate function is called for each item in the input sequence $input, + to return a boolean value. Let $P be the 1-based position of the first item to match the predicate, + or -1 if no item matches the predicate.

+

The function then returns if ($P lt 0) then $seq else fn:subsequence($input, 1, $P).

+
+ +

To exclude the last item, use fn:items-before.

+
+ + + + + + + items-ending-where(10 to 20, function { . gt 12 }) + (10, 11, 12, 13) + + + items-ending-where( + ("January", "February", "March", "April", "May"), + starts-with(?, "A") +) + ("January", "February", "March", "April") + + + items-ending-where(10 to 20, function { . gt 100 }) + (10 to 20) + + + items-ending-where((), boolean#1) + () + + +

")//doc/* +=> items-ending-where(function { boolean(self::h2) }) +=!> name()]]> + "p", "p", "h2" + + + + + + New in 4.0. Accepted 2022-10-25. + + + + + + + + + + + + + + + + deterministic + context-dependent + focus-independent + + + + +

Returns those items from a supplied sequence that have the lowest value of a sort key, where + the sort key can be computed using a caller-supplied function.

+
+ +

The second argument, $collation, defaults to ().

+

Supplying an empty + sequence as $collation is equivalent to supplying + fn:default-collation(). For more + information on collations see .

+ +

The third argument defaults to the function data#1.

+ +

Let $modified-key be the function:

+ function($item) { + $key($item) => data() ! ( + if (. instance of xs:untypedAtomic) then xs:double(.) else . + ) +} + +

That is, the supplied function for computing key values is wrapped in a function that + converts any xs:untypedAtomic values in its result to xs:double. This makes + the function consistent with the behavior of fn:min and fn:max, + but inconsistent with fn:sort, which treats untyped values as strings.

+ +

The result of the function is obtained as follows:

+ + +

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

+
+ +

The input sequence is sorted, by applying the function + fn:sort($input, $collation, $modified-key).

+
+ +

Let $C be the selected collation, or the default collation where applicable.

+
+ +

Let $B be the first item in the sorted sequence.

+
+ +

The function returns those items $A from the input sequence such that + (fn:deep-equal($key($A), $key($B), $C), retaining their order. +

+
+ +
+
+ +

If the set of computed keys contains xs:untypedAtomic values that are not + castable to xs:double then + operation will fail with a dynamic error (). +

+

If the set of computed keys contains values that are not comparable using + the lt operator then the sort + operation will fail with a type error (). +

+
+ + + + ]]> + + + lowest($e/@*) ! name() + ("z") + By default, untyped values are compared as numbers. + + + lowest($e/@*, (), string#1) ! name() + ("x") + Here, the attribute values are compared as strings. + + + lowest(("red", "green", "blue"), (), string-length#1) + ("red") + + + lowest( + ("red", "green", "blue"), + (), + map { + "red" : xs:hexBinary('FF0000'), + "green": xs:hexBinary('008000'), + "blue" : xs:hexBinary('0000FF') + } +) + ("blue") + + + lowest( + ("April", "June", "July", "August"), + (), + string-length#1 +) + ("June", "July") + + + lowest(1 to 25, (), function { . idiv 10 }) + (1, 2, 3, 4, 5, 6, 7, 8, 9) + + + +

To find employees having the lowest salary: +

+ lowest($employees, (), function { xs:decimal(salary) }) +
+
+ + New in 4.0. Accepted 2022-09-20. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + +

Returns true if at least one item in the input sequence matches a supplied predicate.

+
+ +

The effect of the function is equivalent to the following implementation in XQuery:

+ +

or its equivalent in XSLT:

+ + + + +]]> + +
+ +

If the second argument is omitted, the first argument must be a sequence of xs:boolean + values.

+

The implementation may deliver a result as soon as one item is found for which the predicate + returns true; it is not required to evaluate the predicate for every item.

+
+ + + + some(()) + false() + + + some((1=1, 2=2, 3=4)) + true() + + + some((), boolean#1) + false() + + + some((1, 3, 7), function {. mod 2 = 1 }) + true() + + + some(-5 to +5, function {. ge 0 }) + true() + + + some( + ("January", "February", "March", "April", + "September", "October", "November", "December"), + contains(?, "z") +) + false() + + + some( + ("January", "February", "March", "April", + "September", "October", "November", "December") + =!> contains("r") +) + true() + + + + + New in 4.0. Accepted 2022-09-13. + +
+ + + + + + + +

Returns implementation-dependent information about the current state of execution.

+
+ + +

The result of the function is an implementation-dependent string containing diagnostic + information about the current state of execution.

+ +

The function is non-deterministic: multiple calls will typically produce different results.

+ +
+ + +

The function will typically be called to assist in diagnosing dynamic errors.

+
+ + + + +
+ + + + + + + + + + + + deterministic + context-dependent + focus-independent + + + + +

Returns true if all items in a supplied sequence (after atomization) are equal.

+
+ + +

Omitting the second argument, $collation, is equivalent to supplying + fn:default-collation(). For more + information on collations see .

+ + +

The result of the function fn:all-equal($values, $collation) is true if and only if the result + of fn:count(fn:distinct-values($values, $collation)) le 1 is true (that is, if the sequence + is empty, or if all the items in the sequence are equal under the rules of the + fn:distinct-values function).

+
+ + + + + + all-equal((1,2,3)) + false() + + + + + all-equal((1, 1.0, 1.0e0)) + true() + + + + + all-equal("one") + true() + + + + + all-equal(()) + true() + + + + + all-equal( + ("ABC", "abc"), + "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive" +) + true() + + + +

The expression fn:all-equal(//p/@class) returns true if all + p elements have the same value for @class. +

+
+ +

The expression fn:all-equal(*!fn:node-name()) returns true if all + element children of the context node have the same name. +

+
+
+ + Originally proposed for 4.0 under the name fn:uniform. + Accepted 2022-09-20 with a change of name. + +
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + + + +

Returns true if no two items in a supplied sequence are equal.

+
+ + +

Omitting the second argument, $collation, is equivalent to supplying + fn:default-collation(). For more + information on collations see .

+ + +

The result of the function fn:all-different($values, $collation) is true if and only if the result + of fn:count(fn:distinct-values($values, $collation)) eq fn:count($values) is true + (that is, if the sequence + is empty, or if all the items in the sequence are distinct under the rules of the + fn:distinct-values function).

+
+ + + + + + all-different((1,2,3)) + true() + + + + + all-different((1, 1.0, 1.0e0)) + false() + + + + + all-different("one") + true() + + + + + all-different(()) + true() + + + + + all-different( + ("ABC", "abc"), + "http://www.w3.org/2005/xpath-functions/collation/html-ascii-case-insensitive" +) + false() + + + +

The expression fn:all-different(//employee/@ssn) is true if no two employees have the same value for their + @ssn attribute.

+
+ +

The expression fn:all-different(*!fn:node-name()) returns true if all + element children of the context node have distinct names. +

+
+
+ + Originally proposed for 4.0 under the name fn:unique. + Accepted 2022-09-20 with a change of name and with clarifications to the description. + +
+ + + + + + + + + + deterministic + context-independent + focus-independent + + + +

Parses the URI provided and returns a map of its parts.

+
+ + +

The function parses the $uri provided, + returning a map containing its constituent parts: scheme, + authority components, path, etc. + In addition to parsing URIs as defined by + (and ), this function also attempts to + account for strings that are not valid URIs but that often appear + in URI-adjacent spaces, such as file names. Not all such strings + can be successfully parsed as URIs.

+ +

This function is described as a series of transformations + over the input string to identify the parts of a URI that are + present. Some portions of the URI are identified by matching + with a regular expression. This approach is designed to make + the description clear and unambiguous, it is not implementation + advice.

+ +

The following options are available:

+ + + + Identifies the path separator + xs:string + / + + + Identifies the query separator + xs:string + & + + + Indicates that deprecated URI + features should be returned + xs:boolean + false() + + + Indicates that a port number that is the same as + the default port for a given scheme should be omitted. + xs:boolean + false() + + + Indicates that an input URI that begins + with two or more leading slashes should be interprted + as a Windows Universal Naming Convention + Path. (Specifically: that it has the file: scheme.) + xs:boolean + false() + + + +

Processing begins with a string that is equal + to the $uri. If the string contains + any backlashes (\), replace them with forward + slashes (/).

+ +

If the string matches ^(.*)#([^#]*)$, + the string is the first match group and the + fragment is the second match group. Otherwise, + the string is unchanged and the fragment is the empty + sequence.

+ +

If the string matches ^(.*)\?([^\?]*)$, + the string is the first match group and the + query is the second match group. Otherwise, + the string is unchanged and the query is the empty + sequence.

+ + + +

If the string matches ^[a-zA-Z][:|].*$:

+ +

the scheme is file;

+

if the second character in the string is |, it is changed to :;

+

the filepath is the string; and

+

a leading slash / is added to the string.

+
+ +

Otherwise, if the string matches + ^([a-zA-Z][A-Za-z0-9\+\-\.]*):(.*)$:

+ +

the scheme is the first match group,

+

the string is the second match group, and

+

the filepath is the empty sequence.

+
+
+

Finally, if the string does not match either expression:

+ +

the scheme is the empty sequence,

+

the string is unchanged, and

+

the filepath is the empty sequence.

+
+
+
+ +

If the scheme is the empty sequence, the + unc-path option is true, and the string + matches ^//[^/].*$, then the scheme is file + and the filepath is the string. +

+ +

If the scheme is known to be hierarchical, or known + not to be hierarchical, then hierarchical is set accordingly. + Exactly which schemes are known to be hierarchical or + non-hierarchical is + implementation-defined. + If the implementation does not know if a scheme is or is not + hierarchical, the hierarchical setting depends on the + string. If the string is the empty string, + hierarchical is the empty sequence (i.e. not known), + otherwise hierarchical is + true if string begins with / and false otherwise.

+ +

If the scheme is not known or is known to be file and + the string matches ^//*([a-zA-Z]:.*)$, + the authority is empty and the string is + the first match group. Otherwise, if the string + matches ^///*([^/]+)(/.*)?$ then the authority + is the first match group and the string is the second + match group. If the string does not match either + regular expression, the authority is the empty sequence + and the string is unchanged.

+ +

If the string matches ^//*([a-zA-Z]:.*)$, + the authority is empty and the string is + the first match group. Otherwise, if the string + matches ^///*([^/]+)(/.*)?$ then the authority + is the first match group and the string is the second + match group. If the string does not match either + regular expression, the authority is the empty sequence + and the string is unchanged.

+ +

If the authority matches + ^(([^@]*)@)(.*)(:([^:]*))?$, + then the userinfo is match group 2, otherwise + userinfo is the empty sequence. If + userinfo is present and contains a non-empty password, then + userinfo is discarded and set to the empty sequence + unless the allow-deprecated-features option is true.

+ +

When parsing the authority to find the host, + there are four possibilities: the host can be a registered name (e.g., + example.com), an IPv4 address (e.g., 127.0.0.1), + an IPv6 (or IPvFuture) address (e.g., [::1]), or an error + if there is an open square bracket ([) not matched by a + close square bracket (]). In a properly + constructed RFC 3986 URI, the only place where square + brackets may occur is around the IPv6/IPvFuture IP address.

+ + + +

If the authority matches + ^(([^@]*)@)?(\[[^\]]*\])(:([^:]*))?$, + then the host is match group 3, otherwise +

+
+ +

If the authority matches + ^(([^@]*)@)?\[.*$ + then is raised, otherwise +

+
+ +

If the authority matches + ^(([^@]*)@)?([^:]+)(:([^:]*))?$, + then the host is match group 3, otherwise +

+
+ +

the host is the empty sequence.

+
+
+ +

This function does not attempt to decode the components of the + host.

+ +

Similar care must be taken to match the port because an IPv6/IPvFuture + address may contain a colon.

+ + + +

If the authority matches + ^(([^@]*)@)?(\[[^\]]*\])(:([^:]*))?$, + then the port is match group 5, otherwise +

+
+ +

If the authority matches + ^(([^@]*)@)?([^:]+)(:([^:]*))?$, + then the port is match group 5, otherwise +

+
+ +

the port is the empty sequence.

+
+
+ +

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

+ +

If the string is the empty string, then + path is the empty sequence, otherwise path + is the whole string. If the scheme is + file or the empty sequence, and filepath is + the empty sequence, filepath is also the whole string.

+ +

The path separator is the value of the + path-separator option. A + path-segments array is constructed as follows: + tokenize the string on the path + separator, apply uri decoding on each + token, and convert the result to an array.

+ +

Applying uri decoding replaces all occurrences of + plus (+) with spaces and all occurrences of + %[a-fA-F0-9][a-fA-F0-9] with a single character with the + codepoint represented by the two digit hexadecimal number that + follows the % character. In other words, "A%42C" becomes + "ABC" If there are any occurrences of % followed + by up to two characters that are not hexadecimal digits, they are + replaced by the character sequence 0xef, 0xbf, 0xbd + (that is, 0xfffd, the Unicode replacement character, in UTF-8). + After replacing all of the percent-escaped characters, the character sequence is + interpreted as UTF-8 to get the string. In other words "A%XYC%Z%F0%9F%92%A9" becomes + "A�C�💩". If the character sequence is + not a valid sequence of UTF-8 characters, any invalid characters are replaced with the + 0xfffd.

+ +

The query separator is the value of the + query-separator option. + A query-segments value is constructed as follows: tokenize + the query on the query separator. For each + token, construct a map. If the token contains an equal sign (=), + the map contains a key named key with a value equal to the + string preceding the first equal sign, uri decoded, and a key named value + with a value equal to the string following the first equal sign, uri decoded. If the + token does not contain an equal sign, the map contains a single key named + value with a value equal to the token, uri decoded. In every case, + uri decoding is applied to each value add to the map. + The resulting sequence of maps is converted into an array.

+ +

If the filepath is not the empty sequence, + it is uri decoded. On a Windows system, any + forward slashes in the path may be + replaced with backslashes.

+ +

The following map is returned:

+ + { + "uri": $uri, + "scheme": scheme, + "hierarchical": hierarchical, + "authority": authority, + "userinfo": userinfo, + "host": host, + "port": port, + "path": path, + "query": query, + "fragment": fragment, + "path-segments": path-segments, + "query-segments": query-segments, + "filepath": filepath +} + +

The map should only be populated with keys that have a non-empty value (keys + whose value is the empty sequence or an empty array should + be omitted).

+ +

Implementations may implement additional or different rules for URIs that + have a scheme or pattern that they recognize. An implementation might choose + to parse jar: URIs with special rules, for example, since they extend the + syntax in ways not defined by . Implementations may add + additional keys to the map. The meaning of those keys is implementation-defined.

+
+ + +

A dynamic error is raised if + the URI contains an open square bracket in the authority component that + is not followed by a close square bracket.

+
+ + +

Like fn:resolve-uri, this function handles the additional characters + allowed in IRIs in the same way that other unreserved + characters are handled.

+

Unlike fn:resolve-uri, this function is not attempting to resolve + one URI against another and consequently, the errors that can arise under those + circumstances do not apply here. The fn:parse-uri function will + accept strings that would raise errors if resolution was attempted, + see fn:build-uri.

+
+ + + +

In the examples that follow, keys with values that are null, or an empty array, + are elided for editorial clarity. String literals that include an ampersand character + are written as string templates (for example `Barnes&Noble`) to ensure + that the examples work in both XPath and XQuery.

+ + parse-uri( + "http://qt4cg.org/specifications/xpath-functions-40/Overview.html#parse-uri" +) + map { + "uri": "http://qt4cg.org/specifications/xpath-functions-40/Overview.html#parse-uri", + "scheme": "http", + "hierarchical": true(), + "authority": "qt4cg.org", + "host": "qt4cg.org", + "path": "/specifications/xpath-functions-40/Overview.html", + "fragment": "parse-uri", + "path-segments": array { "", "specifications", "xpath-functions-40", "Overview.html" } +} + +
+ + + parse-uri("http://www.ietf.org/rfc/rfc2396.txt") + map { + "uri": "http://www.ietf.org/rfc/rfc2396.txt", + "scheme": "http", + "hierarchical": true(), + "authority": "www.ietf.org", + "host": "www.ietf.org", + "path": "/rfc/rfc2396.txt", + "path-segments": array { "", "rfc", "rfc2396.txt" } +} + + + + + parse-uri("https://example.com/path/to/file") + map { + "uri": "https://example.com/path/to/file", + "scheme": "https", + "hierarchical": true(), + "authority": "example.com", + "host": "example.com", + "path": "/path/to/file", + "path-segments": array { "", "path", "to", "file" } +} + + + + + parse-uri( + `https://example.com:8080/path?s=%22hello world%22&sort=relevance` +) + map { + "uri": `https://example.com:8080/path?s=%22hello world%22&sort=relevance`, + "scheme": "https", + "hierarchical": true(), + "authority": "example.com:8080", + "host": "example.com", + "port": "8080", + "path": "/path", + "query": `s=%22hello world%22&sort=relevance`, + "query-segments": array { + map { "key": "s", "value": '"hello world"' }, + map { "key": "sort", "value": "relevance" } + }, + "path-segments": array { "", "path" } +} + + + + + parse-uri("https://user@example.com/path/to/file") + map { + "uri": "https://user@example.com/path/to/file", + "scheme": "https", + "hierarchical": true(), + "authority": "user@example.com", + "userinfo": "user", + "host": "example.com", + "path": "/path/to/file", + "path-segments": array { "", "path", "to", "file" } +} + + + + + parse-uri("ftp://ftp.is.co.za/rfc/rfc1808.txt") + map { + "uri": "ftp://ftp.is.co.za/rfc/rfc1808.txt", + "scheme": "ftp", + "hierarchical": true(), + "authority": "ftp.is.co.za", + "host": "ftp.is.co.za", + "path": "/rfc/rfc1808.txt", + "path-segments": array { "", "rfc", "rfc1808.txt" } +} + + + + + parse-uri("file:////uncname/path/to/file") + map { + "uri": "file:////uncname/path/to/file", + "scheme": "file", + "hierarchical": true(), + "authority": "uncname", + "host": "uncname", + "path": "/path/to/file", + "filepath": "/path/to/file", + "path-segments": array { "", "path", "to", "file" } +} + + + + + parse-uri("file:///c:/path/to/file") + map { + "uri": "file:///c:/path/to/file", + "scheme": "file", + "hierarchical": true(), + "path": "/c:/path/to/file", + "filepath": "c:/path/to/file", + "path-segments": array { "", "c: ", "path", "to", "file" } +} + + + + + parse-uri("file:/C:/Program%20Files/test.jar") + map { + "uri": "file:/C:/Program%20Files/test.jar", + "scheme": "file", + "hierarchical": true(), + "path": "/C:/Program%20Files/test.jar", + "filepath": "C:/Program Files/test.jar", + "path-segments": array { "", "C: ", "Program Files", "test.jar" } +} + + + + + parse-uri("file:\\c:\path\to\file") + map { + "uri": "file:\\c:\path\to\file", + "scheme": "file", + "hierarchical": true(), + "path": "/c:/path/to/file", + "filepath": "c:/path/to/file", + "path-segments": array { "", "c: ", "path", "to", "file" } +} + + + + + parse-uri("file:\c:\path\to\file") + map { + "uri": "file:\c:\path\to\file", + "scheme": "file", + "hierarchical": true(), + "path": "/c:/path/to/file", + "filepath": "c:/path/to/file", + "path-segments": array { "", "c: ", "path", "to", "file" } +} + + + + + parse-uri("c:\path\to\file") + map { + "uri": "c:\path\to\file", + "scheme": "file", + "hierarchical": true(), + "path": "/c:/path/to/file", + "filepath": "c:/path/to/file", + "path-segments": array { "", "c: ", "path", "to", "file" } +} + + + + + parse-uri("/path/to/file") + +map { + "uri": "/path/to/file", + "hierarchical": true(), + "path": "/path/to/file", + "filepath": "/path/to/file", + "path-segments": array { "", "path", "to", "file" } +} + + + + + parse-uri("#testing") + +map { + "uri": "#testing", + "fragment": "testing" +} + + + + + parse-uri("?q=1") + +map { + "uri": "?q=1", + "query": "q=1", + "query-segments": array { + map { "key": "q", "value": "1" } + } +} + + + + + parse-uri("ldap://[2001:db8::7]/c=GB?objectClass?one") + +map { + "uri": "ldap://[2001:db8::7]/c=GB?objectClass?one", + "scheme": "ldap", + "hierarchical": true(), + "authority": "[2001:db8::7]", + "host": "[2001:db8::7]", + "path": "/c=GB", + "query": "objectClass?one", + "query-segments": array { + map { "value": "objectClass?one" } + }, + "path-segments": array { "", "c=GB" } +} + + + + + parse-uri("mailto:John.Doe@example.com") + +map { + "uri": "mailto:John.Doe@example.com", + "scheme": "mailto", + "hierarchical": false(), + "path": "John.Doe@example.com", + "path-segments": array { "John.Doe@example.com" } +} + + + + + parse-uri("news:comp.infosystems.www.servers.unix") + +map { + "uri": "news:comp.infosystems.www.servers.unix", + "scheme": "news", + "hierarchical": false(), + "path": "comp.infosystems.www.servers.unix", + "path-segments": array { "comp.infosystems.www.servers.unix" } +} + + + + + parse-uri("tel:+1-816-555-1212") + +map { + "uri": "tel:+1-816-555-1212", + "scheme": "tel", + "hierarchical": false(), + "path": "+1-816-555-1212", + "path-segments": array { " 1-816-555-1212" } +} + + + + + parse-uri("telnet://192.0.2.16:80/") + +map { + "uri": "telnet://192.0.2.16:80/", + "scheme": "telnet", + "hierarchical": true(), + "authority": "192.0.2.16:80", + "host": "192.0.2.16", + "port": "80", + "path": "/", + "path-segments": array { "", "" } +} + + + + + parse-uri( + "urn:oasis:names:specification:docbook:dtd:xml:4.1.2" +) + +map { + "uri": "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", + "scheme": "urn", + "hierarchical": false(), + "path": "oasis:names:specification:docbook:dtd:xml:4.1.2", + "path-segments": array { "oasis:names:specification:docbook:dtd:xml:4.1.2" } +} + + + + + parse-uri("tag:textalign.net,2015:ns") + +map { + "uri": "tag:textalign.net,2015:ns", + "scheme": "tag", + "hierarchical": false(), + "path": "textalign.net,2015:ns", + "path-segments": array { "textalign.net,2015:ns" } +} + + + + + + parse-uri("tag:jan@example.com,1999-01-31:my-uri") + +map { + "uri": "tag:jan@example.com,1999-01-31:my-uri", + "scheme": "tag", + "hierarchical": false(), + "path": "jan@example.com,1999-01-31:my-uri", + "path-segments": array { "jan@example.com,1999-01-31:my-uri" } +} + + + + +

This example uses the algorithm described above, not an algorithm that is +specifically aware of the jar: scheme.

+ + parse-uri( + "jar:file:/C:/Program%20Files/test.jar!/foo/bar" +) + +map { + "uri": "jar:file:/C:/Program%20Files/test.jar!/foo/bar", + "scheme": "jar", + "hierarchical": false(), + "path": "file:/C:/Program%20Files/test.jar!/foo/bar", + "path-segments": array { "file:", "C:", "Program Files", "test.jar!", "foo", "bar" } +} + + +
+ +

This example demonstrates that parsing the URI treats non-URI characters in +lexical IRIs as “unreserved characters”. The rationale for this is given in the +description of fn:resolve-uri.

+ + parse-uri("http://www.example.org/Dürst") + +map { + "uri": "http://www.example.org/Dürst", + "scheme": "http", + "hierarchical": true(), + "authority": "www.example.org", + "host": "www.example.org", + "path": "/Dürst", + "path-segments": array { "", "Dürst" } +} + + +
+ +

This example demonstrates a non-standard query separator.

+ + parse-uri( + "https://example.com:8080/path?s=%22hello world%22;sort=relevance", + map { "query-separator": ";" } +) + +map { + "uri": "https://example.com:8080/path?s=%22hello world%22;sort=relevance", + "scheme": "https", + "hierarchical": true(), + "authority": "example.com:8080", + "host": "example.com", + "port": "8080", + "path": "/path", + "query": "s=%22hello world%22;sort=relevance", + "query-segments": array { + map { "key": "s", "value": '"hello world"' }, + map { "key": "sort", "value": "relevance" } + }, + "path-segments": array { "", "path" } +} + +
+ +

This example uses an invalid query separator so raises an error.

+ + parse-uri( + "https://example.com:8080/path?s=%22hello world%22;;sort=relevance", + map { "query-separator": ";;" } +) + + +
+ +

This example demonstrates the use of | instead of : in a Windows +path.

+ + parse-uri("c|/path/to/file") + map { + "uri": "c|/path/to/file", + "scheme": "file", + "hierarchical": true(), + "path": "/c:/path/to/file", + "filepath": "c:/path/to/file", + "path-segments": array { "", "c:", "path", "to", "file" } +} + +
+ +

This example demonstrates the use of | instead of : in a Windows +path with an explicit file: scheme.

+ + parse-uri("file://c|/path/to/file") + map { + "uri": "file://c|/path/to/file", + "scheme": "file", + "hierarchical": true(), + "path": "/c:/path/to/file", + "filepath": "c:/path/to/file", + "path-segments": array { "", "c:", "path", "to", "file" } +} + +
+
+ + Proposed on 17 Oct 2022 to resolve + issue #72. + Accepted in principle on 15 Nov 2022, with some details still + to be resolved. Updated in response to + issue #389 and + issue #390. + FIXME: the examples need to be updated. + + +
+ + + + + + + + + + deterministic + context-dependent + focus-independent + + + +

Constructs a URI from the parts provided.

+
+ + +

A URI is composed from a scheme, authority, path, query, and fragment.

+ +

The following options are available:

+ + + + Identifies the path separator + xs:string + / + + + Identifies the query separator + xs:string + & + + + Indicates that deprecated URI + features should be returned + xs:boolean + false() + + + Indicates that a port number that is the same as + the default port for a given scheme should be omitted. + xs:boolean + false() + + + Indicates that the URI represents + a Windows Universal Naming Convention + Path. + xs:boolean + false() + + + +

The components are derived from the contents of the $parts + map in the following way:

+ +

If the scheme key is present in the map, the URI begins + with the value of that key. A URI is considered to be non-hierarchical + if either the hierarchical key is present in the + $parts map with the value + false() or if the scheme is known to be non-hierarchical. + (In other words, schemes are hierarchical by default.)

+ +

If the scheme is file and the unc-path + option is true, the scheme is delimited by a trailing :////, + otherwise, if the URI is non-hierarchical, the scheme is delimited by + a trailing :. For all other schemes, it is delimited by + a trailing ://. Exactly which schemes are known to be + non-hierarchical is + implementation-defined.

+ +

For simplicity of exposition, we take the + userinfo, host, and + port values from the map and imagine they are + stored in variables with the same name. If the key is not + present in the map, the value of the variable is set to the + empty sequence.

+ +

If $userinfo is non-empty and contains a + non-empty password, then $userinfo is set to the + empty sequence unless the + allow-deprecated-features option is true.

+ +

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

+ +

If any of $userinfo, $host, or $port + exist, the following authority is added to the URI + under construction: + concat((if (exists($userinfo)) then $userinfo || "@" else ""), + $host, + (if (exists($port)) then ":" || $port else ""))

+ +

If none of userinfo, host, or port + is present, and authority is present, the value of the + authority key is added to the URI. (In this case, no attempt + is made to determine if a password or standard port are present, + the authority value is simply added to the string.)

+ +

If the path-segments key exists in the map, then the + path is constructed from the parts, with non-URI characters encoded: + string-join($parts?path-segments ! encode-for-uri(.), $options?path-separator), + otherwise the value of the path key is used. + If the path value is the empty sequence, + the empty string is used for the path. The path is added to the URI.

+ +

If the query-segments key exists in the map, then + a sequence of strings is constructed from each segment in turn. + If the segment contains both a key and a value, + the string is the concatenation of the value of the key, + an equal sign (=), and the value of the value. If it contains + only one of those keys, then it is the value of that key. If it contains + neither, it is ignored. In any case, the keys and values, if present, are subject + to encoding with encode-for-uri. + The query is constructed by joining the resulting + strings into a single string, separated by $options?query-separator). + If the query-segments key does not exist in the map, but + the query key does, then the query is the value of the + query key. If there is a query, it is added to the URI with + a preceding question mark (?).

+ +

If the fragment key exists in the map, then + the value of that key is added to the URI with + a preceding hash mark (#).

+ +

The resulting URI is returned.

+
+ + + + + build-uri(map { + "scheme": "https", + "host": "qt4cg.org", + "port": (), + "path": "/specifications/index.html" + }) + "https://qt4cg.org/specifications/index.html" + + + + + Proposed on 17 Oct 2022 to resolve + issue #72. + Accepted in principle on 15 Nov 2022, with some details still + to be resolved. Updated in response to + issue #389 and + issue #390. + FIXME: the examples need to be updated. + +
+ + + + + + + + + + + deterministic + context-independent + focus-independent + + +

Partitions a sequence of items into a sequence of non-empty arrays containing the same items, + starting a new partition when a supplied condition is true.

+
+ +

Informally, the function starts by creating a partition containing the first item in the input sequence, + if any. For each remaining item J in the input sequence, + other than the first, it calls the supplied $break-when function with two + arguments: the contents of the current partition, and the item J.

+

Each partition is a sequence of items; the function result wraps each partition as an array, and returns + the sequence of arrays.

+

If the $break-when function returns true, the current partition is wrapped as an array and added to the result, + and a new current partition is created, initially containing the item J only. If the $break-when + function returns false, the item J is added to the current partition.

+

More formally, the function returns the result of the expression:

+ fold-left($input, (), function($partitions, $next) { + if (empty($partitions) or $break-when(foot($partitions)?*, $next)) + then ($partitions, [$next]) + else (trunk($partitions), array{foot($partitions)?*, $next}) + }) + +
+ +

The function enables a variety of positional grouping problems to be solved. For example:

+ +

partition($input, function($a, $b) { count($a) eq 3 } + partitions a sequence into fixed size groups of length 3.

+

partition($input, function($a, $b) { boolean($b/self::h1) } + starts a new group whenever an h1 element is encountered.

+

partition($input, function($a, $b) { $b lt foot($a) } + starts a new group whenever an item is encountered whose value is less than + the value of the previous item.

+
+

The callback function is not called to process the first item in the input sequence, because this will + always start a new partition. The first argument to the callback function (the current partition) is always + a non-empty sequence.

+
+ + + + partition( + ("Anita", "Anne", "Barbara", "Catherine", "Christine"), + function($partition, $next) { + substring(head($partition),1,1) ne substring($next,1,1) + } +) + (["Anita", "Anne"], ["Barbara"], ["Catherine", "Christine"]) + + + partition( + (1, 2, 3, 4, 5, 6, 7), + function($partition, $next) { + count($partition) eq 2 + } +) + ([1, 2], [3, 4], [5, 6], [7]) + + + partition( + (1, 4, 6, 3, 1, 1), + function($partition, $next) { + sum($partition) ge 5 + } +) + ([1, 4], [6], [3, 1, 1]) + + + partition( + tokenize("In the beginning was the word"), + function($partition, $next) { + sum(($partition, $next) ! string-length()) gt 10 + } +) + (["In", "the"], ["beginning"], ["was", "the", "word"]) + + + partition( + (1, 2, 3, 6, 7, 9, 10), + function($partition, $next) { + $next != foot($partition) + 1 + } +) + ([1, 2, 3], [6, 7], [9, 10]) + + + + + Proposed for 4.0 + +
+ + diff --git a/src/test/test-data/xslt-3.0.xsd b/src/test/test-xml/xslt-3.0.xsd similarity index 100% rename from src/test/test-data/xslt-3.0.xsd rename to src/test/test-xml/xslt-3.0.xsd diff --git a/src/xqdiagnostics.ts b/src/xqdiagnostics.ts index f7379d0..736de28 100644 --- a/src/xqdiagnostics.ts +++ b/src/xqdiagnostics.ts @@ -1,15 +1,14 @@ import * as vscode from 'vscode'; import * as constants from "./constants"; -import { XQLint } from '@quodatum/xqlint'; -import { XQueryLinter } from "./linting"; -import { channel } from "./common"; +import { XQLint, Marker } from '@quodatum/xqlint'; + +import { channel, isNotXQDoc, unsupportedScheme, Configuration, importRange } from "./common"; + // DiagnosticCollection for XQuery documents -export class XQueryDiagnostics implements vscode.DiagnosticCollection, - Iterable<[uri: vscode.Uri, diagnostics: readonly vscode.Diagnostic[]]> -{ +export class XQueryDiagnostics { diagnosticCollectionXQuery: vscode.DiagnosticCollection; - xqlintCollectionXQuery: Map; + xqlintCollectionXQuery: Map; constructor() { this.diagnosticCollectionXQuery = vscode.languages.createDiagnosticCollection(constants.diagnosticCollections.xquery); @@ -18,22 +17,12 @@ export class XQueryDiagnostics implements vscode.DiagnosticCollection, } - get name() { - return this.diagnosticCollectionXQuery.name; - } - - set(uri: unknown, diagnostics?: unknown): void { - channel.log("xqueryDiagnostics set: "+ uri); - if (uri instanceof Array) { - this.diagnosticCollectionXQuery.set(uri); - } else { - this.diagnosticCollectionXQuery.set(uri as vscode.Uri, diagnostics as vscode.Diagnostic[]); - } - } delete(uri: vscode.Uri): void { - channel.log("xqueryDiagnostics delete: " +uri); - this.diagnosticCollectionXQuery.delete(uri); - this.xqlintCollectionXQuery.delete(uri); + if (this.diagnosticCollectionXQuery.has(uri)) { + channel.log("xqueryDiagnostics delete: " + uri); + this.diagnosticCollectionXQuery.delete(uri); + this.xqlintCollectionXQuery.delete(uri.toString()); + } } clear(): void { @@ -42,9 +31,6 @@ export class XQueryDiagnostics implements vscode.DiagnosticCollection, this.xqlintCollectionXQuery.clear(); } - forEach(callback: (uri: vscode.Uri, diagnostics: readonly vscode.Diagnostic[], collection: vscode.DiagnosticCollection) => any, thisArg?: any): void { - this.diagnosticCollectionXQuery.forEach(callback); - } get(uri: vscode.Uri): readonly vscode.Diagnostic[] { channel.log("xqueryDiagnostics get: " + uri); return this.diagnosticCollectionXQuery.get(uri); @@ -52,14 +38,25 @@ export class XQueryDiagnostics implements vscode.DiagnosticCollection, has(uri: vscode.Uri): boolean { return this.diagnosticCollectionXQuery.has(uri); } - dispose(): void { - this.clear(); + update(uri: vscode.Uri, document: string) { + + const processor = Configuration.xqueryProcessor; + const opts = { "processor": processor, "fileName": uri.fsPath }; + const xqlint = new XQLint(document, opts); + const diags = getDiagnostics(xqlint); + this.xqlintCollectionXQuery.set(uri.toString(), xqlint); + this.diagnosticCollectionXQuery.set(uri, diags) } - // really? https://blog.logrocket.com/understanding-typescript-generators/ - [Symbol.iterator](): Iterator<[uri: vscode.Uri, diagnostics: readonly vscode.Diagnostic[]], any, undefined> { - const it: Iterator<[uri: vscode.Uri, diagnostics: readonly vscode.Diagnostic[]], any, undefined> = this.diagnosticCollectionXQuery[Symbol.iterator](); - return it; + xqlint(uri: vscode.Uri): XQLint { + const k=uri.toString(); + const xq= this.xqlintCollectionXQuery.get(k); + if(xq){ + return xq; + } else{ + console.log("ERROR"); + } } + } /** @@ -67,36 +64,68 @@ export class XQueryDiagnostics implements vscode.DiagnosticCollection, * @param doc xquery document to analyze * @param xqueryDiagnostics diagnostic collection */ -export function refreshDiagnostics(doc: vscode.TextDocument, xqueryDiagnostics: XQueryDiagnostics): void { - const supportedSchemes = [constants.uriSchemes.file, constants.uriSchemes.untitled]; - - if(doc.languageId !== constants.languageIds.xquery || supportedSchemes.indexOf(doc.uri.scheme) === -1){ - return; +export function refreshDiagnostics(doc: vscode.TextDocument, + xqueryDiagnostics: XQueryDiagnostics, + reason: string): void { + if (isNotXQDoc(doc)) return; + const isNew = !xqueryDiagnostics.has(doc.uri); + const refresh = reason === "change"; + channel.log((isNew ? "🆕" : "") + (refresh ? "♻️" : "") + "refreshDiagnostics " + reason + " " + doc.uri.toString()); + if (isNew || refresh) { + xqueryDiagnostics.update(doc.uri, doc.getText()); } - channel.log("refreshDiagnostics" + doc.uri.toString()); - const diagnostics = new XQueryLinter().lint(doc) - - xqueryDiagnostics.set(doc.uri, diagnostics); } - // forward doc changes export function subscribeToDocumentChanges(context: vscode.ExtensionContext, xqueryDiagnostics: XQueryDiagnostics): void { - if (vscode.window.activeTextEditor) { - refreshDiagnostics(vscode.window.activeTextEditor.document, xqueryDiagnostics); + const ed = vscode.window.activeTextEditor; + if (ed && !unsupportedScheme(ed.document.uri)) { + refreshDiagnostics(ed.document, xqueryDiagnostics, "current"); } - context.subscriptions.push( - vscode.window.onDidChangeActiveTextEditor(editor => { - if (editor) refreshDiagnostics(editor.document, xqueryDiagnostics); - }) + + const onDidClose = vscode.workspace.onDidCloseTextDocument( + doc => xqueryDiagnostics.delete(doc.uri) + ); + const onDidChange = vscode.workspace.onDidChangeTextDocument( + e => refreshDiagnostics(e.document, xqueryDiagnostics, "change") ); - context.subscriptions.push( - vscode.workspace.onDidChangeTextDocument(e => refreshDiagnostics(e.document, xqueryDiagnostics)) + // https://stackoverflow.com/questions/68518501/vscode-workspace-ondidchangetextdocument-is-called-even-when-there-is-no-conte + const onDidOpen = vscode.workspace.onDidOpenTextDocument( + doc => refreshDiagnostics(doc, xqueryDiagnostics, "open") ); - context.subscriptions.push( - vscode.workspace.onDidCloseTextDocument(doc => xqueryDiagnostics.delete(doc.uri)) + const onDidActive = vscode.window.onDidChangeActiveTextEditor( + editor => { + if (editor) refreshDiagnostics(editor.document, xqueryDiagnostics, "active"); + } ); + context.subscriptions.push(onDidOpen, onDidChange, onDidClose, onDidActive); +} + +function getDiagnostics(linter: XQLint): vscode.Diagnostic[] { + const diagnostics = new Array(); + linter.getErrors().forEach((error: Marker) => { + diagnostics.push(new vscode.Diagnostic( + importRange(error.pos), + error.message, + isSuppressed(error.message) ? vscode.DiagnosticSeverity.Information : vscode.DiagnosticSeverity.Error + )); + }); + + linter.getWarnings().forEach((warning: Marker) => { + diagnostics.push(new vscode.Diagnostic( + importRange(warning.pos), + warning.message, + vscode.DiagnosticSeverity.Warning + )); + }); + return diagnostics; +} +// [XQST0059] module "http://config" not found +// [XPST0008] "list-details#0": undeclared function +function isSuppressed(msg: string): boolean { + const errs = Configuration.xquerySuppressErrors; + return errs.some((x) => msg.includes(x)); } diff --git a/src/xquery-execution/commands/executeXQuery.ts b/src/xquery-cmds/executeXQuery.ts similarity index 81% rename from src/xquery-execution/commands/executeXQuery.ts rename to src/xquery-cmds/executeXQuery.ts index dcb1f2d..8137479 100644 --- a/src/xquery-execution/commands/executeXQuery.ts +++ b/src/xquery-cmds/executeXQuery.ts @@ -1,10 +1,10 @@ -import { OutputChannel, window, workspace } from "vscode"; -import { Disposable, Range, TextEditor, TextEditorEdit, Uri } from "vscode"; +import { OutputChannel, window } from "vscode"; +import { TextEditor, TextEditorEdit } from "vscode"; -import * as constants from "../../constants"; -import { channel,logdate } from "../../common/channel-basex"; -import { ChildProcess } from "../child-process"; -import { Configuration, NativeCommands } from "../../common"; +import * as constants from "../constants"; +import { channel,logdate } from "../common/channel-basex"; +import { ChildProcess } from "../common/child-process"; +import { Configuration, NativeCommands } from "../common"; let outputChannel:OutputChannel; diff --git a/src/xquery-cmds/index.ts b/src/xquery-cmds/index.ts new file mode 100644 index 0000000..085edde --- /dev/null +++ b/src/xquery-cmds/index.ts @@ -0,0 +1,2 @@ +export * from "./xqcmds"; +export * from "./executeXQuery"; \ No newline at end of file diff --git a/src/xquery-cmds/xqcmds.ts b/src/xquery-cmds/xqcmds.ts new file mode 100644 index 0000000..5780277 --- /dev/null +++ b/src/xquery-cmds/xqcmds.ts @@ -0,0 +1,48 @@ + +import { TextEditor, Selection, window } from "vscode"; +import { channel } from "../common/channel-basex"; +import { Configuration,importRange } from "../common"; +import { diagnosticCollectionXQuery } from "../extension"; + +export async function setProcessor(): Promise { + const processor = Configuration.xqueryProcessor; + const name = await window.showInputBox({ + prompt: "processor", + value: processor + }); + if (name) { + channel.log("setProcessor:" + name); + Configuration.xqueryProcessor = name; + } +} + +// select enclosing declaration +export function selectDeclaration(textEditor: TextEditor): void { + channel.log("selectDeclaration:"); + + const linter = diagnosticCollectionXQuery.xqlint(textEditor.document.uri); + const pos = textEditor.selection.start; + const node = linter.getAST(pos); + const n2=findNode(node,"AnnotatedDecl"); + if(n2){ + const range=importRange(n2.pos); + // include following ; + textEditor.selection = new Selection(range.start, range.end.translate(0,1)); + }else{ + window.showInformationMessage("select declaration - No enclosing declaration") + } + +} + +// select enclosing declaration and trailing ; +export function xmlnsInfo(): void { + console.log("todo"); +} +// return 1st ancestor node with name or undefined +function findNode(node :any,nodeName :string):any{ + let n2 = node; + while (n2 !== null) { + if(n2.name === nodeName) return n2; + n2 = n2.getParent; + } +} \ No newline at end of file diff --git a/src/xquery-execution/commands/index.ts b/src/xquery-execution/commands/index.ts deleted file mode 100644 index d97f33e..0000000 --- a/src/xquery-execution/commands/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./executeXQuery"; diff --git a/src/xquery-execution/index.ts b/src/xquery-execution/index.ts deleted file mode 100644 index 9633bbb..0000000 --- a/src/xquery-execution/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./child-process"; diff --git a/tsconfig.json b/tsconfig.json index 68c6206..e315149 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,7 +5,8 @@ "outDir": "out", "lib": [ "dom", - "es6" + "es6", + "es2019" ], "sourceMap": true, "rootDir": "src", From 84263375f6de3d1697eb84c1cc2ab594816e0f06 Mon Sep 17 00:00:00 2001 From: Andy Bunce Date: Wed, 27 Sep 2023 22:50:26 +0100 Subject: [PATCH 2/8] [mod] use events --- CHANGELOG.md | 14 +-- docs/history.md | 9 ++ docs/index.md | 2 +- package.json | 11 ++- snippets.jsonc | 34 +++++--- src/common/document-selectors.ts | 4 +- src/common/document.ts | 9 ++ src/common/index.ts | 1 + src/common/workspace.ts | 14 +++ src/common/xml-traverser.ts | 1 - src/common/xqlint.ts | 2 +- src/constants.ts | 4 +- src/extension.ts | 26 ++---- src/providers/activate.ts | 17 ++++ src/providers/codeaction.ts | 105 +++++++++++++++++++++++ src/providers/codeactions-diagnostics.ts | 61 +++++++++++++ src/providers/hover.ts | 2 +- src/test/test-xquery/ast-to-xqdoc.xqm | 5 +- src/test/test-xquery/empty.xq | 0 src/xqdiagEvents.ts | 18 ++++ src/xqdiagnostics.ts | 90 +++++++++++++++---- src/xquery-cmds/xqactions.ts | 60 +++++++++++++ src/xquery-cmds/xqcmds.ts | 7 +- tsconfig.json | 2 +- 24 files changed, 431 insertions(+), 67 deletions(-) create mode 100644 docs/history.md create mode 100644 src/common/document.ts create mode 100644 src/common/workspace.ts create mode 100644 src/providers/activate.ts create mode 100644 src/providers/codeaction.ts create mode 100644 src/providers/codeactions-diagnostics.ts create mode 100644 src/test/test-xquery/empty.xq create mode 100644 src/xqdiagEvents.ts create mode 100644 src/xquery-cmds/xqactions.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 2515a23..5d8d5f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,15 @@ +# 0.1.18 (2023-09-21) +* error decorator +* empty codeaction hint # 0.1.16 (2023-09-10) -* [mod] virtual docs updates +* virtual docs updates +* add command basexTools.xqLibrary # 0.1.15 (2023-09-09) -* [ADD] set processor and selectDeclaration commands -* [mod] rework event handlers +* Add commands: set processor and selectDeclaration. +* rework event handlers # 0.1.14 (2023-08-26) -* [mod] Use xqlint 0.3.3 -* [mod] rewrite event subscriptions +* Use xqlint 0.3.3 +* rewrite event subscriptions # 0.1.8 (2023-05-26) * extract namespace library data to `xq-catalogs` component diff --git a/docs/history.md b/docs/history.md new file mode 100644 index 0000000..2eb4a2b --- /dev/null +++ b/docs/history.md @@ -0,0 +1,9 @@ +--- +title: History +summary: The release history of the vscode-basex extension +authors: + - Andy Bunce +date: 2023-07-23 +--- + +Versions... \ No newline at end of file diff --git a/docs/index.md b/docs/index.md index 5d01654..bd8c1a9 100644 --- a/docs/index.md +++ b/docs/index.md @@ -12,7 +12,7 @@ date: 2023-07-05 !!! warning Status This extension is "Work in progress". Errors and changes to be expected. -For information about installing this extension see [here](installation.md). +Information about installing this extension is [here](installation.md). ## Working with XQuery sources * [XQuery coding](xquery/) diff --git a/package.json b/package.json index 3982873..45fbca3 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "vscode-basex", "displayName": "BaseX tools", "description": "BaseX tools: XQuery, XML, XPath Tools for Visual Studio Code", - "version": "0.1.16", + "version": "0.1.18", "preview": true, "publisher": "quodatum", "author": "Andy Bunce (https://github.com/Quodatum)", @@ -56,6 +56,12 @@ "icon": "$(bracket-dot)", "enablement": "editorLangId == xquery" }, + { + "command": "basexTools.xqLibrary", + "title": "BaseX Tools: About known namespaces", + "shortTitle": "BaseX Tools: library", + "enablement": "editorLangId == xquery" + }, { "command": "basexTools.xqLintReport", "title": "BaseX Tools: Analysis of current location in Xquery source", @@ -132,8 +138,6 @@ "basexTools.xquery.suppressErrors": { "type": "array", "default": [ - "[XQST0059]", - "[XPST0008]" ], "description": "Lint Error messages including these strings are marked as info rather than error. TEMP HACK! " } @@ -302,6 +306,7 @@ }, { "id": "basex-script", + "aliases": [ "bxs" ], diff --git a/snippets.jsonc b/snippets.jsonc index df1b148..48bae38 100644 --- a/snippets.jsonc +++ b/snippets.jsonc @@ -1,5 +1,15 @@ { - + "new library module": { + "prefix": "xquery", + "body": [ + "xquery version '3.1';", + "(:~", + ":)", + "module namespace ${1:ns} = '${2:http://www.example.com/}';", + "" + ], + "description": "Library template" + }, "for": { "prefix": "for", "body": "for $${1:item} in ${2:expr}" @@ -48,7 +58,7 @@ "prefix": "sw", "body": [ "switch(${1:foo})", - "case ${2:foo} return ${3:true}", + "case ${2:foo} return ${3:true}", "default return ${4:false}" ], "description": "switch statement" @@ -57,7 +67,7 @@ "prefix": "type", "body": [ "typeswitch(${1:foo})", - "case ${2:foo} return ${3:true}", + "case ${2:foo} return ${3:true}", "default return ${4:false}" ], "description": "typeswitch statement" @@ -74,9 +84,9 @@ "prefix": "tumbling", "body": [ "for tumbling window $${1:varname} in ${2:expr}", - "start at $${3:start} when ${4:expr}", - "end at $${5:end} when ${6:expr}", - "return ${7:expr}" + "start at $${3:start} when ${4:expr}", + "end at $${5:end} when ${6:expr}", + "return ${7:expr}" ], "description": "tumbling window" }, @@ -84,19 +94,16 @@ "prefix": "sliding", "body": [ "for sliding window $${1:varname} in ${2:expr}", - "start at $${3:start} when ${4:expr}", - "end at $${5:end} when ${6:expr}", - "return ${7:expr}" + "start at $${3:start} when ${4:expr}", + "end at $${5:end} when ${6:expr}", + "return ${7:expr}" ], "description": "sliding window" } } //snippet if // if(${1:true}) then ${2:expr} else ${3:true} - // default return ${4:false} - - //snippet let // let $${1:varname} := ${2:expr} //snippet group @@ -116,5 +123,4 @@ //snippet castable // castable as ${1:atomicType} //snippet cast -// cast as ${1:atomicType} - +// cast as ${1:atomicType} \ No newline at end of file diff --git a/src/common/document-selectors.ts b/src/common/document-selectors.ts index 58b8983..e443d03 100644 --- a/src/common/document-selectors.ts +++ b/src/common/document-selectors.ts @@ -4,8 +4,8 @@ import * as constants from "../constants"; export function createDocumentSelector(language: string): DocumentFilter[] { return [ - { language, scheme: constants.uriSchemes.file }, - { language, scheme: constants.uriSchemes.untitled }, + { language: language, scheme: constants.uriSchemes.file }, + { language: language, scheme: constants.uriSchemes.untitled }, ]; } export function isNotXQDoc(doc: TextDocument): boolean { diff --git a/src/common/document.ts b/src/common/document.ts new file mode 100644 index 0000000..269d803 --- /dev/null +++ b/src/common/document.ts @@ -0,0 +1,9 @@ +import { TextDocument,Range} from 'vscode'; + +export function fullRange(document:TextDocument) { + const lastLine = document.lineAt(document.lineCount - 1); + return new Range(document.positionAt(0), lastLine.range.end); +} +export function isEmpty(document:TextDocument) :boolean{ + return (document.lineCount ===1) && document.lineAt(document.lineCount - 1).isEmptyOrWhitespace +} diff --git a/src/common/index.ts b/src/common/index.ts index 65e5abb..ac67251 100644 --- a/src/common/index.ts +++ b/src/common/index.ts @@ -5,3 +5,4 @@ export * from "./extension-state"; export * from "./native-commands"; export * from "./xml-traverser"; export * from "./channel-basex"; +export * from "./document"; diff --git a/src/common/workspace.ts b/src/common/workspace.ts new file mode 100644 index 0000000..a627578 --- /dev/null +++ b/src/common/workspace.ts @@ -0,0 +1,14 @@ +// https://code.visualstudio.com/docs/editor/workspaces + +import * as path from 'path'; +import { Uri, workspace } from 'vscode' + + +export function basePathForFilename(uri:Uri): string { + + if (workspace.workspaceFolders) { + return workspace.getWorkspaceFolder(uri).uri.fsPath; + } else { + return path.dirname(uri.fsPath); + } +} diff --git a/src/common/xml-traverser.ts b/src/common/xml-traverser.ts index 54ddd21..570ecc6 100644 --- a/src/common/xml-traverser.ts +++ b/src/common/xml-traverser.ts @@ -1,5 +1,4 @@ import { Position } from "vscode"; -import { DOMParser } from "xmldom"; export class XmlTraverser { diff --git a/src/common/xqlint.ts b/src/common/xqlint.ts index e1e3f23..11d0c5e 100644 --- a/src/common/xqlint.ts +++ b/src/common/xqlint.ts @@ -1,7 +1,7 @@ import { LintRange } from "@quodatum/xqlint"; import { Range } from "vscode"; -export function importRange(lintRange: LintRange): Range { +export function importRange(lintRange?: LintRange): Range { return lintRange? new Range(lintRange.sl, lintRange.sc, lintRange.el, lintRange.ec) :new Range(0,0,0,0); diff --git a/src/constants.ts b/src/constants.ts index f04d407..bb80128 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -4,7 +4,8 @@ export namespace commands { export const xqDoc = "basexTools.xqDoc"; // used as url scheme export const xqParse = "basexTools.xqParse"; // used as url scheme export const xqProcessor = "basexTools.processor"; - export const xqSelectDeclaration = "basexTools.selectDeclaration"; + export const xqSelectDeclaration = "basexTools.selectDeclaration"; + export const xqLibrary = "basexTools.xqLibrary"; export const xqLintReport = "basexTools.xqLintReport"; export const xqClearDiagnostics ="basexTools.clearDiagnostics" @@ -24,6 +25,7 @@ export namespace contextKeys { export namespace diagnosticCollections { export const xquery = "XQueryDiagnostics"; + export const xqActions = "XQueryActions"; } export namespace languageIds { diff --git a/src/extension.ts b/src/extension.ts index 56de534..4da40d4 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -6,23 +6,21 @@ import { import { channel, createDocumentSelector, ExtensionState, Configuration } from "./common"; import { XQueryDiagnostics, subscribeToDocumentChanges } from "./xqdiagnostics" - +//import { activate as activateActions} from "./xquery-cmds/xqactions"; import { XmlFormatterFactory, XmlFormattingEditProvider } from "./formatting"; import { formatAsXml, minifyXml, xmlToText, textToXml } from "./formatting/commands"; import { xqLintReport, activateVirtualDocs } from "./linting"; import { XmlTreeDataProvider } from "./tree-view"; import { evaluateXPath, getCurrentXPath } from "./xpath/commands"; -import { setProcessor, selectDeclaration, executeXQuery } from "./xquery-cmds"; +import { setProcessor , selectDeclaration, executeXQuery, libraryInfo } from "./xquery-cmds"; import * as constants from "./constants"; -import * as formatter from "./providers/formatting"; -import * as symbols from './providers/symbols'; -import * as hover from './providers/hover'; -import * as completion from './providers/completion'; -import * as documentLink from './providers/documentlink'; +import * as providers from "./providers/activate"; + export const diagnosticCollectionXQuery=new XQueryDiagnostics(); +//const actionDiagnostics = languages.createDiagnosticCollection(constants.diagnosticCollections.xqActions); export function activate(context: ExtensionContext) { channel.log("Extension activate"); @@ -30,19 +28,12 @@ export function activate(context: ExtensionContext) { /* Linting Features */ subscribeToDocumentChanges(context, diagnosticCollectionXQuery); - + //activateActions(context,actionDiagnostics); /* activate XQuery handlers */ - symbols.activate(context); - hover.activate(context); - completion.activate(context); - documentLink.activate(context); - formatter.activate(context); - + providers.activate(context,diagnosticCollectionXQuery); + activateVirtualDocs(context); - - - /* XML Formatting Features */ const xmlXsdDocSelector = [...createDocumentSelector(constants.languageIds.xml), ...createDocumentSelector(constants.languageIds.xsd)]; const xmlFormattingEditProvider = new XmlFormattingEditProvider(XmlFormatterFactory.getXmlFormatter()); @@ -85,6 +76,7 @@ export function activate(context: ExtensionContext) { context.subscriptions.push( commands.registerTextEditorCommand(constants.commands.xqExecute, executeXQuery), commands.registerTextEditorCommand(constants.commands.xqSelectDeclaration, selectDeclaration), + commands.registerTextEditorCommand(constants.commands.xqLibrary, libraryInfo), commands.registerCommand(constants.commands.xqProcessor, setProcessor), commands.registerCommand(constants.commands.xqClearDiagnostics, diagnosticCollectionXQuery.clear), ); diff --git a/src/providers/activate.ts b/src/providers/activate.ts new file mode 100644 index 0000000..89ed384 --- /dev/null +++ b/src/providers/activate.ts @@ -0,0 +1,17 @@ +import { ExtensionContext} from "vscode"; +import {XQueryDiagnostics} from "../xqdiagnostics"; +import * as formatter from "./formatting"; +import * as symbols from './symbols'; +import * as hover from './hover'; +import * as codeAction from './codeaction'; +import * as completion from './completion'; +import * as documentLink from './documentlink'; + +export function activate(context: ExtensionContext,diagnosticCollectionXQuery:XQueryDiagnostics) { + symbols.activate(context); + hover.activate(context); + codeAction.activate(context,diagnosticCollectionXQuery); + completion.activate(context); + documentLink.activate(context); + formatter.activate(context); +} diff --git a/src/providers/codeaction.ts b/src/providers/codeaction.ts new file mode 100644 index 0000000..d41f8c5 --- /dev/null +++ b/src/providers/codeaction.ts @@ -0,0 +1,105 @@ +/*--------------------------------------------------------- + * Copyright (C) Quodatum Ltd + *--------------------------------------------------------*/ + +import * as vscode from 'vscode'; +import { subscribeToDocumentChanges, XQ_ACTION } from './codeactions-diagnostics'; +import { languageIds } from "../constants"; +import { XQueryDiagnostics } from "../xqdiagnostics"; +import { isEmpty } from '../common' +import { IXQParsedEvent } from '../xqdiagEvents'; +const COMMAND = 'code-actions-sample.command'; + +export function activate(context: vscode.ExtensionContext, diagnosticCollectionXQuery: XQueryDiagnostics) { + context.subscriptions.push( + vscode.languages.registerCodeActionsProvider(languageIds.xquery, new XQAction(), { + providedCodeActionKinds: XQAction.providedCodeActionKinds + })); + + const xqActionsDiagnostics = vscode.languages.createDiagnosticCollection("xq-actions"); + context.subscriptions.push(xqActionsDiagnostics); + diagnosticCollectionXQuery.onDidDiag(update); + //subscribeToDocumentChanges(context, xqActionsDiagnostics); + + context.subscriptions.push( + vscode.languages.registerCodeActionsProvider(languageIds.xquery, new Emojinfo(), { + providedCodeActionKinds: Emojinfo.providedCodeActionKinds + }) + ); + + context.subscriptions.push( + vscode.commands.registerCommand(COMMAND, () => vscode.env.openExternal(vscode.Uri.parse('https://unicode.org/emoji/charts-12.0/full-emoji-list.html'))) + ); +} +function update(event: IXQParsedEvent) { + if (event.xqlint) { + console.log("Parsed: " + event.uri.toJSON()) + } else { + console.log("Dropped: "+event.uri.toString()) + } +} +/** + * Provides code actions for converting :) to a smiley emoji. + */ +export class XQAction implements vscode.CodeActionProvider { + + public static readonly providedCodeActionKinds = [ + vscode.CodeActionKind.QuickFix + ]; + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public provideCodeActions(document: vscode.TextDocument, _range: vscode.Range): vscode.CodeAction[] | undefined { + const actions = []; + if (isEmpty(document)) { + const emptyFix = this.insertSnippet(document); + actions.push(emptyFix); + } + return actions; + } + + + + private insertSnippet(document: vscode.TextDocument): vscode.CodeAction { + const fix = new vscode.CodeAction(`insert template`, vscode.CodeActionKind.QuickFix); + fix.edit = new vscode.WorkspaceEdit(); + const startPos = document.positionAt(0); + const snippet = new vscode.SnippetString("module namespace ${1:ns} = '${2:http://www.example.com/}';"); + fix.edit.set(document.uri, [vscode.SnippetTextEdit.insert(startPos, snippet)]) + return fix; + } + + private createCommand(): vscode.CodeAction { + const action = new vscode.CodeAction('Learn more...', vscode.CodeActionKind.Empty); + action.command = { command: COMMAND, title: 'Learn more about emojis', tooltip: 'This will open the unicode emoji page.' }; + return action; + } +} + +/** + * Provides code actions corresponding to diagnostic problems. + */ +export class Emojinfo implements vscode.CodeActionProvider { + + public static readonly providedCodeActionKinds = [ + vscode.CodeActionKind.QuickFix + ]; + + provideCodeActions(document: vscode.TextDocument, range: vscode.Range | vscode.Selection, context: vscode.CodeActionContext, token: vscode.CancellationToken): vscode.CodeAction[] { + // for each diagnostic entry that has the matching `code`, create a code action command + return context.diagnostics + .filter(diagnostic => diagnostic.code === XQ_ACTION) + .map(diagnostic => this.createCommandCodeAction(diagnostic)); + } + + private createCommandCodeAction(diagnostic: vscode.Diagnostic): vscode.CodeAction { + const action = new vscode.CodeAction('Learn more...', vscode.CodeActionKind.QuickFix); + action.command = { command: COMMAND, title: 'Learn more about emojis', tooltip: 'This will open the unicode emoji page.' }; + action.diagnostics = [diagnostic]; + action.isPreferred = true; + return action; + } +} +async function insertSnippet(name: string) { + // the below uses a pre-existing snippet with a name 'Custom Header' + await vscode.commands.executeCommand("editor.action.insertSnippet", { "name": name }); +} diff --git a/src/providers/codeactions-diagnostics.ts b/src/providers/codeactions-diagnostics.ts new file mode 100644 index 0000000..830a9b5 --- /dev/null +++ b/src/providers/codeactions-diagnostics.ts @@ -0,0 +1,61 @@ +/*--------------------------------------------------------- + * Copyright (C) Quodatum. + *--------------------------------------------------------*/ + +/** To demonstrate code actions associated with Diagnostics problems, this file provides a mock diagnostics entries. */ + +import * as vscode from 'vscode'; +import { channel, unsupportedScheme,isEmpty } from '../common'; + +/** Code that is used to associate diagnostic entries with code actions. */ +export const XQ_ACTION = 'xq_action'; + + + +/** + * Analyzes the text document for problems. + * only empty->snippet. + * @param doc text document to analyze + * @param xqActionsDiagnostics diagnostic collection + */ +export function refreshDiagnostics(doc: vscode.TextDocument, xqActionsDiagnostics: vscode.DiagnosticCollection): void { + const diagnostics: vscode.Diagnostic[] = []; + if(!doc || unsupportedScheme(doc.uri)) return; + channel.log("action refresh: "+doc.uri.toString()); + if (isEmpty(doc)) { + diagnostics.push(emptyText()); + } + xqActionsDiagnostics.set(doc.uri, diagnostics); +} + +// create hint +function emptyText():vscode.Diagnostic { + // create range that represents, where in the document the word is + const range = new vscode.Range(0, 0, 0, 0); + const diagnostic = new vscode.Diagnostic(range, "Empty source.", + vscode.DiagnosticSeverity.Warning); + diagnostic.code = XQ_ACTION; + return diagnostic +} + +export function subscribeToDocumentChanges(context: vscode.ExtensionContext, xqActionsDiagnostics: vscode.DiagnosticCollection): void { + if (vscode.window.activeTextEditor) { + refreshDiagnostics(vscode.window.activeTextEditor.document, xqActionsDiagnostics); + } + context.subscriptions.push( + vscode.window.onDidChangeActiveTextEditor(editor => { + if (editor) { + refreshDiagnostics(editor.document, xqActionsDiagnostics); + } + }) + ); + + context.subscriptions.push( + vscode.workspace.onDidChangeTextDocument(e => refreshDiagnostics(e.document, xqActionsDiagnostics)) + ); + + context.subscriptions.push( + vscode.workspace.onDidCloseTextDocument(doc => xqActionsDiagnostics.delete(doc.uri)) + ); + +} \ No newline at end of file diff --git a/src/providers/hover.ts b/src/providers/hover.ts index 2427eae..ee476a1 100644 --- a/src/providers/hover.ts +++ b/src/providers/hover.ts @@ -22,7 +22,7 @@ class XQueryHoverProvider implements vscode.HoverProvider { if (!range) return null const word = document.getText(range); const linter = diagnosticCollectionXQuery.xqlint(document.uri); - + const sctx = linter.getSctx(position); const node = linter.getAST(position); if (node.name === 'WS') return null; diff --git a/src/test/test-xquery/ast-to-xqdoc.xqm b/src/test/test-xquery/ast-to-xqdoc.xqm index 4f1cebf..79cd330 100644 --- a/src/test/test-xquery/ast-to-xqdoc.xqm +++ b/src/test/test-xquery/ast-to-xqdoc.xqm @@ -8,8 +8,7 @@ create xqdoc from parse tree module namespace xqdc = 'quodatum:xqdoca.model.xqdoc'; import module namespace xqcom = 'quodatum:xqdoca.model.comment' at "comment-to-xqdoc.xqm"; -declare namespace xqdoc="http://www.xqdoc.org/1.0"; - +declare namespace xqdoc="http://www.xqdoc.org/1.0"; (:~ build xqdoc from XQuery parse tree @@ -67,7 +66,7 @@ return { $uri } { $name } { $com } - { util:if(xqdc:opt($opts,"body-full"),xqdc:body(root($parse)))} + { util:if(xqdc:opt($opts,"body-full"),xqdc:body(root($parse))) } }; diff --git a/src/test/test-xquery/empty.xq b/src/test/test-xquery/empty.xq new file mode 100644 index 0000000..e69de29 diff --git a/src/xqdiagEvents.ts b/src/xqdiagEvents.ts new file mode 100644 index 0000000..3e239a5 --- /dev/null +++ b/src/xqdiagEvents.ts @@ -0,0 +1,18 @@ +import {Uri} from "vscode"; + +import { XQLint } from "@quodatum/xqlint"; + +export interface IXQParsedEvent { + uri: Uri; + xqlint?: XQLint; +} + +export class XQParsedEvent implements IXQParsedEvent { + uri: Uri; + xqlint: XQLint; + + constructor(uri: Uri,xqLint?:XQLint) { + this.uri = uri; + this.xqlint=xqLint; + } +} \ No newline at end of file diff --git a/src/xqdiagnostics.ts b/src/xqdiagnostics.ts index 736de28..e0a1351 100644 --- a/src/xqdiagnostics.ts +++ b/src/xqdiagnostics.ts @@ -1,5 +1,10 @@ +/* + +*/ import * as vscode from 'vscode'; import * as constants from "./constants"; +import {IXQParsedEvent,XQParsedEvent as ParsedEvent} from "./xqdiagEvents"; + import { XQLint, Marker } from '@quodatum/xqlint'; import { channel, isNotXQDoc, unsupportedScheme, Configuration, importRange } from "./common"; @@ -10,6 +15,9 @@ export class XQueryDiagnostics { diagnosticCollectionXQuery: vscode.DiagnosticCollection; xqlintCollectionXQuery: Map; + private diagEmitter = new vscode.EventEmitter(); + onDidDiag: vscode.Event = this.diagEmitter.event; + constructor() { this.diagnosticCollectionXQuery = vscode.languages.createDiagnosticCollection(constants.diagnosticCollections.xquery); this.xqlintCollectionXQuery = new Map(); @@ -22,6 +30,7 @@ export class XQueryDiagnostics { channel.log("xqueryDiagnostics delete: " + uri); this.diagnosticCollectionXQuery.delete(uri); this.xqlintCollectionXQuery.delete(uri.toString()); + this.diagEmitter.fire(new ParsedEvent(uri)); } } @@ -35,29 +44,34 @@ export class XQueryDiagnostics { channel.log("xqueryDiagnostics get: " + uri); return this.diagnosticCollectionXQuery.get(uri); } + set(uri: vscode.Uri, diagnostics: vscode.Diagnostic[]) { + this.diagnosticCollectionXQuery.set(uri, diagnostics); + } has(uri: vscode.Uri): boolean { return this.diagnosticCollectionXQuery.has(uri); } - update(uri: vscode.Uri, document: string) { - const processor = Configuration.xqueryProcessor; - const opts = { "processor": processor, "fileName": uri.fsPath }; - const xqlint = new XQLint(document, opts); - const diags = getDiagnostics(xqlint); + update(uri: vscode.Uri, document: string) { + const xqlint = linter(uri, document); this.xqlintCollectionXQuery.set(uri.toString(), xqlint); - this.diagnosticCollectionXQuery.set(uri, diags) + this.diagEmitter.fire(new ParsedEvent(uri,xqlint)) } + xqlint(uri: vscode.Uri): XQLint { - const k=uri.toString(); - const xq= this.xqlintCollectionXQuery.get(k); - if(xq){ + const xq = this.xqlintCollectionXQuery.get(uri.toString()); + if (xq) { return xq; - } else{ - console.log("ERROR"); + } else { + throw { name: "NOXQLINT", message: "should not happen" }; } } } +function linter(uri: vscode.Uri, document: string) { + const processor = Configuration.xqueryProcessor; + const opts = { "processor": processor, "fileName": uri.fsPath }; + return new XQLint(document, opts); +} /** * Analyzes the xquery document for problems. @@ -68,14 +82,32 @@ export function refreshDiagnostics(doc: vscode.TextDocument, xqueryDiagnostics: XQueryDiagnostics, reason: string): void { if (isNotXQDoc(doc)) return; + const editor = vscode.window.visibleTextEditors.find( + (editor) => editor.document === doc + ); const isNew = !xqueryDiagnostics.has(doc.uri); const refresh = reason === "change"; channel.log((isNew ? "🆕" : "") + (refresh ? "♻️" : "") + "refreshDiagnostics " + reason + " " + doc.uri.toString()); if (isNew || refresh) { - xqueryDiagnostics.update(doc.uri, doc.getText()); + const text = doc.getText(); + xqueryDiagnostics.update(doc.uri, text); + const xqlint = xqueryDiagnostics.xqlint(doc.uri); + const diagnostics = new Array(); + diagnostics.push(new vscode.Diagnostic( + importRange(), + "A Test", + vscode.DiagnosticSeverity.Information +)), + pushDiagnostics(xqlint, diagnostics); + + xqueryDiagnostics.set(doc.uri, diagnostics); + channel.log("DD:" + diagnostics.length); + } + if (editor) { + const xqlint = xqueryDiagnostics.xqlint(doc.uri); + decorate(editor, xqlint); } } - // forward doc changes export function subscribeToDocumentChanges(context: vscode.ExtensionContext, xqueryDiagnostics: XQueryDiagnostics): void { const ed = vscode.window.activeTextEditor; @@ -103,8 +135,7 @@ export function subscribeToDocumentChanges(context: vscode.ExtensionContext, xqu context.subscriptions.push(onDidOpen, onDidChange, onDidClose, onDidActive); } -function getDiagnostics(linter: XQLint): vscode.Diagnostic[] { - const diagnostics = new Array(); +function pushDiagnostics(linter: XQLint, diagnostics: vscode.Diagnostic[]) { linter.getErrors().forEach((error: Marker) => { diagnostics.push(new vscode.Diagnostic( @@ -123,9 +154,38 @@ function getDiagnostics(linter: XQLint): vscode.Diagnostic[] { }); return diagnostics; } + // [XQST0059] module "http://config" not found // [XPST0008] "list-details#0": undeclared function function isSuppressed(msg: string): boolean { const errs = Configuration.xquerySuppressErrors; return errs.some((x) => msg.includes(x)); } +const parseFailedDecorationType = vscode.window.createTextEditorDecorationType({ + borderWidth: '1px', + borderStyle: 'solid', + overviewRulerColor: 'red', + overviewRulerLane: vscode.OverviewRulerLane.Right, + light: { + // this color will be used in light color themes + borderColor: 'darkred' + }, + dark: { + // this color will be used in dark color themes + borderColor: 'lightred' + } +}); + + +function decorate(editor: vscode.TextEditor, xqlint: XQLint) { + const smallNumbers: vscode.DecorationOptions[] = []; + if (xqlint.hasSyntaxError()) { + const r=xqlint.getErrors(); + const range1=importRange(r[r.length-1].pos); + const lastLine = editor.document.lineAt(editor.document.lineCount - 1); + const range=range1.with(range1.start,lastLine.range.end) + const decoration = { range: range, hoverMessage: 'Parse failed' }; + smallNumbers.push(decoration); + } + editor.setDecorations(parseFailedDecorationType, smallNumbers); +} diff --git a/src/xquery-cmds/xqactions.ts b/src/xquery-cmds/xqactions.ts new file mode 100644 index 0000000..6a2b085 --- /dev/null +++ b/src/xquery-cmds/xqactions.ts @@ -0,0 +1,60 @@ + +/** To demonstrate code actions associated with Diagnostics problems */ +import * as vscode from 'vscode'; + +import { channel, unsupportedScheme } from "../common"; +/** Code that is used to associate diagnostic entries with code actions. */ +export const XQ_ACTION = 'xq_action'; + +export function activate(context: vscode.ExtensionContext,actionDiagnostics:vscode.DiagnosticCollection) { + channel.log("Actions activate"); + subscribeToDocumentChanges(context,actionDiagnostics); +} + +/** + * Analyzes the text document for problems. + * if empty do action + * @param doc text document to analyze + * @param actionDiagnostics diagnostic collection + */ +function refreshDiagnostics(doc: vscode.TextDocument, actionDiagnostics: vscode.DiagnosticCollection): void { + let diagnostics: vscode.Diagnostic[] ; + if(!doc || unsupportedScheme(doc.uri)) return; + channel.log("action refresh: "+doc.uri.toString()); + if (doc.getText() === "") { + diagnostics.push(emptyText()); + } + actionDiagnostics.set(doc.uri,diagnostics); +} + +// create hint +function emptyText():vscode.Diagnostic { + // create range that represents, where in the document the word is + const range = new vscode.Range(0, 0, 0, 0); + const diagnostic = new vscode.Diagnostic(range, "Run template?", + vscode.DiagnosticSeverity.Information); + diagnostic.code = XQ_ACTION; + return diagnostic +} + +function subscribeToDocumentChanges(context: vscode.ExtensionContext, actionDiagnostics: vscode.DiagnosticCollection): void { + if (vscode.window.activeTextEditor) { + refreshDiagnostics(vscode.window.activeTextEditor.document, actionDiagnostics); + } + context.subscriptions.push( + vscode.window.onDidChangeActiveTextEditor(editor => { + if (editor) { + refreshDiagnostics(editor.document, actionDiagnostics); + } + }) + ); + + context.subscriptions.push( + vscode.workspace.onDidChangeTextDocument(e => refreshDiagnostics(e.document, actionDiagnostics)) + ); + + context.subscriptions.push( + vscode.workspace.onDidCloseTextDocument(doc => actionDiagnostics.delete(doc.uri)) + ); + +} \ No newline at end of file diff --git a/src/xquery-cmds/xqcmds.ts b/src/xquery-cmds/xqcmds.ts index 5780277..8b25ce7 100644 --- a/src/xquery-cmds/xqcmds.ts +++ b/src/xquery-cmds/xqcmds.ts @@ -34,10 +34,13 @@ export function selectDeclaration(textEditor: TextEditor): void { } -// select enclosing declaration and trailing ; -export function xmlnsInfo(): void { +// about the library ; +export function libraryInfo(textEditor: TextEditor): void { + const linter = diagnosticCollectionXQuery.xqlint(textEditor.document.uri); console.log("todo"); + window.showInformationMessage("libraryInfo @todo") } + // return 1st ancestor node with name or undefined function findNode(node :any,nodeName :string):any{ let n2 = node; diff --git a/tsconfig.json b/tsconfig.json index e315149..f69cdbe 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -13,7 +13,7 @@ "strict": true, "strictNullChecks": false, "esModuleInterop": true, - "resolveJsonModule": true + "resolveJsonModule": true }, "exclude": [ From f2c4179ddb001748055dde6ed25e5d784954f73d Mon Sep 17 00:00:00 2001 From: Andy Bunce Date: Mon, 23 Oct 2023 15:33:06 +0100 Subject: [PATCH 3/8] [fix] xsl handling --- package.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 45fbca3..06a4e15 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "vscode-basex", "displayName": "BaseX tools", "description": "BaseX tools: XQuery, XML, XPath Tools for Visual Studio Code", - "version": "0.1.18", + "version": "0.2.2", "preview": true, "publisher": "quodatum", "author": "Andy Bunce (https://github.com/Quodatum)", @@ -279,7 +279,7 @@ ".csproj", ".xml", ".xsd", - ".xsl", + ".plist", ".mobileconfig", ".sch" @@ -402,7 +402,7 @@ "typescript": "^4.7.3" }, "dependencies": { - "@quodatum/xqlint": "^0.3.3", + "@quodatum/xqlint": "^0.4.5", "@xmldom/xmldom": "^0.8.10", "bl": "^6.0.4", "xpath": "^0.0.33" From fd8ade8df92b0d70c869594acd8acf3257adf48f Mon Sep 17 00:00:00 2001 From: Andy Bunce Date: Tue, 31 Oct 2023 16:18:21 +0000 Subject: [PATCH 4/8] [mod] statusbar improvements --- CHANGELOG.md | 13 +- docs/xquery/xquery-code-completion.md | 17 ++- docs/xquery/xquery-errors.md | 2 +- docs/xquery/xquery-script-execution.md | 2 +- package-lock.json | 151 ++++++++++--------- package.json | 2 +- snippets.jsonc | 94 ++++++++---- src/common/channel-basex.ts | 2 + src/common/document-selectors.ts | 7 +- src/common/document.ts | 15 +- src/common/index.ts | 8 +- src/common/xqlint.ts | 61 +++++++- src/extension.ts | 26 ++-- src/formatting/commands/xmlToText.ts | 5 +- src/linting/report.ts | 1 - src/providers/activate.ts | 4 +- src/providers/codeaction.ts | 34 +++-- src/providers/completion.ts | 53 ++++--- src/providers/definition.ts | 84 +++++++++++ src/providers/documentlink.ts | 11 +- src/providers/hover.ts | 31 ++-- src/statusbar.ts | 38 +++++ src/test/test-data/issue-257.unformatted.xml | 2 +- src/test/test-xquery/ast-to-xqdoc.xqm | 2 +- src/xpath/commands/getCurrentXPath.ts | 1 - src/xqdiagEvents.ts | 13 +- src/{xqdiagnostics.ts => xqlints.ts} | 38 ++--- src/xquery-cmds/xqcmds.ts | 32 ++-- 28 files changed, 496 insertions(+), 253 deletions(-) create mode 100644 src/providers/definition.ts create mode 100644 src/statusbar.ts rename src/{xqdiagnostics.ts => xqlints.ts} (87%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d8d5f2..bb2756a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,17 @@ +# 0.2.4 (2023-10-28) +* Improve autocomplete +* Improve builtin snippets +* add statusbar +# 0.2.3 (2023-10-23) +* xsl extension conflict #18 +* Use xqlint 0.4.5 +# 0.1.19 (2023-10-06) +* Use xqlint 0.4.1 # 0.1.18 (2023-09-21) -* error decorator +* parseError decorator * empty codeaction hint # 0.1.16 (2023-09-10) -* virtual docs updates +* virtual docs fixes * add command basexTools.xqLibrary # 0.1.15 (2023-09-09) * Add commands: set processor and selectDeclaration. diff --git a/docs/xquery/xquery-code-completion.md b/docs/xquery/xquery-code-completion.md index 8641406..b7f41d0 100644 --- a/docs/xquery/xquery-code-completion.md +++ b/docs/xquery/xquery-code-completion.md @@ -6,6 +6,21 @@ authors: date: 2023-07-05 tags: - XQuery + - completion --- -`Ctl-space` triggered +## Usage +Code completion suggestions can be triggered by `Ctl-space` ![completion](xquery-code-completion.gif) + +## Details +There are several types of completion. The context position is used to determine which to run. +### Type completions +If the previous token was `as` then type completions are displayed. Examples include: +* `let $a as `| +* `declare variable $a as `| +* `declare function local:f( $a as `| +* `declare function local:f( $a as item()) as `| + +### Import completions +### Expression completions + diff --git a/docs/xquery/xquery-errors.md b/docs/xquery/xquery-errors.md index 0612338..07e5379 100644 --- a/docs/xquery/xquery-errors.md +++ b/docs/xquery/xquery-errors.md @@ -5,4 +5,4 @@ authors: - Andy Bunce date: 2023-09-11 --- -TODO +TODO A LIST diff --git a/docs/xquery/xquery-script-execution.md b/docs/xquery/xquery-script-execution.md index a20af25..72ac085 100644 --- a/docs/xquery/xquery-script-execution.md +++ b/docs/xquery/xquery-script-execution.md @@ -9,4 +9,4 @@ date: 2023-07-05 ![doclink](xquery-execution.gif) !!! note Currently starts new basex instance and passes file path to it. - See [vscode-xquery-notebook](https://github.com/Quodatum/vscode-xquery-notebook) for an experimental execution using the basex client and notebook features. \ No newline at end of file + [vscode-xquery-noteook](https://github.com/Quodatum/vscode-xquery-notebook) is an experimental execution using the basex client and notebook features. \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index d4eb459..b27f671 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,15 @@ { "name": "vscode-basex", - "version": "0.1.14", + "version": "0.2.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "vscode-basex", - "version": "0.1.14", + "version": "0.2.4", "license": "MIT", "dependencies": { - "@quodatum/xqlint": "^0.3.3", + "@quodatum/xqlint": "^0.4.5", "@xmldom/xmldom": "^0.8.10", "bl": "^6.0.4", "xpath": "^0.0.33" @@ -411,9 +411,9 @@ } }, "node_modules/@eslint-community/regexpp": { - "version": "4.8.0", - "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.8.0.tgz", - "integrity": "sha512-JylOEEzDiOryeUnFbQz+oViCXS0KsvR1mvHkoMiu5+UiBvy+RYX7tzlIIIEstF/gVa2tj9AQXk3dgnxv6KxhFg==", + "version": "4.10.0", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.10.0.tgz", + "integrity": "sha512-Cu96Sd2By9mCNTx2iyKOmq10v22jUVQv0lQnlGNy16oE9589yE+QADPbrMGCkA51cKZSg3Pu/aTJVTGfL/qjUA==", "dev": true, "engines": { "node": "^12.0.0 || ^14.0.0 || >=16.0.0" @@ -443,21 +443,21 @@ } }, "node_modules/@eslint/js": { - "version": "8.48.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.48.0.tgz", - "integrity": "sha512-ZSjtmelB7IJfWD2Fvb7+Z+ChTIKWq6kjda95fLcQKNS5aheVHn4IkfgRQE3sIIzTcSLwLcLZUD9UBt+V7+h+Pw==", + "version": "8.52.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.52.0.tgz", + "integrity": "sha512-mjZVbpaeMZludF2fsWLD0Z9gCref1Tk4i9+wddjRvpUNqqcndPkBD09N/Mapey0b3jaXbLm2kICwFv2E64QinA==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" } }, "node_modules/@humanwhocodes/config-array": { - "version": "0.11.10", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.10.tgz", - "integrity": "sha512-KVVjQmNUepDVGXNuoRRdmmEjruj0KfiGSbS8LVc12LMsWDQzRXJ0qdhN8L8uUigKpfEHRhlaQFY0ib1tnUbNeQ==", + "version": "0.11.13", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.13.tgz", + "integrity": "sha512-JSBDMiDKSzQVngfRjOdFXgFfklaXI4K9nLF49Auh21lmBWRLIK3+xTErTWD4KU54pb6coM6ESE7Awz/FNU3zgQ==", "dev": true, "dependencies": { - "@humanwhocodes/object-schema": "^1.2.1", + "@humanwhocodes/object-schema": "^2.0.1", "debug": "^4.1.1", "minimatch": "^3.0.5" }, @@ -479,9 +479,9 @@ } }, "node_modules/@humanwhocodes/object-schema": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-1.2.1.tgz", - "integrity": "sha512-ZnQMnLV4e7hDlUvw8H+U8ASL02SS2Gn6+9Ac3wGGLIe7+je2AeAOxPY+izIPJDfFDb7eDjev0Us8MO1iFRN8hA==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/object-schema/-/object-schema-2.0.1.tgz", + "integrity": "sha512-dvuCeX5fC9dXgJn9t+X5atfmgQAzUOWqS1254Gh0m6i8wKd10ebXkfNKiRK+1GWi/yTvvLDHpoxLr0xxxeslWw==", "dev": true }, "node_modules/@nodelib/fs.scandir": { @@ -520,21 +520,21 @@ } }, "node_modules/@quodatum/xq-catalogs": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/@quodatum/xq-catalogs/-/xq-catalogs-0.0.6.tgz", - "integrity": "sha512-R+An3pbaB33BT5au0YSjWD0IbKXGYPawzDv4aJol8TZUusKQPR3mmwl/ScGpReVaY8P3Kk3cb6ILidbUV6UVNg==", + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/@quodatum/xq-catalogs/-/xq-catalogs-0.1.1.tgz", + "integrity": "sha512-21HLvmxq0lbtAW30V6a88Fffl8X4WWWTNhG9ascEdjzDVnRp7WnxAd0E7jbF4GH54a2ens3oC244JIHgi0UO6A==", "engines": { "node": ">=18.1.1" } }, "node_modules/@quodatum/xqlint": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/@quodatum/xqlint/-/xqlint-0.3.3.tgz", - "integrity": "sha512-u1LCTv3wIBGTg8hp3U2xvpSm38RRPIOYMKip/xKEfK/Hu/G0KIntPq824IpbBpoRvhAsgcATEyFEDMDk7iByrA==", + "version": "0.4.5", + "resolved": "https://registry.npmjs.org/@quodatum/xqlint/-/xqlint-0.4.5.tgz", + "integrity": "sha512-dD2X4lFXJUoDwBUgopGPjGePWy2lkmBRnJ2T4lVGegZL9A4H8uzFrnPGPgG/XbZ6reNDQf/u676Z8i0aA/n54Q==", "dependencies": { - "@quodatum/xq-catalogs": "^0.0.6", + "@quodatum/xq-catalogs": "0.1.1", "colors": "1.4.0", - "commander": "~11.0.0", + "commander": "~11.1.0", "final-fs": "~1.6.1" }, "bin": { @@ -564,9 +564,9 @@ } }, "node_modules/@types/json-schema": { - "version": "7.0.12", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.12.tgz", - "integrity": "sha512-Hr5Jfhc9eYOQNPYO5WLDq/n4jqijdHNlDXjuAQkkt+mWdQR+XJToOHrsD4cPaMXpn6KO7y2+wM8AZEs8VpBLVA==", + "version": "7.0.14", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.14.tgz", + "integrity": "sha512-U3PUjAudAdJBeC2pgN8uTIKgxrb4nlDF3SF0++EldXQvQBGkpFZMSnwQiIoDU77tv45VgNkl/L4ouD+rEomujw==", "dev": true }, "node_modules/@types/minimatch": { @@ -576,15 +576,15 @@ "dev": true }, "node_modules/@types/mocha": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.1.tgz", - "integrity": "sha512-/fvYntiO1GeICvqbQ3doGDIP97vWmvFt83GKguJ6prmQM2iXZfFcq6YE8KteFyRtX2/h5Hf91BYvPodJKFYv5Q==", + "version": "10.0.3", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.3.tgz", + "integrity": "sha512-RsOPImTriV/OE4A9qKjMtk2MnXiuLLbcO3nCXK+kvq4nr0iMfFgpjaX3MPLb6f7+EL1FGSelYvuJMV6REH+ZPQ==", "dev": true }, "node_modules/@types/node": { - "version": "14.18.56", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.56.tgz", - "integrity": "sha512-+k+57NVS9opgrEn5l9c0gvD1r6C+PtyhVE4BTnMMRwiEA8ZO8uFcs6Yy2sXIy0eC95ZurBtRSvhZiHXBysbl6w==", + "version": "14.18.63", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz", + "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==", "dev": true }, "node_modules/@types/readable-stream": { @@ -598,21 +598,21 @@ } }, "node_modules/@types/semver": { - "version": "7.5.1", - "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.1.tgz", - "integrity": "sha512-cJRQXpObxfNKkFAZbJl2yjWtJCqELQIdShsogr1d2MilP8dKD9TE/nEKHkJgUNHdGKCQaf9HbIynuV2csLGVLg==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-MMzuxN3GdFwskAnb6fz0orFvhfqi752yjaXylr0Rp4oDg5H0Zn1IuyRhDVvYOwAXoJirx2xuS16I3WjxnAIHiQ==", "dev": true }, "node_modules/@types/vscode": { - "version": "1.81.0", - "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.81.0.tgz", - "integrity": "sha512-YIaCwpT+O2E7WOMq0eCgBEABE++SX3Yl/O02GoMIF2DO3qAtvw7m6BXFYsxnc6XyzwZgh6/s/UG78LSSombl2w==", + "version": "1.83.1", + "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.83.1.tgz", + "integrity": "sha512-BHu51NaNKOtDf3BOonY3sKFFmZKEpRkzqkZVpSYxowLbs5JqjOQemYFob7Gs5rpxE5tiGhfpnMpcdF/oKrLg4w==", "dev": true }, "node_modules/@types/xmldom": { - "version": "0.1.31", - "resolved": "https://registry.npmjs.org/@types/xmldom/-/xmldom-0.1.31.tgz", - "integrity": "sha512-bVy7s0nvaR5D1mT1a8ZkByHWNOGb6Vn4yi5TWhEdmyKlAG+08SA7Md6+jH+tYmMLueAwNeWvHHpeKrr6S4c4BA==", + "version": "0.1.33", + "resolved": "https://registry.npmjs.org/@types/xmldom/-/xmldom-0.1.33.tgz", + "integrity": "sha512-4PH3jqYT1EK0t+bDCZl7wW2A2yM25RapZqJ8/IaFcgr0y+aOiL4QKSrEIBItBzAKlF7nG8b6FPBMi/vTzIURjw==", "dev": true }, "node_modules/@typescript-eslint/eslint-plugin": { @@ -809,10 +809,16 @@ "integrity": "sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q==", "dev": true }, + "node_modules/@ungap/structured-clone": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.2.0.tgz", + "integrity": "sha512-zuVdFrMJiuCDQUMCzQaD6KL28MjnqqN8XnAqiEq9PNm/hCPTSGfrXCOfwj1ow4LFb/tNymJPwsNbVePc1xFqrQ==", + "dev": true + }, "node_modules/@vscode/test-electron": { - "version": "2.3.4", - "resolved": "https://registry.npmjs.org/@vscode/test-electron/-/test-electron-2.3.4.tgz", - "integrity": "sha512-eWzIqXMhvlcoXfEFNWrVu/yYT5w6De+WZXR/bafUQhAp8+8GkQo95Oe14phwiRUPv8L+geAKl/QM2+PoT3YW3g==", + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/@vscode/test-electron/-/test-electron-2.3.6.tgz", + "integrity": "sha512-M31xGH0RgqNU6CZ4/9g39oUMJ99nLzfjA+4UbtIQ6TcXQ6+2qkjOOxedmPBDDCg26/3Al5ubjY80hIoaMwKYSw==", "dev": true, "dependencies": { "http-proxy-agent": "^4.0.1", @@ -844,9 +850,9 @@ } }, "node_modules/acorn": { - "version": "8.10.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.10.0.tgz", - "integrity": "sha512-F0SAmZ8iUtS//m8DmCTA0jlh6TDKkHQyK6xc6V4KDTyZKA9dnvX9/3sRTVQrWm79glUAZbnmmNcdYwUIHWVybw==", + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz", + "integrity": "sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w==", "dev": true, "bin": { "acorn": "bin/acorn" @@ -988,9 +994,9 @@ } }, "node_modules/bl": { - "version": "6.0.7", - "resolved": "https://registry.npmjs.org/bl/-/bl-6.0.7.tgz", - "integrity": "sha512-9FNh0IvlWSU5C9BCDhw0IovmhuqevzBX1AME7BdFHNDMfOju4NmwRWoBrfz5Srs+JNBhxfjrPLxZSnDotgSs9A==", + "version": "6.0.8", + "resolved": "https://registry.npmjs.org/bl/-/bl-6.0.8.tgz", + "integrity": "sha512-HCRq8z0+3vrGCjEKrbnK6blpDZ1xzhfZKCCuyvPC7upGcfXZSmaCumpVao/jC8o1hs/fOqJoCSPMabl+CQTPXg==", "dependencies": { "buffer": "^6.0.3", "inherits": "^2.0.4", @@ -1162,9 +1168,9 @@ } }, "node_modules/commander": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-11.0.0.tgz", - "integrity": "sha512-9HMlXtt/BNoYr8ooyjjNRdIilOTkVJXB+GhxMTtOKwk0R4j4lS4NpjuqmRxroBfnfTSHQIHQB7wryHhXarNjmQ==", + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz", + "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==", "engines": { "node": ">=16" } @@ -1328,18 +1334,19 @@ } }, "node_modules/eslint": { - "version": "8.48.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.48.0.tgz", - "integrity": "sha512-sb6DLeIuRXxeM1YljSe1KEx9/YYeZFQWcV8Rq9HfigmdDEugjLEVEa1ozDjL6YDjBpQHPJxJzze+alxi4T3OLg==", + "version": "8.52.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.52.0.tgz", + "integrity": "sha512-zh/JHnaixqHZsolRB/w9/02akBk9EPrOs9JwcTP2ek7yL5bVvXuRariiaAjjoJ5DvuwQ1WAE/HsMz+w17YgBCg==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", "@eslint/eslintrc": "^2.1.2", - "@eslint/js": "8.48.0", - "@humanwhocodes/config-array": "^0.11.10", + "@eslint/js": "8.52.0", + "@humanwhocodes/config-array": "^0.11.13", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", + "@ungap/structured-clone": "^1.2.0", "ajv": "^6.12.4", "chalk": "^4.0.0", "cross-spawn": "^7.0.2", @@ -1638,12 +1645,12 @@ } }, "node_modules/flat-cache": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.1.0.tgz", - "integrity": "sha512-OHx4Qwrrt0E4jEIcI5/Xb+f+QmJYNj2rrK8wiIdQOIrB9WrrJL8cjZvXdXuBTkkEwEqLycb5BeZDV1o2i9bTew==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.1.1.tgz", + "integrity": "sha512-/qM2b3LUIaIgviBQovTLvijfyOQXPtSRnRK26ksj2J7rzPIecePUIpJsZ4T02Qg+xiAEKIs5K8dsHEd+VaKa/Q==", "dev": true, "dependencies": { - "flatted": "^3.2.7", + "flatted": "^3.2.9", "keyv": "^4.5.3", "rimraf": "^3.0.2" }, @@ -1652,9 +1659,9 @@ } }, "node_modules/flatted": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.7.tgz", - "integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==", + "version": "3.2.9", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.2.9.tgz", + "integrity": "sha512-36yxDn5H7OFZQla0/jFJmbIKTdZAQHngCedGxiMmpNfEZM0sdEeT+WczLQrjK6D7o2aiyLYDnkw0R3JK0Qv1RQ==", "dev": true }, "node_modules/fs.realpath": { @@ -1719,9 +1726,9 @@ } }, "node_modules/globals": { - "version": "13.21.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.21.0.tgz", - "integrity": "sha512-ybyme3s4yy/t/3s35bewwXKOf7cvzfreG2lH0lZl0JB7I4GxRP2ghxOK/Nb9EkRXdbBXZLfq/p/0W2JUONB/Gg==", + "version": "13.23.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.23.0.tgz", + "integrity": "sha512-XAmF0RjlrjY23MA51q3HltdlGxUpXPvg0GioKiD9X6HD28iMjo2dKC8Vqwm7lne4GNr78+RHTfliktR6ZH09wA==", "dev": true, "dependencies": { "type-fest": "^0.20.2" @@ -2047,9 +2054,9 @@ } }, "node_modules/keyv": { - "version": "4.5.3", - "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.3.tgz", - "integrity": "sha512-QCiSav9WaX1PgETJ+SpNnx2PRRapJ/oRSXM4VO5OGYGSjrxbKPVFVhB3l2OCbLCk329N8qyAtsJjSjvVBWzEug==", + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", "dev": true, "dependencies": { "json-buffer": "3.0.1" diff --git a/package.json b/package.json index 06a4e15..2665445 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "vscode-basex", "displayName": "BaseX tools", "description": "BaseX tools: XQuery, XML, XPath Tools for Visual Studio Code", - "version": "0.2.2", + "version": "0.2.4", "preview": true, "publisher": "quodatum", "author": "Andy Bunce (https://github.com/Quodatum)", diff --git a/snippets.jsonc b/snippets.jsonc index 48bae38..e12e220 100644 --- a/snippets.jsonc +++ b/snippets.jsonc @@ -1,21 +1,37 @@ { "new library module": { - "prefix": "xquery", + "isFileTemplate": true, + "prefix": "library module", "body": [ "xquery version '3.1';", "(:~", + "@author: ", + "@date: $CURRENT_YEAR/$CURRENT_MONTH/$CURRENT_DATE", ":)", - "module namespace ${1:ns} = '${2:http://www.example.com/}';", + "module namespace ${1:prefix} = '${2:http://www.example.com/}';", "" ], - "description": "Library template" + "description": "new library module template" }, - "for": { + "new main module": { + "isFileTemplate": true, + "prefix": "main module", + "body": [ + "xquery version '3.1';", + "(:~", + ":)", + "${1:expr}", + "" + ], + "description": "new main module template" + } + , + "for in": { "prefix": "for", - "body": "for $${1:item} in ${2:expr}" + "body": "for \\$${1:item} in ${2:expr}" }, "return": { - "prefix": "ret", + "prefix": "return", "body": "return ${1:expr}" }, "import": { @@ -23,22 +39,31 @@ "body": "import module namespace ${1:ns} = '${2:http://www.example.com/}';", "description": "Import module" }, + "if":{ + "prefix": "if", + "body":[ + "if (${1:boolean})", + "then ${2:expr1}", + "else ${3:expr2}" + ], + "description": "If then else expression" + }, "module": { "prefix": "module", "body": "module namespace ${1:ns} = '${2:http://www.example.com}';" }, "every": { "prefix": "every", - "body": "every $${1:varname} in ${2:expr} satisfies ${3:expr}" + "body": "every \\$${1:varname} in ${2:expr} satisfies ${3:expr}" }, "some": { "prefix": "some", - "body": "some $${1:varname} in ${2:expr} satisfies ${3:expr}" + "body": "some \\$${1:varname} in ${2:expr} satisfies ${3:expr}" }, - "function": { - "prefix": "dec", + "declare function": { + "prefix": ["declare","function"], "body": [ - "(:~ $${2:name} :)", + "(:~ ${2:name} :)", "declare function ${1:ns}:${2:name}(){", "${3:expr}", "};" @@ -46,16 +71,16 @@ "description": "declare function" }, "declare variable": { - "prefix": "dec", + "prefix": ["declare","variable"], "body": [ - "(:~ $${1:varname} :)", - "declare variable $${1:varname} := ${2:expr};", + "(:~ \\$${1:varname} :)", + "declare variable \\$${1:varname} := ${2:expr};", "" ], "description": "declare variable" }, "switch": { - "prefix": "sw", + "prefix": "switch", "body": [ "switch(${1:foo})", "case ${2:foo} return ${3:true}", @@ -75,37 +100,42 @@ "try": { "prefix": "try", "body": [ - "try { ${1:expr} } ", - "catch ${2:*} { ${3:expr} }" + "try {", + " ${1:expr}", + "} catch ${2:*}", + " { ${3:expr}", + "}" ], - "description": "switch statement" + "description": "try catch" }, "tumbling": { - "prefix": "tumbling", + "prefix": ["for","tumbling","window"], "body": [ - "for tumbling window $${1:varname} in ${2:expr}", - "start at $${3:start} when ${4:expr}", - "end at $${5:end} when ${6:expr}", + "for tumbling window \\$${1:varname} in ${2:expr}", + "start at \\$${3:start} when ${4:expr}", + "end at \\$${5:end} when ${6:expr}", "return ${7:expr}" ], "description": "tumbling window" }, "sliding": { - "prefix": "sliding", + "prefix": ["for","sliding","window"], "body": [ - "for sliding window $${1:varname} in ${2:expr}", - "start at $${3:start} when ${4:expr}", - "end at $${5:end} when ${6:expr}", + "for sliding window \\$${1:varname} in ${2:expr}", + "start at \\$${3:start} when ${4:expr}", + "end at \\$${5:end} when ${6:expr}", "return ${7:expr}" ], "description": "sliding window" - } + }, + + "let":{ + "prefix":"let", + "body": "let \\$${1:varname} := ${2:expr}" + } } -//snippet if -// if(${1:true}) then ${2:expr} else ${3:true} -// default return ${4:false} -//snippet let -// let $${1:varname} := ${2:expr} + + //snippet group // group by $${1:varname} := ${2:expr} //snippet order diff --git a/src/common/channel-basex.ts b/src/common/channel-basex.ts index eb78ad8..2f24646 100644 --- a/src/common/channel-basex.ts +++ b/src/common/channel-basex.ts @@ -1,5 +1,6 @@ // debug messages import { OutputChannel, window,Uri } from "vscode"; + // eslint-disable-next-line @typescript-eslint/no-var-requires const version = require('../../package.json'); // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -47,4 +48,5 @@ export class channel { } } channel.log(`Activate vscode-basex(${ version.version }) ***************** XQLint(${ verXQlint })`); +channel.log(`todo`); _channel.show \ No newline at end of file diff --git a/src/common/document-selectors.ts b/src/common/document-selectors.ts index e443d03..360121d 100644 --- a/src/common/document-selectors.ts +++ b/src/common/document-selectors.ts @@ -1,4 +1,4 @@ -import { DocumentFilter, Uri, TextDocument } from "vscode"; +import { DocumentFilter, Uri, TextDocument ,TextEditor} from "vscode"; import * as constants from "../constants"; @@ -8,6 +8,11 @@ export function createDocumentSelector(language: string): DocumentFilter[] { { language: language, scheme: constants.uriSchemes.untitled }, ]; } + +export function isXqEditor(editor: TextEditor):boolean{ + return editor && !isNotXQDoc(editor.document); +} +// must be an xq doc in supported scheme export function isNotXQDoc(doc: TextDocument): boolean { if (!doc || doc.languageId !== constants.languageIds.xquery) return true; return unsupportedScheme(doc.uri) diff --git a/src/common/document.ts b/src/common/document.ts index 269d803..9ab6ffb 100644 --- a/src/common/document.ts +++ b/src/common/document.ts @@ -1,9 +1,16 @@ -import { TextDocument,Range} from 'vscode'; +import { TextDocument, TextEditor, Range, window } from 'vscode'; -export function fullRange(document:TextDocument) { +/* Total range for document */ +export function fullRange(document: TextDocument): Range { const lastLine = document.lineAt(document.lineCount - 1); return new Range(document.positionAt(0), lastLine.range.end); } -export function isEmpty(document:TextDocument) :boolean{ - return (document.lineCount ===1) && document.lineAt(document.lineCount - 1).isEmptyOrWhitespace +/* true if empty */ +export function isEmpty(document: TextDocument): boolean { + return (document.lineCount === 1) && document.lineAt(document.lineCount - 1).isEmptyOrWhitespace } + +/* 1st editor for document */ +export function findEditor(doc: TextDocument): TextEditor | undefined { + return window.visibleTextEditors.find(editor => editor.document === doc) +} \ No newline at end of file diff --git a/src/common/index.ts b/src/common/index.ts index ac67251..c85c77e 100644 --- a/src/common/index.ts +++ b/src/common/index.ts @@ -1,8 +1,10 @@ export * from "./configuration"; -export * from "./xqlint"; +export * from "./channel-basex"; +export * from "./document"; export * from "./document-selectors"; export * from "./extension-state"; export * from "./native-commands"; +export * from "./workspace"; export * from "./xml-traverser"; -export * from "./channel-basex"; -export * from "./document"; +export * from "./xqlint"; + diff --git a/src/common/xqlint.ts b/src/common/xqlint.ts index 11d0c5e..b63c4f9 100644 --- a/src/common/xqlint.ts +++ b/src/common/xqlint.ts @@ -1,8 +1,57 @@ -import { LintRange } from "@quodatum/xqlint"; -import { Range } from "vscode"; +import { Ast, LintRange, XQLint } from "@quodatum/xqlint"; +import { Position, Range } from "vscode"; + export function importRange(lintRange?: LintRange): Range { - return lintRange? - new Range(lintRange.sl, lintRange.sc, lintRange.el, lintRange.ec) - :new Range(0,0,0,0); - } \ No newline at end of file + return lintRange ? + new Range(lintRange.sl, lintRange.sc, lintRange.el, lintRange.ec) + : new Range(0, 0, 0, 0); +} +// return 1st ancestor node with name or undefined +export function findNode(node: Ast, nodeName: string): Ast | undefined { + let n2 = node; + while (n2 !== null) { + if (n2.name === nodeName) return n2; + n2 = n2.getParent; + } +} +// array of AST node names upto root +export function astPath(node: Ast): string[] { + const path: string[] = []; + let n = node; + while (n != null) { + path.push(n.name); + n = n.getParent; + } + return path; +} + + +// metadata about given AST node {type:,path:} +export function inspectAst(linter: XQLint, position: Position) { + const node = linter.getAST(position); + const path = astPath(node); + const r = { + path: path, + type: 'other', + name: node.name, + value: node.value + }; + if (node.name === 'WS') { + r.type = 'WS'; + } else { + const ps = path.join("/"); + if (ps.startsWith("EQName/FunctionEQName/FunctionCall/")) { + r.type = "FunctionCall"; + //@todo arity + } else if (ps.startsWith("EQName/VarName/VarRef")) { + r.type = "VarRef"; + r.value = '$' + r.value; + } else if (path.includes("SequenceType")) { + r.type = "SequenceType"; + } else if (path.includes("Annotation")) { + r.type = "Annotation"; + } + } + return r; +} \ No newline at end of file diff --git a/src/extension.ts b/src/extension.ts index 4da40d4..3ef355f 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -4,8 +4,8 @@ import { } from "vscode"; import { channel, createDocumentSelector, ExtensionState, Configuration } from "./common"; - -import { XQueryDiagnostics, subscribeToDocumentChanges } from "./xqdiagnostics" +import { activate as statusbar } from "./statusbar"; +import { XQLinter, subscribeToDocumentChanges } from "./xqlints" //import { activate as activateActions} from "./xquery-cmds/xqactions"; import { XmlFormatterFactory, XmlFormattingEditProvider } from "./formatting"; import { formatAsXml, minifyXml, xmlToText, textToXml } from "./formatting/commands"; @@ -19,23 +19,24 @@ import * as constants from "./constants"; import * as providers from "./providers/activate"; -export const diagnosticCollectionXQuery=new XQueryDiagnostics(); +export const diagnosticCollectionXQuery=new XQLinter(); //const actionDiagnostics = languages.createDiagnosticCollection(constants.diagnosticCollections.xqActions); export function activate(context: ExtensionContext) { channel.log("Extension activate"); ExtensionState.configure(context); - - /* Linting Features */ - subscribeToDocumentChanges(context, diagnosticCollectionXQuery); + statusbar(context,diagnosticCollectionXQuery); //activateActions(context,actionDiagnostics); /* activate XQuery handlers */ - providers.activate(context,diagnosticCollectionXQuery); - + providers.activate(context,diagnosticCollectionXQuery); activateVirtualDocs(context); + /* Linting Features */ + subscribeToDocumentChanges(context, diagnosticCollectionXQuery); /* XML Formatting Features */ - const xmlXsdDocSelector = [...createDocumentSelector(constants.languageIds.xml), ...createDocumentSelector(constants.languageIds.xsd)]; + const xmlXsdDocSelector = [ + ...createDocumentSelector(constants.languageIds.xml), + ...createDocumentSelector(constants.languageIds.xsd)]; const xmlFormattingEditProvider = new XmlFormattingEditProvider(XmlFormatterFactory.getXmlFormatter()); context.subscriptions.push( commands.registerTextEditorCommand(constants.commands.formatAsXml, formatAsXml), @@ -83,18 +84,13 @@ export function activate(context: ExtensionContext) { // if changes to processor then clear diagnostics workspace.onDidChangeConfiguration(event => { - if (event.affectsConfiguration("basexTools.xquery.processor")) { + if (event.affectsConfiguration(constants.commands.xqProcessor)) { diagnosticCollectionXQuery.clear(); window.showInformationMessage("Processor now: " + Configuration.xqueryProcessor); } }) - window.showInformationMessage("XQuery processor: " + Configuration.xqueryProcessor); } export function deactivate() { channel.log("deactivate"); } - - - - diff --git a/src/formatting/commands/xmlToText.ts b/src/formatting/commands/xmlToText.ts index 2551c7c..fb29674 100644 --- a/src/formatting/commands/xmlToText.ts +++ b/src/formatting/commands/xmlToText.ts @@ -39,11 +39,10 @@ export function textToXml(textEditor: TextEditor): void { const transformed = txt .replace(/</g, "<") .replace(/>/g, ">") - .replace(/&/g, "&") // tslint:disable-next-line .replace(/"/g, '"') - .replace(/'/g, "'"); - + .replace(/'/g, "'") + .replace(/&/g, "&"); textEdit.replace(selection, transformed); }); }); diff --git a/src/linting/report.ts b/src/linting/report.ts index 0127f77..ace4052 100644 --- a/src/linting/report.ts +++ b/src/linting/report.ts @@ -89,7 +89,6 @@ export function xqLintReport(textEditor: vscode.TextEditor): void { selections.forEach(selection => { const pos = selection.start.translate(1, 1); //@TODO const node = linter.getAST(pos); - const sctx = linter.getCompletions(pos); const dx = dump(node); channel.appendLine(dx); }); diff --git a/src/providers/activate.ts b/src/providers/activate.ts index 89ed384..2978588 100644 --- a/src/providers/activate.ts +++ b/src/providers/activate.ts @@ -1,5 +1,5 @@ import { ExtensionContext} from "vscode"; -import {XQueryDiagnostics} from "../xqdiagnostics"; +import {XQLinter} from "../xqlints"; import * as formatter from "./formatting"; import * as symbols from './symbols'; import * as hover from './hover'; @@ -7,7 +7,7 @@ import * as codeAction from './codeaction'; import * as completion from './completion'; import * as documentLink from './documentlink'; -export function activate(context: ExtensionContext,diagnosticCollectionXQuery:XQueryDiagnostics) { +export function activate(context: ExtensionContext,diagnosticCollectionXQuery:XQLinter) { symbols.activate(context); hover.activate(context); codeAction.activate(context,diagnosticCollectionXQuery); diff --git a/src/providers/codeaction.ts b/src/providers/codeaction.ts index d41f8c5..dffa501 100644 --- a/src/providers/codeaction.ts +++ b/src/providers/codeaction.ts @@ -3,22 +3,32 @@ *--------------------------------------------------------*/ import * as vscode from 'vscode'; -import { subscribeToDocumentChanges, XQ_ACTION } from './codeactions-diagnostics'; +import { XQ_ACTION } from './codeactions-diagnostics'; import { languageIds } from "../constants"; -import { XQueryDiagnostics } from "../xqdiagnostics"; +import { XQLinter } from "../xqlints"; import { isEmpty } from '../common' import { IXQParsedEvent } from '../xqdiagEvents'; -const COMMAND = 'code-actions-sample.command'; +const COMMAND = 'code-actions-basex.command'; -export function activate(context: vscode.ExtensionContext, diagnosticCollectionXQuery: XQueryDiagnostics) { +export function activate(context: vscode.ExtensionContext, diagnosticCollectionXQuery: XQLinter) { context.subscriptions.push( - vscode.languages.registerCodeActionsProvider(languageIds.xquery, new XQAction(), { - providedCodeActionKinds: XQAction.providedCodeActionKinds + vscode.languages.registerCodeActionsProvider(languageIds.xquery, new XQActionProvider(), { + providedCodeActionKinds: XQActionProvider.providedCodeActionKinds })); const xqActionsDiagnostics = vscode.languages.createDiagnosticCollection("xq-actions"); + context.subscriptions.push(xqActionsDiagnostics); - diagnosticCollectionXQuery.onDidDiag(update); + const update=function(event: IXQParsedEvent) { + if (event.xqlint) { + console.log("Parsed: " + event.uri.toString()); + xqActionsDiagnostics + } else { + console.log("Dropped: " + event.uri.toString()); + } + + }; + diagnosticCollectionXQuery.onXQParsed(update); //subscribeToDocumentChanges(context, xqActionsDiagnostics); context.subscriptions.push( @@ -31,17 +41,11 @@ export function activate(context: vscode.ExtensionContext, diagnosticCollectionX vscode.commands.registerCommand(COMMAND, () => vscode.env.openExternal(vscode.Uri.parse('https://unicode.org/emoji/charts-12.0/full-emoji-list.html'))) ); } -function update(event: IXQParsedEvent) { - if (event.xqlint) { - console.log("Parsed: " + event.uri.toJSON()) - } else { - console.log("Dropped: "+event.uri.toString()) - } -} + /** * Provides code actions for converting :) to a smiley emoji. */ -export class XQAction implements vscode.CodeActionProvider { +export class XQActionProvider implements vscode.CodeActionProvider { public static readonly providedCodeActionKinds = [ vscode.CodeActionKind.QuickFix diff --git a/src/providers/completion.ts b/src/providers/completion.ts index 5c5f981..da77ac3 100644 --- a/src/providers/completion.ts +++ b/src/providers/completion.ts @@ -1,31 +1,36 @@ import { - CompletionItem, CompletionItemKind, CompletionItemProvider, - Position, TextDocument, ExtensionContext, languages + CompletionItem, CompletionItemKind, CompletionItemProvider,CompletionContext, + Position, TextDocument, ExtensionContext, languages, CompletionList,CancellationToken } from "vscode"; import { languageIds } from "../constants"; +import { createDocumentSelector } from '../common'; import { diagnosticCollectionXQuery } from "../extension"; +import { XQLintCompletion as XQLintCompletionItem} from '@quodatum/xqlint'; export function activate(context: ExtensionContext) { - context.subscriptions.push(languages.registerCompletionItemProvider( - { language: languageIds.xquery }, new XQueryCompletionItemProvider() - )); -} - -class XQueryCompletionItemProvider implements CompletionItemProvider { + const obj={ + provideCompletionItems: async (document: TextDocument, position: Position, + token: CancellationToken, context: CompletionContext) + : Promise => { + const linter = diagnosticCollectionXQuery.xqlint(document.uri); - provideCompletionItems(document: TextDocument, position: Position): CompletionItem[] { - const completionItems = new Array(); - const linter = diagnosticCollectionXQuery.xqlint(document.uri); + const completionItems = new Array(); + linter.getCompletions(position).forEach((x: XQLintCompletionItem) => { + completionItems.push(_getCompletionItem(x)); + }); - linter.getCompletions(position).forEach((x: any) => { - completionItems.push(this._getCompletionItem(x)); - }); + const res = new CompletionList( completionItems,true); + return res; + } + }; - return completionItems; - } + context.subscriptions.push(languages.registerCompletionItemProvider( + createDocumentSelector(languageIds.xquery), obj + )); +} - private _getCompletionItem(xqLintCompletionItem: any): CompletionItem { +function _getCompletionItem(xqLintCompletionItem: XQLintCompletionItem): CompletionItem { const completionItem = new CompletionItem(xqLintCompletionItem.name); completionItem.insertText = xqLintCompletionItem.snippet; @@ -38,7 +43,8 @@ class XQueryCompletionItemProvider implements CompletionItemProvider { const funcStart = (xqLintCompletionItem.value.indexOf(":") + 1); // eslint-disable-next-line no-case-declarations const funcEnd = xqLintCompletionItem.value.indexOf("("); - + //completionItem.commitCharacters=["("]; + completionItem.documentation="Some documentation about "+ xqLintCompletionItem.value; completionItem.insertText = xqLintCompletionItem.value.substring(funcStart, funcEnd); break; @@ -49,8 +55,15 @@ class XQueryCompletionItemProvider implements CompletionItemProvider { case "Function parameter": completionItem.kind = CompletionItemKind.Variable; completionItem.insertText = xqLintCompletionItem.value.substring(1); + completionItem.detail="A " +xqLintCompletionItem.meta; break; - + case "prefix": + completionItem.kind = CompletionItemKind.Class; + completionItem.detail="A namespace prefix"; + break; + case "type": + completionItem.kind = CompletionItemKind.TypeParameter; + break; // everything else default: completionItem.kind = CompletionItemKind.Text; @@ -60,4 +73,4 @@ class XQueryCompletionItemProvider implements CompletionItemProvider { return completionItem; } -} + diff --git a/src/providers/definition.ts b/src/providers/definition.ts new file mode 100644 index 0000000..9d33c6d --- /dev/null +++ b/src/providers/definition.ts @@ -0,0 +1,84 @@ + +'use strict'; + +import vscode from 'vscode'; +import cp = require('child_process'); +import path = require('path'); + + +export class XQueryDefinitionProvider implements vscode.DefinitionProvider { + + private parseDefinitionLocation(output: string, filename: string): vscode.Definition { + + const items: vscode.Location[] = new Array(); + output.split(/\r?\n/) + .forEach(function (value, index, array) { + + if (value !== null && value !== "") { + + const values = value.split(/ +/); + + // Create 113 C:/Users/alefr/Downloads/SynEdit-2_0_8/SynEdit/Source/SynURIOpener.pas constructor Create(AOwner: TComponent); override; + const word = values.shift(); + const line = parseInt(values.shift()) - 1; + + // together again get the filename (which may contains spaces and the previous shift wouldn't work) + let filePath: string; + if (values[ 2 ].indexOf(word + '(') === 0) { + filePath = path.join(AbstractProvider.basePathForFilename(filename), values.shift()); + } else { + const rest: string = values.join(' '); + const idxProc: number = rest.search(/(class\s+)?\b(procedure|function|constructor|destructor)\b/gi); + filePath = rest.substr(0, idxProc - 1); + filePath = path.join(AbstractProvider.basePathForFilename(filename), filePath); + } + + const definition = new vscode.Location( + vscode.Uri.file(filePath), new vscode.Position(line, 0) + ); + + items.push(definition); + } + + }); + + return items; + } + + private definitionLocations(word: string, filename: string): Promise { + + return new Promise((resolve, reject) => { + + this.generateTagsIfNeeded(filename) + .then((value: boolean) => { + if (value) { + + cp.execFile('global', [ '-x', word ], { cwd: AbstractProvider.basePathForFilename(filename) }, (err, stdout, stderr) => { + try { + if (err && (err).code === 'ENOENT') { + console.log(vscode.l10n.t('The "global" command is not available. Make sure it is on PATH')); + } + if (err) return resolve(null); + const result = stdout.toString(); + // console.log(result); + const locs = this.parseDefinitionLocation(result, filename); + return resolve(locs); + } catch (e) { + reject(e); + } + }); + } else { + return resolve(null); + } + }); + }); + } + + public provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): vscode.Definition | Thenable { + const fileName: string = document.fileName; + const word = document.getText(document.getWordRangeAtPosition(position)).split(/\r?\n/)[0]; + return this.definitionLocations(word, fileName).then(locs => { + return locs; + }); + } +} \ No newline at end of file diff --git a/src/providers/documentlink.ts b/src/providers/documentlink.ts index f1921f8..5ebcc9a 100644 --- a/src/providers/documentlink.ts +++ b/src/providers/documentlink.ts @@ -26,14 +26,11 @@ class XQueryDocumentLinks implements DocumentLinkProvider { channel.start("Doclinks" , doc.uri); const linter = diagnosticCollectionXQuery.xqlint(doc.uri); const dlinks = linter.getDocLinks(); - const links: DocumentLink[] = []; - dlinks.forEach((d2:[DocLink])=>{ - const link:DocLink=d2[0] - const range=importRange(link.range ); - - const uri=Uri.joinPath(doc.uri,"../"+ link.uri); - links.push(new DocumentLink(range, uri)); + dlinks.forEach((dl)=>{ + const range=importRange(dl.pos ); + //const uri=Uri.joinPath(doc.uri,"../"+ dl.uri); + links.push(new DocumentLink(range, Uri.file(dl.path))); }); return links; }; diff --git a/src/providers/hover.ts b/src/providers/hover.ts index ee476a1..d0e282d 100644 --- a/src/providers/hover.ts +++ b/src/providers/hover.ts @@ -2,9 +2,11 @@ import * as vscode from "vscode"; -import { Configuration } from "../common"; +import { Configuration ,inspectAst } from "../common"; import { languageIds } from "../constants"; import { diagnosticCollectionXQuery } from "../extension"; +import { XQLint } from '@quodatum/xqlint'; + export function activate(context: vscode.ExtensionContext) { context.subscriptions.push(vscode.languages.registerHoverProvider( @@ -21,30 +23,19 @@ class XQueryHoverProvider implements vscode.HoverProvider { const range = document.getWordRangeAtPosition(position); if (!range) return null const word = document.getText(range); - const linter = diagnosticCollectionXQuery.xqlint(document.uri); - const sctx = linter.getSctx(position); - const node = linter.getAST(position); - if (node.name === 'WS') return null; - - let n2 = node; - const path = [node.name] - while (n2.getParent !== null) { - n2 = n2.getParent; - path.push(n2.name); - } - const ps=path.join('/'); - const isfuncall="EQName/FunctionEQName/FunctionCall/"; - const fc=ps.startsWith(isfuncall); + const linter = diagnosticCollectionXQuery.xqlint(document.uri); + const x=inspectAst(linter,position); + if (x.type==='WS') return null; const parsePath = new vscode.MarkdownString( - 'Path:'); - parsePath.appendText(ps); + 'Path:'); + parsePath.appendText(x.path.join("/")); parsePath.supportHtml = true; parsePath.isTrusted = true; return new vscode.Hover([ - `[${position.line},${position.character}] Type: ${node.name}, Word: ${word}`, - `value: ${node.value}, fc: ${fc}`, + `[${position.line},${position.character}] Type: ${x.name}, Word: ${word}`, + `value: ${x.value}, type: ${ x.type}`, parsePath ]); } -} \ No newline at end of file +} diff --git a/src/statusbar.ts b/src/statusbar.ts new file mode 100644 index 0000000..78ef049 --- /dev/null +++ b/src/statusbar.ts @@ -0,0 +1,38 @@ +// statusbar: show profile when xq active +import * as vscode from 'vscode'; +import { commands } from "./constants"; +import { isXqEditor,Configuration } from "./common"; +import { XQLinter } from './xqlints'; + +let myStatusBarItem: vscode.StatusBarItem; + +export function activate({ subscriptions }: vscode.ExtensionContext, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + diagnostics: XQLinter) { + // create a new status bar item that we can now manage + myStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100); + myStatusBarItem.command = commands.xqProcessor; + + subscriptions.push(myStatusBarItem); + const onDidActive = vscode.window.onDidChangeActiveTextEditor(updateStatusBarItem); + updateStatusBarItem(vscode.window.activeTextEditor); + // register some listener that make sure the status bar always up-to-date + subscriptions.push(onDidActive); + + vscode.workspace.onDidChangeConfiguration(event => { + if (event.affectsConfiguration(commands.xqProcessor)) { + updateStatusBarItem(vscode.window.activeTextEditor); + } + }) +} + +function updateStatusBarItem(active: vscode.TextEditor): void { + if (isXqEditor(active)) { + const profile = Configuration.xqueryProcessor; + myStatusBarItem.text = `$(package) ${profile}`; + myStatusBarItem.tooltip = "select active XQuery profile" + myStatusBarItem.show(); + } else { + myStatusBarItem.hide(); + } +} diff --git a/src/test/test-data/issue-257.unformatted.xml b/src/test/test-data/issue-257.unformatted.xml index 842df62..771154e 100644 --- a/src/test/test-data/issue-257.unformatted.xml +++ b/src/test/test-data/issue-257.unformatted.xml @@ -1,5 +1,5 @@ - diff --git a/src/test/test-xquery/ast-to-xqdoc.xqm b/src/test/test-xquery/ast-to-xqdoc.xqm index 79cd330..c5780c6 100644 --- a/src/test/test-xquery/ast-to-xqdoc.xqm +++ b/src/test/test-xquery/ast-to-xqdoc.xqm @@ -5,7 +5,7 @@ create xqdoc from parse tree @author Andy Bunce, Quodatum, License: Apache-2.0 @TODO refs :) - module namespace xqdc = 'quodatum:xqdoca.model.xqdoc'; + module namespace xqdc = 'quodatum:xqdoca.model.xqdoc'; import module namespace xqcom = 'quodatum:xqdoca.model.comment' at "comment-to-xqdoc.xqm"; declare namespace xqdoc="http://www.xqdoc.org/1.0"; diff --git a/src/xpath/commands/getCurrentXPath.ts b/src/xpath/commands/getCurrentXPath.ts index a39a3fc..af8e925 100644 --- a/src/xpath/commands/getCurrentXPath.ts +++ b/src/xpath/commands/getCurrentXPath.ts @@ -7,7 +7,6 @@ import { XPathBuilder } from "../xpath-builder"; export function getCurrentXPath(editor: TextEditor, edit: TextEditorEdit): void { if (!editor.selection) { window.showInformationMessage("Please put your cursor in an element or attribute name."); - return; } diff --git a/src/xqdiagEvents.ts b/src/xqdiagEvents.ts index 3e239a5..259fc0d 100644 --- a/src/xqdiagEvents.ts +++ b/src/xqdiagEvents.ts @@ -1,18 +1,17 @@ -import {Uri} from "vscode"; - -import { XQLint } from "@quodatum/xqlint"; - +import { Uri, TextDocument } from "vscode"; +import { XQLint } from '@quodatum/xqlint'; export interface IXQParsedEvent { uri: Uri; - xqlint?: XQLint; + xqlint: XQLint; + document?: TextDocument } export class XQParsedEvent implements IXQParsedEvent { uri: Uri; xqlint: XQLint; - constructor(uri: Uri,xqLint?:XQLint) { + constructor(uri: Uri, xqLint?: XQLint) { this.uri = uri; - this.xqlint=xqLint; + this.xqlint = xqLint; } } \ No newline at end of file diff --git a/src/xqdiagnostics.ts b/src/xqlints.ts similarity index 87% rename from src/xqdiagnostics.ts rename to src/xqlints.ts index e0a1351..8ac9c79 100644 --- a/src/xqdiagnostics.ts +++ b/src/xqlints.ts @@ -7,16 +7,17 @@ import {IXQParsedEvent,XQParsedEvent as ParsedEvent} from "./xqdiagEvents"; import { XQLint, Marker } from '@quodatum/xqlint'; -import { channel, isNotXQDoc, unsupportedScheme, Configuration, importRange } from "./common"; +import { channel, isNotXQDoc, unsupportedScheme, + Configuration, importRange, findEditor } from "./common"; // DiagnosticCollection for XQuery documents -export class XQueryDiagnostics { +export class XQLinter { diagnosticCollectionXQuery: vscode.DiagnosticCollection; xqlintCollectionXQuery: Map; private diagEmitter = new vscode.EventEmitter(); - onDidDiag: vscode.Event = this.diagEmitter.event; + onXQParsed: vscode.Event = this.diagEmitter.event; constructor() { this.diagnosticCollectionXQuery = vscode.languages.createDiagnosticCollection(constants.diagnosticCollections.xquery); @@ -79,12 +80,11 @@ function linter(uri: vscode.Uri, document: string) { * @param xqueryDiagnostics diagnostic collection */ export function refreshDiagnostics(doc: vscode.TextDocument, - xqueryDiagnostics: XQueryDiagnostics, + xqueryDiagnostics: XQLinter, reason: string): void { if (isNotXQDoc(doc)) return; - const editor = vscode.window.visibleTextEditors.find( - (editor) => editor.document === doc - ); + const editor =findEditor ( doc); + const isNew = !xqueryDiagnostics.has(doc.uri); const refresh = reason === "change"; channel.log((isNew ? "🆕" : "") + (refresh ? "♻️" : "") + "refreshDiagnostics " + reason + " " + doc.uri.toString()); @@ -101,7 +101,7 @@ export function refreshDiagnostics(doc: vscode.TextDocument, pushDiagnostics(xqlint, diagnostics); xqueryDiagnostics.set(doc.uri, diagnostics); - channel.log("DD:" + diagnostics.length); + channel.log("diagnostics.length: " + diagnostics.length); } if (editor) { const xqlint = xqueryDiagnostics.xqlint(doc.uri); @@ -109,7 +109,7 @@ export function refreshDiagnostics(doc: vscode.TextDocument, } } // forward doc changes -export function subscribeToDocumentChanges(context: vscode.ExtensionContext, xqueryDiagnostics: XQueryDiagnostics): void { +export function subscribeToDocumentChanges(context: vscode.ExtensionContext, xqueryDiagnostics: XQLinter): void { const ed = vscode.window.activeTextEditor; if (ed && !unsupportedScheme(ed.document.uri)) { refreshDiagnostics(ed.document, xqueryDiagnostics, "current"); @@ -164,28 +164,32 @@ function isSuppressed(msg: string): boolean { const parseFailedDecorationType = vscode.window.createTextEditorDecorationType({ borderWidth: '1px', borderStyle: 'solid', + overviewRulerColor: 'red', overviewRulerLane: vscode.OverviewRulerLane.Right, + light: { // this color will be used in light color themes - borderColor: 'darkred' + borderColor: 'darkred', + backgroundColor: 'lightpink', }, dark: { // this color will be used in dark color themes - borderColor: 'lightred' + borderColor: 'lightred', + backgroundColor: 'deeppink', } }); function decorate(editor: vscode.TextEditor, xqlint: XQLint) { - const smallNumbers: vscode.DecorationOptions[] = []; + const theDecorations: vscode.DecorationOptions[] = []; if (xqlint.hasSyntaxError()) { const r=xqlint.getErrors(); - const range1=importRange(r[r.length-1].pos); + const range1=importRange(r[0].pos); const lastLine = editor.document.lineAt(editor.document.lineCount - 1); - const range=range1.with(range1.start,lastLine.range.end) - const decoration = { range: range, hoverMessage: 'Parse failed' }; - smallNumbers.push(decoration); + const range=range1.with(range1.end,lastLine.range.end) + const decoration = { range: range, hoverMessage: 'Parse failed at line:' +range1.end.line}; + theDecorations.push(decoration); } - editor.setDecorations(parseFailedDecorationType, smallNumbers); + editor.setDecorations(parseFailedDecorationType, theDecorations); } diff --git a/src/xquery-cmds/xqcmds.ts b/src/xquery-cmds/xqcmds.ts index 8b25ce7..b620f70 100644 --- a/src/xquery-cmds/xqcmds.ts +++ b/src/xquery-cmds/xqcmds.ts @@ -1,8 +1,9 @@ import { TextEditor, Selection, window } from "vscode"; import { channel } from "../common/channel-basex"; -import { Configuration,importRange } from "../common"; +import { Configuration, importRange } from "../common"; import { diagnosticCollectionXQuery } from "../extension"; +import { findNode } from "../common/xqlint"; export async function setProcessor(): Promise { const processor = Configuration.xqueryProcessor; @@ -19,16 +20,16 @@ export async function setProcessor(): Promise { // select enclosing declaration export function selectDeclaration(textEditor: TextEditor): void { channel.log("selectDeclaration:"); - - const linter = diagnosticCollectionXQuery.xqlint(textEditor.document.uri); + + const linter = diagnosticCollectionXQuery.xqlint(textEditor.document.uri); const pos = textEditor.selection.start; const node = linter.getAST(pos); - const n2=findNode(node,"AnnotatedDecl"); - if(n2){ - const range=importRange(n2.pos); + const n2 = findNode(node, "AnnotatedDecl"); + if (n2) { + const range = importRange(n2.pos); // include following ; - textEditor.selection = new Selection(range.start, range.end.translate(0,1)); - }else{ + textEditor.selection = new Selection(range.start, range.end.translate(0, 1)); + } else { window.showInformationMessage("select declaration - No enclosing declaration") } @@ -36,16 +37,9 @@ export function selectDeclaration(textEditor: TextEditor): void { // about the library ; export function libraryInfo(textEditor: TextEditor): void { - const linter = diagnosticCollectionXQuery.xqlint(textEditor.document.uri); - console.log("todo"); - window.showInformationMessage("libraryInfo @todo") + const linter = diagnosticCollectionXQuery.xqlint(textEditor.document.uri); + const lib=linter.getLibrary(); + console.log("todo: ", lib ); + window.showInformationMessage("libraryInfo @todo") } -// return 1st ancestor node with name or undefined -function findNode(node :any,nodeName :string):any{ - let n2 = node; - while (n2 !== null) { - if(n2.name === nodeName) return n2; - n2 = n2.getParent; - } -} \ No newline at end of file From 5f028005ec27e824a9c97ed318137671e26b3ec5 Mon Sep 17 00:00:00 2001 From: Andy Bunce Date: Sat, 4 Nov 2023 22:40:50 +0000 Subject: [PATCH 5/8] [fix] statusbar --- .vscode/settings.json | 2 +- languages/xquery/xquery.json | 25 +++++++++----- snippets.jsonc | 64 +++++++++++++++++++++++++----------- src/common/configuration.ts | 4 +-- src/common/workspace.ts | 13 ++++++-- src/common/xqlint.ts | 5 +-- src/extension.ts | 17 +++++----- src/statusbar.ts | 9 ++--- src/xqlints.ts | 43 ++++++++++++------------ src/xquery-cmds/xqcmds.ts | 30 ++++++++++++----- 10 files changed, 134 insertions(+), 78 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 64a972f..333e486 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -9,5 +9,5 @@ "yaml.schemas": { "https://json.schemastore.org/mkdocs-1.0.json": "file:///c%3A/Users/mrwhe/git/vscode-basex/mkdocs.yml" }, - "basexTools.xquery.processor": "basex-9" + "basexTools.xquery.processor": "basex-10" } \ No newline at end of file diff --git a/languages/xquery/xquery.json b/languages/xquery/xquery.json index 7993e6e..373283c 100644 --- a/languages/xquery/xquery.json +++ b/languages/xquery/xquery.json @@ -1,6 +1,5 @@ { "comments": { - "lineComment": ["(:", ":)"], "blockComment": [ "(:", ":)"] }, "brackets": [ @@ -8,12 +7,20 @@ [ "[", "]" ], [ "(", ")" ] ], - "surroundingPairs": [ - ["{", "}"], - ["[", "]"], - ["(", ")"], - ["'", "'"], - ["\"", "\""], - ["`", "`"] - ] + "autoClosingPairs": [ + { "open": "{", "close": "}" }, + { "open": "[", "close": "]" }, + { "open": "(", "close": ")" }, + { "open": "'", "close": "'", "notIn": ["string", "comment"] }, + { "open": "\"", "close": "\"", "notIn": ["string"] }, + { "open": "(:", "close": ":", "notIn": ["string"] } + ], + "autoCloseBefore": ";:.,=}])>` \n\t", + "surroundingPairs": [ + ["{", "}"], + ["[", "]"], + ["(", ")"], + ["'", "'"], + ["\"", "\""] + ] } diff --git a/snippets.jsonc b/snippets.jsonc index e12e220..2a3e22e 100644 --- a/snippets.jsonc +++ b/snippets.jsonc @@ -11,7 +11,7 @@ "module namespace ${1:prefix} = '${2:http://www.example.com/}';", "" ], - "description": "new library module template" + "description": "New library module template" }, "new main module": { "isFileTemplate": true, @@ -23,12 +23,21 @@ "${1:expr}", "" ], - "description": "new main module template" - } - , - "for in": { - "prefix": "for", - "body": "for \\$${1:item} in ${2:expr}" + "description": "New main module template" + }, + "flowr": { + "prefix": [ + "for", + "flowr" + ], + "body": [ + "for \\$${1:var} at \\$${2:pos} in ${3:expr}", + "let \\$$4:var2} := ${5:expr}", + "where ${6:boolean}", + "order by ${7:expr}", + "return ${8:expr2}" + ], + "description": "Full FLOWR expression" }, "return": { "prefix": "return", @@ -39,9 +48,9 @@ "body": "import module namespace ${1:ns} = '${2:http://www.example.com/}';", "description": "Import module" }, - "if":{ + "if": { "prefix": "if", - "body":[ + "body": [ "if (${1:boolean})", "then ${2:expr1}", "else ${3:expr2}" @@ -61,7 +70,10 @@ "body": "some \\$${1:varname} in ${2:expr} satisfies ${3:expr}" }, "declare function": { - "prefix": ["declare","function"], + "prefix": [ + "declare", + "function" + ], "body": [ "(:~ ${2:name} :)", "declare function ${1:ns}:${2:name}(){", @@ -71,7 +83,10 @@ "description": "declare function" }, "declare variable": { - "prefix": ["declare","variable"], + "prefix": [ + "declare", + "variable" + ], "body": [ "(:~ \\$${1:varname} :)", "declare variable \\$${1:varname} := ${2:expr};", @@ -109,7 +124,11 @@ "description": "try catch" }, "tumbling": { - "prefix": ["for","tumbling","window"], + "prefix": [ + "for", + "tumbling", + "window" + ], "body": [ "for tumbling window \\$${1:varname} in ${2:expr}", "start at \\$${3:start} when ${4:expr}", @@ -119,7 +138,11 @@ "description": "tumbling window" }, "sliding": { - "prefix": ["for","sliding","window"], + "prefix": [ + "for", + "sliding", + "window" + ], "body": [ "for sliding window \\$${1:varname} in ${2:expr}", "start at \\$${3:start} when ${4:expr}", @@ -128,14 +151,17 @@ ], "description": "sliding window" }, - - "let":{ - "prefix":"let", + "let": { + "prefix": "let", "body": "let \\$${1:varname} := ${2:expr}" - } + }, + "castable": { + "body": "castable as ${1:atomicType}" + }, + "cast": { + "body": "cast as ${1:atomicType}" + } } - - //snippet group // group by $${1:varname} := ${2:expr} //snippet order diff --git a/src/common/configuration.ts b/src/common/configuration.ts index ee19c2d..b7d7873 100644 --- a/src/common/configuration.ts +++ b/src/common/configuration.ts @@ -1,6 +1,6 @@ import { workspace, Uri } from "vscode"; -const ExtensionTopLevelSection = "basexTools"; +export const ExtensionTopLevelSection = "basexTools"; export class Configuration { static get enableXmlTreeView(): boolean { @@ -34,7 +34,7 @@ export class Configuration { static get xquerySuppressErrors(): string[] { return this._getForWindow("xquery.suppressErrors"); } - + // path to executable static get xqueryExecutionEngine(): string { return this._getForWindow("xquery.executionEngine"); } diff --git a/src/common/workspace.ts b/src/common/workspace.ts index a627578..4cbd982 100644 --- a/src/common/workspace.ts +++ b/src/common/workspace.ts @@ -1,14 +1,21 @@ // https://code.visualstudio.com/docs/editor/workspaces import * as path from 'path'; -import { Uri, workspace } from 'vscode' - +import { ConfigurationChangeEvent, ConfigurationScope, Uri, WorkspaceFolder, workspace } from 'vscode' +import { ExtensionTopLevelSection } from '../common' export function basePathForFilename(uri:Uri): string { - if (workspace.workspaceFolders) { return workspace.getWorkspaceFolder(uri).uri.fsPath; } else { return path.dirname(uri.fsPath); } } +export function scope(): ConfigurationScope { + return (workspace.workspaceFolders as WorkspaceFolder[])[0] +} + +// true if config change event effects section +export function affectsConfiguration(event:ConfigurationChangeEvent,section:string):boolean { + return event.affectsConfiguration(`${ExtensionTopLevelSection}.${section}`); +} \ No newline at end of file diff --git a/src/common/xqlint.ts b/src/common/xqlint.ts index b63c4f9..755e2be 100644 --- a/src/common/xqlint.ts +++ b/src/common/xqlint.ts @@ -34,9 +34,10 @@ export function inspectAst(linter: XQLint, position: Position) { const r = { path: path, type: 'other', - name: node.name, - value: node.value + name: node?.name, + value: node?.value }; + if(!node) return r; if (node.name === 'WS') { r.type = 'WS'; } else { diff --git a/src/extension.ts b/src/extension.ts index 3ef355f..cfd7ad3 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -3,7 +3,8 @@ import { TextEditorSelectionChangeKind, workspace } from "vscode"; -import { channel, createDocumentSelector, ExtensionState, Configuration } from "./common"; +import { channel, createDocumentSelector, ExtensionState, + Configuration, affectsConfiguration } from "./common"; import { activate as statusbar } from "./statusbar"; import { XQLinter, subscribeToDocumentChanges } from "./xqlints" //import { activate as activateActions} from "./xquery-cmds/xqactions"; @@ -13,22 +14,22 @@ import { xqLintReport, activateVirtualDocs } from "./linting"; import { XmlTreeDataProvider } from "./tree-view"; import { evaluateXPath, getCurrentXPath } from "./xpath/commands"; -import { setProcessor , selectDeclaration, executeXQuery, libraryInfo } from "./xquery-cmds"; +import { setProcessor, selectDeclaration, executeXQuery, libraryInfo } from "./xquery-cmds"; import * as constants from "./constants"; import * as providers from "./providers/activate"; -export const diagnosticCollectionXQuery=new XQLinter(); +export const diagnosticCollectionXQuery = new XQLinter(); //const actionDiagnostics = languages.createDiagnosticCollection(constants.diagnosticCollections.xqActions); export function activate(context: ExtensionContext) { channel.log("Extension activate"); ExtensionState.configure(context); - statusbar(context,diagnosticCollectionXQuery); + statusbar(context, diagnosticCollectionXQuery); //activateActions(context,actionDiagnostics); /* activate XQuery handlers */ - providers.activate(context,diagnosticCollectionXQuery); + providers.activate(context, diagnosticCollectionXQuery); activateVirtualDocs(context); /* Linting Features */ subscribeToDocumentChanges(context, diagnosticCollectionXQuery); @@ -36,7 +37,7 @@ export function activate(context: ExtensionContext) { /* XML Formatting Features */ const xmlXsdDocSelector = [ ...createDocumentSelector(constants.languageIds.xml), - ...createDocumentSelector(constants.languageIds.xsd)]; + ...createDocumentSelector(constants.languageIds.xsd)]; const xmlFormattingEditProvider = new XmlFormattingEditProvider(XmlFormatterFactory.getXmlFormatter()); context.subscriptions.push( commands.registerTextEditorCommand(constants.commands.formatAsXml, formatAsXml), @@ -84,9 +85,9 @@ export function activate(context: ExtensionContext) { // if changes to processor then clear diagnostics workspace.onDidChangeConfiguration(event => { - if (event.affectsConfiguration(constants.commands.xqProcessor)) { + if (affectsConfiguration(event,'xquery.processor')) { diagnosticCollectionXQuery.clear(); - window.showInformationMessage("Processor now: " + Configuration.xqueryProcessor); + window.showInformationMessage("XQuery profile now: " + Configuration.xqueryProcessor); } }) } diff --git a/src/statusbar.ts b/src/statusbar.ts index 78ef049..573f870 100644 --- a/src/statusbar.ts +++ b/src/statusbar.ts @@ -1,7 +1,7 @@ // statusbar: show profile when xq active import * as vscode from 'vscode'; -import { commands } from "./constants"; -import { isXqEditor,Configuration } from "./common"; +import {commands} from "./constants"; +import { isXqEditor,Configuration, affectsConfiguration} from "./common"; import { XQLinter } from './xqlints'; let myStatusBarItem: vscode.StatusBarItem; @@ -20,7 +20,8 @@ export function activate({ subscriptions }: vscode.ExtensionContext, subscriptions.push(onDidActive); vscode.workspace.onDidChangeConfiguration(event => { - if (event.affectsConfiguration(commands.xqProcessor)) { + //@todo scope? + if (affectsConfiguration(event,'xquery.processor')) { updateStatusBarItem(vscode.window.activeTextEditor); } }) @@ -30,7 +31,7 @@ function updateStatusBarItem(active: vscode.TextEditor): void { if (isXqEditor(active)) { const profile = Configuration.xqueryProcessor; myStatusBarItem.text = `$(package) ${profile}`; - myStatusBarItem.tooltip = "select active XQuery profile" + myStatusBarItem.tooltip = "Active XQuery profile, click to change" myStatusBarItem.show(); } else { myStatusBarItem.hide(); diff --git a/src/xqlints.ts b/src/xqlints.ts index 8ac9c79..c17a279 100644 --- a/src/xqlints.ts +++ b/src/xqlints.ts @@ -3,12 +3,14 @@ */ import * as vscode from 'vscode'; import * as constants from "./constants"; -import {IXQParsedEvent,XQParsedEvent as ParsedEvent} from "./xqdiagEvents"; +import { IXQParsedEvent, XQParsedEvent as ParsedEvent } from "./xqdiagEvents"; import { XQLint, Marker } from '@quodatum/xqlint'; -import { channel, isNotXQDoc, unsupportedScheme, - Configuration, importRange, findEditor } from "./common"; +import { + channel, isNotXQDoc, unsupportedScheme, + Configuration, importRange, findEditor +} from "./common"; // DiagnosticCollection for XQuery documents @@ -17,7 +19,7 @@ export class XQLinter { xqlintCollectionXQuery: Map; private diagEmitter = new vscode.EventEmitter(); - onXQParsed: vscode.Event = this.diagEmitter.event; + onXQParsed: vscode.Event = this.diagEmitter.event; constructor() { this.diagnosticCollectionXQuery = vscode.languages.createDiagnosticCollection(constants.diagnosticCollections.xquery); @@ -55,7 +57,7 @@ export class XQLinter { update(uri: vscode.Uri, document: string) { const xqlint = linter(uri, document); this.xqlintCollectionXQuery.set(uri.toString(), xqlint); - this.diagEmitter.fire(new ParsedEvent(uri,xqlint)) + this.diagEmitter.fire(new ParsedEvent(uri, xqlint)) } xqlint(uri: vscode.Uri): XQLint { @@ -83,7 +85,7 @@ export function refreshDiagnostics(doc: vscode.TextDocument, xqueryDiagnostics: XQLinter, reason: string): void { if (isNotXQDoc(doc)) return; - const editor =findEditor ( doc); + const editor = findEditor(doc); const isNew = !xqueryDiagnostics.has(doc.uri); const refresh = reason === "change"; @@ -93,13 +95,9 @@ export function refreshDiagnostics(doc: vscode.TextDocument, xqueryDiagnostics.update(doc.uri, text); const xqlint = xqueryDiagnostics.xqlint(doc.uri); const diagnostics = new Array(); - diagnostics.push(new vscode.Diagnostic( - importRange(), - "A Test", - vscode.DiagnosticSeverity.Information -)), - pushDiagnostics(xqlint, diagnostics); - + + pushXQLintDiagnostics(diagnostics, xqlint); + xqueryDiagnostics.set(doc.uri, diagnostics); channel.log("diagnostics.length: " + diagnostics.length); } @@ -135,7 +133,9 @@ export function subscribeToDocumentChanges(context: vscode.ExtensionContext, xqu context.subscriptions.push(onDidOpen, onDidChange, onDidClose, onDidActive); } -function pushDiagnostics(linter: XQLint, diagnostics: vscode.Diagnostic[]) { +function pushXQLintDiagnostics( + diagnostics: vscode.Diagnostic[], + linter: XQLint): vscode.Diagnostic[] { linter.getErrors().forEach((error: Marker) => { diagnostics.push(new vscode.Diagnostic( @@ -155,6 +155,7 @@ function pushDiagnostics(linter: XQLint, diagnostics: vscode.Diagnostic[]) { return diagnostics; } + // [XQST0059] module "http://config" not found // [XPST0008] "list-details#0": undeclared function function isSuppressed(msg: string): boolean { @@ -164,10 +165,10 @@ function isSuppressed(msg: string): boolean { const parseFailedDecorationType = vscode.window.createTextEditorDecorationType({ borderWidth: '1px', borderStyle: 'solid', - + overviewRulerColor: 'red', overviewRulerLane: vscode.OverviewRulerLane.Right, - + light: { // this color will be used in light color themes borderColor: 'darkred', @@ -184,11 +185,11 @@ const parseFailedDecorationType = vscode.window.createTextEditorDecorationType({ function decorate(editor: vscode.TextEditor, xqlint: XQLint) { const theDecorations: vscode.DecorationOptions[] = []; if (xqlint.hasSyntaxError()) { - const r=xqlint.getErrors(); - const range1=importRange(r[0].pos); - const lastLine = editor.document.lineAt(editor.document.lineCount - 1); - const range=range1.with(range1.end,lastLine.range.end) - const decoration = { range: range, hoverMessage: 'Parse failed at line:' +range1.end.line}; + const r = xqlint.getErrors(); + const range1 = importRange(r[0].pos); + const lastLine = editor.document.lineAt(editor.document.lineCount - 1); + const range = range1.with(range1.end, lastLine.range.end) + const decoration = { range: range, hoverMessage: 'Parse failed at line:' + range1.end.line }; theDecorations.push(decoration); } editor.setDecorations(parseFailedDecorationType, theDecorations); diff --git a/src/xquery-cmds/xqcmds.ts b/src/xquery-cmds/xqcmds.ts index b620f70..9f6b33d 100644 --- a/src/xquery-cmds/xqcmds.ts +++ b/src/xquery-cmds/xqcmds.ts @@ -1,20 +1,19 @@ -import { TextEditor, Selection, window } from "vscode"; +import { TextEditor, Selection, window, QuickPickItem } from "vscode"; import { channel } from "../common/channel-basex"; import { Configuration, importRange } from "../common"; import { diagnosticCollectionXQuery } from "../extension"; import { findNode } from "../common/xqlint"; +import { profiles, Profile} from '@quodatum/xqlint'; export async function setProcessor(): Promise { const processor = Configuration.xqueryProcessor; - const name = await window.showInputBox({ - prompt: "processor", - value: processor - }); - if (name) { - channel.log("setProcessor:" + name); - Configuration.xqueryProcessor = name; - } + const items:PickProfile[]=profiles().map(item => new PickProfile(item,processor)); + const pick=await window.showQuickPick(items,{title:"Select XQuery profile: "+processor}); + if(pick) { + channel.log("setProcessor:" + pick.id); + Configuration.xqueryProcessor = pick.id; + } } // select enclosing declaration @@ -43,3 +42,16 @@ export function libraryInfo(textEditor: TextEditor): void { window.showInformationMessage("libraryInfo @todo") } +class PickProfile implements QuickPickItem { + label: string; + description = ''; + picked: boolean; + id: string; + + constructor(item:Profile,current :string) { + this.label = `$(package) ${item.id}`; + this.description=item.description; + this.id=item.id + this.picked=item.id===current; // not supported? + } + } From f014ff148b38bf2bbd3947c79f2cb11d779c6146 Mon Sep 17 00:00:00 2001 From: Andy Bunce Date: Mon, 4 Dec 2023 16:10:37 +0000 Subject: [PATCH 6/8] [add] goto definition --- .vscode/launch.json | 1 + CHANGELOG.md | 12 +- README.md | 4 +- languages/bxs/snippets-cmd.jsonc | 36 +++++ languages/bxs/snippets-xml.jsonc | 29 ++++ .../xquery/snippets.jsonc | 2 +- languages/xquery/xquery.json | 4 +- package-lock.json | 96 ++++++------ package.json | 86 ++++++---- src/common/workspace.ts | 9 +- src/common/xqlint.ts | 147 +++++++++++++++--- src/constants.ts | 5 +- src/extension.ts | 14 +- src/linting/report.ts | 8 +- src/providers/activate.ts | 8 +- src/providers/codeaction.ts | 4 +- src/providers/completion.ts | 104 +++++++------ src/providers/definition.ts | 97 +++--------- src/providers/documentlink.ts | 8 +- src/providers/hover.ts | 43 ++--- src/providers/symbols.ts | 4 +- src/statusbar.ts | 4 +- src/test/test-bxs/test-cmd.bxs | 5 + src/test/test-bxs/test-xml.bxs | 9 ++ src/test/test-xquery/test.bxs | 2 - src/xpath/xpath-evaluator.ts | 2 +- src/xqlints.ts | 131 +++++++--------- src/xquery-cmds/executeXQuery.ts | 31 ++-- src/xquery-cmds/xqcmds.ts | 41 ++--- 29 files changed, 558 insertions(+), 388 deletions(-) create mode 100644 languages/bxs/snippets-cmd.jsonc create mode 100644 languages/bxs/snippets-xml.jsonc rename snippets.jsonc => languages/xquery/snippets.jsonc (99%) create mode 100644 src/test/test-bxs/test-cmd.bxs create mode 100644 src/test/test-bxs/test-xml.bxs delete mode 100644 src/test/test-xquery/test.bxs diff --git a/.vscode/launch.json b/.vscode/launch.json index 22a7aef..4c8397c 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -2,6 +2,7 @@ { "version": "0.1.0", "configurations": [ + { "name": "Extension", diff --git a/CHANGELOG.md b/CHANGELOG.md index bb2756a..80ada2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,15 @@ +# 0.2.6 (2023-12-05) +* Improve hovers +* goto definition (current file only) +# 0.2.5 (2023-11-20) +* support otherwise/ ?: +* xqlint 0.5.0 +* replace parseError decorator with standard error # 0.2.4 (2023-10-28) -* Improve autocomplete -* Improve builtin snippets +* Improve autocomplete (but not much) +* Improve XQuery snippets * add statusbar +* create bxs (cmd) and bxs (xml) language ids and snippets # 0.2.3 (2023-10-23) * xsl extension conflict #18 * Use xqlint 0.4.5 diff --git a/README.md b/README.md index ba5b01d..2190120 100644 --- a/README.md +++ b/README.md @@ -11,10 +11,12 @@ The `vscode-basex` extension adds features to support [BaseX](https://basex.org/) development on VSCode. A key feature is a parser for [XQuery](https://quodatum.github.io/basex-xqparse/) sources that supports all BaseX features, including XQuery Update and the Full text search syntax. # Status -__Work in progress. Errors and changes to be expected.__ +* __Work in progress. Errors and changes to be expected.__ + # Features See the [documentation](https://quodatum.github.io/vscode-basex/) for more detail +* Works in a Browser using [Code-server](https://github.com/coder/code-server) or [Github code-server](https://github.com/codespaces) ## XQuery * [Linting] * [Code Completion] diff --git a/languages/bxs/snippets-cmd.jsonc b/languages/bxs/snippets-cmd.jsonc new file mode 100644 index 0000000..c8a6c20 --- /dev/null +++ b/languages/bxs/snippets-cmd.jsonc @@ -0,0 +1,36 @@ +{ + "new basex script": { + "isFileTemplate": true, + "prefix": "BXS (cmd) Script", + "body": [ + "# A BaseX script https://docs.basex.org/wiki/Commands#Command_Scripts", + "" + ], + "description": "New BXS (cmd)" + }, + "create db":{ + "prefix":"create", + "body": "CREATE DB ${1:name} ([input])", + "description": "create a database" + }, + "open db":{ + "prefix":"open", + "body": "OPEN ${1:name}", + "description": "open a database" + }, + "check db":{ + "prefix":"check", + "body": "CHECK ${1:name}", + "description": "open or create a database" + }, + "close db":{ + "prefix":"close", + "body": "CLOSE", + "description": "close database" + }, + "list":{ + "prefix":"list", + "body": "LIST ${1:name}", + "description": "Lists all available databases. If name is specified, the resources of a database are listed. The output can be further restricted to the resources matching the specified path. If database resources are listed, the size is either the number of nodes (for XML resources) or the number of bytes (for binary resources)." + } +} \ No newline at end of file diff --git a/languages/bxs/snippets-xml.jsonc b/languages/bxs/snippets-xml.jsonc new file mode 100644 index 0000000..1dc7a75 --- /dev/null +++ b/languages/bxs/snippets-xml.jsonc @@ -0,0 +1,29 @@ +{ + "new basex script": { + "isFileTemplate": true, + "prefix": "BXS (XML) Script commands", + "body": [ + "", + "", + "${1}", + "" + ], + "description": "New BXS (xml)" + }, + "create db":{ + "prefix":"", + "description": "create a database" + }, + "open db":{ + "prefix":"", + "description": "open a database" + }, + "list":{ + "prefix":"", + "description": "list database content" + } + +} \ No newline at end of file diff --git a/snippets.jsonc b/languages/xquery/snippets.jsonc similarity index 99% rename from snippets.jsonc rename to languages/xquery/snippets.jsonc index 2a3e22e..2d7d9d9 100644 --- a/snippets.jsonc +++ b/languages/xquery/snippets.jsonc @@ -32,7 +32,7 @@ ], "body": [ "for \\$${1:var} at \\$${2:pos} in ${3:expr}", - "let \\$$4:var2} := ${5:expr}", + "let \\$${4:var2} := ${5:expr}", "where ${6:boolean}", "order by ${7:expr}", "return ${8:expr2}" diff --git a/languages/xquery/xquery.json b/languages/xquery/xquery.json index 373283c..2beda9b 100644 --- a/languages/xquery/xquery.json +++ b/languages/xquery/xquery.json @@ -22,5 +22,7 @@ ["(", ")"], ["'", "'"], ["\"", "\""] - ] + ], + "wordPattern": "(-?\\d*\\.\\d\\w*)|([^\\`\\~\\!\\#\\%\\^\\&\\*\\(\\)\\-\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\'\\\"\\,\\<\\>\\/\\?\\s]+)" + } diff --git a/package-lock.json b/package-lock.json index b27f671..d28aaea 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,15 @@ { "name": "vscode-basex", - "version": "0.2.4", + "version": "0.2.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "vscode-basex", - "version": "0.2.4", + "version": "0.2.5", "license": "MIT", "dependencies": { - "@quodatum/xqlint": "^0.4.5", + "@quodatum/xqlint": "^0.5.1", "@xmldom/xmldom": "^0.8.10", "bl": "^6.0.4", "xpath": "^0.0.33" @@ -420,9 +420,9 @@ } }, "node_modules/@eslint/eslintrc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.2.tgz", - "integrity": "sha512-+wvgpDsrB1YqAMdEUCcnTlpfVBH7Vqn6A/NT3D8WVXFIaKMlErPIZT3oCIAVCOtarRpMtelZLqJeU3t7WY6X6g==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.3.tgz", + "integrity": "sha512-yZzuIG+jnVu6hNSzFEN07e8BxF3uAzYtQb6uDkaYZLo6oYZDCq454c5kB8zxnzfCYyP4MIuyBn10L0DqwujTmA==", "dev": true, "dependencies": { "ajv": "^6.12.4", @@ -443,9 +443,9 @@ } }, "node_modules/@eslint/js": { - "version": "8.52.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.52.0.tgz", - "integrity": "sha512-mjZVbpaeMZludF2fsWLD0Z9gCref1Tk4i9+wddjRvpUNqqcndPkBD09N/Mapey0b3jaXbLm2kICwFv2E64QinA==", + "version": "8.54.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.54.0.tgz", + "integrity": "sha512-ut5V+D+fOoWPgGGNj83GGjnntO39xDy6DWxO0wb7Jp3DcMX0TfIqdzHF85VTQkerdyGmuuMD9AKAo5KiNlf/AQ==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -528,9 +528,9 @@ } }, "node_modules/@quodatum/xqlint": { - "version": "0.4.5", - "resolved": "https://registry.npmjs.org/@quodatum/xqlint/-/xqlint-0.4.5.tgz", - "integrity": "sha512-dD2X4lFXJUoDwBUgopGPjGePWy2lkmBRnJ2T4lVGegZL9A4H8uzFrnPGPgG/XbZ6reNDQf/u676Z8i0aA/n54Q==", + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@quodatum/xqlint/-/xqlint-0.5.1.tgz", + "integrity": "sha512-nogRqQF7z3F6ETeD0RaTe5wa32mtH28MF4MGzm5bdWCzGr17+UH5CtXvu0WP/3oxDZWNt+0PAyAlZERxLLiQ8Q==", "dependencies": { "@quodatum/xq-catalogs": "0.1.1", "colors": "1.4.0", @@ -564,9 +564,9 @@ } }, "node_modules/@types/json-schema": { - "version": "7.0.14", - "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.14.tgz", - "integrity": "sha512-U3PUjAudAdJBeC2pgN8uTIKgxrb4nlDF3SF0++EldXQvQBGkpFZMSnwQiIoDU77tv45VgNkl/L4ouD+rEomujw==", + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", "dev": true }, "node_modules/@types/minimatch": { @@ -576,9 +576,9 @@ "dev": true }, "node_modules/@types/mocha": { - "version": "10.0.3", - "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.3.tgz", - "integrity": "sha512-RsOPImTriV/OE4A9qKjMtk2MnXiuLLbcO3nCXK+kvq4nr0iMfFgpjaX3MPLb6f7+EL1FGSelYvuJMV6REH+ZPQ==", + "version": "10.0.6", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.6.tgz", + "integrity": "sha512-dJvrYWxP/UcXm36Qn36fxhUKu8A/xMRXVT2cliFF1Z7UA9liG5Psj3ezNSZw+5puH2czDXRLcXQxf8JbJt0ejg==", "dev": true }, "node_modules/@types/node": { @@ -598,21 +598,21 @@ } }, "node_modules/@types/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-MMzuxN3GdFwskAnb6fz0orFvhfqi752yjaXylr0Rp4oDg5H0Zn1IuyRhDVvYOwAXoJirx2xuS16I3WjxnAIHiQ==", + "version": "7.5.6", + "resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.6.tgz", + "integrity": "sha512-dn1l8LaMea/IjDoHNd9J52uBbInB796CDffS6VdIxvqYCPSG0V0DzHp76GpaWnlhg88uYyPbXCDIowa86ybd5A==", "dev": true }, "node_modules/@types/vscode": { - "version": "1.83.1", - "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.83.1.tgz", - "integrity": "sha512-BHu51NaNKOtDf3BOonY3sKFFmZKEpRkzqkZVpSYxowLbs5JqjOQemYFob7Gs5rpxE5tiGhfpnMpcdF/oKrLg4w==", + "version": "1.84.2", + "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.84.2.tgz", + "integrity": "sha512-LCe1FvCDMJKkPdLVGYhP0HRJ1PDop2gRVm/zFHiOKwYLBRS7vEV3uOOUId4HMV+L1IxqyS+IZXMmlSMRbZGIAw==", "dev": true }, "node_modules/@types/xmldom": { - "version": "0.1.33", - "resolved": "https://registry.npmjs.org/@types/xmldom/-/xmldom-0.1.33.tgz", - "integrity": "sha512-4PH3jqYT1EK0t+bDCZl7wW2A2yM25RapZqJ8/IaFcgr0y+aOiL4QKSrEIBItBzAKlF7nG8b6FPBMi/vTzIURjw==", + "version": "0.1.34", + "resolved": "https://registry.npmjs.org/@types/xmldom/-/xmldom-0.1.34.tgz", + "integrity": "sha512-7eZFfxI9XHYjJJuugddV6N5YNeXgQE1lArWOcd1eCOKWb/FGs5SIjacSYuEJuwhsGS3gy4RuZ5EUIcqYscuPDA==", "dev": true }, "node_modules/@typescript-eslint/eslint-plugin": { @@ -816,9 +816,9 @@ "dev": true }, "node_modules/@vscode/test-electron": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/@vscode/test-electron/-/test-electron-2.3.6.tgz", - "integrity": "sha512-M31xGH0RgqNU6CZ4/9g39oUMJ99nLzfjA+4UbtIQ6TcXQ6+2qkjOOxedmPBDDCg26/3Al5ubjY80hIoaMwKYSw==", + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@vscode/test-electron/-/test-electron-2.3.8.tgz", + "integrity": "sha512-b4aZZsBKtMGdDljAsOPObnAi7+VWIaYl3ylCz1jTs+oV6BZ4TNHcVNC3xUn0azPeszBmwSBDQYfFESIaUQnrOg==", "dev": true, "dependencies": { "http-proxy-agent": "^4.0.1", @@ -1334,15 +1334,15 @@ } }, "node_modules/eslint": { - "version": "8.52.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.52.0.tgz", - "integrity": "sha512-zh/JHnaixqHZsolRB/w9/02akBk9EPrOs9JwcTP2ek7yL5bVvXuRariiaAjjoJ5DvuwQ1WAE/HsMz+w17YgBCg==", + "version": "8.54.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.54.0.tgz", + "integrity": "sha512-NY0DfAkM8BIZDVl6PgSa1ttZbx3xHgJzSNJKYcQglem6CppHyMhRIQkBVSSMaSRnLhig3jsDbEzOjwCVt4AmmA==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.2", - "@eslint/js": "8.52.0", + "@eslint/eslintrc": "^2.1.3", + "@eslint/js": "8.54.0", "@humanwhocodes/config-array": "^0.11.13", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", @@ -1538,9 +1538,9 @@ "dev": true }, "node_modules/fast-glob": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz", - "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==", + "version": "3.3.2", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.2.tgz", + "integrity": "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow==", "dev": true, "dependencies": { "@nodelib/fs.stat": "^2.0.2", @@ -1645,9 +1645,9 @@ } }, "node_modules/flat-cache": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.1.1.tgz", - "integrity": "sha512-/qM2b3LUIaIgviBQovTLvijfyOQXPtSRnRK26ksj2J7rzPIecePUIpJsZ4T02Qg+xiAEKIs5K8dsHEd+VaKa/Q==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-3.2.0.tgz", + "integrity": "sha512-CYcENa+FtcUKLmhhqyctpclsq7QF38pKjZHsGNiSQF5r4FtoKDWabFDl3hzaEQMvT1LHEysw5twgLvpYYb4vbw==", "dev": true, "dependencies": { "flatted": "^3.2.9", @@ -1655,7 +1655,7 @@ "rimraf": "^3.0.2" }, "engines": { - "node": ">=12.0.0" + "node": "^10.12.0 || >=12.0.0" } }, "node_modules/flatted": { @@ -1840,9 +1840,9 @@ ] }, "node_modules/ignore": { - "version": "5.2.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.4.tgz", - "integrity": "sha512-MAb38BcSbH0eHNBxn7ql2NH/kX33OkB3lZ1BNdh7ENeRChHTYsTvWrMubiIAMNS2llXEEgZ1MUOBtXChP3kaFQ==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.0.tgz", + "integrity": "sha512-g7dmpshy+gD7mh88OC9NwSGTKoc3kyLAZQRU1mt53Aw/vnvfXnbC+F/7F7QoYVKbV+KNvJx8wArewKy1vXMtlg==", "dev": true, "engines": { "node": ">= 4" @@ -2499,9 +2499,9 @@ "dev": true }, "node_modules/punycode": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", - "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", "dev": true, "engines": { "node": ">=6" diff --git a/package.json b/package.json index 2665445..d096b1c 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "vscode-basex", "displayName": "BaseX tools", "description": "BaseX tools: XQuery, XML, XPath Tools for Visual Studio Code", - "version": "0.2.4", + "version": "0.2.6", "preview": true, "publisher": "quodatum", "author": "Andy Bunce (https://github.com/Quodatum)", @@ -36,6 +36,25 @@ "node_modules/@quodatum/xq-catalogs" ], "contributes": { + "taskDefinitions": [ + { + "type": "basex", + "required": [ + "task" + ], + "properties": { + "task": { + "type": "string", + "description": "The Rake task to customize" + }, + "file": { + "type": "string", + "description": "The Rake file that provides the task. Can be omitted." + } + }, + "when": "editorLangId == xquery || editorLangId == basexscript.cmd || editorLangId == basexscript.xml" + } + ], "commands": [ { "command": "basexTools.processor", @@ -44,14 +63,14 @@ }, { "command": "basexTools.xqParse", - "title": "BaseX Tools: Parse of XQuery source (xml)", + "title": "BaseX Tools: debug parse tree XML", "shortTitle": "Parse tree XML", "icon": "$(list-tree)", "enablement": "editorLangId == xquery" }, { "command": "basexTools.xqDoc", - "title": "BaseX Tools: XQdoc of XQuery source (json)", + "title": "BaseX Tools: debug xqDoc (json)", "shortTitle": "BaseX Tools: XQdoc for current", "icon": "$(bracket-dot)", "enablement": "editorLangId == xquery" @@ -73,14 +92,14 @@ }, { "command": "basexTools.executeXQuery", - "title": "BaseX Tools: Execute XQuery using standalone BaseX" + "title": "BaseX Tools: Run current file, XQuery or BXS, using standalone BaseX", + "when": "editorLangId == xquery || editorLangId == basexscript.cmd || editorLangId == basexscript.xml" }, { "command": "basexTools.selectDeclaration", "title": "BaseX Tools: Select current declaration", "enablement": "editorLangId == xquery" }, - { "command": "basexTools.getCurrentXPath", "title": "BaseX Tools: Get Current XPath" @@ -90,7 +109,6 @@ "title": "BaseX Tools: Evaluate XPath ", "shortTitle": "BaseX Tools: Evaluate XPath" }, - { "command": "basexTools.formatAsXml", "title": "BaseX Tools: Format as XML" @@ -103,7 +121,6 @@ "command": "basexTools.xmlToText", "title": "BaseX Tools: Convert XML to text (<> -> <>)" }, - { "command": "basexTools.minifyXml", "title": "BaseX Tools: Minify XML" @@ -118,27 +135,16 @@ "basexTools.xquery.processor": { "type": "string", "default": "basex-10", - "enum": [ - "basex-9", - "basex-10", - "" - ], - "enumDescriptions": [ - "BaseX 9.7.5 modules", - "BaseX 10.6 ", - "no custom libraries" - ], - "description": "Identifier for the XQuery processor. Determines available modules" + "description": "Identifier for the XQuery profile. Determines available modules" }, "basexTools.xquery.showHovers": { "type": "boolean", "default": false, - "description": "Show hovers in XQuery source. Currently these show just Diagnostic info" + "description": "Show Diagnostic info in hovers for XQuery source." }, "basexTools.xquery.suppressErrors": { "type": "array", - "default": [ - ], + "default": [], "description": "Lint Error messages including these strings are marked as info rather than error. TEMP HACK! " } } @@ -157,7 +163,7 @@ "basexTools.xquery.executionEngine": { "type": "string", "default": "", - "description": "The path to the executable to run when standalone BaseX. e.g ... \\basex.bat", + "description": "The path to the standalone BaseX executable. e.g. `basex.bat`", "scope": "window" } } @@ -258,7 +264,15 @@ "snippets": [ { "language": "xquery", - "path": "./snippets.jsonc" + "path": "./languages/xquery/snippets.jsonc" + }, + { + "language": "basexscript.cmd", + "path": "./languages/bxs/snippets-cmd.jsonc" + }, + { + "language": "basexscript.xml", + "path": "./languages/bxs/snippets-xml.jsonc" } ], "keybindings": [ @@ -279,7 +293,6 @@ ".csproj", ".xml", ".xsd", - ".plist", ".mobileconfig", ".sch" @@ -305,10 +318,23 @@ "configuration": "./languages/xquery/xquery.json" }, { - "id": "basex-script", - + "id": "basexscript.cmd", + "aliases": [ + "bxs (cmd)" + ], + "extensions": [ + ".bxs" + ], + "icon": { + "light": "./resources/bxs-file.png", + "dark": "./resources/bxs-file.png" + }, + "configuration": "./languages/bxs/bxs.json" + }, + { + "id": "basexscript.xml", "aliases": [ - "bxs" + "bxs (xml)" ], "extensions": [ ".bxs" @@ -328,7 +354,7 @@ }, { "command": "basexTools.executeXQuery", - "when": "editorLangId == xquery" + "when": "editorLangId == xquery || editorLangId == basexscript.cmd || editorLangId == basexscript.xml" }, { "command": "basexTools.getCurrentXPath", @@ -402,9 +428,9 @@ "typescript": "^4.7.3" }, "dependencies": { - "@quodatum/xqlint": "^0.4.5", + "@quodatum/xqlint": "^0.5.1", "@xmldom/xmldom": "^0.8.10", "bl": "^6.0.4", "xpath": "^0.0.33" } -} +} \ No newline at end of file diff --git a/src/common/workspace.ts b/src/common/workspace.ts index 4cbd982..e96ff8c 100644 --- a/src/common/workspace.ts +++ b/src/common/workspace.ts @@ -1,10 +1,13 @@ // https://code.visualstudio.com/docs/editor/workspaces import * as path from 'path'; -import { ConfigurationChangeEvent, ConfigurationScope, Uri, WorkspaceFolder, workspace } from 'vscode' +import { + ConfigurationChangeEvent, ConfigurationScope, Uri, + WorkspaceFolder, workspace +} from 'vscode' import { ExtensionTopLevelSection } from '../common' -export function basePathForFilename(uri:Uri): string { +export function basePathForFilename(uri: Uri): string { if (workspace.workspaceFolders) { return workspace.getWorkspaceFolder(uri).uri.fsPath; } else { @@ -16,6 +19,6 @@ export function scope(): ConfigurationScope { } // true if config change event effects section -export function affectsConfiguration(event:ConfigurationChangeEvent,section:string):boolean { +export function affectsConfiguration(event: ConfigurationChangeEvent, section: string): boolean { return event.affectsConfiguration(`${ExtensionTopLevelSection}.${section}`); } \ No newline at end of file diff --git a/src/common/xqlint.ts b/src/common/xqlint.ts index 755e2be..18e70ca 100644 --- a/src/common/xqlint.ts +++ b/src/common/xqlint.ts @@ -1,5 +1,5 @@ -import { Ast, LintRange, XQLint } from "@quodatum/xqlint"; -import { Position, Range } from "vscode"; +import { Ast, LintRange, Sctx, XQLint } from "@quodatum/xqlint"; +import { Position, Range, MarkdownString } from "vscode"; export function importRange(lintRange?: LintRange): Range { @@ -26,33 +26,144 @@ export function astPath(node: Ast): string[] { return path; } - +export interface What { + path: string[]; // AST + type: WhatType; + value: string; + display?: string; + get: unknown; +} +// +export enum WhatType{ + other, + WS, + VarRef, + FunctionCall, + NamedFunctionRef, + SequenceType, + Annotation, + Constructor, + StringConstructor, + Literal +} // metadata about given AST node {type:,path:} -export function inspectAst(linter: XQLint, position: Position) { - const node = linter.getAST(position); +export function inspectAst(linter: XQLint, position: Position): What { + const pos: Position = position.translate(0, 1) + const node = linter.getAST(pos); + const sctx = linter.getSctx(pos); const path = astPath(node); - const r = { + const r: What = { path: path, - type: 'other', - name: node?.name, - value: node?.value + type: WhatType.other, + value: node?.value, + get: {} }; - if(!node) return r; + if (!node) return r; if (node.name === 'WS') { - r.type = 'WS'; + r.type = WhatType.WS; } else { const ps = path.join("/"); if (ps.startsWith("EQName/FunctionEQName/FunctionCall/")) { - r.type = "FunctionCall"; - //@todo arity - } else if (ps.startsWith("EQName/VarName/VarRef")) { - r.type = "VarRef"; + const arity = calcArity(ancestor(node, "FunctionCall")); + fnType(r, arity, sctx, position); + + } else if (ps.startsWith("EQName/ArrowFunctionSpecifier/")) { + const arity = calcArity(ancestor(node, "ArrowFunctionSpecifier")); + fnType(r, arity, sctx, position); + + } else if (ps.startsWith("EQName/VarName/VarRef/")) { + r.type = WhatType.VarRef; + const qname = sctx.resolveQName(r.value, position); + const v = sctx.getVariable(qname); r.value = '$' + r.value; + r.get = v; + + } else if (path.includes("NamedFunctionRef")) { + const arity = getArity(ancestor(node, "NamedFunctionRef")); + fnType(r, arity, sctx, position); + r.type = WhatType.NamedFunctionRef; + } else if (path.includes("SequenceType")) { - r.type = "SequenceType"; + r.type = WhatType.SequenceType; + } else if (path.includes("Annotation")) { - r.type = "Annotation"; + r.type = WhatType.Annotation; + + } else if (path.includes("Constructor")) { + r.type =WhatType.Constructor; + r.value = "~~constructor"; + + } else if (path.includes("StringConstructor")) { + r.type = WhatType.StringConstructor; + r.value = "``[.."; + + } else if (path.includes("Literal")) { + r.type = WhatType.Literal; + } } return r; -} \ No newline at end of file +} + +// Calculate Arity from functioncall or ArrowFunctionSpecifier +function calcArity(node: Ast): number { + if (node.name === "ArrowFunctionSpecifier") { + // find following arglist + const childs=node.getParent.children; + const pos=childs.indexOf(node); + return 1+ get(childs[1+pos], [ 'Argument']).length; + } else { + return get(node, ['ArgumentList', 'Argument']).length; + } +} +// expect NamedFunctionRef +function getArity(node: Ast): number { + return Number(node.children[2].value); +} + +//update What for function +function fnType(r: What, arity: number, sctx: Sctx, position: Position) { + r.type = WhatType.FunctionCall; + const qname = sctx.resolveQName(r.value, position); + const lib = sctx.getFunction(qname, arity); + r.get = lib; + let result = lib.return; + result = result ?? lib.type; + + r.display = r.value + + "( " + r.get.params.join(", ") + " )" + + (result ? " as " + result : ""); +} + +export function markdownString(value: string): MarkdownString { + const s = new MarkdownString(value); + s.supportHtml = true; + s.isTrusted = true; + return s +} + +// return 1st ancestor node with name or undefined +function ancestor(node: Ast, nodeName: string) { + let n2 = node; + while (n2) { + if (n2.name === nodeName) { return n2; } + n2 = n2.getParent; + } +} + +// var arity = get(node, ['ArgumentList', 'Argument']).length; +function get(node: Ast, path: string[]): Ast[] { + let result: Ast[] = []; + if (path.length === 0) { + return [node] + } + node.children.forEach(function (child) { + if (child.name === path[0] && path.length > 1) { + result = get(child, path.slice(1)); + } else if (child.name === path[0]) { + result.push(child); + } + }); + return result; +} + diff --git a/src/constants.ts b/src/constants.ts index bb80128..b8d3d8f 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -29,9 +29,12 @@ export namespace diagnosticCollections { } export namespace languageIds { + export const bxsCmd = "basexscript.cmd"; + export const bxsXml = "basexscript.xml"; + export const xquery = "xquery"; + export const xml = "xml"; export const xsd = "xsd"; - export const xquery = "xquery"; } export namespace nativeCommands { diff --git a/src/extension.ts b/src/extension.ts index cfd7ad3..3d6c13e 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -6,7 +6,7 @@ import { import { channel, createDocumentSelector, ExtensionState, Configuration, affectsConfiguration } from "./common"; import { activate as statusbar } from "./statusbar"; -import { XQLinter, subscribeToDocumentChanges } from "./xqlints" +import { XQLinters, subscribeToDocumentChanges } from "./xqlints" //import { activate as activateActions} from "./xquery-cmds/xqactions"; import { XmlFormatterFactory, XmlFormattingEditProvider } from "./formatting"; import { formatAsXml, minifyXml, xmlToText, textToXml } from "./formatting/commands"; @@ -20,19 +20,19 @@ import * as constants from "./constants"; import * as providers from "./providers/activate"; -export const diagnosticCollectionXQuery = new XQLinter(); +export const xqLinters = new XQLinters(); //const actionDiagnostics = languages.createDiagnosticCollection(constants.diagnosticCollections.xqActions); export function activate(context: ExtensionContext) { channel.log("Extension activate"); ExtensionState.configure(context); - statusbar(context, diagnosticCollectionXQuery); + statusbar(context, xqLinters); //activateActions(context,actionDiagnostics); /* activate XQuery handlers */ - providers.activate(context, diagnosticCollectionXQuery); + providers.activate(context, xqLinters); activateVirtualDocs(context); /* Linting Features */ - subscribeToDocumentChanges(context, diagnosticCollectionXQuery); + subscribeToDocumentChanges(context, xqLinters); /* XML Formatting Features */ const xmlXsdDocSelector = [ @@ -80,13 +80,13 @@ export function activate(context: ExtensionContext) { commands.registerTextEditorCommand(constants.commands.xqSelectDeclaration, selectDeclaration), commands.registerTextEditorCommand(constants.commands.xqLibrary, libraryInfo), commands.registerCommand(constants.commands.xqProcessor, setProcessor), - commands.registerCommand(constants.commands.xqClearDiagnostics, diagnosticCollectionXQuery.clear), + commands.registerCommand(constants.commands.xqClearDiagnostics, xqLinters.clear), ); // if changes to processor then clear diagnostics workspace.onDidChangeConfiguration(event => { if (affectsConfiguration(event,'xquery.processor')) { - diagnosticCollectionXQuery.clear(); + xqLinters.clear(); window.showInformationMessage("XQuery profile now: " + Configuration.xqueryProcessor); } }) diff --git a/src/linting/report.ts b/src/linting/report.ts index ace4052..6f48868 100644 --- a/src/linting/report.ts +++ b/src/linting/report.ts @@ -3,7 +3,7 @@ import * as vscode from "vscode"; import { commands } from "../constants"; import { channel, dump,closeFileIfOpen, unsupportedScheme } from "../common"; -import { diagnosticCollectionXQuery } from "../extension"; +import { xqLinters } from "../extension"; export function activateVirtualDocs({ subscriptions }: vscode.ExtensionContext) { @@ -14,7 +14,7 @@ export function activateVirtualDocs({ subscriptions }: vscode.ExtensionContext) provideTextDocumentContent(uri: vscode.Uri): string { const orig=sourceUri(uri); if(unsupportedScheme(orig)) return; - return diagnosticCollectionXQuery.xqlint(orig).printAST(); + return xqLinters.xqlint(orig).printAST(); } }; subscriptions.push(vscode.workspace.registerTextDocumentContentProvider(parseScheme, parseProvider)); @@ -45,7 +45,7 @@ export function activateVirtualDocs({ subscriptions }: vscode.ExtensionContext) provideTextDocumentContent(uri: vscode.Uri): string { const orig=sourceUri(uri); if(unsupportedScheme(orig)) return; - const xqdoc=diagnosticCollectionXQuery.xqlint(orig).getXQDoc(); + const xqdoc=xqLinters.xqlint(orig).getXQDoc(); return JSON.stringify(xqdoc,undefined," ") ; } }; @@ -83,7 +83,7 @@ export function activateVirtualDocs({ subscriptions }: vscode.ExtensionContext) // dump node to console export function xqLintReport(textEditor: vscode.TextEditor): void { - const linter = diagnosticCollectionXQuery.xqlint(textEditor.document.uri); + const linter = xqLinters.xqlint(textEditor.document.uri); textEditor.edit(textEdit => { const selections = textEditor.selections; selections.forEach(selection => { diff --git a/src/providers/activate.ts b/src/providers/activate.ts index 2978588..da9d670 100644 --- a/src/providers/activate.ts +++ b/src/providers/activate.ts @@ -1,16 +1,18 @@ import { ExtensionContext} from "vscode"; -import {XQLinter} from "../xqlints"; +import {XQLinters} from "../xqlints"; import * as formatter from "./formatting"; import * as symbols from './symbols'; import * as hover from './hover'; +import * as definition from './definition'; import * as codeAction from './codeaction'; import * as completion from './completion'; import * as documentLink from './documentlink'; -export function activate(context: ExtensionContext,diagnosticCollectionXQuery:XQLinter) { +export function activate(context: ExtensionContext,diagnosticCollectionXQuery:XQLinters) { symbols.activate(context); hover.activate(context); - codeAction.activate(context,diagnosticCollectionXQuery); + definition.activate(context); +// codeAction.activate(context,diagnosticCollectionXQuery); completion.activate(context); documentLink.activate(context); formatter.activate(context); diff --git a/src/providers/codeaction.ts b/src/providers/codeaction.ts index dffa501..f2c258e 100644 --- a/src/providers/codeaction.ts +++ b/src/providers/codeaction.ts @@ -5,12 +5,12 @@ import * as vscode from 'vscode'; import { XQ_ACTION } from './codeactions-diagnostics'; import { languageIds } from "../constants"; -import { XQLinter } from "../xqlints"; +import { XQLinters } from "../xqlints"; import { isEmpty } from '../common' import { IXQParsedEvent } from '../xqdiagEvents'; const COMMAND = 'code-actions-basex.command'; -export function activate(context: vscode.ExtensionContext, diagnosticCollectionXQuery: XQLinter) { +export function activate(context: vscode.ExtensionContext, diagnosticCollectionXQuery: XQLinters) { context.subscriptions.push( vscode.languages.registerCodeActionsProvider(languageIds.xquery, new XQActionProvider(), { providedCodeActionKinds: XQActionProvider.providedCodeActionKinds diff --git a/src/providers/completion.ts b/src/providers/completion.ts index da77ac3..b24176b 100644 --- a/src/providers/completion.ts +++ b/src/providers/completion.ts @@ -1,26 +1,27 @@ +/* eslint-disable no-case-declarations */ import { - CompletionItem, CompletionItemKind, CompletionItemProvider,CompletionContext, - Position, TextDocument, ExtensionContext, languages, CompletionList,CancellationToken + CompletionItem, CompletionItemKind, CompletionContext, + Position, TextDocument, ExtensionContext, languages, CompletionList, CancellationToken } from "vscode"; import { languageIds } from "../constants"; -import { createDocumentSelector } from '../common'; -import { diagnosticCollectionXQuery } from "../extension"; -import { XQLintCompletion as XQLintCompletionItem} from '@quodatum/xqlint'; +import { createDocumentSelector,markdownString } from '../common'; +import { xqLinters } from "../extension"; +import { XQLint, XQLintCompletion as XQLintCompletionItem } from '@quodatum/xqlint'; export function activate(context: ExtensionContext) { - const obj={ - provideCompletionItems: async (document: TextDocument, position: Position, + const obj = { + provideCompletionItems: async (document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext) : Promise => { - const linter = diagnosticCollectionXQuery.xqlint(document.uri); + const linter = xqLinters.xqlint(document.uri); const completionItems = new Array(); linter.getCompletions(position).forEach((x: XQLintCompletionItem) => { - completionItems.push(_getCompletionItem(x)); + completionItems.push(_getCompletionItem(x, linter)); }); - - const res = new CompletionList( completionItems,true); + // isIncomplete https://github.com/microsoft/vscode/issues/99504 + const res = new CompletionList(completionItems, true); return res; } }; @@ -30,47 +31,52 @@ export function activate(context: ExtensionContext) { )); } -function _getCompletionItem(xqLintCompletionItem: XQLintCompletionItem): CompletionItem { - const completionItem = new CompletionItem(xqLintCompletionItem.name); - completionItem.insertText = xqLintCompletionItem.snippet; - - switch (xqLintCompletionItem.meta) { - // functions (always qualified with a colon) - case "function": - completionItem.kind = CompletionItemKind.Function; +function _getCompletionItem( + xqLintCompletionItem: XQLintCompletionItem, + _linter: XQLint): CompletionItem { + const completionItem = new CompletionItem(xqLintCompletionItem.name); + completionItem.insertText = xqLintCompletionItem.snippet; - // eslint-disable-next-line no-case-declarations - const funcStart = (xqLintCompletionItem.value.indexOf(":") + 1); - // eslint-disable-next-line no-case-declarations - const funcEnd = xqLintCompletionItem.value.indexOf("("); - //completionItem.commitCharacters=["("]; - completionItem.documentation="Some documentation about "+ xqLintCompletionItem.value; - completionItem.insertText = xqLintCompletionItem.value.substring(funcStart, funcEnd); - break; + switch (xqLintCompletionItem.meta) { + // functions (always qualified with a colon) + case "function": + completionItem.kind = CompletionItemKind.Function; - // variables and parameters (always qualified with a dollar sign) - case "Let binding": - case "Local variable": - case "Window variable": - case "Function parameter": - completionItem.kind = CompletionItemKind.Variable; - completionItem.insertText = xqLintCompletionItem.value.substring(1); - completionItem.detail="A " +xqLintCompletionItem.meta; - break; - case "prefix": - completionItem.kind = CompletionItemKind.Class; - completionItem.detail="A namespace prefix"; - break; - case "type": - completionItem.kind = CompletionItemKind.TypeParameter; - break; - // everything else - default: - completionItem.kind = CompletionItemKind.Text; - break; - } + const funcStart = (xqLintCompletionItem.value.indexOf(":") + 1); + const funcEnd = xqLintCompletionItem.value.indexOf("("); + //completionItem.commitCharacters=["("]; + completionItem.documentation = "Some documentation about " + xqLintCompletionItem.value; + completionItem.insertText = xqLintCompletionItem.value.substring(funcStart, funcEnd); + break; - return completionItem; + // variables and parameters (always qualified with a dollar sign) + case "Let binding": + case "Local variable": + case "Window variable": + case "Function parameter": + completionItem.kind = CompletionItemKind.Variable; + completionItem.insertText = xqLintCompletionItem.value.substring(1); + completionItem.detail = "A " + xqLintCompletionItem.meta; + break; + case "prefix": + completionItem.kind = CompletionItemKind.Class; + + const value = xqLintCompletionItem.value.slice(0, -1); + const ns=_linter.getSctx().getNamespaceByPrefix(value); + completionItem.detail = ns.uri; + completionItem.documentation = markdownString(ns?.description); + completionItem.insertText = xqLintCompletionItem.value; + break; + case "type": + completionItem.kind = CompletionItemKind.TypeParameter; + break; + // everything else + default: + completionItem.kind = CompletionItemKind.Text; + break; } + return completionItem; +} + diff --git a/src/providers/definition.ts b/src/providers/definition.ts index 9d33c6d..78c5d17 100644 --- a/src/providers/definition.ts +++ b/src/providers/definition.ts @@ -2,83 +2,24 @@ 'use strict'; import vscode from 'vscode'; -import cp = require('child_process'); -import path = require('path'); - - -export class XQueryDefinitionProvider implements vscode.DefinitionProvider { - - private parseDefinitionLocation(output: string, filename: string): vscode.Definition { - - const items: vscode.Location[] = new Array(); - output.split(/\r?\n/) - .forEach(function (value, index, array) { - - if (value !== null && value !== "") { - - const values = value.split(/ +/); - - // Create 113 C:/Users/alefr/Downloads/SynEdit-2_0_8/SynEdit/Source/SynURIOpener.pas constructor Create(AOwner: TComponent); override; - const word = values.shift(); - const line = parseInt(values.shift()) - 1; - - // together again get the filename (which may contains spaces and the previous shift wouldn't work) - let filePath: string; - if (values[ 2 ].indexOf(word + '(') === 0) { - filePath = path.join(AbstractProvider.basePathForFilename(filename), values.shift()); - } else { - const rest: string = values.join(' '); - const idxProc: number = rest.search(/(class\s+)?\b(procedure|function|constructor|destructor)\b/gi); - filePath = rest.substr(0, idxProc - 1); - filePath = path.join(AbstractProvider.basePathForFilename(filename), filePath); - } - - const definition = new vscode.Location( - vscode.Uri.file(filePath), new vscode.Position(line, 0) - ); - - items.push(definition); - } - - }); - - return items; - } - - private definitionLocations(word: string, filename: string): Promise { - - return new Promise((resolve, reject) => { - - this.generateTagsIfNeeded(filename) - .then((value: boolean) => { - if (value) { - - cp.execFile('global', [ '-x', word ], { cwd: AbstractProvider.basePathForFilename(filename) }, (err, stdout, stderr) => { - try { - if (err && (err).code === 'ENOENT') { - console.log(vscode.l10n.t('The "global" command is not available. Make sure it is on PATH')); - } - if (err) return resolve(null); - const result = stdout.toString(); - // console.log(result); - const locs = this.parseDefinitionLocation(result, filename); - return resolve(locs); - } catch (e) { - reject(e); - } - }); - } else { - return resolve(null); - } - }); - }); - } - - public provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): vscode.Definition | Thenable { - const fileName: string = document.fileName; - const word = document.getText(document.getWordRangeAtPosition(position)).split(/\r?\n/)[0]; - return this.definitionLocations(word, fileName).then(locs => { - return locs; - }); +import { inspectAst, WhatType ,importRange} from "../common"; +import { xqLinters } from "../extension"; +import { languageIds } from '../constants'; + +export function activate(context: vscode.ExtensionContext) { + context.subscriptions.push(vscode.languages.registerDefinitionProvider( + { language: languageIds.xquery }, new XQueryDefinitionProvider() + )); +} +const hasDef=[WhatType.FunctionCall,WhatType.VarRef]; +export class XQueryDefinitionProvider implements vscode.DefinitionProvider { + + public provideDefinition(document: vscode.TextDocument, position: vscode.Position, + token: vscode.CancellationToken): vscode.Definition | Thenable { + const linter = xqLinters.xqlint(document.uri); + const what = inspectAst(linter, position); + if (! hasDef.includes(what.type)) return undefined; + const range=importRange(what.get.pos); + return new vscode.Location(document.uri, range.start); } } \ No newline at end of file diff --git a/src/providers/documentlink.ts b/src/providers/documentlink.ts index 5ebcc9a..85f2fdb 100644 --- a/src/providers/documentlink.ts +++ b/src/providers/documentlink.ts @@ -1,9 +1,9 @@ // XQuery Document link provider -/*--------------------------------------------------------------------------------------------- +/*---------------------------------------------------------- * Copyright (c) Quodatum. All rights reserved. * Licensed under the MIT License. - *--------------------------------------------------------------------------------------------*/ + *----------------------------------------------------------*/ import { DocLink } from '@quodatum/xqlint'; import { @@ -11,7 +11,7 @@ import { DocumentLink, DocumentLinkProvider,Uri } from 'vscode'; import { channel,importRange } from "../common"; -import { diagnosticCollectionXQuery } from "../extension"; +import { xqLinters } from "../extension"; import { languageIds } from "../constants"; @@ -24,7 +24,7 @@ class XQueryDocumentLinks implements DocumentLinkProvider { // eslint-disable-next-line @typescript-eslint/no-unused-vars provideDocumentLinks = async (doc: TextDocument, _token: CancellationToken): Promise => { channel.start("Doclinks" , doc.uri); - const linter = diagnosticCollectionXQuery.xqlint(doc.uri); + const linter = xqLinters.xqlint(doc.uri); const dlinks = linter.getDocLinks(); const links: DocumentLink[] = []; dlinks.forEach((dl)=>{ diff --git a/src/providers/hover.ts b/src/providers/hover.ts index d0e282d..362aefe 100644 --- a/src/providers/hover.ts +++ b/src/providers/hover.ts @@ -2,10 +2,10 @@ import * as vscode from "vscode"; -import { Configuration ,inspectAst } from "../common"; +import { Configuration, inspectAst, markdownString } from "../common"; import { languageIds } from "../constants"; -import { diagnosticCollectionXQuery } from "../extension"; -import { XQLint } from '@quodatum/xqlint'; +import { xqLinters } from "../extension"; + export function activate(context: vscode.ExtensionContext) { @@ -13,29 +13,36 @@ export function activate(context: vscode.ExtensionContext) { { language: languageIds.xquery }, new XQueryHoverProvider() )); } + + class XQueryHoverProvider implements vscode.HoverProvider { public provideHover( document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken ): vscode.Hover | null { - if (!Configuration.xqueryShowHovers()) return null; + const range = document.getWordRangeAtPosition(position); if (!range) return null const word = document.getText(range); - const linter = diagnosticCollectionXQuery.xqlint(document.uri); - const x=inspectAst(linter,position); - if (x.type==='WS') return null; - const parsePath = new vscode.MarkdownString( - 'Path:'); - parsePath.appendText(x.path.join("/")); - parsePath.supportHtml = true; - parsePath.isTrusted = true; - - return new vscode.Hover([ - `[${position.line},${position.character}] Type: ${x.name}, Word: ${word}`, - `value: ${x.value}, type: ${ x.type}`, - parsePath - ]); + const linter = xqLinters.xqlint(document.uri); + const what = inspectAst(linter, position); + if (what.type === 'WS') return null; + + const hovers:vscode.MarkdownString[]=[ + what.display?markdownString("**"+what.display+"**"):null, + markdownString(what.get?.description) + ]; + + if (Configuration.xqueryShowHovers()) { + const parsePath = markdownString( + 'Path:'); + parsePath.appendText(what.path.join("/")); + const debugInfo=`[${position.line},${position.character}] Word: ${word}, + value: ${what.value}, type: ${what.type}`; + hovers.push(markdownString(debugInfo)); + hovers.push( parsePath); + } + return new vscode.Hover(hovers); } } diff --git a/src/providers/symbols.ts b/src/providers/symbols.ts index 6e8e344..b71f97b 100644 --- a/src/providers/symbols.ts +++ b/src/providers/symbols.ts @@ -7,7 +7,7 @@ import { } from 'vscode'; import { channel,importRange } from "../common"; import { languageIds } from "../constants"; -import { diagnosticCollectionXQuery } from "../extension"; +import { xqLinters } from "../extension"; // // This class handles XQuery Symbols // @@ -47,7 +47,7 @@ export class DocumentSymbols implements DocumentSymbolProvider { channel.log("DocumentSymbols: " + document.uri); const symbols: DocumentSymbol[] = []; - const linter = diagnosticCollectionXQuery.xqlint(document.uri); + const linter = xqLinters.xqlint(document.uri); const xqdoc = linter.getXQDoc(true); channel.log("got xqdoc"); diff --git a/src/statusbar.ts b/src/statusbar.ts index 573f870..e0abb9b 100644 --- a/src/statusbar.ts +++ b/src/statusbar.ts @@ -2,13 +2,13 @@ import * as vscode from 'vscode'; import {commands} from "./constants"; import { isXqEditor,Configuration, affectsConfiguration} from "./common"; -import { XQLinter } from './xqlints'; +import { XQLinters } from './xqlints'; let myStatusBarItem: vscode.StatusBarItem; export function activate({ subscriptions }: vscode.ExtensionContext, // eslint-disable-next-line @typescript-eslint/no-unused-vars - diagnostics: XQLinter) { + diagnostics: XQLinters) { // create a new status bar item that we can now manage myStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100); myStatusBarItem.command = commands.xqProcessor; diff --git a/src/test/test-bxs/test-cmd.bxs b/src/test/test-bxs/test-cmd.bxs new file mode 100644 index 0000000..54cdfac --- /dev/null +++ b/src/test/test-bxs/test-cmd.bxs @@ -0,0 +1,5 @@ +CREATE DB test +ADD TO embedded.xml embedded +# run query +XQUERY { count(//text()) } +CLOSE \ No newline at end of file diff --git a/src/test/test-bxs/test-xml.bxs b/src/test/test-bxs/test-xml.bxs new file mode 100644 index 0000000..77280a9 --- /dev/null +++ b/src/test/test-bxs/test-xml.bxs @@ -0,0 +1,9 @@ + + + embedded + + { count(//text()) } + ]]> + + \ No newline at end of file diff --git a/src/test/test-xquery/test.bxs b/src/test/test-xquery/test.bxs deleted file mode 100644 index 6dfbb7a..0000000 --- a/src/test/test-xquery/test.bxs +++ /dev/null @@ -1,2 +0,0 @@ -# @see https://docs.basex.org/wiki/Commands -CREATE DB xmark http://files.basex.org/xml/xmark.xml \ No newline at end of file diff --git a/src/xpath/xpath-evaluator.ts b/src/xpath/xpath-evaluator.ts index b556c77..a56dab2 100644 --- a/src/xpath/xpath-evaluator.ts +++ b/src/xpath/xpath-evaluator.ts @@ -36,7 +36,7 @@ export class XPathEvaluator { const nodes = new Array(); const xdoc: Document = new DOMParser().parseFromString(xml, "text/xml"); const resolver = (xpath as any).createNSResolver(xdoc); - const xPathResult = xpath.select1(query, xdoc, resolver, 0, null); + const xPathResult = xpath.selectWithResolver(query, xdoc, resolver, true); const evaluatorResult = new EvaluatorResult(); evaluatorResult.type = EvaluatorResultType.SCALAR_TYPE; diff --git a/src/xqlints.ts b/src/xqlints.ts index c17a279..244bf9a 100644 --- a/src/xqlints.ts +++ b/src/xqlints.ts @@ -11,19 +11,20 @@ import { channel, isNotXQDoc, unsupportedScheme, Configuration, importRange, findEditor } from "./common"; +import { TextDocument } from 'vscode'; // DiagnosticCollection for XQuery documents -export class XQLinter { +export class XQLinters { diagnosticCollectionXQuery: vscode.DiagnosticCollection; - xqlintCollectionXQuery: Map; + xqlintCollection: Map; private diagEmitter = new vscode.EventEmitter(); onXQParsed: vscode.Event = this.diagEmitter.event; constructor() { this.diagnosticCollectionXQuery = vscode.languages.createDiagnosticCollection(constants.diagnosticCollections.xquery); - this.xqlintCollectionXQuery = new Map(); + this.xqlintCollection = new Map(); channel.log("xqueryDiagnostics new"); } @@ -32,15 +33,19 @@ export class XQLinter { if (this.diagnosticCollectionXQuery.has(uri)) { channel.log("xqueryDiagnostics delete: " + uri); this.diagnosticCollectionXQuery.delete(uri); - this.xqlintCollectionXQuery.delete(uri.toString()); + this.xqlintCollection.delete(uri.toString()); this.diagEmitter.fire(new ParsedEvent(uri)); } } clear(): void { - channel.log("xqueryDiagnostics clear"); - this.diagnosticCollectionXQuery.clear(); - this.xqlintCollectionXQuery.clear(); + if (this) { + channel.log("xqueryDiagnostics clear"); + this.xqlintCollection.clear(); + this.diagnosticCollectionXQuery.clear(); + } else { + channel.log("xqueryDiagnostics unset!"); + } } get(uri: vscode.Uri): readonly vscode.Diagnostic[] { @@ -51,63 +56,68 @@ export class XQLinter { this.diagnosticCollectionXQuery.set(uri, diagnostics); } has(uri: vscode.Uri): boolean { - return this.diagnosticCollectionXQuery.has(uri); + return this.xqlintCollection.has(uri.toString()); } - update(uri: vscode.Uri, document: string) { - const xqlint = linter(uri, document); - this.xqlintCollectionXQuery.set(uri.toString(), xqlint); - this.diagEmitter.fire(new ParsedEvent(uri, xqlint)) + update(doc: TextDocument) { + const xqlint = linter(doc.uri, doc.getText()); + this.xqlintCollection.set(doc.uri.toString(), xqlint); + this.diagEmitter.fire(new ParsedEvent(doc.uri, xqlint)) } xqlint(uri: vscode.Uri): XQLint { - const xq = this.xqlintCollectionXQuery.get(uri.toString()); + const xq = this.xqlintCollection.get(uri.toString()); if (xq) { return xq; } else { - throw { name: "NOXQLINT", message: "should not happen" }; + throw { name: "NOXQLINT", message: uri.fsPath }; } } - + xqlint2(doc: TextDocument): XQLint { + if (!this.has(doc.uri)) { + this.update(doc); + } + return this.xqlintCollection.get(doc.uri.toString()); + } } + +// do the parse function linter(uri: vscode.Uri, document: string) { const processor = Configuration.xqueryProcessor; const opts = { "processor": processor, "fileName": uri.fsPath }; return new XQLint(document, opts); + } /** * Analyzes the xquery document for problems. * @param doc xquery document to analyze - * @param xqueryDiagnostics diagnostic collection + * @param xqLinters diagnostic collection */ export function refreshDiagnostics(doc: vscode.TextDocument, - xqueryDiagnostics: XQLinter, + xqLinters: XQLinters, reason: string): void { if (isNotXQDoc(doc)) return; const editor = findEditor(doc); - const isNew = !xqueryDiagnostics.has(doc.uri); + const isNew = !xqLinters.has(doc.uri); const refresh = reason === "change"; channel.log((isNew ? "🆕" : "") + (refresh ? "♻️" : "") + "refreshDiagnostics " + reason + " " + doc.uri.toString()); if (isNew || refresh) { - const text = doc.getText(); - xqueryDiagnostics.update(doc.uri, text); - const xqlint = xqueryDiagnostics.xqlint(doc.uri); - const diagnostics = new Array(); + xqLinters.update(doc); + const xqlint = xqLinters.xqlint(doc.uri); + const diagnostics = new Array(); + pushXQLintDiagnostics(diagnostics, xqlint); - xqueryDiagnostics.set(doc.uri, diagnostics); + xqLinters.set(doc.uri, diagnostics); channel.log("diagnostics.length: " + diagnostics.length); } - if (editor) { - const xqlint = xqueryDiagnostics.xqlint(doc.uri); - decorate(editor, xqlint); - } + } // forward doc changes -export function subscribeToDocumentChanges(context: vscode.ExtensionContext, xqueryDiagnostics: XQLinter): void { +export function subscribeToDocumentChanges(context: vscode.ExtensionContext, xqueryDiagnostics: XQLinters): void { const ed = vscode.window.activeTextEditor; if (ed && !unsupportedScheme(ed.document.uri)) { refreshDiagnostics(ed.document, xqueryDiagnostics, "current"); @@ -135,26 +145,20 @@ export function subscribeToDocumentChanges(context: vscode.ExtensionContext, xqu function pushXQLintDiagnostics( diagnostics: vscode.Diagnostic[], - linter: XQLint): vscode.Diagnostic[] { - - linter.getErrors().forEach((error: Marker) => { - diagnostics.push(new vscode.Diagnostic( - importRange(error.pos), - error.message, - isSuppressed(error.message) ? vscode.DiagnosticSeverity.Information : vscode.DiagnosticSeverity.Error - )); - }); - - linter.getWarnings().forEach((warning: Marker) => { - diagnostics.push(new vscode.Diagnostic( - importRange(warning.pos), - warning.message, - vscode.DiagnosticSeverity.Warning - )); - }); - return diagnostics; -} + linter: XQLint) { + linter.getMarkers().forEach( + (mark: Marker) => { + const type = mark.level === "error" ? vscode.DiagnosticSeverity.Error : vscode.DiagnosticSeverity.Warning + diagnostics.push(new vscode.Diagnostic( + importRange(mark.pos), + mark.message, + isSuppressed(mark.message) ? vscode.DiagnosticSeverity.Information : type + )); + } + ); + +} // [XQST0059] module "http://config" not found // [XPST0008] "list-details#0": undeclared function @@ -162,35 +166,4 @@ function isSuppressed(msg: string): boolean { const errs = Configuration.xquerySuppressErrors; return errs.some((x) => msg.includes(x)); } -const parseFailedDecorationType = vscode.window.createTextEditorDecorationType({ - borderWidth: '1px', - borderStyle: 'solid', - - overviewRulerColor: 'red', - overviewRulerLane: vscode.OverviewRulerLane.Right, - - light: { - // this color will be used in light color themes - borderColor: 'darkred', - backgroundColor: 'lightpink', - }, - dark: { - // this color will be used in dark color themes - borderColor: 'lightred', - backgroundColor: 'deeppink', - } -}); - - -function decorate(editor: vscode.TextEditor, xqlint: XQLint) { - const theDecorations: vscode.DecorationOptions[] = []; - if (xqlint.hasSyntaxError()) { - const r = xqlint.getErrors(); - const range1 = importRange(r[0].pos); - const lastLine = editor.document.lineAt(editor.document.lineCount - 1); - const range = range1.with(range1.end, lastLine.range.end) - const decoration = { range: range, hoverMessage: 'Parse failed at line:' + range1.end.line }; - theDecorations.push(decoration); - } - editor.setDecorations(parseFailedDecorationType, theDecorations); -} + diff --git a/src/xquery-cmds/executeXQuery.ts b/src/xquery-cmds/executeXQuery.ts index 8137479..b9f06a9 100644 --- a/src/xquery-cmds/executeXQuery.ts +++ b/src/xquery-cmds/executeXQuery.ts @@ -2,24 +2,27 @@ import { OutputChannel, window } from "vscode"; import { TextEditor, TextEditorEdit } from "vscode"; import * as constants from "../constants"; -import { channel,logdate } from "../common/channel-basex"; +import { channel, logdate } from "../common/channel-basex"; import { ChildProcess } from "../common/child-process"; import { Configuration, NativeCommands } from "../common"; -let outputChannel:OutputChannel; +let outputChannel: OutputChannel; export async function executeXQuery(editor: TextEditor, edit: TextEditorEdit): Promise { - if(!outputChannel) outputChannel = window.createOutputChannel("XQuery execution"); - - if (editor.document.languageId !== constants.languageIds.xquery) { - window.showErrorMessage("This action can only be performed on an XQuery file."); + const canEval = [constants.languageIds.xquery, + constants.languageIds.bxsCmd, + constants.languageIds.bxsXml]; + if (!canEval.includes(editor.document.languageId)) { + window.showErrorMessage("XQuery execute not supported for filetype."); return; } - const src:string=editor.document.uri.toString(); - channel.log("executeXQuery:" +src); + if (!outputChannel) outputChannel = window.createOutputChannel("XQuery execution"); + + const src: string = editor.document.uri.toString(); + channel.log("executeXQuery:" + src); const executable = Configuration.xqueryExecutionEngine; - const args :string[] = [src]; + const args: string[] = [src]; if (!executable || executable === "") { const action = await window.showWarningMessage("An XQuery execution engine has not been defined.", "Define Now"); if (action === "Define Now") { @@ -30,20 +33,20 @@ export async function executeXQuery(editor: TextEditor, edit: TextEditorEdit): P const disposable = window.setStatusBarMessage("XQuery start execution..."); //outputChannel.clear(); - - outputChannel.appendLine(`${ logdate() } XQuery: ${ src }`); + + outputChannel.appendLine(`${logdate()} XQuery: ${src}`); outputChannel.append("\n"); try { const bl = await ChildProcess.spawn('basex', args); outputChannel.appendLine(bl.toString()); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } catch (e:any) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } catch (e: any) { outputChannel.appendLine(e.toString()); outputChannel.appendLine(e.stdout.toString()); outputChannel.appendLine(e.stderr.toString()); window.showErrorMessage("Xquery error - see channel"); - } + } disposable.dispose(); outputChannel.show(false); } diff --git a/src/xquery-cmds/xqcmds.ts b/src/xquery-cmds/xqcmds.ts index 9f6b33d..aa8d608 100644 --- a/src/xquery-cmds/xqcmds.ts +++ b/src/xquery-cmds/xqcmds.ts @@ -2,25 +2,25 @@ import { TextEditor, Selection, window, QuickPickItem } from "vscode"; import { channel } from "../common/channel-basex"; import { Configuration, importRange } from "../common"; -import { diagnosticCollectionXQuery } from "../extension"; +import { xqLinters } from "../extension"; import { findNode } from "../common/xqlint"; -import { profiles, Profile} from '@quodatum/xqlint'; +import { profiles, Profile } from '@quodatum/xqlint'; export async function setProcessor(): Promise { const processor = Configuration.xqueryProcessor; - const items:PickProfile[]=profiles().map(item => new PickProfile(item,processor)); - const pick=await window.showQuickPick(items,{title:"Select XQuery profile: "+processor}); - if(pick) { + const items: PickProfile[] = profiles().map(item => new PickProfile(item, processor)); + const pick = await window.showQuickPick(items, { title: "Select XQuery profile: " + processor }); + if (pick) { channel.log("setProcessor:" + pick.id); Configuration.xqueryProcessor = pick.id; - } + } } // select enclosing declaration export function selectDeclaration(textEditor: TextEditor): void { channel.log("selectDeclaration:"); - const linter = diagnosticCollectionXQuery.xqlint(textEditor.document.uri); + const linter = xqLinters.xqlint(textEditor.document.uri); const pos = textEditor.selection.start; const node = linter.getAST(pos); const n2 = findNode(node, "AnnotatedDecl"); @@ -35,11 +35,16 @@ export function selectDeclaration(textEditor: TextEditor): void { } // about the library ; -export function libraryInfo(textEditor: TextEditor): void { - const linter = diagnosticCollectionXQuery.xqlint(textEditor.document.uri); - const lib=linter.getLibrary(); - console.log("todo: ", lib ); - window.showInformationMessage("libraryInfo @todo") +export async function libraryInfo(textEditor: TextEditor): Promise { + const linter = xqLinters.xqlint(textEditor.document.uri); + const lib = linter.getLibrary(); + const pick = await window.showQuickPick(Object.keys(lib), + { title: "Select namespace from profile library" }); + if (pick) { + //lib[pick].functions["http://basex.org/modules/admin#logs#0"] + console.log("todo: ", (lib as any)[pick ]); + window.showInformationMessage("libraryInfo: " + pick); + } } class PickProfile implements QuickPickItem { @@ -48,10 +53,10 @@ class PickProfile implements QuickPickItem { picked: boolean; id: string; - constructor(item:Profile,current :string) { - this.label = `$(package) ${item.id}`; - this.description=item.description; - this.id=item.id - this.picked=item.id===current; // not supported? + constructor(item: Profile, current: string) { + this.label = `$(package) ${item.id}`; + this.description = item.description; + this.id = item.id + this.picked = item.id === current; // not supported? } - } +} From 1978bc2f6bd8f0668b44c6d75a50de6d39755a4c Mon Sep 17 00:00:00 2001 From: Andy Bunce Date: Thu, 14 Dec 2023 21:59:52 +0000 Subject: [PATCH 7/8] [mod] symbols outline --- CHANGELOG.md | 3 +- package-lock.json | 44 ++++++++++++------------- src/providers/symbols.ts | 70 ++++++++++++++++++++++++---------------- 3 files changed, 66 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80ada2c..a98b6f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,5 @@ -# 0.2.6 (2023-12-05) +# 0.2.6 (2023-12-14) +* Nested outline * Improve hovers * goto definition (current file only) # 0.2.5 (2023-11-20) diff --git a/package-lock.json b/package-lock.json index d28aaea..3ebc477 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "vscode-basex", - "version": "0.2.5", + "version": "0.2.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "vscode-basex", - "version": "0.2.5", + "version": "0.2.6", "license": "MIT", "dependencies": { "@quodatum/xqlint": "^0.5.1", @@ -420,9 +420,9 @@ } }, "node_modules/@eslint/eslintrc": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.3.tgz", - "integrity": "sha512-yZzuIG+jnVu6hNSzFEN07e8BxF3uAzYtQb6uDkaYZLo6oYZDCq454c5kB8zxnzfCYyP4MIuyBn10L0DqwujTmA==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-2.1.4.tgz", + "integrity": "sha512-269Z39MS6wVJtsoUl10L60WdkhJVdPG24Q4eZTH3nnF6lpvSShEK3wQjDX9JRWAUPvPh7COouPpU9IrqaZFvtQ==", "dev": true, "dependencies": { "ajv": "^6.12.4", @@ -443,9 +443,9 @@ } }, "node_modules/@eslint/js": { - "version": "8.54.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.54.0.tgz", - "integrity": "sha512-ut5V+D+fOoWPgGGNj83GGjnntO39xDy6DWxO0wb7Jp3DcMX0TfIqdzHF85VTQkerdyGmuuMD9AKAo5KiNlf/AQ==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.55.0.tgz", + "integrity": "sha512-qQfo2mxH5yVom1kacMtZZJFVdW+E70mqHMJvVg6WTLo+VBuQJ4TojZlfWBjK0ve5BdEeNAVxOsl/nvNMpJOaJA==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -604,9 +604,9 @@ "dev": true }, "node_modules/@types/vscode": { - "version": "1.84.2", - "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.84.2.tgz", - "integrity": "sha512-LCe1FvCDMJKkPdLVGYhP0HRJ1PDop2gRVm/zFHiOKwYLBRS7vEV3uOOUId4HMV+L1IxqyS+IZXMmlSMRbZGIAw==", + "version": "1.85.0", + "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.85.0.tgz", + "integrity": "sha512-CF/RBon/GXwdfmnjZj0WTUMZN5H6YITOfBCP4iEZlOtVQXuzw6t7Le7+cR+7JzdMrnlm7Mfp49Oj2TuSXIWo3g==", "dev": true }, "node_modules/@types/xmldom": { @@ -994,9 +994,9 @@ } }, "node_modules/bl": { - "version": "6.0.8", - "resolved": "https://registry.npmjs.org/bl/-/bl-6.0.8.tgz", - "integrity": "sha512-HCRq8z0+3vrGCjEKrbnK6blpDZ1xzhfZKCCuyvPC7upGcfXZSmaCumpVao/jC8o1hs/fOqJoCSPMabl+CQTPXg==", + "version": "6.0.9", + "resolved": "https://registry.npmjs.org/bl/-/bl-6.0.9.tgz", + "integrity": "sha512-Vh+M9HMfeTST9rkkQ1utRnOeABNcBO3i0dJMFkenCv7JIp76XWx8uQOGpaXyXVyenrLDZsdAHXbf0Cz18Eb0fw==", "dependencies": { "buffer": "^6.0.3", "inherits": "^2.0.4", @@ -1334,15 +1334,15 @@ } }, "node_modules/eslint": { - "version": "8.54.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.54.0.tgz", - "integrity": "sha512-NY0DfAkM8BIZDVl6PgSa1ttZbx3xHgJzSNJKYcQglem6CppHyMhRIQkBVSSMaSRnLhig3jsDbEzOjwCVt4AmmA==", + "version": "8.55.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.55.0.tgz", + "integrity": "sha512-iyUUAM0PCKj5QpwGfmCAG9XXbZCWsqP/eWAWrG/W0umvjuLRBECwSFdt+rCntju0xEH7teIABPwXpahftIaTdA==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", - "@eslint/eslintrc": "^2.1.3", - "@eslint/js": "8.54.0", + "@eslint/eslintrc": "^2.1.4", + "@eslint/js": "8.55.0", "@humanwhocodes/config-array": "^0.11.13", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", @@ -1726,9 +1726,9 @@ } }, "node_modules/globals": { - "version": "13.23.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.23.0.tgz", - "integrity": "sha512-XAmF0RjlrjY23MA51q3HltdlGxUpXPvg0GioKiD9X6HD28iMjo2dKC8Vqwm7lne4GNr78+RHTfliktR6ZH09wA==", + "version": "13.24.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.24.0.tgz", + "integrity": "sha512-AhO5QUcj8llrbG09iWhPU2B204J1xnPeL8kQmVorSsy+Sjj1sk8gIyh6cUocGmH4L0UuhAJy+hJMRA4mgA4mFQ==", "dev": true, "dependencies": { "type-fest": "^0.20.2" diff --git a/src/providers/symbols.ts b/src/providers/symbols.ts index b71f97b..6034c60 100644 --- a/src/providers/symbols.ts +++ b/src/providers/symbols.ts @@ -1,11 +1,11 @@ -import { VarDecl, FunDecl} from '@quodatum/xqlint'; +import { VarDecl, FunDecl } from '@quodatum/xqlint'; import { SymbolKind, DocumentSymbol, DocumentSymbolProvider, WorkspaceSymbolProvider, - Position, Location,Uri,TextDocument, CancellationToken, + Position, Location, Uri, TextDocument, CancellationToken, ExtensionContext, languages, SymbolInformation } from 'vscode'; -import { channel,importRange } from "../common"; +import { channel, importRange } from "../common"; import { languageIds } from "../constants"; import { xqLinters } from "../extension"; // @@ -31,7 +31,7 @@ class WorkspaceSymbols implements WorkspaceSymbolProvider { name: "fred", containerName: "", kind: SymbolKind.Interface, - location: new Location(Uri.parse("file://aa"),new Position(0,0)) + location: new Location(Uri.parse("file://aa"), new Position(0, 0)) }; symbols.push(si) return symbols; @@ -45,35 +45,49 @@ export class DocumentSymbols implements DocumentSymbolProvider { ): Promise => { channel.log("DocumentSymbols: " + document.uri); - const symbols: DocumentSymbol[] = []; - const linter = xqLinters.xqlint(document.uri); + const linter = xqLinters.xqlint(document.uri); const xqdoc = linter.getXQDoc(true); channel.log("got xqdoc"); - xqdoc.variables.forEach(function (v: VarDecl): void { - const name = "$" + v.name; - const description = v?.description; - //channel.log(name + v); - const range = importRange( v.pos ); - const info = new DocumentSymbol(name, description, SymbolKind.Variable, range, range); - symbols.push(info); - }); - xqdoc.functions.forEach(function (f: FunDecl) { - const name = f.name + "#" + f.params.length; - const description = f?.description; - //channel.log(name ); - const range = importRange( f.pos ); - const info = new DocumentSymbol(name, description, SymbolKind.Function, range, range); - // info.children=[]; - // f.params.forEach(function(paramName: string){ - // info.children.push(makeSymbol(paramName, "", SymbolKind.Variable, f.pos)) - // }); - symbols.push(info); - }); - if(xqdoc.queryBody){ - const range= importRange( xqdoc.queryBody ); + const symbols: DocumentSymbol[] = []; + if (xqdoc.variables.length > 0) { + const vars: DocumentSymbol[] = []; + xqdoc.variables.forEach(function (v: VarDecl): void { + const name = "$" + v.name; + const description = v?.description; + //channel.log(name + v); + const range = importRange(v.pos); + const info = new DocumentSymbol(name, description, SymbolKind.Variable, range, range); + vars.push(info); + }); + const r = importRange(xqdoc.variables[0].pos); + const vs = new DocumentSymbol("Variables", "" + xqdoc.variables.length, SymbolKind.Class, r, r); + vs.children = vars; + symbols.push(vs); + } + if (xqdoc.functions.length > 0) { + const fns: DocumentSymbol[] = []; + xqdoc.functions.forEach(function (f: FunDecl) { + const name = f.name + "#" + f.params.length; + const description = f?.description; + //channel.log(name ); + const range = importRange(f.pos); + const info = new DocumentSymbol(name, description, SymbolKind.Function, range, range); + // info.children=[]; + // f.params.forEach(function(paramName: string){ + // info.children.push(makeSymbol(paramName, "", SymbolKind.Variable, f.pos)) + // }); + fns.push(info); + }); + const r = importRange(xqdoc.functions[0].pos); + const vs = new DocumentSymbol("Functions", "" + xqdoc.functions.length, SymbolKind.Class, r, r); + vs.children = fns; + symbols.push(vs); + } + if (xqdoc.queryBody) { + const range = importRange(xqdoc.queryBody); const q = new DocumentSymbol("querybody", "", SymbolKind.Package, range, range); symbols.push(q); } From d1690e94946a8341e27fbb08b8a2815c49937117 Mon Sep 17 00:00:00 2001 From: Andy Bunce Date: Sun, 31 Dec 2023 16:08:16 +0000 Subject: [PATCH 8/8] [mod] 0.2.7 --- .vscode/settings.json | 2 +- CHANGELOG.md | 4 ++++ README.md | 8 +++++--- package-lock.json | 22 +++++++++++----------- package.json | 12 ++++++------ src/common/configuration.ts | 8 ++++---- src/common/document-selectors.ts | 11 ++++++++--- src/common/xqlint.ts | 25 ++++++++++++++----------- src/constants.ts | 7 ++----- src/extension.ts | 4 ++-- src/providers/activate.ts | 2 +- src/providers/definition.ts | 26 ++++++++++++++++++-------- src/providers/symbols.ts | 4 ++-- src/statusbar.ts | 4 ++-- src/xqlints.ts | 11 +++++++---- src/xquery-cmds/xqcmds.ts | 4 ++-- 16 files changed, 89 insertions(+), 65 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 333e486..64a972f 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -9,5 +9,5 @@ "yaml.schemas": { "https://json.schemastore.org/mkdocs-1.0.json": "file:///c%3A/Users/mrwhe/git/vscode-basex/mkdocs.yml" }, - "basexTools.xquery.processor": "basex-10" + "basexTools.xquery.processor": "basex-9" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index a98b6f0..dda3d2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,11 @@ +# 0.2.7 (2023-12-31) +* goto definition for imported sources +* rename cmd `basexTools.xquery.processor` to `basexTools.xquery.profile` # 0.2.6 (2023-12-14) * Nested outline * Improve hovers * goto definition (current file only) + # 0.2.5 (2023-11-20) * support otherwise/ ?: * xqlint 0.5.0 diff --git a/README.md b/README.md index 2190120..4a7c2b6 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ See the [documentation](https://quodatum.github.io/vscode-basex/) for more detai * [source formating] * [Symbols] * [Snippets] +* [Goto definition] ## XPath * [XPath Evaluation] ## XML @@ -53,8 +54,8 @@ npm run compile vsce package ``` ## Documentation -Uses https://github.com/squidfunk/mkdocs-material -https://quodatum.github.io/basex-xqparse/i-BaseX.xhtml#ArrowFunctionSpecifier +Uses [mkdocs-material](https://github.com/squidfunk/mkdocs-material) + # Inspiration ## VSCode @@ -63,7 +64,8 @@ This project was created from a fork of [DotJoshJohnson/vscode-xml](https://gith The code parsing uses [quodatum/xqlint](https://github.com/Quodatum/xqlint) which a fork of [wcandillon/xqlint](https://github.com/wcandillon/xqlint). These both make use of Gunther Rademacher's [REx](https://www.bottlecaps.de/rex/) Parser Generator. -## Icon +The EBNF is shown [here](https://quodatum.github.io/basex-xqparse/i-BaseX.xhtml) +## Icons Icons used in the XML Tree View are used under the Creative Commons 3.0 BY license. * "Code" icon by Dave Gandy from www.flaticon.com diff --git a/package-lock.json b/package-lock.json index 3ebc477..181730d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "0.2.6", "license": "MIT", "dependencies": { - "@quodatum/xqlint": "^0.5.1", + "@quodatum/xqlint": "^0.6.0", "@xmldom/xmldom": "^0.8.10", "bl": "^6.0.4", "xpath": "^0.0.33" @@ -443,9 +443,9 @@ } }, "node_modules/@eslint/js": { - "version": "8.55.0", - "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.55.0.tgz", - "integrity": "sha512-qQfo2mxH5yVom1kacMtZZJFVdW+E70mqHMJvVg6WTLo+VBuQJ4TojZlfWBjK0ve5BdEeNAVxOsl/nvNMpJOaJA==", + "version": "8.56.0", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-8.56.0.tgz", + "integrity": "sha512-gMsVel9D7f2HLkBma9VbtzZRehRogVRfbr++f06nL2vnCGCNlzOD+/MUov/F4p8myyAHspEhVobgjpX64q5m6A==", "dev": true, "engines": { "node": "^12.22.0 || ^14.17.0 || >=16.0.0" @@ -528,9 +528,9 @@ } }, "node_modules/@quodatum/xqlint": { - "version": "0.5.1", - "resolved": "https://registry.npmjs.org/@quodatum/xqlint/-/xqlint-0.5.1.tgz", - "integrity": "sha512-nogRqQF7z3F6ETeD0RaTe5wa32mtH28MF4MGzm5bdWCzGr17+UH5CtXvu0WP/3oxDZWNt+0PAyAlZERxLLiQ8Q==", + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@quodatum/xqlint/-/xqlint-0.6.0.tgz", + "integrity": "sha512-xjkYCZ47mjwaordye5RUdSLcE5hYYwONK3MO0EPIm4pnlagHh4nzSGS6qXVj+2qjwqP9uw0Yhw/q4FxT7dnMMQ==", "dependencies": { "@quodatum/xq-catalogs": "0.1.1", "colors": "1.4.0", @@ -1334,15 +1334,15 @@ } }, "node_modules/eslint": { - "version": "8.55.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.55.0.tgz", - "integrity": "sha512-iyUUAM0PCKj5QpwGfmCAG9XXbZCWsqP/eWAWrG/W0umvjuLRBECwSFdt+rCntju0xEH7teIABPwXpahftIaTdA==", + "version": "8.56.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.56.0.tgz", + "integrity": "sha512-Go19xM6T9puCOWntie1/P997aXxFsOi37JIHRWI514Hc6ZnaHGKY9xFhrU65RT6CcBEzZoGG1e6Nq+DT04ZtZQ==", "dev": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", "@eslint/eslintrc": "^2.1.4", - "@eslint/js": "8.55.0", + "@eslint/js": "8.56.0", "@humanwhocodes/config-array": "^0.11.13", "@humanwhocodes/module-importer": "^1.0.1", "@nodelib/fs.walk": "^1.2.8", diff --git a/package.json b/package.json index d096b1c..ffe91ab 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "vscode-basex", "displayName": "BaseX tools", "description": "BaseX tools: XQuery, XML, XPath Tools for Visual Studio Code", - "version": "0.2.6", + "version": "0.2.7", "preview": true, "publisher": "quodatum", "author": "Andy Bunce (https://github.com/Quodatum)", @@ -57,9 +57,9 @@ ], "commands": [ { - "command": "basexTools.processor", - "title": "BaseX Tools: get/set XQuery processor", - "shortTitle": "XQuery processor" + "command": "basexTools.profile", + "title": "BaseX Tools: get/set XQuery profile", + "shortTitle": "XQuery profile" }, { "command": "basexTools.xqParse", @@ -132,7 +132,7 @@ "order": 1, "title": "XQuery UI", "properties": { - "basexTools.xquery.processor": { + "basexTools.xquery.profile": { "type": "string", "default": "basex-10", "description": "Identifier for the XQuery profile. Determines available modules" @@ -428,7 +428,7 @@ "typescript": "^4.7.3" }, "dependencies": { - "@quodatum/xqlint": "^0.5.1", + "@quodatum/xqlint": "^0.6.0", "@xmldom/xmldom": "^0.8.10", "bl": "^6.0.4", "xpath": "^0.0.33" diff --git a/src/common/configuration.ts b/src/common/configuration.ts index b7d7873..28e18b2 100644 --- a/src/common/configuration.ts +++ b/src/common/configuration.ts @@ -39,11 +39,11 @@ export class Configuration { return this._getForWindow("xquery.executionEngine"); } - static get xqueryProcessor(): string { - return this._getForWindow("xquery.processor"); + static get xqueryProfile(): string { + return this._getForWindow("xquery.profile"); } - static set xqueryProcessor(value: string) { - this._setForWindow("xquery.processor",value); + static set xqueryProfile(value: string) { + this._setForWindow("xquery.profile",value); } static xqueryShowHovers(): boolean { return this._getForWindow("xquery.showHovers"); diff --git a/src/common/document-selectors.ts b/src/common/document-selectors.ts index 360121d..28e51b8 100644 --- a/src/common/document-selectors.ts +++ b/src/common/document-selectors.ts @@ -1,11 +1,16 @@ import { DocumentFilter, Uri, TextDocument ,TextEditor} from "vscode"; import * as constants from "../constants"; +// eslint-disable-next-line @typescript-eslint/no-namespace +export namespace uriSchemes { + export const file = "file"; + export const untitled = "untitled"; +} export function createDocumentSelector(language: string): DocumentFilter[] { return [ - { language: language, scheme: constants.uriSchemes.file }, - { language: language, scheme: constants.uriSchemes.untitled }, + { language: language, scheme: uriSchemes.file }, + { language: language, scheme: uriSchemes.untitled }, ]; } @@ -19,7 +24,7 @@ export function isNotXQDoc(doc: TextDocument): boolean { } // only supported schemes export function unsupportedScheme(uri: Uri): boolean { - const supportedSchemes = [constants.uriSchemes.file, constants.uriSchemes.untitled]; + const supportedSchemes = [uriSchemes.file, uriSchemes.untitled]; return supportedSchemes.indexOf(uri.scheme) === -1; } diff --git a/src/common/xqlint.ts b/src/common/xqlint.ts index 18e70ca..f3073e7 100644 --- a/src/common/xqlint.ts +++ b/src/common/xqlint.ts @@ -1,4 +1,4 @@ -import { Ast, LintRange, Sctx, XQLint } from "@quodatum/xqlint"; +import { Ast, LintRange, QName, Sctx, XQLint } from "@quodatum/xqlint"; import { Position, Range, MarkdownString } from "vscode"; @@ -30,21 +30,22 @@ export interface What { path: string[]; // AST type: WhatType; value: string; + qname?: QName display?: string; get: unknown; } // export enum WhatType{ - other, - WS, - VarRef, - FunctionCall, - NamedFunctionRef, - SequenceType, - Annotation, - Constructor, - StringConstructor, - Literal + other="other", + WS="WS", + VarRef="VarRef", + FunctionCall="FunctionCall", + NamedFunctionRef="NamedFunctionRef", + SequenceType="SequenceType", + Annotation="Annotation", + Constructor="Constructor", + StringConstructor="StringConstructor", + Literal="Literal" } // metadata about given AST node {type:,path:} export function inspectAst(linter: XQLint, position: Position): What { @@ -74,6 +75,7 @@ export function inspectAst(linter: XQLint, position: Position): What { } else if (ps.startsWith("EQName/VarName/VarRef/")) { r.type = WhatType.VarRef; const qname = sctx.resolveQName(r.value, position); + r.qname=qname; const v = sctx.getVariable(qname); r.value = '$' + r.value; r.get = v; @@ -125,6 +127,7 @@ function getArity(node: Ast): number { function fnType(r: What, arity: number, sctx: Sctx, position: Position) { r.type = WhatType.FunctionCall; const qname = sctx.resolveQName(r.value, position); + r.qname=qname; const lib = sctx.getFunction(qname, arity); r.get = lib; let result = lib.return; diff --git a/src/constants.ts b/src/constants.ts index b8d3d8f..357e999 100644 --- a/src/constants.ts +++ b/src/constants.ts @@ -3,7 +3,7 @@ export namespace commands { export const xqExecute = "basexTools.executeXQuery"; export const xqDoc = "basexTools.xqDoc"; // used as url scheme export const xqParse = "basexTools.xqParse"; // used as url scheme - export const xqProcessor = "basexTools.processor"; + export const xqProcessor = "basexTools.profile"; export const xqSelectDeclaration = "basexTools.selectDeclaration"; export const xqLibrary = "basexTools.xqLibrary"; export const xqLintReport = "basexTools.xqLintReport"; @@ -46,10 +46,7 @@ export namespace stateKeys { export const xPathQueryLast = "xPathQueryLast"; } -export namespace uriSchemes { - export const file = "file"; - export const untitled = "untitled"; -} + export namespace views { export const xmlTreeView = "xmlTreeView"; diff --git a/src/extension.ts b/src/extension.ts index 3d6c13e..b714cbf 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -85,9 +85,9 @@ export function activate(context: ExtensionContext) { // if changes to processor then clear diagnostics workspace.onDidChangeConfiguration(event => { - if (affectsConfiguration(event,'xquery.processor')) { + if (affectsConfiguration(event,'xquery.profile')) { xqLinters.clear(); - window.showInformationMessage("XQuery profile now: " + Configuration.xqueryProcessor); + window.showInformationMessage("XQuery profile now: " + Configuration.xqueryProfile); } }) } diff --git a/src/providers/activate.ts b/src/providers/activate.ts index da9d670..df23816 100644 --- a/src/providers/activate.ts +++ b/src/providers/activate.ts @@ -12,7 +12,7 @@ export function activate(context: ExtensionContext,diagnosticCollectionXQuery:XQ symbols.activate(context); hover.activate(context); definition.activate(context); -// codeAction.activate(context,diagnosticCollectionXQuery); + codeAction.activate(context,diagnosticCollectionXQuery); completion.activate(context); documentLink.activate(context); formatter.activate(context); diff --git a/src/providers/definition.ts b/src/providers/definition.ts index 78c5d17..665a9d1 100644 --- a/src/providers/definition.ts +++ b/src/providers/definition.ts @@ -2,24 +2,34 @@ 'use strict'; import vscode from 'vscode'; -import { inspectAst, WhatType ,importRange} from "../common"; +import { inspectAst, WhatType, importRange } from "../common"; import { xqLinters } from "../extension"; import { languageIds } from '../constants'; export function activate(context: vscode.ExtensionContext) { - context.subscriptions.push(vscode.languages.registerDefinitionProvider( - { language: languageIds.xquery }, new XQueryDefinitionProvider() - )); + context.subscriptions.push(vscode.languages.registerDefinitionProvider( + { language: languageIds.xquery }, new XQueryDefinitionProvider() + )); } -const hasDef=[WhatType.FunctionCall,WhatType.VarRef]; + +const hasDef = [WhatType.FunctionCall, WhatType.NamedFunctionRef, WhatType.VarRef]; export class XQueryDefinitionProvider implements vscode.DefinitionProvider { public provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): vscode.Definition | Thenable { const linter = xqLinters.xqlint(document.uri); const what = inspectAst(linter, position); - if (! hasDef.includes(what.type)) return undefined; - const range=importRange(what.get.pos); - return new vscode.Location(document.uri, range.start); + if (!hasDef.includes(what.type)) return undefined; + const thisns = linter.getXQDoc().ns; + let targetDoc; + if (thisns === what.qname.uri) { //in current doc + targetDoc = document.uri; + } else { + const doclink = linter.getDocLinks().find(d => d.ns === what.qname.uri); + if (doclink) targetDoc = vscode.Uri.file(doclink.path); + } + if (!targetDoc) return undefined; + const range = importRange(what.get.pos); + return new vscode.Location(targetDoc, range.start); } } \ No newline at end of file diff --git a/src/providers/symbols.ts b/src/providers/symbols.ts index 6034c60..6a6f17a 100644 --- a/src/providers/symbols.ts +++ b/src/providers/symbols.ts @@ -63,7 +63,7 @@ export class DocumentSymbols implements DocumentSymbolProvider { vars.push(info); }); const r = importRange(xqdoc.variables[0].pos); - const vs = new DocumentSymbol("Variables", "" + xqdoc.variables.length, SymbolKind.Class, r, r); + const vs = new DocumentSymbol("Variables", "" + xqdoc.variables.length, SymbolKind.Variable, r, r); vs.children = vars; symbols.push(vs); } @@ -82,7 +82,7 @@ export class DocumentSymbols implements DocumentSymbolProvider { fns.push(info); }); const r = importRange(xqdoc.functions[0].pos); - const vs = new DocumentSymbol("Functions", "" + xqdoc.functions.length, SymbolKind.Class, r, r); + const vs = new DocumentSymbol("Functions", "" + xqdoc.functions.length, SymbolKind.Function, r, r); vs.children = fns; symbols.push(vs); } diff --git a/src/statusbar.ts b/src/statusbar.ts index e0abb9b..b59bbe5 100644 --- a/src/statusbar.ts +++ b/src/statusbar.ts @@ -21,7 +21,7 @@ export function activate({ subscriptions }: vscode.ExtensionContext, vscode.workspace.onDidChangeConfiguration(event => { //@todo scope? - if (affectsConfiguration(event,'xquery.processor')) { + if (affectsConfiguration(event,'xquery.profile')) { updateStatusBarItem(vscode.window.activeTextEditor); } }) @@ -29,7 +29,7 @@ export function activate({ subscriptions }: vscode.ExtensionContext, function updateStatusBarItem(active: vscode.TextEditor): void { if (isXqEditor(active)) { - const profile = Configuration.xqueryProcessor; + const profile = Configuration.xqueryProfile; myStatusBarItem.text = `$(package) ${profile}`; myStatusBarItem.tooltip = "Active XQuery profile, click to change" myStatusBarItem.show(); diff --git a/src/xqlints.ts b/src/xqlints.ts index 244bf9a..7c5e146 100644 --- a/src/xqlints.ts +++ b/src/xqlints.ts @@ -83,7 +83,7 @@ export class XQLinters { // do the parse function linter(uri: vscode.Uri, document: string) { - const processor = Configuration.xqueryProcessor; + const processor = Configuration.xqueryProfile; const opts = { "processor": processor, "fileName": uri.fsPath }; return new XQLint(document, opts); @@ -148,12 +148,15 @@ function pushXQLintDiagnostics( linter: XQLint) { linter.getMarkers().forEach( (mark: Marker) => { - const type = mark.level === "error" ? vscode.DiagnosticSeverity.Error : vscode.DiagnosticSeverity.Warning - diagnostics.push(new vscode.Diagnostic( + const type = mark.level === "error" ? vscode.DiagnosticSeverity.Error : vscode.DiagnosticSeverity.Warning; + const diag=new vscode.Diagnostic( importRange(mark.pos), mark.message, isSuppressed(mark.message) ? vscode.DiagnosticSeverity.Information : type - )); + ); + diag.code=mark.code; + diag.source="xqlint"; + diagnostics.push(diag); } ); diff --git a/src/xquery-cmds/xqcmds.ts b/src/xquery-cmds/xqcmds.ts index aa8d608..db162ba 100644 --- a/src/xquery-cmds/xqcmds.ts +++ b/src/xquery-cmds/xqcmds.ts @@ -7,12 +7,12 @@ import { findNode } from "../common/xqlint"; import { profiles, Profile } from '@quodatum/xqlint'; export async function setProcessor(): Promise { - const processor = Configuration.xqueryProcessor; + const processor = Configuration.xqueryProfile; const items: PickProfile[] = profiles().map(item => new PickProfile(item, processor)); const pick = await window.showQuickPick(items, { title: "Select XQuery profile: " + processor }); if (pick) { channel.log("setProcessor:" + pick.id); - Configuration.xqueryProcessor = pick.id; + Configuration.xqueryProfile = pick.id; } }