<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <assert.h>

#include <zorba/external_module.h>
#include <zorba/serialization_callback.h>
#include <zorba/declared_collection.h>
#include <zorba/declared_index.h>

#include "zorbaserialization/serialization_engine.h"

#include "zorbautils/strutil.h"
#include "zorbautils/hashmap_strh.h"
#define ZORBA_UTILS_HASHMAP_WITH_SERIALIZATION
#include "zorbautils/hashmap_itemp.h"
#undef ZORBA_UTILS_HASHMAP_WITH_SERIALIZATION

#include "context/static_context_consts.h"
#include "context/static_context.h"
#include "context/root_static_context.h"
#include "context/namespace_context.h"
#include "context/uri_resolver_wrapper.h"
#include "context/standard_uri_resolvers.h"
#include "context/decimal_format.h"
#include "context/sctx_map_iterator.h"

#include "compiler/expression/expr_base.h"
#include "compiler/expression/var_expr.h"
#include "compiler/xqddf/collection_decl.h"
#include "compiler/xqddf/value_index.h"
#include "compiler/xqddf/value_ic.h"

#include "zorbatypes/collation_manager.h"
#include "zorbatypes/URI.h"

#include "api/unmarshaller.h"

#include "zorbaerrors/error_manager.h"

#include "system/globalenv.h"

#include "types/typemanager.h"
#include "types/casting.h"

#include "functions/function.h"
#include "functions/library.h"
#include "functions/signature.h"

#include "store/api/store.h"
#include "store/api/item_factory.h"
#include "store/api/iterator.h"


using namespace std;

namespace zorba
{

#define ITEM_FACTORY (GENV.getStore().getItemFactory())


SERIALIZABLE_CLASS_VERSIONS(BaseUriInfo)
END_SERIALIZABLE_CLASS_VERSIONS(BaseUriInfo)

SERIALIZABLE_CLASS_VERSIONS(static_context::ctx_module_t)
END_SERIALIZABLE_CLASS_VERSIONS(static_context::ctx_module_t)

SERIALIZABLE_CLASS_VERSIONS(static_context)
END_SERIALIZABLE_CLASS_VERSIONS(static_context)


/***************************************************************************//**

********************************************************************************/
void BaseUriInfo::serialize(::zorba::serialization::Archiver& ar)
{
  ar & thePrologBaseUri;
  ar & theApplicationBaseUri;
  ar & theEntityRetrievalUri;
  ar & theEncapsulatingEntityUri;

  ar & theBaseUri;
}


/***************************************************************************//**

********************************************************************************/
void static_context::ctx_module_t::serialize(serialization::Archiver& ar)
{
  if(ar.is_serializing_out())
  {
    // serialize out: the uri of the module that is used in this plan

    xqpStringStore_t lURI = Unmarshaller::getInternalString(module->getURI());
	  ar.set_is_temp_field(true);
    ar.dont_allow_delay();
    ar & lURI;
	  ar.set_is_temp_field(false);
    ar & dyn_loaded_module;
    ar & sctx;
  }
  else
  {
    // serialize in: load the serialized uri of the module and
    //               get the externalmodule from the user's
    //               registered serialization callback
    xqpStringStore_t lURIStore = 0;
	  ar.set_is_temp_field(true);
    ar & lURIStore;
	  ar.set_is_temp_field(false);
    ar & dyn_loaded_module;
    ar & sctx;

    if (dyn_loaded_module)
    {
      StandardModuleURIResolver* moduleResolver = GENV.getModuleURIResolver();

      ZORBA_ASSERT(sctx);
      module = moduleResolver->getExternalModule(lURIStore, *sctx);

      // no way to get the module
      if (!module)
      {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             << " the external module " << lURIStore
                             << " is not available to be loaded from a"
                             << " dynamic library.");
      }
    }
    else
    {
      // class registered by the user
      SerializationCallback* lCallback = ar.getUserCallback();
      if (!lCallback)
      {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             << " the external module " << lURIStore
                             << " is required but no SerializationCallback is"
                             << " given for retrieving that module.");
      }

      // the life-cycle of the module is managed by the user
      module = lCallback->getExternalModule(lURIStore.getp());
      if (!module)
      {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             << " the external module " << lURIStore
                             << " is not available using the registered"
                             << " SerializationCallback");
      }
    }
  }
}


/***************************************************************************//**
  Default Constructor.
********************************************************************************/
static_context::static_context()
  :
  theParent(NULL),
  theTraceStream(NULL),
  theBaseUriInfo(NULL),
  theDocResolver(0),
  theColResolver(0),
  theExternalModulesMap(NULL),
  theNamespaceBindings(NULL),
  theVariablesMap(NULL),
  theFunctionMap(NULL),
  theFunctionArityMap(NULL),
  theCollectionMap(NULL),
  theCollectionCallback(0),
  theCollectionCallbackData(0),
  theW3CCollectionMap(NULL),
  theIndexMap(NULL),
  theIndexCallback(0),
  theIndexCallbackData(0),
  theICMap(NULL),
  theDocumentMap(NULL),
  theCollationMap(NULL),
  theDefaultCollation(NULL),
  theOptionMap(NULL),
  theXQueryVersion(StaticContextConsts::xquery_version_unknown),
  theXPathCompatibility(StaticContextConsts::xpath_unknown),
  theConstructionMode(StaticContextConsts::cons_unknown),
  theInheritMode(StaticContextConsts::inherit_unknown),
  thePreserveMode(StaticContextConsts::preserve_unknown),
  theOrderingMode(StaticContextConsts::ordering_unknown),
  theEmptyOrderMode(StaticContextConsts::empty_order_unknown),
  theBoundarySpaceMode(StaticContextConsts::boundary_space_unknown),
  theValidationMode(StaticContextConsts::validation_unknown),
  theDecimalFormats(NULL)
{
}


/*******************************************************************************

********************************************************************************/
static_context::static_context(static_context* parent)
  :
  theParent(parent),
  theTraceStream(NULL),
  theBaseUriInfo(NULL),
  theDocResolver(0),
  theColResolver(0),
  theExternalModulesMap(NULL),
  theNamespaceBindings(NULL),
  theVariablesMap(NULL),
  theFunctionMap(NULL),
  theFunctionArityMap(NULL),
  theCollectionMap(0),
  theCollectionCallback(0),
  theCollectionCallbackData(0),
  theW3CCollectionMap(NULL),
  theIndexMap(NULL),
  theIndexCallback(0),
  theIndexCallbackData(0),
  theICMap(NULL),
  theDocumentMap(NULL),
  theCollationMap(NULL),
  theDefaultCollation(NULL),
  theOptionMap(NULL),
  theXQueryVersion(StaticContextConsts::xquery_version_unknown),
  theXPathCompatibility(StaticContextConsts::xpath_unknown),
  theConstructionMode(StaticContextConsts::cons_unknown),
  theInheritMode(StaticContextConsts::inherit_unknown),
  thePreserveMode(StaticContextConsts::preserve_unknown),
  theOrderingMode(StaticContextConsts::ordering_unknown),
  theEmptyOrderMode(StaticContextConsts::empty_order_unknown),
  theBoundarySpaceMode(StaticContextConsts::boundary_space_unknown),
  theValidationMode(StaticContextConsts::validation_unknown),
  theDecimalFormats(NULL)
{
  if (theParent != NULL)
    RCHelper::addReference(theParent);
}


/*******************************************************************************

********************************************************************************/
static_context::static_context(::zorba::serialization::Archiver& ar)
  :
  SimpleRCObject(ar),
  theTraceStream(NULL),
  theBaseUriInfo(NULL),
  theDocResolver(0),
  theColResolver(0),
  theExternalModulesMap(NULL),
  theNamespaceBindings(NULL),
  theVariablesMap(NULL),
  theFunctionMap(NULL),
  theFunctionArityMap(NULL),
  theCollectionMap(0),
  theCollectionCallback(0),
  theCollectionCallbackData(0),
  theW3CCollectionMap(NULL),
  theIndexMap(0),
  theIndexCallback(0),
  theIndexCallbackData(0),
  theICMap(0),
  theDocumentMap(NULL),
  theCollationMap(NULL),
  theDefaultCollation(NULL),
  theOptionMap(NULL),
  theXQueryVersion(StaticContextConsts::xquery_version_unknown),
  theXPathCompatibility(StaticContextConsts::xpath_unknown),
  theConstructionMode(StaticContextConsts::cons_unknown),
  theInheritMode(StaticContextConsts::inherit_unknown),
  thePreserveMode(StaticContextConsts::preserve_unknown),
  theOrderingMode(StaticContextConsts::ordering_unknown),
  theEmptyOrderMode(StaticContextConsts::empty_order_unknown),
  theBoundarySpaceMode(StaticContextConsts::boundary_space_unknown),
  theValidationMode(StaticContextConsts::validation_unknown),
  theDecimalFormats(NULL)
{
}


/***************************************************************************//**
  Destructor.
********************************************************************************/
static_context::~static_context()
{
  if (theExternalModulesMap)
  {
    ExternalModuleMap::iterator ite = theExternalModulesMap->begin();
    ExternalModuleMap::iterator end = theExternalModulesMap->end();
    for(; ite != end; ++ite)
    {
      const ctx_module_t& val = ite.getValue();
      if (val.dyn_loaded_module)
      {
        val.module->destroy();
      }
    }

    delete theExternalModulesMap;
  }

  set_document_uri_resolver(0);
  set_collection_uri_resolver(0);

  if (theVariablesMap)
    delete theVariablesMap;

  if (theFunctionMap)
    delete theFunctionMap;

  if (theFunctionArityMap)
  {
    FunctionArityMap::iterator ite = theFunctionArityMap->begin();
    FunctionArityMap::iterator end = theFunctionArityMap->end();
    for (; ite != end; ++ite)
    {
      delete (*ite).second;
    }

    delete theFunctionArityMap;
  }

  if (theW3CCollectionMap)
    delete theW3CCollectionMap;

  if (theCollectionMap)
    delete theCollectionMap;

  if (theIndexMap)
    delete theIndexMap;

  if (theICMap)
    delete theICMap;

  if (theNamespaceBindings)
    delete theNamespaceBindings;

  if (theDefaultCollation)
    delete theDefaultCollation;

  if (theCollationMap)
  {
    CollationMap::iterator ite = theCollationMap->begin();
    CollationMap::iterator end = theCollationMap->end();
    for ( ; ite != end ; ++ite)
    {
      delete ite->second;
    }

    delete theCollationMap;
    theCollationMap = 0;
  }

  if (theOptionMap)
    delete theOptionMap;

  if (theDecimalFormats)
    delete theDecimalFormats;

  if (theBaseUriInfo)
    delete theBaseUriInfo;

  if (theParent)
    RCHelper::removeReference(theParent);
}


/*******************************************************************************

********************************************************************************/
void static_context::serialize_resolvers(serialization::Archiver& ar)
{
  bool lUserDocResolver, lUserColResolver;
  if (ar.is_serializing_out())
  {
    // serialize out: remember whether a doc and collection
    //                resolver was registered by the user
    lUserDocResolver = ((theDocResolver != NULL) && (dynamic_cast<StandardDocumentURIResolver*>(theDocResolver) == NULL));
    lUserColResolver = ((theColResolver != NULL) && (dynamic_cast<StandardCollectionURIResolver*>(theColResolver) == NULL));

	  ar.set_is_temp_field(true);
    ar & lUserDocResolver;
    ar & lUserColResolver;
	  ar.set_is_temp_field(false);
  }
  else
  {
    // serialize in: set the document and collection resolvers
    //               use one by the user or use the default
    //               if null is returned
    SerializationCallback* lCallback = ar.getUserCallback();

	  ar.set_is_temp_field(true);
    ar & lUserDocResolver; // doc resolver passed by the user
    ar & lUserColResolver; // col resolver passed by the user
	  ar.set_is_temp_field(false);

    // callback required but not available
    if ((lUserDocResolver || lUserColResolver) && !lCallback)
    {
      ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                           "Couldn't load pre-compiled query because"
                           << " a document or collection resolver"
                           << " is required but no SerializationCallback"
                           << " is given for retrieving these resolvers.");
    }

    if (lUserDocResolver) {
      DocumentURIResolver* lDocResolver = lCallback->getDocumentURIResolver();
      if (!lDocResolver)
      {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             " no document URI resolver could be retrieved"
                             " using the given SerializationCallback");
      }
      set_document_uri_resolver(new DocumentURIResolverWrapper(lDocResolver));
    }

    if (lUserColResolver) {
      CollectionURIResolver* lColResolver = lCallback->getCollectionURIResolver();
      if (!lColResolver) {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             " no collection URI resolver could be retrieved"
                             " using the given SerializationCallback");
      }
      set_collection_uri_resolver(new CollectionURIResolverWrapper(lColResolver));
    }
  }
}


/*******************************************************************************

********************************************************************************/
void static_context::serialize_tracestream(serialization::Archiver& ar)
{
  bool lUserTraceStream;
  if (ar.is_serializing_out())
  {
    // serialize out: remember whether the user registered a trace stream
    lUserTraceStream = (theTraceStream != 0);

	  ar.set_is_temp_field(true);
    ar & lUserTraceStream;
	  ar.set_is_temp_field(false);
  }
  else
  {
    // serialize in: set the trace stream from the user
    //               std::cerr is used if non was registered
    SerializationCallback* lCallback = ar.getUserCallback();

	  ar.set_is_temp_field(true);
    ar & lUserTraceStream; // trace stream passed by the user
	  ar.set_is_temp_field(false);

    // callback required but not available
    if (lUserTraceStream && !lCallback)
    {
      ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                           "Couldn't load pre-compiled query because "
                           << " a trace stream"
                           << " is required but no SerializationCallback"
                           << " is given for retrieving it.");
    }

    if (lUserTraceStream) {
      bool lTraceStream =  lCallback->getTraceStream(theTraceStream);
      if (!lTraceStream) {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             " no trace stream could be retrieved"
                             " using the given SerializationCallback.");
      }
    }
  }
}


/*******************************************************************************

********************************************************************************/
void static_context::serialize(::zorba::serialization::Archiver& ar)
{
  if (ar.is_serializing_out())
  {
    ar.set_is_temp_field(true);
    bool  parent_is_root = check_parent_is_root();
    ar & parent_is_root;
    ar.set_is_temp_field(false);

    if(!parent_is_root)
    {
      ar.dont_allow_delay();
      ar & theParent;
    }
    else
    {
      //  context *fooctx = NULL;
      //  ar & fooctx;
    }
  }
  else
  {
    //in serialization
    ar.set_is_temp_field(true);
    bool  parent_is_root;
    ar & parent_is_root;
    ar.set_is_temp_field(false);

    if(parent_is_root)
    {
      set_parent_as_root();
    }
    else
      ar & theParent;

    if(theParent)
      theParent->addReference(theParent->getSharedRefCounter() SYNC_PARAM2(theParent->getRCLock()));
  }

  ar & theBaseUriInfo;

  serialize_resolvers(ar);
  serialize_tracestream(ar);

  ar & theModulePaths;

  ar & theExternalModulesMap;

  SERIALIZE_TYPEMANAGER_RCHANDLE(TypeManager, theTypemgr);

  ar & theNamespaceBindings;
  ar & theDefaultElementNamespace;
  ar & theDefaultFunctionNamespace;

  ar & theVariablesMap;

  ar & theFunctionMap;
  ar & theFunctionArityMap;

  ar & theW3CCollectionMap;
  ar & theCollectionMap;
  ar & theIndexMap;
  ar & theICMap;

  ar & theCollationMap;
  ar & theDefaultCollation;

  ar & theOptionMap;

  SERIALIZE_ENUM(StaticContextConsts::xquery_version_t, theXQueryVersion);
  SERIALIZE_ENUM(StaticContextConsts::xpath_compatibility_t, theXPathCompatibility);
  SERIALIZE_ENUM(StaticContextConsts::construction_mode_t, theConstructionMode);
  SERIALIZE_ENUM(StaticContextConsts::inherit_mode_t, theInheritMode);
  SERIALIZE_ENUM(StaticContextConsts::preserve_mode_t, thePreserveMode);
  SERIALIZE_ENUM(StaticContextConsts::ordering_mode_t, theOrderingMode);
  SERIALIZE_ENUM(StaticContextConsts::empty_order_mode_t, theEmptyOrderMode);
  SERIALIZE_ENUM(StaticContextConsts::boundary_space_mode_t, theBoundarySpaceMode);<commit_msg>Updated static_context::serialize().<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <assert.h>

#include <zorba/external_module.h>
#include <zorba/serialization_callback.h>
#include <zorba/declared_collection.h>
#include <zorba/declared_index.h>

#include "zorbaserialization/serialization_engine.h"

#include "zorbautils/strutil.h"
#include "zorbautils/hashmap_strh.h"
#define ZORBA_UTILS_HASHMAP_WITH_SERIALIZATION
#include "zorbautils/hashmap_itemp.h"
#undef ZORBA_UTILS_HASHMAP_WITH_SERIALIZATION

#include "context/static_context_consts.h"
#include "context/static_context.h"
#include "context/root_static_context.h"
#include "context/namespace_context.h"
#include "context/uri_resolver_wrapper.h"
#include "context/standard_uri_resolvers.h"
#include "context/decimal_format.h"
#include "context/sctx_map_iterator.h"

#include "compiler/expression/expr_base.h"
#include "compiler/expression/var_expr.h"
#include "compiler/xqddf/collection_decl.h"
#include "compiler/xqddf/value_index.h"
#include "compiler/xqddf/value_ic.h"

#include "zorbatypes/collation_manager.h"
#include "zorbatypes/URI.h"

#include "api/unmarshaller.h"

#include "zorbaerrors/error_manager.h"

#include "system/globalenv.h"

#include "types/typemanager.h"
#include "types/casting.h"

#include "functions/function.h"
#include "functions/library.h"
#include "functions/signature.h"

#include "store/api/store.h"
#include "store/api/item_factory.h"
#include "store/api/iterator.h"


using namespace std;

namespace zorba
{

#define ITEM_FACTORY (GENV.getStore().getItemFactory())


SERIALIZABLE_CLASS_VERSIONS(BaseUriInfo)
END_SERIALIZABLE_CLASS_VERSIONS(BaseUriInfo)

SERIALIZABLE_CLASS_VERSIONS(static_context::ctx_module_t)
END_SERIALIZABLE_CLASS_VERSIONS(static_context::ctx_module_t)

SERIALIZABLE_CLASS_VERSIONS(static_context)
END_SERIALIZABLE_CLASS_VERSIONS(static_context)


/***************************************************************************//**

********************************************************************************/
void BaseUriInfo::serialize(::zorba::serialization::Archiver& ar)
{
  ar & thePrologBaseUri;
  ar & theApplicationBaseUri;
  ar & theEntityRetrievalUri;
  ar & theEncapsulatingEntityUri;

  ar & theBaseUri;
}


/***************************************************************************//**

********************************************************************************/
void static_context::ctx_module_t::serialize(serialization::Archiver& ar)
{
  if(ar.is_serializing_out())
  {
    // serialize out: the uri of the module that is used in this plan

    xqpStringStore_t lURI = Unmarshaller::getInternalString(module->getURI());
	  ar.set_is_temp_field(true);
    ar.dont_allow_delay();
    ar & lURI;
	  ar.set_is_temp_field(false);
    ar & dyn_loaded_module;
    ar & sctx;
  }
  else
  {
    // serialize in: load the serialized uri of the module and
    //               get the externalmodule from the user's
    //               registered serialization callback
    xqpStringStore_t lURIStore = 0;
	  ar.set_is_temp_field(true);
    ar & lURIStore;
	  ar.set_is_temp_field(false);
    ar & dyn_loaded_module;
    ar & sctx;

    if (dyn_loaded_module)
    {
      StandardModuleURIResolver* moduleResolver = GENV.getModuleURIResolver();

      ZORBA_ASSERT(sctx);
      module = moduleResolver->getExternalModule(lURIStore, *sctx);

      // no way to get the module
      if (!module)
      {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             << " the external module " << lURIStore
                             << " is not available to be loaded from a"
                             << " dynamic library.");
      }
    }
    else
    {
      // class registered by the user
      SerializationCallback* lCallback = ar.getUserCallback();
      if (!lCallback)
      {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             << " the external module " << lURIStore
                             << " is required but no SerializationCallback is"
                             << " given for retrieving that module.");
      }

      // the life-cycle of the module is managed by the user
      module = lCallback->getExternalModule(lURIStore.getp());
      if (!module)
      {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             << " the external module " << lURIStore
                             << " is not available using the registered"
                             << " SerializationCallback");
      }
    }
  }
}


/***************************************************************************//**
  Default Constructor.
********************************************************************************/
static_context::static_context()
  :
  theParent(NULL),
  theTraceStream(NULL),
  theBaseUriInfo(NULL),
  theDocResolver(0),
  theColResolver(0),
  theExternalModulesMap(NULL),
  theNamespaceBindings(NULL),
  theVariablesMap(NULL),
  theFunctionMap(NULL),
  theFunctionArityMap(NULL),
  theCollectionMap(NULL),
  theCollectionCallback(0),
  theCollectionCallbackData(0),
  theW3CCollectionMap(NULL),
  theIndexMap(NULL),
  theIndexCallback(0),
  theIndexCallbackData(0),
  theICMap(NULL),
  theDocumentMap(NULL),
  theCollationMap(NULL),
  theDefaultCollation(NULL),
  theOptionMap(NULL),
  theXQueryVersion(StaticContextConsts::xquery_version_unknown),
  theXPathCompatibility(StaticContextConsts::xpath_unknown),
  theConstructionMode(StaticContextConsts::cons_unknown),
  theInheritMode(StaticContextConsts::inherit_unknown),
  thePreserveMode(StaticContextConsts::preserve_unknown),
  theOrderingMode(StaticContextConsts::ordering_unknown),
  theEmptyOrderMode(StaticContextConsts::empty_order_unknown),
  theBoundarySpaceMode(StaticContextConsts::boundary_space_unknown),
  theValidationMode(StaticContextConsts::validation_unknown),
  theDecimalFormats(NULL)
{
}


/*******************************************************************************

********************************************************************************/
static_context::static_context(static_context* parent)
  :
  theParent(parent),
  theTraceStream(NULL),
  theBaseUriInfo(NULL),
  theDocResolver(0),
  theColResolver(0),
  theExternalModulesMap(NULL),
  theNamespaceBindings(NULL),
  theVariablesMap(NULL),
  theFunctionMap(NULL),
  theFunctionArityMap(NULL),
  theCollectionMap(0),
  theCollectionCallback(0),
  theCollectionCallbackData(0),
  theW3CCollectionMap(NULL),
  theIndexMap(NULL),
  theIndexCallback(0),
  theIndexCallbackData(0),
  theICMap(NULL),
  theDocumentMap(NULL),
  theCollationMap(NULL),
  theDefaultCollation(NULL),
  theOptionMap(NULL),
  theXQueryVersion(StaticContextConsts::xquery_version_unknown),
  theXPathCompatibility(StaticContextConsts::xpath_unknown),
  theConstructionMode(StaticContextConsts::cons_unknown),
  theInheritMode(StaticContextConsts::inherit_unknown),
  thePreserveMode(StaticContextConsts::preserve_unknown),
  theOrderingMode(StaticContextConsts::ordering_unknown),
  theEmptyOrderMode(StaticContextConsts::empty_order_unknown),
  theBoundarySpaceMode(StaticContextConsts::boundary_space_unknown),
  theValidationMode(StaticContextConsts::validation_unknown),
  theDecimalFormats(NULL)
{
  if (theParent != NULL)
    RCHelper::addReference(theParent);
}


/*******************************************************************************

********************************************************************************/
static_context::static_context(::zorba::serialization::Archiver& ar)
  :
  SimpleRCObject(ar),
  theTraceStream(NULL),
  theBaseUriInfo(NULL),
  theDocResolver(0),
  theColResolver(0),
  theExternalModulesMap(NULL),
  theNamespaceBindings(NULL),
  theVariablesMap(NULL),
  theFunctionMap(NULL),
  theFunctionArityMap(NULL),
  theCollectionMap(0),
  theCollectionCallback(0),
  theCollectionCallbackData(0),
  theW3CCollectionMap(NULL),
  theIndexMap(0),
  theIndexCallback(0),
  theIndexCallbackData(0),
  theICMap(0),
  theDocumentMap(NULL),
  theCollationMap(NULL),
  theDefaultCollation(NULL),
  theOptionMap(NULL),
  theXQueryVersion(StaticContextConsts::xquery_version_unknown),
  theXPathCompatibility(StaticContextConsts::xpath_unknown),
  theConstructionMode(StaticContextConsts::cons_unknown),
  theInheritMode(StaticContextConsts::inherit_unknown),
  thePreserveMode(StaticContextConsts::preserve_unknown),
  theOrderingMode(StaticContextConsts::ordering_unknown),
  theEmptyOrderMode(StaticContextConsts::empty_order_unknown),
  theBoundarySpaceMode(StaticContextConsts::boundary_space_unknown),
  theValidationMode(StaticContextConsts::validation_unknown),
  theDecimalFormats(NULL)
{
}


/***************************************************************************//**
  Destructor.
********************************************************************************/
static_context::~static_context()
{
  if (theExternalModulesMap)
  {
    ExternalModuleMap::iterator ite = theExternalModulesMap->begin();
    ExternalModuleMap::iterator end = theExternalModulesMap->end();
    for(; ite != end; ++ite)
    {
      const ctx_module_t& val = ite.getValue();
      if (val.dyn_loaded_module)
      {
        val.module->destroy();
      }
    }

    delete theExternalModulesMap;
  }

  set_document_uri_resolver(0);
  set_collection_uri_resolver(0);

  if (theVariablesMap)
    delete theVariablesMap;

  if (theFunctionMap)
    delete theFunctionMap;

  if (theFunctionArityMap)
  {
    FunctionArityMap::iterator ite = theFunctionArityMap->begin();
    FunctionArityMap::iterator end = theFunctionArityMap->end();
    for (; ite != end; ++ite)
    {
      delete (*ite).second;
    }

    delete theFunctionArityMap;
  }

  if (theW3CCollectionMap)
    delete theW3CCollectionMap;

  if (theCollectionMap)
    delete theCollectionMap;

  if (theIndexMap)
    delete theIndexMap;

  if (theICMap)
    delete theICMap;

  if (theNamespaceBindings)
    delete theNamespaceBindings;

  if (theDefaultCollation)
    delete theDefaultCollation;

  if (theCollationMap)
  {
    CollationMap::iterator ite = theCollationMap->begin();
    CollationMap::iterator end = theCollationMap->end();
    for ( ; ite != end ; ++ite)
    {
      delete ite->second;
    }

    delete theCollationMap;
    theCollationMap = 0;
  }

  if (theOptionMap)
    delete theOptionMap;

  if (theDecimalFormats)
    delete theDecimalFormats;

  if (theBaseUriInfo)
    delete theBaseUriInfo;

  if (theParent)
    RCHelper::removeReference(theParent);
}


/*******************************************************************************

********************************************************************************/
void static_context::serialize_resolvers(serialization::Archiver& ar)
{
  bool lUserDocResolver, lUserColResolver;
  if (ar.is_serializing_out())
  {
    // serialize out: remember whether a doc and collection
    //                resolver was registered by the user
    lUserDocResolver = ((theDocResolver != NULL) && (dynamic_cast<StandardDocumentURIResolver*>(theDocResolver) == NULL));
    lUserColResolver = ((theColResolver != NULL) && (dynamic_cast<StandardCollectionURIResolver*>(theColResolver) == NULL));

	  ar.set_is_temp_field(true);
    ar & lUserDocResolver;
    ar & lUserColResolver;
	  ar.set_is_temp_field(false);
  }
  else
  {
    // serialize in: set the document and collection resolvers
    //               use one by the user or use the default
    //               if null is returned
    SerializationCallback* lCallback = ar.getUserCallback();

	  ar.set_is_temp_field(true);
    ar & lUserDocResolver; // doc resolver passed by the user
    ar & lUserColResolver; // col resolver passed by the user
	  ar.set_is_temp_field(false);

    // callback required but not available
    if ((lUserDocResolver || lUserColResolver) && !lCallback)
    {
      ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                           "Couldn't load pre-compiled query because"
                           << " a document or collection resolver"
                           << " is required but no SerializationCallback"
                           << " is given for retrieving these resolvers.");
    }

    if (lUserDocResolver) {
      DocumentURIResolver* lDocResolver = lCallback->getDocumentURIResolver();
      if (!lDocResolver)
      {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             " no document URI resolver could be retrieved"
                             " using the given SerializationCallback");
      }
      set_document_uri_resolver(new DocumentURIResolverWrapper(lDocResolver));
    }

    if (lUserColResolver) {
      CollectionURIResolver* lColResolver = lCallback->getCollectionURIResolver();
      if (!lColResolver) {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             " no collection URI resolver could be retrieved"
                             " using the given SerializationCallback");
      }
      set_collection_uri_resolver(new CollectionURIResolverWrapper(lColResolver));
    }
  }
}


/*******************************************************************************

********************************************************************************/
void static_context::serialize_tracestream(serialization::Archiver& ar)
{
  bool lUserTraceStream;
  if (ar.is_serializing_out())
  {
    // serialize out: remember whether the user registered a trace stream
    lUserTraceStream = (theTraceStream != 0);

	  ar.set_is_temp_field(true);
    ar & lUserTraceStream;
	  ar.set_is_temp_field(false);
  }
  else
  {
    // serialize in: set the trace stream from the user
    //               std::cerr is used if non was registered
    SerializationCallback* lCallback = ar.getUserCallback();

	  ar.set_is_temp_field(true);
    ar & lUserTraceStream; // trace stream passed by the user
	  ar.set_is_temp_field(false);

    // callback required but not available
    if (lUserTraceStream && !lCallback)
    {
      ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                           "Couldn't load pre-compiled query because "
                           << " a trace stream"
                           << " is required but no SerializationCallback"
                           << " is given for retrieving it.");
    }

    if (lUserTraceStream) {
      bool lTraceStream =  lCallback->getTraceStream(theTraceStream);
      if (!lTraceStream) {
        ZORBA_ERROR_DESC_OSS(SRL0013_UNABLE_TO_LOAD_QUERY,
                             "Couldn't load pre-compiled query because"
                             " no trace stream could be retrieved"
                             " using the given SerializationCallback.");
      }
    }
  }
}


/*******************************************************************************

********************************************************************************/
void static_context::serialize(::zorba::serialization::Archiver& ar)
{
  if (ar.is_serializing_out())
  {
    ar.set_is_temp_field(true);
    bool  parent_is_root = check_parent_is_root();
    ar & parent_is_root;
    ar.set_is_temp_field(false);

    if(!parent_is_root)
    {
      ar.dont_allow_delay();
      ar & theParent;
    }
    else
    {
      //  context *fooctx = NULL;
      //  ar & fooctx;
    }
  }
  else
  {
    //in serialization
    ar.set_is_temp_field(true);
    bool  parent_is_root;
    ar & parent_is_root;
    ar.set_is_temp_field(false);

    if(parent_is_root)
    {
      set_parent_as_root();
    }
    else
      ar & theParent;

    if(theParent)
      theParent->addReference(theParent->getSharedRefCounter() SYNC_PARAM2(theParent->getRCLock()));
  }

  ar & theModuleNamespace;
  ar & theBaseUriInfo;

  serialize_resolvers(ar);
  serialize_tracestream(ar);

  ar & theModulePaths;

  ar & theExternalModulesMap;

  SERIALIZE_TYPEMANAGER_RCHANDLE(TypeManager, theTypemgr);

  ar & theNamespaceBindings;
  ar & theDefaultElementNamespace;
  ar & theDefaultFunctionNamespace;

  ar & theCtxItemType;

  ar & theVariablesMap;

  ar & theFunctionMap;
  ar & theFunctionArityMap;

  ar & theCollectionMap;
  
  ar & theW3CCollectionMap;
  ar & theDefaultW3CCollectionType;

  ar & theIndexMap;

  ar & theICMap;

  ar & theDocumentMap;

  ar & theCollationMap;
  ar & theDefaultCollation;

  ar & theOptionMap;

  SERIALIZE_ENUM(StaticContextConsts::xquery_version_t, theXQueryVersion);
  SERIALIZE_ENUM(StaticContextConsts::xpath_compatibility_t, theXPathCompatibility);
  SERIALIZE_ENUM(StaticContextConsts::construction_mode_t, theConstructionMode);
  SERIALIZE_ENUM(StaticContextConsts::inherit_mode_t, theInheritMode);
  SERIALIZE_ENUM(StaticContextConsts::preserve_mode_t, thePreserveMode);
  SERIALIZE_ENUM(StaticContextConsts::ordering_mode_t, theOrderingMode);
  SERIALIZE_ENUM(StaticContextConsts::empty_order_mode_t, theEmptyOrderMode);
  SERIALIZE_ENUM(StaticContextConsts::boundary_space_mode_t, theBoundarySpaceMode);
{'fraction_non_alphanumeric': 0.16786443332121584, 'fraction_numerical': 0.004390257543133581, 'mean_word_length': 3.991903964265773, 'pattern_counts': {'":': 0, '<': 89, '<?xml version=': 0, '>': 51, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6320362', 'n_tokens_mistral': 10784, 'n_tokens_neox': 10383, 'n_words': 1842}