← Back to team overview

zorba-coders team mailing list archive

[Merge] lp:~zorba-coders/zorba/threads into lp:zorba

 

Markos Zaharioudakis has proposed merging lp:~zorba-coders/zorba/threads into lp:zorba.

Commit message:
Some work towards multi-threading

Requested reviews:
  Markos Zaharioudakis (markos-za)

For more details, see:
https://code.launchpad.net/~zorba-coders/zorba/threads/+merge/174198

Some work towards multi-threading
-- 
https://code.launchpad.net/~zorba-coders/zorba/threads/+merge/174198
Your team Zorba Coders is subscribed to branch lp:zorba.
=== modified file 'include/zorba/xquery.h'
--- include/zorba/xquery.h	2013-05-28 00:58:27 +0000
+++ include/zorba/xquery.h	2013-07-11 13:41:52 +0000
@@ -29,16 +29,14 @@
 typedef Zorba_SerializerOptions_t* (*itemHandler)(void* aUserData);
 
 /** 
- * \brief This class is the representation of an %XQuery in the %Zorba engine.
+ * \brief This class is the representation of an %XQuery program in the %Zorba engine.
  *
- * To compile and execute an XQuery, an instance of this class must be created. 
- * This is done by using either the createQuery or compileQuery methods of the
- * Zorba class. These methods return an instance of XQuery_t, which is a 
+ * To compile and execute an XQuery program, an instance of this class must be
+ * created. This is done by using either the createQuery or compileQuery methods
+ * of the Zorba class. These methods return an instance of XQuery_t, which is a
  * reference counted smart pointer to a dynamically allocated XQuery object.
- * After receiving an XQuery_t, an application can make multiple copies of it.
- * Hence, an XQuery object can have multiple users, potentially in different
- * threads. The XQuery object is deleted when all XQuery_t objects that point 
- * to it are destroyed.
+ * The XQuery object is deleted when all XQuery_t objects that point to it are
+ * destroyed.
  *
  * The file \link simple.cpp \endlink contains some basic examples the demonstrate
  * the use of this class.
@@ -51,7 +49,7 @@
 {
  public:
   /** 
-   * \brief Destructor that destroys this XQuery object. 
+   * \brief Destructor.
    * 
    * The destructor is called automatically when there are no more XQuery_t
    * smart pointers pointing to this XQuery instance.
@@ -61,11 +59,13 @@
   /** 
    * \brief Set the filename of a query.
    *
-   * This (after URI-encoding) becomes the encapsulating entity's
-   * retrieval URI (in RFC 3986 terms).
+   * This (after URI-encoding) becomes the encapsulating entity's retrieval URI
+   * (in RFC 3986 terms), and may be used in the computation of the program's
+   * static base URI property, as described at 
+   * http://www.w3.org/TR/xquery-30/#dt-base-uri-decl
    */
   virtual void
-  setFileName(const String&) = 0;
+  setFileName(const String& flename) = 0;
   
   /** 
    * \brief Register an DiagnosticHandler to which errors during compilation or
@@ -74,14 +74,14 @@
    * If no DiagnosticHandler has been set via this function, the default error
    * handling mechanism is to throw instances of the ZorbaException class.
    *
-   * @param aDiagnosticHandler DiagnosticHandler to which errors are reported. The
+   * @param handler DiagnosticHandler to which errors are reported. The
    *        caller retains ownership over the DiagnosticHandler passed as
    *        parameter.
    * @throw SystemException if the query has been closed.
    * @see close()
    */
   virtual void
-  registerDiagnosticHandler(DiagnosticHandler* aDiagnosticHandler) = 0;
+  registerDiagnosticHandler(DiagnosticHandler* handler) = 0;
   
   /** 
    * \brief Reset the error handling mechanism back to the default,
@@ -443,7 +443,7 @@
    * This file will contain the output of Zorba profiler.
    */
   virtual void
-  setProfileName( std::string aProfileName ) = 0;
+  setProfileName(std::string aProfileName) = 0;
   
   /**
    * \brief Get the filename of the profile
@@ -468,9 +468,7 @@
    *        not been compiled, the server cannot connect to the client, etc.)
    */
   virtual void
-  debug(
-    const std::string& host,
-    unsigned short port) = 0;
+  debug(const std::string& host, unsigned short port) = 0;
 
   /**
    * \brief Start a debugger server.
@@ -556,7 +554,7 @@
 };
   
 
-// xml serialization of the query (equiv to calling serialize(os) 
+// XML serialization of the query result (equiv to calling serialize(os) 
 ZORBA_DLL_PUBLIC
 std::ostream& operator<< (std::ostream& os, const XQuery_t& aQuery); 
 

=== modified file 'src/annotations/annotations.cpp'
--- src/annotations/annotations.cpp	2013-04-29 01:51:11 +0000
+++ src/annotations/annotations.cpp	2013-07-11 13:41:52 +0000
@@ -325,6 +325,12 @@
 ********************************************************************************/
 AnnotationList::~AnnotationList()
 {
+  for (Annotations::iterator ite = theAnnotationList.begin();
+       ite != theAnnotationList.end();
+       ++ite)
+  {
+    delete *ite;
+  }
 }
 
 
@@ -343,7 +349,7 @@
 AnnotationInternal* AnnotationList::get(csize index) const
 {
   if (index < theAnnotationList.size())
-    return theAnnotationList[index].getp();
+    return theAnnotationList[index];
   else
     return NULL;
 }
@@ -354,12 +360,12 @@
 ********************************************************************************/
 AnnotationInternal* AnnotationList::get(AnnotationInternal::AnnotationId id) const
 {
-  for (ListConstIter_t ite = theAnnotationList.begin();
+  for (Annotations::const_iterator ite = theAnnotationList.begin();
        ite != theAnnotationList.end();
        ++ite)
   {
     if ((*ite)->getId() == id)
-      return (*ite).getp();
+      return (*ite);
   }
 
   return NULL;
@@ -408,7 +414,7 @@
   RuleBitSet lCurrAnn;
 
   // mark and detect duplicates
-  for (ListConstIter_t ite = theAnnotationList.begin();
+  for (Annotations::const_iterator ite = theAnnotationList.begin();
        ite != theAnnotationList.end();
        ++ite)
   {

=== modified file 'src/annotations/annotations.h'
--- src/annotations/annotations.h	2013-04-29 00:41:13 +0000
+++ src/annotations/annotations.h	2013-07-11 13:41:52 +0000
@@ -32,9 +32,6 @@
 class AnnotationInternal;
 class AnnotationList;
 
-typedef rchandle<AnnotationInternal> AnnotationInternal_t;
-typedef rchandle<AnnotationList> AnnotationList_t;
-
 class const_expr;
 
 /*******************************************************************************
@@ -53,7 +50,7 @@
   together in a declaration, then a conflict exists. Each set of annotations
   is implemented as a bitset indexed by annotation id.
 ********************************************************************************/
-class AnnotationInternal : public SimpleRCObject
+class AnnotationInternal : public ::zorba::serialization::SerializeBaseClass
 {
   friend class AnnotationList;
 
@@ -128,7 +125,7 @@
 
 public:
   SERIALIZABLE_CLASS(AnnotationInternal);
-  SERIALIZABLE_CLASS_CONSTRUCTOR2(AnnotationInternal, SimpleRCObject)
+  SERIALIZABLE_CLASS_CONSTRUCTOR(AnnotationInternal)
   void serialize(::zorba::serialization::Archiver& ar);
 
 public:
@@ -149,7 +146,7 @@
 
   Annotation ::= "%" EQName  ("(" Literal  ("," Literal)* ")")?
 ********************************************************************************/
-class AnnotationList : public SimpleRCObject
+class AnnotationList : public ::zorba::serialization::SerializeBaseClass
 {
 public:
   enum DeclarationKind
@@ -165,16 +162,14 @@
 
   typedef AnnotationInternal::AnnotationId AnnotationId;
 
-  typedef std::vector<AnnotationInternal_t> List_t;
-
-  typedef List_t::const_iterator ListConstIter_t;
+  typedef std::vector<AnnotationInternal*> Annotations;
 
 protected:
-  List_t theAnnotationList;
+  Annotations theAnnotationList;
 
 public:
   SERIALIZABLE_CLASS(AnnotationList);
-  SERIALIZABLE_CLASS_CONSTRUCTOR2(AnnotationList, SimpleRCObject)
+  SERIALIZABLE_CLASS_CONSTRUCTOR(AnnotationList)
   void serialize(::zorba::serialization::Archiver& ar);
 
 public:

=== modified file 'src/api/annotationimpl.cpp'
--- src/api/annotationimpl.cpp	2013-02-07 17:24:36 +0000
+++ src/api/annotationimpl.cpp	2013-07-11 13:41:52 +0000
@@ -27,11 +27,16 @@
 
 ********************************************************************************/
 AnnotationImpl::AnnotationImpl(AnnotationInternal* ann) 
-  : theAnnotation(ann)
-{
-}
-
-AnnotationImpl::~AnnotationImpl() {};
+{
+  theAnnotation = new AnnotationInternal(*ann);
+}
+
+
+AnnotationImpl::~AnnotationImpl()
+{
+  delete theAnnotation;
+}
+
 
 Item AnnotationImpl::getQName() const
 {

=== modified file 'src/api/annotationimpl.h'
--- src/api/annotationimpl.h	2013-02-07 17:24:36 +0000
+++ src/api/annotationimpl.h	2013-07-11 13:41:52 +0000
@@ -26,7 +26,6 @@
 {
 
 class AnnotationInternal;
-typedef rchandle<AnnotationInternal> AnnotationInternal_t;
 
 
 /*******************************************************************************
@@ -38,7 +37,7 @@
 {
 protected:
   
-  AnnotationInternal_t  theAnnotation;
+  AnnotationInternal  * theAnnotation;
 
 public:
   AnnotationImpl(AnnotationInternal* ann);

=== modified file 'src/api/serialization/serializer.cpp'
--- src/api/serialization/serializer.cpp	2013-06-29 08:38:53 +0000
+++ src/api/serialization/serializer.cpp	2013-07-11 13:41:52 +0000
@@ -38,10 +38,14 @@
 #include "util/xml_util.h"
 
 #include "system/globalenv.h"
+
 #include "zorbamisc/ns_consts.h"
+
 #include "zorbatypes/integer.h"
 #include "zorbatypes/numconversions.h"
 
+#include "context/static_context.h"
+
 #include "store/api/iterator.h"
 #include "store/api/iterator_factory.h"
 #include "store/api/item.h"
@@ -192,10 +196,12 @@
 
     // the input string is UTF-8
     int char_length;
-    try {
+    try
+    {
       char_length = utf8::char_length(*chars);
     }
-    catch ( utf8::invalid_byte const& ) {
+    catch ( utf8::invalid_byte const& )
+    {
       char_length = 1;
     }
 
@@ -445,9 +451,15 @@
       tr << " ";
 
     if (item->isStreamable())
+    {
       emit_streamable_item(item);
+    }
     else
-      emit_expanded_string(item->getStringValue().c_str(), item->getStringValue().size());
+    {
+      zstring strval;
+      item->getStringValue2(strval);
+      emit_expanded_string(strval.c_str(), strval.size());
+    }
 
     thePreviousItemKind = PREVIOUS_ITEM_WAS_TEXT;
   }

=== modified file 'src/api/staticcontextimpl.cpp'
--- src/api/staticcontextimpl.cpp	2013-05-31 03:38:45 +0000
+++ src/api/staticcontextimpl.cpp	2013-07-11 13:41:52 +0000
@@ -1497,26 +1497,24 @@
 Function_t
 StaticContextImpl::checkInvokable(const Item& aQName, size_t aNumArgs) const
 {
-  Item lType = aQName.getType();
-  if (lType.getStringValue() != "xs:QName")
+  store::Item* qname = Unmarshaller::getInternalItem(aQName);
+
+  if (qname->getTypeCode() != store::XS_QNAME)
   {
-    throw XQUERY_EXCEPTION(
-      err::XPTY0004, ERROR_PARAMS( ZED( BadType_23o ), "xs:QName" )
-    );
+    throw XQUERY_EXCEPTION(err::XPTY0004,
+    ERROR_PARAMS(ZED(BadType_23o), "xs:QName" ));
   }
 
   // test if function with given #args exists
   Function_t lFunc;
+
   std::vector<Function_t> lFunctions;
   findFunctions(aQName, lFunctions);
+
   if (lFunctions.empty())
   {
-    throw XQUERY_EXCEPTION(
-      err::XPST0017,
-      ERROR_PARAMS(
-        aQName.getStringValue(), ZED( FunctionUndeclared_3 ), aNumArgs
-      )
-    );
+    throw XQUERY_EXCEPTION(err::XPST0017,
+    ERROR_PARAMS(aQName.getStringValue(), ZED(FunctionUndeclared_3), aNumArgs));
   }
 
   for (std::vector<Function_t>::const_iterator lIter = lFunctions.begin();
@@ -1531,12 +1529,8 @@
 
   if (!lFunc)
   {
-    throw XQUERY_EXCEPTION(
-      err::XPST0017,
-      ERROR_PARAMS(
-        aQName.getStringValue(), ZED( FunctionUndeclared_3 ), aNumArgs
-      )
-    );
+    throw XQUERY_EXCEPTION(err::XPST0017,
+    ERROR_PARAMS(aQName.getStringValue(), ZED(FunctionUndeclared_3), aNumArgs));
   }
 
   return lFunc;

=== modified file 'src/api/xmldatamanagerimpl.cpp'
--- src/api/xmldatamanagerimpl.cpp	2013-02-07 17:24:36 +0000
+++ src/api/xmldatamanagerimpl.cpp	2013-07-11 13:41:52 +0000
@@ -278,8 +278,7 @@
 {
   ZORBA_DM_TRY
   {
-    Item lQName = theFactory->createQName(static_context::ZORBA_XML_FN_NS,
-                                          "parse");
+    Item lQName = theFactory->createQName(static_context::ZORBA_XML_FN_NS, "parse");
 
     // create a streamable string item
     std::vector<ItemSequence_t> lArgs;
@@ -289,7 +288,9 @@
     Item empty_item;
     Item validated_options;
     NsBindings nsPairs;
-    Item untyped_type = theFactory->createQName(XML_SCHEMA_NS, XML_SCHEMA_PREFIX, "untyped");
+    Item untyped_type = theFactory->createQName(static_context::W3C_XML_SCHEMA_NS,
+                                                "",
+                                                "untyped");
     Item options_node = theFactory->createElementNode(empty_item,
         theFactory->createQName(static_context::ZORBA_XML_FN_OPTIONS_NS, "options"),
         untyped_type, false, false, nsPairs);
@@ -337,7 +338,7 @@
     Item empty_item;
     Item validated_options;
     NsBindings nsPairs;
-    Item untyped_type = theFactory->createQName(XML_SCHEMA_NS, XML_SCHEMA_PREFIX, "untyped");
+    Item untyped_type = theFactory->createQName(static_context::W3C_XML_SCHEMA_NS, "", "untyped");
     Item options_node = theFactory->createElementNode(empty_item,
         theFactory->createQName(static_context::ZORBA_XML_FN_OPTIONS_NS, "options"),
         untyped_type, false, false, nsPairs);

=== modified file 'src/api/xqueryimpl.cpp'
--- src/api/xqueryimpl.cpp	2013-05-28 00:01:01 +0000
+++ src/api/xqueryimpl.cpp	2013-07-11 13:41:52 +0000
@@ -178,6 +178,7 @@
   close();
 }
 
+
 /*******************************************************************************
   Always called while holding theMutex
 ********************************************************************************/

=== modified file 'src/api/xqueryimpl.h'
--- src/api/xqueryimpl.h	2013-05-28 00:01:01 +0000
+++ src/api/xqueryimpl.h	2013-07-11 13:41:52 +0000
@@ -152,23 +152,17 @@
 
  protected:
 
-  class PlanProxy : public RCObject
+  class PlanProxy : public SyncedRCObject
   {
   public:
-    SYNC_CODE(mutable RCLock  theRCLock;)
-
     rchandle<SimpleRCObject>  theRootIter;
 
   public:
     SERIALIZABLE_CLASS(PlanProxy)
-    SERIALIZABLE_CLASS_CONSTRUCTOR2(PlanProxy, RCObject)
+    SERIALIZABLE_CLASS_CONSTRUCTOR2(PlanProxy, SyncedRCObject)
     void serialize(::zorba::serialization::Archiver& ar);
 
   public:
-    long* getSharedRefCounter() const { return NULL; }
-
-    SYNC_CODE(virtual RCLock* getRCLock() const { return &theRCLock; })
-
     PlanProxy(PlanIter_t& root);
   };
 

=== modified file 'src/api/zorbaimpl.cpp'
--- src/api/zorbaimpl.cpp	2013-02-07 17:24:36 +0000
+++ src/api/zorbaimpl.cpp	2013-07-11 13:41:52 +0000
@@ -73,6 +73,7 @@
 }
 #endif
 
+
 ZorbaImpl::ZorbaImpl() : theNumUsers(0)
 {
 #ifdef WIN32
@@ -138,8 +139,10 @@
 XQuery_t ZorbaImpl::createQuery(DiagnosticHandler* aDiagnosticHandler)
 {
   XQuery_t lXQuery(new XQueryImpl());
+
   if (aDiagnosticHandler != 0)
     lXQuery->registerDiagnosticHandler(aDiagnosticHandler);
+
   return lXQuery;
 }
 
@@ -169,9 +172,12 @@
     DiagnosticHandler* aDiagnosticHandler)
 {
   XQuery_t lXQuery(new XQueryImpl());
+
   if (aDiagnosticHandler != 0)
     lXQuery->registerDiagnosticHandler(aDiagnosticHandler);
+
   lXQuery->compile(aQuery, aHints);
+
   return lXQuery;
 }
 

=== modified file 'src/api/zorbaimpl.h'
--- src/api/zorbaimpl.h	2013-02-07 17:24:36 +0000
+++ src/api/zorbaimpl.h	2013-07-11 13:41:52 +0000
@@ -53,16 +53,18 @@
  */
 class ZorbaImpl : public Zorba
 {
- protected:
+protected:
   friend class Zorba;
 
   SYNC_CODE(Mutex theUsersMutex);
   ulong           theNumUsers;
+
 public:
 #ifdef WIN32
   static bool ctrl_c_signaled;
 #endif
- public:
+
+public:
 
   static void notifyError(DiagnosticHandler*, ZorbaException const&);
 
@@ -75,7 +77,7 @@
 
   static void checkItem(const store::Item_t& aItem);
 
- public:
+public:
 
   virtual ~ZorbaImpl();
 

=== modified file 'src/capi/csequence.cpp'
--- src/capi/csequence.cpp	2013-06-18 23:53:59 +0000
+++ src/capi/csequence.cpp	2013-07-11 13:41:52 +0000
@@ -30,6 +30,8 @@
 #include "zorbatypes/float.h"
 #include "zorbatypes/numconversions.h"
 
+#include "context/static_context.h"
+
 #include "error.h"
 
 using namespace zorba;
@@ -240,7 +242,7 @@
     else /* not isNode() */ {
       Item lType = lItem.getType();
       zorba::String lUri = lType.getNamespace();
-      if (lUri != XML_SCHEMA_NS) {
+      if (lUri != static_context::W3C_XML_SCHEMA_NS) {
         // We can only identify non-derived atomic types
         return XQC_INTERNAL_ERROR;
       }

=== modified file 'src/common/shared_types.h'
--- src/common/shared_types.h	2013-06-26 13:56:00 +0000
+++ src/common/shared_types.h	2013-07-11 13:41:52 +0000
@@ -44,9 +44,8 @@
 class QueryLoc;
 
 class function;
+class user_function;
 typedef rchandle<function> function_t;
-
-class user_function;
 typedef rchandle<user_function> user_function_t;
 
 class ItemIterator;
@@ -88,7 +87,6 @@
 
 // Annotations
 class AnnotationList;
-typedef rchandle<AnnotationList> AnnotationList_t;
 
 // Expression nodes
 class expr;

=== modified file 'src/compiler/codegen/plan_visitor.cpp'
--- src/compiler/codegen/plan_visitor.cpp	2013-06-15 02:57:08 +0000
+++ src/compiler/codegen/plan_visitor.cpp	2013-07-11 13:41:52 +0000
@@ -468,7 +468,7 @@
 {
   CODEGEN_TRACE_OUT("");
 
-  FunctionItemInfo* fnInfo = v.get_dynamic_fn_info();
+  FunctionItemInfo* fnInfo = v.get_fi_info();
   fnInfo->theCCB = theCCB;
   fnInfo->theLoc = qloc;
 

=== modified file 'src/compiler/expression/expr_put.cpp'
--- src/compiler/expression/expr_put.cpp	2013-06-15 02:57:08 +0000
+++ src/compiler/expression/expr_put.cpp	2013-07-11 13:41:52 +0000
@@ -553,7 +553,7 @@
   }
 
   user_function* udf = 
-  static_cast<user_function*>(theFunctionItemInfo->theFunction.getp());
+  static_cast<user_function*>(theFunctionItemInfo->theFunction);
 
   if (udf != NULL && udf->getBody() != NULL)
     udf->getBody()->put(os);

=== modified file 'src/compiler/expression/fo_expr.cpp'
--- src/compiler/expression/fo_expr.cpp	2013-02-07 17:24:36 +0000
+++ src/compiler/expression/fo_expr.cpp	2013-07-11 13:41:52 +0000
@@ -62,7 +62,7 @@
     user_function* udf,
     const QueryLoc& loc)
 {
-  function* f = BuiltinFunctionLibrary::getFunction(FunctionConsts::OP_CONCATENATE_N);
+  function* f = GENV_FUNC_LIB->getFunction(FunctionConsts::OP_CONCATENATE_N);
 
   std::auto_ptr<fo_expr> fo(ccb->theEM->create_fo_expr(sctx, udf, loc, f));
 

=== modified file 'src/compiler/expression/function_item_expr.cpp'
--- src/compiler/expression/function_item_expr.cpp	2013-04-24 01:35:58 +0000
+++ src/compiler/expression/function_item_expr.cpp	2013-07-11 13:41:52 +0000
@@ -92,15 +92,16 @@
     bool isInline,
     bool isCoercion)
   :
-  expr(ccb, sctx, udf, loc, function_item_expr_kind),
-  theFunctionItemInfo(new FunctionItemInfo(sctx,
-                                           loc,
-                                           f,
-                                           f->getName(),
-                                           arity,
-                                           isInline,
-                                           isCoercion))
+  expr(ccb, sctx, udf, loc, function_item_expr_kind)
 {
+  theFunctionItemInfo = new FunctionItemInfo(sctx,
+                                             loc,
+                                             f,
+                                             f->getName(),
+                                             arity,
+                                             isInline,
+                                             isCoercion);
+
   assert(f != NULL);
   compute_scripting_kind();
 }
@@ -114,15 +115,16 @@
     bool isInline,
     bool isCoercion)
   :
-  expr(ccb, sctx, udf, loc, function_item_expr_kind),
-  theFunctionItemInfo(new FunctionItemInfo(sctx,
-                                           loc,
-                                           NULL,
-                                           NULL,
-                                           0,
-                                           isInline,
-                                           isCoercion))
+  expr(ccb, sctx, udf, loc, function_item_expr_kind)
 {
+  theFunctionItemInfo = new FunctionItemInfo(sctx,
+                                             loc,
+                                             NULL,
+                                             NULL,
+                                             0,
+                                             isInline,
+                                             isCoercion);
+
   compute_scripting_kind();
 }
 

=== modified file 'src/compiler/expression/function_item_expr.h'
--- src/compiler/expression/function_item_expr.h	2013-04-27 16:36:36 +0000
+++ src/compiler/expression/function_item_expr.h	2013-07-11 13:41:52 +0000
@@ -151,7 +151,7 @@
   virtual ~function_item_expr();
   
 public:
-  FunctionItemInfo* get_dynamic_fn_info() { return theFunctionItemInfo; }
+  FunctionItemInfo* get_fi_info() { return theFunctionItemInfo; }
 
   void add_variable(expr* var, var_expr* substVar);
 

=== modified file 'src/compiler/parsetree/parsenode_print_xqdoc_visitor.cpp'
--- src/compiler/parsetree/parsenode_print_xqdoc_visitor.cpp	2013-06-18 23:53:59 +0000
+++ src/compiler/parsetree/parsenode_print_xqdoc_visitor.cpp	2013-07-11 13:41:52 +0000
@@ -38,6 +38,8 @@
 #include "store/api/copymode.h"
 #include "store/api/iterator.h"
 
+#include "context/static_context.h"
+
 #include "system/globalenv.h"
 #include "zorbamisc/ns_consts.h"
 
@@ -517,9 +519,9 @@
   theIsIndexDecl(false),
   theWaitForIndexSourceLiteral(false)
 {
-  theNamespaceMap["fn"] = XQUERY_XPATH_FN_NS;
-  theNamespaceMap[""] = XQUERY_XPATH_FN_NS;
-  theNamespaceMap[XML_SCHEMA_PREFIX] = XML_SCHEMA_NS;
+  theNamespaceMap["fn"] = static_context::W3C_FN_NS;
+  theNamespaceMap[""] = static_context::W3C_FN_NS;
+  theNamespaceMap[XML_SCHEMA_PREFIX] = static_context::W3C_XML_SCHEMA_NS;
   theNamespaceMap["local"] = XQUERY_LOCAL_FN_NS;
 }
 

=== modified file 'src/compiler/rewriter/rules/type_rules.cpp'
--- src/compiler/rewriter/rules/type_rules.cpp	2013-06-15 02:57:08 +0000
+++ src/compiler/rewriter/rules/type_rules.cpp	2013-07-11 13:41:52 +0000
@@ -605,7 +605,7 @@
     ZORBA_ASSERT(false);
   }
 
-  return BuiltinFunctionLibrary::getFunction(newKind);
+  return GENV_FUNC_LIB->getFunction(newKind);
 }
 
 

=== modified file 'src/compiler/translator/translator.cpp'
--- src/compiler/translator/translator.cpp	2013-06-27 00:05:25 +0000
+++ src/compiler/translator/translator.cpp	2013-07-11 13:41:52 +0000
@@ -684,7 +684,7 @@
 
   std::stack<bool>                       theInWhileStack;
 
-  rchandle<AnnotationList>               theAnnotations;
+  std::auto_ptr<AnnotationList>          theAnnotations;
 
   IndexDecl_t                            theIndexDecl;
   bool                                   theIsInIndexDomain;
@@ -1123,7 +1123,7 @@
     }
     else if (local == "atomic")
     {
-      ns = XML_SCHEMA_NS;
+      ns = static_context::W3C_XML_SCHEMA_NS;
       local = "anyAtomicType";
     }
     else
@@ -1136,7 +1136,7 @@
                           WARN_LOC(loc)));
      }
       
-      ns = XML_SCHEMA_NS;
+      ns = static_context::W3C_XML_SCHEMA_NS;
     }
 
     GENV_ITEMFACTORY->createQName(qnameItem, ns, "", local);
@@ -1428,18 +1428,18 @@
   such a binding exists already in any of these sctxs.
 ********************************************************************************/
 void bind_fn(
-    function_t& f,
+    const function_t& f,
     csize nargs,
     const QueryLoc& loc)
 {
-  theSctx->bind_fn(f, nargs, loc);
-
   theModulesInfo->theGlobalSctx->bind_fn(f, nargs, loc);
 
   if (theExportSctx != NULL)
   {
     theExportSctx->bind_fn(f, nargs, loc);
   }
+
+  theSctx->bind_fn(f, nargs, loc);
 }
 
 
@@ -1647,14 +1647,14 @@
   inlineFuncExpr->add_variable(fiVar, fiSubstVar);
 
   // Create the inline udf obj.
-  user_function_t inlineUDF = 
+  std::auto_ptr<user_function> inlineUDF( 
   new user_function(loc,
                     signature(function_item_expr::create_inline_fname(loc),
                               funcType->get_param_types(),
                               returnType),
                     NULL,
                     SIMPLE_EXPR,
-                    theCCB);
+                    theCCB));
 
   std::vector<var_expr*> argVars;
   std::vector<expr*> arguments;    // Arguments to the dynamic function call
@@ -1669,7 +1669,7 @@
     argVars.push_back(argVar);
 
     expr* arg = CREATE(wrapper)(theRootSctx, theUDF, loc, argVar);
-    arg = normalize_fo_arg(i, arg, inlineUDF, loc);
+    arg = normalize_fo_arg(i, arg, inlineUDF.get(), loc);
     arguments.push_back(arg);
   }
 
@@ -1696,7 +1696,7 @@
   inlineUDF->setArgVars(argVars);
   inlineUDF->setOptimized(true);
 
-  inlineFuncExpr->set_function(inlineUDF, inlineUDF->numArgs());
+  inlineFuncExpr->set_function(inlineUDF.release(), inlineUDF->numArgs());
 
   // pop the scope.
   pop_scope();
@@ -1813,12 +1813,9 @@
     fkind = FunctionConsts::OP_SORT_DISTINCT_NODES_ASC_1;
   }
 
-  fo_expr* dos = theExprManager->
-  create_fo_expr(theRootSctx,
-                 theUDF,
-                 expr->get_loc(),
-                 BuiltinFunctionLibrary::getFunction(fkind),
-                 expr);
+  fo_expr* dos = CREATE(fo)(theRootSctx, theUDF, expr->get_loc(),
+                            GENV_FUNC_LIB->getFunction(fkind),
+                            expr);
 
   normalize_fo(dos);
 
@@ -2209,7 +2206,7 @@
       theSctx->bind_ns(pfx, targetNS, loc);
   }
 
-  if (targetNS == XML_SCHEMA_NS)
+  if (targetNS == static_context::W3C_XML_SCHEMA_NS)
   {
     // Xerces doesn't like importing XMLSchema.xsd schema4schema, so we skip it
     // see Xerces-C++ bug: https://issues.apache.org/jira/browse/XERCESC-1980
@@ -3216,7 +3213,7 @@
     RAISE_ERROR(err::XQST0070, loc,
     ERROR_PARAMS(ZED(XQST0070_ReservedPrefixInDecl_2), pre));
   }
-  else if (uri == XML_NS || uri == XMLNS_NS)
+  else if (uri == static_context::W3C_XML_NS || uri == XMLNS_NS)
   {
     RAISE_ERROR(err::XQST0070, loc,
     ERROR_PARAMS(ZED(XQST0070_ReservedURI_23), pre, uri));
@@ -3243,7 +3240,7 @@
 
   zstring uri = v.get_default_namespace();
 
-  if (uri == XML_NS || uri == XMLNS_NS)
+  if (uri == static_context::W3C_XML_NS || uri == XMLNS_NS)
   {
     RAISE_ERROR(err::XQST0070, loc,
     ERROR_PARAMS(ZED(XQST0070_ReservedURI_23), "", uri));
@@ -3515,7 +3512,7 @@
 
       // Get the parent of the query root sctx. This is the user-specified sctx
       // (if any) or the zorba root sctx (if no user-specified sctx).
-      static_context_t independentSctx =
+      static_context* independentSctx =
       static_cast<static_context *>(theCCB->theRootSctx->get_parent());
 
       // Create the root sctx for the imported module as a child of the
@@ -3841,7 +3838,7 @@
       {
         annotations->accept(*this);
 
-        if (theAnnotations)
+        if (theAnnotations.get())
         {
           theAnnotations->
           checkConflictingDeclarations(AnnotationList::var_decl, loc);
@@ -3874,7 +3871,7 @@
         ve->set_mutable(theSctx->is_feature_set(feature::scripting));
       }
 
-      theAnnotations = NULL;
+      theAnnotations.reset(NULL);
 
       // Put a mapping between the var name and the var_expr in the local sctx.
       // Raise error if var name exists already in local sctx obj.
@@ -3927,8 +3924,8 @@
       RAISE_ERROR(err::XQST0060, loc, ERROR_PARAMS(qnameItem->getStringValue()));
 
     if (ns == static_context::W3C_FN_NS ||
-        ns == XML_NS ||
-        ns == XML_SCHEMA_NS ||
+        ns == static_context::W3C_XML_NS ||
+        ns == static_context::W3C_XML_SCHEMA_NS ||
         ns == XSI_NS ||
         ns == static_context::XQUERY_MATH_FN_NS)
     {
@@ -3984,12 +3981,12 @@
     }
 
     // Create the function signature.
-    bool isVariadic = (theAnnotations ? ZANN_CONTAINS(zann_variadic): false);
+    bool isVariadic = (theAnnotations.get() ? ZANN_CONTAINS(zann_variadic): false);
 
     signature sig(qnameItem, paramTypes, returnType, isVariadic);
 
     // Get the scripting kind of the function
-    bool isSequential = (theAnnotations ?
+    bool isSequential = (theAnnotations.get() ?
                          ZANN_CONTAINS(zann_sequential) :
                          false);
 
@@ -4001,12 +3998,12 @@
       scriptKind = SEQUENTIAL_FUNC_EXPR;
 
     // create the function object
-    function_t f;
+    function_t func;
 
     if (func_decl->is_external())
     {
       // 1. lookup if the function is a built-in function
-      f = theSctx->lookup_fn(qnameItem, numParams, false);
+      function* f = theSctx->lookup_fn(qnameItem, numParams, false);
 
       if (f != 0)
       {
@@ -4036,8 +4033,8 @@
                                     qnameItem->getLocalName())));
         }
 
-        f->setAnnotations(theAnnotations);
-        theAnnotations = NULL; // important to reset
+        f->setAnnotations(theAnnotations.get());
+        theAnnotations.release(); // important to reset
 
         // continue with the next declaration, because we don't add already
         // built-in functions to the static context
@@ -4080,25 +4077,27 @@
 
       ZORBA_ASSERT(ef != NULL);
 
-      f = new external_function(loc,
-                                theRootSctx,
-                                qnameItem->getNamespace(),
-                                sig,
-                                scriptKind,
-                                ef);
+      func = new external_function(loc,
+                                   theRootSctx,
+                                   qnameItem->getNamespace(),
+                                   sig,
+                                   scriptKind,
+                                   ef);
     }
-    else // Process UDF (non-external) function declaration
+    else
     {
-      f = new user_function(loc, sig, NULL, scriptKind, theCCB); // no body for now
+      // It's a UDF (non-external) function declaration. Create a user_function
+      // obj with no body for now.
+      func = new user_function(loc, sig, NULL, scriptKind, theCCB);
     }
 
-    f->setAnnotations(theAnnotations);
-    theAnnotations = NULL; // important to reset
+    func->setAnnotations(theAnnotations.get());
+    theAnnotations.release(); // important to reset
 
     // Create bindings between (function qname item, arity) and function obj
     // in the current sctx of this module and, if this is a lib module, in its
     // export sctx as well.
-    bind_fn(f, numParams, loc);
+    bind_fn(func, numParams, loc);
   }
 
   if (haveXQueryOptions)
@@ -4753,7 +4752,7 @@
 
     ve->set_mutable(false);
 
-    theAnnotations = NULL;
+    theAnnotations.reset(NULL);
 
     // Put a mapping between the var name and the var_expr in the local sctx.
     // Raise error if var name exists already in local sctx obj.
@@ -4819,9 +4818,9 @@
 {
   TRACE_VISIT();
 
-  assert(theAnnotations == NULL);
+  assert(theAnnotations.get() == NULL);
 
-  theAnnotations = new AnnotationList();
+  theAnnotations.reset(new AnnotationList());
 
   return no_state;
 }
@@ -4861,7 +4860,7 @@
 
   if (annotNS == static_context::XQUERY_NS ||
       annotNS == static_context::W3C_XML_NS ||
-      annotNS == XML_SCHEMA_NS ||
+      annotNS == static_context::W3C_XML_SCHEMA_NS ||
       annotNS == XSI_NS ||
       annotNS == static_context::W3C_FN_NS ||
       annotNS == static_context::XQUERY_MATH_FN_NS ||
@@ -4977,9 +4976,9 @@
     lAnns->accept(*this);
   }
 
-  if ( !theAnnotations )
+  if (theAnnotations.get() == NULL)
   {
-    theAnnotations = new AnnotationList();
+    theAnnotations.reset(new AnnotationList());
   }
 
   theAnnotations->
@@ -5058,14 +5057,14 @@
   // Create the collection object and register it in the static context
   StaticallyKnownCollection_t lColl = new StaticallyKnownCollection(
                                             lExpandedQName,
-                                            theAnnotations,
+                                            theAnnotations.get(),
                                             lNodeType,
                                             lCollectionType,
                                             lUpdateMode,
                                             lOrderMode,
                                             lNodeModifier);
 
-  theAnnotations = NULL; // important to reset
+  theAnnotations.release(); // important to reset
 
   theSctx->bind_collection(lColl, loc);
 
@@ -5136,7 +5135,7 @@
     lAnns->accept(*this);
   }
 
-  if (theAnnotations)
+  if (theAnnotations.get())
   {
     theAnnotations->
     checkConflictingDeclarations(AnnotationList::index_decl, loc);
@@ -5161,7 +5160,7 @@
     }
   }
 
-  theAnnotations = NULL;
+  theAnnotations.reset(NULL);
 
   theIndexDecl = index;
   theIsInIndexDomain = true;
@@ -6502,7 +6501,7 @@
 
   var_expr* ve = dynamic_cast<var_expr*>(pop_nodestack());
 
-  if (theAnnotations)
+  if (theAnnotations.get())
   {
     theAnnotations->
     checkConflictingDeclarations(AnnotationList::var_decl, loc);
@@ -6546,7 +6545,7 @@
 
   push_nodestack(initExpr);
 
-  theAnnotations = NULL;
+  theAnnotations.reset(NULL);
 }
 
 
@@ -12595,17 +12594,17 @@
     const QueryLoc& loc)
 {
   xqtref_t type;
-  rchandle<user_function> udf;
+  std::auto_ptr<user_function> udf;
   expr* body;
   
   function_item_expr* fiExpr =
   CREATE(function_item)(theRootSctx, theUDF, loc, false, false);
 
-  function* f = theSctx->lookup_fn(qnameItem, arity, loc);
+  function* func = theSctx->lookup_fn(qnameItem, arity, loc);
 
   // Raise XPST0017 if function could not be found, unless it is a type constructor
   // function
-  if (f == NULL)
+  if (func == NULL)
   {
     type = CTX_TM->
     create_named_type(qnameItem, TypeConstants::QUANT_QUESTION, loc);
@@ -12623,16 +12622,16 @@
     var_expr* argVar = create_temp_var(loc, var_expr::arg_var);
     argVar->set_param_pos(0);
     udfArgs[0] = argVar;
-    expr* body = CREATE(cast)(theRootSctx, udf, loc, argVar, type, false);
+    expr* body = CREATE(cast)(theRootSctx, theUDF, loc, argVar, type, false);
 
-    udf = new user_function(loc,
-                            signature(qnameItem, theRTM.ITEM_TYPE_QUESTION, type),
-                            body,
-                            SIMPLE_EXPR,
-                            theCCB);
+    udf.reset(new user_function(loc,
+                                signature(qnameItem, theRTM.ITEM_TYPE_QUESTION, type),
+                                body,
+                                SIMPLE_EXPR,
+                                theCCB));
 
     udf->setArgVars(udfArgs);
-    f = udf;
+    func = udf.get();
   }
   else
   {
@@ -12640,7 +12639,7 @@
     // the module it belongs to has been imported.
     const zstring& fn_ns = qnameItem->getNamespace();
 
-    if (f->isBuiltin() &&
+    if (func->isBuiltin() &&
         fn_ns != static_context::W3C_FN_NS &&
         fn_ns != static_context::JSONIQ_FN_NS &&
         fn_ns != static_context::XQUERY_MATH_FN_NS &&
@@ -12655,15 +12654,15 @@
 
     // If it is a builtin function F with signature (R, T1, ..., TN) , wrap it
     // in a udf UF: function UF(x1 as T1, ..., xN as TN) as R { F(x1, ... xN) }
-    if (!f->isUdf())
+    if (!func->isUdf())
     {
-      FunctionConsts::FunctionKind fkind = f->getKind();
+      FunctionConsts::FunctionKind fkind = func->getKind();
 
-      udf = new user_function(loc,
-                              f->getSignature(),
-                              NULL, // no body for now
-                              f->getScriptingKind(),
-                              theCCB);
+      udf.reset(new user_function(loc,
+                                  func->getSignature(),
+                                  NULL, // no body for now
+                                  func->getScriptingKind(),
+                                  theCCB));
 
       std::vector<expr*> foArgs(arity);
       std::vector<var_expr*> udfArgs(arity);
@@ -12696,13 +12695,13 @@
 
           fiExpr->add_variable(posVarRef, substVar);
 
-          body = generate_fn_body(f, foArgs, loc);
+          body = generate_fn_body(func, foArgs, loc);
 
           pop_scope();
         }
         else
         {
-          body = generate_fn_body(f, foArgs, loc);
+          body = generate_fn_body(func, foArgs, loc);
         }
 
         break;
@@ -12725,13 +12724,13 @@
 
           fiExpr->add_variable(sizeVarRef, substVar);
 
-          body = generate_fn_body(f, foArgs, loc);
+          body = generate_fn_body(func, foArgs, loc);
 
           pop_scope();
         }
         else
         {
-          body = generate_fn_body(f, foArgs, loc);
+          body = generate_fn_body(func, foArgs, loc);
         }
 
         break;
@@ -12773,13 +12772,13 @@
 
           fiExpr->add_variable(dotVarRef, substVar);
 
-          body = generate_fn_body(f, foArgs, loc);
+          body = generate_fn_body(func, foArgs, loc);
 
           pop_scope();
         }
         else
         {
-          body = generate_fn_body(f, foArgs, loc);
+          body = generate_fn_body(func, foArgs, loc);
         }
 
         break;
@@ -12793,7 +12792,7 @@
         flworBody->add_clause(lc);
         foArgs[1] = CREATE(wrapper)(theRootSctx, theUDF, loc, lc->get_var());
 
-        flworBody->set_return_expr(generate_fn_body(f, foArgs, loc));
+        flworBody->set_return_expr(generate_fn_body(func, foArgs, loc));
         body = flworBody;
         break;
       }
@@ -12853,7 +12852,7 @@
           fiExpr->add_variable(ctxVRef, substVar);
         }
 
-        body = generate_fn_body(f, foArgs, loc);
+        body = generate_fn_body(func, foArgs, loc);
 
         if (varAdded)
           pop_scope();
@@ -12862,7 +12861,7 @@
       }
       default:
       {
-        body = generate_fn_body(f, foArgs, loc);
+        body = generate_fn_body(func, foArgs, loc);
         break;
       }
       } // switch 
@@ -12873,7 +12872,7 @@
     } // if builtin function
     else
     {
-      udf = static_cast<user_function*>(f);
+      udf.reset(static_cast<user_function*>(func));
     }
   }
 
@@ -12882,7 +12881,7 @@
   // because the function item expression may be a forward refereence to a real
   // UDF, in which case udf->numArgs() returns 0 since the UDF declaration has
   // not been fully processed yet.  
-  fiExpr->set_function(udf, arity);
+  fiExpr->set_function(udf.release(), arity);
 
   return fiExpr;
 }
@@ -13035,14 +13034,14 @@
   }
 
   // Create the udf obj.
-  user_function_t udf = 
+  std::auto_ptr<user_function> udf( 
   new user_function(loc,
                     signature(function_item_expr::create_inline_fname(loc),
                               paramTypes,
                               returnType),
                     NULL,
                     SIMPLE_EXPR,
-                    theCCB);
+                    theCCB));
 
   // Parameters, if any, have been translated into LET vars in a flwor expr.
   // The UDF body, which in genral references these LET vars, must become the
@@ -13064,7 +13063,7 @@
       // for arg-value type checking must be placed in the body of the udf itself,
       // instead of the caller.
       argVar->set_type(theRTM.ITEM_TYPE_STAR);
-      lc->set_expr(normalize_fo_arg(i, lc->get_expr(), udf.getp(), loc));
+      lc->set_expr(normalize_fo_arg(i, lc->get_expr(), udf.get(), loc));
 
       argVars.push_back(argVar);
     }
@@ -13078,11 +13077,13 @@
   // Get the function_item_expr and set its function to the udf created above.
   function_item_expr* fiExpr = dynamic_cast<function_item_expr*>(theNodeStack.top());
   assert(fiExpr != NULL);
-  fiExpr->set_function(udf, udf->numArgs());
+  fiExpr->set_function(udf.get(), udf->numArgs());
 
   if (theCCB->theConfig.translate_cb != NULL)
     theCCB->theConfig.translate_cb(udf->getBody(),
                                    udf->getName()->getStringValue().c_str());
+
+  udf.release();
 }
 
 
@@ -13510,13 +13511,13 @@
 
     if (have_uri)
     {
-      if ((ZSTREQ(prefix, "xml") && !ZSTREQ(uri, XML_NS)))
+      if ((ZSTREQ(prefix, "xml") && uri != static_context::W3C_XML_NS))
       {
         RAISE_ERROR(err::XQST0070, loc,
         ERROR_PARAMS(ZED(XQST0070_ReservedPrefix_23), prefix, uri));
       }
 
-      if ((ZSTREQ(uri, XML_NS) && !ZSTREQ(prefix, "xml")) ||
+      if ((uri == static_context::W3C_XML_NS && !ZSTREQ(prefix, "xml")) ||
            ZSTREQ(uri, XMLNS_NS))
       {
         RAISE_ERROR(err::XQST0070, loc,

=== modified file 'src/compiler/xqddf/collection_decl.cpp'
--- src/compiler/xqddf/collection_decl.cpp	2013-02-07 17:24:36 +0000
+++ src/compiler/xqddf/collection_decl.cpp	2013-07-11 13:41:52 +0000
@@ -34,10 +34,10 @@
 
 ********************************************************************************/
 StaticallyKnownCollection::StaticallyKnownCollection(
-    store::Item_t&          aName,
-    const AnnotationList_t& aAnnotations,
-    xqtref_t&               aNodeType,
-    xqtref_t&               aCollectionType,
+    store::Item_t& aName,
+    AnnotationList* aAnnotations,
+    xqtref_t& aNodeType,
+    xqtref_t& aCollectionType,
     StaticContextConsts::declaration_property_t aUpdateProperty,
     StaticContextConsts::declaration_property_t aOrderProperty,
     StaticContextConsts::node_modifier_t        aNodeModifier
@@ -59,6 +59,7 @@
 ********************************************************************************/
 StaticallyKnownCollection::~StaticallyKnownCollection() 
 {
+  delete theAnnotations;
 }
 
 

=== modified file 'src/compiler/xqddf/collection_decl.h'
--- src/compiler/xqddf/collection_decl.h	2013-02-07 17:24:36 +0000
+++ src/compiler/xqddf/collection_decl.h	2013-07-11 13:41:52 +0000
@@ -33,7 +33,7 @@
 {
 private:
   store::Item_t                                theName;
-  AnnotationList_t                             theAnnotations;
+  AnnotationList                             * theAnnotations;
   xqtref_t                                     theNodeType; 
   xqtref_t                                     theCollectionType;
 
@@ -53,10 +53,10 @@
 
 public:
   StaticallyKnownCollection(
-        store::Item_t&          name,
-        const AnnotationList_t& nannotationList,
-        xqtref_t&               nodeType,
-        xqtref_t&               collectionType,
+        store::Item_t& name,
+        AnnotationList* annotationList,
+        xqtref_t& nodeType,
+        xqtref_t& collectionType,
         StaticContextConsts::declaration_property_t updateProperty,
         StaticContextConsts::declaration_property_t orderProperty,
         StaticContextConsts::node_modifier_t        nodeModifier);
@@ -65,7 +65,7 @@
 
   const store::Item* getName() const { return theName.getp(); }
 
-  AnnotationList* getAnnotations() const { return theAnnotations.getp(); };
+  AnnotationList* getAnnotations() const { return theAnnotations; }
 
   StaticContextConsts::declaration_property_t getUpdateProperty() const
   {

=== modified file 'src/context/root_static_context.cpp'
--- src/context/root_static_context.cpp	2013-06-09 08:09:40 +0000
+++ src/context/root_static_context.cpp	2013-07-11 13:41:52 +0000
@@ -141,8 +141,8 @@
     "jn", static_context::JSONIQ_FN_NS,
     "js", static_context::JSONIQ_DM_NS,
     "local", XQUERY_LOCAL_FN_NS,
-    "xml", XML_NS,
-    "xs", XML_SCHEMA_NS,
+    "xml", static_context::W3C_XML_NS,
+    "xs", static_context::W3C_XML_SCHEMA_NS,
     "xsi", XSI_NS,
     NULL, NULL
   };
@@ -275,5 +275,10 @@
 {
 }
 
+
+void root_static_context::free()
+{
+}
+
 }
 /* vim:set et sw=2 ts=2: */

=== modified file 'src/context/root_static_context.h'
--- src/context/root_static_context.h	2013-02-07 17:24:36 +0000
+++ src/context/root_static_context.h	2013-07-11 13:41:52 +0000
@@ -40,6 +40,8 @@
 
   void init();
 
+  virtual void free();
+
   const char** get_builtin_uri_path() const { return theBuiltinURIPath; }
   const char** get_builtin_lib_path() const { return theBuiltinLibPath; }
 };

=== modified file 'src/context/static_context.cpp'
--- src/context/static_context.cpp	2013-07-04 22:17:19 +0000
+++ src/context/static_context.cpp	2013-07-11 13:41:52 +0000
@@ -131,12 +131,13 @@
 *******************************************************************************/
 FunctionInfo::FunctionInfo()
   :
+  theFunction(NULL),
   theIsDisabled(false)
 {
 }
 
 
-FunctionInfo::FunctionInfo(const function_t& f, bool disabled)
+FunctionInfo::FunctionInfo(function* f, bool disabled)
   :
   theFunction(f),
   theIsDisabled(disabled)
@@ -324,14 +325,15 @@
 const zstring
 static_context::DOT_SIZE_VAR_NAME = "$$context-size";
 
+
 const char*
 static_context::W3C_NS_PREFIX = "http://www.w3.org/";;
 
 const char*
-static_context::ZORBA_NS_PREFIX = "http://www.zorba-xquery.com/";;
+static_context::W3C_XML_NS = "http://www.w3.org/XML/1998/namespace";;
 
 const char*
-static_context::ZORBA_IO_NS_PREFIX = "http://zorba.io/";;
+static_context::W3C_XML_SCHEMA_NS = "http://www.w3.org/2001/XMLSchema";;
 
 const char*
 static_context::W3C_FN_NS = "http://www.w3.org/2005/xpath-functions";;
@@ -340,11 +342,15 @@
 static_context::W3C_ERR_NS = "http://www.w3.org/2005/xqt-errors";;
 
 const char*
-static_context::W3C_XML_NS = "http://www.w3.org/XML/1998/namespace";;
-
-const char*
 static_context::XQUERY_MATH_FN_NS = "http://www.w3.org/2005/xpath-functions/math";;
 
+
+const char*
+static_context::ZORBA_NS_PREFIX = "http://www.zorba-xquery.com/";;
+
+const char*
+static_context::ZORBA_IO_NS_PREFIX = "http://zorba.io/";;
+
 const char*
 static_context::ZORBA_MATH_FN_NS =
 "http://www.zorba-xquery.com/modules/math";;
@@ -779,7 +785,7 @@
             << parent << std::endl;
 #endif
 
-  if (theParent != NULL)
+  if (theParent != NULL && !theParent->is_global_root_sctx())
     RCHelper::addReference(theParent);
 }
 
@@ -789,7 +795,7 @@
 ********************************************************************************/
 static_context::static_context(::zorba::serialization::Archiver& ar)
   :
-  SimpleRCObject(ar),
+  SyncedRCObject(ar),
   theParent(NULL),
   theTraceStream(NULL),
   theQueryExpr(NULL),
@@ -871,7 +877,9 @@
     delete theICMap;
 
   if (theFunctionMap)
+  {
     delete theFunctionMap;
+  }
 
   if (theFunctionArityMap)
   {
@@ -879,7 +887,8 @@
     FunctionArityMap::iterator end = theFunctionArityMap->end();
     for (; ite != end; ++ite)
     {
-      delete (*ite).second;
+      std::vector<FunctionInfo>* fv = ite.getValue();
+      delete fv;
     }
 
     delete theFunctionArityMap;
@@ -926,7 +935,7 @@
   if (theBaseUriInfo)
     delete theBaseUriInfo;
 
-  if (theParent)
+  if (theParent && !theParent->is_global_root_sctx())
     RCHelper::removeReference(theParent);
 }
 
@@ -1062,7 +1071,7 @@
     ar & parent_is_root;
     ar.set_is_temp_field(false);
 
-    if(!parent_is_root)
+    if (!parent_is_root)
     {
       ar.dont_allow_delay();
       ar & theParent;
@@ -1081,15 +1090,16 @@
     ar & parent_is_root;
     ar.set_is_temp_field(false);
 
-    if(parent_is_root)
+    if (parent_is_root)
     {
-      set_parent_as_root();
+      theParent = &GENV_ROOT_STATIC_CONTEXT;
     }
     else
+    {
       ar & theParent;
-
-    if (theParent)
-      theParent->addReference(SYNC_CODE(theParent->getRCLock()));
+      ZORBA_ASSERT(theParent);
+      theParent->addReference();
+    }
   }
 
   ar & theModuleNamespace;
@@ -1198,15 +1208,6 @@
 /***************************************************************************//**
 
 ********************************************************************************/
-void static_context::set_parent_as_root()
-{
-  theParent = &GENV_ROOT_STATIC_CONTEXT;
-}
-
-
-/***************************************************************************//**
-
-********************************************************************************/
 expr* static_context::get_query_expr() const
 {
   return theQueryExpr;
@@ -1891,7 +1892,7 @@
     store::Item_t& validatedResult,
     StaticContextConsts::validation_mode_t validationMode) const
 {
-  zstring xsTns(XML_SCHEMA_NS);
+  zstring xsTns(static_context::W3C_XML_SCHEMA_NS);
   return validate(rootElement, validatedResult, xsTns, validationMode);
 }
 
@@ -2456,7 +2457,7 @@
 
 ********************************************************************************/
 void static_context::bind_fn(
-    function_t& f,
+    const function_t& f,
     csize arity,
     const QueryLoc& loc)
 {
@@ -2473,17 +2474,18 @@
     theFunctionMap = new FunctionMap(HashMapItemPointerCmp(0, NULL), size, false);
   }
 
-  FunctionInfo fi(f);
+  FunctionInfo fi(f.getp());
 
   if (!theFunctionMap->insert(qname, fi))
   {
     // There is already a function F with the given qname in theFunctionMap.
     // First, check if F is the same as f, which implies that f is disabled.
     // In this case, re-enable f. Otherwise, we have to use theFunctionArityMap.
-    if (fi.theFunction == f)
+    if (fi.theFunction.getp() == f)
     {
       ZORBA_ASSERT(fi.theIsDisabled);
       fi.theIsDisabled = false;
+      theFunctionMap->update(qname, fi);
       return;
     }
 
@@ -2505,7 +2507,7 @@
       csize numFunctions = fv->size();
       for (csize i = 0; i < numFunctions; ++i)
       {
-        if ((*fv)[i].theFunction == f)
+        if ((*fv)[i].theFunction.getp() == f)
         {
           ZORBA_ASSERT((*fv)[i].theIsDisabled);
           (*fv)[i].theIsDisabled = false;
@@ -2671,7 +2673,7 @@
   {
     if (sctx->theFunctionMap != NULL && sctx->theFunctionMap->get(qname2, fi))
     {
-      function* f = fi.theFunction.getp();
+      function* f = fi.theFunction;
 
       if (f->getArity() == arity || f->isVariadic())
       {
@@ -2694,7 +2696,7 @@
             if ((*fv)[i].theIsDisabled && skipDisabled)
               return NULL;
 
-            return (*fv)[i].theFunction.getp();
+            return (*fv)[i].theFunction;
           }
         }
       }
@@ -2722,7 +2724,7 @@
 
   if (theFunctionMap != NULL && theFunctionMap->get(qname2, fi))
   {
-    function* f = fi.theFunction.getp();
+    function* f = fi.theFunction;
 
     if (f->getArity() == arity || f->isVariadic())
     {
@@ -2744,7 +2746,7 @@
           if ((*fv)[i].theIsDisabled && skipDisabled)
             return NULL;
 
-          return (*fv)[i].theFunction.getp();
+          return (*fv)[i].theFunction;
         }
       }
     }
@@ -2784,7 +2786,7 @@
 
       for (; ite != end; ++ite)
       {
-        function* f = (*ite).second.theFunction.getp();
+        function* f = (*ite).second.theFunction;
 
         if (!(*ite).second.theIsDisabled)
         {
@@ -2842,10 +2844,10 @@
       {
         std::vector<FunctionInfo>* fv = (*ite).second;
 
-        ulong numFunctions = (ulong)fv->size();
-        for (ulong i = 0; i < numFunctions; ++i)
+        csize numFunctions = fv->size();
+        for (csize i = 0; i < numFunctions; ++i)
         {
-          function* f = (*fv)[i].theFunction.getp();
+          function* f = (*fv)[i].theFunction;
 
           if (!(*fv)[i].theIsDisabled)
           {
@@ -2909,7 +2911,7 @@
   if (theFunctionMap != NULL && theFunctionMap->get(qname2, fi))
   {
     if (!fi.theIsDisabled)
-      functions.push_back(fi.theFunction.getp());
+      functions.push_back(fi.theFunction);
   }
 
   std::vector<FunctionInfo>* fv = NULL;
@@ -2920,7 +2922,7 @@
     for (ulong i = 0; i < numFunctions; ++i)
     {
       if (!(*fv)[i].theIsDisabled)
-        functions.push_back((*fv)[i].theFunction.getp());
+        functions.push_back((*fv)[i].theFunction);
     }
   }
 
@@ -3217,11 +3219,8 @@
 
   if (lookup_index(qname) != NULL)
   {
-    throw XQUERY_EXCEPTION(
-      zerr::ZDST0021_INDEX_ALREADY_DECLARED,
-      ERROR_PARAMS( qname->getStringValue() ),
-      ERROR_LOC( loc )
-    );
+    RAISE_ERROR(zerr::ZDST0021_INDEX_ALREADY_DECLARED, loc,
+    ERROR_PARAMS(qname->getStringValue()));
   }
 
   if (theIndexMap == NULL)
@@ -4354,7 +4353,7 @@
     FunctionMap::iterator end = module->theFunctionMap->end();
     for (; ite != end; ++ite)
     {
-      function_t f = (*ite).second.theFunction;
+      function* f = (*ite).second.theFunction;
       if (!f->isPrivate())
         bind_fn(f, f->getArity(), loc);
     }
@@ -4378,7 +4377,7 @@
       csize num = fv->size();
       for (csize i = 0; i < num; ++i)
       {
-        function_t f = (*fv)[i].theFunction;
+        function* f = (*fv)[i].theFunction;
         bind_fn(f, f->getArity(), loc);
       }
     }

=== modified file 'src/context/static_context.h'
--- src/context/static_context.h	2013-06-26 00:26:58 +0000
+++ src/context/static_context.h	2013-07-11 13:41:52 +0000
@@ -145,7 +145,7 @@
 public:
   FunctionInfo();
 
-  FunctionInfo(const function_t& f, bool disabled = false);
+  FunctionInfo(function* f, bool disabled = false);
 
   ~FunctionInfo();
 };
@@ -287,7 +287,8 @@
 
   theParent :
   -----------
-  Pointer to the parent sctx object in the sctx hierarchy.
+  Pointer to the parent sctx object in the sctx hierarchy. Manual ref counting
+  is done via this pointer on the parent, unless the parent is the root sctx.
 
   theTraceStream :
   ----------------
@@ -442,7 +443,7 @@
   context/featueres.h.
 ********************************************************************************/
 
-class static_context : public SimpleRCObject
+class static_context : public SyncedRCObject
 {
   ITEM_PTR_HASH_MAP(StaticallyKnownCollection_t, CollectionMap);
 
@@ -499,6 +500,8 @@
 
   static const char* W3C_XML_NS;    // http://www.w3.org/XML/1998/namespace
 
+  static const char* W3C_XML_SCHEMA_NS; // // http://www.w3.org/2001/XMLSchema
+
   static const char* W3C_FN_NS;     // http://www.w3.org/2005/xpath-functions
   
   static const char* W3C_ERR_NS;    // http://www.w3.org/2005/xqt-errors
@@ -569,11 +572,14 @@
   static const char* ZORBA_OPTION_WARN_NS;
   static const char* ZORBA_OPTION_FEATURE_NS;
   static const char* ZORBA_OPTION_OPTIM_NS;
+
   static const char* XQUERY_NS;                 // http://www.w3.org/2012/xquery
   static const char* XQUERY_OPTION_NS;          // http://www.w3.org/2011/xquery-options
   static const char* ZORBA_VERSIONING_NS;
 
 protected:
+  SYNC_CODE(mutable RCLock                theRCLock;)
+
   static_context                        * theParent;
 
   std::ostream                          * theTraceStream;
@@ -696,6 +702,8 @@
 
   ~static_context();
 
+  SYNC_CODE(RCLock* getRCLock() const { return &theRCLock; })
+
   static_context* get_parent() const { return theParent; }
 
   static_context* create_child_context();
@@ -901,7 +909,7 @@
   //
   // Functions
   //
-  void bind_fn(function_t& f, csize arity, const QueryLoc& loc);
+  void bind_fn(const function_t& f, csize arity, const QueryLoc& loc);
 
   void unbind_fn(const store::Item* qname, csize arity);
 
@@ -929,8 +937,8 @@
         std::vector<function*>& functions) const;
 
   void bind_external_module(
-        ExternalModule* aModule,
-        bool aDynamicallyLoaded = false);
+        ExternalModule* module,
+        bool dynamicallyLoaded = false);
 
   ExternalFunction* lookup_external_function(
         const zstring& prefix,
@@ -1152,8 +1160,6 @@
   //serialization helpers
   bool check_parent_is_root();
 
-  void set_parent_as_root();
-
 private:
 
   void apply_uri_mappers(

=== modified file 'src/functions/external_function.cpp'
--- src/functions/external_function.cpp	2013-02-07 17:24:36 +0000
+++ src/functions/external_function.cpp	2013-07-11 13:41:52 +0000
@@ -43,13 +43,12 @@
     unsigned short scriptingType,
     ExternalFunction* impl) 
   :
-  function(sig, FunctionConsts::FN_UNKNOWN),
+  function(sig, FunctionConsts::FN_UNKNOWN, false),
   theLoc(loc),
   theNamespace(ns),
   theScriptingKind(scriptingType),
   theImpl(impl)
 {
-  resetFlag(FunctionConsts::isBuiltin);
   theModuleSctx = modSctx;
 }
 

=== modified file 'src/functions/function.cpp'
--- src/functions/function.cpp	2013-04-15 13:52:08 +0000
+++ src/functions/function.cpp	2013-07-11 13:41:52 +0000
@@ -34,39 +34,42 @@
 namespace zorba {
 
 
-#ifdef PRE_SERIALIZE_BUILTIN_FUNCTIONS
-SERIALIZE_INTERNAL_METHOD(function)
-#else
 SERIALIZABLE_CLASS_VERSIONS(function);
-#endif
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-function::function(const signature& sig, FunctionConsts::FunctionKind kind)
+function::function(
+    const signature& sig,
+    FunctionConsts::FunctionKind kind,
+    bool isBuiltin)
   :
   theSignature(sig),
   theKind(kind),
   theFlags(0),
+  theAnnotationList(NULL),
   theModuleSctx(NULL),
   theXQueryVersion(StaticContextConsts::xquery_version_1_0)
 {
-  setFlag(FunctionConsts::isBuiltin);
+  if (isBuiltin)
+  {
+    setFlag(FunctionConsts::isBuiltin);
+#ifndef NDEBUG
+    theRefCount = 1000000;
+#endif
+  }
+
   setFlag(FunctionConsts::isDeterministic);
-
-#ifdef PRE_SERIALIZE_BUILTIN_FUNCTIONS
-  zorba::serialization::Archiver& ar =
-  *::zorba::serialization::ClassSerializer::getInstance()->
-  getArchiverForHardcodedObjects();
-
-  if (ar.is_loading_hardcoded_objects())
-  {
-    // register this hardcoded object to help plan serialization
-    function* this_ptr = this;
-    ar & this_ptr;
-  }
-#endif
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+function::~function()
+{
+  delete theAnnotationList;
 }
 
 
@@ -75,11 +78,6 @@
 ********************************************************************************/
 void function::serialize(::zorba::serialization::Archiver& ar)
 {
-#ifdef PRE_SERIALIZE_BUILTIN_FUNCTIONS
-  if (ar.is_loading_hardcoded_objects())
-    return;
-#endif
-
   ar & theSignature;
   SERIALIZE_ENUM(FunctionConsts::FunctionKind, theKind);
   ar & theFlags;
@@ -87,13 +85,19 @@
   ar & theModuleSctx;
   SERIALIZE_ENUM(StaticContextConsts::xquery_version_t, theXQueryVersion);
 
-  // If we don't pre-serialize builtin function, it is possible that a builtin
-  // functions needs to be serialized. This happens for builtin functions that
-  // are disabled, and as a result, have been registered in a non-root static
-  // context.
-#ifdef PRE_SERIALIZE_BUILTIN_FUNCTIONS
-  ZORBA_ASSERT(!isBuiltin());
-#endif
+  // It is possible that a builtin function needs to be serialized. This happens
+  // for builtin functions that are disabled, and as a result, have been
+  // registered in a non-root static context.
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+void function::free()
+{
+  if (!isBuiltin())
+    delete this;
 }
 
 

=== modified file 'src/functions/function.h'
--- src/functions/function.h	2013-04-15 13:52:08 +0000
+++ src/functions/function.h	2013-07-11 13:41:52 +0000
@@ -54,25 +54,23 @@
 	signature                    theSignature;
   FunctionConsts::FunctionKind theKind;
   uint32_t                     theFlags;
-  AnnotationList_t             theAnnotationList;
+  AnnotationList             * theAnnotationList;
   static_context             * theModuleSctx;
 
   StaticContextConsts::xquery_version_t theXQueryVersion;
 
 
 public:
-#ifdef PRE_SERIALIZE_BUILTIN_FUNCTIONS
-  SERIALIZABLE_ABSTRACT_CLASS(function);
-#else
   SERIALIZABLE_CLASS(function);
-#endif
   SERIALIZABLE_CLASS_CONSTRUCTOR3(function, SimpleRCObject, theSignature);
   void serialize(::zorba::serialization::Archiver& ar);
 
 public:
-  function(const signature& sig, FunctionConsts::FunctionKind kind);
-
-  virtual ~function() {}
+  function(const signature& sig, FunctionConsts::FunctionKind k, bool isBuiltin = true);
+
+  virtual ~function();
+
+  void free();
 
   StaticContextConsts::xquery_version_t getXQueryVersion() const
   {
@@ -164,7 +162,7 @@
 
   void setAnnotations(AnnotationList* annotations);
 
-  const AnnotationList* getAnnotationList() const { return theAnnotationList.getp(); }
+  const AnnotationList* getAnnotationList() const { return theAnnotationList; }
 
 	bool validate_args(std::vector<PlanIter_t>& argv) const;
 

=== modified file 'src/functions/function_impl.h'
--- src/functions/function_impl.h	2013-02-07 17:24:36 +0000
+++ src/functions/function_impl.h	2013-07-11 13:41:52 +0000
@@ -44,23 +44,23 @@
 #define DECL_WITH_KIND(sctx, type, sig, kind)                           \
   do                                                                    \
   {                                                                     \
-    function_t type##_ptr(new type(signature sig, kind));               \
+    function* type##_ptr = new type(signature sig, kind);               \
     const store::Item* fname = type##_ptr->getName();                   \
     ulong cnt = type##_ptr->getSignature().paramCount();                \
     DEBUG_FN_DECL(fname, cnt);                                          \
     sctx->bind_fn(type##_ptr, cnt, QueryLoc::null);                     \
-    BuiltinFunctionLibrary::theFunctions[type##_ptr->getKind()] = type##_ptr.getp(); \
+    GENV_FUNC_LIB->addFunction(type##_ptr->getKind(), type##_ptr);      \
   } while(0)
 
 #define DECL(sctx, type, sig)                                           \
   do                                                                    \
   {                                                                     \
-    function_t type##_ptr(new type(signature sig));                     \
+    function* type##_ptr = new type(signature sig);                     \
     const store::Item* fname = type##_ptr->getName();                   \
     ulong cnt = type##_ptr->getSignature().paramCount();                \
     DEBUG_FN_DECL(fname, cnt);                                          \
     sctx->bind_fn(type##_ptr, cnt, QueryLoc::null);                     \
-    BuiltinFunctionLibrary::theFunctions[type##_ptr->getKind()] = type##_ptr.getp(); \
+    GENV_FUNC_LIB->addFunction(type##_ptr->getKind(), type##_ptr);      \
   } while(0)
 
 

=== modified file 'src/functions/library.cpp'
--- src/functions/library.cpp	2013-06-27 00:05:25 +0000
+++ src/functions/library.cpp	2013-07-11 13:41:52 +0000
@@ -91,8 +91,6 @@
 namespace zorba
 {
 
-function**  BuiltinFunctionLibrary::theFunctions = NULL;
-
 // clear static initializer state
 
 // dummy function to tell the windows linker to keep the library.obj
@@ -103,16 +101,16 @@
 }
 
 
-void BuiltinFunctionLibrary::create(static_context* sctx)
+BuiltinFunctionLibrary::BuiltinFunctionLibrary()
 {
-#ifdef PRE_SERIALIZE_BUILTIN_FUNCTIONS
-  zorba::serialization::Archiver& ar = *::zorba::serialization::ClassSerializer::getInstance()->getArchiverForHardcodedObjects();
-
-  ar.set_loading_hardcoded_objects(true);
-#endif
-
   theFunctions = new function*[FunctionConsts::FN_MAX_FUNC];
 
+  memset(&theFunctions[0], 0, FunctionConsts::FN_MAX_FUNC * sizeof(function*));
+}
+
+
+void BuiltinFunctionLibrary::populate(static_context* sctx)
+{
   populate_context_accessors(sctx);
   populate_context_any_uri(sctx);
   populate_context_accessors_impl(sctx);
@@ -180,8 +178,13 @@
 }
 
 
-void BuiltinFunctionLibrary::destroy()
+BuiltinFunctionLibrary::~BuiltinFunctionLibrary()
 {
+  for (csize i = 0; i < FunctionConsts::FN_MAX_FUNC; ++i)
+  {
+    delete theFunctions[i];
+  }
+
   delete [] theFunctions;
 }
 

=== modified file 'src/functions/library.h'
--- src/functions/library.h	2013-02-07 17:24:36 +0000
+++ src/functions/library.h	2013-07-11 13:41:52 +0000
@@ -32,24 +32,30 @@
   friend class GlobalEnvironment;
 
 public:
-  static function  ** theFunctions;
+  function  ** theFunctions;
 
 public:
-  static function* getFunction(FunctionConsts::FunctionKind kind)
+  BuiltinFunctionLibrary();
+
+  ~BuiltinFunctionLibrary();
+
+  void populate(static_context* sctx);
+
+  function* getFunction(FunctionConsts::FunctionKind kind)
   {
     return theFunctions[kind];
   }
 
-private:
-  static void create(static_context* sctx);
-
-  static void destroy();
+  void addFunction(FunctionConsts::FunctionKind kind, function* f)
+  {
+    theFunctions[kind] = f;
+  }
 };
 
 
 
 #define BUILTIN_FUNC(func_code) \
-BuiltinFunctionLibrary::getFunction(FunctionConsts::func_code)
+GENV_FUNC_LIB->getFunction(FunctionConsts::func_code)
 
 
 }

=== modified file 'src/functions/udf.cpp'
--- src/functions/udf.cpp	2013-06-15 21:18:01 +0000
+++ src/functions/udf.cpp	2013-07-11 13:41:52 +0000
@@ -62,7 +62,7 @@
     unsigned short scriptingKind,
     CompilerCB* ccb)
   :
-  function(sig, FunctionConsts::FN_UNKNOWN),
+function(sig, FunctionConsts::FN_UNKNOWN, false),
   theCCB(ccb),
   theLoc(loc),
   theScriptingKind(scriptingKind),
@@ -76,8 +76,6 @@
   theCacheComputed(false)
 {
   setFlag(FunctionConsts::isUDF);
-  resetFlag(FunctionConsts::isBuiltin);
-  setDeterministic(true);
   setPrivate(false);
 }
 

=== modified file 'src/runtime/full_text/ft_util.cpp'
--- src/runtime/full_text/ft_util.cpp	2013-06-11 23:38:49 +0000
+++ src/runtime/full_text/ft_util.cpp	2013-07-11 13:41:52 +0000
@@ -19,13 +19,16 @@
 #include <stdexcept>
 
 #include "diagnostics/xquery_diagnostics.h"
+
 #include "util/locale.h"
-#include "zorbamisc/ns_consts.h"
+
 #include "zorbatypes/integer.h"
 #include "zorbatypes/numconversions.h"
 
 #include "ft_util.h"
 
+#include "context/static_context.h"
+
 using namespace zorba::locale;
 
 namespace zorba {
@@ -41,7 +44,7 @@
       store::Item const *const qname = attr->getNodeName();
       if ( qname &&
            qname->getLocalName() == "lang" &&
-           qname->getNamespace() == XML_NS ) {
+           qname->getNamespace() == static_context::W3C_XML_NS ) {
         *lang = locale::find_lang( attr->getStringValue() );
         found_lang = true;
         break;

=== modified file 'src/runtime/hof/fn_hof_functions_impl.cpp'
--- src/runtime/hof/fn_hof_functions_impl.cpp	2013-06-04 21:47:40 +0000
+++ src/runtime/hof/fn_hof_functions_impl.cpp	2013-07-11 13:41:52 +0000
@@ -163,7 +163,7 @@
     Translator::translate_literal_function(qname, arity, ccb, impSctx, loc);
     
     FunctionItemInfo_t fiInfo =
-    static_cast<function_item_expr*>(fiExpr)->get_dynamic_fn_info();
+    static_cast<function_item_expr*>(fiExpr)->get_fi_info();
 
     fiInfo->theCCB = ccb;
 

=== modified file 'src/runtime/hof/function_item.cpp'
--- src/runtime/hof/function_item.cpp	2013-04-24 01:35:58 +0000
+++ src/runtime/hof/function_item.cpp	2013-07-11 13:41:52 +0000
@@ -141,7 +141,7 @@
   if (ar.is_serializing_out())
   {
     uint32_t planStateSize;
-    (void)static_cast<user_function*>(theFunction.getp())->getPlan(planStateSize, 1);
+    (void)static_cast<user_function*>(theFunction)->getPlan(planStateSize, 1);
   }
 }
 
@@ -158,15 +158,6 @@
 }
 
 
-/*******************************************************************************
-
-********************************************************************************/
-FunctionItem::FunctionItem(::zorba::serialization::Archiver& ar)
-  :
-  store::Item(store::Item::FUNCTION)
-{
-}
-
 ////////////////////////////////////////////////////////////////////////////////
 //                                                                            //
 //  FunctionItem                                                              //
@@ -202,6 +193,16 @@
 /*******************************************************************************
 
 ********************************************************************************/
+FunctionItem::FunctionItem(::zorba::serialization::Archiver& ar)
+  :
+  store::Item(store::Item::FUNCTION)
+{
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
 FunctionItem::~FunctionItem()
 {
 #if 0

=== modified file 'src/runtime/hof/function_item.h'
--- src/runtime/hof/function_item.h	2013-04-24 01:35:58 +0000
+++ src/runtime/hof/function_item.h	2013-07-11 13:41:52 +0000
@@ -112,7 +112,7 @@
 
   static_context              * theClosureSctx;
 
-  function_t                    theFunction;
+  function                    * theFunction;
 
   store::Item_t                 theQName;
 

=== modified file 'src/runtime/nodes/nodes_impl.cpp'
--- src/runtime/nodes/nodes_impl.cpp	2013-05-06 22:57:08 +0000
+++ src/runtime/nodes/nodes_impl.cpp	2013-07-11 13:41:52 +0000
@@ -236,7 +236,7 @@
   store::Item* lAttrName = aAttr->getNodeName();
 
   return (ZSTREQ(lAttrName->getLocalName(), "lang") &&
-          ZSTREQ(lAttrName->getNamespace(), XML_NS));
+          lAttrName->getNamespace() == static_context::W3C_XML_NS);
 }
 
 

=== modified file 'src/runtime/strings/strings_impl.cpp'
--- src/runtime/strings/strings_impl.cpp	2013-06-10 22:49:36 +0000
+++ src/runtime/strings/strings_impl.cpp	2013-07-11 13:41:52 +0000
@@ -1839,7 +1839,7 @@
   store::NsBindings   ns_binding;
   zstring baseURI;
   GENV_ITEMFACTORY->createQName(untyped_type_name,
-                                XML_SCHEMA_NS, XML_SCHEMA_PREFIX, "untyped");
+                                static_context::W3C_XML_SCHEMA_NS, "", "untyped");
   GENV_ITEMFACTORY->createQName(non_match_element_name,
                                 static_context::W3C_FN_NS, "fn", "non-match");
   GENV_ITEMFACTORY->createElementNode(non_match_elem, parent, non_match_element_name, untyped_type_name, false, false, ns_binding, baseURI);
@@ -1968,7 +1968,7 @@
   store::NsBindings   ns_binding;
   zstring baseURI;
   GENV_ITEMFACTORY->createQName(untyped_type_name,
-                                XML_SCHEMA_NS, XML_SCHEMA_PREFIX, "untyped");
+                                static_context::W3C_XML_SCHEMA_NS, "", "untyped");
   GENV_ITEMFACTORY->createQName(match_element_name,
                                 static_context::W3C_FN_NS, "fn", "match");
   store::Item_t match_elem;
@@ -2125,7 +2125,7 @@
     store::NsBindings   ns_binding;
     zstring baseURI;
     GENV_ITEMFACTORY->createQName(untyped_type_name,
-                                  XML_SCHEMA_NS, XML_SCHEMA_PREFIX, "untyped");
+                                  static_context::W3C_XML_SCHEMA_NS, "", "untyped");
     GENV_ITEMFACTORY->createQName(result_element_name,
                                   static_context::W3C_FN_NS, "fn", "analyze-string-result");
     GENV_ITEMFACTORY->createElementNode(result, NULL, result_element_name, untyped_type_name, false, false, ns_binding, baseURI);

=== modified file 'src/store/api/annotation.h'
--- src/store/api/annotation.h	2013-02-07 17:24:36 +0000
+++ src/store/api/annotation.h	2013-07-11 13:41:52 +0000
@@ -24,20 +24,13 @@
 namespace zorba { namespace store {
 
 
-class Annotation : public RCObject
+class Annotation : public SyncedRCObject
 {
-protected:
-  SYNC_CODE(mutable RCLock theRCLock;)
-    
 public:
   Item_t              theName;
   std::vector<Item_t> theLiterals;
 
 public:
-  SYNC_CODE(RCLock* getRCLock() const { return &theRCLock; })
-
-  long* getSharedRefCounter() const { return NULL; } 
-
   virtual ~Annotation() {}
 };
 

=== modified file 'src/store/api/collection.h'
--- src/store/api/collection.h	2013-04-29 14:39:04 +0000
+++ src/store/api/collection.h	2013-07-11 13:41:52 +0000
@@ -23,16 +23,8 @@
 namespace zorba { namespace store {
 
 
-class Collection : public RCObject
+class Collection : public SyncedRCObject
 {
-protected:
-  SYNC_CODE(mutable RCLock theRCLock;)
-
-public:
-  SYNC_CODE(RCLock* getRCLock() const { return &theRCLock; })
-
-  long* getSharedRefCounter() const { return NULL; } 
-
 public:
   virtual ~Collection() {}
 

=== modified file 'src/store/api/ic.h'
--- src/store/api/ic.h	2013-02-07 17:24:36 +0000
+++ src/store/api/ic.h	2013-07-11 13:41:52 +0000
@@ -31,7 +31,7 @@
  * Integrity Constraints class. Contains the name of the IC and the
  * collection name.
  */
-class IC : public RCObject
+class IC : public SyncedRCObject
 {
 public:
   enum ICKind
@@ -40,14 +40,6 @@
     ic_foreignkey 
   };
 
-protected:
-  SYNC_CODE(mutable RCLock theRCLock;)
-
-public:
-  SYNC_CODE(RCLock* getRCLock() const { return &theRCLock; })
-
-  long* getSharedRefCounter() const { return NULL; } 
-
 public:
   virtual ~IC() {}
 

=== modified file 'src/store/api/index.h'
--- src/store/api/index.h	2013-02-07 17:24:36 +0000
+++ src/store/api/index.h	2013-07-11 13:41:52 +0000
@@ -369,11 +369,8 @@
   IndexCondition below).
 
 *******************************************************************************/
-class Index : public RCObject
+class Index : public SyncedRCObject
 {
-protected:
-  SYNC_CODE(mutable RCLock theRCLock;)
-
 public:
   class KeyIterator : virtual public SimpleRCObject
   {
@@ -391,11 +388,6 @@
 
 
 public:
-  SYNC_CODE(RCLock* getRCLock() const { return &theRCLock; })
-
-  long* getSharedRefCounter() const { return NULL; }
-
-public:
 
   virtual ~Index() {}
 

=== modified file 'src/store/api/item.h'
--- src/store/api/item.h	2013-06-29 08:38:53 +0000
+++ src/store/api/item.h	2013-07-11 13:41:52 +0000
@@ -101,7 +101,7 @@
 
   virtual ~Item() {}
 
-  virtual void free() { delete this; }
+  virtual void free();
 
   long getRefCount() const { return theRefCount; }
 

=== modified file 'src/store/naive/atomic_items.cpp'
--- src/store/naive/atomic_items.cpp	2013-06-21 01:06:29 +0000
+++ src/store/naive/atomic_items.cpp	2013-07-11 13:41:52 +0000
@@ -686,8 +686,8 @@
 {
   assert(!isValid());
 
-  store::Item_t lPoolQName =
-      GET_STORE().getQNamePool().insert(aNamespace, zstring(), aLocalName);
+  store::Item_t lPoolQName;
+  GET_STORE().getQNamePool().insert(lPoolQName, aNamespace, zstring(), aLocalName);
 
   QNameItem* lNormalized = static_cast<QNameItem*>(lPoolQName.getp());
   assert(lNormalized->isNormalized());
@@ -705,12 +705,17 @@
   if (theIsInPool)
   {
     thePool.remove(this);
+
+    SYNC_CODE(getRCLock()->release());
+
     return;
   }
   
   assert(!isNormalized());
 
   invalidate(false, NULL);
+  SYNC_CODE(getRCLock()->release());
+
   delete this;
 }
 

=== modified file 'src/store/naive/atomic_items.h'
--- src/store/naive/atomic_items.h	2013-05-24 22:52:47 +0000
+++ src/store/naive/atomic_items.h	2013-07-11 13:41:52 +0000
@@ -424,6 +424,12 @@
 
   const QNameItem* getNormalized() const { return theNormalizedQName; }
   
+  const zstring& getLocalName2() const { return theLocal; }
+  
+  const zstring& getNamespace2() const { return theNamespace; }
+
+  const zstring& getPrefix2() const { return thePrefix; }
+
   bool isBaseUri() const;
   
   bool isIdQName() const;

=== modified file 'src/store/naive/item.cpp'
--- src/store/naive/item.cpp	2013-06-15 02:57:08 +0000
+++ src/store/naive/item.cpp	2013-07-11 13:41:52 +0000
@@ -40,6 +40,12 @@
 {
 
 
+void Item::free()
+{
+  delete this;
+}
+
+
 void Item::addReference() const
 {
 #if defined WIN32 && !defined CYGWIN && !defined ZORBA_FOR_ONE_THREAD_ONLY
@@ -135,6 +141,8 @@
   {
     SYNC_CODE(static_cast<const simplestore::XmlNode*>(this)->getRCLock()->acquire());
 
+    assert(theRefCount > 0);
+
     --theRefCount;
     if (--(*theUnion.treeRCPtr) == 0)
     {
@@ -150,6 +158,7 @@
   case ARRAY:
   {
     SYNC_CODE(static_cast<const simplestore::json::JSONItem*>(this)->getRCLock()->acquire());
+    assert(theRefCount > 0);
 
     if (--theRefCount == 0)
     {
@@ -166,6 +175,8 @@
   {
     SYNC_CODE(static_cast<const simplestore::AtomicItem*>(this)->getRCLock()->acquire());
 
+    assert(theRefCount > 0);
+
     if (--theRefCount == 0)
     {
       SYNC_CODE(static_cast<const simplestore::AtomicItem*>(this)->getRCLock()->release());

=== modified file 'src/store/naive/loader_dtd.cpp'
--- src/store/naive/loader_dtd.cpp	2013-04-16 21:12:12 +0000
+++ src/store/naive/loader_dtd.cpp	2013-07-11 13:41:52 +0000
@@ -1212,9 +1212,11 @@
     csize numBindings = static_cast<csize>(numNamespaces);
 
     // Construct node name
-    store::Item_t nodeName = qnpool.insert(reinterpret_cast<const char*>(uri),
-                                           reinterpret_cast<const char*>(prefix),
-                                           reinterpret_cast<const char*>(lname));
+    store::Item_t nodeName;
+    qnpool.insert(nodeName,
+                  reinterpret_cast<const char*>(uri),
+                  reinterpret_cast<const char*>(prefix),
+                  reinterpret_cast<const char*>(lname));
 
     // Create the element node and push it to the node stack
     ElementNode* elemNode = nfactory.createElementNode(nodeName,
@@ -1335,9 +1337,11 @@
       //std::cout << "  att: " << attr->name << std::endl; std::cout.flush();
 
       const char* lname = reinterpret_cast<const char*>(attr->name);
-      const char* prefix = reinterpret_cast<const char*>( attr->ns != NULL ? attr->ns->prefix : NULL);
-      const char* uri = reinterpret_cast<const char*>( attr->ns != NULL ? attr->ns->href : NULL);
-      store::Item_t qname = qnpool.insert(uri, prefix, lname);
+      const char* prefix = reinterpret_cast<const char*>(attr->ns != NULL ? attr->ns->prefix : NULL);
+      const char* uri = reinterpret_cast<const char*>(attr->ns != NULL ? attr->ns->href : NULL);
+      store::Item_t qname;
+      qnpool.insert(qname, uri, prefix, lname);
+
       AttributeNode* attrNode = nfactory.createAttributeNode(qname);
 
       xmlChar* val = xmlGetProp(node, attr->name);

=== modified file 'src/store/naive/loader_fast.cpp'
--- src/store/naive/loader_fast.cpp	2013-06-19 09:54:46 +0000
+++ src/store/naive/loader_fast.cpp	2013-07-11 13:41:52 +0000
@@ -676,10 +676,12 @@
     csize numBindings = static_cast<csize>(numNamespaces);
 
     // Construct node name
-    store::Item_t nodeName = qnpool.insert(reinterpret_cast<const char*>(uri),
-                                           reinterpret_cast<const char*>(prefix),
-                                           reinterpret_cast<const char*>(lname));
-
+    store::Item_t nodeName;
+    qnpool.insert(nodeName,
+                  reinterpret_cast<const char*>(uri),
+                  reinterpret_cast<const char*>(prefix),
+                  reinterpret_cast<const char*>(lname));
+    
     // Create the element node and push it to the node stack
     ElementNode* elemNode = nfactory.createElementNode(nodeName,
                                                        numBindings,
@@ -803,7 +805,8 @@
         const char* valueBegin = reinterpret_cast<const char*>(attributes[index+3]);
         const char* valueEnd = reinterpret_cast<const char*>(attributes[index+4]);
 
-        store::Item_t qname = qnpool.insert(uri, prefix, lname);
+        store::Item_t qname;
+        qnpool.insert(qname, uri, prefix, lname);
 
         zstring value(valueBegin, valueEnd);
         store::Item_t typedValue;

=== modified file 'src/store/naive/node_items.cpp'
--- src/store/naive/node_items.cpp	2013-06-29 08:38:53 +0000
+++ src/store/naive/node_items.cpp	2013-07-11 13:41:52 +0000
@@ -3645,7 +3645,9 @@
 
   const Store& store = GET_STORE();
 
-  store::Item_t qname = store.getQNamePool().insert(store.XML_URI, "xml", "base");
+  store::Item_t qname;
+  store.getQNamePool().insert(qname, store.XML_URI, "xml", "base");
+
   store::Item_t typeName = store.theSchemaTypeNames[store::XS_ANY_URI];
 
   store::Item_t typedValue;
@@ -5133,7 +5135,7 @@
   theTarget.take(target);
   theContent.take(content);
 
-  theName = qnpool.insert(zstring(), zstring(), theTarget);
+  qnpool.insert(theName, zstring(), zstring(), theTarget);
 
   STORE_TRACE1("Loaded pi node " << this << " target = " << theTarget
               << std::endl);
@@ -5158,7 +5160,7 @@
   theTarget.take(target);
   theContent.take(content);
 
-  theName = qnpool.insert(zstring(), zstring(), theTarget);
+  qnpool.insert(theName, zstring(), zstring(), theTarget);
 
   if (parent)
   {

=== modified file 'src/store/naive/nsbindings.cpp'
--- src/store/naive/nsbindings.cpp	2013-06-20 09:52:25 +0000
+++ src/store/naive/nsbindings.cpp	2013-07-11 13:41:52 +0000
@@ -16,6 +16,7 @@
 #include "stdafx.h"
 
 #include "nsbindings.h"
+#include "store_defs.h"
 
 #include "zorbautils/fatal.h"
 

=== modified file 'src/store/naive/qname_pool.cpp'
--- src/store/naive/qname_pool.cpp	2013-02-07 17:24:36 +0000
+++ src/store/naive/qname_pool.cpp	2013-07-11 13:41:52 +0000
@@ -48,13 +48,16 @@
   QNameItem* qn = &theCache[1];
   QNameItem* last = qn + size - 1;
 
-  for (csize i = 1; qn < last; qn++, i++)
+  for (csize i = 1; qn < last; ++qn, ++i)
   {
     qn->theNextFree = i + 1;
     qn->thePrevFree = i - 1;
     qn->thePosition = i;
   }
   (--qn)->theNextFree = 0;
+
+  qn = &theCache[0];
+  qn->theNextFree =  qn->thePrevFree = qn->thePosition = 0;
 }
 
 
@@ -64,6 +67,27 @@
 QNamePool::~QNamePool() 
 {
   csize n = theHashSet.capacity();
+
+#if 0
+#ifndef NDEBUG
+  csize numInPool = 0;
+  for (csize i = 0; i < theCacheSize; ++i)
+  {
+    QNameItem* qn = &theCache[i];
+
+    if (qn->getRefCount() != 0)
+    {
+      ++numInPool;
+      std::cerr << "QName in pool: RC = " << qn->getRefCount() << " : "
+                << qn->getStringValue() << " at pos : " << qn->thePosition
+                << std::endl;
+    }
+  }
+
+  std::cerr << std::endl << numInPool << "qnames in pool" << std::endl;
+#endif
+#endif
+
   for (csize i = 0; i < n; ++i)
   {
     if (!theHashSet.theHashTab[i].isFree() &&
@@ -84,19 +108,42 @@
 ********************************************************************************/
 void QNamePool::addInFreeList(QNameItem* qn)
 {
-  assert(qn->thePrevFree == 0);
-  assert(qn->theNextFree == 0);
   assert(qn->getRefCount() == 0);
   assert(theCache[theFirstFree].thePrevFree == 0);
 
+  // Nothing to do if qn is already in the free list
+
+  if (qn->thePrevFree != 0 || qn->theNextFree != 0)
+  {
+#ifndef NDEBUG
+    QNameItem* curr = &theCache[theFirstFree];
+    while (curr != NULL && curr != qn)
+      curr = &theCache[curr->theNextFree];
+
+    assert(curr != NULL);
+#endif
+    return;
+  }
+
+  if (theFirstFree == qn->thePosition)
+    return;
+
+  // add it in the list
+
   qn->theNextFree = (uint16_t)theFirstFree;
 
   if (theFirstFree != 0)
+  {
+    assert(theCache[theFirstFree].thePosition == theFirstFree);
+
     theCache[theFirstFree].thePrevFree = qn->thePosition;
+  }
 
   theFirstFree = qn->thePosition;
 
-  theNumFree++;
+  assert(theFirstFree > 0 && theFirstFree < theCacheSize);
+
+  ++theNumFree;
 }
 
 
@@ -107,19 +154,10 @@
 {
   assert(qn->isInCache());
 
-  if (qn->theNextFree == 0 && qn->thePrevFree == 0)
-  {
-    // Either qn does not belong to the free list, or is the only one in the
-    // free list
-
-    if (theFirstFree != qn->thePosition)
-      return;
-  }
-
-  assert(qn->getRefCount() == 0);
-
   if (qn->theNextFree != 0)
   {
+    assert(qn->getRefCount() == 0);
+    assert(theFirstFree > 0 && theFirstFree < theCacheSize);
     assert(theCache[qn->theNextFree].thePrevFree = qn->thePosition);
 
     theCache[qn->theNextFree].thePrevFree = qn->thePrevFree;
@@ -127,12 +165,29 @@
 
   if (qn->thePrevFree != 0)
   {
+    assert(qn->getRefCount() == 0);
+    assert(theFirstFree > 0 && theFirstFree < theCacheSize);
     assert(theCache[qn->thePrevFree].theNextFree = qn->thePosition);
     
     theCache[qn->thePrevFree].theNextFree = qn->theNextFree;
   }
+  else if (qn->theNextFree == 0)
+  {
+    // Either qn does not belong to the free list, or is the only one in the
+    // free list
+    if (theFirstFree != qn->thePosition)
+      return;
+
+    assert(qn->getRefCount() == 0);
+    assert(theFirstFree == qn->thePosition);
+    assert(theNumFree == 1);
+
+    theFirstFree = qn->theNextFree;
+  }
   else
   {
+    // qn is the 1st slot in the free list
+    assert(qn->getRefCount() == 0);
     assert(theFirstFree == qn->thePosition);
 
     theFirstFree = qn->theNextFree;
@@ -140,7 +195,7 @@
 
   qn->theNextFree = qn->thePrevFree = 0;
 
-  theNumFree--;
+  --theNumFree;
 }
 
 
@@ -159,15 +214,14 @@
 
     theFirstFree = qn->theNextFree;
 
-    if (theFirstFree != 0)
-    {
-      assert(theCache[theFirstFree].thePrevFree == qn->thePosition);
-      theCache[theFirstFree].thePrevFree = 0;
-    }
+    assert(theFirstFree == 0 ||
+           theCache[theFirstFree].thePrevFree == qn->thePosition);
+
+    theCache[theFirstFree].thePrevFree = 0;
 
     qn->theNextFree = qn->thePrevFree = 0;
 
-    theNumFree--;
+    --theNumFree;
 
     return qn;
   }
@@ -186,13 +240,15 @@
 {
   QNameItem* normVictim = NULL;
 
-  SYNC_CODE(theHashSet.theMutex.lock(); \
-  bool haveLock = true;)
+  SYNC_CODE(theHashSet.theMutex.lock();)
 
   try 
   {
     if (qn->getRefCount() > 0)
+    {
+      SYNC_CODE(theHashSet.theMutex.unlock();)
       return;
+    }
 
     if (qn->isInCache())
     {
@@ -211,22 +267,20 @@
 
     // Releasing the lock here to avoid deadlock, because decrementing the 
     // normVictim counter might reenter QNamePool::remove.
-    SYNC_CODE(theHashSet.theMutex.unlock(); \
-    haveLock = false;)
-
-    if (normVictim)
-    {
-      normVictim->removeReference();
-    }
-
+    SYNC_CODE(theHashSet.theMutex.unlock();)
   }
   catch(...)
   {
-    SYNC_CODE(if (haveLock) \
-              theHashSet.theMutex.unlock();)
+    SYNC_CODE(theHashSet.theMutex.unlock();)
               
     ZORBA_FATAL(0, "Unexpected exception");
   }
+
+  if (normVictim)
+  {
+    assert(normVictim->getRefCount() > 0 && normVictim->getRefCount() < 10000);
+    normVictim->removeReference();
+  }
 }
 
 
@@ -240,7 +294,8 @@
   copied internally into zstring objects. So, it's always the caller who is
   resposnible for freeing the given strings.
 ********************************************************************************/
-store::Item_t QNamePool::insert(
+void QNamePool::insert(
+    store::Item_t& res,
     const char* ns,
     const char* pre,
     const char* ln)
@@ -251,6 +306,8 @@
   store::Item_t normItem;
   QNameItem* normQName = NULL;
 
+  res = NULL;
+
   bool normalized = (pre == NULL || *pre == '\0');
 
   if (ns == NULL) ns = "";
@@ -286,7 +343,7 @@
           SYNC_CODE(theHashSet.theMutex.unlock();\
           haveLock = false;)
 
-          normItem = insert(ns, NULL, ln);
+          insert(normItem, ns, NULL, ln);
           normQName = static_cast<QNameItem*>(normItem.getp());
           goto retry;
         }
@@ -306,6 +363,9 @@
       cachePin(qn);
     }
 
+    assert(qn->theNextFree == 0);
+    res = qn;
+
     SYNC_CODE(theHashSet.theMutex.unlock();\
     haveLock = false;)
   }
@@ -319,10 +379,9 @@
 
   if (normVictim != NULL)
   {
+    assert(normVictim->getRefCount() > 0 && normVictim->getRefCount() < 10000);
     normVictim->removeReference();
   }
-
-  return qn;
 }
 
 
@@ -331,7 +390,8 @@
   and local name, then create such a qname, insert it in the pool and return an
   rchandle to it. Otherwise, return an rchandle to the existing qname. 
 ********************************************************************************/
-store::Item_t QNamePool::insert(
+void QNamePool::insert(
+    store::Item_t& res,
     const zstring& ns,
     const zstring& pre,
     const zstring& ln)
@@ -342,6 +402,8 @@
   store::Item_t normItem;
   QNameItem* normQName = NULL;
 
+  res = NULL;
+
   bool normalized = pre.empty();
 
   zstring pooledNs;
@@ -377,7 +439,7 @@
           haveLock = false;)
 
           // This call will need the lock.
-          normItem = insert(pooledNs, zstring(), ln);
+          insert(normItem, pooledNs, zstring(), ln);
           normQName = static_cast<QNameItem*>(normItem.getp());
 
           goto retry;
@@ -398,23 +460,24 @@
       cachePin(qn);
     }
 
+    assert(qn->theNextFree == 0);
+    res = qn;
+
     SYNC_CODE(theHashSet.theMutex.unlock();\
     haveLock = false;)
   }
   catch (...)
   {
-    SYNC_CODE(if (haveLock) \
-      theHashSet.theMutex.unlock();)
+    SYNC_CODE(if (haveLock) theHashSet.theMutex.unlock();)
 
     ZORBA_FATAL(0, "Unexpected exception");
   }
 
   if (normVictim != NULL)
   {
+    assert(normVictim->getRefCount() > 0 && normVictim->getRefCount() < 10000);
     normVictim->removeReference();
   }
-
-  return qn;
 }
 
 
@@ -480,9 +543,9 @@
   {
     QNameItem* qn = entry->key();
 
-    if (ztd::equals(qn->getLocalName(), ln, lnlen) &&
-        ztd::equals(qn->getNamespace(), ns, nslen) &&
-        ztd::equals(qn->getPrefix(), pre, prelen))
+    if (ztd::equals(qn->getLocalName2(), ln, lnlen) &&
+        ztd::equals(qn->getNamespace2(), ns, nslen) &&
+        ztd::equals(qn->getPrefix2(), pre, prelen))
       return entry;
 
     entry = entry->getNext();

=== modified file 'src/store/naive/qname_pool.h'
--- src/store/naive/qname_pool.h	2013-02-07 17:24:36 +0000
+++ src/store/naive/qname_pool.h	2013-07-11 13:41:52 +0000
@@ -68,16 +68,16 @@
   public:
     static bool equal(const QNameItem* t1, const QNameItem* t2)
     {
-      return (t1->getLocalName() == t2->getLocalName() &&
-              t1->getNamespace() == t2->getNamespace() &&
-              t1->getPrefix() == t2->getPrefix());
+      return (t1->getLocalName2() == t2->getLocalName2() &&
+              t1->getNamespace2() == t2->getNamespace2() &&
+              t1->getPrefix2() == t2->getPrefix2());
     }
 
     static uint32_t hash(const QNameItem* t)
     {
-      return  hashfun::h32(t->getPrefix().c_str(),
-                           hashfun::h32(t->getLocalName().c_str(),
-                                        hashfun::h32(t->getNamespace().c_str())));
+      return  hashfun::h32(t->getPrefix2().c_str(),
+                           hashfun::h32(t->getLocalName2().c_str(),
+                                        hashfun::h32(t->getNamespace2().c_str())));
     }
   };
 
@@ -115,9 +115,17 @@
 
   ~QNamePool();
 
-  store::Item_t insert(const char* ns, const char* pre, const char* ln);
+  void insert(
+      store::Item_t& res,
+      const char* ns,
+      const char* pre,
+      const char* ln);
   
-  store::Item_t insert(const zstring& ns, const zstring& pre, const zstring& ln);
+  void insert(
+      store::Item_t& res,
+      const zstring& ns,
+      const zstring& pre,
+      const zstring& ln);
   
   void remove(QNameItem* qn);
 

=== modified file 'src/store/naive/simple_item_factory.cpp'
--- src/store/naive/simple_item_factory.cpp	2013-06-21 01:06:29 +0000
+++ src/store/naive/simple_item_factory.cpp	2013-07-11 13:41:52 +0000
@@ -81,7 +81,7 @@
     const zstring& pre,
     const zstring& local)
 {
-  result = theQNamePool->insert(ns, pre, local);
+  theQNamePool->insert(result, ns, pre, local);
   return true;
 }
 
@@ -92,7 +92,7 @@
     const char*    pre,
     const char*    ln)
 {
-  result = theQNamePool->insert(ns, pre, ln);
+  theQNamePool->insert(result, ns, pre, ln);
   return true;
 }
 

=== modified file 'src/store/naive/simple_pul.cpp'
--- src/store/naive/simple_pul.cpp	2013-06-15 02:57:08 +0000
+++ src/store/naive/simple_pul.cpp	2013-07-11 13:41:52 +0000
@@ -166,20 +166,19 @@
 {
   const QNameItem* collName;
 
-  assert(target->isNode()
-      || target->isJSONItem());
+  assert(target->isNode() || target->isJSONItem());
 
   assert(dynamic_cast<const StructuredItem*>(target));
-  const StructuredItem* lStructuredItem =
-      static_cast<const StructuredItem*>(target);
-  const store::Collection* lCollection = lStructuredItem->getCollection();
+
+  const StructuredItem* structuredItem = static_cast<const StructuredItem*>(target);
+
+  const store::Collection* lCollection = structuredItem->getCollection();
 
   if (lCollection != NULL)
   {
-    collName = static_cast<const QNameItem*>(
-        lCollection->getName())->getNormalized();
+    collName = static_cast<const QNameItem*>(lCollection->getName());
 
-    if (collName == theLastCollection)
+    if (theLastCollection != NULL && collName->equals(theLastCollection))
       return theLastPul;
 
     return getCollectionPulByName(collName, lCollection->isDynamic());

=== modified file 'src/store/naive/store.cpp'
--- src/store/naive/store.cpp	2013-06-15 02:57:08 +0000
+++ src/store/naive/store.cpp	2013-07-11 13:41:52 +0000
@@ -185,69 +185,69 @@
 
   theSchemaTypeNames.resize(store::XS_LAST);
 
-  JS_NULL_QNAME = theQNamePool->insert(JS_URI, "js", "null");
-  JS_OBJECT_QNAME = theQNamePool->insert(JS_URI, "js", "object");
-  JS_ARRAY_QNAME = theQNamePool->insert(JS_URI, "js", "array");
-
-  XS_UNTYPED_QNAME = theQNamePool->insert(ns, "xs", "untyped");
-
-  XS_ANY_QNAME = theQNamePool->insert(ns, "xs", "anyType");
-
-  theSchemaTypeNames[store::XS_ANY_ATOMIC] =
-      theQNamePool->insert(ns, "xs", "anyAtomicType");
-
-  theSchemaTypeNames[store::XS_UNTYPED_ATOMIC] =
-      theQNamePool->insert(ns, "xs", "untypedAtomic");
-
-  theSchemaTypeNames[store::XS_ANY_URI] = theQNamePool->insert(ns, "xs", "anyURI");
-  theSchemaTypeNames[store::XS_QNAME] = theQNamePool->insert(ns, "xs", "QName");
-  theSchemaTypeNames[store::XS_NOTATION] = theQNamePool->insert(ns, "xs", "NOTATION");
-  theSchemaTypeNames[store::XS_STRING] = theQNamePool->insert(ns, "xs", "string");
-  theSchemaTypeNames[store::XS_NORMALIZED_STRING] = theQNamePool->insert(ns, "xs", "normalizedString");
-  theSchemaTypeNames[store::XS_TOKEN] = theQNamePool->insert(ns, "xs", "token");
-  theSchemaTypeNames[store::XS_NMTOKEN] = theQNamePool->insert(ns, "xs", "NMTOKEN");
-  theSchemaTypeNames[store::XS_LANGUAGE] = theQNamePool->insert(ns, "xs", "language");
-  theSchemaTypeNames[store::XS_NAME] = theQNamePool->insert(ns, "xs", "Name");
-  theSchemaTypeNames[store::XS_NCNAME] = theQNamePool->insert(ns, "xs", "NCName");
-  theSchemaTypeNames[store::XS_ID] = theQNamePool->insert(ns, "xs", "ID");
-  theSchemaTypeNames[store::XS_IDREF] = theQNamePool->insert(ns, "xs", "IDREF");
-  theSchemaTypeNames[store::XS_ENTITY] = theQNamePool->insert(ns, "xs", "ENTITY");
-
-  theSchemaTypeNames[store::XS_DATETIME] = theQNamePool->insert(ns, "xs", "dateTime");
-  theSchemaTypeNames[store::XS_DATETIME_STAMP] = theQNamePool->insert(ns, "xs", "dateTimeStamp");
-  theSchemaTypeNames[store::XS_DATE] = theQNamePool->insert(ns, "xs", "date");
-  theSchemaTypeNames[store::XS_TIME] = theQNamePool->insert(ns, "xs", "time");
-  theSchemaTypeNames[store::XS_GYEAR_MONTH] = theQNamePool->insert(ns, "xs", "gYearMonth");
-  theSchemaTypeNames[store::XS_GYEAR] = theQNamePool->insert(ns, "xs", "gYear");
-  theSchemaTypeNames[store::XS_GMONTH_DAY] = theQNamePool->insert(ns, "xs", "gMonthDay");
-  theSchemaTypeNames[store::XS_GDAY] = theQNamePool->insert(ns, "xs", "gDay");
-  theSchemaTypeNames[store::XS_GMONTH] = theQNamePool->insert(ns, "xs", "gMonth");
-
-  theSchemaTypeNames[store::XS_DURATION] = theQNamePool->insert(ns, "xs", "duration");
-  theSchemaTypeNames[store::XS_DT_DURATION] = theQNamePool->insert(ns, "xs", "dayTimeDuration");
-  theSchemaTypeNames[store::XS_YM_DURATION] = theQNamePool->insert(ns, "xs", "yearMonthDuration");
-
-  theSchemaTypeNames[store::XS_FLOAT] = theQNamePool->insert(ns, "xs", "float");
-  theSchemaTypeNames[store::XS_DOUBLE] = theQNamePool->insert(ns, "xs", "double");
-  theSchemaTypeNames[store::XS_DECIMAL] = theQNamePool->insert(ns, "xs", "decimal");
-  theSchemaTypeNames[store::XS_INTEGER] = theQNamePool->insert(ns, "xs", "integer");
-  theSchemaTypeNames[store::XS_NON_POSITIVE_INTEGER] = theQNamePool->insert(ns, "xs", "nonPositiveInteger");
-  theSchemaTypeNames[store::XS_NON_NEGATIVE_INTEGER] = theQNamePool->insert(ns, "xs", "nonNegativeInteger");
-  theSchemaTypeNames[store::XS_NEGATIVE_INTEGER] = theQNamePool->insert(ns, "xs", "negativeInteger");
-  theSchemaTypeNames[store::XS_POSITIVE_INTEGER] = theQNamePool->insert(ns, "xs", "positiveInteger");
-
-  theSchemaTypeNames[store::XS_LONG] = theQNamePool->insert(ns, "xs", "long");
-  theSchemaTypeNames[store::XS_INT] = theQNamePool->insert(ns, "xs", "int");
-  theSchemaTypeNames[store::XS_SHORT] = theQNamePool->insert(ns, "xs", "short");
-  theSchemaTypeNames[store::XS_BYTE] = theQNamePool->insert(ns, "xs", "byte");
-  theSchemaTypeNames[store::XS_UNSIGNED_LONG] = theQNamePool->insert(ns, "xs", "unsignedLong");
-  theSchemaTypeNames[store::XS_UNSIGNED_INT] = theQNamePool->insert(ns, "xs", "unsignedInt");
-  theSchemaTypeNames[store::XS_UNSIGNED_SHORT] = theQNamePool->insert(ns, "xs", "unsignedShort");
-  theSchemaTypeNames[store::XS_UNSIGNED_BYTE] = theQNamePool->insert(ns, "xs", "unsignedByte");
-
-  theSchemaTypeNames[store::XS_BASE64BINARY] = theQNamePool->insert(ns, "xs", "base64Binary");
-  theSchemaTypeNames[store::XS_HEXBINARY] = theQNamePool->insert(ns, "xs", "hexBinary");
-  theSchemaTypeNames[store::XS_BOOLEAN] = theQNamePool->insert(ns, "xs", "boolean");
+  theQNamePool->insert(JS_NULL_QNAME, JS_URI, "js", "null");
+  theQNamePool->insert(JS_OBJECT_QNAME, JS_URI, "js", "object");
+  theQNamePool->insert(JS_ARRAY_QNAME, JS_URI, "js", "array");
+
+  theQNamePool->insert(XS_UNTYPED_QNAME, ns, "xs", "untyped");
+
+  theQNamePool->insert(XS_ANY_QNAME, ns, "xs", "anyType");
+
+  theQNamePool->insert(theSchemaTypeNames[store::XS_ANY_ATOMIC],
+                       ns, "xs", "anyAtomicType");
+
+  theQNamePool->insert(theSchemaTypeNames[store::XS_UNTYPED_ATOMIC],
+                       ns, "xs", "untypedAtomic");
+
+  theQNamePool->insert(theSchemaTypeNames[store::XS_ANY_URI], ns, "xs", "anyURI");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_QNAME], ns, "xs", "QName");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_NOTATION], ns, "xs", "NOTATION");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_STRING], ns, "xs", "string");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_NORMALIZED_STRING], ns, "xs", "normalizedString");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_TOKEN], ns, "xs", "token");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_NMTOKEN], ns, "xs", "NMTOKEN");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_LANGUAGE], ns, "xs", "language");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_NAME], ns, "xs", "Name");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_NCNAME], ns, "xs", "NCName");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_ID], ns, "xs", "ID");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_IDREF], ns, "xs", "IDREF");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_ENTITY], ns, "xs", "ENTITY");
+
+  theQNamePool->insert(theSchemaTypeNames[store::XS_DATETIME], ns, "xs", "dateTime");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_DATETIME_STAMP], ns, "xs", "dateTimeStamp");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_DATE], ns, "xs", "date");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_TIME], ns, "xs", "time");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_GYEAR_MONTH], ns, "xs", "gYearMonth");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_GYEAR], ns, "xs", "gYear");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_GMONTH_DAY], ns, "xs", "gMonthDay");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_GDAY], ns, "xs", "gDay");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_GMONTH], ns, "xs", "gMonth");
+
+  theQNamePool->insert(theSchemaTypeNames[store::XS_DURATION], ns, "xs", "duration");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_DT_DURATION], ns, "xs", "dayTimeDuration");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_YM_DURATION], ns, "xs", "yearMonthDuration");
+
+  theQNamePool->insert(theSchemaTypeNames[store::XS_FLOAT], ns, "xs", "float");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_DOUBLE], ns, "xs", "double");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_DECIMAL], ns, "xs", "decimal");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_INTEGER], ns, "xs", "integer");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_NON_POSITIVE_INTEGER], ns, "xs", "nonPositiveInteger");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_NON_NEGATIVE_INTEGER], ns, "xs", "nonNegativeInteger");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_NEGATIVE_INTEGER], ns, "xs", "negativeInteger");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_POSITIVE_INTEGER], ns, "xs", "positiveInteger");
+
+  theQNamePool->insert(theSchemaTypeNames[store::XS_LONG], ns, "xs", "long");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_INT], ns, "xs", "int");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_SHORT], ns, "xs", "short");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_BYTE], ns, "xs", "byte");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_UNSIGNED_LONG], ns, "xs", "unsignedLong");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_UNSIGNED_INT], ns, "xs", "unsignedInt");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_UNSIGNED_SHORT], ns, "xs", "unsignedShort");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_UNSIGNED_BYTE], ns, "xs", "unsignedByte");
+
+  theQNamePool->insert(theSchemaTypeNames[store::XS_BASE64BINARY], ns, "xs", "base64Binary");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_HEXBINARY], ns, "xs", "hexBinary");
+  theQNamePool->insert(theSchemaTypeNames[store::XS_BOOLEAN], ns, "xs", "boolean");
 
   for (csize i = 0; i < store::XS_LAST; ++i)
   {

=== modified file 'src/store/naive/store_defs.h'
--- src/store/naive/store_defs.h	2013-02-26 04:12:43 +0000
+++ src/store/naive/store_defs.h	2013-07-11 13:41:52 +0000
@@ -26,6 +26,7 @@
 //#define EMBEDED_TYPE
 //#define TEXT_ORDPATH
 
+#define XML_NS "http://www.w3.org/XML/1998/namespace";
 
 #define GET_STORE() \
   (*zorba::simplestore::StoreManagerImpl::getStoreInternal())

=== modified file 'src/system/globalenv.cpp'
--- src/system/globalenv.cpp	2013-05-13 08:45:43 +0000
+++ src/system/globalenv.cpp	2013-07-11 13:41:52 +0000
@@ -86,10 +86,11 @@
   RCHelper::addReference(m_globalEnv->theRootTypeManager);
 
   m_globalEnv->theRootStaticContext = new root_static_context();
-  RCHelper::addReference(m_globalEnv->theRootStaticContext);
   m_globalEnv->theRootStaticContext->init();
 
-  BuiltinFunctionLibrary::create(m_globalEnv->theRootStaticContext);
+  m_globalEnv->theFunctionLib = new BuiltinFunctionLibrary();
+
+  m_globalEnv->theFunctionLib->populate(m_globalEnv->theRootStaticContext);
 
   AnnotationInternal::createBuiltIn();
 
@@ -105,7 +106,7 @@
 #endif
 
   std::auto_ptr<XQueryCompilerSubsystem> lSubSystem = 
-    XQueryCompilerSubsystem::create();
+  XQueryCompilerSubsystem::create();
 
   m_globalEnv->m_compilerSubSys = lSubSystem.release();
 
@@ -139,8 +140,9 @@
   delete m_globalEnv->xqueryx_convertor;
 #endif
 
-  RCHelper::removeReference(m_globalEnv->theRootStaticContext);
-  m_globalEnv->theRootStaticContext = 0;
+  delete m_globalEnv->theRootStaticContext;
+
+  delete m_globalEnv->theFunctionLib;
 
   RCHelper::removeReference(m_globalEnv->theRootTypeManager);
   m_globalEnv->theRootTypeManager = 0;
@@ -157,8 +159,6 @@
   // see http://www.icu-project.org/apiref/icu4c/uclean_8h.html#93f27d0ddc7c196a1da864763f2d8920
   m_globalEnv->cleanup_icu();
 
-  BuiltinFunctionLibrary::destroy();
-
   delete m_globalEnv;
 	m_globalEnv = NULL;
 

=== modified file 'src/system/globalenv.h'
--- src/system/globalenv.h	2013-02-07 17:24:36 +0000
+++ src/system/globalenv.h	2013-07-11 13:41:52 +0000
@@ -22,14 +22,17 @@
 #include "common/common.h"
 #include "common/shared_types.h"
 
-namespace zorba {
+namespace zorba
+{
 
 class RootTypeManager;
 class root_static_context;
 class XQueryXConvertor;
 class DynamicLoader;
+class BuiltinFunctionLibrary;
 
-namespace internal {
+namespace internal 
+{
 class HTTPURLResolver;
 class FileURLResolver;
 class AutoFSURIMapper;
@@ -38,12 +41,15 @@
 #endif /* ZORBA_NO_FULL_TEXT */
 }
 
-namespace store {
+namespace store
+{
 class Store;
 }
 
 
-// exported for unit testing only
+/*******************************************************************************
+
+********************************************************************************/
 class ZORBA_DLL_PUBLIC GlobalEnvironment 
 {
 private:
@@ -57,6 +63,8 @@
 
   root_static_context             * theRootStaticContext;
 
+  BuiltinFunctionLibrary          * theFunctionLib;
+
   XQueryCompilerSubsystem         * m_compilerSubSys;
 
 #ifdef ZORBA_XQUERYX
@@ -95,6 +103,8 @@
 
   bool isRootStaticContextInitialized() const;
 
+  BuiltinFunctionLibrary* getFuncLib() const { return theFunctionLib; }
+
   XQueryCompilerSubsystem& getCompilerSubsystem();
 
   store::Store& getStore();
@@ -142,6 +152,8 @@
 
 #define GENV_ROOT_STATIC_CONTEXT GlobalEnvironment::getInstance().getRootStaticContext()
 
+#define GENV_FUNC_LIB GlobalEnvironment::getInstance().getFuncLib()
+
 #define GENV_DYNAMIC_LOADER GlobalEnvironment::getInstance().getDynamicLoader()
 
 }

=== modified file 'src/types/root_typemanager.cpp'
--- src/types/root_typemanager.cpp	2013-06-15 02:57:08 +0000
+++ src/types/root_typemanager.cpp	2013-07-11 13:41:52 +0000
@@ -231,7 +231,7 @@
 
 #define XSQNDECL(var, local)  \
   GENV.getStore().getItemFactory()-> \
-  createQName(var, XML_SCHEMA_NS, XML_SCHEMA_PREFIX, local)
+    createQName(var, static_context::W3C_XML_SCHEMA_NS, "xs", local)
 
   XSQNDECL(XS_ANY_ATOMIC_QNAME, "anyAtomicType");
   XSQNDECL(XS_STRING_QNAME, "string");
@@ -288,7 +288,7 @@
 
   GENV_STORE.getItemFactory()->createQName(JS_NULL_QNAME,
                                            static_context::JSONIQ_DM_NS,
-                                           "js",
+                                           "",
                                            "null");
 
   store::Item* tempQN = NULL;

=== modified file 'src/types/schema/revalidateUtils.cpp'
--- src/types/schema/revalidateUtils.cpp	2013-06-29 08:38:53 +0000
+++ src/types/schema/revalidateUtils.cpp	2013-07-11 13:41:52 +0000
@@ -495,10 +495,8 @@
     std::vector<store::Item_t>& resultList,
     const QueryLoc& loc)
 {
-  xqtref_t type = typeManager->create_named_atomic_type(typeQName,
-                                                        TypeConstants::QUANT_ONE,
-                                                        loc,
-                                                        false);
+  xqtref_t type = typeManager->create_named_simple_type(typeQName);
+
   //cout << " vup        - processTextValue: '" << textValue->c_str() << "'\n";
   //cout << " vup        - processTextValue: " << typeQName->getPrefix()->str()
   // << ":" << typeQName->getLocalName()->str() << "@"
@@ -509,7 +507,15 @@
   store::Item_t result;
   if (type != NULL)
   {
-    if ( type->type_kind() == XQType::USER_DEFINED_KIND )
+    if (type->type_kind() == XQType::ANY_SIMPLE_TYPE_KIND)
+    {
+      if (GENV_ITEMFACTORY->createUntypedAtomic(result, textValue))
+        resultList.push_back(result);
+
+      return;
+    }
+
+    if (type->type_kind() == XQType::USER_DEFINED_KIND)
     {
       const UserDefinedXQType udXQType = static_cast<const UserDefinedXQType&>(*type);
       
@@ -552,7 +558,7 @@
   }
   else
   {
-    if ( GENV_ITEMFACTORY->createUntypedAtomic( result, textValue) )
+    if (GENV_ITEMFACTORY->createUntypedAtomic(result, textValue))
       resultList.push_back(result);
   }
 }

=== modified file 'src/types/schema/schema.cpp'
--- src/types/schema/schema.cpp	2013-06-21 12:07:22 +0000
+++ src/types/schema/schema.cpp	2013-07-11 13:41:52 +0000
@@ -79,7 +79,7 @@
 #endif
 
 
-const char* Schema::XSD_NAMESPACE = XML_SCHEMA_NS;
+const char* Schema::XSD_NAMESPACE = static_context::W3C_XML_SCHEMA_NS;
 
 bool Schema::theIsInitialized = false;
 

=== modified file 'src/types/typeimpl.cpp'
--- src/types/typeimpl.cpp	2013-06-15 02:57:08 +0000
+++ src/types/typeimpl.cpp	2013-07-11 13:41:52 +0000
@@ -181,6 +181,9 @@
 {
   if (theIsBuiltin)
   {
+#ifndef NDEBUG
+    theRefCount = 1000000;
+#endif
     // register this hardcoded object to help plan serialization
     XQType* this_ptr = this;
     *::zorba::serialization::ClassSerializer::getInstance()->

=== modified file 'src/types/typemanagerimpl.cpp'
--- src/types/typemanagerimpl.cpp	2013-06-15 02:57:08 +0000
+++ src/types/typemanagerimpl.cpp	2013-07-11 13:41:52 +0000
@@ -46,6 +46,8 @@
 #include "zorbaserialization/serialize_template_types.h"
 #include "zorbaserialization/serialize_zorba_types.h"
 
+#include "context/static_context.h"
+
 #ifdef ZORBA_XBROWSER
 #include "DOMQName.h"
 #endif
@@ -259,7 +261,7 @@
 
   // If the type name is an XML Schema builtin type, then it cannot be an atomic
   // type (because, otherwise it would have been found above). So we return NULL.
-  if (ZSTREQ(qname->getNamespace(), XML_SCHEMA_NS))
+  if (qname->getNamespace() == static_context::W3C_XML_SCHEMA_NS)
   {
     if (raiseError)
     {
@@ -333,7 +335,7 @@
 
   // If the type name is an XML Schema builtin type, then it can only be one of
   // xs:NMTOKES, xs:IDREFS, or xs:ENTITIES.
-  if (ZSTREQ(qname->getNamespace(), XML_SCHEMA_NS))
+  if (qname->getNamespace() == static_context::W3C_XML_SCHEMA_NS)
   {
     RootTypeManager& rtm = GENV_TYPESYSTEM;
 

=== modified file 'src/util/http_util.cpp'
--- src/util/http_util.cpp	2013-05-31 03:38:45 +0000
+++ src/util/http_util.cpp	2013-07-11 13:41:52 +0000
@@ -24,6 +24,7 @@
 
 #include "api/unmarshaller.h"
 #include "zorbamisc/ns_consts.h"
+#include "context/static_context.h"
 
 #include "http_util.h"
 
@@ -53,16 +54,28 @@
     ItemFactory* lFactory = lInstance->getItemFactory();
     Item lNodeName = lFactory->createQName("http://expath.org/ns/http-client";, "http", "request");
     Item lEmptyItem;
+
     NsBindings nsPairs;
-    nsPairs.push_back(std::make_pair(String(XML_SCHEMA_PREFIX), String(XML_SCHEMA_NS)));
-    Item lRequestElement = lFactory->createElementNode(lEmptyItem, lNodeName,
-                                                       lFactory->createQName(XML_SCHEMA_NS,
-                                                                             XML_SCHEMA_PREFIX, "untyped"),
-                                                       true, false, nsPairs);
-    lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "method"), Item(), lFactory->createString("GET"));
+    nsPairs.push_back(std::make_pair(String(XML_SCHEMA_PREFIX),
+                                     String(static_context::W3C_XML_SCHEMA_NS)));
+
+    Item lRequestElement =
+    lFactory->createElementNode(lEmptyItem, lNodeName,
+                                lFactory->createQName(static_context::W3C_XML_SCHEMA_NS,
+                                                      "", "untyped"),
+                                true, false, nsPairs);
+
+    lFactory->createAttributeNode(lRequestElement,
+                                  lFactory->createQName("", "method"),
+                                  Item(),
+                                  lFactory->createString("GET"));
+
     lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "href"), Item(), lFactory->createString(theUri.c_str()));
+
     lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "override-media-type"), Item(), lFactory->createString("text/plain"));
+
     lFactory->createAttributeNode(lRequestElement, lFactory->createQName("", "follow-redirect"), Item(), lFactory->createString("true"));
+
     Zorba_CompilerHints_t lHints;
     lHints.opt_level = ZORBA_OPT_LEVEL_O1;
     theStaticContext->loadProlog("import module namespace httpc = \"http://www.zorba-xquery.com/modules/http-client\";";,

=== modified file 'src/zorbamisc/ns_consts.h'
--- src/zorbamisc/ns_consts.h	2013-06-25 04:47:15 +0000
+++ src/zorbamisc/ns_consts.h	2013-07-11 13:41:52 +0000
@@ -29,13 +29,10 @@
 
 #define XMLNS_NS                W3C_NS "2000/xmlns/"
 
-#define XML_NS                  W3C_NS "XML/1998/namespace"
-#define XML_SCHEMA_NS           W3C_NS "2001/XMLSchema"
 #define XML_SCHEMA_PREFIX       "xs"
 
 #define XQUERY_ERR_NS           W3C_NS "2005/xqt-errors" //not predeclared in XQuery 3.0
 #define XQUERY_LOCAL_FN_NS      W3C_NS "2005/xquery-local-functions"
-#define XQUERY_XPATH_FN_NS      W3C_NS "2005/xpath-functions"
 
 #define XSI_NS                  W3C_NS "2001/XMLSchema-instance"
 

=== modified file 'src/zorbaserialization/archiver_consts.h'
--- src/zorbaserialization/archiver_consts.h	2013-06-15 02:57:08 +0000
+++ src/zorbaserialization/archiver_consts.h	2013-07-11 13:41:52 +0000
@@ -378,7 +378,8 @@
   TYPE_DebuggerSingletonIterator,
   TYPE_DebuggerCommons,
 
-  TYPE_RCObject,
+  TYPE_SyncedRCObject,
+  TYPE_SimpleRCObject,
 
   TYPE_INT64,
   TYPE_UINT64,

=== modified file 'src/zorbaserialization/serialize_zorba_types.cpp'
--- src/zorbaserialization/serialize_zorba_types.cpp	2013-06-30 10:20:25 +0000
+++ src/zorbaserialization/serialize_zorba_types.cpp	2013-07-11 13:41:52 +0000
@@ -1203,7 +1203,7 @@
       //  store::simplestore::ElementNode *elem_node = dynamic_cast<store::simplestore::ElementNode*>(obj);
       //  haveTypedValue = elem_node->haveTypedValue();
       //  haveEmptyValue = elem_node->haveEmptyValue();
-        if (!ZSTREQ(name_of_type->getNamespace(), XML_SCHEMA_NS) ||
+        if (name_of_type->getNamespace() != static_context::W3C_XML_SCHEMA_NS ||
             !ZSTREQ(name_of_type->getLocalName(), "untyped"))
           haveTypedValue = true;
       }

=== modified file 'src/zorbatypes/rchandle.cpp'
--- src/zorbatypes/rchandle.cpp	2013-02-26 04:12:43 +0000
+++ src/zorbatypes/rchandle.cpp	2013-07-11 13:41:52 +0000
@@ -39,12 +39,15 @@
 
 ********************************************************************************/
 
-SERIALIZABLE_CLASS_VERSIONS(RCObject)
-
-SERIALIZABLE_CLASS_VERSIONS_2(SimpleRCObject, TYPE_RCObject)
-
-
-void RCObject::serialize(::zorba::serialization::Archiver& ar)
+SERIALIZABLE_CLASS_VERSIONS(SyncedRCObject)
+
+SERIALIZABLE_CLASS_VERSIONS_2(SimpleRCObject, TYPE_SimpleRCObject)
+
+
+/*******************************************************************************
+
+********************************************************************************/
+void SyncedRCObject::serialize(::zorba::serialization::Archiver& ar)
 {
   ZORBA_ASSERT(false);
 
@@ -53,67 +56,6 @@
 }
 
 
-void RCObject::addReference(SYNC_CODE(RCLock* lock)) const
-{
-#if defined WIN32 && !defined CYGWIN &&!defined ZORBA_FOR_ONE_THREAD_ONLY
-  if(lock)
-  {
-    InterlockedIncrement(&theRefCount);
-  }
-  else
-  {
-    ++theRefCount;
-  }
-
-#else
-
-  SYNC_CODE(if (lock) lock->acquire());
-
-  ++theRefCount;
-
-  SYNC_CODE(if (lock) lock->release());
-
-#endif
-}
-
-
-void RCObject::removeReference(SYNC_CODE(RCLock* lock))
-{
-#if defined WIN32 && !defined CYGWIN &&!defined ZORBA_FOR_ONE_THREAD_ONLY
-  if (lock)
-  {
-    if (!InterlockedDecrement(&theRefCount))
-    {
-      free();
-      return;
-    }
-  }
-  else
-  {
-    if (--theRefCount == 0)
-    {
-      free();
-      return; 
-    }
-  }
-
-#else
-
-  SYNC_CODE(if (lock) lock->acquire());
-
-  if (--theRefCount == 0)
-  {
-    SYNC_CODE(if (lock) lock->release());
-    free();
-    return; 
-  }
-
-  SYNC_CODE(if (lock) lock->release());
-
-#endif
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
@@ -125,11 +67,13 @@
     theRefCount = 0;
 }
 
+
 size_t SimpleRCObject::alloc_size() const
 {
   return 0;
 }
 
+
 size_t SimpleRCObject::dynamic_size() const
 {
   return sizeof( *this );

=== modified file 'src/zorbatypes/rchandle.h'
--- src/zorbatypes/rchandle.h	2013-02-26 04:12:43 +0000
+++ src/zorbatypes/rchandle.h	2013-07-11 13:41:52 +0000
@@ -26,7 +26,7 @@
 
 #include "zorbautils/fatal.h"
 
-#include "zorbatypes/rclock.h"
+#include "util/atomic_int.h"
 
 #include "zorbaserialization/class_serializer.h"
 
@@ -53,15 +53,19 @@
   reference count becomes 0.
 
 ********************************************************************************/
-class ZORBA_DLL_PUBLIC RCObject : public serialization::SerializeBaseClass
+class SyncedRCObject : public serialization::SerializeBaseClass
 {
 protected:
-  mutable long  theRefCount;
+#ifdef ZORBA_FOR_ONE_THREAD_ONLY
+  mutable long       theRefCount;
+#else
+  mutable atomic_int theRefCount;
+#endif
 
 public:
-  SERIALIZABLE_CLASS(RCObject);
+  SERIALIZABLE_CLASS(SyncedRCObject);
 
-  RCObject(::zorba::serialization::Archiver& ar)  
+  SyncedRCObject(::zorba::serialization::Archiver& ar)  
     :
     ::zorba::serialization::SerializeBaseClass(),
     theRefCount(0)
@@ -71,38 +75,48 @@
   void serialize(::zorba::serialization::Archiver& ar);
 
 public:
-  RCObject()
+  SyncedRCObject()
     :
     ::zorba::serialization::SerializeBaseClass(),
     theRefCount(0)
   {
   }
 
-  RCObject(const RCObject&) 
+  SyncedRCObject(const SyncedRCObject&) 
     :
     ::zorba::serialization::SerializeBaseClass(),
     theRefCount(0) 
   {
   }
 
-  virtual ~RCObject() { }
+  virtual ~SyncedRCObject() { }
 
-  RCObject& operator=(const RCObject&) { return *this; }
+  SyncedRCObject& operator=(const SyncedRCObject&) { return *this; }
 
   virtual void free() { delete this; }
 
+#ifdef ZORBA_FOR_ONE_THREAD_ONLY
   long getRefCount() const { return theRefCount; }
-
-  void addReference(SYNC_CODE(RCLock* lock)) const;
-
-  void removeReference(SYNC_CODE(RCLock* lock));
+#else
+  long getRefCount() const { return theRefCount.load(); }
+#endif
+
+  void addReference() const { ++theRefCount; }
+
+  void removeReference() 
+  {
+    assert(getRefCount() > 0);
+
+    if (--theRefCount == 0)
+      free();
+  }
 };
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-class ZORBA_DLL_PUBLIC SimpleRCObject : public serialization::SerializeBaseClass
+class SimpleRCObject : public serialization::SerializeBaseClass
 {
 protected:
   mutable long  theRefCount;
@@ -145,17 +159,15 @@
 
   long getRefCount() const { return theRefCount; }
 
-  void addReference(SYNC_CODE(RCLock* lock)) const { ++theRefCount; }
+  void addReference() const { ++theRefCount; }
 
-  void removeReference(SYNC_CODE(RCLock* lock))
+  void removeReference() 
   {
+    assert(getRefCount() > 0);
+
     if (--theRefCount == 0)
-    {
       free();
-    }
   }
-
-  SYNC_CODE(RCLock* getRCLock() const { return NULL; })
 };
 
 
@@ -200,7 +212,7 @@
   ~rchandle()
   {
     if (p)
-      p->removeReference(SYNC_CODE(p->getRCLock()));
+      p->removeReference();
     p = 0;
   }
 
@@ -255,8 +267,11 @@
   {
     if (p != rhs)
     {
-      if (p) p->removeReference(SYNC_CODE(p->getRCLock()));
+      if (p)
+        p->removeReference();
+
       p = const_cast<T*>(rhs);
+
       init();
     }
     return *this;
@@ -266,8 +281,11 @@
   {
     if (p != rhs)
     {
-      if (p) p->removeReference(SYNC_CODE(p->getRCLock()));
+      if (p)
+        p->removeReference();
+
       p = static_cast<T*>(const_cast<otherT*>(rhs));
+
       init();
     }
     return *this;
@@ -287,8 +305,11 @@
   {
     if (p != rhs.getp())
     {
-      if (p) p->removeReference(SYNC_CODE(p->getRCLock()));
+      if (p)
+        p->removeReference();
+
       p = static_cast<T*>(rhs.getp());
+
       rhs.setNull();
     }
     return *this;
@@ -298,7 +319,9 @@
   {
     if (p != rhs.p)
     {
-      if (p) p->removeReference(SYNC_CODE(p->getRCLock()));
+      if (p)
+        p->removeReference();
+
       p = rhs.p;
       rhs.p = NULL;
     }
@@ -323,8 +346,8 @@
 protected:
   void init()
   {
-    if (p == 0) return;
-    p->addReference(SYNC_CODE(p->getRCLock()));
+    if (p)
+      p->addReference();
   }
 
 
@@ -332,8 +355,11 @@
   {
     if (p != rhs.getp())
     {
-      if (p) p->removeReference(SYNC_CODE(p->getRCLock()));
+      if (p)
+        p->removeReference();
+
       p = static_cast<T*>(rhs.getp());
+
       init();
     }
     return *this;
@@ -363,22 +389,24 @@
 
 } // namespace ztd
 
+
 /*******************************************************************************
 
 ********************************************************************************/
 template<class T> class const_rchandle : protected rchandle<T> 
 {
 public:
-  const_rchandle (const T *_p = 0) : rchandle<T> (const_cast<T *> (_p)) {}
-
-  const_rchandle (const const_rchandle &rhs) : rchandle<T> (rhs) {}
-
-  const_rchandle (rchandle<T> &rhs) : rchandle<T> (rhs) {}
-
-  const_rchandle(::zorba::serialization::Archiver &ar) {}
-
-  const_rchandle& operator= (const const_rchandle &rhs) {
-    this->assign (rhs);
+  const_rchandle(const T* _p = 0) : rchandle<T>(const_cast<T *>(_p)) {}
+
+  const_rchandle(const const_rchandle& rhs) : rchandle<T>(rhs) {}
+
+  const_rchandle(rchandle<T>& rhs) : rchandle<T>(rhs) {}
+
+  const_rchandle(::zorba::serialization::Archiver& ar) {}
+
+  const_rchandle& operator= (const const_rchandle& rhs)
+  {
+    this->assign(rhs);
     return *this;
   }
 
@@ -387,20 +415,20 @@
 
   void setNull() { rchandle<T>::setNull();}
 
-  const T* getp () const { return rchandle<T>::getp (); }
+  const T* getp() const { return rchandle<T>::getp (); }
 
   typename rchandle<T>::union_T getp_ref() { return rchandle<T>::getp_ref(); }
 
-  operator const T * () const { return rchandle<T>::getp (); }
+  operator const T* () const { return rchandle<T>::getp(); }
 
   const T* operator->() const { return getp(); } 
   const T& operator*() const  { return *getp(); }
 
-  bool operator== (const_rchandle h) const  { return rchandle<T>::operator== (h); }
-  bool operator!= (const_rchandle h) const  { return rchandle<T>::operator!= (h); }
-  bool operator== (const T * pp) const      { return rchandle<T>::operator== (pp); } 
-  bool operator!= (const T * pp) const      { return rchandle<T>::operator!= (pp); } 
-  bool operator< (const_rchandle h) const   { return rchandle<T>::operator<  (h); }
+  bool operator== (const_rchandle h) const  { return rchandle<T>::operator==(h); }
+  bool operator!= (const_rchandle h) const  { return rchandle<T>::operator!=(h); }
+  bool operator== (const T* pp) const       { return rchandle<T>::operator==(pp); } 
+  bool operator!= (const T* pp) const       { return rchandle<T>::operator!=(pp); } 
+  bool operator< (const_rchandle h) const   { return rchandle<T>::operator<(h); }
 };
 
 
@@ -413,13 +441,13 @@
   template<class T> 
   static void addReference(T *t)
   {
-    t->addReference(SYNC_CODE(t->getRCLock()));
+    t->addReference();
   }
 
   template<class T> 
   static void removeReference(T *t)
   {
-    t->removeReference(SYNC_CODE(t->getRCLock()));
+    t->removeReference();
   }
 
   template<class T> 

=== modified file 'test/driver/testdriver_common.cpp'
--- test/driver/testdriver_common.cpp	2013-05-16 08:22:46 +0000
+++ test/driver/testdriver_common.cpp	2013-07-11 13:41:52 +0000
@@ -280,7 +280,8 @@
     bool enableDtd,
     zorba::DiagnosticHandler& errHandler)
 {
-  try {
+  try 
+  {
     zorba::Zorba* engine = driverCtx.theEngine;
     Specification& spec = *driverCtx.theSpec;
     zorba::ItemFactory& factory = *engine->getItemFactory();
@@ -336,7 +337,8 @@
       dctx->setVariable(zorba::String("x"), riter);
     }
   }
-  catch (zorba::ZorbaException const& e) {
+  catch (zorba::ZorbaException const& e)
+  {
     errHandler.error(e);
   }
 }
@@ -457,6 +459,7 @@
   }
 }
 
+
 /**
  * Set all options on the provided static context.
  */
@@ -467,7 +470,8 @@
   for (lIter = spec.optionsBegin(); lIter != spec.optionsEnd(); ++lIter)
   {
     zorba::Item lQName = driverCtx.theEngine->getItemFactory()->
-      createQName(lIter->theOptName);
+    createQName(lIter->theOptName);
+
     std::string lValue = lIter->theOptValue;
     sctx->declareOption(lQName, lValue);
   }
@@ -475,41 +479,47 @@
   if ( spec.getEnableDtd() )
   {
     zorba::Item lQName = driverCtx.theEngine->getItemFactory()->
-      createQName(
-          "http://www.zorba-xquery.com/options/features";, "", "enable");
+    createQName("http://www.zorba-xquery.com/options/features";, "", "enable");
+
     sctx->declareOption(lQName, "dtd");
   }
 }
 
+
 /**
  * Register a URIMapper on the provided static context, and save it
  * in the DriverContext for later reference.
  */
-void addURIMapper
-(DriverContext& driverCtx, const zorba::StaticContext_t& sctx,
- zorba::URIMapper* mapper)
+void addURIMapper(
+    DriverContext& driverCtx,
+    const zorba::StaticContext_t& sctx,
+    zorba::URIMapper* mapper)
 {
   sctx->registerURIMapper(mapper);
   driverCtx.theURIMappers.push_back(mapper);
 }
 
+
 /**
  * Register a URLResolver on the provided static context, and save it
  * in the DriverContext for later reference.
  */
-void addURLResolver
-(DriverContext& driverCtx, const zorba::StaticContext_t& sctx,
- zorba::URLResolver* resolver)
+void addURLResolver(
+    DriverContext& driverCtx,
+    const zorba::StaticContext_t& sctx,
+    zorba::URLResolver* resolver)
 {
   sctx->registerURLResolver(resolver);
   driverCtx.theURLResolvers.push_back(resolver);
 }
 
+
 /**
  * Set all full-text URI mappers on the provided static context.
  */
-void setFullTextURIMappers
-(DriverContext& driverCtx, const zorba::StaticContext_t& sctx)
+void setFullTextURIMappers(
+    DriverContext& driverCtx,
+    const zorba::StaticContext_t& sctx)
 {
 #ifndef ZORBA_NO_FULL_TEXT
   Specification& spec = * (driverCtx.theSpec);
@@ -522,8 +532,7 @@
 /**
  * Set the module paths based on a :- or ;-separated list of paths.
  */
-void setModulePaths
-(std::string paths, zorba::StaticContext_t& sctx)
+void setModulePaths(std::string paths, zorba::StaticContext_t& sctx)
 {
   std::vector<zorba::String> lModulePaths;
   std::string lPath;
@@ -533,15 +542,19 @@
   char lDelim = ':';
 #endif
 
-  while (zorba::ztd::split(paths, lDelim, &lPath, &paths)) {
+  while (zorba::ztd::split(paths, lDelim, &lPath, &paths))
+  {
     lModulePaths.push_back(lPath);
   }
+
   lModulePaths.push_back(paths);
 
   // Add the default paths for test modules.
   zorba::String lDefPath = zorba::CMAKE_BINARY_DIR + "/TEST_URI_PATH";
   lModulePaths.push_back(lDefPath);
+
   lDefPath = zorba::CMAKE_BINARY_DIR + "/TEST_LIB_PATH";
   lModulePaths.push_back(lDefPath);
+
   sctx->setModulePaths(lModulePaths);
 }

=== modified file 'test/driver/testdriver_common.h'
--- test/driver/testdriver_common.h	2013-05-16 08:22:46 +0000
+++ test/driver/testdriver_common.h	2013-07-11 13:41:52 +0000
@@ -93,10 +93,11 @@
                << "[line " << xe->source_line() << "]"
                << "[column " <<  xe->source_column() << "]"
                << "[file " <<  xe->source_uri() << "]";
-      if(zorba::UserException const *ue = dynamic_cast<zorba::UserException const*>(&e))
+
+      if (zorba::UserException const *ue = dynamic_cast<zorba::UserException const*>(&e))
       {
         zorba::UserException::error_object_type  const & err_objs = ue->error_object();
-        if(!err_objs.empty())
+        if (!err_objs.empty())
         {
           strdescr << " and ..." << std::endl << "User parameters:";
           for(size_t i=0;i<err_objs.size();i++)

=== modified file 'test/driver/testdriver_mt.cpp'
--- test/driver/testdriver_mt.cpp	2013-06-25 07:47:47 +0000
+++ test/driver/testdriver_mt.cpp	2013-07-11 13:41:52 +0000
@@ -58,70 +58,112 @@
 std::string module_path;
 
 /*******************************************************************************
-  theQueriesDir      : The full pathname of the dir that contains the queries
-                       to run. It is created by appending the user-provided
-                       bucket name to RBKT_SRC_DIR/Queries (for example,
-                       RBKT_SRC_DIR/Queries/w3c_testsuite/Expressions).
-  theRefsDir         : The full pathname of the dir that contains the expected
-                       results of the queries. It is created by appending the
-                       user-provided bucket name to RBKT_SRC_DIR/ExpQueryResults.
-  theResultsDir      : The full pathname of the directory under which the result
-                       and error files of the queries will be placed. It is
-                       created by appending the user-provided bucket name to
-                       RBKT_BINARY_DIR/QueryResults.
-
-  theQueryFilenames  : The relative pathnames of the queries found under
-                       theQueriesDir. The pathname are relative to theQueriesDir.
-
-  theNumQueries      : The number of queries found under theQueriesDir.
-
-  theNumRunsPerQuery : The number of times to run each query.
-
-  theNumQueryRuns    : How many times has each query being run so far.
-
-  theQueryObjects    : Pointers to the compiled query object for each query.
-
-  theQueryStates     : For each query, whether the query was run successfuly or not.
-
-  theQueryLocks      :
-  theGlobalLock      :
+
+  theQueriesDir
+  -------------
+  The full pathname of the dir that contains the queries to run. It is a path
+  of the form <bucket-path>/Queries/<bucket-name>, where <bucket-path> is either
+  a user-provided absolute dir path, or RBKT_BINARY_DIR and <bucket-name> is a
+  user-provided bucket name (actually a relative dir path, which may also be
+  empty).
+
+  theRefsDir
+  ----------
+  The full pathname of the dir that contains the expected results of the queries.
+  It is a path of the form <bucket-path>/ExpQueryResults/<bucket-name>, where
+  <bucket-path> is either a user-provided absolute dir path, or RBKT_BINARY_DIR
+  and <bucket-name> is a user-provided bucket name (actually a relative dir path,
+  which may also be empty).
+
+  theResultsDir
+  -------------
+  The full pathname of the directory under which the result and error files of
+  the queries will be placed. It is a path of the form
+  RBKT_BINARY_DIR/QueryResults/<bucket-name>.
+
+  theIsW3Cbucket
+  --------------
+  Whether the user-provided bucket is inside W3C XQTS.
+
+  theQueryFilenames
+  -----------------
+  The relative pathnames of the queries found under theQueriesDir. The pathnames
+  are relative to theQueriesDir.
+
+  theNumQueries
+  -------------
+  The number of queries found under theQueriesDir.
+
+  theNumRunsPerQuery
+  ------------------
+  The number of times to run each query.
+
+  theNumThreads
+  -------------
+  The number of threads to use.
+
+  theOutput
+  ---------
+  The stream where the output should go to.
+
+
+  theNumQueryRuns
+  ---------------
+  How many times has each query being run so far.
+
+  theQueryStates
+  --------------
+  For each query, whether the query was run successfuly or not.
+
+  theQueryLocks :
+  ---------------
+  One lock per query. It is needed to protect theQueryObjects[queryNo] position.
+
+  theGlobalLock :
+  ---------------
+  Acquired while the next query to be run is selected and locked by each thread.
 
 ********************************************************************************/
 class Queries
 {
 public:
   std::string                   theQueriesDir;
+
   std::string                   theRefsDir;
+
   std::string                   theResultsDir;
 
+  bool                          theIsW3Cbucket;
+
   std::vector<std::string>      theQueryFilenames;
 
-  bool                          theIsW3Cbucket;
-
   long                          theNumQueries;
 
   long                          theNumRunsPerQuery;
 
+  long                          theNumThreads;
+
+  std::ostream&                 theOutput;
+
+
   std::vector<long>             theNumQueryRuns;
 
-  std::vector<zorba::XQuery_t>  theQueryObjects;
-
   std::vector<bool>             theQueryStates;
 
-  long                          theNumThreads;
-
-  std::ostream&                 theOutput;
-
   std::vector<zorba::Mutex*>    theQueryLocks;
+
   zorba::Mutex                  theGlobalLock;
 
 public:
-  Queries(std::ostream& lOutput)
+  Queries(std::ostream& output)
     :
+    theIsW3Cbucket(false),
+    theNumQueries(0),
     theNumRunsPerQuery(1),
     theNumThreads(1),
-    theOutput(lOutput)
-  {}
+    theOutput(output)
+  {
+  }
 
   ~Queries();
 
@@ -131,47 +173,55 @@
 };
 
 
+/*******************************************************************************
+
+********************************************************************************/
 Queries::~Queries()
 {
   clear();
 }
 
 
+/*******************************************************************************
+
+********************************************************************************/
 void Queries::clear()
 {
   for (long i = 0; i < theNumQueries; i++)
   {
-    theQueryObjects[i] = NULL;
     delete theQueryLocks[i];
   }
 
   theQueryFilenames.clear();
   theNumQueryRuns.clear();
-  theQueryObjects.clear();
+  theQueryStates.clear();
 
   theNumQueries = 0;
 }
 
 
+/*******************************************************************************
+  Invoked under the protection of theGlobalLock.
+********************************************************************************/
 long Queries::getQuery()
 {
-  static long nextQuery = 0;
+  static long currQuery = 0;
 
   if (theNumThreads == 1)
   {
-    if (nextQuery == theNumQueries)
+    if (currQuery == theNumQueries)
       return -1;
 
-    if (theNumQueryRuns[nextQuery] == theNumRunsPerQuery)
+    if (theNumQueryRuns[currQuery] == theNumRunsPerQuery)
     {
-      ++nextQuery;
+      ++currQuery;
 
-      if (nextQuery == theNumQueries)
+      if (currQuery == theNumQueries)
         return -1;
     }
 
-    theNumQueryRuns[nextQuery]++;
-    return nextQuery;
+    theNumQueryRuns[currQuery]++;
+    return currQuery;
   }
 
   long randomNum = rand();
@@ -236,48 +286,60 @@
 void createPath(const fs::path& filePath, std::ofstream& fileStream)
 {
 #if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
+
   fileStream.open(filePath.file_string().c_str());
+
+  if (!fileStream.good())
+  {
+    fs::path dirPath = filePath;
+    dirPath = dirPath.remove_leaf();
+    
+    if (!fs::exists(dirPath.file_string()))
+    {
+      fs::create_directories(dirPath.file_string());
+
+      // clear the bad flag on windows, which for some unknown reason doesn't
+      // reset when opening a file again
+      fileStream.clear(); 
+
+      fileStream.open(filePath.file_string().c_str());
+    }
+
+    if (!fileStream.good())
+    {
+      std::cerr << "Could not open file: " 
+                << filePath.file_string() << std::endl;
+      abort();
+    }
+  }
+
 #else
+
   fileStream.open(filePath.generic_string().c_str());
-#endif
+
   if (!fileStream.good())
   {
     fs::path dirPath = filePath;
     dirPath = dirPath.remove_leaf();
     
-#if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
-    if (!fs::exists(dirPath.file_string()))
-#else
     if (!fs::exists(dirPath.generic_string()))
-#endif
     {
-#if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
-      fs::create_directories(dirPath.file_string());
-#else
       fs::create_directories(dirPath.generic_string());
-#endif
 
       // clear the bad flag on windows, which for some unknown reason doesn't
       // reset when opening a file again
       fileStream.clear(); 
-#if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
-      fileStream.open(filePath.file_string().c_str());
-#else
       fileStream.open(filePath.generic_string().c_str());
-#endif
     }
 
     if (!fileStream.good())
     {
       std::cerr << "Could not open file: " 
-#if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
-                << filePath.file_string() << std::endl;
-#else
                 << filePath.generic_string() << std::endl;
-#endif
       abort();
     }
   }
+#endif
 }
 
 
@@ -338,18 +400,16 @@
 
   ulong numCanon = 0;
 
-  long queryNo;
-
   std::string w3cDataDir = "/Queries/w3c_testsuite/TestSources/";
   std::string uri_map_file = rbkt_src_dir + w3cDataDir + "uri.txt";
   std::string mod_map_file = rbkt_src_dir + w3cDataDir + "module.txt";
   std::string col_map_file = rbkt_src_dir + w3cDataDir + "collection.txt";
 
-  std::auto_ptr<zorba::TestSchemaURIMapper> smapper
-    (new zorba::TestSchemaURIMapper(uri_map_file.c_str(), false));
+  std::auto_ptr<zorba::TestSchemaURIMapper> smapper;
   std::auto_ptr<zorba::TestModuleURIMapper> mmapper;
-  std::auto_ptr<zorba::TestCollectionURIMapper>    cmapper;
-  std::auto_ptr<zorba::TestSchemeURIMapper>    dmapper;
+  std::auto_ptr<zorba::TestCollectionURIMapper> cmapper;
+
+  std::auto_ptr<zorba::TestSchemeURIMapper> dmapper;
   std::auto_ptr<zorba::TestURLResolver> tresolver;
 
   while (1)
@@ -374,34 +434,23 @@
     driverContext.theRbktBinaryDir = rbkt_bin_dir;
     driverContext.theSpec = &querySpec;
 
-    zorba::XQuery_t query;
-
     // Choose a query to run. If no query is available, the thread finishes. 
     // To choose the next query, the whole query container must be locked.
     // After the query is chosen, we release the global container lock and
-    // acquire the query-specific lock for the chosen query. The query lock
-    // is needed to protect the queries->theQueryObjects[queryNo] position and
-    // to make sure that the query will be compiled only once.
+    // acquire the query-specific lock for the chosen query.
     queries->theGlobalLock.lock();
 
-    queryNo = queries->getQuery();
+    long queryNo = queries->getQuery();
 
     if (queryNo < 0)
     {
-      queries->theOutput << "Thread " << tno << " finished " << std::endl;
-      queries->theOutput << std::endl << "Number of canonicaliations = " << numCanon << std::endl;
+      queries->theOutput << "Thread " << tno << " finished " << std::endl
+                         << std::endl << "Number of canonicaliations = "
+                         << numCanon << std::endl;
       queries->theGlobalLock.unlock();
       return 0;
     }
 
-    queries->theQueryLocks[queryNo]->lock();
-    queries->theGlobalLock.unlock();
-#ifndef WIN32
-    sched_yield();
-#else
-    // SwitchToThread();
-#endif
-
     // Form the full pathname for the file containing the query.
     relativeQueryFile = queries->theQueryFilenames[queryNo];
     queryPath = fs::path(queries->theQueriesDir) / (relativeQueryFile);
@@ -411,11 +460,23 @@
 #else
     std::string testName = fs::change_extension(queryPath, "").generic_string();
 #endif
+
     ulong pos = testName.find("Queries");
     testName = testName.substr(pos + 8);
 
     queries->theOutput << "*** " << queryNo << " : " << testName
-                       << " by thread " << tno << std::endl << std::endl;
+                       << " by thread " << tno << " runNo : "
+                       << queries->theNumQueryRuns[queryNo]
+                       << std::endl << std::endl;
+
+    queries->theQueryLocks[queryNo]->lock();
+    queries->theGlobalLock.unlock();
+
+#ifndef WIN32
+    sched_yield();
+#else
+    // SwitchToThread();
+#endif
 
     // Form the full pathname for the .spec file that may be associated
     // with this query. If the .spec file exists, read its contents to
@@ -423,11 +484,13 @@
     // exprected errors, or the pathnames of reference-result files.
     specPath = fs::change_extension(queryPath, ".spec");
     if (fs::exists(specPath))
+    {
 #if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
       querySpec.parseFile(specPath.file_string(), rbkt_src_dir, rbkt_bin_dir); 
 #else
       querySpec.parseFile(specPath.generic_string(), rbkt_src_dir, rbkt_bin_dir);
 #endif
+    }
 
     // Get the pathnames of the ref-result files found in the .spec file (if any).
     // If no ref-results file was specified in the .spec file, create a default
@@ -446,6 +509,7 @@
     if (refFilePaths.size() == 0) 
     {
       std::string relativeRefFile = relativeQueryFile;
+
       if (queries->theIsW3Cbucket)
       {
         ulong pos;
@@ -481,28 +545,32 @@
     createPath(resultFilePath, resFileStream);
     createPath(errorFilePath, errFileStream);
 
+    queries->theQueryLocks[queryNo]->unlock();
+
     // Create the static context. If this is a w3c query, install special uri
     // resolvers in the static context.
     zorba::StaticContext_t sctx = zorba->createStaticContext();
 
     if (queries->theIsW3Cbucket) 
     {
-      mmapper.reset
-        (new zorba::TestModuleURIMapper(mod_map_file.c_str(),
-          testName, false));
-      cmapper.reset(new zorba::TestCollectionURIMapper(
-            col_map_file.c_str(), rbkt_src_dir));
+      smapper.reset(
+      new zorba::TestSchemaURIMapper(uri_map_file.c_str(), false));
+
+      mmapper.reset(
+      new zorba::TestModuleURIMapper(mod_map_file.c_str(), testName, false));
+
+      cmapper.reset(
+      new zorba::TestCollectionURIMapper(col_map_file.c_str(), rbkt_src_dir));
+
       addURIMapper(driverContext, sctx, smapper.get());
       addURIMapper(driverContext, sctx, mmapper.get());
       addURIMapper(driverContext, sctx, cmapper.get());
 
       sctx->setXQueryVersion(zorba::xquery_version_1_0);
-      zorba::Item lEnable
-        = zorba->getItemFactory()->createQName(
-              "http://www.zorba-xquery.com/options/features";, "", "enable");
-      zorba::Item lDisable
-        = zorba->getItemFactory()->createQName(
-            "http://www.zorba-xquery.com/options/features";, "", "disable");
+
+      zorba::Item lDisable = zorba->getItemFactory()->
+      createQName("http://www.zorba-xquery.com/options/features";, "", "disable");
+
       sctx->declareOption(lDisable, "scripting");
       sctx->setTraceStream(queries->theOutput);
     }
@@ -513,6 +581,7 @@
     {
       dmapper.reset(new zorba::TestSchemeURIMapper(rbkt_src_dir));
       addURIMapper(driverContext, sctx, dmapper.get());
+
       tresolver.reset(new zorba::TestURLResolver());
       addURLResolver(driverContext, sctx, tresolver.get());
     }
@@ -535,82 +604,63 @@
 #endif
 
     //
-    // Compile the query, if it has not been compiled already. 
-    //
-    if (queries->theQueryObjects[queryNo] == 0)
-    {
-#if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
-      slurp_file(queryPath.file_string().c_str(),
-                 queryString,
-                 rbkt_src_dir,
-                 rbkt_bin_dir);
-#else
-      slurp_file(queryPath.generic_string().c_str(),
-                 queryString,
-                 rbkt_src_dir,
-                 rbkt_bin_dir);
-#endif
-                 
-
-      try
-      {
-        query = zorba->createQuery(&errHandler);
-
-#if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
-        query->setFileName(queryPath.file_string());
-#else
-        query->setFileName(queryPath.generic_string());
-#endif
-        query->compile(queryString.c_str(), sctx, getCompilerHints());
-      }
-      catch(...)
-      {
-        queries->theOutput << "FAILURE : thread " << tno << " query " << queryNo
-                           << " : " << queries->theQueryFilenames[queryNo]
-                           << std::endl
-                           << "Reason: received an unexpected exception during compilation"
-                           << std::endl << std::endl;
-
-        queries->theQueryLocks[queryNo]->unlock();
-        failure = true;
-        goto done;
-      }
-
-      if (errHandler.errors())
-      {
-        if (checkErrors(querySpec, errHandler, queries->theOutput))
-        {
-          queries->theQueryLocks[queryNo]->unlock();
-          goto done;
-        }
-        else
-        {
-          queries->theOutput << "FAILURE : thread " << tno << " query " << queryNo
-                             << " : " << queries->theQueryFilenames[queryNo]
-                             << std::endl
-                             << "Reason: received the following unexpected compilation errors : ";
-          printErrors(errHandler, NULL, false, queries->theOutput);
-          queries->theOutput << std::endl << std::endl;
-
-          queries->theQueryLocks[queryNo]->unlock();
-          failure = true;
-          goto done;
-        }
-      }
-
-      queries->theQueryObjects[queryNo] = query;
-    }
-
-    queries->theQueryLocks[queryNo]->unlock();
-
-    //
-    // Clone the compiled query and register with it the error handler of the
-    // current thread.
-    // 
-    query = queries->theQueryObjects[queryNo]->clone();
+    // Create the query and register the error handler with it.
+    //
+    zorba::XQuery_t query = zorba->createQuery(&errHandler);
 
     query->registerDiagnosticHandler(&errHandler);
 
+    //
+    // Compile the query
+    //
+#if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
+    slurp_file(queryPath.file_string().c_str(),
+               queryString, rbkt_src_dir, rbkt_bin_dir);
+#else
+    slurp_file(queryPath.generic_string().c_str(),
+               queryString, rbkt_src_dir, rbkt_bin_dir);
+#endif
+
+    try
+    {
+#if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
+      query->setFileName(queryPath.file_string());
+#else
+      query->setFileName(queryPath.generic_string());
+#endif
+
+      query->compile(queryString.c_str(), sctx, getCompilerHints());
+    }
+    catch(...)
+    {
+      queries->theOutput << "FAILURE : thread " << tno << " query " << queryNo
+                         << " : " << queries->theQueryFilenames[queryNo]
+                         << std::endl
+                         << "Reason: received an unexpected exception during compilation"
+                         << std::endl << std::endl;
+      failure = true;
+      goto done;
+    }
+
+    if (errHandler.errors())
+    {
+      if (checkErrors(querySpec, errHandler, queries->theOutput))
+      {
+        goto done;
+      }
+      else
+      {
+        queries->theOutput << "FAILURE : thread " << tno << " query " << queryNo
+                           << " : " << queries->theQueryFilenames[queryNo]
+                           << std::endl
+                           << "Reason: received the following unexpected compilation errors : ";
+        printErrors(errHandler, NULL, false, queries->theOutput);
+        queries->theOutput << std::endl << std::endl;
+
+        failure = true;
+        goto done;
+      }
+    }
 
     //
     // Execute the query
@@ -628,6 +678,7 @@
         lSerOptions.indent = ZORBA_INDENT_NO;
 
         query->execute(resFileStream, &lSerOptions);
+
         resFileStream.close();
       }
     }
@@ -661,7 +712,8 @@
       }
     }
     else if (querySpec.getComparisonMethod() != "Ignore" 
-             && querySpec.errorsSize() > 0 && !refFileSpecified)
+             && querySpec.errorsSize() > 0 &&
+             !refFileSpecified)
     {
       queries->theOutput << "FAILURE : thread " << tno << " query " << queryNo
                          << " : " << queries->theQueryFilenames[queryNo]
@@ -756,6 +808,9 @@
 }
 
 
+/*******************************************************************************
+
+********************************************************************************/
 void usage()
 {
   std::cerr << "\nusage: testdriver_mt -b <bucket> [options]       OR" << std::endl
@@ -769,6 +824,9 @@
 }
 
 
+/*******************************************************************************
+
+********************************************************************************/
 int
 #ifdef _WIN32_WCE
 _tmain(int argc, _TCHAR* argv[])
@@ -878,16 +936,20 @@
   // This is a cheap and easy way to make a "null" ostream:
   std::ostringstream nullstream;
   nullstream.clear(std::ios::badbit);
+
+  //
+  // Create the query manager
+  //
   Queries queries(quiet ? nullstream : std::cout);
+
   queries.theNumRunsPerQuery = numRunsPerQuery;
   queries.theNumThreads = numThreads;
 
-  // Unfortunately there are still places SOMEwhere (in zorba? in a
-  // dependent library?) that output to stderr. It's important for the
-  // remote queue in particular that -q actually work, so we attempt
-  // to shut them up here. QQQ if we can figure out where those
-  // messages are coming from it would be better to fix those than
-  // take this heavy-handed approach.
+  // Unfortunately there are still places SOMEwhere (in zorba? in a dependent
+  // library?) that output to stderr. It's important for the remote queue in
+  // particular that -q actually work, so we attempt to shut them up here.
+  // QQQ if we can figure out where those messages are coming from it would be
+  // better to fix those than take this heavy-handed approach.
   if (quiet) 
   {
 #ifndef WIN32
@@ -904,8 +966,6 @@
   if (bucketPath == "") 
   {
     bucketPath = zorba::RBKT_SRC_DIR;
-    // QQQ Probably should have an option for specifying alternative
-    // resultsDir too
   }
   else 
   {
@@ -927,7 +987,9 @@
 			testExtension = ".xqx";
 		}
     else if ((pos = refsDir.find("XQuery")) != std::string::npos)
+    {
       refsDir = refsDir.erase(pos, 7);
+    }
   }
 
   reportFilepath = zorba::RBKT_BINARY_DIR + "/../../Testing/" + reportFilename;
@@ -945,38 +1007,35 @@
 #else
   path = fs::system_complete(fs::path(queriesDir));
 #endif
+
   if (!fs::is_directory(path))
   {
     std::cerr << "The directory " << queriesDir << " could not be found" << std::endl;
     exit(2);
   }
+
 #if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
   queries.theQueriesDir = path.file_string();
+  path = fs::system_complete(fs::path(refsDir, fs::native));
 #else
   queries.theQueriesDir = path.generic_string();
-#endif
-
-#if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
-  path = fs::system_complete(fs::path(refsDir, fs::native));
-#else
   path = fs::system_complete(fs::path(refsDir));
 #endif
+
   if (!fs::is_directory(path))
   {
     std::cerr << "The directory " << refsDir << " could not be found" << std::endl;
     exit(2);
   }
+
 #if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
   queries.theRefsDir = path.native_directory_string();
+  path = fs::system_complete(fs::path(resultsDir, fs::native));
 #else
   queries.theRefsDir = path.parent_path().generic_string();
-#endif
-
-#if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
-  path = fs::system_complete(fs::path(resultsDir, fs::native));
-#else
   path = fs::system_complete(fs::path(resultsDir));
 #endif
+
   if (!fs::exists(path))
   {
     fs::create_directories(path);
@@ -986,6 +1045,7 @@
     std::cerr << "The pathname " << resultsDir << " is not a directory" << std::endl;
     exit(2);
   }
+
 #if !defined(BOOST_FILESYSTEM_VERSION) || BOOST_FILESYSTEM_VERSION == 2
   queries.theResultsDir = path.native_directory_string();
 #else
@@ -1045,7 +1105,6 @@
   // Prepare the Queries container
   //
   queries.theNumQueryRuns.resize(queries.theNumQueries);
-  queries.theQueryObjects.resize(queries.theNumQueries);
   queries.theQueryLocks.resize(queries.theNumQueries);
   queries.theQueryStates.resize(queries.theNumQueries);
 

=== modified file 'test/rbkt/Queries/zorba/updates/forms.xsd'
--- test/rbkt/Queries/zorba/updates/forms.xsd	2012-06-01 08:35:24 +0000
+++ test/rbkt/Queries/zorba/updates/forms.xsd	2013-07-11 13:41:52 +0000
@@ -11,7 +11,7 @@
      </xs:sequence>
     </xs:complexType>
 
-      <xs:element name="form" type="Form"></xs:element>
+    <xs:element name="form" type="Form"></xs:element>
 
     <xs:complexType name="Hidden">
       <xs:attribute name="name" type="xs:string" use="required"></xs:attribute>


Follow ups