zorba-coders team mailing list archive
-
zorba-coders team
-
Mailing list archive
-
Message #04049
[Merge] lp:~paul-lucas/zorba/feature-ft_module into lp:~zorba-coders/zorba/zorba-experimental
Matthias Brantner has proposed merging lp:~paul-lucas/zorba/feature-ft_module into lp:~zorba-coders/zorba/zorba-experimental.
Requested reviews:
Zorba Coders (zorba-coders)
For more details, see:
https://code.launchpad.net/~paul-lucas/zorba/feature-ft_module/+merge/90021
create a try.zorba-xquery.com web interface for this branch
--
The attached diff has been truncated due to its size.
https://code.launchpad.net/~paul-lucas/zorba/feature-ft_module/+merge/90021
Your team Zorba Coders is requested to review the proposed merge of lp:~paul-lucas/zorba/feature-ft_module into lp:~zorba-coders/zorba/zorba-experimental.
=== modified file 'CMakeConfiguration.txt'
--- CMakeConfiguration.txt 2011-09-16 19:55:59 +0000
+++ CMakeConfiguration.txt 2012-01-25 00:12:28 +0000
@@ -70,10 +70,6 @@
SET(ZORBA_FOR_ONE_THREAD_ONLY OFF CACHE BOOL "compile zorba for single threaded use")
MESSAGE(STATUS "ZORBA_FOR_ONE_THREAD_ONLY: " ${ZORBA_FOR_ONE_THREAD_ONLY})
-# by default the zorba command line client is deactivated until it gets to a more stable and userfriendly state
-SET(ZORBA_WITH_DEBUGGER_CLIENT OFF CACHE BOOL "build and install zorbas command line debugger client")
-MESSAGE(STATUS "ZORBA_WITH_DEBUGGER_CLIENT: " ${ZORBA_WITH_DEBUGGER_CLIENT})
-
IF (DEFINED UNIX)
IF (NOT DEFINED ZORBA_HAVE_PTHREAD_H AND NOT DEFINED ZORBA_FOR_ONE_THREAD_ONLY)
MESSAGE(FATAL_ERROR "pthread is not available")
=== modified file 'CMakeLists.txt'
--- CMakeLists.txt 2011-10-09 13:56:39 +0000
+++ CMakeLists.txt 2012-01-25 00:12:28 +0000
@@ -417,13 +417,35 @@
# zorba versioning
SET(ZORBA_MAJOR_NUMBER "2")
-SET(ZORBA_MINOR_NUMBER "0")
-SET(ZORBA_PATCH_NUMBER "1")
+SET(ZORBA_MINOR_NUMBER "1")
+SET(ZORBA_PATCH_NUMBER "0")
SET(ZORBA_VERSION ${ZORBA_MAJOR_NUMBER}.${ZORBA_MINOR_NUMBER}.${ZORBA_PATCH_NUMBER})
MESSAGE(STATUS "Zorba version number: ${ZORBA_VERSION}")
-SET(ZORBA_MODULES_INSTALL_DIR "share/zorba-${ZORBA_VERSION}/modules"
- CACHE STRING "Path (relative to installdir) to modules" FORCE)
-MARK_AS_ADVANCED(ZORBA_MODULES_INSTALL_DIR)
+
+SET(ZORBA_LIB_DIRNAME "lib" CACHE STRING
+ "directory name for libs (may want to set to 'lib64' on 64-bit Linux platforms)")
+
+# Directories for modules and schemas. "Core" are those which are
+# shipped with Zorba and must be present for correct Zorba
+# functionality. "Non-core" are developed independently of Zorba and
+# have different version lifecycles.
+#
+# URI dir is for things resolved by URI - specifically modules (.xq
+# files) and schemas (.xsd files) - which are platform-
+# independent. Lib dir is for platform-specific files, specifically
+# shared libraries for module external functions.
+SET(ZORBA_NONCORE_URI_DIR "share/zorba/uris"
+ CACHE STRING "Path (relative to installdir) to non-core modules/schemas")
+MARK_AS_ADVANCED(ZORBA_NONCORE_URI_DIR)
+SET(ZORBA_CORE_URI_DIR "${ZORBA_NONCORE_URI_DIR}/core/${ZORBA_VERSION}"
+ CACHE STRING "Path (relative to installdir) to core modules/schemas")
+MARK_AS_ADVANCED(ZORBA_CORE_URI_DIR)
+SET(ZORBA_NONCORE_LIB_DIR "${ZORBA_LIB_DIRNAME}/zorba"
+ CACHE STRING "Path (relative to installdir) to non-core libraries")
+MARK_AS_ADVANCED(ZORBA_NONCORE_LIB_DIR)
+SET(ZORBA_CORE_LIB_DIR "${ZORBA_NONCORE_LIB_DIR}/core/${ZORBA_VERSION}"
+ CACHE STRING "Path (relative to installdir) to core libraries")
+MARK_AS_ADVANCED(ZORBA_CORE_LIB_DIR)
# add compiler variables
ADD_DEFINITIONS(${DEFINITIONS})
@@ -460,7 +482,7 @@
SET(ZORBA_CMAKE_DIR "cmake" CACHE STRING
"Relative path to CMake files in Zorba installation")
ELSE (WIN32)
- SET(ZORBA_CMAKE_DIR "share/zorba-${ZORBA_VERSION}/cmake" CACHE STRING
+ SET(ZORBA_CMAKE_DIR "share/cmake/zorba-${ZORBA_VERSION}" CACHE STRING
"Relative path to CMake files in Zorba installation")
ENDIF (WIN32)
@@ -534,4 +556,4 @@
# This dependency is zorba-only related, which is why it's added here
# and not within zorba-modules, which is for general use in other
# non-zorba modules.
-ADD_DEPENDENCIES(check_uris gen_diag_modules)
+ADD_DEPENDENCIES(check_core_uris gen_diag_modules)
=== modified file 'CPackSourceConfig.cmake.in'
--- CPackSourceConfig.cmake.in 2009-10-30 16:24:51 +0000
+++ CPackSourceConfig.cmake.in 2012-01-25 00:12:28 +0000
@@ -19,7 +19,7 @@
SET(CPACK_CMAKE_GENERATOR "Unix Makefiles")
SET(CPACK_GENERATOR "TGZ;TZ")
-SET(CPACK_IGNORE_FILES "test/coverity/;dist/;_CPack_Packages/;build/;build./;CVS/;/\\.svn/;\\.swp$;\\.#;/#")
+SET(CPACK_IGNORE_FILES "test/coverity/;dist/;_CPack_Packages/;build/;build./;CVS/;/\\.svn/;\\.swp$;\\.#;/#;\\.bzr/")
SET(CPACK_INSTALLED_DIRECTORIES "@CMAKE_SOURCE_DIR@;/")
SET(CPACK_INSTALL_CMAKE_PROJECTS "")
SET(CPACK_MODULE_PATH "")
=== modified file 'ChangeLog'
--- ChangeLog 2011-10-20 23:05:55 +0000
+++ ChangeLog 2012-01-25 00:12:28 +0000
@@ -1,13 +1,58 @@
Zorba - The XQuery Processor
-version 2.x
-
- * Custom Full-text thesaurus.
- * Fixed bug #3401971 (node-by-reference on dynamic collections)
+version 2.2
+
+ * No-copy optimization: avoids copying nodes during node-constructor expressions.
+ * Added external function annotations %ann:propagates-input-nodes and
+ %ann:must-copy-input-nodes to be used by the no-copy optimization.
+ * Caching of results for recursive functions with atomic parameter and return types.
+ * Added %ann:cache and %ann:no-cache to enable or disable caching of results of functions with atomic parameter and return types.
+ * Fixed bug 917923 (bug in copying outer var values into the eval dynamic context)
+ * Fixed bug 909126 (bug in cloning of var_expr)
+ * Fixed bug in destruction of exit_catcher_expr
+ * Types-related optimization for the comparison operators
+ * Fixed bug #911585 (management of variables during eval)
+ * Fixed bug #866423 (fn:empty and fn:exists iterators must reset their input in
+ case of early-out)
+ * Added index management function to the C++ api's StaticCollectionManager.
+ * Fixed bug #905041 (allow for the default element and function namespaces to be
+ set multiple times via the c++ api).
+ * Fixed bug #907872 (segfault when returning an input ItemSequence from an external function).
+ * Fixed bug #905050 (setting and getting the context item type via the c++ api).
+ * Added createDayTimeDuration, createYearMonthDuration, createDocumentNode, createCommentNode, createPiNode to api's ItemFactory.
+ * Added split function to the string module that allows for streamable tokenization but doesn't have regular expression
+ support.
+ * zerr is not predeclared anymore to be http://www.zorba-xquery.com/errors
+ * Add new XQuery interface for the PHP bindings.
+ * Added API method Item::getNamespaceBindings().
+ * Added API method StaticContext::getNamespaceBindings() (see bug #905035)
+ * Deprecated StaticContext:getNamespaceURIByPrefix()
+
+version 2.1
+
+New Features:
+ * New node-position module. This module allows to obtain a representation of a node position, which
+ can be used to assess structural relationships with other nodes.
+ * New node-reference module. References can be obtained for any node, and
+ different nodes cannot have the same identifier.
+ * Custom Full-text thesaurus using Zorba URI resolver mechanism.
+ * Modified C++ API to add isSequential, getExternalVariables, isBoundContextItem and
+ isBoundExternalVariable Functions
+ * Collection allows to retrieve information about the type
+ and the annotations of a static collection.
+ * Implemented the probe-index-range-value for general indexes
+ * Added ExternalFunctionParameter class to be registered in the DynamicContext
+ * New module for compiling and executing XQueries from XQuery (xqxq)
+ * External functions are allowed to be updating (i.e. return a pending update list)
+
+Optimization:
* Optimization for positioned sequence access (e.g. $x[$x[1]] where $x is a
sequence of integers)
- * documentation improvements
- * installer improvements
+ * Optimization for count(collection()) expressions
+ * Optimization of the fn:substring function in the case when its $start and $length arguments
+ are integers
+
+Bug Fixes/Other Changes:
* Fixed bug #3403291 (build for Fedora 15)
* Fixed bug #3397293 (Incorrect XQueryX error message)
* Fixed bug #3398637 (Nested element constructors cause loss of namespace bindings)
@@ -15,20 +60,19 @@
* Fixed bug #3404689 (assignment problem in flwor)
* Fix for bug #3404450 (testdriver_mt problem: caching and validation of docs)
* Fixed installation bug to not install the .so for test modules
- * Fix for running ctest on Windows
* Fixed bug #3390410 (Adding a node to a collection causes out of bound in vector)
* Fixed bug #3406200 (node types were not being moved to new tree during node detach)
* Fixed bug #3406191 (Namespace bindings lost after update due to bug in node detach)
* Fixed bug #3290122 (ZDST0003 needs collection name)
- * Collection allows to retrieve information about the type
- and the annotations of a static collection.
* Fixed bug #3406272 (merging of adjacent text nodes must be done after all
updates have been applied).
+ * Don't raise warnings for unknown annotations.
* Fixed bug #3409344 (during detach, if the node being detached is the root of
its tree, it should be detached from the tree as well; otherwise memory
corruption will occur)
* Fixed bug # (Should not destroy the parent of a node that is being detached
before the detach is done).
+ * Added const qualifier to StaticContext::getAuditEvent()
* Fixed bug #3408181 (available-collection() returns undeclared collections)
* Fixed bug #859465 (Fatal error if a PUL contains two deactivate IC primitives)
* Fixed bug #859467 (Fatal error if a PUL contains two activate Foreign Key primitives)
@@ -36,11 +80,10 @@
* Fixed bug #859522 (Fatal error if a PUL contains two delete document primitives)
* Fixed bug #859968 (Using put on an attribute produces an invalid XDM instance and may cause segmentation faults)
* Fixed bug #855314 (should not fold a constant expr that returns an error item)
- * Added ExternalFunctionParameter class to be registered in the DynamicContext
+ * Fixed bug when parsing a document with a base-uri attribute.
* Fixed bug #863320 (Sentence is incorrectly incremented when token characters end without sentence terminator)
* Fixed bug #863730 (static delete-node* functions don't raise ZDDY0012)
- * Implemented the probe-index-range-value for general indexes
- * Fixed bug #867662 ("nullptr" warning)
+ * Removed ZSTR0005 and ZSTR0006 error codes
* Fixed bug #868258 (Assertion failure with two delete collection)
* Fixed bug #871623 and #871629 (assertion failures with insertions in dynamic collections)
* Fixed bug #867262 (allow reuse of iterator over ExtFuncArgItemSequence)
@@ -54,6 +97,36 @@
* Fixed bug #872796 (validate-in-place can interfere with other update primitives)
* Fixed bug #872799 (validate-in-place can set incorrect types)
* Fixed bug #855715 (Invalid escaped characters in regex not caught)
+ * Fixed bug #868325 (fn:analyze-string fails with some recursive subgroups)
+ * Fixed bug #872697 (segmentation fault with validation of NMTOKENS)
+ * General index cannot be declared as unique if the type of its key is
+ xs:anyAtomicType or xs:untypedAtomic.
+ * Added undo for node revalidation
+ * Optimization for count(collection()) expressions
+ * Fixed bug #867133 (SWIG PHP build failure on Mac OSX)
+ * Fixed bug #872796 (validate-in-place can interfere with other update primitives)
+ * Fixed bug #872799 (validate-in-place can set incorrect types)
+ * Fixed bug #872850 (Serialization of Tumbling Window For fails)
+ * Fixed bug #855715 (Invalid escaped characters in regex not caught)
+ * Fixed bug #862089 (Split binary/xq install directories for modules) by
+ splitting "module path" into separate URI and Library paths
+ * Fixed bug #872502 (validation of the JSON module xqdoc fails)
+ * Fixed bug #897619 (testdriver_mt can not run the XQueryX tests)
+ * Fixed bug #867107 (xqdoc dependency to zorba is wrong)
+ * Fixed bug #897616 (Fix the generation of the XQFTTS report results for
+ W3C)
+
+version 2.0.3
+ * Fixed bug #867662 ("nullptr" warning)
+ * documentation improvements
+
+version 2.0.2
+ * Fixed bug #3401971 (node-by-reference on dynamic collections)
+ * documentation improvements
+ * installer improvements
+ * Fixed bug #3403291 (build for Fedora 15)
+ * Don't install the .so for test modules
+ * Fix for running ctest on Windows
version 2.0.1
=== modified file 'NOTICE.txt'
--- NOTICE.txt 2011-10-19 15:28:51 +0000
+++ NOTICE.txt 2012-01-25 00:12:28 +0000
@@ -1,5 +1,5 @@
-----------
-Zorba 2.0.1
+Zorba 2.1.0
-----------
(Note: This file is generated automatically from NOTICE.xml.
=== modified file 'bin/CMakeLists.txt'
--- bin/CMakeLists.txt 2011-08-05 02:21:55 +0000
+++ bin/CMakeLists.txt 2012-01-25 00:12:28 +0000
@@ -15,33 +15,38 @@
INCLUDE_DIRECTORIES(AFTER ${CMAKE_SOURCE_DIR}/src/)
INCLUDE_DIRECTORIES(AFTER ${CMAKE_CURRENT_SOURCE_DIR})
-IF(ZORBA_WITH_DEBUGGER_CLIENT)
- CONFIGURE_FILE (debug_client/event_handler_init.cpp.in debug_client/event_handler_init.cpp)
-
- SET(DEBUG_CLIENT_SRCS
- debug_client/tuple.h
- debug_client/main.cpp
- debug_client/debug_command.h
- debug_client/debug_command.cpp
- debug_client/command_line_handler.h
- debug_client/command_line_handler.cpp
- debug_client/lock_free_queue.h
- debug_client/event_handler.h
- debug_client/event_handler.cpp
- ${CMAKE_CURRENT_BINARY_DIR}/debug_client/event_handler_init.cpp
+IF (ZORBA_WITH_DEBUGGER)
+ IF (NOT WIN32)
+ FIND_PACKAGE (Libedit)
+ IF (LIBEDIT_FOUND)
+ INCLUDE_DIRECTORIES (${LIBEDIT_INCLUDE_DIRS})
+ SET (LIBEDIT_LIBS ${LIBEDIT_LIBRARIES})
+ SET (ZORBA_HAVE_LIBEDIT_H ${LIBEDIT_FOUND})
+ ENDIF (LIBEDIT_FOUND)
+ ENDIF (NOT WIN32)
+
+ CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/debugger/config.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/debugger/config.h)
+ MESSAGE(STATUS "configured ${CMAKE_CURRENT_SOURCE_DIR}/debugger/config.h.cmake --> ${CMAKE_CURRENT_BINARY_DIR}/debugger/config.h")
+ INCLUDE_DIRECTORIES (BEFORE ${CMAKE_CURRENT_BINARY_DIR}/debugger)
+
+ SET (DEBUG_CLIENT_SRCS
+ debugger/main.cpp
+ debugger/xqdb_client.cpp
+ debugger/process_listener.cpp
+ debugger/command_prompt.cpp
+ debugger/command_line_handler.cpp
+ debugger/event_handler.cpp
)
- CONFIGURE_FILE (debug_client/message-handler.xq message-handler.xq)
-
- ZORBA_GENERATE_EXE("debuggercmd" "${DEBUG_CLIENT_SRCS}" "" "debugger" "bin")
-ENDIF(ZORBA_WITH_DEBUGGER_CLIENT)
+ ZORBA_GENERATE_EXE ("xqdb" "${DEBUG_CLIENT_SRCS}" "${LIBEDIT_LIBS}" "xqdb" "bin")
+ENDIF (ZORBA_WITH_DEBUGGER)
SET(SRCS
zorbacmd.cpp
zorbacmdproperties.cpp
error_printer.cpp
util.cpp
- module_path.cpp
+ path_util.cpp
)
INCLUDE("${CMAKE_SOURCE_DIR}/cmake_modules/ZorbaGenerateExe.cmake")
@@ -84,3 +89,37 @@
# test the --option option to set an option in the static context
ZORBA_ADD_TEST(bin/zorba_option zorbacmd -q "${CMAKE_CURRENT_SOURCE_DIR}/test/option.xq" -f --option "{http://www.zorba-xquery.com}option=value")
ZORBA_SET_TEST_PROPERTY(bin/zorba_option PASS_REGULAR_EXPRESSION "value")
+
+# test the --uri-path, --lib-path, and --module-path args.
+# Use the versioning tests as they utilize test modules already.
+SET (_testdir
+ "${CMAKE_CURRENT_SOURCE_DIR}/../test/rbkt/Queries/zorba/versioning")
+SET (_uridir "${CMAKE_BINARY_DIR}/TEST_URI_PATH")
+SET (_libdir "${CMAKE_BINARY_DIR}/TEST_LIB_PATH")
+ZORBA_ADD_TEST(bin/zorba_uri_path_1 zorbacmd -f -q "${_testdir}/import1.xq"
+ --uri-path "${_uridir}")
+ZORBA_SET_TEST_PROPERTY(bin/zorba_uri_path_1
+ PASS_REGULAR_EXPRESSION "hello, v2")
+
+ZORBA_ADD_TEST(bin/zorba_uri_path_2 zorbacmd -f -q "${_testdir}/external1.xq"
+ --uri-path "${_uridir}")
+ZORBA_SET_TEST_PROPERTY(bin/zorba_uri_path_2
+ PASS_REGULAR_EXPRESSION "ZXQP0008")
+
+ZORBA_ADD_TEST(bin/zorba_uri_path_3 zorbacmd -f -q "${_testdir}/external1.xq"
+ --uri-path "${_uridir}" --lib-path "${_libdir}")
+ZORBA_SET_TEST_PROPERTY(bin/zorba_uri_path_3
+ PASS_REGULAR_EXPRESSION "hello, v2")
+
+IF(WIN32)
+ SET(PATH_SEP ";")
+ELSE(WIN32)
+ SET(PATH_SEP ":")
+ENDIF(WIN32)
+ZORBA_ADD_TEST(bin/zorba_module_path_1 zorbacmd -f -q "${_testdir}/external1.xq"
+ --module-path "${_libdir}${PATH_SEP}${_uridir}")
+ZORBA_SET_TEST_PROPERTY(bin/zorba_module_path_1
+ PASS_REGULAR_EXPRESSION "hello, v2")
+
+# test compilation of the perf script
+ZORBA_ADD_TEST(bin/zorba_compilechk4 zorbacmd -q "${CMAKE_CURRENT_SOURCE_DIR}/../test/zperf/src/start.xq" -f --compile-only)
=== removed file 'bin/debug_client/debug_command.cpp'
--- bin/debug_client/debug_command.cpp 2011-07-01 01:53:24 +0000
+++ bin/debug_client/debug_command.cpp 1970-01-01 00:00:00 +0000
@@ -1,99 +0,0 @@
-/*
- * Copyright 2006-2008 The FLWOR Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <iostream>
-#include "debug_client/debug_command.h"
-
-namespace zorba { namespace debugclient {
-
-
- void CommandLine::execute()
- {
- for (;;) {
- std::cout << "zdb>> ";
- std::string command;
- std::getline(std::cin, command);
- std::vector<std::string> args;
- args << command;
- std::map<std::string, UntypedCommand*>::iterator lIter = theCommands.find(args[0]);
- if (lIter == theCommands.end()) {
- std::cout << args[0] << ": Command not found" << std::endl;
- continue;
- }
- if (!lIter->second->execute(args))
- continue;
- return;
- }
- }
-
-
- CommandLine::~CommandLine()
- {
- for (std::map<std::string, UntypedCommand*>::iterator i = theCommands.begin();
- i != theCommands.end(); ++i)
- {
- delete i->second;
- }
- }
-
- CommandLine& CommandLine::operator<<(UntypedCommand *aCommand)
- {
- theCommands.insert(std::make_pair(aCommand->get_name(), aCommand));
- return *this;
- }
-}}
-
-namespace std {
- vector<string>& operator<< (vector<string>& vec, const string& str)
- {
- string::size_type before = 0;
- string::size_type pos = str.find(" ", 0);
- while (pos != str.npos) {
- std::string lSub = str.substr(before, pos - before);
- if (lSub[0] == '"') {
- std::string::size_type lBeforeCopy = before;
- do {
- lBeforeCopy = str.find("\"", lBeforeCopy + 1);
- } while (pos != str.npos && str.size() > pos + 1 && str[pos + 1] == '\\');
- pos = lBeforeCopy;
- lSub = str.substr(before + 1, pos - before - 1);
- }
- vec.push_back(lSub);
- before = pos + 1;
- pos = str.find(" ", before);
- }
- std::string lSub = str.substr(before);
- if (lSub[0] == '"') {
- pos = str.find("\"", before + 1);
- lSub = str.substr(before + 1, pos - before - 1);
- }
- vec.push_back(lSub);
- return vec;
- }
-
- set<string>& operator<< (set<string>& vec, const string& str)
- {
- string::size_type before = 0;
- string::size_type pos = str.find(" ", 0);
- while (pos != str.npos) {
- vec.insert(str.substr(before, pos));
- before = pos + 1;
- pos = str.find(" ", before);
- }
- vec.insert(str.substr(before));
- return vec;
- }
-
-}
=== removed file 'bin/debug_client/event_handler_init.cpp.in'
--- bin/debug_client/event_handler_init.cpp.in 2011-07-01 01:53:24 +0000
+++ bin/debug_client/event_handler_init.cpp.in 1970-01-01 00:00:00 +0000
@@ -1,41 +0,0 @@
-/*
- * Copyright 2006-2008 The FLWOR Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <fstream>
-#include "debug_client/event_handler.h"
-
-namespace zorba { namespace debugclient {
-
- std::istream* EventHandler::getCurrentDirectory() {
- const char* build_dir = "@CMAKE_BINARY_DIR@/bin/message-handler.xq";
- const char* install_dir =
-#ifndef WIN32
- "@CMAKE_INSTALL_PREFIX@/bin/";
-#else
- "C:/Program Files/Zorba XQuery Processor @ZORBA_MAJOR_NUMBER@.@ZORBA_MINOR_NUMBER@.@ZORBA_PATCH_NUMBER@/bin/";
-#endif
- std::auto_ptr<std::ifstream> stream(new std::ifstream(build_dir));
- if (stream->good()) {
- return stream.release();
- }
- stream.reset(new std::ifstream(install_dir));
- if (stream->good()) {
- return stream.release();
- }
- return 0;
- }
-
-}} // end of namespace zorba::debugclient
-
=== removed file 'bin/debug_client/lock_free_queue.cpp'
--- bin/debug_client/lock_free_queue.cpp 2011-07-01 01:53:24 +0000
+++ bin/debug_client/lock_free_queue.cpp 1970-01-01 00:00:00 +0000
@@ -1,16 +0,0 @@
-/*
- * Copyright 2006-2008 The FLWOR Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include "lock_free_queue.h"
=== removed file 'bin/debug_client/message-handler.xq'
--- bin/debug_client/message-handler.xq 2011-08-26 23:36:24 +0000
+++ bin/debug_client/message-handler.xq 1970-01-01 00:00:00 +0000
@@ -1,165 +0,0 @@
-(:
- : Copyright 2006-2009 The FLWOR Foundation.
- :
- : Licensed under the Apache License, Version 2.0 (the "License");
- : you may not use this file except in compliance with the License.
- : You may obtain a copy of the License at
- :
- : http://www.apache.org/licenses/LICENSE-2.0
- :
- : Unless required by applicable law or agreed to in writing, software
- : distributed under the License is distributed on an "AS IS" BASIS,
- : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- : See the License for the specific language governing permissions and
- : limitations under the License.
-:)
-
-import module namespace refl = 'http://www.zorba-xquery.com/modules/reflection';
-import module namespace sctx = "http://www.zorba-xquery.com/modules/introspection/sctx";
-import module namespace base64 = "http://www.zorba-xquery.com/modules/converters/base64";
-
-
-declare variable $local:localns as xs:string := 'http://www.w3.org/2005/xquery-local-functions';
-
-
-declare variable $local:endl as xs:string := '
-';
-
-declare function local:has-to-stop($resp as element())
-{
- fn:not(($resp/@command/data(.) eq "stop" and $resp/@reason/data(.) eq "ok")
- or ($resp/@status/data(.) eq "stopped")
- or ($resp/@status/data(.) eq "stopping"))
-};
-
-declare function local:status($resp as element())
-{
- fn:concat(
- "Status: ", $resp/@status/data(.), $local:endl,
- "Reason: ", $resp/@reason/data(.), $local:endl,
- let $msg := $resp/text()
- return
- if (fn:empty($msg) or $msg eq "") then
- ""
- else
- fn:concat($msg, $local:endl)
- )
-};
-
-
-declare function local:run($resp as element()) {
- if ($resp/@status/data(.) eq "starting") then
- "Starting query"
- else
- local:status($resp)
-};
-
-declare function local:stop($resp as element())
-{
- local:status($resp)
-};
-
-declare function local:breakpoint_set($resp as element())
-{
- if ($resp/error) then
- fn:concat("Error when setting a breakpoint: ", if ($resp/error/message) then $resp/error/message/text() else concat(" errcode: ", data($resp/error/@code)))
- else
- fn:concat("set breakpoint with id ", data($resp/@id), " and state ", data($resp/@state))
-};
-
-declare function local:breakpoint_list($resp as element())
-{
- string-join(
- for $b in $resp/breakpoint
- return concat("Breakpoint ", data($b/@id), " at ", data($b/@filename), ":", data($b/@lineno), " ", data($b/@state)),
- $local:endl
- )
-};
-
-declare function local:breakpoint_remove($resp as element())
-{
- "Breakpoint removed"
-};
-
-declare function local:stack_depth($resp as element())
-{
- concat("Depth: ", data($resp/@depth))
-};
-
-declare function local:stack_get($resp as element())
-{
- string-join(
- for $s in $resp/stack
- return concat("Level ", data($s/@level), " at ", data($s/@filename), ":", data($s/@lineno)),
- $local:endl
- )
-};
-
-
-declare function local:context_names($resp as element())
-{
- string-join(
- for $c in $resp/context
- return concat("Context: ", data($c/@name), " id: ", data($c/@id)),
- $local:endl
- )
-};
-
-declare function local:context_get($resp as element())
-{
- string-join(
- for $p in $resp/property
- return concat(data($p/@fullname), ": [", data($p/@type), "]",
- if ($p/text() ne "") then concat(": ", base64:decode($p/text())) else ""),
- $local:endl
- )
-};
-
-declare function local:eval($resp as element())
-{
- if (data($resp/@success) eq "1") then
- local:context_get($resp)
- else
- concat("Eval failed", ":", $resp/error/message/text())
-};
-
-declare function local:process-response($resp as element())
-{
- if (data($resp/@command) eq "") then
- (fn:true(), $resp/@transaction_id/data(.), local:status($resp))
- else
- let $fun-cont-name := fn:QName($local:localns, concat("local:", $resp/@command/data(.), "-cont"))
- let $fun-msg-name := fn:QName($local:localns, concat("local:", $resp/@command/data(.)))
- return (
- if (sctx:function-arguments-count($fun-cont-name) = 1) then
- refl:invoke($fun-cont-name, $resp)
- else
- local:has-to-stop($resp),
- $resp/@transaction_id/data(.),
- if (sctx:function-arguments-count($fun-msg-name) = 1) then
- refl:invoke($fun-msg-name, $resp)
- else
- "Recieved a message - command not implemented"
- )
-};
-
-declare function local:process-init($init as element())
-{
- fn:true(),
- 0,
- fn:concat(fn:string-join(
- ('Established connection with', $init/@language/data(.), 'client', $init/@appid/data(.)), ' '), '
-')
-};
-
-declare function local:main($response as element()) {
- let $process-fun as xs:QName := fn:QName($local:localns, concat("local:process-", node-name($response)))
- return
- if (sctx:function-arguments-count($process-fun) = 1) then
- refl:invoke($process-fun, $response)
- else (
- true(),
- ($response/@transaction_id, 0)[1]/data(.),
- "ERROR: Recieved unknown node from client"
- )
-};
=== renamed directory 'bin/debug_client' => 'bin/debugger'
=== renamed file 'bin/debug_client/debug_command.h' => 'bin/debugger/command.h'
--- bin/debug_client/debug_command.h 2011-07-04 08:05:46 +0000
+++ bin/debugger/command.h 2012-01-25 00:12:28 +0000
@@ -14,7 +14,9 @@
* limitations under the License.
*/
#pragma once
-#include <zorba/config.h>
+#ifndef ZORBA_DEBUGGER_COMMAND_H
+#define ZORBA_DEBUGGER_COMMAND_H
+
#include <string>
#include <vector>
#include <iostream>
@@ -23,151 +25,18 @@
#include <sstream>
#include <memory>
#include <typeinfo>
-#include "debug_client/tuple.h"
-
-namespace zorba { namespace debugclient {
+
+#include <zorba/config.h>
+
+#include "command_arg.h"
+#include "tuple.h"
+
+
+namespace zorba { namespace debugger {
class DebugClientParseException : public std::exception {
};
- template<typename Tuple>
- class CommandArg;
-
- template<typename Tuple>
- class CommandArgInstance {
- public:
- virtual int get_index() const = 0;
- virtual const CommandArg<Tuple>* get_arg() const = 0;
- virtual void insertValue(Tuple& t) = 0;
- virtual bool isSet(Tuple& t) const = 0;
- };
-
- template<typename T, int Idx, typename Tuple>
- class TypedCommandArgInstance : public CommandArgInstance<Tuple>
- {
- public:
- TypedCommandArgInstance(T aValue, const CommandArg<Tuple>* aArg)
- : theValue(aValue), theArg(aArg) {}
- virtual int get_index() const { return Idx; }
- virtual const CommandArg<Tuple>* get_arg() const { return theArg; }
- virtual void insertValue(Tuple& t)
- {
- ZORBA_TR1_NS::get<Idx>(t).first = true;
- ZORBA_TR1_NS::get<Idx>(t).second = theValue;
- }
- virtual bool isSet(Tuple& t) const
- {
- return ZORBA_TR1_NS::get<Idx>(t).first;
- }
- private:
- T theValue;
- const CommandArg<Tuple>* theArg;
- };
-
- template<typename Tuple>
- class CommandArgType {
- public:
- virtual CommandArgInstance<Tuple>* parse(const std::string& str,
- const CommandArg<Tuple>* arg) = 0;
- virtual bool isVoid() const = 0;
- virtual bool isSet(Tuple& t) const = 0;
- virtual ~CommandArgType() {}
- };
-
- template<typename T, int Idx, typename Tuple>
- class TypedCommandArgType : public CommandArgType<Tuple> {
- public:
- typedef T Type;
- public: // implementation
- TypedCommandArgType(bool aIsVoid) : theIsVoid(aIsVoid) {}
- TypedCommandArgType(const T& aValue,
- bool aIsVoid)
- : theDefault(aValue), theIsVoid(aIsVoid) {}
- virtual CommandArgInstance<Tuple>* parse(const std::string& str,
- const CommandArg<Tuple>* arg)
- {
- T aValue;
- std::stringstream stream(str);
- stream >> aValue;
- if (stream.fail()) {
- std::cerr << "Could not parse argument of type "
- << typeid(T).name()
- << std::endl;
- return 0;
- }
- return new TypedCommandArgInstance<T, Idx, Tuple>(aValue, arg);
- }
- virtual bool isVoid() const { return theIsVoid; }
- virtual bool isSet(Tuple& t) const
- {
- return ZORBA_TR1_NS::get<Idx>(t).first;
- }
- private:
- TypedCommandArgType<T, Idx, Tuple>() {}
- T theDefault;
- bool theIsVoid;
- };
-
- template<typename Tuple>
- class CommandArg {
- public:
- CommandArg(unsigned aId,
- CommandArgType<Tuple>* aType,
- const std::set<std::string>& aFlags,
- const std::string& aDescription,
- bool aIsRequired)
- : theId(aId),
- theType(aType),
- theFlags(aFlags),
- theDescription(aDescription),
- theIsRequired(aIsRequired)
- {
- }
- ~CommandArg() { delete theType; }
- unsigned get_id() const { return theId; }
- bool canHandle(const std::string& arg) const
- {
- if (theFlags.find(arg) != theFlags.end()) {
- return true;
- }
- return false;
- }
- CommandArgInstance<Tuple>* parse(const std::string& str) const
- {
- return theType->parse(str, this);
- }
- bool isVoid() const {
- return theType->isVoid();
- }
- bool isRequired() const { return theIsRequired; }
- std::string get_name() const {
- return *(theFlags.begin());
- }
- bool isSet(Tuple& t) const
- {
- return theType->isSet(t);
- }
- private:
- unsigned theId;
- CommandArgType<Tuple>* theType;
- std::set<std::string> theFlags;
- std::string theDescription;
- bool theIsRequired;
- };
-}} // end namespace zorba
-
-namespace std {
-
- /**
- * This is a helper split function
- */
- vector<string>& operator<< (vector<string>& vec, const string& str);
-
- set<string>& operator<< (set<string>& vec, const string& str);
-} //end namespace std
-
-namespace zorba { namespace debugclient {
-
template<typename Func, typename Tuple, int CommandIdx>
class CommandInstance
{
@@ -188,8 +57,10 @@
class UntypedCommand {
public:
- virtual std::string get_name() const = 0;
- virtual std::string get_description() const = 0;
+ virtual std::string getName() const = 0;
+ virtual std::set<std::string> getAliases() const = 0;
+ virtual std::string getDescription() const = 0;
+ virtual void printHelp() const = 0;
virtual bool execute(const std::vector<std::string>& args) = 0;
};
@@ -197,77 +68,141 @@
class Command : public UntypedCommand {
public:
Command(const std::string& aName, Func& aFunction, const std::string& aDescription)
- : theName(aName), theFunction(aFunction), theDescription(aDescription) {}
+ : theName(aName), theFunction(aFunction), theDescription(aDescription)
+ {}
+
+ Command(const std::string& aName, const std::set<std::string> aAliases, Func& aFunction, const std::string& aDescription)
+ : theName(aName), theAliases(aAliases), theFunction(aFunction), theDescription(aDescription)
+ {}
+
~Command();
+
public:
- Command& operator() (unsigned aId,
- const std::string& aFlags,
- CommandArgType<Tuple>* aType,
- const std::string& aDescription = "",
- bool isRequired = false);
- virtual std::string get_name() const { return theName; }
- virtual std::string get_description() const { return theDescription; }
+
+ void
+ addArgument(
+ unsigned aId,
+ const std::string& aFlags,
+ CommandArgType<Tuple>* aType,
+ const std::string& aDescription = "",
+ bool isRequired = false);
+
+ static void
+ splitNames(
+ const std::string& names,
+ std::set<std::string>& set);
+
+ virtual std::string
+ getName() const
+ {
+ return theName;
+ }
+
+ virtual std::set<std::string> getAliases() const
+ {
+ return theAliases;
+ }
+
+ virtual std::string
+ getDescription() const
+ {
+ return theDescription;
+ }
+
+ virtual void
+ printHelp() const;
+
virtual bool execute(const std::vector<std::string>& args)
{
CommandInstance<Func, Tuple, CommandIdx> instance(theFunction, theTuple);
- if (instance.parseArguments(args, theArgs))
+ if (instance.parseArguments(args, theArgs)) {
instance.execute();
- else
- return false;
- return true;
+ return true;
+ }
+ return false;
}
private:
std::string theName;
+ std::set<std::string> theAliases;
Func& theFunction;
Tuple theTuple;
std::string theDescription;
- std::map<std::string, CommandArg<Tuple>* > theArgs;
- };
-
- class CommandLine {
- public:
- ~CommandLine();
- public:
- void execute();
- CommandLine& operator<< (UntypedCommand* aCommand);
- private:
- std::map<std::string, UntypedCommand*> theCommands;
- };
-
- template<typename Func, typename Tuple, int CommandIdx>
- Command<Func, Tuple, CommandIdx>::~Command()
- {
- typedef std::map<std::string, CommandArg<Tuple>* > ArgType;
- for (typename ArgType::iterator i = theArgs.begin(); i != theArgs.end(); ++i) {
- delete i->second;
- }
- }
-
-
- template<typename Func, typename Tuple, int CommandIdx>
- Command<Func, Tuple, CommandIdx>&
- Command<Func, Tuple, CommandIdx>::operator() (unsigned aId,
- const std::string& aFlags,
- CommandArgType<Tuple>* aType,
- const std::string& aDescription,
- bool isRequired)
- {
- std::set<std::string> args;
- args << aFlags;
- for (std::set<std::string>::iterator i = args.begin(); i != args.end(); ++i) {
- std::string toAdd = (i->size() == 1) ? "-" + *i : "--" + *i;
- theArgs.insert(std::make_pair(toAdd,
- new CommandArg<Tuple>(aId,
- aType,
- args,
- aDescription,
- isRequired)
- )
- );
- }
- return *this;
- }
-
+ std::map<std::string, CommandArg<Tuple>*> theArgs;
+ };
+
+/*****************************************************************************/
+/*****************************************************************************/
+
+template<typename Func, typename Tuple, int CommandIdx>
+Command<Func, Tuple, CommandIdx>::~Command()
+{
+ typedef std::map<std::string, CommandArg<Tuple>*> ArgType;
+ for (typename ArgType::iterator i = theArgs.begin(); i != theArgs.end(); ++i) {
+ delete i->second;
+ }
+}
+
+template<typename Func, typename Tuple, int CommandIdx>
+void
+Command<Func, Tuple, CommandIdx>::printHelp() const
+{
+ std::cout << "Purpose: " << getDescription() << std::endl;
+
+ typename std::map<std::string, CommandArg<Tuple>*>::const_iterator lIter = theArgs.begin();
+ if (lIter == theArgs.end()) {
+ std::cout << "This command has no arguments." << std::endl;
+ std::cout << std::endl;
+ return;
+ }
+
+ std::cout << "Arguments:" << std::endl << std::endl;
+ for (; lIter != theArgs.end(); ++lIter) {
+ std::cout << " " << lIter->first << "\t" << lIter->second->getDescription() << std::endl;
+ }
+ std::cout << std::endl;
+}
+
+template<typename Func, typename Tuple, int CommandIdx>
+void
+Command<Func, Tuple, CommandIdx>::splitNames(const std::string& aNames, std::set<std::string>& aSet)
+{
+ std::string::size_type before = 0;
+ std::string::size_type pos = aNames.find(" ", 0);
+ while (pos != aNames.npos) {
+ std::string lName = aNames.substr(before, pos);
+ if (lName != "") {
+ aSet.insert(lName);
+ }
+ before = pos + 1;
+ pos = aNames.find(" ", before);
+ }
+ std::string lName = aNames.substr(before);
+ if (lName != "") {
+ aSet.insert(lName);
+ }
+}
+
+template<typename Func, typename Tuple, int CommandIdx>
+void
+Command<Func, Tuple, CommandIdx>::addArgument(
+ unsigned aId,
+ const std::string& aFlags,
+ CommandArgType<Tuple>* aType,
+ const std::string& aDescription,
+ bool isRequired)
+{
+ std::set<std::string> lNames;
+ splitNames(aFlags, lNames);
+
+ for (std::set<std::string>::iterator i = lNames.begin(); i != lNames.end(); ++i) {
+ std::string toAdd = (i->size() == 1) ? "-" + *i : "--" + *i;
+ CommandArg<Tuple>* lArg = new CommandArg<Tuple>(aId, aType, lNames, aDescription, isRequired);
+ theArgs.insert(std::make_pair(toAdd, lArg));
+ }
+}
+
+/*****************************************************************************/
+
template<typename Tuple, typename T, int Idx>
CommandArgType<Tuple>* createArgType(Tuple t)
{
@@ -290,6 +225,16 @@
return new Command<Func, Tuple, CommandIdx>(aName, aFunction, aDescription);
}
+ template<int CommandIdx, typename Tuple, typename Func>
+ Command<Func, Tuple, CommandIdx>* createCommand(Tuple t,
+ const std::string& aName,
+ const std::set<std::string>& aAliases,
+ Func& aFunction,
+ const std::string& aDescription)
+ {
+ return new Command<Func, Tuple, CommandIdx>(aName, aAliases, aFunction, aDescription);
+ }
+
template<typename Func, typename Tuple, int CommandIdx>
bool CommandInstance<Func, Tuple, CommandIdx>::
parseArguments(const std::vector<std::string>& args,
@@ -301,29 +246,34 @@
for (ArgType::size_type i = 1; i < size; ++i) {
typename CArgType::const_iterator pos = aCommandArgs.find(args[i]);
if (pos == aCommandArgs.end()) {
- std::cerr << "Error: Unknown Argument " << args[i] << std::endl;
+ std::cerr << "Error: Unknown option " << args[i] << std::endl;
parseError = true;
return false;
}
const CommandArg<Tuple>& arg = *(pos->second);
- if (!arg.isVoid() && args[++i][0] == '-') {
- std::cerr << "Did not expect parameter for option " << args[i] << std::endl;
- return false;
- }
std::auto_ptr<CommandArgInstance<Tuple> > instance;
if (arg.isVoid()) {
instance.reset(arg.parse("1"));
} else {
+ ++i;
+ if (i >= size) {
+ std::cerr << "Error: Missing value for argument " << args[i - 1] << std::endl;
+ parseError = true;
+ allSet = false;
+ return false;
+ }
instance.reset(arg.parse(args[i]));
}
- instance->insertValue(theTuple);
+ if (instance.get()) {
+ instance->insertValue(theTuple);
+ }
}
bool allSet = true;
for (typename CArgType::const_iterator i = aCommandArgs.begin();
i != aCommandArgs.end(); ++i)
{
if (i->second->isRequired() && !i->second->isSet(theTuple)) {
- std::cerr << "Error: Argument " << i->second->get_name() << " not set" << std::endl;
+ std::cerr << "Error: Argument -" << i->second->getName() << " not set" << std::endl;
allSet = false;
}
}
@@ -336,4 +286,7 @@
theFunction.template handle<CommandIdx>(this->theTuple);
}
-}} // end of namespace zorba::debugclient
+} // namespace zorba
+} // namespace debugger
+
+#endif // ZORBA_DEBUGGER_COMMAND_H
=== added file 'bin/debugger/command_arg.h'
--- bin/debugger/command_arg.h 1970-01-01 00:00:00 +0000
+++ bin/debugger/command_arg.h 2012-01-25 00:12:28 +0000
@@ -0,0 +1,237 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+#ifndef ZORBA_DEBUGGER_COMMAND_ARG_H
+#define ZORBA_DEBUGGER_COMMAND_ARG_H
+
+#include <string>
+#include <iostream>
+#include <set>
+#include <sstream>
+
+#include "tuple.h"
+
+
+namespace zorba { namespace debugger {
+
+template<typename Tuple>
+class CommandArg;
+
+template<typename Tuple>
+class CommandArgInstance {
+ public:
+ virtual int get_index() const = 0;
+ virtual const CommandArg<Tuple>* get_arg() const = 0;
+ virtual void insertValue(Tuple& t) = 0;
+ virtual bool isSet(Tuple& t) const = 0;
+};
+
+template<typename T, int Idx, typename Tuple>
+class TypedCommandArgInstance : public CommandArgInstance<Tuple>
+{
+ public:
+ TypedCommandArgInstance(T aValue, const CommandArg<Tuple>* aArg)
+ : theValue(aValue), theArg(aArg)
+ {
+ }
+
+ virtual int
+ get_index() const
+ {
+ return Idx;
+ }
+
+ virtual const CommandArg<Tuple>*
+ get_arg() const
+ {
+ return theArg;
+ }
+
+ virtual void
+ insertValue(Tuple& t)
+ {
+ ZORBA_TR1_NS::get<Idx>(t).first = true;
+ ZORBA_TR1_NS::get<Idx>(t).second = theValue;
+ }
+
+ virtual bool isSet(Tuple& t) const
+ {
+ return ZORBA_TR1_NS::get<Idx>(t).first;
+ }
+
+ private:
+
+ T theValue;
+ const CommandArg<Tuple>* theArg;
+};
+
+template<typename Tuple>
+class CommandArgType
+{
+ public:
+ virtual CommandArgInstance<Tuple>*
+ parse(
+ const std::string& str,
+ const CommandArg<Tuple>* arg) = 0;
+
+ virtual bool
+ isVoid() const = 0;
+
+ virtual bool
+ isSet(Tuple& t) const = 0;
+
+ virtual ~CommandArgType() {}
+};
+
+ template<typename T, int Idx, typename Tuple>
+ class TypedCommandArgType : public CommandArgType<Tuple> {
+ public:
+ typedef T Type;
+ public: // implementation
+ TypedCommandArgType(bool aIsVoid) : theIsVoid(aIsVoid) {}
+ TypedCommandArgType(const T& aValue,
+ bool aIsVoid)
+ : theDefault(aValue), theIsVoid(aIsVoid) {}
+ virtual CommandArgInstance<Tuple>* parse(const std::string& str,
+ const CommandArg<Tuple>* arg)
+ {
+ T aValue;
+
+ // special treatment for strings
+ // this is a double hack:
+ // - we check the type name if this starts with: class std::basic_string
+ // - we use void* in readEntireString to workaround the template type T
+ // which would otherwise complain during compilation if types and
+ // operators do not match
+ // TOSO: probably someone can find a more elegant solution
+ std::string lTypeName(typeid(T).name());
+ if (lTypeName.find("class std::basic_string") == 0) {
+ readEntireString(str, &aValue);
+ } else {
+ std::stringstream stream(str);
+ std::stringstream out;
+ stream >> aValue;
+ if (stream.fail()) {
+ std::cerr << "Error: Could not parse value \"" << str << "\" as type "
+ << typeid(T).name()
+ << std::endl;
+ return 0;
+ }
+ }
+
+ return new TypedCommandArgInstance<T, Idx, Tuple>(aValue, arg);
+ }
+ virtual bool isVoid() const { return theIsVoid; }
+ virtual bool isSet(Tuple& t) const
+ {
+ return ZORBA_TR1_NS::get<Idx>(t).first;
+ }
+ private:
+ void readEntireString(std::string aIn, void* aValue)
+ {
+ *((std::string*)aValue) = aIn;
+ }
+
+ TypedCommandArgType<T, Idx, Tuple>() {}
+ T theDefault;
+ bool theIsVoid;
+ };
+
+ template<typename Tuple>
+ class CommandArg {
+ public:
+ CommandArg(unsigned aId,
+ CommandArgType<Tuple>* aType,
+ const std::set<std::string>& aNames,
+ const std::string& aDescription,
+ bool aIsRequired)
+ : theId(aId),
+ theType(aType),
+ theNames(aNames),
+ theDescription(aDescription),
+ theIsRequired(aIsRequired)
+ {
+ }
+
+ ~CommandArg()
+ {
+ delete theType;
+ }
+
+ unsigned
+ get_id() const
+ {
+ return theId;
+ }
+
+ bool
+ canHandle(const std::string& arg) const
+ {
+ if (theNames.find(arg) != theNames.end()) {
+ return true;
+ }
+ return false;
+ }
+
+ CommandArgInstance<Tuple>*
+ parse(const std::string& str) const
+ {
+ return theType->parse(str, this);
+ }
+
+ bool
+ isVoid() const
+ {
+ return theType->isVoid();
+ }
+
+ bool
+ isRequired() const
+ {
+ return theIsRequired;
+ }
+
+ std::string
+ getName() const
+ {
+ return *(theNames.begin());
+ }
+
+ std::string
+ getDescription() const
+ {
+ return theDescription;
+ }
+
+ bool
+ isSet(Tuple& t) const
+ {
+ return theType->isSet(t);
+ }
+
+ private:
+
+ unsigned theId;
+ CommandArgType<Tuple>* theType;
+ std::set<std::string> theNames;
+ std::string theDescription;
+ bool theIsRequired;
+ };
+
+} // namespace zorba
+} // namespace debugger
+
+#endif // ZORBA_DEBUGGER_COMMAND_ARG_H
=== modified file 'bin/debugger/command_line_handler.cpp'
--- bin/debug_client/command_line_handler.cpp 2011-07-01 01:53:24 +0000
+++ bin/debugger/command_line_handler.cpp 2012-01-25 00:12:28 +0000
@@ -1,4 +1,4 @@
-/*
+ /*
* Copyright 2006-2008 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -23,225 +23,385 @@
# define msleep Sleep
#endif
-namespace zorba { namespace debugclient {
+#include "command_prompt.h"
+
+
+namespace zorba { namespace debugger {
- using namespace ::std;
using namespace ::ZORBA_TR1_NS;
- CommandLineHandler::CommandLineHandler(unsigned short port,
- LockFreeConsumer<std::size_t>& aConsumer,
- LockFreeConsumer<bool>& aContinueQueue,
- EventHandler& aHandler,
- CommandLine& aCommandLine)
+CommandLineHandler::CommandLineHandler(
+ unsigned short port,
+ LockFreeConsumer<std::size_t>& aConsumer,
+ LockFreeConsumer<bool>& aContinueQueue,
+ EventHandler* aHandler,
+ CommandPrompt* aCommandPrompt)
: theConsumer(aConsumer),
theContinueQueue(aContinueQueue),
- theClient(DebuggerClient::createDebuggerClient(&aHandler, port, "localhost")),
- theCommandLine(aCommandLine),
- theQuit(false), theContinue(false), theWaitFor(0)
+ theClient(DebuggerClient::createDebuggerClient(aHandler, port, "localhost")),
+ theCommandLine(aCommandPrompt),
+ theQuit(false), theTerminated(true), theContinue(false), theWaitFor(0)
{
addCommands();
}
- CommandLineHandler::~CommandLineHandler()
- {
- }
+CommandLineHandler::~CommandLineHandler()
+{
+}
- void CommandLineHandler::execute()
- {
- theClient->accept();
- std::set<std::size_t> lIdList;
- do {
+void
+CommandLineHandler::execute()
+{
+ theClient->accept();
+ std::set<std::size_t> lIdList;
+ do {
+ getNextId(lIdList);
+ while (lIdList.find(theWaitFor) == lIdList.end()) {
getNextId(lIdList);
- while (!theQuit && lIdList.find(theWaitFor) == lIdList.end()) {
- getNextId(lIdList);
- msleep(20);
- }
- while (!theContinueQueue.consume(theQuit)) {
- msleep(20);
- }
- theQuit = !theQuit;
- if (!theQuit) {
- theCommandLine.execute();
- while (theContinue) {
- theContinue = false;
- theCommandLine.execute();
- }
- }
- } while (!theQuit);
- }
-
- void CommandLineHandler::getNextId(std::set<std::size_t>& aIdList)
- {
- std::size_t result;
- if (theConsumer.consume(result)) {
- aIdList.insert(result);
- }
- }
-
- template<>
- void CommandLineHandler::handle<Status>(ZORBA_TR1_NS::tuple<> &t)
- {
- theWaitFor = theClient->status();
- }
-
- template<>
- void CommandLineHandler::handle<Quit>(ZORBA_TR1_NS::tuple<> &t)
- {
+ msleep(20);
+ }
+ bool lCanQuit;
+ while (!theContinueQueue.consume(lCanQuit)) {
+ msleep(20);
+ }
+ if (lCanQuit) {
+ theTerminated = true;
+ }
+ theCommandLine->execute();
+ while (theContinue) {
+ theContinue = false;
+ theCommandLine->execute();
+ }
+ } while (!theQuit);
+}
+
+void
+CommandLineHandler::getNextId(std::set<std::size_t>& aIdList)
+{
+ std::size_t result;
+ if (theConsumer.consume(result)) {
+ aIdList.insert(result);
+ }
+}
+
+template<>
+void
+CommandLineHandler::handle<Status>(ZORBA_TR1_NS::tuple<> &t)
+{
+ theWaitFor = theClient->status();
+}
+
+template<>
+void
+CommandLineHandler::handle<Variables>(ZORBA_TR1_NS::tuple<> &t)
+{
+ theWaitFor = theClient->variables();
+}
+
+template<>
+void
+CommandLineHandler::handle<Quit>(ZORBA_TR1_NS::tuple<> &t)
+{
+ if (!theTerminated) {
bool answered = false;
while (!answered) {
std::cout << "Do you really want to stop debugging and exit? (y/n) ";
- char answer;
- std::cin >> answer;
- std::cout << std::endl;
- if (answer == 'y') {
+ std::string lAnswer;
+ std::getline(std::cin, lAnswer);
+ if (lAnswer == "y" || lAnswer == "yes") {
answered = true;
- } else if (answered == 'n') {
+ } else if (lAnswer == "n" || lAnswer == "no") {
theContinue = true;
return;
}
}
- theWaitFor = theClient->stop();
- theClient->quit();
- }
-
- template<>
- void CommandLineHandler::handle<Run>(ZORBA_TR1_NS::tuple<> &t)
- {
- theWaitFor = theClient->run();
- }
-
- template<>
- void CommandLineHandler::handle<BreakpointSet>(std::tr1::tuple<bstring, bstring, bint> &t)
- {
- DebuggerClient::BreakpointType lType = DebuggerClient::Line;
- bool lEnabled = true;
- if (get<0>(t).first) {
- if (get<0>(t).second == "disabled") {
- lEnabled = false;
- }
- }
- theWaitFor = theClient->breakpoint_set(lType,
- lEnabled,
- get<1>(t).second,
- get<2>(t).second);
- }
-
- template<>
- void CommandLineHandler::handle<BreakpointGet>(tuple<bint> &aTuple)
- {
- theWaitFor = theClient->breakpoint_get(get<0>(aTuple).second);
- }
-
- template<>
- void CommandLineHandler::handle<BreakpointDel>(tuple<bint> &aTuple)
- {
- theWaitFor = theClient->breakpoint_remove(get<0>(aTuple).second);
- }
-
- template<>
- void CommandLineHandler::handle<BreakpointList>(tuple<> &t)
- {
- theWaitFor = theClient->breakpoint_list();
- }
-
- template<>
- void CommandLineHandler::handle<StackDepth>(tuple<> &t)
- {
- theWaitFor = theClient->stack_depth();
- }
-
- template<>
- void CommandLineHandler::handle<StackGet>(tuple<bint> &aTuple)
- {
- if (get<0>(aTuple).first) {
- theWaitFor = theClient->stack_get(get<0>(aTuple).second);
- } else {
- theWaitFor = theClient->stack_get();
- }
- }
-
- template<>
- void CommandLineHandler::handle<ContextNames>(tuple<>& aTuple)
- {
- theWaitFor = theClient->context_names();
- }
-
- template<>
- void CommandLineHandler::handle<ContextGet>(tuple<bint> &aTuple)
- {
- if (get<0>(aTuple).first)
- theWaitFor = theClient->context_get(get<0>(aTuple).second);
- else
- theWaitFor = theClient->context_get();
- }
-
- template<>
- void CommandLineHandler::handle<Eval>(tuple<bstring>& aTuple)
- {
- theWaitFor = theClient->eval(get<0>(aTuple).second);
- }
-
- void CommandLineHandler::addCommands()
- {
- theCommandLine << createCommand<Status>(tuple<>(), "status", *this,
- "Gets the status of the server");
- theCommandLine << createCommand<Quit>(tuple<>(), "quit", *this,
- "Stops debugging and quits the client");
- theCommandLine << createCommand<Run>(tuple<>(), "run", *this, "Run the Query");
- {
- Command<CommandLineHandler, tuple<bstring, bstring, bint>, BreakpointSet>* lCommand =
- createCommand<BreakpointSet>(tuple<bstring, bstring, bint>(), "break", *this, "Set a breakpoint");
- (*lCommand)(0, "s", createArgType<tuple<bstring, bstring, bint>, std::string, 0>(tuple<bstring, bstring, bint>()),
- "breakpoint state (enabled or disabled - default: enabled)", false);
- (*lCommand)(1, "f", createArgType<tuple<bstring, bstring, bint>, std::string, 1>(tuple<bstring, bstring, bint>()),
- "The name of the file where to stop", true);
- (*lCommand)(2, "l", createArgType<tuple<bstring, bstring, bint>, int, 2>(tuple<bstring, bstring, bint>()),
- "The line number", true);
-
- theCommandLine << lCommand;
- }
- {
- Command<CommandLineHandler, tuple<bint>, BreakpointGet>* lCommand
- = createCommand<BreakpointGet>(tuple<bint>(), "binfo", *this,
- "Get information about a given breakpoint");
- (*lCommand)(0, "i", createArgType<tuple<bint>, int, 0>(tuple<bint>()),
- "The id of the breakpoint", true);
-
- theCommandLine << lCommand;
- }
- {
- Command<CommandLineHandler, tuple<bint>, BreakpointDel>* lCommand
- = createCommand<BreakpointDel>(tuple<bint>(), "bdel", *this, "Delete a breakpoint with a given id");
- (*lCommand)(0, "i", createArgType<tuple<bint>, int, 0>(tuple<bint>()), "The id of the breakpoint", true);
-
- theCommandLine << lCommand;
- }
- theCommandLine << createCommand<BreakpointList>(tuple<>(), "blist", *this, "List all set breakpoints");
- theCommandLine << createCommand<StackDepth>(tuple<>(), "sdepth", *this, "Get the depth of the stack");
- {
- Command<CommandLineHandler, tuple<bint>, StackGet>* lCommand
- = createCommand<StackGet>(tuple<bint>(), "sget", *this, "Get information about one or all stack frames");
- (*lCommand)(0, "d", createArgType<tuple<bint>, int, 0>(tuple<bint>()), "The stack entry two show (show all if not provided)", false);
- theCommandLine << lCommand;
- }
- theCommandLine << createCommand<ContextNames>(tuple<>(), "cnames", *this, "Get the names of the avilable contexts");
- {
- Command<CommandLineHandler, tuple<bint>, ContextGet>* lCommand
- = createCommand<ContextGet>(tuple<bint>(), "cget", *this, "Get a context");
-
- (*lCommand)(0, "c", createArgType<tuple<bint>, int, 0>(tuple<bint>()), "The id of the context", false);
-
- theCommandLine << lCommand;
- }
- {
- Command<CommandLineHandler, tuple<bstring>, Eval>* lCommand
- = createCommand<Eval>(tuple<bstring>(), "eval", *this, "Evaluate a function");
-
- (*lCommand)(0, "c", createArgType<tuple<bstring>, std::string, 0>(tuple<bstring>()), "The command to evaluate", true);
-
- theCommandLine << lCommand;
- }
- }
-
-}} // namespace zorba::debugclient
-
+ }
+ theWaitFor = theClient->stop(true);
+ theClient->quit();
+ theQuit = true;
+}
+
+template<>
+void
+CommandLineHandler::handle<Run>(ZORBA_TR1_NS::tuple<> &t)
+{
+ theTerminated = false;
+ theWaitFor = theClient->run();
+}
+
+template<>
+void
+CommandLineHandler::handle<Stop>(ZORBA_TR1_NS::tuple<> &t)
+{
+ theWaitFor = theClient->stop(false);
+}
+
+template<>
+void
+CommandLineHandler::handle<BreakpointSet>(std::tr1::tuple<bstring, bstring, bint> &aTuple)
+{
+ DebuggerClient::BreakpointType lType = DebuggerClient::Line;
+ bool lEnabled = true;
+ if (get<0>(aTuple).first) {
+ if (get<0>(aTuple).second == "disabled") {
+ lEnabled = false;
+ }
+ }
+ theWaitFor = theClient->breakpoint_set(lType,
+ lEnabled,
+ get<1>(aTuple).second,
+ get<2>(aTuple).second);
+}
+
+template<>
+void
+CommandLineHandler::handle<BreakpointGet>(tuple<bint> &aTuple)
+{
+ theWaitFor = theClient->breakpoint_get(get<0>(aTuple).second);
+}
+
+template<>
+void
+CommandLineHandler::handle<BreakpointRemove>(tuple<bint> &aTuple)
+{
+ theWaitFor = theClient->breakpoint_remove(get<0>(aTuple).second);
+}
+
+template<>
+void
+CommandLineHandler::handle<BreakpointList>(tuple<> &aTuple)
+{
+ theWaitFor = theClient->breakpoint_list();
+}
+
+template<>
+void
+CommandLineHandler::handle<StackDepth>(tuple<> &aTuple)
+{
+ theWaitFor = theClient->stack_depth();
+}
+
+template<>
+void
+CommandLineHandler::handle<StackGet>(tuple<bint> &aTuple)
+{
+ if (get<0>(aTuple).first) {
+ theWaitFor = theClient->stack_get(get<0>(aTuple).second);
+ } else {
+ theWaitFor = theClient->stack_get();
+ }
+}
+
+template<>
+void
+CommandLineHandler::handle<ContextNames>(tuple<>& aTuple)
+{
+ theWaitFor = theClient->context_names();
+}
+
+template<>
+void CommandLineHandler::handle<ContextGet>(tuple<bint, bint> &aTuple)
+{
+ int lDepth = -1;
+ int lContext = -1;
+
+ if (get<0>(aTuple).first) {
+ lDepth = get<0>(aTuple).second;
+ }
+ if (get<1>(aTuple).first) {
+ lContext = get<1>(aTuple).second;
+ }
+ theWaitFor = theClient->context_get(lDepth, lContext);
+}
+
+template<>
+void CommandLineHandler::handle<Source>(tuple<bint, bint, bstring> &aTuple)
+{
+ theWaitFor = theClient->source(
+ get<2>(aTuple).second,
+ get<0>(aTuple).second,
+ get<1>(aTuple).second);
+}
+
+template<>
+void CommandLineHandler::handle<Eval>(tuple<bstring>& aTuple)
+{
+ theWaitFor = theClient->eval(get<0>(aTuple).second);
+}
+
+template<>
+void
+CommandLineHandler::handle<StepIn>(ZORBA_TR1_NS::tuple<> &t)
+{
+ theTerminated = false;
+ theWaitFor = theClient->step_into();
+}
+
+template<>
+void
+CommandLineHandler::handle<StepOut>(ZORBA_TR1_NS::tuple<> &t)
+{
+ theWaitFor = theClient->step_out();
+}
+
+template<>
+void
+CommandLineHandler::handle<StepOver>(ZORBA_TR1_NS::tuple<> &t)
+{
+ theTerminated = false;
+ theWaitFor = theClient->step_over();
+}
+
+void
+CommandLineHandler::addCommands()
+{
+ typedef tuple<> TUPLE;
+ typedef tuple<bint> TUPLE_INT;
+ typedef tuple<bstring> TUPLE_STR;
+ typedef tuple<bint, bint> TUPLE_INT_INT;
+ typedef tuple<bstring, bstring, bint> TUPLE_STR_STR_INT;
+ typedef tuple<bint, bint, bstring> TUPLE_INT_INT_STR;
+
+ // DBGP: status
+ *theCommandLine << createCommand<Status>(TUPLE(), "status", *this, "Gets the status of the server");
+
+ // ALIAS: variables (context_get -c -1)
+ {
+ std::set<std::string> lAliases;
+ lAliases.insert("vars");
+ *theCommandLine << createCommand<Variables>(TUPLE(), "variables", lAliases, *this, "Gets the variables visible in the current scope");
+ }
+
+ // META: quit
+ *theCommandLine << createCommand<Quit>(TUPLE(), "quit", *this, "Stops debugging and quits the client");
+
+ // DBGP: run
+ *theCommandLine << createCommand<Run>(TUPLE(), "run", *this, "Run the query");
+
+ // DBGP: stop
+ *theCommandLine << createCommand<Stop>(TUPLE(), "stop", *this, "Stop the query");
+
+ // DBGP: breakpoint_set
+ {
+ std::set<std::string> lAliases;
+ lAliases.insert("break");
+ Command<CommandLineHandler, TUPLE_STR_STR_INT, BreakpointSet>* lCommand =
+ createCommand<BreakpointSet>(TUPLE_STR_STR_INT(), "bset", lAliases, *this, "Set a breakpoint");
+
+ lCommand->addArgument(0, "s", createArgType<TUPLE_STR_STR_INT, std::string, 0>(TUPLE_STR_STR_INT()), "breakpoint state (optional, 'enabled' or 'disabled', default: enabled)", false);
+ lCommand->addArgument(1, "f", createArgType<TUPLE_STR_STR_INT, std::string, 1>(TUPLE_STR_STR_INT()), "name of the file where to stop", true);
+ lCommand->addArgument(2, "l", createArgType<TUPLE_STR_STR_INT, int, 2>(TUPLE_STR_STR_INT()), "line number", true);
+
+ *theCommandLine << lCommand;
+ }
+
+ // DBGP: breakpoint_get
+ {
+ Command<CommandLineHandler, TUPLE_INT, BreakpointGet>* lCommand =
+ createCommand<BreakpointGet>(TUPLE_INT(), "bget", *this, "Get information about a given breakpoint");
+
+ lCommand->addArgument(0, "d", createArgType<TUPLE_INT, int, 0>(TUPLE_INT()), "breakpoint ID", true);
+
+ *theCommandLine << lCommand;
+ }
+
+ // DBGP: breakpoint_remove
+ {
+ std::set<std::string> lAliases;
+ lAliases.insert("clear");
+ lAliases.insert("delete");
+ Command<CommandLineHandler, TUPLE_INT, BreakpointRemove>* lCommand =
+ createCommand<BreakpointRemove>(TUPLE_INT(), "bremove", lAliases, *this, "Delete a breakpoint");
+
+ lCommand->addArgument(0, "d", createArgType<TUPLE_INT, int, 0>(TUPLE_INT()), "breakpoint ID", true);
+
+ *theCommandLine << lCommand;
+ }
+
+ // DBGP: breakpoint_list
+ *theCommandLine << createCommand<BreakpointList>(TUPLE(), "blist", *this, "List all set breakpoints");
+
+ // DBGP: stack_depth
+ *theCommandLine << createCommand<StackDepth>(TUPLE(), "sdepth", *this, "Get the depth of the stack");
+
+ // DBGP: stack_get
+ {
+ Command<CommandLineHandler, TUPLE_INT, StackGet>* lCommand =
+ createCommand<StackGet>(TUPLE_INT(), "sget", *this, "Get information about one or all stack frames");
+
+ lCommand->addArgument(0, "d", createArgType<TUPLE_INT, int, 0>(TUPLE_INT()), "stack frame to show: 0 for current stack frame, N for the main module (optional, all frames are shown if not provided)", false);
+
+ *theCommandLine << lCommand;
+ }
+
+ // DBGP: context_names
+ *theCommandLine << createCommand<ContextNames>(tuple<>(), "cnames", *this, "Get the names of the avilable contexts");
+ // the DBGP -d arguments for this command is omitted since we always have/return: 0 - Local, 1 - Global
+
+ // DBGP: context_get
+ {
+ Command<CommandLineHandler, TUPLE_INT_INT, ContextGet>* lCommand =
+ createCommand<ContextGet>(TUPLE_INT_INT(), "cget", *this, "Get a context (list variables in this context)");
+
+ lCommand->addArgument(0, "d", createArgType<TUPLE_INT_INT, int, 0>(TUPLE_INT_INT()), "stack depth (optional, default: 0)", false);
+ lCommand->addArgument(0, "c", createArgType<TUPLE_INT_INT, int, 1>(TUPLE_INT_INT()), "context ID: 0 for Local, 1 for Global (optional, default: 0)", false);
+
+ *theCommandLine << lCommand;
+ }
+
+ // DBGP: source
+ {
+ std::set<std::string> lAliases;
+ lAliases.insert("list");
+ Command<CommandLineHandler, TUPLE_INT_INT_STR, Source>* lCommand =
+ createCommand<Source>(TUPLE_INT_INT_STR(), "source", lAliases, *this, "List source code");
+
+ lCommand->addArgument(0, "b", createArgType<TUPLE_INT_INT_STR, int, 0>(TUPLE_INT_INT_STR()), "begin line (optional, default: first line)", false);
+ lCommand->addArgument(1, "e", createArgType<TUPLE_INT_INT_STR, int, 1>(TUPLE_INT_INT_STR()), "end line (optional, default: last line)", false);
+ lCommand->addArgument(2, "f", createArgType<TUPLE_INT_INT_STR, std::string, 2>(TUPLE_INT_INT_STR()), "file URI (optional, default: the file in the top-most stack frame during execution, main module otherwise)", false);
+
+ *theCommandLine << lCommand;
+ }
+
+ // DBGP: eval
+ {
+ std::set<std::string> lAliases;
+ lAliases.insert("print");
+ Command<CommandLineHandler, TUPLE_STR, Eval>* lCommand =
+ createCommand<Eval>(TUPLE_STR(), "eval", lAliases, *this, "Evaluate an expression");
+
+ // TODO: this argument should not be here at all. Eval has the form: eval -i transaction_id -- {DATA}
+ // Eval should be called with a command like: eval 1 + 3
+ // - no need for an argument name
+ // - everything following the fist contiguous set of whitespaces are sent as string
+ lCommand->addArgument(0, "c", createArgType<TUPLE_STR, std::string, 0>(TUPLE_STR()), "expression to evaluate", true);
+
+ *theCommandLine << lCommand;
+ }
+
+ // DBGP: step_in
+ {
+ std::set<std::string> lAliases;
+ lAliases.insert("step");
+ lAliases.insert("s");
+ *theCommandLine << createCommand<StepIn>(TUPLE(), "in", lAliases, *this, "Step in");
+ }
+
+ // DBGP: step_out
+ {
+ std::set<std::string> lAliases;
+ lAliases.insert("finish");
+ *theCommandLine << createCommand<StepOut>(TUPLE(), "out", lAliases, *this, "Step out");
+ }
+
+ // DBGP: step_over
+ {
+ std::set<std::string> lAliases;
+ lAliases.insert("next");
+ lAliases.insert("n");
+ *theCommandLine << createCommand<StepOver>(TUPLE(), "over", lAliases, *this, "Step over");
+ }
+}
+
+} // namespace zorba
+} // namespace debugger
=== modified file 'bin/debugger/command_line_handler.h'
--- bin/debug_client/command_line_handler.h 2011-07-01 01:53:24 +0000
+++ bin/debugger/command_line_handler.h 2012-01-25 00:12:28 +0000
@@ -14,46 +14,71 @@
* limitations under the License.
*/
#pragma once
+#ifndef ZORBA_DEBUGGER_COMMAND_LINE_HANDLER_H
+#define ZORBA_DEBUGGER_COMMAND_LINE_HANDLER_H
#include <set>
#include <cassert>
+
#include <zorba/debugger_client.h>
-#include "debug_command.h"
+
+#include "command.h"
#include "event_handler.h"
-namespace zorba { namespace debugclient {
-
+
+namespace zorba { namespace debugger {
+
+ class CommandPrompt;
+
enum Commands {
Status,
+ Variables,
+ Quit,
Run,
+ Stop,
BreakpointSet,
BreakpointGet,
- BreakpointDel,
+ BreakpointRemove,
BreakpointList,
StackDepth,
StackGet,
ContextNames,
ContextGet,
+ Source,
Eval,
- Quit
+ StepIn,
+ StepOut,
+ StepOver
};
- class CommandLineHandler {
+class CommandLineHandler
+{
private:
+
typedef std::pair<bool, std::string> bstring;
typedef std::pair<bool, int> bint;
+
public:
- CommandLineHandler(unsigned short port,
- LockFreeConsumer<std::size_t>& aConsumer,
- LockFreeConsumer<bool>& aContinueQueue,
- EventHandler& aHandler,
- CommandLine& aCommandLine);
+
+ CommandLineHandler(
+ unsigned short port,
+ LockFreeConsumer<std::size_t>& aConsumer,
+ LockFreeConsumer<bool>& aContinueQueue,
+ EventHandler* aHandler,
+ CommandPrompt* aCommandPrompt);
+
~CommandLineHandler();
+
public:
void execute();
+
public: // Handlers
+
template<int>
- void handle(ZORBA_TR1_NS::tuple<>& aTuple) { assert(false); }
+ void handle(ZORBA_TR1_NS::tuple<>& aTuple)
+ {
+ assert(false);
+ }
template<int>
void handle(ZORBA_TR1_NS::tuple<bstring, bstring, bint>& t)
@@ -62,63 +87,96 @@
}
template<int>
+ void handle(ZORBA_TR1_NS::tuple<bint, bint, bstring>& t)
+ {
+ assert(false);
+ }
+
+ template<int>
void handle(ZORBA_TR1_NS::tuple<bint>& aTuple)
{
assert(false);
}
template<int>
+ void handle(ZORBA_TR1_NS::tuple<bint, bint>& aTuple)
+ {
+ assert(false);
+ }
+
+ template<int>
void handle(ZORBA_TR1_NS::tuple<bstring>& aTuple)
{
assert(false);
}
+
private:
- LockFreeConsumer<std::size_t>& theConsumer;
- LockFreeConsumer<bool>& theContinueQueue;
- DebuggerClient* theClient;
- CommandLine& theCommandLine;
- bool theQuit;
- bool theContinue;
- std::size_t theWaitFor;
+ LockFreeConsumer<std::size_t>& theConsumer;
+ LockFreeConsumer<bool>& theContinueQueue;
+ DebuggerClient* theClient;
+ CommandPrompt* theCommandLine;
+ bool theQuit;
+ bool theTerminated;
+ bool theContinue;
+ std::size_t theWaitFor;
+
private:
void getNextId(std::set<std::size_t>& aIdList);
void addCommands();
- };
-
- template<>
- void CommandLineHandler::handle<Status> (ZORBA_TR1_NS::tuple<>& t);
-
- template<>
- void CommandLineHandler::handle<Quit> (ZORBA_TR1_NS::tuple<>& t);
-
- template<>
- void CommandLineHandler::handle<Run> (ZORBA_TR1_NS::tuple<> &t);
-
- template<>
- void CommandLineHandler::handle<StackDepth> (ZORBA_TR1_NS::tuple<>& t);
-
- template<>
- void CommandLineHandler::handle<BreakpointList> (ZORBA_TR1_NS::tuple<>& aTuple);
-
- template<>
- void CommandLineHandler::handle<BreakpointSet> (ZORBA_TR1_NS::tuple<bstring, bstring, bint> &t);
-
- template<>
- void CommandLineHandler::handle<BreakpointGet> (ZORBA_TR1_NS::tuple<bint>& aTuple);
-
- template<>
- void CommandLineHandler::handle<BreakpointDel>(ZORBA_TR1_NS::tuple<bint> &aTuple);
-
- template<>
- void CommandLineHandler::handle<StackGet> (ZORBA_TR1_NS::tuple<bint>& aTuple);
-
- template<>
- void CommandLineHandler::handle<ContextNames>(ZORBA_TR1_NS::tuple<> &aTuple);
-
- template<>
- void CommandLineHandler::handle<ContextGet>(ZORBA_TR1_NS::tuple<bint> &aTuple);
-
- template<>
- void CommandLineHandler::handle<Eval>(ZORBA_TR1_NS::tuple<bstring>& aTuple);
-
-}} // close namespaces zorba::debugclient
+};
+
+template<>
+void CommandLineHandler::handle<Status> (ZORBA_TR1_NS::tuple<>& t);
+
+template<>
+void CommandLineHandler::handle<Quit> (ZORBA_TR1_NS::tuple<>& t);
+
+template<>
+void CommandLineHandler::handle<Run> (ZORBA_TR1_NS::tuple<> &t);
+
+template<>
+void CommandLineHandler::handle<Stop> (ZORBA_TR1_NS::tuple<> &t);
+
+template<>
+void CommandLineHandler::handle<StackDepth> (ZORBA_TR1_NS::tuple<>& t);
+
+template<>
+void CommandLineHandler::handle<BreakpointList> (ZORBA_TR1_NS::tuple<>& aTuple);
+
+template<>
+void CommandLineHandler::handle<BreakpointSet> (ZORBA_TR1_NS::tuple<bstring, bstring, bint> &t);
+
+template<>
+void CommandLineHandler::handle<BreakpointGet> (ZORBA_TR1_NS::tuple<bint>& aTuple);
+
+template<>
+void CommandLineHandler::handle<BreakpointRemove>(ZORBA_TR1_NS::tuple<bint> &aTuple);
+
+template<>
+void CommandLineHandler::handle<StackGet> (ZORBA_TR1_NS::tuple<bint>& aTuple);
+
+template<>
+void CommandLineHandler::handle<ContextNames>(ZORBA_TR1_NS::tuple<> &aTuple);
+
+template<>
+void CommandLineHandler::handle<ContextGet>(ZORBA_TR1_NS::tuple<bint, bint> &aTuple);
+
+template<>
+void CommandLineHandler::handle<Source>(ZORBA_TR1_NS::tuple<bint, bint, bstring> &aTuple);
+
+template<>
+void CommandLineHandler::handle<Eval>(ZORBA_TR1_NS::tuple<bstring>& aTuple);
+
+template<>
+void CommandLineHandler::handle<StepIn> (ZORBA_TR1_NS::tuple<> &t);
+
+template<>
+void CommandLineHandler::handle<StepOut> (ZORBA_TR1_NS::tuple<> &t);
+
+template<>
+void CommandLineHandler::handle<StepOver> (ZORBA_TR1_NS::tuple<> &t);
+
+} // namespace zorba
+} // namespace debugger
+
+#endif // ZORBA_DEBUGGER_COMMAND_LINE_HANDLER_H
=== added file 'bin/debugger/command_prompt.cpp'
--- bin/debugger/command_prompt.cpp 1970-01-01 00:00:00 +0000
+++ bin/debugger/command_prompt.cpp 2012-01-25 00:12:28 +0000
@@ -0,0 +1,287 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "command_prompt.h"
+
+#include <string>
+#include <vector>
+#include <map>
+#include <iostream>
+
+#include "command.h"
+
+
+namespace zorba { namespace debugger {
+
+#ifdef ZORBA_HAVE_LIBEDIT_H
+const char*
+prompt(EditLine* aEl) {
+ return "(xqdb) ";
+}
+#endif
+
+CommandPrompt::CommandPrompt()
+{
+#ifdef ZORBA_HAVE_LIBEDIT_H
+ theEditLine = el_init("xqdb", stdin, stdout, stderr);
+ theHistory = history_init();
+ HistEvent lHistoryEvent;
+ history(theHistory, &lHistoryEvent, H_SETSIZE, 100);
+
+ el_set(theEditLine, EL_PROMPT, prompt);
+
+ el_set(theEditLine, EL_HIST, history, theHistory);
+ el_set(theEditLine, EL_EDITOR, "emacs");
+#endif
+}
+
+CommandPrompt::~CommandPrompt()
+{
+#ifdef ZORBA_HAVE_LIBEDIT_H
+ history_end(theHistory);
+ el_end(theEditLine);
+#endif
+
+ std::map<std::string, UntypedCommand*>::iterator lIter;
+ for (lIter = theCommands.begin(); lIter != theCommands.end(); ++lIter) {
+ delete lIter->second;
+ }
+}
+
+void
+CommandPrompt::printHelp(UntypedCommand* aCommand)
+{
+ // if no command is provided, print all the available commands
+ if (!aCommand) {
+ std::cout << "Available commands:" << std::endl;
+
+ // print the names of all commands
+ std::map<std::string, UntypedCommand*>::iterator lIter = theCommands.begin();
+ while (lIter != theCommands.end()) {
+ std::cout << " " << (*lIter).first;
+ std::set<std::string> lAliases = (*lIter).second->getAliases();
+ std::set<std::string>::const_iterator lAliasIter = lAliases.begin();
+ while (lAliasIter != lAliases.end()) {
+ std::cout << ", " << *lAliasIter;
+ lAliasIter++;
+ }
+ std::cout << std::endl;
+ lIter++;
+ }
+
+ // some hints for detailed help
+ std::cout << std::endl;
+ std::cout << "Type help <command> to get more information about one command." << std::endl;
+ std::cout << std::endl;
+ } else {
+ // ok, so we have a command; then print the help
+ aCommand->printHelp();
+ }
+}
+
+void
+CommandPrompt::execute()
+{
+ bool lWithOutput = true;
+
+ for (;;) {
+#ifdef ZORBA_HAVE_LIBEDIT_H
+ const char* lBuf;
+ int lCharsRead = -1;
+ lBuf = el_gets(theEditLine, &lCharsRead);
+ std::string lCommandLine(lBuf, lCharsRead - 1);
+#else
+ if (lWithOutput) {
+ std::cout << "(xqdb) ";
+ }
+ lWithOutput = true;
+ std::string lCommandLine;
+ std::getline(std::cin, lCommandLine);
+ if (std::cin.fail()) {
+ lWithOutput = false;
+ std::cin.clear();
+ continue;
+ }
+#endif
+
+ std::vector<std::string> lArgs;
+
+ // split the command into arguments
+ parseLine(lCommandLine, lArgs);
+ std::string::size_type lSize = lArgs.size();
+
+ // empty command? do nothing!
+ if (lSize == 0) {
+ lArgs = theLastArgs;
+ if (lArgs.size() == 0) {
+ continue;
+ }
+ }
+#ifdef ZORBA_HAVE_LIBEDIT_H
+ else {
+ HistEvent lHistoryEvent;
+ history(theHistory, &lHistoryEvent, H_ENTER, lCommandLine.c_str());
+ }
+#endif
+ theLastArgs = lArgs;
+
+ UntypedCommand* lCommand = NULL;
+
+ // help is not a command but a hook here
+ if (lArgs.at(0) == "h" || lArgs.at(0) == "help") {
+ std::string lCmd = "";
+
+ // if the user needs the help for a specific command
+ if (lSize > 1) {
+ // do nothing if we don't have a command starting with this prefix?
+ // findCommand will print the appropriate errors
+ if (!findCommand(lArgs[1], lCommand)) {
+ continue;
+ }
+ }
+ printHelp(lCommand);
+ continue;
+ }
+ if (findCommand(lArgs[0], lCommand) && lCommand->execute(lArgs)) {
+ return;
+ }
+ continue;
+ }
+}
+
+CommandPrompt&
+CommandPrompt::operator<<(UntypedCommand *aCommand)
+{
+ theCommands.insert(std::make_pair(aCommand->getName(), aCommand));
+ return *this;
+}
+
+bool
+CommandPrompt::findCommand(const std::string& aPrefix, UntypedCommand*& aCommand)
+{
+ std::vector<UntypedCommand*> lFoundCommands;
+
+ std::map<std::string, UntypedCommand*>::iterator lIter = theCommands.begin();
+ while (lIter != theCommands.end()) {
+ // if a command name is equal with the prefix, this is the command we want
+ if ((*lIter).first == aPrefix) {
+ aCommand = (*lIter).second;
+ return true;
+ }
+
+ bool lIsCandidate = false;
+
+ // add this command to candidate commands if the prefix matches
+ if ((*lIter).first.find(aPrefix) == 0) {
+ lFoundCommands.push_back((*lIter).second);
+ lIsCandidate = true;
+ }
+
+ // now process the aliases
+ std::set<std::string> lAliases = (*lIter).second->getAliases();
+ std::set<std::string>::const_iterator lAliasIter = lAliases.begin();
+ while (lAliasIter != lAliases.end()) {
+ // if a command alias is equal with the prefix, this is the command we want
+ if (*lAliasIter == aPrefix) {
+ aCommand = (*lIter).second;
+ return true;
+ }
+
+ // add this command to candidate commands if the prefix matches one alias
+ // and if the command is not already added
+ if (!lIsCandidate && (*lAliasIter).find(aPrefix) == 0) {
+ lFoundCommands.push_back((*lIter).second);
+ break;
+ }
+ lAliasIter++;
+ }
+
+ lIter++;
+ }
+
+ if (lFoundCommands.empty()) {
+ std::cout << "Command not found: " << aPrefix << std::endl;
+ return false;
+ }
+
+ if (lFoundCommands.size() > 1) {
+ std::cout << "Ambigous command: " << aPrefix << std::endl;
+ // show all possible commands that start with this prefix
+ for (std::string::size_type i = 0; i < lFoundCommands.size(); i++) {
+ UntypedCommand* lCommand = lFoundCommands.at(i);
+
+ // commands
+ if (lCommand->getName().find(aPrefix) == 0) {
+ std::cout << " " << lCommand->getName() << std::endl;
+ }
+
+ // and aliases
+ std::set<std::string> lAliases = lCommand->getAliases();
+ std::set<std::string>::const_iterator lAliasIter = lAliases.begin();
+ while (lAliasIter != lAliases.end()) {
+ if ((*lAliasIter).find(aPrefix) == 0) {
+ std::cout << " " << *lAliasIter << std::endl;
+ }
+ lAliasIter++;
+ }
+ }
+ return false;
+ }
+
+ aCommand = lFoundCommands[0];
+ return true;
+}
+
+void
+CommandPrompt::parseLine(const std::string& aLine, std::vector<std::string>& aVector)
+{
+ std::string::size_type lBefore = 0;
+ std::string::size_type lPos = aLine.find_first_of(" \t", 0);
+
+ while (lPos != aLine.npos) {
+ std::string lSub = aLine.substr(lBefore, lPos - lBefore);
+
+ // if two consecutive spaces, you get an empty string here
+ if (lSub != "") {
+ if (lSub[0] == '"') {
+ std::string::size_type lBeforeCopy = lBefore;
+ do {
+ lBeforeCopy = aLine.find("\"", lBeforeCopy + 1);
+ } while (lPos != aLine.npos && aLine.size() > lPos + 1 && aLine[lPos + 1] == '\\');
+ lPos = lBeforeCopy;
+ lSub = aLine.substr(lBefore + 1, lPos - lBefore - 1);
+ }
+ aVector.push_back(lSub);
+ }
+
+ lBefore = lPos + 1;
+ lPos = aLine.find_first_of(" \t", lBefore);
+ }
+ std::string lSub = aLine.substr(lBefore);
+
+ // catching the case when the command ends with a space
+ if (lSub == "") {
+ return;
+ }
+
+ if (lSub[0] == '"') {
+ lPos = aLine.find("\"", lBefore + 1);
+ lSub = aLine.substr(lBefore + 1, lPos - lBefore - 1);
+ }
+ aVector.push_back(lSub);
+}
+
+} // namespace zorba
+} // namespace debugger
=== added file 'bin/debugger/command_prompt.h'
--- bin/debugger/command_prompt.h 1970-01-01 00:00:00 +0000
+++ bin/debugger/command_prompt.h 2012-01-25 00:12:28 +0000
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+#ifndef ZORBA_DEBUGGER_COMMAND_PROMPT_H
+#define ZORBA_DEBUGGER_COMMAND_PROMPT_H
+
+#include <string>
+#include <map>
+#include <vector>
+
+#include "config.h"
+
+#ifdef ZORBA_HAVE_LIBEDIT_H
+# include <histedit.h>
+#endif
+
+
+namespace zorba { namespace debugger {
+
+class UntypedCommand;
+
+class CommandPrompt
+{
+ public:
+ CommandPrompt();
+ ~CommandPrompt();
+
+ public:
+
+ void execute();
+
+ CommandPrompt& operator<< (UntypedCommand* command);
+
+ private:
+
+ void
+ printHelp(UntypedCommand* command);
+
+ bool
+ findCommand(const std::string& prefix, UntypedCommand*& command);
+
+ void
+ parseLine(const std::string& line, std::vector<std::string>& vector);
+
+ private:
+ std::map<std::string, UntypedCommand*> theCommands;
+ std::vector<std::string> theLastArgs;
+
+#ifdef ZORBA_HAVE_LIBEDIT_H
+ EditLine* theEditLine;
+ History* theHistory;
+#endif
+};
+
+
+} // namespace zorba
+} // namespace debugger
+
+#endif // ZORBA_DEBUGGER_COMMAND_PROMPT_H
=== added file 'bin/debugger/config.h.cmake'
--- bin/debugger/config.h.cmake 1970-01-01 00:00:00 +0000
+++ bin/debugger/config.h.cmake 2012-01-25 00:12:28 +0000
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// This header is configured by Zorba's build process -- DO NOT EDIT!
+
+#ifndef ZORBA_DEBUGGER_CONFIG_H
+#define ZORBA_DEBUGGER_CONFIG_H
+
+#cmakedefine ZORBA_HAVE_LIBEDIT_H
+
+#endif /* ZORBA_DEBUGGER_CONFIG_H */
=== modified file 'bin/debugger/event_handler.cpp'
--- bin/debug_client/event_handler.cpp 2011-07-01 01:53:24 +0000
+++ bin/debugger/event_handler.cpp 2012-01-25 00:12:28 +0000
@@ -13,88 +13,93 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
+#include "event_handler.h"
+
+#include <sstream>
+
#include <zorba/zorba.h>
#include <zorba/store_manager.h>
#include <zorba/iterator.h>
-#include <sstream>
-#include "debug_client/event_handler.h"
-namespace zorba { namespace debugclient {
+namespace zorba { namespace debugger {
- EventHandler::EventHandler(LockFreeProducer<std::size_t>& aQueue, LockFreeProducer<bool>& aContProducer)
+EventHandler::EventHandler(LockFreeProducer<std::size_t>& aQueue, LockFreeProducer<bool>& aContProducer)
: theIdQueue(aQueue), theContinueProducer(aContProducer),
theStore(StoreManager::getStore()),
theZorbaInstance(Zorba::getInstance(theStore)),
theStaticContext(theZorbaInstance->createStaticContext())
-
- {
- try {
- Zorba_CompilerHints_t lHints;
- lHints.opt_level = ZORBA_OPT_LEVEL_O1;
- std::auto_ptr<std::istream> stream(getCurrentDirectory());
- zorba::String query;
- char buffer[1024];
- std::string::size_type s;
- while ((s = stream->readsome(buffer, 1024))) {
- query.append(std::string(buffer, s));
- }
- theStaticContext->loadProlog(query, lHints);
- } catch (zorba::ZorbaException& e) {
- std::cerr << "Exception: I was not able to load the query file:" << std::endl;
- std::cerr << e.what() << std::endl;
- throw;
- }
- }
-
- EventHandler::~EventHandler()
- {
- theStaticContext = 0;
- theZorbaInstance->shutdown();
- StoreManager::shutdownStore(theStore);
- }
-
- void EventHandler::parseMessage(const std::string &aMessage)
- {
- try {
- zorba::String queryString = "local:main(";
- queryString += aMessage + ")";
- XQuery_t query = theZorbaInstance->compileQuery(queryString, theStaticContext);
- Iterator_t lIter = query->iterator();
- Item item;
- lIter->open();
- bool doContinue = false;
- lIter->next(item);
- {
- const std::string& continueString = item.getStringValue().str();
- if (continueString == "true") {
- doContinue = true;
- } else if (continueString == "false") {
- doContinue = false;
- } else {
- std::stringstream stream(continueString);
- stream >> doContinue;
- }
- }
- lIter->next(item);
- std::size_t lId;
- {
- std::stringstream stream(item.getStringValue().c_str());
- stream >> lId;
- }
- lIter->next(item);
- std::cout << item.getStringValue() << std::endl;
- theContinueProducer.produce(doContinue);
- theIdQueue.produce(lId);
- } catch (ZorbaException& e) {
- std::cerr << "FATAL: could not execute query: " << std::endl;
- std::cerr << e << std::endl;
- std::cerr << "This is a bug, please report to zorba-users@xxxxxxxxxxxxxxxxxxxxx" << std::endl;
- theContinueProducer.produce(false);
- }
- }
-
- void EventHandler::error(unsigned int errcode, const std::string &msg)
- {
- std::cerr << "Error " << errcode << ": " << msg << std::endl;
- }
-}}
+{
+}
+
+EventHandler::~EventHandler()
+{
+ theStaticContext = 0;
+ theZorbaInstance->shutdown();
+ StoreManager::shutdownStore(theStore);
+}
+
+void
+EventHandler::init()
+{
+ try {
+ Zorba_CompilerHints_t lHints;
+ lHints.opt_level = ZORBA_OPT_LEVEL_O1;
+ zorba::String lProlog("import module namespace dmh = 'http://www.zorba-xquery.com/modules/debugger/dbgp-message-handler';");
+ theStaticContext->loadProlog(lProlog, lHints);
+ } catch (zorba::ZorbaException& e) {
+ std::cerr << "Exception: I was not able to load the query file:" << std::endl;
+ std::cerr << e.what() << std::endl;
+ throw;
+ }
+}
+
+void
+EventHandler::parseMessage(const std::string &aMessage)
+{
+ try {
+#ifndef NDEBUG
+ // uncomment this to see the raw messages received by the event handler
+ //std::cout << "Processing response: " << aMessage << std::endl;
+#endif
+ // the query to process the response
+ std::stringstream lQueryStream;
+ lQueryStream << "dmh:process(" << aMessage << ")";
+ XQuery_t lQuery = theZorbaInstance->compileQuery(lQueryStream.str(), theStaticContext);
+
+ // get the query result sequrence:
+ // 1. a message
+ Iterator_t lIter = lQuery->iterator();
+ Item lItem;
+ lIter->open();
+ lIter->next(lItem);
+ std::size_t lId;
+ std::stringstream lStream(lItem.getStringValue().c_str());
+ lStream >> lId;
+
+ // 2. an "idle" flag (to disable quit confirmation)
+ bool lCanQuit = false;
+ if (lIter->next(lItem)) {
+ String lMessage = lItem.getStringValue();
+ lCanQuit = lMessage == "idle";
+ std::cout << std::endl << lItem.getStringValue() << std::endl;
+ }
+ theContinueProducer.produce(lCanQuit);
+
+ // go and solve the event with this id
+ theIdQueue.produce(lId);
+ } catch (ZorbaException& e) {
+ std::cerr << "FATAL: could not execute query: " << std::endl;
+ std::cerr << e << std::endl;
+ std::cerr << "This is a bug, please report it at http://bugs.launchpad.net/zorba" << std::endl;
+ }
+}
+
+void
+EventHandler::error(unsigned int errcode, const std::string &msg)
+{
+ std::cerr << "Error " << errcode << ": " << msg << std::endl;
+}
+
+} // namespace zorba
+} // namespace debugger
=== modified file 'bin/debugger/event_handler.h'
--- bin/debug_client/event_handler.h 2011-07-01 01:53:24 +0000
+++ bin/debugger/event_handler.h 2012-01-25 00:12:28 +0000
@@ -14,33 +14,46 @@
* limitations under the License.
*/
#pragma once
+#ifndef ZORBA_DEBUGGER_EVENT_HANDLER_H
+#define ZORBA_DEBUGGER_EVENT_HANDLER_H
+
#include <string>
#include <iostream>
+
#include <zorba/debugger_event_handler.h>
#include <zorba/static_context.h>
+
#include "lock_free_queue.h"
-namespace zorba {
- class Zorba;
-}
-
-namespace zorba { namespace debugclient {
-
- class EventHandler : public zorba::DebuggerEventHandler
- {
+
+namespace zorba { namespace debugger {
+
+class EventHandler : public zorba::DebuggerEventHandler
+{
public:
- EventHandler(LockFreeProducer<std::size_t>& aQueue, LockFreeProducer<bool>& aContQueue);
+ EventHandler(
+ LockFreeProducer<std::size_t>& aQueue,
+ LockFreeProducer<bool>& aContQueue);
+
~EventHandler();
+
public:
virtual void parseMessage(const std::string& aMessage);
+
virtual void error(unsigned int errcode, const std::string& msg);
+
+ virtual void init();
+
private:
- static std::istream* getCurrentDirectory();
LockFreeProducer<std::size_t>& theIdQueue;
LockFreeProducer<bool>& theContinueProducer;
void* theStore;
Zorba* theZorbaInstance;
StaticContext_t theStaticContext;
- };
+
+};
-}} // end of namespace zorba::debugclient
+} // namespace zorba
+} // namespace debugger
+
+#endif // ZORBA_DEBUGGER_EVENT_HANDLER_H
=== modified file 'bin/debugger/lock_free_queue.h'
--- bin/debug_client/lock_free_queue.h 2011-07-01 01:53:24 +0000
+++ bin/debugger/lock_free_queue.h 2012-01-25 00:12:28 +0000
@@ -14,10 +14,14 @@
* limitations under the License.
*/
#pragma once
+#ifndef ZORBA_DEBUGGER_LOCK_FREE_QUEUE_H
+#define ZORBA_DEBUGGER_LOCK_FREE_QUEUE_H
+
#include <iostream>
#include <list>
-namespace zorba { namespace debugclient {
+
+namespace zorba { namespace debugger {
template<typename T>
class LockFreeProducer
@@ -80,4 +84,8 @@
}
return false;
}
-}} // namespace zorba::debugclient
+
+} // namespace zorba
+} // namespace debugger
+
+#endif // ZORBA_DEBUGGER_LOCK_FREE_QUEUE_H
=== modified file 'bin/debugger/main.cpp'
--- bin/debug_client/main.cpp 2011-07-01 01:53:24 +0000
+++ bin/debugger/main.cpp 2012-01-25 00:12:28 +0000
@@ -13,12 +13,286 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
+#ifdef WIN32
+# include <windows.h>
+# include <string.h>
+# include <strsafe.h>
+#endif
+
+#include <vector>
+
#include <zorba/config.h>
-#include "debug_command.h"
-#include "command_line_handler.h"
+
+#include "xqdb_client.h"
+#include "process_listener.h"
+
using namespace zorba;
-using namespace zorba::debugclient;
+using namespace zorba::debugger;
+
+
+std::auto_ptr<XqdbClient> theClient;
+
+// this will make sure the xqdb process will not quit when Ctrl-C is pressed
+#ifdef WIN32
+BOOL WINAPI
+ctrlC_Handler(DWORD aCtrlType)
+{
+ if (CTRL_C_EVENT == aCtrlType) {
+ return true;
+ }
+ return false;
+}
+#else
+void
+ctrlC_Handler(int lParam)
+{
+ // an empty sugnal handler on Linux should do the job
+}
+#endif
+
+
+// this handler function is passed the the zorba process listener and will
+// the client if the zorba process terminates
+void
+onExitProcess(ExitCode aExitCode) {
+ std::cout << std::endl << "Terminating debugger client." << std::endl;
+
+#ifndef WIN32
+ XqdbClient* lClient = theClient.release();
+ if (lClient) {
+ delete lClient;
+ }
+#endif
+
+ exit(aExitCode);
+}
+
+
+int
+startZorba(std::string& aExec, std::vector<std::string>& aArgs, std::auto_ptr<ProcessListener>& aProcessListener)
+{
+#ifdef WIN32
+ // **************************
+ // start a process on Windows
+
+ DWORD iReturnVal = 0;
+
+ std::wstring lExec;
+ std::wstring lArgs;
+
+ lExec.assign(aExec.begin(), aExec.end());
+
+ // the executable must be the first in the list of arguments
+ lArgs.append(L"\"");
+ lArgs.append(lExec);
+ lArgs.append(L"\"");
+
+ for (std::vector<std::string>::size_type j = 0; j < aArgs.size(); j++) {
+ std::string lArg(aArgs.at(j));
+ std::wstring lArgW;
+ lArgW.assign(lArg.begin(), lArg.end());
+ lArgs.append(L" ");
+ lArgs.append(lArgW);
+ }
+
+ // CreateProcessW can modify Parameters thus we allocate needed memory
+ wchar_t * pwszParam = new wchar_t[lArgs.size() + 1];
+ if (pwszParam == 0) {
+ return 1;
+ }
+ const wchar_t* pchrTemp = lArgs.c_str();
+ wcscpy_s(pwszParam, lArgs.size() + 1, pchrTemp);
+
+ // CreateProcess API initialization
+ STARTUPINFOW siStartupInfo;
+ PROCESS_INFORMATION piProcessInfo;
+ memset(&siStartupInfo, 0, sizeof(siStartupInfo));
+ memset(&piProcessInfo, 0, sizeof(piProcessInfo));
+ siStartupInfo.cb = sizeof(siStartupInfo);
+
+ BOOL lResult = CreateProcessW(
+ const_cast<LPCWSTR>(lExec.c_str()),
+ pwszParam, 0, 0, false,
+ CREATE_DEFAULT_ERROR_MODE, 0, 0,
+ &siStartupInfo, &piProcessInfo);
+
+ if (lResult) {
+ // Watch the process
+ aProcessListener.reset(new ProcessListener(piProcessInfo.dwProcessId, &onExitProcess));
+ }
+ else {
+ // CreateProcess failed
+ iReturnVal = GetLastError();
+ LPVOID lpMsgBuf;
+ LPVOID lpDisplayBuf;
+
+ FormatMessage(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL,
+ iReturnVal,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPTSTR) &lpMsgBuf,
+ 0, NULL);
+
+ // Display the error message and exit the process
+
+ lpDisplayBuf = (LPVOID)LocalAlloc(
+ LMEM_ZEROINIT,
+ (lstrlen((LPCTSTR)lpMsgBuf) + 40) * sizeof(TCHAR));
+
+ StringCchPrintf(
+ (LPTSTR)lpDisplayBuf,
+ LocalSize(lpDisplayBuf) / sizeof(TCHAR),
+ TEXT("Error (%d) when starting zorba: %s"),
+ iReturnVal,
+ lpMsgBuf);
+
+ std::wstring lErrorW((wchar_t*)lpDisplayBuf);
+ std::string lError;
+ lError.assign(lErrorW.begin(), lErrorW.end());
+ std::cout << lError << std::endl;
+
+ LocalFree(lpMsgBuf);
+ LocalFree(lpDisplayBuf);
+ }
+
+ // Free memory
+ delete[]pwszParam;
+ pwszParam = 0;
+
+ // Release handles
+ CloseHandle(piProcessInfo.hProcess);
+ CloseHandle(piProcessInfo.hThread);
+
+ return iReturnVal;
+
+#else
+ // ************************
+ // start a process on Linux
+
+ pid_t pID = fork();
+ if (pID == 0) {
+ // Code only executed by child process
+ std::stringstream lCommand;
+ lCommand << aExec;
+ for (std::vector<std::string>::size_type j = 0; j < aArgs.size(); j++) {
+ lCommand << " " << aArgs.at(j);
+ }
+
+ int lRes = system(lCommand.str().c_str());
+ exit(lRes);
+ }
+ else {
+ // Code only executed by parent process
+ if (pID < 0) {
+ std::cerr << "Failed to fork Zorba" << std::endl;
+ return pID;
+ }
+
+ // Watch the process
+ aProcessListener.reset(new ProcessListener(pID, &onExitProcess));
+
+ return 0;
+ }
+#endif
+}
+
+void printUsage(std::string& aProgram)
+{
+ std::cerr << "Usage:" << std::endl
+ << " " << aProgram << " <zorba_arguments>" << std::endl
+ << " this will start a debugger command line and a zorba process with the given arguments" << std::endl;
+}
+
+bool
+processArguments(
+ int argc,
+ char* argv[],
+ std::string& aProgram,
+ bool& aStandalone,
+ std::string& aZorba,
+ unsigned int& aPort,
+ std::vector<std::string>& aZorbaArgs)
+{
+ aPort = 28028;
+
+ // find the path to Zorba and this executable name
+ aProgram = argv[0];
+
+#ifdef WIN32
+ char lSep = '\\';
+#else
+ char lSep = '/';
+#endif
+ std::string::size_type lPos = aProgram.find_last_of(lSep);
+
+ std::stringstream lZs;
+
+ if (lPos == aProgram.npos) {
+ lZs << "." << lSep;
+ } else {
+ lZs << aProgram.substr(0, lPos + 1);
+ aProgram = aProgram.substr(lPos + 1);
+ }
+ lZs << "zorba";
+#ifdef WIN32
+ lZs << ".exe";
+#endif
+ aZorba = lZs.str();
+
+
+ bool lHasFileArg = false;
+ bool lHasQueryArg = false;
+ bool lHasQueryVal = false;
+
+ // find if the user asked for help or specified a specific port
+ for (int i = 1; i < argc; i++) {
+ std::string lArg = argv[i];
+ if (lArg == "-h" || lArg == "--help") {
+ return false;
+ }
+ else if (lArg == "-p" || lArg == "--debug-port") {
+ // if there is one more argument
+ if (i < argc - 1) {
+ // get the port value
+ int lPort;
+ std::stringstream lStream(argv[i + 1]);
+ lStream >> lPort;
+ if (!lStream.fail()) {
+ aPort = lPort;
+ }
+ }
+ }
+ else if (lArg == "-f") {
+ lHasFileArg = true;
+ }
+ else if (lArg == "-q") {
+ lHasQueryArg = true;
+ if (++i < argc) {
+ lHasQueryVal = true;
+ }
+ }
+ }
+
+ if (!lHasFileArg || !lHasQueryArg || !lHasQueryVal) {
+ std::cout << "Not enough arguments to start Zorba." << std::endl;
+ std::cout << "Running the standalone XQuery debugger client on port: " << aPort << std::endl;
+ return true;
+ }
+
+ // zorba will need the -d flag
+ aZorbaArgs.push_back("-d");
+
+ // gather all arguments (excepting the program name)
+ for (int i = 1; i < argc; i++) {
+ aZorbaArgs.push_back(argv[i]);
+ }
+
+ aStandalone = false;
+ return true;
+}
#ifndef _WIN32_WCE
int
@@ -28,24 +302,72 @@
_tmain(int argc, _TCHAR* argv[])
#endif
{
- int port = 28028;
- if (argv[1]) {
- std::stringstream stream(argv[1]);
- stream >> port;
- if (stream.fail() || argv[2]) {
- std::cerr << "Unknown argument. USAGE: " << argv[0] << " [PORT]" << std::endl;
- return 2;
+#ifdef WIN32
+ SetConsoleCtrlHandler(ctrlC_Handler, TRUE);
+#else
+ signal(SIGINT, ctrlC_Handler);
+#endif
+
+ // **************************************************************************
+ // processing arguments
+
+ std::string lProgram, lZorbaExec;
+ unsigned int lPort = 28028;
+ std::vector<std::string> lZorbaArgs;
+
+ bool lStandalone = true;
+ if (!processArguments(argc, argv, lProgram, lStandalone, lZorbaExec, lPort, lZorbaArgs)) {
+ printUsage(lProgram);
+ return 1;
+ }
+
+#ifndef NDEBUG
+ // **************************************************************************
+ // debug reporting
+
+ if (!lStandalone) {
+ std::cout << "Communication port: " << lPort << std::endl;
+ std::cout << "Zorba executable: " << lZorbaExec << std::endl;
+ std::cout << "Zorba arguments: ";
+ for (std::vector<std::string>::size_type j = 0; j < lZorbaArgs.size(); j++) {
+ std::cout << lZorbaArgs.at(j) << " ";
}
+ std::cout << std::endl;
}
+#endif
+
try {
- LockFreeQueue<std::size_t> lQueue;
- LockFreeQueue<bool> lContEvent;
- EventHandler lHandler(lQueue, lContEvent);
- CommandLine cli;
- CommandLineHandler handler(port, lQueue, lContEvent, lHandler, cli);
- handler.execute();
+ // **************************************************************************
+ // start a zorba
+
+ // This is a process listener used to watch the Zorba process termination.
+ std::auto_ptr<ProcessListener> lProcessListener;
+
+ if (!lStandalone) {
+ int lResult = startZorba(lZorbaExec, lZorbaArgs, lProcessListener);
+ if (lResult) {
+ return lResult;
+ }
+ } else {
+ std::cout << "Listening for an incomming Zorba connection on port " << lPort << "..." << std::endl;
+ }
+
+ // **************************************************************************
+ // start the debugger command line
+
+ theClient.reset(new XqdbClient(lPort));
+ theClient->start();
+
} catch (...) {
- return 4;
- }
+ return -1;
+ }
+
+#ifndef WIN32
+ XqdbClient* lClient = theClient.release();
+ if (lClient) {
+ delete lClient;
+ }
+#endif
+
return 0;
}
=== added file 'bin/debugger/process_listener.cpp'
--- bin/debugger/process_listener.cpp 1970-01-01 00:00:00 +0000
+++ bin/debugger/process_listener.cpp 2012-01-25 00:12:28 +0000
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "process_listener.h"
+
+#include <iostream>
+
+#ifdef ZORBA_HAVE_PTHREAD_H
+# include <cassert>
+#endif
+
+
+namespace zorba { namespace debugger {
+
+ProcessListener::ProcessListener(ProcessId aProcessID, ExitCallbackType aCallback)
+ : theProcessID(aProcessID), theCallback(aCallback)
+{
+#ifdef WIN32
+ theThread = CreateThread(NULL, 0, &run, (void*) this, 0, &theThreadId);
+#else
+ if (pthread_create(&theThread, NULL, &run, (void*) this)) {
+ assert(false);
+ }
+#endif
+}
+
+ProcessListener::~ProcessListener()
+{
+}
+
+ProcessId
+ProcessListener::getProcessID()
+{
+ return theProcessID;
+}
+
+ExitCallbackType
+ProcessListener::getCallback()
+{
+ return theCallback;
+}
+
+
+ZORBA_THREAD_RETURN
+ProcessListener::run(void* params)
+{
+ ProcessListener* lThis = static_cast<ProcessListener*>(params);
+ ExitCode lExitCode = -1;
+ ProcessId lPid = lThis->getProcessID();
+
+#ifdef WIN32
+ HANDLE lProcessHandle = OpenProcess(SYNCHRONIZE, false, lPid);
+ if (lProcessHandle != NULL) {
+ // wait for the process to exit
+ DWORD lResult = WaitForSingleObject(lProcessHandle, INFINITE);
+
+ // find out the process exit code if possible
+ if (!GetExitCodeProcess(lProcessHandle, &lExitCode)) {
+ lExitCode = -1;
+ }
+ DWORD dw = GetLastError();
+
+ // wait a little for zorba to dump the garbage
+ Sleep(1000);
+ }
+#else
+ int lChildExitStatus;
+
+ // wait for the process to exit
+ waitpid(lPid, &lChildExitStatus, 0);
+
+ // find out the process exit code if possible
+ if (WIFEXITED(lChildExitStatus)) {
+ lExitCode = WEXITSTATUS(lChildExitStatus);
+ }
+
+ // wait a little for zorba to dump the garbage
+ sleep(1);
+#endif
+
+ // and call the callback when this happened
+ ExitCallbackType lCallback = lThis->getCallback();
+ lCallback(lExitCode);
+
+ for (int i = 0; i < 10; i++) {
+ std::cout << i << std::endl;
+ }
+ return NULL;
+}
+
+} // namespace zorba
+} // namespace debugger
=== added file 'bin/debugger/process_listener.h'
--- bin/debugger/process_listener.h 1970-01-01 00:00:00 +0000
+++ bin/debugger/process_listener.h 2012-01-25 00:12:28 +0000
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+#ifndef ZORBA_DEBUGGER_PROCESS_LISTENER_H
+#define ZORBA_DEBUGGER_PROCESS_LISTENER_H
+
+#include <zorba/config.h>
+
+#ifdef ZORBA_HAVE_PTHREAD_H
+# include <pthread.h>
+# include <sys/wait.h>
+ typedef pthread_t ThreadId;
+ typedef pid_t ProcessId;
+ typedef int ExitCode;
+# define ZORBA_THREAD_RETURN void *
+#else
+# include <windows.h>
+ typedef DWORD ThreadId;
+ typedef DWORD ProcessId;
+ typedef DWORD ExitCode;
+# define ZORBA_THREAD_RETURN DWORD WINAPI
+#endif
+
+typedef void (*ExitCallbackType)(ExitCode);
+
+
+namespace zorba { namespace debugger {
+
+class ProcessListener
+{
+ public:
+ ProcessListener(ProcessId processID, ExitCallbackType callback);
+
+ ~ProcessListener();
+
+ ProcessId
+ getProcessID();
+
+ ExitCallbackType
+ getCallback();
+
+ private:
+
+ static ZORBA_THREAD_RETURN run(void* params);
+
+ private:
+
+#ifdef ZORBA_HAVE_PTHREAD_H
+ pthread_t theThread;
+#else
+ ThreadId theThreadId;
+ HANDLE theThread;
+#endif
+
+ ProcessId theProcessID;
+ ExitCallbackType theCallback;
+};
+
+} // namespace zorba
+} // namespace debugger
+
+#endif // ZORBA_DEBUGGER_PROCESS_LISTENER_H
=== modified file 'bin/debugger/tuple.h'
--- bin/debug_client/tuple.h 2011-07-04 08:05:46 +0000
+++ bin/debugger/tuple.h 2012-01-25 00:12:28 +0000
@@ -14,9 +14,15 @@
* limitations under the License.
*/
#pragma once
+#ifndef ZORBA_DEBUGGER_TUPLE_H
+#define ZORBA_DEBUGGER_TUPLE_H
+
#include <zorba/config.h>
+
#if ZORBA_TR1_IN_TR1_SUBDIRECTORY
# include <tr1/tuple>
#else
# include <tuple>
#endif
+
+#endif // ZORBA_DEBUGGER_TUPLE_H
=== added file 'bin/debugger/xqdb_client.cpp'
--- bin/debugger/xqdb_client.cpp 1970-01-01 00:00:00 +0000
+++ bin/debugger/xqdb_client.cpp 2012-01-25 00:12:28 +0000
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "xqdb_client.h"
+
+#include <iostream>
+
+#ifdef ZORBA_HAVE_PTHREAD_H
+# include <cassert>
+#endif
+
+
+namespace zorba { namespace debugger {
+
+XqdbClient::XqdbClient(unsigned int aPort)
+{
+ theIdQueue = new LockFreeQueue<std::size_t>();
+ theQuitQueue = new LockFreeQueue<bool>();
+ theEventHandler = new EventHandler(*theIdQueue, *theQuitQueue);
+ theEventHandler->init();
+
+ theCommandPrompt = new CommandPrompt();
+ theCommandLineHandler = new CommandLineHandler(aPort, *theIdQueue, *theQuitQueue, theEventHandler, theCommandPrompt);
+}
+
+XqdbClient::~XqdbClient()
+{
+ if (theCommandLineHandler) {
+ delete theCommandLineHandler;
+ }
+ if (theCommandPrompt) {
+ delete theCommandPrompt;
+ }
+ if (theEventHandler) {
+ delete theEventHandler;
+ }
+
+ delete theIdQueue;
+ delete theQuitQueue;
+}
+
+void
+XqdbClient::start()
+{
+ theCommandLineHandler->execute();
+}
+
+
+} // namespace zorba
+} // namespace debugger
=== added file 'bin/debugger/xqdb_client.h'
--- bin/debugger/xqdb_client.h 1970-01-01 00:00:00 +0000
+++ bin/debugger/xqdb_client.h 2012-01-25 00:12:28 +0000
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2006-2008 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+#ifndef ZORBA_DEBUGGER_XQDB_CLIENT_H
+#define ZORBA_DEBUGGER_XQDB_CLIENT_H
+
+#include "command_prompt.h"
+#include "command_line_handler.h"
+
+
+namespace zorba { namespace debugger {
+
+class XqdbClient {
+
+ public:
+
+ XqdbClient(unsigned int aPort);
+
+ ~XqdbClient();
+
+ void
+ start();
+
+ private:
+
+ LockFreeQueue<std::size_t>* theIdQueue;
+ LockFreeQueue<bool>* theQuitQueue;
+
+ EventHandler* theEventHandler;
+ CommandPrompt* theCommandPrompt;
+ CommandLineHandler* theCommandLineHandler;
+};
+
+
+} // namespace zorba
+} // namespace debugger
+
+#endif // ZORBA_DEBUGGER_XQDB_CLIENT_H
=== renamed file 'bin/module_path.cpp' => 'bin/path_util.cpp'
--- bin/module_path.cpp 2011-05-25 16:40:26 +0000
+++ bin/path_util.cpp 2012-01-25 00:12:28 +0000
@@ -14,85 +14,100 @@
* limitations under the License.
*/
-#include "module_path.h"
+#include "path_util.h"
#include <stdlib.h>
-#include "zorba/zorba_string.h"
+//#include "zorba/zorba_string.h"
#include "zorba/util/path.h"
#include "util.h"
#include "zorbacmdproperties.h"
+#include <zorba/static_context.h>
namespace zorba {
-std::string
-ModulePath::getEnvironmentModulePath()
+namespace PathUtil {
+
+static std::string
+getPathFromEnvironment(std::string const& aEnvVar)
{
- std::string lEnvName("ZORBA_MODULE_PATH");
#ifdef WIN32
char* lBuffer;
size_t lLen=0;
- errno_t lErr = getenv_s(&lLen, NULL, 0, lEnvName.c_str());
+ errno_t lErr = getenv_s(&lLen, NULL, 0, aEnvVar.c_str());
if (lErr || !lLen) return "";
lBuffer = (char*)malloc(lLen * sizeof(char));
if (!lBuffer) return "";
- getenv_s(&lLen, lBuffer, lLen, lEnvName.c_str());
+ getenv_s(&lLen, lBuffer, lLen, aEnvVar.c_str());
std::string lRes(lBuffer);
free(lBuffer);
return lRes;
#else
- const char* lEnvValue = getenv(lEnvName.c_str());
- return lEnvValue!=0?lEnvValue:"";
+ const char* lEnvValue = getenv(aEnvVar.c_str());
+ return lEnvValue != 0 ? lEnvValue : "";
#endif
}
-void
-ModulePath::convertVector(
- const std::vector<std::string>& aSource,
- std::vector<String>& aDest)
-{
- for (std::vector<std::string>::const_iterator lIter = aSource.begin();
- lIter != aSource.end(); ++lIter) {
- aDest.push_back(*lIter);
- }
-}
-void
-ModulePath::tokenizeModulePath(
- const std::string& aModulePath,
- std::vector<std::string>& aResult)
+static void
+tokenizePath(
+ const std::string& aPathStr,
+ std::vector<String>& aResult)
{
+ std::vector<std::string> lPath;
#ifdef WIN32
- Util::tokenize(aModulePath, ";", aResult);
+ Util::tokenize(aPathStr, ";", lPath);
#else
- Util::tokenize(aModulePath, ":", aResult);
+ Util::tokenize(aPathStr, ":", lPath);
#endif
+ for (std::vector<std::string>::iterator lIter = lPath.begin();
+ lIter != lPath.end(); ++lIter) {
+ aResult.push_back(*lIter);
+ }
}
void
-ModulePath::getModulePaths(
+setPathsOnContext(
const ZorbaCMDProperties& aProperties,
- std::vector<String>& aModulePaths)
+ StaticContext_t& aStaticCtx)
{
- std::vector<std::string> lModulePaths; // result vector
- std::string lModulePath; // temporary variable for collections paths
-
- // 1. add the module paths from the command line properties
- aProperties.getModulePaths(lModulePath);
-
- tokenizeModulePath(lModulePath, lModulePaths);
-
- // 2. add the module paths from the environment
- lModulePath = ModulePath::getEnvironmentModulePath();
-
- tokenizeModulePath(lModulePath, lModulePaths);
-
- // 3. add the current working directory as module path
+ std::vector<String> lPath;
+ std::string lPathStr, lEnvStr;
+
+ // Compute the current working directory to append to all paths.
filesystem_path lCWD;
- lModulePaths.push_back(lCWD.get_path());
-
- // convert std::string to zorba::String
- convertVector(lModulePaths, aModulePaths);
+
+ // setModulePaths() *overwrites* the URI path and lib path, so there's no
+ // sense in calling both. So if either --module-path or ZORBA_MODULE_PATH
+ // exists, just use those.
+ aProperties.getModulePath(lPathStr);
+ lEnvStr = getPathFromEnvironment("ZORBA_MODULE_PATH");
+ if (lPathStr.length() > 0 || lEnvStr.length() > 0) {
+ tokenizePath(lPathStr, lPath);
+ tokenizePath(lEnvStr, lPath);
+ lPath.push_back(lCWD.get_path());
+ aStaticCtx->setModulePaths(lPath);
+ }
+ else {
+ // Compute and set URI path
+ aProperties.getURIPath(lPathStr);
+ tokenizePath(lPathStr, lPath);
+ lEnvStr = getPathFromEnvironment("ZORBA_URI_PATH");
+ tokenizePath(lEnvStr, lPath);
+ lPath.push_back(lCWD.get_path());
+ aStaticCtx->setURIPath(lPath);
+ lPath.clear();
+
+ // Compute and set lib path
+ aProperties.getLibPath(lPathStr);
+ tokenizePath(lPathStr, lPath);
+ lEnvStr = getPathFromEnvironment("ZORBA_LIB_PATH");
+ lPath.push_back(lCWD.get_path());
+ tokenizePath(lEnvStr, lPath);
+ aStaticCtx->setLibPath(lPath);
+ }
}
+} /* namespace ModulePath */
+
} /* namespace zorba */
=== renamed file 'bin/module_path.h' => 'bin/path_util.h'
--- bin/module_path.h 2010-02-12 08:57:04 +0000
+++ bin/path_util.h 2012-01-25 00:12:28 +0000
@@ -18,6 +18,7 @@
#include <vector>
#include <string>
+#include <zorba/api_shared_types.h>
class ZorbaCMDProperties;
@@ -25,30 +26,14 @@
class String;
- class ModulePath {
- protected:
- static std::string
- getEnvironmentModulePath();
-
- static void
- convertVector(const std::vector<std::string>& aSource,
- std::vector<String>& aDest);
-
- static void
- tokenizeModulePath(const std::string& aModulePath,
- std::vector<std::string>& aResult);
-
- static void
- getInstalledModulePath(const std::string& aModulePath,
- std::vector<std::string>& aResult);
-
- public:
- static void
- getModulePaths(const ZorbaCMDProperties& aProperties,
- std::vector<String>& aModulePaths);
-
-
- };
+ namespace PathUtil {
+
+ void
+ setPathsOnContext(const ZorbaCMDProperties& aProperties,
+ zorba::StaticContext_t& aStaticCtx);
+
+
+ }
} /* namespace zorba */
#endif
=== modified file 'bin/zorbacmd.cpp'
--- bin/zorbacmd.cpp 2011-07-11 11:12:23 +0000
+++ bin/zorbacmd.cpp 2012-01-25 00:12:28 +0000
@@ -43,7 +43,7 @@
#include "error_printer.h"
#include "util.h"
-#include "module_path.h"
+#include "path_util.h"
// For setting the base URI from the current directory
#include <zorba/util/path.h>
@@ -70,7 +70,7 @@
#ifndef ZORBA_NO_FULL_TEXT
OneToOneURIMapper theStopWordsMapper(EntityData::STOP_WORDS);
-OneToOneURIMapper theThesaurusMapper(EntityData::THESAURUS, URIMapper::COMPONENT);
+OneToOneURIMapper theThesaurusMapper(EntityData::THESAURUS);
#endif
bool
@@ -85,10 +85,8 @@
// 2. environment ZORBA_MODULE_PATH
// 3. current working directory
{
- std::vector<String> lModulePaths;
- ModulePath::getModulePaths(aProperties, lModulePaths);
-
- aStaticContext->setModulePaths(lModulePaths);
+ std::vector<String> lModulePath;
+ PathUtil::setPathsOnContext(aProperties, aStaticContext);
}
if (aProperties.boundarySpace().size() != 0 )
@@ -509,12 +507,24 @@
Zorba_CompilerHints lHints;
// default is O1 in the Zorba_CompilerHints constructor
- if (properties.optimizationLevel() == "O0") {
+ if (properties.optimizationLevel() == "O0")
+ {
lHints.opt_level = ZORBA_OPT_LEVEL_O0;
- } else if (properties.optimizationLevel() == "O2") {
+ }
+ else if (properties.optimizationLevel() == "O2")
+ {
lHints.opt_level = ZORBA_OPT_LEVEL_O2;
}
+ lHints.for_serialization_only = true;
+
+#if ZORBACMD_LOAD_SYSTEM_PROPERTIES
+ if (Properties::instance()->serializeOnlyQuery() == 0)
+ {
+ lHints.for_serialization_only = false;
+ }
+#endif
+
// default is false
if (properties.libModule())
{
@@ -577,8 +587,6 @@
return 12;
}
- // if (diagnosticHandler.
-
//
// Create and populate the dynamic context
//
@@ -661,19 +669,22 @@
XmlDataManager* store = zorbaInstance->getXmlDataManager();
timing.startTimer(TimingInfo::UNLOAD_TIMER, i);
+
DocumentManager* lMgr = store->getDocumentManager();
ItemSequence_t lSeq = lMgr->availableDocuments();
Iterator_t lIter = lSeq->getIterator();
lIter->open();
Item lURI;
- while (lIter->next(lURI)) {
+ while (lIter->next(lURI))
+ {
lMgr->remove(lURI.getStringValue());
}
+
timing.stopTimer(TimingInfo::UNLOAD_TIMER, i);
timing.stopTimer(TimingInfo::TOTAL_TIMER, i);
}
- }
+ } // for each execution
return 0;
}
@@ -704,7 +715,7 @@
return 1;
}
- TimingInfo timing(lProperties.multiple());
+ TimingInfo engineTiming(lProperties.multiple());
bool doTiming = lProperties.timing();
bool debug = false;
@@ -741,14 +752,14 @@
// Start the engine
- timing.startTimer(TimingInfo::INIT_TIMER, 2);
+ engineTiming.startTimer(TimingInfo::INIT_TIMER, 2);
void* store = zorba::StoreManager::getStore();
zorba::Zorba* lZorbaInstance = zorba::Zorba::getInstance(store);
{
- timing.stopTimer(TimingInfo::INIT_TIMER, 2);
+ engineTiming.stopTimer(TimingInfo::INIT_TIMER, 2);
// For each query ...
@@ -770,14 +781,14 @@
if (asFile)
{
path.resolve_relative ();
- qfile.reset (new std::ifstream (path.c_str ()));
+ qfile.reset(new std::ifstream (path.c_str ()));
}
else
{
- qfile.reset (new std::istringstream(fURI));
+ qfile.reset(new std::istringstream(fURI));
}
- if ( asFile && (!qfile->good() || qfile->eof()) )
+ if (asFile && (!qfile->good() || qfile->eof()))
{
std::cerr << "file {" << fname << "} not found or not readable." << std::endl;
lProperties.printHelp(std::cout);
@@ -793,7 +804,8 @@
//
// Print the query if requested
//
- if (lProperties.printQuery()) {
+ if (lProperties.printQuery())
+ {
*lOutputStream << "\nQuery number " << queryNo << " :\n";
std::copy (std::istreambuf_iterator<char> (*qfile),
std::istreambuf_iterator<char> (),
@@ -836,8 +848,10 @@
}
// Parse the query
- if (lProperties.parseOnly()) {
- try {
+ if (lProperties.parseOnly())
+ {
+ try
+ {
zorba::XQuery_t lQuery = lZorbaInstance->createQuery();
if (asFile) {
lQuery->setFileName(path.get_path());
@@ -845,7 +859,8 @@
lQuery->parse (*qfile);
}
- catch (zorba::ZorbaException const& ze) {
+ catch (zorba::ZorbaException const& ze)
+ {
std::cerr << ze << std::endl;
return 6;
}
@@ -853,30 +868,44 @@
// Compile and run it if necessary.
// Print timing information if requested.
- else if (!debug) {
- if (compileOnly) {
- try {
+ else if (!debug)
+ {
+ if (compileOnly)
+ {
+ try
+ {
zorba::XQuery_t aQuery = lZorbaInstance->createQuery();
- if (asFile) {
+ if (asFile)
+ {
aQuery->setFileName(path.get_path());
}
+
aQuery->parse(*qfile);
+
qfile->clear();
qfile->seekg(0); // go back to the beginning
- } catch (zorba::XQueryException const& qe) {
- ErrorPrinter::print(qe, std::cerr, lProperties.printErrorsAsXml(), lProperties.indent());
+ }
+ catch (zorba::XQueryException const& qe)
+ {
+ ErrorPrinter::print(qe,
+ std::cerr,
+ lProperties.printErrorsAsXml(),
+ lProperties.indent());
return 6;
}
}
+ TimingInfo queryTiming(lProperties.multiple());
+
int status = compileAndExecute(lZorbaInstance,
lProperties,
lStaticContext,
path.get_path(),
*qfile,
*lOutputStream,
- timing);
- if (status != 0) {
+ queryTiming);
+ if (status != 0)
+ {
// reset the file handler (in case output option was provided)
// in order to delete the created output file
lFileStream.reset();
@@ -884,21 +913,25 @@
return status;
}
- if (doTiming) {
- timing.print(std::cout);
+ if (doTiming)
+ {
+ queryTiming.print(std::cout);
}
}
#ifdef ZORBA_WITH_DEBUGGER
// Debug the query. Do not allow "compileOnly" flags and inline queries
- else if (debug) {
- if (compileOnly) {
+ else if (debug)
+ {
+ if (compileOnly)
+ {
std::cerr << "cannot debug a query if the compileOnly option is specified"
<< std::endl;
return 7;
}
- if (!asFile) {
+ if (!asFile)
+ {
std::cerr << "Cannot debug inline queries." << std::endl;
return 8;
}
@@ -908,7 +941,8 @@
zorba::XQuery_t lQuery;
- try {
+ try
+ {
lQuery = lZorbaInstance->createQuery();
lQuery->setFileName(lFileName);
lQuery->setDebugMode(true);
@@ -927,21 +961,24 @@
lHost = "127.0.0.1";
}
- if (lProperties.debug()) {
- Zorba_SerializerOptions lSerOptions =
- Zorba_SerializerOptions::SerializerOptionsFromStringParams(
- lProperties.getSerializerParameters());
- createSerializerOptions(lSerOptions, lProperties);
+ Zorba_SerializerOptions lSerOptions =
+ Zorba_SerializerOptions::SerializerOptionsFromStringParams(
+ lProperties.getSerializerParameters());
+ createSerializerOptions(lSerOptions, lProperties);
- if (!lProperties.hasNoLogo() && !lProperties.debug()) {
- std::cout << "Zorba XQuery Debugger Server\n" << copyright_str << std::endl;
- }
- lQuery->debug(*lOutputStream, lSerOptions, lHost, lProperties.getDebugPort());
+ if (!lProperties.hasNoLogo())
+ {
+ std::cout << "Zorba XQuery Debugger Server\n" << copyright_str << std::endl;
}
+
+ lQuery->debug(*lOutputStream, lSerOptions, lHost, lProperties.getDebugPort());
}
catch (zorba::XQueryException const& qe)
{
- ErrorPrinter::print(qe, std::cerr, lProperties.printErrorsAsXml(), lProperties.indent());
+ ErrorPrinter::print(qe,
+ std::cerr,
+ lProperties.printErrorsAsXml(),
+ lProperties.indent());
return 5;
}
catch (zorba::ZorbaException const& ze)
@@ -958,7 +995,7 @@
if (doTiming)
{
- timing.startTimer(TimingInfo::DEINIT_TIMER, 2);
+ engineTiming.startTimer(TimingInfo::DEINIT_TIMER, 2);
}
lZorbaInstance->shutdown();
@@ -966,11 +1003,11 @@
if (doTiming)
{
- timing.stopTimer(TimingInfo::DEINIT_TIMER, 2);
+ engineTiming.stopTimer(TimingInfo::DEINIT_TIMER, 2);
std::cout << std::endl << "Engine Shutdown Time : "
- << timing.elapsedDeinitWalltime
- << " (user: " << timing.elapsedDeinitCputime << ")"
+ << engineTiming.elapsedDeinitWalltime
+ << " (user: " << engineTiming.elapsedDeinitCputime << ")"
<< " milliseconds" << std::endl;
}
return 0;
=== modified file 'bin/zorbacmdproperties.cpp'
--- bin/zorbacmdproperties.cpp 2011-07-21 19:21:25 +0000
+++ bin/zorbacmdproperties.cpp 2012-01-25 00:12:28 +0000
@@ -166,11 +166,20 @@
}
-void ZorbaCMDProperties::getModulePaths(std::string& aPaths) const
-{
- aPaths = theModulePath;
-}
-
+void ZorbaCMDProperties::getModulePath(std::string& aPath) const
+{
+ aPath = theModulePath;
+}
+
+void ZorbaCMDProperties::getURIPath(std::string& aPath) const
+{
+ aPath = theUriPath;
+}
+
+void ZorbaCMDProperties::getLibPath(std::string& aPath) const
+{
+ aPath = theLibPath;
+}
std::vector<std::pair<std::string,std::string> > ZorbaCMDProperties::getSerializerParameters() const
{
=== modified file 'bin/zorbacmdproperties.h'
--- bin/zorbacmdproperties.h 2011-06-29 17:25:50 +0000
+++ bin/zorbacmdproperties.h 2012-01-25 00:12:28 +0000
@@ -84,8 +84,14 @@
getSerializerParameters() const;
void
- getModulePaths(std::string&) const;
+ getModulePath(std::string&) const;
+ void
+ getURIPath(std::string&) const;
+
+ void
+ getLibPath(std::string&) const;
+
bool isDebug(){ return theDebug; }
bool hasNoLogo(){ return theNoLogo; }
=== modified file 'bin/zorbacmdproperties.txt'
--- bin/zorbacmdproperties.txt 2011-07-04 08:31:01 +0000
+++ bin/zorbacmdproperties.txt 2012-01-25 00:12:28 +0000
@@ -28,7 +28,9 @@
("debug-port,p", po::value<unsigned int>()->default_value (28028), "The port on which the DBGP-enabled debugger client listens for connections. Defaults to: 28028")
("no-logo", "Print no logo when starting.")
("timeout", po::value<long>()->default_value(-1), "Specify a timeout in seconds. After the specified time, the execution of the query will be aborted.")
-("module-path", po::value<std::string>(), "Module paths added to the built-in resolver, i.e. where module imports are looking for modules.")
+("uri-path", po::value<std::string>(), "URI path (list of directories) added to the built-in URI resolver, i.e. where to find modules/schemas to import.")
+("lib-path", po::value<std::string>(), "Library path (list of directories) where Zorba will look for dynamic libraries (e.g., module external function implementations.")
+("module-path", po::value<std::string>(), "Path (list of directories) to add to both the URI and Library paths.")
("option", po::value<std::vector<std::string> >(), "Set an XQuery option in the static context. The QName of the option is passed as a string in the notation by James Clark (i.e. {namespace}localname). For example, --option {http://www.zorba-xquery.com}option=value").
("trailing-nl", "Output a trailing newline after the result of the query.")
("stop-words", po::value<std::vector<std::string> >(), "Mapping specifying a stop-words URI to another.")
=== modified file 'bin/zorbacmdproperties_base.h'
--- bin/zorbacmdproperties_base.h 2011-07-04 08:31:01 +0000
+++ bin/zorbacmdproperties_base.h 2012-01-25 00:12:28 +0000
@@ -34,7 +34,7 @@
class ZorbaCMDPropertiesBase : public ::zorba::PropertiesBase {
protected:
const char **get_all_options () const {
- static const char *result [] = { "--timing", "--output-file", "--serialization-parameter", "--serialize-html", "--serialize-text", "--indent", "--print-query", "--print-errors-as-xml", "--byte-order-mark", "--omit-xml-declaration", "--base-uri", "--boundary-space", "--default-collation", "--construction-mode", "--ordering-mode", "--multiple", "--query", "--as-files", "--external-variable", "--context-item", "--optimization-level", "--lib-module", "--parse-only", "--compile-only", "--no-serializer", "--debug", "--debug-host", "--debug-port", "--no-logo", "--timeout", "--module-path", "--option", "--trailing-nl", "--stop-words", "--thesaurus", NULL };
+ static const char *result [] = { "--timing", "--output-file", "--serialization-parameter", "--serialize-html", "--serialize-text", "--indent", "--print-query", "--print-errors-as-xml", "--byte-order-mark", "--omit-xml-declaration", "--base-uri", "--boundary-space", "--default-collation", "--construction-mode", "--ordering-mode", "--multiple", "--query", "--as-files", "--external-variable", "--context-item", "--optimization-level", "--lib-module", "--parse-only", "--compile-only", "--no-serializer", "--debug", "--debug-host", "--debug-port", "--no-logo", "--timeout", "--uri-path", "--lib-path", "--module-path", "--option", "--trailing-nl", "--stop-words", "--thesaurus", NULL };
return result;
}
bool theTiming;
@@ -67,6 +67,8 @@
unsigned int theDebugPort;
bool theNoLogo;
long theTimeout;
+ std::string theUriPath;
+ std::string theLibPath;
std::string theModulePath;
std::vector<std::string> theOption;
bool theTrailingNl;
@@ -127,6 +129,8 @@
const unsigned int &debugPort () const { return theDebugPort; }
const bool &noLogo () const { return theNoLogo; }
const long &timeout () const { return theTimeout; }
+ const std::string &uriPath () const { return theUriPath; }
+ const std::string &libPath () const { return theLibPath; }
const std::string &modulePath () const { return theModulePath; }
const std::vector<std::string> &option () const { return theOption; }
const bool &trailingNl () const { return theTrailingNl; }
@@ -262,6 +266,16 @@
if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
if (*argv == NULL) { result = "No value given for --timeout option"; break; } init_val (*argv, theTimeout, d);
}
+ else if (strcmp (*argv, "--uri-path") == 0) {
+ int d = 2;
+ if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
+ if (*argv == NULL) { result = "No value given for --uri-path option"; break; } init_val (*argv, theUriPath, d);
+ }
+ else if (strcmp (*argv, "--lib-path") == 0) {
+ int d = 2;
+ if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
+ if (*argv == NULL) { result = "No value given for --lib-path option"; break; } init_val (*argv, theLibPath, d);
+ }
else if (strcmp (*argv, "--module-path") == 0) {
int d = 2;
if ((*argv) [1] == '-' || (*argv) [2] == '\0') { d = 0; ++argv; }
@@ -327,11 +341,13 @@
"--compile-only\nOnly compile (don't execute)\n\n"
"--no-serializer\nDo not serialize (discard) result.\n\n"
"--debug, -d\nLaunch the Zorba debugger server and connect to a DBGP-enabled debugger client.\n\n"
-"--debug-host, -p\nThe host where the DBGP-enabled debugger client listens for connections. Defaults to: 127.0.0.1\n\n"
+"--debug-host, -h\nThe host where the DBGP-enabled debugger client listens for connections. Defaults to: 127.0.0.1\n\n"
"--debug-port, -p\nThe port on which the DBGP-enabled debugger client listens for connections. Defaults to: 28028\n\n"
"--no-logo\nPrint no logo when starting.\n\n"
"--timeout\nSpecify a timeout in seconds. After the specified time, the execution of the query will be aborted.\n\n"
-"--module-path\nModule paths added to the built-in resolver, i.e. where module imports are looking for modules.\n\n"
+"--uri-path\nURI path (list of directories) added to the built-in URI resolver, i.e. where to find modules/schemas to import.\n\n"
+"--lib-path\nLibrary path (list of directories) where Zorba will look for dynamic libraries (e.g., module external function implementations.\n\n"
+"--module-path\nPath (list of directories) to add to both the URI and Library paths.\n\n"
"--option\nSet an XQuery option in the static context. The QName of the option is passed as a string in the notation by James Clark (i.e. {namespace}localname). For example, --option {http://www.zorba-xquery.com}option=value\n\n"
"--trailing-nl\nOutput a trailing newline after the result of the query.\n\n"
"--stop-words\nMapping specifying a stop-words URI to another.\n\n"
=== added file 'cmake_modules/FindLibedit.cmake'
--- cmake_modules/FindLibedit.cmake 1970-01-01 00:00:00 +0000
+++ cmake_modules/FindLibedit.cmake 2012-01-25 00:12:28 +0000
@@ -0,0 +1,46 @@
+# Copyright 2011 The FLWOR Foundation.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# - Try to find the libedit library
+#
+# Once done this will define
+#
+# LIBEDIT_FOUND - True if libedit library is found
+# LIBEDIT_INCLUDE_DIRS - Directory to include to get libedit headers
+# LIBEDIT_LIBRARIES - Libraries to link against for the libedit library
+#
+
+FIND_PATH (
+ LIBEDIT_INCLUDE
+ editline/readline.h
+ PATHS ${LIBEDIT_INCLUDE_DIR} /usr/include /usr/local/include
+)
+MESSAGE(STATUS ${LIBEDIT_INCLUDE})
+
+FIND_LIBRARY (
+ LIBEDIT_LIBRARY
+ NAMES edit
+ PATHS ${LIBEDIT_LIBRARY_DIR} /usr/lib /usr/local/lib /usr/lib64 /usr/local/lib64
+)
+MESSAGE(STATUS ${LIBEDIT_LIBRARY})
+
+SET (LIBEDIT_INCLUDE_DIRS ${LIBEDIT_INCLUDE})
+SET (LIBEDIT_LIBRARIES ${LIBEDIT_LIBRARY})
+
+FIND_PACKAGE_HANDLE_STANDARD_ARGS (
+ Libedit
+ DEFAULT_MSG
+ LIBEDIT_INCLUDE LIBEDIT_LIBRARY
+)
+
=== modified file 'cmake_modules/FindPHP5.cmake'
--- cmake_modules/FindPHP5.cmake 2011-08-19 00:03:31 +0000
+++ cmake_modules/FindPHP5.cmake 2012-01-25 00:12:28 +0000
@@ -97,6 +97,11 @@
_zend_rsrc_list_get_rsrc_type
_zend_wrong_param_count
_zval_used_for_init
+ _zval_is_true
+ _zend_lookup_class
+ __object_init
+ __zend_hash_add_or_update
+ _php_strtolower
)
SET(CMAKE_SHARED_MODULE_CREATE_C_FLAGS
"${CMAKE_SHARED_MODULE_CREATE_C_FLAGS},-U,${symbol}")
=== modified file 'cmake_modules/ZorbaModule.cmake'
--- cmake_modules/ZorbaModule.cmake 2011-10-10 10:31:20 +0000
+++ cmake_modules/ZorbaModule.cmake 2012-01-25 00:12:28 +0000
@@ -272,12 +272,12 @@
IF(NOT ${PROJECT_NAME} STREQUAL "zorba")
STRING(REPLACE "-" "_" component_name ${PROJECT_NAME})
INSTALL(TARGETS ${module_lib_target}
- ${target_type} DESTINATION ${ZORBA_MODULES_INSTALL_DIR}/${module_path}
+ ${target_type} DESTINATION ${ZORBA_NONCORE_LIB_DIR}/${module_path}
COMPONENT ${component_name})
ELSE(NOT ${PROJECT_NAME} STREQUAL "zorba")
INSTALL(TARGETS ${module_lib_target}
- ${target_type} DESTINATION ${ZORBA_MODULES_INSTALL_DIR}/${module_path})
+ ${target_type} DESTINATION ${ZORBA_CORE_LIB_DIR}/${module_path})
ENDIF(NOT ${PROJECT_NAME} STREQUAL "zorba")
ENDIF (NOT MODULE_TEST_ONLY)
@@ -296,7 +296,7 @@
ENDIF (patch_ver)
ENDIF (MODULE_VERSION)
FOREACH (version_infix "" ${version_infixes})
- ADD_COPY_RULE ("${SOURCE_FILE}" "${module_path}/${module_filename}"
+ ADD_COPY_RULE ("URI" "${SOURCE_FILE}" "${module_path}/${module_filename}"
"${version_infix}" "" "${MODULE_TEST_ONLY}")
ENDFOREACH (version_infix)
@@ -304,7 +304,7 @@
IF (module_lib_target)
GET_TARGET_PROPERTY (lib_location "${module_lib_target}" LOCATION)
GET_FILENAME_COMPONENT (lib_filename "${lib_location}" NAME)
- ADD_COPY_RULE ("${lib_location}" "${module_path}/${lib_filename}"
+ ADD_COPY_RULE ("LIB" "${lib_location}" "${module_path}/${lib_filename}"
"" "${module_lib_target}" "${MODULE_TEST_ONLY}")
ENDIF (module_lib_target)
@@ -357,27 +357,30 @@
ADD_ZORBA_MANIFEST_ENTRY("schema" ${SCHEMA_URI} "")
ENDIF (NOT SCHEMA_TEST_ONLY)
- ADD_COPY_RULE ("${SOURCE_FILE}" "${schema_path}/${schema_filename}"
+ ADD_COPY_RULE ("URI" "${SOURCE_FILE}" "${schema_path}/${schema_filename}"
"" "" "${SCHEMA_TEST_ONLY}")
ENDMACRO (DECLARE_ZORBA_SCHEMA)
# Utility macro for setting up a build rule to copy a file to a
-# particular (possible versioned) file in URI_PATH if such a file has
+# particular (possibly versioned) file in a shared directory if such a file has
# not already been output.
+# FILE_TYPE: Either "URI" or "LIB"; will be used to determine which shared
+# directory to place output in (URI_PATH or LIB_PATH).
# INPUT_FILE: Absolute path to file to copy.
# OUTPUT_FILE: Relative path to output file (relative to URI_PATH).
# VERSION_ARG: Version; may be "" for non-versioned files.
# DEPEND_TARGET: A CMake target name upon which the copy rule should depend;
# may be "".
# TEST_ONLY: If 1, file is for testcases only; will be copied into
-# TEST_URI_PATH and will not be installed
-MACRO (ADD_COPY_RULE INPUT_FILE OUTPUT_FILE VERSION_ARG DEPEND_TARGET TEST_ONLY)
+# TEST_URI_PATH/TEST_LIB_PATH and will not be installed
+MACRO (ADD_COPY_RULE FILE_TYPE INPUT_FILE OUTPUT_FILE VERSION_ARG
+ DEPEND_TARGET TEST_ONLY)
# Choose output base directory
IF (${TEST_ONLY} EQUAL 1)
- SET (_output_basedir "${CMAKE_BINARY_DIR}/TEST_URI_PATH")
+ SET (_output_basedir "${CMAKE_BINARY_DIR}/TEST_${FILE_TYPE}_PATH")
ELSE (${TEST_ONLY} EQUAL 1)
- SET (_output_basedir "${CMAKE_BINARY_DIR}/URI_PATH")
+ SET (_output_basedir "${CMAKE_BINARY_DIR}/${FILE_TYPE}_PATH")
ENDIF (${TEST_ONLY} EQUAL 1)
# Compute the modified output filename by inserting VERSION_ARG (if
@@ -404,19 +407,27 @@
IF (file_found EQUAL -1)
SET_PROPERTY (GLOBAL APPEND PROPERTY "${_dir_sym}-output-files"
"${_output_file}")
- # Save the input file, output file, and any library dependency
- # target for this rule in a global property
+ # Detect whether this is a core URI or not
+ IF (PROJECT_NAME STREQUAL "zorba")
+ SET (_is_core 1)
+ ELSE (PROJECT_NAME STREQUAL "zorba")
+ SET (_is_core 0)
+ ENDIF (PROJECT_NAME STREQUAL "zorba")
+
+ # Save the (input file, output file, any library dependency
+ # target, and whether this is a core or non-core file) for this
+ # rule in a global property
SET_PROPERTY (GLOBAL APPEND PROPERTY ZORBA_URI_FILES
- "${INPUT_FILE}" "${_output_file}" "${DEPEND_TARGET}")
+ "${INPUT_FILE}" "${_output_file}" "${DEPEND_TARGET}" "${_is_core}")
# For .xq and .xsd files, also set up an INSTALL rule (if not TEST_ONLY).
IF (NOT ${TEST_ONLY} EQUAL 1)
IF (${_output_ext} STREQUAL ".xq" OR ${_output_ext} STREQUAL ".xsd")
- IF(NOT PROJECT_NAME STREQUAL "zorba")
+ IF(NOT _is_core)
STRING(REPLACE "-" "_" component_name ${PROJECT_NAME})
INSTALL (FILES "${INPUT_FILE}"
- DESTINATION "${ZORBA_MODULES_INSTALL_DIR}/${_output_path}"
+ DESTINATION "${ZORBA_NONCORE_URI_DIR}/${_output_path}"
RENAME "${_output_filename}"
COMPONENT "${component_name}")
@@ -434,13 +445,11 @@
FILE(APPEND ${CMAKE_BINARY_DIR}/CMakeCPackModules.cmake "SET(CPACK_COMPONENT_${component_name2}_INSTALL_TYPES Full)\n")
ENDIF (NOT ${component_name}_cpack)
- ELSE(NOT PROJECT_NAME STREQUAL "zorba")
+ ELSE(NOT _is_core)
INSTALL (FILES "${INPUT_FILE}"
- DESTINATION "${ZORBA_MODULES_INSTALL_DIR}/${_output_path}"
+ DESTINATION "${ZORBA_CORE_URI_DIR}/${_output_path}"
RENAME "${_output_filename}")
- ENDIF(NOT PROJECT_NAME STREQUAL "zorba")
-
-
+ ENDIF(NOT _is_core)
ENDIF (${_output_ext} STREQUAL ".xq" OR ${_output_ext} STREQUAL ".xsd")
ENDIF (NOT ${TEST_ONLY} EQUAL 1)
@@ -485,16 +494,17 @@
IF (POLICY CMP0007)
CMAKE_POLICY (SET CMP0007 NEW)
ENDIF (POLICY CMP0007)
- MESSAGE (STATUS "Creating check_uris target")
+ MESSAGE (STATUS "Creating check_core_uris and check_uris targets")
GET_PROPERTY (copy_rules GLOBAL PROPERTY ZORBA_URI_FILES)
SET (_output_files)
WHILE (copy_rules)
- # Pop three items off the list, and set up the corresponding
+ # Pop four items off the list, and set up the corresponding
# rule
LIST (GET copy_rules 0 _input_file)
LIST (GET copy_rules 1 _output_file)
LIST (GET copy_rules 2 _depend_target)
- LIST (REMOVE_AT copy_rules 0 1 2)
+ LIST (GET copy_rules 3 _is_core)
+ LIST (REMOVE_AT copy_rules 0 1 2 3)
SET (_depends "${_input_file}")
IF (_depend_target)
LIST (APPEND _depends "${_depend_target}")
@@ -504,12 +514,30 @@
"${_input_file}" "${_output_file}"
DEPENDS ${_depends}
COMMENT "Copying ${_input_file} to URI path" VERBATIM)
- LIST (APPEND _output_files "${_output_file}")
+ IF (_is_core)
+ LIST (APPEND _core_output_files "${_output_file}")
+ ELSE (_is_core)
+ LIST (APPEND _noncore_output_files "${_output_file}")
+ ENDIF (_is_core)
ENDWHILE (copy_rules)
- ADD_CUSTOM_TARGET (check_uris ALL DEPENDS ${_output_files} VERBATIM)
- SET_TARGET_PROPERTIES(check_uris PROPERTIES
- FOLDER "Modules"
- )
+
+ # Targets and dependencies:
+ # ALL depends on check_uris; check_uris depends on check_core_uris;
+ # zorbacmd depends on check_core_uris.
+ ADD_CUSTOM_TARGET (check_uris ALL
+ DEPENDS ${_noncore_output_files} VERBATIM)
+ SET_TARGET_PROPERTIES(check_uris PROPERTIES FOLDER "Modules")
+ # Only create check_core_uris target and associated dependencies if
+ # there are any core URIs; there should never be any when building a
+ # standalone module project.
+ LIST (LENGTH _core_output_files _num_core)
+ IF (_num_core GREATER 0)
+ ADD_CUSTOM_TARGET (check_core_uris
+ DEPENDS ${_core_output_files} VERBATIM)
+ ADD_DEPENDENCIES(check_uris check_core_uris)
+ ADD_DEPENDENCIES(zorbacmd check_core_uris)
+ SET_TARGET_PROPERTIES(check_core_uris PROPERTIES FOLDER "Modules")
+ ENDIF (_num_core GREATER 0)
SET_PROPERTY (GLOBAL PROPERTY ZORBA_URI_FILES)
#add 'xqdoc' and 'xqdoc-xml' targets
@@ -695,7 +723,7 @@
COMMENT "Building XQDoc XML documentation ..."
)
MESSAGE(STATUS " added target xqdoc-xml")
- ADD_DEPENDENCIES(xqdoc-xml zorba_simplestore)
+ ADD_DEPENDENCIES(xqdoc-xml zorbacmd check_core_uris)
SET_TARGET_PROPERTIES (xqdoc-xml PROPERTIES
EXCLUDE_FROM_DEFAULT_BUILD 1
=== modified file 'config/CMakeLists.txt'
--- config/CMakeLists.txt 2011-09-08 19:19:54 +0000
+++ config/CMakeLists.txt 2012-01-25 00:12:28 +0000
@@ -34,7 +34,8 @@
SET(Zorba_EXE_PATH "${ZORBA_ROOT}/bin/zorba")
SET(Zorba_EXTERNALMODULECONFIG_FILE
"${ZORBA_ROOT}/${ZORBA_CMAKE_DIR}/ExternalModuleConfig.cmake.in")
-SET(Zorba_MODULES_INSTALL_DIR "${ZORBA_ROOT}/${ZORBA_MODULES_INSTALL_DIR}")
+SET(Zorba_NONCORE_URI_DIR "${ZORBA_ROOT}/${ZORBA_NONCORE_URI_DIR}")
+SET(Zorba_NONCORE_LIB_DIR "${ZORBA_ROOT}/${ZORBA_NONCORE_LIB_DIR}")
CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/ZorbaConfig.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/ZorbaConfig.cmake" @ONLY)
@@ -58,7 +59,7 @@
STRING (REPLACE ".exe" ".bat" Zorba_TESTDRIVER ${Zorba_TESTDRIVER})
ENDIF (WIN32)
-SET(Zorba_EXE_PATH "${ZORBA_EXE}")
+SET(Zorba_EXE_PATH "${ZORBA_EXE}")
SET(Zorba_EXTERNALMODULECONFIG_FILE
"${CMAKE_CURRENT_SOURCE_DIR}/ExternalModuleConfig.cmake.in")
# Note: We also set these two into the parent's scope, so that it is
@@ -67,10 +68,9 @@
"${CMAKE_CURRENT_SOURCE_DIR}/ExternalModuleConfig.cmake.in"
PARENT_SCOPE)
SET(Zorba_EXE "${ZORBA_EXE}" PARENT_SCOPE)
+SET(Zorba_NONCORE_URI_DIR "${ZORBA_NONCORE_URI_DIR}")
+SET(Zorba_NONCORE_LIB_DIR "${ZORBA_NONCORE_LIB_DIR}")
-# Note: This value doesn't really make much sense, but neither does any
-# other value
-SET(Zorba_MODULES_INSTALL_DIR "${ZORBA_MODULES_INSTALL_DIR}")
CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/ZorbaConfig.cmake.in"
"${CMAKE_BINARY_DIR}/ZorbaConfig.cmake" @ONLY)
=== modified file 'config/ZorbaConfig.cmake.in'
--- config/ZorbaConfig.cmake.in 2011-08-24 09:09:02 +0000
+++ config/ZorbaConfig.cmake.in 2012-01-25 00:12:28 +0000
@@ -47,10 +47,13 @@
"Path to Zorba's testdriver" FORCE)
SET_NORMALIZED (Zorba_EXE "@Zorba_EXE_PATH@" CACHE PATH "Path to Zorba executable" FORCE)
-# Tell the user project where modules are installed. Note: This variable
-# is all-uppercase because it is also used internally by Zorba's build.
-SET (ZORBA_MODULES_INSTALL_DIR "@Zorba_MODULES_INSTALL_DIR@"
- CACHE STRING "Path to Zorba modules in this Zorba installation" FORCE)
+# Tell the user project where (non-core) modules are installed. Note:
+# These variables are all-uppercase because they are also used
+# internally by Zorba's build.
+SET (ZORBA_NONCORE_URI_DIR "@Zorba_NONCORE_URI_DIR@"
+ CACHE STRING "Path to Zorba to non-core modules/schemas in this Zorba installation" FORCE)
+SET (ZORBA_NONCORE_LIB_DIR "@Zorba_NONCORE_LIB_DIR@"
+ CACHE STRING "Path to Zorba to non-core libraries in this Zorba installation" FORCE)
# Tell the user project where to find the "USE" file.
# This file uses the above settings to configure the user project.
=== modified file 'doc/cxx/examples/errors.cpp'
--- doc/cxx/examples/errors.cpp 2011-08-11 05:11:12 +0000
+++ doc/cxx/examples/errors.cpp 2012-01-25 00:12:28 +0000
@@ -139,12 +139,12 @@
// make sure that the warning zwarn::ZWST0002 is turned
// into an error
StaticContext_t lCtx = aZorba->createStaticContext();
- lCtx->declareOption(lQName, "ZWST0002");
+ lCtx->declareOption(lQName, "ZWST0003");
std::ostringstream s;
- s << "declare namespace unknown = 'unknown-annotation';" << std::endl
- << "declare %unknown:test variable $var := 3;" << std::endl
- << "$var" << std::endl;
+ s << "declare namespace z = 'http://www.zorba-xquery.com/annotations';" << std::endl
+ << "declare %z:sequential function local:foo() { 1 };" << std::endl
+ << "local:foo()" << std::endl;
XQuery_t lQuery = aZorba->compileQuery(s.str(), lCtx);
std::cout << lQuery << std::endl;
=== modified file 'doc/cxx/examples/simple.cpp'
--- doc/cxx/examples/simple.cpp 2011-06-14 14:21:49 +0000
+++ doc/cxx/examples/simple.cpp 2012-01-25 00:12:28 +0000
@@ -33,14 +33,14 @@
std::cout << lQuery << std::endl;
- return true;
+ return true;
}
bool
example_2(Zorba* aZorba)
{
- XQuery_t lQuery = aZorba->compileQuery("1+2");
+ XQuery_t lQuery = aZorba->compileQuery("1+2");
Iterator_t lIterator = lQuery->iterator();
lIterator->open();
@@ -53,7 +53,7 @@
lIterator->close();
- return true;
+ return true;
}
@@ -61,7 +61,7 @@
example_3(Zorba* aZorba)
{
- XQuery_t lQuery = aZorba->compileQuery("1 div 0");
+ XQuery_t lQuery = aZorba->compileQuery("1 div 0");
try {
std::cout << lQuery << std::endl;
} catch ( ZorbaException& e ) {
@@ -69,7 +69,7 @@
return true;
}
- return false;
+ return false;
}
@@ -125,9 +125,7 @@
bool
example_7()
{
-
std::cout << Zorba::version() << std::endl;
-
return true;
}
@@ -246,7 +244,8 @@
bool
example_12(Zorba* aZorba)
{
- XQuery_t lQuery = aZorba->compileQuery("<a><b attr='1'/><b attr='2'/></a>");
+ XQuery_t lQuery = aZorba->compileQuery
+ ("<a xmlns:foo='http://www.zorba-xquery.com/'><b attr='1' xmlns:bar='http://www.zorba-xquery.com/uri2'/><b attr='2'/></a>");
Iterator_t lIterator = lQuery->iterator();
lIterator->open();
@@ -263,16 +262,24 @@
Item lNodeName;
lChild.getNodeName(lNodeName);
std::cout << "node name " << lNodeName.getStringValue() << std::endl;
+
Iterator_t lAttrIter = lChild.getAttributes();
-
lAttrIter->open();
-
Item lAttr;
while (lAttrIter->next(lAttr))
{
std::cout << " attribute value " << lAttr.getStringValue() << std::endl;
}
lAttrIter->close();
+
+ NsBindings lBindings;
+ lChild.getNamespaceBindings(lBindings,
+ store::StoreConsts::ONLY_LOCAL_NAMESPACES);
+ for (NsBindings::const_iterator ite = lBindings.begin();
+ ite != lBindings.end(); ++ite) {
+ std::cout << " namespace binding " << ite->first
+ << "->" << ite->second << std::endl;
+ }
}
lChildIter->close();
}
=== modified file 'doc/php/CMakeLists.txt'
--- doc/php/CMakeLists.txt 2011-06-20 12:44:21 +0000
+++ doc/php/CMakeLists.txt 2012-01-25 00:12:28 +0000
@@ -1,4 +1,4 @@
-# Copyright 2006-2008 The FLWOR Foundation.
+# Copyright 2006-2012 The FLWOR Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
=== modified file 'doc/php/examples/CMakeLists.txt'
--- doc/php/examples/CMakeLists.txt 2011-08-19 00:03:31 +0000
+++ doc/php/examples/CMakeLists.txt 2012-01-25 00:12:28 +0000
@@ -1,4 +1,4 @@
-# Copyright 2006-2008 The FLWOR Foundation.
+# Copyright 2006-2012 The FLWOR Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@@ -20,14 +20,24 @@
MESSAGE(STATUS "PHP Path:" ${phpPath})
SET(phpExtensionPath ${CMAKE_BINARY_DIR}/swig/php)
MESSAGE(STATUS "PHP Extension Path: " ${phpExtensionPath})
+ SET(phpIncludePath ${CMAKE_BINARY_DIR}/swig/php)
+ MESSAGE(STATUS "PHP Include Path: " ${phpExtensionPath})
CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/php.ini.in ${CMAKE_CURRENT_BINARY_DIR}/php.ini)
MESSAGE(STATUS "Configuration file: " ${CMAKE_CURRENT_BINARY_DIR}/php.ini)
CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/simple.php.in ${CMAKE_CURRENT_BINARY_DIR}/simple.php)
MESSAGE(STATUS "Simple configuration file: " ${CMAKE_CURRENT_BINARY_DIR}/simple.php)
- ADD_TEST("php" ${PHP5_EXECUTABLE} -c ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}/simple.php)
+ CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/test.php.in ${CMAKE_CURRENT_BINARY_DIR}/test.php)
+ MESSAGE(STATUS "PHP test file configured: " ${CMAKE_CURRENT_BINARY_DIR}/test.php)
+ ADD_TEST("php1" ${PHP5_EXECUTABLE} -c ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}/simple.php)
MESSAGE(STATUS "Installing: " ${CMAKE_CURRENT_BINARY_DIR}/simple.php)
-
- INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/simple.php
+ ADD_TEST("php2" ${PHP5_EXECUTABLE} -c ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_BINARY_DIR}/test.php)
+
+ EXPECTED_FAILURE(php2 918592)
+
+ MESSAGE(STATUS "Installing: " ${CMAKE_CURRENT_BINARY_DIR}/test.php)
+
+
+ INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/simple.php ${CMAKE_CURRENT_BINARY_DIR}/test.php
COMPONENT "php_examples"
DESTINATION
share/doc/zorba-${ZORBA_MAJOR_NUMBER}.${ZORBA_MINOR_NUMBER}.${ZORBA_PATCH_NUMBER}/php/examples)
=== modified file 'doc/php/examples/php.ini.in'
--- doc/php/examples/php.ini.in 2009-10-30 16:34:37 +0000
+++ doc/php/examples/php.ini.in 2012-01-25 00:12:28 +0000
@@ -1,2 +1,3 @@
enable_dl=On
extension_dir=@phpExtensionPath@
+include_path=".:@phpIncludePath@"
\ No newline at end of file
=== modified file 'doc/php/examples/simple.php.in'
--- doc/php/examples/simple.php.in 2011-08-04 02:14:56 +0000
+++ doc/php/examples/simple.php.in 2012-01-25 00:12:28 +0000
@@ -1,6 +1,6 @@
<?php
/*
- * Copyright 2006-2008 The FLWOR Foundation.
+ * Copyright 2006-2012 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-require '@phpPath@/zorba_api_wrapper.php';
+require '@phpPath@/Zorba/zorba_api_wrapper.php';
function example_1(Zorba $aZorba)
{
=== added file 'doc/php/examples/test.php.in'
--- doc/php/examples/test.php.in 1970-01-01 00:00:00 +0000
+++ doc/php/examples/test.php.in 2012-01-25 00:12:28 +0000
@@ -0,0 +1,120 @@
+<?php
+/*
+ * Copyright 2006-2012 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+require '@phpPath@/Zorba/XQueryProcessor.php';
+
+function omitXMLDecl($xml)
+{
+ $xml = str_replace('<?xml version="1.0" encoding="UTF-8"?>', '', $xml);
+ $xml = trim($xml);
+ return $xml;
+}
+
+function assertEquality($test, $reference, $label)
+{
+ $test = omitXMLDecl($test);
+ echo "=====================================\n";
+ var_dump($test);
+ var_dump($reference);
+ if($test != $reference) {
+ throw new Exception(
+ "Test "
+ . $label
+ . " failed. Result:\n"
+ . $test
+ . "\nDoesn't match reference:\n"
+ . $reference
+ );
+ }
+}
+/* Test 1 */
+$xquery = new XQueryProcessor();
+$xquery->importQuery('1+1');
+$result = $xquery->execute();
+assertEquality($result, '2', "1+1");
+
+/* Test 2 */
+$query = '
+declare variable $foo as xs:string external;
+declare variable $bar as xs:integer external;
+declare variable $doc1 as document-node() external;
+declare variable $doc2-str as xs:string external;
+declare variable $doc2 as document-node() := parse-xml($doc2-str);
+
+$foo, $bar, $doc1 , $doc2
+';
+
+$xquery->importQuery($query);
+
+$xquery->setVariable("foo", "bar");
+$xquery->setVariable("bar", 3);
+
+$doc = simplexml_load_string('<root />');
+$xquery->setVariable("doc1", $doc);
+
+$doc = "<root />";
+$xquery->setVariable("doc2-str", $doc);
+
+$result = trim($xquery->execute());
+assertEquality($result, "bar 3<root/><root/>", "Test PHP Types Mapping");
+
+/* Test 3 */
+$xquery->importQuery("(1, 2, <foo bar='bar' />)");
+$it = $xquery->getIterator();
+
+foreach($it as $pos => $value) {
+ switch($pos) {
+ case 0:
+ assertEquality($value, "1", "Consume the item at position {$pos}");
+ break;
+ case 1:
+ assertEquality($value, "2", "Consume the item at position {$pos}");
+ break;
+ case 3:
+ assertEquality($value, '<foo bar="bar"/>', "Consume the item at position {$pos}");
+ break;
+ }
+}
+
+//Let's do it again by leveraging the SPL IteratorAggregate
+foreach($xquery as $pos => $value) {
+ switch($pos) {
+ case 0:
+ assertEquality($value, "1", "Consume the item at position {$pos}");
+ break;
+ case 1:
+ assertEquality($value, "2", "Consume the item at position {$pos}");
+ break;
+ case 3:
+ assertEquality($value, '<foo bar="bar"/>', "Consume the item at position {$pos}");
+ break;
+ }
+}
+
+//Try the same query with execute
+$result = $xquery->execute();
+assertEquality($result, "1 2<foo bar=\"bar\"/>", "Execute To URI");
+
+/* Test 4 */
+$xquery->importQueryFromURI("@phpPath@/test.xq");
+$result = $xquery->execute();
+assertEquality($result, "2", "Test importQueryFromURI");
+
+/* Test 5 */
+//$xquery->importQueryFromURI("http://zorba.s3.amazonaws.com/test.xq");
+//$result = $xquery->execute();
+//assertEquality($result, "2", "Test importQueryFromURI");
+?>
=== modified file 'doc/php/examples/zorba_api.php'
--- doc/php/examples/zorba_api.php 2010-01-27 13:25:24 +0000
+++ doc/php/examples/zorba_api.php 2012-01-25 00:12:28 +0000
@@ -1,6 +1,6 @@
<?php
/*
- * Copyright 2006-2008 The FLWOR Foundation.
+ * Copyright 2006-2012 The FLWOR Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
=== modified file 'doc/zorba/commandline.dox'
--- doc/zorba/commandline.dox 2011-07-24 22:28:31 +0000
+++ doc/zorba/commandline.dox 2012-01-25 00:12:28 +0000
@@ -112,8 +112,14 @@
--timeout
Specify a timeout in seconds. After the specified time, the execution of the query will be aborted.
+--uri-path
+URI path (list of directories) added to the built-in URI resolver, i.e. where to find modules/schemas to import.
+
+--lib-path
+Library path (list of directories) where Zorba will look for dynamic libraries (e.g., module external function implementations.
+
--module-path
-Module paths added to the built-in resolver, i.e. where module imports are looking for modules.
+Path (list of directories) to add to both the URI and Library paths.
--option
Set an XQuery option in the static context. The QName of the option is passed as a string in the notation by James Clark (i.e. {namespace}localname). For example, --option {http://www.zorba-xquery.com}option=value
=== modified file 'doc/zorba/external_functions.dox'
--- doc/zorba/external_functions.dox 2011-08-19 17:04:48 +0000
+++ doc/zorba/external_functions.dox 2012-01-25 00:12:28 +0000
@@ -112,8 +112,8 @@
load it at runtime.
To locate a dynamic libary, Zorba first transforms its target
-namespace URI to a relative file path and then uses the "modules path"
-mechanism (described in \ref uriresolvers) to turn this relative path
+namespace URI to a relative file path and then uses the "Library Path"
+mechanism (described in \ref libpath) to turn this relative path
to the absolute path name of the dynamic library file. The
transformation of the URI to a relative path is done using the
following steps. In describing the steps, we will use the URI
=== modified file 'doc/zorba/ft_thesaurus.dox'
--- doc/zorba/ft_thesaurus.dox 2011-08-31 13:17:59 +0000
+++ doc/zorba/ft_thesaurus.dox 2012-01-25 00:12:28 +0000
@@ -438,7 +438,7 @@
The \c Thesaurus class is:
\code
-class Thesaurus {
+class Thesaurus : public Resource {
public:
typedef /* implementation-defined */ ptr;
typedef /* implementation-defined */ range_type;
@@ -446,12 +446,15 @@
class iterator {
public:
typedef /* implementation-defined */ ptr;
+ virtual void destroy() const = 0;
virtual bool next( String *synonym ) = 0;
protected:
virtual ~iterator();
};
virtual iterator::ptr lookup( String const &phrase, String const &relationship, range_type at_least, range_type at_most ) const = 0;
+
+ virtual void destroy() const = 0; // interited from Resource
protected:
virtual ~Thesaurus();
};
@@ -566,51 +569,49 @@
A real thesaurus would load a large number of synonyms,
of course.
-\subsection ft_class_thesaurus_provider The ThesaurusProvider Class
+\subsection ft_class_thesaurus_resolver A Thesaurus URL Resolver Class
In addition to a \c Thesaurus,
-you must also implement a \c ThesaurusProvider
-that, given a language, provides a \c Thesaurus for that language:
-
-\code
-class ThesaurusProvider {
-public:
- virtual ~ThesaurusProvider();
- virtual Thesaurus::ptr getThesaurus( String const &uri, locale::iso639_1::type lang ) const = 0;
-};
-\endcode
-
-A simple \c ThesaurusProvider for our simple thesaurus can be implemented as:
-
-\code
-class MyThesaurusProvider : public ThesaurusProvider {
-public:
- ThesaurusProvider( String const &uri ) : uri_( uri ) { }
- Thesaurus::ptr getThesaurus( String const &uri, locale::iso639_1::type lang ) const;
+you must also implement a "thesaurus resolver" class
+that,
+given a URL and a language,
+provides a \c Thesaurus for that language.
+A simple \c ThesaurusURLResolver
+for our simple thesaurus can be implemented as:
+
+\code
+class ThesaurusURLResolver : public URLResolver {
+public:
+ ThesaurusURLResolver( String const &url ) : url_( url ) { }
+ Resource* resolveURL( String const &url, EntityData const* ); // inherited
private:
- String const uri_;
+ String const url_;
};
-Thesaurus::ptr
-MyThesaurusProvider::getThesaurus( String const &uri, locale::iso639_1::type lang ) const {
+Resource*
+ThesaurusURLResolver::resolveURL( String const &url, EntityData const *data ) const {
+ ThesaurusEntityData const *const t_data = dynamic_cast<ThesaurusEntityData const*>( data );
+ assert( t_data );
static MyThesaurus thesaurus;
- Thesaurus::ptr result;
- if ( uri == uri_ )
- switch ( lang ) {
+ if ( url == url_ )
+ switch ( t_data->getLanguage() ) {
case locale::iso639_1::en:
case locale::iso639_1::unknown:
//
- // Here, we could test to ensure that the language of our thesaurus
- // matches the language sought, but in our case, we want our thesaurus
- // to be used for all languages since "foo" and "foobar" are universal.
+ // Here, we could test to ensure that the language of our thesaurus matches the
+ // language sought, but in our case, we want our thesaurus to be used for all
+ // languages since "foo" and "foobar" are universal.
//
default:
- result.reset( &thesaurus );
+ return &thesaurus;
}
- return std::move( result );
+ return 0;
}
\endcode
+For more on \c URLResolver, see
+\ref uriresolvers.
+
\subsection ft_thesaurus_enable Using Your Thesaurus
To enable your thesaurus to be used,
@@ -618,8 +619,8 @@
\code
StaticContext_t sctx = zorba->createStaticContext();
-MyThesaurusProvider provider( "http://www.example.com" );
-sctx->addThesaurusProvider( &provider );
+ThesaurusURLResolver resolver( "http://www.example.com" );
+sctx->registerURLResolver( &resolver );
\endcode
You can then perform a query using your thesaurus:
=== modified file 'doc/zorba/impl_dep_features.dox'
--- doc/zorba/impl_dep_features.dox 2011-10-07 08:28:43 +0000
+++ doc/zorba/impl_dep_features.dox 2012-01-25 00:12:28 +0000
@@ -216,7 +216,7 @@
<tr bgcolor="lightcyan">
<td>W3C XQuery Update Facility 1.0</td>
<td>The mechanism (if any) by which an external function can return an XDM instance and/or a pending update list to the invoking query.</td>
- <td>Zorba allows external functions to be implemented in C++. Such functions may return XDM instances. However, it is not possible to implement an updating external function.</td>
+ <td>Zorba allows external functions to be implemented in C++. Such functions may return XDM instances. Moreover, external functions declared as updating may return pending update lists generated by any updating expression. However, it's not possible to create new update primtives and return those.</td>
</tr>
<tr bgcolor="lightcyan">
<td>W3C XQuery Update Facility 1.0</td>
@@ -744,4 +744,4 @@
<td>static</td>
<td>no wildcards </td>
</tr>
-</table>*/
\ No newline at end of file
+</table>*/
=== modified file 'doc/zorba/modules_authoring.dox'
--- doc/zorba/modules_authoring.dox 2011-08-17 09:25:23 +0000
+++ doc/zorba/modules_authoring.dox 2012-01-25 00:12:28 +0000
@@ -268,12 +268,12 @@
and then execute Zorba as follows:
\code
-% zorba --module-path /tmp/myproject/build/URI_PATH -f -q query.xq
+% zorba --uri-path /tmp/myproject/build/URI_PATH -f -q query.xq
<?xml version="1.0" encoding="UTF-8"?>
hello
\endcode
-By providing this one <tt>--module-path</tt> argument, Zorba will
+By providing this one <tt>--uri-path</tt> argument, Zorba will
automatically be able to load any of our modules or schemas by URI,
rather than requiring explicit filesystem paths to them. This makes it
much easier to develop larger XQuery applications, because the entire
@@ -281,7 +281,6 @@
of your queries to change the paths to load your modules as you move
from development to production.
-
\ref modules_authoring_2
\ref modules_building_in
=== modified file 'doc/zorba/modules_authoring_2.dox'
--- doc/zorba/modules_authoring_2.dox 2011-08-19 17:04:48 +0000
+++ doc/zorba/modules_authoring_2.dox 2012-01-25 00:12:28 +0000
@@ -280,11 +280,12 @@
2. Link them together into an appropriately-named shared library for
your operating system
-3. Copy the resulting shared library into <tt>URI_PATH</tt> with the
-correct name and location, and
+3. Copy the resulting shared library into
+<tt><build_dir>/LIB_PATH</tt> with the correct name and location, and
4. Create an <tt>INSTALL</tt> rule so that the shared library will be
-installed correctly along with your project.
+installed correctly along with your project. It will be automatically
+installed into Zorba's default non-core library path (see \libpath).
If your code depends on other dynamic libraries, you can pass the full
paths to those libraries to <tt>DECLARE_ZORBA_MODULE()</tt> using the
=== modified file 'doc/zorba/modules_building_in.dox'
--- doc/zorba/modules_building_in.dox 2011-08-17 09:25:23 +0000
+++ doc/zorba/modules_building_in.dox 2012-01-25 00:12:28 +0000
@@ -3,7 +3,7 @@
Once you have created a module project (see \ref modules_authoring)
containing modules and schemas, there are two different ways that you
can build those modules directly into Zorba, such that they are on
-Zorba's default module path and will be found automatically.
+Zorba's default URI and Library paths and will be found automatically.
These same techniques can be used with non-core modules developed by
the Zorba team.
=== modified file 'doc/zorba/options.dox'
--- doc/zorba/options.dox 2011-09-14 06:15:19 +0000
+++ doc/zorba/options.dox 2012-01-25 00:12:28 +0000
@@ -37,16 +37,20 @@
In the following, we describe the set of options available in Zorba.
+
\subsubsection options_features Enabling or Disabling Features
-Zorba provides a couple of extensions to XQuery.
-For example, the scripting extension and the data definition facility are both features not defined by the W3C but available in Zorba.
-The user can enable or disable any of these extensions using an option declaration, respectively.
-The URI of the names of these options is <tt>http://www.zorba-xquery.com/options/features</tt>.
-The local name to enable a feature is <tt>enable</tt> and to disable a feature is <tt>disable</tt>, respectively.
-As a value, any of these options allows a comma separated list of feature names (QNames).
+Zorba provides a couple of extensions to XQuery. For example, the scripting
+extension and the data definition facility are both features not defined by
+the W3C but available in Zorba. The user can enable or disable any of these
+extensions using an option declaration, respectively. The URI of the names
+of these options is <tt>http://www.zorba-xquery.com/options/features</tt>.
+The local name to enable a feature is <tt>enable</tt> and to disable a feature
+is <tt>disable</tt>, respectively. As a value, any of these options allows
+a comma separated list of feature names (QNames).
-For example, to disable the scripting and data definition facility feature, the following option declaration may be used:
+For example, to disable the scripting and data definition facility feature,
+the following option declaration may be used:
\code
declare namespace op = "http://www.zorba-xquery.com/options/features";
@@ -55,23 +59,84 @@
declare option op:disable "f:scripting, f:ddl";
\endcode
-If a given feature doesn't specify a prefix, the name is resolved against the default feature namespace <tt>http://www.zorba-xquery.com/features</tt>.
-All Zorba specific features presented in the following are declared in this namespace.
+If a given feature doesn't specify a prefix, the name is resolved against the
+default feature namespace <tt>http://www.zorba-xquery.com/features</tt>. All
+Zorba specific features presented in the following are declared in this namespace.
<ul>
- <li><b>scripting:</b> This local name can be used to enable or disable the Zorba Scripting Extension. Per default, the feature is enabled.</li>
- <li><b>xqddf:</b> The <tt>xqddf</tt> local name refers to the Zorba specific XQuery Data Definition Facility. The feature is enabled by default.</li>
- <li><b>trace:</b> The <a href="http://www.w3.org/TR/xpath-functions-30/#func-trace">fn:trace</a> function can be used to retrieve an execution trace of a query. The local name <tt>trace</tt> can be used to disable execution trace printing, i.e. calls to fn:trace are eliminated. Per default, the feature is enabled.</li>
- <li><b>hof:</b> Higher-order functions will be introduced in the upcoming XQuery 3.0 recommendation. This feature is only partially implemented in Zorba. Hence, it is disabled by default. However, the local name <tt>hof</tt> can be used to enable the feature if requested.</li>
- <li><b>dtd:</b> The local name <tt>dtd</tt> can be used to enable or disable DTD validation when parsing resources retrieved by <a href="http://www.w3.org/TR/xpath-functions-30/#func-doc">fn:doc</a>. DTD validation is disabled by default.</li>
+<li><b>scripting:</b> This local name can be used to enable or disable the
+Zorba Scripting Extension. Per default, the feature is enabled.
+</li>
+<li><b>xqddf:</b> The <tt>xqddf</tt> local name refers to the Zorba specific
+XQuery Data Definition Facility. The feature is enabled by default.
+</li>
+<li><b>trace:</b> The
+<a href="http://www.w3.org/TR/xpath-functions-30/#func-trace">fn:trace</a>
+function can be used to retrieve an execution trace of a query. The local name
+<tt>trace</tt> can be used to disable execution trace printing, i.e. calls to
+fn:trace are eliminated. Per default, the feature is enabled.
+</li>
+<li><b>hof:</b> Higher-order functions will be introduced in the upcoming
+XQuery 3.0 recommendation. This feature is only partially implemented in Zorba.
+Hence, it is disabled by default. However, the local name <tt>hof</tt> can be
+used to enable the feature if requested.
+</li>
+<li><b>dtd:</b> The local name <tt>dtd</tt> can be used to enable or disable
+DTD validation when parsing resources retrieved by
+<a href="http://www.w3.org/TR/xpath-functions-30/#func-doc">fn:doc</a>. DTD
+validation is disabled by default.
+</li>
</ul>
+\subsubsection options_Optimizations Providing Optimizer Hints
+
+Options can also be used to provide the Zorba optimizer with certain "hints".
+All options used for this purpose have a QName whose namespace URI is
+<tt>http://www.zorba-xquery.com/options/optimizer</tt>. For some hints, the
+optimizer needs to know only whether the hint should be applied or not; no
+additional information is required. For such hints, Zorba recognizes two
+options, whose local name is <tt>enable</tt> and <tt>disable</tt>, respectivaly,
+and whose value is a comma separated list of hint names.
+
+Currently, Zorba recognizes only one optimizer hint, called the
+for-serialization-only hint. It is used to tell the optimizer that the only
+operation that me be applied to the query result (i.e., to the sequence of
+items returned by the query) is serialization. With this knowledge, the
+optimizer may be able to apply optimizations that would not be possible
+otherwise. For example, it may be able to avoid the copying of nodes that
+are returned by an enclosed expression within a node constructor.
+
+The following query shows the usage of this hint. The query groups a number of
+sale records by country, and prints the sales in each country within a <country>
+tag whose name attribute gives the name of the associated country. The optimizer
+can use the for-serialization-only hint to avoid copying the $sale nodes when
+it constructs each of the new <country> nodes.
+
+\code
+declare namespace opt = "http://www.zorba-xquery.com/options/optimizer";
+
+declare option opt:enable "for-serialization-only";
+
+for $sale in doc("sales.xml")/sale
+let $country := $sale/country
+group by $country
+return <country name={$country}>{$sale}</country>
+
+\endcode
+
+The for-serialization-only hint can also be turned on or off via the use of the
+Zorba_CompilerHints struct in the C++ API. Using an option declaration to enable
+or disable the hint overwrites the value stored in Zorba_CompilerHints.
+
+
\subsubsection options_warning Warnings in Zorba
-Warnings are diagnostic messages that report constructions which are not inherently erroneous but which are risky or suggest there may have been an error.
-Analogous to errors, warnings are identified by QNames.
-Using options, the user can control whether a particular warning (or all warnings) is (are) enabled, disabled, or treated as an error.
+Warnings are diagnostic messages that report constructions which are not
+inherently erroneous but which are risky or suggest there may have been an
+error. Analogous to errors, warnings are identified by QNames. Using options,
+the user can control whether a particular warning (or all warnings) is (are)
+enabled, disabled, or treated as an error.
For example, given the following prolog, all warnings are treated as errors:
@@ -82,11 +147,13 @@
declare option op:error "w:all";
\endcode
-If a given warning doesn't specify a prefix, the name is resolved against the default warning namespace <tt>http://www.zorba-xquery.com/warnings</tt>.
-All Zorba specific warnings are defined in this namespace.
-A comprehensive list of warnings is contained at the end of the C++ header file diagnostic_list.h.
+If a given warning doesn't specify a prefix, the name is resolved against the
+default warning namespace <tt>http://www.zorba-xquery.com/warnings</tt>. All
+Zorba specific warnings are defined in this namespace. A comprehensive list
+of warnings is contained at the end of the C++ header file diagnostic_list.h.
-The following snippet causes the warning <tt>ZWST0002</tt> (warn for unknown annotations) to be suppressed:
+The following snippet causes the warning <tt>ZWST0002</tt> (warn for unknown
+annotations) to be suppressed:
\code
declare namespace op = "http://www.zorba-xquery.com/options/warnings";
@@ -97,46 +164,56 @@
\subsubsection options_versioning Zorba Module Versioning
-Zorba provides a way that allows the developer of a module to specify a version of his module without changing the target namespace.
-An importing module can specify restriction on the version of a module it wants to use.
-This allows developers to easily declare dependencies between particular versions of a module.
-In addition, a module can specify on which version of Zorba it depends.
+Zorba provides a way that allows the developer of a module to specify a version
+of his module without changing the target namespace. An importing module can
+specify restriction on the version of a module it wants to use. This allows
+developers to easily declare dependencies between particular versions of a
+module. In addition, a module can specify on which version of Zorba it depends.
Details about module versioning can be found at \ref mod_versioning.
The options to declare the module and zorba version are listed here for completeness.
-To declare version 2.5 of a module that depends on version 2.0 of Zorba, the following option declaration may be used.
+To declare version 2.5 of a module that depends on version 2.0 of Zorba, the
+following option declaration may be used.
+
\code
declare namespace ver = "http://www.zorba-xquery.com/options/versioning";
declare option ver:module-version "2.5";
declare option ver:zorba-version "2.0";
\endcode
+
\subsection options_introspection Introspecting Options in XQuery
-In a module, the introspection module of Zorba can be used to get the value of an option that is declared.
+In a module, the introspection module of Zorba can be used to get the value
+of an option that is declared.
-Specifically, the following function retrieves the value of an option that is declared in the prolog of
-the module.
-The function returns the empty sequence if the option is not contained in the static context.
+Specifically, the following function retrieves the value of an option that
+is declared in the prolog of the module. The function returns the empty
+sequence if the option is not contained in the static context.
\code
declare function sctx:option($name as xs:QName) as xs:string? external;
\endcode
+
\subsection options_available Options in Host Languages and External Functions
-Besides declaring an option in the prolog of a module, options can also be declared or retrieved using the StaticContext representation in any of the language bindings (i.e. C++, C, PHP, Ruby, Python, or Java).
+Besides declaring an option in the prolog of a module, options can also be
+declared or retrieved using the StaticContext representation in any of the
+language bindings (i.e. C++, C, PHP, Ruby, Python, or Java).
-For instance, the C++ API provides the following two functions to retrieve the value of an option declared in a query and declare options to be used in a query, respectively.
+For instance, the C++ API provides the following two functions to retrieve
+the value of an option declared in a query and declare options to be used
+in a query, respectively.
<ul>
<li> bool StaticContext::getOption( const Item& aQName, String& aOptionValue) const;
<li> void StaticContext::declareOption( const Item& aQName, const String& aOptionValue);
</ul>
-For example, the following code snippet depicts how the higher-order function feature can be enabled for all modules compiled with the given static context.
-
+For example, the following code snippet depicts how the higher-order function
+feature can be enabled for all modules compiled with the given static context.
\code
zorba::StaticContext_t lContext = zorba->createStaticContext();
@@ -149,45 +226,60 @@
zorba::XQuery_t lQuery = zorba->compileQuery("1+1", lContext);
\endcode
-Declaring and retrieving the value of an option is particularly useful in external functions.
-The developer of an external function can retrieve the value of an option (from the static context passed to the function).
-This way, she can customize the behavior of her function.
+Declaring and retrieving the value of an option is particularly useful in
+external functions. The developer of an external function can retrieve the
+value of an option (from the static context passed to the function). This
+way, she can customize the behavior of her function.
+
\section annotation_introduction Annotations
-In XQuery (starting version 3.0) <a href="http://www.w3.org/TR/xquery-30/#id-annotations">annotations</a> may be used to properties associated with functions and variables.
-Zorba also uses annotations for collections and indexes.
-Annotations are <tt>(QName, value)</tt> pairs.
-The prefix of the QName is resolved using the statically known namespaces.
+In XQuery (starting with version 3.0)
+<a href="http://www.w3.org/TR/xquery-30/#id-annotations">annotations</a> may
+be used to properties associated with functions and variables. Zorba also uses
+annotations for collections and indexes. Annotations are <tt>(QName, value)</tt>
+pairs. The prefix of the QName is resolved using the statically known namespaces.
If no prefix is present, the name is the default function namespace.
+
\subsection annotations_available Available Annotations
\subsubsection xquery_annotations XQuery 3.0 Annotation
+
XQuery 3.0 itself defines two annotations: <tt>%fn:public</tt> and <tt>%fn:private</tt>.
-Those annotations allow the user to declare a function or a variable as public or private, respectively.
-A private variable or function is hidden from a module import.
-That is, it can not be used in the importing module.
+Those annotations allow the user to declare a function or a variable as public
+or private, respectively. A private variable or function is hidden from a module
+import. That is, it can not be used in the importing module.
-For example, a function declared a module as follows, can not be used in a module which imports the <tt>mymodule</tt> module:
+For example, a function declared a module as follows, can not be used in a module
+which imports the <tt>mymodule</tt> module:
\code
declare %private function mymodule:foo() { "foo" };
\endcode
+
\subsubsection zorba_annotations Zorba Specific Annotations
-Zorba provides a couple of annotations that allow the user to define the semantics of functions, variables, collections, and indexes.
-All these annotations have the namespace <tt>http://www.zorba-xquery.com/annotations</tt>.
+Zorba provides a number of annotations that allow the user to define the
+semantics of functions, variables, collections, and indexes. All these
+annotations have the namespace <tt>http://www.zorba-xquery.com/annotations</tt>.
+
\paragraph deterministic_annotation Deterministic and Nondeterministic Functions
-A deterministic function is a function that always evaluates to the same result if it is invoked multiple times with the same arguments during the evaluation of a <a href="scripting_spec.html#id-snapshot-scope">snapshot</a>.
-In general, all functions defined by XQuery are deterministic.
-However, a module developer might develop a function (in a host language) which does not guarantee to be deterministic.
-For example, a function generating random numbers is clearly not deterministic.
-Knowing about this property is crucial for the query optimizer to retain the semantics (e.g. caching would lead to incorrect results).
-
-For this reason, Zorba provides two annotations (<tt>nondeterministic</tt> and <tt>deterministic</tt>) that allow a developer to declare whether a function is deterministic or not.
+
+A deterministic function is a function that always evaluates to the same result
+if it is invoked multiple times with the same arguments during the evaluation
+of a <a href="scripting_spec.html#id-snapshot-scope">snapshot</a>. In general,
+all functions defined by XQuery are deterministic. However, a module developer
+might develop a function (in a host language) which does not guarantee to be
+deterministic. For example, a function generating random numbers is clearly
+not deterministic. Knowing about this property is crucial for the query optimizer
+to retain the semantics (e.g. caching would lead to incorrect results).
+
+For this reason, Zorba provides two annotations (<tt>nondeterministic</tt> and
+<tt>deterministic</tt>) that allow a developer to declare whether a function
+is deterministic or not.
As an example, the following snippet declares a nondeterministic random function.
@@ -200,7 +292,9 @@
If not specified otherwise, all functions are being treated as deterministic.
If some function invokes a nondeterministic function, the invoking function itself must also be declared as nondeterministc, otherwise zerr::ZXQP0040 is raised.
+
\paragraph sequential_annotation Sequential Functions
+
In XQuery 3.0, an expression never has any side effects other than constructing new nodes (not even updating expressions, which merely produce a pending update list).
Zorba Scripting programs may have side effects.
Side effects can be made with statements.
@@ -247,7 +341,9 @@
$key-type as xs:QName) as empty-sequence() external;
\endcode
+
\paragraph streamable_annotation Streamable Strings
+
A function annotated with the <tt>streamable</tt> annotation is a function that may return an xs:string item whose content is streamed.
Such a string is called a streamable string.
They have the advantage that their contents does not need to be materialized in memory.
@@ -278,6 +374,89 @@
In order to be able to use the value twice, the <tt>string:materialize</tt> function must be used to materialize the entire contents of the file <tt>myfile.txt</tt> in memory.
Otherwise, the error zerr:ZSTR0055 is raised.
+
+\paragraph caching_annotation Caching Results of Functions
+
+Caching of function results may improve performance when computationally
+expensive functions are invoked multiple times with the same arguments.
+
+If the optimization level is O1 or higher, Zorba automatically caches results
+of recursive, deterministic, and non-sequential functions whose parameter and
+return types are subtypes of xs:anyAtomicType. Specifically, if such a function
+is called more than once with the same arguments, the result of the first call
+will be cached and subsequent calls will return the cached value without
+re-evaluating the function.
+
+For example, in the following recursive function computing a fibonacci number,
+each result is automatically cached and, hence, dramatically improves performance.
+
+\include zorba/udf/udf-fib-rec.xq
+
+Specifically, this optimization reduces the complexity of the function from
+O(1.6^n) to O(n).
+
+In order to explicitly disable function caching, the user can specify the
+<tt>%ann:no-cache</tt> annotation.
+
+In addition, the user can use the <tt>%ann:cache</tt> annotation to cache the
+results of functions other than the ones that are automatically cached. However,
+this will only work if the function is not updating and its parameter and return
+types are subtypes of xs:anyAtomicType; otherwise, Zorba will raise a warning
+(zwarn:ZWST0005) and simply ignore the %ann:cache annotation.
+
+Please note, that explicitly enforcing caching for sequential or nondeterministic
+functions might not give the intended result. In such cases, Zorba will raise a
+warning (zwarn:ZWST0006) but obey the %ann:cache annotation.
+
+
+\paragraph no_copy_rule_annotation Avoiding Node Copying in Node Constructors.
+
+According to the XQuery specification, any nodes (and their subtrees) returned
+by an enclosed expression appearing inside a node constructor must be copied,
+and it is the copied subtrees that are then connected to the newly constructed
+node. However, such copying is not always necessary. If no copying is done, then
+some nodes will be "shared" by multiple trees. XML trees that do not contain
+any shared nodes will be refered to as "stand-alone trees".
+
+Whether node copying is really necessary or not depends on the kind of operations
+that are going to be performed on the nodes and their associated trees after the
+node construction. For example, copying is necessary if any operations involving
+node identity, document ordering, or reverse axis traversals are to be performed
+on the newly constructed tree. Copying is also necessary if the relevant nodes may
+be involved in a later update operation. The Zorba optimizer is able to analyze
+the query expressions and determine automatically whether copying is required or not.
+However, the optimizer needs some help from the user in the case of external
+functions, because it cannot look into the operations of such functions. For this,
+Zorba provides two annotations that users may annotate their external functions
+with in order to help the optimizer determine whether to copy nodes or not.
+
+<ul>
+<li>
+<b>%ann:must-copy-input-nodes</b>. This annotation has an associated value, which
+is a list of integer literals. The meaning of the annotation is the following:
+If a number N appears in the value, then the function requires that any nodes
+that are bound to the N-th parameter when the function is called, must belong to
+standalone trees (because the function is going to perform on such nodes an
+operation that requires standalone trees). As a result of this information, the
+optimizer makes sure that node copying is done during any node constructor whose
+result (or any subtree of it) may be given as input to such an external function.
+</li>
+<li>
+<b>%ann:propagates-input-nodes</b>. This annotation has an associated value, which
+is a list of integer literals. The meaning of the annotation is the following:
+If a number N appears in the value, then the function may return to its caller
+a node n that is bound to the N-th parameter, or a node in the subtree of n. This
+annotation helps the optimizer determine whether nodes consumed by an expression
+are comming from a node constructor, so that if the expression requires stand-alone
+trees, then the optimizer will make sure that the relavant node constructor does
+copy nodes.
+</li>
+</ul>
+
+The absence of any of the above annotations from an external function declaration
+is treated as if the annotation was present with a value listing all the numbers
+between 1 and M, where M is the function arity.
+
\paragraph collection_index_annotations Annotations on Collections and Indexes
The \ref xqddf uses annotations to assign properties to collections and indexes.
=== modified file 'doc/zorba/uriresolvers.dox'
--- doc/zorba/uriresolvers.dox 2011-08-17 09:25:23 +0000
+++ doc/zorba/uriresolvers.dox 2012-01-25 00:12:28 +0000
@@ -56,9 +56,9 @@
the algorithm listed below.
<li>Second, Zorba attempts to load the relative path within every
-directory listed on its <i>module path</i>. (Note: the terminology
-here is a misnomer; the same mechanism is used for all URIs, not just
-modules.)
+directory listed on its <i>URI path</i>. (Through this documentation,
+a "path" is defines as "an ordered list of directories in the
+filesystem.)
</ol>
@@ -71,7 +71,7 @@
<ol>
<li>The domain (authority) component of the URI is reversed, and then
-transformed into a path notation separated by forward slashes:
+transformed into a relative filename separated by forward slashes:
<code>www.example.com</code> => <code>com/example/www</code>
<li>The path component of the URI is appended:
@@ -100,35 +100,35 @@
</ul>
-\subsection modulepath The "Module Path"
+\subsection uripath Zorba's URI Path
Zorba will now attempt to find the named file relative to each
-directory in the "module path". By default, the only entry on the
-module path is the directory
-<code>/usr/share/zorba-2.0.0/modules/</code> (on Unix and MacOS X) or
+directory in the <i>URI Path</i>. By default, the only entry on the
+URI path is the directory
+<code>/usr/share/zorba/uris/</code> (on Unix and MacOS X) or
<code>C:\\Program Files\\Zorba
-2.0.0\\share\\zorba-2.0.0\\modules</code> (on Windows). So, to
+2.1.0\\share\\zorba\\uris</code> (on Windows). So, to
complete this example, assuming Zorba is installed on a Unix system in
the default location, Zorba will attempt to resolve the module
namespace URI <code>http://www.example.com/modules/utils</code> to the
file
\code
- /usr/share/zorba-2.0.0/modules/com/example/www/modules/utils.xq
+ /usr/share/zorba/modules/com/example/www/modules/utils.xq
\endcode
-If you have modules installed in other locations on your system, you
-may provide additional search paths either by passing the
-<code>--module-path</code> command-line argument to Zorba, or by
-setting the <code>ZORBA_MODULE_PATH</code> environment variable. In
-both cases, the value is an ordered list of filesystem paths separated
-by ":" (on Unix/MacOS X) or ";" (on Windows). Zorba will search each
-path on the module path in the order specified, and the first match
-found will be used. So, for example, if you invoke Zorba as follows
-(example is for a Unix system):
+If you have modules or schemas installed in other locations on your
+system, you may provide additional search directories either by
+passing the <code>--uri-path</code> command-line argument to Zorba, or
+by setting the <code>ZORBA_URI_PATH</code> environment variable. In
+both cases, the value is an ordered list of filesystem directories
+separated by ":" (on Unix/MacOS X) or ";" (on Windows). Zorba will
+search each directory on the URI path in the order specified, and the
+first match found will be used. So, for example, if you invoke Zorba
+as follows (example is for a Unix system):
\code
- zorba --module-path '/home/foo/xquery/modules:/opt/share/xquery/modules'
+ zorba --uri-path '/home/foo/xquery/uris:/opt/share/xquery/uris'
-q 'import module namespace utils="http://www.example.com/modules/utils"; 1'
\endcode
@@ -136,31 +136,108 @@
order:
\code
- /home/foo/xquery/modules/com/example/www/modules/utils.xq
- /opt/share/xquery/modules/com/example/www/modules/utils.xq
- /usr/share/zorba-2.0.0/modules/com/example/www/modules/utils.xq
+ /home/foo/xquery/uris/com/example/www/modules/utils.xq
+ /opt/share/xquery/uris/com/example/www/modules/utils.xq
+ /usr/share/zorba/uris/com/example/www/modules/utils.xq
\endcode
-If, after searching all module path directories, no match is found for
+If, after searching all URI path directories, no match is found for
a given URI, Zorba will by default fall back to interpretting the URI
-as a URL and loading the resource via HTTP (at least, assuming the URI
+as a URL and loading the resource via HTTP (assuming the URI
has the http: scheme).
+\section libpath Zorba's Library Path
+
+The above URI path mechanism is used for all URIs that are resolved by
+Zorba - most especially module and schema imports, but also full-text
+thesaurus and stop-word lists, documents, and so on.
+
+When considering modules in particular, however, there is another
+important path: the Library Path. Zorba will look on this path when it
+needs to load dynamic libraries containing the implementation of
+external functions for a module (ie, those functions implemented in
+C++; see \ref mod_author_cpp). This path is separate from the URI
+path because on certain systems - most notably Fedora, but also other
+Linux distributions - it is important that platform-dependent binary
+files (such as dynamic libraries) be installed in a separate directory
+structure from platform-independent files (such as <code>.xq</code>
+module files and <code>.xsd</code> schema files).
+
+The Library Path mechanism is exactly parallel to the URI Path
+mechanism. The default, built-in entry on this path is
+<code>/usr/lib/zorba</code> (on Unix and MacOS X) and
+<code>C:\\Program Files\\Zorba 2.1.0\\lib\\zorba</code> (on
+Windows). You can add directories to this path using the
+<code>--lib-path</code> command-line argument, or by setting the
+<code>ZORBA_LIB_PATH</code> environment variable.
+
+\section internalpaths Internal (Core) Paths
+
+There is actually one additional built-in directory on Zorba's URI
+Path, and one additional built-in directory on Zorba's Library Path,
+in addition to the default values mentioned above. These directories
+hold Zorba's built-in "core" modules (see \ref core_modules). The
+directories are subdirectories of the default directory named
+"core/ZORBA_VERSION". So for example, for Zorba 2.1.0 on Unix, the
+default internal URI directory is
+<code>/usr/share/zorba/uris/core/2.1.0</code> and the default internal
+library directory is <code>/usr/lib/zorba/core/2.1.0</code>.
+
+These directories are separate to make it easier to upgrade Zorba, or
+support multiple installed versions of Zorba, while allowing non-core
+modules to be installed and versioned indepedently of the Zorba
+version. Normally you should not modify the contents of these
+directories.
+
+\section configurepaths Changing the Default Paths
+
+All four paths mentioned above - the core and non-core URI Path, and
+the core and non-core Library Path - have compiled-in default values
+as discussed. All four of these default values can be modified at
+Zorba build time to meet your environment's requirements. You can do
+this by specifying alternate values for the following CMake variables:
+
+\code
+ZORBA_NONCORE_URI_DIR
+ZORBA_CORE_URI_DIR
+ZORBA_NONCORE_LIB_DIR
+ZORBA_CORE_LIB_DIR
+\endcode
+
+Note that these are <i>relative</i> directories, and will be resolved
+relative to <code>CMAKE_INSTALL_PREFIX</code>.
+
+\section modulepath Zorba's "Module Path"
+
+Earlier versions of Zorba had a single path for specifying where both
+platform-dependent library files and platform-independent module and
+schema files were located. This was somewhat inaccurately named the
+"module path". For backwards compatibility, Zorba still supports a
+<code>--module-path</code> command-line argument and a
+<code>ZORBA_MODULE_PATH</code> environment variable (and the C++ API
+has a <code>StaticContext::setModulePaths()</code> method).
+Specifying a set of directories as the "module path" using any of
+these mechanisms is exactly the same as specifying that set of
+directories as both the URI path and library path.
+
+The Module Path is deprecated, and these mechanisms may be removed in
+a future major version of Zorba. There is no "default module path".
+
\section cplusplus C++ API for URI Resolving
-\subsection extmodulepath Modifying the Module Path programmatically
+\subsection cppuripath Modifying the URI Path programmatically
The simplest modification to Zorba's default behavior is setting the
-module-path programmatically. This allows you to have different module
+URI path programmatically. This allows you to have different URI
paths per static context, if you wish.
The <code>StaticContext</code> C++ API class provides the
-<code>setModulePaths()</code> method for this purpose. It is passed a
+<code>setURIPath()</code> method for this purpose. It is passed a
vector of <code>zorba::String</code> values, each being an absolute
-path to add to the module path.
+directory to add to the URI path.
For example, the following code snippet creates a
-<code>StaticContext</code> object; adds two module paths to the module
+<code>StaticContext</code> object; adds two directories to the URI
path component of this static context; and compiles and executes a
query given the information that is present in this static context
(passed as the second parameter to the <code>compileQuery()</code>
@@ -170,12 +247,12 @@
// Create a new static context
zorba::StaticContext_t staticCtx = zorba->createStaticContext();
- // Set the module paths
- std::vector<zorba::String> modulePaths(2);
- modulePaths[0] = "/home/foo/xquery/modules";
- modulePaths[1] = "/opt/share/xquery/modules";
+ // Set the URI Path
+ std::vector<zorba::String> uriPath(2);
+ uriPath[0] = "/home/foo/xquery/uris";
+ uriPath[1] = "/opt/share/xquery/uris";
- staticCtx->setModulePaths(modulePaths);
+ staticCtx->setURIPath(uriPath);
// Compile a query using the static context created above
zorba::XQuery_t query = zorba->compileQuery(
@@ -186,6 +263,12 @@
std::cout << query << std::endl;
\endcode
+\subsection cpplibpath Modifying the Library Path programmatically
+
+Similarly, <code>StaticContext</code> has a method named
+<code>setLibPath()</code> for specifying the Library Path to use. In
+operation it behaves exactly like <code>setURIPath()</code>.
+
\subsection mapresolve URI Mappers and URL Resolvers
Now we will discuss more advanced techniques for manipulating Zorba's
@@ -228,9 +311,8 @@
\subsubsection urimappers URI Mappers
Zorba includes a few built-in URI Mappers. For instance, the mechanism
-which iterates through the module path and produces a set of
-filesystem paths where the URI might be located is implemented as a
-URI Mapper.
+which iterates through the URI path and produces a set of filesystem
+files where the URI might be located is implemented as a URI Mapper.
To implement your own URI Mapper, subclass the C++ API class
<code>URIMapper</code> and implement the <code>mapURI()</code> method:
=== modified file 'doc/zorba/xqddf.dox'
--- doc/zorba/xqddf.dox 2011-10-05 17:49:48 +0000
+++ doc/zorba/xqddf.dox 2012-01-25 00:12:28 +0000
@@ -1375,6 +1375,14 @@
AtomicType ::= QName
IndexKeyCollation ::= 'collation' UriLiteral
+
+ Note: the following annotations are accepted within the context of an index declaration:
+
+ %ann:unique, %ann:nonunique,
+ %ann:value-range, %ann:value-equality,
+ %ann:general-range, %ann:general-equality,
+ %ann:manual or %ann:automatic
+
\endcode
Syntactically, each index is defined by an <a href="#index_declaration">
@@ -1385,8 +1393,8 @@
value indexes and general indexes. Whether an index is a value or a general
index is determined by the value of the usage property, which is explained below.
-Index declarations (for both value and general indexes) must be placed inside module prologs.
-The Prolog syntax is extended accordingly, as shown above.
+Index declarations (for both value and general indexes) must be placed inside
+module prologs. The Prolog syntax is extended accordingly, as shown above.
An additional constraint (not expressible syntactically) is that only library
modules may contain index declarations [<a href="#ERRZDST0023">zerr:ZDST0023</a>].
The reasons for this rule are the same as those for collections (see \ref
@@ -1424,7 +1432,10 @@
(or key tuple in the case of value indexs) with exactly one domain node.
Otherwise, if the index is '%ann:nonunique', multiple domain nodes may have the
same key value, and as a result, each index entry associates a key with a
-set of domain nodes.
+set of domain nodes. In the current implementation, it is not allowed to declare
+an index as unique if it is a general index whose IndexKeyTypeDecl is either absent
+or specifies xs:anyAtomicType or xs:untypedAtomic as its atomic type
+[<a href="#ERRZDST0025">zerr:ZDST0025</a>].
The usage property specifies the kind of the index based on the query expressions
that may be optimized by using the index. A <strong>value equality index</strong>
@@ -1529,16 +1540,17 @@
\subsection index_creation Index Creation
-As explained already, indexes are just sets of index entries, mapping key items
-or key tuples to domain nodes. In terms of the XQuery language, these sets
-"live" in the dynamic context. In particular, XQDDF extends the dynamic context
-with a component called the <strong>available indexes</strong>. This is a map
-whose entries associate the expanded QName of an index with the entry set of the
-index. If an entry for an index appears in the available indexes of a module,
-the index is said to be available to that module.
+As explained already, indexes are just sets of index entries, where an index
+entry maps a key item or a key tuple to a set of domain nodes (to be more
+precise, an index entry contains some kind of "pointers" to nodes, not the
+nodes themselves). In terms of the XQuery language, indexes "live" in the
+dynamic context. In particular, XQDDF extends the dynamic context with a
+component called the <strong>available indexes</strong>. This is a map whose
+entries associate the expanded QName of an index with the entry set for that
+index.
In practice, the available indexes component is implemented by Zorba's storage
-system. To begin with, each index entry set is implemented by some appropriate
+system. To begin with, each index is implemented by some appropriate
data structure that acts as an index entry container. The description of
potential data structures is beyond the scope of this document, but the typical
choices are either some sort of hash table(s) (for equality indexes) or some kind
@@ -1595,9 +1607,7 @@
indexes, an error is raised [<a href="#ERRZDDY0028">zerr:ZDDY0028</a>]. The result
of the domain expression after duplicate elimination is called the <strong>domain
sequence</strong>. If the domain sequence contains a node that does not belong to
-a collection, an error is raised [<a href="#ERRZDDY0020">zerr:ZDDY0020</a>] (the
-purpose of this rule is to prevent nodes constructed by node construction
-expression to appear as domain nodes).</li>
+a collection, an error is raised [<a href="#ERRZDDY0020">zerr:ZDDY0020</a>].</li>
<li>
For each node D in the domain sequence, the IndexKeySpecs are evaluated in some
@@ -1619,8 +1629,8 @@
</li>
<li>
- Duplicate values, which may arise in the case of general indexes only, are
- eliminated from the key sequence.
+ Duplicate values (which may arise in the case of general indexes only) are
+ eliminated from the atomized sequence.
</li>
</ul>
@@ -1630,12 +1640,12 @@
<ul>
<li>
- The result of each IndexKeySpec is a single atomic item. We call this
- item a <strong>key item</strong>.
+ The result of each IndexKeySpec is a single atomic item or the empty sequence.
+ We call this result a <strong>key value</strong>.
</li>
<li>
- Let D<sub>i</sub> be the i-th domain node, and K<sub>ij</sub> be the key item
+ Let D<sub>i</sub> be the i-th domain node, and K<sub>ij</sub> be the key value
computed for D<sub>i</sub> by the j-th IndexKeySpec (where the numbering of
the IndexKeySpecs is done using their order of appearance in the index
declaration). Let K<sub>i</sub> be the tuple [K<sub>i1</sub>, ...,
@@ -1650,16 +1660,14 @@
tuples and domain nodes is one-to-one. In this case, if the index already
contains an entry whose key tuple is equal to K<sub>i</sub>, an error is
raised [<a href="#ERRZDDY0024">zerr:ZDDY0024</a>]. Otherwise, the entry
- [K<sub>i</sub>, D<sub>i</sub>] is inserted in the index container (to be very
- precise, the entry contains a "pointer" to the node, not the node itself).
+ [K<sub>i</sub>, D<sub>i</sub>] is inserted in the index container.
</li>
<li>
- If the index is non-unique, it maps key tuples to sets of domain nodes. In
- this case, if the index already contains an entry whose key is equal to
- K<sub>i</sub>, D<sub>i</sub> is added to the set associated with K<sub>i</sub>.
- Otherwise, the entry [K<sub>i</sub>, { D<sub>i</sub> }] is inserted in the
- index.
+ If the index is non-unique, then if it already contains an entry whose key
+ tuple is equal to K<sub>i</sub>, D<sub>i</sub> is added to the set associated
+ with K<sub>i</sub>. Otherwise, the entry [K<sub>i</sub>, { D<sub>i</sub> }]
+ is inserted in the index.
</li>
</ul>
@@ -1673,7 +1681,7 @@
to value indexes, the result of this IndexKeySpec may be a sequence of any
number of atomic items, and the items may have different data types. We call
this sequence a <strong>key sequence</strong>, and each atomic item in it a
- <strong>key item</strong>.
+ <strong>key item</strong> (the key sequence may also be the empty sequence).
</li>
<li>
@@ -1694,17 +1702,6 @@
into K<sub>i</sub>.
</li>
- <li>
- If any item in the expanded key sequence has a data type that is not a
- primitive builtin type, this data type is changed to the nearest base type
- that is a primitive builtin type. For example, xs:token is changed to
- xs:string, and xs:long is changed to xs:decimal. (Note: this is a conceptual
- description of the index creation process. The actual implementation may
- differ from this description as long as the results of
- <a href="#index_probing">probe functions</a> are always the same as those
- implied by this conceptual description.)
- </li>
-
<li>
The next step is to insert in the index a mapping from K<sub>ij</sub> to
D<sub>i</sub>, for each key item K<sub>ij</sub> in the expanded key sequence
@@ -1714,32 +1711,25 @@
</li>
<li>
- If the index is declared as unique, the relationship between between key
- items and domain nodes is one-to-one. In this case, if the index already
- contains an entry whose key item has the same type as K<sub>ij</sub> and
- its value is equal to K<sub>ij</sub>, an error is raised
+ If the index is declared as unique, the relationship between key items and
+ domain nodes is one-to-one. In this case, if the index already contains an
+ entry whose key item is equal to K<sub>ij</sub>, an error is raised
[<a href="#ERRZDDY0024">zerr:ZDDY0024</a>]. Otherwise, the entry
[K<sub>ij</sub>, D<sub>i</sub>] is inserted in the index container.
- <li>
-
- <li>
- If the index is non-unique, it maps key items to sets of domain nodes. In
- this case, if the index already contains an entry whose key K has the same
- type as K<sub>ij</sub> and its value is equal to K<sub>ij</sub>, D<sub>i</sub>
- is added to the set associated with K. Otherwise, the entry [K<sub>ij</sub>,
- { D<sub>i</sub> }] is inserted into the index.
- </li>
-
- <li>
- In addition to its entry set, each general index entry stores 2 extra flags:
- The <strong>multi-key flag</strong> is set to true if there is any domain
- node whose unexpanded key sequence contained more than 1 items; otherwise the
- flag is false. The <strong>untyped flag</strong> is set to true if during the
- expansion of a key sequence, an untyped key was successfully cast to an item
- with a type other than xs:string or xs:anyURI.; otherwise the flag is false.
- As we will see later, these flags are needed during <a href="#index_probing">
- index probing</a>.
- </li>
+ </li>
+
+ <li>
+ If the index is non-unique, then if it already contains an entry whose key
+ K is equal to K<sub>ij</sub>, D<sub>i</sub> is added to the node set
+ associated with K. Otherwise, the entry [K<sub>ij</sub>, { D<sub>i</sub> }]
+ is inserted into the index.
+ </li>
+
+ <li>
+ The index maintains a "special" entry for all domain nodes whose key sequence
+ is empty. All such nodes are inserted in the node set associated with this entry.
+ </li>
+
</ul>
<li>
@@ -1764,35 +1754,39 @@
The delete function is evaluated as follows:
- <ul>
- <li>If the given expanded QName does not identify an index among the
-statically known indexes in the static context of the invoking module, an error
-is raised [<a href="#ERRZDDY0021">zerr:ZDDY0021</a>].</li>
- <li>If the given expanded QName does not identify an index among the available
+<ul>
+<li>
+If the given expanded QName does not identify an index among the statically
+known indexes in the static context of the invoking module, an error is
+raised [<a href="#ERRZDDY0021">zerr:ZDDY0021</a>].
+</li>
+<li>
+If the given expanded QName does not identify an index among the available
indexes in the dynamic context of the invoking module, an error is raised [<a
-href="#ERRZDDY0023" title="zerr:ZDDY0023">zerr:ZDDY0023</a>].</li>
- <li>The result of the function is an empty XDM instance and a pending update
-list that consists of a single update primitive:
-upd:deleteIndex($indexName).</li>
- </ul>
+href="#ERRZDDY0023">zerr:ZDDY0023</a>].
+</li>
+<li>
+The result of the function is an empty XDM instance and a pending update
+list that consists of a single update primitive: upd:deleteIndex($indexName).
+</li>
+</ul>
The update primitive is applied as follows:
- <ul>
- <li>The index entry container for the index is found via the indexes
-table.</li>
- <li>All entries in the container are destroyed.</li>
- <li>The container itself is destroyed.</li>
- <li>The entry mapping the index name to the index entry container is removed
+<ul>
+<li>The index entry container for the index is found via the indexes table.</li>
+<li>All entries in the container are destroyed.</li>
+<li>The container itself is destroyed.</li>
+<li>The entry mapping the index name to the index entry container is removed
from the indexes table.</li>
- </ul>
+</ul>
\subsection index_probing Index Probing
Probing an index means retrieving the domain nodes associated with a particular
-search condition Probing can be done via the xqddf functions
+search condition. Probing can be done via the xqddf functions
idml:probe-index-point-value, idml:probe-index-point-general,
idml:probe-index-range-value, or idml:probe-index-range-general.
For each of these functions, the first argument is a QName identifying an index.
@@ -1803,72 +1797,97 @@
respectively. All of the functions return their result sorted in document order
and without duplicate nodes.
+
<strong>idml:probe-index-point-value</strong>
+
<a name="probe_index_point_value" id="probe_index_point_value"></a>
\code
idml:probe-index-point-value($indexUri as xs:QName,
- $key1 as xs:anyAtomicType?,
- ...,
- $keyM as xs:anyAtomicType?) as node()*
+ $key1 as xs:anyAtomicType?,
+ ...,
+ $keyM as xs:anyAtomicType?) as node()*
\endcode
-For the probe-index-point-value function, the search condition is specified as a
-number of <strong>search keys</strong> comprising a <strong>search
-tuple</strong>. A search key is either an atomic item or the empty sequence.
-The number of search keys must be equal to the number of IndexKeySpecs found
-in the index declaration [<a href="#ERRZDDY0025"> zerr:ZDDY0025</a>]. (Remember
-that for general indexes, there can be only one IndexKeySpec, and as a result,
-for general indexes, the probe-index-point-value function takes only one search
-value as input). Furthermore, for each search key that is not the empty sequence,
-its type must match the sequence type specified in the corresponding IndexKeyTypeDecl;
-otherwise, a type error is raised [err:XPTY0004].
-
-The result of this function is either an error or the set of domain nodes for which
-the following xquery condition returns true:
+The probe-index-point-value function retrieves the domain nodes associated by
+value equality with a given <strong>search tuple</strong>. The search tuple
+consists of a number of <strong>search keys</strong>, where each search key
+is either an atomic item or the empty sequence. The result of this function
+is either an error or the set of domain nodes for which the following xquery
+expression returns true:
\code
-$key1 eq $node/keyExpr1 and ... and $keyM eq $node/keyExprM
+$key1 eq $node/keyExpr1 and ... and $keyM eq $node/keyExprN
\endcode
-where keyExpr<sub>i</sub> is the expression specified in the i-th keyspec
-of the index. Notice that this definition implies that if any of search keys
-is the empty sequence, the result of the probe is also the empty sequence.
-
-In addition to the error conditions described already, the function raises
-a type error [err:XPTY0004] if the index is general and (a) the multi-key flag
-of the index is true, or (b) the untyped flag of the index is true and the type of
-any non-empty search key is something other than xs:untypedAtomic, xs:string, or
-xs:anyURI (or subtype of these).
+where keyExpr-i is the expression specified in the i<sup>th</sup> keyspec
+of the index and N is the number of keyspecs for the index. Notice that this
+definition implies that if any of search keys is the empty sequence, the
+result of the probe is also the empty sequence.
+
+In addition to the errors that may be raised by the above expression, the
+probe-index-point-value function may raise the following errors:
+
+<ul>
+<li>
+ <a href="#ERRZDDY0021">zerr:ZDDY0021</a> or <a href="#ERRZDDY0023">zerr:ZDDY0023</a>,
+if the index is not among the statically known indexes or the available indexes.
+</li>
+<li>
+[<a href="#ERRZDDY0025">zerr:ZDDY0025</a>], if the number of search keys is not
+equal to the number of keyspecs found in the index declaration.
+</li>
+<li>
+[err:XPTY0004], if a non-empty seach key is given, whose type does not match
+the sequence type specified in the corresponding keyspec.
+</li>
+</ul>
<strong>idml:probe-index-point-general</strong>
+
<a name="probe_index_point_general" id="probe_index_point_general"></a>
\code
idml:probe-index-point-general($indexUri as xs:QName,
- $keys as xs:anyAtomicType*) as node()*
+ $keys as xs:anyAtomicType*) as node()*
\endcode
-This method is supported by general indexes only [<a href="#ERRZDDY0029">
-zerr:ZDDY0029</a>]. The search condition is specified as a <strong>search
-sequence</strong> consisting of an arbitrary number of <strong>search keys
-</strong>, where each search key is an atomic item. If the search sequence
-is non-empty, the type of each search key must match the atomic type specified
-by the IndexKeyTypeDecl of the index; otherwise, a type error is raised [err:XPTY0004].
-
-The result of this function is either an error or the set of domain nodes for which
-the following xquery condition returns true:
+The probe-index-point-general function retrieves the domain nodes associated by
+general equality with a given <strong>search sequence</strong>. The search
+sequence consists of an arbitrary number of <strong>search keys</strong>, where
+each search key is an atomic item. The function is supported by general indexes
+only [<a href="#ERRZDDY0029">zerr:ZDDY0029</a>]. Its result is either an error
+or the set of domain nodes for which the following xquery expression returns true:
\code
$keys = $node/keyExpr
\endcode
-where keyExpr is the expression specified in the keyspec of the index.
+where keyExpr is the expression specified in the keyspec of the index (remember
+that for general indexes, there can be only one keyspec).
+
+In addition to the errors that may be raised by the above expression, the
+probe-index-point-value function may raise the following errors:
+
+<ul>
+<li>
+ <a href="#ERRZDDY0021">zerr:ZDDY0021</a> or <a href="#ERRZDDY0023">zerr:ZDDY0023</a>,
+if the index is not among the statically known indexes or the available indexes.
+</li>
+<li>
+[<a href="#ERRZDDY0029">zerr:ZDDY0029</a>], if the index is not general.
+</li>
+<li>
+[err:XPTY0004], if the search sequence contains a search key, whose type does
+not match the sequence type specified in the keyspec of the index.
+</li>
+</ul>
<strong>idml:probe-index-range-value</strong>
+
<a name="probe_index_range_value" id="probe_index_range_value"></a>
\code
probe-index-range-value($indexUri as xs:QName,
@@ -1887,22 +1906,22 @@
$upperBoundIncludedM as xs:boolean) as node()*
\endcode
-The probe-index-range-value function can be invoked on range indices only
-(value or general) [<a href="#ERRZDDY0026">zerr:ZDDY0026</a>]. The search
-condition is specified as a number M of <strong>rangespecs</strong>, where
-each rangespec consists of six values. The number M must be greater than
-0 and less than or equal to the number N of keyspecs found in the declaration
-of the given index [<a href="#ERRZDDY0025">zerr:ZDDY0025</a>]. If M is less
+The probe-index-range-value function retrieves the domain nodes associated by
+value order-comparison (operators le, lt, ge, gt) with a given <strong>search
+box</strong>. The search box is specified as a number M of <strong>rangespecs
+</strong>, where each rangespec consists of six values. The number M must be
+greater than 0 and less than or equal to the number N of keyspecs found in the
+index declaration [<a href="#ERRZDDY0025">zerr:ZDDY0025</a>]. If M is less
than N, then the "missing" rangespecs are assumed to have the following
value: [(), (), false, false, false, false]. As a result, from now on, we
can assume that M is equal to N (Remember that for general indexes, there
can be only one IndexKeySpec, and as a result, for general indexes, M = N = 1).
The i<sup>th</sup> rangespec corresponds to the i<sup>th</sup> keyspec, and
-specifies a condition on the key values that are produced by evaluating that
-keyspec for every domain node. Specifically, we define the i<sup>th</sup>
+specifies a search condition on the key values that are produced by evaluating
+that keyspec for every domain node. Specifically, we define the i<sup>th</sup>
<strong>rangespec result</strong> as the set of domain nodes for which the
-following xquery condition returns true:
+following xquery expression returns true:
\code
if ($haveLowerBound-i and $haveUpperBound-i) then
@@ -1920,26 +1939,40 @@
$lowerBoundsIncluded-i is true or false, and uop is either the le or the
lt operator depending on whether $upperBoundsIncluded-i is true or false.
-In computing the i<sup>th</sup> rangespec result, a type error [err:XPTY0004]
-is raised in the following cases: (a) $haveLowerBound-i is true and
-$lowerBound-i is an atomic item whose type does not match the atomic
-type specified by i<sup>th</sup> keyspec, or (b) $haveUpperBound-i is
-true and $upperBound-i is an atomic item whose type does not match
-the atomic type specified by i<sup>th</sup> keyspec, or (c) the index is general
-and its multi-key flag is true, or (d) the index is general, its untyped flag
-is true, $haveLowerBound-i is true, and $lowerBound-i is
-an atomic item whose type is something other than xs:untypedAtomic, xs:string,
-or xs:anyURI (or subtype of these), or (e) the index is general, its untyped flag
-is true, $haveUpperBound-i is true, and $upperBound-i is
-an atomic item whose type is something other than xs:untypedAtomic, xs:string,
-or xs:anyURI (or subtype of these).
+The result of the probe-index-range-value function is either an error, or the
+intersection of all the rangespec results. In addition to the errors that may
+be raised by a rangespec expression, the function may raise the following errors:
-The result of the probe-index-range-value is either one of the errors described
-above, or the intersection of all the rangespec results.
+<ul>
+<li>
+ <a href="#ERRZDDY0021">zerr:ZDDY0021</a> or <a href="#ERRZDDY0023">zerr:ZDDY0023</a>,
+if the index is not among the statically known indexes or the available indexes.
+</li>
+<li>
+[<a href="#ERRZDDY0026">zerr:ZDDY0026</a>], if the index is not a range index.
+</li>
+<li>
+[<a href="#ERRZDDY0025">zerr:ZDDY0025</a>], if the number of rangespecs passed
+as arguments is zero or greater than the number of keys declared for the index.
+</li>
+<li>
+[err:XPTY0004], if $haveLowerBound-i is true and $lowerBound-i is an atomic
+item whose type does not match the sequence type specified by the i<sup>th</sup>
+keyspec, or $haveUpperBound-i is true and $upperBound-i is an atomic item
+whose type does not match the sequence type specified by the i<sup>th</sup> keyspec.
+</li>
+<li>
+[<a href="#ERRZDDY0034">zerr:ZDDY0034</a>], if (a) the index is general (in which
+case there is only one rangespac), (b) the index is untyped, (c) there is both a
+lower and an upper bound, and (d) if T1 and T2 are the types of the lower and
+upper bound, neither T1 is a subtype of T2 nor T2 is a subtype of T1.
+</li>
+</ul>
<strong>idml:probe-index-range-general</strong>
+
<a name="probe_index_range_general" id="probe_index_range_general"></a>
\code
probe-index-range-general($indexUri as xs:QName,
@@ -1951,15 +1984,13 @@
$upperBoundIncluded as xs:boolean) as node()*
\endcode
-This method is supported by general range indexes only [<a href="#ERRZDDY0030">
-zerr:ZDDY0030</a>]. The search condition is specified as two sequences of atomic
-search key items and four boolean values. If any of the search sequences is
-non-empty, the type of each atomic item in it must match the atomic type specified
-by the IndexKeyTypeDecl of the index; otherwise, a type error is raised
-[zerr:XPTY0004].
-
-The result of this function is either an error or the set of domain nodes for
-which the following xquery expression returns true:
+The probe-index-range-general function retrieves the domain nodes associated
+by general order-comparison (operators <=, <, >=, >) with one or two
+<strong>search sequences</strong>. Each search sequence consists of an
+arbitrary number of <strong>search keys</strong>, where each search key is
+an atomic item. This method is supported by general range indexes only
+[<a href="#ERRZDDY0030">zerr:ZDDY0030</a>]. Its result is either an error or
+the set of domain nodes for which the following xquery expression returns true:
\code
if ($haveLowerBound and $haveUpperBound) then
@@ -1972,11 +2003,30 @@
fn:true()
\endcode
-where keyExpr is the expression specified in the keySpec of the index,
+where keyExpr is the expression specified in the keyspec of the index,
lop is either the <= or the < operator depending on whether $lowerBoundsIncluded
is true or false, and uop is either the <= or the < operator depending on whether
$upperBoundsIncluded is true or false.
+In addition to the errors that may be raised by the above expression, the
+probe-index-point-value function may raise the following errors:
+
+<ul>
+<li>
+ <a href="#ERRZDDY0021">zerr:ZDDY0021</a> or <a href="#ERRZDDY0023">zerr:ZDDY0023</a>,
+if the index is not among the statically known indexes or the available indexes.
+</li>
+<li>
+[<a href="#ERRZDDY0030">zerr:ZDDY0030</a>], if the index is not a general range index.
+</li>
+<li>
+[err:XPTY0004], if $haveLowerBound is true and $lowerBoundKeys constains an
+atomic item whose type does not match the sequence type specified by the index
+keyspec, or $haveUpperBound is true and $upperBoundKeys contains an atomic item
+whose type does not match the sequence type specified by the index keyspec.
+</li>
+</ul>
+
\subsection index_maintenance Index Maintenance
@@ -2293,8 +2343,8 @@
<a name="ERRZDST0024" id="ERRZDST0024"></a>zerr:ZDST0024, The declaration for
index specifies multiple values for the same property.
- <a name="ERRZDST0025" id="ERRZDST0025"></a>zerr:ZDST0025, The declaration for
-index specifies conflicting property values.
+ <a name="ERRZDST0025" id="ERRZDST0025"></a>zerr:ZDST0025, The index cannot be
+declared as unique.
<a name="ERRZDST0026" id="ERRZDST0026"></a>zerr:ZDST0026, The declaration for
index contains an invalid property value.
@@ -2447,6 +2497,9 @@
<a name="ERRZDDY0033" id="ERRZDDY0033"></a>zerr:ZDDY0033, Conditions for
integrity constraint were not met on collection.
+
+ <a name="ERRZDDY0034" id="ERRZDDY0034"></a>zerr:ZDDY0034, Index range-value
+ probe has search keys with incompatible types
</strong>
*/
=== modified file 'doc/zorba/xqdoc/templates/main.html'
--- doc/zorba/xqdoc/templates/main.html 2011-10-07 08:28:43 +0000
+++ doc/zorba/xqdoc/templates/main.html 2012-01-25 00:12:28 +0000
@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<html>
<head>
- <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
+ <meta content="text/html; charset=utf-8" http-equiv="content-type" />
<meta content="public" http-equiv="CACHE-CONTROL" />
<meta content="-1" http-equiv="Expires" />
<link rel="stylesheet" type="text/css" href="styles/main.css" />
- <link rel="stylesheet" href="styles/jquery.treeview.css" />
+ <link rel="stylesheet" href="styles/jquery.treeview.css" type="text/css" />
<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript" src="lib/jquery.cookie.js"></script>
<script type="text/javascript" src="lib/jquery.treeview.js"></script>
@@ -16,25 +16,37 @@
<link type="text/css" rel="stylesheet" href="styles/shCore.css"/>
<link type="text/css" rel="stylesheet" href="styles/shThemeDefault.css"/>
<link type="text/css" rel="stylesheet" href="styles/shThemeXQuery.css"/>
- <script type="text/javascript">
- SyntaxHighlighter.all()
- </script>
- <script type="text/javascript">
- jQuery(document).ready(function() {
- $("#documentation").treeview({
- control: "#treecontrol",
- animated: "fast",
- collapsed: true,
- unique: false,
- persist: "cookie"
- });
- });
- </script>
- <script src="http://www.google.com/js/gweb/analytics/autotrack.js"></script>
- <script>//
- new gweb.analytics.AutoTrack({profile: 'UA-4281090-1'});
- //</script>
- </head>
+<script type="text/javascript">
+//<![CDATA[
+SyntaxHighlighter.all()
+//]]>
+</script>
+ <script type="text/javascript">
+//<![CDATA[
+jQuery(document).ready(function() {
+$("#documentation").treeview({
+control: "#treecontrol",
+animated: "fast",
+collapsed: true,
+unique: false,
+persist: "cookie"
+});
+});
+//]]>
+</script>
+ <script type="text/javascript" src="http://www.google.com/js/gweb/analytics/autotrack.js"></script>
+<script type="text/javascript">
+//<![CDATA[
+new gweb.analytics.AutoTrack({profile: 'UA-4281090-1'});
+//]]>
+</script>
+<style type="text/css">
+/*<![CDATA[*/
+ div.c2 {clear:both;}
+ li.c1 {width:102px !important;}
+/*]]>*/
+</style>
+</head>
<body>
<div id="header">
<div class="innerheader text-left">
@@ -63,8 +75,8 @@
<div id="main">
<div id="leftMenu" >
<div id="treecontrol">
- <a title="Collapse the entire tree below" href="#"><img src="images/minus.gif" /> Collapse All</a>
- <a title="Expand the entire tree below" href="#"><img src="images/plus.gif" /> Expand All</a>
+ <a title="Collapse the entire tree below" href="#"><img src="images/minus.gif" alt="minus"/> Collapse All</a>
+ <a title="Expand the entire tree below" href="#"><img src="images/plus.gif" alt="plus"/> Expand All</a>
</div>
</div>
<div id="rightcontent" />
@@ -89,7 +101,7 @@
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
- <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
+ <noscript><p>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></p></noscript>
<a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a>
</div>
</div>
=== modified file 'include/zorba/config.h.cmake'
--- include/zorba/config.h.cmake 2011-08-22 15:14:14 +0000
+++ include/zorba/config.h.cmake 2012-01-25 00:12:28 +0000
@@ -39,19 +39,19 @@
#endif /* WIN32 */
// Platform headers
-#cmakedefine ZORBA_HAVE_COLL_H
+#cmakedefine ZORBA_HAVE_COLL_H
#cmakedefine ZORBA_HAVE_EXECINFO_H
#cmakedefine ZORBA_HAVE_FLEXLEXER_H
#cmakedefine ZORBA_HAVE_ICONV_H
-#cmakedefine ZORBA_HAVE_INTTYPES_H
-#cmakedefine ZORBA_HAVE_LIMITS_H
-#cmakedefine ZORBA_HAVE_PTHREAD_H
-#cmakedefine ZORBA_HAVE_STDINT_H
-#cmakedefine ZORBA_HAVE_STDLIB_H
+#cmakedefine ZORBA_HAVE_INTTYPES_H
+#cmakedefine ZORBA_HAVE_LIMITS_H
+#cmakedefine ZORBA_HAVE_PTHREAD_H
+#cmakedefine ZORBA_HAVE_STDINT_H
+#cmakedefine ZORBA_HAVE_STDLIB_H
#cmakedefine ZORBA_HAVE_SYS_MOUNT_H
#cmakedefine ZORBA_HAVE_SYS_TYPES_H
-#cmakedefine ZORBA_HAVE_USTRING_H
-#cmakedefine ZORBA_HAVE_UTYPES_H
+#cmakedefine ZORBA_HAVE_USTRING_H
+#cmakedefine ZORBA_HAVE_UTYPES_H
// Platform functions
#cmakedefine ZORBA_HAVE_CLOCKGETTIME_FUNCTION
@@ -138,7 +138,10 @@
#define ZORBA_MAJOR_NUMBER ${ZORBA_MAJOR_NUMBER}
#define ZORBA_MINOR_NUMBER ${ZORBA_MINOR_NUMBER}
#define ZORBA_PATCH_NUMBER ${ZORBA_PATCH_NUMBER}
-#define ZORBA_MODULES_INSTALL_DIR "${ZORBA_MODULES_INSTALL_DIR}"
+#define ZORBA_CORE_URI_DIR "${ZORBA_CORE_URI_DIR}"
+#define ZORBA_CORE_LIB_DIR "${ZORBA_CORE_LIB_DIR}"
+#define ZORBA_NONCORE_URI_DIR "${ZORBA_NONCORE_URI_DIR}"
+#define ZORBA_NONCORE_LIB_DIR "${ZORBA_NONCORE_LIB_DIR}"
// Zorba features
#cmakedefine ZORBA_NO_FULL_TEXT
@@ -150,7 +153,6 @@
#cmakedefine ZORBA_WITH_DEBUGGER
#cmakedefine ZORBA_WITH_FILE_ACCESS
#cmakedefine ZORBA_WITH_LIBXML2_SAX
-#cmakedefine ZORBA_WITH_DEBUGGER_CLIENT
// Zorba parser configuration
#cmakedefine ZORBA_DEBUG_PARSER
=== modified file 'include/zorba/debugger_client.h'
--- include/zorba/debugger_client.h 2011-07-24 22:28:31 +0000
+++ include/zorba/debugger_client.h 2012-01-25 00:12:28 +0000
@@ -162,6 +162,13 @@
* @return The id of the request.
*/
virtual std::size_t status() = 0;
+
+ /**
+ * @brief Get the variables in all the contexts in the topmost stack frame.
+ *
+ * @return The id of the request.
+ */
+ virtual std::size_t variables() = 0;
/**
* @brief Query the debug engine for supported features.
@@ -266,9 +273,13 @@
* This command tells the debug engine, that it should
* break the execution at the next point possible.
*
+ * @param withQuit This is a Zorba extension of the DBGP protocol that
+ * controls if the client should terminate execution and quit (true)
+ * or only terminate execution but not quit (false). This is used
+ * by command line clients that implement multiple query runs.
* @return The id of this request
*/
- virtual std::size_t stop() = 0;
+ virtual std::size_t stop(bool withQuit) = 0;
/**
* @brief Send the detach command to the debug engine.
@@ -521,6 +532,7 @@
*/
virtual void quit() = 0;
};
+
}//end of namespace
+
#endif
-/* vim:set et sw=2 ts=2: */
=== modified file 'include/zorba/dynamic_context.h'
--- include/zorba/dynamic_context.h 2011-10-03 09:18:49 +0000
+++ include/zorba/dynamic_context.h 2012-01-25 00:12:28 +0000
@@ -43,6 +43,7 @@
class ZORBA_DLL_PUBLIC DynamicContext
{
public:
+
/**
* \brief Defines the external variable identified by aQName and assigns it
* the value of aItem.
@@ -261,7 +262,19 @@
*/
virtual ExternalFunctionParameter*
getExternalFunctionParameter ( const String& aName ) const = 0;
-
+
+ /** \brief Returns true if the variable is bound to a value
+ *
+ * @param aNamespace the namespace of the qname of the variable to check
+ * @param aLocalname the localname of the qname of the variable to check
+ */
+ virtual bool
+ isBoundExternalVariable(const String& aNamespace, const String& aLocalname) const = 0;
+
+ /** \brief Returns true if a context item has been bound to the Dynamic Context
+ */
+ virtual bool
+ isBoundContextItem() const = 0;
protected:
/** \brief Destructor
=== modified file 'include/zorba/internal/type_traits.h'
--- include/zorba/internal/type_traits.h 2011-08-26 03:41:52 +0000
+++ include/zorba/internal/type_traits.h 2012-01-25 00:12:28 +0000
@@ -53,12 +53,13 @@
///////////////////////////////////////////////////////////////////////////////
+#ifndef ZORBA_CXX_UNIQUE_PTR
namespace zorba {
namespace internal {
/**
* \internal
- * Dummy rvalue class used by unique_ptr to prevent copying.
+ * Dummy rvalue class used by unique_ptr to prevent implicit copying.
*/
template<typename T>
class rv : public T {
@@ -89,6 +90,7 @@
} // namespace internal
} // namespace zorba
+#endif /* ZORBA_CXX_UNIQUE_PTR */
///////////////////////////////////////////////////////////////////////////////
=== modified file 'include/zorba/internal/unique_ptr.h'
--- include/zorba/internal/unique_ptr.h 2011-08-27 14:57:52 +0000
+++ include/zorba/internal/unique_ptr.h 2012-01-25 00:12:28 +0000
@@ -40,8 +40,8 @@
template<typename T> inline
typename enable_if<zorba::internal::is_movable<T>::value,
zorba::internal::rv<T>&>::type
-move( T &t ) {
- return *static_cast<zorba::internal::rv<T>*>( &t );
+move( T const &t ) {
+ return *static_cast<zorba::internal::rv<T>*>( const_cast<T*>( &t ) );
}
template<typename T> inline
=== modified file 'include/zorba/item.h'
--- include/zorba/item.h 2011-06-14 17:26:33 +0000
+++ include/zorba/item.h 2012-01-25 00:12:28 +0000
@@ -19,6 +19,8 @@
#include <iostream>
#include <zorba/config.h>
#include <zorba/api_shared_types.h>
+#include <zorba/store_consts.h>
+#include <vector>
namespace zorba {
@@ -31,6 +33,11 @@
void operator&(zorba::serialization::Archiver &ar, zorba::Item &obj);
}
+/**
+ * Used for Item::getNamespaceBindings() and ItemFactory::createElementNode().
+ */
+typedef std::vector<std::pair<String, String> > NsBindings;
+
/** \brief The Zorba Item interface.
*
* This class is the Zorba representation of an Item as defined in the
@@ -266,7 +273,7 @@
/** \brief Get an iterator for the children of this (node) Item.
*
* Note that this function is only available for node Items.
- * The file \link simple.cpp \endlink contains some basic examples the demonstrate
+ * The file \link simple.cpp \endlink contains some basic examples that demonstrate
* the use of this function.
*
* @return Iterator over the children of this node.
@@ -278,7 +285,7 @@
/** \brief Get an iterator for the attributes of this (node) Item.
*
* Note that this function is only available for node Items.
- * The file \link simple.cpp \endlink contains some basic examples the demonstrate
+ * The file \link simple.cpp \endlink contains some basic examples that demonstrate
* the use of this function.
*
* @return Iterator over the attributes of this node.
@@ -287,6 +294,25 @@
Iterator_t
getAttributes() const;
+ /** \brief Get an iterator for the namespace bindings of this (element) Item.
+ *
+ * Note that this function is only available for element Items.
+ * The file \link simple.cpp \endlink contains some basic examples that demonstrate
+ * the use of this function.
+ *
+ * @param aBindings An STL list to receive the namespace bindings of this node (each
+ * represented as a std::pair<zorba::String,zorba::String> where the
+ * first string is the namespace prefix and the second is the namespace URI).
+ * @param aScope An instance of NsScoping to declare which bindings to return:
+ * those local to the element; those local to all parent elements; or all bindings
+ * (the default).
+ * @throw ZorbaException if an error occured, e.g. the Item is not of type element.
+ */
+ void
+ getNamespaceBindings(NsBindings& aBindings,
+ store::StoreConsts::NsScoping aNsScoping = store::StoreConsts::ALL_NAMESPACES)
+ const;
+
/** \brief Get parent of this (node) Item.
*
* Note that this function is only available for node Items.
@@ -300,7 +326,7 @@
/** \brief Get the name of this (node) Item.
*
* Note that this function is only available for node Items.
- * The file \link simple.cpp \endlink contains some basic examples the demonstrate
+ * The file \link simple.cpp \endlink contains some basic examples that demonstrate
* the use of this function.
*
* @return bool if the name of the node was retrieved successfully
=== modified file 'include/zorba/item_factory.h'
--- include/zorba/item_factory.h 2011-07-24 22:28:31 +0000
+++ include/zorba/item_factory.h 2012-01-25 00:12:28 +0000
@@ -22,6 +22,7 @@
#include <zorba/config.h>
#include <zorba/api_shared_types.h>
+#include <zorba/item.h>
#include <zorba/streams.h>
namespace zorba {
@@ -327,6 +328,34 @@
createDuration ( short aYear, short aMonths, short aDays,
short aHours, short aMinutes, double aSeconds ) = 0;
+ /** \brief Creates a dayTimeDuration Item
+ * see [http://www.w3.org/TR/xpath-functions/#duration-subtypes]
+ *
+ * @param aValue String lexical representation of the duration.
+ * @return the dayTimeDuration Item.
+ */
+ virtual Item
+ createDayTimeDuration( const String& aValue ) = 0;
+
+ /** \brief Creates a yearMonthDuration Item
+ * see [http://www.w3.org/TR/xpath-functions/#duration-subtypes]
+ *
+ * @param aValue String lexical representation of the duration.
+ * @return the yearMonthDuration Item.
+ */
+ virtual Item
+ createYearMonthDuration( const String& aValue ) = 0;
+
+ /** \brief Creates a documentNode Item
+ * see [http://www.w3.org/TR/xpath-functions/#duration-subtypes]
+ *
+ * @param aBaseUri String representation of the Base URI.
+ * @param aDocUri String representation of the Document URI.
+ * @return the documentNode Item.
+ */
+ virtual Item
+ createDocumentNode( const String& aBaseUri, const String& aDocUri ) = 0;
+
/** \brief creates a float item
* see [http://www.w3.org/tr/xmlschema-2/#float]
*
@@ -579,7 +608,7 @@
Item aTypeName,
bool aHasTypedValue,
bool aHasEmptyValue,
- std::vector<std::pair<String, String> > aNsBindings) = 0;
+ NsBindings aNsBindings) = 0;
/**
* Create a new attribute node N and place it among the
@@ -609,6 +638,36 @@
std::vector<Item> aTypedValue) = 0;
/**
+ * Create a new comment node N and place it as the last child of a given
+ * parent node. If no parent is given, N becomes the root (and single node)
+ * of a new XML tree.
+ *
+ * @param parent The parent P of the new node; may be NULL.
+ * @param content The content of the new node.
+ * @return The new node N created by this method
+ */
+ virtual Item createCommentNode (
+ Item aParent,
+ String &aContent) = 0;
+
+ /**
+ * Create a new Processing Instruction node N and place it among the
+ * children of a given parent node. If no parent is given, N becomes the
+ * root (and single node) of a new XML tree.
+ *
+ * @param aParent The parent P of the new node; may be NULL.
+ * @param aTarget The Target of the new node.
+ * @param aContent The Content of the new node.
+ * @param aBaseUri The Base URI of the new node, may be NULL.
+ * @return The new node N created by this method
+ */
+ virtual Item createPiNode (
+ Item aParent,
+ String &aTarget,
+ String &aContent,
+ String &aBaseUri)=0;
+
+ /**
* Create a new text node N and place it among the
* children of a given parent node. If no parent is given, N becomes the
* root (and single node) of a new XML tree.
=== modified file 'include/zorba/options.h'
--- include/zorba/options.h 2011-07-24 22:28:31 +0000
+++ include/zorba/options.h 2012-01-25 00:12:28 +0000
@@ -51,11 +51,20 @@
* example_6 in file \link simple.cpp \endlink shows an example
* how CompilerHints can be used.
*/
-typedef struct Zorba_CompilerHints {
+typedef struct Zorba_CompilerHints
+{
/** \brief The optimization level that is used */
Zorba_opt_level_t opt_level;
/** \brief Treat the query as a library module */
bool lib_module;
+
+ /**
+ * \brief By default, this flag is set to false. Applications may set it to
+ * true if they plan to execute the query only via one of the methods that
+ * serialize the query result.
+ */
+ bool for_serialization_only;
+
#ifdef __cplusplus
/** \brief Default constructor for CompilerHints which assigns default values to all hints (C++ only).
*
@@ -67,7 +76,9 @@
#endif
} Zorba_CompilerHints_t;
-typedef enum {
+
+typedef enum
+{
ZORBA_SERIALIZATION_METHOD_XML,
ZORBA_SERIALIZATION_METHOD_HTML,
ZORBA_SERIALIZATION_METHOD_XHTML,
@@ -75,12 +86,16 @@
ZORBA_SERIALIZATION_METHOD_BINARY
} Zorba_serialization_method_t;
-typedef enum {
+
+typedef enum
+{
ZORBA_BYTE_ORDER_MARK_YES,
ZORBA_BYTE_ORDER_MARK_NO
} Zorba_byte_order_mark_t;
-typedef enum {
+
+typedef enum
+{
ZORBA_ESCAPE_URI_ATTRIBUTES_YES,
ZORBA_ESCAPE_URI_ATTRIBUTES_NO
} Zorba_escape_uri_attributes_t;
=== modified file 'include/zorba/pregenerated/diagnostic_list.h'
--- include/zorba/pregenerated/diagnostic_list.h 2011-10-19 15:28:51 +0000
+++ include/zorba/pregenerated/diagnostic_list.h 2012-01-25 00:12:28 +0000
@@ -458,6 +458,8 @@
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZXQD0005_INVALID_KEY_FOR_MAP;
+extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZXQD0006_INVALID_UTF8_BYTE_SEQUENCE;
+
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZAPI0002_XQUERY_COMPILATION_FAILED;
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZAPI0003_XQUERY_NOT_COMPILED;
@@ -474,6 +476,8 @@
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZAPI0009_XQUERY_NOT_COMPILED_IN_DEBUG_MODE;
+extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZAPI0011_ELEMENT_NOT_DECLARED;
+
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZAPI0014_INVALID_ARGUMENT;
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZAPI0015_CREATEMODULE_NOT_FOUND;
@@ -598,6 +602,8 @@
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZDDY0034_INDEX_RANGE_VALUE_PROBE_BAD_KEY_TYPES;
+extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZDDY0035_INDEX_GENERAL_INSERT;
+
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZDDY0031_IC_NOT_DECLARED;
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZDDY0032_IC_NOT_ACTIVATED;
@@ -624,6 +630,8 @@
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZDST0024_INDEX_MULTIPLE_PROPERTY_VALUES;
+extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZDST0025_INDEX_BAD_UNIQUE_PROPERTY;
+
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZDST0026_INDEX_INVALID_PROPERTY_VALUE;
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZDST0027_INDEX_BAD_KEY_TYPE;
@@ -684,10 +692,6 @@
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZSTR0004_INDEX_PARTIAL_KEY_REMOVE;
-extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZSTR0005_INDEX_PARTIAL_KEY_PROBE;
-
-extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZSTR0006_INDEX_INVALID_BOX_PROBE;
-
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZSTR0007_INDEX_UNSUPPORTED_PROBE_CONDITION;
extern ZORBA_DLL_PUBLIC ZorbaErrorCode ZSTR0008_COLLECTION_ALREADY_EXISTS;
@@ -752,6 +756,10 @@
extern ZORBA_DLL_PUBLIC ZorbaWarningCode ZWST0004_AMBIGUOUS_SEQUENTIAL_FLWOR;
+extern ZORBA_DLL_PUBLIC ZorbaWarningCode ZWST0005_CACHING_NOT_POSSIBLE;
+
+extern ZORBA_DLL_PUBLIC ZorbaWarningCode ZWST0006_CACHING_MIGHT_NOT_BE_INTENDED;
+
} // namespace zwarn
} // namespace zorba
#endif /* ZORBA_DIAGNOSTIC_LIST_API_H */
=== modified file 'include/zorba/static_collection_manager.h'
--- include/zorba/static_collection_manager.h 2011-09-12 22:42:28 +0000
+++ include/zorba/static_collection_manager.h 2012-01-25 00:12:28 +0000
@@ -23,14 +23,14 @@
namespace zorba {
/** \brief Using the StaticCollectionManager one can retrieve information
- * about statically declared collections as well as manage them.
+ * about statically declared collections and indexes as well as manage them.
*
* The StaticCollectionManager can be retrieved from (1) a compiled XQuery
* or (2) a StaticContext object. In both cases, this class provides access
- * to information for the collections that are declared in (1) all the
+ * to information for the collections and indexes that are declared in (1) all the
* modules (transitively) imported by the main query or (2) the module
* that resulted in the compilation of the StaticContext, respectively.
- * Moreover, this class allows to create or delete such collections.
+ * Moreover, this class allows to create or delete such collections and indexes.
*
*/
class ZORBA_DLL_PUBLIC StaticCollectionManager : public CollectionManager
@@ -56,6 +56,69 @@
virtual bool
isDeclaredCollection(const Item& aQName) const = 0;
+ /**
+ * Create the index with the given name.
+ *
+ * @param aName The name of the index to create.
+ *
+ * @throw zerr:ZDDY0021 if a index with the given name is not declared.
+ *
+ * @throw zerr:ZDDY0022 if a index with the given name already exists.
+ */
+ virtual void
+ createIndex(const Item& aQName) = 0;
+
+ /**
+ * Create the index with the given name.
+ *
+ * @param aName The name of the index to create.
+ *
+ * @throw zerr:ZDDY0021 if a index with the given name is not declared.
+ *
+ * @throw zerr:ZDDY0009 if a index with the given name does not exist
+ */
+ virtual void
+ deleteIndex(const Item& aQName) = 0;
+
+ /**
+ * This function returns a sequence of names of the indexes
+ * that are available.
+ *
+ * @return The list of names of the available indexes.
+ */
+ virtual ItemSequence_t
+ availableIndexes() const = 0;
+
+ /**
+ * This function returns true if a index with the given name is available.
+ *
+ * @param aName The name of the index that is being checked.
+ *
+ * @return true if the index is available and false otherwise.
+ */
+ virtual bool
+ isAvailableIndex(const Item& aQName) const = 0;
+
+ /**
+ * List all the indexes that are declared in the XQuery or the
+ * StaticContext that was used to retrieve this StaticCollectionManager.
+ *
+ * @return a sequence of QNames of all said indexes
+ */
+ virtual ItemSequence_t
+ declaredIndexes() const = 0;
+
+ /**
+ * Checks if a index with a given QName is declared in the XQuery
+ * or the StaticContext that was used to retrieve this
+ * StaticCollectionManager.
+ *
+ * @return true if a collection with the given name is declared,
+ * false otherwise.
+ */
+ virtual bool
+ isDeclaredIndex(const Item& aQName) const = 0;
+
virtual ~StaticCollectionManager() {}
}; /* class StaticCollectionManager */
=== modified file 'include/zorba/static_context.h'
--- include/zorba/static_context.h 2011-08-31 13:17:59 +0000
+++ include/zorba/static_context.h 2012-01-25 00:12:28 +0000
@@ -47,536 +47,626 @@
* it is the responibility of the client code to synchronize assignments to the
* SmartPtr holding this object.
*/
- class ZORBA_DLL_PUBLIC StaticContext : public SmartObject
- {
- public:
- /** \brief Destructor
- */
- virtual ~StaticContext() {}
-
- /** \brief Loads the declarations and definitions of a given XQuery prolog into
- * this static context.
- *
- * This function compiles the prolog passed as first parameter and loads
- * all declarations and definitions into this static context.
- *
- * The static context extended by this prolog can then be used for creating
- * a compiling a new query.
- *
- * A StaticException is raised if the prolog could not be compiled or
- * if the prolog does not contain valid declarations (e.g. duplicate declarations).
- */
- virtual void
- loadProlog(const String&, const Zorba_CompilerHints_t &hints) = 0;
-
- /** \brief Create a child static context, i.e. a context with the same information,
- * of the given static context.
- *
- * A child static context carries the same context as it's parent but
- * can override any information.
- */
- virtual StaticContext_t
- createChildContext() const = 0;
-
- /** \brief Add a pair (prefix, URI) to the statically known namespaces that
- * are available during query compilation.
- *
- * See http://www.w3.org/TR/xquery/#static_context.
- *
- * @param aPrefix the prefix String.
- * @param aURI the URI String.
- * @return true if the pair was added to the set of statically known namespaces,
- * false otherwise.
- * @throw ZorbaException if an error occures.
- */
- virtual bool
- addNamespace( const String& aPrefix, const String& aURI ) = 0;
-
- /** \brief Get the namespace URI for a given prefix.
- *
- * @param aPrefix the prefix for which to retrieve the namespace URI.
- * @return String the URI for the given prefix or an empty String if no URI
- * could be found for the given prefix and an DiagnosticHandler has been
- * registered.
- * @throw ZorbaException if an error occured (e.g. no URI could be found for the given prefix).
- */
- virtual String
- getNamespaceURIByPrefix( const String& aPrefix ) const = 0;
-
- /** \brief Set the default element and type namespace
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @param aURI of the default element and type namespace URI.
- * @return true if the default element and type namespace URI has been set, false otherwise
- * if an DiagnosticHandler has been registered.
- * @throw ZorbaException if an error occured.
- */
- virtual bool
- setDefaultElementAndTypeNamespace( const String& aURI ) = 0;
-
- /** \brief Get the default element and type namespace URI.
- *
- * @return String the URI for the default element and type namespace.
- * @throw ZorbaException if an error occured.
- */
- virtual String
- getDefaultElementAndTypeNamespace( ) const = 0;
-
- /** \brief Set the default functionnamespace
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @param aURI of the default function namespace.
- * @return true if the default function namespace URI has been set, false otherwise
- * if an DiagnosticHandler has been registered.
- * @throw ZorbaException if an error occured.
- */
- virtual bool
- setDefaultFunctionNamespace( const String& aURI ) = 0;
-
- /** \brief Get the default function namespace.
- *
- * @return String the URI of the default function namespace.
- * DiagnosticHandler has been registered.
- * @throw ZorbaException if an error occured.
- */
- virtual String
- getDefaultFunctionNamespace( ) const = 0;
-
- /** \brief Adds a collation URI.
- *
- * The URI specifies the locale and collation strength of the collation that is added.
- * A valid collation URI must begin with %http://www.zorba-xquery.com/collations/.
- * This prefix is followed by a collation strength (i.e. PRIMARY, SECONDARY, TERTIARY,
- * QUATTERNARY, or IDENTICAL) followed by a '/'.
- * After the strength a lower-case two- or three-letter ISO-639 language code must follow.
- * The URI may end with an upper-case two-letter ISO-3166.
- * For example, %http://www.zorba-xquery.com/collations/PRIMARY/en/US
- * specifies an english language with US begin the country..
- *
- * Internally, ICU is used for comparing strings. For detailed description see
- * http://www.icu-project.org/apiref/icu4c/classCollator.html
- * and http://www.icu-project.org/apiref/icu4c/classLocale.html
- *
- * @param aURI the URI of the collation.
- * @throw ZorbaException if an error occured (e.g. the URI was not a valid
- * collation URI).
- */
- virtual void
- addCollation( const String& aURI ) = 0;
-
- /** \brief Set the URI of the default collation.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @param aURI URI of the default collation.
- * @throw ZorbaException if an error occured (e.g., the URI does not
- * identify a collation among the statically known collations.
- */
- virtual void
- setDefaultCollation( const String& aURI ) = 0;
-
- /** \brief Get the URI of the default collation
- *
- * @return String the URI of the default collation.
- */
- virtual String
- getDefaultCollation() const = 0;
-
- /** \brief Set the XQuery processing mode (version 1.0 or 3.0).
- *
- *
- * @param aMode the XQuery version.
- * @return true if the version was set, false otherwise.
- */
- virtual bool
- setXQueryVersion( xquery_version_t aMode ) = 0;
-
- /** \brief Get the XQuery processing mode (version 1.0 or 3.0).
- *
- *
- * @return xquery_version_t the XQuery version processing mode.
- */
- virtual xquery_version_t
- getXQueryVersion( ) const = 0;
-
- /** \brief Set the XPath 1.0 compatibility mode.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @param aMode the XPath 1.0 compatibility mode.
- * @return true if the mode was set, false otherwise.
- */
- virtual bool
- setXPath1_0CompatibMode( xpath1_0compatib_mode_t aMode ) = 0;
-
- /** \brief Get the XPath 1.0 compatibility mode.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @return xpath1_0compatib_mode_t the XPath 1.0 compatibility mode.
- */
- virtual xpath1_0compatib_mode_t
- getXPath1_0CompatibMode( ) const = 0;
-
- /** \brief Set the construction mode.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @param aMode the construction mode.
- * @return true if the mode was set, false otherwise.
- */
- virtual bool
- setConstructionMode( construction_mode_t aMode ) = 0;
-
- /** \brief Get the construction mode.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @return construction_mode_t the construction mode.
- */
- virtual construction_mode_t
- getConstructionMode( ) const = 0;
-
- /** \brief Set the ordering mode.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @param aMode the ordering mode.
- * @return true if the mode was set, false otherwise.
- */
- virtual bool
- setOrderingMode( ordering_mode_t aMode ) = 0;
-
- /** \brief Get the ordering mode.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @return ordering_mode_t the ordering mode.
- */
- virtual ordering_mode_t
- getOrderingMode( ) const = 0;
-
- /** \brief Set the default order for the empty sequence.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @param aMode the default order for the empty sequence.
- * @return true if the mode was set, false otherwise.
- */
- virtual bool
- setDefaultOrderForEmptySequences( order_empty_mode_t aMode ) = 0;
-
- /** \brief Get the default order for the empty sequence.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @return order_empty_mode_t the ordering mode.
- */
- virtual order_empty_mode_t
- getDefaultOrderForEmptySequences( ) const = 0;
-
- /** \brief Set the boundary space policy.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @param aMode the boundary space policy.
- * @return true if the mode was set, false otherwise.
- */
- virtual bool
- setBoundarySpacePolicy( boundary_space_mode_t aMode) = 0;
-
- /** \brief Get the boundary space policy.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @return boundary_space_mode_t the boundary space policy.
- */
- virtual boundary_space_mode_t
- getBoundarySpacePolicy( ) const = 0;
-
- /** \brief Set the copy namespace mode.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @param aPreserve the preserve mode.
- * @param aInherit the inherit mode.
- * @return true if the mode was set, false otherwise.
- */
- virtual bool
- setCopyNamespacesMode( preserve_mode_t aPreserve,
- inherit_mode_t aInherit ) = 0;
-
- /** \brief Get the copy namespace mode.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @return aPreserve the preserve mode.
- * @return aInherit the inherit mode.
- */
- virtual void
- getCopyNamespacesMode( preserve_mode_t& aPreserve,
- inherit_mode_t& aInherit ) const = 0;
-
- /** \brief Set the base URI.
- * (see http://www.w3.org/TR/xquery/#static_context)
- *
- * @param aBaseURI the base URI as String.
- * @return true if the base URI has been set, false otherwise.
- */
- virtual bool
- setBaseURI( const String& aBaseURI ) = 0;
-
- /** \brief Get the base URI.
- *
- * @return String the base URI.
- */
- virtual String
- getBaseURI( ) const = 0;
-
- /** \brief Get the revalidation mode.
- *
- * @return the revalidation mode.
- */
- virtual validation_mode_t
- getRevalidationMode() const = 0;
-
- /** \brief Set the revalidation mode.
- *
- * @param aMode the revalidation mode.
- */
- virtual void
- setRevalidationMode(validation_mode_t aMode) = 0;
-
- /** \brief Register a module providing access to external functions.
- *
- * Register a module that provides access to external functions.
- * The caller keeps the ownership of the Module and the StatelessExternalFunction
- * objects passed to this function.
- *
- * @param aModule the module object
- * @return true if the module has been set, false otherwise.
- */
- virtual bool
- registerModule(ExternalModule* aModule) = 0;
-
- /**
- * \brief Register a URI Mapper which will transform a given URI
- * into several alternate potential URIs.
- *
- * QQQ doc
- */
- virtual void
- registerURIMapper(URIMapper* aMapper) = 0;
-
- /**
- * \brief Register a URL Resolver which will transform a given
- * URL into a Resource.
- *
- * QQQ doc
- */
- virtual void
- registerURLResolver(URLResolver* aResolver) = 0;
-
- /** \brief Set the type of a statically known document
- */
- virtual void
- setDocumentType(const String& aDocUri, TypeIdentifier_t type) = 0;
-
- /** \brief Get the type of a statically known document
- */
- virtual TypeIdentifier_t
- getDocumentType(const String& aDocUri) const = 0;
-
- /** \brief Set the type of a statically known collection
- */
- virtual void
- setCollectionType(const String& aCollectionUri, TypeIdentifier_t type) = 0;
-
- /** \brief Get the type of a statically known collection
- */
- virtual TypeIdentifier_t
- getCollectionType(const String& aCollectionUri) const = 0;
-
-#ifndef ZORBA_NO_FULL_TEXT
- virtual void
- addThesaurusProvider( ThesaurusProvider const* ) = 0;
-
- virtual void
- removeThesaurusProvider( ThesaurusProvider const* ) = 0;
-#endif /* ZORBA_NO_FULL_TEXT */
-
- /** \brief Check if a function with the given name and arity are registered in the context.
- */
- virtual bool
- containsFunction(const String& aFnNameUri, const String& aFnNameLocal, int arity) const = 0;
-
- virtual void
- findFunctions(const Item& aQName, std::vector<Function_t>& aFunctions) const = 0;
-
- virtual void
- disableFunction(const Function_t& aFunction) = 0;
-
- virtual void
- disableFunction(const Item& aQName, int arity) = 0;
-
- virtual void
- getFunctionAnnotations(const Item& aQName, int arity, std::vector<Annotation_t>& aAnnotations) const = 0;
-
- /** \brief Set the type of the context item.
- */
- virtual void
- setContextItemStaticType(TypeIdentifier_t type) = 0;
-
- /** \brief Fetch the type of the context item.
- */
- virtual TypeIdentifier_t
- getContextItemStaticType() const = 0;
-
- /** \brief Set the output stream that is used by the fn:trace function
- *
- * Sets the output stream that is used by the fn:trace function to the given output stream.
- * The default stream is std::cerr.
- *
- */
- virtual void
- setTraceStream(std::ostream&) = 0;
-
- /** \brief Resets the output stream that is used by the fn:trace function to std::cerr
- */
- virtual void
- resetTraceStream() = 0;
-
- /** \brief Get an option that was declared using the declare option syntax
- *
- * @param aQName The QName of the option to get.
- * @param aOptionValue The value of the option if found.
- * @return true if the option was found, false otherwise.
- */
- virtual bool
- getOption( const Item& aQName, String& aOptionValue) const = 0;
-
- /** \brief Declare an option (same as using declare option in XQuery)
- *
- * @param aQName The QName of the option to declare.
- * @param aOptionValue The value of the option to declare.
- */
- virtual void
- declareOption( const Item& aQName, const String& aOptionValue) = 0;
-
- virtual void
- setModulePaths( const std::vector<String>& aModulePaths ) = 0;
-
- virtual void
- getModulePaths( std::vector<String>& aModulePaths ) const = 0;
-
- virtual void
- getFullModulePaths( std::vector<String>& aFullModulePaths ) const = 0;
-
- /** \brief Resolves the given URI against the value of the base-uri
- * property from the static context.
- *
- * @param aRelativeUri The relative URI to be resolved.
- */
- virtual String
- resolve(const String& aRelativeUri) const = 0;
-
- /** \brief Resolves the given relative URI against the absolute base URI.
- *
- * @param aRelativeUri The relative URI to be resolved.
- * @param aBaseUri The absolute URI against which the resolving is performed.
- */
- virtual String
- resolve(const String& aRelativeUri, const String& aBaseUri) const = 0;
-
- /** \brief Validates this Item.
- * Note: works only on document and element nodes, otherwise returns false.
- *
- * @param rootElement the root of the tree beeing validated
- * @param validatedResult the result of the validation
- * @param validationMode Validation mode: default value is validate_strict
- * @return true if validation is correct, false if validation is disabled, throws errors if validation fails
- * @throw ZorbaException if any validation error occured
- */
- virtual bool
- validate(
- const Item& rootElement,
- Item& validatedResult,
- validation_mode_t validationMode = validate_strict
- ) const = 0;
-
- /** \brief Validates this Item while loading the schema for targetNamespace
- * Note: works only on document or element nodes, otherwise returns false.
- *
- * @param rootElement the root of the tree beeing validated
- * @param validatedResult the result of the validation
- * @param targetNamespace the expected namespace of root of the tree beeing validated ???
- * @param validationMode Validation mode: default value is validate_strict
- * @return true if validation is correct, false if validation is disabled, throws errors if validation fails
- * @throw ZorbaException if any validation error occured
- */
- virtual bool
- validate(
- const Item& rootElement,
- Item& validatedResult,
- const String& targetNamespace,
- validation_mode_t validationMode = validate_strict
- ) const = 0;
-
- /** \brief Validates stringValue as XML simple content, i.e. the text value of attributes or
- * text only element content.
- *
- * @param stringValue the value to be validated
- * @param typeQName
- * @param resultList the result of the validation, a vector of atomic Items
- * @return true if validation is correct, false if validation is disabled, throws errors if validation fails
- * @throw ZorbaException if any validation error occured
- */
- virtual bool
- validateSimpleContent(
- const String& stringValue,
- const Item& typeQName,
- std::vector<Item>& resultList
- ) const= 0;
-
- /** \brief Invokes the XQuery function with the given name and
- * the given parameters.
- *
- * Note that the function to be invoked needs to be declared in this static
- * context. In order to declare a function in the static context, the
- * loadProlog method of this class can be used.
- *
- * Also note that if the function to be invoked is an updating function,
- * its resulting pending update list is implicitly applied by this function.
- *
- * @param aQName the name of the function to be invoked
- * @param aArgs a vector of ItemSequences. One entry in the vector
- * corresponds to one argument that is passed to the function.
- *
- * @return The result of the function that is invoked. If the function
- * to be invoked is an updating function, the resulting item sequence
- * is empty.
- */
- virtual ItemSequence_t
- invoke(const Item& aQName,
- const std::vector<ItemSequence_t>& aArgs) const = 0;
-
- /** \brief Returns a CollectionManager responsible for all collections
- * which are statically declared in this static context.
- *
- * The collection manager provides a set of functions for managing
- * collections and their contents.
- *
- * @return The collection manager responsible for managing
- * collections of this context.
- *
- */
- virtual StaticCollectionManager*
- getStaticCollectionManager() const = 0;
-
- /**
- * @brief sets the audit event that will be populated during execution
- *
- * @param anEvent the audit event
- */
- virtual void
- setAuditEvent(audit::Event* anEvent) = 0;
-
- /**
- * @brief gets the audit event that is populated during execution
- *
- * @return the audit event
- */
- virtual audit::Event*
- getAuditEvent() = 0;
-
+class ZORBA_DLL_PUBLIC StaticContext : public SmartObject
+{
+ public:
+ /** \brief Destructor
+ */
+ virtual ~StaticContext() {}
+
+ /** \brief Loads the declarations and definitions of a given XQuery prolog into
+ * this static context.
+ *
+ * This function compiles the prolog passed as first parameter and loads
+ * all declarations and definitions into this static context.
+ *
+ * The static context extended by this prolog can then be used for creating
+ * a compiling a new query.
+ *
+ * A StaticException is raised if the prolog could not be compiled or
+ * if the prolog does not contain valid declarations (e.g. duplicate declarations).
+ */
+ virtual void
+ loadProlog(const String&, const Zorba_CompilerHints_t &hints) = 0;
+
+ /** \brief Create a child static context, i.e. a context with the same information,
+ * of the given static context.
+ *
+ * A child static context carries the same context as it's parent but
+ * can override any information.
+ */
+ virtual StaticContext_t
+ createChildContext() const = 0;
+
+ /** \brief Add a pair (prefix, URI) to the statically known namespaces that
+ * are available during query compilation.
+ *
+ * See http://www.w3.org/TR/xquery/#static_context.
+ *
+ * @param aPrefix the prefix String.
+ * @param aURI the URI String.
+ * @return true if the pair was added to the set of statically known namespaces,
+ * false otherwise.
+ * @throw ZorbaException if an error occures.
+ */
+ virtual bool
+ addNamespace( const String& aPrefix, const String& aURI ) = 0;
+
+ /** \brief Get the namespace URI for a given prefix.
+ *
+ * @param aPrefix the prefix for which to retrieve the namespace URI.
+ * @return String the URI for the given prefix or an empty String if no URI
+ * could be found for the given prefix and an DiagnosticHandler has been
+ * registered.
+ * @throw ZorbaException if an error occured (e.g. no URI could be found for the given prefix).
+ *
+ * @deprecated This function is deprecated. Use getNamespaceBindings instead.
+ */
+ virtual String
+ getNamespaceURIByPrefix( const String& aPrefix ) const = 0;
+
+ /**
+ * \brief Get the list of all namespace bindings (prefix, uri)
+ * declared in this and its parent static contexts.
+ *
+ * @param aBindings the bindings are added to this list
+ */
+ virtual void
+ getNamespaceBindings( NsBindings& aBindings ) const = 0;
+
+ /** \brief Set the default element and type namespace
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @param aURI of the default element and type namespace URI.
+ * @return true if the default element and type namespace URI has been set, false otherwise
+ * if an DiagnosticHandler has been registered.
+ * @throw ZorbaException if an error occured.
+ */
+ virtual bool
+ setDefaultElementAndTypeNamespace( const String& aURI ) = 0;
+
+ /** \brief Get the default element and type namespace URI.
+ *
+ * @return String the URI for the default element and type namespace.
+ * @throw ZorbaException if an error occured.
+ */
+ virtual String
+ getDefaultElementAndTypeNamespace( ) const = 0;
+
+ /** \brief Set the default functionnamespace
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @param aURI of the default function namespace.
+ * @return true if the default function namespace URI has been set, false otherwise
+ * if an DiagnosticHandler has been registered.
+ * @throw ZorbaException if an error occured.
+ */
+ virtual bool
+ setDefaultFunctionNamespace( const String& aURI ) = 0;
+
+ /** \brief Get the default function namespace.
+ *
+ * @return String the URI of the default function namespace.
+ * DiagnosticHandler has been registered.
+ * @throw ZorbaException if an error occured.
+ */
+ virtual String
+ getDefaultFunctionNamespace( ) const = 0;
+
+ /** \brief Adds a collation URI.
+ *
+ * The URI specifies the locale and collation strength of the collation that is added.
+ * A valid collation URI must begin with %http://www.zorba-xquery.com/collations/.
+ * This prefix is followed by a collation strength (i.e. PRIMARY, SECONDARY, TERTIARY,
+ * QUATTERNARY, or IDENTICAL) followed by a '/'.
+ * After the strength a lower-case two- or three-letter ISO-639 language code must follow.
+ * The URI may end with an upper-case two-letter ISO-3166.
+ * For example, %http://www.zorba-xquery.com/collations/PRIMARY/en/US
+ * specifies an english language with US begin the country..
+ *
+ * Internally, ICU is used for comparing strings. For detailed description see
+ * http://www.icu-project.org/apiref/icu4c/classCollator.html
+ * and http://www.icu-project.org/apiref/icu4c/classLocale.html
+ *
+ * @param aURI the URI of the collation.
+ * @throw ZorbaException if an error occured (e.g. the URI was not a valid
+ * collation URI).
+ */
+ virtual void
+ addCollation( const String& aURI ) = 0;
+
+ /** \brief Set the URI of the default collation.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @param aURI URI of the default collation.
+ * @throw ZorbaException if an error occured (e.g., the URI does not
+ * identify a collation among the statically known collations.
+ */
+ virtual void
+ setDefaultCollation( const String& aURI ) = 0;
+
+ /** \brief Get the URI of the default collation
+ *
+ * @return String the URI of the default collation.
+ */
+ virtual String
+ getDefaultCollation() const = 0;
+
+ /** \brief Set the XQuery processing mode (version 1.0 or 3.0).
+ *
+ *
+ * @param aMode the XQuery version.
+ * @return true if the version was set, false otherwise.
+ */
+ virtual bool
+ setXQueryVersion( xquery_version_t aMode ) = 0;
+
+ /** \brief Get the XQuery processing mode (version 1.0 or 3.0).
+ *
+ *
+ * @return xquery_version_t the XQuery version processing mode.
+ */
+ virtual xquery_version_t
+ getXQueryVersion( ) const = 0;
+
+ /** \brief Set the XPath 1.0 compatibility mode.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @param aMode the XPath 1.0 compatibility mode.
+ * @return true if the mode was set, false otherwise.
+ */
+ virtual bool
+ setXPath1_0CompatibMode( xpath1_0compatib_mode_t aMode ) = 0;
+
+ /** \brief Get the XPath 1.0 compatibility mode.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @return xpath1_0compatib_mode_t the XPath 1.0 compatibility mode.
+ */
+ virtual xpath1_0compatib_mode_t
+ getXPath1_0CompatibMode( ) const = 0;
+
+ /** \brief Set the construction mode.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @param aMode the construction mode.
+ * @return true if the mode was set, false otherwise.
+ */
+ virtual bool
+ setConstructionMode( construction_mode_t aMode ) = 0;
+
+ /** \brief Get the construction mode.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @return construction_mode_t the construction mode.
+ */
+ virtual construction_mode_t
+ getConstructionMode( ) const = 0;
+
+ /** \brief Set the ordering mode.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @param aMode the ordering mode.
+ * @return true if the mode was set, false otherwise.
+ */
+ virtual bool
+ setOrderingMode( ordering_mode_t aMode ) = 0;
+
+ /** \brief Get the ordering mode.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @return ordering_mode_t the ordering mode.
+ */
+ virtual ordering_mode_t
+ getOrderingMode( ) const = 0;
+
+ /** \brief Set the default order for the empty sequence.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @param aMode the default order for the empty sequence.
+ * @return true if the mode was set, false otherwise.
+ */
+ virtual bool
+ setDefaultOrderForEmptySequences( order_empty_mode_t aMode ) = 0;
+
+ /** \brief Get the default order for the empty sequence.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @return order_empty_mode_t the ordering mode.
+ */
+ virtual order_empty_mode_t
+ getDefaultOrderForEmptySequences( ) const = 0;
+
+ /** \brief Set the boundary space policy.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @param aMode the boundary space policy.
+ * @return true if the mode was set, false otherwise.
+ */
+ virtual bool
+ setBoundarySpacePolicy( boundary_space_mode_t aMode) = 0;
+
+ /** \brief Get the boundary space policy.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @return boundary_space_mode_t the boundary space policy.
+ */
+ virtual boundary_space_mode_t
+ getBoundarySpacePolicy( ) const = 0;
+
+ /** \brief Set the copy namespace mode.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @param aPreserve the preserve mode.
+ * @param aInherit the inherit mode.
+ * @return true if the mode was set, false otherwise.
+ */
+ virtual bool
+ setCopyNamespacesMode( preserve_mode_t aPreserve,
+ inherit_mode_t aInherit ) = 0;
+
+ /** \brief Get the copy namespace mode.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @return aPreserve the preserve mode.
+ * @return aInherit the inherit mode.
+ */
+ virtual void
+ getCopyNamespacesMode( preserve_mode_t& aPreserve,
+ inherit_mode_t& aInherit ) const = 0;
+
+ /** \brief Set the base URI.
+ * (see http://www.w3.org/TR/xquery/#static_context)
+ *
+ * @param aBaseURI the base URI as String.
+ * @return true if the base URI has been set, false otherwise.
+ */
+ virtual bool
+ setBaseURI( const String& aBaseURI ) = 0;
+
+ /** \brief Get the base URI.
+ *
+ * @return String the base URI.
+ */
+ virtual String
+ getBaseURI( ) const = 0;
+
+ /** \brief Get the revalidation mode.
+ *
+ * @return the revalidation mode.
+ */
+ virtual validation_mode_t
+ getRevalidationMode() const = 0;
+
+ /** \brief Set the revalidation mode.
+ *
+ * @param aMode the revalidation mode.
+ */
+ virtual void
+ setRevalidationMode(validation_mode_t aMode) = 0;
+
+ /** \brief Register a module providing access to external functions.
+ *
+ * Register a module that provides access to external functions.
+ * The caller keeps the ownership of the Module and the StatelessExternalFunction
+ * objects passed to this function.
+ *
+ * @param aModule the module object
+ * @return true if the module has been set, false otherwise.
+ */
+ virtual bool
+ registerModule(ExternalModule* aModule) = 0;
+
+ /**
+ * \brief Register a URI Mapper which will transform a given URI
+ * into several alternate potential URIs.
+ *
+ * QQQ doc
+ */
+ virtual void
+ registerURIMapper(URIMapper* aMapper) = 0;
+
+ /**
+ * \brief Register a URL Resolver which will transform a given
+ * URL into a Resource.
+ *
+ * QQQ doc
+ */
+ virtual void
+ registerURLResolver(URLResolver* aResolver) = 0;
+
+ /** \brief Set the type of a statically known document
+ */
+ virtual void
+ setDocumentType(const String& aDocUri, TypeIdentifier_t type) = 0;
+
+ /** \brief Get the type of a statically known document
+ */
+ virtual TypeIdentifier_t
+ getDocumentType(const String& aDocUri) const = 0;
+
+ /** \brief Set the type of a statically known collection
+ */
+ virtual void
+ setCollectionType(const String& aCollectionUri, TypeIdentifier_t type) = 0;
+
+ /** \brief Get the type of a statically known collection
+ */
+ virtual TypeIdentifier_t
+ getCollectionType(const String& aCollectionUri) const = 0;
+
+ /** \brief Check if a function with the given name and arity are registered in the context.
+ */
+ virtual bool
+ containsFunction(const String& aFnNameUri, const String& aFnNameLocal, int arity) const = 0;
+
+ virtual void
+ findFunctions(const Item& aQName, std::vector<Function_t>& aFunctions) const = 0;
+
+ virtual void
+ disableFunction(const Function_t& aFunction) = 0;
+
+ virtual void
+ disableFunction(const Item& aQName, int arity) = 0;
+
+ virtual void
+ getFunctionAnnotations(const Item& aQName, int arity, std::vector<Annotation_t>& aAnnotations) const = 0;
+
+ /** \brief Set the type of the context item.
+ */
+ virtual void
+ setContextItemStaticType(TypeIdentifier_t type) = 0;
+
+ /** \brief Fetch the type of the context item.
+ */
+ virtual TypeIdentifier_t
+ getContextItemStaticType() const = 0;
+
+ /** \brief Set the output stream that is used by the fn:trace function
+ *
+ * Sets the output stream that is used by the fn:trace function to the given output stream.
+ * The default stream is std::cerr.
+ *
+ */
+ virtual void
+ setTraceStream(std::ostream&) = 0;
+
+ /** \brief Resets the output stream that is used by the fn:trace function to std::cerr
+ */
+ virtual void
+ resetTraceStream() = 0;
+
+ /** \brief Get an option that was declared using the declare option syntax
+ *
+ * @param aQName The QName of the option to get.
+ * @param aOptionValue The value of the option if found.
+ * @return true if the option was found, false otherwise.
+ */
+ virtual bool
+ getOption( const Item& aQName, String& aOptionValue) const = 0;
+
+ /** \brief Declare an option (same as using declare option in XQuery)
+ *
+ * @param aQName The QName of the option to declare.
+ * @param aOptionValue The value of the option to declare.
+ */
+ virtual void
+ declareOption( const Item& aQName, const String& aOptionValue) = 0;
+
+ /**
+ * @brief Set the URI and library lookup paths (lists of filesystem
+ * directories) for this static context. Note that calling this method
+ * will override any values previously passed to \link setURIPath()
+ * and \link setLibPath().
+ * @deprecated Use \link setURIPath() and \link setLibPath().
+ *
+ * Convenience method which adds the listed directories to both the
+ * URI path and Library path for this static context.
+ */
+ virtual void
+ setModulePaths( const std::vector<String>& aModulePaths ) = 0;
+
+ /**
+ * @brief Return the union of the URI and library lookup paths (lists of
+ * filesystem directories) for this static context. @deprecated Use \link
+ * getURIPath() and \link getLibPath().
+ * @deprecated Use \link getURIPath() and \link getLibPath().
+ *
+ * Returns any values set by \link setLibPath() and/or \link setURIPath()
+ * on this static context.
+ */
+ virtual void
+ getModulePaths( std::vector<String>& aModulePaths ) const = 0;
+
+ /**
+ * @brief Return the union of the URI and library lookup paths (lists of
+ * filesystem directories) for this static context and all its parents.
+ * @deprecated Use \link getFullURIPath() and \link getFullLibPath().
+ */
+ virtual void
+ getFullModulePaths( std::vector<String>& aFullModulePaths ) const = 0;
+
+ /** \brief Resolves the given URI against the value of the base-uri
+ * property from the static context.
+ *
+ * @param aRelativeUri The relative URI to be resolved.
+ */
+ virtual String
+ resolve(const String& aRelativeUri) const = 0;
+
+ /** \brief Resolves the given relative URI against the absolute base URI.
+ *
+ * @param aRelativeUri The relative URI to be resolved.
+ * @param aBaseUri The absolute URI against which the resolving is performed.
+ */
+ virtual String
+ resolve(const String& aRelativeUri, const String& aBaseUri) const = 0;
+
+ /** \brief Validates this Item.
+ * Note: works only on document and element nodes, otherwise returns false.
+ *
+ * @param rootElement the root of the tree beeing validated
+ * @param validatedResult the result of the validation
+ * @param validationMode Validation mode: default value is validate_strict
+ * @return true if validation is correct, false if validation is disabled, throws errors if validation fails
+ * @throw ZorbaException if any validation error occured
+ */
+ virtual bool
+ validate(
+ const Item& rootElement,
+ Item& validatedResult,
+ validation_mode_t validationMode = validate_strict) const = 0;
+
+ /** \brief Validates this Item while loading the schema for targetNamespace
+ * Note: works only on document or element nodes, otherwise returns false.
+ *
+ * @param rootElement the root of the tree beeing validated
+ * @param validatedResult the result of the validation
+ * @param targetNamespace the expected namespace of root of the tree beeing validated ???
+ * @param validationMode Validation mode: default value is validate_strict
+ * @return true if validation is correct, false if validation is disabled, throws errors if validation fails
+ * @throw ZorbaException if any validation error occured
+ */
+ virtual bool
+ validate(
+ const Item& rootElement,
+ Item& validatedResult,
+ const String& targetNamespace,
+ validation_mode_t validationMode = validate_strict) const = 0;
+
+ /** \brief Validates stringValue as XML simple content, i.e. the text value of attributes or
+ * text only element content.
+ *
+ * @param stringValue the value to be validated
+ * @param typeQName
+ * @param resultList the result of the validation, a vector of atomic Items
+ * @return true if validation is correct, false if validation is disabled, throws errors if validation fails
+ * @throw ZorbaException if any validation error occured
+ */
+ virtual bool
+ validateSimpleContent(
+ const String& stringValue,
+ const Item& typeQName,
+ std::vector<Item>& resultList) const= 0;
+
+ /** \brief Invokes the XQuery function with the given name and
+ * the given parameters.
+ *
+ * Note that the function to be invoked needs to be declared in this static
+ * context. In order to declare a function in the static context, the
+ * loadProlog method of this class can be used.
+ *
+ * Also note that if the function to be invoked is an updating function,
+ * its resulting pending update list is implicitly applied by this function.
+ *
+ * @param aQName the name of the function to be invoked
+ * @param aArgs a vector of ItemSequences. One entry in the vector
+ * corresponds to one argument that is passed to the function.
+ *
+ * @return The result of the function that is invoked. If the function
+ * to be invoked is an updating function, the resulting item sequence
+ * is empty.
+ */
+ virtual ItemSequence_t
+ invoke(const Item& aQName, const std::vector<ItemSequence_t>& aArgs) const = 0;
+
+ /** \brief Returns a CollectionManager responsible for all collections
+ * which are statically declared in this static context.
+ *
+ * The collection manager provides a set of functions for managing
+ * collections and their contents.
+ *
+ * @return The collection manager responsible for managing
+ * collections of this context.
+ *
+ */
+ virtual StaticCollectionManager*
+ getStaticCollectionManager() const = 0;
+
+ /**
+ * @brief sets the audit event that will be populated during execution
+ *
+ * @param anEvent the audit event
+ */
+ virtual void
+ setAuditEvent(audit::Event* anEvent) = 0;
+
+ /**
+ * @brief gets the audit event that is populated during execution
+ *
+ * @return the audit event
+ */
+ virtual audit::Event*
+ getAuditEvent() const = 0;
+
+
+ /** \brief Returns the QName of all external variables within the
+ * static context
+ *
+ * @param aVarsIter iterator to store the results.
+ * @throw ZorbaException if an error occured.
+ */
+ virtual void
+ getExternalVariables(Iterator_t& aVarsIter) const = 0;
+
+ /**
+ * @brief Set the URI lookup path (list of filesystem directories) for this
+ * static context.
+ *
+ * Queries which resolve URIs (for instance, importing modules or schemas)
+ * will look in these directories.
+ */
+ virtual void
+ setURIPath(const std::vector<String>& aURIPath) = 0;
+
+ /**
+ * @brief Return the URI lookup path (list of filesystem directories) for
+ * this static context.
+ *
+ * Returns any values set by \link setURIPath() on this static context.
+ * To return the full URI lookup path for this static context and
+ * all its parents (usually most useful), call \link getFullURIPath().
+ */
+ virtual void
+ getURIPath(std::vector<String>& aURIPath) const = 0;
+
+ /**
+ * @brief Return the URI lookup path (list of filesystem directories) for
+ * this static context and all its parents.
+ */
+ virtual void
+ getFullURIPath(std::vector<String>& aURIPath) const = 0;
+
+ /**
+ * @brief Set the library lookup path (list of filesystem directories) for
+ * this static context.
+ *
+ * Queries which import modules that have external function
+ * implementations will look for the implementation of those functions
+ * (shared libraries) in these directories.
+ */
+ virtual void
+ setLibPath(const std::vector<String>& aLibPath) = 0;
+
+ /**
+ * @brief Return the URI lookup path (list of filesystem directories) for
+ * this static context.
+ *
+ * Returns any values set by \link setLibPath() on this static context.
+ * To return the full library lookup path for this static context and
+ * all its parents (usually most useful), call \link getFullLibPath().
+ */
+ virtual void
+ getLibPath(std::vector<String>& aLibPath) const = 0;
+
+ /**
+ * @brief Return the URI lookup path (list of filesystem directories) for
+ * this static context and all its parents.
+ */
+ virtual void
+ getFullLibPath(std::vector<String>& aLibPath) const = 0;
};
+
} /* namespace zorba */
#endif
/* vim:set et sw=2 ts=2: */
=== modified file 'include/zorba/stemmer.h'
--- include/zorba/stemmer.h 2011-08-31 19:27:14 +0000
+++ include/zorba/stemmer.h 2012-01-25 00:12:28 +0000
@@ -52,6 +52,23 @@
virtual void destroy() const = 0;
/**
+ * Various properties of this %Stemmer.
+ */
+ struct Properties {
+ /**
+ * The URI that uniquely identifies this %Stemmer.
+ */
+ char const* uri;
+ };
+
+ /**
+ * Gets the Properties of this %Stemmer.
+ *
+ * @param result The Properties to populate.
+ */
+ virtual void properties( Properties *result ) const = 0;
+
+ /**
* Stems the given word.
*
* @param word The word to stem.
=== modified file 'include/zorba/thesaurus.h'
--- include/zorba/thesaurus.h 2011-09-07 20:08:18 +0000
+++ include/zorba/thesaurus.h 2012-01-25 00:12:28 +0000
@@ -24,6 +24,7 @@
#include <zorba/internal/unique_ptr.h>
#include <zorba/internal/ztd.h>
#include <zorba/locale.h>
+#include <zorba/uri_resolvers.h>
#include <zorba/zorba_string.h>
namespace zorba {
@@ -31,9 +32,23 @@
///////////////////////////////////////////////////////////////////////////////
/**
- * A %Thesaurus is an abstract base class for thesaurus implementations.
- */
-class ZORBA_DLL_PUBLIC Thesaurus {
+ * Contains additional data for URIMappers and URLResolvers
+ * when mapping/resolving a Thesaurus URI.
+ */
+class ZORBA_DLL_PUBLIC ThesaurusEntityData : public EntityData {
+public:
+ /**
+ * Gets the language for which a thesaurus is being requested.
+ *
+ * @return said language.
+ */
+ virtual locale::iso639_1::type getLanguage() const = 0;
+};
+
+/**
+ * A %Thesaurus is-a Resource for thesaurus implementations.
+ */
+class ZORBA_DLL_PUBLIC Thesaurus : public Resource {
public:
typedef std::unique_ptr<Thesaurus,internal::ztd::destroy_delete<Thesaurus> >
ptr;
@@ -64,20 +79,20 @@
* @return Returns \c true only if there is a next synonym.
*/
virtual bool next( String *synonym ) = 0;
+
protected:
- virtual ~iterator() {}
+ virtual ~iterator() { }
};
/**
* Destroys this %Thesaurus.
* This function is called by Zorba when the %Thesaurus is no longer needed.
*
- * If your ThesaurusProvider dynamically allocates %Thesaurus objects, then
- * the implementation can simply be (and usually is) <code>delete
- * this</code>.
+ * If your URLResolver dynamically allocates %Thesaurus objects, then the
+ * implementation can simply be (and usually is) <code>delete this</code>.
*
- * If your ThesaurusProvider returns a pointer to a static %Thesaurus object,
- * then the implementation should do nothing.
+ * If your URLResolver returns a pointer to a static %Thesaurus object, then
+ * the implementation should do nothing.
*/
virtual void destroy() const = 0;
@@ -102,25 +117,6 @@
virtual ~Thesaurus();
};
-/**
- * A %ThesaurusProvider, given an language, provies a thesaurus for it.
- */
-class ZORBA_DLL_PUBLIC ThesaurusProvider {
-public:
- virtual ~ThesaurusProvider();
-
- /**
- * Gets a Thesaurus for the given language.
- *
- * @param uri The URI provided in the query for the thesaurus.
- * @param lang The language to get a Thesaurus for.
- * @return The relevant Thesaurus or \c NULL if no thesaurus for the given
- * language is available.
- */
- virtual Thesaurus::ptr
- getThesaurus( String const &uri, locale::iso639_1::type lang ) const = 0;
-};
-
///////////////////////////////////////////////////////////////////////////////
} // namespace zorba
=== modified file 'include/zorba/tokenizer.h'
--- include/zorba/tokenizer.h 2011-08-31 19:27:14 +0000
+++ include/zorba/tokenizer.h 2012-01-25 00:12:28 +0000
@@ -67,8 +67,6 @@
* A %Callback is called once per token.
* This is only internally by Zorba.
* You do not need to derive from this class.
- * The only thing you need to do is call the callback's \c operator() once
- * for each token you parse in \c tokenize().
*/
class Callback {
public:
@@ -77,19 +75,55 @@
virtual ~Callback();
/**
+ * This member-function is called whenever an item that is being tokenized
+ * is entered or exited.
+ *
+ * @param item The item being entered or exited.
+ * @param entering If \c true, the item is being entered; if \c false, the
+ * item is being exited.
+ */
+ virtual void item( Item const &item, bool entering );
+
+ /**
* This member-function is called once per token.
*
* @param utf8_s The UTF-8 token string. It is not null-terminated.
* @param utf8_len The number of bytes in the token string.
+ * @param lang The language of the token.
* @param token_no The token number. Token numbers start at 0.
* @param sent_no The sentence number. Sentence numbers start at 1.
* @param para_no The paragraph number. Paragraph numbers start at 1.
- * @param payload Optional user-defined data.
- */
- virtual void operator()( char const *utf8_s, size_type utf8_len,
- size_type token_no, size_type sent_no,
- size_type para_no, void *payload = 0 ) = 0;
- };
+ * @param item The Item this token is from, if any.
+ */
+ virtual void token( char const *utf8_s, size_type utf8_len,
+ locale::iso639_1::type lang,
+ size_type token_no, size_type sent_no,
+ size_type para_no, Item const *item = 0 ) = 0;
+ };
+
+ /////////////////////////////////////////////////////////////////////////////
+
+ /**
+ * Various properties of this %Tokenizer.
+ */
+ struct Properties {
+ /**
+ * If \c true, XML elements separate tokens.
+ */
+ bool elements_separate_tokens;
+
+ /**
+ * The URI that uniquely identifies this %Tokenizer.
+ */
+ char const* uri;
+ };
+
+ /**
+ * Gets the Properties of this %Tokenizer.
+ *
+ * @param result The Properties to populate.
+ */
+ virtual void properties( Properties *result ) const = 0;
/////////////////////////////////////////////////////////////////////////////
@@ -106,39 +140,6 @@
virtual void destroy() const = 0;
/**
- * Trace options for XML elements combined via bitwise-or.
- */
- enum ElementTraceOptions {
- trace_none = 0x0, ///< Trace no elements.
- trace_begin = 0x1, ///< Trace the beginning of elements.
- trace_end = 0x2 ///< Trace the ending of elements.
- };
-
- /**
- * Gets the trace options. If the value is \c trace_none, then the paragraph
- * number will be incremented upon entering an XML element; if the value is
- * anything other than \c trace_none, then the tokenizer assumes
- * responsibility for incrementing the paragraph number.
- *
- * @return Returns said options.
- */
- int trace_options() const {
- return trace_options_;
- }
-
- /**
- * This function is called whenever an XML element is entered during
- * tokenization. Note that this function is called only if \c
- * trace_options() returns non-zero.
- *
- * @param qname The element's QName.
- * @param trace_options The bitwise-or of the trace option(s) in effect for a
- * particular call.
- * @see trace_options()
- */
- virtual void element( Item const &qname, int trace_options );
-
- /**
* Gets this %Tokenizer's associated Numbers.
*
* @return Returns said Numbers.
@@ -153,6 +154,16 @@
Numbers const& numbers() const;
/**
+ * Tokenizes the given node.
+ *
+ * @param node The node to tokenize.
+ * @param lang The default language to use.
+ * @param callback The Callback to call once per token.
+ */
+ void tokenize_node( Item const &node, locale::iso639_1::type lang,
+ Callback &callback );
+
+ /**
* Tokenizes the given string.
*
* @param utf8_s The UTF-8 string to tokenize. It need not be
@@ -162,11 +173,11 @@
* @param wildcards If \c true, allows XQuery wildcard syntax characters to
* be part of tokens.
* @param callback The Callback to call once per token.
- * @param payload Optional user-defined data.
+ * @param item The Item this string is from, if any.
*/
- virtual void tokenize( char const *utf8_s, size_type utf8_len,
- locale::iso639_1::type lang, bool wildcards,
- Callback &callback, void *payload = 0 ) = 0;
+ virtual void tokenize_string( char const *utf8_s, size_type utf8_len,
+ locale::iso639_1::type lang, bool wildcards,
+ Callback &callback, Item const *item = 0 ) = 0;
/////////////////////////////////////////////////////////////////////////////
@@ -175,27 +186,70 @@
* Constructs a %Tokenizer.
*
* @param numbers the Numbers to use.
- * @param trace_options The bitwise-or of the available trace options, if
- * any.
*/
- Tokenizer( Numbers &numbers, int trace_options = trace_none );
+ Tokenizer( Numbers &numbers );
/**
* Destroys a %Tokenizer.
*/
virtual ~Tokenizer() = 0;
+ /**
+ * Given an element, finds its \c xml:lang attribute, if any, and gets its
+ * value.
+ *
+ * @param element The element to check.
+ * @param lang A pointer to where to put the found language, if any.
+ * @return Returns \c true only if an \c xml:lang attribute is found and the
+ * value is a known language.
+ */
+ bool find_lang_attribute( Item const &element, locale::iso639_1::type *lang );
+
+ /**
+ * This member-function is called whenever an item that is being tokenized is
+ * entered or exited.
+ *
+ * @param item The item being entered or exited.
+ * @param entering If \c true, the item is being entered; if \c false, the
+ * item is being exited.
+ */
+ virtual void item( Item const &item, bool entering );
+
+ /**
+ * Tokenizes the given node and all of its child nodes, if any. For each
+ * node, it is required that this function call the item() member function of
+ * both this %Tokenizer and of the Callback twice, once each for entrance and
+ * exit.
+ *
+ * @param node The node to tokenize.
+ * @param lang The default language to use.
+ * @param callback The Callback to call per token.
+ * @param tokenize_acp If \c true, additionally tokenize all attribute,
+ * comment, and processing-instruction nodes encountered;
+ * if \c false, skip them.
+ */
+ void tokenize_node_impl( Item const &node, locale::iso639_1::type lang,
+ Callback &callback, bool tokenize_acp );
+
private:
- int trace_options_;
- Numbers *no_;
+ Numbers *numbers_;
};
+inline Tokenizer::Tokenizer( Numbers &numbers ) : numbers_( &numbers ) {
+}
+
inline Tokenizer::Numbers& Tokenizer::numbers() {
- return *no_;
+ return *numbers_;
}
inline Tokenizer::Numbers const& Tokenizer::numbers() const {
- return *no_;
+ return *numbers_;
+}
+
+inline void Tokenizer::tokenize_node( Item const &item,
+ locale::iso639_1::type lang,
+ Callback &callback ) {
+ tokenize_node_impl( item, lang, callback, true );
}
///////////////////////////////////////////////////////////////////////////////
=== modified file 'include/zorba/uri_resolvers.h'
--- include/zorba/uri_resolvers.h 2011-08-17 15:48:35 +0000
+++ include/zorba/uri_resolvers.h 2012-01-25 00:12:28 +0000
@@ -25,6 +25,9 @@
#include <zorba/item.h>
#include <zorba/zorba_string.h>
#include <zorba/streams.h>
+#include <zorba/locale.h>
+#include <zorba/internal/unique_ptr.h>
+#include <zorba/internal/ztd.h>
/**
* @file uri_resolvers.h
@@ -47,7 +50,19 @@
class ZORBA_DLL_PUBLIC Resource
{
public:
+ typedef std::unique_ptr<Resource,internal::ztd::destroy_delete<Resource> > ptr;
+
virtual ~Resource() = 0;
+
+ /**
+ * @brief Destroy/clean up this Resource.
+ *
+ * Zorba will call this method when it no longer needs the Resource. It
+ * is the responsibility of subclasses to clean up appropriate when
+ * this method is called, including calling "delete this" if the Resource
+ * was allocated with "new".
+ */
+ virtual void destroy() const = 0;
};
/**
@@ -90,9 +105,8 @@
* and URLResolvers when mapping/resolving a URI.
*
* This base class specifies the kind of entity for which this URI is being
- * resolved - for instance, a schema URI or a module URI. In the future,
- * there may be kind-specific subclasses containing additional information;
- * as yet however there are none.
+ * resolved - for instance, a schema URI or a module URI. Subclasses of
+ * this class will provide additional data for specific kinds of entities.
*/
class ZORBA_DLL_PUBLIC EntityData
{
@@ -254,6 +268,7 @@
* Constructor. Specify the Entity Kind you wish to map. Optionally,
* specify whether this should be a CANDIDATE or COMPONENT mapper;
* default is CANDIDATE.
+ * QQQ COMPONENT is no longer used; delete?
*/
OneToOneURIMapper(EntityData::Kind aEntityKind,
URIMapper::Kind aMapperKind = URIMapper::CANDIDATE);
=== modified file 'include/zorba/xquery.h'
--- include/zorba/xquery.h 2011-07-25 17:40:50 +0000
+++ include/zorba/xquery.h 2012-01-25 00:12:28 +0000
@@ -304,7 +304,7 @@
*/
virtual void
printPlan(std::ostream& aStream, bool aDotFormat = false) const = 0;
-
+
/**
* \brief Check if this query is an updating query.
*
@@ -316,6 +316,17 @@
virtual bool
isUpdating() const = 0;
+ /**
+ * \brief Check if this query is a sequential query.
+ *
+ * @return true if the query is a sequential query, false otherwise.
+ * @throw SystemException if the query is not compiled or has been closed.
+ * @see close()
+ * @see compile(...)
+ */
+ virtual bool
+ isSequential() const = 0;
+
/** \brief Save the compiled execution plan.
*
* After compiling an XQuery program you can save the execution plan in some
@@ -524,6 +535,13 @@
virtual StaticCollectionManager*
getStaticCollectionManager() const = 0;
+ /** \brief Returns the QName of all external variables
+ *
+ * @param aVarsIter iterator to store the results.
+ * @throw ZorbaException if an error occured.
+ */
+ virtual void
+ getExternalVariables(Iterator_t& aVarsIter) const = 0;
/**
*
=== modified file 'include/zorba/zorba.h'
--- include/zorba/zorba.h 2011-06-17 03:47:29 +0000
+++ include/zorba/zorba.h 2012-01-25 00:12:28 +0000
@@ -33,6 +33,7 @@
#include <zorba/collection_manager.h>
#include <zorba/xquery.h>
#include <zorba/zorba_string.h>
+#include <zorba/iterator.h>
namespace zorba {
=== modified file 'modules/ExternalModules.conf'
--- modules/ExternalModules.conf 2011-10-11 22:26:10 +0000
+++ modules/ExternalModules.conf 2012-01-25 00:12:28 +0000
@@ -26,16 +26,17 @@
# "tag" is the VCS tag to check out (optional - defaults to HEAD;
# currently only works for bzr, since svn tags are just different URLS)
-data-cleaning bzr lp:zorba/data-cleaning-module zorba-2.0.3
-data-converters bzr lp:zorba/data-converters-module zorba-2.0.3
-data-formatting bzr lp:zorba/data-formatting-module zorba-2.0.3
-email bzr lp:zorba/email-module zorba-2.0.3
-excel bzr lp:zorba/excel-module zorba-2.0.3
-geo bzr lp:zorba/geo-module zorba-2.0.3
-http-client bzr lp:zorba/http-client-module zorba-2.0.3
-image bzr lp:zorba/image-module zorba-2.0.3
-languages bzr lp:zorba/languages-module zorba-2.0.3
-oauth bzr lp:zorba/oauth-module zorba-2.0.3
-process bzr lp:zorba/process-module zorba-2.0.3
-security bzr lp:zorba/security-module zorba-2.0.3
-system bzr lp:zorba/system-module zorba-2.0.3
+data-cleaning bzr lp:zorba/data-cleaning-module zorba-2.1
+data-converters bzr lp:zorba/data-converters-module zorba-2.1
+data-formatting bzr lp:zorba/data-formatting-module zorba-2.1
+email bzr lp:zorba/email-module zorba-2.1
+excel bzr lp:zorba/excel-module zorba-2.1
+geo bzr lp:zorba/geo-module zorba-2.1
+http-client bzr lp:zorba/http-client-module zorba-2.1
+image bzr lp:zorba/image-module zorba-2.1
+languages bzr lp:zorba/languages-module zorba-2.1
+oauth bzr lp:zorba/oauth-module zorba-2.1
+process bzr lp:zorba/process-module zorba-2.1
+security bzr lp:zorba/security-module zorba-2.1
+system bzr lp:zorba/system-module zorba-2.1
+xqxq bzr lp:zorba/xqxq-module zorba-2.1
=== modified file 'modules/com/zorba-xquery/www/modules/CMakeLists.txt'
--- modules/com/zorba-xquery/www/modules/CMakeLists.txt 2011-09-30 08:08:13 +0000
+++ modules/com/zorba-xquery/www/modules/CMakeLists.txt 2012-01-25 00:12:28 +0000
@@ -46,6 +46,8 @@
URI "http://www.zorba-xquery.com/modules/math")
DECLARE_ZORBA_MODULE(FILE node-reference.xq VERSION 2.0
URI "http://www.zorba-xquery.com/modules/node-reference")
+DECLARE_ZORBA_MODULE(FILE node-position.xq VERSION 2.0
+ URI "http://www.zorba-xquery.com/modules/node-position")
DECLARE_ZORBA_MODULE(FILE node.xq VERSION 2.0
URI "http://www.zorba-xquery.com/modules/node")
DECLARE_ZORBA_MODULE(FILE project_xqdoc.xq VERSION 2.0
@@ -56,13 +58,18 @@
URI "http://www.zorba-xquery.com/modules/reflection")
DECLARE_ZORBA_MODULE(FILE schema.xq VERSION 2.0
URI "http://www.zorba-xquery.com/modules/schema")
-DECLARE_ZORBA_MODULE(FILE string.xq VERSION 2.0
+DECLARE_ZORBA_MODULE(FILE string.xq VERSION 2.1
URI "http://www.zorba-xquery.com/modules/string")
DECLARE_ZORBA_MODULE(FILE xml.xq VERSION 2.0
URI "http://www.zorba-xquery.com/modules/xml")
DECLARE_ZORBA_MODULE(FILE xqdoc.xq VERSION 2.0
URI "http://www.zorba-xquery.com/modules/xqdoc")
+IF(NOT ZORBA_NO_FULL_TEXT)
+ DECLARE_ZORBA_MODULE(FILE full-text.xq VERSION 2.0
+ URI "http://www.zorba-xquery.com/modules/full-text")
+ENDIF(NOT ZORBA_NO_FULL_TEXT)
+
# Subdirectories
DECLARE_ZORBA_MODULE(FILE converters/base64.xq VERSION 2.0
URI "http://www.zorba-xquery.com/modules/converters/base64")
@@ -98,6 +105,13 @@
DECLARE_ZORBA_MODULE(FILE store/static/integrity_constraints/dml.xq VERSION 2.0
URI "http://www.zorba-xquery.com/modules/store/static/integrity_constraints/dml")
+# debugger client DBGP message handler module
+IF (ZORBA_WITH_DEBUGGER)
+ DECLARE_ZORBA_MODULE (FILE debugger/dbgp-message-handler.xq VERSION 1.0
+ URI "http://www.zorba-xquery.com/modules/debugger/dbgp-message-handler")
+ENDIF (ZORBA_WITH_DEBUGGER)
+
+
# error and warning modules
DECLARE_ZORBA_MODULE (FILE pregenerated/errors.xq
URI "http://www.zorba-xquery.com/errors"
=== added directory 'modules/com/zorba-xquery/www/modules/debugger'
=== added file 'modules/com/zorba-xquery/www/modules/debugger/dbgp-message-handler.xq'
--- modules/com/zorba-xquery/www/modules/debugger/dbgp-message-handler.xq 1970-01-01 00:00:00 +0000
+++ modules/com/zorba-xquery/www/modules/debugger/dbgp-message-handler.xq 2012-01-25 00:12:28 +0000
@@ -0,0 +1,277 @@
+xquery version "3.0";
+
+(:
+ : Copyright 2006-2009 The FLWOR Foundation.
+ :
+ : Licensed under the Apache License, Version 2.0 (the "License");
+ : you may not use this file except in compliance with the License.
+ : You may obtain a copy of the License at
+ :
+ : http://www.apache.org/licenses/LICENSE-2.0
+ :
+ : Unless required by applicable law or agreed to in writing, software
+ : distributed under the License is distributed on an "AS IS" BASIS,
+ : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ : See the License for the specific language governing permissions and
+ : limitations under the License.
+:)
+module namespace dmh = "http://www.zorba-xquery.com/modules/debugger/dbgp-message-handler";
+
+import module namespace base64 = "http://www.zorba-xquery.com/modules/converters/base64";
+
+declare namespace ver = "http://www.zorba-xquery.com/options/versioning";
+declare option ver:module-version "1.0";
+
+
+declare variable $dmh:endl as xs:string := "
+";
+
+(:~
+ : Set this variale to true if you want to have mode debug information when
+ : an error occurs.
+ :)
+declare variable $dmh:debug as xs:boolean := fn:false();
+
+
+declare %private function dmh:status($resp as element(response))
+{
+ switch ($resp/@status)
+ case "starting"
+ case "stopping"
+ return "idle"
+ case "break"
+ return
+ let $status := $resp/@status
+ let $whyInfo :=
+ if ($resp/@reason ne "ok") then
+ fn:concat(" (", $resp/@reason, ")")
+ else
+ ""
+ let $whereInfo :=
+ if ($resp/text()[1] ne "") then
+ fn:concat(" in ", $resp/text()[1])
+ else
+ ""
+ return
+ fn:concat($status, $whyInfo, $whereInfo)
+ default
+ return $resp/@status
+};
+
+declare %private function dmh:source($resp as element(response))
+{
+ $resp/text()
+};
+
+declare %private function dmh:breakpoint-set($resp as element(response))
+{
+ fn:concat("set breakpoint with id ", data($resp/@id), " and state ", data($resp/@state))
+};
+
+declare %private function dmh:breakpoint-get($resp as element(response))
+{
+ let $b := $resp/breakpoint
+ return
+ fn:concat(
+ "Breakpoint ", $b/@id, $dmh:endl,
+ " type: ", $b/@type, $dmh:endl,
+ " file: ", $b/@filename, $dmh:endl,
+ " line: ", $b/@lineno, $dmh:endl,
+ " state: ", $b/@state
+ )
+};
+
+declare %private function dmh:breakpoint-list($resp as element(response))
+{
+ fn:string-join(
+ let $bs := $resp/breakpoint
+ return
+ if (fn:exists($bs)) then
+ fn:concat(
+ "--------------------------------------", $dmh:endl,
+ "| ID | State | Line | File", $dmh:endl,
+ "|--------|-----------|--------|-------", $dmh:endl,
+ fn:string-join(
+ for $b in $bs
+ return
+ fn:concat(
+ "| ", dmh:lpottl($b/@id, 6, " "), " ",
+ "| ", if ($b/@state eq "enabled") then "enabled " else "disabled ", " ",
+ "| ", dmh:lpottl($b/@lineno, 6, " "), " ",
+ "| ", $b/@filename, $dmh:endl),
+ ""
+ ),
+ "--------------------------------------", $dmh:endl
+ )
+ else
+ "No breakpoints set"
+ )
+};
+
+(:~
+ : left-pad-or-trim-to-length
+ :)
+declare %private function dmh:lpottl($value as xs:string, $length as xs:integer, $padChar as xs:string)
+ as xs:string
+{
+ let $padChar := fn:substring($padChar, 1, 1)
+ let $len := fn:string-length($value)
+ return
+ if ($len < $length) then
+ let $pad :=
+ fn:string-join(
+ for $i in 1 to $length - $len
+ return $padChar,
+ ""
+ )
+ return
+ fn:concat($pad, $value)
+ else
+ fn:substring($value, $len - $length + 1)
+};
+
+declare %private function dmh:breakpoint-remove($resp as element(response))
+{
+ "Breakpoint removed"
+};
+
+declare %private function dmh:stack-depth($resp as element(response))
+{
+ fn:concat("depth: ", $resp/@depth)
+};
+
+declare %private function dmh:stack-get($resp as element(response))
+{
+ fn:string-join(
+ for $s in $resp/stack
+ return
+ fn:concat("#", $s/@level, " in ", $s/@where, " at ", $s/@filename, ":", $s/@lineno),
+ $dmh:endl
+ )
+};
+
+
+declare %private function dmh:context-names($resp as element(response))
+{
+ fn:string-join(
+ for $c in $resp/context
+ return
+ fn:concat("context ", $c/@id, ": ", $c/@name),
+ $dmh:endl
+ )
+};
+
+declare %private function dmh:context-get($resp as element(response))
+{
+ fn:string-join(
+ for $p in $resp/property
+ return
+ fn:concat($p/@fullname, " ", $p/@type,
+ if ($p/text() ne "") then
+ fn:concat(": ", base64:decode($p/text()))
+ else
+ ""
+ ),
+ $dmh:endl
+ )
+};
+
+declare %private function dmh:eval($resp as element(response))
+{
+ if ($resp/@success eq "1") then
+ dmh:context-get($resp)
+ else
+ dmh:report-error("An unknown error occured while evaluating expression.")
+};
+
+declare %private function dmh:report-error(
+ $message as xs:string)
+{
+ dmh:report-error($message, ())
+};
+
+declare %private function dmh:report-error(
+ $message as xs:string,
+ $debugMessage as xs:string*)
+{
+ fn:string-join(
+ (
+ (: the error message :)
+ fn:concat("Error: ", $message),
+
+ (: the debug info :)
+ if ($dmh:debug and fn:string-length($debugMessage) gt 0) then
+ $debugMessage
+ else
+ ()
+ ),
+ $dmh:endl
+ )
+};
+
+declare %private function dmh:process-response($resp as element(response))
+{
+ switch ($resp/@command)
+ case "eval" return dmh:eval($resp)
+ case "context_get" return dmh:context-get($resp)
+ case "context_names" return dmh:context-names($resp)
+ case "stack_get" return dmh:stack-get($resp)
+ case "stack_depth" return dmh:stack-depth($resp)
+ case "breakpoint_remove" return dmh:breakpoint-remove($resp)
+ case "breakpoint_list" return dmh:breakpoint-list($resp)
+ case "breakpoint_get" return dmh:breakpoint-get($resp)
+ case "breakpoint_set" return dmh:breakpoint-set($resp)
+ case "source" return dmh:source($resp)
+
+ (: continuation command only need to display/process the status :)
+ case "run"
+ case "step_into"
+ case "step_out"
+ case "step_over"
+ case "stop"
+ case "status"
+ return dmh:status($resp)
+
+ default
+ return dmh:report-error(fn:concat("Command not implemented: ", $resp/@command))
+};
+
+declare function dmh:process-init($init as element(init))
+{
+ fn:string-join(
+ ("Established connection with", $init/@language, "client", $init/@appid),
+ " "
+ )
+};
+
+declare function dmh:process($message as element())
+{
+ let $nodeName := fn:local-name($message)
+ let $id := fn:data($message/@transaction_id)
+ return
+ if ($nodeName eq "response") then
+ (: no transaction_id :)
+ if (fn:count($id) eq 0 or $id eq "") then
+ (0, dmh:report-error("Invalid response", "Missing or empty response transaction ID."))
+ (: wrong transaction_id :)
+ else if (xs:string(fn:number($id)) eq "NaN") then
+ (0, dmh:report-error("Invalid response", "Invalid value for response transaction ID."))
+ (: no or empty command :)
+ else if (fn:count($message/@command) eq 0 or $message/@command eq "") then
+ ($id, dmh:report-error("Invalid response", "Missing or empty response command attribute."))
+ (: error response :)
+ else if (fn:exists($message/error)) then
+ ($id, dmh:report-error(fn:data($message/error/message), fn:concat("Error code: ", fn:data($message/error/@code))))
+ else
+ ($id, dmh:process-response($message))
+ else if ($nodeName eq "init") then
+ (0, dmh:process-init($message))
+ else
+ (
+ if (fn:count($id) eq 0 or $id eq "" or xs:string(fn:number($id)) eq "NaN") then
+ 0
+ else
+ $id,
+ dmh:report-error(fn:concat("Unknown message node: ", $nodeName))
+ )
+};
=== added file 'modules/com/zorba-xquery/www/modules/full-text.xq'
--- modules/com/zorba-xquery/www/modules/full-text.xq 1970-01-01 00:00:00 +0000
+++ modules/com/zorba-xquery/www/modules/full-text.xq 2012-01-25 00:12:28 +0000
@@ -0,0 +1,207 @@
+xquery version "3.0";
+
+(:
+ : Copyright 2006-2011 The FLWOR Foundation.
+ :
+ : Licensed under the Apache License, Version 2.0 (the "License");
+ : you may not use this file except in compliance with the License.
+ : You may obtain a copy of the License at
+ :
+ : http://www.apache.org/licenses/LICENSE-2.0
+ :
+ : Unless required by applicable law or agreed to in writing, software
+ : distributed under the License is distributed on an "AS IS" BASIS,
+ : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ : See the License for the specific language governing permissions and
+ : limitations under the License.
+ :)
+
+(:~
+ : This module provides an XQuery API to full-text functions.
+ :)
+module namespace ft = "http://www.zorba-xquery.com/modules/full-text";
+declare namespace ver = "http://www.zorba-xquery.com/options/versioning";
+declare option ver:module-version "2.0";
+
+(:~
+ : Gets the host's default language.
+ :
+ : @return said language.
+ :)
+declare function ft:host-lang()
+ as xs:language external;
+
+(:~
+ : Checks whether the given word is a stop-word.
+ :
+ : @param $word The word to check. The word's language is assumed to be the
+ : host machine's current language.
+ : @return <code>true</code> only if the <code>$word</code> is a stop-word.
+ :)
+declare function ft:is-stop-word( $word as xs:string )
+ as xs:boolean external;
+
+(:~
+ : Checks whether the given word is a stop-word.
+ :
+ : @param $word The word to check.
+ : @param $lang The language of <code>$word</code>.
+ : @return <code>true</code> only if the <code>$word</code> is a stop-word.
+ :)
+declare function ft:is-stop-word( $word as xs:string, $lang as xs:language )
+ as xs:boolean external;
+
+(:~
+ : Stems the given word.
+ :
+ : @param $word The word to stem. The word's language is assumed to be the
+ : host machine's current language.
+ : @return the stem of <code>$word</code>.
+ :)
+declare function ft:stem( $word as xs:string )
+ as xs:string external;
+
+(:~
+ : Stems the given word.
+ :
+ : @param $word The word to stem.
+ : @param $lang The language of <code>$word</code>.
+ : @return the stem of <code>$word</code>.
+ :)
+declare function ft:stem( $word as xs:string, $lang as xs:language )
+ as xs:string external;
+
+(:~
+ : Strips all diacritical marks from all characters.
+ :
+ : @param $string The string to strip diacritical marks from.
+ : @return <code>$string</code> with diacritical marks stripped.
+ :)
+declare function ft:strip-diacritics( $string as xs:string )
+ as xs:string external;
+
+(:~
+ : Looks-up the given phrase in the default thesaurus.
+ :
+ : @param $phrase The phrase to look up. The phrase's language is assumed to
+ : be in the host machine's current language.
+ : @return the related phrases.
+ :)
+declare function ft:thesaurus-lookup( $phrase as xs:string )
+ as xs:string+ external;
+
+(:~
+ : Looks-up the given phrase in a thesaurus.
+ :
+ : @param $uri The URI specifying the thesaurus to use.
+ : @param $phrase The phrase to look up. The phrase's language is assumed to
+ : be in the host machine's current language.
+ : @return the related phrases.
+ :)
+declare function ft:thesaurus-lookup( $uri as xs:string, $phrase as xs:string )
+ as xs:string+ external;
+
+(:~
+ : Looks-up the given phrase in a thesaurus.
+ :
+ : @param $uri The URI specifying the thesaurus to use.
+ : @param $phrase The phrase to look up.
+ : @param $lang The language of <code>$phrase</code>.
+ : @return the related phrases.
+ :)
+declare function ft:thesaurus-lookup( $uri as xs:string, $phrase as xs:string,
+ $lang as xs:language )
+ as xs:string+ external;
+
+(:~
+ : Looks-up the given phrase in a thesaurus.
+ :
+ : @param $uri The URI specifying the thesaurus to use.
+ : @param $phrase The phrase to look up.
+ : @param $lang The language of <code>$phrase</code>.
+ : @param $relationship The relationship the results are to have to
+ : <code>$phrase</code>.
+ : @return the related phrases.
+ :)
+declare function ft:thesaurus-lookup( $uri as xs:string, $phrase as xs:string,
+ $lang as xs:language,
+ $relationship as xs:string )
+ as xs:string+ external;
+
+(:~
+ : Looks-up the given phrase in a thesaurus.
+ :
+ : @param $uri The URI specifying the thesaurus to use.
+ : @param $phrase The phrase to look up.
+ : @param $lang The language of <code>$phrase</code>.
+ : @param $relationship The relationship the results are to have to
+ : <code>$phrase</code>.
+ : @param $level-least The minimum number of levels within the thesaurus to be
+ : travers$ed.
+ : @param $level-most The maximum number of levels within the thesaurus to be
+ : traversed.
+ : @return the related phrases.
+ :)
+declare function ft:thesaurus-lookup( $uri as xs:string, $phrase as xs:string,
+ $lang as xs:language,
+ $relationship as xs:string,
+ $level-least as xs:integer,
+ $level-most as xs:integer )
+ as xs:string+ external;
+
+(:~
+ : Tokenizes the given document.
+ :
+ : @param $doc The XML document to tokenize. The document's default language
+ : is assumed to be the host machine's current language.
+ : @return a (possibly empty) sequence of tokens.
+ :)
+declare function ft:tokenize( $doc as node() )
+ as node()* external;
+
+(:~
+ : Tokenizes the given document.
+ :
+ : @param $doc The document to tokenize.
+ : @param $lang The default language of <code>$doc</code>.
+ : @return a (possibly empty) sequence of tokens.
+ :)
+declare function ft:tokenize( $doc as node(), $lang as xs:language )
+ as node()* external;
+
+(:~
+ : Tokenizes the given string.
+ :
+ : @param $string The string to tokenize. The string's default language is
+ : assumed to be the host machine's current language.
+ : @return a (possibly empty) sequence of tokens.
+ :)
+declare function ft:tokenize-string( $string as xs:string )
+ as xs:string*
+{
+ () (: TODO :)
+};
+
+(:~
+ : Tokenizes the given string.
+ :
+ : @param $string The string to tokenize.
+ : @param $lang The default language of <code>$string</code>.
+ : @return a (possibly empty) sequence of tokens.
+ :)
+declare function ft:tokenize-string( $string as xs:string,
+ $lang as xs:language )
+ as xs:string*
+{
+ () (: TODO :)
+};
+
+(:~
+ : Gets properties of the tokenizer.
+ :
+ : @return said properties.
+ :)
+declare function ft:tokenizer-properties()
+ as node() external;
+
+(: vim:set et sw=2 ts=2: :)
=== modified file 'modules/com/zorba-xquery/www/modules/http-client.xq.src/http_response_handler.cpp'
--- modules/com/zorba-xquery/www/modules/http-client.xq.src/http_response_handler.cpp 2011-07-29 08:12:36 +0000
+++ modules/com/zorba-xquery/www/modules/http-client.xq.src/http_response_handler.cpp 2012-01-25 00:12:28 +0000
@@ -126,7 +126,7 @@
String lLocalName = "response";
Item lNodeName = theFactory->createQName(theNamespace, lLocalName);
theResponse = theFactory->createElementNode(lNullParent, lNodeName,
- theUntypedQName, true, false, std::vector<std::pair<String, String> >());
+ theUntypedQName, true, false, NsBindings());
theFactory->createAttributeNode(theResponse,
theFactory->createQName("", "status"), lNullType,
theFactory->createInteger(aStatus));
@@ -165,7 +165,7 @@
Item lNullType;
Item lElem = theFactory->createElementNode(lParent,
theFactory->createQName(theNamespace, "header"), theUntypedQName, true,
- true, std::vector<std::pair<String, String> >());
+ true, NsBindings());
theFactory->createAttributeNode(lElem, theFactory->createQName("", "name"),
lNullType, theFactory->createString(aName));
theFactory->createAttributeNode(lElem, theFactory->createQName("", "value"),
@@ -180,7 +180,7 @@
Item lNullType;
Item lElem = theFactory->createElementNode(lParent,
theFactory->createQName(theNamespace, "body"), theUntypedQName, true,
- true, std::vector<std::pair<String, String> >());
+ true, NsBindings());
theFactory->createAttributeNode(lElem,
theFactory->createQName("", "media-type"),
lNullType, theFactory->createString(aContentType));
@@ -201,7 +201,7 @@
Item lNullType;
Item lElem = theFactory->createElementNode(theResponse,
theFactory->createQName(theNamespace, "body"), theUntypedQName, true,
- true, std::vector<std::pair<String, String> >());
+ true, NsBindings());
theFactory->createAttributeNode(lElem,
theFactory->createQName("", "content-type"),
lNullType, theFactory->createString(aContentType));
=== added file 'modules/com/zorba-xquery/www/modules/node-position.xq'
--- modules/com/zorba-xquery/www/modules/node-position.xq 1970-01-01 00:00:00 +0000
+++ modules/com/zorba-xquery/www/modules/node-position.xq 2012-01-25 00:12:28 +0000
@@ -0,0 +1,524 @@
+xquery version "1.0";
+(:
+ : Copyright 2006-2011 The FLWOR Foundation.
+ :
+ : Licensed under the Apache License, Version 2.0 (the "License");
+ : you may not use this file except in compliance with the License.
+ : You may obtain a copy of the License at
+ :
+ : http://www.apache.org/licenses/LICENSE-2.0
+ :
+ : Unless required by applicable law or agreed to in writing, software
+ : distributed under the License is distributed on an "AS IS" BASIS,
+ : WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ : See the License for the specific language governing permissions and
+ : limitations under the License.
+ :)
+
+(:~
+ : This module provides a function (np:node-position) that, given a node,
+ : returns positional information about the node in the form of an xs:anyURI
+ : item. The module also defines functions that use such positional information
+ : to determine: (1) positional relationships between two nodes (e.g. if one
+ : is the ancestor of another) and (2) positional properties of a single node
+ : (e.g. its level in the tree).
+ :
+ : Within this module, the term "node position" will be used to refer to an
+ : xs:anyURI item that is returned by the np:node-position function.
+ :
+ : @author Federico Cavalieri, Markos Zaharioudakis
+ :
+ : @project XDM/node
+ :)
+module namespace np = "http://www.zorba-xquery.com/modules/node-position";
+
+declare namespace ver = "http://www.zorba-xquery.com/options/versioning";
+declare option ver:module-version "2.0";
+
+(:~
+ : Return a URI item containing positional information for a given node.
+ :
+ : <p>Within a snapshot, each has a different positional URI. However,
+ : different nodes in different snapshots might have the same URI.</p>
+ :
+ : @param $arg the node for which the positional information URI
+ : should be computed
+ :
+ : @return the opaque positional information URI of the node.
+ :)
+declare function np:node-position(
+ $arg as node()
+) as xs:anyURI external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : an ancestor of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is an ancestor of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential descendant node position
+ : @param $n-pos2 the potential ancestor node position
+ :
+ : @return true if the node position $n-pos2 is an ancestor of the node position
+ : $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:ancestor-of(
+ $pos1 as xs:anyURI,
+ $pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : a descendant of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is a descendant of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential ancestor node position
+ : @param $n-pos2 the potential descendant node position
+ :
+ : @return true if the node position $n-pos2 is a descendant of the node
+ : position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:descendant-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument belongs
+ : to the subtree rooted at the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node belongs to the subtree rooted at the
+ : first. Otherwise, the result of the function does not imply anything about
+ : the positional relationship of the two nodes.
+ :
+ : This function differs from np:descendant-of in the way it treats attribute
+ : nodes. np:descendant-of follows the XQuery/XPath specification for the
+ : descendant axis, and as a result, it does not consider attributes as
+ : descendants of any nodes; it will always return false if $n-pos2 was
+ : obtained from an attribute node.In contrast, np:in-subtree-of will return
+ : true if $n-pos2 was obtained from an attribute node that appeared in the
+ : subtree of the node that $n-pos1 was obtained from.
+ :
+ : @param $n-pos1 the potential subtree root node position
+ : @param $n-pos2 the potential node in the subtree node position
+ :
+ : @return true if the node position $n-pos2 belongs to the subtree rooted at
+ : the node position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:in-subtree-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : the parent of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is the parent of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential child node position
+ : @param $n-pos2 the potential parent node position
+ :
+ : @return true if the node position $n-pos2 is the parent of the node position
+ : $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:parent-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : a child of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is a child of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential parent node position
+ : @param $n-pos2 the potential child node position
+ :
+ : @return true if the node position $n-pos2 is a child of the node position
+ : $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:child-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : an attribute of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is an attribute of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential parent node position
+ : @param $n-pos2 the potential attribute node position
+ :
+ : @return true if the node position $n-pos2 is an attribute of the node
+ : position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:attribute-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : a following-sibling of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is a following-sibling of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential preceding-sibling node position
+ : @param $n-pos2 the potential following-sibling node position
+ :
+ : @return true if the node position $n-pos2 is a following-sibling of the node
+ : position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:following-sibling-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : a preceding-sibling of the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is a preceding-sibling of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential following-sibling node position
+ : @param $n-pos2 the potential preceding-sibling node position
+ :
+ : @return true if the node position $n-pos2 is a preceding-sibling of the node
+ : position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:preceding-sibling-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether two node positions are siblings.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is a sibling of the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 a node position
+ : @param $n-pos2 a node position
+ :
+ : @return true if the two node positions $n-pos1 and $n-pos2 are siblings;
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:sibling-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : following the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is following the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential preceding node position
+ : @param $n-pos2 the potential following node position
+ :
+ : @return true if node positions $n-pos1 and $n-pos2 belong to the same XML
+ : tree and $n-pos2 is following the node position $n-pos1; false
+ : otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node position
+ : computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:following-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : following in document order the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is following in document order the
+ : first. Otherwise, the result of the function does not imply anything about
+ : the positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential preceding node position
+ : @param $n-pos2 the potential following node position
+ :
+ : @return true if the node position $n-pos2 is following in document order the
+ : node position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:following-in-document-order-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : preceding the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is preceding the first.
+ : Otherwise, the result of the function does not imply anything about the
+ : positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential following node position
+ : @param $n-pos2 the potential preceding node position
+ :
+ : @return true if node positions $n-pos1 and $n-pos2 belong to the same XML
+ : tree and $n-pos2 is preceding the node position $n-pos1; false
+ : otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:preceding-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether the node position given as second argument is
+ : preceding in document order the node position given as first argument.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the second node is preceding in document order the
+ : first. Otherwise, the result of the function does not imply anything about
+ : the positional relationship of the two nodes.
+ :
+ : @param $n-pos1 the potential following node position
+ : @param $n-pos2 the potential preceding node position
+ :
+ : @return true if the node position $n-pos2 is preceding in document order the
+ : node position $n-pos1; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:preceding-in-document-order-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Computes the level of a node position in its tree.
+ :
+ : Note: The root node of a tree is at level one.
+ :
+ : The result of the function applies to the corresponding node as well,
+ : that is, within the snapshot in which the position was computed, the node
+ : level is the returned one.
+ : The result of the function does not imply anything about the
+ : node level in other snapshots.
+ :
+ : @param $n-pos the node position of the node whose level should be
+ : determined.
+ :
+ : @return the level in the tree of the node position $n-pos as xs:integer.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:level(
+ $n-pos as xs:anyURI) as xs:integer external;
+
+(:~
+ : Determines whether a node position corresponds to an attribute node.
+ :
+ : @param $n-pos the potential attribute node position
+ :
+ : @return true if the node position $n-pos corresponds to an attribute;
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-attribute(
+ $n-pos1 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether a node position corresponds to a comment node.
+ :
+ : @param $n-pos the potential comment node position
+ :
+ : @return true if the node position $n-pos corresponds to an comment;
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-comment(
+ $n-pos1 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether a node position corresponds to a document node.
+ :
+ : @param $n-pos the potential document node position
+ :
+ : @return true if the node position $n-pos corresponds to a document;
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-document(
+ $n-pos1 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether a node position corresponds to an element node.
+ :
+ : @param $n-pos the potential element node position
+ :
+ : @return true if the node position $n-pos corresponds to an element;
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-element(
+ $n-pos1 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether a node position corresponds to an processing-instruction
+ : node.
+ :
+ : @param $n-pos the potential processing-instruction node position
+ :
+ : @return true if the node position $n-pos corresponds to a processing
+ : instruction; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-processing-instruction(
+ $n-pos1 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether a node position corresponds to a text node.
+ :
+ : @param $n-pos the potential text node position
+ :
+ : @return true if the node position $n-pos corresponds to a text;
+ : false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:is-text(
+ $n-pos1 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether two node positions belong to the same tree.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the two nodes belong to the same tree.
+ : Otherwise, the result of the function does not imply anything about
+ : the positional relationship of the two nodes.
+ :
+ : @param $n-pos1 a node position
+ : @param $n-pos2 a node position
+ :
+ : @return true if the two nodes whose node positions are $n-pos1
+ : and $n-pos2 belong to the same tree.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:in-same-tree-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether a node position belongs to a collection.
+ :
+ : @param $n-pos the node position
+ :
+ : @return true if the node position $n-pos
+ : belongs to a collection; false otherwise.
+ :
+ : @error zerr:ZAPI0028 if the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:in-collection(
+ $n-pos as xs:anyURI) as xs:boolean external;
+
+(:~
+ : Determines whether two node positions belong to the same collection.
+ :
+ : If the two positions were obtained within the same snapshot S, then the
+ : result of the function applies to the corresponding nodes as well, that
+ : is, within snapshot S, the two nodes belong to the same collection.
+ : Otherwise, the result of the function does not imply anything about
+ : the positional relationship of the two nodes.
+ :
+ : @param $n-pos1 a node position
+ : @param $n-pos2 a node position
+ :
+ : @return true if the two nodes whose node positions are $n-pos1
+ : and $n-pos2 belong to the same collection.
+ :
+ : @error zerr:ZAPI0028 if one of the given URI is not a valid node
+ : position computed by the <tt>np:node-position</tt> function.
+ :)
+declare function np:in-same-collection-of(
+ $n-pos1 as xs:anyURI,
+ $n-pos2 as xs:anyURI) as xs:boolean external;
=== modified file 'modules/com/zorba-xquery/www/modules/pregenerated/errors.xq'
--- modules/com/zorba-xquery/www/modules/pregenerated/errors.xq 2011-10-19 15:28:51 +0000
+++ modules/com/zorba-xquery/www/modules/pregenerated/errors.xq 2012-01-25 00:12:28 +0000
@@ -217,6 +217,10 @@
(:~
:)
+declare variable $zerr:ZXQD0006 as xs:QName := fn:QName($zerr:NS, "zerr:ZXQD0006");
+
+(:~
+:)
declare variable $zerr:ZAPI0002 as xs:QName := fn:QName($zerr:NS, "zerr:ZAPI0002");
(:~
@@ -249,6 +253,10 @@
(:~
:)
+declare variable $zerr:ZAPI0011 as xs:QName := fn:QName($zerr:NS, "zerr:ZAPI0011");
+
+(:~
+:)
declare variable $zerr:ZAPI0014 as xs:QName := fn:QName($zerr:NS, "zerr:ZAPI0014");
(:~
@@ -497,6 +505,10 @@
(:~
:)
+declare variable $zerr:ZDDY0035 as xs:QName := fn:QName($zerr:NS, "zerr:ZDDY0035");
+
+(:~
+:)
declare variable $zerr:ZDDY0031 as xs:QName := fn:QName($zerr:NS, "zerr:ZDDY0031");
(:~
@@ -549,6 +561,10 @@
(:~
:)
+declare variable $zerr:ZDST0025 as xs:QName := fn:QName($zerr:NS, "zerr:ZDST0025");
+
+(:~
+:)
declare variable $zerr:ZDST0026 as xs:QName := fn:QName($zerr:NS, "zerr:ZDST0026");
(:~
@@ -664,14 +680,6 @@
(:~
:)
-declare variable $zerr:ZSTR0005 as xs:QName := fn:QName($zerr:NS, "zerr:ZSTR0005");
-
-(:~
-:)
-declare variable $zerr:ZSTR0006 as xs:QName := fn:QName($zerr:NS, "zerr:ZSTR0006");
-
-(:~
-:)
declare variable $zerr:ZSTR0007 as xs:QName := fn:QName($zerr:NS, "zerr:ZSTR0007");
(:~
=== modified file 'modules/com/zorba-xquery/www/modules/pregenerated/warnings.xq'
--- modules/com/zorba-xquery/www/modules/pregenerated/warnings.xq 2011-10-19 15:28:51 +0000
+++ modules/com/zorba-xquery/www/modules/pregenerated/warnings.xq 2012-01-25 00:12:28 +0000
@@ -53,4 +53,23 @@
(:~
:)
-declare variable $zwarn:ZWST0004 as xs:QName := fn:QName($zwarn:NS, "zwarn:ZWST0004");
\ No newline at end of file
+declare variable $zwarn:ZWST0004 as xs:QName := fn:QName($zwarn:NS, "zwarn:ZWST0004");
+
+(:~
+ :
+ : This warning is raised if the user explicitly enables caching
+ : of function results (using the %ann:cache annotation) but the function
+ : is updating or its parameter and return types are not subtypes of
+ : xs:anyAtomicType.
+ :
+:)
+declare variable $zwarn:ZWST0005 as xs:QName := fn:QName($zwarn:NS, "zwarn:ZWST0005");
+
+(:~
+ :
+ : This warning is raised if the user explicitly enables caching
+ : of function results (using the %ann:cache annotation) and the function
+ : is annotated as sequential or nondeterministic.
+ :
+:)
+declare variable $zwarn:ZWST0006 as xs:QName := fn:QName($zwarn:NS, "zwarn:ZWST0006");
\ No newline at end of file
=== modified file 'modules/com/zorba-xquery/www/modules/store/static/indexes/dml.xq'
--- modules/com/zorba-xquery/www/modules/store/static/indexes/dml.xq 2011-08-26 23:36:24 +0000
+++ modules/com/zorba-xquery/www/modules/store/static/indexes/dml.xq 2012-01-25 00:12:28 +0000
@@ -22,7 +22,7 @@
:
: <p>This module is part of <a href="../../html/xqddf.html">Zorba's XQuery Data
: Definition Facility</a>. All the indexes managed by this module
- : have to be pre-declared in the prolog of a module. Please refer to the
+ : have to be pre-declared in the prolog of a library module. Please refer to the
: <a href="../../html/data_lifecycle.html">general documentation</a>
: for more information and examples.</p>
:
@@ -35,7 +35,7 @@
: @see http://www.zorba-xquery.com/modules/store/static/integrity_constraints/dml
: @see <a href="www.zorba-xquery.com_errors.html">http://www.zorba-xquery.com/errors</a>
:
- : @author Nicolae Brinza, Matthias Brantner, David Graf, Till Westmann, Markos Zaharioudakis
+ : @author Zorba Team
:
: @project store/indexes/static
:
@@ -46,29 +46,39 @@
declare namespace ann = "http://www.zorba-xquery.com/annotations";
declare namespace ver = "http://www.zorba-xquery.com/options/versioning";
+
declare option ver:module-version "2.0";
(:~
- : The probe function retrieves the domain nodes associated with a particular
- : search condition, which is presented as a single key tuple. This function
- : is variadic and accepts a variable number of key arguments.
- :
- : The first argument is the QName identifying the index to probe. The remaining
- : arguments specify the search condition, which is given as a number of
- : (optional) atomic items comprising a key tuple. The number of key tuples
- : given must be equal to the number of keys declared for the index.
+ : <p>The probe-index-point-value function retrieves from an index the domain
+ : nodes associated by value equality with a given <strong>search tuple</strong>.
+ : The search tuple consists of a number of <strong>search keys</strong>, where
+ : each search key is either an atomic item or the empty sequence. The number
+ : of search keys given must be equal to the number of keys declared for the
+ : index. Since the number of keys differs from one index to another, this
+ : function is variadic.</p>
+ :
+ : <p>The result of the function is either an error or the set of domain nodes for
+ : which the following xquery expression returns true:</p>
+ :
+ : <pre>
+ : $key1 eq $node/keyExpr1 and ... and $keyM eq $node/keyExprM
+ : </pre>
+ : where keyExpr<sub>i</sub> is the expression specified in the i-th keyspec
+ : of the index.
:
: @param $name The QName of the index to probe
- : @param $key_i any number of key used to probe the index (i.e. the search condition).
- :
- : @return If the index contains an entry with the given key tuple,
- : the associated domain nodes are
- : returned. Otherwise, the empty sequence is returned.
+ : @param $key_i the search keys used to probe the index with. The i-th search
+ : key corresponds to the i-th key expression in the index declaration.
+ : @return The set of domain nodes that satisfy the search condition.
:
: @error zerr:ZDDY0021 if the index with name $name is not declared.
: @error zerr:ZDDY0023 if the index with name $name does not exist.
- : @error zerr:ZDDY0025 if the number of keys passed as arguments
- : does not match the number of keys declared for the index.
+ : @error zerr:ZDDY0025 if the number of search keys passed as arguments is not
+ : the same as the number of keys declared for the index.
+ : @error err:XPTY0004 if a non-empty seach key is given, whose type does not match
+ : the sequence type specified in the corresponding keyspec.
+ :
:)
declare %ann:variadic function idml:probe-index-point-value(
$name as xs:QName,
@@ -76,55 +86,171 @@
(:~
- : The probe function retrieves the domain nodes associated with a particular
- : search condition, which is presented as a range of key tuples.
- : This function accept a variable number of arguments.
- :
- : To describe the semantics of this function, we start by defining the i-th
- : key column of an index as the set of key items produced by evaluating the
- : i-th keyspec of the index for every domain node. Then, the search condition
- : of a range probe can be defined as a number of rangespecs, where a
- : rangespec describes a constraint on the values of a key column. The first
- : rangespec applies to the first key column, the second rangespec to the
- : second key column, etc. The number of rangespecs must be less or equal to
- : the number of keyspecs found in the declaration of the given index.
- : Each rangespec consists of six values (i.e. rangeLowerBound_i,
- : rangeUpperBound_i, rangeHaveLowerBound_i, rangeHaveUpperBound_i,
- : rangeLowerBoundIncluded_i, rangeUpperBoundIncluded_i). Because the
- : function is declared as variadic, several rangespecs can be passed
- : as arguments to the function.
+ : <p>The probe-index-point-general function retrieves from an index the domain
+ : nodes associated by general equality with a given <strong>search sequence
+ : </strong>. The search sequence consists of an arbitrary number of <strong>
+ : search keys</strong>, where each search key is an atomic item. The function
+ : is supported by general indexes only. Its result is either an error or the
+ : set of domain nodes for which the following xquery expression returns true:</p>
+ : <pre>
+ : $keys = $node/keyExpr
+ : </pre>
+ : where keyExpr is the expression specified in the keyspec of the index (remember
+ : that for general indexes, there can be only one keyspec).
+ :
+ : @param $name The QName of the index to probe.
+ : @param $key The search sequence.
+ : @return The set of domain nodes that satisfy the search condition.
+ :
+ : @error zerr:ZDDY0021 if the index with name $name is not declared.
+ : @error zerr:ZDDY0023 if the index with name $name does not exist.
+ : @error zerr:ZDDY0029 if the index is not general.
+ : @error err:XPTY0004 if the search sequence contains a search key, whose
+ : type does not match the sequence type specified in the keyspec of
+ : the index.
+ :)
+declare function idml:probe-index-point-general(
+ $name as xs:QName,
+ $key as xs:anyAtomicType*) as node()* external;
+
+
+(:~
+ : <p>The probe-index-range-value function retrieves the domain nodes associated
+ : by value order-comparison (operators le, lt, ge, gt) with a given <strong>search
+ : box</strong>. The search box is specified as a number M of <strong>rangespecs
+ : </strong>, where each rangespec consists of six values. The number M must be
+ : greater than 0 and less than or equal to the number N of keyspecs found in the
+ : index declaration. If M is less than N, then the "missing" rangespecs are
+ : assumed to have the following value: [(), (), false, false, false, false].
+ : As a result, we can assume that M is equal to N (Remember that for general
+ : indexes, there can be only one IndexKeySpec, and as a result, for general
+ : indexes, M = N = 1). Since the number of keys differs from one index to
+ : another, this function is variadic.</p>
+ :
+ : <p>The i<sup>th</sup> rangespec corresponds to the i<sup>th</sup> keyspec, and
+ : specifies a search condition on the key values that are produced by evaluating
+ : that keyspec for every domain node. Specifically, we define the i<sup>th</sup>
+ : <strong>rangespec result</strong> as the set of domain nodes for which the
+ : following xquery expression returns true:</p>
+ :
+ :<pre>
+ : if ($haveLowerBound-i and $haveUpperBound-i) then
+ : $lowerBound-i lop $node/keyExpr-i and $node/keyExpr-i uop $upperBound-i
+ : else if ($haveLowerBound-i) then
+ : $lowerBound-i lop $node/keyExpr-i
+ : else if ($haveUpperBound-i) then
+ : $node/keyExpr-i uop $upperBound-i
+ : else
+ : fn:true()
+ :</pre>
+ :
+ : <p>where keyExpr-i is the expression specified by the i<sup>th</sup> keyspec
+ : of the index, lop is either the le or the lt operator depending on whether
+ : $lowerBoundsIncluded-i is true or false, and uop is either the le or the
+ : lt operator depending on whether $upperBoundsIncluded-i is true or false.</p>
+ :
+ : <p>The result of the probe-index-range-value function is either an error,
+ : or the intersection of all the rangespec results.</p>
:
: @param $name The QName of the index to probe
- : @param $rangeLowerBound1 The lower bound in a range of key values.
- : @param $rangeUpperBound1 The upper bound in a range of key values.
- : @param $rangeHaveLowerBound If false, then there is no lower bound, or
- : equivalently, the lower bound is -INFINITY. Otherwise, the lower
- : bound is the one given by the rangeLowerBound value.
- : @param $rangeHaveUpperBound If false, then there is no upper bound, or
- : equivalently, the upper bound is +INFINITY. Otherwise, the upper
- : bound is the one given by the rangeUpperBound value.
- : @param $rangeLowerBoundIncluded If false, then the range is open from below,
- : i.e., the rangeLowerBound value is not considered part of the
- : range. Otherwise, the range is closed from below, i.e., the
- : rangeLowerBound value is part of the range.
- : @param $rangeUpperBoundIncluded If false, then the range is open from above,
- : i.e., the rangeUpperBound value is not considered part of the
- : range. Otherwise, the range is closed from above, i.e., the
- : rangeUpperBound value is part of the range.
- : @return The sequence of domain nodes matching this range probe.
+ : @param $lowerBound-i The lower bound in a range of key values.
+ : @param $upperBound-i The upper bound in a range of key values.
+ : @param $haveLowerBound-i If false, then there is no lower bound, or
+ : equivalently, the lower bound is -INFINITY. Otherwise, the lower
+ : bound is the one given by the lowerBound-i value.
+ : @param $haveUpperBound-i If false, then there is no upper bound, or
+ : equivalently, the upper bound is +INFINITY. Otherwise, the upper
+ : bound is the one given by the upperBound-i value.
+ : @param $lowerBoundIncluded-i If false, then the range is open from below,
+ : i.e., the lowerBound-i value is not considered part of the
+ : range. Otherwise, the range is closed from below, i.e., the
+ : lowerBound-i value is part of the range.
+ : @param $upperBoundIncluded-i If false, then the range is open from above,
+ : i.e., the upperBound-i value is not considered part of the
+ : range. Otherwise, the range is closed from above, i.e., the
+ : upperBound-i value is part of the range.
+ : @return The set of domain nodes that satisfy the search condition.
:
: @error zerr:ZDDY0021 if the index with name $name is not declared.
: @error zerr:ZDDY0023 if the index with name $name does not exist.
: @error zerr:ZDDY0025 if the number of rangespecs passed as arguments
- : does not match the number of keys declared for the index.
- :)
-declare %ann:variadic function idml:probe-index-range-value($name as xs:QName,
- $rangeLowerBound1 as xs:anyAtomicType?,
- $rangeUpperBound1 as xs:anyAtomicType?,
- $rangeHaveLowerBound1 as xs:boolean,
- $rangeHaveupperBound1 as xs:boolean,
- $rangeLowerBoundIncluded1 as xs:boolean,
- $rangeupperBoundIncluded1 as xs:boolean) as node()* external;
+ : is zero or greater than the number of keys declared for the index.
+ : @error zerr:ZDDY0026 if the index is not a range index.
+ : @error err:XPTY0004 if $haveLowerBound-i is true and $lowerBound-i is an
+ : atomic item whose type does not match the sequence type specified
+ : by the i<sup>th</sup> keyspec, or $haveUpperBound-i is true and
+ : $upperBound-i is an atomic item whose type does not match the
+ : sequence type specified by the i<sup>th</sup> keyspec.
+ : @error zerr:ZDDY0034 if (a) the index is general (in which case there is
+ : only one rangespac), (b) the index is untyped, (c) there is both a
+ : lower and an upper bound, and (d) if T1 and T2 are the types of the
+ : lower and upper bound, neither T1 is a subtype of T2 nor T2 is a
+ : subtype of T1.
+ :)
+declare %ann:variadic function idml:probe-index-range-value(
+ $name as xs:QName,
+ $lowerBound-i as xs:anyAtomicType?,
+ $upperBound-i as xs:anyAtomicType?,
+ $haveLowerBound-i as xs:boolean,
+ $haveUpperBound-i as xs:boolean,
+ $lowerBoundIncluded-i as xs:boolean,
+ $upperBoundIncluded-i as xs:boolean) as node()* external;
+
+
+(:~
+ : <p>The probe-index-range-general function retrieves the domain nodes associated
+ : by general order-comparison (operators <=, <, >=, >) with one or two
+ : <strong>search sequences</strong>. Each search sequence consists of an
+ : arbitrary number of <strong>search keys</strong>, where each search key is
+ : an atomic item. This method is supported by general range indexes only. Its
+ : result is either an error or the set of domain nodes for which the following
+ : xquery expression returns true:</p>
+ :
+ : <pre>
+ : if ($haveLowerBound and $haveUpperBound) then
+ : $lowerBoundKeys lop $node/keyExpr and $node/keyExpr uop $upperBoundKeys
+ : else if ($haveLowerBound) then
+ : $lowerBoundKeys lop $node/keyExpr
+ : else if ($haveUpperBound) then
+ : $node/keyExpr uop $upperBoundKeys
+ : else
+ : fn:true()
+ : </pre>
+ :
+ : <p>where keyExpr is the expression specified in the keyspec of the index,
+ : lop is either the <= or the < operator depending on whether
+ : $lowerBoundsIncluded is true or false, and uop is either the <= or the
+ : < operator depending on whether $upperBoundsIncluded is true or false</p>.
+ :
+ : @param $name The QName of the index to probe.
+ : @param $lowerBound The lower bound search sequence.
+ : @param $upperBound The upper bound search sequence.
+ : @param $haveLowerBound Whether a lower bound search sequence exists or not.
+ : @param $haveUpperBound Whether an upper bound search sequence exists or not.
+ : @param $lowerBoundIncluded Whether to use the <= or the < operator when
+ : comparing a search key from $lowerBound with an index key.
+ : @param $upperBoundIncluded Whether to use the <= or the < operator when
+ : comparing an index key with a search key from $upperBound.
+ : @return The set of domain nodes that satisfy the search condition
+ :
+ : @error zerr:ZDDY0021 if the index with name $name is not declared.
+ : @error zerr:ZDDY0023 if the index with name $name does not exist.
+ : @error zerr:ZDDY0030 if the index is not a general range index.
+ : @error err:XPTY0004 if $haveLowerBound is true and $lowerBoundKeys constains
+ : an atomic item whose type does not match the sequence type specified by the
+ : index keyspec, or $haveUpperBound is true and $upperBoundKeys contains an
+ : atomic item whose type does not match the sequence type specified by the
+ : index keyspec.
+ :)
+declare function idml:probe-index-range-general(
+ $name as xs:QName,
+ $lowerBound as xs:anyAtomicType*,
+ $upperBound as xs:anyAtomicType*,
+ $haveLowerBound as xs:boolean,
+ $haveUpperBound as xs:boolean,
+ $lowerBoundIncluded as xs:boolean,
+ $upperBoundIncluded as xs:boolean) as node()* external;
+
(:~
: The refresh-index function is an updating function which updates
@@ -136,6 +262,7 @@
: @return The result of the function is an empty XDM instance and a
: pending update list which, when applied, refreshes the contents
: of the index.that consists of a
+ :
: @error zerr:ZDDY0021 if the index with name $name is not declared.
: @error zerr:ZDDY0023 if the index with name $name does not exist.
:)
=== modified file 'modules/com/zorba-xquery/www/modules/string.xq'
--- modules/com/zorba-xquery/www/modules/string.xq 2011-08-03 15:12:40 +0000
+++ modules/com/zorba-xquery/www/modules/string.xq 2012-01-25 00:12:28 +0000
@@ -25,7 +25,7 @@
:)
module namespace string = "http://www.zorba-xquery.com/modules/string";
declare namespace ver = "http://www.zorba-xquery.com/options/versioning";
-declare option ver:module-version "2.0";
+declare option ver:module-version "2.1";
(:~
: This function materializes a streamable string.
@@ -63,3 +63,23 @@
:
:)
declare function string:is-streamable($s as xs:string) as xs:boolean external;
+
+(:~
+ : Returns a sequence of strings constructed by splitting the input wherever the given
+ : separator is found.
+ :
+ : The function is different from fn:tokenize. It doesn't allow
+ : the separator to be a regular expression. This restriction allows for more
+ : performant implementation. Specifically, the function processes
+ : streamable strings as input in a streamable way which is particularly useful
+ : to tokenize huge strings (e.g. if returned by the file module's read-text
+ : function).
+ :
+ : @param $s the input string to split
+ : @param $separator the separator used for splitting the input string $s
+ :
+ : @return a sequence of strings constructed by splitting the input
+ :)
+declare function string:split(
+ $s as xs:string,
+ $separator as xs:string) as xs:string* external;
=== modified file 'modules/com/zorba-xquery/www/modules/xml.xq' (properties changed: +x to -x)
=== modified file 'modules/com/zorba-xquery/www/modules/xqdoc2xhtml/index.xq'
--- modules/com/zorba-xquery/www/modules/xqdoc2xhtml/index.xq 2011-10-19 05:09:31 +0000
+++ modules/com/zorba-xquery/www/modules/xqdoc2xhtml/index.xq 2012-01-25 00:12:28 +0000
@@ -957,22 +957,22 @@
{if(contains($type, "updating")) then
<a href="{$xquSpec}"
title="updating"
- target="_blank"><img src="{concat($imagesPath, "Updating.gif")}" /></a>
+ target="_blank"><img src="{concat($imagesPath, "Updating.gif")}" alt="Updating"/></a>
else ()}
{if(contains($type, "sequential")) then
<a href="{$xqsSpec}"
title="sequential"
- target="_blank"><img src="{concat($imagesPath, "Sequential.gif")}" /></a>
+ target="_blank"><img src="{concat($imagesPath, "Sequential.gif")}" alt="Sequential"/></a>
else ()}
{if(contains($type, "nondeterministic ")) then
<a href="{$ZorbaOptAndAnn}"
title="%ann:nondeterministic"
- target="_blank"><img src="{concat($imagesPath, "Nondeterministic.gif")}" /></a>
+ target="_blank"><img src="{concat($imagesPath, "Nondeterministic.gif")}" alt="Nondeterministic"/></a>
else ()}
{if(contains($type, "variadic")) then
<a title="A function annotated with the http://www.zorba-xquery.com/annotations:variadic annotation is a function of indefinite arity, i.e. one that accepts a variable number of arguments."
href="{$ZorbaOptAndAnn}"
- target="_blank"><img src="{concat($imagesPath, "Variadic.gif")}" /></a>
+ target="_blank"><img src="{concat($imagesPath, "Variadic.gif")}" alt="Variadic"/></a>
else ()}
{if(contains($type, "streamable")) then
<a href="{$ZorbaOptAndAnn}" title="A function annotated with the http://www.zorba-xquery.com/annotations:streamable annotation is
@@ -983,10 +983,10 @@
However, the disadvantage is that a streamable string can only be consumed exactly once.
If a streamable string is consumed more than once, an error is raised.
In order to enable multiple consumers of a streamable string, the string:materialize function can be used
- to materialize the entire contents in an (regular) xs:string item." target="_blank"><img src="{concat($imagesPath, "Streamable.gif")}" /></a>
+ to materialize the entire contents in an (regular) xs:string item." target="_blank"><img src="{concat($imagesPath, "Streamable.gif")}" alt="Streamable"/></a>
else ()}
{if(contains($type, "external")) then
- <a href="{$xqExternal}" title="external" target="_blank"><img src="{concat($imagesPath, "External.gif")}" /></a>
+ <a href="{$xqExternal}" title="external" target="_blank"><img src="{concat($imagesPath, "External.gif")}" alt="External"/></a>
else ()}
</span>
};
@@ -1121,6 +1121,13 @@
else
(<div class="subsubsection">XQuery version and encoding for this module:</div>,
<p class="annotationText">xquery version "{$module/xqdoc:comment/xqdoc:custom[@tag='XQuery version']/text()}" encoding "{$module/xqdoc:comment/xqdoc:custom[@tag='encoding']/text()}";</p>)
+ ),
+ let $modVersion := xqdoc2html:get-module-version($moduleUri)
+ return
+ if($modVersion = "") then ()
+ else
+ (<div class="subsubsection">Zorba version for this module:</div>,
+ <p>The latest version of this module is <strong>{$modVersion}</strong>. For more information about module versioning in Zorba please check out <a href="../../html/modules_using.html#mod_versioning" target="_blank">this</a> resource.</p>
)
};
@@ -1154,7 +1161,7 @@
: @return the XHTML for the module annotations.
:)
declare %private function xqdoc2html:annotations-module($comment) {
- let $annotations := $comment/xqdoc:*[not((local-name(.) = ("description", "param", "return", "error", "deprecated", "see", "library", "project", "custom")))]
+ let $annotations := $comment/xqdoc:*[not((local-name(.) = ("description", "param", "return", "error", "deprecated", "see", "project", "custom")))]
return
for $annotation in $annotations
let $annName := local-name($annotation)
@@ -1195,7 +1202,7 @@
declare %private function xqdoc2html:module-dependencies(
$xqdoc) {
if (fn:count($xqdoc/xqdoc:imports/xqdoc:import) > 0 or
- fn:count($xqdoc/xqdoc:module/xqdoc:comment/xqdoc:*[(local-name(.) = ("library"))]) > 0) then
+ fn:count($xqdoc/xqdoc:module/xqdoc:comment/xqdoc:custom[@tag="library"]) > 0) then
(<div class="section"><span id="module_dependencies">Module Dependencies</span></div>,
xqdoc2html:imports($xqdoc))
else
@@ -1238,10 +1245,10 @@
}
</ul></p>
else (),
- if (fn:count($xqdoc/xqdoc:module/xqdoc:comment/xqdoc:*[(local-name(.) = ("library"))]) > 0) then
+ if (fn:count($xqdoc/xqdoc:module/xqdoc:comment/xqdoc:custom[@tag="library"]) > 0) then
<p>External C++ library dependencies:<ul>
{
- for $library in $xqdoc/xqdoc:module/xqdoc:comment/xqdoc:*[(local-name(.) = ("library"))]
+ for $library in $xqdoc/xqdoc:module/xqdoc:comment/xqdoc:custom[@tag="library"]
return
<li>{$library/node()}</li>
}
@@ -1374,9 +1381,9 @@
<td>
<tt>{
if ($isDeprecated) then
- <span class="functName"><del><a href="#{$name}-{$param-number}" title="{normalize-space($description)}">{$name}</a></del></span>
+ <span class="functName"><del><a href="#{$name}-{$param-number}" title="{$shortDescription}">{$name}</a></del></span>
else
- <span class="functName"><a href="#{$name}-{$param-number}" title="{normalize-space($description)}">{$name}</a></span>
+ <span class="functName"><a href="#{$name}-{$param-number}" title="{$shortDescription}">{$name}</a></span>
}{xqdoc2html:split-function-signature($paramsAndReturn)}<br /><span class="padding">{$shortDescription}</span>
</tt>
</td>
@@ -1531,7 +1538,7 @@
if (exists($params)) then
(<div class="subsubsection">Parameters:</div>,
<ul>
- {for $param in $params return <li>{data($param)}</li>}
+ {for $param in $params return <li>{$param/node()}</li>}
</ul>)
else ()
};
=== modified file 'src/annotations/annotations.cpp'
--- src/annotations/annotations.cpp 2011-08-11 17:19:25 +0000
+++ src/annotations/annotations.cpp 2012-01-25 00:12:28 +0000
@@ -15,21 +15,17 @@
*/
#include "stdafx.h"
-#include <cmath>
-
#include "annotations/annotations.h"
-#include "system/globalenv.h"
#include "store/api/item.h"
#include "store/api/item_factory.h"
-#include "context/static_context.h"
-#include "context/static_context_consts.h"
#include "compiler/expression/expr.h"
#include "zorbaserialization/serialization_engine.h"
#include "diagnostics/assert.h"
+#include "diagnostics/util_macros.h"
#include "system/globalenv.h"
@@ -38,90 +34,283 @@
SERIALIZABLE_CLASS_VERSIONS(AnnotationInternal)
END_SERIALIZABLE_CLASS_VERSIONS(AnnotationInternal)
-SERIALIZABLE_CLASS_VERSIONS(AnnotationLiteral)
-END_SERIALIZABLE_CLASS_VERSIONS(AnnotationLiteral)
-
SERIALIZABLE_CLASS_VERSIONS(AnnotationList)
END_SERIALIZABLE_CLASS_VERSIONS(AnnotationList);
-/*******************************************************************************
-
-********************************************************************************/
-AnnotationInternal::AnnotationInternal(const store::Item_t& aExpandedQName)
+std::vector<store::Item_t>
+AnnotationInternal::theAnnotId2NameMap;
+
+ItemHandleHashMap<AnnotationInternal::AnnotationId>
+AnnotationInternal::theAnnotName2IdMap(0, NULL, 64, false);
+
+std::vector<AnnotationInternal::RuleBitSet>
+AnnotationInternal::theRuleSet;
+
+
+/*******************************************************************************
+ Static method, called from GlobalEnvironment::init()
+********************************************************************************/
+void AnnotationInternal::createBuiltIn()
+{
+ store::Item_t qname;
+ AnnotationId id;
+
+ theAnnotId2NameMap.resize(zann_end);
+
+ //
+ // W3C annotations
+ //
+ GENV_ITEMFACTORY->createQName(qname, static_context::W3C_FN_NS, "fn", "public");
+ id = fn_public;
+ theAnnotId2NameMap[id] = qname;
+ theAnnotName2IdMap.insert(qname, id);
+
+ GENV_ITEMFACTORY->createQName(qname, static_context::W3C_FN_NS, "fn", "private");
+ id = fn_private;
+ theAnnotId2NameMap[id] = qname;
+ theAnnotName2IdMap.insert(qname, id);
+
+#define ZANN(a, b) \
+ GENV_ITEMFACTORY->createQName(qname, ZORBA_ANNOTATIONS_NS, "", #a); \
+ id = zann_##b; \
+ theAnnotId2NameMap[id] = qname; \
+ theAnnotName2IdMap.insert(qname, id);
+
+
+ //
+ // Zorba annotations - deterministic/nondeterministic
+ //
+ ZANN(deterministic, deterministic);
+ ZANN(nondeterministic, nondeterministic);
+
+ //
+ // Zorba annotations - xquery scripting
+ //
+ ZANN(assignable, assignable);
+ ZANN(nonassignable, nonassignable);
+
+ ZANN(sequential, sequential);
+ ZANN(nonsequential, nonsequential);
+
+ //
+ // Zorba annotations - optimizer
+ //
+ ZANN(propagates-input-nodes, propagates_input_nodes);
+ ZANN(must-copy-input-nodes, must_copy_input_nodes);
+
+ //
+ // Zorba annotations - misc
+ //
+ ZANN(variadic, variadic);
+
+ ZANN(streamable, streamable);
+
+ ZANN(cache, cache);
+ ZANN(no-cache, nocache);
+
+ //
+ // Zorba annotations - xqddf
+ //
+ ZANN(unique, unique);
+ ZANN(nonunique, nonunique);
+
+ ZANN(value-equality, value_equality);
+ ZANN(general-equality, general_equality);
+ ZANN(value-range, value_range);
+ ZANN(general-range, general_range);
+
+ ZANN(automatic, automatic);
+ ZANN(manual, manual);
+
+ ZANN(mutable, mutable);
+ ZANN(queue, queue);
+ ZANN(append-only, append_only);
+ ZANN(const, const);
+
+ ZANN(ordered, ordered);
+ ZANN(unordered, unordered);
+
+ ZANN(read-only-nodes, read_only_nodes);
+ ZANN(mutable-nodes, mutable_nodes);
+
+#undef ZANN
+
+ // create a set of rules to detect conflicts between annotations
+#define ZANN(a) \
+ ( 1 << static_cast<uint64_t>(AnnotationInternal::a) )
+
+ theRuleSet.push_back(
+ ZANN(zann_unique) |
+ ZANN(zann_nonunique));
+
+ theRuleSet.push_back(
+ ZANN(zann_value_equality) |
+ ZANN(zann_general_equality) |
+ ZANN(zann_value_range) |
+ ZANN(zann_general_range));
+
+ theRuleSet.push_back(
+ ZANN(zann_automatic) |
+ ZANN(zann_manual));
+
+ theRuleSet.push_back(
+ ZANN(zann_mutable) |
+ ZANN(zann_queue) |
+ ZANN(zann_append_only) |
+ ZANN(zann_const));
+
+ theRuleSet.push_back(
+ ZANN(zann_ordered) |
+ ZANN(zann_unordered));
+
+ theRuleSet.push_back(
+ ZANN(zann_assignable) |
+ ZANN(zann_nonassignable));
+
+ theRuleSet.push_back(
+ ZANN(zann_deterministic) |
+ ZANN(zann_nondeterministic));
+
+ theRuleSet.push_back(
+ ZANN(zann_sequential) |
+ ZANN(zann_nonsequential));
+
+ theRuleSet.push_back(
+ ZANN(zann_cache) |
+ ZANN(zann_nocache));
+
+ theRuleSet.push_back(
+ ZANN(fn_private) |
+ ZANN(fn_public));
+
+ theRuleSet.push_back(
+ ZANN(zann_unordered) |
+ ZANN(zann_queue));
+
+ theRuleSet.push_back(
+ ZANN(zann_unordered) |
+ ZANN(zann_append_only));
+
+ theRuleSet.push_back(
+ ZANN(zann_queue) |
+ ZANN(zann_append_only));
+
+ theRuleSet.push_back(
+ ZANN(zann_read_only_nodes) |
+ ZANN(zann_mutable_nodes));
+#undef ZANN
+}
+
+
+/*******************************************************************************
+ Static method, called from GlobalEnvironment::destroy()
+********************************************************************************/
+void AnnotationInternal::destroyBuiltIn()
+{
+ theAnnotId2NameMap.clear();
+ theAnnotName2IdMap.clear();
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+AnnotationInternal::AnnotationId AnnotationInternal::lookup(
+ const store::Item_t& qname)
+{
+ ItemHandleHashMap<AnnotationId>::iterator ite = theAnnotName2IdMap.find(qname);
+
+ if (ite == theAnnotName2IdMap.end())
+ return zann_end;
+
+ return (*ite).second;
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+store::Item* AnnotationInternal::lookup(AnnotationInternal::AnnotationId id)
+{
+ assert(id < zann_end);
+ assert(id < theAnnotId2NameMap.size());
+
+ return theAnnotId2NameMap[id].getp();
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+AnnotationInternal::AnnotationInternal(const store::Item_t& qname)
:
- theQName(aExpandedQName)
+ theId(zann_end),
+ theQName(qname)
{
+ ItemHandleHashMap<AnnotationId>::iterator ite = theAnnotName2IdMap.find(qname);
+ if (ite != theAnnotName2IdMap.end())
+ theId = (*ite).second;
}
+/*******************************************************************************
+
+********************************************************************************/
AnnotationInternal::AnnotationInternal(
- const store::Item_t& aExpandedQName,
- const std::vector<AnnotationLiteral_t>& aLiteralList)
+ const store::Item_t& qname,
+ std::vector<store::Item_t>& literals)
:
- theQName(aExpandedQName),
- theLiteralList(aLiteralList)
+ theId(zann_end),
+ theQName(qname)
{
+ theLiterals.swap(literals);
+
+ ItemHandleHashMap<AnnotationId>::iterator ite = theAnnotName2IdMap.find(qname);
+ if (ite != theAnnotName2IdMap.end())
+ theId = (*ite).second;
}
+/*******************************************************************************
+
+********************************************************************************/
void AnnotationInternal::serialize(::zorba::serialization::Archiver& ar)
{
+ SERIALIZE_ENUM(AnnotationId, theId);
ar & theQName;
- ar & theLiteralList;
+ ar & theLiterals;
}
+/*******************************************************************************
+
+********************************************************************************/
const store::Item* AnnotationInternal::getQName() const
{
return theQName.getp();
}
-unsigned int AnnotationInternal::getNumLiterals() const
-{
- return (unsigned int)theLiteralList.size();
-}
-
-
-const AnnotationLiteral* AnnotationInternal::getLiteral(unsigned int index) const
-{
- if (index < theLiteralList.size())
- return theLiteralList[index];
- else
- return NULL;
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
-void AnnotationLiteral::serialize(::zorba::serialization::Archiver& ar)
-{
- ar & theLiteral;
-}
-
-
-AnnotationLiteral::AnnotationLiteral(const store::Item_t& aLiteralValue)
- : theLiteral(aLiteralValue)
-{
-}
-
-
-store::Item_t AnnotationLiteral::getLiteralItem() const
-{
- return theLiteral;
-}
-
-
-AnnotationInternal* AnnotationList::getAnnotation(unsigned int index) const
-{
- if (index < theAnnotationList.size())
- return theAnnotationList[index].getp();
- else
- return NULL;
-}
-
+/*******************************************************************************
+
+********************************************************************************/
+csize AnnotationInternal::getNumLiterals() const
+{
+ return theLiterals.size();
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+store::Item* AnnotationInternal::getLiteral(csize index) const
+{
+ if (index < theLiterals.size())
+ return theLiterals[index].getp();
+ else
+ return NULL;
+}
/*******************************************************************************
@@ -152,42 +341,58 @@
/*******************************************************************************
********************************************************************************/
+AnnotationInternal* AnnotationList::get(csize index) const
+{
+ if (index < theAnnotationList.size())
+ return theAnnotationList[index].getp();
+ else
+ return NULL;
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+AnnotationInternal* AnnotationList::get(AnnotationInternal::AnnotationId id) const
+{
+ for (ListConstIter_t ite = theAnnotationList.begin();
+ ite != theAnnotationList.end();
+ ++ite)
+ {
+ if ((*ite)->getId() == id)
+ return (*ite).getp();
+ }
+
+ return NULL;
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+bool AnnotationList::contains(AnnotationInternal::AnnotationId id) const
+{
+ return (get(id) != NULL);
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
void AnnotationList::push_back(
- const store::Item_t& aExpQName,
- const std::vector<rchandle<const_expr> >& aLiterals)
+ const store::Item_t& qname,
+ const std::vector<rchandle<const_expr> >& literals)
{
- std::vector<AnnotationLiteral_t> lLiterals;
+ std::vector<store::Item_t> lLiterals;
- for (std::vector<rchandle<const_expr> >::const_iterator it = aLiterals.begin();
- it != aLiterals.end();
+ for (std::vector<rchandle<const_expr> >::const_iterator it = literals.begin();
+ it != literals.end();
++it)
{
- lLiterals.push_back(new AnnotationLiteral((*it)->get_val()));
- }
-
- theAnnotationList.push_back(new AnnotationInternal(aExpQName, lLiterals));
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
-bool AnnotationList::contains(const store::Item_t& aSearchQName) const
-{
- if (aSearchQName.getp() == NULL)
- return false;
-
- // sequential search might not be the most efficient but
- // how many annotations might a function or variable have? 5?
- for (ListConstIter_t lIter = theAnnotationList.begin();
- lIter != theAnnotationList.end();
- ++lIter)
- {
- if ((*lIter)->getQName()->equals(aSearchQName))
- return true;
- }
-
- return false;
+ lLiterals.push_back((*it)->get_val());
+ }
+
+ theAnnotationList.push_back(new AnnotationInternal(qname, lLiterals));
}
@@ -196,232 +401,59 @@
********************************************************************************/
void AnnotationList::checkConflictingDeclarations(const QueryLoc& loc) const
{
- static_context& lCtx = GENV_ROOT_STATIC_CONTEXT;
-
// make sure we don't have more annotations then max 64 bit
- assert( static_cast<uint64_t>(StaticContextConsts::zann_end) <
- std::numeric_limits<uint64_t>::max() );
+ assert(AnnotationInternal::zann_end < 64);
RuleBitSet lCurrAnn;
// mark and detect duplicates
- for (ListConstIter_t lIter = theAnnotationList.begin();
- lIter != theAnnotationList.end();
- ++lIter)
+ for (ListConstIter_t ite = theAnnotationList.begin();
+ ite != theAnnotationList.end();
+ ++ite)
{
- store::Item_t lQName = const_cast<store::Item*>((*lIter)->getQName());
- StaticContextConsts::annotations_t lAnn = lCtx.lookup_ann(lQName);
+ const store::Item* qname = (*ite)->getQName();
+ AnnotationId id = (*ite)->getId();
// detect duplicate annotations (if we "know" them)
- if ( lAnn != StaticContextConsts::zann_end && lCurrAnn.test( lAnn ) )
+ if (id != AnnotationInternal::zann_end && lCurrAnn.test(id))
{
- throw XQUERY_EXCEPTION(
- err::XQST0106,
- ERROR_PARAMS(
- lQName->getStringValue(),
- ZED(XQST0106_THE_SAME)
- ),
- ERROR_LOC(loc));
+ RAISE_ERROR(err::XQST0106, loc,
+ ERROR_PARAMS(qname->getStringValue(), ZED(XQST0106_THE_SAME)));
}
- lCurrAnn.set( lAnn );
+ lCurrAnn.set(id);
}
// check rules
- for ( std::vector<RuleBitSet>::const_iterator lIter = theRuleSet.begin();
- lIter != theRuleSet.end();
- ++lIter )
+ std::vector<RuleBitSet>::const_iterator ite = AnnotationInternal::theRuleSet.begin();
+ std::vector<RuleBitSet>::const_iterator end = AnnotationInternal::theRuleSet.end();
+
+ for (; ite != end; ++ite)
{
- const RuleBitSet lCurrSet = *lIter;
- if ( ( lCurrAnn & lCurrSet ).count() > 1 )
+ const RuleBitSet& lCurrSet = *ite;
+
+ if ((lCurrAnn & lCurrSet).count() > 1)
{
// build error string to return set of conflicting annotations
std::ostringstream lProblems;
- for ( size_t i = 0, j = 0; i < StaticContextConsts::zann_end; ++i )
+ for (csize i = 0, j = 0; i < AnnotationInternal::zann_end; ++i)
{
- if ( lCurrSet.test( i ) )
+ if (lCurrSet.test(i))
{
- lProblems
- << lCtx.lookup_ann(
- static_cast<StaticContextConsts::annotations_t>(i)
- )->getStringValue()
- << ((j == lCurrSet.count() - 1) ? "" : ", ");
+ AnnotationId id = static_cast<AnnotationId>(i);
+
+ lProblems << AnnotationInternal::lookup(id)->getStringValue()
+ << ((j == lCurrSet.count() - 1) ? "" : ", ");
++j;
}
}
- throw XQUERY_EXCEPTION(
- err::XQST0106,
- ERROR_PARAMS(
- lProblems.str(),
- ZED(XQST0106_CONFLICTING)
- ),
- ERROR_LOC(loc));
+
+ RAISE_ERROR(err::XQST0106, loc,
+ ERROR_PARAMS(lProblems.str(), ZED(XQST0106_CONFLICTING)));
}
}
}
-void AnnotationList::createBuiltIn(static_context* aCtx)
-{
- store::Item_t lTmp;
-
- //
- // W3C annotations
- //
- GENV_ITEMFACTORY->createQName(lTmp, static_context::W3C_FN_NS, "fn", "public");
- aCtx->add_ann(StaticContextConsts::fn_public, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, static_context::W3C_FN_NS, "fn", "private");
- aCtx->add_ann(StaticContextConsts::fn_private, lTmp);
-
- //
- // Zorba annotations - deterministic/nondeterministic
- //
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "deterministic");
- aCtx->add_ann(StaticContextConsts::zann_deterministic, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "nondeterministic");
- aCtx->add_ann(StaticContextConsts::zann_nondeterministic, lTmp);
-
- //
- // Zorba annotations - xquery scripting
- //
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "assignable");
- aCtx->add_ann(StaticContextConsts::zann_assignable, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "nonassignable");
- aCtx->add_ann(StaticContextConsts::zann_nonassignable, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "sequential");
- aCtx->add_ann(StaticContextConsts::zann_sequential, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "nonsequential");
- aCtx->add_ann(StaticContextConsts::zann_nonsequential, lTmp);
-
- //
- // Zorba annotations - misc
- //
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "variadic");
- aCtx->add_ann(StaticContextConsts::zann_variadic, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "streamable");
- aCtx->add_ann(StaticContextConsts::zann_streamable, lTmp);
-
- //
- // Zorba annotations - xqddf
- //
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "unique");
- aCtx->add_ann(StaticContextConsts::zann_unique, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "nonunique");
- aCtx->add_ann(StaticContextConsts::zann_nonunique, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "value-equality");
- aCtx->add_ann(StaticContextConsts::zann_value_equality, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "general-equality");
- aCtx->add_ann(StaticContextConsts::zann_general_equality, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "value-range");
- aCtx->add_ann(StaticContextConsts::zann_value_range, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "general-range");
- aCtx->add_ann(StaticContextConsts::zann_general_range, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "automatic");
- aCtx->add_ann(StaticContextConsts::zann_automatic, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "manual");
- aCtx->add_ann(StaticContextConsts::zann_manual, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "mutable");
- aCtx->add_ann(StaticContextConsts::zann_mutable, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "queue");
- aCtx->add_ann(StaticContextConsts::zann_queue, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "append-only");
- aCtx->add_ann(StaticContextConsts::zann_append_only, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "const");
- aCtx->add_ann(StaticContextConsts::zann_const, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "ordered");
- aCtx->add_ann(StaticContextConsts::zann_ordered, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "unordered");
- aCtx->add_ann(StaticContextConsts::zann_unordered, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "read-only-nodes");
- aCtx->add_ann(StaticContextConsts::zann_read_only_nodes, lTmp);
-
- GENV_ITEMFACTORY->createQName(lTmp, ZORBA_ANNOTATIONS_NS, "", "mutable-nodes");
- aCtx->add_ann(StaticContextConsts::zann_mutable_nodes, lTmp);
-
- // create a set of rules to detect conflicts between annotations
-#define ZANN(a) \
- ( 1 << static_cast<uint64_t>(StaticContextConsts:: a) )
- theRuleSet.push_back(
- ZANN(zann_unique) |
- ZANN(zann_nonunique)
- );
- theRuleSet.push_back(
- ZANN(zann_value_equality) |
- ZANN(zann_general_equality) |
- ZANN(zann_value_range) |
- ZANN(zann_general_range)
- );
- theRuleSet.push_back(
- ZANN(zann_automatic) |
- ZANN(zann_manual)
- );
- theRuleSet.push_back(
- ZANN(zann_mutable) |
- ZANN(zann_queue) |
- ZANN(zann_append_only) |
- ZANN(zann_const)
- );
- theRuleSet.push_back(
- ZANN(zann_ordered) |
- ZANN(zann_unordered)
- );
- theRuleSet.push_back(
- ZANN(zann_assignable) |
- ZANN(zann_nonassignable)
- );
- theRuleSet.push_back(
- ZANN(zann_deterministic) |
- ZANN(zann_nondeterministic)
- );
- theRuleSet.push_back(
- ZANN(zann_sequential) |
- ZANN(zann_nonsequential)
- );
- theRuleSet.push_back(
- ZANN(fn_private) |
- ZANN(fn_public)
- );
- theRuleSet.push_back(
- ZANN(zann_unordered) |
- ZANN(zann_queue)
- );
- theRuleSet.push_back(
- ZANN(zann_unordered) |
- ZANN(zann_append_only)
- );
- theRuleSet.push_back(
- ZANN(zann_queue) |
- ZANN(zann_append_only)
- );
- theRuleSet.push_back(
- ZANN(zann_read_only_nodes) |
- ZANN(zann_mutable_nodes)
- );
-#undef ZANN
-}
-
-std::vector<AnnotationList::RuleBitSet> AnnotationList::theRuleSet;
-
-
} /* namespace zorba */
/* vim:set et sw=2 ts=2: */
=== modified file 'src/annotations/annotations.h'
--- src/annotations/annotations.h 2011-07-21 01:30:19 +0000
+++ src/annotations/annotations.h 2012-01-25 00:12:28 +0000
@@ -19,39 +19,99 @@
#include <vector>
#include <bitset>
+
#include "common/shared_types.h"
+
#include "compiler/parsetree/parsenodes.h"
+#include "zorbautils/hashmap_itemh.h"
+
namespace zorba
{
-class AnnotationLiteral;
class AnnotationInternal;
class AnnotationList;
typedef rchandle<AnnotationInternal> AnnotationInternal_t;
typedef rchandle<AnnotationList> AnnotationList_t;
-typedef rchandle<AnnotationLiteral> AnnotationLiteral_t;
class const_expr;
/*******************************************************************************
-
+ Annotation ::= "%" EQName ("(" Literal ("," Literal)* ")")?
********************************************************************************/
class AnnotationInternal : public SimpleRCObject
{
friend class AnnotationList;
-protected:
- store::Item_t theQName;
- std::vector<AnnotationLiteral_t> theLiteralList;
-
-public:
- AnnotationInternal(const store::Item_t& aExpandedQName);
+public:
+ enum AnnotationId
+ {
+ fn_public = 0,
+ fn_private,
+ zann_deterministic,
+ zann_nondeterministic,
+ zann_assignable,
+ zann_nonassignable,
+ zann_sequential,
+ zann_nonsequential,
+ zann_propagates_input_nodes,
+ zann_must_copy_input_nodes,
+ zann_cache,
+ zann_nocache,
+ zann_variadic,
+ zann_streamable,
+ zann_unique,
+ zann_nonunique,
+ zann_value_equality,
+ zann_general_equality,
+ zann_value_range,
+ zann_general_range,
+ zann_automatic,
+ zann_manual,
+ zann_mutable,
+ zann_queue,
+ zann_append_only,
+ zann_const,
+ zann_ordered,
+ zann_unordered,
+ zann_read_only_nodes,
+ zann_mutable_nodes,
+
+ // must be at the end
+ zann_end
+ };
+
+protected:
+ typedef std::bitset<zann_end + 1> RuleBitSet;
+
+protected:
+ static std::vector<store::Item_t> theAnnotId2NameMap;
+
+ static ItemHandleHashMap<AnnotationId> theAnnotName2IdMap;
+
+ static std::vector<RuleBitSet> theRuleSet;
+
+protected:
+ AnnotationId theId;
+ store::Item_t theQName;
+ std::vector<store::Item_t> theLiterals;
+
+public:
+ static void createBuiltIn();
+
+ static void destroyBuiltIn();
+
+ static AnnotationId lookup(const store::Item_t& qname);
+
+ static store::Item* lookup(AnnotationId id);
+
+public:
+ AnnotationInternal(const store::Item_t& qname);
AnnotationInternal(
- const store::Item_t& aExpandedQName,
- const std::vector<AnnotationLiteral_t>& aLiteralList);
+ const store::Item_t& qname,
+ std::vector<store::Item_t>& literals);
public:
SERIALIZABLE_CLASS(AnnotationInternal);
@@ -59,55 +119,37 @@
void serialize(::zorba::serialization::Archiver& ar);
public:
- virtual ~AnnotationInternal() { };
+ ~AnnotationInternal() { };
+
+ AnnotationId getId() const { return theId; }
const store::Item* getQName() const;
- unsigned int getNumLiterals() const;
-
- const AnnotationLiteral* getLiteral(unsigned int index) const;
-};
-
-
-
-/*******************************************************************************
-
-********************************************************************************/
-class AnnotationLiteral : public SimpleRCObject
-{
-protected:
- store::Item_t theLiteral;
-
-public:
- AnnotationLiteral(const store::Item_t& aLiteral);
-
-public:
- SERIALIZABLE_CLASS(AnnotationLiteral);
- SERIALIZABLE_CLASS_CONSTRUCTOR2(AnnotationLiteral, SimpleRCObject)
- void serialize(::zorba::serialization::Archiver& ar);
-
-public:
- virtual ~AnnotationLiteral() {};
-
- store::Item_t getLiteralItem() const;
-};
-
-
-/*******************************************************************************
-
+ csize getNumLiterals() const;
+
+ store::Item* getLiteral(csize index) const;
+};
+
+
+/*******************************************************************************
+ AnnotationList := Annotation*
+
+ Annotation ::= "%" EQName ("(" Literal ("," Literal)* ")")?
********************************************************************************/
class AnnotationList : public SimpleRCObject
{
public:
+ typedef AnnotationInternal::RuleBitSet RuleBitSet;
+
+ typedef AnnotationInternal::AnnotationId AnnotationId;
+
typedef std::vector<AnnotationInternal_t> List_t;
+
typedef List_t::const_iterator ListConstIter_t;
protected:
List_t theAnnotationList;
- typedef std::bitset<StaticContextConsts::zann_end + 1> RuleBitSet;
- static std::vector<RuleBitSet> theRuleSet;
-
public:
SERIALIZABLE_CLASS(AnnotationList);
SERIALIZABLE_CLASS_CONSTRUCTOR2(AnnotationList, SimpleRCObject)
@@ -116,22 +158,21 @@
public:
AnnotationList();
- virtual ~AnnotationList();
-
- size_t size() const { return theAnnotationList.size(); }
-
- AnnotationInternal* getAnnotation(unsigned int index) const;
+ ~AnnotationList();
+
+ csize size() const { return theAnnotationList.size(); }
+
+ AnnotationInternal* get(csize index) const;
+
+ AnnotationInternal* get(AnnotationInternal::AnnotationId id) const;
+
+ bool contains(AnnotationInternal::AnnotationId id) const;
void push_back(
- const store::Item_t& aExpQName,
- const std::vector<rchandle<const_expr> >& aLiterals);
-
- bool contains(const store::Item_t& aSearchQName) const;
+ const store::Item_t& qname,
+ const std::vector<rchandle<const_expr> >& literals);
void checkConflictingDeclarations(const QueryLoc& loc) const;
-
-public:
- static void createBuiltIn(static_context* aCtx);
};
=== modified file 'src/api/annotationimpl.cpp'
--- src/api/annotationimpl.cpp 2011-06-14 17:26:33 +0000
+++ src/api/annotationimpl.cpp 2012-01-25 00:12:28 +0000
@@ -50,7 +50,7 @@
if (i >= theAnnotation->getNumLiterals())
return Item(NULL);
- Item lItem(theAnnotation->getLiteral(i)->getLiteralItem().getp());
+ Item lItem(theAnnotation->getLiteral(i));
return lItem;
}
=== modified file 'src/api/collectionimpl.cpp'
--- src/api/collectionimpl.cpp 2011-09-15 13:11:51 +0000
+++ src/api/collectionimpl.cpp 2012-01-25 00:12:28 +0000
@@ -30,6 +30,7 @@
#include "api/zorbaimpl.h"
#include "api/unmarshaller.h"
+#include "diagnostics/assert.h"
#include "diagnostics/xquery_diagnostics.h"
#include "diagnostics/zorba_exception.h"
@@ -45,6 +46,7 @@
#include "context/static_context.h"
+#include "types/typeimpl.h"
#include "types/typeops.h"
#include "compiler/xqddf/collection_decl.h"
@@ -444,17 +446,10 @@
{
store::Annotation_t lSAnn = *lIter;
- std::vector<AnnotationLiteral_t> lILiterals;
- std::vector<store::Item_t>::const_iterator lLiteral;
- for (lLiteral = lSAnn->theLiterals.begin();
- lLiteral != lSAnn->theLiterals.end();
- ++lLiteral)
- {
- lILiterals.push_back(new AnnotationLiteral(*lLiteral));
- }
+ std::vector<store::Item_t> lLiterals = lSAnn->theLiterals;
aAnnotations.push_back(
- new AnnotationImpl(new AnnotationInternal(lSAnn->theName, lILiterals)));
+ new AnnotationImpl(new AnnotationInternal(lSAnn->theName, lLiterals)));
}
}
ZORBA_DM_CATCH
=== modified file 'src/api/dynamiccontextimpl.cpp'
--- src/api/dynamiccontextimpl.cpp 2011-10-03 09:18:49 +0000
+++ src/api/dynamiccontextimpl.cpp 2012-01-25 00:12:28 +0000
@@ -593,6 +593,7 @@
return false;
}
+
/****************************************************************************//**
********************************************************************************/
@@ -608,5 +609,37 @@
return 0;
}
+
+/****************************************************************************//**
+
+********************************************************************************/
+bool
+DynamicContextImpl::isBoundExternalVariable(const String& aNamespace, const String& aLocalname) const
+{
+ ZORBA_DCTX_TRY
+ {
+ if(theQuery->isBoundVariable(aNamespace, aLocalname))
+ return true;
+ }
+ ZORBA_DCTX_CATCH
+ return false;
+}
+
+/****************************************************************************//**
+
+********************************************************************************/
+bool
+DynamicContextImpl::isBoundContextItem() const
+{
+ ZORBA_DCTX_TRY
+ {
+ String varName = Unmarshaller::newString(static_context::DOT_VAR_NAME);
+ if(theQuery->isBoundVariable("", varName))
+ return true;
+ }
+ ZORBA_DCTX_CATCH
+ return false;
+}
+
} // namespace zorba
/* vim:set et sw=2 ts=2: */
=== modified file 'src/api/dynamiccontextimpl.h'
--- src/api/dynamiccontextimpl.h 2011-10-03 09:18:49 +0000
+++ src/api/dynamiccontextimpl.h 2012-01-25 00:12:28 +0000
@@ -81,6 +81,7 @@
virtual ~DynamicContextImpl();
public:
+
virtual bool
getVariable(
const String& inNamespace,
@@ -142,6 +143,12 @@
virtual ExternalFunctionParameter*
getExternalFunctionParameter ( const String& aName ) const;
+ virtual bool
+ isBoundExternalVariable(const String& aNamespace, const String& aLocalname) const;
+
+ virtual bool
+ isBoundContextItem() const;
+
protected:
void checkNoIterators() const;
=== modified file 'src/api/functionimpl.cpp'
--- src/api/functionimpl.cpp 2011-09-05 02:06:22 +0000
+++ src/api/functionimpl.cpp 2012-01-25 00:12:28 +0000
@@ -63,7 +63,7 @@
try
{
for (unsigned int i = 0; i < ann_list->size(); ++i)
- annotations.push_back(new AnnotationImpl(ann_list->getAnnotation(i)));
+ annotations.push_back(new AnnotationImpl(ann_list->get(i)));
}
catch (ZorbaException const& e)
{
=== modified file 'src/api/item.cpp'
--- src/api/item.cpp 2011-06-14 17:26:33 +0000
+++ src/api/item.cpp 2012-01-25 00:12:28 +0000
@@ -380,6 +380,32 @@
return NULL;
}
+void
+Item::getNamespaceBindings(NsBindings& aBindings,
+ store::StoreConsts::NsScoping aNsScoping) const
+{
+ ITEM_TRY
+ SYNC_CODE(AutoLock lock(GENV_STORE.getGlobalLock(), Lock::READ);)
+
+ store::NsBindings lStoreBindings;
+ m_item->getNamespaceBindings(lStoreBindings, aNsScoping);
+ aBindings.reserve(aBindings.size() + lStoreBindings.size());
+
+ store::NsBindings::iterator ite = lStoreBindings.begin();
+ store::NsBindings::iterator end = lStoreBindings.end();
+ for (; ite != end; ++ite) {
+ zstring& prefix = ite->first;
+ zstring& nsuri = ite->second;
+ aBindings.push_back(
+ std::pair<String, String>(
+ Unmarshaller::newString(prefix),
+ Unmarshaller::newString(nsuri))
+ );
+ }
+
+ ITEM_CATCH
+}
+
Item
Item::getParent() const
{
=== modified file 'src/api/itemfactoryimpl.cpp'
--- src/api/itemfactoryimpl.cpp 2011-07-22 07:23:17 +0000
+++ src/api/itemfactoryimpl.cpp 2012-01-25 00:12:28 +0000
@@ -406,8 +406,39 @@
return &*lItem;
}
-
-
+
+Item ItemFactoryImpl::createDayTimeDuration( const String& aValue )
+{
+ zstring const &lString = Unmarshaller::getInternalString( aValue );
+ store::Item_t lItem;
+ theItemFactory->createDayTimeDuration(lItem, lString.c_str(), lString.size());
+
+ return &*lItem;
+}
+
+Item ItemFactoryImpl::createYearMonthDuration( const String& aValue )
+{
+ zstring const &lString = Unmarshaller::getInternalString( aValue );
+ store::Item_t lItem;
+ theItemFactory->createYearMonthDuration(lItem, lString.c_str(), lString.size());
+
+ return &*lItem;
+}
+
+Item ItemFactoryImpl::createDocumentNode( const String& aBaseUri, const String& aDocUri )
+{
+ store::Item_t lItem;
+ zstring &lBaseUri = Unmarshaller::getInternalString( aBaseUri );
+ zstring &lDocUri = Unmarshaller::getInternalString( aDocUri );
+ try {
+ theItemFactory->createDocumentNode(lItem, lBaseUri, lDocUri);
+ }
+ catch ( std::exception const& ) {
+ // ignore
+ }
+ return &*lItem;
+}
+
Item ItemFactoryImpl::createFloat ( const String& aValue )
{
zstring const &lString = Unmarshaller::getInternalString( aValue );
@@ -665,7 +696,7 @@
Item aTypeName,
bool aHasTypedValue,
bool aHasEmptyValue,
- std::vector<std::pair<String, String> > aNsBindings)
+ NsBindings aNsBindings)
{
store::Item_t lItem;
store::Item_t lNodeName = Unmarshaller::getInternalItem(aNodeName);
@@ -738,10 +769,36 @@
}
+zorba::Item ItemFactoryImpl::createCommentNode(Item aParent, String &aContent)
+{
+ store::Item_t lItem;
+ zstring &lContent = Unmarshaller::getInternalString(aContent);
+ theItemFactory->createCommentNode(lItem,
+ Unmarshaller::getInternalItem(aParent),
+ lContent);
+ return &*lItem;
+}
+
+
+zorba::Item ItemFactoryImpl::createPiNode(Item aParent, String &aTarget, String &aContent, String &aBaseUri)
+{
+ store::Item_t lItem;
+ zstring &lTarget = Unmarshaller::getInternalString(aTarget);
+ zstring &lContent = Unmarshaller::getInternalString(aContent);
+ zstring &lBaseUri = Unmarshaller::getInternalString(aBaseUri);
+ theItemFactory->createPiNode(lItem,
+ Unmarshaller::getInternalItem(aParent),
+ lTarget,
+ lContent,
+ lBaseUri);
+ return &*lItem;
+}
+
+
zorba::Item ItemFactoryImpl::createTextNode(Item parent, String content)
{
store::Item_t lItem;
- zstring lContent = Unmarshaller::getInternalString(content);
+ zstring &lContent = Unmarshaller::getInternalString(content);
theItemFactory->createTextNode(lItem,
Unmarshaller::getInternalItem(parent),
lContent);
=== modified file 'src/api/itemfactoryimpl.h'
--- src/api/itemfactoryimpl.h 2011-07-22 07:23:17 +0000
+++ src/api/itemfactoryimpl.h 2012-01-25 00:12:28 +0000
@@ -125,7 +125,16 @@
virtual Item
createDuration ( short aYears, short aMonths, short aDays,
short aHours, short aMinutes, double aSeconds );
-
+
+ virtual Item
+ createDayTimeDuration( const String& aValue );
+
+ virtual Item
+ createYearMonthDuration( const String& aValue );
+
+ virtual Item
+ createDocumentNode( const String& aBaseUri, const String& aDocUri );
+
virtual Item
createFloat ( const String& aValue );
@@ -204,7 +213,7 @@
Item aTypeName,
bool aHasTypedValue,
bool aHasEmptyValue,
- std::vector<std::pair<String, String> > aNsBindings);
+ NsBindings aNsBindings);
virtual Item
createAttributeNode(Item aParent,
@@ -218,7 +227,20 @@
Item aTypeName,
std::vector<Item> aTypedValue);
- virtual Item createTextNode(
+ virtual Item
+ createCommentNode (
+ Item aParent,
+ String &aContent);
+
+ virtual Item
+ createPiNode (
+ Item aParent,
+ String &aTarget,
+ String &aContent,
+ String &aBaseUri);
+
+ virtual Item
+ createTextNode(
Item parent,
String content);
=== modified file 'src/api/options.cpp'
--- src/api/options.cpp 2011-06-14 17:26:33 +0000
+++ src/api/options.cpp 2012-01-25 00:12:28 +0000
@@ -19,12 +19,24 @@
#include <zorba/options.h>
Zorba_CompilerHints::Zorba_CompilerHints()
-: opt_level(ZORBA_OPT_LEVEL_O1),
- lib_module(false)
-{}
+ :
+ opt_level(ZORBA_OPT_LEVEL_O1),
+ lib_module(false),
+ for_serialization_only(false)
+{
+}
+
+
+void Zorba_CompilerHints_default(Zorba_CompilerHints_t* aHints)
+{
+ Zorba_CompilerHints_t lDefault;
+ *aHints = lDefault;
+}
+
Zorba_SerializerOptions::Zorba_SerializerOptions()
-: ser_method(ZORBA_SERIALIZATION_METHOD_XML),
+ :
+ ser_method(ZORBA_SERIALIZATION_METHOD_XML),
byte_order_mark(ZORBA_BYTE_ORDER_MARK_NO),
escape_uri_attributes(ZORBA_ESCAPE_URI_ATTRIBUTES_NO),
include_content_type(ZORBA_INCLUDE_CONTENT_TYPE_NO),
@@ -34,9 +46,13 @@
standalone(ZORBA_STANDALONE_OMIT),
undeclare_prefixes(ZORBA_UNDECLARE_PREFIXES_NO),
encoding(ZORBA_ENCODING_UTF8)
-{}
-
-void Zorba_SerializerOptions::SetSerializerOption(const char* parameter, const char* value)
+{
+}
+
+
+void Zorba_SerializerOptions::SetSerializerOption(
+ const char* parameter,
+ const char* value)
{
if (parameter == NULL || value == NULL)
return;
@@ -112,6 +128,7 @@
}
}
+
Zorba_SerializerOptions_t Zorba_SerializerOptions::SerializerOptionsFromStringParams(const std::vector<std::pair<std::string, std::string> >& params)
{
Zorba_SerializerOptions_t opt;
@@ -127,11 +144,6 @@
return opt;
}
-void Zorba_CompilerHints_default(Zorba_CompilerHints_t* aHints)
-{
- Zorba_CompilerHints_t lDefault;
- *aHints = lDefault;
-}
Zorba_SerializerOptions_t* Zorba_SerializerOptions_default()
{
@@ -139,11 +151,13 @@
return lDefault;
}
+
void Zorba_SerializerOptions_free(Zorba_SerializerOptions_t* serializerOptions)
{
delete serializerOptions;
}
+
void Zorba_SerializerOptions_set(Zorba_SerializerOptions_t* serializerOptions, const char* parameter, const char* value)
{
if (serializerOptions == NULL || parameter == NULL || value == NULL)
=== modified file 'src/api/serialization/serializer.cpp'
--- src/api/serialization/serializer.cpp 2011-06-20 15:38:42 +0000
+++ src/api/serialization/serializer.cpp 2012-01-25 00:12:28 +0000
@@ -407,9 +407,8 @@
}
else if (item->getNodeKind() == store::StoreConsts::attributeNode)
{
- throw XQUERY_EXCEPTION(
- err::SENR0001, ERROR_PARAMS( item->getStringValue(), ZED( AttributeNode ) )
- );
+ throw XQUERY_EXCEPTION(err::SENR0001,
+ ERROR_PARAMS(item->getStringValue(), ZED(AttributeNode)));
}
else
{
@@ -423,13 +422,17 @@
********************************************************************************/
void serializer::emitter::emit_node(const store::Item* item, int depth)
{
- if (item->getNodeKind() == store::StoreConsts::documentNode)
+ switch (item->getNodeKind())
+ {
+ case store::StoreConsts::documentNode:
{
emit_node_children(item, depth);
previous_item = PREVIOUS_ITEM_WAS_NODE;
+
+ break;
}
- else if (item->getNodeKind() == store::StoreConsts::elementNode)
+ case store::StoreConsts::elementNode:
{
store::Item* qnameItem = item->getNodeName();
const zstring& prefix = qnameItem->getPrefix();
@@ -452,7 +455,7 @@
previous_item = PREVIOUS_ITEM_WAS_NODE;
- bool should_remove_binding = emit_bindings(item);
+ bool should_remove_binding = emit_bindings(item, depth);
int closed_parent_tag = emit_node_children(item, depth+1);
@@ -472,8 +475,10 @@
}
previous_item = PREVIOUS_ITEM_WAS_NODE;
+
+ break;
}
- else if (item->getNodeKind() == store::StoreConsts::attributeNode)
+ case store::StoreConsts::attributeNode:
{
store::Item* qnameItem = item->getNodeName();
const zstring& prefix = qnameItem->getPrefix();
@@ -492,8 +497,10 @@
tr << "\"";
previous_item = PREVIOUS_ITEM_WAS_NODE;
+
+ break;
}
- else if (item->getNodeKind() == store::StoreConsts::textNode)
+ case store::StoreConsts::textNode:
{
zstring text;
item->getStringValue2(text);
@@ -509,22 +516,30 @@
{
previous_item = PREVIOUS_ITEM_WAS_NODE;
}
+
+ break;
}
- else if (item->getNodeKind() == store::StoreConsts::commentNode)
+ case store::StoreConsts::commentNode:
{
tr << "<!--" << item->getStringValue() << "-->";
previous_item = PREVIOUS_ITEM_WAS_NODE;
+
+ break;
}
- else if (item->getNodeKind() == store::StoreConsts::piNode)
+ case store::StoreConsts::piNode:
{
tr << "<?" << item->getTarget() << " " << item->getStringValue() << "?>";
previous_item = PREVIOUS_ITEM_WAS_NODE;
+
+ break;
}
- else
+ default:
{
+ ZORBA_ASSERT(false);
tr << "node of type: " << item->getNodeKind();
}
+ }
}
@@ -673,15 +688,42 @@
/*******************************************************************************
********************************************************************************/
-bool serializer::emitter::emit_bindings(const store::Item* item)
+bool serializer::emitter::emit_bindings(const store::Item* item, int depth)
{
// emit namespace bindings
store::NsBindings nsBindings;
- item->getNamespaceBindings(nsBindings);
-
- ulong numBindings = (ulong)nsBindings.size();
-
- for (ulong i = 0; i < numBindings; ++i)
+ if (depth == 0)
+ {
+ item->getNamespaceBindings(nsBindings);
+ }
+ else
+ {
+ //item->getNamespaceBindings(nsBindings, store::StoreConsts::ONLY_LOCAL_NAMESPACES);
+ item->getNamespaceBindings(nsBindings);
+
+ store::Item* nodeName = item->getNodeName();
+
+ const zstring& prefix = nodeName->getPrefix();
+ const zstring& nsuri = nodeName->getNamespace();
+ if (prefix.empty() && nsuri.empty())
+ {
+ store::NsBindings::const_iterator ite = nsBindings.begin();
+ store::NsBindings::const_iterator end = nsBindings.end();
+
+ for (; ite != end; ++ite)
+ {
+ if (ite->second.empty() && ite->first.empty())
+ break;
+ }
+
+ if (ite == end)
+ nsBindings.push_back(std::pair<zstring, zstring>(prefix, nsuri));
+ }
+ }
+
+ csize numBindings = nsBindings.size();
+
+ for (csize i = 0; i < numBindings; ++i)
{
if (!haveBinding(nsBindings[i]))
{
@@ -728,11 +770,11 @@
********************************************************************************/
bool serializer::emitter::haveBinding(std::pair<zstring, zstring>& nsBinding) const
{
- for (ulong i = 0; i < theBindings.size(); ++i)
+ for (csize i = 0; i < theBindings.size(); ++i)
{
const store::NsBindings& nsBindings = theBindings[i];
- for (ulong j = 0; j < nsBindings.size(); ++j)
+ for (csize j = 0; j < nsBindings.size(); ++j)
{
if (nsBindings[j].first == nsBinding.first &&
nsBindings[j].second == nsBinding.second)
@@ -1087,7 +1129,7 @@
previous_item = PREVIOUS_ITEM_WAS_NODE;
- bool should_remove_binding = emit_bindings(item);
+ bool should_remove_binding = emit_bindings(item, depth);
// If there is a head element, and the include-content-type parameter has
// the value yes, the HTML output method MUST add a meta element as the
@@ -1314,7 +1356,7 @@
}
}
- bool should_remove_binding = emit_bindings(item);
+ bool should_remove_binding = emit_bindings(item, depth);
closed_parent_tag |= emit_node_children(item, depth+1);
@@ -1406,7 +1448,7 @@
/*******************************************************************************
********************************************************************************/
-bool serializer::sax2_emitter::emit_bindings(const store::Item * item)
+bool serializer::sax2_emitter::emit_bindings(const store::Item * item, int)
{
return false;
}
@@ -1646,6 +1688,7 @@
/*******************************************************************************
+
********************************************************************************/
void serializer::text_emitter::emit_declaration()
{
@@ -1653,6 +1696,7 @@
/*******************************************************************************
+
********************************************************************************/
void serializer::text_emitter::emit_streamable_item(store::Item* item)
{
@@ -1661,14 +1705,18 @@
std::streambuf * pbuf;
std::streamsize read_bytes;
std::istream& is = item->getStream();
-
- // prepare the stream
+ std::streampos pos;
std::ios::iostate const old_exceptions = is.exceptions();
- is.exceptions( std::ios::badbit | std::ios::failbit );
- std::streampos const pos = is.tellg();
- if (pos)
- is.seekg(0, std::ios::beg);
- is.exceptions(is.exceptions() & ~std::ios::failbit);
+
+ if (item->isSeekable())
+ {
+ // prepare the stream
+ is.exceptions( std::ios::badbit | std::ios::failbit );
+ pos = is.tellg();
+ if (pos)
+ is.seekg(0, std::ios::beg);
+ is.exceptions(is.exceptions() & ~std::ios::failbit);
+ }
// read bytes and do string expansion
do
@@ -1682,15 +1730,20 @@
// restore stream's state
is.clear(); // clear eofbit
- if (pos)
+ if (item->isSeekable())
{
- is.exceptions(is.exceptions() | std::ios::failbit);
- is.seekg(pos, std::ios::beg);
+ if (pos)
+ {
+ is.exceptions(is.exceptions() | std::ios::failbit);
+ is.seekg(pos, std::ios::beg);
+ }
+ is.exceptions(old_exceptions);
}
- is.exceptions(old_exceptions);
}
+
/*******************************************************************************
+
********************************************************************************/
void serializer::text_emitter::emit_item(store::Item* item)
{
@@ -2051,9 +2104,11 @@
void
serializer::validate_parameters(void)
{
- if (method == PARAMETER_VALUE_XML || method == PARAMETER_VALUE_XHTML) {
+ if (method == PARAMETER_VALUE_XML || method == PARAMETER_VALUE_XHTML)
+ {
// XML-only validation
- if (method == PARAMETER_VALUE_XML) {
+ if (method == PARAMETER_VALUE_XML)
+ {
if (version != "1.0" && version != "1.1")
throw XQUERY_EXCEPTION(
err::SESU0013, ERROR_PARAMS( version, "XML", "\"1.0\", \"1.1\"" )
@@ -2061,12 +2116,14 @@
}
// XHTML-only validation
- if (method == PARAMETER_VALUE_XHTML) {
+ if (method == PARAMETER_VALUE_XHTML)
+ {
}
// XML and XHTML validation
- if (omit_xml_declaration == PARAMETER_VALUE_YES) {
+ if (omit_xml_declaration == PARAMETER_VALUE_YES)
+ {
if (standalone != PARAMETER_VALUE_OMIT)
throw XQUERY_EXCEPTION(
err::SEPM0009, ERROR_PARAMS( ZED( SEPM0009_NotOmit ) )
@@ -2081,11 +2138,15 @@
throw XQUERY_EXCEPTION( err::SEPM0010 );
}
- if (method == PARAMETER_VALUE_HTML) {
+ if (method == PARAMETER_VALUE_HTML)
+ {
// Default value for "version" when method is HTML is "4.0"
- if (version_has_default_value) {
+ if (version_has_default_value)
+ {
version = "4.0";
- } else if (!(ztd::equals(version, "4.0", 3) || ztd::equals(version, "4.01", 4))) {
+ }
+ else if (!(ztd::equals(version, "4.0", 3) || ztd::equals(version, "4.01", 4)))
+ {
throw XQUERY_EXCEPTION(
err::SESU0013, ERROR_PARAMS( version, "HTML", "\"4.0\", \"4.01\"" )
);
@@ -2168,12 +2229,14 @@
validate_parameters();
- if (!setup(aOStream)) {
+ if (!setup(aOStream))
+ {
return;
}
// in case we use SAX event notifications
- if (aHandler) {
+ if (aHandler)
+ {
// only allow XML-based methods for SAX notifications
if (method != PARAMETER_VALUE_XML &&
method != PARAMETER_VALUE_XHTML) {
@@ -2190,10 +2253,12 @@
e->emit_declaration();
store::Item_t lItem;
-//+ aObject->open();
- while (aObject->next(lItem)) {
+ //+ aObject->open();
+ while (aObject->next(lItem))
+ {
// PUL's cannot be serialized
- if (lItem->isPul()) {
+ if (lItem->isPul())
+ {
throw ZORBA_EXCEPTION(zerr::ZAPI0007_CANNOT_SERIALIZE_PUL);
}
@@ -2214,7 +2279,9 @@
void* aHandlerData)
{
validate_parameters();
- if (!setup(stream)) {
+
+ if (!setup(stream))
+ {
return;
}
@@ -2222,22 +2289,27 @@
store::Item_t lItem;
//object->open();
- while (object->next(lItem)) {
+ while (object->next(lItem))
+ {
Zorba_SerializerOptions_t* lSerParams = aHandler(aHandlerData);
- if (lSerParams) {
+ if (lSerParams)
+ {
SerializerImpl::setSerializationParameters(*this, *lSerParams);
- if (!setup(stream)) {
+ if (!setup(stream))
+ {
return;
}
}
// PUL's cannot be serialized
- if (lItem->isPul()) {
+ if (lItem->isPul())
+ {
throw ZORBA_EXCEPTION(zerr::ZAPI0007_CANNOT_SERIALIZE_PUL);
}
e->emit_item(&*lItem);
- }
+ }
+
//object->close();
e->emit_declaration_end();
}
=== modified file 'src/api/serialization/serializer.h'
--- src/api/serialization/serializer.h 2011-06-14 17:26:33 +0000
+++ src/api/serialization/serializer.h 2012-01-25 00:12:28 +0000
@@ -123,10 +123,10 @@
* to be serialized.
* @param stream The stream to serialize to.
*/
- void serialize(store::Iterator_t object, std::ostream& stream);
+ void serialize(store::Iterator_t object, std::ostream& stream);
void serialize(
- store::Iterator_t object,
+ store::Iterator_t object,
std::ostream& stream,
itemHandler aHandler,
void* aHandlerData);
@@ -249,7 +249,7 @@
* @return returns true if the function has added a set of bindings to the list,
* which should be removed when the elememnt is out of the scope.
*/
- virtual bool emit_bindings(const store::Item* item);
+ virtual bool emit_bindings(const store::Item* item, int depth);
/**
* Serializes the given string, performing character expansion
@@ -426,7 +426,7 @@
void emit_node_children(const store::Item* item);
- bool emit_bindings(const store::Item* item);
+ bool emit_bindings(const store::Item* item, int depth);
void emit_item(store::Item* item );
};
=== modified file 'src/api/staticcollectionmanagerimpl.cpp'
--- src/api/staticcollectionmanagerimpl.cpp 2011-09-16 13:26:06 +0000
+++ src/api/staticcollectionmanagerimpl.cpp 2012-01-25 00:12:28 +0000
@@ -68,6 +68,7 @@
theFactory(aFactory),
theColDDLNamespace("http://www.zorba-xquery.com/modules/store/static/collections/ddl"),
theColDMLNamespace("http://www.zorba-xquery.com/modules/store/static/collections/dml"),
+ theIdxDDLNamespace("http://www.zorba-xquery.com/modules/store/static/indexes/ddl"),
theDiagnosticHandler(aDiagnosticHandler)
{
// the context passed as parameter is not used anywhere in here.
@@ -104,6 +105,7 @@
Zorba_CompilerHints_t lHints;
std::ostringstream lProlog;
lProlog << "import module namespace d = '" << theColDDLNamespace << "';";
+ lProlog << "import module namespace iddl = '" << theIdxDDLNamespace << "';";
aCtx->loadProlog(lProlog.str(), lHints);
}
@@ -245,6 +247,165 @@
}
+/*******************************************************************************
+
+********************************************************************************/
+void
+StaticCollectionManagerImpl::createIndex(const Item& aQName)
+{
+ ZORBA_DM_TRY
+ {
+ Item lFunc = theFactory->createQName(theIdxDDLNamespace, "create");
+
+ std::vector<ItemSequence_t> lArgs;
+ lArgs.push_back(new SingletonItemSequence(aQName));
+
+ ItemSequence_t lSeq = theContext->invoke(lFunc, lArgs);
+ Iterator_t lIter = lSeq->getIterator();
+ lIter->open();
+ Item lRes;
+ lIter->next(lRes);
+ }
+ ZORBA_DM_CATCH
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+void
+StaticCollectionManagerImpl::deleteIndex(const Item& aQName)
+{
+ // do a check here in order to get better (non-confusing) error messages
+ if (!isDeclaredIndex(aQName))
+ {
+ throw ZORBA_EXCEPTION(zerr::ZDDY0021_INDEX_NOT_DECLARED,
+ ERROR_PARAMS(aQName.getStringValue()));
+ }
+
+ ZORBA_DM_TRY
+ {
+ if (!isAvailableIndex(aQName))
+ {
+ throw ZORBA_EXCEPTION(zerr::ZDDY0023_INDEX_DOES_NOT_EXIST,
+ ERROR_PARAMS(aQName.getStringValue()));
+ }
+
+ Item lFunc = theFactory->createQName(theIdxDDLNamespace, "delete");
+
+ std::vector<ItemSequence_t> lArgs;
+ lArgs.push_back(new SingletonItemSequence(aQName));
+
+ ItemSequence_t lSeq = theContext->invoke(lFunc, lArgs);
+ Iterator_t lIter = lSeq->getIterator();
+ lIter->open();
+ Item lRes;
+ lIter->next(lRes);
+ }
+ ZORBA_DM_CATCH
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+ItemSequence_t
+StaticCollectionManagerImpl::availableIndexes() const
+{
+ ZORBA_DM_TRY
+ {
+ Item lFunc = theFactory->createQName(theIdxDDLNamespace,
+ "available-indexes");
+
+ std::vector<ItemSequence_t> lArgs;
+ return theContext->invoke(lFunc, lArgs);
+ }
+ ZORBA_DM_CATCH
+ return 0;
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+bool
+StaticCollectionManagerImpl::isAvailableIndex(const Item& aQName) const
+{
+ // do a check here in order to get better (non-confusing) error messages
+ if (!isDeclaredIndex(aQName))
+ {
+ throw ZORBA_EXCEPTION(zerr::ZDDY0001_COLLECTION_NOT_DECLARED,
+ ERROR_PARAMS(aQName.getStringValue()));
+ }
+
+ ZORBA_DM_TRY
+ {
+ Item lFunc = theFactory->createQName(theIdxDDLNamespace,
+ "is-available-index");
+
+ std::vector<ItemSequence_t> lArgs;
+ lArgs.push_back(new SingletonItemSequence(aQName));
+
+ ItemSequence_t lSeq = theContext->invoke(lFunc, lArgs);
+ Iterator_t lIter = lSeq->getIterator();
+ lIter->open();
+ Item lRes;
+ if (!lIter->next(lRes))
+ return false;
+
+ return lRes.getBooleanValue();
+ }
+ ZORBA_DM_CATCH
+ return false;
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+ItemSequence_t
+StaticCollectionManagerImpl::declaredIndexes() const
+{
+ ZORBA_DM_TRY
+ {
+ Item lFunc = theFactory->createQName(theIdxDDLNamespace,
+ "declared-indexes");
+
+ std::vector<ItemSequence_t> lArgs;
+ return theContext->invoke(lFunc, lArgs);
+ }
+ ZORBA_DM_CATCH
+ return 0;
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+bool
+StaticCollectionManagerImpl::isDeclaredIndex(const Item& aQName) const
+{
+ ZORBA_DM_TRY
+ {
+ Item lFunc = theFactory->createQName(theIdxDDLNamespace,
+ "is-declared-index");
+
+ std::vector<ItemSequence_t> lArgs;
+ lArgs.push_back(new SingletonItemSequence(aQName));
+
+ ItemSequence_t lSeq = theContext->invoke(lFunc, lArgs);
+ Iterator_t lIter = lSeq->getIterator();
+ lIter->open();
+ Item lRes;
+ if (!lIter->next(lRes))
+ return false;
+ return lRes.getBooleanValue();
+ }
+ ZORBA_DM_CATCH
+ return false;
+}
+
+
/////////////////////////////////////////////////////////////////////////////////
// //
// StaticCollectionManagerSetImpl //
@@ -451,6 +612,132 @@
********************************************************************************/
void
+StaticCollectionManagerSetImpl::createIndex(const Item& aQName)
+{
+ for (MgrSet::iterator lIter = theMgrs.begin();
+ lIter != theMgrs.end();
+ ++lIter)
+ {
+ if ((*lIter)->isDeclaredIndex(aQName))
+ {
+ (*lIter)->createIndex(aQName);
+ return;
+ }
+ }
+
+ throw ZORBA_EXCEPTION(zerr::ZDDY0021_INDEX_NOT_DECLARED,
+ ERROR_PARAMS(aQName.getStringValue()));
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+void
+StaticCollectionManagerSetImpl::deleteIndex(const Item& aQName)
+{
+ for (MgrSet::iterator lIter = theMgrs.begin();
+ lIter != theMgrs.end();
+ ++lIter)
+ {
+ if ((*lIter)->isDeclaredIndex(aQName))
+ {
+ (*lIter)->deleteIndex(aQName);
+ return;
+ }
+ }
+
+ throw ZORBA_EXCEPTION(zerr::ZDDY0021_INDEX_NOT_DECLARED,
+ ERROR_PARAMS(aQName.getStringValue()));
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+ItemSequence_t
+StaticCollectionManagerSetImpl::availableIndexes() const
+{
+ std::vector<ItemSequence_t> lSequences;
+ for (MgrSet::const_iterator lIter = theMgrs.begin();
+ lIter != theMgrs.end();
+ ++lIter)
+ {
+ lSequences.push_back((*lIter)->availableIndexes());
+ }
+ // need to do duplicate elimination because
+ // indexes are coming from static contexts
+ // which might be imported multiple times
+ return new ItemSequenceChainer(lSequences, true);
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+bool
+StaticCollectionManagerSetImpl::isAvailableIndex(const Item& aQName) const
+{
+ for (MgrSet::const_iterator lIter = theMgrs.begin();
+ lIter != theMgrs.end();
+ ++lIter)
+ {
+ if ((*lIter)->isDeclaredIndex(aQName) &&
+ (*lIter)->isAvailableIndex(aQName))
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+ItemSequence_t
+StaticCollectionManagerSetImpl::declaredIndexes() const
+{
+ std::vector<ItemSequence_t> lSequences;
+ for (MgrSet::const_iterator lIter = theMgrs.begin();
+ lIter != theMgrs.end();
+ ++lIter)
+ {
+ lSequences.push_back((*lIter)->declaredIndexes());
+ }
+ // we need to do duplicate elimination of the sequence because
+ // the contexts might contain the declaration of a index
+ // multiple times. This happens if the set of contexts contains
+ // the context that declares the index as well as some
+ // contexts that result from compiling modules that import
+ // the module declaring the index.
+ return new ItemSequenceChainer(lSequences, true);
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+bool
+StaticCollectionManagerSetImpl::isDeclaredIndex(const Item& aQName) const
+{
+ for (MgrSet::const_iterator lIter = theMgrs.begin();
+ lIter != theMgrs.end();
+ ++lIter)
+ {
+ if ((*lIter)->isDeclaredIndex(aQName))
+ {
+ return true;
+ }
+ }
+ return false;
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+void
StaticCollectionManagerSetImpl::registerDiagnosticHandler(
DiagnosticHandler* aDiagnosticHandler)
{
=== modified file 'src/api/staticcollectionmanagerimpl.h'
--- src/api/staticcollectionmanagerimpl.h 2011-09-14 11:08:52 +0000
+++ src/api/staticcollectionmanagerimpl.h 2012-01-25 00:12:28 +0000
@@ -80,6 +80,7 @@
ItemFactory * theFactory;
std::string theColDDLNamespace;
std::string theColDMLNamespace;
+ std::string theIdxDDLNamespace;
StaticContext_t theContext;
CollectionManagerImpl* theCollMgr;
@@ -125,6 +126,24 @@
virtual bool
isDeclaredCollection(const Item& aQName) const;
+ virtual void
+ createIndex(const Item& aQName);
+
+ virtual void
+ deleteIndex(const Item& aQName);
+
+ virtual ItemSequence_t
+ availableIndexes() const;
+
+ virtual bool
+ isAvailableIndex(const Item& aQName) const;
+
+ virtual ItemSequence_t
+ declaredIndexes() const;
+
+ virtual bool
+ isDeclaredIndex(const Item& aQName) const;
+
}; /* class StaticCollectionManagerImpl */
@@ -187,6 +206,24 @@
virtual bool
isDeclaredCollection(const Item& aQName) const;
+ virtual void
+ createIndex(const Item& aQName);
+
+ virtual void
+ deleteIndex(const Item& aQName);
+
+ virtual ItemSequence_t
+ availableIndexes() const;
+
+ virtual bool
+ isAvailableIndex(const Item& aQName) const;
+
+ virtual ItemSequence_t
+ declaredIndexes() const;
+
+ virtual bool
+ isDeclaredIndex(const Item& aQName) const;
+
}; /* class StaticCollectionManagerSetImpl */
=== modified file 'src/api/staticcontextimpl.cpp'
--- src/api/staticcontextimpl.cpp 2011-09-14 11:08:52 +0000
+++ src/api/staticcontextimpl.cpp 2012-01-25 00:12:28 +0000
@@ -27,6 +27,7 @@
#include <zorba/empty_sequence.h>
#include "store/api/item_factory.h"
+#include "store/api/temp_seq.h"
#include "api/unmarshaller.h"
#include "api/zorbaimpl.h"
@@ -35,6 +36,7 @@
#include "api/xqueryimpl.h"
#include "api/invoke_item_sequence.h"
#include "api/staticcollectionmanagerimpl.h"
+#include "api/vectoriterator.h"
#include "context/static_context.h"
#include "context/static_context_consts.h"
@@ -46,6 +48,7 @@
#include "compiler/parser/query_loc.h"
#include "compiler/api/compilercb.h"
+#include "compiler/expression/var_expr.h"
#include "functions/function.h"
@@ -191,7 +194,7 @@
********************************************************************************/
String
-StaticContextImpl::getNamespaceURIByPrefix( const String& aPrefix ) const
+StaticContextImpl::getNamespaceURIByPrefix(const String& aPrefix) const
{
try
{
@@ -212,17 +215,48 @@
return "";
}
+/*******************************************************************************
+
+********************************************************************************/
+void
+StaticContextImpl::getNamespaceBindings( NsBindings& aBindings ) const
+{
+ try
+ {
+ store::NsBindings lBindings;
+ theCtx->get_namespace_bindings(lBindings);
+ aBindings.reserve(aBindings.size() + lBindings.size());
+
+ for (store::NsBindings::const_iterator lIter = lBindings.begin();
+ lIter != lBindings.end(); ++lIter)
+ {
+ aBindings.push_back(
+ std::pair<zorba::String, zorba::String>(
+ Unmarshaller::newString(lIter->first),
+ Unmarshaller::newString(lIter->second)
+ )
+ );
+ }
+ }
+ catch (ZorbaException const& e)
+ {
+ ZorbaImpl::notifyError(theDiagnosticHandler, e);
+ }
+ catch (std::exception const& e)
+ {
+ ZorbaImpl::notifyError(theDiagnosticHandler, e.what());
+ }
+}
/*******************************************************************************
********************************************************************************/
bool
-StaticContextImpl::setDefaultElementAndTypeNamespace( const String& aURI )
+StaticContextImpl::setDefaultElementAndTypeNamespace(const String& aURI)
{
ZORBA_TRY
const zstring& lURI = Unmarshaller::getInternalString(aURI);
- QueryLoc loc;
- theCtx->set_default_elem_type_ns(lURI, loc);
+ theCtx->set_default_elem_type_ns(lURI, false, QueryLoc::null);
return true;
ZORBA_CATCH
return false;
@@ -233,7 +267,7 @@
********************************************************************************/
String
-StaticContextImpl::getDefaultElementAndTypeNamespace( ) const
+StaticContextImpl::getDefaultElementAndTypeNamespace() const
{
try
{
@@ -255,12 +289,12 @@
********************************************************************************/
bool
-StaticContextImpl::setDefaultFunctionNamespace( const String& aURI )
+StaticContextImpl::setDefaultFunctionNamespace(const String& aURI)
{
ZORBA_TRY
const zstring& lURI = Unmarshaller::getInternalString(aURI);
QueryLoc loc;
- theCtx->set_default_function_ns(lURI, loc);
+ theCtx->set_default_function_ns(lURI, false, loc);
return true;
ZORBA_CATCH
return false;
@@ -749,34 +783,6 @@
return TypeOps::get_type_identifier(theCtx->get_typemanager(), *xqType);
}
-
-#ifndef ZORBA_NO_FULL_TEXT
-/*******************************************************************************
-
-********************************************************************************/
-
-void StaticContextImpl::addThesaurusProvider( ThesaurusProvider const *p ) {
- if ( !theThesaurusProviders[ p ] ) {
- internal::ThesaurusProviderWrapper *const w =
- new internal::ThesaurusProviderWrapper( p );
- theThesaurusProviders[ p ] = w;
- theCtx->add_thesaurus_provider( w );
- }
-}
-
-void StaticContextImpl::removeThesaurusProvider( ThesaurusProvider const *p ) {
- thesaurus_providers_t::iterator const i = theThesaurusProviders.find( p );
- if ( i != theThesaurusProviders.end() ) {
- internal::ThesaurusProviderWrapper const *const w = i->second;
- theThesaurusProviders.erase( i );
- theCtx->remove_thesaurus_provider( w );
- delete w;
- }
-}
-
-#endif /* ZORBA_NO_FULL_TEXT */
-
-
/*******************************************************************************
********************************************************************************/
@@ -861,7 +867,7 @@
try
{
for (unsigned int i = 0; i < ann_list->size(); i++)
- aAnnotations.push_back(new AnnotationImpl(ann_list->getAnnotation(i)));
+ aAnnotations.push_back(new AnnotationImpl(ann_list->get(i)));
}
catch (ZorbaException const& e)
{
@@ -874,7 +880,8 @@
StaticContextImpl::setContextItemStaticType(TypeIdentifier_t type)
{
xqtref_t xqType = NULL;
- if (type != NULL) {
+ if (type != NULL)
+ {
xqType = theCtx->get_typemanager()->create_type(*type);
}
theCtx->set_context_item_type(xqType);
@@ -963,50 +970,151 @@
theSctxMap = impl.theCompilerCB->theSctxMap;
}
-
-void StaticContextImpl::setModulePaths(const std::vector<String>& aModulePaths)
+static void
+toInternalPath(const std::vector<String>& aPublicStrings,
+ std::vector<zstring>& aInternalStrings)
{
- try
+ for (std::vector<String>::const_iterator lIter = aPublicStrings.begin();
+ lIter != aPublicStrings.end(); ++lIter)
{
- std::vector<zstring> lModulePaths;
-
- for (std::vector<String>::const_iterator lIter = aModulePaths.begin();
- lIter != aModulePaths.end(); ++lIter)
+ if (lIter->length() != 0)
{
- if (lIter->length() != 0)
+ aInternalStrings.push_back(Unmarshaller::getInternalString(*lIter).c_str());
+ zstring& lPath = aInternalStrings.back();
+ if (lPath[lPath.length() - 1] != *filesystem_path::get_directory_separator())
{
- lModulePaths.push_back(Unmarshaller::getInternalString(*lIter).c_str());
- zstring& lPath = lModulePaths.back();
- if (lPath.rfind(filesystem_path::get_directory_separator()) != std::string::npos)
- {
- lPath.append(filesystem_path::get_directory_separator());
- }
+ lPath.append(filesystem_path::get_directory_separator());
}
-
}
-
- theCtx->set_module_paths(lModulePaths);
- }
- catch (ZorbaException const& e)
- {
- ZorbaImpl::notifyError(theDiagnosticHandler, e);
- }
-}
-
+ }
+}
+
+static void
+toPublicPath(const std::vector<zstring>& aInternalStrings,
+ std::vector<String>& aPublicStrings)
+{
+ for (std::vector<zstring>::const_iterator lIter = aInternalStrings.begin();
+ lIter != aInternalStrings.end(); ++lIter)
+ {
+ aPublicStrings.push_back(lIter->c_str());
+ }
+}
+
+void
+StaticContextImpl::setURIPath(const std::vector<String> &aURIPath)
+{
+ try
+ {
+ std::vector<zstring> lInternalURIPath;
+ toInternalPath(aURIPath, lInternalURIPath);
+ theCtx->set_uri_path(lInternalURIPath);
+ }
+ catch (ZorbaException const& e)
+ {
+ ZorbaImpl::notifyError(theDiagnosticHandler, e);
+ }
+}
+
+void
+StaticContextImpl::getURIPath(std::vector<String> &aURIPath) const
+{
+ try
+ {
+ std::vector<zstring> lInternalURIPath;
+ theCtx->get_uri_path(lInternalURIPath);
+ toPublicPath(lInternalURIPath, aURIPath);
+ }
+ catch (ZorbaException const& e)
+ {
+ ZorbaImpl::notifyError(theDiagnosticHandler, e);
+ }
+}
+
+void
+StaticContextImpl::getFullURIPath(std::vector<String> &aURIPath) const
+{
+ try
+ {
+ std::vector<zstring> lInternalURIPath;
+ theCtx->get_full_uri_path(lInternalURIPath);
+ toPublicPath(lInternalURIPath, aURIPath);
+ }
+ catch (ZorbaException const& e)
+ {
+ ZorbaImpl::notifyError(theDiagnosticHandler, e);
+ }
+}
+
+void
+StaticContextImpl::setLibPath(const std::vector<String> &aLibPath)
+{
+ try
+ {
+ std::vector<zstring> lInternalLibPath;
+ toInternalPath(aLibPath, lInternalLibPath);
+ theCtx->set_lib_path(lInternalLibPath);
+ }
+ catch (ZorbaException const& e)
+ {
+ ZorbaImpl::notifyError(theDiagnosticHandler, e);
+ }
+}
+
+void
+StaticContextImpl::getLibPath(std::vector<String> &aLibPath) const
+{
+ try
+ {
+ std::vector<zstring> lInternalLibPath;
+ theCtx->get_lib_path(lInternalLibPath);
+ toPublicPath(lInternalLibPath, aLibPath);
+ }
+ catch (ZorbaException const& e)
+ {
+ ZorbaImpl::notifyError(theDiagnosticHandler, e);
+ }
+}
+
+void
+StaticContextImpl::getFullLibPath(std::vector<String> &aLibPath) const
+{
+ try
+ {
+ std::vector<zstring> lInternalLibPath;
+ theCtx->get_full_lib_path(lInternalLibPath);
+ toPublicPath(lInternalLibPath, aLibPath);
+ }
+ catch (ZorbaException const& e)
+ {
+ ZorbaImpl::notifyError(theDiagnosticHandler, e);
+ }
+}
+
+void StaticContextImpl::setModulePaths(const std::vector<String>& aModulePaths)
+{
+ try
+ {
+ std::vector<zstring> lInternalModulePath;
+ toInternalPath(aModulePaths, lInternalModulePath);
+ theCtx->set_lib_path(lInternalModulePath);
+ theCtx->set_uri_path(lInternalModulePath);
+ }
+ catch (ZorbaException const& e)
+ {
+ ZorbaImpl::notifyError(theDiagnosticHandler, e);
+ }
+}
void StaticContextImpl::getModulePaths(std::vector<String>& aModulePaths) const
{
try
{
- std::vector<zstring> lModulePaths;
-
- theCtx->get_module_paths(lModulePaths);
-
- for (std::vector<zstring>::const_iterator lIter = lModulePaths.begin();
- lIter != lModulePaths.end(); ++lIter)
- {
- aModulePaths.push_back(lIter->c_str());
- }
+ std::vector<zstring> lInternalModulePath;
+ theCtx->get_lib_path(lInternalModulePath);
+ toPublicPath(lInternalModulePath, aModulePaths);
+ lInternalModulePath.clear();
+ theCtx->get_uri_path(lInternalModulePath);
+ toPublicPath(lInternalModulePath, aModulePaths);
}
catch (ZorbaException const& e)
{
@@ -1020,15 +1128,12 @@
{
try
{
- std::vector<zstring> lFullModulePaths;
-
- theCtx->get_full_module_paths(lFullModulePaths);
-
- for (std::vector<zstring>::const_iterator lIter = lFullModulePaths.begin();
- lIter != lFullModulePaths.end(); ++lIter)
- {
- aFullModulePaths.push_back(lIter->c_str());
- }
+ std::vector<zstring> lInternalModulePath;
+ theCtx->get_full_lib_path(lInternalModulePath);
+ toPublicPath(lInternalModulePath, aFullModulePaths);
+ lInternalModulePath.clear();
+ theCtx->get_full_uri_path(lInternalModulePath);
+ toPublicPath(lInternalModulePath, aFullModulePaths);
}
catch (ZorbaException const& e)
{
@@ -1351,10 +1456,32 @@
audit::Event*
-StaticContextImpl::getAuditEvent()
+StaticContextImpl::getAuditEvent() const
{
return theCtx->get_audit_event();
}
+
+void
+StaticContextImpl::getExternalVariables(Iterator_t& aVarsIter) const
+{
+ ZORBA_TRY
+ std::vector<var_expr_t> lVars;
+ theCtx->getVariables(lVars, true, false, true);
+
+ std::vector<var_expr_t>::const_iterator lIte = lVars.begin();
+ std::vector<var_expr_t>::const_iterator lEnd = lVars.end();
+ std::vector<store::Item_t> lExVars;
+
+ for (; lIte != lEnd; ++lIte)
+ {
+ lExVars.push_back(lIte->getp()->get_name());
+ }
+
+ Iterator_t vIter = new VectorIterator(lExVars, theDiagnosticHandler);
+ aVarsIter = vIter;
+ ZORBA_CATCH
+}
+
} /* namespace zorba */
/* vim:set et sw=2 ts=2: */
=== modified file 'src/api/staticcontextimpl.h'
--- src/api/staticcontextimpl.h 2011-08-31 13:17:59 +0000
+++ src/api/staticcontextimpl.h 2012-01-25 00:12:28 +0000
@@ -30,11 +30,6 @@
class DiagnosticHandler;
class StaticCollectionManagerImpl;
class static_context;
-#ifndef ZORBA_NO_FULL_TEXT
- namespace internal {
- class ThesaurusProviderWrapper;
- }
-#endif /* ZORBA_NO_FULL_TEXT */
/*******************************************************************************
@@ -62,14 +57,6 @@
DiagnosticHandler * theDiagnosticHandler;
bool theUserDiagnosticHandler;
-#ifndef ZORBA_NO_FULL_TEXT
- typedef std::map<ThesaurusProvider const*,
- internal::ThesaurusProviderWrapper const*>
- thesaurus_providers_t;
-
- thesaurus_providers_t theThesaurusProviders;
-#endif /* ZORBA_NO_FULL_TEXT */
-
// allow for lazy creation
mutable StaticCollectionManagerImpl* theCollectionMgr;
@@ -91,6 +78,9 @@
String getNamespaceURIByPrefix( const String& prefix ) const;
+ void
+ getNamespaceBindings( NsBindings& aBindings ) const;
+
bool setDefaultElementAndTypeNamespace( const String& URI );
String getDefaultElementAndTypeNamespace( ) const;
@@ -186,14 +176,6 @@
virtual TypeIdentifier_t
getCollectionType(const String& aCollectionUri) const;
-#ifndef ZORBA_NO_FULL_TEXT
- virtual void
- addThesaurusProvider( ThesaurusProvider const* );
-
- virtual void
- removeThesaurusProvider( ThesaurusProvider const* );
-#endif /* ZORBA_NO_FULL_TEXT */
-
virtual bool
containsFunction(const String& aFnNameUri, const String& aFnNameLocal, int arity) const;
@@ -265,9 +247,30 @@
virtual void
setAuditEvent(audit::Event* anEvent);
-
+
virtual audit::Event*
- getAuditEvent();
+ getAuditEvent() const;
+
+ virtual void
+ getExternalVariables(Iterator_t& aVarsIter) const;
+
+ virtual void
+ setURIPath(const std::vector<String>& aURIPath);
+
+ virtual void
+ getURIPath(std::vector<String>& aURIPath) const;
+
+ virtual void
+ getFullURIPath(std::vector<String>& aURIPath) const;
+
+ virtual void
+ setLibPath(const std::vector<String>& aLibPath);
+
+ virtual void
+ getLibPath(std::vector<String>& aLibPath) const;
+
+ virtual void
+ getFullLibPath(std::vector<String>& aLibPath) const;
protected:
String
=== modified file 'src/api/stemmer_wrapper.cpp'
--- src/api/stemmer_wrapper.cpp 2011-08-25 15:54:19 +0000
+++ src/api/stemmer_wrapper.cpp 2012-01-25 00:12:28 +0000
@@ -42,6 +42,12 @@
api_stemmer_.release()->destroy();
}
+void StemmerWrapper::properties( Properties *p ) const {
+ zorba::Stemmer::Properties api_p;
+ api_stemmer_->properties( &api_p );
+ p->uri = api_p.uri;
+}
+
void StemmerWrapper::stem( zstring const &word, iso639_1::type lang,
zstring *result ) const {
String const api_word( Unmarshaller::newString( word ) );
=== modified file 'src/api/stemmer_wrapper.h'
--- src/api/stemmer_wrapper.h 2011-08-30 19:11:59 +0000
+++ src/api/stemmer_wrapper.h 2012-01-25 00:12:28 +0000
@@ -35,6 +35,7 @@
// inherited
void destroy() const;
+ void properties( Properties* ) const;
void stem( zstring const &word, locale::iso639_1::type lang,
zstring *result ) const;
private:
=== modified file 'src/api/thesaurus.cpp'
--- src/api/thesaurus.cpp 2011-09-07 20:08:18 +0000
+++ src/api/thesaurus.cpp 2012-01-25 00:12:28 +0000
@@ -29,10 +29,6 @@
// // out-of-line since it's virtual
//}
-ThesaurusProvider::~ThesaurusProvider() {
- // out-of-line since it's virtual
-}
-
///////////////////////////////////////////////////////////////////////////////
} // namespace zorba
=== modified file 'src/api/uri_resolver_wrappers.cpp'
--- src/api/uri_resolver_wrappers.cpp 2011-07-22 07:23:17 +0000
+++ src/api/uri_resolver_wrappers.cpp 2012-01-25 00:12:28 +0000
@@ -18,28 +18,45 @@
#include "uri_resolver_wrappers.h"
#include "uriresolverimpl.h"
#include "unmarshaller.h"
+#include <zorba/thesaurus.h>
+#include <runtime/full_text/thesaurus.h>
+#include <context/thesaurus_wrappers.h>
namespace zorba
{
-
+ // "Convenience" class for passing an internal EntityData object to
+ // external mappers/resolvers. This can serve as a plain EntityData or
+ // a ThesaurusEntityData. However, when there's another EntityData subclass
+ // in future, this won't work as EntityData becomes an ambiguous base class...
+#ifndef ZORBA_NO_FULL_TEXT
+ class EntityDataWrapper : public ThesaurusEntityData
+#else
class EntityDataWrapper : public EntityData
+#endif /* ZORBA_NO_FULL_TEXT */
{
public:
- static EntityDataWrapper const* create(impl::EntityData::Kind aKind) {
+ static EntityDataWrapper const* create(internal::EntityData const* aData) {
// More ugly: Create a public-API EntityData with the same Entity Kind,
// but only if it's one of the publicly-supported kinds
- switch (aKind) {
- case impl::EntityData::MODULE:
+ switch (aData->getKind()) {
+ case internal::EntityData::MODULE:
return new EntityDataWrapper(EntityData::MODULE);
- case impl::EntityData::SCHEMA:
+ case internal::EntityData::SCHEMA:
return new EntityDataWrapper(EntityData::SCHEMA);
- case impl::EntityData::THESAURUS:
- return new EntityDataWrapper(EntityData::THESAURUS);
- case impl::EntityData::STOP_WORDS:
+#ifndef ZORBA_NO_FULL_TEXT
+ case internal::EntityData::THESAURUS:
+ {
+ EntityDataWrapper* retval = new EntityDataWrapper(EntityData::THESAURUS);
+ retval->theThesaurusLang =
+ dynamic_cast<const internal::ThesaurusEntityData*>(aData)->getLanguage();
+ return retval;
+ }
+ case internal::EntityData::STOP_WORDS:
return new EntityDataWrapper(EntityData::STOP_WORDS);
- case impl::EntityData::COLLECTION:
+#endif /* ZORBA_NO_FULL_TEXT */
+ case internal::EntityData::COLLECTION:
return new EntityDataWrapper(EntityData::COLLECTION);
- case impl::EntityData::DOCUMENT:
+ case internal::EntityData::DOCUMENT:
return new EntityDataWrapper(EntityData::DOCUMENT);
default:
return NULL;
@@ -50,12 +67,21 @@
return theKind;
}
+#ifndef ZORBA_NO_FULL_TEXT
+ virtual zorba::locale::iso639_1::type getLanguage() const {
+ return theThesaurusLang;
+ }
+#endif /* ZORBA_NO_FULL_TEXT */
+
private:
EntityDataWrapper(EntityData::Kind aKind)
: theKind(aKind)
{}
EntityData::Kind const theKind;
+#ifndef ZORBA_NO_FULL_TEXT
+ zorba::locale::iso639_1::type theThesaurusLang;
+#endif /* ZORBA_NO_FULL_TEXT */
};
URIMapperWrapper::URIMapperWrapper(zorba::URIMapper& aUserMapper)
@@ -68,40 +94,40 @@
void
URIMapperWrapper::mapURI
(const zstring& aUri,
- impl::EntityData const* aEntityData,
+ internal::EntityData const* aEntityData,
static_context const& aSctx,
std::vector<zstring>& oUris)
{
std::auto_ptr<const EntityDataWrapper> lDataWrap
- (EntityDataWrapper::create(aEntityData->getKind()));
+ (EntityDataWrapper::create(aEntityData));
if (lDataWrap.get() == NULL) {
return;
}
std::vector<zorba::String> lUserUris;
// QQQ should public API have a StaticContext on it?
- theUserMapper.mapURI(zorba::String(aUri.c_str()),
- lDataWrap.get(), lUserUris);
+ theUserMapper.mapURI(zorba::String(aUri.c_str()), lDataWrap.get(),
+ lUserUris);
std::vector<zorba::String>::iterator iter;
for (iter = lUserUris.begin(); iter != lUserUris.end(); iter++) {
oUris.push_back(Unmarshaller::getInternalString(*iter));
}
}
- impl::URIMapper::Kind
+ internal::URIMapper::Kind
URIMapperWrapper::mapperKind()
{
// Still so ugly.
switch (theUserMapper.mapperKind()) {
case URIMapper::COMPONENT:
- return impl::URIMapper::COMPONENT;
+ return internal::URIMapper::COMPONENT;
case URIMapper::CANDIDATE:
- return impl::URIMapper::CANDIDATE;
+ return internal::URIMapper::CANDIDATE;
}
assert(false);
// dummy return
- return impl::URIMapper::COMPONENT;
+ return internal::URIMapper::COMPONENT;
}
@@ -112,40 +138,50 @@
URLResolverWrapper::~URLResolverWrapper()
{}
- impl::Resource*
+ internal::Resource*
URLResolverWrapper::resolveURL
(const zstring& aUrl,
- impl::EntityData const* aEntityData)
+ internal::EntityData const* aEntityData)
{
std::auto_ptr<const EntityDataWrapper> lDataWrap
- (EntityDataWrapper::create(aEntityData->getKind()));
+ (EntityDataWrapper::create(aEntityData));
if (lDataWrap.get() == NULL) {
return NULL;
}
- impl::StreamResource* lRetval = nullptr;
- // Get the user's Resource. It's OK to use an auto_ptr here for safety,
- // because the Resource will have been created by a factory method inside
- // libzorba (no cross-DLL memory allocation issue).
- std::auto_ptr<Resource> lUserPtr
+ internal::Resource* lRetval = nullptr;
+ // Get the user's Resource.
+ Resource::ptr lUserPtr
(theUserResolver.resolveURL(zorba::String(aUrl.c_str()),
lDataWrap.get()));
if (lUserPtr.get() != NULL) {
- // This will get a bit more complicated when we publicly support more than
- // one kind of Resource subclass.
+ // Sooo ugly... have to try down-casting to each subclass in turn to
+ // figure out what kind of Resource we've got.
StreamResourceImpl* lUserStream =
dynamic_cast<StreamResourceImpl*>(lUserPtr.get());
if (lUserStream != NULL) {
// Here we pass memory ownership of the std::istream to the internal
// StreamResource, by passing the StreamReleaser to it and setting the
// user's StreamResource's StreamReleaser to nullptr.
- lRetval = new impl::StreamResource(lUserStream->getStream(),
+ lRetval = new internal::StreamResource(lUserStream->getStream(),
lUserStream->getStreamReleaser());
lUserStream->setStreamReleaser(nullptr);
}
+#ifndef ZORBA_NO_FULL_TEXT
else {
- assert(false);
+ Thesaurus* lUserThesaurus = dynamic_cast<Thesaurus*>(lUserPtr.get());
+ if (lUserThesaurus != NULL) {
+ // Here we pass memory ownership of the actual Thesaurus to the
+ // internal ThesaurusWrapper.
+ lRetval = new internal::ThesaurusWrapper
+ (Thesaurus::ptr(lUserThesaurus));
+ lUserPtr.release();
+ }
+ else {
+ assert(false);
+ }
}
+#endif /* ZORBA_NO_FULL_TEXT */
}
return lRetval;
}
=== modified file 'src/api/uri_resolver_wrappers.h'
--- src/api/uri_resolver_wrappers.h 2011-07-12 20:15:01 +0000
+++ src/api/uri_resolver_wrappers.h 2012-01-25 00:12:28 +0000
@@ -37,7 +37,7 @@
namespace zorba {
-class URIMapperWrapper : public zorba::impl::URIMapper
+class URIMapperWrapper : public zorba::internal::URIMapper
{
public:
@@ -46,18 +46,18 @@
virtual ~URIMapperWrapper();
virtual void mapURI(const zstring& aUri,
- zorba::impl::EntityData const* aEntityData,
+ zorba::internal::EntityData const* aEntityData,
static_context const& aSctx,
std::vector<zstring>& oUris);
- virtual zorba::impl::URIMapper::Kind mapperKind();
+ virtual zorba::internal::URIMapper::Kind mapperKind();
private:
zorba::URIMapper& theUserMapper;
};
-class URLResolverWrapper : public zorba::impl::URLResolver
+class URLResolverWrapper : public zorba::internal::URLResolver
{
public:
@@ -65,8 +65,8 @@
virtual ~URLResolverWrapper();
- virtual zorba::impl::Resource* resolveURL(const zstring& aUrl,
- zorba::impl::EntityData const* aEntityData);
+ virtual zorba::internal::Resource* resolveURL(const zstring& aUrl,
+ zorba::internal::EntityData const* aEntityData);
private:
=== modified file 'src/api/uriresolverimpl.cpp'
--- src/api/uriresolverimpl.cpp 2011-08-17 15:48:35 +0000
+++ src/api/uriresolverimpl.cpp 2012-01-25 00:12:28 +0000
@@ -37,6 +37,11 @@
}
}
+ void StreamResourceImpl::destroy() const
+ {
+ delete this;
+ }
+
StreamResource* StreamResource::create(std::istream* aStream,
StreamReleaser aStreamReleaser)
{
=== modified file 'src/api/uriresolverimpl.h'
--- src/api/uriresolverimpl.h 2011-07-22 07:23:17 +0000
+++ src/api/uriresolverimpl.h 2012-01-25 00:12:28 +0000
@@ -37,6 +37,8 @@
virtual ~StreamResourceImpl();
+ virtual void destroy() const;
+
private:
StreamResourceImpl(std::istream* aStream, StreamReleaser aStreamReleaser);
=== modified file 'src/api/xmldatamanagerimpl.cpp'
--- src/api/xmldatamanagerimpl.cpp 2011-09-15 11:46:01 +0000
+++ src/api/xmldatamanagerimpl.cpp 2012-01-25 00:12:28 +0000
@@ -216,8 +216,7 @@
{
ZORBA_DM_TRY
{
- Item lQName = theFactory->createQName(static_context::W3C_FN_NS.c_str(),
- "parse-xml");
+ Item lQName = theFactory->createQName(static_context::W3C_FN_NS, "parse-xml");
// create a streamable string item
std::vector<ItemSequence_t> lArgs;
@@ -247,7 +246,7 @@
{
ZORBA_DM_TRY
{
- Item lQName = theFactory->createQName(static_context::W3C_FN_NS.c_str(),
+ Item lQName = theFactory->createQName(static_context::W3C_FN_NS,
"parse-xml");
// create a streamable string item
@@ -280,7 +279,7 @@
{
ZORBA_DM_TRY
{
- Item lQName = theFactory->createQName(static_context::ZORBA_XML_FN_NS.c_str(),
+ Item lQName = theFactory->createQName(static_context::ZORBA_XML_FN_NS,
"parse-xml-fragment");
// create a streamable string item
@@ -315,7 +314,7 @@
{
ZORBA_DM_TRY
{
- Item lQName = theFactory->createQName(static_context::ZORBA_XML_FN_NS.c_str(),
+ Item lQName = theFactory->createQName(static_context::ZORBA_XML_FN_NS,
"parse-xml-fragment");
// create a streamable string item
@@ -349,7 +348,7 @@
{
ZORBA_DM_TRY
{
- Item lQName = theFactory->createQName(static_context::ZORBA_FETCH_FN_NS.c_str(),
+ Item lQName = theFactory->createQName(static_context::ZORBA_FETCH_FN_NS,
"content");
// create a streamable string item
=== modified file 'src/api/xqueryimpl.cpp'
--- src/api/xqueryimpl.cpp 2011-09-14 11:08:52 +0000
+++ src/api/xqueryimpl.cpp 2012-01-25 00:12:28 +0000
@@ -46,6 +46,7 @@
#include "api/serializerimpl.h"
#include "api/auditimpl.h"
#include "api/staticcollectionmanagerimpl.h"
+#include "api/vectoriterator.h"
#include "context/static_context.h"
#include "context/dynamic_context.h"
@@ -54,6 +55,7 @@
#include "compiler/api/compiler_api.h"
#include "compiler/api/compilercb.h"
+#include "compiler/expression/var_expr.h"
#include "runtime/base/plan_iterator.h"
#include "runtime/api/plan_wrapper.h"
@@ -61,8 +63,10 @@
#include "runtime/visitors/printer_visitor_api.h"
#include "runtime/util/flowctl_exception.h"
+#include "store/api/temp_seq.h"
#include "store/api/item.h"
#include "store/api/store.h"
+#include "store/api/item_factory.h"
#include "zorbaserialization/xml_archiver.h"
#include "zorbaserialization/bin_archiver.h"
@@ -554,6 +558,7 @@
// Set the compiler config.
// If lib_module is set to true the query will be considered a library module
theCompilerCB->theConfig.lib_module = aHints.lib_module;
+ theCompilerCB->theConfig.for_serialization_only = aHints.for_serialization_only;
CompilerCB::config::opt_level_t optLevel;
if (aHints.opt_level == ZORBA_OPT_LEVEL_O0)
optLevel = CompilerCB::config::O0;
@@ -567,10 +572,10 @@
#ifdef ZORBA_WITH_DEBUGGER
// if the debug mode is set, we force the gflwor, we set the query input stream
- if (theIsDebugMode) {
+ if (theIsDebugMode)
+ {
theCompilerCB->theConfig.force_gflwor = true;
- theCompilerCB->theDebuggerCommons =
- new DebuggerCommons(theCompilerCB->theRootSctx);
+ theCompilerCB->theDebuggerCommons = new DebuggerCommons(theCompilerCB->theRootSctx);
theCompilerCB->theConfig.opt_level = CompilerCB::config::O0;
}
#endif
@@ -729,6 +734,97 @@
/*******************************************************************************
+
+********************************************************************************/
+void XQueryImpl::getExternalVariables(Iterator_t& aVarsIter) const
+{
+ try
+ {
+ checkNotClosed();
+ checkCompiled();
+
+ std::vector<var_expr_t> lVars;
+
+ std::map<short, static_context_t>::const_iterator lIte =
+ theCompilerCB->theSctxMap.begin();
+
+ std::map<short, static_context_t>::const_iterator lEnd =
+ theCompilerCB->theSctxMap.end();
+
+ for(; lIte != lEnd; ++lIte)
+ {
+ lIte->second.getp()->getVariables(lVars, false, false, true);
+ }
+
+ std::vector<var_expr_t>::const_iterator lVarIte = lVars.begin();
+ std::vector<var_expr_t>::const_iterator lVarEnd = lVars.end();
+ std::vector<store::Item_t> lExVars;
+
+ for(; lVarIte != lVarEnd; ++lVarIte)
+ {
+ lExVars.push_back((*lVarIte)->get_name());
+ }
+
+ Iterator_t vIter = new VectorIterator(lExVars, theDiagnosticHandler);
+
+ aVarsIter = vIter;
+
+ }
+ QUERY_CATCH
+}
+
+/*******************************************************************************
+
+********************************************************************************/
+bool XQueryImpl::isBoundVariable(
+ const String& aNamespace,
+ const String& aLocalname) const
+{
+ try
+ {
+ checkNotClosed();
+ checkCompiled();
+
+ var_expr* var = NULL;
+
+ zstring& nameSpace = Unmarshaller::getInternalString(aNamespace);
+ zstring& localName = Unmarshaller::getInternalString(aLocalname);
+
+ store::Item_t qname;
+ GENV_ITEMFACTORY->createQName(qname, nameSpace, zstring(), localName);
+
+ std::map<short, static_context_t>& lMap = theCompilerCB->theSctxMap;
+ std::map<short, static_context_t>::const_iterator lIte = lMap.begin();
+ std::map<short, static_context_t>::const_iterator lEnd = lMap.end();
+
+ for (; lIte != lEnd; ++lIte)
+ {
+ var = lIte->second->lookup_var(qname, QueryLoc::null, zerr::ZXQP0000_NO_ERROR);
+
+ if(var)
+ break;
+ }
+
+ if(var == NULL)
+ throw XQUERY_EXCEPTION(zerr::ZAPI0011_ELEMENT_NOT_DECLARED,
+ ERROR_PARAMS(BUILD_STRING('{', qname->getNamespace(), '}', qname->getLocalName()), ZED(Variable)));
+
+ if (var->hasInitializer())
+ return true;
+
+ ulong varId = var->get_unique_id();
+
+ if (theDynamicContext->is_set_variable(varId))
+ return true;
+
+ return false;
+ }
+ QUERY_CATCH
+ return true;
+}
+
+
+/*******************************************************************************
Give to the caller read-only access to the static context of the query
********************************************************************************/
const StaticContext* XQueryImpl::getStaticContext() const
@@ -771,6 +867,25 @@
/*******************************************************************************
+ Return true, if the root expr of the query is a sequential expr.
+********************************************************************************/
+bool XQueryImpl::isSequential() const
+{
+ SYNC_CODE(AutoMutex lock(&theMutex);)
+
+ try
+ {
+ checkNotClosed();
+ checkCompiled();
+
+ return theCompilerCB->isSequential();
+ }
+ QUERY_CATCH
+ return false;
+}
+
+
+/*******************************************************************************
Serialize the execution plan inot the given output stream.
********************************************************************************/
bool XQueryImpl::saveExecutionPlan(
@@ -868,7 +983,6 @@
}
-
/*******************************************************************************
Note: this method is allowed to be called while the query is executing.
This is required to invoke external function that need access to the dynamic
=== modified file 'src/api/xqueryimpl.h'
--- src/api/xqueryimpl.h 2011-09-14 11:08:52 +0000
+++ src/api/xqueryimpl.h 2012-01-25 00:12:28 +0000
@@ -284,7 +284,11 @@
const StaticContext* getStaticContext() const;
+ void getExternalVariables(Iterator_t& aVarsIter) const;
+
bool isUpdating() const;
+
+ bool isSequential() const;
bool saveExecutionPlan(
std::ostream& os,
@@ -393,6 +397,8 @@
#endif
void notifyAllWarnings() const;
+
+ bool isBoundVariable(const String& aNamespace, const String& aLocalname) const;
};
=== modified file 'src/api/zorbaimpl.cpp'
--- src/api/zorbaimpl.cpp 2011-07-13 01:56:45 +0000
+++ src/api/zorbaimpl.cpp 2012-01-25 00:12:28 +0000
@@ -98,7 +98,7 @@
{
void* store2 = StoreManager::getStore();
(void)store2;
- assert(store == NULL || store2 == store);
+ assert(store2 == store);
GlobalEnvironment::init(store);
}
=== modified file 'src/compiler/api/compiler_api.cpp'
--- src/compiler/api/compiler_api.cpp 2011-08-19 23:22:48 +0000
+++ src/compiler/api/compiler_api.cpp 2012-01-25 00:12:28 +0000
@@ -236,15 +236,19 @@
audit::ScopedRecord& aAuditRecord)
{
{
- zorba::time::Timer lTimer;
- zorba::audit::DurationAuditor durationAudit(
- aAuditRecord, zorba::audit::XQUERY_COMPILATION_TRANSLATION_DURATION, lTimer);
+ time::Timer lTimer;
+ audit::DurationAuditor durationAudit(aAuditRecord,
+ audit::XQUERY_COMPILATION_TRANSLATION_DURATION,
+ lTimer);
+
rootExpr = normalize(ast); // also does the translation
}
{
- zorba::time::Timer lTimer;
- zorba::audit::DurationAuditor durationAudit(
- aAuditRecord, zorba::audit::XQUERY_COMPILATION_OPTIMIZATION_DURATION, lTimer);
+ time::Timer lTimer;
+ audit::DurationAuditor durationAudit(aAuditRecord,
+ audit::XQUERY_COMPILATION_OPTIMIZATION_DURATION,
+ lTimer);
+
rootExpr = optimize(rootExpr);
}
@@ -254,9 +258,11 @@
PlanIter_t plan;
{
- zorba::time::Timer lTimer;
- zorba::audit::DurationAuditor durationAudit(
- aAuditRecord, zorba::audit::XQUERY_COMPILATION_CODEGENERATION_DURATION, lTimer);
+ time::Timer lTimer;
+ audit::DurationAuditor durationAudit(aAuditRecord,
+ audit::XQUERY_COMPILATION_CODEGENERATION_DURATION,
+ lTimer);
+
plan = codegen("main query", rootExpr, theCompilerCB, nextDynamicVarId);
}
@@ -328,7 +334,7 @@
"stream URL" hack in StreamResource - this is the only place in the code where
we use the two-arg StreamResource constructor.
*******************************************************************************/
-class FakeLibraryModuleURLResolver : public impl::URLResolver
+class FakeLibraryModuleURLResolver : public internal::URLResolver
{
public:
FakeLibraryModuleURLResolver
@@ -341,8 +347,8 @@
virtual ~FakeLibraryModuleURLResolver()
{}
- virtual impl::Resource* resolveURL
- (zstring const& aUrl, impl::EntityData const* aEntityData)
+ virtual internal::Resource* resolveURL
+ (zstring const& aUrl, internal::EntityData const* aEntityData)
{
if (aUrl != theLibraryModuleNamespace) {
return NULL;
@@ -351,7 +357,7 @@
// Pass a nullptr StreamReleaser; memory ownership of the istream remains
// with the caller of this method.
// QQQ We can remove this third argument when we can compile modules individually
- return new impl::StreamResource(&theStream, nullptr,
+ return new internal::StreamResource(&theStream, nullptr,
theLibraryModuleFilename);
}
=== modified file 'src/compiler/api/compiler_api.h'
--- src/compiler/api/compiler_api.h 2011-07-12 20:15:01 +0000
+++ src/compiler/api/compiler_api.h 2012-01-25 00:12:28 +0000
@@ -32,6 +32,7 @@
CompilerCB * theCompilerCB;
+public:
XQueryCompiler(CompilerCB* aCompilerCB);
virtual ~XQueryCompiler();
@@ -85,14 +86,14 @@
{
friend class GlobalEnvironment;
- public:
+public:
XQueryCompilerSubsystem();
virtual ~XQueryCompilerSubsystem();
virtual Rewriter* getDefaultOptimizingRewriter() = 0;
- private:
+private:
static std::auto_ptr<XQueryCompilerSubsystem> create();
};
=== modified file 'src/compiler/api/compilercb.cpp'
--- src/compiler/api/compilercb.cpp 2011-06-14 17:26:33 +0000
+++ src/compiler/api/compilercb.cpp 2012-01-25 00:12:28 +0000
@@ -60,6 +60,7 @@
:
opt_level(O1),
lib_module(false),
+ for_serialization_only(false),
parse_cb(NULL)
{
translate_cb = optimize_cb = NULL;
@@ -97,6 +98,7 @@
ar & force_gflwor;
SERIALIZE_ENUM(opt_level_t, opt_level);
ar & lib_module;
+ ar & for_serialization_only;
ar & print_item_flow;
}
@@ -114,6 +116,7 @@
theIsEval(false),
theIsLoadProlog(false),
theIsUpdating(false),
+ theIsSequential(false),
theTimeout(timeout),
theTempIndexCounter(0)
{
@@ -135,6 +138,7 @@
theIsEval(false),
theIsLoadProlog(false),
theIsUpdating(false),
+ theIsSequential(false),
theTimeout(cb.theTimeout),
theTempIndexCounter(0),
theConfig(cb.theConfig)
=== modified file 'src/compiler/api/compilercb.h'
--- src/compiler/api/compilercb.h 2011-06-14 17:26:33 +0000
+++ src/compiler/api/compilercb.h 2012-01-25 00:12:28 +0000
@@ -93,6 +93,9 @@
dummy module (see XQueryCompiler::createMainModule() method). This flag is
a copy of the lib_module flag in Zorba_CompilerHints_t.
+ - theConfig.for_serialization_only :
+ This flag is a copy of the for_serialization_only flag in Zorba_CompilerHints_t.
+
- theConfig.parse_cb :
Pointer to the function to call to print the AST that results from parsing
the query.
@@ -120,6 +123,7 @@
bool force_gflwor;
opt_level_t opt_level;
bool lib_module;
+ bool for_serialization_only;
ast_callback parse_cb;
expr_callback translate_cb;
expr_callback optimize_cb;
@@ -139,11 +143,11 @@
typedef std::map<short, static_context_t> SctxMap;
public:
- XQueryDiagnostics* theXQueryDiagnostics;
+ XQueryDiagnostics * theXQueryDiagnostics;
SctxMap theSctxMap;
- static_context* theRootSctx;
+ static_context * theRootSctx;
#ifdef ZORBA_WITH_DEBUGGER
DebuggerCommons* theDebuggerCommons;
@@ -155,6 +159,8 @@
bool theIsUpdating;
+ bool theIsSequential;
+
long theTimeout;
ulong theTempIndexCounter;
@@ -181,6 +187,10 @@
bool isUpdating() const { return theIsUpdating; }
+ void setIsSequential(bool aIsSequential) {theIsSequential = aIsSequential;}
+
+ bool isSequential() const { return theIsSequential;}
+
static_context* getStaticContext(short id);
};
=== modified file 'src/compiler/codegen/plan_visitor.cpp'
--- src/compiler/codegen/plan_visitor.cpp 2011-09-16 19:36:18 +0000
+++ src/compiler/codegen/plan_visitor.cpp 2012-01-25 00:12:28 +0000
@@ -98,6 +98,7 @@
#endif
#include "functions/function.h"
+#include "functions/udf.h"
#include "functions/library.h"
#include "types/typeops.h"
@@ -199,7 +200,10 @@
/*******************************************************************************
-
+ A FlworClauseVarMap is created for each flwor clause that defines variables.
+ If M is such a clause, then for each variable Vi defined by M, theVarExprs[i]
+ and theVarRebinds[i] contain an entry for Vi. theVarExprs[i] contains the
+ var_expr representing the Vi definition.
********************************************************************************/
class FlworClauseVarMap : public SimpleRCObject
{
@@ -207,7 +211,7 @@
bool theIsGeneral;
const flwor_clause * theClause;
- std::vector<const var_expr*> theVarExprs;
+ std::vector<var_expr*> theVarExprs;
std::vector<VarRebind_t> theVarRebinds;
public:
@@ -222,8 +226,8 @@
long find_var(const var_expr* var) const
{
- ulong numVars = (ulong)theVarExprs.size();
- for (ulong i = 0; i < numVars; ++i)
+ csize numVars = theVarExprs.size();
+ for (csize i = 0; i < numVars; ++i)
{
if (theVarExprs[i] == var)
return i;
@@ -322,6 +326,7 @@
std::stack<expr*> theConstructorsStack;
std::stack<EnclosedExprContext> theEnclosedContextStack;
+ std::stack<bool> theCopyNodesStack;
ulong theNextDynamicVarId;
@@ -633,6 +638,41 @@
}
+/***************************************************************************//**
+
+********************************************************************************/
+bool begin_visit(var_set_expr& v)
+{
+ CODEGEN_TRACE_IN("");
+ return true;
+}
+
+
+void end_visit(var_set_expr& v)
+{
+ CODEGEN_TRACE_OUT("");
+
+ const var_expr* varExpr = v.get_var_expr();
+
+ xqtref_t exprType = v.get_expr()->get_return_type();
+
+ PlanIter_t exprIter = pop_itstack();
+
+ CtxVarAssignIterator* iter =
+ new CtxVarAssignIterator(sctx,
+ qloc,
+ varExpr->get_unique_id(),
+ varExpr->get_name(),
+ (varExpr->get_kind() == var_expr::local_var),
+ exprIter);
+
+ if (exprType->get_quantifier() == TypeConstants::QUANT_ONE)
+ iter->setSingleItem();
+
+ push_itstack(iter);
+}
+
+
/*******************************************************************************
VarRef expr
********************************************************************************/
@@ -759,7 +799,7 @@
{
varRebind = new VarRebind;
- clauseVarMap->theVarExprs.push_back(&var);
+ clauseVarMap->theVarExprs.push_back(const_cast<var_expr*>(&var));
clauseVarMap->theVarRebinds.push_back(varRebind);
varRebind->theInputVar = varIter;
@@ -1189,14 +1229,14 @@
const group_clause::rebind_list_t& grouping_vars = gbc->get_grouping_vars();
const group_clause::rebind_list_t& nongrouping_vars = gbc->get_nongrouping_vars();
- for (unsigned i = 0; i < grouping_vars.size(); i++)
+ for (unsigned i = 0; i < grouping_vars.size(); ++i)
{
VarRebind_t varRebind = new VarRebind;
clauseVarMap->theVarExprs.push_back(grouping_vars[i].second.getp());
clauseVarMap->theVarRebinds.push_back(varRebind);
}
- for (unsigned i = 0; i < nongrouping_vars.size(); i++)
+ for (unsigned i = 0; i < nongrouping_vars.size(); ++i)
{
VarRebind_t varRebind = new VarRebind;
clauseVarMap->theVarExprs.push_back(nongrouping_vars[i].second.getp());
@@ -1363,22 +1403,17 @@
xqtref_t colType = colExpr->get_return_type();
- if (TypeOps::is_subtype(tm, *colType, *rtm.STRING_TYPE_STAR, loc) ||
- TypeOps::is_subtype(tm, *colType, *rtm.DOUBLE_TYPE_STAR, loc) ||
- TypeOps::is_subtype(tm, *colType, *rtm.FLOAT_TYPE_STAR, loc) ||
- TypeOps::is_subtype(tm, *colType, *rtm.LONG_TYPE_STAR, loc) ||
- TypeOps::is_subtype(tm, *colType, *rtm.UNSIGNED_LONG_TYPE_STAR, loc) ||
- TypeOps::is_equal(tm,
- *TypeOps::prime_type(tm, *colType),
- *rtm.DECIMAL_TYPE_ONE,
- loc) ||
- TypeOps::is_equal(tm,
- *TypeOps::prime_type(tm, *colType),
- *rtm.INTEGER_TYPE_ONE,
- loc) ||
- TypeOps::is_subtype(tm, *colType, *rtm.DATE_TYPE_STAR, loc) ||
- TypeOps::is_subtype(tm, *colType, *rtm.TIME_TYPE_STAR, loc) ||
- TypeOps::is_subtype(tm, *colType, *rtm.DATETIME_TYPE_STAR, loc))
+ if (colType->type_kind() == XQType::NODE_TYPE_KIND)
+ {
+ colType = static_cast<const NodeXQType*>(colType.getp())->get_content_type();
+ }
+
+ if (colType != NULL &&
+ TypeOps::is_subtype(tm, *colType, *rtm.ANY_ATOMIC_TYPE_STAR, loc) &&
+ !TypeOps::is_equal(tm,
+ *TypeOps::prime_type(tm, *colType),
+ *rtm.ANY_ATOMIC_TYPE_ONE,
+ loc))
{
return true;
}
@@ -1669,7 +1704,7 @@
if (c.get_kind() != flwor_clause::where_clause)
{
ZORBA_ASSERT(!theClauseStack.empty());
- ulong stackSize = (ulong)theClauseStack.size();
+ csize stackSize = theClauseStack.size();
clauseVarMap = theClauseStack[stackSize-1];
theClauseStack.resize(stackSize - 1);
@@ -1878,9 +1913,12 @@
std::vector<flwor::NonGroupingSpec>& ngspecs)
{
const group_clause* gbc = static_cast<const group_clause*>(clauseVarMap->theClause);
+
const group_clause::rebind_list_t& gvars = gbc->get_grouping_vars();
const group_clause::rebind_list_t& ngvars = gbc->get_nongrouping_vars();
+
const std::vector<std::string>& collations = gbc->get_collations();
+
long numVars = (long)(gvars.size() + ngvars.size());
long numGroupVars = (long)gvars.size();
long i = numVars - 1;
@@ -1900,7 +1938,12 @@
const std::vector<PlanIter_t>& varRefs = varRebind->theOutputVarRefs;
- gspecs.push_back(flwor::GroupingSpec(pop_itstack(), varRefs, collations[i]));
+ bool fastComparison = nativeColumnSort(clauseVarMap->theVarExprs[i]);
+
+ gspecs.push_back(flwor::GroupingSpec(pop_itstack(),
+ varRefs,
+ collations[i],
+ fastComparison));
}
}
@@ -2019,13 +2062,13 @@
{
CODEGEN_TRACE_OUT("");
- ulong numVars = v.var_count();
+ csize numVars = v.var_count();
checked_vector<PlanIter_t> args(numVars+1);
checked_vector<store::Item_t> varnames(numVars);
checked_vector<xqtref_t> vartypes(numVars);
- for (ulong i = 0; i < numVars; ++i)
+ for (csize i = 0; i < numVars; ++i)
{
varnames[i] = v.get_var(i)->get_name();
vartypes[i] = v.get_var(i)->get_type();
@@ -2044,7 +2087,9 @@
varnames,
vartypes,
v.get_inner_scripting_kind(),
- localBindings));
+ localBindings,
+ v.getNodeCopy(),
+ false));
}
#ifdef ZORBA_WITH_DEBUGGER
@@ -2070,23 +2115,25 @@
std::vector<PlanIter_t> argvEvalIter;
- ulong numVars = v.var_count();
+ csize numVars = v.var_count();
std::vector<store::Item_t> varnames(numVars);
std::vector<xqtref_t> vartypes(numVars);
//create the eval iterator children
- for (ulong i = 0; i < numVars; i++) {
+ for (csize i = 0; i < numVars; i++)
+ {
varnames[i] = v.get_var(i)->get_name();
vartypes[i] = v.get_var(i)->get_type();
argvEvalIter.push_back(pop_itstack());
}
- argvEvalIter.push_back(
- new DebuggerSingletonIterator(sctx, qloc, theCCB->theDebuggerCommons));
+
+ argvEvalIter.push_back(new DebuggerSingletonIterator(sctx,
+ qloc,
+ theCCB->theDebuggerCommons));
// now reverse them (first the expression, then the variables)
reverse(argvEvalIter.begin(), argvEvalIter.end());
-
// get the debugger iterator from the debugger stack
std::auto_ptr<DebugIterator> lDebugIterator(theDebuggerStack.top());
theDebuggerStack.pop();
@@ -2101,16 +2148,20 @@
// child 1
store::NsBindings localBindings;
- if (v.getNSCtx()) {
+ if (v.getNSCtx())
+ {
v.getNSCtx()->getAllBindings(localBindings);
}
+
argv.push_back(new EvalIterator(sctx,
qloc,
argvEvalIter,
varnames,
vartypes,
- SIMPLE_EXPR,
- localBindings));
+ SEQUENTIAL_FUNC_EXPR,
+ localBindings,
+ true,
+ true));
lDebugIterator->setChildren(&argv);
lDebugIterator->setVariables(varnames, vartypes);
@@ -2233,7 +2284,7 @@
{
CODEGEN_TRACE_OUT("");
- const function* func = v.get_func();
+ function* func = v.get_func();
std::vector<PlanIter_t> argv;
@@ -2277,45 +2328,12 @@
dynamic_cast<EnclosedIterator*>(iter.getp())->setInUpdateExpr();
}
}
-#if 0
else if (func->isUdf())
{
- const user_function* udf = static_cast<const user_function*>(func);
-
- if (udf->isExiting())
- {
- TypeManager* tm = v.get_type_manager();
-
- const xqtref_t& udfType = udf->getSignature().returnType();
-
- expr* body = udf->getBody();
-
- std::vector<expr*> exitExprs;
- ulong numExitExprs;
- ulong i;
-
- body->get_exprs_of_kind(exit_expr_kind, exitExprs);
-
- for (i = 0; i < numExitExprs; ++i)
- {
- if (!TypeOps::is_subtype(tm,
- *exitExprs[i]->get_return_type(),
- *udfType,
- loc))
- break;
- }
-
- if (i < numExitExprs)
- {
- UDFunctionCallIterator* udfIter =
- dynamic_cast<UDFunctionCallIterator*>(iter.getp());
-
- ZORBA_ASSERT(udfIter != NULL);
- udfIter->setCheckType();
- }
- }
+ // need to computeResultCaching here for iterprint to work
+ user_function* udf = static_cast<user_function*>(func);
+ udf->computeResultCaching(theCCB->theXQueryDiagnostics);
}
-#endif
}
else
{
@@ -2797,6 +2815,9 @@
theConstructorsStack.push(&v);
theEnclosedContextStack.push(ELEMENT_CONTENT);
+ if (v.copyInputNodes())
+ theCopyNodesStack.push(true);
+
return true;
}
@@ -2806,13 +2827,18 @@
CODEGEN_TRACE_OUT("");
PlanIter_t lContent = pop_itstack();
- PlanIter_t lContIter = new DocumentContentIterator(sctx, qloc, lContent);
- PlanIter_t lDocIter = new DocumentIterator(sctx, qloc, lContIter);
+ PlanIter_t lDocIter = new DocumentIterator(sctx,
+ qloc,
+ lContent,
+ !theCopyNodesStack.empty());
push_itstack(lDocIter);
theEnclosedContextStack.pop();
expr* e = plan_visitor_ns::pop_stack(theConstructorsStack);
ZORBA_ASSERT(e == &v);
+
+ if (v.copyInputNodes())
+ theCopyNodesStack.pop();
}
@@ -2823,6 +2849,9 @@
theConstructorsStack.push(&v);
theEnclosedContextStack.push(ELEMENT_CONTENT);
+ if (v.copyInputNodes())
+ theCopyNodesStack.push(true);
+
return true;
}
@@ -2848,9 +2877,9 @@
expr* e = plan_visitor_ns::pop_stack(theConstructorsStack);
ZORBA_ASSERT(e == &v);
- // Handling of the special case where the QName expression of a direct element constructor
- // has in itself a direct constructor. In that case the QName expression should have
- // isRoot set to true.
+ // Handling of the special case where the QName expression of a direct element
+ // constructor has in itself a direct constructor. In that case the QName
+ // expression should have isRoot set to true.
elem_expr* top_elem_expr = NULL;
if (!theConstructorsStack.empty())
top_elem_expr = dynamic_cast<elem_expr*>(theConstructorsStack.top());
@@ -2868,8 +2897,12 @@
lAttrsIter,
lContentIter,
v.getNSCtx(),
- isRoot);
+ isRoot,
+ !theCopyNodesStack.empty());
push_itstack(iter);
+
+ if (v.copyInputNodes())
+ theCopyNodesStack.pop();
}
=== modified file 'src/compiler/expression/abstract_expr_visitor.h'
--- src/compiler/expression/abstract_expr_visitor.h 2011-06-14 17:26:33 +0000
+++ src/compiler/expression/abstract_expr_visitor.h 2012-01-25 00:12:28 +0000
@@ -84,6 +84,7 @@
EXPR_VISITOR_METHODS (block_expr);
EXPR_VISITOR_METHODS (apply_expr);
EXPR_VISITOR_METHODS (var_decl_expr);
+ EXPR_VISITOR_METHODS (var_set_expr);
EXPR_VISITOR_METHODS (exit_expr);
EXPR_VISITOR_METHODS (exit_catcher_expr);
EXPR_VISITOR_METHODS (flowctl_expr);
=== modified file 'src/compiler/expression/expr.cpp'
--- src/compiler/expression/expr.cpp 2011-09-16 19:36:18 +0000
+++ src/compiler/expression/expr.cpp 2012-01-25 00:12:28 +0000
@@ -720,10 +720,12 @@
doc_expr::doc_expr(
static_context* sctx,
const QueryLoc& loc,
- expr_t aContent)
+ expr* aContent,
+ bool copyNodes)
:
expr(sctx, loc, doc_expr_kind),
- theContent(aContent)
+ theContent(aContent),
+ theCopyInputNodes(copyNodes)
{
compute_scripting_kind();
}
@@ -733,6 +735,7 @@
{
serialize_baseclass(ar, (expr*)this);
ar & theContent;
+ ar & theCopyInputNodes;
}
@@ -749,7 +752,11 @@
expr_t doc_expr::clone(substitution_t& subst) const
{
- return new doc_expr(theSctx, get_loc(), CLONE(getContent(), subst));
+ doc_expr* clone = new doc_expr(theSctx,
+ get_loc(),
+ CLONE(getContent(), subst),
+ theCopyInputNodes);
+ return clone;
}
@@ -759,15 +766,17 @@
elem_expr::elem_expr(
static_context* sctx,
const QueryLoc& aLoc,
- expr_t aQNameExpr,
- expr_t aAttrs,
- expr_t aContent,
- const namespace_context* aNSCtx)
+ expr* aQNameExpr,
+ expr* attrs,
+ expr* content,
+ const namespace_context* aNSCtx,
+ bool copyNodes)
:
namespace_context_base_expr(sctx, aLoc, elem_expr_kind, aNSCtx),
theQNameExpr(aQNameExpr),
- theAttrs(aAttrs),
- theContent(aContent)
+ theAttrs(attrs),
+ theContent(content),
+ theCopyInputNodes(copyNodes)
{
compute_scripting_kind();
@@ -778,14 +787,16 @@
elem_expr::elem_expr(
static_context* sctx,
const QueryLoc& aLoc,
- expr_t aQNameExpr,
- expr_t aContent,
- const namespace_context* aNSCtx)
+ expr* aQNameExpr,
+ expr* content,
+ const namespace_context* aNSCtx,
+ bool copyNodes)
:
namespace_context_base_expr(sctx, aLoc, elem_expr_kind, aNSCtx),
theQNameExpr(aQNameExpr),
theAttrs(0),
- theContent(aContent)
+ theContent(content),
+ theCopyInputNodes(copyNodes)
{
compute_scripting_kind();
@@ -800,6 +811,7 @@
ar & theAttrs;
ar & theContent;
ar & theNSCtx;
+ ar & theCopyInputNodes;
}
@@ -831,12 +843,14 @@
expr_t elem_expr::clone(substitution_t& subst) const
{
- return new elem_expr(theSctx,
- get_loc(),
- CLONE(getQNameExpr(), subst),
- CLONE(getAttrs(), subst),
- CLONE(getContent(), subst),
- getNSCtx());
+ elem_expr* clone = new elem_expr(theSctx,
+ get_loc(),
+ CLONE(getQNameExpr(), subst),
+ CLONE(getAttrs(), subst),
+ CLONE(getContent(), subst),
+ getNSCtx(),
+ theCopyInputNodes);
+ return clone;
}
@@ -1388,13 +1402,14 @@
eval_expr::eval_expr(
static_context* sctx,
const QueryLoc& loc,
- expr_t e,
+ const expr_t& e,
expr_script_kind_t scriptingKind,
namespace_context* nsCtx)
:
namespace_context_base_expr(sctx, loc, eval_expr_kind, nsCtx),
theExpr(e),
- theInnerScriptingKind(scriptingKind)
+ theInnerScriptingKind(scriptingKind),
+ theDoNodeCopy(false)
{
compute_scripting_kind();
}
@@ -1402,11 +1417,12 @@
void eval_expr::serialize(::zorba::serialization::Archiver& ar)
{
- serialize_baseclass(ar, (expr*)this);
+ serialize_baseclass(ar, (namespace_context_base_expr*)this);
ar & theExpr;
ar & theVars;
ar & theArgs;
SERIALIZE_ENUM(expr_script_kind_t, theInnerScriptingKind);
+ ar & theDoNodeCopy;
}
@@ -1439,8 +1455,9 @@
theExpr->clone(s),
theInnerScriptingKind,
theNSCtx.getp());
+ new_eval->setNodeCopy(theDoNodeCopy);
- for (ulong i = 0; i < theVars.size(); ++i)
+ for (csize i = 0; i < theVars.size(); ++i)
{
var_expr_t cloneVar = dynamic_cast<var_expr*>(theVars[i]->clone(s).getp());
assert(cloneVar != NULL);
@@ -1458,41 +1475,15 @@
debugger_expr::debugger_expr(
static_context* sctx,
const QueryLoc& loc,
- expr_t aChild,
- std::list<GlobalBinding> aGlobals,
+ const expr_t& aChild,
namespace_context* nsCtx,
bool aIsVarDeclaration)
:
namespace_context_base_expr(sctx, loc, debugger_expr_kind, nsCtx),
theExpr(aChild),
- theGlobals(aGlobals),
theIsVarDeclaration(aIsVarDeclaration)
{
- theScriptingKind = aChild->get_scripting_detail();
-}
-
-void debugger_expr::store_local_variables(checked_vector<var_expr_t>& aScopedVariables)
-{
- std::set<const store::Item*> lQNames;
- checked_vector<var_expr_t>::reverse_iterator it;
- for ( it = aScopedVariables.rbegin(); it != aScopedVariables.rend(); ++it )
- {
- if ( lQNames.find((*it)->get_name()) == lQNames.end() )
- {
- lQNames.insert( (*it)->get_name() );
- var_expr_t lValue = (*it);
- var_expr_t lVariable(new var_expr(theSctx,
- theLoc,
- var_expr::eval_var,
- lValue->get_name() ) );
- lVariable->set_type( lValue->get_type() );
- add_var(lVariable, lValue.getp());
- }
- }
-}
-
-void debugger_expr::compute_scripting_kind()
-{
+ compute_scripting_kind();
}
void debugger_expr::serialize(::zorba::serialization::Archiver& ar)
@@ -1501,9 +1492,15 @@
ar & theExpr;
ar & theVars;
ar & theArgs;
- ar & theGlobals;
ar & theIsVarDeclaration;
}
+
+
+void debugger_expr::compute_scripting_kind()
+{
+ theScriptingKind = theExpr->get_scripting_detail();
+}
+
#endif
=== modified file 'src/compiler/expression/expr.h'
--- src/compiler/expression/expr.h 2011-09-20 14:33:34 +0000
+++ src/compiler/expression/expr.h 2012-01-25 00:12:28 +0000
@@ -117,7 +117,7 @@
order_type_t get_type() const { return theType; }
- const expr* get_expr() const { return theExpr; }
+ expr* get_expr() const { return theExpr.getp(); }
void compute_scripting_kind();
@@ -157,7 +157,7 @@
expr_t,
rchandle<TypeManager>);
- const expr* get_expr() const { return theExpr; }
+ expr* get_expr() const { return theExpr.getp(); }
const store::Item* get_type_name() const { return theTypeName; }
@@ -557,6 +557,7 @@
protected:
expr_t theContent;
+ bool theCopyInputNodes;
public:
SERIALIZABLE_CLASS(doc_expr)
@@ -564,9 +565,13 @@
void serialize(::zorba::serialization::Archiver& ar);
public:
- doc_expr(static_context* sctx, const QueryLoc&, expr_t aContent);
-
- const expr* getContent() const { return theContent.getp(); }
+ doc_expr(static_context* sctx, const QueryLoc&, expr* content, bool copyNodes);
+
+ expr* getContent() const { return theContent.getp(); }
+
+ bool copyInputNodes() const { return theCopyInputNodes; }
+
+ void setCopyInputNodes() { theCopyInputNodes = true; }
void compute_scripting_kind();
@@ -613,7 +618,8 @@
expr_t theQNameExpr;
expr_t theAttrs;
expr_t theContent;
-
+ bool theCopyInputNodes;
+
public:
SERIALIZABLE_CLASS(elem_expr)
SERIALIZABLE_CLASS_CONSTRUCTOR2(elem_expr, namespace_context_base_expr)
@@ -623,23 +629,29 @@
elem_expr(
static_context* sctx,
const QueryLoc&,
- expr_t aQNameExpr,
- expr_t aAttrs,
- expr_t aContent,
- const namespace_context* aNSCtx);
+ expr* qnameExpr,
+ expr* attrs,
+ expr* content,
+ const namespace_context* nsCtx,
+ bool copyNodes);
elem_expr(
static_context* sctx,
const QueryLoc&,
- expr_t aQNameExpr,
- expr_t aContent,
- const namespace_context* aNSCtx);
+ expr* qnameExpr,
+ expr* content,
+ const namespace_context* nsCtx,
+ bool copyNodes);
- const expr* getQNameExpr() const { return theQNameExpr.getp(); }
-
- const expr* getContent() const { return theContent.getp(); }
-
- const expr* getAttrs() const { return theAttrs; }
+ expr* getQNameExpr() const { return theQNameExpr.getp(); }
+
+ expr* getContent() const { return theContent.getp(); }
+
+ expr* getAttrs() const { return theAttrs.getp(); }
+
+ bool copyInputNodes() const { return theCopyInputNodes; }
+
+ void setCopyInputNodes() { theCopyInputNodes = true; }
void compute_scripting_kind();
@@ -696,9 +708,9 @@
expr_t aQNameExpr,
expr_t aValueExpr);
- const expr* getQNameExpr() const { return theQNameExpr.getp(); }
+ expr* getQNameExpr() const { return theQNameExpr.getp(); }
- const expr* getValueExpr() const { return theValueExpr.getp(); }
+ expr* getValueExpr() const { return theValueExpr.getp(); }
const store::Item* getQName() const;
@@ -738,10 +750,10 @@
public:
text_expr(
- static_context* sctx,
- const QueryLoc&,
- text_constructor_type,
- expr_t);
+ static_context* sctx,
+ const QueryLoc&,
+ text_constructor_type,
+ expr_t);
expr* get_text() const { return theContentExpr.getp(); }
@@ -777,9 +789,9 @@
public:
pi_expr(static_context* sctx, const QueryLoc&, expr_t, expr_t);
- const expr* get_target_expr() const { return theTargetExpr.getp(); }
+ expr* get_target_expr() const { return theTargetExpr.getp(); }
- const expr* get_content_expr() const { return theContentExpr.getp(); }
+ expr* get_content_expr() const { return theContentExpr.getp(); }
void compute_scripting_kind();
@@ -883,7 +895,7 @@
void add(rchandle<pragma> p) { thePragmas.push_back(p); }
- const expr* get_expr() const { return theExpr; }
+ expr* get_expr() const { return theExpr.getp(); }
void compute_scripting_kind();
@@ -918,8 +930,10 @@
********************************************************************************/
class catch_clause;
+
typedef rchandle<catch_clause> catch_clause_t;
+
class catch_clause : public SimpleRCObject
{
friend class expr;
@@ -990,15 +1004,15 @@
expr* get_try_expr() const { return theTryExpr.getp(); }
- expr* get_catch_expr(ulong i) const { return theCatchExprs[i].getp(); }
+ expr* get_catch_expr(csize i) const { return theCatchExprs[i].getp(); }
void add_catch_expr(expr_t e);
void add_clause(catch_clause_t cc);
- uint32_t clause_count() const { return (uint32_t)theCatchClauses.size(); }
+ csize clause_count() const { return theCatchClauses.size(); }
- catch_clause_t const& operator[](int i) const { return theCatchClauses[i]; }
+ catch_clause_t const& operator[](csize i) const { return theCatchClauses[i]; }
void compute_scripting_kind();
@@ -1135,10 +1149,27 @@
There is no syntax corresponding to the eval_expr. Instead, an eval_expr is
created by the translator whenever a call to the eval() function is reached.
- theExpr : The expr that computes the query string to be evaluated by eval.
- theVars : There is one eval var for each non-global var that is in scope
- where the call to the eval function appears at.
- theArgs : The domain expr of each eval var.
+ theExpr:
+ --------
+ The expr that computes the query string to be evaluated by eval.
+
+ theVars:
+ --------
+ There is one "eval" var for each non-global var that is in scope where the call
+ to the eval function appears at.
+
+ theArgs:
+ --------
+ The domain expr of each eval var. Initially, the domain expr of an eval var
+ is always another var. However, that other var may be later inlined, so in
+ general, the domain expr of an eval var may be any expr.
+
+ theInnerScriptingKind:
+ ----------------------
+
+ theDoNodeCopy:
+ --------------
+
********************************************************************************/
class eval_expr : public namespace_context_base_expr
{
@@ -1147,9 +1178,10 @@
protected:
expr_t theExpr;
- checked_vector<var_expr_t> theVars;
+ std::vector<var_expr_t> theVars;
std::vector<expr_t> theArgs;
expr_script_kind_t theInnerScriptingKind;
+ bool theDoNodeCopy;
public:
SERIALIZABLE_CLASS(eval_expr)
@@ -1160,17 +1192,17 @@
eval_expr(
static_context* sctx,
const QueryLoc& loc,
- expr_t e,
+ const expr_t& e,
expr_script_kind_t scriptingKind,
namespace_context* nsCtx);
expr* get_expr() const { return theExpr.getp(); }
- expr* get_arg_expr(ulong i) { return theArgs[i].getp(); }
-
- ulong var_count() const { return (ulong)theVars.size(); }
-
- const var_expr* get_var(ulong i) const { return theVars[i]; }
+ expr* get_arg_expr(csize i) { return theArgs[i].getp(); }
+
+ csize var_count() const { return theVars.size(); }
+
+ const var_expr* get_var(csize i) const { return theVars[i]; }
void add_var(const var_expr_t& var, const expr_t& arg)
{
@@ -1180,6 +1212,10 @@
expr_script_kind_t get_inner_scripting_kind() const;
+ bool getNodeCopy() const { return theDoNodeCopy; }
+
+ void setNodeCopy(bool v) { theDoNodeCopy = true; }
+
void compute_scripting_kind();
void accept(expr_visitor&);
@@ -1193,6 +1229,19 @@
#ifdef ZORBA_WITH_DEBUGGER
/***************************************************************************//**
debugger expression
+
+ theExpr:
+ --------
+ The wrapped expr
+
+ theVars:
+ --------
+
+ theArgs:
+ --------
+
+ theIsVarDeclaration:
+ --------------------
********************************************************************************/
class debugger_expr : public namespace_context_base_expr
{
@@ -1203,7 +1252,6 @@
expr_t theExpr;
checked_vector<var_expr_t> theVars;
std::vector<expr_t> theArgs;
- std::list<GlobalBinding> theGlobals;
bool theIsVarDeclaration;
public:
@@ -1213,26 +1261,23 @@
public:
debugger_expr(
- static_context* sctx,
- const QueryLoc& loc,
- expr_t aChild,
- std::list<GlobalBinding> aGlobals,
- namespace_context* nsCtx,
- bool aIsVarDeclaration);
+ static_context* sctx,
+ const QueryLoc& loc,
+ const expr_t& aChild,
+ namespace_context* nsCtx,
+ bool aIsVarDeclaration);
expr* get_expr() const { return theExpr.getp(); }
- std::list<GlobalBinding> getGlobals() const { return theGlobals; }
-
bool isVarDeclaration() const { return theIsVarDeclaration; }
void accept(expr_visitor&);
std::ostream& put(std::ostream&) const;
- ulong var_count() const { return (ulong)theVars.size(); }
+ csize var_count() const { return theVars.size(); }
- const var_expr* get_var(ulong i) const { return theVars[i]; }
+ const var_expr* get_var(csize i) const { return theVars[i]; }
void add_var(const var_expr_t& var, const expr_t& arg)
{
@@ -1241,9 +1286,6 @@
}
void compute_scripting_kind();
-
-private:
- void store_local_variables(checked_vector<var_expr_t>& aScopedVariables);
};
#endif
=== modified file 'src/compiler/expression/expr_annotations.cpp'
--- src/compiler/expression/expr_annotations.cpp 2011-06-14 17:26:33 +0000
+++ src/compiler/expression/expr_annotations.cpp 2012-01-25 00:12:28 +0000
@@ -19,64 +19,6 @@
namespace zorba {
-#if 0
-void SourceFinder::findSources(expr *e)
-{
- switch(e->get_expr_kind())
- {
- case flwor_expr_kind:
- case gflwor_expr_kind:
- findSources(static_cast<flwor_expr *>(e)->getReturnExpr());
- break;
-
- case fo_expr_kind:
- {
- fo_expr *fo = static_cast<fo_expr *>(e);
- const function *fn = fo->get_func();
- if (fn->isSource()) {
- m_sources.insert(fo);
- } else {
- findSourcesInChildren(fo);
- }
- }
- break;
-
- case var_expr_kind:
- {
- var_expr *var = static_cast<var_expr *>(e);
- switch(var->get_kind()) {
- case var_expr::for_var:
- case var_expr::let_var:
- findSources(&*var->get_flwor_clause()->get_expr());
- break;
-
- case var_expr::context_var:
- case var_expr::param_var:
- m_sources.insert(var);
- break;
-
- default:
- break;
- }
- }
- break;
-
- default:
- findSourcesInChildren(e);
- break;
- }
-}
-
-void SourceFinder::findSourcesInChildren(expr *e)
-{
- for(expr_iterator i = e->expr_begin(); !i.done(); ++i) {
- if (*i != NULL) {
- findSources(*i);
- }
- }
-}
-#endif
-
bool ExpressionPropertyComputer::returnsDuplicateNodes(expr *e)
{
=== modified file 'src/compiler/expression/expr_base.cpp'
--- src/compiler/expression/expr_base.cpp 2011-08-12 10:21:10 +0000
+++ src/compiler/expression/expr_base.cpp 2012-01-25 00:12:28 +0000
@@ -50,7 +50,7 @@
static xqtref_t print_expr_and_type(expr* e, xqtref_t t)
{
- if (Properties::instance()->printStaticTypes ())
+ if (Properties::instance()->printStaticTypes())
{
std::cout << "Return type for " << e << ":\n";
e->put(std::cout);
@@ -85,10 +85,10 @@
bool expr::is_sequential(short theScriptingKind)
{
return (theScriptingKind & (VAR_SETTING_EXPR |
- APPLYING_EXPR |
- EXITING_EXPR |
- BREAKING_EXPR |
- SEQUENTIAL_FUNC_EXPR)) != 0;
+ APPLYING_EXPR |
+ EXITING_EXPR |
+ BREAKING_EXPR |
+ SEQUENTIAL_FUNC_EXPR)) != 0;
}
@@ -526,6 +526,52 @@
/*******************************************************************************
+
+********************************************************************************/
+BoolAnnotationValue expr::getWillBeSerialized() const
+{
+ return (BoolAnnotationValue)
+ ((theFlags1 & WILL_BE_SERIALIZED_MASK) >> WILL_BE_SERIALIZED);
+}
+
+
+void expr::setWillBeSerialized(BoolAnnotationValue v)
+{
+ theFlags1 &= ~WILL_BE_SERIALIZED_MASK;
+ theFlags1 |= (v << WILL_BE_SERIALIZED);
+}
+
+
+bool expr::willBeSerialized() const
+{
+ BoolAnnotationValue v = getWillBeSerialized();
+ return (v == ANNOTATION_TRUE || v == ANNOTATION_TRUE_FIXED);
+}
+
+
+/*******************************************************************************
+ This annotation tells whether the expr must produce nodes that belong to
+ "standalone" trees or not. A tree is standalone if it does not contain
+ references to other trees. Such references are created when the optimizer
+ decides that it is ok to avoid copying the referenced subtree (as would be
+ required by required by a strict implementation of the spec, eg., during
+ node construction).
+********************************************************************************/
+BoolAnnotationValue expr::getMustCopyNodes() const
+{
+ return (BoolAnnotationValue)
+ ((theFlags1 & MUST_COPY_NODES_MASK) >> MUST_COPY_NODES);
+}
+
+
+void expr::setMustCopyNodes(BoolAnnotationValue v)
+{
+ theFlags1 &= ~MUST_COPY_NODES_MASK;
+ theFlags1 |= (v << MUST_COPY_NODES);
+}
+
+
+/*******************************************************************************
Return true if the expr does not reference any variables.
********************************************************************************/
bool expr::is_constant() const
@@ -633,20 +679,59 @@
/*******************************************************************************
********************************************************************************/
-void expr::get_exprs_of_kind(expr_kind_t kind, std::vector<expr*>& exprs) const
+void expr::get_exprs_of_kind(
+ expr_kind_t kind,
+ bool deep,
+ std::vector<expr*>& exprs) const
{
if (kind == get_expr_kind())
{
exprs.push_back(const_cast<expr*>(this));
- }
-
- ExprConstIterator iter(this);
- while(!iter.done())
- {
- const expr* ce = iter.get_expr();
- if (ce)
- {
- ce->get_exprs_of_kind(kind, exprs);
+
+ if (!deep)
+ return;
+ }
+
+ ExprConstIterator iter(this);
+ while(!iter.done())
+ {
+ const expr* ce = iter.get_expr();
+ if (ce)
+ {
+ ce->get_exprs_of_kind(kind, deep, exprs);
+ }
+
+ iter.next();
+ }
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+void expr::get_fo_exprs_of_kind(
+ FunctionConsts::FunctionKind kind,
+ bool deep,
+ std::vector<expr*>& exprs) const
+{
+ if (get_expr_kind() == fo_expr_kind)
+ {
+ if (static_cast<const fo_expr*>(this)->get_func()->getKind() == kind)
+ {
+ exprs.push_back(const_cast<expr*>(this));
+
+ if (!deep)
+ return;
+ }
+ }
+
+ ExprConstIterator iter(this);
+ while(!iter.done())
+ {
+ const expr* ce = iter.get_expr();
+ if (ce)
+ {
+ ce->get_fo_exprs_of_kind(kind, deep, exprs);
}
iter.next();
@@ -751,18 +836,25 @@
{
const fo_expr* foExpr = static_cast<const fo_expr *>(this);
const function* func = foExpr->get_func();
- ulong numArgs = foExpr->num_args();
+ csize numArgs = foExpr->num_args();
- for (ulong i = 0; i < numArgs; ++i) {
+ for (csize i = 0; i < numArgs; ++i)
+ {
const expr* argExpr = foExpr->get_arg(i);
- if (func->isMap(i)) {
- if (argExpr->is_map_internal(e, found) && found) {
+ if (func->isMap(i))
+ {
+ if (argExpr->is_map_internal(e, found) && found)
+ {
return true;
- } else if (found) {
+ }
+ else if (found)
+ {
return false;
}
- } else if (argExpr->contains_expr(e)) {
+ }
+ else if (argExpr->contains_expr(e))
+ {
return false;
}
}
@@ -775,9 +867,9 @@
{
const flwor_expr* flworExpr = static_cast<const flwor_expr *>(this);
bool haveOrderBy = false;
- ulong numClauses = flworExpr->num_clauses();
+ csize numClauses = flworExpr->num_clauses();
- for (ulong i = 0; i < numClauses; ++i)
+ for (csize i = 0; i < numClauses; ++i)
{
const flwor_clause* clause = (*flworExpr)[i];
@@ -845,8 +937,8 @@
const orderby_clause* obc = static_cast<const orderby_clause*>(clause);
- ulong numColumns = obc->num_columns();
- for (ulong k = 0; k < numColumns; ++k)
+ csize numColumns = obc->num_columns();
+ for (csize k = 0; k < numColumns; ++k)
{
if (obc->get_column_expr(k)->contains_expr(e))
return false;
@@ -858,7 +950,7 @@
default:
ZORBA_ASSERT(false);
}
- }
+ } // for each clause
if (found)
{
@@ -971,6 +1063,7 @@
return false; // TODO
case var_decl_expr_kind:
+ case var_set_expr_kind:
{
return !contains_expr(e);
}
=== modified file 'src/compiler/expression/expr_base.h'
--- src/compiler/expression/expr_base.h 2011-07-29 06:13:28 +0000
+++ src/compiler/expression/expr_base.h 2012-01-25 00:12:28 +0000
@@ -49,33 +49,41 @@
enum expr_kind_t
{
- attr_expr_kind,
- axis_step_expr_kind,
- castable_expr_kind,
- cast_expr_kind,
const_expr_kind,
+
+ var_expr_kind,
+
doc_expr_kind,
elem_expr_kind,
- extension_expr_kind,
+ attr_expr_kind,
+ text_expr_kind,
+ pi_expr_kind,
+
+ relpath_expr_kind,
+ axis_step_expr_kind,
+ match_expr_kind,
+
flwor_expr_kind,
- fo_expr_kind,
gflwor_expr_kind,
if_expr_kind,
+ trycatch_expr_kind,
+
+ fo_expr_kind,
+ dynamic_function_invocation_expr_kind,
+ function_item_expr_kind,
+
+ castable_expr_kind,
+ cast_expr_kind,
instanceof_expr_kind,
- match_expr_kind,
+ treat_expr_kind,
+ promote_expr_kind,
name_cast_expr_kind,
+
+ validate_expr_kind,
+
+ extension_expr_kind,
+
order_expr_kind,
- pi_expr_kind,
- promote_expr_kind,
- relpath_expr_kind,
- text_expr_kind,
- treat_expr_kind,
- validate_expr_kind,
- var_expr_kind,
-
- dynamic_function_invocation_expr_kind,
- function_item_expr_kind,
- trycatch_expr_kind,
#ifndef ZORBA_NO_FULL_TEXT
ft_expr_kind,
@@ -89,6 +97,7 @@
block_expr_kind,
var_decl_expr_kind,
+ var_set_expr_kind,
apply_expr_kind,
exit_expr_kind,
exit_catcher_expr_kind,
@@ -132,18 +141,24 @@
IGNORES_DUPLICATE_NODES = 6,
NON_DISCARDABLE = 8,
UNFOLDABLE = 10,
- CONTAINS_RECURSIVE_CALL = 12
+ CONTAINS_RECURSIVE_CALL = 12,
+ PROPAGATES_INPUT_NODES = 14,
+ WILL_BE_SERIALIZED = 16,
+ MUST_COPY_NODES = 18
} Annotationkey;
typedef enum
{
- PRODUCES_SORTED_NODES_MASK = 0x003,
- PRODUCES_DISTINCT_NODES_MASK = 0x00C,
- IGNORES_SORTED_NODES_MASK = 0x030,
+ PRODUCES_SORTED_NODES_MASK = 0x003,
+ PRODUCES_DISTINCT_NODES_MASK = 0x00C,
+ IGNORES_SORTED_NODES_MASK = 0x030,
IGNORES_DUPLICATE_NODES_MASK = 0x0C0,
- NON_DISCARDABLE_MASK = 0x300,
- UNFOLDABLE_MASK = 0xC00,
- CONTAINS_RECURSIVE_CALL_MASK = 0x3000
+ NON_DISCARDABLE_MASK = 0x300,
+ UNFOLDABLE_MASK = 0xC00,
+ CONTAINS_RECURSIVE_CALL_MASK = 0x3000,
+ PROPAGATES_INPUT_NODES_MASK = 0xC000,
+ WILL_BE_SERIALIZED_MASK = 0x30000,
+ MUST_COPY_NODES_MASK = 0xC0000
} AnnotationMask;
@@ -243,6 +258,11 @@
bool producesDistinctNodes() const;
+ // Annotation : propagatesInputNodes
+ BoolAnnotationValue getPropagatesInputNodes() const;
+
+ void setPropagatesInputNodes(BoolAnnotationValue v);
+
// Annotation : ignores-sorted-nodes
BoolAnnotationValue getIgnoresSortedNodes() const;
@@ -278,6 +298,18 @@
bool containsRecursiveCall() const;
+ // Annotation : mustCopyNodes
+ BoolAnnotationValue getMustCopyNodes() const;
+
+ void setMustCopyNodes(BoolAnnotationValue v);
+
+ // Annotation : willBeSerialized
+ BoolAnnotationValue getWillBeSerialized() const;
+
+ void setWillBeSerialized(BoolAnnotationValue v);
+
+ bool willBeSerialized() const;
+
bool is_constant() const;
bool is_nondeterministic() const;
@@ -288,7 +320,15 @@
bool contains_node_construction() const;
- void get_exprs_of_kind(expr_kind_t kind, std::vector<expr*>& exprs) const;
+ void get_exprs_of_kind(
+ expr_kind_t kind,
+ bool deep,
+ std::vector<expr*>& exprs) const;
+
+ void get_fo_exprs_of_kind(
+ FunctionConsts::FunctionKind kind,
+ bool deep,
+ std::vector<expr*>& exprs) const;
bool is_map(expr* e, static_context* sctx) const;
=== modified file 'src/compiler/expression/expr_classes.h'
--- src/compiler/expression/expr_classes.h 2011-06-14 17:26:33 +0000
+++ src/compiler/expression/expr_classes.h 2012-01-25 00:12:28 +0000
@@ -60,6 +60,7 @@
class block_expr;
class apply_expr;
class var_decl_expr;
+ class var_set_expr;
class exit_expr;
class exit_catcher_expr;
class while_expr;
=== modified file 'src/compiler/expression/expr_iter.cpp'
--- src/compiler/expression/expr_iter.cpp 2011-09-20 14:33:34 +0000
+++ src/compiler/expression/expr_iter.cpp 2012-01-25 00:12:28 +0000
@@ -518,7 +518,7 @@
EXPR_ITER_BEGIN();
EXPR_ITER_NEXT(repExpr->theTargetExpr);
- EXPR_ITER_NEXT(repExpr->theReplaceExpr);
+ EXPR_ITER_NEXT(repExpr->theSourceExpr);
EXPR_ITER_END();
break;
@@ -531,7 +531,7 @@
EXPR_ITER_BEGIN();
EXPR_ITER_NEXT(renExpr->theTargetExpr);
- EXPR_ITER_NEXT(renExpr->theNameExpr);
+ EXPR_ITER_NEXT(renExpr->theSourceExpr);
EXPR_ITER_END();
break;
@@ -592,6 +592,15 @@
break;
}
+ case var_set_expr_kind:
+ {
+ var_set_expr* varSetExpr = static_cast<var_set_expr*>(theExpr);
+ EXPR_ITER_BEGIN();
+ EXPR_ITER_NEXT(varSetExpr->theExpr);
+ EXPR_ITER_END();
+ break;
+ }
+
case flowctl_expr_kind:
{
EXPR_ITER_BEGIN();
=== modified file 'src/compiler/expression/expr_put.cpp'
--- src/compiler/expression/expr_put.cpp 2011-06-14 17:26:33 +0000
+++ src/compiler/expression/expr_put.cpp 2012-01-25 00:12:28 +0000
@@ -424,7 +424,7 @@
return os;
}
-ostream& eval_expr::put( ostream& os) const
+ostream& eval_expr::put(ostream& os) const
{
BEGIN_PUT( eval_expr );
for (ulong i = 0; i < theArgs.size(); i++)
@@ -438,15 +438,15 @@
END_PUT();
}
-ostream& function_trace_expr::put( ostream& os) const
+ostream& function_trace_expr::put(ostream& os) const
{
- BEGIN_PUT( function_trace_expr );
- theExpr->put (os);
+ BEGIN_PUT(function_trace_expr);
+ theExpr->put(os);
END_PUT();
}
-ostream& apply_expr::put( ostream& os) const
+ostream& apply_expr::put(ostream& os) const
{
BEGIN_PUT(apply_expr);
theExpr->put(os);
@@ -454,32 +454,46 @@
}
-ostream& var_decl_expr::put( ostream& os) const
+ostream& var_decl_expr::put(ostream& os) const
{
- BEGIN_PUT( var_decl_expr );
+ BEGIN_PUT(var_decl_expr);
+
theVarExpr->put(os);
if (theInitExpr)
theInitExpr->put(os);
- END_PUT();
-}
-
-
-ostream& if_expr::put( ostream& os) const
-{
- BEGIN_PUT( if_expr );
+
+ END_PUT();
+}
+
+
+ostream& var_set_expr::put(ostream& os) const
+{
+ BEGIN_PUT(var_set_expr);
+
+ theVarExpr->put(os);
+ theExpr->put(os);
+
+ END_PUT();
+}
+
+
+ostream& if_expr::put(ostream& os) const
+{
+ BEGIN_PUT(if_expr);
theCondExpr->put(os);
PUT_SUB("THEN", theThenExpr);
PUT_SUB("ELSE", theElseExpr);
END_PUT();
}
-ostream& fo_expr::put( ostream& os) const
+
+ostream& fo_expr::put(ostream& os) const
{
const store::Item* qname = theFunction->getName();
BEGIN_PUT2( qname->getStringValue() << "/" << num_args() );
- ulong numArgs = (ulong)theArgs.size();
+ csize numArgs = theArgs.size();
- for (ulong i = 0; i < numArgs; ++i)
+ for (csize i = 0; i < numArgs; ++i)
{
theArgs[i]->put(os);
}
@@ -747,32 +761,46 @@
ostream& elem_expr::put(ostream& os) const
{
- BEGIN_PUT( elem_expr );
+ BEGIN_PUT(elem_expr);
+
+ os << indent << "copy nodes = " << theCopyInputNodes << std::endl;
+
if (theQNameExpr != NULL)
theQNameExpr->put(os);
+
if (theAttrs != NULL)
theAttrs->put(os);
+
if (theContent != NULL)
theContent->put(os);
+
END_PUT();
}
-ostream& doc_expr::put( ostream& os) const
+
+ostream& doc_expr::put(ostream& os) const
{
- BEGIN_PUT( doc_expr );
+ BEGIN_PUT(doc_expr);
+
+ os << indent << "copy nodes = " << theCopyInputNodes << std::endl;
+
theContent->put(os);
+
END_PUT();
}
-ostream& attr_expr::put( ostream& os) const
+
+ostream& attr_expr::put(ostream& os) const
{
- BEGIN_PUT( attr_expr );
+ BEGIN_PUT(attr_expr);
- theQNameExpr->put (os);
+ theQNameExpr->put(os);
PUT_SUB( "=", theValueExpr );
+
END_PUT();
}
+
ostream& text_expr::put(ostream& os) const
{
BEGIN_PUT( text_expr );
@@ -808,7 +836,7 @@
{
BEGIN_PUT( replace_expr );
theTargetExpr->put(os);
- PUT_SUB( ",", theReplaceExpr );
+ PUT_SUB( ",", theSourceExpr );
END_PUT();
}
@@ -816,7 +844,7 @@
{
BEGIN_PUT(rename_expr);
theTargetExpr->put(os);
- PUT_SUB(",", theNameExpr);
+ PUT_SUB(",", theSourceExpr);
END_PUT();
}
=== modified file 'src/compiler/expression/expr_type.cpp'
--- src/compiler/expression/expr_type.cpp 2011-08-12 10:21:10 +0000
+++ src/compiler/expression/expr_type.cpp 2012-01-25 00:12:28 +0000
@@ -1,12 +1,12 @@
/*
* Copyright 2006-2008 The FLWOR Foundation.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -77,7 +77,7 @@
if (deep)
{
ExprIterator iter(this);
- while (!iter.done())
+ while (!iter.done())
{
(*iter)->compute_return_type(deep, modified);
iter.next();
@@ -126,7 +126,7 @@
ulong numClauses = e->num_clauses();
- for (ulong i = 0; i < numClauses && quant != TypeConstants::QUANT_STAR; ++i)
+ for (ulong i = 0; i < numClauses && quant != TypeConstants::QUANT_STAR; ++i)
{
const flwor_clause* c = e->theClauses[i];
@@ -186,7 +186,7 @@
{
domainExpr = e->get_domain_expr();
ZORBA_ASSERT(domainExpr != NULL);
-
+
xqtref_t domainType = domainExpr->get_return_type();
if (e->theKind == var_expr::for_var)
@@ -256,10 +256,10 @@
{
xqtref_t stepType = sourceType;
- for (ulong i = 1; i < e->size(); ++i)
+ for (ulong i = 1; i < e->size(); ++i)
{
const axis_step_expr* axisStep = e->theSteps[i].cast<axis_step_expr>();
-
+
stepType = axis_step_type(theSctx,
axisStep,
static_cast<const NodeXQType*>(stepType.getp()));
@@ -300,7 +300,7 @@
Follow ups