← Back to team overview

zorba-coders team mailing list archive

[Merge] lp:~zorba-coders/zorba/expr-memman2 into lp:zorba

 

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

Requested reviews:
  Markos Zaharioudakis (markos-za)

For more details, see:
https://code.launchpad.net/~zorba-coders/zorba/expr-memman2/+merge/119523

New memory management for compiler expressions (fixes bug #1036111)
-- 
The attached diff has been truncated due to its size.
https://code.launchpad.net/~zorba-coders/zorba/expr-memman2/+merge/119523
Your team Zorba Coders is subscribed to branch lp:zorba.
=== modified file 'bin/zorbacmd.cpp'
--- bin/zorbacmd.cpp	2012-08-14 11:13:50 +0000
+++ bin/zorbacmd.cpp	2012-08-14 12:29:44 +0000
@@ -39,6 +39,9 @@
 #include <zorba/xquery_functions.h>
 #include <zorba/uri_resolvers.h>
 #include <zorba/serialization_callback.h>
+#include <zorba/audit.h>
+#include <zorba/audit_scoped.h>
+
 #include <zorba/store_manager.h>
 
 //#define DO_AUDIT
@@ -66,6 +69,8 @@
 #  include "system/properties.h"
 #endif
 
+//#define DO_AUDIT
+
 using namespace zorba;
 namespace zorbatm = zorba::time;
 
@@ -181,6 +186,35 @@
     }
   }
 
+#ifdef DO_AUDIT
+  zorba::audit::Provider* lAuditProvider = zorba->getAuditProvider();
+  zorba::audit::Configuration* config = lAuditProvider->createConfiguration();
+  std::vector<zorba::String> property_names;
+  zorba::audit::Configuration::getPropertyNames(property_names);
+
+  bool lIsStatic;
+
+  lIsStatic = zorba::audit::Configuration::
+  enableProperty(config, property_names, "xquery/compilation/parse-duration");
+  assert(lIsStatic);
+
+  lIsStatic = zorba::audit::Configuration::
+  enableProperty(config, property_names, "xquery/compilation/translation-duration");
+  assert(lIsStatic);
+
+  lIsStatic = zorba::audit::Configuration::
+  enableProperty(config, property_names, "xquery/compilation/optimization-duration");
+  assert(lIsStatic);
+
+  lIsStatic = zorba::audit::Configuration::
+  enableProperty(config, property_names, "xquery/compilation/codegeneration-duration");
+  assert(lIsStatic);
+
+  zorba::audit::Event* event = lAuditProvider->createEvent(config);
+
+  sctx->setAuditEvent(event);
+#endif // DO_AUDIT
+
 #ifndef ZORBA_NO_FULL_TEXT
   {
     ZorbaCMDProperties::FullText_t::const_iterator lIter = props.stopWordsBegin();

=== modified file 'cmake_modules/CMakeUseFlex.cmake'
--- cmake_modules/CMakeUseFlex.cmake	2012-08-14 11:13:50 +0000
+++ cmake_modules/CMakeUseFlex.cmake	2012-08-14 12:29:44 +0000
@@ -29,6 +29,7 @@
 
 IF(NOT FLEX_EXECUTABLE)
   MESSAGE(STATUS "Looking for flex")
+  FIND_PATH(FLEX_INCLUDE_DIR FlexLexer.h)
   FIND_PROGRAM(FLEX_EXECUTABLE flex)
   IF(FLEX_EXECUTABLE)
     EXEC_PROGRAM(
@@ -70,6 +71,7 @@
     ELSE(FLEX_PREFIX_OUTPUTS)
       SET(PREFIX "yy")
     ENDIF(FLEX_PREFIX_OUTPUTS)
+<<<<<<< TREE
     # If we regenerate the scanner, be sure to copy the corresponding
     # FlexLexer.h as well. Put it in the top-level src/ directory since
     # that path is on the include-directories list; also, that way
@@ -81,6 +83,19 @@
       ARGS -E copy_if_different
          "${FLEX_INCLUDE_DIR}/FlexLexer.h"
          "${FLEXLEXERH}")
+=======
+    # If we regenerate the scanner, be sure to copy the corresponding
+    # FlexLexer.h as well. Put it in the top-level src/ directory since
+    # that path is on the include-directories list; also, that way
+    # multiple flex'd files will all share the include file.
+    SET(FLEXLEXERH "${CMAKE_CURRENT_BINARY_DIR}/FlexLexer.h")
+    ADD_CUSTOM_COMMAND(
+      OUTPUT "${FLEXLEXERH}"
+      COMMAND "${CMAKE_COMMAND}"
+      ARGS -E copy_if_different
+         "${FLEX_INCLUDE_DIR}/FlexLexer.h"
+	 "${FLEXLEXERH}")
+>>>>>>> MERGE-SOURCE
     SET(OUTFILE "${CMAKE_CURRENT_BINARY_DIR}/${PATH}/${PREFIX}.cpp")
     ADD_CUSTOM_COMMAND(
       OUTPUT "${OUTFILE}"

=== modified file 'doc/c/examples/ccontext.c'
--- doc/c/examples/ccontext.c	2012-08-14 11:13:50 +0000
+++ doc/c/examples/ccontext.c	2012-08-14 12:29:44 +0000
@@ -207,7 +207,8 @@
   lExpr2->execute(lExpr2, lContext, &lSequence2);
 
   // iterate over the result two times
-  while ( lSequence2->next(lSequence2) != XQC_END_OF_SEQUENCE ) {
+  while ( lSequence2->next(lSequence2) != XQC_END_OF_SEQUENCE ) 
+  {
     lSequence2->string_value(lSequence2, &lStringValue);
     printf("%s ", lStringValue);
   }
@@ -349,7 +350,7 @@
 
   if ( zorba_implementation(&impl, store) != XQC_NO_ERROR)
     return 1;
-
+  /*
   printf("executing C example 1\n");
   res = ccontext_example_1(impl);
   if (!res) { impl->free(impl); return 1; };
@@ -364,12 +365,12 @@
   res = ccontext_example_3(impl);
   if (!res) { impl->free(impl); return 1; };
   printf("\n");
-
+  */
   printf("executing C example 4\n");
   res = ccontext_example_4(impl);
   if (!res) { impl->free(impl); return 1; };
   printf("\n");
-
+  /*
   printf("executing C example 5\n");
   res = ccontext_example_5(impl);
   if (!res) { impl->free(impl); return 1; };
@@ -379,7 +380,7 @@
   res = ccontext_example_6(impl);
   if (!res) { impl->free(impl); return 1; };
   printf("\n");
-
+  */
   impl->free(impl);
   shutdown_store(store);
   return 0;

=== modified file 'src/annotations/annotations.cpp'
--- src/annotations/annotations.cpp	2012-08-14 11:13:50 +0000
+++ src/annotations/annotations.cpp	2012-08-14 12:29:44 +0000
@@ -37,13 +37,13 @@
 SERIALIZABLE_CLASS_VERSIONS(AnnotationList)
 
 
-std::vector<store::Item_t> 
+std::vector<store::Item_t>
 AnnotationInternal::theAnnotId2NameMap;
 
-ItemHandleHashMap<AnnotationInternal::AnnotationId> 
+ItemHandleHashMap<AnnotationInternal::AnnotationId>
 AnnotationInternal::theAnnotName2IdMap(0, NULL, 64, false);
 
-std::vector<AnnotationInternal::RuleBitSet> 
+std::vector<AnnotationInternal::RuleBitSet>
 AnnotationInternal::theRuleSet;
 
 
@@ -380,11 +380,11 @@
 ********************************************************************************/
 void AnnotationList::push_back(
     const store::Item_t& qname,
-    const std::vector<rchandle<const_expr> >& literals)
+    const std::vector<const_expr* >& literals)
 {
   std::vector<store::Item_t> lLiterals;
 
-  for (std::vector<rchandle<const_expr> >::const_iterator it = literals.begin();
+  for (std::vector<const_expr* >::const_iterator it = literals.begin();
        it != literals.end();
        ++it)
   {

=== modified file 'src/annotations/annotations.h'
--- src/annotations/annotations.h	2012-08-14 11:13:50 +0000
+++ src/annotations/annotations.h	2012-08-14 12:29:44 +0000
@@ -107,11 +107,11 @@
   static store::Item* lookup(AnnotationId id);
 
 public:
-  AnnotationInternal(const store::Item_t& qname); 
+  AnnotationInternal(const store::Item_t& qname);
 
   AnnotationInternal(
     const store::Item_t& qname,
-    std::vector<store::Item_t>& literals); 
+    std::vector<store::Item_t>& literals);
 
 public:
   SERIALIZABLE_CLASS(AnnotationInternal);
@@ -158,7 +158,7 @@
 public:
   AnnotationList();
 
-	~AnnotationList();
+  ~AnnotationList();
 
   csize size() const { return theAnnotationList.size(); }
 
@@ -170,7 +170,7 @@
 
   void push_back(
       const store::Item_t& qname,
-      const std::vector<rchandle<const_expr> >& literals);
+      const std::vector<const_expr*>& literals);
 
   void checkConflictingDeclarations(const QueryLoc& loc) const;
 };

=== modified file 'src/api/auditimpl.cpp'
--- src/api/auditimpl.cpp	2012-08-14 11:13:50 +0000
+++ src/api/auditimpl.cpp	2012-08-14 12:29:44 +0000
@@ -59,14 +59,19 @@
 //************************************************************************
 
 const PropertyImpl INVALID("");
+
 const PropertyImpl XQUERY_COMPILATION_FILENAME(
     XQUERY_COMPILATION, "filename", 0, Property::STRING);
+
 const PropertyImpl XQUERY_COMPILATION_PARSE_DURATION(
     XQUERY_COMPILATION, "parse-duration", 1, Property::INT);
+
 const PropertyImpl XQUERY_COMPILATION_TRANSLATION_DURATION(
     XQUERY_COMPILATION, "translation-duration", 2, Property::INT);
+
 const PropertyImpl XQUERY_COMPILATION_OPTIMIZATION_DURATION(
     XQUERY_COMPILATION, "optimization-duration", 3, Property::INT);
+
 const PropertyImpl XQUERY_COMPILATION_CODEGENERATION_DURATION(
     XQUERY_COMPILATION, "codegeneration-duration", 4, Property::INT);
 

=== modified file 'src/api/dynamiccontextimpl.cpp'
--- src/api/dynamiccontextimpl.cpp	2012-08-14 11:13:50 +0000
+++ src/api/dynamiccontextimpl.cpp	2012-08-14 12:29:44 +0000
@@ -303,8 +303,8 @@
         TypeOps::is_equal(tm, *itemType, *rtm.STRING_TYPE_ONE, QueryLoc::null) &&
         (invalid_char = utf8::validate(value->getStringValue().c_str())) != NULL)
     {
-      throw XQUERY_EXCEPTION(err::FOCH0001, 
-      ERROR_PARAMS(zstring("#x") + 
+      throw XQUERY_EXCEPTION(err::FOCH0001,
+      ERROR_PARAMS(zstring("#x") +
       BUILD_STRING(std::uppercase << std::hex
                    << (static_cast<unsigned int>(*invalid_char) & 0xFF)) ));
     }
@@ -618,7 +618,7 @@
 /****************************************************************************//**
 
 ********************************************************************************/
-bool 
+bool
 DynamicContextImpl::isBoundExternalVariable(const String& aNamespace, const String& aLocalname) const
 {
   ZORBA_DCTX_TRY

=== modified file 'src/api/staticcontextimpl.cpp'
--- src/api/staticcontextimpl.cpp	2012-08-14 11:13:50 +0000
+++ src/api/staticcontextimpl.cpp	2012-08-14 12:29:44 +0000
@@ -73,6 +73,7 @@
 ********************************************************************************/
 StaticContextImpl::StaticContextImpl(DiagnosticHandler* aDiagnosticHandler)
   :
+  theCompilerCB(NULL),
   theMaxVarId(2),
   theDiagnosticHandler(aDiagnosticHandler),
   theUserDiagnosticHandler(true),
@@ -98,6 +99,7 @@
     DiagnosticHandler* aDiagnosticHandler)
   :
   theCtx(aCtx),
+  theCompilerCB(NULL),
   theMaxVarId(2),
   theDiagnosticHandler(aDiagnosticHandler),
   theUserDiagnosticHandler(true),
@@ -120,6 +122,7 @@
 StaticContextImpl::StaticContextImpl(const StaticContextImpl& aStaticContext)
   :
   StaticContext(),
+  theCompilerCB(NULL),
   theMaxVarId(2),
   theDiagnosticHandler(aStaticContext.theDiagnosticHandler),
   theUserDiagnosticHandler(aStaticContext.theUserDiagnosticHandler),
@@ -151,6 +154,11 @@
   {
     delete theCollectionMgr;
   }
+
+  theCtx = NULL;
+
+  if (theCompilerCB)
+    delete theCompilerCB;
 }
 
 
@@ -936,7 +944,7 @@
 StaticContextImpl::setContextItemStaticType(TypeIdentifier_t type)
 {
   xqtref_t xqType = NULL;
-  if (type != NULL) 
+  if (type != NULL)
   {
     xqType = theCtx->get_typemanager()->create_type(*type);
   }
@@ -1015,6 +1023,8 @@
     const String& prolog,
     const Zorba_CompilerHints_t& hints)
 {
+  ZORBA_ASSERT(theCompilerCB == NULL);
+
   // Create and compile an internal query whose prolog is the given prolog and
   // its body is just the emtpy sequence expression: "()".
   XQueryImpl impl;
@@ -1023,7 +1033,9 @@
   // Copy theSctxMap of the internal query into "this". When "this" is then passed
   // as an input to a user query Q, theSctxMap of Q will be initialized as a copy
   // of this->theSctxMap.
-  theSctxMap = impl.theCompilerCB->theSctxMap;
+  //theSctxMap = impl.theCompilerCB->theSctxMap;
+  theCompilerCB = impl.theCompilerCB;
+  impl.theCompilerCB = NULL;
 }
 
 
@@ -1486,7 +1498,7 @@
     // The same is true for this sctx
     Iterator_t lIter = impl->iterator();
     return new InvokeItemSequence(impl.release(), lIter, const_cast<StaticContextImpl*>(this));
-  } 
+  }
   catch (ZorbaException const& e)
   {
     ZorbaImpl::notifyError(theDiagnosticHandler, e);

=== modified file 'src/api/staticcontextimpl.h'
--- src/api/staticcontextimpl.h	2012-08-14 11:13:50 +0000
+++ src/api/staticcontextimpl.h	2012-08-14 12:29:44 +0000
@@ -65,7 +65,9 @@
 protected:
   static_context_t                    theCtx;
 
-  std::map<csize, static_context_t>   theSctxMap;
+  CompilerCB                        * theCompilerCB;
+
+  //std::map<csize, static_context_t>   theSctxMap;
 
   ulong                               theMaxVarId;
 

=== modified file 'src/api/xqueryimpl.cpp'
--- src/api/xqueryimpl.cpp	2012-08-14 11:13:50 +0000
+++ src/api/xqueryimpl.cpp	2012-08-14 12:29:44 +0000
@@ -190,13 +190,11 @@
     delete theCompilerCB;
     theCompilerCB = NULL;
   }
-  else
-  {
-    ar.set_ccb(theCompilerCB);
-  }
 
   ar & theCompilerCB;
+
   ar & thePlanProxy;
+
   ar & theStaticContext;
 
   if (!ar.is_serializing_out())
@@ -336,7 +334,7 @@
     theDiagnosticHandler = aDiagnosticHandler;
     theUserDiagnosticHandler = true;
 
-    if (theCollMgr) 
+    if (theCollMgr)
     {
       theCollMgr->registerDiagnosticHandler(theDiagnosticHandler);
     }
@@ -488,11 +486,13 @@
 
     // If the static context results from loadProlog, we need all the contexts
     // that were created when compiling the load-prolog query
-    theCompilerCB->theSctxMap =
-    static_cast<StaticContextImpl*>(aStaticContext.get())->theSctxMap;
-
-    ulong nextVarId = 
-    static_cast<StaticContextImpl*>(aStaticContext.get())->getMaxVarId();
+    StaticContextImpl* externalSctx =
+    static_cast<StaticContextImpl*>(aStaticContext.get());
+
+    if (externalSctx->theCompilerCB)
+      theCompilerCB->theSctxMap = externalSctx->theCompilerCB->theSctxMap;
+
+    ulong nextVarId = externalSctx->getMaxVarId();
 
     std::istringstream lQueryStream(aQuery.c_str());
 
@@ -521,11 +521,13 @@
 
     // if the static context results from loadProlog, we need all the context
     // that were created when compiling the load-prolog query
-    theCompilerCB->theSctxMap =
-    static_cast<StaticContextImpl*>(aStaticContext.get())->theSctxMap;
-
-    ulong nextVarId = 
-    static_cast<StaticContextImpl*>(aStaticContext.get())->getMaxVarId();
+    StaticContextImpl* externalSctx =
+    static_cast<StaticContextImpl*>(aStaticContext.get());
+
+    if (externalSctx->theCompilerCB)
+      theCompilerCB->theSctxMap = externalSctx->theCompilerCB->theSctxMap;
+
+    ulong nextVarId = externalSctx->getMaxVarId();
 
     doCompile(aQuery, aHints, true, nextVarId);
   }
@@ -588,7 +590,7 @@
 
 #ifdef ZORBA_WITH_DEBUGGER
   // if the debug mode is set, we force the gflwor, we set the query input stream
-  if (theIsDebugMode) 
+  if (theIsDebugMode)
   {
     theCompilerCB->theConfig.force_gflwor = true;
     theCompilerCB->theDebuggerCommons = new DebuggerCommons(theCompilerCB->theRootSctx);
@@ -724,7 +726,7 @@
   checkNotClosed();
   checkCompiled();
 
-  if (!theCollMgr) 
+  if (!theCollMgr)
   {
     std::vector<StaticCollectionManagerImpl*> lMgrs;
 
@@ -733,7 +735,7 @@
 
     for (CompilerCB::SctxMap::iterator lIter = theCompilerCB->theSctxMap.begin();
         lIter != theCompilerCB->theSctxMap.end();
-         ++lIter) 
+         ++lIter)
     {
       // this object is only need to construct the StaticCollectionManagerImpl
       // but it's not used after the construction anymore
@@ -780,10 +782,17 @@
       extVars.push_back((*lVarIte)->getName());
     } 
 
+<<<<<<< TREE
    Iterator_t vIter = new VectorIterator(extVars, theDiagnosticHandler);
 
     aVarsIter = vIter; 
     
+=======
+   Iterator_t vIter = new VectorIterator(extVars, theDiagnosticHandler);
+
+   aVarsIter = vIter;
+
+>>>>>>> MERGE-SOURCE
   }
   QUERY_CATCH
 }
@@ -802,7 +811,7 @@
 
     zstring& nameSpace = Unmarshaller::getInternalString(aNamespace);
     zstring& localName = Unmarshaller::getInternalString(aLocalname);
-    
+
     store::Item_t qname;
     GENV_ITEMFACTORY->createQName(qname, nameSpace, zstring(), localName);
     
@@ -1413,7 +1422,7 @@
                                    aCallbackData,
                                    aHost,
                                    aPort);
-    if (!aDebuggerServer.run()) 
+    if (!aDebuggerServer.run())
     {
       aDebuggerServer.throwError();
     }
@@ -1432,14 +1441,14 @@
 {
   SYNC_CODE(AutoMutex lock(&theMutex);)
 
-  try 
+  try
   {
-    if (theIsClosed) 
+    if (theIsClosed)
     {
       return;
     }
 
-    if (theResultIterator != NULL) 
+    if (theResultIterator != NULL)
     {
       theResultIterator->closeInternal();
       theResultIterator = NULL;
@@ -1447,7 +1456,7 @@
 
     theExecuting = false;
 
-    if (thePlanProxy) 
+    if (thePlanProxy)
     {
       thePlanProxy = NULL;
     }
@@ -1456,7 +1465,7 @@
     theXQueryDiagnostics = NULL;
 
     // see registerDiagnosticHandler
-    if (!theUserDiagnosticHandler) 
+    if (!theUserDiagnosticHandler)
     {
       delete theDiagnosticHandler;
       theDiagnosticHandler = NULL;
@@ -1471,7 +1480,7 @@
     theStaticContext = NULL;
 
     // theCompilerCB may be NULL if an error occured while serializing "this" in.
-    if (theCompilerCB) 
+    if (theCompilerCB)
     {
 #ifdef ZORBA_WITH_DEBUGGER
       delete theCompilerCB->theDebuggerCommons;
@@ -1493,7 +1502,7 @@
 ********************************************************************************/
 void XQueryImpl::checkIsDebugMode() const
 {
-  if (!theIsDebugMode) 
+  if (!theIsDebugMode)
   {
     throw ZORBA_EXCEPTION( zerr::ZAPI0009_XQUERY_NOT_COMPILED_IN_DEBUG_MODE );
   }

=== modified file 'src/common/shared_types.h'
--- src/common/shared_types.h	2012-08-14 11:13:50 +0000
+++ src/common/shared_types.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,14 +22,14 @@
 
 #include "store/api/shared_types.h"
 
-namespace zorba 
+namespace zorba
 {
 
 class XQueryDiagnostics;
-  
-namespace types 
+
+namespace types
 {
-  class TypeIdentifier; 
+  class TypeIdentifier;
 };
 
 
@@ -82,7 +82,7 @@
 
 
 // Parsenodes
-class parsenode; 
+class parsenode;
 class exprnode;
 typedef rchandle<parsenode> parsenode_t;
 
@@ -91,16 +91,13 @@
 typedef rchandle<AnnotationList> AnnotationList_t;
 
 // Expression nodes
-class expr; 
+class expr;
 class fo_expr;
 class var_expr;
 class flwor_clause;
 class forletwin_clause;
 class for_clause;
 class let_clause;
-typedef rchandle<expr> expr_t;
-typedef rchandle<var_expr> var_expr_t;
-typedef rchandle<fo_expr> fo_expr_t;
 typedef rchandle<flwor_clause> flwor_clause_t;
 typedef rchandle<for_clause> for_clause_t;
 typedef rchandle<let_clause> let_clause_t;

=== modified file 'src/compiler/api/compiler_api.cpp'
--- src/compiler/api/compiler_api.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/api/compiler_api.cpp	2012-08-14 12:29:44 +0000
@@ -154,8 +154,8 @@
 
   if(xqxconvertor->isXQueryX((char*)xquery_str.c_str()))
   {
-    // identify XQueryX by content: 
-    // root tag = 
+    // identify XQueryX by content:
+    // root tag =
     // "<prefix:module ... xmlns:prefix="http://www.w3.org/2005/XQueryX"; ... > "
 
     is_xqueryx = true;
@@ -211,18 +211,17 @@
   zorba::audit::ScopedRecord sar(ae);
 
   const char* lFileName = aFileName.c_str();
-  zorba::audit::ScopedAuditor<const char*> filenameAudit(
-      sar, zorba::audit::XQUERY_COMPILATION_FILENAME, lFileName);
+
+  audit::ScopedAuditor<const char*>
+  filenameAudit(sar, zorba::audit::XQUERY_COMPILATION_FILENAME, lFileName);
 
   parsenode_t lAST;
 
   {
     time::Timer lTimer;
 
-    audit::DurationAuditor 
-    durationAudit(sar,
-                  audit::XQUERY_COMPILATION_PARSE_DURATION,
-                  lTimer);
+    audit::DurationAuditor
+    durationAudit(sar, audit::XQUERY_COMPILATION_PARSE_DURATION, lTimer);
 
     lAST = parse(aXQuery, aFileName);
 
@@ -233,9 +232,7 @@
     }
   }
 
-  expr_t rootExpr;
-
-  return compile(lAST, true, rootExpr, nextDynamicVarId, sar);
+  return compile(lAST, true, nextDynamicVarId, sar);
 }
 
 
@@ -245,14 +242,15 @@
 PlanIter_t XQueryCompiler::compile(
     const parsenode_t& ast,
     bool applyPUL,
-    expr_t& rootExpr,
     ulong& nextDynamicVarId,
     audit::ScopedRecord& aAuditRecord)
 {
+  expr* rootExpr;
+
   {
     time::Timer lTimer;
 
-    audit::DurationAuditor 
+    audit::DurationAuditor
     durationAudit(aAuditRecord,
                   audit::XQUERY_COMPILATION_TRANSLATION_DURATION,
                   lTimer);
@@ -276,6 +274,7 @@
 #endif
 
   PlanIter_t plan;
+
   {
     time::Timer lTimer;
 
@@ -287,6 +286,7 @@
     plan = codegen("main query", rootExpr, theCompilerCB, nextDynamicVarId);
   }
 
+  //theCompilerCB->getExprManager()->garbageCollect();
   return plan;
 }
 
@@ -294,7 +294,7 @@
 /*******************************************************************************
 
 ********************************************************************************/
-expr_t XQueryCompiler::normalize(parsenode_t aParsenode)
+expr* XQueryCompiler::normalize(parsenode_t aParsenode)
 {
 #if 0
   time::walltime startTime;
@@ -304,9 +304,13 @@
   time::get_current_walltime(startTime);
 #endif
 
-  expr_t lExpr = translate(*aParsenode, theCompilerCB);
+  expr* lExpr = translate(*aParsenode, theCompilerCB);
 
 #if 0
+  std::cout << "Num exprs after translation = "
+            << theCompilerCB->getExprManager()->numExprs()
+            << std::endl << std::endl;
+
   time::get_current_walltime(stopTime);
   elapsedTime = time::get_walltime_elapsed(startTime, stopTime);      
   std::cout << "Translation time = " << elapsedTime << std::endl;
@@ -325,11 +329,11 @@
 /*******************************************************************************
 
 ********************************************************************************/
-expr_t XQueryCompiler::optimize(expr_t lExpr)
+expr* XQueryCompiler::optimize(expr* lExpr)
 {
   // Build the call-graph among the udfs that are actually used in the query
   // program.
-  UDFGraph udfGraph(lExpr.getp());
+  UDFGraph udfGraph(lExpr);
 
   // By default all UDFs are marked as deterministic. Now, we find which udfs
   // are actually non-deterministic and mark them as such. This has to be done
@@ -354,7 +358,7 @@
   lExpr = rCtx.getRoot();
 
   if ( theCompilerCB->theConfig.optimize_cb != NULL )
-    theCompilerCB->theConfig.optimize_cb(lExpr.getp(), "main query");
+    theCompilerCB->theConfig.optimize_cb(lExpr, "main query");
 
   return lExpr;
 }
@@ -362,7 +366,7 @@
 
 /******************************************************************************
   This is a small helper class used when the user wants to compile a library
-  module. The ONLY place it is used (and should be used) is in the 
+  module. The ONLY place it is used (and should be used) is in the
   XQueryCompiler::createMainModule method below.
   QQQ When we have the ability to compile a library module indepedently, this
   rather hacky class can go away. At that time, we can also eliminate the
@@ -372,28 +376,32 @@
 class FakeLibraryModuleURLResolver : public internal::URLResolver
 {
 public:
-  FakeLibraryModuleURLResolver
-  (zstring const& aLibraryModuleNamespace, 
-    zstring const& aLibraryModuleFilename, std::istream& aStream)
-    : theLibraryModuleNamespace(aLibraryModuleNamespace),
-      theLibraryModuleFilename(aLibraryModuleFilename),
-      theStream(aStream)
+  FakeLibraryModuleURLResolver(
+      zstring const& aLibraryModuleNamespace,
+      zstring const& aLibraryModuleFilename,
+      std::istream& aStream)
+    :
+    theLibraryModuleNamespace(aLibraryModuleNamespace),
+    theLibraryModuleFilename(aLibraryModuleFilename),
+    theStream(aStream)
   {}
+
   virtual ~FakeLibraryModuleURLResolver()
   {}
 
-  virtual internal::Resource* resolveURL
-  (zstring const& aUrl, internal::EntityData const* aEntityData)
+  virtual internal::Resource* resolveURL(
+      const zstring& aUrl,
+      const internal::EntityData* aEntityData)
   {
-    if (aUrl != theLibraryModuleNamespace) {
+    if (aUrl != theLibraryModuleNamespace) 
+    {
       return NULL;
     }
     assert (theStream.good());
     // Pass a nullptr StreamReleaser; memory ownership of the istream remains
     // with the caller of this method.
     // QQQ We can remove this third argument when we can compile modules individually
-    return new internal::StreamResource(&theStream, nullptr,
-                                    theLibraryModuleFilename);
+    return new internal::StreamResource(&theStream, nullptr, theLibraryModuleFilename);
   }
 
 private:
@@ -414,28 +422,27 @@
   //get the namespace from the LibraryModule
   LibraryModule* mod_ast = dynamic_cast<LibraryModule *>(&*aLibraryModule);
   if (!mod_ast)
-    throw ZORBA_EXCEPTION(
-      zerr::ZAPI0002_XQUERY_COMPILATION_FAILED,
-      ERROR_PARAMS( ZED( BadLibraryModule ) )
-		);
+    throw ZORBA_EXCEPTION(zerr::ZAPI0002_XQUERY_COMPILATION_FAILED,
+    ERROR_PARAMS(ZED(BadLibraryModule)));
 
   const zstring& lib_namespace = mod_ast->get_decl()->get_target_namespace();
 
   URI lURI(lib_namespace);
   if(!lURI.is_absolute())
   {
-    throw XQUERY_EXCEPTION(
-      err::XQST0046, ERROR_PARAMS( lURI.toString(), ZED( MustBeAbsoluteURI ) ),
-      ERROR_LOC( mod_ast->get_decl()->get_location() )
-		);
+    throw XQUERY_EXCEPTION(err::XQST0046,
+    ERROR_PARAMS(lURI.toString(), ZED(MustBeAbsoluteURI)),
+      ERROR_LOC(mod_ast->get_decl()->get_location()));
   }
 
   // Set up the original query stream as the result of resolving the
   // library module's URI
   aXQuery.clear();
   aXQuery.seekg(0);
+
   FakeLibraryModuleURLResolver* aFakeResolver =
-    new FakeLibraryModuleURLResolver(lib_namespace.str(), aFileName, aXQuery);
+  new FakeLibraryModuleURLResolver(lib_namespace.str(), aFileName, aXQuery);
+
   theCompilerCB->theRootSctx->add_url_resolver(aFakeResolver);
 
   // create a dummy main module and parse it

=== modified file 'src/compiler/api/compiler_api.h'
--- src/compiler/api/compiler_api.h	2012-08-14 11:13:50 +0000
+++ src/compiler/api/compiler_api.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -26,7 +26,7 @@
 namespace zorba {
 
 
-class XQueryCompiler 
+class XQueryCompiler
 {
 public:
 
@@ -34,55 +34,44 @@
 
 public:
   XQueryCompiler(CompilerCB* aCompilerCB);
-    
+
   virtual ~XQueryCompiler();
 
-  void
-  parseOnly(
-      std::istream& aXQuery,
-      const zstring& aFileName);
+  void parseOnly(std::istream& aXQuery, const zstring& aFileName);
 
-  void
-  xqdoc(
+  void xqdoc(
       std::istream& aXQuery,
       const zstring& aFileName,
       store::Item_t& aResult,
       const store::Item_t& aDateTime);
 
-  parsenode_t
-  parse(
-      std::istream& aXQuery,
-      const zstring& aFileName);
+  parsenode_t parse(std::istream& aXQuery, const zstring& aFileName);
 
-  PlanIter_t
-  compile(
+  PlanIter_t compile(
       std::istream& aXQuery,
       const zstring& aFileName,
       ulong& nextDynamicVarId);
 
-  PlanIter_t
-  compile(
+  PlanIter_t compile(
       const parsenode_t& ast,
       bool applyPUL,
-      expr_t& rootExpr,
       ulong& nextDynamicVarId,
       audit::ScopedRecord& aAuditRecord);
 
 protected:
-  expr_t normalize(parsenode_t ast);
+  expr* normalize(parsenode_t ast);
 
-  expr_t optimize(expr_t lExpr);
+  expr* optimize(expr* expr);
 
 private:
-  parsenode_t 
-  createMainModule(
-      parsenode_t aLibraryModule,
-      std::istream& aXQuery,
-      const zstring& aFileName);
+  parsenode_t createMainModule(
+      parsenode_t libModule,
+      std::istream& xquery,
+      const zstring& fileName);
 };
 
 
-class XQueryCompilerSubsystem 
+class XQueryCompilerSubsystem
 {
   friend class GlobalEnvironment;
 

=== modified file 'src/compiler/api/compilercb.cpp'
--- src/compiler/api/compilercb.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/api/compilercb.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -30,7 +30,7 @@
 #include "zorbaserialization/serialize_zorba_types.h"
 
 
-namespace zorba 
+namespace zorba
 {
 
 SERIALIZABLE_CLASS_VERSIONS(CompilerCB)
@@ -80,7 +80,7 @@
 /*******************************************************************************
 
 ********************************************************************************/
-CompilerCB::config::config(::zorba::serialization::Archiver& ar) 
+CompilerCB::config::config(::zorba::serialization::Archiver& ar)
   :
   parse_cb(NULL),
   translate_cb(NULL),
@@ -121,6 +121,8 @@
   theTimeout(timeout),
   theTempIndexCounter(0)
 {
+  theEM = new ExprManager(this);
+
   if (timeout >= 0)
     theHaveTimeout = true;
 }
@@ -128,7 +130,7 @@
 
 /*******************************************************************************
   Used by the eval iterator to create a new ccb as a copy of the ccb of the
-  enclosing query. 
+  enclosing query.
 *******************************************************************************/
 CompilerCB::CompilerCB(const CompilerCB& cb)
   :
@@ -148,6 +150,7 @@
   theTempIndexCounter(0),
   theConfig(cb.theConfig)
 {
+  theEM = new ExprManager(this);
 }
 
 
@@ -165,14 +168,17 @@
   theHasEval(false),
   theIsEval(false)
 {
+  theEM = new ExprManager(this);
 }
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-CompilerCB::~CompilerCB() 
+CompilerCB::~CompilerCB()
 {
+  theSctxMap.clear();
+  delete theEM;
 }
 
 
@@ -181,6 +187,8 @@
 ********************************************************************************/
 void CompilerCB::serialize(::zorba::serialization::Archiver& ar)
 {
+  ar.set_ccb(this);
+
   ar & theHasEval;
   ar & theIsEval;
   ar & theIsLoadProlog;
@@ -190,7 +198,7 @@
 #ifdef ZORBA_WITH_DEBUGGER
   ar & theDebuggerCommons;
 #endif
-  if (!ar.is_serializing_out()) 
+  if (!ar.is_serializing_out())
   {
     //don't serialize this
     theXQueryDiagnostics = NULL;

=== modified file 'src/compiler/api/compilercb.h'
--- src/compiler/api/compilercb.h	2012-08-14 11:13:50 +0000
+++ src/compiler/api/compilercb.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -32,6 +32,9 @@
 
 #include "zorbaserialization/class_serializer.h"
 
+#include "compiler/expression/mem_manager.h"
+#include "compiler/expression/expr_manager.h"
+
 namespace zorba {
 
 #ifdef ZORBA_WITH_DEBUGGER
@@ -57,7 +60,7 @@
   A query-level (or eval-level) map that stores the sctx objs that need to be
   kept around for the whole duration of a query (including runtime). In non-
   DEBUGGER mode, the map stores only for root sctx of each module. In DEBUGGER
-  mode, it stores all the sctxs created by each module. Each sctx stored in 
+  mode, it stores all the sctxs created by each module. Each sctx stored in
   this map has an associated numeric id, and theSctxMap actually maps these
   numeric ids to their associated sctx objs. The map is modified by the methods
   TranslatorImpl::end_visit(ModuleImport) and TranslatorImpl::push_scope().
@@ -89,7 +92,7 @@
 
   theIsUpdating :
   ---------------
-  Set to true if the root expr of the query or eval expr is an updating expr. 
+  Set to true if the root expr of the query or eval expr is an updating expr.
 
   theTimeout :
   ------------
@@ -124,13 +127,13 @@
 public:
   struct config : public zorba::serialization::SerializeBaseClass
   {
-    typedef enum 
+    typedef enum
     {
       O0,
       O1,
       O2
     } opt_level_t;
-    
+
     typedef void (* expr_callback) (const expr *, const std::string& name);
 
     typedef void (* ast_callback) (const parsenode *, const std::string& name);
@@ -157,7 +160,9 @@
 
   typedef std::map<csize, static_context_t> SctxMap;
 
-public:  
+public:
+  ExprManager             * theEM;
+
   XQueryDiagnostics       * theXQueryDiagnostics;
 
   SctxMap                   theSctxMap;
@@ -211,6 +216,11 @@
   bool isSequential() const { return theIsSequential;}
 
   static_context* getStaticContext(int id);
+
+  ExprManager* getExprManager() const { return theEM; }
+
+  MemoryManager& getMemoryManager() const { return theEM->getMemory(); }
+
 };
 
 

=== modified file 'src/compiler/codegen/plan_visitor.cpp'
--- src/compiler/codegen/plan_visitor.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/codegen/plan_visitor.cpp	2012-08-14 12:29:44 +0000
@@ -206,7 +206,7 @@
   A FlworClauseVarMap is created for each flwor clause that defines variables.
   If M is such a clause, then for each variable Vi defined by M, theVarExprs[i]
   and theVarRebinds[i] contain an entry for Vi. theVarExprs[i] contains the
-  var_expr representing the Vi definition. 
+  var_expr representing the Vi definition.
 ********************************************************************************/
 class FlworClauseVarMap : public SimpleRCObject
 {
@@ -250,7 +250,7 @@
 
 #ifndef ZORBA_NO_FULL_TEXT
 
-class plan_ftnode_visitor : public ftnode_visitor 
+class plan_ftnode_visitor : public ftnode_visitor
 {
 public:
   typedef std::vector<PlanIter_t> PlanIter_list_t;
@@ -357,7 +357,7 @@
     hash64map<std::vector<LetVarIter_t>*>* arg_var_map = NULL)
   :
   theDepth(0),
-  theNextDynamicVarId(nextDynamicVarId),  
+  theNextDynamicVarId(nextDynamicVarId),
   arg_var_iter_map(arg_var_map),
   theCCB(ccb)
 {
@@ -661,14 +661,14 @@
 
   PlanIter_t exprIter = pop_itstack();
 
-  CtxVarAssignIterator* iter = 
+  CtxVarAssignIterator* iter =
   new CtxVarAssignIterator(sctx,
                            qloc,
                            varExpr->get_unique_id(),
                            varExpr->get_name(),
                            (varExpr->get_kind() == var_expr::local_var),
                            exprIter);
-  
+
   if (exprType->get_quantifier() == TypeConstants::QUANT_ONE)
     iter->setSingleItem();
 
@@ -763,7 +763,7 @@
 
     // Look for the inner-most clause C that knows about this variable. C is
     // either the clause D_C that defines the var, or the inner-most orderby
-    // or materialize clause the comes after D_C and rebinds the var to its 
+    // or materialize clause the comes after D_C and rebinds the var to its
     // output.
     long i = stackSize - 1;
     while(true)
@@ -786,8 +786,8 @@
 
     if (clauseVarMap->theIsGeneral || flworExpr->is_sequential())
     {
-      // For each orderby or materialize clause O after C, bind the var iter 
-      // created by the previous clause to the input of O, and then create a new 
+      // For each orderby or materialize clause O after C, bind the var iter
+      // created by the previous clause to the input of O, and then create a new
       // var iter and put it to the output of O.
       for (++i; i < stackSize; ++i)
       {
@@ -931,18 +931,18 @@
           v.get_clause(numClauses-1)->get_kind() != flwor_clause::materialize_clause &&
           (v.get_order_clause() != NULL || v.get_group_clause() == NULL))
       {
-        materialize_clause* mat = 
+        materialize_clause* mat =
         new materialize_clause(v.get_sctx(), v.get_return_expr()->get_loc());
 
         v.add_clause(mat);
         ++numClauses;
       }
     } // !isGeneral
-    
+
     if (isGeneral)
     {
       std::vector<OrderModifier> modifiers;
-      std::vector<expr_t> orderingExprs;
+      std::vector<expr*> orderingExprs;
 
       csize numForClauses = 0;
       csize i = 0;
@@ -968,7 +968,7 @@
 
           if (c->get_expr()->is_sequential())
           {
-            if (k == flwor_clause::for_clause || 
+            if (k == flwor_clause::for_clause ||
                 k == flwor_clause::window_clause ||
                 numForClauses > 0)
             {
@@ -980,8 +980,8 @@
                   v.get_clause(i-1)->get_kind() != flwor_clause::order_clause &&
                   v.get_clause(i-1)->get_kind() != flwor_clause::group_clause)
               {
-                orderby_clause* mat = 
-                new orderby_clause(v.get_sctx(), 
+                orderby_clause* mat =
+                new orderby_clause(v.get_sctx(),
                                    c->get_loc(),
                                    true,
                                    modifiers,
@@ -996,8 +996,8 @@
                   (i < numClauses - 1 &&
                    v.get_clause(i+1)->get_kind() != flwor_clause::group_clause))
               {
-                orderby_clause* mat = 
-                new orderby_clause(v.get_sctx(), 
+                orderby_clause* mat =
+                new orderby_clause(v.get_sctx(),
                                    c->get_loc(),
                                    true,
                                    modifiers,
@@ -1031,8 +1031,8 @@
           lastClause->get_kind() != flwor_clause::order_clause &&
           lastClause->get_kind() != flwor_clause::group_clause)
       {
-        orderby_clause* mat = 
-        new orderby_clause(v.get_sctx(), 
+        orderby_clause* mat =
+        new orderby_clause(v.get_sctx(),
                            v.get_return_expr()->get_loc(),
                            true,
                            modifiers,
@@ -1238,14 +1238,14 @@
     for (unsigned i = 0; i < grouping_vars.size(); ++i)
     {
       VarRebind_t varRebind = new VarRebind;
-      clauseVarMap->theVarExprs.push_back(grouping_vars[i].second.getp());
+      clauseVarMap->theVarExprs.push_back(grouping_vars[i].second);
       clauseVarMap->theVarRebinds.push_back(varRebind);
     }
 
     for (unsigned i = 0; i < nongrouping_vars.size(); ++i)
     {
       VarRebind_t varRebind = new VarRebind;
-      clauseVarMap->theVarExprs.push_back(nongrouping_vars[i].second.getp());
+      clauseVarMap->theVarExprs.push_back(nongrouping_vars[i].second);
       clauseVarMap->theVarRebinds.push_back(varRebind);
     }
 
@@ -1291,56 +1291,56 @@
   if (inVars.posvar != NULL)
   {
     VarRebind_t varRebind = new VarRebind;
-    clauseVarMap->theVarExprs.push_back(inVars.posvar.getp());
+    clauseVarMap->theVarExprs.push_back(inVars.posvar);
     clauseVarMap->theVarRebinds.push_back(varRebind);
   }
 
   if (inVars.curr != NULL)
   {
     VarRebind_t varRebind = new VarRebind;
-    clauseVarMap->theVarExprs.push_back(inVars.curr.getp());
+    clauseVarMap->theVarExprs.push_back(inVars.curr);
     clauseVarMap->theVarRebinds.push_back(varRebind);
   }
 
   if (inVars.prev != NULL)
   {
     VarRebind_t varRebind = new VarRebind;
-    clauseVarMap->theVarExprs.push_back(inVars.prev.getp());
+    clauseVarMap->theVarExprs.push_back(inVars.prev);
     clauseVarMap->theVarRebinds.push_back(varRebind);
   }
 
   if (inVars.next != NULL)
   {
     VarRebind_t varRebind = new VarRebind;
-    clauseVarMap->theVarExprs.push_back(inVars.next.getp());
+    clauseVarMap->theVarExprs.push_back(inVars.next);
     clauseVarMap->theVarRebinds.push_back(varRebind);
   }
 
   if (outVars.posvar != NULL)
   {
     VarRebind_t varRebind = new VarRebind;
-    clauseVarMap->theVarExprs.push_back(outVars.posvar.getp());
+    clauseVarMap->theVarExprs.push_back(outVars.posvar);
     clauseVarMap->theVarRebinds.push_back(varRebind);
   }
 
   if (outVars.curr != NULL)
   {
     VarRebind_t varRebind = new VarRebind;
-    clauseVarMap->theVarExprs.push_back(outVars.curr.getp());
+    clauseVarMap->theVarExprs.push_back(outVars.curr);
     clauseVarMap->theVarRebinds.push_back(varRebind);
   }
 
   if (outVars.prev != NULL)
   {
     VarRebind_t varRebind = new VarRebind;
-    clauseVarMap->theVarExprs.push_back(outVars.prev.getp());
+    clauseVarMap->theVarExprs.push_back(outVars.prev);
     clauseVarMap->theVarRebinds.push_back(varRebind);
   }
 
   if (outVars.next != NULL)
   {
     VarRebind_t varRebind = new VarRebind;
-    clauseVarMap->theVarExprs.push_back(outVars.next.getp());
+    clauseVarMap->theVarExprs.push_back(outVars.next);
     clauseVarMap->theVarRebinds.push_back(varRebind);
   }
 }
@@ -1416,7 +1416,7 @@
 
   if (colType != NULL &&
       TypeOps::is_subtype(tm, *colType, *rtm.ANY_ATOMIC_TYPE_STAR, loc) &&
-      !TypeOps::is_equal(tm, 
+      !TypeOps::is_equal(tm,
                          *TypeOps::prime_type(tm, *colType),
                          *rtm.ANY_ATOMIC_TYPE_ONE,
                          loc))
@@ -1580,7 +1580,7 @@
   //
   else if (c.get_kind() == flwor_clause::count_clause)
   {
-    var_expr_t var = static_cast<const count_clause *>(&c)->get_var();
+    var_expr* var = static_cast<const count_clause *>(&c)->get_var();
 
     ZORBA_ASSERT(clauseVarMap->theVarRebinds.size() == 1);
 
@@ -1736,15 +1736,15 @@
 
       for (ulong i = 0; i < numVars; ++i)
       {
-        VarRebind* varRebind = clauseVarMap->theVarRebinds[i].getp();
-        
+        VarRebind* varRebind = clauseVarMap->theVarRebinds[i];
+
         ForVarIterator* forIter = dynamic_cast<ForVarIterator*>
                                   (varRebind->theInputVar.getp());
 
         if (forIter != NULL)
         {
           inputForVars[numForVars] = forIter;
-          
+
           outputForVarsRefs[numForVars] = varRebind->theOutputVarRefs;
           ++numForVars;
         }
@@ -1755,17 +1755,17 @@
           ZORBA_ASSERT(letIter != NULL);
 
           inputLetVars[numLetVars] = letIter;
-          
+
           outputLetVarsRefs[numLetVars] = varRebind->theOutputVarRefs;
           ++numLetVars;
         }
       }
-      
+
       inputForVars.resize(numForVars);
       outputForVarsRefs.resize(numForVars);
       inputLetVars.resize(numLetVars);
       outputLetVarsRefs.resize(numLetVars);
-      
+
       materializeClause.reset(new flwor::MaterializeClause(c.get_loc(),
                                                            inputForVars,
                                                            inputLetVars,
@@ -1841,14 +1841,14 @@
 
       PlanIter_t domainIter = pop_itstack();
 
-      std::vector<PlanIter_t>& varRefs = 
+      std::vector<PlanIter_t>& varRefs =
       clauseVarMap->theVarRebinds[0]->theOutputVarRefs;
 
       if (fc->get_pos_var())
       {
         ZORBA_ASSERT(clauseVarMap->theVarRebinds.size() == 2);
 
-        std::vector<PlanIter_t>& posVarRefs = 
+        std::vector<PlanIter_t>& posVarRefs =
         clauseVarMap->theVarRebinds[1]->theOutputVarRefs;
 
         forletClauses.push_back(flwor::ForLetClause(var->get_name(),
@@ -1881,7 +1881,7 @@
 
       PlanIter_t domainIter = pop_itstack();
 
-      std::vector<PlanIter_t>& varRefs = 
+      std::vector<PlanIter_t>& varRefs =
       clauseVarMap->theVarRebinds[0]->theOutputVarRefs;
 
       forletClauses.push_back(flwor::ForLetClause(var->get_name(),
@@ -1988,7 +1988,7 @@
   {
     catch_clause* cc = &*v[i];
     catch_clause::var_map_t& vars = cc->get_vars();
-    
+
     for (catch_clause::var_map_t::const_iterator lIter = vars.begin();
          lIter != vars.end();
          ++lIter)
@@ -2139,7 +2139,7 @@
   std::vector<int> isGlobalVar(numVars);
 
   //create the eval iterator children
-  for (csize i = 0; i < numVars; i++) 
+  for (csize i = 0; i < numVars; i++)
   {
     varNames[i] = v.get_var(i)->get_name();
     varTypes[i] = v.get_var(i)->get_type();
@@ -2169,7 +2169,7 @@
 
   // child 1
   store::NsBindings localBindings;
-  if (v.getNSCtx()) 
+  if (v.getNSCtx())
   {
     v.getNSCtx()->getAllBindings(localBindings);
   }
@@ -2189,7 +2189,7 @@
   lDebugIterator->setVariables(varNames, varTypes);
 
   // link all debugger iterators in the tree
-  if (!theDebuggerStack.empty()) 
+  if (!theDebuggerStack.empty())
   {
     theDebuggerStack.top()->addChild(lDebugIterator.get());
     lDebugIterator->setParent(theDebuggerStack.top());
@@ -2214,7 +2214,7 @@
   PlanIter_t iterThen = pop_itstack();
   PlanIter_t iterCond = pop_itstack();
 
-  PlanIter_t iterIfThenElse = 
+  PlanIter_t iterIfThenElse =
   new IfThenElseIterator(sctx, qloc, iterCond, iterThen, iterElse);
 
   push_itstack(&*iterIfThenElse);
@@ -2227,7 +2227,7 @@
   return true;
 }
 
-void end_visit(exit_expr& v) 
+void end_visit(exit_expr& v)
 {
   CODEGEN_TRACE_OUT("");
   push_itstack(new ExitIterator(sctx, qloc, pop_itstack()));
@@ -2240,14 +2240,14 @@
   return true;
 }
 
-void end_visit(exit_catcher_expr& v) 
+void end_visit(exit_catcher_expr& v)
 {
   CODEGEN_TRACE_OUT("");
   push_itstack(new ExitCatcherIterator(sctx, qloc, pop_itstack()));
 }
 
 
-bool begin_visit(flowctl_expr& v) 
+bool begin_visit(flowctl_expr& v)
 {
   CODEGEN_TRACE_IN("");
   return true;
@@ -2257,7 +2257,7 @@
 {
   CODEGEN_TRACE_OUT("");
   enum FlowCtlException::action a;
-  switch (v.get_action()) 
+  switch (v.get_action())
   {
   case flowctl_expr::BREAK:
     a = FlowCtlException::BREAK;
@@ -2273,13 +2273,13 @@
 }
 
 
-bool begin_visit(while_expr& v) 
+bool begin_visit(while_expr& v)
 {
   CODEGEN_TRACE_IN("");
   return true;
 }
 
-void end_visit(while_expr& v) 
+void end_visit(while_expr& v)
 {
   CODEGEN_TRACE_OUT("");
   push_itstack(new LoopIterator (sctx, qloc, pop_itstack()));
@@ -2314,7 +2314,7 @@
 
   argv.resize(v.num_args());
   generate(argv.rbegin(), argv.rend(), ztd::stack_to_generator(itstack));
-  
+
   const QueryLoc& loc = qloc;
 
   if (v.is_sequential())
@@ -2397,7 +2397,7 @@
   CODEGEN_TRACE_OUT("");
   PlanIter_t arg;
   arg = pop_itstack();
-  push_itstack(new TreatIterator(sctx, qloc, arg, 
+  push_itstack(new TreatIterator(sctx, qloc, arg,
                                  v.get_target_type(),
                                  v.get_check_prime(),
                                  v.get_err(),
@@ -2557,7 +2557,7 @@
   }
   //ZORBA_ASSERT(pathIte != NULL);
 
-  rchandle<match_expr> testExpr = v.getTest();
+  match_expr* testExpr = v.getTest();
 
   NodePredicate* prd = new NodePredicate();
 
@@ -2760,7 +2760,7 @@
 }
 
 
-void end_visit(axis_step_expr& v) 
+void end_visit(axis_step_expr& v)
 {
   CODEGEN_TRACE_OUT("");
 }
@@ -2794,7 +2794,7 @@
 
     axisItep->setWildKind(wildKind);
 
-    if (wildKind == match_no_wild) 
+    if (wildKind == match_no_wild)
     {
       axisItep->setQName(v.getQName());
     }
@@ -2816,7 +2816,7 @@
     axisItep->setNodeKind(v.getNodeKind());
     axisItep->setQName(v.getQName());
     store::Item* typeName = v.getTypeName();
-    if (typeName != NULL) 
+    if (typeName != NULL)
     {
       axisItep->setType(sctx->get_typemanager()->
                         create_named_type(typeName,
@@ -2866,7 +2866,7 @@
   PlanIter_t lContent = pop_itstack();
   PlanIter_t lDocIter = new DocumentIterator(sctx,
                                              qloc,
-                                             lContent, 
+                                             lContent,
                                              !theCopyNodesStack.empty());
   push_itstack(lDocIter);
 
@@ -2915,7 +2915,7 @@
   ZORBA_ASSERT(e == &v);
 
   // Handling of the special case where the QName expression of a direct element
-  // constructor has in itself a direct constructor. In that case the QName 
+  // constructor has in itself a direct constructor. In that case the QName
   // expression should have isRoot set to true.
   elem_expr* top_elem_expr = NULL;
   if (!theConstructorsStack.empty())
@@ -3153,10 +3153,10 @@
 
   bool copyInput = true;
 
-  push_itstack(new JSONObjectIterator(sctx, 
-                                      qloc, 
-                                      inputs, 
-                                      copyInput, 
+  push_itstack(new JSONObjectIterator(sctx,
+                                      qloc,
+                                      inputs,
+                                      copyInput,
                                       v.is_accumulating()));
 }
 
@@ -3410,8 +3410,8 @@
   std::vector<rchandle<copy_clause> >::const_iterator lEnd  = v.end();
   for (; lIter != lEnd; ++lIter)
   {
-    rchandle<var_expr> var = (*lIter)->getVar();
-    expr_t sourceExpr = (*lIter)->getExpr();
+    var_expr* var = (*lIter)->getVar();
+    expr* sourceExpr = (*lIter)->getExpr();
     xqtref_t sourceType = sourceExpr->get_return_type();
 
     if (TypeOps::is_subtype(tm, *sourceType, *GENV_TYPESYSTEM.ANY_SIMPLE_TYPE, qloc))
@@ -3512,7 +3512,7 @@
       PlanIter_t top = pop_itstack();
       XMLIterPrinter vp(std::cout);
       print_iter_plan(vp, top);
-      std::cout << "=============================" << std::endl;    
+      std::cout << "=============================" << std::endl;
     }
     ZORBA_ASSERT(0);
   }
@@ -3547,7 +3547,7 @@
 void V::end_visit( ftrange &r ) {
   PlanIter_t it2 = plan_visitor_->pop_itstack();
   PlanIter_t it1;
-  if ( r.get_expr2() ) {
+  if ( *(r.get_expr2()) ) {
     it1 = plan_visitor_->pop_itstack();
   } else {
     it1 = it2;

=== modified file 'src/compiler/codegen/plan_visitor.h'
--- src/compiler/codegen/plan_visitor.h	2012-08-14 11:13:50 +0000
+++ src/compiler/codegen/plan_visitor.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,7 +21,7 @@
 
 #include "common/shared_types.h"
 
-namespace zorba 
+namespace zorba
 {
 
 class expr;

=== modified file 'src/compiler/expression/CMakeLists.txt'
--- src/compiler/expression/CMakeLists.txt	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/CMakeLists.txt	2012-08-14 12:29:44 +0000
@@ -26,7 +26,9 @@
     fo_expr.cpp
     script_exprs.cpp
     update_exprs.cpp
-    function_item_expr.cpp)
+    function_item_expr.cpp
+    mem_manager.cpp
+    expr_manager.cpp)
 
 IF (NOT ZORBA_NO_FULL_TEXT)
   LIST(APPEND EXPRESSION_SRCS

=== modified file 'src/compiler/expression/expr.cpp'
--- src/compiler/expression/expr.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/expr.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -43,12 +43,15 @@
 #include "compiler/expression/expr_utils.h"
 #include "compiler/expression/expr_visitor.h"
 #include "compiler/parser/parse_constants.h"
+#include "compiler/expression/expr_manager.h"
+
 #include "compiler/api/compilercb.h"
 
 #include "store/api/store.h"
 #include "store/api/item_factory.h"
 
-namespace zorba 
+
+namespace zorba
 {
 
 
@@ -88,23 +91,24 @@
   [68] IfExpr ::= "if" "(" Expr ")" "then" ExprSingle "else" ExprSingle
 ********************************************************************************/
 if_expr::if_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    expr_t condExpr,
-    expr_t thenExpr,
-    expr_t elseExpr)
+    expr* condExpr,
+    expr* thenExpr,
+    expr* elseExpr)
   :
-  expr(sctx, loc, if_expr_kind),
+  expr(ccb, sctx, loc, if_expr_kind),
   theThenExpr(thenExpr),
   theElseExpr(elseExpr)
 {
   if (sctx != NULL &&
-      !TypeOps::is_equal(sctx->get_typemanager(), 
+      !TypeOps::is_equal(sctx->get_typemanager(),
                          *condExpr->get_return_type(),
                          *GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE,
                          loc))
   {
-    fo_expr* boolExpr = new fo_expr(sctx,
+    fo_expr* boolExpr = theCCB->theEM->create_fo_expr(sctx,
                                     loc,
                                     GET_BUILTIN_FUNCTION(FN_BOOLEAN_1),
                                     condExpr);
@@ -153,7 +157,7 @@
   {
     theScriptingKind = VACUOUS_EXPR;
   }
-  else 
+  else
   {
     theScriptingKind = SIMPLE_EXPR;
   }
@@ -162,9 +166,9 @@
 }
 
 
-expr_t if_expr::clone(substitution_t& subst) const 
+expr* if_expr::clone(substitution_t& subst) const
 {
-  return new if_expr(theSctx,
+  return theCCB->theEM->create_if_expr(theSctx,
                      get_loc(),
                      get_cond_expr()->clone(subst),
                      get_then_expr()->clone(subst),
@@ -176,12 +180,13 @@
 
 ********************************************************************************/
 order_expr::order_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     order_type_t type,
-    expr_t inExpr)
+    expr* inExpr)
   :
-  expr(sctx, loc, order_expr_kind),
+  expr(ccb, sctx, loc, order_expr_kind),
   theType(type),
   theExpr(inExpr)
 {
@@ -198,9 +203,9 @@
 }
 
 
-expr_t order_expr::clone(substitution_t& subst) const
+expr* order_expr::clone(substitution_t& subst) const
 {
-  return new order_expr(theSctx, get_loc(), get_type(), get_expr()->clone(subst));
+  return theCCB->theEM->create_order_expr(theSctx, get_loc(), get_type(), get_expr()->clone(subst));
 }
 
 
@@ -208,14 +213,15 @@
 
 ********************************************************************************/
 validate_expr::validate_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     enum ParseConstants::validation_mode_t mode,
     const store::Item_t& typeName,
-    expr_t inExpr,
+    expr* inExpr,
     rchandle<TypeManager> typemgr)
   :
-  expr(sctx, loc, validate_expr_kind),
+  expr(ccb, sctx, loc, validate_expr_kind),
   theMode(mode),
   theTypeName(typeName),
   theTypeMgr(typemgr),
@@ -236,9 +242,9 @@
 }
 
 
-expr_t validate_expr::clone(substitution_t& subst) const
+expr* validate_expr::clone(substitution_t& subst) const
 {
-  return new validate_expr(theSctx,
+  return theCCB->theEM->create_validate_expr(theSctx,
                            get_loc(),
                            get_valmode(),
                            const_cast<store::Item*>(get_type_name()),
@@ -251,12 +257,13 @@
   Base for expression classes that require a namespace context
 ********************************************************************************/
 namespace_context_base_expr::namespace_context_base_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     expr_kind_t kind,
     const namespace_context* aNSCtx)
   :
-  expr(sctx, loc, kind),
+  expr(ccb, sctx, loc, kind),
   theNSCtx(const_cast<namespace_context*>(aNSCtx))
 {
 }
@@ -264,7 +271,7 @@
 
 const namespace_context* namespace_context_base_expr::getNSCtx() const
 {
-  return theNSCtx.getp(); 
+  return theNSCtx.getp();
 }
 
 
@@ -273,13 +280,14 @@
   Base for cast, treat, promote, castable, instanceof
 ********************************************************************************/
 cast_or_castable_base_expr::cast_or_castable_base_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     expr_kind_t kind,
-    const expr_t& input,
+    expr* input,
     const xqtref_t& type)
   :
-  expr(sctx, loc, kind),
+  expr(ccb, sctx, loc, kind),
   theInputExpr(input),
   theTargetType(type)
 {
@@ -290,13 +298,13 @@
 }
 
 
-xqtref_t cast_or_castable_base_expr::get_target_type() const 
+xqtref_t cast_or_castable_base_expr::get_target_type() const
 {
   return theTargetType;
 }
 
 
-void cast_or_castable_base_expr::set_target_type(xqtref_t target) 
+void cast_or_castable_base_expr::set_target_type(xqtref_t target)
 {
   theTargetType = target;
 }
@@ -317,13 +325,14 @@
   Base for cast, treat, promote
 ********************************************************************************/
 cast_base_expr::cast_base_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     expr_kind_t kind,
-    const expr_t& input,
+    expr* input,
     const xqtref_t& type)
-  : 
-  cast_or_castable_base_expr(sctx, loc, kind, input, type)
+  :
+  cast_or_castable_base_expr(ccb, sctx, loc, kind, input, type)
 {
   setNonDiscardable(ANNOTATION_TRUE_FIXED);
 }
@@ -335,46 +344,48 @@
   SingleType ::= AtomicType "?"?
 ********************************************************************************/
 cast_expr::cast_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& inputExpr,
+    expr* inputExpr,
     const xqtref_t& type)
   :
-  cast_base_expr(sctx, loc, cast_expr_kind, inputExpr, type)
+  cast_base_expr(ccb, sctx, loc, cast_expr_kind, inputExpr, type)
 {
   assert(type->get_quantifier() == TypeConstants::QUANT_ONE ||
          type->get_quantifier() == TypeConstants::QUANT_QUESTION);
 }
 
 
-bool cast_expr::is_optional() const 
+bool cast_expr::is_optional() const
 {
-  return theTargetType->get_quantifier() == TypeConstants::QUANT_QUESTION; 
+  return theTargetType->get_quantifier() == TypeConstants::QUANT_QUESTION;
 }
 
 
-expr_t cast_expr::clone(substitution_t& subst) const
+expr* cast_expr::clone(substitution_t& subst) const
 {
-  return new cast_expr(theSctx,
+  return theCCB->theEM->create_cast_expr(theSctx,
                        get_loc(),
-                       get_input()->clone(subst), 
+                       get_input()->clone(subst),
                        get_target_type());
 }
 
 
 /***************************************************************************//**
-	TreatExpr ::= CastableExpr ( "treat" "as" SequenceType )?
+  TreatExpr ::= CastableExpr ( "treat" "as" SequenceType )?
 ********************************************************************************/
 treat_expr::treat_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& inputExpr,
+    expr* inputExpr,
     const xqtref_t& type,
     TreatIterator::ErrorKind err,
     bool check_prime,
     store::Item* qname)
   :
-  cast_base_expr(sctx, loc, treat_expr_kind, inputExpr, type),
+  cast_base_expr(ccb, sctx, loc, treat_expr_kind, inputExpr, type),
   theErrorKind(err),
   theCheckPrime(check_prime),
   theQName(qname)
@@ -382,11 +393,11 @@
 }
 
 
-expr_t treat_expr::clone(substitution_t& subst) const
+expr* treat_expr::clone(substitution_t& subst) const
 {
-  return new treat_expr(theSctx,
+  return theCCB->theEM->create_treat_expr(theSctx,
                         get_loc(),
-                        get_input()->clone(subst), 
+                        get_input()->clone(subst),
                         get_target_type(),
                         get_err(),
                         get_check_prime(),
@@ -398,23 +409,24 @@
 
 ********************************************************************************/
 promote_expr::promote_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& input,
+    expr* input,
     const xqtref_t& type,
     PromoteIterator::ErrorKind err,
     store::Item* qname)
   :
-  cast_base_expr(sctx, loc, promote_expr_kind, input, type),
+  cast_base_expr(ccb, sctx, loc, promote_expr_kind, input, type),
   theErrorKind(err),
   theQName(qname)
 {
 }
 
 
-expr_t promote_expr::clone(substitution_t& subst) const
+expr* promote_expr::clone(substitution_t& subst) const
 {
-  return new promote_expr(theSctx, 
+  return theCCB->theEM->create_promote_expr(theSctx,
                           get_loc(),
                           get_input()->clone(subst),
                           get_target_type(),
@@ -427,13 +439,14 @@
   Base for castable, instanceof
 ********************************************************************************/
 castable_base_expr::castable_base_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     expr_kind_t kind,
-    const expr_t& input,
+    expr* input,
     const xqtref_t& type)
   :
-  cast_or_castable_base_expr(sctx, loc, kind, input, type)
+  cast_or_castable_base_expr(ccb, sctx, loc, kind, input, type)
 {
 }
 
@@ -444,25 +457,26 @@
   SingleType ::= AtomicType "?"?
 ********************************************************************************/
 castable_expr::castable_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& inputExpr,
+    expr* inputExpr,
     const xqtref_t& type)
   :
-  castable_base_expr (sctx, loc, castable_expr_kind, inputExpr, type)
-{
-}
-
-
-bool castable_expr::is_optional() const 
-{
-  return theTargetType->get_quantifier() == TypeConstants::QUANT_QUESTION; 
-}
-
-
-expr_t castable_expr::clone(substitution_t& subst) const
-{
-  return new castable_expr(theSctx, 
+  castable_base_expr (ccb, sctx, loc, castable_expr_kind, inputExpr, type)
+{
+}
+
+
+bool castable_expr::is_optional() const
+{
+  return theTargetType->get_quantifier() == TypeConstants::QUANT_QUESTION;
+}
+
+
+expr* castable_expr::clone(substitution_t& subst) const
+{
+  return theCCB->theEM->create_castable_expr(theSctx,
                            get_loc(),
                            get_input()->clone(subst),
                            get_target_type());
@@ -470,24 +484,25 @@
 
 
 /***************************************************************************//**
-	InstanceofExpr ::= TreatExpr ( "instance" "of" SequenceType )?
+  InstanceofExpr ::= TreatExpr ( "instance" "of" SequenceType )?
 ********************************************************************************/
 instanceof_expr::instanceof_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& inputExpr,
+    expr* inputExpr,
     const xqtref_t& type,
     bool checkPrimeOnly)
   :
-  castable_base_expr(sctx, loc, instanceof_expr_kind, inputExpr, type),
+  castable_base_expr(ccb, sctx, loc, instanceof_expr_kind, inputExpr, type),
   theCheckPrimeOnly(checkPrimeOnly)
 {
 }
 
 
-expr_t instanceof_expr::clone(substitution_t& subst) const
+expr* instanceof_expr::clone(substitution_t& subst) const
 {
-  return new instanceof_expr(theSctx,
+  return theCCB->theEM->create_instanceof_expr(theSctx,
                              get_loc(),
                              get_input()->clone(subst),
                              get_target_type());
@@ -498,13 +513,14 @@
 
 ********************************************************************************/
 name_cast_expr::name_cast_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    expr_t inputExpr,
+    expr* inputExpr,
     const namespace_context* aNSCtx,
     bool isAttrName)
   :
-  namespace_context_base_expr(sctx, loc, name_cast_expr_kind, aNSCtx),
+  namespace_context_base_expr(ccb, sctx, loc, name_cast_expr_kind, aNSCtx),
   theInputExpr(inputExpr),
   theIsAttrName(isAttrName)
 {
@@ -523,9 +539,9 @@
 }
 
 
-expr_t name_cast_expr::clone(substitution_t& subst) const
+expr* name_cast_expr::clone(substitution_t& subst) const
 {
-  return new name_cast_expr(theSctx,
+  return theCCB->theEM->create_name_cast_expr(theSctx,
                             get_loc(),
                             get_input()->clone(subst),
                             getNSCtx(),
@@ -537,12 +553,13 @@
   CompDocConstructor ::= "document" "{" Expr "}"
 ********************************************************************************/
 doc_expr::doc_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     expr* aContent,
     bool copyNodes)
   :
-  expr(sctx, loc, doc_expr_kind),
+  expr(ccb, sctx, loc, doc_expr_kind),
   theContent(aContent),
   theCopyInputNodes(copyNodes)
 {
@@ -561,9 +578,9 @@
 }
 
 
-expr_t doc_expr::clone(substitution_t& subst) const
+expr* doc_expr::clone(substitution_t& subst) const
 {
-  doc_expr* clone = new doc_expr(theSctx,
+  doc_expr* clone = theCCB->theEM->create_doc_expr(theSctx,
                                  get_loc(),
                                  CLONE(getContent(), subst),
                                  theCopyInputNodes);
@@ -575,6 +592,7 @@
 
 ********************************************************************************/
 elem_expr::elem_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& aLoc,
     expr* aQNameExpr,
@@ -583,7 +601,7 @@
     const namespace_context* aNSCtx,
     bool copyNodes)
   :
-  namespace_context_base_expr(sctx, aLoc, elem_expr_kind, aNSCtx),
+  namespace_context_base_expr(ccb, sctx, aLoc, elem_expr_kind, aNSCtx),
   theQNameExpr(aQNameExpr),
   theAttrs(attrs),
   theContent(content),
@@ -596,6 +614,7 @@
 
 
 elem_expr::elem_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& aLoc,
     expr* aQNameExpr,
@@ -603,7 +622,7 @@
     const namespace_context* aNSCtx,
     bool copyNodes)
   :
-  namespace_context_base_expr(sctx, aLoc, elem_expr_kind, aNSCtx),
+  namespace_context_base_expr(ccb, sctx, aLoc, elem_expr_kind, aNSCtx),
   theQNameExpr(aQNameExpr),
   theAttrs(0),
   theContent(content),
@@ -613,7 +632,7 @@
 
   setUnfoldable(ANNOTATION_TRUE_FIXED);
 }
-  
+
 
 void elem_expr::compute_scripting_kind()
 {
@@ -641,9 +660,9 @@
 }
 
 
-expr_t elem_expr::clone(substitution_t& subst) const
+expr* elem_expr::clone(substitution_t& subst) const
 {
-  elem_expr* clone =  new elem_expr(theSctx,
+  elem_expr* clone =  theCCB->theEM->create_elem_expr(theSctx,
                                     get_loc(),
                                     CLONE(getQNameExpr(), subst),
                                     CLONE(getAttrs(), subst),
@@ -658,12 +677,13 @@
 
 ********************************************************************************/
 attr_expr::attr_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    expr_t aQNameExpr,
-    expr_t aValueExpr)
+    expr* aQNameExpr,
+    expr* aValueExpr)
   :
-  expr(sctx, loc, attr_expr_kind),
+  expr(ccb, sctx, loc, attr_expr_kind),
   theQNameExpr(aQNameExpr),
   theValueExpr(aValueExpr)
 {
@@ -675,7 +695,7 @@
 
 const store::Item* attr_expr::getQName() const
 {
-  const_expr* qnExpr =  dynamic_cast<const_expr*>(theQNameExpr.getp());
+  const_expr* qnExpr =  dynamic_cast<const_expr*>(theQNameExpr);
   if (qnExpr != 0)
     return qnExpr->get_val();
 
@@ -707,9 +727,9 @@
 }
 
 
-expr_t attr_expr::clone(substitution_t& subst) const
+expr* attr_expr::clone(substitution_t& subst) const
 {
-  return new attr_expr(theSctx,
+  return theCCB->theEM->create_attr_expr(theSctx,
                        get_loc(),
                        CLONE(getQNameExpr(), subst),
                        CLONE(getValueExpr(), subst));
@@ -723,12 +743,13 @@
 
 ********************************************************************************/
 text_expr::text_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     text_constructor_type type_arg,
-    expr_t content)
+    expr* content)
   :
-  expr(sctx, loc, text_expr_kind),
+  expr(ccb, sctx, loc, text_expr_kind),
   type(type_arg),
   theContentExpr(content)
 {
@@ -749,9 +770,9 @@
 }
 
 
-expr_t text_expr::clone(substitution_t& subst) const
+expr* text_expr::clone(substitution_t& subst) const
 {
-  return new text_expr(theSctx, get_loc(), get_type(), CLONE(get_text(), subst));
+  return theCCB->theEM->create_text_expr(theSctx, get_loc(), get_type(), CLONE(get_text(), subst));
 }
 
 
@@ -759,12 +780,13 @@
 
 ********************************************************************************/
 pi_expr::pi_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    expr_t targetExpr,
-    expr_t contentExpr)
+    expr* targetExpr,
+    expr* contentExpr)
 :
-  expr(sctx, loc, pi_expr_kind),
+  expr(ccb, sctx, loc, pi_expr_kind),
   theTargetExpr(targetExpr),
   theContentExpr(contentExpr)
 {
@@ -798,9 +820,9 @@
 }
 
 
-expr_t pi_expr::clone(substitution_t& subst) const
+expr* pi_expr::clone(substitution_t& subst) const
 {
-  return new pi_expr(theSctx,
+  return theCCB->theEM->create_pi_expr(theSctx,
                      get_loc(),
                      CLONE(get_target_expr(), subst),
                      CLONE(get_content_expr(), subst));
@@ -812,9 +834,9 @@
   Normally, it is used to wrap a var_expr in order to represent a var reference
   (see var_expr.h). But it may wrap any other kind of expr as well.
 ********************************************************************************/
-wrapper_expr::wrapper_expr(static_context* sctx, const QueryLoc& loc, expr_t wrapped)
+wrapper_expr::wrapper_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, expr* wrapped)
   :
-  expr(sctx, loc, wrapper_expr_kind),
+  expr(ccb, sctx, loc, wrapper_expr_kind),
   theWrappedExpr(wrapped)
 {
   compute_scripting_kind();
@@ -827,75 +849,77 @@
 }
 
 
-expr_t wrapper_expr::clone(substitution_t& subst) const
+expr* wrapper_expr::clone(substitution_t& subst) const
 {
-  expr_t e = theWrappedExpr->clone(subst);
+  expr* e = theWrappedExpr->clone(subst);
 
   if (theWrappedExpr->get_expr_kind() == var_expr_kind &&
       e->get_expr_kind() != var_expr_kind)
     return e;
   else
-    return new wrapper_expr(theSctx, get_loc(), e);
+    return theCCB->theEM->create_wrapper_expr(theSctx, get_loc(), e);
 }
 
 
 /***************************************************************************//**
 
 ********************************************************************************/
-const_expr::const_expr(static_context* sctx, const QueryLoc& loc, zstring& v)
-  :
-  expr(sctx, loc, const_expr_kind)
-{
-  GENV_ITEMFACTORY->createString(theValue, v); 
-  theScriptingKind = SIMPLE_EXPR;
-}
-
-
-const_expr::const_expr(static_context* sctx, const QueryLoc& loc, const std::string& v)
-  :
-  expr(sctx, loc, const_expr_kind)
-{
-  zstring tmp(v);
-  GENV_ITEMFACTORY->createString(theValue, tmp); 
-  theScriptingKind = SIMPLE_EXPR;
-}
-
-
-const_expr::const_expr(static_context* sctx, const QueryLoc& loc, const char* v)
-  :
-  expr(sctx, loc, const_expr_kind)
-{
-  zstring tmp(v);
-  GENV_ITEMFACTORY->createString(theValue, tmp); 
-  theScriptingKind = SIMPLE_EXPR;
-}
-
-
-const_expr::const_expr(static_context* sctx, const QueryLoc& loc, xs_integer v)
-  :
-  expr(sctx, loc, const_expr_kind)
+const_expr::const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, zstring& v)
+  :
+  expr(ccb, sctx, loc, const_expr_kind)
+{
+  GENV_ITEMFACTORY->createString(theValue, v);
+  theScriptingKind = SIMPLE_EXPR;
+}
+
+
+const_expr::const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, const std::string& v)
+  :
+  expr(ccb, sctx, loc, const_expr_kind)
+{
+  zstring tmp(v);
+  GENV_ITEMFACTORY->createString(theValue, tmp);
+  theScriptingKind = SIMPLE_EXPR;
+}
+
+
+const_expr::const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, const char* v)
+  :
+  expr(ccb, sctx, loc, const_expr_kind)
+{
+  zstring tmp(v);
+  GENV_ITEMFACTORY->createString(theValue, tmp);
+  theScriptingKind = SIMPLE_EXPR;
+}
+
+
+const_expr::const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, xs_integer v)
+  :
+  expr(ccb, sctx, loc, const_expr_kind)
 {
   GENV_ITEMFACTORY->createInteger(theValue, v);
   theScriptingKind = SIMPLE_EXPR;
 }
 
 const_expr::const_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     xs_decimal v)
   :
-  expr(sctx, loc, const_expr_kind)
+  expr(ccb, sctx, loc, const_expr_kind)
 {
   GENV_ITEMFACTORY->createDecimal(theValue, v);
   theScriptingKind = SIMPLE_EXPR;
 }
 
 const_expr::const_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     xs_double v)
   :
-  expr(sctx, loc, const_expr_kind)
+  expr(ccb, sctx, loc, const_expr_kind)
 {
   GENV_ITEMFACTORY->createDouble(theValue, v);
   theScriptingKind = SIMPLE_EXPR;
@@ -903,11 +927,12 @@
 
 
 const_expr::const_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     xs_boolean v)
   :
-  expr(sctx, loc, const_expr_kind)
+  expr(ccb, sctx, loc, const_expr_kind)
 {
   GENV_ITEMFACTORY->createBoolean(theValue, v);
   theScriptingKind = SIMPLE_EXPR;
@@ -915,11 +940,12 @@
 
 
 const_expr::const_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     store::Item_t v)
   :
-  expr(sctx, loc, const_expr_kind),
+  expr(ccb, sctx, loc, const_expr_kind),
   theValue(v)
 {
   theScriptingKind = SIMPLE_EXPR;
@@ -927,13 +953,14 @@
 
 
 const_expr::const_expr(
+    CompilerCB* ccb,
     static_context* sctx,
-    const QueryLoc& aLoc, 
+    const QueryLoc& aLoc,
     const char* aNamespace,
-    const char* aPrefix, 
+    const char* aPrefix,
     const char* aLocal)
   :
-  expr(sctx, aLoc, const_expr_kind)
+  expr(ccb, sctx, aLoc, const_expr_kind)
 {
   GENV_ITEMFACTORY->createQName(theValue, aNamespace, aPrefix, aLocal);
   theScriptingKind = SIMPLE_EXPR;
@@ -946,9 +973,9 @@
 }
 
 
-expr_t const_expr::clone(substitution_t&) const
+expr* const_expr::clone(substitution_t&) const
 {
-  return new const_expr(theSctx, get_loc(), theValue);
+  return theCCB->theEM->create_const_expr(theSctx, get_loc(), theValue);
 }
 
 
@@ -964,21 +991,23 @@
 
 
 extension_expr::extension_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc)
   :
-  expr(sctx, loc, extension_expr_kind)
+  expr(ccb, sctx, loc, extension_expr_kind)
 {
   compute_scripting_kind();
 }
 
 
 extension_expr::extension_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    expr_t e)
+    expr* e)
   :
-  expr(sctx, loc, extension_expr_kind),
+  expr(ccb, sctx, loc, extension_expr_kind),
   theExpr(e)
 {
   compute_scripting_kind();
@@ -996,26 +1025,26 @@
 }
 
 
-expr_t extension_expr::clone(substitution_t& subst) const 
+expr* extension_expr::clone(substitution_t& subst) const
 {
-  rchandle<extension_expr> lClone(0);
+  extension_expr* lClone(0);
   lClone = (
-    theExpr == 0 ? new extension_expr(theSctx, get_loc())
-                 : new extension_expr(theSctx, get_loc(), theExpr->clone()) );
+    theExpr == 0 ? theCCB->theEM->create_extension_expr(theSctx, get_loc())
+                 : theCCB->theEM->create_extension_expr(theSctx, get_loc(), theExpr->clone()) );
   // pragm doesn't contain expressions. Thus, it is not cloned.
   for ( std::vector<rchandle<pragma> >::const_iterator lIter = thePragmas.begin();
         lIter != thePragmas.end();
-        ++lIter ) 
+        ++lIter )
   {
     lClone->add(*lIter);
   }
-  return lClone.getp();
+  return lClone;
 }
 
 
 /////////////////////////////////////////////////////////////////////////
 //                                                                     //
-//	XQuery 3.0 expressions                                             //
+//  XQuery 3.0 expressions                                             //
 //  [http://www.w3.org/TR/xquery-3/]                                   //
 //                                                                     //
 /////////////////////////////////////////////////////////////////////////
@@ -1030,18 +1059,19 @@
 
 
 trycatch_expr::trycatch_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    expr_t tryExpr)
+    expr* tryExpr)
   :
-  expr(sctx, loc, trycatch_expr_kind),
+  expr(ccb, sctx, loc, trycatch_expr_kind),
   theTryExpr(tryExpr)
 {
   compute_scripting_kind();
 }
 
 
-void trycatch_expr::add_catch_expr(expr_t e)
+void trycatch_expr::add_catch_expr(expr* e)
 {
   theCatchExprs.insert(theCatchExprs.begin(), e);
 
@@ -1068,9 +1098,9 @@
 
   csize numCatchClauses = theCatchClauses.size();
 
-  for (csize i = 0; i < numCatchClauses; ++i) 
+  for (csize i = 0; i < numCatchClauses; ++i)
   {
-    const expr* catchExpr = theCatchExprs[i].getp();
+    const expr* catchExpr = theCatchExprs[i];
     short catchKind = catchExpr->get_scripting_detail();
 
     if (catchKind == VACUOUS_EXPR)
@@ -1085,7 +1115,7 @@
         RAISE_ERROR(err::XUST0001, catchExpr->get_loc(),
         ERROR_PARAMS(ZED(XUST0001_TRYCATCH)));
       }
-        
+
       if (!is_updating() && !is_vacuous() && (catchKind & UPDATING_EXPR))
       {
         RAISE_ERROR(err::XUST0001, catchExpr->get_loc(),
@@ -1115,34 +1145,34 @@
 
   for (nt_list_t::const_iterator lIter = theNameTests.begin();
        lIter != theNameTests.end();
-       ++lIter) 
+       ++lIter)
   {
     lClause->add_nametest_h(lIter->getp());
   }
   for (var_map_t::const_iterator lIter = theVarMap.begin();
        lIter != theVarMap.end();
-       ++lIter) 
+       ++lIter)
   {
-    lClause->add_var((catch_clause::var_type)lIter->first, lIter->second.getp());
+    lClause->add_var((catch_clause::var_type)lIter->first, lIter->second);
   }
 
   return lClause.getp();
 }
 
 
-expr_t trycatch_expr::clone(substitution_t& subst) const
+expr* trycatch_expr::clone(substitution_t& subst) const
 {
   std::auto_ptr<trycatch_expr> lTryCatch(
-      new trycatch_expr(theSctx, get_loc(), theTryExpr->clone(subst)));
+      theCCB->theEM->create_trycatch_expr(theSctx, get_loc(), theTryExpr->clone(subst)));
 
-  for (std::vector<expr_t>::const_iterator lIter = theCatchExprs.begin();
+  for (std::vector<expr*>::const_iterator lIter = theCatchExprs.begin();
        lIter != theCatchExprs.end();
-       ++lIter) 
+       ++lIter)
   {
     lTryCatch->add_catch_expr((*lIter)->clone(subst));
   }
 
-  for (uint32_t i = 0; i < clause_count(); ++i) 
+  for (uint32_t i = 0; i < clause_count(); ++i)
   {
     lTryCatch->add_clause(theCatchClauses[i]->clone(subst));
   }
@@ -1155,14 +1185,15 @@
 
 ********************************************************************************/
 eval_expr::eval_expr(
+    CompilerCB* creating_ccb,
     CompilerCB* ccb,
     static_context* sctx,
-    const QueryLoc& loc, 
-    const expr_t& e,
+    const QueryLoc& loc,
+    expr* e,
     expr_script_kind_t scriptingKind,
     namespace_context* nsCtx)
   :
-  namespace_context_base_expr(sctx, loc, eval_expr_kind, nsCtx),
+  namespace_context_base_expr(creating_ccb, sctx, loc, eval_expr_kind, nsCtx),
   theExpr(e),
   theInnerScriptingKind(scriptingKind),
   theDoNodeCopy(false)
@@ -1174,9 +1205,9 @@
 }
 
 
-expr_script_kind_t eval_expr::get_inner_scripting_kind() const 
+expr_script_kind_t eval_expr::get_inner_scripting_kind() const
 {
-  return theInnerScriptingKind; 
+  return theInnerScriptingKind;
 }
 
 
@@ -1196,11 +1227,12 @@
 }
 
 
-expr_t eval_expr::clone(substitution_t& s) const
+expr* eval_expr::clone(substitution_t& s) const
 {
-  rchandle<eval_expr> new_eval = new eval_expr(NULL,
-                                               theSctx, 
-                                               theLoc, 
+  eval_expr* new_eval = theCCB->theEM->create_eval_expr(
+                                               NULL,
+                                               theSctx,
+                                               theLoc,
                                                theExpr->clone(s),
                                                theInnerScriptingKind,
                                                theNSCtx.getp());
@@ -1208,12 +1240,12 @@
 
   for (csize i = 0; i < theVars.size(); ++i)
   {
-    var_expr_t cloneVar = dynamic_cast<var_expr*>(theVars[i]->clone(s).getp());
+    var_expr* cloneVar = dynamic_cast<var_expr*>(theVars[i]->clone(s));
     assert(cloneVar != NULL);
     new_eval->add_var(cloneVar, (theArgs[i] ? theArgs[i]->clone(s) : NULL));
   }
 
-  return new_eval.getp();
+  return new_eval;
 }
 
 
@@ -1222,13 +1254,14 @@
 
 ********************************************************************************/
 debugger_expr::debugger_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& aChild,
+    expr* aChild,
     namespace_context* nsCtx,
     bool aIsVarDeclaration)
   :
-  namespace_context_base_expr(sctx, loc, debugger_expr_kind, nsCtx),
+  namespace_context_base_expr(ccb, sctx, loc, debugger_expr_kind, nsCtx),
   theExpr(aChild),
   theIsVarDeclaration(aIsVarDeclaration)
 {
@@ -1248,11 +1281,12 @@
 
 ********************************************************************************/
 function_trace_expr::function_trace_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    expr_t aChild)
+    expr* aChild)
   :
-  expr(sctx, loc, function_trace_expr_kind),
+  expr(ccb, sctx, loc, aChild->get_expr_kind()),
   theExpr(aChild),
   theFunctionArity(0)
 {
@@ -1262,9 +1296,9 @@
 }
 
 
-function_trace_expr::function_trace_expr(expr_t aExpr)
+function_trace_expr::function_trace_expr(expr* aExpr)
   :
-  expr(aExpr->get_sctx(), aExpr->get_loc(), function_trace_expr_kind),
+  expr(aExpr->get_ccb(), aExpr->get_sctx(), aExpr->get_loc(), function_trace_expr_kind),
   theExpr(aExpr),
   theFunctionArity(0)
 {
@@ -1274,7 +1308,7 @@
 }
 
 
-function_trace_expr::~function_trace_expr() 
+function_trace_expr::~function_trace_expr()
 {
 }
 
@@ -1285,14 +1319,16 @@
 }
 
 
-expr_t function_trace_expr::clone(substitution_t& s) const
+expr* function_trace_expr::clone(substitution_t& s) const
 {
-  function_trace_expr* clone = new function_trace_expr(theExpr->clone(s));
+  function_trace_expr* clone = theCCB->theEM->
+      create_function_trace_expr(theExpr->clone(s));
 
   clone->theFunctionName = theFunctionName;
   clone->theFunctionLocation = theFunctionLocation;
   clone->theFunctionCallLocation = theFunctionCallLocation;
   clone->theFunctionArity = theFunctionArity;
+
   return clone;
 }
 

=== modified file 'src/compiler/expression/expr.h'
--- src/compiler/expression/expr.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/expr.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -39,45 +39,47 @@
 
 #include "runtime/core/sequencetypes.h"
 
-namespace zorba 
+namespace zorba
 {
 
+class ExprManager;
 class expr_visitor;
 class NodeNameTest;
 class signature;
 
-
-
 /*******************************************************************************
   [68] IfExpr ::= "if" "(" Expr ")" "then" ExprSingle "else" ExprSingle
 ********************************************************************************/
-class if_expr : public expr 
+class if_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
-  expr_t theCondExpr;
-  expr_t theThenExpr;
-  expr_t theElseExpr;
+  expr* theCondExpr;
+  expr* theThenExpr;
+  expr* theElseExpr;
 
-public:
+protected:
   if_expr(
+        CompilerCB* ccb,
         static_context* sctx,
         const QueryLoc& loc,
-        expr_t c,
-        expr_t t,
-        expr_t e);
-
-  expr* get_cond_expr() const { return theCondExpr.getp(); }
-
-  expr* get_then_expr() const { return theThenExpr.getp(); }
-
-  expr* get_else_expr() const { return theElseExpr.getp(); }
+        expr* c,
+        expr* t,
+        expr* e);
+
+public:
+  expr* get_cond_expr() const { return theCondExpr; }
+
+  expr* get_then_expr() const { return theThenExpr; }
+
+  expr* get_else_expr() const { return theElseExpr; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -88,13 +90,14 @@
 /***************************************************************************//**
 
 ********************************************************************************/
-class order_expr : public expr 
+class order_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 public:
-  enum order_type_t 
+  enum order_type_t
   {
     ordered,
     unordered
@@ -102,18 +105,19 @@
 
 protected:
   order_type_t theType;
-  expr_t       theExpr;
+  expr*       theExpr;
+
+protected:
+  order_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, order_type_t, expr*);
 
 public:
-  order_expr(static_context* sctx, const QueryLoc&, order_type_t, expr_t);
-
   order_type_t get_type() const { return theType; }
 
-  expr* get_expr() const { return theExpr.getp(); }
+  expr* get_expr() const { return theExpr; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -124,8 +128,9 @@
 /***************************************************************************//**
 
 ********************************************************************************/
-class validate_expr : public expr 
+class validate_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
@@ -133,18 +138,20 @@
   ParseConstants::validation_mode_t theMode;
   store::Item_t                     theTypeName;
   rchandle<TypeManager>             theTypeMgr;
-  expr_t                            theExpr;
+  expr*                            theExpr;
 
-public:
+protected:
   validate_expr(
+        CompilerCB* ccb,
         static_context* sctx,
         const QueryLoc&,
         ParseConstants::validation_mode_t,
         const store::Item_t& aTypeName,
-        expr_t,
+        expr*,
         rchandle<TypeManager>);
 
-  expr* get_expr() const { return theExpr.getp(); }
+public:
+  expr* get_expr() const { return theExpr; }
 
   const store::Item* get_type_name() const { return theTypeName; }
 
@@ -154,7 +161,7 @@
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -174,6 +181,7 @@
 
 protected:
   namespace_context_base_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
       expr_kind_t kind,
@@ -187,25 +195,26 @@
 /***************************************************************************//**
   Base for cast, treat, promote, castable, instanceof
 ********************************************************************************/
-class cast_or_castable_base_expr : public expr 
+class cast_or_castable_base_expr : public expr
 {
   friend class ExprIterator;
   friend class expr;
 
 protected:
-  expr_t   theInputExpr;
+  expr*   theInputExpr;
   xqtref_t theTargetType;
 
 protected:
   cast_or_castable_base_expr(
+        CompilerCB* ccb,
         static_context* sctx,
         const QueryLoc& loc,
         expr_kind_t kind,
-        const expr_t& input,
+        expr* input,
         const xqtref_t& type);
-  
+
 public:
-  expr* get_input() const { return theInputExpr.getp(); }
+  expr* get_input() const { return theInputExpr; }
 
   xqtref_t get_target_type() const;
 
@@ -222,13 +231,14 @@
 {
   friend class ExprIterator;
 
-public:
+protected:
   cast_base_expr(
-      static_context* sctx, 
-      const QueryLoc& loc,
-      expr_kind_t kind,
-      const expr_t& input,
-      const xqtref_t& type);
+        CompilerCB* ccb,
+        static_context* sctx,
+        const QueryLoc& loc,
+        expr_kind_t kind,
+        expr* input,
+        const xqtref_t& type);
 };
 
 
@@ -239,15 +249,22 @@
 ********************************************************************************/
 class cast_expr : public cast_base_expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
+protected:
+  cast_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      const QueryLoc&,
+      expr*,
+      const xqtref_t&);
+
 public:
-  cast_expr(static_context* sctx, const QueryLoc&, const expr_t&, const xqtref_t&);
-
   bool is_optional() const;
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -256,7 +273,7 @@
 
 
 /***************************************************************************//**
-	TreatExpr ::= CastableExpr ( "treat" "as" SequenceType )?
+  TreatExpr ::= CastableExpr ( "treat" "as" SequenceType )?
 
   theCheckPrime : Normally, this is true. If false, then during runtime, only
                   the cardinality of theInputExpr will be checked w.r.t. the
@@ -265,11 +282,12 @@
                   static type of theInputExpr is a subtype of the prime type of
                   theTargetType.
 
-  theFnQName    : Stores the QName of the function, if the treat expr is used 
+  theFnQName    : Stores the QName of the function, if the treat expr is used
                   to cast the function's body to its result type
 ********************************************************************************/
-class treat_expr : public cast_base_expr 
+class treat_expr : public cast_base_expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
@@ -278,16 +296,18 @@
   bool                     theCheckPrime;
   store::Item_t            theQName;
 
-public:
+protected:
   treat_expr(
-        static_context* sctx, 
-        const QueryLoc& loc,
-        const expr_t& input,
-        const xqtref_t& type,
+        CompilerCB* ccb,
+        static_context* sctx,
+        const QueryLoc&,
+        expr*,
+        const xqtref_t&,
         TreatIterator::ErrorKind err,
         bool check_prime = true,
         store::Item* qname = NULL);
 
+public:
   TreatIterator::ErrorKind get_err() const { return theErrorKind; }
 
   bool get_check_prime() const { return theCheckPrime; }
@@ -298,7 +318,7 @@
 
   store::Item_t get_qname() const { return theQName; }
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -323,7 +343,7 @@
      - If the target type is the NONE type, F(I) = error, else
      - If the actual type is a subtype of the target type, F(I) = I, else
      - If the target type is not an atomic type, F(I) = error, else
-     - If the actual type is untypedAtomic and the target type is not QName, 
+     - If the actual type is untypedAtomic and the target type is not QName,
        F(I) = cast(I, target type), else
      - If the actual type is (subtype of) decimal and the target type is float,
        F(I) = cast(I, target type), else
@@ -339,27 +359,30 @@
   -----------
   Stores the QName of the function, if the promote expr is used to cast the
   function's body to its result type
-  
+
 ********************************************************************************/
 class promote_expr : public cast_base_expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
   PromoteIterator::ErrorKind theErrorKind;
-  store::Item_t              theQName; 
-  
-public:
+  store::Item_t              theQName;
+
+protected:
   promote_expr(
-      static_context* sctx, 
-      const QueryLoc& loc, 
-      const expr_t& input, 
-      const xqtref_t& type, 
+      CompilerCB* ccb,
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* input,
+      const xqtref_t& type,
       PromoteIterator::ErrorKind err,
       store::Item* qname);
 
-  expr_t clone(substitution_t& s) const;
+public:
+  expr* clone(substitution_t& s) const;
 
   PromoteIterator::ErrorKind get_err() const { return theErrorKind; }
 
@@ -376,16 +399,17 @@
 /***************************************************************************//**
   Base for castable, instanceof
 ********************************************************************************/
-class castable_base_expr : public cast_or_castable_base_expr 
+class castable_base_expr : public cast_or_castable_base_expr
 {
   friend class ExprIterator;
 
-public:
+protected:
   castable_base_expr(
+        CompilerCB* ccb,
         static_context* sctx,
         const QueryLoc&,
         expr_kind_t kind,
-        const expr_t&,
+        expr*,
         const xqtref_t&);
 };
 
@@ -395,17 +419,24 @@
 
   SingleType ::= AtomicType "?"?
 ********************************************************************************/
-class castable_expr : public castable_base_expr 
+class castable_expr : public castable_base_expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
+protected:
+  castable_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      const QueryLoc&,
+      expr*,
+      const xqtref_t&);
+
 public:
-  castable_expr(static_context* sctx, const QueryLoc&, const expr_t&, const xqtref_t&);
-  
   bool is_optional() const;
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -414,33 +445,36 @@
 
 
 /***************************************************************************//**
-	InstanceofExpr ::= TreatExpr ( "instance" "of" SequenceType )?
+  InstanceofExpr ::= TreatExpr ( "instance" "of" SequenceType )?
 
-  theCheckPrimeOnly : 
+  theCheckPrimeOnly :
   Normally, this is false. It is set to true only if this is an instanceof expr
   that is created during the translation of a PredicateList (see translator.cpp).
   This flag is used during the PartialEval rule.
 
 ********************************************************************************/
-class instanceof_expr : public castable_base_expr 
+class instanceof_expr : public castable_base_expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
   bool theCheckPrimeOnly;
 
-public:
+protected:
   instanceof_expr(
+      CompilerCB* ccb,
       static_context* sctx,
-      const QueryLoc&, 
-      const expr_t&, 
+      const QueryLoc&,
+      expr*,
       const xqtref_t&,
       bool checkPrimeOnly = false);
 
+public:
   bool getCheckPrimeOnly() const { return theCheckPrimeOnly; }
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -460,28 +494,31 @@
 ********************************************************************************/
 class name_cast_expr : public namespace_context_base_expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 private:
-  expr_t             theInputExpr;
+  expr*             theInputExpr;
   bool               theIsAttrName;
 
-public:
+protected:
   name_cast_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc&,
-      expr_t,
+      expr*,
       const namespace_context*,
       bool isAttr);
 
-  expr* get_input() const { return theInputExpr.getp(); }
+public:
+  expr* get_input() const { return theInputExpr; }
 
   bool is_attr_name() const { return theIsAttrName; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -492,19 +529,21 @@
 /***************************************************************************//**
   CompDocConstructor ::= "document" "{" Expr "}"
 ********************************************************************************/
-class doc_expr : public expr 
+class doc_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
-  expr_t theContent;
+  expr* theContent;
   bool   theCopyInputNodes;
 
+protected:
+  doc_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, expr* content, bool copyNodes);
+
 public:
-  doc_expr(static_context* sctx, const QueryLoc&, expr* content, bool copyNodes);
-
-  expr* getContent() const { return theContent.getp(); }
+  expr* getContent() const { return theContent; }
 
   bool copyInputNodes() const { return theCopyInputNodes; }
 
@@ -512,7 +551,7 @@
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -548,17 +587,19 @@
 ********************************************************************************/
 class elem_expr : public namespace_context_base_expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
-  expr_t theQNameExpr;
-  expr_t theAttrs;
-  expr_t theContent;
+  expr* theQNameExpr;
+  expr* theAttrs;
+  expr* theContent;
   bool   theCopyInputNodes;
 
-public:
+protected:
   elem_expr(
+        CompilerCB* ccb,
         static_context* sctx,
         const QueryLoc&,
         expr* qnameExpr,
@@ -566,28 +607,30 @@
         expr* content,
         const namespace_context* nsCtx,
         bool copyNodes);
-  
+
   elem_expr(
+        CompilerCB* ccb,
         static_context* sctx,
         const QueryLoc&,
         expr* qnameExpr,
         expr* content,
         const namespace_context* nsCtx,
         bool copyNodes);
-  
-  expr* getQNameExpr() const { return theQNameExpr.getp(); }
-
-  expr* getContent() const { return theContent.getp(); }
-
-  expr* getAttrs() const { return theAttrs.getp(); }
+
+public:
+  expr* getQNameExpr() const { return theQNameExpr; }
+
+  expr* getContent() const { return theContent; }
+
+  expr* getAttrs() const { return theAttrs; }
 
   bool copyInputNodes() const { return theCopyInputNodes; }
 
   void setCopyInputNodes() { theCopyInputNodes = true; }
 
   void compute_scripting_kind();
-  
-  expr_t clone(substitution_t& s) const;  
+
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -619,31 +662,34 @@
   CommonContent ::= PredefinedEntityRef | CharRef | "{{" | "}}" | EnclosedExpr
 
 ********************************************************************************/
-class attr_expr : public expr 
+class attr_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
-  expr_t theQNameExpr;
-  expr_t theValueExpr;
+  expr* theQNameExpr;
+  expr* theValueExpr;
 
-public:
+protected:
   attr_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    expr_t aQNameExpr,
-    expr_t aValueExpr);
-
-  expr* getQNameExpr() const { return theQNameExpr.getp(); }
-
-  expr* getValueExpr() const { return theValueExpr.getp(); }
+    expr* aQNameExpr,
+    expr* aValueExpr);
+
+public:
+  expr* getQNameExpr() const { return theQNameExpr; }
+
+  expr* getValueExpr() const { return theValueExpr; }
 
   const store::Item* getQName() const;
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -654,13 +700,14 @@
 /***************************************************************************//**
 
 ********************************************************************************/
-class text_expr : public expr 
+class text_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 public:
-  typedef enum 
+  typedef enum
   {
     text_constructor,
     comment_constructor
@@ -668,22 +715,24 @@
 
 protected:
   text_constructor_type type;
-  expr_t                theContentExpr;
+  expr*                theContentExpr;
 
-public:
+protected:
   text_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc&,
       text_constructor_type,
-      expr_t);
+      expr*);
 
-  expr* get_text() const { return theContentExpr.getp(); }
+public:
+  expr* get_text() const { return theContentExpr; }
 
   text_constructor_type get_type() const { return type; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;  
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -694,25 +743,27 @@
 /***************************************************************************//**
 
 ********************************************************************************/
-class pi_expr : public expr 
+class pi_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
-  expr_t theTargetExpr;
-  expr_t theContentExpr;
+  expr* theTargetExpr;
+  expr* theContentExpr;
+
+protected:
+  pi_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, expr*, expr*);
 
 public:
-  pi_expr(static_context* sctx, const QueryLoc&, expr_t, expr_t);
- 
-  expr* get_target_expr() const { return theTargetExpr.getp(); }
+  expr* get_target_expr() const { return theTargetExpr; }
 
-  expr* get_content_expr() const { return theContentExpr.getp(); }
+  expr* get_content_expr() const { return theContentExpr; }
 
   void compute_scripting_kind();
-  
-  expr_t clone(substitution_t& s) const;  
+
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -723,38 +774,40 @@
 /***************************************************************************//**
 
 ********************************************************************************/
-class const_expr : public expr 
+class const_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
   store::Item_t theValue;
 
+protected:
+  const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, zstring& sval);
+
+  const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, const std::string& sval);
+
+  const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, const char* sval);
+
+  const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, xs_integer);
+
+  const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, xs_decimal);
+
+  const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, xs_double);
+
+  const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, xs_boolean);
+
+  const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, store::Item_t);
+
+  const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, const char* ns, const char* pre, const char* local);
+
 public:
-  const_expr(static_context* sctx, const QueryLoc&, zstring& sval);
-
-  const_expr(static_context* sctx, const QueryLoc&, const std::string& sval);
-
-  const_expr(static_context* sctx, const QueryLoc&, const char* sval);
-
-  const_expr(static_context* sctx, const QueryLoc&, xs_integer);
-
-  const_expr(static_context* sctx, const QueryLoc&, xs_decimal);
-
-  const_expr(static_context* sctx, const QueryLoc&, xs_double);
-
-  const_expr(static_context* sctx, const QueryLoc&, xs_boolean);
-
-  const_expr(static_context* sctx, const QueryLoc&, store::Item_t);  
-
-  const_expr(static_context* sctx, const QueryLoc&, const char* ns, const char* pre, const char* local);
-
   store::Item* get_val() const { return theValue.getp(); }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -781,27 +834,29 @@
 /***************************************************************************//**
 
 ********************************************************************************/
-class extension_expr : public expr 
+class extension_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
   std::vector<rchandle<pragma> > thePragmas;
-  expr_t                         theExpr;
+  expr*                         theExpr;
+
+protected:
+  extension_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&);
+
+  extension_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, expr*);
 
 public:
-  extension_expr(static_context* sctx, const QueryLoc&);
-
-  extension_expr(static_context* sctx, const QueryLoc&, expr_t);
-
   void add(rchandle<pragma> p) { thePragmas.push_back(p); }
 
-  expr* get_expr() const { return theExpr.getp(); }
+  expr* get_expr() const { return theExpr; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& subst) const;
+  expr* clone(substitution_t& subst) const;
 
   void accept(expr_visitor&);
 
@@ -811,7 +866,7 @@
 
 /////////////////////////////////////////////////////////////////////////
 //                                                                     //
-//	XQuery 3.0 expressions                                             //
+//  XQuery 3.0 expressions                                             //
 //  [http://www.w3.org/TR/xquery-3/]                                   //
 //                                                                     //
 /////////////////////////////////////////////////////////////////////////
@@ -836,7 +891,7 @@
 typedef rchandle<catch_clause> catch_clause_t;
 
 
-class catch_clause : public SimpleRCObject 
+class catch_clause : public SimpleRCObject
 {
   friend class expr;
   friend class trycatch_expr;
@@ -856,61 +911,64 @@
 public:
   typedef rchandle<NodeNameTest> nt_t;
   typedef std::vector<nt_t> nt_list_t;
-  typedef std::map<int, var_expr_t> var_map_t;
+  typedef std::map<int, var_expr*> var_map_t;
 
 protected:
   nt_list_t  theNameTests;
   var_map_t  theVarMap;
-  
+
 public:
   catch_clause();
-  
+
+public:
   void set_nametests(nt_list_t& a) { theNameTests = a; }
 
   nt_list_t& get_nametests() { return theNameTests; }
-  
+
   void add_nametest_h(nt_t n) { theNameTests.push_back(n); }
 
   void set_vars(var_map_t& a) { theVarMap = a; }
 
   var_map_t& get_vars() { return theVarMap; }
-  
-  void add_var(var_type v, var_expr_t n) { theVarMap[v] = n; }
-  
+
+  void add_var(var_type v, var_expr* n) { theVarMap[v] = n; }
+
   catch_clause_t clone(expr::substitution_t& subst) const;
 };
 
 
-class trycatch_expr : public expr 
+class trycatch_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
-  expr_t                      theTryExpr;
-  std::vector<expr_t>         theCatchExprs;
+  expr*                      theTryExpr;
+  std::vector<expr*>         theCatchExprs;
   std::vector<catch_clause_t> theCatchClauses;
 
+protected:
+  trycatch_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, expr* tryExpr);
+
 public:
-  trycatch_expr(static_context* sctx, const QueryLoc&, expr_t tryExpr);
-
-  expr* get_try_expr() const { return theTryExpr.getp(); }
+  expr* get_try_expr() const { return theTryExpr; }
 
   void set_try_expr(expr* e) { theTryExpr = e; }
 
-  expr* get_catch_expr(csize i) const { return theCatchExprs[i].getp(); }
+  expr* get_catch_expr(csize i) const { return theCatchExprs[i]; }
 
-  void add_catch_expr(expr_t e);
+  void add_catch_expr(expr* e);
 
   void add_clause(catch_clause_t cc);
-  
+
   csize clause_count() const { return theCatchClauses.size(); }
-  
+
   const catch_clause_t& operator[](csize i) const { return theCatchClauses[i]; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& subst) const;
+  expr* clone(substitution_t& subst) const;
 
   void accept(expr_visitor&);
 
@@ -920,7 +978,7 @@
 
 /////////////////////////////////////////////////////////////////////////
 //                                                                     //
-//	Zorba expressions                                                  //
+//  Zorba expressions                                                  //
 //                                                                     //
 /////////////////////////////////////////////////////////////////////////
 
@@ -929,26 +987,28 @@
   Normally, it is used to wrap a var_expr in order to represent a var reference
   (see var_expr.h). But it may wrap any other kind of expr as well.
 ********************************************************************************/
-class wrapper_expr : public expr 
+class wrapper_expr : public expr
 {
   friend class ExprIterator;
   friend class expr;
-
-protected:
-  expr_t theWrappedExpr;
+  friend class ExprManager;
+
+protected:
+  expr* theWrappedExpr;
+
+protected:
+  wrapper_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, expr* wrapped);
 
 public:
-  wrapper_expr(static_context* sctx, const QueryLoc& loc, expr_t wrapped);
-
-  expr* get_expr() const { return theWrappedExpr.getp(); }
-
-  void set_expr(const expr* e) { theWrappedExpr = e; }
+  expr* get_expr() const { return theWrappedExpr; }
+
+  void set_expr(expr* e) { theWrappedExpr = e;}
 
   void compute_scripting_kind();
 
   void accept(expr_visitor&);
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   std::ostream& put(std::ostream&) const;
 };
@@ -961,33 +1021,36 @@
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
 
 protected:
-  expr_t        theExpr;
+  expr*        theExpr;
   store::Item_t theFunctionName;
   QueryLoc      theFunctionLocation;
   QueryLoc      theFunctionCallLocation;
   unsigned int  theFunctionArity;
 
-public:
+protected:
   function_trace_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
-      expr_t aChild);
-
-  function_trace_expr(expr_t aExpr);
-
+      expr* aChild);
+
+  function_trace_expr(expr* aExpr);
+
+public:
   virtual ~function_trace_expr();
 
   void compute_scripting_kind();
 
   void accept(expr_visitor&);
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   std::ostream& put(std::ostream&) const;
 
-  expr* get_expr() const { return theExpr.getp(); }
+  expr* get_expr() const { return theExpr; }
 
   void setFunctionName(store::Item_t aFunctionName)
   {
@@ -1018,7 +1081,7 @@
   {
     return theFunctionCallLocation;
   }
-  
+
   void setFunctionArity(unsigned int arity)
   {
     theFunctionArity = arity;
@@ -1061,34 +1124,37 @@
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
 
 protected:
-  expr_t                      theExpr;
+  expr*                      theExpr;
 
-  std::vector<var_expr_t>     theVars;
-  std::vector<expr_t>         theArgs;
+  std::vector<var_expr*>     theVars;
+  std::vector<expr*>         theArgs;
 
   expr_script_kind_t          theInnerScriptingKind;
   bool                        theDoNodeCopy;
 
-public:
+protected:
   eval_expr(
+      CompilerCB* creating_ccb,
       CompilerCB* ccb,
       static_context* sctx,
-      const QueryLoc& loc, 
-      const expr_t& e,
+      const QueryLoc& loc,
+      expr* e,
       expr_script_kind_t scriptingKind,
       namespace_context* nsCtx);
 
-  expr* get_expr() const { return theExpr.getp(); }
+public:
+  expr* get_expr() const { return theExpr; }
 
-  expr* get_arg_expr(csize i) { return theArgs[i].getp(); }
+  expr* get_arg_expr(csize i) { return theArgs[i]; }
 
   csize var_count() const { return theVars.size(); }
 
   const var_expr* get_var(csize i) const { return theVars[i]; }
 
-  void add_var(const var_expr_t& var, const expr_t& arg) 
+  void add_var(var_expr* var, expr* arg)
   {
     theVars.push_back(var);
     theArgs.push_back(arg);
@@ -1104,7 +1170,7 @@
 
   void accept(expr_visitor&);
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   std::ostream& put(std::ostream&) const;
 };
@@ -1131,22 +1197,25 @@
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
 
 private:
-  expr_t                      theExpr;
-  checked_vector<var_expr_t>  theVars;
-  std::vector<expr_t>         theArgs;
+  expr*                      theExpr;
+  checked_vector<var_expr*>  theVars;
+  std::vector<expr*>         theArgs;
   bool                        theIsVarDeclaration;
 
-public:
+protected:
   debugger_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
-      const expr_t& aChild,
+      expr* aChild,
       namespace_context* nsCtx,
       bool aIsVarDeclaration);
 
-  expr* get_expr() const { return theExpr.getp(); }
+public:
+  expr* get_expr() const { return theExpr; }
 
   bool isVarDeclaration() const { return theIsVarDeclaration; }
 
@@ -1158,7 +1227,7 @@
 
   const var_expr* get_var(csize i) const { return theVars[i]; }
 
-  void add_var(const var_expr_t& var, const expr_t& arg) 
+  void add_var(var_expr* var, expr* arg)
   {
     theVars.push_back(var);
     theArgs.push_back(arg);

=== modified file 'src/compiler/expression/expr_base.cpp'
--- src/compiler/expression/expr_base.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/expr_base.cpp	2012-08-14 12:29:44 +0000
@@ -23,6 +23,9 @@
 #include "compiler/expression/path_expr.h"
 #include "compiler/expression/expr_iter.h"
 #include "compiler/expression/expr_visitor.h"
+#include "compiler/expression/expr_manager.h"
+
+#include "compiler/api/compilercb.h"
 
 #include "functions/function.h"
 #include "functions/library.h"
@@ -72,9 +75,9 @@
 /*******************************************************************************
 
 ********************************************************************************/
-expr_t expr::iter_end_expr = NULL;
+expr* expr::iter_end_expr = NULL;
 
-expr_t* expr::iter_done = &expr::iter_end_expr;
+expr** expr::iter_done = &expr::iter_end_expr;
 
 
 /*******************************************************************************
@@ -85,7 +88,7 @@
   return (theScriptingKind & (VAR_SETTING_EXPR |
                               APPLYING_EXPR |
                               EXITING_EXPR |
-                              BREAKING_EXPR | 
+                              BREAKING_EXPR |
                               SEQUENTIAL_FUNC_EXPR)) != 0;
 }
 
@@ -94,7 +97,7 @@
 {
   if (e != 0 && e->is_updating())
   {
-    throw XQUERY_EXCEPTION(err::XUST0001, 
+    throw XQUERY_EXCEPTION(err::XUST0001,
                            ERROR_PARAMS(ZED(XUST0001_Generic)),
                            ERROR_LOC(e->get_loc()));
   }
@@ -105,7 +108,7 @@
 {
   if (e != 0 && e->is_updating())
   {
-    throw XQUERY_EXCEPTION(err::XUST0001, 
+    throw XQUERY_EXCEPTION(err::XUST0001,
                            ERROR_PARAMS(ZED(XUST0001_Generic)),
                            ERROR_LOC(e->get_loc()));
   }
@@ -120,12 +123,13 @@
 /*******************************************************************************
 
 ********************************************************************************/
-expr::expr(static_context* sctx, const QueryLoc& loc, expr_kind_t k)
+expr::expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, expr_kind_t k)
   :
   theSctx(sctx),
   theLoc(loc),
   theKind(k),
-  theFlags1(0)
+  theFlags1(0),
+  theCCB(ccb)
 {
   theScriptingKind = UNKNOWN_SCRIPTING_KIND;
 
@@ -146,9 +150,9 @@
 /*******************************************************************************
 
 ********************************************************************************/
-TypeManager* expr::get_type_manager() const 
+TypeManager* expr::get_type_manager() const
 {
-  return theSctx->get_typemanager(); 
+  return theSctx->get_typemanager();
 }
 
 
@@ -235,14 +239,14 @@
 /*******************************************************************************
 
 ********************************************************************************/
-expr_t expr::clone() const
+expr* expr::clone() const
 {
   substitution_t subst;
   return clone(subst);
 }
 
 
-expr_t expr::clone(substitution_t& subst) const
+expr* expr::clone(substitution_t& subst) const
 {
   throw XQUERY_EXCEPTION(zerr::ZXQP0003_INTERNAL_ERROR, ERROR_LOC(get_loc()));
 }
@@ -256,8 +260,8 @@
   ExprIterator iter(this);
   while (!iter.done())
   {
-    if (*iter != NULL)
-      (*iter)->accept(v);
+    if (**iter != NULL)
+      (**iter)->accept(v);
 
     iter.next();
   }
@@ -316,7 +320,7 @@
   ExprIterator iter(this);
   while (!iter.done())
   {
-    (*iter)->clear_annotations();
+    (**iter)->clear_annotations();
     iter.next();
   }
 }
@@ -541,11 +545,11 @@
 
 
 /*******************************************************************************
-  This annotation tells whether the expr must produce nodes that belong to 
-  "standalone" trees or not. A tree is standalone if it does not contain 
-  references to other trees. Such references are created when the optimizer 
+  This annotation tells whether the expr must produce nodes that belong to
+  "standalone" trees or not. A tree is standalone if it does not contain
+  references to other trees. Such references are created when the optimizer
   decides that it is ok to avoid copying the referenced subtree (as would be
-  required by required by a strict implementation of the spec, eg., during 
+  required by required by a strict implementation of the spec, eg., during
   node construction).
 ********************************************************************************/
 BoolAnnotationValue expr::getMustCopyNodes() const
@@ -590,18 +594,18 @@
 /*******************************************************************************
   Replace all references to "oldExpr" inside "e" with references to "newExpr".
 ********************************************************************************/
-void expr::replace_expr(const expr* oldExpr, const expr* newExpr)
+void expr::replace_expr(expr* oldExpr, expr* newExpr)
 {
   ExprIterator iter(this);
   while (!iter.done())
   {
-    if ((*iter).getp() == oldExpr)
+    if ((**iter) == oldExpr)
     {
-      (*iter) = newExpr;
+      (**iter) = newExpr;
     }
     else
     {
-      (*iter)->replace_expr(oldExpr, newExpr);
+      (**iter)->replace_expr(oldExpr, newExpr);
     }
 
     iter.next();
@@ -791,13 +795,13 @@
   if (found)
     return true;
 
-  if (this == e) 
+  if (this == e)
   {
     found = true;
     return true;
   }
 
-  switch(get_expr_kind()) 
+  switch(get_expr_kind())
   {
 #ifdef ZORBA_WITH_DEBUGGER
   case debugger_expr_kind:
@@ -829,13 +833,13 @@
     const function* func = foExpr->get_func();
     csize numArgs = foExpr->num_args();
 
-    for (csize i = 0; i < numArgs; ++i) 
+    for (csize i = 0; i < numArgs; ++i)
     {
       const expr* argExpr = foExpr->get_arg(i);
 
-      if (func->isMap(i)) 
+      if (func->isMap(i))
       {
-        if (argExpr->is_map_internal(e, found) && found) 
+        if (argExpr->is_map_internal(e, found) && found)
         {
           return true;
         }
@@ -1166,13 +1170,13 @@
 ********************************************************************************/
 xqtref_t expr::get_return_type_with_empty_input(const expr* input) const
 {
-  expr_t emptyExpr = new fo_expr(input->get_sctx(),
+  expr* emptyExpr = theCCB->theEM->create_fo_expr(input->get_sctx(),
                                  QueryLoc::null,
                                  GET_BUILTIN_FUNCTION(OP_CONCATENATE_N));
   expr::substitution_t subst;
   subst[input] = emptyExpr;
 
-  expr_t cloneExpr = clone(subst);
+  expr* cloneExpr = clone(subst);
 
   return cloneExpr->get_return_type();
 }

=== modified file 'src/compiler/expression/expr_base.h'
--- src/compiler/expression/expr_base.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/expr_base.h	2012-08-14 12:29:44 +0000
@@ -38,13 +38,12 @@
 class static_context;
 
 class expr;
-typedef rchandle<expr> expr_t;
 
 class wrapper_expr;
-typedef rchandle<wrapper_expr> wrapper_expr_t;
 
 class expr_visitor;
 
+class CompilerCB;
 
 enum expr_kind_t
 {
@@ -85,7 +84,7 @@
   order_expr_kind,
 
 #ifndef ZORBA_NO_FULL_TEXT
-	ft_expr_kind,
+  ft_expr_kind,
 #endif /* ZORBA_NO_FULL_TEXT */
 
   delete_expr_kind,
@@ -121,7 +120,7 @@
 /*******************************************************************************
   Base class for the expression tree node hierarchy
 ********************************************************************************/
-class expr : public SimpleRCObject
+class expr
 {
   friend class expr_iterator_data;
   friend class ExprIterator;
@@ -132,9 +131,7 @@
   friend class function_trace_expr;
 
 public:
-  typedef rchandle<expr> expr_t;
-
-  typedef std::map<const expr *, expr_t> substitution_t;
+  typedef std::map<const expr *, expr*> substitution_t;
 
   typedef substitution_t::iterator subst_iter_t;
 
@@ -170,8 +167,8 @@
 
 
 protected:
-  static expr_t      iter_end_expr;
-  static expr_t    * iter_done;
+  static expr*      iter_end_expr;
+  static expr*    * iter_done;
 
 protected:
   static_context   * theSctx;
@@ -187,6 +184,8 @@
 
   FreeVars           theFreeVars;
 
+  CompilerCB       * theCCB;
+
 public:
   static bool is_sequential(unsigned short theScriptingKind);
 
@@ -194,13 +193,18 @@
 
   static void checkNonUpdating(const expr* e);
 
+  virtual void free() {}
+
+protected:
+  expr(CompilerCB*, static_context*, const QueryLoc&, expr_kind_t);
+
+  expr() : theSctx(NULL), theFlags1(0), theCCB(NULL) {}
+
 public:
-  expr() : theSctx(NULL), theFlags1(0) {}
-
-  expr(static_context*, const QueryLoc&, expr_kind_t);
-
   virtual ~expr();
 
+  CompilerCB* get_ccb() {return theCCB;}
+
   expr_kind_t get_expr_kind() const { return static_cast<expr_kind_t>(theKind); }
 
   const QueryLoc& get_loc() const { return theLoc; }
@@ -237,9 +241,9 @@
 
   xqtref_t get_return_type();
 
-  expr_t clone() const;
+  expr* clone() const;
 
-  virtual expr_t clone(substitution_t& substitution) const;
+  virtual expr* clone(substitution_t& substitution) const;
 
   virtual void accept(expr_visitor& v) = 0;
 
@@ -327,7 +331,7 @@
 
   bool is_nondeterministic() const;
 
-  void replace_expr(const expr* oldExpr, const expr* newExpr);
+  void replace_expr(expr* oldExpr, expr* newExpr);
 
   bool contains_expr(const expr* e) const;
 

=== modified file 'src/compiler/expression/expr_classes.h'
--- src/compiler/expression/expr_classes.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/expr_classes.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,38 +17,38 @@
 #include <zorba/config.h>
 #include "common/shared_types.h"
 
-namespace zorba 
+namespace zorba
 {
-  class order_modifier; 
-  class flwor_expr; 
-  class case_clause; 
-  class if_expr; 
+  class order_modifier;
+  class flwor_expr;
+  class case_clause;
+  class if_expr;
   class fo_expr;
 #ifndef ZORBA_NO_FULL_TEXT
   class ftcontains_expr;
 #endif /* ZORBA_NO_FULL_TEXT */
   class promote_expr;
-  class instanceof_expr; 
-  class treat_expr; 
-  class castable_expr; 
-  class cast_expr; 
+  class instanceof_expr;
+  class treat_expr;
+  class castable_expr;
+  class cast_expr;
   class name_cast_expr;
-  class validate_expr; 
-  class extension_expr; 
+  class validate_expr;
+  class extension_expr;
   class relpath_expr;
-  class axis_step_expr; 
-  class match_expr; 
+  class axis_step_expr;
+  class match_expr;
   class const_expr;
-  class order_expr; 
+  class order_expr;
 
-  class elem_expr; 
+  class elem_expr;
   class doc_expr;
   class attr_expr;
   class text_expr;
   class pi_expr;
 
   class trycatch_expr;
-  class function_item_expr; 
+  class function_item_expr;
   class dynamic_function_invocation_expr;
 
   class insert_expr;
@@ -57,16 +57,16 @@
   class rename_expr;
   class transform_expr;
 
-  class block_expr; 
+  class block_expr;
   class apply_expr;
   class var_decl_expr;
   class var_set_expr;
   class exit_expr;
-  class exit_catcher_expr; 
-  class while_expr; 
+  class exit_catcher_expr;
+  class while_expr;
   class flowctl_expr;
 
-  class eval_expr; 
+  class eval_expr;
   class debugger_expr;
   class function_trace_expr;
   class wrapper_expr;

=== modified file 'src/compiler/expression/expr_consts.h'
--- src/compiler/expression/expr_consts.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/expr_consts.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -17,7 +17,7 @@
 #ifndef ZORBA_COMPILER_EXPR_CONSTS_H
 #define ZORBA_COMPILER_EXPR_CONSTS_H
 
-namespace zorba 
+namespace zorba
 {
 
 
@@ -77,16 +77,16 @@
                                  // expr may return non-empty XDM as well.
 
   VAR_SETTING_EXPR       =   8,  // An expr E during the evaluation of which a
-                                 // var may be set and that var is declared 
+                                 // var may be set and that var is declared
                                  // outside the innermost block that contains E.
 
-  APPLYING_EXPR          =  16,  // An expr during the evaluation of which a 
+  APPLYING_EXPR          =  16,  // An expr during the evaluation of which a
                                  // PUL may get applied.
 
   EXITING_EXPR           =  32,  // An expr during the evaluation of which an
                                  // exit expression may be executed.
 
-  BREAKING_EXPR          =  64,  // An expr E during the evaluation of which 
+  BREAKING_EXPR          =  64,  // An expr E during the evaluation of which
                                  // a break or continue expr may be executed
                                  // and the the while or flwor expr being
                                  // broken or continued contains E.
@@ -105,7 +105,7 @@
 };
 
 
-class CompareConsts 
+class CompareConsts
 {
 public:
   enum CompareType
@@ -121,7 +121,7 @@
 };
 
 
-class ArithmeticConsts 
+class ArithmeticConsts
 {
 public:
   enum OperationKind

=== modified file 'src/compiler/expression/expr_iter.cpp'
--- src/compiler/expression/expr_iter.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/expr_iter.cpp	2012-08-14 12:29:44 +0000
@@ -46,7 +46,7 @@
 do                                                                  \
 {                                                                   \
   theState = __LINE__;                                              \
-  theCurrentChild = reinterpret_cast<expr_t*>(&(subExprHandle));    \
+  theCurrentChild = reinterpret_cast<expr**>(&(subExprHandle));    \
                                                                     \
   if ((subExprHandle) != NULL)                                      \
   {                                                                 \
@@ -99,11 +99,11 @@
 
 void ExprIterator::next()
 {
-  flwor_clause* c;
-  window_clause* wc;
-  orderby_clause* oc;
-  group_clause* gc;
-  flwor_wincond* wincond;
+  flwor_clause* c = NULL;
+  window_clause* wc = NULL;
+  orderby_clause* oc = NULL;
+  group_clause* gc = NULL;
+  flwor_wincond* wincond = NULL;
 
   switch (theExpr->get_expr_kind())
   {

=== modified file 'src/compiler/expression/expr_iter.h'
--- src/compiler/expression/expr_iter.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/expr_iter.h	2012-08-14 12:29:44 +0000
@@ -35,11 +35,11 @@
 protected:
   expr                                 * theExpr;
 
-  expr_t                               * theCurrentChild;
+  expr                                ** theCurrentChild;
   int                                    theState;
 
-  std::vector<expr_t>::iterator          theArgsIter;
-  std::vector<expr_t>::iterator          theArgsEnd;
+  std::vector<expr*>::iterator          theArgsIter;
+  std::vector<expr*>::iterator          theArgsEnd;
 
   flwor_expr::clause_list_t::iterator    theClausesIter;
   flwor_expr::clause_list_t::iterator    theClausesBegin;
@@ -54,9 +54,9 @@
   std::vector<copy_clause_t>::iterator   theCopyClauseEnd;
 
 #ifndef ZORBA_NO_FULL_TEXT
-  std::vector<expr_t*>                   theFTSelectionExprs;
-  std::vector<expr_t*>::iterator         theFTSelectionExprsIter;
-  std::vector<expr_t*>::iterator         theFTSelectionExprsEnd;
+  std::vector<expr**>                   theFTSelectionExprs;
+  std::vector<expr**>::iterator         theFTSelectionExprsIter;
+  std::vector<expr**>::iterator         theFTSelectionExprsEnd;
 #endif /* ZORBA_NO_FULL_TEXT */
 
 public:
@@ -66,7 +66,7 @@
 
   void next();
 
-  expr_t& operator*() const { return *(theCurrentChild); }
+  expr** operator*() const { return (theCurrentChild); }
 
   bool done() const { return theCurrentChild == expr::iter_done; }
 
@@ -87,7 +87,7 @@
   {
   }
 
-  expr* get_expr() const { return theCurrentChild->getp(); }
+  expr* get_expr() const { return *theCurrentChild; }
 };
 
 

=== added file 'src/compiler/expression/expr_manager.cpp'
--- src/compiler/expression/expr_manager.cpp	1970-01-01 00:00:00 +0000
+++ src/compiler/expression/expr_manager.cpp	2012-08-14 12:29:44 +0000
@@ -0,0 +1,840 @@
+/*
+ * Copyright 2006-2012 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "expr_manager.h"
+
+#include "mem_manager.h"
+
+#include "expr.h"
+#include "ftnode.h"
+#include "var_expr.h"
+#include "flwor_expr.h"
+#include "fo_expr.h"
+#include "ft_expr.h"
+#include "function_item_expr.h"
+#include "path_expr.h"
+#include "script_exprs.h"
+#include "update_exprs.h"
+#include "json_exprs.h"
+
+namespace zorba
+{
+
+//A simple expression that can just be deallocated without calling the
+//destructor.
+class NullExpr : public expr
+{
+public:
+  NullExpr() : expr(NULL, NULL, QueryLoc(), unknown_expr_kind){}
+  void accept(expr_visitor& v){}
+  void compute_scripting_kind(){}
+  std::ostream& put(std::ostream& stream) const{return stream;}
+};
+
+
+ExprManager::ExprManager(CompilerCB* ccb)
+  :
+  theCCB(ccb)
+{
+  theExprs.reserve(1024);
+}
+
+
+//calls on the destructors and also keeps tracks of certain numbers
+ExprManager::~ExprManager()
+{
+  for(std::vector<expr*>::iterator iter = theExprs.begin();
+      iter != theExprs.end();
+      ++iter)
+  {
+    //Here we delete all remaining exprs, we assume that they may be "held"
+    //by a reference somewhere.
+    //To prevent deleting an already deleted expr, we replace them with
+    //a NullExpr
+
+    expr* exp = *iter;
+
+    exp->~expr();
+
+    //constructs a new NULLExpr where the old expr existed
+    new (exp) NullExpr();
+  }
+}
+
+
+expr* ExprManager::reg(expr* exp)
+{
+  theExprs.push_back(exp);
+  return exp;
+}
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+#define CREATE_AND_RETURN_EXPR(EXPRTYPE, ...) \
+  EXPRTYPE* EXPPTR = new (theMemoryMgr) EXPRTYPE(theCCB, __VA_ARGS__); \
+  reg(EXPPTR); \
+  return EXPPTR
+
+#define CREATE_AND_RETURN(TYPE, ...) \
+  TYPE* EXPPTR = new (theMemoryMgr) TYPE(__VA_ARGS__); \
+  return EXPPTR
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+
+if_expr* ExprManager::create_if_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* cond_expr,
+    expr* then_expr,
+    expr* else_expr)
+{
+  CREATE_AND_RETURN_EXPR(if_expr, sctx, loc, cond_expr, then_expr, else_expr);
+}
+
+
+order_expr* ExprManager::create_order_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    order_expr::order_type_t order,
+    expr* exp)
+{
+  CREATE_AND_RETURN_EXPR(order_expr, sctx, loc, order, exp);
+}
+
+
+validate_expr* ExprManager::create_validate_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    ParseConstants::validation_mode_t mode,
+    const store::Item_t& aTypeName,
+    expr* validated,
+    rchandle<TypeManager> tm)
+{
+  CREATE_AND_RETURN_EXPR(validate_expr, sctx, loc, mode, aTypeName, validated, tm);
+}
+
+
+cast_expr* ExprManager::create_cast_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* casted,
+    xqtref_t type)
+{
+  CREATE_AND_RETURN_EXPR(cast_expr, sctx, loc, casted, type);
+}
+
+
+treat_expr* ExprManager::create_treat_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* treated,
+    const xqtref_t& type,
+    TreatIterator::ErrorKind err,
+    bool check_prime,
+    store::Item* qname)
+{
+  CREATE_AND_RETURN_EXPR(treat_expr,
+  sctx, loc, treated, type, err, check_prime, qname);
+}
+
+
+promote_expr* ExprManager::create_promote_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* promoted,
+    const xqtref_t& type,
+    PromoteIterator::ErrorKind err,
+    store::Item* qname)
+{
+  CREATE_AND_RETURN_EXPR(promote_expr, sctx, loc, promoted, type, err, qname);
+}
+
+
+castable_expr* ExprManager::create_castable_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* castable,
+    xqtref_t type)
+{
+  CREATE_AND_RETURN_EXPR(castable_expr, sctx, loc, castable, type);
+}
+
+
+instanceof_expr* ExprManager::create_instanceof_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* instanced,
+    xqtref_t type,
+    bool checkPrimeOnly)
+{
+  CREATE_AND_RETURN_EXPR(instanceof_expr,
+          sctx, loc, instanced, type, checkPrimeOnly);
+}
+
+
+name_cast_expr* ExprManager::create_name_cast_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* casted,
+    const namespace_context* ns,
+    bool isAttr)
+{
+  CREATE_AND_RETURN_EXPR(name_cast_expr, sctx, loc, casted, ns, isAttr);
+}
+
+
+doc_expr* ExprManager::create_doc_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* content,
+    bool copyNodes)
+{
+  CREATE_AND_RETURN_EXPR(doc_expr, sctx, loc, content, copyNodes);
+}
+
+
+elem_expr* ExprManager::create_elem_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* qnameExpr,
+    expr* attrs,
+    expr* content,
+    const namespace_context* nsCtx,
+    bool copyNodes)
+{
+  CREATE_AND_RETURN_EXPR(elem_expr,
+          sctx, loc, qnameExpr, attrs, content, nsCtx, copyNodes);
+}
+
+
+elem_expr* ExprManager::create_elem_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* qnameExpr,
+    expr* content,
+    const namespace_context* nsCtx,
+    bool copyNodes)
+{
+  CREATE_AND_RETURN_EXPR(elem_expr,
+          sctx, loc, qnameExpr, content, nsCtx, copyNodes);
+}
+
+
+attr_expr* ExprManager::create_attr_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* aQNameExpr,
+    expr* aValueExpr)
+{
+  CREATE_AND_RETURN_EXPR(attr_expr, sctx, loc, aQNameExpr, aValueExpr);
+}
+
+
+text_expr* ExprManager::create_text_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    text_expr::text_constructor_type textType,
+    expr* text)
+{
+  CREATE_AND_RETURN_EXPR(text_expr, sctx, loc, textType, text);
+}
+
+
+pi_expr* ExprManager::create_pi_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* targetExpr,
+    expr* contentExpr)
+{
+  CREATE_AND_RETURN_EXPR(pi_expr, sctx, loc, targetExpr, contentExpr);
+}
+
+
+const_expr* ExprManager::create_const_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    zstring& sval)
+{
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, sval);
+}
+
+
+const_expr* ExprManager::create_const_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    const std::string& sval)
+{
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, sval);
+}
+
+
+const_expr* ExprManager::create_const_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    const char* sval)
+{
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, sval);
+}
+
+
+const_expr* ExprManager::create_const_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    xs_integer val)
+{
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, val);
+}
+
+
+const_expr* ExprManager::create_const_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    xs_decimal val)
+{
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, val);
+}
+
+
+const_expr* ExprManager::create_const_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    xs_double val)
+{
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, val);
+}
+
+
+const_expr* ExprManager::create_const_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    xs_boolean val)
+{
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, val);
+}
+
+
+const_expr* ExprManager::create_const_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    store::Item_t val)
+{
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, val);
+}
+
+
+const_expr* ExprManager::create_const_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    const char* ns,
+    const char* pre,
+    const char* local)
+{
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, ns, pre, local);
+}
+
+
+extension_expr* ExprManager::create_extension_expr(
+    static_context* sctx,
+    const QueryLoc& loc)
+{
+  CREATE_AND_RETURN_EXPR(extension_expr, sctx, loc);
+}
+
+
+extension_expr* ExprManager::create_extension_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* extended)
+{
+  CREATE_AND_RETURN_EXPR(extension_expr, sctx, loc, extended);
+}
+
+
+catch_clause* ExprManager::create_catch_clause()
+{
+  CREATE_AND_RETURN(catch_clause);
+}
+
+
+trycatch_expr* ExprManager::create_trycatch_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* tryExpr)
+{
+  CREATE_AND_RETURN_EXPR(trycatch_expr, sctx, loc, tryExpr);
+}
+
+
+wrapper_expr* ExprManager::create_wrapper_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* wrapped)
+{
+  CREATE_AND_RETURN_EXPR(wrapper_expr, sctx, loc, wrapped);
+}
+
+
+function_trace_expr* ExprManager::create_function_trace_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* aChild)
+{
+  CREATE_AND_RETURN_EXPR(function_trace_expr, sctx, loc, aChild);
+}
+
+
+function_trace_expr* ExprManager::create_function_trace_expr(expr* aExpr)
+{
+  //this function gets the ExprManager from the expression it recieves.
+  return static_cast<function_trace_expr*>
+      (reg(new (theMemoryMgr) function_trace_expr(aExpr)));
+}
+
+
+eval_expr* ExprManager::create_eval_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* e,
+    expr_script_kind_t scriptingKind,
+    namespace_context* nsCtx)
+{
+  CREATE_AND_RETURN_EXPR(eval_expr, ccb, sctx, loc, e, scriptingKind, nsCtx);
+}
+
+#ifdef ZORBA_WITH_DEBUGGER
+
+debugger_expr* ExprManager::create_debugger_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* aChild,
+    namespace_context* nsCtx,
+    bool aIsVarDeclaration)
+{
+  CREATE_AND_RETURN_EXPR(debugger_expr,
+  sctx, loc, aChild, nsCtx, aIsVarDeclaration);
+}
+
+#endif
+
+////////////////////////////////////////////////////////////////////////////////
+
+var_expr* ExprManager::create_var_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    var_expr::var_kind k,
+    store::Item* name)
+{
+  CREATE_AND_RETURN_EXPR(var_expr, sctx, loc, k, name);
+}
+
+
+var_expr* ExprManager::create_var_expr(const var_expr& source)
+{
+  return static_cast<var_expr*>(reg(new (theMemoryMgr) var_expr(source)));
+}
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+
+#ifdef ZORBA_WITH_JSON
+
+json_array_expr* ExprManager::create_json_array_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* content)
+{
+  CREATE_AND_RETURN_EXPR(json_array_expr, sctx, loc, content);
+}
+
+
+json_object_expr* ExprManager::create_json_object_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* content,
+    bool accumulate)
+{
+  CREATE_AND_RETURN_EXPR(json_object_expr, sctx, loc, content, accumulate);
+}
+
+
+json_direct_object_expr* ExprManager::create_json_direct_object_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<expr*>& names,
+    std::vector<expr*>& values)
+{
+  CREATE_AND_RETURN_EXPR(json_direct_object_expr, sctx, loc, names, values);
+}
+
+
+#endif // ZORBA_WITH_JSON
+
+////////////////////////////////////////////////////////////////////////////////
+
+
+insert_expr* ExprManager::create_insert_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    store::UpdateConsts::InsertType insertType,
+    expr* aSourceExpr,
+    expr* aTargetExpr)
+{
+  CREATE_AND_RETURN_EXPR(insert_expr,
+  sctx, loc, insertType, aSourceExpr, aTargetExpr);
+}
+
+
+delete_expr* ExprManager::create_delete_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* aTargetExpr)
+{
+  CREATE_AND_RETURN_EXPR(delete_expr, sctx, loc, aTargetExpr);
+}
+
+
+replace_expr* ExprManager::create_replace_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    store::UpdateConsts::ReplaceType aType,
+    expr* aSourceExpr,
+    expr* aTargetExpr)
+{
+  CREATE_AND_RETURN_EXPR(replace_expr, sctx, loc, aType, aSourceExpr, aTargetExpr);
+}
+
+
+rename_expr* ExprManager::create_rename_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* aSourceExpr,
+    expr* aTargetExpr)
+{
+  CREATE_AND_RETURN_EXPR(rename_expr, sctx, loc, aSourceExpr, aTargetExpr);
+}
+
+
+copy_clause* ExprManager::create_copy_clause(var_expr* aVar, expr* aExpr)
+{
+  CREATE_AND_RETURN(copy_clause, aVar, aExpr);
+}
+
+
+transform_expr* ExprManager::create_transform_expr(
+    static_context* sctx,
+    const QueryLoc& loc)
+{
+  CREATE_AND_RETURN_EXPR(transform_expr, sctx, loc);
+}
+
+
+block_expr* ExprManager::create_block_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    bool allowLastUpdating,
+    std::vector<expr*>& seq,
+    std::vector<var_expr*>* assignedVars)
+{
+  CREATE_AND_RETURN_EXPR(block_expr,
+  sctx, loc, allowLastUpdating, seq, assignedVars);
+}
+
+
+apply_expr* ExprManager::create_apply_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* inExpr,
+    bool discardXDM)
+{
+  CREATE_AND_RETURN_EXPR(apply_expr, sctx, loc, inExpr, discardXDM);
+}
+
+
+var_decl_expr* ExprManager::create_var_decl_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    var_expr* varExpr,
+    expr* initExpr)
+{
+  CREATE_AND_RETURN_EXPR(var_decl_expr, sctx, loc, varExpr, initExpr);
+}
+
+
+var_set_expr* ExprManager::create_var_set_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    var_expr* varExpr,
+    expr* setExpr)
+{
+  CREATE_AND_RETURN_EXPR(var_set_expr, sctx, loc, varExpr, setExpr);
+}
+
+
+exit_expr* ExprManager::create_exit_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* inExpr)
+{
+  CREATE_AND_RETURN_EXPR(exit_expr, sctx, loc, inExpr);
+}
+
+
+exit_catcher_expr* ExprManager::create_exit_catcher_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* inExpr,
+    std::vector<expr*>& exitExprs)
+{
+  CREATE_AND_RETURN_EXPR(exit_catcher_expr, sctx, loc, inExpr, exitExprs);
+}
+
+
+flowctl_expr* ExprManager::create_flowctl_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    flowctl_expr::action action)
+{
+  CREATE_AND_RETURN_EXPR(flowctl_expr, sctx, loc, action);
+}
+
+
+while_expr* ExprManager::create_while_expr(
+      static_context* sctx, const QueryLoc& loc, expr* body)
+{
+  CREATE_AND_RETURN_EXPR(while_expr, sctx, loc, body);
+}
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+relpath_expr* ExprManager::create_relpath_expr(
+     static_context* sctx,
+     const QueryLoc& loc)
+{
+  CREATE_AND_RETURN_EXPR(relpath_expr, sctx, loc);
+}
+
+
+axis_step_expr* ExprManager::create_axis_step_expr(
+    static_context* sctx,
+    const QueryLoc& loc)
+{
+  CREATE_AND_RETURN_EXPR(axis_step_expr, sctx, loc);
+}
+
+
+match_expr* ExprManager::create_match_expr(
+    static_context* sctx,
+    const QueryLoc& loc)
+{
+  CREATE_AND_RETURN_EXPR(match_expr, sctx, loc);
+}
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+dynamic_function_invocation_expr*
+ExprManager::create_dynamic_function_invocation_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* anExpr,
+    const std::vector<expr*>& args)
+{
+  CREATE_AND_RETURN_EXPR(dynamic_function_invocation_expr, sctx, loc, anExpr, args);
+}
+
+
+function_item_expr* ExprManager::create_function_item_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    const store::Item* aQName,
+    function* f,
+    uint32_t aArity)
+{
+  CREATE_AND_RETURN_EXPR(function_item_expr, sctx, loc, aQName, f, aArity);
+}
+
+
+function_item_expr* ExprManager::create_function_item_expr(
+    static_context* sctx,
+    const QueryLoc& loc)
+{
+  CREATE_AND_RETURN_EXPR(function_item_expr, sctx, loc);
+}
+
+
+ftcontains_expr* ExprManager::create_ftcontains_expr(
+    static_context* sctx,
+    QueryLoc const& loc,
+    expr* range,
+    ftnode *ftselection,
+    expr* ftignore)
+{
+  CREATE_AND_RETURN_EXPR(ftcontains_expr, sctx, loc, range, ftselection, ftignore);
+}
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+//this calls the static create_seq within fo_expr
+fo_expr* ExprManager::create_seq(static_context* sctx, const QueryLoc& loc)
+{
+  //TODO make fo_expr use this factory to generate everything
+  return fo_expr::create_seq(theCCB, sctx, loc);
+}
+
+
+fo_expr* ExprManager::create_fo_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    const function* f,
+    expr* arg)
+{
+  CREATE_AND_RETURN_EXPR(fo_expr, sctx, loc, f, arg);
+}
+
+
+fo_expr* ExprManager::create_fo_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    const function* f,
+    expr* arg1,
+    expr* arg2)
+{
+  CREATE_AND_RETURN_EXPR(fo_expr, sctx, loc, f, arg1, arg2);
+}
+
+
+fo_expr* ExprManager::create_fo_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    const function* f,
+    const std::vector<expr*>& args)
+{
+  CREATE_AND_RETURN_EXPR(fo_expr, sctx, loc, f, args);
+}
+
+fo_expr* ExprManager::create_fo_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    const function* f)
+{
+
+  CREATE_AND_RETURN_EXPR(fo_expr, sctx, loc, f);
+}
+////////////////////////////////////////////////////////////////////////////////
+
+for_clause* ExprManager::create_for_clause(
+    static_context* sctx,
+    const QueryLoc& loc,
+    var_expr* varExpr,
+    expr* domainExpr,
+    var_expr* posVarExpr,
+    var_expr* scoreVarExpr,
+    bool isOuter)
+{
+  CREATE_AND_RETURN(for_clause,
+          sctx, theCCB, loc, varExpr, domainExpr, posVarExpr, scoreVarExpr, isOuter);
+}
+
+let_clause* ExprManager::create_let_clause(
+    static_context* sctx,
+    const QueryLoc& loc,
+    var_expr* varExpr,
+    expr* domainExpr,
+    bool lazy)
+{
+  CREATE_AND_RETURN(let_clause, sctx, theCCB, loc, varExpr, domainExpr, lazy);
+}
+
+window_clause* ExprManager::create_window_clause(
+    static_context* sctx,
+    const QueryLoc& loc,
+    window_clause::window_t winKind,
+    var_expr* varExpr,
+    expr* domainExpr,
+    flwor_wincond_t winStart,
+    flwor_wincond_t winStop,
+    bool lazy)
+{
+  CREATE_AND_RETURN(window_clause,
+          sctx, theCCB, loc, winKind, varExpr, domainExpr, winStart, winStop, lazy);
+}
+
+flwor_wincond* ExprManager::create_flwor_wincond(
+  static_context* sctx,
+  bool isOnly,
+  const flwor_wincond::vars& in_vars,
+  const flwor_wincond::vars& out_vars,
+  expr* cond)
+{
+  CREATE_AND_RETURN(flwor_wincond, theCCB, sctx, isOnly, in_vars, out_vars, cond);
+}
+
+group_clause* ExprManager::create_group_clause(
+    static_context* sctx,
+    const QueryLoc& loc,
+    const flwor_clause::rebind_list_t& gvars,
+    flwor_clause::rebind_list_t ngvars,
+    const std::vector<std::string>& collations)
+{
+  CREATE_AND_RETURN(group_clause, sctx, loc, gvars, ngvars, collations);
+}
+
+orderby_clause* ExprManager::create_orderby_clause(
+  static_context* sctx,
+  const QueryLoc& loc,
+  bool stable,
+  const std::vector<OrderModifier>& modifiers,
+  const std::vector<expr*>& orderingExprs)
+{
+  CREATE_AND_RETURN(orderby_clause, sctx, loc, stable, modifiers, orderingExprs);
+}
+
+materialize_clause* ExprManager::create_materialize_clause(
+      static_context* sctx, const QueryLoc& loc)
+{
+  CREATE_AND_RETURN(materialize_clause, sctx, loc);
+}
+
+count_clause* ExprManager::create_count_clause(
+      static_context* sctx, const QueryLoc& loc, var_expr* var)
+{
+  CREATE_AND_RETURN(count_clause, sctx, loc, var);
+}
+
+where_clause* ExprManager::create_where_clause(
+      static_context* sctx, const QueryLoc& loc, expr* where)
+{
+  CREATE_AND_RETURN(where_clause, sctx, loc, where);
+}
+
+flwor_expr* ExprManager::create_flwor_expr(
+      static_context* sctx, const QueryLoc& loc, bool general)
+{
+  CREATE_AND_RETURN_EXPR(flwor_expr, sctx, loc, general);
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+
+} // namespace zorba
+

=== added file 'src/compiler/expression/expr_manager.h'
--- src/compiler/expression/expr_manager.h	1970-01-01 00:00:00 +0000
+++ src/compiler/expression/expr_manager.h	2012-08-14 12:29:44 +0000
@@ -0,0 +1,528 @@
+/*
+ * Copyright 2006-2012 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#ifndef ZORBA_COMPILER_EXPRMANAGER_H
+#define ZORBA_COMPILER_EXPRMANAGER_H
+
+#include "expr_classes.h"
+#include "expr.h"
+#include "script_exprs.h"
+#include "flwor_expr.h"
+#include "ftnode.h"
+
+#include "mem_manager.h"
+
+namespace zorba
+{
+
+class CompilerCB;
+
+class ExprManager
+{
+private:
+  std::vector<expr*>   theExprs;
+  MemoryManager        theMemoryMgr;
+  CompilerCB         * theCCB;
+
+public:
+  ExprManager(CompilerCB* ccb);
+
+  ~ExprManager();
+
+  expr* reg(expr*);
+
+private:
+  //An ExprManager is the only object to handle a collection of Exprs and
+  //the memory in which they recide. Copying it in a senseful way would.
+  //require copying all the memory, which is costly and useless.
+  ExprManager(const ExprManager&);
+  ExprManager& operator= (const ExprManager&);
+
+public:
+  MemoryManager& getMemory() { return theMemoryMgr; }
+
+  csize numExprs() const { return theExprs.size(); }
+
+public:
+  if_expr* create_if_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* cond_expr,
+      expr* then_expr,
+      expr* else_expr);
+
+  order_expr* create_order_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      order_expr::order_type_t,
+      expr*);
+
+  validate_expr* create_validate_expr(
+      static_context*,
+      const QueryLoc&,
+      ParseConstants::validation_mode_t,
+      const store::Item_t& aTypeName,
+      expr* validated,
+      rchandle<TypeManager>);
+
+  cast_expr* create_cast_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr*,
+      xqtref_t);
+
+  treat_expr* create_treat_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* input,
+      const xqtref_t& type,
+      TreatIterator::ErrorKind err,
+      bool check_prime = true,
+      store::Item* qnname = NULL);
+
+
+  promote_expr* create_promote_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* input,
+      const xqtref_t& type,
+      PromoteIterator::ErrorKind err,
+      store::Item* qname);
+
+  castable_expr* create_castable_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr*,
+      xqtref_t);
+
+  instanceof_expr* create_instanceof_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr*,
+      xqtref_t,
+      bool checkPrimeOnly = false);
+
+  name_cast_expr* create_name_cast_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr*,
+      const namespace_context*,
+      bool isAttr);
+
+  doc_expr* create_doc_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr* content,
+      bool copyNodes);
+
+  elem_expr* create_elem_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr* qnameExpr,
+      expr* attrs,
+      expr* content,
+      const namespace_context* nsCtx,
+      bool copyNodes);
+
+  elem_expr* create_elem_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr* qnameExpr,
+      expr* content,
+      const namespace_context* nsCtx,
+      bool copyNodes);
+
+  attr_expr* create_attr_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* aQNameExpr,
+      expr* aValueExpr);
+
+  text_expr* create_text_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      text_expr::text_constructor_type,
+      expr*);
+
+  pi_expr* create_pi_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr*,
+      expr*);
+
+  const_expr* create_const_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      zstring& sval);
+
+  const_expr* create_const_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      const std::string& sval);
+
+  const_expr* create_const_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      const char* sval);
+
+  const_expr* create_const_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      xs_integer);
+
+  const_expr* create_const_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      xs_decimal);
+
+  const_expr* create_const_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      xs_double);
+
+  const_expr* create_const_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      xs_boolean);
+
+  const_expr* create_const_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      store::Item_t);
+
+  const_expr* create_const_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      const char* ns,
+      const char* pre,
+      const char* local);
+
+  extension_expr* create_extension_expr(
+      static_context* sctx,
+      const QueryLoc&);
+
+  extension_expr* create_extension_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr*);
+
+  catch_clause* create_catch_clause();
+
+  trycatch_expr* create_trycatch_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr* tryExpr);
+
+  wrapper_expr* create_wrapper_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* wrapped);
+
+  function_trace_expr* create_function_trace_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* aChild);
+
+  function_trace_expr* create_function_trace_expr(expr* aExpr);
+
+  eval_expr* create_eval_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* e,
+      expr_script_kind_t scriptingKind,
+      namespace_context* nsCtx);
+
+#ifdef ZORBA_WITH_DEBUGGER
+  debugger_expr* create_debugger_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* aChild,
+      namespace_context* nsCtx,
+      bool aIsVarDeclaration);
+#endif
+
+////////////////////////////////////////////////////////////////////////////////
+
+  var_expr* create_var_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      var_expr::var_kind k,
+      store::Item* name);
+
+  var_expr* create_var_expr(const var_expr& source);
+
+////////////////////////////////////////////////////////////////////////////////
+
+#ifdef ZORBA_WITH_JSON
+
+  json_array_expr* create_json_array_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* content);
+
+  json_object_expr* create_json_object_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* content,
+      bool accumulate);
+
+  json_direct_object_expr* create_json_direct_object_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      std::vector<expr*>& names,
+      std::vector<expr*>& values);
+
+#endif
+
+////////////////////////////////////////////////////////////////////////////////
+
+  insert_expr* create_insert_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      store::UpdateConsts::InsertType,
+      expr* aSourceExpr,
+      expr* aTargetExpr);
+
+  delete_expr* create_delete_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr*);
+
+  replace_expr* create_replace_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      store::UpdateConsts::ReplaceType aType,
+      expr*,
+      expr*);
+
+  rename_expr* create_rename_expr(
+      static_context* sctx,
+      const QueryLoc&,
+      expr*,
+      expr*);
+
+  copy_clause* create_copy_clause(var_expr* aVar, expr* aExpr);
+
+  transform_expr* create_transform_expr(
+      static_context* sctx,
+      const QueryLoc& loc);
+
+  block_expr* create_block_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      bool allowLastUpdating,
+      std::vector<expr*>& seq,
+      std::vector<var_expr*>* assignedVars);
+
+  apply_expr* create_apply_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* inExpr,
+      bool discardXDM);
+
+  var_decl_expr* create_var_decl_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      var_expr* varExpr,
+      expr* initExpr);
+
+  var_set_expr* create_var_set_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      var_expr* varExpr,
+      expr* setExpr);
+
+  exit_expr* create_exit_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* inExpr);
+
+  exit_catcher_expr* create_exit_catcher_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* inExpr,
+      std::vector<expr*>& exitExprs);
+
+  flowctl_expr* create_flowctl_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      flowctl_expr::action action);
+
+  while_expr* create_while_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* body);
+
+////////////////////////////////////////////////////////////////////////////////
+
+  relpath_expr* create_relpath_expr(static_context* sctx, const QueryLoc& loc);
+
+  axis_step_expr* create_axis_step_expr(static_context* sctx, const QueryLoc&);
+
+  match_expr* create_match_expr(static_context* sctx, const QueryLoc&);
+
+////////////////////////////////////////////////////////////////////////////////
+
+  dynamic_function_invocation_expr* create_dynamic_function_invocation_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* anExpr,
+      const std::vector<expr*>& args);
+
+  function_item_expr* create_function_item_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      const store::Item* aQName,
+      function* f,
+      uint32_t aArity);
+
+  function_item_expr* create_function_item_expr(
+      static_context* sctx,
+      const QueryLoc& loc);
+
+  ftcontains_expr* create_ftcontains_expr(
+      static_context*,
+      QueryLoc const&,
+      expr* range,
+      ftnode *ftselection,
+      expr* ftignore);
+
+////////////////////////////////////////////////////////////////////////////////
+
+  //this calls the static create_seq within fo_expr
+  fo_expr* create_seq(static_context* sctx, const QueryLoc &);
+
+  fo_expr* create_fo_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      const function* f,
+      expr* arg);
+
+  fo_expr* create_fo_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      const function* f,
+      expr* arg1,
+      expr* arg2);
+
+  fo_expr* create_fo_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      const function* f,
+      const std::vector<expr*>& args);
+
+  fo_expr* create_fo_expr(
+    static_context* sctx,
+    const QueryLoc& loc,
+    const function* f);
+
+////////////////////////////////////////////////////////////////////////////////
+
+  for_clause* create_for_clause(
+      static_context* sctx,
+      const QueryLoc& loc,
+      var_expr* varExpr,
+      expr* domainExpr,
+      var_expr* posVarExpr = NULL,
+      var_expr* scoreVarExpr = NULL,
+      bool isOuter = false);
+
+  let_clause* create_let_clause(
+      static_context* sctx,
+      const QueryLoc& loc,
+      var_expr* varExpr,
+      expr* domainExpr,
+      bool lazy = false);
+
+  window_clause* create_window_clause(
+      static_context* sctx,
+      const QueryLoc& loc,
+      window_clause::window_t winKind,
+      var_expr* varExpr,
+      expr* domainExpr,
+      flwor_wincond_t winStart,
+      flwor_wincond_t winStop,
+      bool lazy = false);
+
+  flwor_wincond* create_flwor_wincond(
+      static_context* sctx,
+      bool isOnly,
+      const flwor_wincond::vars& in_vars,
+      const flwor_wincond::vars& out_vars,
+      expr* cond);
+
+  group_clause* create_group_clause(
+      static_context* sctx,
+      const QueryLoc& loc,
+      const flwor_clause::rebind_list_t& gvars,
+      flwor_clause::rebind_list_t ngvars,
+      const std::vector<std::string>& collations);
+
+  orderby_clause * create_orderby_clause (
+      static_context* sctx,
+      const QueryLoc& loc,
+      bool stable,
+      const std::vector<OrderModifier>& modifiers,
+      const std::vector<expr*>& orderingExprs);
+
+  materialize_clause* create_materialize_clause(
+      static_context* sctx,
+      const QueryLoc& loc);
+
+  count_clause* create_count_clause(
+      static_context* sctx,
+      const QueryLoc& loc,
+      var_expr* var);
+
+  where_clause* create_where_clause(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* where);
+
+  flwor_expr* create_flwor_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      bool general);
+};
+
+////////////////////////////////////////////////////////////////////////////////
+
+#ifdef ZORBA_WITH_JSON
+
+json_array_expr* create_json_array_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* content);
+
+json_object_expr* create_json_object_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* content,
+      bool accumulate);
+
+json_direct_object_expr* create_json_direct_object_expr(
+      static_context* sctx,
+      const QueryLoc& loc,
+      std::vector<expr*>& names,
+      std::vector<expr*>& values);
+
+#endif
+
+} // namespace zorba
+
+#endif // ZORBA_COMPILER_EXPRMANAGER_H

=== modified file 'src/compiler/expression/expr_put.cpp'
--- src/compiler/expression/expr_put.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/expr_put.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -50,7 +50,7 @@
 
 using namespace std;
 
-namespace zorba 
+namespace zorba
 {
 
 #define BEGIN_PUT_NO_LOCATION(LABEL) \
@@ -79,7 +79,7 @@
   if ( !(EXPR) ) ; else { os << indent << (LABEL) << "\n" << inc_indent; (EXPR)->put(os); os << dec_indent; }
 
 
-static inline zstring qname_to_string(store::Item_t qname) 
+static inline zstring qname_to_string(store::Item_t qname)
 {
   zstring result;
   zstring pfx = qname->getPrefix();
@@ -91,7 +91,7 @@
 }
 
 
-static inline ostream& put_qname(store::Item_t qname, ostream& os) 
+static inline ostream& put_qname(store::Item_t qname, ostream& os)
 {
   zstring pfx = qname->getPrefix();
   zstring ns = qname->getNamespace();
@@ -102,13 +102,13 @@
 }
 
 
-static inline string expr_addr(const void* e) 
+static inline string expr_addr(const void* e)
 {
   if (Properties::instance()->noTreeIds ())
   {
     return "";
   }
-  else 
+  else
   {
     ostringstream os;
     os << " (" << e << ")";
@@ -117,7 +117,7 @@
 }
 
 
-static inline string expr_loc(const expr* e) 
+static inline string expr_loc(const expr* e)
 {
   if (e == NULL)
     return "";
@@ -128,7 +128,7 @@
     os << " (loc: " << e->get_loc().getLineBegin() << ", " << e->get_loc().getColumnBegin() << ")";
     return os.str ();
   }
-  else 
+  else
   {
     return "";
   }
@@ -173,7 +173,7 @@
 ostream& block_expr::put( ostream& os) const
 {
   BEGIN_PUT( block_expr );
-  for (checked_vector<expr_t>::const_iterator i = this->theArgs.begin ();
+  for (checked_vector<expr*>::const_iterator i = this->theArgs.begin ();
        i != theArgs.end (); i++)
     (*i)->put (os);
   END_PUT();
@@ -189,7 +189,7 @@
   }
 
 #if VERBOSE
-  if (theDeclaredType != NULL) 
+  if (theDeclaredType != NULL)
   {
     os << " type=" << theDeclaredType->toString();
   }
@@ -216,13 +216,13 @@
 
   put_qname(theVarExpr->get_name(), os);
 
-  os << expr_addr(theVarExpr.getp());
+  os << expr_addr(theVarExpr);
 
   if (thePosVarExpr != NULL)
   {
     os << " AT ";
     put_qname(thePosVarExpr->get_name(), os);
-    os << expr_addr(thePosVarExpr.getp());
+    os << expr_addr(thePosVarExpr);
   }
   os << endl << indent << "[\n" << inc_indent;
 
@@ -248,7 +248,7 @@
 
   put_qname(theVarExpr->get_name(), os);
 
-  os << expr_addr(theVarExpr.getp());
+  os << expr_addr(theVarExpr);
 
   os << endl << indent << "[\n" << inc_indent;
 
@@ -289,13 +289,13 @@
 }
 
 
-ostream& group_clause::put(ostream& os) const 
+ostream& group_clause::put(ostream& os) const
 {
   BEGIN_PUT(group_clause);
 
   os << indent << "GROUP BY EXPRS";
 
-  for (unsigned i = 0; i < theGroupVars.size(); i++) 
+  for (unsigned i = 0; i < theGroupVars.size(); i++)
   {
     PUT_SUB("", theGroupVars[i].first);
     os << inc_indent << indent << "-->" << dec_indent;
@@ -304,18 +304,18 @@
 
   os << indent << "NON GROUP BY VARS ";
 
-  for (unsigned i = 0; i < theNonGroupVars.size(); i++) 
+  for (unsigned i = 0; i < theNonGroupVars.size(); i++)
   {
     PUT_SUB("", theNonGroupVars[i].first);
     os << inc_indent << indent << "-->" << dec_indent;
     theNonGroupVars[i].second->put(os) << endl;
   }
-  
+
   END_PUT();
 }
 
 
-ostream& orderby_clause::put(ostream& os) const 
+ostream& orderby_clause::put(ostream& os) const
 {
   BEGIN_PUT(orderby_clause);
 
@@ -323,7 +323,7 @@
 
   csize numColumns = num_columns();
 
-  for (csize i = 0; i < numColumns; i++) 
+  for (csize i = 0; i < numColumns; i++)
   {
     theOrderingExprs[i]->put(os);
   }
@@ -331,12 +331,12 @@
   os << endl;
 
   os << indent << "VAR REBINDS ";
-  for (unsigned i = 0; i < theRebindList.size (); i++) 
+  for (unsigned i = 0; i < theRebindList.size (); i++)
   {
     os << "$";
     put_qname(theRebindList[i].first->get_varname(), os);
-    os << " (" << theRebindList[i].first.getp() << " -> " 
-       << theRebindList[i].second.getp() << ") ";
+    os << " (" << theRebindList[i].first << " -> "
+       << theRebindList[i].second << ") ";
   }
   os << endl;
 #endif
@@ -344,7 +344,7 @@
 }
 
 
-ostream& materialize_clause::put(ostream& os) const 
+ostream& materialize_clause::put(ostream& os) const
 {
   BEGIN_PUT(materialize_clause);
 
@@ -356,7 +356,7 @@
 {
   BEGIN_PUT(flwor_expr);
 
-  for (csize i = 0; i < num_clauses(); i++) 
+  for (csize i = 0; i < num_clauses(); i++)
   {
     const flwor_clause& c = *(get_clause(i));
 
@@ -367,9 +367,9 @@
       PUT_SUB( "WHERE", static_cast<const where_clause *>(&c)->get_expr() );
       break;
     }
-    case flwor_clause::count_clause: 
+    case flwor_clause::count_clause:
     {
-      os << indent << "COUNT $"; 
+      os << indent << "COUNT $";
       put_qname(static_cast<const count_clause *>(&c)->get_var()->get_name(), os);
       os << endl;
       break;
@@ -412,11 +412,11 @@
   }
 
   os << indent << "RETURN\n" << inc_indent;
-  if (theReturnExpr == NULL) 
+  if (theReturnExpr == NULL)
   {
     os << indent << "NULL";
   }
-  else 
+  else
   {
     theReturnExpr->put(os);
   }
@@ -460,7 +460,7 @@
     os << endl << inc_indent;
     if (theArgs[i])
       theArgs[i]->put(os);
-    os << dec_indent << indent << "]" << endl; 
+    os << dec_indent << indent << "]" << endl;
   }
   theExpr->put (os);
   END_PUT();
@@ -531,7 +531,7 @@
 
 
 #ifndef ZORBA_NO_FULL_TEXT
-ostream& ftcontains_expr::put( ostream &os ) const 
+ostream& ftcontains_expr::put( ostream &os ) const
 {
   BEGIN_PUT( ftcontains_expr );
   PUT_SUB( "RANGE", range_ );
@@ -614,7 +614,7 @@
 {
   BEGIN_PUT( validate_expr );
 
-  switch (theMode) 
+  switch (theMode)
   {
   case ParseConstants::val_strict: os << "strict\n"; break;
   case ParseConstants::val_lax: os << "lax\n"; break;
@@ -641,10 +641,10 @@
 ostream& relpath_expr::put( ostream& os) const
 {
   BEGIN_PUT( relpath_expr );
-  
-  for (std::vector<expr_t>::const_iterator it = begin(); it != end(); ++it)
+
+  for (std::vector<expr*>::const_iterator it = begin(); it != end(); ++it)
   {
-    expr_t expr = *it;
+    expr* expr = *it;
     if (it == begin ())
     {
       expr->put (os);
@@ -683,7 +683,7 @@
 
   os << "::";
 
-  if (theNodeTest != NULL) 
+  if (theNodeTest != NULL)
   {
     theNodeTest->put(os);
   }
@@ -777,7 +777,7 @@
   os << indent << "order_expr" << expr_addr (this) << "\n" << inc_indent
      << indent << "[ ";
 
-  switch (theType) 
+  switch (theType)
   {
   case ordered: os << "ordered\n"; break;
   case unordered: os << "unordered\n"; break;
@@ -869,9 +869,9 @@
 {
   BEGIN_PUT(json_direct_object_expr);
 
-  std::vector<expr_t>::const_iterator ite1 = theNames.begin();
-  std::vector<expr_t>::const_iterator end1 = theNames.end();
-  std::vector<expr_t>::const_iterator ite2 = theValues.begin();
+  std::vector<expr*>::const_iterator ite1 = theNames.begin();
+  std::vector<expr*>::const_iterator end1 = theNames.end();
+  std::vector<expr*>::const_iterator ite2 = theValues.begin();
   for (; ite1 != end1; ++ite1, ++ite2)
   {
     (*ite1)->put(os);

=== modified file 'src/compiler/expression/expr_type.cpp'
--- src/compiler/expression/expr_type.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/expr_type.cpp	2012-08-14 12:29:44 +0000
@@ -80,7 +80,7 @@
     ExprIterator iter(this);
     while (!iter.done())
     {
-      (*iter)->compute_return_type(deep, modified);
+      (**iter)->compute_return_type(deep, modified);
       iter.next();
     }
   }
@@ -168,7 +168,7 @@
     var_expr::var_kind varKind = e->get_kind();
 
     xqtref_t derivedType;
-    expr* domainExpr;
+    expr* domainExpr = NULL;
 
     // The translator has already set theDeclaredType of pos_vars, count_vars,
     // wincond_out_pos_vars, and wincond_in_pos_vars to xs:positiveInteger.
@@ -258,9 +258,9 @@
       {
         xqtref_t stepType = sourceType;
 
-        for (csize i = 1; i < e->size(); ++i) 
+        for (csize i = 1; i < e->size(); ++i)
         {
-          const axis_step_expr* axisStep = e->theSteps[i].cast<axis_step_expr>();
+          const axis_step_expr* axisStep = static_cast<axis_step_expr*>(e->theSteps[i]);
 
           stepType = axis_step_type(theSctx,
                                     axisStep,
@@ -325,7 +325,7 @@
     }
     case FunctionConsts::FN_SUBSEQUENCE_3:
     {
-      const_expr* lenExpr = dynamic_cast<const_expr*>(e->theArgs[2].getp());
+      const_expr* lenExpr = dynamic_cast<const_expr*>(e->theArgs[2]);
 
       if (lenExpr != NULL)
       {
@@ -465,7 +465,7 @@
   case doc_expr_kind:
   {
     contentType = (theSctx->construction_mode() == StaticContextConsts::cons_preserve ?
-                   rtm.ANY_TYPE : 
+                   rtm.ANY_TYPE :
                    rtm.UNTYPED_TYPE);
 
     newType = tm->create_node_type(store::StoreConsts::documentNode,

=== modified file 'src/compiler/expression/flwor_expr.cpp'
--- src/compiler/expression/flwor_expr.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/flwor_expr.cpp	2012-08-14 12:29:44 +0000
@@ -26,6 +26,8 @@
 #include "compiler/expression/expr.h"
 #include "compiler/expression/expr_visitor.h"
 
+#include "compiler/api/compilercb.h"
+
 #include "types/root_typemanager.h"
 #include "types/typeops.h"
 
@@ -44,14 +46,16 @@
 ********************************************************************************/
 forletwin_clause::forletwin_clause(
     static_context* sctx,
+    CompilerCB* ccb,
     const QueryLoc& loc,
     flwor_clause::ClauseKind kind,
-    var_expr_t varExpr,
-    expr_t domainExpr)
+    var_expr* varExpr,
+    expr* domainExpr)
   :
   flwor_clause(sctx, loc, kind),
   theVarExpr(varExpr),
-  theDomainExpr(domainExpr)
+  theDomainExpr(domainExpr),
+  theCCB(ccb)
 {
   if (theVarExpr != NULL)
     theVarExpr->set_flwor_clause(this);
@@ -68,13 +72,13 @@
 }
 
 
-void forletwin_clause::set_expr(expr_t v)
+void forletwin_clause::set_expr(expr* v)
 {
   theDomainExpr = v;
 }
 
 
-void forletwin_clause::set_var(var_expr_t v)
+void forletwin_clause::set_var(var_expr* v)
 {
   theVarExpr = v;
 
@@ -111,14 +115,15 @@
 ********************************************************************************/
 for_clause::for_clause(
     static_context* sctx,
+    CompilerCB* ccb,
     const QueryLoc& loc,
-    var_expr_t varExpr,
-    expr_t domainExpr,
-    var_expr_t posVarExpr,
-    var_expr_t scoreVarExpr,
+    var_expr* varExpr,
+    expr* domainExpr,
+    var_expr* posVarExpr,
+    var_expr* scoreVarExpr,
     bool isAllowingEmpty)
   :
-  forletwin_clause(sctx, loc, flwor_clause::for_clause, varExpr, domainExpr),
+  forletwin_clause(sctx, ccb, loc, flwor_clause::for_clause, varExpr, domainExpr),
   thePosVarExpr(posVarExpr),
   theScoreVarExpr(scoreVarExpr),
   theAllowingEmpty(isAllowingEmpty)
@@ -161,11 +166,11 @@
                          *declaredType));
           }
 
-          domainExpr = new treat_expr(sctx,
-                                      loc,
-                                      domainExpr,
-                                      declaredType,
-                                      TreatIterator::TYPE_MATCH);
+          domainExpr = theCCB->theEM->create_treat_expr(sctx,
+                                            loc,
+                                            domainExpr,
+                                            declaredType,
+                                            TreatIterator::TYPE_MATCH);
 
           set_expr(domainExpr);
         }
@@ -187,17 +192,17 @@
 
 var_expr* for_clause::get_pos_var() const
 {
-  return thePosVarExpr.getp();
+  return thePosVarExpr;
 }
 
 
 var_expr* for_clause::get_score_var() const
 {
-  return theScoreVarExpr.getp();
+  return theScoreVarExpr;
 }
 
 
-void for_clause::set_pos_var(var_expr_t v)
+void for_clause::set_pos_var(var_expr* v)
 {
   thePosVarExpr = v;
   if (thePosVarExpr != NULL)
@@ -205,7 +210,7 @@
 }
 
 
-void for_clause::set_score_var(var_expr_t v)
+void for_clause::set_score_var(var_expr* v)
 {
   theScoreVarExpr = v;
   if (theScoreVarExpr != NULL)
@@ -215,28 +220,29 @@
 
 flwor_clause_t for_clause::clone(expr::substitution_t& subst) const
 {
-  expr_t domainCopy = theDomainExpr->clone(subst);
-
-  var_expr_t varCopy(new var_expr(*theVarExpr));
-  subst[theVarExpr.getp()] = varCopy.getp();
-
-  var_expr_t posvarCopy;
-  var_expr* pos_var_ptr = thePosVarExpr.getp();
+  expr* domainCopy = theDomainExpr->clone(subst);
+
+  var_expr* varCopy = theCCB->theEM->create_var_expr(*theVarExpr);
+  subst[theVarExpr] = varCopy;
+
+  var_expr* posvarCopy = NULL;
+  var_expr* pos_var_ptr = thePosVarExpr;
   if (pos_var_ptr)
   {
-    posvarCopy = new var_expr(*pos_var_ptr);
-    subst[pos_var_ptr] = posvarCopy.getp();
+    posvarCopy = theCCB->theEM->create_var_expr(*pos_var_ptr);
+    subst[pos_var_ptr] = posvarCopy;
   }
 
-  var_expr_t scorevarCopy;
-  var_expr* score_var_ptr = theScoreVarExpr.getp();
+  var_expr* scorevarCopy = NULL;
+  var_expr* score_var_ptr = theScoreVarExpr;
   if (score_var_ptr)
   {
-    scorevarCopy = new var_expr(*score_var_ptr);
-    subst[score_var_ptr] = scorevarCopy.getp();
+    scorevarCopy = theCCB->theEM->create_var_expr(*score_var_ptr);
+    subst[score_var_ptr] = scorevarCopy;
   }
 
   return new for_clause(theContext,
+                        theCCB,
                         get_loc(),
                         varCopy,
                         domainCopy,
@@ -251,12 +257,13 @@
 ********************************************************************************/
 let_clause::let_clause(
     static_context* sctx,
+    CompilerCB* ccb,
     const QueryLoc& loc,
-    var_expr_t varExpr,
-    expr_t domainExpr,
+    var_expr* varExpr,
+    expr* domainExpr,
     bool lazy)
   :
-  forletwin_clause(sctx, loc, flwor_clause::let_clause, varExpr, domainExpr),
+  forletwin_clause(sctx, ccb, loc, flwor_clause::let_clause, varExpr, domainExpr),
   theScoreVarExpr(NULL),
   theLazyEval(lazy)
 {
@@ -285,7 +292,7 @@
           ERROR_PARAMS(ZED(BadType_23o), *domainType, ZED(NoTreatAs_4), *declaredType));
         }
 
-        domainExpr = new treat_expr(sctx,
+        domainExpr = theCCB->theEM->create_treat_expr(sctx,
                                     loc,
                                     domainExpr,
                                     declaredType,
@@ -307,11 +314,11 @@
 
 var_expr* let_clause::get_score_var() const
 {
-  return theScoreVarExpr.getp();
+  return theScoreVarExpr;
 }
 
 
-void let_clause::set_score_var(var_expr_t v)
+void let_clause::set_score_var(var_expr* v)
 {
   theScoreVarExpr = v;
   if (theScoreVarExpr != NULL)
@@ -321,22 +328,27 @@
 
 flwor_clause_t let_clause::clone(expr::substitution_t& subst) const
 {
-  expr_t domainCopy = theDomainExpr->clone(subst);
+  expr* domainCopy = theDomainExpr->clone(subst);
 
-  var_expr_t varCopy(new var_expr(*theVarExpr));
-  subst[theVarExpr.getp()] = varCopy.getp();
+  var_expr* varCopy = theCCB->theEM->create_var_expr(*theVarExpr);
+  subst[theVarExpr] = varCopy;
 
 #if 0
-  var_expr_t scorevarCopy;
-  var_expr* score_var_ptr = theScoreVarExpr.getp();
+  var_expr* scorevarCopy = NULL;
+  var_expr* score_var_ptr = theScoreVarExpr;
   if (score_var_ptr)
   {
     scorevarCopy = new var_expr(*score_var_ptr);
-    subst->get(score_var_ptr) = scorevarCopy.getp();
+    subst->get(score_var_ptr) = scorevarCopy;
   }
 #endif
 
-  return new let_clause(theContext, get_loc(), varCopy, domainCopy, theLazyEval);
+  return new let_clause(theContext,
+                        theCCB,
+                        get_loc(),
+                        varCopy,
+                        domainCopy,
+                        theLazyEval);
 }
 
 
@@ -346,15 +358,16 @@
 ********************************************************************************/
 window_clause::window_clause(
     static_context* sctx,
+    CompilerCB* ccb,
     const QueryLoc& loc,
     window_t winKind,
-    var_expr_t varExpr,
-    expr_t domainExpr,
+    var_expr* varExpr,
+    expr* domainExpr,
     flwor_wincond_t winStart,
     flwor_wincond_t winStop,
     bool lazy)
   :
-  forletwin_clause(sctx, loc, flwor_clause::window_clause, varExpr, domainExpr),
+  forletwin_clause(sctx, ccb, loc, flwor_clause::window_clause, varExpr, domainExpr),
   theWindowKind(winKind),
   theWinStartCond(winStart),
   theWinStopCond(winStop),
@@ -383,7 +396,7 @@
       if (!TypeOps::is_subtype(tm, *rtm.ITEM_TYPE_STAR, *varType, loc) &&
           !TypeOps::is_subtype(tm, *domainType, *varType, loc))
       {
-        domainExpr = new treat_expr(sctx,
+        domainExpr = theCCB->theEM->create_treat_expr(sctx,
                                     loc,
                                     domainExpr,
                                     varType,
@@ -424,10 +437,10 @@
 
 flwor_clause_t window_clause::clone(expr::substitution_t& subst) const
 {
-  expr_t domainCopy = theDomainExpr->clone(subst);
+  expr* domainCopy = theDomainExpr->clone(subst);
 
-  var_expr_t varCopy(new var_expr(*theVarExpr));
-  subst[theVarExpr.getp()] = varCopy.getp();
+  var_expr* varCopy = theCCB->theEM->create_var_expr(*theVarExpr);
+  subst[theVarExpr] = varCopy;
 
   flwor_wincond_t cloneStartCond;
   flwor_wincond_t cloneStopCond;
@@ -439,6 +452,7 @@
     cloneStopCond = theWinStopCond->clone(subst);
 
   return new window_clause(theContext,
+                           theCCB,
                            get_loc(),
                            theWindowKind,
                            varCopy,
@@ -453,16 +467,18 @@
 
 ********************************************************************************/
 flwor_wincond::flwor_wincond(
+    CompilerCB* ccb,
     static_context* sctx,
     bool isOnly,
     const vars& in_vars,
     const vars& out_vars,
-    expr_t cond)
+    expr* cond)
   :
   theIsOnly(isOnly),
   theInputVars(in_vars),
   theOutputVars(out_vars),
-  theCondExpr(cond)
+  theCondExpr(cond),
+  theCCB(ccb)
 {
   expr::checkSimpleExpr(theCondExpr);
 
@@ -477,7 +493,7 @@
                           *GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE,
                           theCondExpr->get_loc()))
     {
-      theCondExpr = new fo_expr(theCondExpr->get_sctx(),
+      theCondExpr = theCCB->theEM->create_fo_expr(theCondExpr->get_sctx(),
                                 theCondExpr->get_loc(),
                                 GET_BUILTIN_FUNCTION(FN_BOOLEAN_1),
                                 theCondExpr);
@@ -493,6 +509,11 @@
 
 
 flwor_wincond::vars::vars()
+:
+posvar(NULL),
+curr(NULL),
+prev(NULL),
+next(NULL)
 {
 }
 
@@ -512,34 +533,35 @@
 
 
 void flwor_wincond::vars::clone(
+    ExprManager* mgr,
     flwor_wincond::vars& cloneVars,
     expr::substitution_t& subst) const
 {
   if (posvar != NULL)
   {
-    var_expr_t varCopy(new var_expr(*posvar));
-    subst[posvar.getp()] = varCopy.getp();
+    var_expr* varCopy = mgr->create_var_expr(*posvar);
+    subst[posvar] = varCopy;
     cloneVars.posvar = varCopy;
   }
 
   if (curr != NULL)
   {
-    var_expr_t varCopy(new var_expr(*curr));
-    subst[curr.getp()] = varCopy.getp();
+    var_expr* varCopy = mgr->create_var_expr(*curr);
+    subst[curr] = varCopy;
     cloneVars.curr = varCopy;
   }
 
   if (prev != NULL)
   {
-    var_expr_t varCopy(new var_expr(*prev));
-    subst[prev.getp()] = varCopy.getp();
+    var_expr* varCopy = mgr->create_var_expr(*prev);
+    subst[prev] = varCopy;
     cloneVars.prev = varCopy;
   }
 
   if (next != NULL)
   {
-    var_expr_t varCopy(new var_expr(*next));
-    subst[next.getp()] = varCopy.getp();
+    var_expr* varCopy = mgr->create_var_expr(*next);
+    subst[next] = varCopy;
     cloneVars.next = varCopy;
   }
 }
@@ -557,12 +579,17 @@
   flwor_wincond::vars cloneInVars;
   flwor_wincond::vars cloneOutVars;
 
-  theInputVars.clone(cloneInVars, subst);
-  theOutputVars.clone(cloneOutVars, subst);
-
-  expr_t cloneCondExpr = theCondExpr->clone(subst);
-
-  return new flwor_wincond(NULL, theIsOnly, cloneInVars, cloneOutVars, cloneCondExpr);
+  theInputVars.clone(theCCB->theEM, cloneInVars, subst);
+  theOutputVars.clone(theCCB->theEM, cloneOutVars, subst);
+
+  expr* cloneCondExpr = theCondExpr->clone(subst);
+
+  return new flwor_wincond(theCCB,
+                           NULL,
+                           theIsOnly,
+                           cloneInVars,
+                           cloneOutVars,
+                           cloneCondExpr);
 }
 
 
@@ -610,8 +637,8 @@
   csize numVars = theGroupVars.size();
   for (csize i = 0; i < numVars; ++i)
   {
-    if (theGroupVars[i].second.getp() == var)
-      return theGroupVars[i].first.getp();
+    if (theGroupVars[i].second == var)
+      return theGroupVars[i].first;
   }
 
   return NULL;
@@ -623,8 +650,8 @@
   csize numVars = theNonGroupVars.size();
   for (csize i = 0; i < numVars; ++i)
   {
-    if (theNonGroupVars[i].second.getp() == var)
-      return theNonGroupVars[i].first.getp();
+    if (theNonGroupVars[i].second == var)
+      return theNonGroupVars[i].first;
   }
 
   return NULL;
@@ -639,18 +666,25 @@
   rebind_list_t cloneGroupVars(numGroupVars);
   rebind_list_t cloneNonGroupVars(numNonGroupVars);
 
+  ExprManager* exprMgr = NULL;
+
+  if (numGroupVars > 0)
+    exprMgr = theGroupVars[0].first->get_ccb()->theEM;
+  else if (numNonGroupVars > 0)
+    exprMgr = theNonGroupVars[0].first->get_ccb()->theEM;
+
   for (csize i = 0; i < numGroupVars; ++i)
   {
     cloneGroupVars[i].first = theGroupVars[i].first->clone(subst);
-    cloneGroupVars[i].second = new var_expr(*theGroupVars[i].second);
-    subst[theGroupVars[i].second.getp()] = cloneGroupVars[i].second.getp();
+    cloneGroupVars[i].second = exprMgr->create_var_expr(*theGroupVars[i].second);
+    subst[theGroupVars[i].second] = cloneGroupVars[i].second;
   }
 
   for (csize i = 0; i < numNonGroupVars; ++i)
   {
     cloneNonGroupVars[i].first = theNonGroupVars[i].first->clone(subst);
-    cloneNonGroupVars[i].second = new var_expr(*theNonGroupVars[i].second);
-    subst[theNonGroupVars[i].second.getp()] = cloneNonGroupVars[i].second.getp();
+    cloneNonGroupVars[i].second = exprMgr->create_var_expr(*theNonGroupVars[i].second);
+    subst[theNonGroupVars[i].second] = cloneNonGroupVars[i].second;
   }
 
   return new group_clause(theContext,
@@ -669,15 +703,15 @@
     const QueryLoc& loc,
     bool stable,
     const std::vector<OrderModifier>& modifiers,
-    const std::vector<expr_t>& orderingExprs)
+    const std::vector<expr*>& orderingExprs)
   :
   flwor_clause(sctx, loc, flwor_clause::order_clause),
   theStableOrder(stable),
   theModifiers(modifiers),
   theOrderingExprs(orderingExprs)
 {
-  std::vector<expr_t>::const_iterator ite = orderingExprs.begin();
-  std::vector<expr_t>::const_iterator end = orderingExprs.end();
+  std::vector<expr*>::const_iterator ite = orderingExprs.begin();
+  std::vector<expr*>::const_iterator end = orderingExprs.end();
 
   for (; ite != end; ++ite)
   {
@@ -690,7 +724,7 @@
 {
   ulong numColumns = num_columns();
 
-  std::vector<expr_t> cloneExprs(numColumns);
+  std::vector<expr*> cloneExprs(numColumns);
 
   for (ulong i = 0; i < numColumns; ++i)
   {
@@ -732,7 +766,7 @@
 /*******************************************************************************
 
 ********************************************************************************/
-count_clause::count_clause(static_context* sctx, const QueryLoc& loc, var_expr_t var)
+count_clause::count_clause(static_context* sctx, const QueryLoc& loc, var_expr* var)
   :
   flwor_clause(sctx, loc, flwor_clause::count_clause),
   theVarExpr(var)
@@ -749,8 +783,10 @@
 
 flwor_clause_t count_clause::clone(expr::substitution_t& subst) const
 {
-  var_expr_t cloneVar = new var_expr(*theVarExpr);
-  subst[theVarExpr.getp()] = cloneVar;
+  ExprManager* exprMgr = theVarExpr->get_ccb()->theEM;
+
+  var_expr* cloneVar = exprMgr->create_var_expr(*theVarExpr);
+  subst[theVarExpr] = cloneVar;
 
   return new count_clause(theContext, get_loc(), cloneVar);
 }
@@ -759,7 +795,7 @@
 /*******************************************************************************
 
 ********************************************************************************/
-where_clause::where_clause(static_context* sctx, const QueryLoc& loc, expr_t where)
+where_clause::where_clause(static_context* sctx, const QueryLoc& loc, expr* where)
   :
   flwor_clause(sctx, loc, flwor_clause::where_clause),
   theWhereExpr(where)
@@ -768,7 +804,7 @@
 }
 
 
-void where_clause::set_expr(expr_t where)
+void where_clause::set_expr(expr* where)
 {
   theWhereExpr = where;
 }
@@ -776,7 +812,7 @@
 
 flwor_clause_t where_clause::clone(expr::substitution_t& subst) const
 {
-  expr_t cloneExpr = theWhereExpr->clone(subst);
+  expr* cloneExpr = theWhereExpr->clone(subst);
 
   return new where_clause(theContext, get_loc(), cloneExpr);
 }
@@ -785,11 +821,12 @@
 /*******************************************************************************
 
 ********************************************************************************/
-flwor_expr::flwor_expr(static_context* sctx, const QueryLoc& loc, bool general)
+flwor_expr::flwor_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, bool general)
   :
-  expr(sctx, loc, (general ? gflwor_expr_kind : flwor_expr_kind)),
+  expr(ccb, sctx, loc, (general ? gflwor_expr_kind : flwor_expr_kind)),
   theIsGeneral(general),
-  theHasSequentialClauses(false)
+  theHasSequentialClauses(false),
+  theReturnExpr(NULL)
 {
   theScriptingKind = SIMPLE_EXPR;
 }
@@ -848,7 +885,7 @@
 /*******************************************************************************
 
 ********************************************************************************/
-void flwor_expr::add_where(expr_t e)
+void flwor_expr::add_where(expr* e)
 {
   where_clause* whereClause = new where_clause(theSctx, e->get_loc(), e);
 
@@ -1043,15 +1080,15 @@
       const flwor_wincond::vars& startVars = startCond->get_out_vars();
       const flwor_wincond::vars& stopVars = stopCond->get_out_vars();
 
-      if (startVars.posvar) varExprs.push_back(startVars.posvar.getp());
-      if (startVars.curr) varExprs.push_back(startVars.curr.getp());
-      if (startVars.prev) varExprs.push_back(startVars.prev.getp());
-      if (startVars.next) varExprs.push_back(startVars.next.getp());
+      if (startVars.posvar) varExprs.push_back(startVars.posvar);
+      if (startVars.curr) varExprs.push_back(startVars.curr);
+      if (startVars.prev) varExprs.push_back(startVars.prev);
+      if (startVars.next) varExprs.push_back(startVars.next);
 
-      if (stopVars.posvar) varExprs.push_back(stopVars.posvar.getp());
-      if (stopVars.curr) varExprs.push_back(stopVars.curr.getp());
-      if (stopVars.prev) varExprs.push_back(stopVars.prev.getp());
-      if (stopVars.next) varExprs.push_back(stopVars.next.getp());
+      if (stopVars.posvar) varExprs.push_back(stopVars.posvar);
+      if (stopVars.curr) varExprs.push_back(stopVars.curr);
+      if (stopVars.prev) varExprs.push_back(stopVars.prev);
+      if (stopVars.next) varExprs.push_back(stopVars.next);
     }
   }
 }
@@ -1072,7 +1109,7 @@
     if (k == flwor_clause::for_clause ||
         k == flwor_clause::let_clause ||
         k == flwor_clause::window_clause)
-    { 
+    {
       const forletwin_clause* c2 = static_cast<const forletwin_clause*>(c);
 
       theScriptingKind |= c2->get_expr()->get_scripting_detail();
@@ -1113,11 +1150,11 @@
 /*******************************************************************************
 
 ********************************************************************************/
-expr_t flwor_expr::clone(substitution_t& subst) const
+expr* flwor_expr::clone(substitution_t& subst) const
 {
   ulong numClauses = num_clauses();
 
-  flwor_expr_t cloneFlwor = new flwor_expr(theSctx, get_loc(), theIsGeneral);
+  flwor_expr* cloneFlwor = theCCB->theEM->create_flwor_expr(theSctx, get_loc(), theIsGeneral);
 
   for (ulong i = 0; i < numClauses; ++i)
   {
@@ -1128,7 +1165,7 @@
 
   cloneFlwor->set_return_expr(theReturnExpr->clone(subst));
 
-  return cloneFlwor.getp();
+  return cloneFlwor;
 }
 
 

=== modified file 'src/compiler/expression/flwor_expr.h'
--- src/compiler/expression/flwor_expr.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/flwor_expr.h	2012-08-14 12:29:44 +0000
@@ -23,10 +23,11 @@
 #include "compiler/expression/var_expr.h"
 #include "compiler/expression/expr_utils.h"
 
-
 namespace zorba
 {
 
+class ExprManager;
+
 class order_modifier;
 class flwor_clause;
 class for_clause;
@@ -47,8 +48,6 @@
 typedef rchandle<materialize_clause> materialize_clause_t;
 typedef rchandle<group_clause> group_clause_t;
 
-typedef rchandle<flwor_expr> flwor_expr_t;
-
 
 /***************************************************************************//**
 
@@ -59,7 +58,7 @@
   friend class ExprIterator;
 
 public:
-  typedef std::vector<std::pair<expr_t, var_expr_t> > rebind_list_t;
+  typedef std::vector<std::pair<expr*, var_expr*> > rebind_list_t;
 
   typedef enum
   {
@@ -98,7 +97,7 @@
 
   virtual expr* get_expr() const { return NULL; }
 
-  virtual void set_expr(expr_t v) { }
+  virtual void set_expr(expr* v) { }
 
   virtual var_expr* get_pos_var() const { return NULL; }
 
@@ -140,26 +139,28 @@
   friend class ExprIterator;
 
 protected:
-  var_expr_t   theVarExpr;
-  expr_t       theDomainExpr;
+  var_expr   * theVarExpr;
+  expr       * theDomainExpr;
+  CompilerCB * theCCB;
 
 public:
   forletwin_clause(
         static_context* sctx,
+        CompilerCB* exprMan,
         const QueryLoc& loc,
         ClauseKind kind,
-        var_expr_t varExpr,
-        expr_t domainExpr);
+        var_expr* varExpr,
+        expr* domainExpr);
 
   ~forletwin_clause();
 
-  void set_expr(expr_t v);
-
-  expr* get_expr() const { return theDomainExpr.getp(); }
-
-  var_expr* get_var() const { return theVarExpr.getp(); }
-
-  void set_var(var_expr_t v);
+  void set_expr(expr* v);
+
+  expr* get_expr() const { return theDomainExpr; }
+
+  var_expr* get_var() const { return theVarExpr; }
+
+  void set_var(var_expr* v);
 };
 
 
@@ -172,18 +173,19 @@
   friend class ExprIterator;
 
 protected:
-  var_expr_t    thePosVarExpr;
-  var_expr_t    theScoreVarExpr;
+  var_expr    * thePosVarExpr;
+  var_expr    * theScoreVarExpr;
   bool          theAllowingEmpty;
 
 public:
   for_clause(
         static_context* sctx,
+        CompilerCB* exprMan,
         const QueryLoc& loc,
-        var_expr_t varExpr,
-        expr_t domainExpr,
-        var_expr_t posVarExpr = NULL,
-        var_expr_t scoreVarExpr = NULL,
+        var_expr* varExpr,
+        expr* domainExpr,
+        var_expr* posVarExpr = NULL,
+        var_expr* scoreVarExpr = NULL,
         bool isOuter = false);
 
   ~for_clause();
@@ -197,9 +199,9 @@
 
   var_expr* get_score_var() const;
 
-  void set_pos_var(var_expr_t v);
+  void set_pos_var(var_expr* v);
 
-  void set_score_var(var_expr_t v);
+  void set_score_var(var_expr* v);
 
   flwor_clause_t clone(expr::substitution_t& substitution) const;
 
@@ -217,15 +219,16 @@
   friend class ExprIterator;
 
 protected:
-  var_expr_t  theScoreVarExpr;
+  var_expr  * theScoreVarExpr;
   bool        theLazyEval;
 
 public:
   let_clause(
         static_context* sctx,
+        CompilerCB* exprMan,
         const QueryLoc& loc,
-        var_expr_t varExpr,
-        expr_t domainExpr,
+        var_expr* varExpr,
+        expr* domainExpr,
         bool lazy = false);
 
   ~let_clause();
@@ -233,7 +236,7 @@
 public:
   var_expr* get_score_var() const;
 
-  void set_score_var(var_expr_t v);
+  void set_score_var(var_expr* v);
 
   void setLazyEval(bool v) { theLazyEval = v; }
 
@@ -268,10 +271,11 @@
 public:
   window_clause(
         static_context* sctx,
+        CompilerCB* exprMan,
         const QueryLoc& loc,
         window_t winKind,
-        var_expr_t varExpr,
-        expr_t domainExpr,
+        var_expr* varExpr,
+        expr* domainExpr,
         flwor_wincond_t winStart,
         flwor_wincond_t winStop,
         bool lazy = false);
@@ -337,16 +341,16 @@
 public:
   struct vars
   {
-    var_expr_t posvar;
-    var_expr_t curr;
-    var_expr_t prev;
-    var_expr_t next;
+    var_expr* posvar;
+    var_expr* curr;
+    var_expr* prev;
+    var_expr* next;
 
     vars();
     ~vars();
     void set_flwor_clause(flwor_clause* c);
 
-    void clone(vars& cloneVars, expr::substitution_t& subst) const;
+    void clone(ExprManager* mgr, vars& cloneVars, expr::substitution_t& subst) const;
 
     std::ostream& put(std::ostream&) const;
   };
@@ -355,19 +359,22 @@
   bool    theIsOnly;
   vars    theInputVars;
   vars    theOutputVars;
-  expr_t  theCondExpr;
+  expr  * theCondExpr;
+
+  CompilerCB* theCCB;
 
 public:
   flwor_wincond(
+      CompilerCB* ccb,
       static_context* sctx,
       bool isOnly,
       const vars& in_vars,
       const vars& out_vars,
-      expr_t cond);
+      expr* cond);
 
   ~flwor_wincond();
 
-  expr* get_cond() const { return theCondExpr.getp(); }
+  expr* get_cond() const { return theCondExpr; }
 
   void set_cond(expr* cond) { theCondExpr = cond; }
 
@@ -481,7 +488,7 @@
 
   bool                        theStableOrder;
   std::vector<OrderModifier>  theModifiers;
-  std::vector<expr_t>         theOrderingExprs;
+  std::vector<expr*>          theOrderingExprs;
 
 public:
   orderby_clause (
@@ -489,23 +496,23 @@
       const QueryLoc& loc,
       bool stable,
       const std::vector<OrderModifier>& modifiers,
-      const std::vector<expr_t>& orderingExprs);
+      const std::vector<expr*>& orderingExprs);
 
   bool is_stable() const { return theStableOrder; }
 
   const std::vector<OrderModifier>& get_modifiers() const { return theModifiers; }
 
-  const std::vector<expr_t>& get_column_exprs() const { return theOrderingExprs; }
-
-  std::vector<expr_t>::iterator begin() { return theOrderingExprs.begin(); }
-
-  std::vector<expr_t>::iterator end() { return theOrderingExprs.end(); }
+  const std::vector<expr*>& get_column_exprs() const { return theOrderingExprs; }
+
+  std::vector<expr*>::iterator begin() { return theOrderingExprs.begin(); }
+
+  std::vector<expr*>::iterator end() { return theOrderingExprs.end(); }
 
   csize num_columns() const { return theOrderingExprs.size(); }
 
-  expr* get_column_expr(csize i) const { return theOrderingExprs[i].getp(); }
+  expr* get_column_expr(csize i) const { return theOrderingExprs[i]; }
 
-  void set_column_expr(csize i, expr_t e) { theOrderingExprs[i] = e; }
+  void set_column_expr(csize i, expr* e) { theOrderingExprs[i] = e; }
 
   flwor_clause_t clone(expr::substitution_t& substitution) const;
 
@@ -541,14 +548,14 @@
   friend class ExprIterator;
 
 protected:
-  var_expr_t theVarExpr;
+  var_expr* theVarExpr;
 
 public:
-  count_clause(static_context* sctx, const QueryLoc& loc, var_expr_t var);
+  count_clause(static_context* sctx, const QueryLoc& loc, var_expr* var);
 
   ~count_clause();
 
-  var_expr* get_var() const { return theVarExpr.getp(); }
+  var_expr* get_var() const { return theVarExpr; }
 
   flwor_clause_t clone(expr::substitution_t& substitution) const;
 };
@@ -562,14 +569,14 @@
   friend class ExprIterator;
   friend class flwor_expr;
 
-  expr_t theWhereExpr;
+  expr* theWhereExpr;
 
 public:
-  where_clause(static_context* sctx, const QueryLoc& loc, expr_t where);
-
-  expr* get_expr() const { return theWhereExpr.getp(); }
-
-  void set_expr(expr_t where);
+  where_clause(static_context* sctx, const QueryLoc& loc, expr* where);
+
+  expr* get_expr() const { return theWhereExpr; }
+
+  void set_expr(expr* where);
 
   flwor_clause_t clone(expr::substitution_t& substitution) const;
 };
@@ -605,6 +612,7 @@
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
 
 public:
   typedef std::vector<rchandle<flwor_clause> > clause_list_t;
@@ -613,18 +621,19 @@
   bool          theIsGeneral;
   bool          theHasSequentialClauses;
   clause_list_t theClauses;
-  expr_t        theReturnExpr;
+  expr*        theReturnExpr;
+
+protected:
+  flwor_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, bool general);
 
 public:
-  flwor_expr(static_context* sctx, const QueryLoc& loc, bool general);
-
   bool is_general() const { return theIsGeneral; }
 
   void set_general(bool v) { theIsGeneral = true; }
 
-  expr* get_return_expr() const { return theReturnExpr.getp(); }
+  expr* get_return_expr() const { return theReturnExpr; }
 
-  void set_return_expr(expr_t e)
+  void set_return_expr(expr* e)
   {
     theReturnExpr = e;
     compute_scripting_kind();
@@ -640,7 +649,7 @@
 
   void add_clause(ulong pos, flwor_clause* c);
 
-  void add_where(expr_t e);
+  void add_where(expr* e);
 
   void remove_clause(csize pos);
 
@@ -654,7 +663,7 @@
 
   void get_vars_defined(std::vector<var_expr*>& varExprs) const;
 
-  expr_t clone(substitution_t& substitution) const;
+  expr* clone(substitution_t& substitution) const;
 
   // The following 5 methods are for the simple flwor only. They should be
   // removed eventually.

=== modified file 'src/compiler/expression/fo_expr.cpp'
--- src/compiler/expression/fo_expr.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/fo_expr.cpp	2012-08-14 12:29:44 +0000
@@ -20,6 +20,8 @@
 #include "compiler/expression/fo_expr.h"
 #include "compiler/expression/expr_visitor.h"
 
+#include "compiler/api/compilercb.h"
+
 #include "context/static_context.h"
 
 #include "functions/library.h"
@@ -38,7 +40,7 @@
 {
   if (v.begin_visit(*this))
   {
-    accept_children(v); 
+    accept_children(v);
   }
 
   v.end_visit(*this);
@@ -53,22 +55,23 @@
   UnionExpr, and IntersectExceptExpr.
 ********************************************************************************/
 
-fo_expr* fo_expr::create_seq(static_context* sctx, const QueryLoc& loc)
+fo_expr* fo_expr::create_seq(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc)
 {
   function* f = BuiltinFunctionLibrary::getFunction(FunctionConsts::OP_CONCATENATE_N);
 
-  std::auto_ptr<fo_expr> fo(new fo_expr(sctx, loc, f));
+  std::auto_ptr<fo_expr> fo(ccb->theEM->create_fo_expr(sctx, loc, f));
 
   return fo.release();
 }
 
 
 fo_expr::fo_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     const function* f)
   :
-  expr(sctx, loc, fo_expr_kind),
+  expr(ccb, sctx, loc, fo_expr_kind),
   theFunction(const_cast<function*>(f))
 {
   // This method is private and it is to be used only by the clone method
@@ -78,12 +81,13 @@
 
 
 fo_expr::fo_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     const function* f,
-    const expr* arg)
+    expr* arg)
   :
-  expr(sctx, loc, fo_expr_kind),
+  expr(ccb, sctx, loc, fo_expr_kind),
   theFunction(const_cast<function*>(f))
 {
   assert(f != NULL);
@@ -95,13 +99,14 @@
 
 
 fo_expr::fo_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     const function* f,
-    const expr* arg1,
-    const expr* arg2)
+    expr* arg1,
+    expr* arg2)
   :
-  expr(sctx, loc, fo_expr_kind),
+  expr(ccb, sctx, loc, fo_expr_kind),
   theFunction(const_cast<function*>(f))
 {
   assert(f != NULL);
@@ -114,12 +119,13 @@
 
 
 fo_expr::fo_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     const function* f,
-    const std::vector<expr_t>& args)
+    const std::vector<expr*>& args)
   :
-  expr(sctx, loc, fo_expr_kind),
+  expr(ccb, sctx, loc, fo_expr_kind),
   theArgs(args),
   theFunction(const_cast<function*>(f))
 {
@@ -172,7 +178,7 @@
           RAISE_ERROR(err::XUST0001, theArgs[i]->get_loc(),
           ERROR_PARAMS(ZED(XUST0001_CONCAT)));
         }
-        
+
         if (i > 0 && !is_updating() && !is_vacuous() && (argKind & UPDATING_EXPR))
         {
           RAISE_ERROR(err::XUST0001, theArgs[i]->get_loc(),
@@ -213,7 +219,7 @@
       if (theArgs[i] == NULL)
         continue;
 
-      expr* arg = theArgs[i].getp();
+      expr* arg = theArgs[i];
 
       if (arg->is_updating())
       {
@@ -246,7 +252,7 @@
 }
 
 
-expr_t fo_expr::clone(substitution_t& subst) const
+expr* fo_expr::clone(substitution_t& subst) const
 {
   if (get_func()->getKind() == FunctionConsts::STATIC_COLLECTIONS_DML_COLLECTION_1)
   {
@@ -256,7 +262,7 @@
       return i->second;
   }
 
-  std::auto_ptr<fo_expr> fo(new fo_expr(theSctx, get_loc(), get_func()));
+  std::auto_ptr<fo_expr> fo(theCCB->theEM->create_fo_expr(theSctx, get_loc(), get_func()));
 
   for (csize i = 0; i < theArgs.size(); ++i)
     fo->theArgs.push_back(theArgs[i]->clone(subst));

=== modified file 'src/compiler/expression/fo_expr.h'
--- src/compiler/expression/fo_expr.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/fo_expr.h	2012-08-14 12:29:44 +0000
@@ -36,34 +36,41 @@
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
 
 protected:
-  checked_vector<expr_t>   theArgs;
+  checked_vector<expr*>    theArgs;
   function               * theFunction;
 
 public:
-  static fo_expr* create_seq(static_context* sctx, const QueryLoc &);
+
+protected:
+  static fo_expr* create_seq(CompilerCB* theExpMan, static_context* sctx, const QueryLoc &);
+
+protected:
+  fo_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    const QueryLoc& loc,
+    const function* f,
+    expr* arg);
+
+  fo_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    const QueryLoc& loc,
+    const function* f,
+    expr* arg1,
+    expr* arg2);
+
+  fo_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    const QueryLoc& loc,
+    const function* f,
+    const std::vector<expr*>& args);
 
 public:
-  fo_expr(
-    static_context* sctx,
-    const QueryLoc& loc,
-    const function* f,
-    const expr* arg);
-
-  fo_expr(
-    static_context* sctx,
-    const QueryLoc& loc,
-    const function* f,
-    const expr* arg1,
-    const expr* arg2);
-
-  fo_expr(
-    static_context* sctx,
-    const QueryLoc& loc,
-    const function* f,
-    const std::vector<expr_t>& args);
-
   function* get_func() const { return theFunction; }
 
   void set_func(function* f) { theFunction = f; }
@@ -74,56 +81,45 @@
 
   csize num_args() const { return theArgs.size(); }
 
-  expr* get_arg(csize i) const { return theArgs[i].getp(); }
+  expr* get_arg(csize i) const { return theArgs[i]; }
 
   void set_arg(csize i, expr* e) { theArgs[i] = e; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
 
 private:
-  fo_expr(static_context* sctx, const QueryLoc& loc, const function* f);
+  fo_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, const function* f);
 };
 
 ////////// The following expressions in the AST "decay" into an fo_expr ///////
 
 typedef fo_expr additive_expr;
-typedef rchandle<additive_expr> additive_expr_t;
 
 typedef fo_expr and_expr;
-typedef rchandle<and_expr> and_expr_t;
 
 typedef fo_expr comparison_expr;
-typedef rchandle<comparison_expr> comparison_expr_t;
 
 typedef fo_expr enclosed_expr;
-typedef rchandle<enclosed_expr> enclosed_expr_t;
 
 typedef fo_expr intersect_except_expr;
-typedef rchandle<intersect_except_expr> intersect_except_expr_t;
 
 typedef fo_expr multiplicative_expr;
-typedef rchandle<multiplicative_expr> multiplicative_expr_t;
 
 typedef fo_expr or_expr;
-typedef rchandle<or_expr> or_expr_t;
 
 typedef fo_expr quantified_expr;
-typedef rchandle<quantified_expr> quantified_expr_t;
 
 typedef fo_expr range_expr;
-typedef rchandle<range_expr> range_expr_t;
 
 typedef fo_expr unary_expr;
-typedef rchandle<unary_expr> unary_expr_t;
 
 typedef fo_expr union_expr;
-typedef rchandle<union_expr> union_expr_t;
 
 } // namespace zorba
 

=== modified file 'src/compiler/expression/ft_expr.cpp'
--- src/compiler/expression/ft_expr.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/ft_expr.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -20,6 +20,8 @@
 #include "compiler/expression/ftnode.h"
 #include "compiler/expression/ftnode_visitor.h"
 
+#include "compiler/api/compilercb.h"
+
 using namespace std;
 
 namespace zorba {
@@ -31,13 +33,14 @@
 ///////////////////////////////////////////////////////////////////////////////
 
 ftcontains_expr::ftcontains_expr(
+  CompilerCB* ccb,
   static_context* sctx,
   QueryLoc const &loc,
-  expr_t range,
+  expr* range,
   ftnode *ftselection,
-  expr_t ftignore
+  expr* ftignore
 ) :
-  expr( sctx, loc, ft_expr_kind ),
+  expr(ccb, sctx, loc, ft_expr_kind ),
   range_( range ),
   ftselection_( ftselection ),
   ftignore_( ftignore )
@@ -56,12 +59,12 @@
   v.end_visit( *this );
 }
 
-expr_t ftcontains_expr::clone( substitution_t &s ) const {
-  return new ftcontains_expr(
+expr* ftcontains_expr::clone( substitution_t &s ) const {
+  return theCCB->theEM->create_ftcontains_expr(
     theSctx, get_loc(),
     range_->clone( s ),
     ftselection_->clone( s ).release(),
-    ftignore_.isNull() ? 0 : ftignore_->clone( s )
+    ftignore_ == NULL ? 0 : ftignore_->clone( s )
   );
 }
 

=== modified file 'src/compiler/expression/ft_expr.h'
--- src/compiler/expression/ft_expr.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/ft_expr.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -27,34 +27,37 @@
 /**
  * An ftcontains_expr is-an expr for the FTContainsExpr.
  */
-class ftcontains_expr : public expr 
+class ftcontains_expr : public expr
 {
   friend class ExprIterator;
+  friend class ExprManager;
 
-public:
+protected:
   ftcontains_expr(
+    CompilerCB* ccb,
     static_context*,
     QueryLoc const&,
-    expr_t range,
+    expr* range,
     ftnode *ftselection,
-    expr_t ftignore
+    expr* ftignore
   );
 
-  expr_t clone( substitution_t& ) const;
+public:
+  expr* clone( substitution_t& ) const;
   void compute_scripting_kind();
 
-  expr_t get_range() const { return range_; }
+  expr* get_range() const { return range_; }
   ftnode_t get_ftselection() const { return ftselection_; }
-  expr_t get_ignore() const { return ftignore_; }
+  expr* get_ignore() const { return ftignore_; }
 
   void accept( expr_visitor& );
 
   std::ostream& put( std::ostream& ) const;
 
 private:
-  expr_t range_;
+  expr* range_;
   ftnode_t ftselection_;
-  expr_t ftignore_;
+  expr* ftignore_;
 };
 
 } // namespace zorba

=== modified file 'src/compiler/expression/ftnode.cpp'
--- src/compiler/expression/ftnode.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/ftnode.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -35,7 +35,7 @@
 namespace zorba {
 
 ///////////////////////////////////////////////////////////////////////////////
-  
+
 
 SERIALIZE_INTERNAL_METHOD(ftnode)
 
@@ -175,6 +175,11 @@
   return static_cast<PointerType>( p->clone( s ).release() );
 }
 
+template<>
+inline expr* clone_ptr( expr* p, expr::substitution_t &s ) {
+  return static_cast<expr*>( p->clone( s ) );
+}
+
 template<class RCHandleValueType>
 inline RCHandleValueType* clone_ptr( rchandle<RCHandleValueType> const &p,
                                      expr::substitution_t &s ) {
@@ -734,8 +739,8 @@
 ftrange::ftrange(
   QueryLoc const &loc,
   ft_range_mode::type mode,
-  expr_t const &expr1,
-  expr_t expr2
+  expr* const &expr1,
+  expr* expr2
 ) :
   ftnode( loc ),
   mode_( mode ),
@@ -1114,7 +1119,7 @@
   ar & subnode_;
 }
 
-ftweight::ftweight( QueryLoc const &loc, expr_t const &weight_expr ) :
+ftweight::ftweight( QueryLoc const &loc, expr* const &weight_expr ) :
   ftnode( loc ), weight_expr_( weight_expr )
 {
 }
@@ -1126,7 +1131,7 @@
 }
 
 ftnode_t ftweight::clone( expr::substitution_t &s ) const {
-  return new ftweight( get_loc(), weight_expr_->clone( s ).release() );
+  return new ftweight( get_loc(), weight_expr_->clone( s ) );
 }
 
 ostream& ftweight::put( ostream &o ) const {
@@ -1172,7 +1177,7 @@
 
 ftwindow_filter::ftwindow_filter(
   QueryLoc const &loc,
-  expr_t const &window_expr,
+  expr* const &window_expr,
   ft_unit::type unit )
 :
   ftpos_filter( loc ),
@@ -1190,7 +1195,7 @@
 
 ftnode_t ftwindow_filter::clone( expr::substitution_t &s ) const {
   return new ftwindow_filter(
-    get_loc(), window_expr_->clone( s ).release(), unit_
+    get_loc(), window_expr_->clone( s ), unit_
   );
 }
 
@@ -1211,7 +1216,7 @@
 
 ftwords::ftwords(
   QueryLoc const &loc,
-  expr_t const &value_expr,
+  expr* const &value_expr,
   ft_anyall_mode::type mode
 ) :
   ftnode( loc ),
@@ -1227,7 +1232,7 @@
 }
 
 ftnode_t ftwords::clone( expr::substitution_t &s ) const {
-  return new ftwords( get_loc(), value_expr_->clone( s ).release(), mode_ );
+  return new ftwords( get_loc(), value_expr_->clone( s ), mode_ );
 }
 
 ostream& ftwords::put( ostream &o ) const {

=== modified file 'src/compiler/expression/ftnode.h'
--- src/compiler/expression/ftnode.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/ftnode.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -459,11 +459,11 @@
   SERIALIZABLE_CLASS_CONSTRUCTOR2(ftweight,ftnode)
   void serialize( serialization::Archiver& );
 
-  ftweight( QueryLoc const&, expr_t const &weight_expr );
+  ftweight( QueryLoc const&, expr* const &weight_expr );
 
   ft_visit_result::type accept( ftnode_visitor& );
   ftnode_t clone( expr::substitution_t& ) const;
-  expr_t& get_weight_expr() { return weight_expr_; }
+  expr** get_weight_expr() { return &weight_expr_; }
   PlanIter_t get_weight_iter() const { return weight_iter_; }
   std::ostream& put( std::ostream& ) const;
 
@@ -472,7 +472,7 @@
   }
 
 private:
-  expr_t weight_expr_;
+  expr* weight_expr_;
   PlanIter_t weight_iter_;
 };
 
@@ -697,12 +697,12 @@
   SERIALIZABLE_CLASS_CONSTRUCTOR2(ftwindow_filter,ftpos_filter)
   void serialize( serialization::Archiver& );
 
-  ftwindow_filter( QueryLoc const&, expr_t const&, ft_unit::type );
+  ftwindow_filter( QueryLoc const&, expr* const&, ft_unit::type );
 
   ft_visit_result::type accept( ftnode_visitor& );
   ftnode_t clone( expr::substitution_t& ) const;
   ft_unit::type get_unit() const { return unit_; }
-  expr_t& get_window_expr() { return window_expr_; }
+  expr** get_window_expr() { return &window_expr_; }
   PlanIter_t get_window_iter() const { return window_iter_; }
   std::ostream& put( std::ostream& ) const;
 
@@ -711,7 +711,7 @@
   }
 
 private:
-  expr_t window_expr_;
+  expr* window_expr_;
   ft_unit::type unit_;
   PlanIter_t window_iter_;
 };
@@ -813,14 +813,14 @@
   ftrange(
     QueryLoc const&,
     ft_range_mode::type,
-    expr_t const &expr1,
-    expr_t expr2 = 0
+    expr* const &expr1,
+    expr* expr2 = 0
   );
 
   ft_visit_result::type accept( ftnode_visitor& );
   ftnode_t clone( expr::substitution_t& ) const;
-  expr_t& get_expr1() { return expr1_; }
-  expr_t& get_expr2() { return expr2_; }
+  expr** get_expr1() { return &expr1_; }
+  expr** get_expr2() { return &expr2_; }
   PlanIter_t get_plan_iter1() const { return iter1_; }
   PlanIter_t get_plan_iter2() const { return iter2_; }
   ft_range_mode::type get_mode() const { return mode_; }
@@ -833,8 +833,8 @@
 
 private:
   ft_range_mode::type mode_;
-  expr_t expr1_;
-  expr_t expr2_;
+  expr* expr1_;
+  expr* expr2_;
   PlanIter_t iter1_;
   PlanIter_t iter2_;
 };
@@ -848,13 +848,13 @@
 
   ftwords(
     QueryLoc const&,
-    expr_t const&,
+    expr* const&,
     ft_anyall_mode::type = ft_anyall_mode::DEFAULT
   );
 
   ft_visit_result::type accept( ftnode_visitor& );
   ftnode_t clone( expr::substitution_t& ) const;
-  expr_t& get_value_expr() { return value_expr_; }
+  expr** get_value_expr() { return &value_expr_; }
   PlanIter_t get_value_iter() const { return value_iter_; }
   ft_anyall_mode::type get_mode() const { return mode_; }
   std::ostream& put( std::ostream& ) const;
@@ -864,7 +864,7 @@
   }
 
 private:
-  expr_t value_expr_;
+  expr* value_expr_;
   ft_anyall_mode::type mode_;
   PlanIter_t value_iter_;
 };

=== modified file 'src/compiler/expression/ftnode_visitor.cpp'
--- src/compiler/expression/ftnode_visitor.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/ftnode_visitor.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -46,9 +46,9 @@
 DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftprimary_with_options );
 
 ft_visit_result::type V::begin_visit( ftrange &r ) {
-  push_back( &r.get_expr1() );
+  push_back( r.get_expr1() );
   if ( r.get_expr2() )
-    push_back( &r.get_expr2() );
+    push_back( r.get_expr2() );
   return ft_visit_result::no_end;
 }
 DEF_FTNODE_VISITOR_END_VISIT( V, ftrange );
@@ -57,13 +57,13 @@
 DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftunary_not );
 
 ft_visit_result::type V::begin_visit( ftweight &w ) {
-  push_back( &w.get_weight_expr() );
+  push_back( w.get_weight_expr() );
   return ft_visit_result::no_end;
 }
 DEF_FTNODE_VISITOR_END_VISIT( V, ftweight );
 
 ft_visit_result::type V::begin_visit( ftwords &w ) {
-  push_back( &w.get_value_expr() );
+  push_back( w.get_value_expr() );
   return ft_visit_result::no_end;
 }
 DEF_FTNODE_VISITOR_END_VISIT( V, ftwords );
@@ -77,7 +77,7 @@
 DEF_FTNODE_VISITOR_VISIT_MEM_FNS( V, ftscope_filter );
 
 ft_visit_result::type V::begin_visit( ftwindow_filter &wf ) {
-  push_back( &wf.get_window_expr() );
+  push_back( wf.get_window_expr() );
   return ft_visit_result::no_end;
 }
 DEF_FTNODE_VISITOR_END_VISIT( V, ftwindow_filter )

=== modified file 'src/compiler/expression/ftnode_visitor.h'
--- src/compiler/expression/ftnode_visitor.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/ftnode_visitor.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -96,7 +96,7 @@
  */
 class FTNodeExprCollector : public ftnode_visitor {
 public:
-  typedef std::vector<expr_t*> expr_list_t;
+  typedef std::vector<expr**> expr_list_t;
 
   expr_visitor* get_expr_visitor();
 
@@ -138,7 +138,7 @@
   DECL_FTNODE_VISITOR_VISIT_MEM_FNS( ftwild_card_option );
 
 private:
-  void push_back( expr_t* e ) {
+  void push_back( expr** e ) {
     expr_list_.push_back( e );
   }
 

=== modified file 'src/compiler/expression/function_item_expr.cpp'
--- src/compiler/expression/function_item_expr.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/function_item_expr.cpp	2012-08-14 12:29:44 +0000
@@ -16,9 +16,10 @@
 #include "stdafx.h"
 
 #include "compiler/expression/function_item_expr.h"
-
 #include "compiler/expression/expr_visitor.h"
 
+#include "compiler/api/compilercb.h"
+
 #include "functions/function.h"
 #include "functions/udf.h"
 #include "functions/signature.h"
@@ -30,12 +31,13 @@
 
 
 dynamic_function_invocation_expr::dynamic_function_invocation_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& anExpr,
-    const std::vector<expr_t>& args)
+    expr* anExpr,
+    const std::vector<expr*>& args)
   :
-  expr(sctx, loc, dynamic_function_invocation_expr_kind),
+  expr(ccb, sctx, loc, dynamic_function_invocation_expr_kind),
   theExpr(anExpr),
   theArgs(args)
 {
@@ -54,17 +56,17 @@
 }
 
 
-expr_t dynamic_function_invocation_expr::clone(substitution_t& s) const
+expr* dynamic_function_invocation_expr::clone(substitution_t& s) const
 {
-  checked_vector<expr_t> lNewArgs;
-  for (checked_vector<expr_t>::const_iterator lIter = theArgs.begin();
+  checked_vector<expr*> lNewArgs;
+  for (checked_vector<expr*>::const_iterator lIter = theArgs.begin();
        lIter != theArgs.end();
        ++lIter)
   {
     lNewArgs.push_back((*lIter)->clone(s));
   }
 
-  return new dynamic_function_invocation_expr(theSctx,
+  return theCCB->theEM->create_dynamic_function_invocation_expr(theSctx,
                                               get_loc(),
                                               theExpr->clone(s),
                                               lNewArgs);
@@ -79,13 +81,14 @@
 
 
 function_item_expr::function_item_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     const store::Item* aQName,
     function* f,
     uint32_t aArity)
-	:
-  expr(sctx, loc, function_item_expr_kind),
+  :
+  expr(ccb, sctx, loc, function_item_expr_kind),
   theQName(const_cast<store::Item*>(aQName)),
   theFunction(f),
   theArity(aArity)
@@ -96,10 +99,11 @@
 
 
 function_item_expr::function_item_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc)
-	:
-  expr(sctx, loc, function_item_expr_kind),
+  :
+  expr(ccb, sctx, loc, function_item_expr_kind),
   theQName(0),
   theFunction(NULL),
   theArity(0)
@@ -119,7 +123,7 @@
 }
 
 
-const std::vector<expr_t>& function_item_expr::get_vars() const
+const std::vector<expr*>& function_item_expr::get_vars() const
 {
   return theScopedVariables;
 }
@@ -140,18 +144,18 @@
 }
 
 
-expr_t function_item_expr::clone(substitution_t& s) const
+expr* function_item_expr::clone(substitution_t& s) const
 {
   std::auto_ptr<function_item_expr> lNewExpr(
-      new function_item_expr(theSctx,
+      theCCB->theEM->create_function_item_expr(theSctx,
                              get_loc(),
                              theFunction->getName(),
                              theFunction.getp(),
                              theArity)
   );
 
-  std::vector<expr_t> lNewVariables;
-  for (std::vector<expr_t>::const_iterator lIter = theScopedVariables.begin();
+  std::vector<expr*> lNewVariables;
+  for (std::vector<expr*>::const_iterator lIter = theScopedVariables.begin();
        lIter != theScopedVariables.end();
        ++lIter)
   {

=== modified file 'src/compiler/expression/function_item_expr.h'
--- src/compiler/expression/function_item_expr.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/function_item_expr.h	2012-08-14 12:29:44 +0000
@@ -38,29 +38,32 @@
 {
   friend class ExprIterator;
   friend class expr;
-
-protected:
-  expr_t                 theExpr;
-  std::vector<expr_t>    theArgs;
-
-public:
+  friend class ExprManager;
+
+protected:
+  expr                * theExpr;
+  std::vector<expr*>    theArgs;
+
+protected:
   dynamic_function_invocation_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
-      const expr_t& anExpr,
-      const std::vector<expr_t>& args);
-
-	const expr_t get_function() const { return theExpr; }
-
-  const std::vector<expr_t>& get_args() const { return theArgs; }
-
-	void compute_scripting_kind();
-
-  expr_t clone(substitution_t& s) const;
-
-	void accept(expr_visitor&);
-
-	std::ostream& put(std::ostream& os) const;
+      expr* anExpr,
+      const std::vector<expr*>& args);
+
+public:
+  const expr* get_function() const { return theExpr; }
+
+  const std::vector<expr*>& get_args() const { return theArgs; }
+
+  void compute_scripting_kind();
+
+  expr* clone(substitution_t& s) const;
+
+  void accept(expr_visitor&);
+
+  std::ostream& put(std::ostream& os) const;
 };
 
 
@@ -99,15 +102,19 @@
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
 
 private:
   store::Item_t        theQName;
-	function_t           theFunction;
+  function_t           theFunction;
   uint32_t             theArity;
-  std::vector<expr_t>  theScopedVariables;
+  std::vector<expr*>  theScopedVariables;
 
 public:
-	function_item_expr(
+
+protected:
+  function_item_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
       const store::Item* aQName,
@@ -115,30 +122,32 @@
       uint32_t aArity);
 
   function_item_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc);
 
+public:
   ~function_item_expr();
 
   void add_variable(expr* var);
 
   void set_function(user_function_t& udf);
 
-	function* get_function() const { return theFunction.getp(); }
+  function* get_function() const { return theFunction.getp(); }
 
   const store::Item_t& get_qname() const { return theQName; }
 
   uint32_t get_arity() const { return theArity; }
 
-  const std::vector<expr_t>& get_vars() const;
-
-	void compute_scripting_kind();
-
-  expr_t clone(substitution_t& s) const;
-
-	void accept(expr_visitor&);
-
-	std::ostream& put(std::ostream& os) const;
+  const std::vector<expr*>& get_vars() const;
+
+  void compute_scripting_kind();
+
+  expr* clone(substitution_t& s) const;
+
+  void accept(expr_visitor&);
+
+  std::ostream& put(std::ostream& os) const;
 };
 
 } //end of namespace

=== modified file 'src/compiler/expression/json_exprs.cpp'
--- src/compiler/expression/json_exprs.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/json_exprs.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -16,10 +16,11 @@
 #include "stdafx.h"
 #include "compiler/expression/json_exprs.h"
 #include "compiler/expression/expr_visitor.h"
+#include "compiler/api/compilercb.h"
 
 #ifdef ZORBA_WITH_JSON
 
-namespace zorba 
+namespace zorba
 {
 
 DEF_EXPR_ACCEPT(json_array_expr)
@@ -30,18 +31,19 @@
  JSONArrayConstructor ::= "[" Expr? "]"
 ********************************************************************************/
 json_array_expr::json_array_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& content)
+    expr* content)
   :
-  expr(sctx, loc, json_array_expr_kind),
+  expr(ccb, sctx, loc, json_array_expr_kind),
   theContentExpr(content)
 {
   compute_scripting_kind();
 }
 
 
-void json_array_expr::compute_scripting_kind() 
+void json_array_expr::compute_scripting_kind()
 {
   if (theContentExpr)
   {
@@ -58,11 +60,12 @@
 }
 
 
-expr_t json_array_expr::clone(substitution_t& subst) const
+expr* json_array_expr::clone(substitution_t& subst) const
 {
-  return new json_array_expr(theSctx,
-                             get_loc(),
-                             theContentExpr->clone(subst));
+  return theCCB->theEM->
+         create_json_array_expr(theSctx,
+                                get_loc(),
+                                theContentExpr->clone(subst));
 }
 
 
@@ -74,12 +77,13 @@
   The Expr must return a sequence of zero or more objects
 ********************************************************************************/
 json_object_expr::json_object_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& content,
+    expr* content,
     bool accumulate)
   :
-  expr(sctx, loc, json_object_expr_kind),
+  expr(ccb, sctx, loc, json_object_expr_kind),
   theContentExpr(content),
   theAccumulate(accumulate)
 {
@@ -87,7 +91,7 @@
 }
 
 
-void json_object_expr::compute_scripting_kind() 
+void json_object_expr::compute_scripting_kind()
 {
   if (theContentExpr)
   {
@@ -104,14 +108,14 @@
 }
 
 
-expr_t json_object_expr::clone(substitution_t& subst) const
+expr* json_object_expr::clone(substitution_t& subst) const
 {
-  return new json_object_expr(theSctx,
-                              get_loc(),
-                              (theContentExpr ?
-                               theContentExpr->clone(subst) :
-                               NULL),
-                              theAccumulate);
+  return theCCB->theEM->
+         create_json_object_expr(theSctx,
+                                 get_loc(),
+                                 (theContentExpr ?
+                                  theContentExpr->clone(subst) : NULL),
+                                 theAccumulate);
 }
 
 
@@ -124,12 +128,13 @@
   The 2nd ExprSingle must contain exactly one item of any kind.
 ********************************************************************************/
 json_direct_object_expr::json_direct_object_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    std::vector<expr_t>& names,
-    std::vector<expr_t>& values)
+    std::vector<expr*>& names,
+    std::vector<expr*>& values)
   :
-  expr(sctx, loc, json_direct_object_expr_kind)
+  expr(ccb, sctx, loc, json_direct_object_expr_kind)
 {
   assert(names.size() == values.size());
 
@@ -140,12 +145,12 @@
 }
 
 
-void json_direct_object_expr::compute_scripting_kind() 
+void json_direct_object_expr::compute_scripting_kind()
 {
   theScriptingKind = SIMPLE_EXPR;
 
-  std::vector<expr_t>::const_iterator ite = theNames.begin();
-  std::vector<expr_t>::const_iterator end = theNames.end();
+  std::vector<expr*>::const_iterator ite = theNames.begin();
+  std::vector<expr*>::const_iterator end = theNames.end();
   for (; ite != end; ++ite)
   {
     theScriptingKind |= (*ite)->get_scripting_detail();
@@ -170,16 +175,16 @@
 }
 
 
-expr_t json_direct_object_expr::clone(substitution_t& subst) const
+expr* json_direct_object_expr::clone(substitution_t& subst) const
 {
-  std::vector<expr_t> names;
-  std::vector<expr_t> values;
+  std::vector<expr*> names;
+  std::vector<expr*> values;
 
   names.reserve(theNames.size());
   values.reserve(theValues.size());
 
-  std::vector<expr_t>::const_iterator ite = theNames.begin();
-  std::vector<expr_t>::const_iterator end = theNames.end();
+  std::vector<expr*>::const_iterator ite = theNames.begin();
+  std::vector<expr*>::const_iterator end = theNames.end();
   for (; ite != end; ++ite)
   {
     names.push_back((*ite)->clone(subst));
@@ -192,7 +197,8 @@
     values.push_back((*ite)->clone(subst));
   }
 
-  return new json_direct_object_expr(theSctx, get_loc(), names, values);
+  return theCCB->theEM->
+         create_json_direct_object_expr(theSctx, get_loc(), names, values);
 }
 
 

=== modified file 'src/compiler/expression/json_exprs.h'
--- src/compiler/expression/json_exprs.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/json_exprs.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -27,34 +27,37 @@
 #ifdef ZORBA_WITH_JSON
 
 
-namespace zorba 
+namespace zorba
 {
 
 /*******************************************************************************
   ArrayConstructor ::= "[" Expr? "]"
 ********************************************************************************/
-class json_array_expr : public expr 
+class json_array_expr : public expr
 {
   friend class ExprIterator;
-
-protected:
-  expr_t  theContentExpr;
-
-public:
+  friend class ExprManager;
+
+protected:
+  expr * theContentExpr;
+
+protected:
   json_array_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
-      const expr_t& content);
+      expr* content);
 
-  expr* get_expr() const { return theContentExpr.getp(); }
+public:
+  expr* get_expr() const { return theContentExpr; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 
@@ -65,32 +68,35 @@
 
   The Expr must return a sequence of zero or more objects
 ********************************************************************************/
-class json_object_expr : public expr 
+class json_object_expr : public expr
 {
   friend class ExprIterator;
+  friend class ExprManager;
 
 protected:
-  expr_t  theContentExpr;
+  expr  * theContentExpr;
   bool    theAccumulate;
 
-public:
+protected:
   json_object_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
-      const expr_t& content,
+      expr* content,
       bool accumulate);
 
-  expr* get_expr() const { return theContentExpr.getp(); }
+public:
+  expr* get_expr() const { return theContentExpr; }
 
   bool is_accumulating() const { return theAccumulate; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 
@@ -102,34 +108,37 @@
   The 1st ExprSingle must return exactly one string.
   The 2nd ExprSingle must contain exactly one item of any kind.
 ********************************************************************************/
-class json_direct_object_expr : public expr 
+class json_direct_object_expr : public expr
 {
   friend class ExprIterator;
-
-protected:
-  std::vector<expr_t>  theNames;
-  std::vector<expr_t>  theValues;
-
-public:
+  friend class ExprManager;
+
+protected:
+  std::vector<expr*>  theNames;
+  std::vector<expr*>  theValues;
+
+protected:
   json_direct_object_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
-      std::vector<expr_t>& names,
-      std::vector<expr_t>& values);
+      std::vector<expr*>& names,
+      std::vector<expr*>& values);
 
+public:
   csize num_pairs() const { return theNames.size(); }
 
-  expr* get_value_expr(csize i) const { return theValues[i].getp(); }
+  expr* get_value_expr(csize i) const { return theValues[i]; }
 
-  expr* get_name_expr(csize i) const { return theNames[i].getp(); }
+  expr* get_name_expr(csize i) const { return theNames[i]; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 

=== added file 'src/compiler/expression/mem_manager.cpp'
--- src/compiler/expression/mem_manager.cpp	1970-01-01 00:00:00 +0000
+++ src/compiler/expression/mem_manager.cpp	2012-08-14 12:29:44 +0000
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2006-2012 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "mem_manager.h"
+
+#include <iostream>
+#include <new>
+
+namespace zorba
+{
+
+/*******************************************************************************
+
+********************************************************************************/
+MemoryManager::MemoryManager()
+{
+  thePages.reserve(1024);
+
+  thePageStart = new char[thePageSize];
+
+  if (thePageStart == NULL)
+    throw std::bad_alloc();
+
+  thePageEnd = thePageStart + thePageSize;
+  theFreeSize = thePageSize;
+  thePages.push_back(thePageStart);
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+MemoryManager::~MemoryManager()
+{
+  for(std::vector<char*>::iterator iter = thePages.begin();
+      iter != thePages.end();
+      ++iter)
+  {
+    delete [] (*iter);
+  }
+}
+
+
+} // namespace zorba

=== added file 'src/compiler/expression/mem_manager.h'
--- src/compiler/expression/mem_manager.h	1970-01-01 00:00:00 +0000
+++ src/compiler/expression/mem_manager.h	2012-08-14 12:29:44 +0000
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2006-2012 The FLWOR Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+#ifndef ZORBA_COMPILER_MEMMANAGER_H
+#define ZORBA_COMPILER_MEMMANAGER_H
+
+#include <cassert>
+#include <stdlib.h>
+#include <vector>
+
+namespace zorba
+{
+
+
+/******************************************************************************
+                                 Memory Manager                               
+*******************************************************************************/
+class MemoryManager
+{
+private:
+  static const size_t  thePageSize = 16384;
+
+  std::vector<char*>   thePages;
+
+  char               * thePageStart;
+  char               * thePageEnd;
+  size_t               theFreeSize;
+
+public:
+  MemoryManager();
+
+  ~MemoryManager();
+
+  void* allocate(size_t size)
+  {
+    assert(size > 0 && size <= thePageSize);
+
+    if (theFreeSize < size)
+    {
+      thePageStart = new char[thePageSize];
+
+      if (thePageStart == NULL)
+        throw std::bad_alloc();
+
+      thePageEnd = thePageStart + thePageSize;
+      theFreeSize = thePageSize;
+      thePages.push_back(thePageStart);
+    }
+
+    void* allocation = (void*)(thePageEnd - theFreeSize);
+    theFreeSize -= size;
+
+    return allocation;
+  }
+
+private:
+  // A memory manager is the only existing object handling memory
+  // Since it's all data that it contains, there is no sense in copying it.
+  MemoryManager(const MemoryManager&);
+  MemoryManager& operator=(const MemoryManager&);
+};
+
+} // namespace zorba
+
+
+
+/*******************************************************************************
+  This handles the creation of data within the memory pool using the format
+  new (MemPool) constructor
+
+  For more information see
+  http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.14
+********************************************************************************/
+inline void* operator new(size_t size, zorba::MemoryManager& mem)
+{
+  return mem.allocate(size);
+}
+
+
+inline void operator delete(void* p, zorba::MemoryManager& mem)
+{
+  // Memory is freed when MemoryManager is destroyed 
+}
+
+#endif /*ZORBA_COMPILER_MEMMANAGER_H*/

=== modified file 'src/compiler/expression/path_expr.cpp'
--- src/compiler/expression/path_expr.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/path_expr.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,8 +25,10 @@
 #include "compiler/expression/path_expr.h"
 #include "compiler/expression/expr_visitor.h"
 
-
-namespace zorba 
+#include "compiler/api/compilercb.h"
+
+
+namespace zorba
 {
 
 
@@ -40,19 +42,19 @@
   RelativPathExpr ::= "/" | ("/" | "//")?  StepExpr (("/" | "//") StepExpr)*
 
 ********************************************************************************/
-relpath_expr::relpath_expr(static_context* sctx, const QueryLoc& loc)
+relpath_expr::relpath_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc)
   :
-  expr(sctx, loc, relpath_expr_kind)
+  expr(ccb, sctx, loc, relpath_expr_kind)
 {
   theScriptingKind = SIMPLE_EXPR;
 }
 
 
-void relpath_expr::add_back(expr_t step)
+void relpath_expr::add_back(expr* step)
 {
   if (step->is_updating())
   {
-    throw XQUERY_EXCEPTION(err::XUST0001, 
+    throw XQUERY_EXCEPTION(err::XUST0001,
                            ERROR_PARAMS(ZED(XUST0001_Generic)),
                            ERROR_LOC(get_loc()));
   }
@@ -77,11 +79,11 @@
 
   for (unsigned i = 0; i < size(); ++i)
   {
-    expr* step = theSteps[i].getp();
+    expr* step = theSteps[i];
 
     if (step->is_updating())
     {
-      throw XQUERY_EXCEPTION(err::XUST0001, 
+      throw XQUERY_EXCEPTION(err::XUST0001,
                              ERROR_PARAMS(ZED(XUST0001_Generic)),
                              ERROR_LOC(get_loc()));
     }
@@ -98,9 +100,9 @@
 }
 
 
-expr_t relpath_expr::clone(substitution_t& subst) const
+expr* relpath_expr::clone(substitution_t& subst) const
 {
-  std::auto_ptr<relpath_expr> re(new relpath_expr(theSctx, get_loc()));
+  std::auto_ptr<relpath_expr> re(theCCB->theEM->create_relpath_expr(theSctx, get_loc()));
 
   for (unsigned i = 0; i < size(); ++i)
   {
@@ -117,16 +119,16 @@
   AxisStep ::= Axis NodeTest Predicate*
 
 ********************************************************************************/
-axis_step_expr::axis_step_expr(static_context* sctx, const QueryLoc& loc)
+axis_step_expr::axis_step_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc)
   :
-  expr(sctx, loc, axis_step_expr_kind),
+  expr(ccb, sctx, loc, axis_step_expr_kind),
   theReverseOrder(false)
 {
   compute_scripting_kind();
 }
 
 
-bool axis_step_expr::is_reverse_axis(axis_kind_t k) 
+bool axis_step_expr::is_reverse_axis(axis_kind_t k)
 {
   return (k == axis_kind_ancestor ||
           k == axis_kind_ancestor_or_self ||
@@ -135,6 +137,10 @@
           k == axis_kind_preceding_sibling);
 }
 
+void axis_step_expr::setTest(match_expr* v)
+{
+  theNodeTest = v;
+}
 
 void axis_step_expr::compute_scripting_kind()
 {
@@ -142,9 +148,9 @@
 }
 
 
-expr_t axis_step_expr::clone(substitution_t& subst) const
+expr* axis_step_expr::clone(substitution_t& subst) const
 {
-  axis_step_expr* ae = new axis_step_expr(theSctx, get_loc());
+  axis_step_expr* ae = theCCB->theEM->create_axis_step_expr(theSctx, get_loc());
   ae->setAxis(getAxis());
   ae->setTest(getTest());
   ae->theReverseOrder = theReverseOrder;
@@ -164,9 +170,9 @@
                      PITest | CommentTest | TextTest | AnyKindTest
 
 ********************************************************************************/
-match_expr::match_expr(static_context* sctx, const QueryLoc& loc)
+match_expr::match_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc)
   :
-  expr(sctx, loc, match_expr_kind),
+  expr(ccb, sctx, loc, match_expr_kind),
   theDocTestKind(match_no_test),
   theWildKind(match_no_wild),
   theQName(NULL),
@@ -214,9 +220,9 @@
 }
 
 
-expr_t match_expr::clone(substitution_t& subst) const
+expr* match_expr::clone(substitution_t& subst) const
 {
-  match_expr* me = new match_expr(theSctx, get_loc());
+  match_expr* me = theCCB->theEM->create_match_expr(theSctx, get_loc());
   me->setTestKind(getTestKind());
   me->setDocTestKind(getDocTestKind());
   me->setWildName(getWildName());

=== modified file 'src/compiler/expression/path_expr.h'
--- src/compiler/expression/path_expr.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/path_expr.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -23,7 +23,7 @@
 #include "zorbatypes/zstring.h"
 
 
-namespace zorba 
+namespace zorba
 {
 
 class match_expr;
@@ -31,7 +31,7 @@
 
 /*******************************************************************************
 
-  PathExpr ::= 	("/" RelativePathExpr?) |
+  PathExpr ::=  ("/" RelativePathExpr?) |
                 ("//" RelativePathExpr) |
                 RelativePathExpr
 
@@ -49,34 +49,36 @@
  RelativPathExpr ::= "/" | ("/" | "//")?  StepExpr (("/" | "//") StepExpr)*
 
 ********************************************************************************/
-class relpath_expr : public expr 
+class relpath_expr : public expr
 {
   friend class ExprIterator;
   friend class expr;
-
-protected:
-  std::vector<expr_t> theSteps;
+  friend class ExprManager;
+
+protected:
+  std::vector<expr*> theSteps;
+
+protected:
+  relpath_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc);
 
 public:
-  relpath_expr(static_context* sctx, const QueryLoc& loc);
-
-	size_t size() const { return theSteps.size(); }
-
-	void add_back(expr_t step);
+  size_t size() const { return theSteps.size(); }
+
+  void add_back(expr* step);
 
   void erase(csize i) { theSteps.erase(theSteps.begin() + i); }
 
   csize numSteps() const { return theSteps.size(); }
 
-  expr* operator[](csize n) const { return theSteps[n].getp(); }
-
-  std::vector<expr_t>::const_iterator begin() const { return theSteps.begin(); }
-
-  std::vector<expr_t>::const_iterator end() const { return theSteps.end(); }
+  expr* operator[](csize n) const { return theSteps[n]; }
+
+  std::vector<expr*>::const_iterator begin() const { return theSteps.begin(); }
+
+  std::vector<expr*>::const_iterator end() const { return theSteps.end(); }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t &) const;
+  expr* clone(substitution_t &) const;
 
   void accept(expr_visitor&);
 
@@ -96,22 +98,24 @@
   AxisStep ::= Axis NodeTest Predicate*
 
 ********************************************************************************/
-class axis_step_expr : public expr 
+class axis_step_expr : public expr
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
 
 protected:
   axis_kind_t             theAxis;
   bool                    theReverseOrder;
-  expr_t                  theNodeTest;
+  expr                  * theNodeTest;
 
 public:
   static bool is_reverse_axis(axis_kind_t kind);
 
+protected:
+  axis_step_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&);
+
 public:
-  axis_step_expr(static_context* sctx, const QueryLoc&);
-
   axis_kind_t getAxis() const { return theAxis; }
 
   void setAxis(axis_kind_t v) { theAxis = v; }
@@ -122,16 +126,16 @@
 
   bool is_reverse_axis() const { return is_reverse_axis(getAxis()); }
 
-  match_expr* getTest() const 
+  match_expr* getTest() const
   {
-    return reinterpret_cast<match_expr*>(theNodeTest.getp());
+    return reinterpret_cast<match_expr*>(theNodeTest);
   }
 
-  void setTest(rchandle<match_expr> v) { theNodeTest = v.getp(); }
+  void setTest(match_expr* v);
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t &) const;
+  expr* clone(substitution_t &) const;
 
   void accept(expr_visitor&);
 
@@ -155,10 +159,11 @@
   and theNilledAllowed data members are not used.
 
 ********************************************************************************/
-class match_expr : public expr 
+class match_expr : public expr
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
 
 protected:
   match_test_t      theTestKind;
@@ -171,9 +176,10 @@
   store::Item_t     theTypeName;
   bool              theNilledAllowed;
 
+protected:
+  match_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&);
+
 public:
-  match_expr(static_context* sctx, const QueryLoc&);
-
   match_test_t getTestKind() const { return theTestKind; }
 
   void setTestKind(enum match_test_t v) { theTestKind = v; }
@@ -189,7 +195,7 @@
   const zstring& getWildName() const { return theWildName; }
 
   template<class StringType>
-  void setWildName(const StringType& v) { theWildName = v; } 
+  void setWildName(const StringType& v) { theWildName = v; }
 
   store::Item* getQName() const { return theQName.getp(); }
 
@@ -207,7 +213,7 @@
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t &) const;
+  expr* clone(substitution_t &) const;
 
   void accept(expr_visitor&);
 

=== modified file 'src/compiler/expression/script_exprs.cpp'
--- src/compiler/expression/script_exprs.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/script_exprs.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,12 +21,14 @@
 #include "compiler/expression/expr.h"
 #include "compiler/expression/expr_visitor.h"
 
+#include "compiler/api/compilercb.h"
+
 #include "functions/function.h"
 
 #include "diagnostics/assert.h"
 
 
-namespace zorba 
+namespace zorba
 {
 
 DEF_EXPR_ACCEPT(block_expr)
@@ -43,13 +45,14 @@
 
 ********************************************************************************/
 block_expr::block_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     bool allowLastUpdating,
-    std::vector<expr_t>& seq,
+    std::vector<expr*>& seq,
     std::vector<var_expr*>* assignedVars)
   :
-  expr(sctx, loc, block_expr_kind),
+  expr(ccb, sctx, loc, block_expr_kind),
   theArgs(seq)
 {
   compute_scripting_kind2(assignedVars, allowLastUpdating);
@@ -61,7 +64,7 @@
 }
 
 
-void block_expr::add_at(csize pos, const expr_t& arg)
+void block_expr::add_at(csize pos, expr* arg)
 {
   assert(arg->get_expr_kind() != var_set_expr_kind);
 
@@ -70,7 +73,7 @@
 }
 
 
-void block_expr::compute_scripting_kind() 
+void block_expr::compute_scripting_kind()
 {
   ZORBA_ASSERT(false);
 }
@@ -78,7 +81,7 @@
 
 void block_expr::compute_scripting_kind2(
     std::vector<var_expr*>* assignedVars,
-    bool allowLastUpdating) 
+    bool allowLastUpdating)
 {
   bool vacuous = true;
 
@@ -94,7 +97,7 @@
 
     if (theArgs[i]->get_expr_kind() == var_decl_expr_kind)
     {
-      var_decl_expr* varDeclExpr = static_cast<var_decl_expr*>(theArgs[i].getp());
+      var_decl_expr* varDeclExpr = static_cast<var_decl_expr*>(theArgs[i]);
 
       var_expr* varExpr = varDeclExpr->get_var_expr();
 
@@ -106,7 +109,7 @@
 
         if (kind != VACUOUS_EXPR)
           vacuous = false;
-        
+
         theScriptingKind |= kind;
       }
 
@@ -116,9 +119,9 @@
         {
           std::vector<var_expr*>::iterator ite = (*assignedVars).begin();
           std::vector<var_expr*>::iterator end = (*assignedVars).end();
-          
+
           ite = std::find(ite, end, varExpr);
-          
+
           if (ite != end)
             ite = (*assignedVars).erase(ite);
           else
@@ -163,13 +166,13 @@
 }
 
 
-expr_t block_expr::clone(substitution_t& subst) const
+expr* block_expr::clone(substitution_t& subst) const
 {
-  checked_vector<expr_t> seq2;
+  checked_vector<expr*> seq2;
   for (csize i = 0; i < theArgs.size(); ++i)
     seq2.push_back(theArgs[i]->clone(subst));
 
-  return new block_expr(theSctx, get_loc(), true, seq2, NULL);
+  return theCCB->theEM->create_block_expr(theSctx, get_loc(), true, seq2, NULL);
 }
 
 
@@ -177,12 +180,13 @@
 
 ********************************************************************************/
 apply_expr::apply_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& inExpr,
+    expr* inExpr,
     bool discardXDM)
   :
-  expr(sctx, loc, apply_expr_kind),
+  expr(ccb, sctx, loc, apply_expr_kind),
   theExpr(inExpr),
   theDiscardXDM(discardXDM)
 {
@@ -201,9 +205,9 @@
 }
 
 
-expr_t apply_expr::clone(substitution_t& subst) const
+expr* apply_expr::clone(substitution_t& subst) const
 {
-  return new apply_expr(theSctx, get_loc(), theExpr->clone(subst), theDiscardXDM);
+  return theCCB->theEM->create_apply_expr(theSctx, get_loc(), theExpr->clone(subst), theDiscardXDM);
 }
 
 
@@ -211,12 +215,13 @@
 
 ********************************************************************************/
 var_decl_expr::var_decl_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const var_expr_t& varExpr,
-    const expr_t& initExpr)
+    var_expr* varExpr,
+    expr* initExpr)
   :
-  expr(sctx, loc, var_decl_expr_kind),
+  expr(ccb, sctx, loc, var_decl_expr_kind),
   theVarExpr(varExpr),
   theInitExpr(initExpr)
 {
@@ -234,8 +239,8 @@
 {
   // Note: var_expr objs for global vars live longer than their associated
   // var_decl_expr, because such var_expr objs are also registered in the sctx.
-  if (theInitExpr)
-    theVarExpr->remove_set_expr(this);
+  //if (theInitExpr)
+  //  theVarExpr->remove_set_expr(this);
 }
 
 
@@ -257,12 +262,12 @@
 }
 
 
-expr_t var_decl_expr::clone(substitution_t& s) const
+expr* var_decl_expr::clone(substitution_t& s) const
 {
-  var_expr_t varCopy(new var_expr(*theVarExpr));
-  s[theVarExpr.getp()] = varCopy.getp();
+  var_expr* varCopy = theCCB->theEM->create_var_expr(*theVarExpr);
+  s[theVarExpr] = varCopy;
 
-  return new var_decl_expr(theSctx,
+  return theCCB->theEM->create_var_decl_expr(theSctx,
                            get_loc(),
                            varCopy,
                            (theInitExpr ? theInitExpr->clone(s) : NULL));
@@ -273,16 +278,17 @@
 
 ********************************************************************************/
 var_set_expr::var_set_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const var_expr_t& varExpr,
-    const expr_t& setExpr)
+    var_expr* varExpr,
+    expr* setExpr)
   :
-  expr(sctx, loc, var_set_expr_kind),
+  expr(ccb, sctx, loc, var_set_expr_kind),
   theVarExpr(varExpr),
   theExpr(setExpr)
 {
-  assert(varExpr->get_kind() == var_expr::prolog_var || 
+  assert(varExpr->get_kind() == var_expr::prolog_var ||
          varExpr->get_kind() == var_expr::local_var);
 
   compute_scripting_kind();
@@ -296,7 +302,7 @@
 
 var_set_expr::~var_set_expr()
 {
-  theVarExpr->remove_set_expr(this);
+  //theVarExpr->remove_set_expr(this);
 }
 
 
@@ -313,15 +319,15 @@
 }
 
 
-expr_t var_set_expr::clone(substitution_t& s) const
+expr* var_set_expr::clone(substitution_t& s) const
 {
-  expr_t varClone = theVarExpr->clone(s);
+  expr* varClone = theVarExpr->clone(s);
 
   ZORBA_ASSERT(varClone->get_expr_kind() == var_expr_kind);
 
-  return new var_set_expr(theSctx,
+  return theCCB->theEM->create_var_set_expr(theSctx,
                           get_loc(),
-                          static_cast<var_expr*>(varClone.getp()),
+                          static_cast<var_expr*>(varClone),
                           theExpr->clone(s));
 }
 
@@ -330,11 +336,12 @@
 
 ********************************************************************************/
 exit_expr::exit_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& inExpr)
+    expr* inExpr)
   :
-  expr(sctx, loc, exit_expr_kind),
+  expr(ccb, sctx, loc, exit_expr_kind),
   theExpr(inExpr),
   theCatcherExpr(NULL)
 {
@@ -361,9 +368,9 @@
 }
 
 
-expr_t exit_expr::clone(substitution_t& subst) const
+expr* exit_expr::clone(substitution_t& subst) const
 {
-  expr* clone = new exit_expr(theSctx, get_loc(), get_expr()->clone(subst));
+  expr* clone = theCCB->theEM->create_exit_expr(theSctx, get_loc(), get_expr()->clone(subst));
 
   subst[this] = clone;
 
@@ -375,12 +382,13 @@
 
 ********************************************************************************/
 exit_catcher_expr::exit_catcher_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& inExpr,
+    expr* inExpr,
     std::vector<expr*>& exitExprs)
   :
-  expr(sctx, loc, exit_catcher_expr_kind),
+  expr(ccb, sctx, loc, exit_catcher_expr_kind),
   theExpr(inExpr)
 {
   theExitExprs.swap(exitExprs);
@@ -430,9 +438,9 @@
 }
 
 
-expr_t exit_catcher_expr::clone(substitution_t& subst) const
+expr* exit_catcher_expr::clone(substitution_t& subst) const
 {
-  expr_t clonedInput = get_expr()->clone(subst);
+  expr* clonedInput = get_expr()->clone(subst);
 
   std::vector<expr*> clonedExits;
   std::vector<expr*>::const_iterator ite = theExitExprs.begin();
@@ -444,7 +452,7 @@
     clonedExits.push_back(subst[*ite]);
   }
 
-  return new exit_catcher_expr(theSctx, get_loc(), clonedInput, clonedExits);
+  return theCCB->theEM->create_exit_catcher_expr(theSctx, get_loc(), clonedInput, clonedExits);
 }
 
 
@@ -452,9 +460,9 @@
 /*******************************************************************************
 
 ********************************************************************************/
-flowctl_expr::flowctl_expr(static_context* sctx, const QueryLoc& loc, enum action action)
+flowctl_expr::flowctl_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, enum action action)
   :
-  expr(sctx, loc, flowctl_expr_kind),
+  expr(ccb, sctx, loc, flowctl_expr_kind),
   theAction(action)
 {
   compute_scripting_kind();
@@ -471,18 +479,18 @@
 }
 
 
-expr_t flowctl_expr::clone(substitution_t& subst) const
+expr* flowctl_expr::clone(substitution_t& subst) const
 {
-  return new flowctl_expr(theSctx, get_loc(), get_action());
+  return theCCB->theEM->create_flowctl_expr(theSctx, get_loc(), get_action());
 }
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-while_expr::while_expr(static_context* sctx, const QueryLoc& loc, expr_t body)
-  : 
-  expr(sctx, loc, while_expr_kind),
+while_expr::while_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, expr* body)
+  :
+  expr(ccb, sctx, loc, while_expr_kind),
   theBody(body)
 {
   compute_scripting_kind();
@@ -491,7 +499,7 @@
 
 void while_expr::compute_scripting_kind()
 {
-  block_expr* seqExpr = static_cast<block_expr*>(theBody.getp());
+  block_expr* seqExpr = static_cast<block_expr*>(theBody);
 
   expr* condExpr = (*seqExpr)[0];
 
@@ -516,11 +524,10 @@
 }
 
 
-expr_t while_expr::clone(substitution_t& subst) const
+expr* while_expr::clone(substitution_t& subst) const
 {
-  return new while_expr(theSctx, get_loc(), get_body()->clone(subst));
+  return theCCB->theEM->create_while_expr(theSctx, get_loc(), get_body()->clone(subst));
 }
-
 
 
 }

=== modified file 'src/compiler/expression/script_exprs.h'
--- src/compiler/expression/script_exprs.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/script_exprs.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,7 +22,7 @@
 #include "compiler/expression/expr_base.h"
 
 
-namespace zorba 
+namespace zorba
 {
 
 class expr_visitor;
@@ -94,7 +94,7 @@
   contrast, the grammar allows only the last operand to be simple; all the other
   operands must be sequential or vacuous.
 
-  EXCEPTION: At the top level, a Program consists of 0 or more statements 
+  EXCEPTION: At the top level, a Program consists of 0 or more statements
   followed by an expr, which may be updating. In the case of a "normal" program,
   we can wrap this expr with an apply_expr and model the Program as a block
   expr. However, this does not work in the case of eval-updating. The solution
@@ -103,23 +103,26 @@
 ********************************************************************************/
 class block_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
-  std::vector<expr_t> theArgs;
+  std::vector<expr*> theArgs;
 
-public:
+protected:
   block_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
       bool allowLastUpdating,
-      std::vector<expr_t>& seq,
+      std::vector<expr*>& seq,
       std::vector<var_expr*>* assignedVars);
 
+public:
   ~block_expr();
 
-  void add_at(csize pos, const expr_t& arg);
+  void add_at(csize pos, expr* arg);
 
   csize size() const { return theArgs.size(); }
 
@@ -127,7 +130,7 @@
 
   expr* operator[](csize i) { return theArgs[i]; }
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -136,7 +139,7 @@
 private:
   void compute_scripting_kind();
 
-  void compute_scripting_kind2(    
+  void compute_scripting_kind2(
       std::vector<var_expr*>* assignedVars,
       bool allowLastUpdating) ;
 };
@@ -145,33 +148,36 @@
 /*******************************************************************************
   ApplyStatement ::= ExprSimple ";"
 ********************************************************************************/
-class apply_expr : public expr 
+class apply_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 private:
-  expr_t theExpr;
+  expr * theExpr;
   bool   theDiscardXDM;
 
-public:
+protected:
   apply_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
-      const expr_t& inExpr,
+      expr* inExpr,
       bool discardXDM);
 
-  expr* get_expr() const { return theExpr.getp(); }
+public:
+  expr* get_expr() const { return theExpr;}
 
   bool discardsXDM() const { return theDiscardXDM; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 
@@ -184,7 +190,7 @@
 
   Annotation ::= "%" EQName ("(" Literal ("," Literal)* ")")?
 
-  VarDecl ::= "variable" "$" VarName TypeDeclaration? 
+  VarDecl ::= "variable" "$" VarName TypeDeclaration?
               ((":=" VarValue) | ("external" (":=" VarDefaultValue)?))
 
   For Local Var:
@@ -193,9 +199,9 @@
   VarDeclExpr ::= ("local" Annotation*)? "variable" "$" VarName TypeDeclaration?
                   (":=" ExprSingle)?
 
-  var_decl_expr is used to declare block-local and prolog variables (including 
+  var_decl_expr is used to declare block-local and prolog variables (including
   the context item, if it is declared in the prolog). During runtime, the
-  associated iterator creates in the local dynamic context a binding between 
+  associated iterator creates in the local dynamic context a binding between
   the variable id and the variable value. If the declaration includes an
   initializing expr, the iterator computes the initExpr and stores the resulting
   value inside this binding.
@@ -203,31 +209,34 @@
   Note: the init expr must be non-updating. For global vars, it must also be
   non-sequential.
 ********************************************************************************/
-class var_decl_expr : public expr 
+class var_decl_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
-  var_expr_t theVarExpr;
-  expr_t     theInitExpr;
+  var_expr * theVarExpr;
+  expr     * theInitExpr;
 
-public:
+protected:
   var_decl_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
-      const var_expr_t& varExpr,
-      const expr_t& initExpr);
+      var_expr* varExpr,
+      expr* initExpr);
 
+public:
   ~var_decl_expr();
 
-  var_expr* get_var_expr() const { return theVarExpr.getp(); }
+  var_expr* get_var_expr() const { return theVarExpr; }
 
-  expr* get_init_expr() const { return theInitExpr.getp(); }
+  expr* get_init_expr() const { return theInitExpr; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -242,35 +251,38 @@
   The RHS of the assignment must be a non-updating expr.
 
   var_set_expr is used to assign a value to a prolog or block-local var. During
-  runtime, the function computes theExpr and stores the resulting value inside 
+  runtime, the function computes theExpr and stores the resulting value inside
   the appropriate dynamic ctx (global or local), at the location that is identified
   by the variable id.
 ********************************************************************************/
-class var_set_expr : public expr 
+class var_set_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
-  var_expr_t theVarExpr;
-  expr_t     theExpr;
+  var_expr * theVarExpr;
+  expr     * theExpr;
 
-public:
+protected:
   var_set_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
-      const var_expr_t& varExpr,
-      const expr_t& setExpr);
+      var_expr* varExpr,
+      expr* setExpr);
 
+public:
   ~var_set_expr();
 
-  var_expr* get_var_expr() const { return theVarExpr.getp(); }
+  var_expr* get_var_expr() const { return theVarExpr; }
 
-  expr* get_expr() const { return theExpr.getp(); }
+  expr* get_expr() const { return theExpr; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
@@ -281,32 +293,38 @@
 /*******************************************************************************
   ExitExpr ::= "exit" "with" ExprSingle
 ********************************************************************************/
-class exit_expr : public expr 
+class exit_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 private:
-  expr_t               theExpr;
+  expr               * theExpr;
 
   exit_catcher_expr  * theCatcherExpr;
 
+protected:
+  exit_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      const QueryLoc& loc,
+      expr* inExpr);
+
 public:
-  exit_expr(static_context* sctx, const QueryLoc& loc, const expr_t& inExpr);
-
   ~exit_expr();
 
-  expr* get_expr() const { return theExpr.getp(); }
+  expr* get_expr() const { return theExpr; }
 
   void setCatcherExpr(exit_catcher_expr* e) { theCatcherExpr = e; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 
@@ -323,54 +341,58 @@
   -------------
   All the exit_exprs that appear in the body of the udf.
 ********************************************************************************/
-class exit_catcher_expr : public expr 
+class exit_catcher_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 private:
-  expr_t             theExpr;
+  expr             * theExpr;
 
   std::vector<expr*> theExitExprs;
 
-public:
+protected:
   exit_catcher_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
-      const expr_t& inExpr,
+      expr* inExpr,
       std::vector<expr*>& exitExprs);
 
+public:
   ~exit_catcher_expr();
 
-  expr* get_expr() const { return theExpr.getp(); }
+  expr* get_expr() const { return theExpr; }
 
-  std::vector<expr*>::const_iterator exitExprsBegin() const 
+  std::vector<expr*>::const_iterator exitExprsBegin() const
   {
-    return theExitExprs.begin(); 
+    return theExitExprs.begin();
   }
 
-  std::vector<expr*>::const_iterator exitExprsEnd() const 
+  std::vector<expr*>::const_iterator exitExprsEnd() const
   {
-    return theExitExprs.end(); 
+    return theExitExprs.end();
   }
 
   void removeExitExpr(const expr* exitExpr);
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-class flowctl_expr : public expr 
+class flowctl_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
@@ -380,48 +402,51 @@
 protected:
   enum action theAction;
 
+protected:
+  flowctl_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, enum action action);
+
 public:
-  flowctl_expr(static_context* sctx, const QueryLoc& loc, enum action action);
-
   enum action get_action() const { return theAction; }
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void compute_scripting_kind();
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 
 /*******************************************************************************
-	WhileExpr ::= "while" "(" Expr ")" Statement
+  WhileExpr ::= "while" "(" Expr ")" Statement
 
   theBody : It is a block_expr, whose 1st child is the following expr:
             if (cond_expr) then () else break
             The subsequent children are what it generated by the Statement.
 ********************************************************************************/
-class while_expr : public expr 
+class while_expr : public expr
 {
+  friend class ExprManager;
   friend class ExprIterator;
   friend class expr;
 
 protected:
-  expr_t theBody;
+  expr* theBody;
+
+protected:
+  while_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, expr* body);
 
 public:
-  while_expr(static_context* sctx, const QueryLoc& loc, expr_t body);
-
-  expr* get_body() const { return theBody.getp(); }
+  expr* get_body() const { return theBody; }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 

=== modified file 'src/compiler/expression/update_exprs.cpp'
--- src/compiler/expression/update_exprs.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/update_exprs.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -19,10 +19,12 @@
 #include "compiler/expression/var_expr.h"
 #include "compiler/expression/expr_visitor.h"
 
+#include "compiler/api/compilercb.h"
+
 #include "diagnostics/assert.h"
 #include "diagnostics/xquery_diagnostics.h"
 
-namespace zorba 
+namespace zorba
 {
 
 
@@ -37,14 +39,15 @@
 
 ********************************************************************************/
 update_expr_base::update_expr_base(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     expr_kind_t kind,
-    const expr_t& targetExpr,
-    const expr_t& sourceExpr)
+    expr* targetExpr,
+    expr* sourceExpr)
   :
-	expr(sctx, loc, kind),
-	theTargetExpr(targetExpr),
+  expr(ccb, sctx, loc, kind),
+  theTargetExpr(targetExpr),
   theSourceExpr(sourceExpr)
 {
   compute_scripting_kind();
@@ -66,21 +69,22 @@
 
 ********************************************************************************/
 insert_expr::insert_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     store::UpdateConsts::InsertType aType,
-    const expr_t& sourceExpr,
-    const expr_t& targetExpr)
+    expr* sourceExpr,
+    expr* targetExpr)
   :
-	update_expr_base(sctx, loc, insert_expr_kind, targetExpr, sourceExpr),
+  update_expr_base(ccb, sctx, loc, insert_expr_kind, targetExpr, sourceExpr),
   theType(aType)
 {
 }
 
 
-expr_t insert_expr::clone(substitution_t& subst) const
+expr* insert_expr::clone(substitution_t& subst) const
 {
-  return new insert_expr(theSctx,
+  return theCCB->theEM->create_insert_expr(theSctx,
                          get_loc(),
                          getType(),
                          getSourceExpr()->clone(subst),
@@ -92,18 +96,19 @@
 
 ********************************************************************************/
 delete_expr::delete_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& targetExpr)
+    expr* targetExpr)
   :
-	update_expr_base(sctx, loc, delete_expr_kind, targetExpr, NULL)
+  update_expr_base(ccb, sctx, loc, delete_expr_kind, targetExpr, NULL)
 {
 }
 
 
-expr_t delete_expr::clone(substitution_t& subst) const
+expr* delete_expr::clone(substitution_t& subst) const
 {
-  return new delete_expr(theSctx, get_loc(), getTargetExpr()->clone(subst));
+  return theCCB->theEM->create_delete_expr(theSctx, get_loc(), getTargetExpr()->clone(subst));
 }
 
 
@@ -111,21 +116,22 @@
 
 ********************************************************************************/
 replace_expr::replace_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     store::UpdateConsts::ReplaceType aType,
-    const expr_t& targetExpr,
-    const expr_t& replaceExpr)
+    expr* targetExpr,
+    expr* replaceExpr)
   :
-	update_expr_base(sctx, loc, replace_expr_kind, targetExpr, replaceExpr),
+  update_expr_base(ccb, sctx, loc, replace_expr_kind, targetExpr, replaceExpr),
   theType(aType)
 {
 }
 
 
-expr_t replace_expr::clone(substitution_t& subst) const
+expr* replace_expr::clone(substitution_t& subst) const
 {
-  return new replace_expr(theSctx,
+  return theCCB->theEM->create_replace_expr(theSctx,
                           get_loc(),
                           getType(),
                           getTargetExpr()->clone(subst),
@@ -137,19 +143,20 @@
 
 ********************************************************************************/
 rename_expr::rename_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
-    const expr_t& targetExpr,
-    const expr_t& nameExpr)
+    expr* targetExpr,
+    expr* nameExpr)
   :
-	update_expr_base(sctx, loc, rename_expr_kind, targetExpr, nameExpr)
+  update_expr_base(ccb, sctx, loc, rename_expr_kind, targetExpr, nameExpr)
 {
 }
 
 
-expr_t rename_expr::clone(substitution_t& subst) const
+expr* rename_expr::clone(substitution_t& subst) const
 {
-  return new rename_expr(theSctx,
+  return theCCB->theEM->create_rename_expr(theSctx,
                          get_loc(),
                          getTargetExpr()->clone(subst),
                          getNameExpr()->clone(subst));
@@ -159,7 +166,7 @@
 /*******************************************************************************
 
 ********************************************************************************/
-copy_clause::copy_clause(var_expr_t aVar, expr_t aExpr)
+copy_clause::copy_clause(var_expr* aVar, expr* aExpr)
   :
   theVar(aVar),
   theExpr(aExpr)
@@ -170,36 +177,37 @@
 
 copy_clause::~copy_clause()
 {
-  if(theVar)
+  if (theVar)
     theVar->set_copy_clause(NULL);
 }
 
 
-copy_clause_t copy_clause::clone(expr::substitution_t& subst) const 
+copy_clause_t copy_clause::clone(expr::substitution_t& subst) const
 {
   ZORBA_ASSERT(theVar && theExpr);
 
-  expr_t domainCopy = theExpr->clone(subst);
-
-  var_expr_t varCopy = new var_expr(*theVar);
-
-  subst[theVar.getp()] = varCopy.getp();
-
-  return new copy_clause(varCopy, domainCopy);   
+  expr* domainCopy = theExpr->clone(subst);
+
+  var_expr* varCopy = theExpr->get_ccb()->theEM->create_var_expr(*theVar);
+
+  subst[theVar] = varCopy;
+
+  return new copy_clause(varCopy, domainCopy);
 }
 
 
 transform_expr::transform_expr(
+    CompilerCB* ccb,
     static_context* sctx,
-	  const QueryLoc& loc)
+    const QueryLoc& loc)
   :
-	expr(sctx, loc, transform_expr_kind)
+  expr(ccb, sctx, loc, transform_expr_kind)
 {
   theScriptingKind = SIMPLE_EXPR;
 }
 
 
-void transform_expr::setModifyExpr(expr* e) 
+void transform_expr::setModifyExpr(expr* e)
 {
   theModifyExpr = e;
 
@@ -238,15 +246,16 @@
 }
 
 
-expr_t transform_expr::clone(substitution_t& subst) const 
+expr* transform_expr::clone(substitution_t& subst) const
 {
   ZORBA_ASSERT(theModifyExpr && theReturnExpr);
 
-  rchandle<transform_expr> cloneExpr(new transform_expr(theSctx, get_loc()));
+  transform_expr* cloneExpr =
+    theCCB->theEM->create_transform_expr(theSctx, get_loc());
 
   for (std::vector<copy_clause_t>::const_iterator lIter = theCopyClauses.begin();
        lIter != theCopyClauses.end();
-       ++lIter) 
+       ++lIter)
   {
     cloneExpr->add_back((*lIter)->clone(subst));
   }
@@ -254,7 +263,7 @@
   cloneExpr->setModifyExpr(theModifyExpr->clone(subst));
   cloneExpr->setReturnExpr(theReturnExpr->clone(subst));
 
-  return cloneExpr.getp();
+  return cloneExpr;
 }
 
 

=== modified file 'src/compiler/expression/update_exprs.h'
--- src/compiler/expression/update_exprs.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/update_exprs.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -22,13 +22,13 @@
 #include "compiler/expression/expr_base.h"
 
 
-namespace zorba 
+namespace zorba
 {
 
 
 /////////////////////////////////////////////////////////////////////////
 //                                                                     //
-//	Update expressions                                                 //
+//  Update expressions                                                 //
 //  [http://www.w3.org/TR/xqupdate/]                                   //
 //                                                                     //
 /////////////////////////////////////////////////////////////////////////
@@ -40,20 +40,21 @@
 class update_expr_base : public expr
 {
 protected:
-	expr_t  theTargetExpr;
-	expr_t  theSourceExpr;
+  expr * theTargetExpr;
+  expr * theSourceExpr;
 
 public:
-	update_expr_base(
+  update_expr_base(
+    CompilerCB* ccb,
     static_context* sctx,
-		const QueryLoc&,
+    const QueryLoc&,
     expr_kind_t kind,
-		const expr_t& targetExpr,
-    const expr_t& sourceExpr);
-
-	expr* getTargetExpr() const { return theTargetExpr.getp(); }
-
-	expr* getSourceExpr() const { return theSourceExpr.getp(); }
+    expr* targetExpr,
+    expr* sourceExpr);
+
+  expr* getTargetExpr() const { return theTargetExpr; }
+
+  expr* getSourceExpr() const { return theSourceExpr; }
 
   void compute_scripting_kind();
 };
@@ -66,25 +67,29 @@
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
 
 protected:
   store::UpdateConsts::InsertType theType;
 
-public:
-	insert_expr(
+
+protected:
+  insert_expr(
+    CompilerCB* ccb,
     static_context* sctx,
-		const QueryLoc&,
+    const QueryLoc&,
     store::UpdateConsts::InsertType,
-		const expr_t& aSourceExpr,
-		const expr_t& aTargetExpr);
+    expr* aSourceExpr,
+    expr* aTargetExpr);
 
+public:
   store::UpdateConsts::InsertType getType() const { return theType; }
-  
-  expr_t clone(substitution_t& s) const;
+
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 
@@ -95,15 +100,18 @@
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
+
+
+protected:
+  delete_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, expr*);
 
 public:
-	delete_expr(static_context* sctx, const QueryLoc&, const expr_t&);
-
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 
@@ -114,27 +122,30 @@
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
 
 protected:
   store::UpdateConsts::ReplaceType theType;
 
-public:
-	replace_expr(
+protected:
+  replace_expr(
+    CompilerCB* ccb,
     static_context* sctx,
-		const QueryLoc&,
+    const QueryLoc&,
     store::UpdateConsts::ReplaceType aType,
-		const expr_t&,
-		const expr_t&);
+    expr*,
+    expr*);
 
+public:
   store::UpdateConsts::ReplaceType getType() const { return theType; }
 
-	expr* getReplaceExpr() const { return theSourceExpr.getp(); }
+  expr* getReplaceExpr() const { return theSourceExpr; }
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 
@@ -145,21 +156,24 @@
 {
   friend class ExprIterator;
   friend class expr;
+  friend class ExprManager;
 
-public:
-	rename_expr(
+protected:
+  rename_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc&,
-      const expr_t&,
-      const expr_t&);
-
-	expr* getNameExpr() const { return theSourceExpr.getp(); }
-
-  expr_t clone(substitution_t& s) const;
+      expr*,
+      expr*);
+
+public:
+  expr* getNameExpr() const { return theSourceExpr; }
+
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 
@@ -176,19 +190,24 @@
   friend class expr;
   friend class transform_expr;
   friend class ExprIterator;
+  friend class ExprManager;
 
 private:
-  var_expr_t theVar;
-  expr_t     theExpr;
+  var_expr  * theVar;
+  expr      * theExpr;
+  CompilerCB* theExprManager;
+
+protected:
+  copy_clause(var_expr* aVar, expr* aExpr);
 
 public:
-  copy_clause(var_expr_t aVar, expr_t aExpr);
-
   ~copy_clause();
 
-  var_expr* getVar()  const { return theVar.getp(); }
-
-  expr* getExpr() const { return theExpr.getp(); }
+  void free() {}
+
+  var_expr* getVar()  const { return theVar; }
+
+  expr* getExpr() const { return theExpr; }
 
   copy_clause_t clone(expr::substitution_t& s) const;
 
@@ -200,42 +219,44 @@
 {
   friend class ExprIterator;
   friend class expr;
-
-protected:
-	std::vector<copy_clause_t> theCopyClauses;
-	expr_t                     theModifyExpr;
-	expr_t                     theReturnExpr;
+  friend class ExprManager;
+
+protected:
+  std::vector<copy_clause_t> theCopyClauses;
+  expr                     * theModifyExpr;
+  expr                     * theReturnExpr;
+
+protected:
+  transform_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc);
 
 public:
-	transform_expr(static_context* sctx, const QueryLoc& loc);
-
-	expr_t getModifyExpr() const { return theModifyExpr; }
-
-	expr_t getReturnExpr() const { return theReturnExpr; }
+  expr* getModifyExpr() const { return theModifyExpr; }
+
+  expr* getReturnExpr() const { return theReturnExpr; }
 
   void setModifyExpr(expr* e);
 
   void setReturnExpr(expr* e);
 
-	void add_back(copy_clause_t c);
-
-	copy_clause_t const& operator[](int i) const { return theCopyClauses[i]; }
-
-	std::vector<copy_clause_t>::const_iterator begin() const
+  void add_back(copy_clause_t c);
+
+  copy_clause_t const& operator[](int i) const { return theCopyClauses[i]; }
+
+  std::vector<copy_clause_t>::const_iterator begin() const
   { return theCopyClauses.begin(); }
 
-	std::vector<copy_clause_t>::const_iterator end() const
+  std::vector<copy_clause_t>::const_iterator end() const
   { return theCopyClauses.end(); }
 
-	csize size() const { return theCopyClauses.size(); }
+  csize size() const { return theCopyClauses.size(); }
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& s) const;
+  expr* clone(substitution_t& s) const;
 
   void accept(expr_visitor&);
 
-	std::ostream& put(std::ostream&) const;
+  std::ostream& put(std::ostream&) const;
 };
 
 

=== modified file 'src/compiler/expression/var_expr.cpp'
--- src/compiler/expression/var_expr.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/var_expr.cpp	2012-08-14 12:29:44 +0000
@@ -21,6 +21,7 @@
 #include "compiler/expression/update_exprs.h"
 #include "compiler/expression/flwor_expr.h"
 #include "compiler/expression/expr_visitor.h"
+#include "compiler/api/compilercb.h"
 
 #include "types/typeops.h"
 
@@ -67,12 +68,13 @@
 
 ********************************************************************************/
 var_expr::var_expr(
+    CompilerCB* ccb,
     static_context* sctx,
     const QueryLoc& loc,
     var_kind k,
     store::Item* name)
   :
-  expr(sctx, loc, var_expr_kind),
+  expr(ccb, sctx, loc, var_expr_kind),
   theUniqueId(0),
   theVarKind(k),
   theName(name),
@@ -292,7 +294,7 @@
 /*******************************************************************************
 
 ********************************************************************************/
-void var_expr::remove_set_expr(expr* e) 
+void var_expr::remove_set_expr(expr* e)
 {
   assert(theVarKind == local_var || theVarKind == prolog_var);
 
@@ -334,7 +336,7 @@
 /*******************************************************************************
 
 ********************************************************************************/
-expr::expr_t var_expr::clone(expr::substitution_t& subst) const
+expr* var_expr::clone(expr::substitution_t& subst) const
 {
   expr::subst_iter_t i = subst.find(this);
 

=== modified file 'src/compiler/expression/var_expr.h'
--- src/compiler/expression/var_expr.h	2012-08-14 11:13:50 +0000
+++ src/compiler/expression/var_expr.h	2012-08-14 12:29:44 +0000
@@ -19,7 +19,7 @@
 
 #include "compiler/expression/expr_base.h"
 
-namespace zorba 
+namespace zorba
 {
 
 class flwor_clause;
@@ -27,10 +27,14 @@
 class for_clause;
 class copy_clause;
 class var_expr;
+<<<<<<< TREE
 class VarInfo;
 
 typedef rchandle<var_expr> var_expr_t;
 
+=======
+class VarInfo;
+>>>>>>> MERGE-SOURCE
 
 /******************************************************************************
 
@@ -77,7 +81,7 @@
 
   theFlworClause:
   ---------------
-  If this is a var declared in flwor clause, theFlworClause points to the 
+  If this is a var declared in flwor clause, theFlworClause points to the
   defining clause. That clause also contains the defining expr for the var
   and a pointer back to this var_exr.
 
@@ -91,7 +95,7 @@
   ------------
   For arg vars, it is the position, within the param list, of parameter that is
   bound to this arg var.
-  
+
   theUDF:
   -------
   For arg vars, the corresponding UDF.
@@ -120,6 +124,7 @@
 class var_expr : public expr
 {
   friend class expr;
+  friend class ExprManager;
 
 public:
   enum var_kind
@@ -175,7 +180,7 @@
 
   bool                  theIsExternal;
 
-  bool                  theIsPrivate; 
+  bool                  theIsPrivate;
 
   bool                  theIsMutable;
 
@@ -184,8 +189,9 @@
 public:
   static std::string decode_var_kind(enum var_kind);
 
-public:
+protected:
   var_expr(
+      CompilerCB* ccb,
       static_context* sctx,
       const QueryLoc& loc,
       var_kind k,
@@ -193,12 +199,22 @@
 
   var_expr(const var_expr& source);
 
-  virtual ~var_expr();
-
-  void set_var_info(VarInfo* v);
-
-  VarInfo* get_var_info() const { return theVarInfo; }
-
+<<<<<<< TREE
+  virtual ~var_expr();
+
+  void set_var_info(VarInfo* v);
+
+  VarInfo* get_var_info() const { return theVarInfo; }
+
+=======
+  virtual ~var_expr();
+
+public:
+  void set_var_info(VarInfo* v);
+
+  VarInfo* get_var_info() const { return theVarInfo; }
+
+>>>>>>> MERGE-SOURCE
   ulong get_unique_id() const { return theUniqueId; }
 
   void set_unique_id(ulong v);
@@ -260,12 +276,12 @@
   std::vector<expr*>::const_iterator setExprsBegin() const { return theSetExprs.begin(); }
 
   std::vector<expr*>::const_iterator setExprsEnd() const { return theSetExprs.end(); }
-  
+
   bool is_context_item() const;
 
   void compute_scripting_kind();
 
-  expr_t clone(substitution_t& subst) const;
+  expr* clone(substitution_t& subst) const;
 
   void accept(expr_visitor&);
 
@@ -273,16 +289,16 @@
 };
 
 
-struct GlobalBinding 
+struct GlobalBinding
 {
-  var_expr_t  theVar;
-  expr_t      theExpr;
+  var_expr  * theVar;
+  expr      * theExpr;
   bool        theIsExternal;
 
 public:
   GlobalBinding() : theIsExternal(false) {}
 
-  GlobalBinding(const var_expr_t& v, const expr_t& e, bool external)
+  GlobalBinding(var_expr* v, expr* e, bool external)
     :
     theVar(v),
     theExpr(e),

=== removed directory 'src/compiler/indexing'
=== removed file 'src/compiler/indexing/index_tools.cpp'
--- src/compiler/indexing/index_tools.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/indexing/index_tools.cpp	1970-01-01 00:00:00 +0000
@@ -1,231 +0,0 @@
-/*
- * Copyright 2006-2008 The FLWOR Foundation.
- * 
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- * 
- * http://www.apache.org/licenses/LICENSE-2.0
- * 
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#include <vector>
-#include <utility>
-
-
-#include "functions/function.h"
-
-#include "compiler/indexing/index_tools.h"
-#include "compiler/expression/flwor_expr.h"
-#include "compiler/expression/path_expr.h"
-#include "compiler/expression/fo_expr.h"
-#include "compiler/expression/expr.h"
-
-#include "system/globalenv.h"
-
-#include "store/api/item_factory.h"
-
-namespace zorba {
-
-
-/*******************************************************************************
-  Return true if the given expr is of the form "fn:collection(arg_expr)" where
-  arg_expr is a constant.
-********************************************************************************/
-static bool isHoistableCollection(expr* e)
-{
-  if (e->get_expr_kind() != fo_expr_kind) 
-    return false;
-
-  fo_expr* fo = static_cast<fo_expr *>(e);
-
-  if (fo->get_func()->getKind() != FunctionConsts::FN_COLLECTION_1 ||
-      fo->num_args() != 1) 
-    return false;
-
-  const expr* arg = fo->get_arg(0);
-  return arg->is_constant();
-}
-
-
-/*******************************************************************************
-  Assuming that the given expr is of the form "fn:collection(arg_expr)" where
-  arg_expr is a constant, return the URI of the collection (i.e., the string
-  value of the const arg).
-********************************************************************************/
-static zstring* getCollectionName(const expr* e)
-{
-  const fo_expr* fo = static_cast<const fo_expr *>(e);
-  const const_expr* arg = static_cast<const const_expr *>(fo->get_arg(0));
-  const store::Item* val = arg->get_val();
-  return val->getStringValueP();
-}
-
-
-typedef std::vector<std::pair<expr_t, expr_t> > hoisted_collections_t;
-
-
-/*******************************************************************************
-
-********************************************************************************/
-static rchandle<var_expr> createTempLetVar(short sctx, const QueryLoc& loc, int counter)
-{
-  std::stringstream ss;
-  ss << "$$opt_temp_" << (counter);
-  std::string varname = ss.str();
-  store::Item_t qname;
-  GENV_ITEMFACTORY->createQName(qname, "", "", varname.c_str());
-  rchandle<var_expr> var = new var_expr(sctx, loc, var_expr::let_var, qname);
-
-  return var;
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
-static expr_t hoistCollectionSources(
-    expr_t e,
-    hoisted_collections_t& h,
-    int& count)
-{
-  if (isHoistableCollection(e.getp())) 
-  {
-    rchandle<var_expr> var(createTempLetVar(e->get_sctx_id(), e->get_loc(), count));
-    std::pair<expr_t, expr_t> p(var.getp(), e);
-    h.push_back(p);
-    return new wrapper_expr(e->get_sctx_id(), e->get_loc(), var.getp());
-  }
-
-  expr_iterator i = e->expr_begin();
-  while(!i.done()) 
-  {
-    *i = hoistCollectionSources(*i, h, count);
-    ++i;
-  }
-
-  return e;
-}
-
-
-/*******************************************************************************
-  This function tries to see if the given expression is a map in the given var.
-  If this returns true, then it is guaranteed to be a map. If it returns false,
-  it may still be a map, but this algorithm could not determine that.
-  It assumes that the variable occurs at most once.
-********************************************************************************/
-static bool isMapInVar(const expr* e, const var_expr* var)
-{
-  if (e == var) 
-  {
-    return true;
-  }
-
-  switch(e->get_expr_kind()) 
-  {
-    case wrapper_expr_kind:
-      return isMapInVar(static_cast<const wrapper_expr *>(e)->get_expr(), var);
-
-    case flwor_expr_kind: 
-    {
-      const flwor_expr* flwor = static_cast<const flwor_expr *>(e);
-
-      for(int i = static_cast<int>(flwor->num_clauses()) - 1; i >= 0; --i) 
-      {
-        const flwor_clause* clause = (*flwor)[i];
-        bool isMap = false;
-
-        switch(clause->get_kind()) 
-        {
-          case flwor_clause::for_clause:
-            isMap = (isMap ||
-                     isMapInVar(static_cast<const for_clause *>(clause)->get_expr(), var));
-
-          case flwor_clause::let_clause:
-          case flwor_clause::where_clause:
-          case flwor_clause::order_clause:
-            continue;
-
-          default:
-            return false;
-        }
-
-        return isMap;
-      }
-    }
-
-    case relpath_expr_kind: 
-    {
-      const relpath_expr* re = static_cast<const relpath_expr *>(e);
-      return isMapInVar((*re)[0], var);
-    }
-
-    default:
-      break;
-  }
-
-  return false;
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
-void IndexTools::inferIndexCreators(ValueIndex *vi)
-{
-  expr *de = vi->getDomainExpr();
-  expr_t ne = de->clone();
-  hoisted_collections_t h;
-  int count = 0;
-  expr_t he = hoistCollectionSources(ne, h, count);
-  if (h.size() > 1) {
-    return;
-  }
-  /*
-
-    Commenting out for now. But these are the things that need to happen here:
-
-      0. Create an expression that is of the following form:
-
-        let $t := $externalVar
-        for $de in $t
-        let $k1 := key1($de)
-        let $k2 := key1($de)
-        .
-        .
-        .
-        return createTuple($k1, $k2, ... $de)
-
-      1. For each substituted variable that the DE is a map in, replace it
-      with an external variable
-
-      2. Create an IndexCreator that is capable of evaluating this expression
-      with the external variable set to the given item in the appendIndexEntries() call.
-
-      3. For each tuple that is returned by this plan, create an IndexEntry containing
-      the contents of the tuple.
-
-
-
-  expr_t e = new flwor_expr(de->get_loc(), true);
-  flwor_expr *f = static_cast<flwor_expr *>(e.getp());
-  for(hoisted_collections_t::iterator i = h.begin(); i != h.end(); ++i) {
-    var_expr *var = static_cast<var_expr *>(i->first.getp());
-    expr *ce = i->second.getp();
-    xpqStringStore *cName = getCollectionName(ce);
-
-    let_clause_t lc = new let_clause(i->first->get_loc(), var, i->second.getp());
-    var->set_flwor_clause(lc.getp());
-
-    f->add_clause(lc.getp());
-  }
-  f->set_return_expr(he.getp());
-  */
-}
-
-}
-/* vim:set et sw=2 ts=2: */

=== modified file 'src/compiler/parsetree/parsenodes.h'
--- src/compiler/parsetree/parsenodes.h	2012-08-14 11:13:50 +0000
+++ src/compiler/parsetree/parsenodes.h	2012-08-14 12:29:44 +0000
@@ -3579,9 +3579,9 @@
 
   enum ParseConstants::steptype_t get_step_type() const { return step_type; }
 
-  rchandle<exprnode> get_step_expr() const { return step_expr_h; }
+  exprnode* get_step_expr() const { return step_expr_h.getp(); }
 
-  rchandle<exprnode> get_relpath_expr() const { return relpath_expr_h; }
+  exprnode* get_relpath_expr() const { return relpath_expr_h.getp(); }
 
   bool is_implicit() const { return is_implicit_b; }
 
@@ -3615,11 +3615,11 @@
     rchandle<ReverseStep>,
     rchandle<PredicateList>);
 
-  rchandle<ForwardStep> get_forward_step() const { return forward_step_h; }
-
-  rchandle<ReverseStep> get_reverse_step() const { return reverse_step_h; }
-
-  rchandle<PredicateList> get_predicate_list() const { return predicate_list_h; }
+  ForwardStep* get_forward_step() const { return forward_step_h.getp(); }
+
+  ReverseStep* get_reverse_step() const { return reverse_step_h.getp(); }
+
+  PredicateList* get_predicate_list() const { return predicate_list_h.getp(); }
 
   enum ParseConstants::axis_kind_t get_axis_kind() const;
 
@@ -3647,11 +3647,11 @@
     const QueryLoc&,
     rchandle<AbbrevForwardStep>);
 
-  rchandle<ForwardAxis> get_forward_axis() const { return theForwardAxis; }
-
-  rchandle<parsenode> get_node_test() const { return node_test_h; }
-
-  rchandle<AbbrevForwardStep> get_abbrev_step() const { return theAbbrevStep; }
+  ForwardAxis* get_forward_axis() const { return theForwardAxis.getp(); }
+
+  parsenode* get_node_test() const { return node_test_h.getp(); }
+
+  AbbrevForwardStep* get_abbrev_step() const { return theAbbrevStep.getp(); }
 
   enum ParseConstants::axis_kind_t get_axis_kind() const;
 

=== modified file 'src/compiler/rewriter/framework/rewriter_context.cpp'
--- src/compiler/rewriter/framework/rewriter_context.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/framework/rewriter_context.cpp	2012-08-14 12:29:44 +0000
@@ -18,7 +18,9 @@
 #include <sstream>
 
 #include "compiler/rewriter/framework/rewriter_context.h"
+#include "compiler/api/compilercb.h"
 #include "compiler/expression/expr_base.h"
+#include "compiler/expression/expr_manager.h"
 
 #include "functions/udf.h"
 
@@ -31,12 +33,13 @@
 
 RewriterContext::RewriterContext(
     CompilerCB* aCompilerCB,
-    const expr_t& root,
+    expr* root,
     user_function* udf,
     const zstring& msg,
     bool orderedMode)
   :
   theCCB(aCompilerCB),
+  theEM(theCCB->theEM),
   theRoot(root),
   theUDF(udf),
   theMessage(msg),
@@ -67,19 +70,19 @@
 }
 
 
-expr_t RewriterContext::getRoot()
+expr* RewriterContext::getRoot()
 {
   return theRoot;
 }
 
 
-void RewriterContext::setRoot(expr_t root)
+void RewriterContext::setRoot(expr* root)
 {
   theRoot = root;
 }
 
 
-rchandle<var_expr> RewriterContext::createTempVar(
+var_expr* RewriterContext::createTempVar(
     static_context* sctx,
     const QueryLoc& loc,
     var_expr::var_kind kind)
@@ -89,7 +92,7 @@
   std::string varname = ss.str();
   store::Item_t qname;
   GENV_ITEMFACTORY->createQName(qname, "", "", varname.c_str());
-  rchandle<var_expr> var = new var_expr(sctx, loc, kind, qname);
+  var_expr* var = theEM->create_var_expr(sctx, loc, kind, qname);
 
   return var;
 }

=== modified file 'src/compiler/rewriter/framework/rewriter_context.h'
--- src/compiler/rewriter/framework/rewriter_context.h	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/framework/rewriter_context.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -25,8 +25,9 @@
 #include "util/dynamic_bitset.h"
 
 #include "compiler/expression/var_expr.h"
+#include "compiler/expression/expr_manager.h"
 
-namespace zorba 
+namespace zorba
 {
 
 class user_function;
@@ -45,7 +46,7 @@
   theVarIdMap:
   ------------
   Maps a var_expr to its unique "prefix" id. The "prefix" id has the following
-  property: for 2 vars v1 and v2, v1 is defined before v2 if and only if 
+  property: for 2 vars v1 and v2, v1 is defined before v2 if and only if
   prefix-id(v1) < prefix-id(v2). See index_flwor_vars() function in
   tools/expr_tools.cpp for more details.
 
@@ -66,15 +67,17 @@
 
   theFlworStack:
   --------------
-  The current "in-scope" flwor exprs, ie., flwor exprs that the rule has 
+  The current "in-scope" flwor exprs, ie., flwor exprs that the rule has
   entered but not exited yet.
 ********************************************************************************/
-class RewriterContext 
+class RewriterContext
 {
 public:
   CompilerCB                 * theCCB;
 
-  expr_t                       theRoot;
+  ExprManager                * theEM;
+
+  expr                       * theRoot;
 
   user_function              * theUDF;
 
@@ -87,13 +90,13 @@
   VarIdMap                   * theVarIdMap;
   IdVarMap                   * theIdVarMap;
   ExprVarsMap                * theExprVarsMap;
-  std::vector<expr_t>          theFlworStack;
+  std::vector<expr*>           theFlworStack;
   std::vector<bool>            theInReturnClause;
 
 public:
   RewriterContext(
       CompilerCB* cb,
-      const expr_t& root,
+      expr* root,
       user_function* udf,
       const zstring& msg,
       bool orderedMode);
@@ -102,11 +105,11 @@
 
   CompilerCB* getCompilerCB() const { return theCCB; }
 
-  expr_t getRoot();
-
-  void setRoot(expr_t root);
-
-  rchandle<var_expr> createTempVar(
+  expr* getRoot();
+
+  void setRoot(expr* root);
+
+  var_expr* createTempVar(
       static_context* sctx,
       const QueryLoc& loc,
       var_expr::var_kind kind);
@@ -126,7 +129,7 @@
   UDFCallChain(fo_expr* caller, UDFCallChain* prevCaller)
     :
     theFo(caller),
-    thePrev(prevCaller) 
+    thePrev(prevCaller)
   {
   }
 };

=== modified file 'src/compiler/rewriter/framework/rule_driver.cpp'
--- src/compiler/rewriter/framework/rule_driver.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/framework/rule_driver.cpp	2012-08-14 12:29:44 +0000
@@ -58,7 +58,7 @@
     for (rules_t::iterator i = m_rules.begin(); i != end; ++i)
     {
       bool rule_modified = false;
-      expr_t newRoot = (*i)->apply(rCtx, &*rCtx.getRoot(), rule_modified);
+      expr* newRoot = (*i)->apply(rCtx, &*rCtx.getRoot(), rule_modified);
 
       if (newRoot != NULL)
       {
@@ -94,7 +94,7 @@
 {
   bool modified = false;
 
-  expr_t newRoot = theRule->apply(rCtx, &*rCtx.getRoot(), modified);
+  expr* newRoot = theRule->apply(rCtx, &*rCtx.getRoot(), modified);
 
   if (newRoot != NULL)
   {

=== modified file 'src/compiler/rewriter/rewriters/default_optimizer.cpp'
--- src/compiler/rewriter/rewriters/default_optimizer.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rewriters/default_optimizer.cpp	2012-08-14 12:29:44 +0000
@@ -28,7 +28,7 @@
 #include "system/properties.h"
 
 
-namespace zorba 
+namespace zorba
 {
 
 class FoldRules : public RuleMajorDriver
@@ -160,7 +160,7 @@
     HoistRule rule;
     bool local_modified = false;
 
-    expr_t e = rule.apply(rCtx, rCtx.getRoot().getp(), local_modified);
+    expr* e = rule.apply(rCtx, rCtx.getRoot(), local_modified);
 
     if (e != rCtx.getRoot())
       rCtx.setRoot(e);
@@ -170,7 +170,7 @@
     {
       modified = true;
 
-      if (Properties::instance()->printIntermediateOpt()) 
+      if (Properties::instance()->printIntermediateOpt())
       {
         std::cout << "After hoisting : " << std::endl;
         rCtx.getRoot()->put(std::cout) << std::endl;
@@ -211,9 +211,9 @@
                                          freeset,
                                          *rCtx.theExprVarsMap);
 
-      local_modified = false; 
+      local_modified = false;
 
-      expr_t e = rule.apply(rCtx, rCtx.getRoot().getp(), local_modified);
+      expr* e = rule.apply(rCtx, rCtx.getRoot(), local_modified);
 
       if (e != rCtx.getRoot())
         rCtx.setRoot(e);
@@ -222,7 +222,7 @@
       {
         modified = true;
 
-        if (Properties::instance()->printIntermediateOpt()) 
+        if (Properties::instance()->printIntermediateOpt())
         {
           std::cout << "After index join : " << std::endl;
           rCtx.getRoot()->put(std::cout) << std::endl;

=== modified file 'src/compiler/rewriter/rules/expr_minimize_rules.cpp'
--- src/compiler/rewriter/rules/expr_minimize_rules.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rules/expr_minimize_rules.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -28,7 +28,7 @@
 
 #include "types/typeops.h"
 
-namespace zorba 
+namespace zorba
 {
 
 static expr_t get_constant_if_typequant_one(expr* e, bool& modified);
@@ -38,8 +38,8 @@
 /*******************************************************************************
   This rule looks for exprs of the form:
 
-  FN(E) or 
-  FN(flwor_FE), 
+  FN(E) or
+  FN(flwor_FE),
   where FN is one of fn:count, fn:empty, or fn:exists, and flwor_FE is a flwor
   expr whose return expr is FE.
 
@@ -51,7 +51,7 @@
   applied to FFE and so on.
 ********************************************************************************/
 
-RULE_REWRITE_PRE(ReplaceExprWithConstantOneWhenPossible) 
+RULE_REWRITE_PRE(ReplaceExprWithConstantOneWhenPossible)
 {
   if (node->get_expr_kind() != fo_expr_kind)
     return NULL;
@@ -62,12 +62,12 @@
 
   if (fkind == FunctionConsts::FN_COUNT_1 ||
       fkind == FunctionConsts::FN_EMPTY_1 ||
-      fkind == FunctionConsts::FN_EXISTS_1) 
+      fkind == FunctionConsts::FN_EXISTS_1)
   {
     bool modified = false;
     expr_t child = fo->get_arg(0);
     expr_t nc = get_constant_if_typequant_one(child, modified);
-    if (nc != NULL) 
+    if (nc != NULL)
     {
       fo->set_arg(0, nc);
       return node;
@@ -77,7 +77,7 @@
 }
 
 
-RULE_REWRITE_POST(ReplaceExprWithConstantOneWhenPossible) 
+RULE_REWRITE_POST(ReplaceExprWithConstantOneWhenPossible)
 {
   return NULL;
 }
@@ -87,20 +87,20 @@
 {
   TypeManager* tm = e->get_type_manager();
 
-  if (e->get_expr_kind() != const_expr_kind) 
+  if (e->get_expr_kind() != const_expr_kind)
   {
     if (!e->isNonDiscardable() &&
-        TypeOps::type_cnt(tm, *(e->get_return_type())) == 1) 
+        TypeOps::type_cnt(tm, *(e->get_return_type())) == 1)
     {
       modified = true;
-      return new const_expr(e->get_sctx(), e->get_loc(), 1);
+      return rCtx.theEM->create_const_expr(e->get_sctx(), e->get_loc(), 1;
     }
     else if (e->get_expr_kind() == flwor_expr_kind)
     {
       flwor_expr* flwor = static_cast<flwor_expr *>(e);
       expr* ret = flwor->get_return_expr();
       expr_t newRet = get_constant_if_typequant_one(ret, modified);
-      if (newRet != NULL) 
+      if (newRet != NULL)
       {
         modified = true;
         flwor->set_return_expr(newRet);

=== modified file 'src/compiler/rewriter/rules/flwor_rules.cpp'
--- src/compiler/rewriter/rules/flwor_rules.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rules/flwor_rules.cpp	2012-08-14 12:29:44 +0000
@@ -48,7 +48,7 @@
 
 static bool var_in_try_block_or_in_loop(const var_expr*, const expr*, bool, bool, bool&);
 
-static bool is_subseq_pred(RewriterContext&, const flwor_expr*, const expr*, var_expr_t&, expr_t&);
+static bool is_subseq_pred(RewriterContext&, flwor_expr*, expr*, var_expr**, expr**);
 
 
 #define MODIFY( expr ) do { modified = true; expr; } while (0)
@@ -85,8 +85,8 @@
   }
 
 protected:
-  expr_t rewritePre(expr* node, RewriterContext& rCtx);
-  expr_t rewritePost(expr* node, RewriterContext& rCtx);
+  expr* rewritePre(expr* node, RewriterContext& rCtx);
+  expr* rewritePost(expr* node, RewriterContext& rCtx);
 };
 
 
@@ -125,7 +125,7 @@
 /*******************************************************************************
   Replace all references to var "var" inside the expr "root" with expr "subst"
 ********************************************************************************/
-expr_t subst_vars(
+expr* subst_vars(
     const RewriterContext& rCtx0,
     expr* root,
     const var_expr* var,
@@ -174,14 +174,14 @@
   csize numForLetClauses = 0;
 
   // numClauses may be 0 in the case this flwor became a common sub-expression
-  // due to var-inlining inside an if-then-else expr (see test 
+  // due to var-inlining inside an if-then-else expr (see test
   // zorba/optim/flwor_vars_02.xq)
   if (numClauses == 0)
   {
     return flwor.get_return_expr();
   }
 
-  const forletwin_clause& flwc = 
+  const forletwin_clause& flwc =
   *static_cast<const forletwin_clause *>(flwor.get_clause(0));
 
   // "for $x in E return $x"  --> "E"
@@ -198,7 +198,7 @@
   // "for $x in ... where E ... return ...", and E doesn't depend on FLWOR vars -->
   // "if E then flwor else ()", where flwor is the original flwor expr without the
   // where clause.
-  expr* whereExpr;
+  expr* whereExpr = NULL;
   if ((whereExpr = flwor.get_where()) != NULL && !flwor.has_sequential_clauses())
   {
     const expr::FreeVars& whereVars = whereExpr->getFreeVars();
@@ -211,18 +211,18 @@
                           std::inserter(diff, diff.begin()));
     if (diff.empty())
     {
-      expr_t oldWhere = whereExpr;
+      expr* oldWhere = whereExpr;
       flwor.remove_where_clause();
 
-      rchandle<if_expr> ifExpr = new if_expr(sctx,
+      if_expr* ifExpr = rCtx.theEM->create_if_expr(sctx,
                                              loc,
                                              oldWhere,
                                              &flwor,
-                                             fo_expr::create_seq(sctx, loc));
+                                             rCtx.theEM->create_seq(sctx, loc));
 
       fix_if_annotations(ifExpr);
 
-      return ifExpr.getp();
+      return ifExpr;
     }
   }
 
@@ -256,7 +256,7 @@
       ulong domainCount = domainType->max_card();
       const var_expr* pvar = fc->get_pos_var();
 
-      if (pvar != NULL && 
+      if (pvar != NULL &&
           expr_tools::count_variable_uses(&flwor, pvar, &rCtx, 1) == 0)
       {
         MODIFY(fc->set_pos_var(NULL));
@@ -270,7 +270,7 @@
 
       // FOR clause with 0 cardinality
       if (domainCount == 0)
-        return fo_expr::create_seq(sctx, LOC(node));
+        return rCtx.theEM->create_seq(sctx, LOC(node));
 
       // FOR clause with cardinality 0 or 1
 
@@ -279,7 +279,10 @@
         MODIFY(subst_vars(rCtx,
                           node,
                           pvar,
-                          new const_expr(sctx, loc, xs_integer::one())));
+                          rCtx.theEM->create_const_expr(sctx,
+                                                   loc,
+                                                   xs_integer::one())
+        ));
       }
 
       int uses = expr_tools::count_variable_uses(&flwor, var, &rCtx, 2);
@@ -367,12 +370,15 @@
         let_clause_t save = lc;
         MODIFY(flwor.remove_clause(i));
         const QueryLoc& loc = var->get_loc();
-        var_expr_t fvar = new var_expr(sctx, loc, var_expr::for_var, var->get_name());
+        var_expr* fvar = rCtx.theEM->create_var_expr(sctx,
+                                                 loc,
+                                                 var_expr::for_var,
+                                                 var->get_name());
         fvar->getFreeVars().insert(fvar);
-        for_clause_t fc = new for_clause(sctx, loc, fvar, domainExpr);
+        for_clause_t fc = new for_clause(sctx, rCtx.theCCB, loc, fvar, domainExpr);
         flwor.add_clause(i, fc);
 
-        subst_vars(rCtx, node, var, fvar.getp());
+        subst_vars(rCtx, node, var, fvar);
       }
     }
   }
@@ -387,7 +393,7 @@
       flwor_clause::rebind_list_t::const_iterator gVarsEnd = gVars.end();
       for (; gVarsIte != gVarsEnd; ++gVarsIte)
       {
-        subst_vars(rCtx, flworp, gVarsIte->second.getp(), gVarsIte->first.getp());
+        subst_vars(rCtx, flworp, gVarsIte->second, gVarsIte->first);
       }
 
       const flwor_clause::rebind_list_t& ngVars = gc->get_nongrouping_vars();
@@ -395,25 +401,25 @@
       flwor_clause::rebind_list_t::const_iterator ngVarsEnd = ngVars.end();
       for (; ngVarsIte != ngVarsEnd; ++ngVarsIte)
       {
-        subst_vars(rCtx, flworp, ngVarsIte->second.getp(), ngVarsIte->first.getp());
+        subst_vars(rCtx, flworp, ngVarsIte->second, ngVarsIte->first);
       }
     }
 
-    expr_t result = flwor.get_return_expr();
-    expr* whereExpr;
+    expr* result = flwor.get_return_expr();
+    expr* whereExpr = NULL;
 
     if ((whereExpr = flwor.get_where()) != NULL)
     {
-      rchandle<if_expr> ifExpr = 
-      new if_expr(whereExpr->get_sctx(),
+      if_expr* ifExpr =
+      rCtx.theEM->create_if_expr(whereExpr->get_sctx(),
                   LOC(whereExpr),
                   whereExpr,
                   result,
-                  fo_expr::create_seq(whereExpr->get_sctx(),
+                  rCtx.theEM->create_seq(whereExpr->get_sctx(),
                                       LOC(whereExpr)));
       fix_if_annotations(ifExpr);
-      
-      return ifExpr.getp();
+
+      return ifExpr;
     }
 
     return result;
@@ -434,7 +440,7 @@
   FOR, LET, or WINDOW clauses of a flwor expr.
 ********************************************************************************/
 static void collect_flw_vars(
-    const flwor_expr& flwor, 
+    const flwor_expr& flwor,
     expr::FreeVars& vars)
 {
   for (csize i = 0; i < flwor.num_clauses(); ++i)
@@ -527,9 +533,9 @@
   Check if it is OK to fold (inline) a FOR/LET var X that we know is referenced
   only once withing its flwor expr.
 
-  For a LET var, varQuant is always QUNAT_ONE. 
+  For a LET var, varQuant is always QUNAT_ONE.
 
-  For a FOR var, varQuant is the quantifier of the type of the domain expr. 
+  For a FOR var, varQuant is the quantifier of the type of the domain expr.
   It can be either QUANT_ONE or QUANT_QUESTION.
 ********************************************************************************/
 static bool safe_to_fold_single_use(
@@ -538,7 +544,7 @@
     const flwor_expr& flwor)
 {
   bool declared = false;
-  expr_t referencingExpr = NULL;
+  expr* referencingExpr = NULL;
 
   TypeManager* tm = var->get_type_manager();
 
@@ -625,7 +631,7 @@
         if (varQuant != TypeConstants::QUANT_ONE)
         {
           // X is a FOR var which is referenced in the current LET clause, and
-          // whose domain may be the empty sequence. We cannot inline in this 
+          // whose domain may be the empty sequence. We cannot inline in this
           // case.
           return false;
         }
@@ -640,7 +646,7 @@
     }
     else if (kind == flwor_clause::where_clause)
     {
-      if (varQuant == TypeConstants::QUANT_ONE && 
+      if (varQuant == TypeConstants::QUANT_ONE &&
           expr_tools::count_variable_uses(c.get_expr(), var, NULL, 1) == 1)
       {
         referencingExpr = c.get_expr();
@@ -671,7 +677,7 @@
   {
     if (varQuant != TypeConstants::QUANT_ONE)
     {
-      xqtref_t type = 
+      xqtref_t type =
       flwor.get_return_expr()->get_return_type_with_empty_input(var);
 
       if (TypeOps::is_equal(tm,
@@ -693,16 +699,16 @@
   return !var_in_try_block_or_in_loop(var,
                                       referencingExpr,
                                       false,
-                                      hasNodeConstr, 
+                                      hasNodeConstr,
                                       found);
 }
 
 
 /*******************************************************************************
-  Given a variable V and an expression E that references V at most once, return 
+  Given a variable V and an expression E that references V at most once, return
   true if E does indeed reference V and
   (a) the reference occurs inside a for-loop within E, or
-  (b) 
+  (b)
 ********************************************************************************/
 static bool var_in_try_block_or_in_loop(
     const var_expr* v,
@@ -767,7 +773,7 @@
   {
     const flwor_expr& flwor = *static_cast<const flwor_expr *>(e);
 
-		expr_t referencingExpr = NULL;
+		expr* referencingExpr = NULL;
 
     for (ulong i = 0; i < flwor.num_clauses(); ++i)
     {
@@ -788,7 +794,7 @@
             flc.get_expr()->get_return_type()->max_card() >= 2)
         {
           // we assume here that the var will be referenced somewhere in the
-          // remainder of the flwor expr, but this is not necessarily true 
+          // remainder of the flwor expr, but this is not necessarily true
           // ???? TODO
           return true;
         }
@@ -901,8 +907,8 @@
 
   if_expr* ifReturnExpr = NULL;
   expr* elseExpr = NULL;
-  expr_t condExpr;
-  expr_t thenExpr;
+  expr* condExpr = NULL;
+  expr* thenExpr = NULL;
 
   if (flwor->get_return_expr()->get_expr_kind() == if_expr_kind)
   {
@@ -929,8 +935,8 @@
     modified = true;
   }
 
-  expr_t posExpr;
-  var_expr_t posVar;
+  expr* posExpr = NULL;
+  var_expr* posVar = NULL;
 
   // '... for $x at $p in E ... where $p = posExpr ... return ...' -->
   // '... for $x in fn:subsequence(E, posExpr, 1) ... return ...
@@ -940,23 +946,23 @@
   // are before the clause that defines the pos var.
   if (whereExpr != NULL &&
       ! flwor->has_sequential_clauses() &&
-      is_subseq_pred(rCtx, flwor, whereExpr, posVar, posExpr) &&
+      is_subseq_pred(rCtx, flwor, whereExpr, &posVar, &posExpr) &&
       expr_tools::count_variable_uses(flwor, posVar, &rCtx, 2) <= 1)
   {
     function* seq_point = GET_BUILTIN_FUNCTION(OP_ZORBA_SEQUENCE_POINT_ACCESS_2);
     expr* domainExpr = posVar->get_for_clause()->get_expr();
 
-    std::vector<expr_t> args(2);
+    std::vector<expr*> args(2);
     args[0] = domainExpr;
     args[1] = posExpr;
 
-    rchandle<fo_expr> result = new fo_expr(whereExpr->get_sctx(),
+    fo_expr* result = rCtx.theEM->create_fo_expr(whereExpr->get_sctx(),
                                            LOC(whereExpr),
                                            seq_point,
                                            args);
-    expr_tools::fix_annotations(&*result);
+    expr_tools::fix_annotations(result);
     for_clause* clause = posVar->get_for_clause();
-    clause->set_expr(&*result);
+    clause->set_expr(result);
     clause->set_pos_var(NULL);
     flwor->remove_where_clause();
 
@@ -978,27 +984,27 @@
 
   (a)  op is eq or =, and
   (b1) posExpr is an integer literal with value >= 1, or
-  (b2) the flwor expr has no sequential clauses and posExpr is an expression 
-       whose type is xs:integer? and which does not reference the for var 
-       associated with posVar nor any other vars that are defined after that 
+  (b2) the flwor expr has no sequential clauses and posExpr is an expression
+       whose type is xs:integer? and which does not reference the for var
+       associated with posVar nor any other vars that are defined after that
        for var.
 
-  TODO: (b2) can be relaxed somewhat: it is ok if all the sequential clauses are 
+  TODO: (b2) can be relaxed somewhat: it is ok if all the sequential clauses are
   before the clause that defines the pos var.
 ********************************************************************************/
 static bool is_subseq_pred(
     RewriterContext& rCtx,
-    const flwor_expr* flworExpr,
-    const expr* condExpr,
-    var_expr_t& posVar,
-    expr_t& posExpr)
+    flwor_expr* flworExpr,
+    expr* condExpr,
+    var_expr** posVar,
+    expr** posExpr)
 {
   static_context* sctx = condExpr->get_sctx();
   TypeManager* tm = sctx->get_typemanager();
   RootTypeManager& rtm = GENV_TYPESYSTEM;
-  const QueryLoc& posLoc = posExpr->get_loc();
+  const QueryLoc& posLoc = (*posExpr)->get_loc();
 
-  const fo_expr* fo;
+  const fo_expr* fo = NULL;
   const function* f;
 
   while (true)
@@ -1024,13 +1030,13 @@
 
   for (ulong i = 0; i < 2; ++i)
   {
-    posVar = fo->get_arg(i)->get_var();
-    posExpr = fo->get_arg(1 - i);
-    const const_expr* posConstExpr = dynamic_cast<const const_expr*>(posExpr.getp());
+    *posVar = const_cast<var_expr*>(fo->get_arg(i)->get_var());
+    *posExpr = fo->get_arg(1 - i);
+    const const_expr* posConstExpr = dynamic_cast<const const_expr*>(*posExpr);
 
-    if (posVar != NULL &&
-        posVar->get_kind() == var_expr::pos_var &&
-        flworExpr->defines_variable(posVar) >= 0)
+    if (*posVar != NULL &&
+        (*posVar)->get_kind() == var_expr::pos_var &&
+        flworExpr->defines_variable(*posVar) >= 0)
     {
       if (posConstExpr != NULL)
       {
@@ -1048,7 +1054,7 @@
       }
       else if (!flworExpr->has_sequential_clauses())
       {
-        xqtref_t posExprType = posExpr->get_return_type();
+        xqtref_t posExprType = (*posExpr)->get_return_type();
 
         if (TypeOps::is_subtype(tm, *posExprType, *rtm.INTEGER_TYPE_QUESTION, posLoc))
         {
@@ -1058,13 +1064,13 @@
 
           DynamicBitset varset(numFlworVars);
           ExprVarsMap exprVarMap;
-          expr_tools::build_expr_to_vars_map(posExpr, varidMap, varset, exprVarMap);
+          expr_tools::build_expr_to_vars_map(*posExpr, varidMap, varset, exprVarMap);
 
-          var_expr* forVar = posVar->get_for_clause()->get_var();
+          var_expr* forVar = (*posVar)->get_for_clause()->get_var();
           ulong forVarId = varidMap[forVar];
 
           std::vector<ulong> posExprVarIds;
-          exprVarMap[posExpr].getSet(posExprVarIds);
+          exprVarMap[*posExpr].getSet(posExprVarIds);
 
           ulong numPosExprVars = (ulong)posExprVarIds.size();
           for (ulong i = 0; i < numPosExprVars; ++i)
@@ -1072,7 +1078,7 @@
             if (posExprVarIds[i] >= forVarId)
               return false;
           }
-          
+
           return true;
         }
       }
@@ -1102,7 +1108,7 @@
     // TODO: If the return clause is sequential, we can still do the merge,
     // but we must keep both the outer and the inner materialize clauses.
 
-    flwor_expr_t returnFlwor = static_cast<flwor_expr*>(flwor->get_return_expr());
+    flwor_expr* returnFlwor = static_cast<flwor_expr*>(flwor->get_return_expr());
 
     // If the outer flwor is not general, and it contains where, groupby, or
     // orderby clauses, we cannot merge because for/let clauses cannot appear
@@ -1125,11 +1131,11 @@
     }
 
     csize numClauses = returnFlwor->num_clauses();
-    
+
     for (csize i = 0; i < numClauses; ++i)
     {
       const flwor_clause* c = returnFlwor->get_clause(i);
-      
+
       if (c->get_kind() == flwor_clause::group_clause ||
           c->get_kind() == flwor_clause::order_clause)
       {
@@ -1155,14 +1161,14 @@
   for (ulong i = 0; i < numClauses; ++i)
   {
     bool merge = false;
-    flwor_expr_t nestedFlwor;
+    flwor_expr* nestedFlwor = NULL;
     ulong numNestedClauses;
 
     flwor_clause* c = flwor->get_clause(i);
 
     expr* domainExpr = c->get_expr();
 
-    if (domainExpr != NULL && 
+    if (domainExpr != NULL &&
         domainExpr->get_expr_kind() == flwor_expr_kind &&
         !domainExpr->is_sequential())
     {

=== modified file 'src/compiler/rewriter/rules/fold_rules.cpp'
--- src/compiler/rewriter/rules/fold_rules.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rules/fold_rules.cpp	2012-08-14 12:29:44 +0000
@@ -55,17 +55,17 @@
 
 static void remove_wincond_vars(const flwor_wincond*, expr::FreeVars&);
 
-static bool standalone_expr(expr_t);
-
-static bool already_folded(expr_t, RewriterContext&);
-
-static expr_t partial_eval_fo (RewriterContext&, fo_expr*);
-
-static expr_t partial_eval_logic(fo_expr*, bool, RewriterContext&);
-
-static expr_t partial_eval_eq(RewriterContext&, fo_expr&);
-
-static expr_t partial_eval_return_clause(flwor_expr* flworExpr, bool& modified);
+static bool standalone_expr(expr*);
+
+static bool already_folded(expr*, RewriterContext&);
+
+static expr* partial_eval_fo (RewriterContext&, fo_expr*);
+
+static expr* partial_eval_logic(fo_expr*, bool, RewriterContext&);
+
+static expr* partial_eval_eq(RewriterContext&, fo_expr&);
+
+static expr* partial_eval_return_clause(flwor_expr* flworExpr, bool& modified, RewriterContext& rCtx);
 
 static bool maybe_needs_implicit_timezone(const fo_expr* fo);
 
@@ -73,9 +73,9 @@
 /*******************************************************************************
 
 ********************************************************************************/
-static expr_t execute (
+static expr* execute (
     CompilerCB* compilercb,
-    expr_t node,
+    expr* node,
     vector<store::Item_t>& result)
 {
   ulong nextVarId = 1;
@@ -90,7 +90,7 @@
     //std::cout << "Const folding expr : " << std::endl;
     //node->put(std::cout);
     //std::cout << std::endl;
-    
+
     PlanWrapperHolder pw(new PlanWrapper(plan,
                                          &expr_ccb,
                                          0,      // dynamic ctx
@@ -135,11 +135,11 @@
                               "http://www.w3.org/2005/xqt-errors";,
                               "err",
                               error::ZorbaError::toString(lErrorCode).c_str());
-    expr_t err_expr = new fo_expr(node->get_sctx_id(),
+    expr* err_expr = rCtx.theEM->create_fo_expr(node->get_sctx_id(),
                                   loc,
                                   GET_BUILTIN_FUNCTION(FN_ERROR_2),
-                                  new const_expr(node->get_sctx_id(), loc, qname),
-                                  new const_expr(node->get_sctx_id(), loc, e.theDescription));
+                                  rCtx.theEM->create_const_expr(node->get_sctx_id(), loc, qname),
+                                  rCtx.theEM->create_const_expr(node->get_sctx_id(), loc, e.theDescription));
     err_expr->setUnfoldable(ANNOTATION_TRUE_FIXED);
     err_expr->setNonDiscardable(ANNOTATION_TRUE_FIXED);
     return err_expr;
@@ -165,7 +165,7 @@
   The NON_DISCARDABLE property is used during the application of the PartialEval
   rule below.
 ********************************************************************************/
-expr_t MarkExprs::apply(RewriterContext& rCtx, expr* node, bool& modified)
+expr* MarkExprs::apply(RewriterContext& rCtx, expr* node, bool& modified)
 {
   BoolAnnotationValue saveNonDiscardable = node->getNonDiscardable();
   BoolAnnotationValue saveUnfoldable = node->getUnfoldable();
@@ -191,7 +191,7 @@
 
       if (!udf->isOptimized())
       {
-        udf->optimize(rCtx.theCCB);
+        udf->optimize();
       }
 
       if (rCtx.theUDF != NULL &&
@@ -202,7 +202,7 @@
     }
   }
 
-  // Process the subexprs of the current expr. If any of the children is 
+  // Process the subexprs of the current expr. If any of the children is
   // nondiscardable, unfoldable, or contains recursive calls, then the current
   // expr is also nondiscardable, unfoldable, or contains recursive calls.
   ExprConstIterator iter(node);
@@ -229,7 +229,7 @@
   {
     if (node->is_sequential())
     {
-      curNonDiscardable = ANNOTATION_TRUE_FIXED; 
+      curNonDiscardable = ANNOTATION_TRUE_FIXED;
     }
     else
     {
@@ -239,18 +239,18 @@
       {
         fo_expr* fo = static_cast<fo_expr *>(node);
         function* f = fo->get_func();
-          
+
         bool isErrorFunc = (dynamic_cast<const fn_error*>(f) != NULL);
-          
+
         if (f->getKind() == FunctionConsts::FN_TRACE_2 ||
             isErrorFunc)
         {
           curNonDiscardable = ANNOTATION_TRUE_FIXED;
         }
-        
+
         break;
       }
-        
+
       case cast_expr_kind:
       case treat_expr_kind:
       case promote_expr_kind:
@@ -258,7 +258,7 @@
         curNonDiscardable = ANNOTATION_TRUE_FIXED;
         break;
       }
-        
+
       default:
       {
         break;
@@ -272,7 +272,7 @@
   {
     if (node->is_sequential())
     {
-      curUnfoldable = ANNOTATION_TRUE_FIXED; 
+      curUnfoldable = ANNOTATION_TRUE_FIXED;
     }
     else
     {
@@ -295,17 +295,17 @@
         {
           curUnfoldable = ANNOTATION_TRUE_FIXED;
         }
-      
+
         break;
       }
-      
+
       case var_expr_kind:
       {
         var_expr::var_kind varKind = static_cast<var_expr *>(node)->get_kind();
 
         if (varKind == var_expr::prolog_var || varKind == var_expr::local_var)
           curUnfoldable = ANNOTATION_TRUE_FIXED;
-        
+
         break;
       }
 
@@ -322,7 +322,7 @@
         curUnfoldable = ANNOTATION_TRUE_FIXED;
         break;
       }
-  
+
       case delete_expr_kind:
       case insert_expr_kind:
       case rename_expr_kind:
@@ -407,7 +407,7 @@
 
   if (node->get_expr_kind() == var_expr_kind)
   {
-    var_expr_t v = static_cast<var_expr *>(node);
+    var_expr* v = static_cast<var_expr *>(node);
     freevars.insert(v);
   }
   else
@@ -417,7 +417,7 @@
     ExprIterator iter(node);
     while (!iter.done())
     {
-      expr* e = *iter;
+      expr* e = **iter;
 
       const expr::FreeVars& kfv = e->getFreeVars();
       std::copy(kfv.begin(),
@@ -477,7 +477,7 @@
 
           for (csize i = 0; i < numGroupVars; ++i)
           {
-            freevars.erase(gvars[i].second.getp());
+            freevars.erase(gvars[i].second);
           }
 
           const flwor_clause::rebind_list_t& ngvars = gc->get_nongrouping_vars();
@@ -485,7 +485,7 @@
 
           for (csize i = 0; i < numNonGroupVars; ++i)
           {
-            freevars.erase(ngvars[i].second.getp());
+            freevars.erase(ngvars[i].second);
           }
         }
         else if (c->get_kind() == flwor_clause::count_clause)
@@ -509,15 +509,15 @@
   const flwor_wincond::vars& inVars = cond->get_in_vars();
   const flwor_wincond::vars& outVars = cond->get_out_vars();
 
-  freevars.erase(inVars.posvar.getp());
-  freevars.erase(inVars.curr.getp());
-  freevars.erase(inVars.prev.getp());
-  freevars.erase(inVars.next.getp());
+  freevars.erase(inVars.posvar);
+  freevars.erase(inVars.curr);
+  freevars.erase(inVars.prev);
+  freevars.erase(inVars.next);
 
-  freevars.erase(outVars.posvar.getp());
-  freevars.erase(outVars.curr.getp());
-  freevars.erase(outVars.prev.getp());
-  freevars.erase(outVars.next.getp());
+  freevars.erase(outVars.posvar);
+  freevars.erase(outVars.curr);
+  freevars.erase(outVars.prev);
+  freevars.erase(outVars.next);
 }
 
 
@@ -539,13 +539,13 @@
       rtype->max_card() <= 1)
   {
     vector<store::Item_t> result;
-    expr_t folded = execute(rCtx.getCompilerCB(), node, result);
+    expr* folded = execute(rCtx.getCompilerCB(), node, result);
     if (folded == NULL)
     {
       ZORBA_ASSERT (result.size () <= 1);
       folded = (result.size () == 1 ?
-                ((expr*) (new const_expr(node->get_sctx(), LOC(node), result[0]))) :
-                ((expr*) (fo_expr::create_seq(node->get_sctx(), LOC(node)))));
+                ((expr*) (rCtx.theEM->create_const_expr(node->get_sctx(), LOC(node), result[0]))) :
+                ((expr*) (rCtx.theEM->create_seq(node->get_sctx(), LOC(node)))));
     }
     return folded;
   }
@@ -558,21 +558,21 @@
 }
 
 
-static bool standalone_expr(expr_t e)
+static bool standalone_expr(expr* e)
 {
   expr_kind_t k = e->get_expr_kind ();
   return k != match_expr_kind && k != axis_step_expr_kind;
 }
 
 
-static bool already_folded(expr_t e, RewriterContext& rCtx)
+static bool already_folded(expr* e, RewriterContext& rCtx)
 {
   if (e->get_expr_kind () == const_expr_kind)
     return true;
   if (e->get_expr_kind () != fo_expr_kind)
     return false;
 
-  const fo_expr* fo = e.dyn_cast<fo_expr>().getp ();
+  const fo_expr* fo = dynamic_cast<fo_expr*>(e);
 
   return (fo->get_func()->getKind() == FunctionConsts::OP_CONCATENATE_N &&
           fo->num_args() == 0);
@@ -623,7 +623,7 @@
   TypeManager* tm = node->get_type_manager();
 
   // if node is a castable or instance-of expr
-  const castable_base_expr* cbe;
+  const castable_base_expr* cbe = NULL;
   if ((cbe = dynamic_cast<const castable_base_expr *>(node)) != NULL)
   {
     expr* arg = cbe->get_input();
@@ -636,7 +636,7 @@
 
     if (TypeOps::is_subtype(tm, *argType, *targetType, node->get_loc()))
     {
-      return new const_expr(node->get_sctx(), LOC(node), true);
+      return rCtx.theEM->create_const_expr(node->get_sctx(), LOC(node), true);
     }
     else if (node->get_expr_kind() == instanceof_expr_kind)
     {
@@ -650,7 +650,7 @@
 
       return (TypeOps::intersect_type(*argType, *targetType, tm) ==
               GENV_TYPESYSTEM.NONE_TYPE ?
-              new const_expr(node->get_sctx(), LOC(node), false) :
+              rCtx.theEM->create_const_expr(node->get_sctx(), LOC(node), false) :
               NULL);
     }
     else
@@ -692,7 +692,7 @@
 }
 
 
-static expr_t partial_eval_fo(RewriterContext& rCtx, fo_expr* fo)
+static expr* partial_eval_fo(RewriterContext& rCtx, fo_expr* fo)
 {
   TypeManager* tm = fo->get_type_manager();
 
@@ -726,7 +726,7 @@
 
       if (fkind == FunctionConsts::FN_COUNT_1 && type_cnt != -1)
       {
-        return new const_expr(fo->get_sctx(),
+        return rCtx.theEM->create_const_expr(fo->get_sctx(),
                               fo->get_loc(),
                               xs_integer(type_cnt));
       }
@@ -734,24 +734,24 @@
       {
         if (type_cnt == 0)
         {
-          return new const_expr(fo->get_sctx(), fo->get_loc(), true);
+          return rCtx.theEM->create_const_expr(fo->get_sctx(), fo->get_loc(), true);
         }
-        else if (argQuant == TypeConstants::QUANT_ONE || 
+        else if (argQuant == TypeConstants::QUANT_ONE ||
                  argQuant == TypeConstants::QUANT_PLUS)
         {
-          return new const_expr(fo->get_sctx(), fo->get_loc(), false);
+          return rCtx.theEM->create_const_expr(fo->get_sctx(), fo->get_loc(), false);
         }
       }
       else if (fkind == FunctionConsts::FN_EXISTS_1)
       {
         if (type_cnt == 0)
         {
-          return new const_expr(fo->get_sctx(), fo->get_loc(), false);
+          return rCtx.theEM->create_const_expr(fo->get_sctx(), fo->get_loc(), false);
         }
-        else if (argQuant == TypeConstants::QUANT_ONE || 
+        else if (argQuant == TypeConstants::QUANT_ONE ||
                  argQuant == TypeConstants::QUANT_PLUS)
         {
-          return new const_expr(fo->get_sctx(), fo->get_loc(), true);
+          return rCtx.theEM->create_const_expr(fo->get_sctx(), fo->get_loc(), true);
         }
       }
     }
@@ -759,10 +759,11 @@
     if (arg->get_expr_kind() == flwor_expr_kind)
     {
       bool modified = false;
-      expr_t newArg = partial_eval_return_clause(static_cast<flwor_expr*>(arg),
-                                                 modified);
+      expr* newArg = partial_eval_return_clause(static_cast<flwor_expr*>(arg),
+                                                 modified,
+                                                 rCtx);
 
-      if (newArg.getp() != arg)
+      if (newArg != arg)
         fo->set_arg(0, newArg);
 
       if (modified)
@@ -773,7 +774,7 @@
   }
   else if (fkind == FunctionConsts::FN_BOOLEAN_1)
   {
-    expr_t arg = fo->get_arg(0);
+    expr* arg = fo->get_arg(0);
     if (!arg->isNonDiscardable())
     {
       xqtref_t argType = arg->get_return_type();
@@ -782,7 +783,7 @@
                               *GENV_TYPESYSTEM.ANY_NODE_TYPE_PLUS,
                               arg->get_loc()))
       {
-        return new const_expr(fo->get_sctx(), fo->get_loc(), true);
+        return rCtx.theEM->create_const_expr(fo->get_sctx(), fo->get_loc(), true);
       }
     }
   }
@@ -795,7 +796,7 @@
   fo is a logical "and" or "or" expr. If "and" then the shortcircuit_val is
   false, otherwise, shortcircuit_val is true.
 ********************************************************************************/
-static expr_t partial_eval_logic(
+static expr* partial_eval_logic(
     fo_expr* fo,
     bool shortcircuit_val,
     RewriterContext& rCtx)
@@ -810,12 +811,12 @@
   for (ulong i = 0; i < numArgs; ++i)
   {
     const expr* arg = fo->get_arg(i);
-    const const_expr* constArg;
+    const const_expr* constArg = NULL;
 
     if ((constArg = dynamic_cast<const const_expr*>(arg)) != NULL)
     {
       if (constArg->get_val()->getEBV() == shortcircuit_val)
-        return new const_expr(fo->get_sctx(), LOC(fo), (xs_boolean)shortcircuit_val);
+        return rCtx.theEM->create_const_expr(fo->get_sctx(), LOC(fo), (xs_boolean)shortcircuit_val);
     }
     else
     {
@@ -834,7 +835,7 @@
   if (nonConst1 < 0)
   {
     // All args are constant exprs
-    return new const_expr(fo->get_sctx(), LOC(fo), (xs_boolean) ! shortcircuit_val);
+    return rCtx.theEM->create_const_expr(fo->get_sctx(), LOC(fo), (xs_boolean) ! shortcircuit_val);
   }
 
   if (nonConst2 < 0)
@@ -842,14 +843,14 @@
     // Only one of the args is a constant expr. The non-const arg is pointed
     // to by nonConst1.
 
-    expr_t arg = fo->get_arg(nonConst1);
+    expr* arg = fo->get_arg(nonConst1);
 
     if (! TypeOps::is_subtype(tm,
                               *arg->get_return_type(),
                               *GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE,
                               arg->get_loc()))
     {
-      arg = expr_tools::fix_annotations(new fo_expr(fo->get_sctx(),
+      arg = expr_tools::fix_annotations(rCtx.theEM->create_fo_expr(fo->get_sctx(),
                                                     LOC(fo),
                                                     GET_BUILTIN_FUNCTION(FN_BOOLEAN_1),
                                                     arg));
@@ -870,7 +871,7 @@
   3. if int_const == 1 --> fn:exactly-one-noraise(expr)
   4. if int_const > 1  --> fn:exactly-one-noraise(fn:subsequence(expr, int_const, 2))
 ********************************************************************************/
-static expr_t partial_eval_eq(RewriterContext& rCtx, fo_expr& fo)
+static expr* partial_eval_eq(RewriterContext& rCtx, fo_expr& fo)
 {
   int i;
   fo_expr* count_expr = NULL;
@@ -906,38 +907,38 @@
     if (ival < 0)
     {
       if (!count_expr->isNonDiscardable())
-        return new const_expr(val_expr->get_sctx(), LOC(val_expr), false);
+        return rCtx.theEM->create_const_expr(val_expr->get_sctx(), LOC(val_expr), false);
     }
     else if (ival == 0)
     {
       return expr_tools::fix_annotations(
-             new fo_expr(fo.get_sctx(), fo.get_loc(),
+             rCtx.theEM->create_fo_expr(fo.get_sctx(), fo.get_loc(),
                          GET_BUILTIN_FUNCTION(FN_EMPTY_1),
                          count_expr->get_arg(0)));
     }
     else if (ival == 1)
     {
       return expr_tools::fix_annotations(
-             new fo_expr(fo.get_sctx(),
+             rCtx.theEM->create_fo_expr(fo.get_sctx(),
                          fo.get_loc(),
                          GET_BUILTIN_FUNCTION(OP_EXACTLY_ONE_NORAISE_1),
                          count_expr->get_arg(0)));
     }
     else
     {
-      std::vector<expr_t> args(3);
+      std::vector<expr*> args(3);
       args[0] = count_expr->get_arg(0);
       args[1] = val_expr;
-      args[2] = new const_expr(val_expr->get_sctx(), LOC(val_expr), xs_integer(2));
+      args[2] = rCtx.theEM->create_const_expr(val_expr->get_sctx(), LOC(val_expr), xs_integer(2));
 
-      expr_t subseq_expr = expr_tools::fix_annotations(
-      new fo_expr(count_expr->get_sctx(),
+      expr* subseq_expr = expr_tools::fix_annotations(
+      rCtx.theEM->create_fo_expr(count_expr->get_sctx(),
                   LOC(count_expr),
                   GET_BUILTIN_FUNCTION(OP_ZORBA_SUBSEQUENCE_INT_3),
                   args));
 
       return expr_tools::fix_annotations(
-             new fo_expr(fo.get_sctx(),
+             rCtx.theEM->create_fo_expr(fo.get_sctx(),
                          fo.get_loc(),
                          GET_BUILTIN_FUNCTION(OP_EXACTLY_ONE_NORAISE_1),
                          subseq_expr));
@@ -951,7 +952,9 @@
 /*******************************************************************************
 
 ********************************************************************************/
-static expr_t partial_eval_return_clause(flwor_expr* flworExpr, bool& modified)
+static expr* partial_eval_return_clause(flwor_expr* flworExpr,
+                                        bool& modified,
+                                        RewriterContext& rCtx)
 {
   expr* returnExpr = flworExpr->get_return_expr();
 
@@ -973,15 +976,15 @@
       {
         assert(c->get_kind() == flwor_clause::let_clause);
 
-        return new const_expr(returnExpr->get_sctx(), returnExpr->get_loc(), 1);
+        return rCtx.theEM->create_const_expr(returnExpr->get_sctx(), returnExpr->get_loc(), 1);
       }
     }
     else if (returnExpr->get_expr_kind() != const_expr_kind)
     {
       modified = true;
 
-      expr_t newRet = 
-      new const_expr(returnExpr->get_sctx(), returnExpr->get_loc(), 1);
+      expr* newRet =
+      rCtx.theEM->create_const_expr(returnExpr->get_sctx(), returnExpr->get_loc(), 1);
 
       flworExpr->set_return_expr(newRet);
 
@@ -991,10 +994,10 @@
 
   if (returnExpr->get_expr_kind() == flwor_expr_kind)
   {
-    expr_t newRet = 
-    partial_eval_return_clause(static_cast<flwor_expr*>(returnExpr),  modified);
+    expr* newRet =
+    partial_eval_return_clause(static_cast<flwor_expr*>(returnExpr),  modified, rCtx);
 
-    if (newRet.getp() != returnExpr)
+    if (newRet != returnExpr)
     {
       flworExpr->set_return_expr(newRet);
       assert(modified);
@@ -1021,21 +1024,21 @@
     const fo_expr* fo = static_cast<const fo_expr *> (node);
 
     const user_function* udf = dynamic_cast<const user_function *>(fo->get_func());
-    expr_t body;
+    expr* body = NULL;
 
-    if (NULL != udf && 
-        //!udf->isSequential() && 
+    if (NULL != udf &&
+        //!udf->isSequential() &&
         (NULL != (body = udf->getBody())) &&
         !udf->isExiting() &&
         udf->isLeaf())
     {
-      const std::vector<var_expr_t>& udfArgs = udf->getArgVars();
+      const std::vector<var_expr*>& udfArgs = udf->getArgVars();
 
       expr::substitution_t subst;
 
       for (ulong i = 0; i < udfArgs.size(); ++i)
       {
-        var_expr_t p = udfArgs[i];
+        var_expr* p = udfArgs[i];
         subst[p] = fo->get_arg(i);
 
         if (fo->get_arg(i)->is_sequential())
@@ -1044,19 +1047,19 @@
 
       try
       {
-        expr_t body = udf->getBody();
+        expr* body = udf->getBody();
         body = body->clone(subst);
         body->clear_annotations();
         if (rCtx.getCompilerCB()->theConfig.opt_level <= CompilerCB::config::O1)
         {
-          function_trace_expr* dummy = new function_trace_expr(body);
+          function_trace_expr* dummy = rCtx.theEM->create_function_trace_expr(body);
           dummy->setFunctionName(udf->getName());
           dummy->setFunctionArity((unsigned int)udf->getArgVars().size());
           dummy->setFunctionCallLocation(node->get_loc());
           dummy->setFunctionLocation(udf->getLoc());
           return dummy;
         }
-        else 
+        else
         {
           return body;
         }

=== modified file 'src/compiler/rewriter/rules/hoist_rules.cpp'
--- src/compiler/rewriter/rules/hoist_rules.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rules/hoist_rules.cpp	2012-08-14 12:29:44 +0000
@@ -45,7 +45,7 @@
     const ExprVarsMap&,
     struct PathHolder*);
 
-static expr_t try_hoisting(
+static expr* try_hoisting(
     RewriterContext&,
     expr*,
     const VarIdMap&,
@@ -74,12 +74,13 @@
 struct PathHolder
 {
   struct PathHolder  * prev;
-  expr_t               expr;
+  expr               * theExpr;
   long                 clauseCount;
 
-  PathHolder() 
+  PathHolder()
     :
     prev(NULL),
+    theExpr(NULL),
     clauseCount(0)
   {
   }
@@ -90,7 +91,7 @@
   This rule looks for exprs that are inside a for loop but do not depend on the
   loop variable, and then moves such exprs outside the loop.
 ********************************************************************************/
-expr_t HoistRule::apply(
+expr* HoistRule::apply(
     RewriterContext& rCtx,
     expr* node,
     bool& modified)
@@ -109,12 +110,12 @@
   PathHolder root;
   modified = hoist_expressions(rCtx, node, varmap, freevarMap, &root);
 
-  if (modified && root.expr != NULL)
+  if (modified && root.theExpr != NULL)
   {
-    assert(root.expr->get_expr_kind() == flwor_expr_kind);
+    assert(root.theExpr->get_expr_kind() == flwor_expr_kind);
 
-    static_cast<flwor_expr*>(root.expr.getp())->set_return_expr(node);
-    return root.expr;
+    static_cast<flwor_expr*>(root.theExpr)->set_return_expr(node);
+    return root.theExpr;
   }
 
   return node;
@@ -139,7 +140,7 @@
 
     PathHolder step;
     step.prev = path;
-    step.expr = e;
+    step.theExpr = e;
 
     csize numForLetClauses = flwor->num_forlet_clauses();
     csize i = 0;
@@ -149,32 +150,32 @@
       forletwin_clause* flc = static_cast<forletwin_clause*>(flwor->get_clause(i));
       expr* domainExpr = flc->get_expr();
 
-      expr_t unhoistExpr = 
+      expr* unhoistExpr =
       try_hoisting(rCtx, domainExpr, varmap, freevarMap, &step);
 
       if (unhoistExpr != NULL)
       {
-        flc->set_expr(unhoistExpr.getp());
+        flc->set_expr(unhoistExpr);
         status = true;
         numForLetClauses = flwor->num_forlet_clauses();
         // TODO: the expr that was just hoisted here, may contain sub-exprs that
-        // can be hoisted even earlier. 
+        // can be hoisted even earlier.
       }
       else if (domainExpr->is_sequential())
       {
         PathHolder root;
 
-        bool hoisted = 
+        bool hoisted =
         hoist_expressions(rCtx, domainExpr, varmap, freevarMap, &root);
 
         if (hoisted)
         {
-          if (root.expr != NULL)
+          if (root.theExpr != NULL)
           {
-            assert(root.expr->get_expr_kind() == flwor_expr_kind);
+            assert(root.theExpr->get_expr_kind() == flwor_expr_kind);
 
-            static_cast<flwor_expr*>(root.expr.getp())->set_return_expr(domainExpr);
-            flc->set_expr(root.expr.getp());
+            static_cast<flwor_expr*>(root.theExpr)->set_return_expr(domainExpr);
+            flc->set_expr(root.theExpr);
           }
 
           status = true;
@@ -183,7 +184,7 @@
       }
       else
       {
-        bool hoisted = 
+        bool hoisted =
         hoist_expressions(rCtx, domainExpr, varmap, freevarMap, &step);
 
         if (hoisted)
@@ -198,16 +199,16 @@
       assert(numForLetClauses == flwor->num_forlet_clauses());
     }
 
-    expr_t we = flwor->get_where();
+    expr* we = flwor->get_where();
     if (we != NULL)
     {
       ZORBA_ASSERT(!we->is_sequential());
 
-      expr_t unhoistExpr = try_hoisting(rCtx, we, varmap, freevarMap, &step);
+      expr* unhoistExpr = try_hoisting(rCtx, we, varmap, freevarMap, &step);
 
       if (unhoistExpr != NULL)
       {
-        flwor->set_where(unhoistExpr.getp());
+        flwor->set_where(unhoistExpr);
         status = true;
       }
       else
@@ -218,12 +219,12 @@
 
     // TODO: hoist orderby exprs
 
-    expr_t re = flwor->get_return_expr();
-    expr_t unhoistExpr = try_hoisting(rCtx, re, varmap, freevarMap, &step);
+    expr* re = flwor->get_return_expr();
+    expr* unhoistExpr = try_hoisting(rCtx, re, varmap, freevarMap, &step);
 
     if (unhoistExpr != NULL)
     {
-      flwor->set_return_expr(unhoistExpr.getp());
+      flwor->set_return_expr(unhoistExpr);
       status = true;
     }
     else if (re->is_sequential())
@@ -231,12 +232,12 @@
       PathHolder root;
       bool nestedModified = hoist_expressions(rCtx, re, varmap, freevarMap, &root);
 
-      if (nestedModified && root.expr != NULL)
+      if (nestedModified && root.theExpr != NULL)
       {
-        assert(root.expr->get_expr_kind() == flwor_expr_kind);
+        assert(root.theExpr->get_expr_kind() == flwor_expr_kind);
 
-        static_cast<flwor_expr*>(root.expr.getp())->set_return_expr(re);
-        flwor->set_return_expr(root.expr.getp());
+        static_cast<flwor_expr*>(root.theExpr)->set_return_expr(re);
+        flwor->set_return_expr(root.theExpr);
       }
 
       status = nestedModified || status;
@@ -251,19 +252,19 @@
   {
     PathHolder step;
     step.prev = path;
-    step.expr = e;
+    step.theExpr = e;
 
     ExprIterator iter(e);
 
     while(!iter.done())
     {
-      expr* ce = &*(*iter);
+      expr* ce = **iter;
       if (ce)
       {
-        expr_t unhoistExpr = try_hoisting(rCtx, ce, varmap, freevarMap, &step);
+        expr* unhoistExpr = try_hoisting(rCtx, ce, varmap, freevarMap, &step);
         if (unhoistExpr != NULL)
         {
-          *iter = unhoistExpr.getp();
+          **iter = unhoistExpr;
           status = true;
         }
         else
@@ -285,17 +286,17 @@
       // TODO: if no updating child exprs have been encountered so far, subexprs
       // of the current child expr may be hoisted outside the sequential expr as
       // long as they don't reference any local vars.
-      expr_t ce = *iter;
+      expr* ce = **iter;
 
       PathHolder root;
       bool nestedModified = hoist_expressions(rCtx, ce, varmap, freevarMap, &root);
 
-      if (nestedModified && root.expr != NULL)
+      if (nestedModified && root.theExpr != NULL)
       {
-        assert(root.expr->get_expr_kind() == flwor_expr_kind);
+        assert(root.theExpr->get_expr_kind() == flwor_expr_kind);
 
-        static_cast<flwor_expr*>(root.expr.getp())->set_return_expr(ce);
-        (*iter) = root.expr;
+        static_cast<flwor_expr*>(root.theExpr)->set_return_expr(ce);
+        (**iter) = root.theExpr;
       }
 
       status = nestedModified || status;
@@ -317,13 +318,13 @@
 
     while(!iter.done())
     {
-      expr* ce = &*(*iter);
+      expr* ce = **iter;
       if (ce)
       {
-        expr_t unhoistExpr = try_hoisting(rCtx, ce, varmap, freevarMap, path);
+        expr* unhoistExpr = try_hoisting(rCtx, ce, varmap, freevarMap, path);
         if (unhoistExpr != NULL)
         {
-          *iter = unhoistExpr.getp();
+          **iter = unhoistExpr;
           status = true;
         }
         else
@@ -345,7 +346,7 @@
   flwor expr inside the stack of flwor exprs that is accessible via the "holder"
   param.
 ********************************************************************************/
-static expr_t try_hoisting(
+static expr* try_hoisting(
     RewriterContext& rCtx,
     expr* e,
     const VarIdMap& varmap,
@@ -369,13 +370,13 @@
   int i = 0;
 
   // step->prev == NULL means that expr e is not inside any flwor expr, and as a
-  // result, there is nothing to hoist. 
+  // result, there is nothing to hoist.
   while (step->prev != NULL)
   {
-    if (step->expr->get_expr_kind() == trycatch_expr_kind)
+    if (step->theExpr->get_expr_kind() == trycatch_expr_kind)
     {
       // Should not hoist an expr out of a try-catch if it contains any try-catch vars
-      trycatch_expr* trycatch = static_cast<trycatch_expr*>(step->expr.getp());
+      trycatch_expr* trycatch = static_cast<trycatch_expr*>(step->theExpr);
       csize numClauses = trycatch->clause_count();
 
       for (csize i = 0; i < numClauses; ++i)
@@ -388,18 +389,18 @@
         catch_clause::var_map_t::const_iterator end = trycatchVars.end();
         for (; ite != end; ++ite)
         {
-          const var_expr_t& trycatchVar = (*ite).second;
+          var_expr* trycatchVar = (*ite).second;
 
-          if (contains_var(trycatchVar.getp(), varmap, varset))
+          if (contains_var(trycatchVar, varmap, varset))
             return NULL;
-        } 
+        }
       }
     }
     else
     {
-      assert(step->expr->get_expr_kind() == flwor_expr_kind);
+      assert(step->theExpr->get_expr_kind() == flwor_expr_kind);
 
-      flwor_expr* flwor = static_cast<flwor_expr*>(step->expr.getp());
+      flwor_expr* flwor = static_cast<flwor_expr*>(step->theExpr);
       group_clause* gc = flwor->get_group_clause();
 
       // If any free variable is a group-by variable, give up.
@@ -410,29 +411,29 @@
 
         for (csize i = 0; i < numGroupVars; ++i)
         {
-          if (contains_var(gvars[i].second.getp(), varmap, varset))
+          if (contains_var(gvars[i].second, varmap, varset))
             return NULL;
         }
 
         const flwor_clause::rebind_list_t& ngvars = gc->get_nongrouping_vars();
         csize numNonGroupVars = ngvars.size();
-        
+
         for (csize i = 0; i < numNonGroupVars; ++i)
         {
-          if (contains_var(ngvars[i].second.getp(), varmap, varset))
+          if (contains_var(ngvars[i].second, varmap, varset))
             return NULL;
         }
       }
 
       // Check whether expr e references any variables from the current flwor. If
-      // not, then e can be hoisted out of the current flwor and we repeat the 
+      // not, then e can be hoisted out of the current flwor and we repeat the
       // while-loop to see if e can be hoisted w.r.t. the previous (outer) flwor.
       // If yes, then let V be the inner-most var referenced by e. If there are any
       // FOR vars after V, e can be hoisted out of any such FOR vars. Otherwise, e
       // cannot be hoisted.
       for (i = step->clauseCount - 1; i >= 0; --i)
       {
-        const forletwin_clause* flc = 
+        const forletwin_clause* flc =
         static_cast<const forletwin_clause*>(flwor->get_clause(i));
 
         if (flc->get_expr()->is_sequential())
@@ -448,7 +449,7 @@
           foundReferencedFLWORVar = true;
           break;
         }
-        
+
         inloop = (inloop ||
                   (flc->get_kind() == flwor_clause::for_clause &&
                    flc->get_expr()->get_return_type()->max_card() >= 2));
@@ -471,9 +472,9 @@
   // var: $$temp := op:hoist(e) (b) we place the $$temp declaration right after
   // variable V, and (c) we replace e with op:unhoist($$temp).
 
-  var_expr_t letvar(rCtx.createTempVar(e->get_sctx(), e->get_loc(), var_expr::let_var));
+  var_expr* letvar(rCtx.createTempVar(e->get_sctx(), e->get_loc(), var_expr::let_var));
 
-  expr_t hoisted = new fo_expr(e->get_sctx(),
+  expr* hoisted = rCtx.theEM->create_fo_expr(e->get_sctx(),
                                e->get_loc(),
                                GET_BUILTIN_FUNCTION(OP_HOIST_1),
                                e);
@@ -481,44 +482,45 @@
   hoisted->setFlags(e->getFlags());
   letvar->setFlags(e->getFlags());
 
-  let_clause_t flref(new let_clause(e->get_sctx(), e->get_loc(), letvar, hoisted));
+  let_clause_t flref(new let_clause(e->get_sctx(), rCtx.theCCB, e->get_loc(), letvar, hoisted));
 
   letvar->set_flwor_clause(flref.getp());
 
   if (step->prev == NULL)
   {
-    if (step->expr == NULL)
+    if (step->theExpr == NULL)
     {
-      step->expr = new flwor_expr(e->get_sctx(), e->get_loc(), false);
+      step->theExpr= rCtx.theEM->create_flwor_expr(e->get_sctx(), e->get_loc(), false);
     }
-    static_cast<flwor_expr*>(step->expr.getp())->add_clause(flref);
+    static_cast<flwor_expr*>(step->theExpr)->add_clause(flref);
   }
-  else if (step->expr->get_expr_kind() == flwor_expr_kind)
+  else if (step->theExpr->get_expr_kind() == flwor_expr_kind)
   {
-    static_cast<flwor_expr*>(step->expr.getp())->add_clause(i + 1, flref);
+    static_cast<flwor_expr*>(step->theExpr)->add_clause(i + 1, flref);
     ++step->clauseCount;
   }
   else
   {
-    assert(step->expr->get_expr_kind() == trycatch_expr_kind);
-    trycatch_expr* trycatchExpr = static_cast<trycatch_expr*>(step->expr.getp());
-
-    flwor_expr_t flwor = new flwor_expr(e->get_sctx(), e->get_loc(), false);
+    assert(step->theExpr->get_expr_kind() == trycatch_expr_kind);
+
+    trycatch_expr* trycatchExpr = static_cast<trycatch_expr*>(step->theExpr);
+
+    flwor_expr* flwor = rCtx.theEM->create_flwor_expr(e->get_sctx(), e->get_loc(), false);
     flwor->add_clause(flref);
     flwor->set_return_expr(trycatchExpr->get_try_expr());
 
     trycatchExpr->set_try_expr(flwor);
   }
 
-  expr_t unhoisted = new fo_expr(e->get_sctx(),
+  expr* unhoisted = rCtx.theEM->create_fo_expr(e->get_sctx(),
                                  e->get_loc(),
                                  GET_BUILTIN_FUNCTION(OP_UNHOIST_1),
-                                 new wrapper_expr(e->get_sctx(),
+                                 rCtx.theEM->create_wrapper_expr(e->get_sctx(),
                                                   e->get_loc(),
-                                                  letvar.getp()));
+                                                  letvar));
   unhoisted->setFlags(e->getFlags());
 
-  return unhoisted.getp();
+  return unhoisted;
 }
 
 
@@ -556,7 +558,7 @@
       k == const_expr_kind ||
       k == axis_step_expr_kind ||
       k == match_expr_kind ||
-      (k == wrapper_expr_kind && 
+      (k == wrapper_expr_kind &&
        non_hoistable(static_cast<const wrapper_expr*>(e)->get_expr())) ||
       is_already_hoisted(e) ||
       is_enclosed_expr(e) ||

=== modified file 'src/compiler/rewriter/rules/index_join_rule.cpp'
--- src/compiler/rewriter/rules/index_join_rule.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rules/index_join_rule.cpp	2012-08-14 12:29:44 +0000
@@ -68,9 +68,9 @@
 /*******************************************************************************
   This rule analyzes the where clause of flwor exprs to deterimne whether any
   predicate in the clause is a join predicate and whether the associated join
-  can be converted into a hashjoin using an index that is built on-th-fly. 
+  can be converted into a hashjoin using an index that is built on-th-fly.
 ********************************************************************************/
-expr_t IndexJoinRule::apply(RewriterContext& rCtx, expr* node, bool& modified)
+expr* IndexJoinRule::apply(RewriterContext& rCtx, expr* node, bool& modified)
 {
   flwor_expr* flworExpr = NULL;
 
@@ -101,14 +101,14 @@
     if (isIndexJoinPredicate(rCtx, predInfo))
     {
       rewriteJoin(rCtx, predInfo, modified);
-      
+
       if (modified)
       {
         predInfo.theFlworExpr->remove_where_clause();
-          
-        expr_t e = rCtx.theFlworStack.back();
-
-        ZORBA_ASSERT(e.getp() == node || e->get_expr_kind() == block_expr_kind);
+
+        expr* e = rCtx.theFlworStack.back();
+
+        ZORBA_ASSERT(e == node || e->get_expr_kind() == block_expr_kind);
 
         rCtx.theFlworStack.pop_back();
         rCtx.theInReturnClause.pop_back();
@@ -123,29 +123,29 @@
       {
         PredicateInfo predInfo;
         predInfo.theFlworExpr = flworExpr;
-        predInfo.thePredicate = (*iter);
-        
+        predInfo.thePredicate = (**iter);
+
         if (isIndexJoinPredicate(rCtx, predInfo))
         {
           rewriteJoin(rCtx, predInfo, modified);
-          
+
           if (modified)
           {
-            expr_t trueExpr = new const_expr(flworExpr->get_sctx(),
+            expr* trueExpr = rCtx.theEM->create_const_expr(flworExpr->get_sctx(),
                                              flworExpr->get_loc(),
                                              true);
-            (*iter) = trueExpr;
-            
-            expr_t e = rCtx.theFlworStack.back();
-            
-            ZORBA_ASSERT(e.getp() == node || e->get_expr_kind() == block_expr_kind);
-            
+            (**iter) = trueExpr;
+
+            expr* e = rCtx.theFlworStack.back();
+
+            ZORBA_ASSERT(e == node || e->get_expr_kind() == block_expr_kind);
+
             rCtx.theFlworStack.pop_back();
             rCtx.theInReturnClause.pop_back();
             return e;
           }
         }
-        
+
         iter.next();
       }
     }
@@ -156,19 +156,19 @@
   ExprIterator iter(node);
   while (!iter.done())
   {
-    expr_t currChild = *iter;
+    expr* currChild = **iter;
 
-    if (flworExpr != NULL && currChild.getp() == flworExpr->get_return_expr())
+    if (flworExpr != NULL && currChild == flworExpr->get_return_expr())
       rCtx.theInReturnClause.back() = true;
 
-    expr_t newChild = apply(rCtx, currChild.getp(), modified);
+    expr* newChild = apply(rCtx, currChild, modified);
 
     if (currChild != newChild)
     {
       assert(modified);
-      *iter = newChild;
+      **iter = newChild;
     }
-    
+
     if (modified)
       break;
 
@@ -182,9 +182,9 @@
   }
   else if (node->get_expr_kind() == flwor_expr_kind)
   {
-    expr_t e = rCtx.theFlworStack.back();
+    expr* e = rCtx.theFlworStack.back();
 
-    ZORBA_ASSERT(e.getp() == node || e->get_expr_kind() == block_expr_kind);
+    ZORBA_ASSERT(e == node || e->get_expr_kind() == block_expr_kind);
 
     rCtx.theFlworStack.pop_back();
     rCtx.theInReturnClause.pop_back();
@@ -198,12 +198,12 @@
 
 
 /*******************************************************************************
-  Check whether the given predicate is a join predicate that can be converted 
+  Check whether the given predicate is a join predicate that can be converted
   to a hashjoin.
 ********************************************************************************/
 static bool isIndexJoinPredicate(RewriterContext& rCtx, PredicateInfo& predInfo)
 {
-  const fo_expr* foExpr;
+  const fo_expr* foExpr = NULL;
   const function* fn;
   const expr* predExpr = predInfo.thePredicate;
 
@@ -389,7 +389,7 @@
 
       if (domainType->get_quantifier() != TypeConstants::QUANT_ONE)
       {
-        // found a real FOR var, so we return it. 
+        // found a real FOR var, so we return it.
         return var;
       }
     }
@@ -466,7 +466,7 @@
   // fc->get_expr should not be modified, because we may discover later that the
   // rewrite is not possible after all,
   expr::substitution_t subst;
-  expr_t domainExpr = fc->get_expr()->clone(subst);
+  expr* domainExpr = fc->get_expr()->clone(subst);
 
   if (!expandVars(rCtx, domainExpr, predInfo.theOuterVarId, maxInnerVarId))
     return;
@@ -480,10 +480,10 @@
   store::Item_t qname;
   GENV_ITEMFACTORY->createQName(qname, "", "", os.str().c_str());
 
-  expr_t qnameExpr(new const_expr(sctx, loc, qname));
-  expr_t buildExpr;
+  expr* qnameExpr(rCtx.theEM->create_const_expr(sctx, loc, qname));
+  expr* buildExpr = NULL;
 
-  fo_expr_t createExpr = new fo_expr(sctx,
+  fo_expr* createExpr = rCtx.theEM->create_fo_expr(sctx,
                                      loc,
                                      GET_BUILTIN_FUNCTION(OP_CREATE_INTERNAL_INDEX_2),
                                      qnameExpr,
@@ -501,7 +501,7 @@
     // return expr of F. Otherwise, we first break up F by creating a sub-flwor
     // expr (subF) and moving all clauses of F that appear after V's defining
     // clause into subF, making the return expr of f be the return expr of subF,
-    // and setting subF as the return expr of F. Then, we create the index in 
+    // and setting subF as the return expr of F. Then, we create the index in
     // the return expr of F.
 
     const var_expr* mostInnerVar = (*rCtx.theIdVarMap)[maxInnerVarId];
@@ -527,7 +527,7 @@
 
       const QueryLoc& nestedLoc = mostInnerVarClause->get_loc();
 
-      flwor_expr_t nestedFlwor = new flwor_expr(sctx, nestedLoc, false);
+      flwor_expr* nestedFlwor = rCtx.theEM->create_flwor_expr(sctx, nestedLoc, false);
 
       for (csize i = mostInnerVarPos+1; i < numClauses; ++i)
       {
@@ -541,11 +541,11 @@
 
       nestedFlwor->set_return_expr(innerFlwor->get_return_expr());
 
-      std::vector<expr_t> args(2);
-      args[0] = createExpr.getp();
-      args[1] = nestedFlwor.getp();
+      std::vector<expr*> args(2);
+      args[0] = createExpr;
+      args[1] = nestedFlwor;
 
-      block_expr* seqExpr = new block_expr(sctx, loc, false, args, NULL);
+      block_expr* seqExpr = rCtx.theEM->create_block_expr(sctx, loc, false, args, NULL);
 
       innerFlwor->set_return_expr(seqExpr);
 
@@ -574,15 +574,15 @@
           }
         }
 
-        seqExpr->add_at(arg, createExpr.getp());
+        seqExpr->add_at(arg, createExpr);
       }
       else
       {
-        std::vector<expr_t> args(2);
-        args[0] = createExpr.getp();
+        std::vector<expr*> args(2);
+        args[0] = createExpr;
         args[1] = returnExpr;
 
-        block_expr* seqExpr = new block_expr(sctx, loc, false, args, NULL);
+        block_expr* seqExpr = rCtx.theEM->create_block_expr(sctx, loc, false, args, NULL);
 
         innerFlwor->set_return_expr(seqExpr);
       }
@@ -591,7 +591,7 @@
   else
   {
     // The inner domain expr does not reference any flwor vars. In this case,
-    // find the flwor expr defining the outer var and create the index just 
+    // find the flwor expr defining the outer var and create the index just
     // before this flwor.
     flwor_expr* outerFlworExpr = NULL;
     ulong outerPosInStack = 0;
@@ -605,11 +605,11 @@
       return;
 
     //  Build outer sequential expr
-    std::vector<expr_t> args(2);
-    args[0] = createExpr.getp();
+    std::vector<expr*> args(2);
+    args[0] = createExpr;
     args[1] = outerFlworExpr;
 
-    block_expr* seqExpr = new block_expr(sctx, loc, false, args, NULL);
+    block_expr* seqExpr = rCtx.theEM->create_block_expr(sctx, loc, false, args, NULL);
 
     rCtx.theFlworStack[outerPosInStack] = seqExpr;
   }
@@ -619,39 +619,39 @@
   //
   // Replace the expr defining the inner var with an index probe.
   //
-  fo_expr_t probeExpr;
+  fo_expr* probeExpr = NULL;
 
   if (predInfo.theIsGeneral)
   {
-    probeExpr = 
-    new fo_expr(sctx,
+    probeExpr =
+    rCtx.theEM->create_fo_expr(sctx,
                 loc,
                 GET_BUILTIN_FUNCTION(FN_ZORBA_XQDDF_PROBE_INDEX_POINT_GENERAL_N),
                 qnameExpr,
                 const_cast<expr*>(predInfo.theOuterOp));
 
-    probeExpr = 
-    new fo_expr(sctx,
+    probeExpr =
+    rCtx.theEM->create_fo_expr(sctx,
                 loc,
                 GET_BUILTIN_FUNCTION(OP_SORT_DISTINCT_NODES_ASC_1),
                 probeExpr);
   }
   else
   {
-    probeExpr = 
-    new fo_expr(sctx,
+    probeExpr =
+    rCtx.theEM->create_fo_expr(sctx,
                 loc,
                 GET_BUILTIN_FUNCTION(FN_ZORBA_XQDDF_PROBE_INDEX_POINT_VALUE_N),
                 qnameExpr,
                 const_cast<expr*>(predInfo.theOuterOp));
   }
 
-  fc->set_expr(probeExpr.getp());
+  fc->set_expr(probeExpr);
 
   //
   // Create the IndexDecl obj
   //
-  IndexDecl_t idx = new IndexDecl(sctx, loc, qname);
+  IndexDecl_t idx = new IndexDecl(sctx, rCtx.theCCB, loc, qname);
 
   if (predInfo.theIsGeneral)
     idx->setGeneral(true);
@@ -664,7 +664,7 @@
 
   idx->setDomainPositionVariable(rCtx.createTempVar(sctx, loc, var_expr::pos_var));
 
-  std::vector<expr_t> columnExprs(1);
+  std::vector<expr*> columnExprs(1);
   std::vector<xqtref_t> columnTypes(1);
   std::vector<OrderModifier> modifiers(1);
 
@@ -781,7 +781,7 @@
   ExprIterator iter(subExpr);
   while (!iter.done())
   {
-    if (!expandVars(rCtx, *iter, outerVarId, maxVarId))
+    if (!expandVars(rCtx, **iter, outerVarId, maxVarId))
       return false;
 
     iter.next();
@@ -804,17 +804,17 @@
   flworExpr = NULL;
 
   long numFlwors = (long)rCtx.theFlworStack.size();
- 
+
   for (long i = numFlwors - 1; i >= 0; --i)
   {
     if (rCtx.theFlworStack[i]->get_expr_kind() == trycatch_expr_kind)
       return false;
 
-    flworExpr = dynamic_cast<flwor_expr*>(rCtx.theFlworStack[i].getp());
+    flworExpr = dynamic_cast<flwor_expr*>(rCtx.theFlworStack[i]);
 
     assert(flworExpr != NULL);
 
-    if (i < numFlwors - 1 && 
+    if (i < numFlwors - 1 &&
         rCtx.theInReturnClause[i] == true &&
         flworExpr->is_sequential())
       return false;

=== modified file 'src/compiler/rewriter/rules/nodeid_rules.cpp'
--- src/compiler/rewriter/rules/nodeid_rules.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rules/nodeid_rules.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -39,7 +39,7 @@
 #include "diagnostics/assert.h"
 
 
-namespace zorba 
+namespace zorba
 {
 
 
@@ -48,7 +48,7 @@
   already, set it to the value of the ignore-sorted-nodes annotations of the
   source expr.
 ********************************************************************************/
-static void pushdown_ignores_sorted_nodes(expr* src, expr* target) 
+static void pushdown_ignores_sorted_nodes(expr* src, expr* target)
 {
   if (target->getIgnoresSortedNodes() != ANNOTATION_FALSE)
     target->setIgnoresSortedNodes(src->getIgnoresSortedNodes());
@@ -59,7 +59,7 @@
   If the ignore-sorted-nodes annotation of the target expr is not set to false
   already, set it to the given value.
 ********************************************************************************/
-static void set_ignores_sorted_nodes(expr* target, BoolAnnotationValue v) 
+static void set_ignores_sorted_nodes(expr* target, BoolAnnotationValue v)
 {
   if (target->getIgnoresSortedNodes() != ANNOTATION_FALSE)
     target->setIgnoresSortedNodes(v);
@@ -71,7 +71,7 @@
   false already, set it to the value of the ignore-duplicate-nodes annotations
   of the source expr.
 ********************************************************************************/
-static void pushdown_ignores_duplicate_nodes(expr* src, expr* target) 
+static void pushdown_ignores_duplicate_nodes(expr* src, expr* target)
 {
   if (target->getIgnoresDuplicateNodes() != ANNOTATION_FALSE)
     target->setIgnoresDuplicateNodes(src->getIgnoresDuplicateNodes());
@@ -82,7 +82,7 @@
   If the ignore-duplicates-nodes annotation of the target expr is not set to
   false already, set it to the given value.
 ********************************************************************************/
-static void set_ignores_duplicate_nodes(expr* target, BoolAnnotationValue v) 
+static void set_ignores_duplicate_nodes(expr* target, BoolAnnotationValue v)
 {
   if (target->getIgnoresDuplicateNodes() != ANNOTATION_FALSE)
     target->setIgnoresDuplicateNodes(v);
@@ -102,7 +102,7 @@
   The rule works in a top-down fashion, first setting the annotations of an
   expression e and then moving down to the children of e.
 ********************************************************************************/
-expr_t MarkConsumerNodeProps::apply(
+expr* MarkConsumerNodeProps::apply(
     RewriterContext& rCtx,
     expr* node,
     bool& modified)
@@ -119,7 +119,7 @@
   case order_expr_kind :
   {
     saveInOrderedMode = rCtx.theIsInOrderedMode;
-      
+
     order_expr* orderExpr = static_cast<order_expr *>(node);
 
     rCtx.theIsInOrderedMode = (orderExpr->get_type() == order_expr::ordered ?
@@ -182,18 +182,18 @@
     break;
   }
 
-  case flwor_expr_kind: 
+  case flwor_expr_kind:
   {
     flwor_expr* flwor = static_cast<flwor_expr *>(node);
 
     // no need to do anything for the where expr or the orderby exprs because
     // they don't produce nodes.
-    
+
     // The annotations for the return expr are the same as those of its
     // containing flwor expr.
     pushdown_ignores_sorted_nodes(node, flwor->get_return_expr());
     pushdown_ignores_duplicate_nodes(node, flwor->get_return_expr());
-    
+
     // apply the rule recursively on the return expr
     apply(rCtx, flwor->get_return_expr(), modified);
 
@@ -210,12 +210,12 @@
         let_clause* lc = static_cast<let_clause*>(clause);
         expr* domainExpr = lc->get_expr();
         var_expr* var = lc->get_var();
-        
+
         // The annotations for the domain expr are the same as those of its
         // associated LET var.
         domainExpr->setIgnoresSortedNodes(var->getIgnoresSortedNodes());
         domainExpr->setIgnoresDuplicateNodes(var->getIgnoresDuplicateNodes());
-        
+
         // apply the rule recursively on the domainExpr
         apply(rCtx, domainExpr, modified);
       }
@@ -224,8 +224,8 @@
         for_clause* fc = static_cast<for_clause*>(clause);
         expr* domainExpr = fc->get_expr();
         var_expr* posVar = fc->get_pos_var();
-        assert(posVar == NULL || posVar->get_kind() == var_expr::pos_var); 
-        
+        assert(posVar == NULL || posVar->get_kind() == var_expr::pos_var);
+
         // If a flwor expr does not need to care about producing nodes in doc
         // order, then the domain expr of a FOR variable does not need to care
         // either, unless there is a POS variable associated with the FOR var.
@@ -240,7 +240,7 @@
         {
           domainExpr->setIgnoresSortedNodes(ANNOTATION_FALSE);
         }
-        
+
         // apply the rule recursively on the domainExpr
         apply(rCtx, domainExpr, modified);
       }
@@ -254,9 +254,9 @@
       {
         // apply the rule recursively on the orderby exprs
         orderby_clause* oc = static_cast<orderby_clause*>(clause);
-      
+
         csize numExprs = oc->num_columns();
-      
+
         for (csize i = 0; i < numExprs; ++i)
         {
           apply(rCtx, oc->get_column_expr(i), modified);
@@ -265,8 +265,8 @@
     }
     return NULL;
   }
-  
-  case if_expr_kind: 
+
+  case if_expr_kind:
   {
     if_expr* ite = static_cast<if_expr *>(node);
     pushdown_ignores_sorted_nodes(node, ite->get_then_expr());
@@ -276,14 +276,14 @@
     break;
   }
 
-  case wrapper_expr_kind : 
+  case wrapper_expr_kind :
   {
     wrapper_expr* we = static_cast<wrapper_expr *>(node);
     pushdown_ignores_sorted_nodes(node, we->get_expr());
     pushdown_ignores_duplicate_nodes(node, we->get_expr());
     break;
-  }    
-  
+  }
+
   case function_trace_expr_kind :
   {
     function_trace_expr* fte = static_cast<function_trace_expr*>(node);
@@ -292,9 +292,9 @@
     break;
   }
 
-  case relpath_expr_kind : 
+  case relpath_expr_kind :
   {
-    expr_t arg = (*static_cast<relpath_expr *>(node))[0];
+    expr* arg = (*static_cast<relpath_expr *>(node))[0];
     pushdown_ignores_sorted_nodes(node, arg);
     pushdown_ignores_duplicate_nodes(node, arg);
     break;
@@ -304,17 +304,17 @@
   case castable_expr_kind :
   case instanceof_expr_kind :
   {
-    cast_or_castable_base_expr* curExpr = 
+    cast_or_castable_base_expr* curExpr =
     static_cast<cast_or_castable_base_expr*>(node);
 
     expr* arg = curExpr->get_input();
 
     xqtref_t targetType = curExpr->get_target_type();
     TypeConstants::quantifier_t q = targetType->get_quantifier();
-    
+
     set_ignores_sorted_nodes(arg, ANNOTATION_TRUE);
 
-    if (targetType->is_empty()) 
+    if (targetType->is_empty())
     {
       set_ignores_duplicate_nodes(arg, ANNOTATION_TRUE);
     }
@@ -328,28 +328,28 @@
     {
       set_ignores_duplicate_nodes(arg, ANNOTATION_FALSE);
     }
-    
+
     break;
   }
-  
+
   case promote_expr_kind :
   case treat_expr_kind :
   {
     cast_base_expr* curExpr = static_cast<cast_base_expr*>(node);
 
     expr* arg = curExpr->get_input();
-      
+
     xqtref_t targetType = curExpr->get_target_type();
     TypeConstants::quantifier_t q = targetType->get_quantifier();
 
-    if (targetType->is_empty()) 
+    if (targetType->is_empty())
     {
       set_ignores_sorted_nodes(arg, ANNOTATION_TRUE);
       set_ignores_duplicate_nodes(arg, ANNOTATION_TRUE);
     }
     else
     {
-      if (q == TypeConstants::QUANT_ONE || q == TypeConstants::QUANT_QUESTION) 
+      if (q == TypeConstants::QUANT_ONE || q == TypeConstants::QUANT_QUESTION)
       {
         set_ignores_sorted_nodes(arg, ANNOTATION_TRUE);
       }
@@ -357,7 +357,7 @@
       {
         pushdown_ignores_sorted_nodes(curExpr, arg);
       }
-      
+
       if (curExpr->getIgnoresDuplicateNodes() == ANNOTATION_TRUE &&
           (q == TypeConstants::QUANT_STAR ||
            (q == TypeConstants::QUANT_PLUS &&
@@ -370,41 +370,41 @@
         set_ignores_duplicate_nodes(arg, ANNOTATION_FALSE);
       }
     }
-    
+
     break;
   }
-  
-  case fo_expr_kind : 
+
+  case fo_expr_kind :
   {
     fo_expr* fo = static_cast<fo_expr *>(node);
     function* f = fo->get_func();
-    
+
     FunctionConsts::FunctionKind fkind = f->getKind();
-    
+
     csize numArgs = fo->num_args();
-    
+
     for (csize i = 0; i < numArgs; ++i)
     {
       expr* arg = fo->get_arg(i);
-        
+
       set_ignores_sorted_nodes(arg, f->ignoresSortedNodes(node, i));
-      
+
       set_ignores_duplicate_nodes(arg, f->ignoresDuplicateNodes(node, i));
     }
-      
+
     if (fkind == FunctionConsts::FN_ZERO_OR_ONE_1 ||
         fkind == FunctionConsts::FN_EXACTLY_ONE_1)
     {
-      // If these functions are over a duplicate elimination function, the 
+      // If these functions are over a duplicate elimination function, the
       // duplicate elimination is pulled up into the runtime iterators for
       // fn:zero-or-one or fn:exactly-one.
-      expr_t arg = fo->get_arg(0);
-      
+      expr* arg = fo->get_arg(0);
+
       if (arg->get_expr_kind() == fo_expr_kind)
       {
-        const fo_expr* fo = static_cast<fo_expr *>(arg.getp());
+        const fo_expr* fo = static_cast<fo_expr *>(arg);
         const function* argFunc = fo->get_func();
-        
+
         if (argFunc->isNodeDistinctFunction())
         {
           set_ignores_duplicate_nodes(arg, ANNOTATION_TRUE);
@@ -412,10 +412,10 @@
         }
       }
     }
-    
+
     break;
   }
-  
+
 #ifdef ZORBA_WITH_JSON
   case json_object_expr_kind :
   {
@@ -467,13 +467,13 @@
   case function_item_expr_kind : // TODO
   {
     ExprIterator iter(node);
-    while (!iter.done()) 
+    while (!iter.done())
     {
       if (rCtx.theIsInOrderedMode)
-        (*iter)->setIgnoresSortedNodes(ANNOTATION_FALSE);
-
-      (*iter)->setIgnoresDuplicateNodes(ANNOTATION_TRUE);
-      
+        (**iter)->setIgnoresSortedNodes(ANNOTATION_FALSE);
+
+      (**iter)->setIgnoresDuplicateNodes(ANNOTATION_TRUE);
+
       iter.next();
     }
 
@@ -492,14 +492,14 @@
     ZORBA_ASSERT(false);
   }
   }
-  
+
   ExprIterator iter(node);
   while (!iter.done())
   {
-    apply(rCtx, *iter, modified);
+    apply(rCtx, **iter, modified);
     iter.next();
   }
- 
+
   if (node->get_expr_kind() == order_expr_kind)
      rCtx.theIsInOrderedMode = saveInOrderedMode;
 
@@ -508,9 +508,9 @@
 
 
 /*******************************************************************************
-  
+
 ********************************************************************************/
-expr_t MarkProducerNodeProps::apply(
+expr* MarkProducerNodeProps::apply(
     RewriterContext& rCtx,
     expr* node,
     bool& modified)
@@ -529,7 +529,7 @@
 {
   fo_expr* fo = dynamic_cast<fo_expr *>(node);
 
-  if (fo != NULL) 
+  if (fo != NULL)
   {
     const function* f = fo->get_func();
 
@@ -540,7 +540,7 @@
     const op_node_sort_distinct_base* nsdf;
     nsdf = dynamic_cast<const op_node_sort_distinct_base*>(f);
 
-    if (nsdf != NULL) 
+    if (nsdf != NULL)
     {
       expr* argExpr = fo->get_arg(0);
 
@@ -548,12 +548,12 @@
 
       if (fmin != f)
       {
-        if (fmin != NULL) 
+        if (fmin != NULL)
         {
           fo->set_func(fmin);
           return fo;
         }
-        else 
+        else
         {
           return fo->get_arg(0);
         }
@@ -565,16 +565,16 @@
 }
 
 
-RULE_REWRITE_POST(EliminateNodeOps) 
+RULE_REWRITE_POST(EliminateNodeOps)
 {
-  return NULL; 
+  return NULL;
 }
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-expr_t MarkNodeCopyProps::apply(
+expr* MarkNodeCopyProps::apply(
     RewriterContext& rCtx,
     expr* node,
     bool& modified)
@@ -635,7 +635,7 @@
     expr* node,
     UDFCallChain& udfCaller)
 {
-  switch (node->get_expr_kind()) 
+  switch (node->get_expr_kind())
   {
   case const_expr_kind:
   case var_expr_kind:
@@ -709,12 +709,12 @@
     }
     else
     {
-      std::vector<expr_t>::const_iterator ite = e->begin();
-      std::vector<expr_t>::const_iterator end = e->end();
+      std::vector<expr*>::const_iterator ite = e->begin();
+      std::vector<expr*>::const_iterator end = e->end();
 
       for (++ite; ite != end; ++ite)
       {
-        axis_step_expr* axisExpr = static_cast<axis_step_expr*>((*ite).getp());
+        axis_step_expr* axisExpr = static_cast<axis_step_expr*>((*ite));
         axis_kind_t axisKind = axisExpr->getAxis();
 
         if (axisKind != axis_kind_child &&
@@ -769,7 +769,7 @@
         {
           var_expr* argVar = udf->getArgVar(i);
 
-          // if an arg var of this udf has been marked as a source before, it 
+          // if an arg var of this udf has been marked as a source before, it
           // means that that var is consumed in some "nodeid-sesitive" operation,
           // so we now have to find the sources of the arg expr and mark them.
           if (theSourceFinder->theVarSourcesMap.find(argVar) !=
@@ -878,7 +878,7 @@
   case while_expr_kind:
   case flowctl_expr_kind:
   case exit_expr_kind:
-  case exit_catcher_expr_kind: 
+  case exit_catcher_expr_kind:
   {
     break;
   }
@@ -906,7 +906,7 @@
         {
           short scriptingKind = child->get_scripting_detail();
 
-          if (scriptingKind & APPLYING_EXPR || 
+          if (scriptingKind & APPLYING_EXPR ||
               scriptingKind & EXITING_EXPR ||
               scriptingKind & SEQUENTIAL_FUNC_EXPR)
           {
@@ -939,11 +939,21 @@
       theSourceFinder->findNodeSources(arg, &udfCaller, sources);
       markSources(sources);
     }
+<<<<<<< TREE
 
     std::vector<VarInfo*> globalVars;
+=======
+#if 1
+    std::vector<VarInfo*> globalVars;
+>>>>>>> MERGE-SOURCE
     node->get_sctx()->getVariables(globalVars, false, true);
+<<<<<<< TREE
   
     FOR_EACH(std::vector<VarInfo*>, ite, globalVars)
+=======
+
+    FOR_EACH(std::vector<VarInfo*>, ite, globalVars)
+>>>>>>> MERGE-SOURCE
     {
       var_expr* globalVar = (*ite)->getVar();
 
@@ -954,7 +964,7 @@
       theSourceFinder->findNodeSources(globalVar, &udfCaller, sources);
       markSources(sources);
     }
-
+#endif
     break;
   }
 
@@ -981,16 +991,16 @@
     // Conservatively assume that the function item that is going to be executed
     // requires stand-alone trees as inputs, so find and mark the sources in the
     // arguments. TODO: look for function_item_expr in the subtree to check if
-    // this assumption is really true. 
-    dynamic_function_invocation_expr* e = 
+    // this assumption is really true.
+    dynamic_function_invocation_expr* e =
     static_cast<dynamic_function_invocation_expr*>(node);
 
-    const std::vector<expr_t>& args = e->get_args();
+    const std::vector<expr*>& args = e->get_args();
 
-    FOR_EACH(std::vector<expr_t>, ite, args)
+    FOR_EACH(std::vector<expr*>, ite, args)
     {
       std::vector<expr*> sources;
-      theSourceFinder->findNodeSources((*ite).getp(), &udfCaller, sources);
+      theSourceFinder->findNodeSources((*ite), &udfCaller, sources);
       markSources(sources);
     }
 
@@ -1017,10 +1027,10 @@
   }
 
   ExprIterator iter(node);
-  while(!iter.done()) 
+  while(!iter.done())
   {
-    expr* child = (*iter).getp();
-    if (child != NULL) 
+    expr* child = (**iter);
+    if (child != NULL)
     {
       applyInternal(rCtx, child, udfCaller);
     }
@@ -1041,7 +1051,7 @@
   for (; ite != end; ++ite)
   {
     expr* source = (*ite);
-    
+
     switch (source->get_expr_kind())
     {
     case doc_expr_kind:
@@ -1120,7 +1130,7 @@
       return;
     }
 
-    case var_expr::prolog_var: 
+    case var_expr::prolog_var:
     case var_expr::local_var:
     {
       if (!e->willBeSerialized())
@@ -1221,11 +1231,11 @@
         markForSerialization(body);
       }
 
-      std::vector<var_expr_t>::const_iterator ite = udf->getArgVars().begin();
-      std::vector<var_expr_t>::const_iterator end = udf->getArgVars().end();
+      std::vector<var_expr*>::const_iterator ite = udf->getArgVars().begin();
+      std::vector<var_expr*>::const_iterator end = udf->getArgVars().end();
       for (; ite != end; ++ite)
       {
-        expr* argVar = (*ite).getp();
+        expr* argVar = (*ite);
         if (argVar->willBeSerialized())
         {
           expr* argExpr = e->get_arg(ite - udf->getArgVars().begin());
@@ -1292,7 +1302,7 @@
     break;
   }
 
-  case exit_catcher_expr_kind: 
+  case exit_catcher_expr_kind:
   {
     exit_catcher_expr* e = static_cast<exit_catcher_expr*>(node);
 
@@ -1320,8 +1330,13 @@
     {
       markForSerialization(e->get_arg_expr(i));
     }
+<<<<<<< TREE
 
     std::vector<VarInfo*> globalVars;
+=======
+#if 1
+    std::vector<VarInfo*> globalVars;
+>>>>>>> MERGE-SOURCE
     e->get_sctx()->getVariables(globalVars, true, true);
   
     FOR_EACH(std::vector<VarInfo*>, ite, globalVars)
@@ -1329,7 +1344,7 @@
       var_expr* globalVar = (*ite)->getVar();
       markForSerialization(globalVar);
     }
-
+#endif
     return;
   }
 
@@ -1340,14 +1355,14 @@
 
   case dynamic_function_invocation_expr_kind:
   {
-    dynamic_function_invocation_expr* e = 
+    dynamic_function_invocation_expr* e =
     static_cast<dynamic_function_invocation_expr*>(node);
 
-    const std::vector<expr_t>& args = e->get_args();
+    const std::vector<expr*>& args = e->get_args();
 
-    FOR_EACH(std::vector<expr_t>, ite, args)
+    FOR_EACH(std::vector<expr*>, ite, args)
     {
-      markForSerialization((*ite).getp());
+      markForSerialization((*ite));
     }
 
     break;
@@ -1389,10 +1404,10 @@
   node->setWillBeSerialized(ANNOTATION_TRUE);
 
   ExprIterator iter(node);
-  while(!iter.done()) 
+  while(!iter.done())
   {
-    expr* child = (*iter).getp();
-    if (child != NULL) 
+    expr* child = (**iter);
+    if (child != NULL)
     {
       markForSerialization(child);
     }

=== modified file 'src/compiler/rewriter/rules/path_rules.cpp'
--- src/compiler/rewriter/rules/path_rules.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rules/path_rules.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,20 +21,20 @@
 #include "compiler/expression/path_expr.h"
 
 
-namespace zorba 
+namespace zorba
 {
 
 RULE_REWRITE_PRE(EliminateExtraneousPathSteps)
 {
   relpath_expr* re = dynamic_cast<relpath_expr *>(node);
-  if (re != NULL) 
+  if (re != NULL)
   {
     csize numSteps = re->size();
-    
-    for (csize i = 0; i < numSteps - 1; i++) 
+
+    for (csize i = 0; i < numSteps - 1; i++)
     {
       axis_step_expr* axisStep = dynamic_cast<axis_step_expr*>((*re)[i]);
-      
+
       if (axisStep != NULL &&
           axisStep->getAxis() == axis_kind_descendant_or_self &&
           axisStep->getTest()->getTestKind() == match_anykind_test)
@@ -51,7 +51,7 @@
       }
     }
 
-    if (numSteps == 1) 
+    if (numSteps == 1)
     {
       return (*re) [0];
     }

=== modified file 'src/compiler/rewriter/rules/rule_base.cpp'
--- src/compiler/rewriter/rules/rule_base.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rules/rule_base.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -21,7 +21,7 @@
 #include "compiler/expression/expr_iter.h"
 
 
-namespace zorba 
+namespace zorba
 {
 
 
@@ -30,14 +30,14 @@
   of "curExpr". If any rewrite is done anywhere inside the expr sub tree rooted
   at "curExpr", then "modified" will be set to true ("modified" is never set to
   false by this method). If as part of a re-write, "curExpr" is rewriten into
-  another expr E, then E is returned to the caller.   
+  another expr E, then E is returned to the caller.
 ********************************************************************************/
-expr_t PrePostRewriteRule::apply(RewriterContext& rCtx, expr* curExpr, bool& modified)
+expr* PrePostRewriteRule::apply(RewriterContext& rCtx, expr* curExpr, bool& modified)
 {
-  expr_t result = NULL;
+  expr* result = NULL;
 
-  expr_t newExpr = rewritePre(&*curExpr, rCtx);
-  if (newExpr != NULL) 
+  expr* newExpr = rewritePre(&*curExpr, rCtx);
+  if (newExpr != NULL)
   {
     curExpr = newExpr;
     result = newExpr;
@@ -48,17 +48,17 @@
 
   while (!iter.done())
   {
-    expr_t new_e = apply(rCtx, (*iter).getp(), modified);
+    expr* new_e = apply(rCtx, **iter, modified);
     if (new_e != NULL)
     {
-      *iter = &*new_e;
+      **iter = new_e;
     }
 
     iter.next();
   }
 
   newExpr = rewritePost(&*curExpr, rCtx);
-  if (newExpr != NULL) 
+  if (newExpr != NULL)
   {
     result = newExpr;
     modified = true;

=== modified file 'src/compiler/rewriter/rules/rule_base.h'
--- src/compiler/rewriter/rules/rule_base.h	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rules/rule_base.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -30,7 +30,7 @@
 /*******************************************************************************
 
 ********************************************************************************/
-class RewriteRule : public SimpleRCObject 
+class RewriteRule : public SimpleRCObject
 {
 public:
   typedef enum
@@ -76,7 +76,7 @@
 
   const std::string& getRuleName() const { return theRuleName; }
 
-  virtual expr_t apply(RewriterContext& rCtx, expr* node, bool& modified) = 0;
+  virtual expr* apply(RewriterContext& rCtx, expr* node, bool& modified) = 0;
 };
 
 
@@ -94,12 +94,12 @@
 
   virtual ~PrePostRewriteRule() { }
 
-  expr_t apply(RewriterContext& rCtx, expr* node, bool& modifed);
+  expr* apply(RewriterContext& rCtx, expr* node, bool& modifed);
 
 protected:
-  virtual expr_t rewritePre(expr* node, RewriterContext& rCtx) = 0;
+  virtual expr* rewritePre(expr* node, RewriterContext& rCtx) = 0;
 
-  virtual expr_t rewritePost(expr* node, RewriterContext& rCtx) = 0;
+  virtual expr* rewritePost(expr* node, RewriterContext& rCtx) = 0;
 };
 
 
@@ -116,15 +116,15 @@
   ~name() { }                                                       \
                                                                     \
  protected:                                                         \
-  expr_t rewritePre(expr* node, RewriterContext& rCtx);             \
+  expr* rewritePre(expr* node, RewriterContext& rCtx);             \
                                                                     \
-  expr_t rewritePost(expr* node, RewriterContext& rCtx);            \
+  expr* rewritePost(expr* node, RewriterContext& rCtx);            \
 }
 
 
-#define RULE_REWRITE_PRE(name) expr_t name::rewritePre(expr* node, RewriterContext& rCtx)
+#define RULE_REWRITE_PRE(name) expr* name::rewritePre(expr* node, RewriterContext& rCtx)
 
-#define RULE_REWRITE_POST(name) expr_t name::rewritePost(expr* node, RewriterContext& rCtx)
+#define RULE_REWRITE_POST(name) expr* name::rewritePost(expr* node, RewriterContext& rCtx)
 
 }
 

=== modified file 'src/compiler/rewriter/rules/ruleset.h'
--- src/compiler/rewriter/rules/ruleset.h	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rules/ruleset.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -24,7 +24,7 @@
 #include "compiler/rewriter/rules/rule_base.h"
 
 
-namespace zorba 
+namespace zorba
 {
 
 
@@ -59,13 +59,13 @@
 /*******************************************************************************
 
 ********************************************************************************/
-class FoldConst : public PrePostRewriteRule 
+class FoldConst : public PrePostRewriteRule
 {
 protected:
   bool  theFoldExpensiveOps;
 
-public:     
-  FoldConst(bool fold_expensive_ops) 
+public:
+  FoldConst(bool fold_expensive_ops)
     :
     PrePostRewriteRule(RewriteRule::FoldConst, "FoldConst"),
     theFoldExpensiveOps(fold_expensive_ops)
@@ -73,60 +73,60 @@
   }
 
 protected:
-  expr_t rewritePre(expr* node, RewriterContext& rCtx);
+  expr* rewritePre(expr* node, RewriterContext& rCtx);
 
-  expr_t rewritePost(expr* node, RewriterContext& rCtx);
+  expr* rewritePost(expr* node, RewriterContext& rCtx);
 };
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-class MarkExprs : public RewriteRule 
+class MarkExprs : public RewriteRule
 {
 public:
   MarkExprs() : RewriteRule(RewriteRule::MarkExprs, "MarkExprs") {}
 
-  expr_t apply(RewriterContext& rCtx, expr* node, bool& modified);
+  expr* apply(RewriterContext& rCtx, expr* node, bool& modified);
 };
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-class MarkConsumerNodeProps : public RewriteRule 
+class MarkConsumerNodeProps : public RewriteRule
 {
 public:
-  MarkConsumerNodeProps() 
+  MarkConsumerNodeProps()
     :
     RewriteRule(RewriteRule::MarkConsumerNodeProps, "MarkConsumerNodeProps")
   {
   }
 
-  expr_t apply(RewriterContext& rCtx, expr* node, bool& modified);
+  expr* apply(RewriterContext& rCtx, expr* node, bool& modified);
 };
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-class MarkProducerNodeProps : public RewriteRule 
+class MarkProducerNodeProps : public RewriteRule
 {
 public:
-  MarkProducerNodeProps() 
+  MarkProducerNodeProps()
     :
     RewriteRule(RewriteRule::MarkProducerNodeProps, "MarkProducerNodeProps")
   {
   }
 
-  expr_t apply(RewriterContext& rCtx, expr* node, bool& modified);
+  expr* apply(RewriterContext& rCtx, expr* node, bool& modified);
 };
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-class MarkNodeCopyProps : public RewriteRule 
+class MarkNodeCopyProps : public RewriteRule
 {
   typedef std::set<fo_expr*> UdfCalls;
   //typedef std::vector<fo_expr*> UdfCalls;
@@ -138,13 +138,13 @@
   //UdfCalls       theUdfCallPath;
 
 public:
-  MarkNodeCopyProps() 
+  MarkNodeCopyProps()
     :
     RewriteRule(RewriteRule::MarkNodeCopyProps, "MarkNodeCopyProps")
   {
   }
 
-  expr_t apply(RewriterContext& rCtx, expr* node, bool& modified);
+  expr* apply(RewriterContext& rCtx, expr* node, bool& modified);
 
 protected:
   void applyInternal(RewriterContext& rCtx, expr* node, UDFCallChain& udfCaller);
@@ -158,12 +158,12 @@
 /*******************************************************************************
 
 ********************************************************************************/
-class HoistRule : public RewriteRule 
+class HoistRule : public RewriteRule
 {
 public:
   HoistRule() : RewriteRule(RewriteRule::IndexJoin, "Hoist") {}
 
-  expr_t apply(RewriterContext& rCtx, expr* node, bool& modified);
+  expr* apply(RewriterContext& rCtx, expr* node, bool& modified);
 };
 
 
@@ -171,12 +171,12 @@
 /*******************************************************************************
 
 ********************************************************************************/
-class IndexJoinRule : public RewriteRule 
+class IndexJoinRule : public RewriteRule
 {
 public:
   IndexJoinRule() : RewriteRule(RewriteRule::IndexJoin, "IndexJoin") {}
 
-  expr_t apply(RewriterContext& rCtx, expr* node, bool& modified);
+  expr* apply(RewriterContext& rCtx, expr* node, bool& modified);
 };
 
 

=== modified file 'src/compiler/rewriter/rules/type_rules.cpp'
--- src/compiler/rewriter/rules/type_rules.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/rules/type_rules.cpp	2012-08-14 12:29:44 +0000
@@ -43,13 +43,14 @@
 namespace zorba
 {
 
-static expr_t wrap_in_num_promotion(
+static expr* wrap_in_num_promotion(
     function* fn,
     expr* arg,
     const xqtref_t& oldt,
-    const xqtref_t& t);
+    const xqtref_t& t,
+    RewriterContext& rCtx);
 
-static xqtref_t specialize_numeric(fo_expr* fo, static_context* sctx);
+static xqtref_t specialize_numeric(fo_expr* fo, static_context* sctx, RewriterContext& rCtx);
 
 static function* flip_value_cmp(FunctionConsts::FunctionKind kind);
 
@@ -73,7 +74,7 @@
 
   static_context* sctx = rCtx.getStaticContext(node);
 
-  expr_t bodyExpr = udf->getBody();
+  expr* bodyExpr = udf->getBody();
   xqtref_t bodyType = bodyExpr->get_return_type();
   xqtref_t declaredType = udf->getSignature().return_type();
 
@@ -103,7 +104,7 @@
 
     if (fo->get_func()->getKind() == FunctionConsts::FN_BOOLEAN_1)
     {
-      expr_t arg = fo->get_arg(0);
+      expr* arg = fo->get_arg(0);
       xqtref_t arg_type = arg->get_return_type();
       if (TypeOps::is_subtype(tm, *arg_type, *rtm.BOOLEAN_TYPE_ONE, arg->get_loc()))
         return arg;
@@ -113,7 +114,7 @@
 
     if (fo->get_func()->getKind() == FunctionConsts::FN_DATA_1)
     {
-      expr_t arg = fo->get_arg(0);
+      expr* arg = fo->get_arg(0);
       xqtref_t arg_type = arg->get_return_type();
       if (TypeOps::is_subtype(tm, *arg_type, *rtm.ANY_ATOMIC_TYPE_STAR, arg->get_loc()))
         return arg;
@@ -122,18 +123,18 @@
     }
   }
 
-  cast_base_expr* pe;
+  cast_base_expr* pe = NULL;
 
   // Note: the if cond is true for promote_expr, treat_expr, and cast_expr
   if ((pe = dynamic_cast<cast_base_expr *>(node)) != NULL)
   {
-    expr_t arg = pe->get_input();
+    expr* arg = pe->get_input();
     xqtref_t arg_type = arg->get_return_type();
     xqtref_t target_type = pe->get_target_type();
 
     if (arg->get_expr_kind() == fo_expr_kind)
     {
-      fo_expr* fo = static_cast<fo_expr *>(arg.getp());
+      fo_expr* fo = static_cast<fo_expr *>(arg);
       const function* fn = fo->get_func();
 
       if (fn->isExternal())
@@ -158,7 +159,7 @@
     if (node->get_expr_kind() == cast_expr_kind &&
         TypeOps::is_equal(tm, *arg_ptype, *target_ptype, arg->get_loc()))
     {
-      return new treat_expr(sctx,
+      return rCtx.theEM->create_treat_expr(sctx,
                             node->get_loc(),
                             arg,
                             target_type,
@@ -221,7 +222,7 @@
     if (fnKind == FunctionConsts::FN_SUM_1 ||
         fnKind == FunctionConsts::FN_SUM_2)
     {
-      expr_t argExpr = fo->get_arg(0);
+      expr* argExpr = fo->get_arg(0);
       xqtref_t argType = argExpr->get_return_type();
       std::vector<xqtref_t> argTypes;
       argTypes.push_back(argType);
@@ -236,7 +237,7 @@
                                 *rtm.UNTYPED_ATOMIC_TYPE_STAR,
                                 argExpr->get_loc()))
         {
-          expr_t promoteExpr = new promote_expr(argExpr->get_sctx(),
+          expr* promoteExpr = rCtx.theEM->create_promote_expr(argExpr->get_sctx(),
                                                 argExpr->get_loc(),
                                                 argExpr,
                                                 rtm.DOUBLE_TYPE_STAR,
@@ -252,7 +253,7 @@
     else if (fnKind == FunctionConsts::OP_UNARY_MINUS_1 ||
              fnKind == FunctionConsts::OP_UNARY_PLUS_1)
     {
-      expr_t argExpr = fo->get_arg(0);
+      expr* argExpr = fo->get_arg(0);
       xqtref_t argType = argExpr->get_return_type();
       std::vector<xqtref_t> argTypes;
       argTypes.push_back(argType);
@@ -269,10 +270,10 @@
              fnKind == FunctionConsts::FN_SUBSTRING_2 ||
              fnKind == FunctionConsts::FN_SUBSTRING_3)
     {
-      expr_t posExpr = fo->get_arg(1);
+      expr* posExpr = fo->get_arg(1);
       if (posExpr->get_expr_kind() == promote_expr_kind)
       {
-        promote_expr* promoteExpr = static_cast<promote_expr*>(posExpr.getp());
+        promote_expr* promoteExpr = static_cast<promote_expr*>(posExpr);
         posExpr = promoteExpr->get_input();
       }
 
@@ -281,10 +282,10 @@
 
       if (fo->num_args() == 3)
       {
-        expr_t lenExpr = fo->get_arg(2);
+        expr* lenExpr = fo->get_arg(2);
         if (lenExpr->get_expr_kind() == promote_expr_kind)
         {
-          promote_expr* promoteExpr = static_cast<promote_expr*>(lenExpr.getp());
+          promote_expr* promoteExpr = static_cast<promote_expr*>(lenExpr);
           lenExpr = promoteExpr->get_input();
         }
 
@@ -330,7 +331,7 @@
             ! TypeOps::is_numeric_or_untyped(tm, *t1))
           return NULL;
 
-        if (specialize_numeric(fo, sctx) != NULL)
+        if (specialize_numeric(fo, sctx, rCtx) != NULL)
           return node;
       }
       else if (props.specializeCmp() && fn->isComparisonFunction())
@@ -351,7 +352,7 @@
         {
           xqtref_t string_type = rtm.STRING_TYPE_QUESTION;
           bool string_cmp = true;
-          expr_t nargs[2];
+          expr* nargs[2];
 
           for (int i = 0; i < 2; ++i)
           {
@@ -361,7 +362,7 @@
 
             if (TypeOps::is_subtype(tm, *type, *rtm.UNTYPED_ATOMIC_TYPE_QUESTION, loc))
             {
-              nargs[i] = new cast_expr(arg->get_sctx(),
+              nargs[i] = rCtx.theEM->create_cast_expr(arg->get_sctx(),
                                        arg->get_loc(),
                                        arg,
                                        string_type);
@@ -393,7 +394,7 @@
           }
           else if (TypeOps::is_numeric(tm, *t0) && TypeOps::is_numeric(tm, *t1))
           {
-            xqtref_t aType = specialize_numeric(fo, sctx);
+            xqtref_t aType = specialize_numeric(fo, sctx, rCtx);
             if (aType != NULL)
             {
               if (TypeOps::is_equal(tm,
@@ -402,7 +403,7 @@
                                     fo->get_loc()) &&
                   TypeOps::is_subtype(tm, *t0, *rtm.INTEGER_TYPE_ONE, fo->get_loc()))
               {
-                expr_t tmp = fo->get_arg(0);
+                expr* tmp = fo->get_arg(0);
                 fo->set_arg(0, fo->get_arg(1));
                 fo->set_arg(1, tmp);
                 fo->set_func(flip_value_cmp(fo->get_func()->getKind()));
@@ -440,7 +441,7 @@
           if (!TypeOps::is_equal(tm, *colType, *rtm.EMPTY_TYPE, colLoc) &&
               TypeOps::is_subtype(tm, *colType, *rtm.UNTYPED_ATOMIC_TYPE_STAR, colLoc))
           {
-            expr_t castExpr = new cast_expr(colExpr->get_sctx(),
+            expr* castExpr = rCtx.theEM->create_cast_expr(colExpr->get_sctx(),
                                             colExpr->get_loc(),
                                             colExpr,
                                             rtm.STRING_TYPE_QUESTION);
@@ -460,7 +461,7 @@
 }
 
 
-static xqtref_t specialize_numeric(fo_expr* fo, static_context* sctx)
+static xqtref_t specialize_numeric(fo_expr* fo, static_context* sctx, RewriterContext& rCtx)
 {
   TypeManager* tm = fo->get_type_manager();
 
@@ -490,8 +491,8 @@
   {
     fo->set_func(replacement);
 
-    expr_t newArg0 = wrap_in_num_promotion(replacement, arg0, t0, aType);
-    expr_t newArg1 = wrap_in_num_promotion(replacement, arg1, t1, aType);
+    expr* newArg0 = wrap_in_num_promotion(replacement, arg0, t0, aType, rCtx);
+    expr* newArg1 = wrap_in_num_promotion(replacement, arg1, t1, aType, rCtx);
 
     if (newArg0 != NULL)
       fo->set_arg(0, newArg0);
@@ -506,11 +507,12 @@
 }
 
 
-static expr_t wrap_in_num_promotion(
+static expr* wrap_in_num_promotion(
     function* fn,
     expr* arg,
     const xqtref_t& oldt,
-    const xqtref_t& t)
+    const xqtref_t& t,
+    RewriterContext& rCtx)
 {
   TypeManager* tm = arg->get_type_manager();
 
@@ -528,7 +530,7 @@
       arg = pe->get_input();
   }
 
-  return new promote_expr(arg->get_sctx(),
+  return rCtx.theEM->create_promote_expr(arg->get_sctx(),
                           arg->get_loc(),
                           arg,
                           t,

=== modified file 'src/compiler/rewriter/tools/dataflow_annotations.cpp'
--- src/compiler/rewriter/tools/dataflow_annotations.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/tools/dataflow_annotations.cpp	2012-08-14 12:29:44 +0000
@@ -4,7 +4,7 @@
  * 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
@@ -36,7 +36,7 @@
 #include "diagnostics/assert.h"
 
 
-namespace zorba 
+namespace zorba
 {
 
 
@@ -58,7 +58,7 @@
 ********************************************************************************/
 void DataflowAnnotationsComputer::compute(expr* e)
 {
-  switch(e->get_expr_kind()) 
+  switch(e->get_expr_kind())
   {
   case var_decl_expr_kind:
     compute_var_decl_expr(static_cast<var_decl_expr*>(e));
@@ -91,7 +91,7 @@
     break;
   }
 
-  case exit_catcher_expr_kind: 
+  case exit_catcher_expr_kind:
   {
     default_walk(e);
     generic_compute(e);
@@ -135,7 +135,7 @@
   case trycatch_expr_kind:
     compute_trycatch_expr(static_cast<trycatch_expr *>(e));
     break;
-    
+
   case promote_expr_kind:
     compute_promote_expr(static_cast<promote_expr *>(e));
     break;
@@ -179,11 +179,11 @@
   case relpath_expr_kind:
     compute_relpath_expr(static_cast<relpath_expr *>(e));
     break;
-    
+
   case axis_step_expr_kind:
     compute_axis_step_expr(static_cast<axis_step_expr *>(e));
     break;
-    
+
   case match_expr_kind:
     compute_match_expr(static_cast<match_expr *>(e));
     break;
@@ -191,7 +191,7 @@
   case const_expr_kind:
     compute_const_expr(static_cast<const_expr *>(e));
     break;
-    
+
   case order_expr_kind:
     compute_order_expr(static_cast<order_expr *>(e));
     break;
@@ -199,19 +199,19 @@
   case elem_expr_kind:
     compute_elem_expr(static_cast<elem_expr *>(e));
     break;
-    
+
   case doc_expr_kind:
     compute_doc_expr(static_cast<doc_expr *>(e));
     break;
-    
+
   case attr_expr_kind:
     compute_attr_expr(static_cast<attr_expr *>(e));
     break;
-    
+
   case text_expr_kind:
     compute_text_expr(static_cast<text_expr *>(e));
     break;
-    
+
   case pi_expr_kind:
     compute_pi_expr(static_cast<pi_expr *>(e));
     break;
@@ -226,7 +226,7 @@
     DISTINCT_NODES(e);
   }
 #endif
-    
+
   case dynamic_function_invocation_expr_kind: // TODO
   case function_item_expr_kind: // TODO
   case delete_expr_kind:        // TODO
@@ -240,7 +240,7 @@
   case eval_expr_kind:          // TODO
   case debugger_expr_kind:      // TODO
     break;
-    
+
   default:
     ZORBA_ASSERT(false);
   }
@@ -253,10 +253,10 @@
 void DataflowAnnotationsComputer::default_walk(expr* e)
 {
   ExprIterator iter(e);
-  while(!iter.done()) 
+  while(!iter.done())
   {
-    expr* child = (*iter).getp();
-    if (child != NULL) 
+    expr* child = (**iter);
+    if (child != NULL)
     {
       compute(child);
     }
@@ -279,7 +279,7 @@
   xqtref_t rt = e->get_return_type();
   TypeConstants::quantifier_t quant = rt->get_quantifier();
 
-  if (quant == TypeConstants::QUANT_ONE || quant == TypeConstants::QUANT_QUESTION) 
+  if (quant == TypeConstants::QUANT_ONE || quant == TypeConstants::QUANT_QUESTION)
   {
     SORTED_NODES(e);
     DISTINCT_NODES(e);
@@ -297,7 +297,7 @@
 {
   generic_compute(e);
   default_walk(e);
-  
+
   var_expr* varExpr = e->get_var_expr();
   expr* initExpr = e->get_init_expr();
 
@@ -349,9 +349,9 @@
 ********************************************************************************/
 void DataflowAnnotationsComputer::compute_var_expr(var_expr* e)
 {
-  if (!generic_compute(e)) 
+  if (!generic_compute(e))
   {
-    if (e->get_kind() == var_expr::let_var) 
+    if (e->get_kind() == var_expr::let_var)
     {
       PROPOGATE_SORTED_NODES(e->get_forletwin_clause()->get_expr(), e);
       PROPOGATE_DISTINCT_NODES(e->get_forletwin_clause()->get_expr(), e);
@@ -476,7 +476,7 @@
 {
   default_walk(e);
 
-  if (!generic_compute(e)) 
+  if (!generic_compute(e))
   {
     const function* f = e->get_func();
 
@@ -491,12 +491,12 @@
     else if (sorted == FunctionConsts::NO)
     {
       e->setProducesSortedNodes(ANNOTATION_FALSE);
-    } 
-    else 
+    }
+    else
     {
       BoolAnnotationValue sorted = ANNOTATION_FALSE;
 
-      for (ulong i = 0; i < nArgs; ++i) 
+      for (ulong i = 0; i < nArgs; ++i)
       {
         if (f->propagatesSortedNodes(i))
         {
@@ -510,11 +510,11 @@
 
     FunctionConsts::AnnotationValue distinct = f->producesDistinctNodes();
 
-    if (distinct == FunctionConsts::YES) 
+    if (distinct == FunctionConsts::YES)
     {
       DISTINCT_NODES(e);
     }
-    else if (distinct == FunctionConsts::NO) 
+    else if (distinct == FunctionConsts::NO)
     {
       e->setProducesDistinctNodes(ANNOTATION_FALSE);
     }
@@ -522,9 +522,9 @@
     {
       BoolAnnotationValue distinct = ANNOTATION_FALSE;
 
-      for (ulong i = 0; i < nArgs; ++i) 
+      for (ulong i = 0; i < nArgs; ++i)
       {
-        if (f->propagatesDistinctNodes(i)) 
+        if (f->propagatesDistinctNodes(i))
         {
           distinct = e->get_arg(i)->getProducesDistinctNodes();
           break;
@@ -554,7 +554,7 @@
 void DataflowAnnotationsComputer::compute_treat_expr(treat_expr *e)
 {
   default_walk(e);
-  if (!generic_compute(e)) 
+  if (!generic_compute(e))
   {
     PROPOGATE_SORTED_NODES(e->get_input(), e);
     PROPOGATE_DISTINCT_NODES(e->get_input(), e);
@@ -579,7 +579,7 @@
 void DataflowAnnotationsComputer::compute_cast_expr(cast_expr* e)
 {
   default_walk(e);
-  if (!generic_compute(e)) 
+  if (!generic_compute(e))
   {
     PROPOGATE_SORTED_NODES(e->get_input(), e);
     PROPOGATE_DISTINCT_NODES(e->get_input(), e);
@@ -589,7 +589,7 @@
 void DataflowAnnotationsComputer::compute_name_cast_expr(name_cast_expr* e)
 {
   default_walk(e);
-  if (!generic_compute(e)) 
+  if (!generic_compute(e))
   {
     PROPOGATE_SORTED_NODES(e->get_input(), e);
     PROPOGATE_DISTINCT_NODES(e->get_input(), e);
@@ -609,7 +609,7 @@
 void DataflowAnnotationsComputer::compute_extension_expr(extension_expr* e)
 {
   default_walk(e);
-  if (!generic_compute(e)) 
+  if (!generic_compute(e))
   {
     PROPOGATE_SORTED_NODES(e->get_expr(), e);
     PROPOGATE_DISTINCT_NODES(e->get_expr(), e);
@@ -624,7 +624,7 @@
 {
   default_walk(e);
 
-  if (!generic_compute(e)) 
+  if (!generic_compute(e))
   {
     csize num_steps = e->size();
     bool only_child_axes = true;
@@ -632,7 +632,7 @@
     ulong num_following_axes = 0;
     bool reverse_axes = false;
 
-    for (csize i = 1; i < num_steps; ++i) 
+    for (csize i = 1; i < num_steps; ++i)
     {
       axis_step_expr* ase = dynamic_cast<axis_step_expr *>((*e)[i]);
       assert(ase != NULL);
@@ -662,7 +662,7 @@
       }
     }
 
-    if (only_child_axes) 
+    if (only_child_axes)
     {
       PROPOGATE_SORTED_NODES((*e)[0], e);
       PROPOGATE_DISTINCT_NODES((*e)[0], e);
@@ -671,11 +671,11 @@
     {
       xqtref_t crt = (*e)[0]->get_return_type();
 
-      if (crt->max_card() <= 1) 
+      if (crt->max_card() <= 1)
       {
         bool sorted = false;
         bool distinct = false;
-        if (num_steps == 2) 
+        if (num_steps == 2)
         {
           distinct = true;
           sorted = true;
@@ -689,7 +689,7 @@
         {
           if (reverse_axes == false &&
               num_desc_axes <= 1 &&
-              num_following_axes == 0) 
+              num_following_axes == 0)
           {
             distinct = true;
           }
@@ -801,7 +801,7 @@
 
 /*******************************************************************************
   If the result of the given expr may contain costructed nodes, find the node-
-  constructor exprs where such nodes may come from. 
+  constructor exprs where such nodes may come from.
 
   If "node" is inside a UDF, "udfCaller" contains the fo expr that invoked that
   UDF.
@@ -833,14 +833,14 @@
       --i;
 
       // Note: If this method is called to find the sources of an expr within the
-      // body of a function_item, then udfCaller->theFo will be NULL. 
+      // body of a function_item, then udfCaller->theFo will be NULL.
       while(udfCaller->theFo && varExpr->get_udf() != udfCaller->theFo->get_func())
       {
         udfCaller = udfCaller->thePrev;
       }
 
       if (udfCaller->theFo)
-      {  
+      {
         fo_expr* foExpr = udfCaller->theFo;
         expr* foArg = foExpr->get_arg(varExpr->get_param_pos());
         std::vector<expr*> argSources;
@@ -879,7 +879,7 @@
   if (TypeOps::is_subtype(tm, *retType, *rtm.ANY_ATOMIC_TYPE_STAR, node->get_loc()))
     return;
 
-  switch(node->get_expr_kind()) 
+  switch(node->get_expr_kind())
   {
   case const_expr_kind:
   {
@@ -957,7 +957,7 @@
       return;
     }
 
-    case var_expr::prolog_var: 
+    case var_expr::prolog_var:
     case var_expr::local_var:
     {
       VarSourcesMap::iterator ite = theVarSourcesMap.find(e);
@@ -1010,7 +1010,7 @@
 
     case var_expr::catch_var:
     {
-      // If in the try clause there is an fn:error that generates nodes, it will 
+      // If in the try clause there is an fn:error that generates nodes, it will
       // be (conservatively) treated as a "must copy" function, so all of those
       // nodes will be in standalone trees.
       return;
@@ -1065,7 +1065,7 @@
   case json_object_expr_kind:
   case json_array_expr_kind:
   {
-    // TODO? We need to drill inside a json pair or array constructor only 
+    // TODO? We need to drill inside a json pair or array constructor only
     // if we are coming from an unbox or flatten call ????
     break;
   }
@@ -1110,7 +1110,7 @@
     if (f->isUdf() && static_cast<user_function*>(f)->getBody() != NULL)
     {
       user_function* udf = static_cast<user_function*>(f);
- 
+
       bool recursive = (currentUdf ? currentUdf->isMutuallyRecursiveWith(udf) : false);
 
       if (recursive)
@@ -1165,7 +1165,7 @@
             var_expr* argVar = static_cast<var_expr*>(source);
             ZORBA_ASSERT(argVar->get_kind() == var_expr::arg_var);
             expr* argExpr = e->get_arg(argVar->get_param_pos());
-            
+
             findNodeSourcesRec(argExpr, sources, currentUdf);
           }
           else
@@ -1231,7 +1231,7 @@
     break;
   }
 
-  case exit_catcher_expr_kind: 
+  case exit_catcher_expr_kind:
   {
     exit_catcher_expr* e = static_cast<exit_catcher_expr*>(node);
 
@@ -1266,7 +1266,7 @@
     // Conservatively assume that the function item that is going to be executed
     // is going to propagate its inputs, so find the sources in the arguments.
     // TODO: look for function_item_expr in the subtree to check if this assumption
-    // is really true. 
+    // is really true.
     break;
   }
 
@@ -1276,7 +1276,7 @@
     // TODO
     return;
   }
-    
+
   case castable_expr_kind:
   case cast_expr_kind:
   case instanceof_expr_kind:
@@ -1298,10 +1298,10 @@
   }
 
   ExprIterator iter(node);
-  while(!iter.done()) 
+  while(!iter.done())
   {
-    expr* child = (*iter).getp();
-    if (child != NULL) 
+    expr* child = (**iter);
+    if (child != NULL)
     {
       findNodeSourcesRec(child, sources, currentUdf);
     }
@@ -1325,7 +1325,7 @@
   if (TypeOps::is_subtype(tm, *retType, *rtm.ANY_ATOMIC_TYPE_STAR, node->get_loc()))
     return;
 
-  switch(node->get_expr_kind()) 
+  switch(node->get_expr_kind())
   {
   case const_expr_kind:
   {
@@ -1395,7 +1395,7 @@
       return;
     }
 
-    case var_expr::prolog_var: 
+    case var_expr::prolog_var:
     case var_expr::local_var:
     {
       VarSourcesMap::iterator ite = theVarSourcesMap.find(e);
@@ -1446,7 +1446,7 @@
 
     case var_expr::catch_var:
     {
-      // If in the try clause there is an fn:error that generates nodes, it will 
+      // If in the try clause there is an fn:error that generates nodes, it will
       // be (conservatively) treated as a "must copy" function, so all of those
       // nodes will be in standalone trees.
       return;
@@ -1593,7 +1593,7 @@
     break;
   }
 
-  case exit_catcher_expr_kind: 
+  case exit_catcher_expr_kind:
   {
     exit_catcher_expr* e = static_cast<exit_catcher_expr*>(node);
 
@@ -1628,7 +1628,7 @@
     // Conservatively assume that the function item that is going to be executed
     // is going to propagate its inputs, so find the sources in the arguments.
     // TODO: look for function_item_expr in the subtree to check if this assumption
-    // is really true. 
+    // is really true.
     break;
   }
 
@@ -1638,7 +1638,7 @@
     // TODO
     return;
   }
-    
+
   case castable_expr_kind:
   case cast_expr_kind:
   case instanceof_expr_kind:
@@ -1660,10 +1660,10 @@
   }
 
   ExprIterator iter(node);
-  while(!iter.done()) 
+  while(!iter.done())
   {
-    expr* child = (*iter).getp();
-    if (child != NULL) 
+    expr* child = (**iter);
+    if (child != NULL)
     {
       findLocalNodeSources(child, sources);
     }

=== modified file 'src/compiler/rewriter/tools/expr_tools.cpp'
--- src/compiler/rewriter/tools/expr_tools.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/tools/expr_tools.cpp	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -97,7 +97,7 @@
     {
       if (!count_variable_uses_rec(iter.get_expr(), var, rCtx, limit, count))
         return false;
-      
+
       iter.next();
     }
   }
@@ -126,11 +126,11 @@
 /*******************************************************************************
   copy annotations when wrapping an expression in a new one
 ********************************************************************************/
-expr_t fix_annotations(expr* new_expr, const expr* old_expr) 
+expr* fix_annotations(expr* new_expr, const expr* old_expr)
 {
-  if (old_expr == NULL) 
+  if (old_expr == NULL)
   {
-    switch (new_expr->get_expr_kind()) 
+    switch (new_expr->get_expr_kind())
     {
     case fo_expr_kind:
       old_expr = static_cast<const fo_expr*>(new_expr)->get_arg(0);
@@ -140,7 +140,7 @@
       return NULL;
     }
   }
-  
+
   const expr::FreeVars& old_set = old_expr->getFreeVars();
   const expr::FreeVars& new_set = new_expr->getFreeVars();
 
@@ -177,7 +177,7 @@
   ExprIterator iter(e);
   while (!iter.done())
   {
-    replace_var((*iter), oldVar, newVar);
+    replace_var((**iter), oldVar, newVar);
     iter.next();
   }
 }
@@ -198,7 +198,7 @@
   in FV(e).
 
   Given 2 vars v1 and v2 in FV(e), their prefix ids allows to check if v1 is
-  defined before v2: v1 is defined before v2 iff id(v1) < id(v2). 
+  defined before v2: v1 is defined before v2 iff id(v1) < id(v2).
 ********************************************************************************/
 void index_flwor_vars(
     const expr* e,
@@ -207,13 +207,13 @@
     IdVarMap* idvarmap)
 {
   if (e->get_expr_kind() == flwor_expr_kind ||
-      e->get_expr_kind() == gflwor_expr_kind) 
+      e->get_expr_kind() == gflwor_expr_kind)
   {
     const flwor_expr* flwor = static_cast<const flwor_expr *>(e);
 
     for (flwor_expr::clause_list_t::const_iterator i = flwor->clause_begin();
          i != flwor->clause_end();
-         ++i) 
+         ++i)
     {
       const flwor_clause* c = *i;
 
@@ -262,7 +262,7 @@
 
         for (csize i = 0; i < numGroupVars; ++i)
         {
-          add_var(gvars[i].second.getp(), numVars, varidmap, idvarmap);
+          add_var(gvars[i].second, numVars, varidmap, idvarmap);
         }
 
         const flwor_clause::rebind_list_t& ngvars = gc->get_nongrouping_vars();
@@ -270,7 +270,7 @@
 
         for (csize i = 0; i < numNonGroupVars; ++i)
         {
-          add_var(ngvars[i].second.getp(), numVars, varidmap, idvarmap);
+          add_var(ngvars[i].second, numVars, varidmap, idvarmap);
         }
       }
       else if (c->get_kind() == flwor_clause::count_clause)
@@ -309,15 +309,15 @@
     for (csize i = 0; i < numClauses; ++i)
     {
       const catch_clause_t& clause = (*trycatch)[i];
-      
+
       catch_clause::var_map_t& trycatchVars = clause->get_vars();
-      
+
       catch_clause::var_map_t::const_iterator ite = trycatchVars.begin();
       catch_clause::var_map_t::const_iterator end = trycatchVars.end();
       for (; ite != end; ++ite)
       {
-        const var_expr_t& trycatchVar = (*ite).second;
-        add_var(trycatchVar.getp(), numVars, varidmap, idvarmap);
+        var_expr* trycatchVar = (*ite).second;
+        add_var(trycatchVar, numVars, varidmap, idvarmap);
       }
 
       index_flwor_vars(trycatch->get_catch_expr(i), numVars, varidmap, idvarmap);
@@ -326,10 +326,10 @@
   else
   {
     ExprConstIterator iter(e);
-    while(!iter.done()) 
+    while(!iter.done())
     {
       const expr* ce = iter.get_expr();
-      if (ce) 
+      if (ce)
       {
         index_flwor_vars(ce, numVars, varidmap, idvarmap);
       }
@@ -350,18 +350,18 @@
 {
   const flwor_wincond::vars& inVars = cond->get_in_vars();
   const flwor_wincond::vars& outVars = cond->get_out_vars();
-          
-  add_var(inVars.posvar.getp(), numVars, varidmap, idvarmap);
-  add_var(inVars.curr.getp(), numVars, varidmap, idvarmap);
-  add_var(inVars.prev.getp(), numVars, varidmap, idvarmap);
-  add_var(inVars.next.getp(), numVars, varidmap, idvarmap);
+
+  add_var(inVars.posvar, numVars, varidmap, idvarmap);
+  add_var(inVars.curr, numVars, varidmap, idvarmap);
+  add_var(inVars.prev, numVars, varidmap, idvarmap);
+  add_var(inVars.next, numVars, varidmap, idvarmap);
 
   index_flwor_vars(cond->get_cond(), numVars, varidmap, idvarmap);
 
-  add_var(outVars.posvar.getp(), numVars, varidmap, idvarmap);
-  add_var(outVars.curr.getp(), numVars, varidmap, idvarmap);
-  add_var(outVars.prev.getp(), numVars, varidmap, idvarmap);
-  add_var(outVars.next.getp(), numVars, varidmap, idvarmap);
+  add_var(outVars.posvar, numVars, varidmap, idvarmap);
+  add_var(outVars.curr, numVars, varidmap, idvarmap);
+  add_var(outVars.prev, numVars, varidmap, idvarmap);
+  add_var(outVars.next, numVars, varidmap, idvarmap);
 }
 
 
@@ -388,7 +388,7 @@
   of variables that belong to FV(e) and are referenced by E. Let V(E) be this
   set. V(E) is implemented as a bitset ("freeset") whose size is equal to the
   size of FV(e) and whose i-th bit is on iff the var with prefix id i belongs
-  to V(E). The mapping between E and V(E) is stored in "freevarMap".  
+  to V(E). The mapping between E and V(E) is stored in "freevarMap".
 ********************************************************************************/
 void build_expr_to_vars_map(
     expr* e,
@@ -396,7 +396,7 @@
     DynamicBitset& freeset,
     ExprVarsMap& freevarMap)
 {
-  if (e->get_expr_kind() == var_expr_kind) 
+  if (e->get_expr_kind() == var_expr_kind)
   {
     set_bit(static_cast<var_expr *>(e), varmap, freeset, true);
     freevarMap[e] = freeset;
@@ -407,10 +407,10 @@
 
   DynamicBitset eFreeset(numVars);
   ExprIterator iter(e);
-  while(!iter.done()) 
+  while(!iter.done())
   {
-    expr* ce = &*(*iter);
-    if (ce) 
+    expr* ce = **iter;
+    if (ce)
     {
       eFreeset.reset();
       build_expr_to_vars_map(ce, varmap, eFreeset, freevarMap);
@@ -423,7 +423,7 @@
   // so remove these vars from the freeset of the flwor, if they have been added
   // there.
   if (e->get_expr_kind() == flwor_expr_kind ||
-      e->get_expr_kind() == gflwor_expr_kind) 
+      e->get_expr_kind() == gflwor_expr_kind)
   {
     flwor_expr* flwor = static_cast<flwor_expr *>(e);
 
@@ -472,15 +472,15 @@
 
         for (csize i = 0; i < numGroupVars; ++i)
         {
-          set_bit(gvars[i].second.getp(), varmap, freeset, false);
+          set_bit(gvars[i].second, varmap, freeset, false);
         }
 
         const flwor_clause::rebind_list_t& ngvars = gc->get_nongrouping_vars();
         csize numNonGroupVars = ngvars.size();
-        
+
         for (csize i = 0; i < numNonGroupVars; ++i)
         {
-          set_bit(ngvars[i].second.getp(), varmap, freeset, false);
+          set_bit(ngvars[i].second, varmap, freeset, false);
         }
       }
       else if (c->get_kind() == flwor_clause::count_clause)
@@ -500,15 +500,15 @@
     for (csize i = 0; i < numClauses; ++i)
     {
       const catch_clause_t& clause = (*trycatch)[i];
-      
+
       catch_clause::var_map_t& trycatchVars = clause->get_vars();
-      
+
       catch_clause::var_map_t::const_iterator ite = trycatchVars.begin();
       catch_clause::var_map_t::const_iterator end = trycatchVars.end();
       for (; ite != end; ++ite)
       {
-        const var_expr_t& trycatchVar = (*ite).second;
-        set_bit(trycatchVar.getp(), varmap, freeset, false);
+        var_expr* trycatchVar = (*ite).second;
+        set_bit(trycatchVar, varmap, freeset, false);
       }
     }
   }
@@ -528,15 +528,15 @@
   const flwor_wincond::vars& inVars = cond->get_in_vars();
   const flwor_wincond::vars& outVars = cond->get_out_vars();
 
-  set_bit(inVars.posvar.getp(), varmap, freeset, false);
-  set_bit(inVars.curr.getp(), varmap, freeset, false);
-  set_bit(inVars.prev.getp(), varmap, freeset, false);
-  set_bit(inVars.next.getp(), varmap, freeset, false);
+  set_bit(inVars.posvar, varmap, freeset, false);
+  set_bit(inVars.curr, varmap, freeset, false);
+  set_bit(inVars.prev, varmap, freeset, false);
+  set_bit(inVars.next, varmap, freeset, false);
 
-  set_bit(outVars.posvar.getp(), varmap, freeset, false);
-  set_bit(outVars.curr.getp(), varmap, freeset, false);
-  set_bit(outVars.prev.getp(), varmap, freeset, false);
-  set_bit(outVars.next.getp(), varmap, freeset, false);
+  set_bit(outVars.posvar, varmap, freeset, false);
+  set_bit(outVars.curr, varmap, freeset, false);
+  set_bit(outVars.prev, varmap, freeset, false);
+  set_bit(outVars.next, varmap, freeset, false);
 }
 
 
@@ -569,7 +569,7 @@
 /*******************************************************************************
 
 ********************************************************************************/
-static void set_must_copy(expr* target, BoolAnnotationValue v) 
+static void set_must_copy(expr* target, BoolAnnotationValue v)
 {
   assert(v != ANNOTATION_UNKNOWN);
 
@@ -608,7 +608,7 @@
   already, set it to the value of the no-node-copy annotations of the
   source expr.
 ********************************************************************************/
-static void pushdown_must_copy(expr* src, expr* target) 
+static void pushdown_must_copy(expr* src, expr* target)
 {
   set_must_copy(target, src->getMustCopyNodes());
 }
@@ -617,29 +617,29 @@
 /*******************************************************************************
 
 ********************************************************************************/
-static void pushdown_window_vars(const flwor_wincond* cond, expr* target) 
+static void pushdown_window_vars(const flwor_wincond* cond, expr* target)
 {
   const flwor_wincond::vars& inVars = cond->get_in_vars();
 
   if (inVars.curr)
-    pushdown_must_copy(inVars.curr.getp(), target);
+    pushdown_must_copy(inVars.curr, target);
 
   if (inVars.prev)
-    pushdown_must_copy(inVars.prev.getp(), target);
+    pushdown_must_copy(inVars.prev, target);
 
   if (inVars.next)
-    pushdown_must_copy(inVars.next.getp(), target);
+    pushdown_must_copy(inVars.next, target);
 
   const flwor_wincond::vars& outVars = cond->get_out_vars();
 
   if (outVars.curr)
-    pushdown_must_copy(outVars.curr.getp(), target);
+    pushdown_must_copy(outVars.curr, target);
 
   if (outVars.prev)
-    pushdown_must_copy(outVars.prev.getp(), target);
-  
+    pushdown_must_copy(outVars.prev, target);
+
   if (outVars.next)
-    pushdown_must_copy(outVars.next.getp(), target);
+    pushdown_must_copy(outVars.next, target);
 }
 
 
@@ -648,7 +648,7 @@
 ********************************************************************************/
 void computeMustCopyProperty(expr* inExpr)
 {
-  switch(inExpr->get_expr_kind()) 
+  switch(inExpr->get_expr_kind())
   {
   case const_expr_kind:
   {
@@ -685,12 +685,12 @@
       //pushdown_no_node_copy(inExpr, argExpr);
     }
 
-    case var_expr::prolog_var: 
+    case var_expr::prolog_var:
     case var_expr::local_var:
     {
       // TODO: pass into this function a map with one entry per in-scope var.
-      // The entry maps the var to the most recently encountered assignment 
-      // expr for this var. 
+      // The entry maps the var to the most recently encountered assignment
+      // expr for this var.
       return;
     }
 
@@ -754,12 +754,12 @@
   {
     const relpath_expr* e = static_cast<const relpath_expr*>(inExpr);
 
-    std::vector<expr_t>::const_iterator ite = e->begin();
-    std::vector<expr_t>::const_iterator end = e->end();
+    std::vector<expr*>::const_iterator ite = e->begin();
+    std::vector<expr*>::const_iterator end = e->end();
 
     for (++ite; ite != end; ++ite)
     {
-      axis_step_expr* axisExpr = static_cast<axis_step_expr*>((*ite).getp());
+      axis_step_expr* axisExpr = static_cast<axis_step_expr*>((*ite));
       axis_kind_t axisKind = axisExpr->getAxis();
 
       if (axisKind != axis_kind_child &&
@@ -767,7 +767,7 @@
           axisKind != axis_kind_self &&
           axisKind != axis_kind_attribute)
       {
-        set_must_copy((*e)[0].getp(), ANNOTATION_TRUE_FIXED);
+        set_must_copy((*e)[0], ANNOTATION_TRUE_FIXED);
         break;
       }
     }
@@ -849,7 +849,7 @@
 
         for (; ite != end; ++ite)
         {
-          pushdown_must_copy((*ite).second.getp(), (*ite).first.getp());
+          pushdown_must_copy((*ite).second, (*ite).first);
         }
 
         ite = gc->beginNonGroupVars();
@@ -857,7 +857,7 @@
 
         for (; ite != end; ++ite)
         {
-          pushdown_must_copy((*ite).second.getp(), (*ite).first.getp());
+          pushdown_must_copy((*ite).second, (*ite).first);
         }
 
         break;
@@ -866,8 +866,8 @@
       {
         orderby_clause* ob = static_cast<orderby_clause*>(clause);
 
-        std::vector<expr_t>::iterator ite = ob->begin();
-        std::vector<expr_t>::iterator end = ob->end();
+        std::vector<expr*>::iterator ite = ob->begin();
+        std::vector<expr*>::iterator end = ob->end();
 
         for (; ite != end; ++ite)
         {

=== modified file 'src/compiler/rewriter/tools/expr_tools.h'
--- src/compiler/rewriter/tools/expr_tools.h	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/tools/expr_tools.h	2012-08-14 12:29:44 +0000
@@ -47,16 +47,16 @@
 {
 
 int count_variable_uses(
-    const expr* root, 
-    const var_expr* var, 
-    RewriterContext* rCtx, 
+    const expr* root,
+    const var_expr* var,
+    RewriterContext* rCtx,
     int limit);
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-expr_t fix_annotations(expr* new_expr, const expr* old_expr = NULL);
+expr* fix_annotations(expr* new_expr, const expr* old_expr = NULL);
 
 
 /*******************************************************************************

=== modified file 'src/compiler/rewriter/tools/udf_graph.cpp'
--- src/compiler/rewriter/tools/udf_graph.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/tools/udf_graph.cpp	2012-08-14 12:29:44 +0000
@@ -207,12 +207,12 @@
     return;
 
   user_function* udf = node->theUDF;
-  expr_t body = udf->getBody();
+  expr* body = udf->getBody();
 
   // Note: the body can be NULL when using Plan Serialization
   while (body != NULL)
   {
-    udf->optimize(ccb);
+    udf->optimize();
 
     body = udf->getBody();
 
@@ -221,17 +221,17 @@
 #if 1
     // Set the return type of the function to the type of its body. But do not
     // do it if the body type is a user-defined type because the udf may be
-    // used in another module which does not import the schema that describes 
+    // used in another module which does not import the schema that describes
     // this user-defined type.
     xqtref_t bodyType = body->get_return_type();
     xqtref_t declaredType = udf->getSignature().returnType();
-    
+
     bool udt = (bodyType->type_kind() == XQType::USER_DEFINED_KIND);
 
     if (bodyType->type_kind() == XQType::NODE_TYPE_KIND)
     {
       const NodeXQType* nodeType = static_cast<const NodeXQType*>(bodyType.getp());
-        
+
       xqtref_t contentType = nodeType->get_content_type();
 
       udt = (contentType->type_kind() == XQType::USER_DEFINED_KIND);

=== modified file 'src/compiler/rewriter/tools/udf_graph.h'
--- src/compiler/rewriter/tools/udf_graph.h	2012-08-14 11:13:50 +0000
+++ src/compiler/rewriter/tools/udf_graph.h	2012-08-14 12:29:44 +0000
@@ -1,12 +1,12 @@
 /*
  * Copyright 2006-2008 The FLWOR Foundation.
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
- * 
+ *
  * http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -42,7 +42,7 @@
   ulong                   theVisitId;
 
 public:
-  UDFNode(user_function* udf) 
+  UDFNode(user_function* udf)
     :
     theUDF(udf),
     theVisitId(0)
@@ -71,7 +71,7 @@
 
 
 /******************************************************************************
-  UDFGraph represents the call-graph among all the UDFs that may be invoked 
+  UDFGraph represents the call-graph among all the UDFs that may be invoked
   during the evaluation of a given expr E. We call this graph the "call-graph
   of E".
 
@@ -88,7 +88,7 @@
 
   theRoot:
   --------
-  A "dummy" udf node representing theExpr 
+  A "dummy" udf node representing theExpr
 
   theVisitId:
   -----------
@@ -99,14 +99,14 @@
   traversal reaches a node, we check whether the visit id of the node is == to
   the traversal visit id. If true, we know that the node has been visited already
   by the current traversal. Otherwise, we set its visit id to the visit id of
-  the traversal.   
+  the traversal.
 *******************************************************************************/
-class UDFGraph 
+class UDFGraph
 {
   typedef HashMap<user_function*, UDFNode*, UDFHashMapCmp> UDFMap;
 
 protected:
-  expr_t     theExpr;
+  expr     * theExpr;
   UDFMap     theNodes;
   UDFNode  * theRoot;
   ulong      theVisitId;

=== modified file 'src/compiler/translator/translator.cpp'
--- src/compiler/translator/translator.cpp	2012-08-14 11:13:50 +0000
+++ src/compiler/translator/translator.cpp	2012-08-14 12:29:44 +0000
@@ -116,7 +116,7 @@
 class ModulesInfo;
 class TranslatorImpl;
 
-static expr_t translate_aux(
+static expr* translate_aux(
     TranslatorImpl* rootTranslator,
     const parsenode& root,
     static_context* rootSctx,
@@ -191,9 +191,9 @@
 #define LAST_IDX_VARNAME getLastIdxVarName()
 
 #define DOT_REF                                             \
-  new wrapper_expr(theRootSctx,                             \
+  theExprManager->create_wrapper_expr(theRootSctx,          \
                    loc,                                     \
-                   lookup_ctx_var(DOT_VARNAME, loc).getp())
+                   lookup_ctx_var(DOT_VARNAME, loc))
 
 namespace translator_ns
 {
@@ -271,7 +271,7 @@
   CompilerCB                        * theCCB;
   hashmap<zstring, static_context_t>  mod_sctx_map;
   hashmap<zstring, zstring>           mod_ns_map;
-  checked_vector<expr_t>              theInitExprs;
+  checked_vector<expr*>              theInitExprs;
   std::auto_ptr<static_context>       globalSctx;
 
 public:
@@ -552,6 +552,8 @@
 
   CompilerCB                           * theCCB;
 
+  ExprManager                          * theExprManager;
+
   ModulesInfo                          * theModulesInfo;
   std::map<zstring, zstring>             theModulesStack;
   bool                                   theHaveModuleImportCycle;
@@ -597,7 +599,7 @@
 
   int                                    theTempVarCounter;
 
-  std::stack<expr_t>                     theNodeStack;
+  std::stack<expr*>                     theNodeStack;
 
 #ifndef ZORBA_NO_FULL_TEXT
   std::stack<ftnode*>                    theFTNodeStack;
@@ -638,7 +640,7 @@
   rchandle<QName>                      theDotPosVarName;
   rchandle<QName>                      theLastIdxVarName;
 
-  std::vector<var_expr_t>              theScopedVars;
+  std::vector<var_expr*>              theScopedVars;
 
   StaticContextConsts::xquery_version_t theMaxLibModuleVersion;
 
@@ -657,6 +659,7 @@
   theRootTranslator(rootTranslator),
   theRTM(GENV_TYPESYSTEM),
   theCCB(minfo->theCCB),
+  theExprManager(theCCB->theEM),
   theModulesInfo(minfo),
   theModulesStack(modulesStack),
   theHaveModuleImportCycle(false),
@@ -726,19 +729,19 @@
 
 const QName* getDotVarName() const
 {
-  return theRootTranslator->theDotVarName.getp();
+  return theRootTranslator->theDotVarName;
 }
 
 
 const QName* getDotPosVarName() const
 {
-  return theRootTranslator->theDotPosVarName.getp();
+  return theRootTranslator->theDotPosVarName;
 }
 
 
 const QName* getLastIdxVarName() const
 {
-  return theRootTranslator->theLastIdxVarName.getp();
+  return theRootTranslator->theLastIdxVarName;
 }
 
 
@@ -746,11 +749,11 @@
 /*******************************************************************************
   Pop the top n exprs from theNodeStack and return the last expr that was popped.
 ********************************************************************************/
-expr_t pop_nodestack(int n = 1)
+expr* pop_nodestack(int n = 1)
 {
   ZORBA_ASSERT(n >= 0);
 
-  expr_t e_h;
+  expr* e_h;
 
   for (; n > 0; --n)
   {
@@ -776,7 +779,7 @@
 /*******************************************************************************
   Push the given expr into theNodeStack.
 ********************************************************************************/
-inline void push_nodestack(const expr_t& e)
+inline void push_nodestack(expr* e)
 {
   theNodeStack.push(e);
 
@@ -784,7 +787,7 @@
   if (Properties::instance()->traceTranslator())
   {
     std::cout << "Pushed to nodestack: \n";
-    if (e.getp() != NULL)
+    if (e != NULL)
       e->put(std::cout) << std::endl;
     else
       std::cout << "NULL" << std::endl;
@@ -796,11 +799,11 @@
 /*******************************************************************************
   Assert that the top expr in theNodeStack is a var_expr and pop it.
 ********************************************************************************/
-var_expr_t pop_nodestack_var()
+var_expr* pop_nodestack_var()
 {
-  expr_t e = pop_nodestack();
+  expr* e = pop_nodestack();
   assert (e == NULL || e->get_expr_kind() == var_expr_kind);
-  return static_cast<var_expr *>(e.getp());
+  return static_cast<var_expr *>(e);
 }
 
 
@@ -808,9 +811,9 @@
   Return rchandle to the expr at the top of theNodeStack, or NULL if theNodeStack
   is empty.
 ********************************************************************************/
-expr_t peek_nodestk_or_null()
+expr* peek_nodestk_or_null()
 {
-  return (theNodeStack.empty()) ? expr_t(NULL) : theNodeStack.top();
+  return (theNodeStack.empty()) ? NULL : theNodeStack.top();
 }
 
 
@@ -818,7 +821,7 @@
   Return rchandle to the expr at the top of theNodeStack (crash if theNodeStack
   is empty).
 ********************************************************************************/
-expr_t top_nodestack()
+expr* top_nodestack()
 {
   ZORBA_FATAL( !theNodeStack.empty(), "" );
   return theNodeStack.top();
@@ -829,9 +832,11 @@
   Check if the top expr in theNodeStack is an axis_step, and if so return
   rchandle to it (but do not pop). Otherwise, raise error.
 ********************************************************************************/
-rchandle<axis_step_expr> expect_axis_step_top()
+axis_step_expr* expect_axis_step_top()
 {
-  rchandle<axis_step_expr> axisExpr = peek_nodestk_or_null().dyn_cast<axis_step_expr>();
+  axis_step_expr* axisExpr =
+    dynamic_cast<axis_step_expr*>(peek_nodestk_or_null());
+
   if (axisExpr == NULL)
   {
     std::cout << "Expecting axis step on top of stack; ";
@@ -1068,13 +1073,13 @@
 /*******************************************************************************
   Create a var_expr for a variable with a given qname item, kind, and type
 ********************************************************************************/
-var_expr_t create_var(
+var_expr* create_var(
     const QueryLoc& loc,
     store::Item* qname,
     var_expr::var_kind kind,
     xqtref_t type = NULL)
 {
-  var_expr_t e = new var_expr(theRootSctx, loc, kind, qname);
+  var_expr* e = theExprManager->create_var_expr(theRootSctx, loc, kind, qname);
 
   if (kind == var_expr::pos_var ||
       kind == var_expr::count_var ||
@@ -1094,7 +1099,7 @@
   given qname is expanded to a qname item. An error is raised if the qname
   expansion fails (because there is no namespace binding for the given prefix).
 ********************************************************************************/
-var_expr_t create_var(
+var_expr* create_var(
     const QueryLoc& loc,
     const QName* qname,
     var_expr::var_kind kind,
@@ -1110,7 +1115,7 @@
   Create a var_expr for an internal variable with a given kind. The name to be
   used for the internally generated variable is unique within this translator.
 ********************************************************************************/
-var_expr_t create_temp_var(const QueryLoc& loc, var_expr::var_kind kind)
+var_expr* create_temp_var(const QueryLoc& loc, var_expr::var_kind kind)
 {
   std::string localName = "$$temp" + ztd::to_string(theTempVarCounter++);
 
@@ -1126,13 +1131,17 @@
   Raise error if a var with the same expanded qname is already in the given
   sctx obj.
 ********************************************************************************/
-void bind_var(var_expr_t e, static_context* sctx)
+void bind_var(var_expr* e, static_context* sctx)
 {
   assert(sctx != NULL);
 
+<<<<<<< TREE
   switch (e->get_kind())
   {
   case var_expr::let_var:
+=======
+  if (e->get_kind() == var_expr::let_var)
+>>>>>>> MERGE-SOURCE
   {
     sctx->bind_var(e, e->get_loc(), err::XQST0039);
     break;
@@ -1162,13 +1171,13 @@
   var_expr. Raise error if a var with the same expanded qname item is already
   in the given sctx obj.
 ********************************************************************************/
-var_expr_t bind_var(
+var_expr* bind_var(
     const QueryLoc& loc,
     store::Item* qname,
     var_expr::var_kind kind,
     xqtref_t type = NULL)
 {
-  var_expr_t e = create_var(loc, qname, kind, type);
+  var_expr* e = create_var(loc, qname, kind, type);
   bind_var(e, theSctx);
   return e;
 }
@@ -1180,13 +1189,13 @@
   Raise error if a var with the same expanded qname item is already in the
   given sctx obj or if the expansion of the given qname to a qname item fails.
 ********************************************************************************/
-var_expr_t bind_var(
+var_expr* bind_var(
     const QueryLoc& loc,
     const QName* qname,
     var_expr::var_kind kind,
     xqtref_t type = NULL)
 {
-  var_expr_t e = create_var(loc, qname, kind, type);
+  var_expr* e = create_var(loc, qname, kind, type);
   bind_var(e, theSctx);
   return e;
 }
@@ -1202,7 +1211,7 @@
 
   If var is not found, the method raises appropriate error.
 ********************************************************************************/
-var_expr_t lookup_ctx_var(const QName* qname, const QueryLoc& loc)
+var_expr* lookup_ctx_var(const QName* qname, const QueryLoc& loc)
 {
   if (theIsInIndexDomain)
   {
@@ -1333,7 +1342,7 @@
 ********************************************************************************/
 fo_expr* create_empty_seq(const QueryLoc& loc)
 {
-  return fo_expr::create_seq(theRootSctx, loc);
+  return theExprManager->create_seq(theRootSctx, loc);
 }
 
 
@@ -1374,7 +1383,7 @@
 
   for (csize i = 0; i < n; ++i)
   {
-    expr::expr_t argExpr = foExpr->get_arg(i);
+    expr* argExpr = foExpr->get_arg(i);
 
     xqtref_t paramType;
 
@@ -1420,7 +1429,7 @@
       {
         argExpr = wrap_in_atomization(argExpr);
         argExpr = wrap_in_type_promotion(argExpr,
-                                         paramType, 
+                                         paramType,
                                          PromoteIterator::FUNC_PARAM,
                                          func->getName());
       }
@@ -1442,9 +1451,9 @@
 /*******************************************************************************
   Wrap the given expr in an fn:data() function
 ********************************************************************************/
-expr_t wrap_in_atomization(expr* e)
+expr* wrap_in_atomization(expr* e)
 {
-  return new fo_expr(theRootSctx,
+  return theExprManager->create_fo_expr(theRootSctx,
                      e->get_loc(),
                      GET_BUILTIN_FUNCTION(FN_DATA_1),
                      e);
@@ -1454,21 +1463,26 @@
 /*******************************************************************************
 
 ********************************************************************************/
-expr_t wrap_in_type_promotion(
-    const expr_t& e,
+expr* wrap_in_type_promotion(
+    expr* e,
     const xqtref_t& type,
     PromoteIterator::ErrorKind errorKind,
     store::Item* qname = NULL)
 {
-  return new promote_expr(theRootSctx, e->get_loc(), e, type, errorKind, qname);
+  return theExprManager->create_promote_expr(theRootSctx,
+                                             e->get_loc(),
+                                             e,
+                                             type,
+                                             errorKind,
+                                             qname);
 }
 
 
 /*******************************************************************************
 
 ********************************************************************************/
-expr_t wrap_in_type_match(
-    expr_t e,
+expr* wrap_in_type_match(
+    expr* e,
     const xqtref_t& type,
     const QueryLoc& loc,
     TreatIterator::ErrorKind errorKind,
@@ -1478,33 +1492,44 @@
 
   // treat_expr should be avoided for updating expressions, but in that case
   // "type" will be item()* anyway
-  return (TypeOps::is_subtype(tm, *theRTM.ITEM_TYPE_STAR, *type, loc) ?
-          e :
-          new treat_expr(theRootSctx, e->get_loc(), e, type, errorKind, true, qname));
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
-fo_expr* wrap_in_enclosed_expr(expr_t contentExpr, const QueryLoc& loc)
-{
-  return new fo_expr(theRootSctx,
-                     loc,
-                     GET_BUILTIN_FUNCTION(OP_ENCLOSED_1),
-                     contentExpr);
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
-expr_t wrap_in_bev(expr_t e)
-{
-  fo_expr* fo = new fo_expr(theRootSctx,
-                            e->get_loc(),
-                            GET_BUILTIN_FUNCTION(FN_BOOLEAN_1),
-                            e);
+  if (TypeOps::is_subtype(tm, *theRTM.ITEM_TYPE_STAR, *type, loc))
+  {
+    return e;
+  }
+  else
+  {
+    return theExprManager->create_treat_expr(theRootSctx,
+                                             e->get_loc(),
+                                             e,
+                                             type,
+                                             errorKind,
+                                             true,
+                                             qname);
+}
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+fo_expr* wrap_in_enclosed_expr(expr* contentExpr, const QueryLoc& loc)
+{
+  return theExprManager->create_fo_expr(theRootSctx,
+                                        loc,
+                                        GET_BUILTIN_FUNCTION(OP_ENCLOSED_1),
+                                        contentExpr);
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+expr* wrap_in_bev(expr * e)
+{
+  fo_expr* fo = theExprManager->create_fo_expr(theRootSctx,
+                                               e->get_loc(),
+                                               GET_BUILTIN_FUNCTION(FN_BOOLEAN_1),
+                                               e);
   return fo;
 }
 
@@ -1516,7 +1541,7 @@
   fn:sort-distinct-nodes-asc, or
   fn:sort-distinct-nodes-desc
 ********************************************************************************/
-expr_t wrap_in_dos_and_dupelim(expr_t expr, bool atomics, bool reverse = false)
+expr* wrap_in_dos_and_dupelim(expr* expr, bool atomics, bool reverse = false)
 {
   FunctionConsts::FunctionKind fkind;
 
@@ -1537,11 +1562,11 @@
     fkind = FunctionConsts::OP_SORT_DISTINCT_NODES_ASC_1;
   }
 
-  rchandle<fo_expr> dos = new fo_expr(theRootSctx,
+  fo_expr* dos = theExprManager->create_fo_expr(theRootSctx,
                                       expr->get_loc(),
                                       BuiltinFunctionLibrary::getFunction(fkind),
                                       expr);
-  normalize_fo(dos.getp());
+  normalize_fo(dos);
 
   return &*dos;
 }
@@ -1551,11 +1576,11 @@
   Create a LET clause for the given LET variable "lv", with the given expr "e" as
   its defining expression.
 ********************************************************************************/
-let_clause_t wrap_in_letclause(expr_t e, var_expr_t lv)
+let_clause_t wrap_in_letclause(expr* e, var_expr* lv)
 {
   assert (lv->get_kind () == var_expr::let_var);
 
-  return new let_clause(theRootSctx, e->get_loc(), lv, e.getp());
+  return new let_clause(theRootSctx, theCCB, e->get_loc(), lv, e);
 }
 
 
@@ -1565,7 +1590,7 @@
   expr "e" as its defining expression.
 ********************************************************************************/
 let_clause_t wrap_in_letclause(
-    expr_t e,
+    expr* e,
     const QueryLoc& loc,
     const QName* qname)
 {
@@ -1578,7 +1603,7 @@
   this new var_expr, with the given expr "e" as its defining expression. NOTE:
   the internal var is not registered in the sctx.
 ********************************************************************************/
-let_clause_t wrap_in_letclause(expr_t e)
+let_clause_t wrap_in_letclause(expr* e)
 {
   return wrap_in_letclause(e, create_temp_var(e->get_loc(), var_expr::let_var));
 }
@@ -1588,7 +1613,7 @@
   Create a FOR clause for the given FOR variable "fv" and its associated POS var
   "pv" (pv may be NULL). Use the given expr "e" as the defining expr for "fv".
 ********************************************************************************/
-for_clause_t wrap_in_forclause(expr_t e, var_expr_t fv, var_expr_t pv)
+for_clause_t wrap_in_forclause(expr* e, var_expr* fv, var_expr* pv)
 {
   assert(fv->get_kind () == var_expr::for_var);
   if (pv != NULL)
@@ -1596,7 +1621,8 @@
     assert(pv->get_kind() == var_expr::pos_var);
   }
 
-  return new for_clause(theRootSctx, e->get_loc(), fv, e, pv);
+  return new for_clause(theRootSctx, theCCB,
+                        e->get_loc(), fv, e, pv);
 }
 
 
@@ -1607,7 +1633,7 @@
   defining expression of the FOR var.
 ********************************************************************************/
 for_clause_t wrap_in_forclause(
-    expr_t expr,
+    expr* expr,
     const QueryLoc& loc,
     const QName* fv_qname,
     const QName* pv_qname)
@@ -1623,13 +1649,13 @@
   this new var_expr, with the given expr as its defining expression. NOTE:
   the internal var is not registered in the sctx.
 ********************************************************************************/
-for_clause_t wrap_in_forclause(expr_t expr, bool add_posvar)
+for_clause_t wrap_in_forclause(expr* expr, bool add_posvar)
 {
-  var_expr_t fv = create_temp_var(expr->get_loc(), var_expr::for_var);
+  var_expr* fv = create_temp_var(expr->get_loc(), var_expr::for_var);
 
-  var_expr_t pv = (add_posvar ?
+  var_expr* pv = (add_posvar ?
                    create_temp_var(expr->get_loc(), var_expr::pos_var) :
-                   var_expr_t(NULL));
+                   NULL);
 
   return wrap_in_forclause(expr, fv, pv);
 }
@@ -1643,12 +1669,12 @@
   return retExpr
 
 ********************************************************************************/
-rchandle<flwor_expr> wrap_in_let_flwor(
-    expr_t domExpr,
-    var_expr_t lv,
-    expr_t retExpr)
+flwor_expr* wrap_in_let_flwor(
+    expr* domExpr,
+    var_expr* lv,
+    expr* retExpr)
 {
-  rchandle<flwor_expr> fe = new flwor_expr(theRootSctx, lv->get_loc(), false);
+  flwor_expr* fe = theExprManager->create_flwor_expr(theRootSctx, lv->get_loc(), false);
 
   fe->add_clause(wrap_in_letclause(domExpr, lv));
 
@@ -1672,7 +1698,7 @@
     for $$dot at $$pos in inputExpr
     .....
 ********************************************************************************/
-rchandle<flwor_expr> wrap_expr_in_flwor(
+flwor_expr* wrap_expr_in_flwor(
     expr* inputExpr,
     bool withContextSize)
 {
@@ -1680,7 +1706,7 @@
 
   push_scope();
 
-  rchandle<flwor_expr> flworExpr = new flwor_expr(theRootSctx, loc, false);
+  flwor_expr* flworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
 
   if (withContextSize)
   {
@@ -1688,13 +1714,13 @@
     let_clause_t lcInputSeq = wrap_in_letclause(inputExpr);
 
     // compute the size of the input seq
-    rchandle<fo_expr> countExpr = new fo_expr(theRootSctx,
+    fo_expr* countExpr = theExprManager->create_fo_expr(theRootSctx,
                                               loc,
                                               GET_BUILTIN_FUNCTION(FN_COUNT_1),
                                               lcInputSeq->get_var());
     normalize_fo(countExpr);
 
-    let_clause_t lcLast = wrap_in_letclause(countExpr.getp(),
+    let_clause_t lcLast = wrap_in_letclause(countExpr,
                                             loc,
                                             LAST_IDX_VARNAME);
 
@@ -1738,7 +1764,7 @@
   beginning (e.g. inside functions).
 ********************************************************************************/
 void wrap_in_debugger_expr(
-  expr_t& aExpr,
+  expr* aExpr,
   const QueryLoc& aLoc,
   bool aIsMainModuleBreakable = false,
   bool aIsVarDeclaration = false)
@@ -1746,7 +1772,7 @@
 #ifdef ZORBA_WITH_DEBUGGER
   if (theCCB->theDebuggerCommons != NULL)
   {
-    std::auto_ptr<debugger_expr> lExpr(new debugger_expr(theSctx,
+    std::auto_ptr<debugger_expr> lExpr(theExprManager->create_debugger_expr(theSctx,
                                                          aLoc,
                                                          aExpr,
                                                          theNSCtx,
@@ -1777,14 +1803,14 @@
         continue;
       }
 
-      var_expr_t evalVar = create_var(lBreakable.getLocation(),
+      var_expr* evalVar = create_var(lBreakable.getLocation(),
                                       lVarname,
                                       var_expr::eval_var,
                                       NULL);
 
-      expr_t argExpr = new wrapper_expr(theRootSctx,
+      expr* argExpr = theExprManager->create_wrapper_expr(theRootSctx,
                                         lBreakable.getLocation(),
-                                        rchandle<expr>(argVar));
+                                        argVar);
       lExpr->add_var(evalVar, argExpr);
     }
 
@@ -1831,7 +1857,7 @@
 
       for (int j =  (int)varDecls.size() - 1; j >= 0; --j)
       {
-        VarInDecl* varDecl = varDecls[j].getp();
+        VarInDecl* varDecl = varDecls[j];
 
         vars.insert(lookup_var(varDecl->get_var_name(), loc, err::XPST0008));
 
@@ -1950,12 +1976,12 @@
   treat(ctxvar-get(varName), type)
 
 ********************************************************************************/
-void declare_var(const GlobalBinding& b, std::vector<expr_t>& stmts)
+void declare_var(const GlobalBinding& b, std::vector<expr*>& stmts)
 {
   function* varGet = GET_BUILTIN_FUNCTION(OP_VAR_GET_1);
 
-  expr_t initExpr = b.theExpr;
-  var_expr_t varExpr = b.theVar;
+  expr* initExpr = b.theExpr;
+  var_expr* varExpr = b.theVar;
 
   const QueryLoc& loc = varExpr->get_loc();
 
@@ -1967,29 +1993,30 @@
     varType = GENV_TYPESYSTEM.ITEM_TYPE_ONE;
   }
 
-  if (initExpr != NULL && varType != NULL)
+  if (initExpr != NULL && varType != NULL && !b.is_extern())
   {
-    initExpr = new treat_expr(theRootSctx,
-                              loc,
-                              initExpr,
-                              varType,
-                              TreatIterator::TYPE_MATCH);
+    initExpr = theExprManager->create_treat_expr(theRootSctx,
+                                                 loc,
+                                                 initExpr,
+                                                 varType,
+                                                 TreatIterator::TYPE_MATCH);
   }
 
-  expr_t declExpr = new var_decl_expr(theRootSctx, loc, varExpr, initExpr);
+  expr* declExpr = 
+  theExprManager->create_var_decl_expr(theRootSctx, loc, varExpr, initExpr);
 
   stmts.push_back(declExpr);
 
-  // check type for vars that are external or have an init expr
+  // check type for vars that are external
   if (varType != NULL && b.is_extern())
   {
-    expr_t getExpr = new fo_expr(theRootSctx, loc, varGet, varExpr);
+    expr* getExpr = theExprManager->create_fo_expr(theRootSctx, loc, varGet, varExpr);
 
-    stmts.push_back(new treat_expr(theRootSctx,
-                                   loc,
-                                   getExpr,
-                                   varType, 
-                                   TreatIterator::TYPE_MATCH));
+    stmts.push_back(theExprManager->create_treat_expr(theRootSctx,
+                                                      loc,
+                                                      getExpr,
+                                                      varType,
+                                                      TreatIterator::TYPE_MATCH));
   }
 }
 
@@ -2005,7 +2032,7 @@
   "program" expr is the result of translating the MainModule Program. For non-root
   modules, "program" is an empty fn:concatenate() expr.
 ********************************************************************************/
-expr_t wrap_in_globalvar_assign(const expr_t& program)
+expr* wrap_in_globalvar_assign(expr* program)
 {
   assert(theAssignedVars.size() == 1);
 
@@ -2016,12 +2043,12 @@
     declare_var(*i, theModulesInfo->theInitExprs);
   }
 
-  expr_t preloadedInitExpr = static_cast<static_context*>(theSctx->get_parent())->
+  expr* preloadedInitExpr = static_cast<static_context*>(theSctx->get_parent())->
                              get_query_expr();
 
   if (!theModulesInfo->theInitExprs.empty() || preloadedInitExpr != NULL)
   {
-    std::vector<expr_t> args;
+    std::vector<expr*> args;
     args.reserve(2 + theModulesInfo->theInitExprs.size());
 
     if (preloadedInitExpr)
@@ -2036,7 +2063,7 @@
       args.push_back(program);
     }
 
-    block_expr* res = new block_expr(theRootSctx,
+    block_expr* res = theExprManager->create_block_expr(theRootSctx,
                                      program->get_loc(),
                                      theCCB->theIsEval,
                                      args,
@@ -2227,7 +2254,7 @@
   non-empty string, the corresponding schema is imported. If the location is
   QueryLoc::null, the wrapped expression's location will be used.
 *******************************************************************************/
-expr_t wrap_in_validate_expr_strict(
+expr* wrap_in_validate_expr_strict(
     expr* aExpr,
     const zstring& aSchemaURI)
 {
@@ -2235,7 +2262,7 @@
   import_schema_auto_prefix(lLoc, aSchemaURI.c_str(), NULL);
 
   store::Item_t qname;
-  return new validate_expr(theRootSctx,
+  return theExprManager->create_validate_expr(theRootSctx,
                            lLoc,
                            ParseConstants::val_strict,
                            qname,
@@ -2332,7 +2359,7 @@
   // However, do not create a ver_decl expr for it, because this will create a
   // treat_as expr as well, so the ctx item will always appear as being used,
   // and as a result it will always have to be set.
-  var_expr_t var = bind_var(loc,
+  var_expr* var = bind_var(loc,
                             DOT_VARNAME,
                             var_expr::prolog_var,
                             theSctx->get_context_item_type());
@@ -2348,14 +2375,14 @@
 {
   TRACE_VISIT_OUT();
 
-  expr_t program = pop_nodestack();
+  expr* program = pop_nodestack();
 
   assert(theCCB->theIsEval || !program->is_updating());
 
   // If an appliaction set a type for the context item via the c++ api, then
   // create a full declaration for it in order to enforce that type.
   if (!theHaveContextItemDecl &&
-      theSctx->get_context_item_type() != theRTM.ITEM_TYPE_ONE.getp())
+      theRTM.ITEM_TYPE_ONE != theSctx->get_context_item_type())
   {
     var_expr* var = lookup_ctx_var(DOT_VARNAME, loc);
     var->set_external(true);
@@ -2395,7 +2422,7 @@
 {
   TRACE_VISIT_OUT();
 
-  expr_t program = wrap_in_globalvar_assign(create_empty_seq(loc));
+  expr* program = wrap_in_globalvar_assign(create_empty_seq(loc));
 
   theAssignedVars.pop_back();
 
@@ -2458,7 +2485,7 @@
   found = theModulesInfo->mod_sctx_map.get(uri, lTmpCtx);
   ZORBA_ASSERT(found);
 
-  export_sctx = lTmpCtx.getp();
+  export_sctx = lTmpCtx;
 }
 
 
@@ -3143,7 +3170,7 @@
                               zstring(ZORBA_OPTION_MODULE_VERSION),
                               loc);
         zstring lImportedVersion;
-        if (!moduleRootSctx->lookup_option(lMajorOpt.getp(), lImportedVersion))
+        if (!moduleRootSctx->lookup_option(lMajorOpt, lImportedVersion))
         {
           lImportedVersion = "0.0";
         }
@@ -3181,7 +3208,7 @@
     // current module. Note: We catch duplicate functions / vars in
     // theModulesInfo->globalSctx. We can safely ignore the return value.
     // We might even be able to assert() here (not sure though).
-    theSctx->import_module(importedSctx.getp(), loc);
+    theSctx->import_module(importedSctx, loc);
 
   } // for (vector<zstring>::iterator ite = lURIs.begin();
 }
@@ -3220,7 +3247,7 @@
        it != v.end();
        ++it)
   {
-    const OptionDecl* opt_decl = it->dyn_cast<OptionDecl>().getp();
+    const OptionDecl* opt_decl = it->dyn_cast<OptionDecl>();
 
     if (opt_decl != NULL)
     {
@@ -3246,7 +3273,7 @@
       continue;
     }
 
-    const FunctionDecl* func_decl = it->dyn_cast<FunctionDecl>().getp();
+    const FunctionDecl* func_decl = it->dyn_cast<FunctionDecl>();
 
     // skip variable and option declarations.
     if (func_decl == NULL)
@@ -3270,7 +3297,7 @@
     // - Function must be declared in a non-NULL namespace.
     // - Function must not be in any of the reserved namespaces.
     // - In a module, all exports must be inside the target ns.
-    const QName* fname = func_decl->get_name().getp();
+    const QName* fname = func_decl->get_name();
     store::Item_t qnameItem;
     expand_function_qname(qnameItem, fname, fname->get_location());
 
@@ -3306,8 +3333,8 @@
          it != params->end();
          ++it)
     {
-      const Param* param = (*it).getp();
-      const SequenceType* paramType = param->get_typedecl().getp();
+      const Param* param = (*it);
+      const SequenceType* paramType = param->get_typedecl();
       if (paramType == NULL)
       {
         paramTypes.push_back(GENV_TYPESYSTEM.ITEM_TYPE_STAR);
@@ -3363,7 +3390,7 @@
       // 1. lookup if the function is a built-in function
       f = theSctx->lookup_fn(qnameItem, numParams, false);
 
-      if (f.getp() != 0)
+      if (f != 0)
       {
         if (f->isUdf())
         {
@@ -3525,7 +3552,7 @@
   if (v.get_return_type() != NULL)
     pop_tstack();
 
-  expr_t body;
+  expr* body = NULL;
   user_function* udf = NULL;
 
   if (!v.is_external())
@@ -3593,10 +3620,10 @@
     // If function has any params, they have been wraped in a flwor expr. Set the
     // return clause of the flwor to the body expr of the function, and then make
     // this flwor be the actual body of the function.
-    std::vector<var_expr_t> args;
+    std::vector<var_expr*> args;
     if (numParams > 0)
     {
-      rchandle<flwor_expr> flwor = pop_nodestack().dyn_cast<flwor_expr>();
+      flwor_expr* flwor = dynamic_cast<flwor_expr*>(pop_nodestack());
       ZORBA_ASSERT(flwor != NULL);
 
       for (csize i = 0; i < numParams; ++i)
@@ -3608,14 +3635,14 @@
       }
 
       flwor->set_return_expr(body);
-      body = flwor.getp();
+      body = flwor;
 
       udf->setArgVars(args);
     }
 
     if (udf->isExiting())
     {
-      body = new exit_catcher_expr(theRootSctx, loc, body, theExitExprs);
+      body = theExprManager->create_exit_catcher_expr(theRootSctx, loc, body, theExitExprs);
     }
 
     // Wrap the UDF body to the type-related expr that enforce the declared
@@ -3637,7 +3664,7 @@
     {
       body = wrap_in_type_match(body,
                                 returnType,
-                                loc, 
+                                loc,
                                 TreatIterator::FUNC_RETURN,
                                 udf->getName());
     }
@@ -3654,7 +3681,7 @@
     // pop it from the node stack, but then we just discard it.
     if (numParams > 0)
     {
-      rchandle<flwor_expr> flwor = pop_nodestack().dyn_cast<flwor_expr>();
+      flwor_expr* flwor = dynamic_cast<flwor_expr*>(pop_nodestack());
       ZORBA_ASSERT(flwor != NULL);
     }
   }
@@ -3672,8 +3699,8 @@
 
   if (v.size() > 0)
   {
-    rchandle<flwor_expr> flwor = new flwor_expr(theRootSctx, loc, false);
-    push_nodestack(flwor.getp());
+    flwor_expr* flwor = theExprManager->create_flwor_expr(theRootSctx, loc, false);
+    push_nodestack(flwor);
   }
   return no_state;
 }
@@ -3699,14 +3726,14 @@
 {
   TRACE_VISIT_OUT();
 
-  rchandle<flwor_expr> flwor = theNodeStack.top().cast<flwor_expr> ();
+  flwor_expr* flwor = static_cast<flwor_expr*> (theNodeStack.top());
   ZORBA_ASSERT(flwor != NULL);
 
   store::Item_t qnameItem;
   expand_no_default_qname(qnameItem, v.get_name(), loc);
 
-  var_expr_t arg_var = create_var(loc, qnameItem, var_expr::arg_var);
-  var_expr_t subst_var = bind_var(loc, qnameItem, var_expr::let_var);
+  var_expr* arg_var = create_var(loc, qnameItem, var_expr::arg_var);
+  var_expr* subst_var = bind_var(loc, qnameItem, var_expr::let_var);
 
   let_clause_t lc = wrap_in_letclause(&*arg_var, subst_var);
 
@@ -3786,7 +3813,7 @@
   store::Item_t qnameItem;
   expand_no_default_qname(qnameItem, v.get_var_name(), loc);
 
-  var_expr_t ve;
+  var_expr* ve = NULL;
 
   if (v.is_global())
   {
@@ -3808,7 +3835,7 @@
     ve = create_var(loc, qnameItem, var_expr::local_var);
   }
 
-  push_nodestack(ve.getp());
+  push_nodestack(ve);
   return no_state;
 }
 
@@ -3820,9 +3847,9 @@
   if (v.is_global())
     theCurrentPrologVFDecl.setNull();
 
-  expr_t initExpr = (v.get_binding_expr() == NULL ? expr_t(NULL) : pop_nodestack());
+  expr* initExpr = (v.get_binding_expr() == NULL ? NULL : pop_nodestack());
 
-  var_expr_t ve = dynamic_cast<var_expr*>(pop_nodestack().getp());
+  var_expr* ve = dynamic_cast<var_expr*>(pop_nodestack());
 
   if (theAnnotations)
   {
@@ -3906,12 +3933,12 @@
     // The ve and its associated intExpr will be put into var_decl_expr that
     // will be created by the translation of the parent block expr, immediately
     // after returning from this method.
-    push_nodestack(ve.getp());
+    push_nodestack(ve);
 
 #ifdef ZORBA_WITH_DEBUGGER
     if (initExpr != NULL && theCCB->theDebuggerCommons != NULL)
     {
-      QueryLoc lExpandedLocation = 
+      QueryLoc lExpandedLocation =
       expandQueryLoc(v.get_var_name()->get_location(), initExpr->get_loc());
 
       wrap_in_debugger_expr(initExpr, lExpandedLocation, false, true);
@@ -3966,7 +3993,7 @@
   //bool recognised = false;
 
   store::Item_t lExpandedQName;
-  expand_function_qname(lExpandedQName, v.get_qname().getp(), loc);
+  expand_function_qname(lExpandedQName, v.get_qname(), loc);
 
   zstring annotNS = lExpandedQName->getNamespace();
 
@@ -3987,7 +4014,7 @@
     //recognised = true;
   }
 
-  std::vector<rchandle<const_expr> > lLiterals;
+  std::vector<const_expr*> lLiterals;
 
   if (v.get_literals())
   {
@@ -3997,7 +4024,7 @@
          lIter != v.get_literals()->end();
          ++lIter)
     {
-      rchandle<const_expr> lLiteral = dynamic_cast<const_expr*>(pop_nodestack().getp());
+      const_expr* lLiteral = dynamic_cast<const_expr*>(pop_nodestack());
       lLiterals.insert(lLiterals.begin(), lLiteral);
     }
   }
@@ -4042,7 +4069,7 @@
 {
   TRACE_VISIT_OUT();
 
-  expr_t initExpr;
+  expr* initExpr = NULL;
   if (v.get_expr() != NULL)
     initExpr = pop_nodestack();
 
@@ -4059,7 +4086,7 @@
     assert(type != NULL);
   }
 
-  var_expr_t var;
+  var_expr* var = NULL;
 
   if (inLibraryModule())
   {
@@ -4187,7 +4214,7 @@
   StaticContextConsts::declaration_property_t lOrderMode;
   StaticContextConsts::node_modifier_t lNodeModifier;
 
-  std::vector<rchandle<const_expr> > lLiterals;
+  std::vector<const_expr* > lLiterals;
   if (ZANN_CONTAINS(zann_queue))
   {
     lUpdateMode = StaticContextConsts::decl_queue;
@@ -4316,7 +4343,7 @@
     ERROR_PARAMS(qname->get_qname()));
   }
 
-  IndexDecl_t index = new IndexDecl(theSctx, loc, qnameItem);
+  IndexDecl_t index = new IndexDecl(theSctx, theCCB,  loc, qnameItem);
   index->setGeneral(false);
   index->setUnique(false);
   index->setMethod(IndexDecl::HASH);
@@ -4388,7 +4415,7 @@
 
   IndexDecl* index = theIndexDecl;
 
-  expr_t domainExpr = pop_nodestack();
+  expr* domainExpr = pop_nodestack();
 
   if (!domainExpr->is_simple())
   {
@@ -4443,7 +4470,7 @@
   // and not allow the domain expr to return duplicate nodes.
   if (index->isGeneral())
   {
-    domainExpr = new fo_expr(theRootSctx,
+    domainExpr = theExprManager->create_fo_expr(theRootSctx,
                              domainExpr->get_loc(),
                              GET_BUILTIN_FUNCTION(OP_CHECK_DISTINCT_NODES_1),
                              domainExpr);
@@ -4452,7 +4479,7 @@
   std::string msg = "Domain expr for index " + index->getName()->getStringValue().str();
 
   if (theCCB->theConfig.translate_cb != NULL)
-    theCCB->theConfig.translate_cb(domainExpr.getp(), msg);
+    theCCB->theConfig.translate_cb(domainExpr, msg);
 
   // Optimize the domain expr. We do this even if the optimizer is off.
   // if (theCCB->theConfig.opt_level == CompilerCB::config::O1)
@@ -4486,7 +4513,7 @@
 
   ulong numColumns = v.size();
 
-  std::vector<expr_t> keyExprs(numColumns);
+  std::vector<expr*> keyExprs(numColumns);
   std::vector<xqtref_t> keyTypes(numColumns);
   std::vector<OrderModifier> keyModifiers(numColumns);
 
@@ -4499,7 +4526,7 @@
 
     const QueryLoc& kloc = keySpec->get_location();
 
-    expr_t keyExpr = pop_nodestack();
+    expr* keyExpr = pop_nodestack();
 
     if (!keyExpr->is_simple())
     {
@@ -4577,7 +4604,7 @@
     {
       // Eliminate duplicate key values, as they don't play any role in a
       // general comparison predicate.
-      keyExpr = new fo_expr(theRootSctx,
+      keyExpr = theExprManager->create_fo_expr(theRootSctx,
                             keyExpr->get_loc(),
                             GET_BUILTIN_FUNCTION(FN_DISTINCT_VALUES_1),
                             keyExpr);
@@ -4607,7 +4634,7 @@
     msg << "key expr " << i << " for index " << index->getName()->getStringValue();
 
     if (theCCB->theConfig.translate_cb != NULL)
-      theCCB->theConfig.translate_cb(keyExpr.getp(), msg.str());
+      theCCB->theConfig.translate_cb(keyExpr, msg.str());
 
     // Optimize the key expr. We do this even if the optimizer is off.
     // if (theCCB->theConfig.opt_level == CompilerCB::config::O1)
@@ -4708,42 +4735,43 @@
     **********************/
 
     // "example:coll1"
-    expr_t qnameStrExpr = new const_expr(theRootSctx, loc,
+    expr* qnameStrExpr = theExprManager->create_const_expr(theRootSctx, loc,
                                          ic.getCollName()->get_qname().str());
 
     zstring prefixStr = ic.getCollName()->get_prefix();
     zstring uriStr;
     theSctx->lookup_ns(uriStr, prefixStr, loc);
 
-    expr_t uriStrExpr = new const_expr(theRootSctx, loc, uriStr);
+    expr* uriStrExpr = theExprManager->create_const_expr(theRootSctx, loc, uriStr);
 
     // fn:QName("uri", "example:coll1")
-    fo_expr_t qnameExpr = new fo_expr(theRootSctx, loc,
+    fo_expr* qnameExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                       GET_BUILTIN_FUNCTION(FN_QNAME_2),
                                       uriStrExpr, qnameStrExpr);
 
     // dc:collection(xs:QName("example:coll1"))
     function* fn_collection = GET_BUILTIN_FUNCTION(STATIC_COLLECTIONS_DML_COLLECTION_1);
     ZORBA_ASSERT(fn_collection != NULL);
-    std::vector<expr_t> argColl;
-    argColl.push_back(qnameExpr.getp());
-    fo_expr_t collExpr = new fo_expr(theRootSctx, loc, fn_collection, argColl);
+    std::vector<expr*> argColl;
+    argColl.push_back(qnameExpr);
+    fo_expr* collExpr = theExprManager->create_fo_expr(theRootSctx, loc, fn_collection, argColl);
 
     // $x
     const QName* varQName = ic.getCollVarName();
-    var_expr_t varExpr = bind_var(loc, varQName, var_expr::let_var, NULL);
+    var_expr* varExpr = bind_var(loc, varQName, var_expr::let_var, NULL);
 
     // let $x := dc:collection(xs:QName("example:coll1"))
     let_clause* lc = new let_clause(theRootSctx,
+                                    theCCB,
                                     loc,
                                     varExpr,
-                                    collExpr.getp());
+                                    collExpr);
 
-    flwor_expr_t flworExpr = new flwor_expr(theRootSctx, loc, false);
+    flwor_expr* flworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
     flworExpr->add_clause(lc);
     // flworExpr-> return clause to be set in end_visitor
 
-    push_nodestack(flworExpr.getp());
+    push_nodestack(flworExpr);
   }
   break;
 
@@ -4780,7 +4808,7 @@
       dynamic_cast<const ICCollUniqueKeyCheck&>(v);
 
     // "org:employees"
-    expr_t qnameStrExpr = new const_expr(theRootSctx,
+    expr* qnameStrExpr = theExprManager->create_const_expr(theRootSctx,
                                          loc,
                                          ic.getCollName()->get_qname().str());
 
@@ -4788,19 +4816,19 @@
     zstring uriStr;
     theSctx->lookup_ns(uriStr, prefixStr, loc);
 
-    expr_t uriStrExpr = new const_expr(theRootSctx, loc, uriStr);
+    expr* uriStrExpr = theExprManager->create_const_expr(theRootSctx, loc, uriStr);
 
     // fn:QName("org-uri", "org:employees")
-    fo_expr_t qnameExpr = new fo_expr(theRootSctx, loc,
+    fo_expr* qnameExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                       GET_BUILTIN_FUNCTION(FN_QNAME_2),
                                       uriStrExpr, qnameStrExpr);
 
     // dc:collection(xs:QName("org:employees"))
     function* fn_collection = GET_BUILTIN_FUNCTION(STATIC_COLLECTIONS_DML_COLLECTION_1);
     ZORBA_ASSERT(fn_collection != NULL);
-    std::vector<expr_t> argColl;
-    argColl.push_back(qnameExpr.getp());
-    fo_expr_t collExpr = new fo_expr(theRootSctx, loc, fn_collection, argColl);
+    std::vector<expr*> argColl;
+    argColl.push_back(qnameExpr);
+    fo_expr* collExpr = theExprManager->create_fo_expr(theRootSctx, loc, fn_collection, argColl);
 
     // $x
     const QName* varQName = ic.getNodeVarName();
@@ -4810,33 +4838,34 @@
     // every $x_ in $x satisfies exists ...
     // every is implemented as a flowr expr
     push_scope();
-    flwor_expr_t evFlworExpr = new flwor_expr(theRootSctx, loc, false);
-    evFlworExpr->set_return_expr(new const_expr(theRootSctx, loc, true));
+    flwor_expr* evFlworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
+    evFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx, loc, true));
 
     // $x_ in dc:collection( xs:QName("org:employees") )
-    var_expr_t evVarExpr = bind_var(loc,
+    var_expr* evVarExpr = bind_var(loc,
                                     varItem,
                                     var_expr::for_var,
                                     NULL);
 
     // maybe make one more collExpr?
-    evFlworExpr->add_clause(wrap_in_forclause(collExpr.getp(), evVarExpr, NULL));
+    evFlworExpr->add_clause(wrap_in_forclause(collExpr, evVarExpr, NULL));
 
     pop_scope();
     // end every
 
     // let $x := dc:collection(xs:QName("org:employees"))
     //   return
-    var_expr_t varExpr = bind_var(loc,
-                                  varItem.getp(),
+    var_expr* varExpr = bind_var(loc,
+                                  varItem,
                                   var_expr::let_var,
                                   NULL);
 
     let_clause* letClause = new let_clause(theRootSctx,
+                                           theCCB,
                                            loc,
                                            varExpr,
-                                           collExpr.getp());
-    flwor_expr_t flworExpr = new flwor_expr(theRootSctx, loc, false);
+                                           collExpr);
+    flwor_expr* flworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
 
 
 
@@ -4844,9 +4873,9 @@
     // flworExpr->set_return_expr( andExpr ); done in end_visit
 
     // push evFlworExpr because where clause must be set
-    push_nodestack(evFlworExpr.getp());
+    push_nodestack(evFlworExpr);
     // push the top expresion
-    push_nodestack(flworExpr.getp());
+    push_nodestack(flworExpr);
   }
   break;
 
@@ -4871,47 +4900,47 @@
       dynamic_cast<const ICCollForeachNode&>(v);
 
     // "org:transactions"
-    expr_t qnameStrExpr = new const_expr(theRootSctx, loc,
+    expr* qnameStrExpr = theExprManager->create_const_expr(theRootSctx, loc,
                                          ic.getCollName()->get_qname().str());
 
     zstring prefixStr = ic.getCollName()->get_prefix();
     zstring uriStr;
     theSctx->lookup_ns(uriStr, prefixStr, loc);
 
-    expr_t uriStrExpr = new const_expr(theRootSctx, loc, uriStr);
+    expr* uriStrExpr = theExprManager->create_const_expr(theRootSctx, loc, uriStr);
 
     // fn:QName("org-uri", "org:transactions")
-    fo_expr_t qnameExpr = new fo_expr(theRootSctx, loc,
+    fo_expr* qnameExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                       GET_BUILTIN_FUNCTION(FN_QNAME_2),
                                       uriStrExpr, qnameStrExpr);
 
     // dc:collection(xs:QName("org:transactions"))
     function* fn_collection = GET_BUILTIN_FUNCTION(STATIC_COLLECTIONS_DML_COLLECTION_1);
     ZORBA_ASSERT(fn_collection != NULL);
-    std::vector<expr_t> argColl;
-    argColl.push_back(qnameExpr.getp());
-    fo_expr_t collExpr = new fo_expr(theRootSctx, loc, fn_collection, argColl);
+    std::vector<expr*> argColl;
+    argColl.push_back(qnameExpr);
+    fo_expr* collExpr = theExprManager->create_fo_expr(theRootSctx, loc, fn_collection, argColl);
 
     // every $x_ in $x satisfies exists ...
     // every is implemented as a flowr expr
     //push_scope();
-    flwor_expr_t evFlworExpr = new flwor_expr(theRootSctx, loc, false);
-    evFlworExpr->set_return_expr(new const_expr(theRootSctx, loc, true));
+    flwor_expr* evFlworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
+    evFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx, loc, true));
 
     // $x
     const QName* varQName = ic.getCollVarName();
 
     // $x_ in dc:collection( xs:QName("org:employees") )
-    var_expr_t evVarExpr = bind_var(loc, varQName, var_expr::for_var, NULL);
+    var_expr* evVarExpr = bind_var(loc, varQName, var_expr::for_var, NULL);
 
     // maybe make one more collExpr?
-    evFlworExpr->add_clause(wrap_in_forclause(collExpr.getp(),
+    evFlworExpr->add_clause(wrap_in_forclause(collExpr,
                                               evVarExpr,
                                               NULL));
 
     //pop_scope();
     // end every
-    push_nodestack(evFlworExpr.getp());
+    push_nodestack(evFlworExpr);
   }
   break;
 
@@ -4943,65 +4972,65 @@
 
     // TO part
     // "org:employees"
-    expr_t toQnameStrExpr = new const_expr(theRootSctx, loc,
+    expr* toQnameStrExpr = theExprManager->create_const_expr(theRootSctx, loc,
                                            ic.getToCollName()->get_qname().str());
     zstring toPrefixStr = ic.getToCollName()->get_prefix();
     zstring toUriStr;
     theSctx->lookup_ns(toUriStr, toPrefixStr, loc);
 
-    expr_t toUriStrExpr = new const_expr(theRootSctx, loc, toUriStr);
+    expr* toUriStrExpr = theExprManager->create_const_expr(theRootSctx, loc, toUriStr);
 
     // xs:QName("org:employees")
-    fo_expr_t toQnameExpr = new fo_expr(theRootSctx, loc,
+    fo_expr* toQnameExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                         GET_BUILTIN_FUNCTION(FN_QNAME_2),
                                         toUriStrExpr, toQnameStrExpr);
 
     // dc:collection(xs:QName("org:employees"))
     function* toFnCollection = GET_BUILTIN_FUNCTION(STATIC_COLLECTIONS_DML_COLLECTION_1);
     ZORBA_ASSERT(toFnCollection != NULL);
-    std::vector<expr_t> toArgColl;
-    toArgColl.push_back(toQnameExpr.getp());
-    fo_expr_t toCollExpr = new fo_expr(theRootSctx, loc, toFnCollection,
+    std::vector<expr*> toArgColl;
+    toArgColl.push_back(toQnameExpr);
+    fo_expr* toCollExpr = theExprManager->create_fo_expr(theRootSctx, loc, toFnCollection,
                                        toArgColl);
 
     // some $y in dc:collection( xs:QName("org:employees") )
     // satisfies ... eq ...
     // implemented using flowr
-    flwor_expr_t someFlworExpr = new flwor_expr(theRootSctx, loc, false);
-    someFlworExpr->set_return_expr(new const_expr(theRootSctx, loc, true));
+    flwor_expr* someFlworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
+    someFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx, loc, true));
 
     // $y
     const QName* toVarQName = ic.getToNodeVarName();
-    var_expr_t toVarExpr = bind_var(loc, toVarQName, var_expr::for_var, NULL);
+    var_expr* toVarExpr = bind_var(loc, toVarQName, var_expr::for_var, NULL);
 
     // for $y in dc:collection(xs:QName("org:employees"))
-    someFlworExpr->add_clause(wrap_in_forclause(toCollExpr.getp(),
+    someFlworExpr->add_clause(wrap_in_forclause(toCollExpr,
                                                 toVarExpr,
                                                 NULL));
 
 
     // FROM part
     // "org:transactions"
-    expr_t fromQnameStrExpr = new const_expr(theRootSctx, loc,
+    expr* fromQnameStrExpr = theExprManager->create_const_expr(theRootSctx, loc,
                                              ic.getFromCollName()->get_qname().str());
 
     zstring fromPrefixStr = ic.getFromCollName()->get_prefix();
     zstring fromUriStr;
     theSctx->lookup_ns(fromUriStr, fromPrefixStr, loc);
 
-    expr_t fromUriStrExpr = new const_expr(theRootSctx, loc, fromUriStr);
+    expr* fromUriStrExpr = theExprManager->create_const_expr(theRootSctx, loc, fromUriStr);
 
     // fn:QName("org-uri", "org:transactions")
-    fo_expr_t fromQnameExpr = new fo_expr(theRootSctx, loc,
+    fo_expr* fromQnameExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                           GET_BUILTIN_FUNCTION(FN_QNAME_2),
                                           fromUriStrExpr, fromQnameStrExpr);
 
     // dc:collection(xs:QName("org:transactions"))
     function* fromFnCollection = GET_BUILTIN_FUNCTION(STATIC_COLLECTIONS_DML_COLLECTION_1);
     ZORBA_ASSERT(fromFnCollection != NULL);
-    std::vector<expr_t> fromArgColl;
-    fromArgColl.push_back(fromQnameExpr.getp());
-    fo_expr_t fromCollExpr = new fo_expr(theRootSctx,
+    std::vector<expr*> fromArgColl;
+    fromArgColl.push_back(fromQnameExpr);
+    fo_expr* fromCollExpr = theExprManager->create_fo_expr(theRootSctx,
                                          loc,
                                          fromFnCollection,
                                          fromArgColl);
@@ -5009,20 +5038,20 @@
     // every $x in dc:collection( xs:QName("org:transactions") )
     // satisfies ...
     // implemented using flowr
-    flwor_expr_t evFlworExpr = new flwor_expr(theRootSctx, loc, false);
-    evFlworExpr->set_return_expr(new const_expr(theRootSctx, loc, true));
+    flwor_expr* evFlworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
+    evFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx, loc, true));
 
     // $x
     const QName* fromVarQName = ic.getFromNodeVarName();
-    var_expr_t fromVarExpr = bind_var(loc, fromVarQName, var_expr::for_var, NULL);
+    var_expr* fromVarExpr = bind_var(loc, fromVarQName, var_expr::for_var, NULL);
 
     // for $x in dc:collection(xs:QName("org:transactions"))
-    evFlworExpr->add_clause(wrap_in_forclause(fromCollExpr.getp(),
+    evFlworExpr->add_clause(wrap_in_forclause(fromCollExpr,
                                               fromVarExpr, NULL));
 
 
-    push_nodestack(someFlworExpr.getp());
-    push_nodestack(evFlworExpr.getp());
+    push_nodestack(someFlworExpr);
+    push_nodestack(evFlworExpr);
   }
   break;
 
@@ -5039,7 +5068,7 @@
   TRACE_VISIT_OUT();
 
   //fill in the body of the function
-  expr_t body;
+  expr* body = NULL;
   const QName* qname = v.getName();
 
   // todo cezar: error if user expresions are sequential
@@ -5051,13 +5080,13 @@
     {
       //const ICCollSimpleCheck ic = dynamic_cast<const ICCollSimpleCheck&>(v);
 
-      expr_t icExpr = pop_nodestack();
+      expr* icExpr = pop_nodestack();
 
-      flwor_expr_t flworExpr =
-        dynamic_cast<flwor_expr*>(pop_nodestack().getp());
+      flwor_expr* flworExpr =
+        dynamic_cast<flwor_expr*>(pop_nodestack());
 
       // let ... return ...
-      flworExpr->set_return_expr( wrap_in_atomization(icExpr.getp()) );
+      flworExpr->set_return_expr( wrap_in_atomization(icExpr) );
 
       body = flworExpr;
     }
@@ -5094,76 +5123,76 @@
 
       //////  Get data from stack
       // $x/@id
-      expr_t uniKeyExpr = pop_nodestack();
+      expr* uniKeyExpr = pop_nodestack();
 
       // flwor result expr
-      flwor_expr_t flworExpr =
-        dynamic_cast<flwor_expr*>(pop_nodestack().getp());
+      flwor_expr* flworExpr =
+        dynamic_cast<flwor_expr*>(pop_nodestack());
 
       // flwor implementing every
-      flwor_expr_t evFlworExpr =
-        dynamic_cast<flwor_expr*>(pop_nodestack().getp());
+      flwor_expr* evFlworExpr =
+        dynamic_cast<flwor_expr*>(pop_nodestack());
 
 
       ////// Set latest details
 
       //fn:data( userExpr )
-      expr_t atomizedUniKeyExpr = wrap_in_atomization(uniKeyExpr.getp());
+      expr* atomizedUniKeyExpr = wrap_in_atomization(uniKeyExpr);
 
       // exists( $x/@id )
-      expr_t existsExpr = new fo_expr(theRootSctx, loc,
+      expr* existsExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                       GET_BUILTIN_FUNCTION(FN_EXISTS_1),
-                                      uniKeyExpr.getp());
+                                      uniKeyExpr);
 
 #if 0
       zstring commentStr("#trace fnExists");
-      expr_t comentExpr = new const_expr(theRootSctx, loc, commentStr);
-      fo_expr_t fnTraceExpr = new fo_expr(theRootSctx,
+      expr* comentExpr = theExprManager->create_const_expr(theRootSctx, loc, commentStr);
+      fo_expr* fnTraceExpr = theExprManager->create_fo_expr(theRootSctx,
                                          loc,
                                          GET_BUILTIN_FUNCTION(FN_TRACE_2),
-                                         existsExpr.getp(), comentExpr.getp());
+                                         existsExpr, comentExpr);
 #endif
 
 
       // every ... satisfies evTestExpr
-      fo_expr_t fnNotExpr = new fo_expr(theRootSctx,
+      fo_expr* fnNotExpr = theExprManager->create_fo_expr(theRootSctx,
                                         loc,
                                         GET_BUILTIN_FUNCTION(FN_NOT_1),
                                         existsExpr);
 
-      evFlworExpr->add_where(fnNotExpr.getp());
+      evFlworExpr->add_where(fnNotExpr);
 
-      fo_expr_t everyExpr = new fo_expr(theRootSctx,
+      fo_expr* everyExpr = theExprManager->create_fo_expr(theRootSctx,
                                         loc,
                                         GET_BUILTIN_FUNCTION(FN_EMPTY_1),
-                                        evFlworExpr.getp());
+                                        evFlworExpr);
 
       // functx:are-distinct-values( $x/@id )
       // implemented as count(distinct-values($seq)) = count($seq)
       //distinct-values($seq)
-      fo_expr_t distinctValuesExpr = new fo_expr(theRootSctx, loc,
+      fo_expr* distinctValuesExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                  GET_BUILTIN_FUNCTION(FN_DISTINCT_VALUES_1),
-                                                 atomizedUniKeyExpr.getp());
+                                                 atomizedUniKeyExpr);
 
       // count($sec)
-      fo_expr_t countSecExpr = new fo_expr(theRootSctx, loc,
+      fo_expr* countSecExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                            GET_BUILTIN_FUNCTION(FN_COUNT_1),
-                                           atomizedUniKeyExpr.getp());
+                                           atomizedUniKeyExpr);
       // count(distinct-values($sec))
-      fo_expr_t countDVExpr = new fo_expr(theRootSctx, loc,
+      fo_expr* countDVExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                           GET_BUILTIN_FUNCTION(FN_COUNT_1),
-                                          distinctValuesExpr.getp());
+                                          distinctValuesExpr);
 
       // countDV = countSec
-      fo_expr_t equalExpr = new fo_expr(theRootSctx, loc,
+      fo_expr* equalExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                         GET_BUILTIN_FUNCTION(OP_EQUAL_2),
-                                        countDVExpr.getp(), countSecExpr.getp());
+                                        countDVExpr, countSecExpr);
       // (...) and (...)
-      fo_expr_t andExpr = new fo_expr(theRootSctx, loc,
+      fo_expr* andExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                       GET_BUILTIN_FUNCTION(OP_AND_N),
-                                      everyExpr.getp(), equalExpr.getp());
+                                      everyExpr, equalExpr);
 
-      flworExpr->set_return_expr(andExpr.getp());
+      flworExpr->set_return_expr(andExpr);
 
       body = flworExpr;
     }
@@ -5188,26 +5217,26 @@
 
       //////  Get data from stack
       // $x/sale gt 0
-      expr_t evTestExpr = wrap_in_atomization(pop_nodestack());
+      expr* evTestExpr = wrap_in_atomization(pop_nodestack());
 
       // flwor expr
-      flwor_expr_t evFlworExpr =
-        dynamic_cast<flwor_expr*>(pop_nodestack().getp());
+      flwor_expr* evFlworExpr =
+        dynamic_cast<flwor_expr*>(pop_nodestack());
 
       // fn:not
-      fo_expr_t fnNotExpr = new fo_expr(theRootSctx,
+      fo_expr* fnNotExpr = theExprManager->create_fo_expr(theRootSctx,
                                         loc,
                                         GET_BUILTIN_FUNCTION(FN_NOT_1),
-                                        evTestExpr.getp());
+                                        evTestExpr);
 
       // where not( exists($x/sale gt 0) )
-      evFlworExpr->add_where(fnNotExpr.getp());
+      evFlworExpr->add_where(fnNotExpr);
 
       // fn:empty
-      fo_expr_t emptyExpr = new fo_expr(theRootSctx,
+      fo_expr* emptyExpr = theExprManager->create_fo_expr(theRootSctx,
                                         loc,
                                         GET_BUILTIN_FUNCTION(FN_EMPTY_1),
-                                        evFlworExpr.getp());
+                                        evFlworExpr);
 
       body = emptyExpr;
     }
@@ -5217,48 +5246,48 @@
     {
       //////  Get data from stack
       // $y/id
-      expr_t toKeyExpr = wrap_in_atomization(pop_nodestack());
+      expr* toKeyExpr = wrap_in_atomization(pop_nodestack());
 
       // $x//sale/empid
-      expr_t fromKeyExpr = wrap_in_atomization(pop_nodestack());
+      expr* fromKeyExpr = wrap_in_atomization(pop_nodestack());
 
       // result expr
-      flwor_expr_t evFlworExpr = dynamic_cast<flwor_expr*>(pop_nodestack().getp());
+      flwor_expr* evFlworExpr = dynamic_cast<flwor_expr*>(pop_nodestack());
 
       // some flwor expr
-      flwor_expr_t someFlworExpr = dynamic_cast<flwor_expr*>(pop_nodestack().getp());
+      flwor_expr* someFlworExpr = dynamic_cast<flwor_expr*>(pop_nodestack());
 
 
       // maybe add fn:data ?
       // $y/id eq $x//sale/empid
-      fo_expr_t eqExpr = new fo_expr(theRootSctx,
+      fo_expr* eqExpr = theExprManager->create_fo_expr(theRootSctx,
                                      loc,
                                      GET_BUILTIN_FUNCTION(OP_VALUE_EQUAL_2),
-                                     toKeyExpr.getp(),
-                                     fromKeyExpr.getp());
+                                     toKeyExpr,
+                                     fromKeyExpr);
       normalize_fo(eqExpr);
 
-      expr_t someTestExpr = eqExpr.getp();
-      someTestExpr = wrap_in_bev(someTestExpr.getp());
-      someFlworExpr->add_where(someTestExpr.getp());
+      expr* someTestExpr = eqExpr;
+      someTestExpr = wrap_in_bev(someTestExpr);
+      someFlworExpr->add_where(someTestExpr);
 
       // fn:exists
-      fo_expr_t fnExistsExpr = new fo_expr(theRootSctx, loc,
+      fo_expr* fnExistsExpr = theExprManager->create_fo_expr(theRootSctx, loc,
                                            GET_BUILTIN_FUNCTION(FN_EXISTS_1),
-                                           someFlworExpr.getp());
+                                           someFlworExpr);
       // fn:not()
-      fo_expr_t evFnNotExpr = new fo_expr(theRootSctx,
+      fo_expr* evFnNotExpr = theExprManager->create_fo_expr(theRootSctx,
                                           loc,
                                           GET_BUILTIN_FUNCTION(FN_NOT_1),
-                                          fnExistsExpr.getp());
+                                          fnExistsExpr);
 
-      evFlworExpr->add_where(evFnNotExpr.getp());
+      evFlworExpr->add_where(evFnNotExpr);
 
       // fn:empty
-      fo_expr_t fnEmptyExpr = new fo_expr(theRootSctx,
+      fo_expr* fnEmptyExpr = theExprManager->create_fo_expr(theRootSctx,
                                         loc,
                                         GET_BUILTIN_FUNCTION(FN_EMPTY_1),
-                                        evFlworExpr.getp());
+                                        evFlworExpr);
 
 
       body = fnEmptyExpr;
@@ -5276,7 +5305,7 @@
     qname->get_localname();
 
   if (theCCB->theConfig.optimize_cb != NULL)
-    theCCB->theConfig.optimize_cb(body.getp(), msg.str());
+    theCCB->theConfig.optimize_cb(body, msg.str());
 
   ulong nextVarId = 1;
   PlanIter_t icIter = codegen("integrity constraint", body, theCCB, nextVarId);
@@ -5359,7 +5388,7 @@
 {
   TRACE_VISIT_OUT();
 
-  expr_t program = pop_nodestack();
+  expr* program = pop_nodestack();
 
   // Mark the program as non-sequential if the only reason it is marked sequential
   // is because it contains exit exprs.
@@ -5377,7 +5406,7 @@
 
   if (program->is_updating() && !theCCB->theIsEval)
   {
-    program = new apply_expr(theRootSctx,
+    program = theExprManager->create_apply_expr(theRootSctx,
                              program->get_loc(),
                              program,
                              false); // don't discard XDM
@@ -5467,11 +5496,11 @@
   bool inEval = theCCB->theIsEval;
   bool allowLastUpdating = false;
 
-  std::vector<expr_t> stmts;
+  std::vector<expr*> stmts;
 
   // push a dummy block_expr in the node stack so that local var decls can
   // assert that their parent is a block expr.
-  expr_t dummyBlock = new block_expr(theRootSctx, loc, false, stmts, NULL);
+  expr* dummyBlock = theExprManager->create_block_expr(theRootSctx, loc, false, stmts, NULL);
   push_nodestack(dummyBlock);
 
   push_scope();
@@ -5489,8 +5518,8 @@
 
     if (dynamic_cast<const VarDecl*>(v[i]) != NULL)
     {
-      expr_t val = pop_nodestack();
-      var_expr_t ve = pop_nodestack().cast<var_expr>();
+      expr* val = pop_nodestack();
+      var_expr* ve = static_cast<var_expr*>(pop_nodestack());
 
       GlobalBinding b(ve, val, false);
 
@@ -5500,7 +5529,7 @@
     }
     else
     {
-      expr_t childExpr = pop_nodestack();
+      expr* childExpr = pop_nodestack();
 
       // If the last child is an updating expr
       if (topLevel && i == numExprs - 1 && childExpr->is_updating())
@@ -5511,7 +5540,7 @@
         }
         else
         {
-          childExpr = new apply_expr(theRootSctx, loc, childExpr, false);
+          childExpr = theExprManager->create_apply_expr(theRootSctx, loc, childExpr, false);
         }
       }
 
@@ -5542,7 +5571,7 @@
   std::vector<var_expr*>& prevAssignedVars = theAssignedVars[numScopes-1];
   std::vector<var_expr*>& lastAssignedVars = theAssignedVars[numScopes];
 
-  expr_t blockExpr = new block_expr(theRootSctx,
+  expr* blockExpr = theExprManager->create_block_expr(theRootSctx,
                                     loc,
                                     allowLastUpdating,
                                     stmts,
@@ -5605,7 +5634,7 @@
 {
   TRACE_VISIT_OUT();
 
-  var_expr_t ve = lookup_var(v.get_name(), loc, err::XPST0008);
+  var_expr* ve = lookup_var(v.get_name(), loc, err::XPST0008);
 
   if ((ve->get_kind() != var_expr::local_var &&
        ve->get_kind() != var_expr::prolog_var) ||
@@ -5617,18 +5646,18 @@
 
   xqtref_t varType = ve->get_type();
 
-  expr_t valueExpr = pop_nodestack();
+  expr* valueExpr = pop_nodestack();
 
   if (varType != NULL)
-    valueExpr = new treat_expr(theRootSctx,
-                               loc,
-                               valueExpr,
-                               varType,
-                               TreatIterator::TYPE_MATCH);
-
-  push_nodestack(new var_set_expr(theRootSctx, loc, ve, valueExpr));
-
-  theAssignedVars.back().push_back(ve.getp());
+    valueExpr = theExprManager->create_treat_expr(theRootSctx,
+                                                  loc,
+                                                  valueExpr,
+                                                  varType,
+                                                  TreatIterator::TYPE_MATCH);
+
+  push_nodestack(theExprManager->create_var_set_expr(theRootSctx, loc, ve, valueExpr));
+
+  theAssignedVars.back().push_back(ve);
 }
 
 
@@ -5644,9 +5673,9 @@
 
 void end_visit(const ApplyExpr& v, void* visit_state)
 {
-  expr_t param = pop_nodestack();
+  expr* param = pop_nodestack();
 
-  push_nodestack(new apply_expr(theRootSctx,
+  push_nodestack(theExprManager->create_apply_expr(theRootSctx,
                                 param->get_loc(),
                                 param,
                                 true)); // discard XDM
@@ -5670,7 +5699,7 @@
 {
   TRACE_VISIT_OUT();
 
-  expr_t childExpr = pop_nodestack();
+  expr* childExpr = pop_nodestack();
 
   if (childExpr->is_updating())
   {
@@ -5678,7 +5707,7 @@
 
     if (!inUDFBody() && !theCCB->theIsEval)
     {
-      childExpr = new apply_expr(theRootSctx, loc, childExpr, false);
+      childExpr = theExprManager->create_apply_expr(theRootSctx, loc, childExpr, false);
     }
   }
   else if (childExpr->is_sequential())
@@ -5686,7 +5715,7 @@
     theHaveSequentialExitExprs = true;
   }
 
-  expr_t exitExpr = new exit_expr(theRootSctx, loc, childExpr);
+  expr* exitExpr = theExprManager->create_exit_expr(theRootSctx, loc, childExpr);
 
   if (inUDFBody())
   {
@@ -5695,7 +5724,7 @@
     user_function* udf = static_cast<user_function*>(f);
 
     udf->setExiting(true);
-    theExitExprs.push_back(exitExpr.getp());
+    theExitExprs.push_back(exitExpr);
   }
 
   push_nodestack(exitExpr);
@@ -5719,25 +5748,25 @@
 {
   TRACE_VISIT_OUT();
 
-  expr_t bodyExpr = pop_nodestack();
-  expr_t condExpr = pop_nodestack();
+  expr* bodyExpr = pop_nodestack();
+  expr* condExpr = pop_nodestack();
 
-  condExpr = new if_expr(theRootSctx,
+  condExpr = theExprManager->create_if_expr(theRootSctx,
                          loc,
                          condExpr,
                          create_empty_seq(loc),
-                         new flowctl_expr(theRootSctx, loc, flowctl_expr::BREAK));
+                         theExprManager->create_flowctl_expr(theRootSctx, loc, flowctl_expr::BREAK));
 
   block_expr* seqBody = NULL;
 
-  std::vector<expr_t> stmts;
+  std::vector<expr*> stmts;
 
   stmts.push_back(condExpr);
   stmts.push_back(bodyExpr);
 
-  seqBody = new block_expr(bodyExpr->get_sctx(), loc, false, stmts, NULL);
+  seqBody = theExprManager->create_block_expr(bodyExpr->get_sctx(), loc, false, stmts, NULL);
 
-  push_nodestack(new while_expr(theRootSctx, loc, seqBody));
+  push_nodestack(theExprManager->create_while_expr(theRootSctx, loc, seqBody));
 
   theInWhileStack.pop();
 }
@@ -5783,7 +5812,7 @@
     ZORBA_FATAL(false, "");
   }
 
-  push_nodestack(new flowctl_expr(theRootSctx, loc, a));
+  push_nodestack(theExprManager->create_flowctl_expr(theRootSctx, loc, a));
 }
 
 
@@ -5806,21 +5835,21 @@
 
   assert(v.numberOfChildren() > 1);
 
-  std::vector<expr_t> args;
+  std::vector<expr*> args;
 
   for (int i = 0; i < v.numberOfChildren(); ++i)
   {
-    expr_t e = pop_nodestack();
+    expr* e = pop_nodestack();
     args.push_back(e);
   }
 
-  fo_expr_t concatExpr = new fo_expr(theRootSctx,
-                                  loc,
-                                  op_concatenate,
-                                  args);
-  normalize_fo(concatExpr.getp());
+  fo_expr* concatExpr = theExprManager->create_fo_expr(theRootSctx,
+                                                        loc,
+                                                        op_concatenate,
+                                                        args);
+  normalize_fo(concatExpr);
 
-  push_nodestack(concatExpr.getp());
+  push_nodestack(concatExpr);
 }
 
 
@@ -5901,9 +5930,9 @@
     ERROR_PARAMS(ZED(XPST0003_XQueryVersionAtLeast30_2), theSctx->xquery_version()));
   }
 
-  rchandle<flwor_expr> flwor = new flwor_expr(theRootSctx, loc, v.is_general());
+  flwor_expr* flwor = theExprManager->create_flwor_expr(theRootSctx, loc, v.is_general());
 
-  expr_t retExpr = pop_nodestack();
+  expr* retExpr = pop_nodestack();
 
   wrap_in_debugger_expr(retExpr, retExpr->get_loc());
 
@@ -5961,7 +5990,7 @@
 
   theFlworClausesStack.resize(curClausePos);
 
-  push_nodestack(flwor.getp());
+  push_nodestack(flwor);
 }
 
 
@@ -6051,7 +6080,7 @@
 {
   TRACE_VISIT_OUT();
 
-  expr_t domainExpr = pop_nodestack();
+  expr* domainExpr = pop_nodestack();
 
   if (domainExpr->is_updating())
     throw XQUERY_EXCEPTION(err::XUST0001, ERROR_LOC(loc));
@@ -6059,7 +6088,7 @@
   // it's important to insert the debugger before the scope is pushed.
   // Otherwise, the variable in question would already be in scope for
   // the debugger but no value would be bound
-  QueryLoc lExpandedLocation = 
+  QueryLoc lExpandedLocation =
   expandQueryLoc(v.get_var_name()->get_location(), domainExpr->get_loc());
 
   wrap_in_debugger_expr(domainExpr, lExpandedLocation);
@@ -6068,8 +6097,8 @@
 
   xqtref_t type = (v.get_var_type() == NULL ? NULL : pop_tstack());
 
-  var_expr_t varExpr = bind_var(loc, v.get_var_name(), var_expr::for_var, type);
-  var_expr_t posVarExpr;
+  var_expr* varExpr = bind_var(loc, v.get_var_name(), var_expr::for_var, type);
+  var_expr* posVarExpr = NULL;
 
   const PositionalVar* pv = v.get_posvar();
 
@@ -6085,6 +6114,7 @@
   }
 
   for_clause* fc = new for_clause(theRootSctx,
+                                  theCCB,
                                   loc,
                                   varExpr,
                                   domainExpr,
@@ -6154,7 +6184,7 @@
 void create_let_clause(
     const QueryLoc loc,
     const QName* varName,
-    expr_t domainExpr,
+    expr* domainExpr,
     xqtref_t type)
 {
   if (domainExpr->is_updating())
@@ -6170,9 +6200,10 @@
 
   push_scope();
 
-  var_expr_t varExpr = bind_var(loc, varName, var_expr::let_var, type);
+  var_expr* varExpr = bind_var(loc, varName, var_expr::let_var, type);
 
   let_clause* clause = new let_clause(theRootSctx,
+                                      theCCB,
                                       loc,
                                       varExpr,
                                       domainExpr);
@@ -6189,14 +6220,14 @@
 
   if (v.get_kind() == VarGetsDecl::let_var)
   {
-    expr_t domainExpr = pop_nodestack();
+    expr* domainExpr = pop_nodestack();
 
     create_let_clause(loc, v.get_var_name(), domainExpr, type);
   }
   else
   {
     push_scope();
-    push_nodestack(create_var(loc, v.get_var_name(), var_expr::let_var, type).getp());
+    push_nodestack(create_var(loc, v.get_var_name(), var_expr::let_var, type));
   }
 }
 
@@ -6230,13 +6261,14 @@
   // translating the window conditions and the window var.
 
   // Pop the window the domain expr.
-  expr_t windowDomainExpr = pop_nodestack();
+  expr* windowDomainExpr = pop_nodestack();
 
   window_clause::window_t winKind = (v.get_wintype() == WindowClause::tumbling_window ?
                                      window_clause::tumbling_window :
                                      window_clause::sliding_window);
 
   window_clause* clause = new window_clause(theRootSctx,
+                                            theCCB,
                                             v.get_location(),
                                             winKind,
                                             NULL,
@@ -6258,12 +6290,11 @@
 {
   TRACE_VISIT_OUT();
 
-  window_clause* windowClause = dynamic_cast<window_clause*>(
-                                theFlworClausesStack.back().getp());
+  window_clause* windowClause = theFlworClausesStack.back().dyn_cast<window_clause>();
   assert(windowClause != NULL);
 
   // Pop the window var and associate it with this window clause
-  var_expr_t windowVarExpr = pop_nodestack_var();
+  var_expr* windowVarExpr = pop_nodestack_var();
   windowVarExpr->set_flwor_clause(windowClause);
 
   // Create var_exprs for output window-condition vars, associate them with this
@@ -6304,12 +6335,13 @@
     rchandle<FLWORWinCond> cond = v[i];
     if (cond != NULL)
     {
-      expr_t condExpr = pop_nodestack();
+      expr* condExpr = pop_nodestack();
 
       rchandle<WindowVars> vars = cond->get_winvars();
       pop_wincond_vars(vars, inputCondVarExprs[i]);
 
-      conds[i] = new flwor_wincond(theSctx,
+      conds[i] = new flwor_wincond(theCCB,
+                                   theSctx,
                                    cond->is_only(),
                                    inputCondVarExprs[i],
                                    outputCondVarExprs[i],
@@ -6336,10 +6368,10 @@
                                       var_expr::wincond_in_pos_var :
                                       var_expr::wincond_out_pos_var);
 
-  var_expr_t posVarExpr;
-  var_expr_t curVarExpr;
-  var_expr_t nextVarExpr;
-  var_expr_t prevVarExpr;
+  var_expr* posVarExpr = NULL;
+  var_expr* curVarExpr = NULL;
+  var_expr* nextVarExpr = NULL;
+  var_expr* prevVarExpr = NULL;
 
   rchandle<PositionalVar> pv = v.get_posvar();
   if (pv != NULL)
@@ -6347,7 +6379,7 @@
     posVarExpr = bind_var(pv->get_location(), pv->get_name(), pvarKind);
 
     posVarExpr->set_flwor_clause(windowClause);
-    push_nodestack(posVarExpr.getp());
+    push_nodestack(posVarExpr);
   }
 
   if (v.get_curr())
@@ -6355,7 +6387,7 @@
     curVarExpr = bind_var(loc, v.get_curr(), varKind);
 
     curVarExpr->set_flwor_clause(windowClause);
-    push_nodestack(curVarExpr.getp());
+    push_nodestack(curVarExpr);
   }
 
   if (v.get_prev())
@@ -6363,7 +6395,7 @@
     prevVarExpr = bind_var(loc, v.get_prev(), varKind);
 
     prevVarExpr->set_flwor_clause(windowClause);
-    push_nodestack(prevVarExpr.getp());
+    push_nodestack(prevVarExpr);
   }
 
   if (v.get_next())
@@ -6371,7 +6403,7 @@
     nextVarExpr = bind_var(loc, v.get_next(), varKind);
 
     nextVarExpr->set_flwor_clause(windowClause);
-    push_nodestack(nextVarExpr.getp());
+    push_nodestack(nextVarExpr);
   }
 }
 
@@ -6396,6 +6428,36 @@
 
 
 /*******************************************************************************
+<<<<<<< TREE
+=======
+  WindowVarDecl ::= "$" VarName TypeDeclaration? "in"  ExprSingle
+********************************************************************************/
+void* begin_visit(const WindowVarDecl& v)
+{
+  TRACE_VISIT();
+
+  // Done with input window condition vars.
+  pop_scope();
+
+  return no_state;
+}
+
+void end_visit(const WindowVarDecl& v, void* /*visit_state*/)
+{
+  TRACE_VISIT_OUT();
+
+  // Create scope for the window var
+  push_scope();
+
+  xqtref_t type = (v.get_var_type() == NULL ? NULL : pop_tstack());
+
+  var_expr* ve = bind_var(loc, v.get_var_name(), var_expr::win_var, type);
+  push_nodestack(ve);
+}
+
+
+/*******************************************************************************
+>>>>>>> MERGE-SOURCE
   WindowStartCondition ::= "start" WindowVars "when" ExprSingle
 
   WindowEndCondition ::= "only"? "end" WindowVars "when" ExprSingle
@@ -6488,7 +6550,7 @@
   for (csize i = 0; i < lList->size(); ++i)
   {
     GroupSpec* spec = (*lList)[i];
-    
+
     const QName* varname = spec->get_var_name();
 
     const var_expr* ve = NULL;
@@ -6524,8 +6586,8 @@
   {
     push_nodestack(const_cast<var_expr *>(*i));
 
-    var_expr_t ve = create_var(loc, (*i)->get_name(), var_expr::non_groupby_var);
-    push_nodestack(ve.getp());
+    var_expr* ve = create_var(loc, (*i)->get_name(), var_expr::non_groupby_var);
+    push_nodestack(ve);
   }
 
   return no_state;
@@ -6570,7 +6632,7 @@
 
         if (groupSpec.get_collation_spec() != NULL &&
             prevSpec.get_collation_spec() != NULL &&
-            groupSpec.get_collation_spec()->get_uri() == 
+            groupSpec.get_collation_spec()->get_uri() ==
             prevSpec.get_collation_spec()->get_uri())
           break;
       }
@@ -6585,6 +6647,7 @@
       store::Item_t varName;
       expand_no_default_qname(varName, groupSpec.get_var_name(), loc);
 
+<<<<<<< TREE
       VarInfo* var = sctx->lookup_var(varName.getp());
 
       if (!var)
@@ -6594,22 +6657,33 @@
       }
 
       expr_t inputExpr = var->getVar();
+=======
+      VarInfo* var = sctx->lookup_var(varName.getp());
+
+      if (!var)
+      {
+        RAISE_ERROR(err::XPST0008, loc,
+        ERROR_PARAMS(varName->getStringValue(), ZED(VariabledUndeclared)));
+      }
+
+      expr* inputExpr = var->getVar();
+>>>>>>> MERGE-SOURCE
 
       if (inputExpr->get_expr_kind() == var_expr_kind)
       {
-        inputExpr = new wrapper_expr(theRootSctx, loc, inputExpr);
+        inputExpr = theExprManager->create_wrapper_expr(theRootSctx, loc, inputExpr);
       }
 
       inputExpr = wrap_in_atomization(inputExpr);
 
       push_scope();
 
-      var_expr_t gvar = bind_var(loc,
+      var_expr* gvar = bind_var(loc,
                                  groupSpec.get_var_name(),
                                  var_expr::groupby_var,
                                  inputExpr->get_return_type());
 
-      grouping_rebind.push_back(std::pair<expr_t, var_expr_t>(inputExpr, gvar));
+      grouping_rebind.push_back(std::pair<expr*, var_expr*>(inputExpr, gvar));
 
       if (groupSpec.get_collation_spec() != NULL)
       {
@@ -6629,17 +6703,18 @@
 
   push_scope();
 
-  var_expr_t ngvar;
+  var_expr* ngvar = NULL;
 
   while (NULL != (ngvar = pop_nodestack_var()))
   {
-    var_expr_t inputVar = pop_nodestack_var();
+    var_expr* inputVar = pop_nodestack_var();
 
     bind_var(ngvar, theSctx);
 
-    expr_t inputExpr = new wrapper_expr(theRootSctx, loc, inputVar.getp());
+    expr* inputExpr =
+    theExprManager->create_wrapper_expr(theRootSctx, loc, inputVar);
 
-    nongrouping_rebind.push_back(std::pair<expr_t, var_expr_t>(inputExpr, ngvar));
+    nongrouping_rebind.push_back(std::pair<expr*, var_expr*>(inputExpr, ngvar));
   }
 
   group_clause* clause = new group_clause(theRootSctx,
@@ -6683,11 +6758,11 @@
 
   if (v.get_binding_expr() != NULL)
   {
-    expr_t domainExpr = pop_nodestack();
+    expr* domainExpr = pop_nodestack();
 
     if (v.get_var_type() != NULL)
       type = pop_tstack();
-    
+
     create_let_clause(loc, v.get_var_name(), domainExpr, type);
   }
 }
@@ -6726,7 +6801,7 @@
   csize numOrderSpecs = orderSpecs.size();
 
   std::vector<OrderModifier> modifiers(numOrderSpecs);
-  std::vector<expr_t> orderExprs(numOrderSpecs);
+  std::vector<expr*> orderExprs(numOrderSpecs);
 
   for (int i = numOrderSpecs - 1; i >= 0; --i)
   {
@@ -6751,7 +6826,7 @@
         RAISE_ERROR(err::XQST0076, loc, ERROR_PARAMS(collationUri));
     }
 
-    expr_t orderExpr = pop_nodestack();
+    expr* orderExpr = pop_nodestack();
 
     if (orderExpr->is_updating())
       throw XQUERY_EXCEPTION(err::XUST0001, ERROR_LOC(loc));
@@ -6872,7 +6947,7 @@
 {
   TRACE_VISIT_OUT ();
 
-  expr_t whereExpr = pop_nodestack();
+  expr* whereExpr = pop_nodestack();
 
   if (whereExpr->is_updating())
     throw XQUERY_EXCEPTION(err::XUST0001, ERROR_LOC(loc));
@@ -6906,7 +6981,7 @@
 {
   TRACE_VISIT_OUT();
 
-  var_expr_t varExpr = bind_var(loc, v.get_varname(), var_expr::count_var, NULL);
+  var_expr* varExpr = bind_var(loc, v.get_varname(), var_expr::count_var, NULL);
 
   count_clause* clause = new count_clause(theRootSctx,
                                           loc,
@@ -6966,15 +7041,15 @@
 
   v.get_switch_expr()->accept(*this);
 
-  expr_t se = pop_nodestack();
+  expr* se = pop_nodestack();
 
   se = wrap_in_atomization(se);
 
   // atomizedFlwor = [let $atomv := data(E) return NULL]
-  var_expr_t atomv = create_temp_var(v.get_switch_expr()->get_location(),
+  var_expr* atomv = create_temp_var(v.get_switch_expr()->get_location(),
                                      var_expr::let_var);
 
-  expr_t atomizedFlwor = wrap_in_let_flwor(se, atomv, NULL);
+  expr* atomizedFlwor = wrap_in_let_flwor(se, atomv, NULL);
 
   // TODO: cast as xs:string should not really be necessary
   // atomizedFlwor =
@@ -6985,26 +7060,26 @@
   //          then $atomv cast as xs:string
   //          else $atomv
   //     return NULL]
-  static_cast<flwor_expr*>(atomizedFlwor.getp())->set_return_expr(
-    new if_expr(theRootSctx,
+  static_cast<flwor_expr*>(atomizedFlwor)->set_return_expr(
+    theExprManager->create_if_expr(theRootSctx,
                 loc,
-                new instanceof_expr(theRootSctx,
+                theExprManager->create_instanceof_expr(theRootSctx,
                                     loc,
-                                    atomv.getp(),
+                                    atomv,
                                     theRTM.UNTYPED_ATOMIC_TYPE_ONE),
-                new cast_expr(theRootSctx,
+                theExprManager->create_cast_expr(theRootSctx,
                               loc,
-                              atomv.getp(),
+                              atomv,
                               theRTM.STRING_TYPE_ONE),
-                atomv.getp()));
+                atomv));
 
   // flworExpr = [let $sv := atomizedFlwor return NULL]
-  var_expr_t sv = create_temp_var(v.get_switch_expr()->get_location(), var_expr::let_var);
-  expr_t flworExpr = wrap_in_let_flwor(atomizedFlwor, sv, NULL);
+  var_expr* sv = 

Follow ups