← Back to team overview

zorba-coders team mailing list archive

[Merge] lp:~zorba-coders/zorba/markos-scratch into lp:zorba

 

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

Commit message:
Associated expressions with UDFs

Requested reviews:
  Markos Zaharioudakis (markos-za)

For more details, see:
https://code.launchpad.net/~zorba-coders/zorba/markos-scratch/+merge/128675

Associated expressions with UDFs
-- 
https://code.launchpad.net/~zorba-coders/zorba/markos-scratch/+merge/128675
Your team Zorba Coders is subscribed to branch lp:zorba.
=== modified file 'src/compiler/expression/CMakeLists.txt'
--- src/compiler/expression/CMakeLists.txt	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/CMakeLists.txt	2012-10-09 10:29:25 +0000
@@ -14,6 +14,7 @@
 SET(EXPRESSION_SRCS
     expr_consts.cpp
     expr_base.cpp
+    expr_clone.cpp
     expr_iter.cpp
     expr_type.cpp
     expr.cpp

=== modified file 'src/compiler/expression/expr.cpp'
--- src/compiler/expression/expr.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/expr.cpp	2012-10-09 10:29:25 +0000
@@ -83,22 +83,19 @@
 DEF_EXPR_ACCEPT (pi_expr)
 
 
-#define CLONE( e, s ) ((e) == NULL ? NULL : (e)->clone(s))
-
-
-
 /*******************************************************************************
   [68] IfExpr ::= "if" "(" Expr ")" "then" ExprSingle "else" ExprSingle
 ********************************************************************************/
 if_expr::if_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* condExpr,
     expr* thenExpr,
     expr* elseExpr)
   :
-  expr(ccb, sctx, loc, if_expr_kind),
+  expr(ccb, sctx, udf, loc, if_expr_kind),
   theThenExpr(thenExpr),
   theElseExpr(elseExpr)
 {
@@ -108,10 +105,13 @@
                          *GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE,
                          loc))
   {
-    fo_expr* boolExpr = theCCB->theEM->create_fo_expr(sctx,
-                                    loc,
-                                    GET_BUILTIN_FUNCTION(FN_BOOLEAN_1),
-                                    condExpr);
+    fo_expr* boolExpr = theCCB->theEM->
+    create_fo_expr(sctx,
+                   udf,
+                   loc,
+                   GET_BUILTIN_FUNCTION(FN_BOOLEAN_1),
+                   condExpr);
+
     condExpr = boolExpr;
   }
 
@@ -166,27 +166,18 @@
 }
 
 
-expr* if_expr::cloneImpl(substitution_t& subst) const 
-{
-  return theCCB->theEM->create_if_expr(theSctx,
-                     get_loc(),
-                     get_cond_expr()->clone(subst),
-                     get_then_expr()->clone(subst),
-                     get_else_expr()->clone(subst));
-}
-
-
 /***************************************************************************//**
 
 ********************************************************************************/
 order_expr::order_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     order_type_t type,
     expr* inExpr)
   :
-  expr(ccb, sctx, loc, order_expr_kind),
+  expr(ccb, sctx, udf, loc, order_expr_kind),
   theType(type),
   theExpr(inExpr)
 {
@@ -203,25 +194,20 @@
 }
 
 
-expr* order_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_order_expr(theSctx, get_loc(), get_type(), get_expr()->clone(subst));
-}
-
-
 /***************************************************************************//**
 
 ********************************************************************************/
 validate_expr::validate_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     enum ParseConstants::validation_mode_t mode,
     const store::Item_t& typeName,
     expr* inExpr,
     rchandle<TypeManager> typemgr)
   :
-  expr(ccb, sctx, loc, validate_expr_kind),
+  expr(ccb, sctx, udf, loc, validate_expr_kind),
   theMode(mode),
   theTypeName(typeName),
   theTypeMgr(typemgr),
@@ -242,16 +228,6 @@
 }
 
 
-expr* validate_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_validate_expr(theSctx,
-                           get_loc(),
-                           get_valmode(),
-                           const_cast<store::Item*>(get_type_name()),
-                           get_expr()->clone(subst),
-                           get_typemgr());
-}
-
 
 /***************************************************************************//**
   Base for expression classes that require a namespace context
@@ -259,11 +235,12 @@
 namespace_context_base_expr::namespace_context_base_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr_kind_t kind,
     const namespace_context* aNSCtx)
   :
-  expr(ccb, sctx, loc, kind),
+  expr(ccb, sctx, udf, loc, kind),
   theNSCtx(const_cast<namespace_context*>(aNSCtx))
 {
 }
@@ -282,12 +259,13 @@
 cast_or_castable_base_expr::cast_or_castable_base_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr_kind_t kind,
     expr* input,
     const xqtref_t& type)
   :
-  expr(ccb, sctx, loc, kind),
+  expr(ccb, sctx, udf, loc, kind),
   theInputExpr(input),
   theTargetType(type)
 {
@@ -327,12 +305,13 @@
 cast_base_expr::cast_base_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr_kind_t kind,
     expr* input,
     const xqtref_t& type)
   :
-  cast_or_castable_base_expr(ccb, sctx, loc, kind, input, type)
+  cast_or_castable_base_expr(ccb, sctx, udf, loc, kind, input, type)
 {
   setNonDiscardable(ANNOTATION_TRUE_FIXED);
 }
@@ -346,11 +325,12 @@
 cast_expr::cast_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* inputExpr,
     const xqtref_t& type)
   :
-  cast_base_expr(ccb, sctx, loc, cast_expr_kind, inputExpr, type)
+  cast_base_expr(ccb, sctx, udf, loc, cast_expr_kind, inputExpr, type)
 {
   assert(type->get_quantifier() == TypeConstants::QUANT_ONE ||
          type->get_quantifier() == TypeConstants::QUANT_QUESTION);
@@ -363,21 +343,13 @@
 }
 
 
-expr* cast_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_cast_expr(theSctx,
-                       get_loc(),
-                       get_input()->clone(subst),
-                       get_target_type());
-}
-
-
 /***************************************************************************//**
   TreatExpr ::= CastableExpr ( "treat" "as" SequenceType )?
 ********************************************************************************/
 treat_expr::treat_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* inputExpr,
     const xqtref_t& type,
@@ -385,7 +357,7 @@
     bool check_prime,
     store::Item* qname)
   :
-  cast_base_expr(ccb, sctx, loc, treat_expr_kind, inputExpr, type),
+  cast_base_expr(ccb, sctx, udf, loc, treat_expr_kind, inputExpr, type),
   theErrorKind(err),
   theCheckPrime(check_prime),
   theQName(qname)
@@ -393,31 +365,20 @@
 }
 
 
-expr* treat_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_treat_expr(theSctx,
-                        get_loc(),
-                        get_input()->clone(subst),
-                        get_target_type(),
-                        get_err(),
-                        get_check_prime(),
-                        get_qname());
-}
-
-
 /***************************************************************************//**
 
 ********************************************************************************/
 promote_expr::promote_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* input,
     const xqtref_t& type,
     PromoteIterator::ErrorKind err,
     store::Item* qname)
   :
-  cast_base_expr(ccb, sctx, loc, promote_expr_kind, input, type),
+  cast_base_expr(ccb, sctx, udf, loc, promote_expr_kind, input, type),
   theErrorKind(err),
   theQName(qname)
 {
@@ -427,29 +388,19 @@
 }
 
 
-expr* promote_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_promote_expr(theSctx,
-                          get_loc(),
-                          get_input()->clone(subst),
-                          get_target_type(),
-                          theErrorKind,
-                          theQName.getp());
-}
-
-
 /***************************************************************************//**
   Base for castable, instanceof
 ********************************************************************************/
 castable_base_expr::castable_base_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr_kind_t kind,
     expr* input,
     const xqtref_t& type)
   :
-  cast_or_castable_base_expr(ccb, sctx, loc, kind, input, type)
+  cast_or_castable_base_expr(ccb, sctx, udf, loc, kind, input, type)
 {
 }
 
@@ -462,11 +413,12 @@
 castable_expr::castable_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* inputExpr,
     const xqtref_t& type)
   :
-  castable_base_expr (ccb, sctx, loc, castable_expr_kind, inputExpr, type)
+  castable_base_expr(ccb, sctx, udf, loc, castable_expr_kind, inputExpr, type)
 {
 }
 
@@ -477,53 +429,37 @@
 }
 
 
-expr* castable_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_castable_expr(theSctx,
-                           get_loc(),
-                           get_input()->clone(subst),
-                           get_target_type());
-}
-
-
 /***************************************************************************//**
   InstanceofExpr ::= TreatExpr ( "instance" "of" SequenceType )?
 ********************************************************************************/
 instanceof_expr::instanceof_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* inputExpr,
     const xqtref_t& type,
     bool checkPrimeOnly)
   :
-  castable_base_expr(ccb, sctx, loc, instanceof_expr_kind, inputExpr, type),
+  castable_base_expr(ccb, sctx, udf, loc, instanceof_expr_kind, inputExpr, type),
   theCheckPrimeOnly(checkPrimeOnly)
 {
 }
 
 
-expr* instanceof_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_instanceof_expr(theSctx,
-                             get_loc(),
-                             get_input()->clone(subst),
-                             get_target_type());
-}
-
-
 /***************************************************************************//**
 
 ********************************************************************************/
 name_cast_expr::name_cast_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* inputExpr,
     const namespace_context* aNSCtx,
     bool isAttrName)
   :
-  namespace_context_base_expr(ccb, sctx, loc, name_cast_expr_kind, aNSCtx),
+  namespace_context_base_expr(ccb, sctx, udf, loc, name_cast_expr_kind, aNSCtx),
   theInputExpr(inputExpr),
   theIsAttrName(isAttrName)
 {
@@ -542,27 +478,18 @@
 }
 
 
-expr* name_cast_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_name_cast_expr(theSctx,
-                            get_loc(),
-                            get_input()->clone(subst),
-                            getNSCtx(),
-                            theIsAttrName);
-}
-
-
 /***************************************************************************//**
   CompDocConstructor ::= "document" "{" Expr "}"
 ********************************************************************************/
 doc_expr::doc_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* aContent,
     bool copyNodes)
   :
-  expr(ccb, sctx, loc, doc_expr_kind),
+  expr(ccb, sctx, udf, loc, doc_expr_kind),
   theContent(aContent),
   theCopyInputNodes(copyNodes)
 {
@@ -581,22 +508,13 @@
 }
 
 
-expr* doc_expr::cloneImpl(substitution_t& subst) const
-{
-  doc_expr* clone = theCCB->theEM->create_doc_expr(theSctx,
-                                 get_loc(),
-                                 CLONE(getContent(), subst),
-                                 theCopyInputNodes);
-  return clone;
-}
-
-
 /***************************************************************************//**
 
 ********************************************************************************/
 elem_expr::elem_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& aLoc,
     expr* aQNameExpr,
     expr* attrs,
@@ -604,7 +522,7 @@
     const namespace_context* aNSCtx,
     bool copyNodes)
   :
-  namespace_context_base_expr(ccb, sctx, aLoc, elem_expr_kind, aNSCtx),
+  namespace_context_base_expr(ccb, sctx, udf, aLoc, elem_expr_kind, aNSCtx),
   theQNameExpr(aQNameExpr),
   theAttrs(attrs),
   theContent(content),
@@ -619,13 +537,14 @@
 elem_expr::elem_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& aLoc,
     expr* aQNameExpr,
     expr* content,
     const namespace_context* aNSCtx,
     bool copyNodes)
   :
-  namespace_context_base_expr(ccb, sctx, aLoc, elem_expr_kind, aNSCtx),
+  namespace_context_base_expr(ccb, sctx, udf, aLoc, elem_expr_kind, aNSCtx),
   theQNameExpr(aQNameExpr),
   theAttrs(0),
   theContent(content),
@@ -663,30 +582,18 @@
 }
 
 
-expr* elem_expr::cloneImpl(substitution_t& subst) const
-{
-  elem_expr* clone =  theCCB->theEM->create_elem_expr(theSctx,
-                                    get_loc(),
-                                    CLONE(getQNameExpr(), subst),
-                                    CLONE(getAttrs(), subst),
-                                    CLONE(getContent(), subst),
-                                    getNSCtx(),
-                                    theCopyInputNodes);
-  return clone;
-}
-
-
 /***************************************************************************//**
 
 ********************************************************************************/
 attr_expr::attr_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* aQNameExpr,
     expr* aValueExpr)
   :
-  expr(ccb, sctx, loc, attr_expr_kind),
+  expr(ccb, sctx, udf, loc, attr_expr_kind),
   theQNameExpr(aQNameExpr),
   theValueExpr(aValueExpr)
 {
@@ -730,15 +637,6 @@
 }
 
 
-expr* attr_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_attr_expr(theSctx,
-                       get_loc(),
-                       CLONE(getQNameExpr(), subst),
-                       CLONE(getValueExpr(), subst));
-}
-
-
 DEF_EXPR_ACCEPT(attr_expr)
 
 
@@ -748,11 +646,12 @@
 text_expr::text_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     text_constructor_type type_arg,
     expr* content)
   :
-  expr(ccb, sctx, loc, text_expr_kind),
+  expr(ccb, sctx, udf, loc, text_expr_kind),
   type(type_arg),
   theContentExpr(content)
 {
@@ -773,23 +672,18 @@
 }
 
 
-expr* text_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_text_expr(theSctx, get_loc(), get_type(), CLONE(get_text(), subst));
-}
-
-
 /***************************************************************************//**
 
 ********************************************************************************/
 pi_expr::pi_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* targetExpr,
     expr* contentExpr)
 :
-  expr(ccb, sctx, loc, pi_expr_kind),
+  expr(ccb, sctx, udf, loc, pi_expr_kind),
   theTargetExpr(targetExpr),
   theContentExpr(contentExpr)
 {
@@ -823,23 +717,18 @@
 }
 
 
-expr* pi_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_pi_expr(theSctx,
-                     get_loc(),
-                     CLONE(get_target_expr(), subst),
-                     CLONE(get_content_expr(), subst));
-}
-
-
-
 /*******************************************************************************
   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(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, expr* wrapped)
+wrapper_expr::wrapper_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc,
+    expr* wrapped)
   :
-  expr(ccb, sctx, loc, wrapper_expr_kind),
+  expr(ccb, sctx, udf, loc, wrapper_expr_kind),
   theWrappedExpr(wrapped)
 {
   compute_scripting_kind();
@@ -852,77 +741,89 @@
 }
 
 
-expr* wrapper_expr::cloneImpl(substitution_t& subst) const
-{
-  expr* e = theWrappedExpr->clone(subst);
-
-  if (theWrappedExpr->get_expr_kind() == var_expr_kind &&
-      e->get_expr_kind() != var_expr_kind)
-    return e;
-  else
-    return theCCB->theEM->create_wrapper_expr(theSctx, get_loc(), e);
-}
-
-
 /***************************************************************************//**
 
 ********************************************************************************/
-const_expr::const_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, zstring& v)
+const_expr::const_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc,
+    zstring& v)
   :
-  expr(ccb, sctx, loc, const_expr_kind)
+  expr(ccb, sctx, udf, 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)
+const_expr::const_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc,
+    const std::string& v)
+  :
+  expr(ccb, sctx, udf, loc, const_expr_kind)
+{
+  zstring tmp(v);
+  GENV_ITEMFACTORY->createString(theValue, tmp);
+  theScriptingKind = SIMPLE_EXPR;
+}
+
+
+const_expr::const_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc,
+    const char* v)
+  :
+  expr(ccb, sctx, udf, loc, const_expr_kind)
+{
+  zstring tmp(v);
+  GENV_ITEMFACTORY->createString(theValue, tmp);
+  theScriptingKind = SIMPLE_EXPR;
+}
+
+
+const_expr::const_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc,
+    xs_integer v)
+  :
+  expr(ccb, sctx, udf, loc, const_expr_kind)
 {
   GENV_ITEMFACTORY->createInteger(theValue, v);
   theScriptingKind = SIMPLE_EXPR;
 }
 
+
 const_expr::const_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     xs_decimal v)
   :
-  expr(ccb, sctx, loc, const_expr_kind)
+  expr(ccb, sctx, udf, loc, const_expr_kind)
 {
   GENV_ITEMFACTORY->createDecimal(theValue, v);
   theScriptingKind = SIMPLE_EXPR;
 }
 
+
 const_expr::const_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     xs_double v)
   :
-  expr(ccb, sctx, loc, const_expr_kind)
+  expr(ccb, sctx, udf, loc, const_expr_kind)
 {
   GENV_ITEMFACTORY->createDouble(theValue, v);
   theScriptingKind = SIMPLE_EXPR;
@@ -932,10 +833,11 @@
 const_expr::const_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     xs_boolean v)
   :
-  expr(ccb, sctx, loc, const_expr_kind)
+  expr(ccb, sctx, udf, loc, const_expr_kind)
 {
   GENV_ITEMFACTORY->createBoolean(theValue, v);
   theScriptingKind = SIMPLE_EXPR;
@@ -945,10 +847,11 @@
 const_expr::const_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const store::Item_t& v)
   :
-  expr(ccb, sctx, loc, const_expr_kind),
+  expr(ccb, sctx, udf, loc, const_expr_kind),
   theValue(v)
 {
   theScriptingKind = SIMPLE_EXPR;
@@ -958,12 +861,13 @@
 const_expr::const_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& aLoc,
     const char* aNamespace,
     const char* aPrefix,
     const char* aLocal)
   :
-  expr(ccb, sctx, aLoc, const_expr_kind)
+  expr(ccb, sctx, udf, aLoc, const_expr_kind)
 {
   GENV_ITEMFACTORY->createQName(theValue, aNamespace, aPrefix, aLocal);
   theScriptingKind = SIMPLE_EXPR;
@@ -976,21 +880,16 @@
 }
 
 
-expr* const_expr::cloneImpl(substitution_t&) const
-{
-  return theCCB->theEM->create_const_expr(theSctx, get_loc(), theValue);
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
 extension_expr::extension_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc)
   :
-  expr(ccb, sctx, loc, extension_expr_kind)
+  expr(ccb, sctx, udf, loc, extension_expr_kind)
 {
   compute_scripting_kind();
 }
@@ -999,10 +898,11 @@
 extension_expr::extension_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* e)
   :
-  expr(ccb, sctx, loc, extension_expr_kind),
+  expr(ccb, sctx, udf, loc, extension_expr_kind),
   theExpr(e)
 {
   compute_scripting_kind();
@@ -1020,23 +920,6 @@
 }
 
 
-expr* extension_expr::cloneImpl(substitution_t& subst) const 
-{
-  extension_expr* lClone(0);
-  lClone = (
-    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<pragma*>::const_iterator lIter = thePragmas.begin();
-        lIter != thePragmas.end();
-        ++lIter )
-  {
-    lClone->add(*lIter);
-  }
-  return lClone;
-}
-
-
 /////////////////////////////////////////////////////////////////////////
 //                                                                     //
 //  XQuery 3.0 expressions                                             //
@@ -1049,7 +932,8 @@
 
 ********************************************************************************/
 catch_clause::catch_clause(CompilerCB* ccb)
-:theCCB(ccb)
+  :
+  theCCB(ccb)
 {
 }
 
@@ -1057,10 +941,11 @@
 trycatch_expr::trycatch_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* tryExpr)
   :
-  expr(ccb, sctx, loc, trycatch_expr_kind),
+  expr(ccb, sctx, udf, loc, trycatch_expr_kind),
   theTryExpr(tryExpr)
 {
   compute_scripting_kind();
@@ -1145,6 +1030,7 @@
   {
     lClause->add_nametest_h(lIter->getp());
   }
+
   for (var_map_t::const_iterator lIter = theVarMap.begin();
        lIter != theVarMap.end();
        ++lIter)
@@ -1156,39 +1042,19 @@
 }
 
 
-expr* trycatch_expr::cloneImpl(substitution_t& subst) const
-{
-  std::auto_ptr<trycatch_expr> lTryCatch(
-      theCCB->theEM->create_trycatch_expr(theSctx, get_loc(), theTryExpr->clone(subst)));
-
-  for (std::vector<expr*>::const_iterator lIter = theCatchExprs.begin();
-       lIter != theCatchExprs.end();
-       ++lIter)
-  {
-    lTryCatch->add_catch_expr((*lIter)->clone(subst));
-  }
-
-  for (csize i = 0; i < clause_count(); ++i)
-  {
-    lTryCatch->add_clause(theCatchClauses[i]->clone(subst));
-  }
-
-  return lTryCatch.release();
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
 eval_expr::eval_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* e,
     expr_script_kind_t scriptingKind,
     namespace_context* nsCtx)
   :
-  namespace_context_base_expr(ccb, sctx, loc, eval_expr_kind, nsCtx),
+  namespace_context_base_expr(ccb, sctx, udf, loc, eval_expr_kind, nsCtx),
   theExpr(e),
   theInnerScriptingKind(scriptingKind),
   theDoNodeCopy(false)
@@ -1222,33 +1088,6 @@
 }
 
 
-expr* eval_expr::cloneImpl(substitution_t& s) const
-{
-  eval_expr* new_eval = theCCB->theEM->
-  create_eval_expr(theSctx,
-                   theLoc,
-                   theExpr->clone(s),
-                   theInnerScriptingKind,
-                   theNSCtx.getp());
-
-  new_eval->setNodeCopy(theDoNodeCopy);
-
-  new_eval->theOuterVarNames = theOuterVarNames;
-  new_eval->theOuterVarTypes = theOuterVarTypes;
-
-  csize numVars = theOuterVarNames.size();
-
-  new_eval->theArgs.resize(numVars);
-
-  for (csize i = 0; i < numVars; ++i)
-  {
-    new_eval->theArgs[i] = theArgs[i]->clone(s);
-  }
-
-  return new_eval;
-}
-
-
 #ifdef ZORBA_WITH_DEBUGGER
 /*******************************************************************************
 
@@ -1256,12 +1095,13 @@
 debugger_expr::debugger_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* aChild,
     namespace_context* nsCtx,
     bool aIsVarDeclaration)
   :
-  namespace_context_base_expr(ccb, sctx, loc, debugger_expr_kind, nsCtx),
+  namespace_context_base_expr(ccb, sctx, udf, loc, debugger_expr_kind, nsCtx),
   theExpr(aChild),
   theIsVarDeclaration(aIsVarDeclaration)
 {
@@ -1283,10 +1123,11 @@
 function_trace_expr::function_trace_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* aChild)
   :
-  expr(ccb, sctx, loc, aChild->get_expr_kind()),
+  expr(ccb, sctx, udf, loc, aChild->get_expr_kind()),
   theExpr(aChild),
   theFunctionArity(0)
 {
@@ -1298,7 +1139,11 @@
 
 function_trace_expr::function_trace_expr(expr* aExpr)
   :
-  expr(aExpr->get_ccb(), aExpr->get_sctx(), aExpr->get_loc(), function_trace_expr_kind),
+  expr(aExpr->get_ccb(),
+       aExpr->get_sctx(),
+       aExpr->get_udf(),
+       aExpr->get_loc(),
+       function_trace_expr_kind),
   theExpr(aExpr),
   theFunctionArity(0)
 {
@@ -1319,20 +1164,5 @@
 }
 
 
-expr* function_trace_expr::cloneImpl(substitution_t& s) const
-{
-  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;
-}
-
-
-
 } /* namespace zorba */
 /* vim:set et sw=2 ts=2: */

=== modified file 'src/compiler/expression/expr.h'
--- src/compiler/expression/expr.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/expr.h	2012-10-09 10:29:25 +0000
@@ -58,14 +58,15 @@
   friend class expr;
 
 protected:
-  expr* theCondExpr;
-  expr* theThenExpr;
-  expr* theElseExpr;
+  expr  * theCondExpr;
+  expr  * theThenExpr;
+  expr  * theElseExpr;
 
 protected:
   if_expr(
         CompilerCB* ccb,
         static_context* sctx,
+        user_function* udf,
         const QueryLoc& loc,
         expr* c,
         expr* t,
@@ -80,8 +81,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -105,11 +104,17 @@
   };
 
 protected:
-  order_type_t theType;
-  expr*       theExpr;
+  order_type_t   theType;
+  expr         * theExpr;
 
 protected:
-  order_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, order_type_t, expr*);
+  order_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      order_type_t,
+      expr*);
 
 public:
   order_type_t get_type() const { return theType; }
@@ -118,8 +123,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -139,17 +142,18 @@
   ParseConstants::validation_mode_t theMode;
   store::Item_t                     theTypeName;
   rchandle<TypeManager>             theTypeMgr;
-  expr*                            theExpr;
+  expr                            * theExpr;
 
 protected:
   validate_expr(
-        CompilerCB* ccb,
-        static_context* sctx,
-        const QueryLoc&,
-        ParseConstants::validation_mode_t,
-        const store::Item_t& aTypeName,
-        expr*,
-        rchandle<TypeManager>);
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      ParseConstants::validation_mode_t,
+      const store::Item_t& aTypeName,
+      expr*,
+      rchandle<TypeManager>);
 
 public:
   expr* get_expr() const { return theExpr; }
@@ -162,8 +166,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -184,6 +186,7 @@
   namespace_context_base_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr_kind_t kind,
       const namespace_context* aNSCtx);
@@ -207,12 +210,13 @@
 
 protected:
   cast_or_castable_base_expr(
-        CompilerCB* ccb,
-        static_context* sctx,
-        const QueryLoc& loc,
-        expr_kind_t kind,
-        expr* input,
-        const xqtref_t& type);
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc& loc,
+      expr_kind_t kind,
+      expr* input,
+      const xqtref_t& type);
 
 public:
   expr* get_input() const { return theInputExpr; }
@@ -234,12 +238,13 @@
 
 protected:
   cast_base_expr(
-        CompilerCB* ccb,
-        static_context* sctx,
-        const QueryLoc& loc,
-        expr_kind_t kind,
-        expr* input,
-        const xqtref_t& type);
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc& loc,
+      expr_kind_t kind,
+      expr* input,
+      const xqtref_t& type);
 };
 
 
@@ -258,6 +263,7 @@
   cast_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*,
       const xqtref_t&);
@@ -265,8 +271,6 @@
 public:
   bool is_optional() const;
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -299,14 +303,15 @@
 
 protected:
   treat_expr(
-        CompilerCB* ccb,
-        static_context* sctx,
-        const QueryLoc&,
-        expr*,
-        const xqtref_t&,
-        TreatIterator::ErrorKind err,
-        bool check_prime = true,
-        store::Item* qname = NULL);
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      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; }
@@ -319,8 +324,6 @@
 
   store::Item_t get_qname() const { return theQName; }
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -379,6 +382,7 @@
   promote_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* input,
       const xqtref_t& type,
@@ -386,8 +390,6 @@
       store::Item* qname);
 
 public:
-  expr* cloneImpl(substitution_t& s) const;
-
   PromoteIterator::ErrorKind get_err() const { return theErrorKind; }
 
   void set_qname(const store::Item_t& qname) { theQName = qname; }
@@ -409,12 +411,13 @@
 
 protected:
   castable_base_expr(
-        CompilerCB* ccb,
-        static_context* sctx,
-        const QueryLoc&,
-        expr_kind_t kind,
-        expr*,
-        const xqtref_t&);
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      expr_kind_t kind,
+      expr*,
+      const xqtref_t&);
 };
 
 
@@ -433,6 +436,7 @@
   castable_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*,
       const xqtref_t&);
@@ -440,8 +444,6 @@
 public:
   bool is_optional() const;
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -470,6 +472,7 @@
   instanceof_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*,
       const xqtref_t&,
@@ -478,8 +481,6 @@
 public:
   bool getCheckPrimeOnly() const { return theCheckPrimeOnly; }
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -510,6 +511,7 @@
   name_cast_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*,
       const namespace_context*,
@@ -522,8 +524,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -540,11 +540,17 @@
   friend class expr;
 
 protected:
-  expr* theContent;
-  bool   theCopyInputNodes;
+  expr  * theContent;
+  bool     theCopyInputNodes;
 
 protected:
-  doc_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, expr* content, bool copyNodes);
+  doc_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      expr* content,
+      bool copyNodes);
 
 public:
   expr* getContent() const { return theContent; }
@@ -555,8 +561,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -596,25 +600,27 @@
   friend class expr;
 
 protected:
-  expr* theQNameExpr;
-  expr* theAttrs;
-  expr* theContent;
-  bool   theCopyInputNodes;
+  expr  * theQNameExpr;
+  expr  * theAttrs;
+  expr  * theContent;
+  bool    theCopyInputNodes;
 
 protected:
   elem_expr(
-        CompilerCB* ccb,
-        static_context* sctx,
-        const QueryLoc&,
-        expr* qnameExpr,
-        expr* attrs,
-        expr* content,
-        const namespace_context* nsCtx,
-        bool copyNodes);
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      expr* qnameExpr,
+      expr* attrs,
+      expr* content,
+      const namespace_context* nsCtx,
+      bool copyNodes);
 
   elem_expr(
         CompilerCB* ccb,
         static_context* sctx,
+        user_function* udf,
         const QueryLoc&,
         expr* qnameExpr,
         expr* content,
@@ -634,8 +640,6 @@
 
   void compute_scripting_kind();
   
-  expr* cloneImpl(substitution_t& s) const;  
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -673,16 +677,17 @@
   friend class expr;
 
 protected:
-  expr* theQNameExpr;
-  expr* theValueExpr;
+  expr  * theQNameExpr;
+  expr  * theValueExpr;
 
 protected:
   attr_expr(
-    CompilerCB* ccb,
-    static_context* sctx,
-    const QueryLoc& loc,
-    expr* aQNameExpr,
-    expr* aValueExpr);
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc& loc,
+      expr* aQNameExpr,
+      expr* aValueExpr);
 
 public:
   expr* getQNameExpr() const { return theQNameExpr; }
@@ -693,8 +698,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -718,13 +721,14 @@
   } text_constructor_type;
 
 protected:
-  text_constructor_type type;
-  expr*                theContentExpr;
+  text_constructor_type   type;
+  expr                  * theContentExpr;
 
 protected:
   text_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       text_constructor_type,
       expr*);
@@ -736,8 +740,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;  
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -754,11 +756,17 @@
   friend class expr;
 
 protected:
-  expr* theTargetExpr;
-  expr* theContentExpr;
+  expr * theTargetExpr;
+  expr * theContentExpr;
 
 protected:
-  pi_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, expr*, expr*);
+  pi_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      expr*,
+      expr*);
 
 public:
   expr* get_target_expr() const { return theTargetExpr; }
@@ -767,8 +775,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;  
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -788,31 +794,76 @@
   store::Item_t theValue;
 
 protected:
-  const_expr(CompilerCB*, static_context*, const QueryLoc&, zstring& sval);
-
-  const_expr(CompilerCB*, static_context*, const QueryLoc&, const std::string& sval);
-
-  const_expr(CompilerCB*, static_context*, const QueryLoc&, const char* sval);
-
-  const_expr(CompilerCB*, static_context*, const QueryLoc&, xs_integer);
-
-  const_expr(CompilerCB*, static_context*, const QueryLoc&, xs_decimal);
-
-  const_expr(CompilerCB*, static_context*, const QueryLoc&, xs_double);
-
-  const_expr(CompilerCB*, static_context*, const QueryLoc&, xs_boolean);
-
-  const_expr(CompilerCB*, static_context*, const QueryLoc&, const store::Item_t&);
-
-  const_expr(CompilerCB*, static_context*, const QueryLoc&, const char* ns, const char* pre, const char* local);
+  const_expr(
+      CompilerCB*,
+      static_context*,
+      user_function* udf,
+      const QueryLoc&,
+      zstring& sval);
+
+  const_expr(
+      CompilerCB*,
+      static_context*,
+      user_function* udf,
+      const QueryLoc&,
+      const std::string& sval);
+
+  const_expr(
+      CompilerCB*,
+      static_context*,
+      user_function* udf,
+      const QueryLoc&,
+      const char* sval);
+
+  const_expr(
+      CompilerCB*,
+      static_context*,
+      user_function* udf,
+      const QueryLoc&,
+      xs_integer);
+
+  const_expr(
+      CompilerCB*,
+      static_context*,
+      user_function* udf,
+      const QueryLoc&,
+      xs_decimal);
+
+  const_expr(
+      CompilerCB*,
+      static_context*,
+      user_function* udf,
+      const QueryLoc&,
+      xs_double);
+
+  const_expr(
+      CompilerCB*,
+      static_context*,
+      user_function* udf,
+      const QueryLoc&,
+      xs_boolean);
+
+  const_expr(
+      CompilerCB*,
+      static_context*,
+      user_function* udf,
+      const QueryLoc&,
+      const store::Item_t&);
+
+  const_expr(
+      CompilerCB*,
+      static_context*,
+      user_function* udf,
+      const QueryLoc&,
+      const char* ns,
+      const char* pre,
+      const char* local);
 
 public:
   store::Item* get_val() const { return theValue.getp(); }
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -829,13 +880,22 @@
   friend class expr;
 
 protected:
-  std::vector<pragma*> thePragmas;
-  expr*                theExpr;
+  std::vector<pragma*>   thePragmas;
+  expr                 * theExpr;
 
 protected:
-  extension_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&);
+  extension_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&);
 
-  extension_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, expr*);
+  extension_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      expr*);
 
 public:
   void add(pragma* p) { thePragmas.push_back(p); }
@@ -844,8 +904,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& subst) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -934,7 +992,12 @@
   std::vector<catch_clause*> theCatchClauses;
 
 protected:
-  trycatch_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, expr* tryExpr);
+  trycatch_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      expr* tryExpr);
 
 public:
   expr* get_try_expr() const { return theTryExpr; }
@@ -953,8 +1016,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& subst) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -979,10 +1040,15 @@
   friend class ExprManager;
 
 protected:
-  expr* theWrappedExpr;
+  expr  * theWrappedExpr;
 
 protected:
-  wrapper_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, expr* wrapped);
+  wrapper_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc& loc,
+      expr* wrapped);
 
 public:
   expr* get_expr() const { return theWrappedExpr; }
@@ -993,8 +1059,6 @@
 
   void accept(expr_visitor&);
 
-  expr* cloneImpl(substitution_t& s) const;
-
   std::ostream& put(std::ostream&) const;
 };
 
@@ -1019,6 +1083,7 @@
   function_trace_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* aChild);
 
@@ -1031,8 +1096,6 @@
 
   void accept(expr_visitor&);
 
-  expr* cloneImpl(substitution_t& s) const;
-
   std::ostream& put(std::ostream&) const;
 
   expr* get_expr() const { return theExpr; }
@@ -1133,6 +1196,7 @@
   eval_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* e,
       expr_script_kind_t scriptingKind,
@@ -1166,8 +1230,6 @@
 
   void accept(expr_visitor&);
 
-  expr* cloneImpl(substitution_t& s) const;
-
   std::ostream& put(std::ostream&) const;
 };
 
@@ -1205,6 +1267,7 @@
   debugger_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* aChild,
       namespace_context* nsCtx,

=== modified file 'src/compiler/expression/expr_base.cpp'
--- src/compiler/expression/expr_base.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/expr_base.cpp	2012-10-09 10:29:25 +0000
@@ -19,7 +19,6 @@
 #include "compiler/expression/expr.h"
 #include "compiler/expression/fo_expr.h"
 #include "compiler/expression/flwor_expr.h"
-#include "compiler/expression/script_exprs.h"
 #include "compiler/expression/path_expr.h"
 #include "compiler/expression/expr_iter.h"
 #include "compiler/expression/expr_visitor.h"
@@ -123,13 +122,19 @@
 /*******************************************************************************
 
 ********************************************************************************/
-expr::expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, expr_kind_t k)
+expr::expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc,
+    expr_kind_t k)
   :
+  theCCB(ccb),
   theSctx(sctx),
+  theUDF(udf),
   theLoc(loc),
   theKind(k),
-  theFlags1(0),
-  theCCB(ccb)
+  theFlags1(0)
 {
   theScriptingKind = UNKNOWN_SCRIPTING_KIND;
 
@@ -239,40 +244,6 @@
 /*******************************************************************************
 
 ********************************************************************************/
-expr* expr::clone() const
-{
-  substitution_t subst;
-  return clone(subst);
-}
-
-
-expr* expr::clone(substitution_t& subst) const
-{
-  expr* lNewExpr = cloneImpl(subst);
-
-  if (containsPragma())
-  {
-    lNewExpr->setContainsPragma(ANNOTATION_TRUE);
-    std::vector<pragma*> lPragmas;
-    theCCB->lookup_pragmas(this, lPragmas);
-    for (size_t i = 0; i < lPragmas.size(); ++i)
-    {
-      theCCB->add_pragma(lNewExpr, lPragmas[i]);
-    }
-  }
-  return lNewExpr;
-}
-
-
-expr* expr::cloneImpl(substitution_t& subst) const
-{
-  throw XQUERY_EXCEPTION(zerr::ZXQP0003_INTERNAL_ERROR, ERROR_LOC(get_loc()));
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
 void expr::accept_children(expr_visitor& v)
 {
   ExprIterator iter(this);
@@ -1212,13 +1183,18 @@
 ********************************************************************************/
 xqtref_t expr::get_return_type_with_empty_input(const expr* input) const
 {
-  expr* emptyExpr = theCCB->theEM->create_fo_expr(input->get_sctx(),
-                                 QueryLoc::null,
-                                 GET_BUILTIN_FUNCTION(OP_CONCATENATE_N));
+  assert(input->get_udf() == theUDF);
+
+  expr* emptyExpr = theCCB->theEM->
+  create_fo_expr(input->get_sctx(),
+                 theUDF,
+                 QueryLoc::null,
+                 GET_BUILTIN_FUNCTION(OP_CONCATENATE_N));
+
   expr::substitution_t subst;
   subst[input] = emptyExpr;
 
-  expr* cloneExpr = clone(subst);
+  expr* cloneExpr = clone(theUDF, subst);
 
   return cloneExpr->get_return_type();
 }

=== modified file 'src/compiler/expression/expr_base.h'
--- src/compiler/expression/expr_base.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/expr_base.h	2012-10-09 10:29:25 +0000
@@ -173,8 +173,12 @@
   static expr*    * iter_done;
 
 protected:
+  CompilerCB * const theCCB;
+
   static_context   * theSctx;
 
+  user_function    * theUDF;
+
   QueryLoc           theLoc;
 
   unsigned short     theKind;
@@ -186,8 +190,6 @@
 
   FreeVars           theFreeVars;
 
-  CompilerCB  *const theCCB;
-
 public:
   static bool is_sequential(unsigned short theScriptingKind);
 
@@ -196,14 +198,20 @@
   static void checkNonUpdating(const expr* e);
 
 protected:
-  expr(CompilerCB*, static_context*, const QueryLoc&, expr_kind_t);
+  expr(CompilerCB*, static_context*, user_function*, const QueryLoc&, expr_kind_t);
 
-  expr() : theSctx(NULL), theFlags1(0), theCCB(NULL) {}
+  expr() : theCCB(NULL), theSctx(NULL), theUDF(NULL), theFlags1(0) {}
 
 public:
   virtual ~expr();
 
-  CompilerCB* get_ccb() {return theCCB;}
+  CompilerCB* get_ccb() { return theCCB; }
+
+  static_context* get_sctx() const { return theSctx; }
+
+  TypeManager* get_type_manager() const;
+
+  user_function* get_udf() const { return theUDF; }
 
   expr_kind_t get_expr_kind() const { return static_cast<expr_kind_t>(theKind); }
 
@@ -211,10 +219,6 @@
 
   void set_loc(const QueryLoc& loc) { theLoc = loc; }
 
-  static_context* get_sctx() const { return theSctx; }
-
-  TypeManager* get_type_manager() const;
-
   uint32_t getFlags() const { return theFlags1; }
 
   void setFlags(uint32_t flags) { theFlags1 = flags; }
@@ -241,11 +245,9 @@
 
   xqtref_t get_return_type();
 
-  expr* clone() const;
-
-  expr* clone(substitution_t&) const;
-
-  virtual expr* cloneImpl(substitution_t& substitution) const;
+  expr* clone(user_function* udf) const;
+
+  expr* clone(user_function* udf, substitution_t& subst) const;
 
   virtual void accept(expr_visitor& v) = 0;
 

=== modified file 'src/compiler/expression/expr_manager.cpp'
--- src/compiler/expression/expr_manager.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/expr_manager.cpp	2012-10-09 10:29:25 +0000
@@ -35,60 +35,6 @@
 namespace zorba
 {
 
-#if 0
-//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; }
-};
-
-
-class NullFlworClause : public flwor_clause
-{
-public:
-  //it being a let clause is arbitrary, it doesn't matter what type it is.
-  NullFlworClause() :flwor_clause(NULL, NULL, QueryLoc(), flwor_clause::let_clause) {}
-
-  std::ostream& put(std::ostream& stream) const { return stream; }
-
-  flwor_clause* clone(expr::substitution_t &) const { return NULL; }
-};
-
-
-class NullWincond : public flwor_wincond
-{
-public:
-  NullWincond() : flwor_wincond(NULL, NULL, false, vars(), vars(), NULL) {}
-
-  std::ostream& put(std::ostream& stream) const { return stream; }
-};
-
-
-class NullCatchClause : public catch_clause
-{
-public:
-  NullCatchClause() : catch_clause(NULL) {}
-
-  std::ostream& put(std::ostream& stream) const{return stream;}
-};
-
-
-class NullCopyClause : public copy_clause
-{
-public:
-  NullCopyClause() : copy_clause(NULL, NULL, NULL) {}
-};
-#endif
-
-
 ExprManager::ExprManager(CompilerCB* ccb)
   :
   theCCB(ccb)
@@ -219,49 +165,54 @@
 
 if_expr* ExprManager::create_if_expr(
     static_context* sctx,
+    user_function* udf,
     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);
+  CREATE_AND_RETURN_EXPR(if_expr, sctx, udf, loc, cond_expr, then_expr, else_expr);
 }
 
 
 order_expr* ExprManager::create_order_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     order_expr::order_type_t order,
     expr* exp)
 {
-  CREATE_AND_RETURN_EXPR(order_expr, sctx, loc, order, exp);
+  CREATE_AND_RETURN_EXPR(order_expr, sctx, udf, loc, order, exp);
 }
 
 
 validate_expr* ExprManager::create_validate_expr(
     static_context* sctx,
+    user_function* udf,
     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);
+  CREATE_AND_RETURN_EXPR(validate_expr, sctx, udf, loc, mode, aTypeName, validated, tm);
 }
 
 
 cast_expr* ExprManager::create_cast_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* casted,
     xqtref_t type)
 {
-  CREATE_AND_RETURN_EXPR(cast_expr, sctx, loc, casted, type);
+  CREATE_AND_RETURN_EXPR(cast_expr, sctx, udf, loc, casted, type);
 }
 
 
 treat_expr* ExprManager::create_treat_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* treated,
     const xqtref_t& type,
@@ -270,67 +221,73 @@
     store::Item* qname)
 {
   CREATE_AND_RETURN_EXPR(treat_expr,
-  sctx, loc, treated, type, err, check_prime, qname);
+  sctx, udf, loc, treated, type, err, check_prime, qname);
 }
 
 
 promote_expr* ExprManager::create_promote_expr(
     static_context* sctx,
+    user_function* udf,
     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);
+  CREATE_AND_RETURN_EXPR(promote_expr, sctx, udf, loc, promoted, type, err, qname);
 }
 
 
 castable_expr* ExprManager::create_castable_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* castable,
     xqtref_t type)
 {
-  CREATE_AND_RETURN_EXPR(castable_expr, sctx, loc, castable, type);
+  CREATE_AND_RETURN_EXPR(castable_expr, sctx, udf, loc, castable, type);
 }
 
 
 instanceof_expr* ExprManager::create_instanceof_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* instanced,
     xqtref_t type,
     bool checkPrimeOnly)
 {
   CREATE_AND_RETURN_EXPR(instanceof_expr,
-          sctx, loc, instanced, type, checkPrimeOnly);
+          sctx, udf, loc, instanced, type, checkPrimeOnly);
 }
 
 
 name_cast_expr* ExprManager::create_name_cast_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* casted,
     const namespace_context* ns,
     bool isAttr)
 {
-  CREATE_AND_RETURN_EXPR(name_cast_expr, sctx, loc, casted, ns, isAttr);
+  CREATE_AND_RETURN_EXPR(name_cast_expr, sctx, udf, loc, casted, ns, isAttr);
 }
 
 
 doc_expr* ExprManager::create_doc_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* content,
     bool copyNodes)
 {
-  CREATE_AND_RETURN_EXPR(doc_expr, sctx, loc, content, copyNodes);
+  CREATE_AND_RETURN_EXPR(doc_expr, sctx, udf, loc, content, copyNodes);
 }
 
 
 elem_expr* ExprManager::create_elem_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* qnameExpr,
     expr* attrs,
@@ -339,12 +296,13 @@
     bool copyNodes)
 {
   CREATE_AND_RETURN_EXPR(elem_expr,
-          sctx, loc, qnameExpr, attrs, content, nsCtx, copyNodes);
+          sctx, udf, loc, qnameExpr, attrs, content, nsCtx, copyNodes);
 }
 
 
 elem_expr* ExprManager::create_elem_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* qnameExpr,
     expr* content,
@@ -352,137 +310,151 @@
     bool copyNodes)
 {
   CREATE_AND_RETURN_EXPR(elem_expr,
-          sctx, loc, qnameExpr, content, nsCtx, copyNodes);
+          sctx, udf, loc, qnameExpr, content, nsCtx, copyNodes);
 }
 
 
 attr_expr* ExprManager::create_attr_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* aQNameExpr,
     expr* aValueExpr)
 {
-  CREATE_AND_RETURN_EXPR(attr_expr, sctx, loc, aQNameExpr, aValueExpr);
+  CREATE_AND_RETURN_EXPR(attr_expr, sctx, udf, loc, aQNameExpr, aValueExpr);
 }
 
 
 text_expr* ExprManager::create_text_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     text_expr::text_constructor_type textType,
     expr* text)
 {
-  CREATE_AND_RETURN_EXPR(text_expr, sctx, loc, textType, text);
+  CREATE_AND_RETURN_EXPR(text_expr, sctx, udf, loc, textType, text);
 }
 
 
 pi_expr* ExprManager::create_pi_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* targetExpr,
     expr* contentExpr)
 {
-  CREATE_AND_RETURN_EXPR(pi_expr, sctx, loc, targetExpr, contentExpr);
+  CREATE_AND_RETURN_EXPR(pi_expr, sctx, udf, loc, targetExpr, contentExpr);
 }
 
 
 const_expr* ExprManager::create_const_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     zstring& sval)
 {
-  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, sval);
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, udf, loc, sval);
 }
 
 
 const_expr* ExprManager::create_const_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const std::string& sval)
 {
-  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, sval);
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, udf, loc, sval);
 }
 
 
 const_expr* ExprManager::create_const_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const char* sval)
 {
-  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, sval);
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, udf, loc, sval);
 }
 
 
 const_expr* ExprManager::create_const_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     xs_integer val)
 {
-  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, val);
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, udf, loc, val);
 }
 
 
 const_expr* ExprManager::create_const_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     xs_decimal val)
 {
-  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, val);
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, udf, loc, val);
 }
 
 
 const_expr* ExprManager::create_const_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     xs_double val)
 {
-  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, val);
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, udf, loc, val);
 }
 
 
 const_expr* ExprManager::create_const_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     xs_boolean val)
 {
-  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, val);
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, udf, loc, val);
 }
 
 
 const_expr* ExprManager::create_const_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     store::Item_t val)
 {
-  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, val);
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, udf, loc, val);
 }
 
 
 const_expr* ExprManager::create_const_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const char* ns,
     const char* pre,
     const char* local)
 {
-  CREATE_AND_RETURN_EXPR(const_expr, sctx, loc, ns, pre, local);
+  CREATE_AND_RETURN_EXPR(const_expr, sctx, udf, loc, ns, pre, local);
 }
 
 
 extension_expr* ExprManager::create_extension_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc)
 {
-  CREATE_AND_RETURN_EXPR(extension_expr, sctx, loc);
+  CREATE_AND_RETURN_EXPR(extension_expr, sctx, udf, loc);
 }
 
 
 extension_expr* ExprManager::create_extension_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* extended)
 {
-  CREATE_AND_RETURN_EXPR(extension_expr, sctx, loc, extended);
+  CREATE_AND_RETURN_EXPR(extension_expr, sctx, udf, loc, extended);
 }
 
 
@@ -494,32 +466,36 @@
 
 trycatch_expr* ExprManager::create_trycatch_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* tryExpr)
 {
-  CREATE_AND_RETURN_EXPR(trycatch_expr, sctx, loc, tryExpr);
+  CREATE_AND_RETURN_EXPR(trycatch_expr, sctx, udf, loc, tryExpr);
 }
 
 
 wrapper_expr* ExprManager::create_wrapper_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* wrapped)
 {
-  CREATE_AND_RETURN_EXPR(wrapper_expr, sctx, loc, wrapped);
+  CREATE_AND_RETURN_EXPR(wrapper_expr, sctx, udf, loc, wrapped);
 }
 
-
+#if 0
 function_trace_expr* ExprManager::create_function_trace_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* aChild)
 {
-  CREATE_AND_RETURN_EXPR(function_trace_expr, sctx, loc, aChild);
+  CREATE_AND_RETURN_EXPR(function_trace_expr, sctx, udf, loc, aChild);
 }
-
-
-function_trace_expr* ExprManager::create_function_trace_expr(expr* aExpr)
+#endif
+
+function_trace_expr* ExprManager::create_function_trace_expr(
+    expr* aExpr)
 {
   //this function gets the ExprManager from the expression it recieves.
   function_trace_expr* e = new (theMemoryMgr) function_trace_expr(aExpr);
@@ -530,25 +506,27 @@
 
 eval_expr* ExprManager::create_eval_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* e,
     expr_script_kind_t scriptingKind,
     namespace_context* nsCtx)
 {
-  CREATE_AND_RETURN_EXPR(eval_expr, sctx, loc, e, scriptingKind, nsCtx);
+  CREATE_AND_RETURN_EXPR(eval_expr, sctx, udf, loc, e, scriptingKind, nsCtx);
 }
 
 #ifdef ZORBA_WITH_DEBUGGER
 
 debugger_expr* ExprManager::create_debugger_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* aChild,
     namespace_context* nsCtx,
     bool aIsVarDeclaration)
 {
   CREATE_AND_RETURN_EXPR(debugger_expr,
-  sctx, loc, aChild, nsCtx, aIsVarDeclaration);
+  sctx, udf, loc, aChild, nsCtx, aIsVarDeclaration);
 }
 
 #endif
@@ -557,17 +535,20 @@
 
 var_expr* ExprManager::create_var_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     var_expr::var_kind k,
     store::Item* name)
 {
-  CREATE_AND_RETURN_EXPR(var_expr, sctx, loc, k, name);
+  CREATE_AND_RETURN_EXPR(var_expr, sctx, udf, loc, k, name);
 }
 
 
-var_expr* ExprManager::create_var_expr(const var_expr& source)
+var_expr* ExprManager::create_var_expr(
+    user_function* udf,
+    const var_expr& source)
 {
-  var_expr* e = new (theMemoryMgr) var_expr(source);
+  var_expr* e = new (theMemoryMgr) var_expr(udf, source);
   reg(e);
   return e;
 }
@@ -580,30 +561,33 @@
 
 json_array_expr* ExprManager::create_json_array_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* content)
 {
-  CREATE_AND_RETURN_EXPR(json_array_expr, sctx, loc, content);
+  CREATE_AND_RETURN_EXPR(json_array_expr, sctx, udf, loc, content);
 }
 
 
 json_object_expr* ExprManager::create_json_object_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* content,
     bool accumulate)
 {
-  CREATE_AND_RETURN_EXPR(json_object_expr, sctx, loc, content, accumulate);
+  CREATE_AND_RETURN_EXPR(json_object_expr, sctx, udf, loc, content, accumulate);
 }
 
 
 json_direct_object_expr* ExprManager::create_json_direct_object_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     std::vector<expr*>& names,
     std::vector<expr*>& values)
 {
-  CREATE_AND_RETURN_EXPR(json_direct_object_expr, sctx, loc, names, values);
+  CREATE_AND_RETURN_EXPR(json_direct_object_expr, sctx, udf, loc, names, values);
 }
 
 
@@ -614,43 +598,47 @@
 
 insert_expr* ExprManager::create_insert_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     store::UpdateConsts::InsertType insertType,
     expr* aSourceExpr,
     expr* aTargetExpr)
 {
   CREATE_AND_RETURN_EXPR(insert_expr,
-  sctx, loc, insertType, aSourceExpr, aTargetExpr);
+  sctx, udf, loc, insertType, aSourceExpr, aTargetExpr);
 }
 
 
 delete_expr* ExprManager::create_delete_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* aTargetExpr)
 {
-  CREATE_AND_RETURN_EXPR(delete_expr, sctx, loc, aTargetExpr);
+  CREATE_AND_RETURN_EXPR(delete_expr, sctx, udf, loc, aTargetExpr);
 }
 
 
 replace_expr* ExprManager::create_replace_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     store::UpdateConsts::ReplaceType aType,
     expr* aSourceExpr,
     expr* aTargetExpr)
 {
-  CREATE_AND_RETURN_EXPR(replace_expr, sctx, loc, aType, aSourceExpr, aTargetExpr);
+  CREATE_AND_RETURN_EXPR(replace_expr, sctx, udf, loc, aType, aSourceExpr, aTargetExpr);
 }
 
 
 rename_expr* ExprManager::create_rename_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* aSourceExpr,
     expr* aTargetExpr)
 {
-  CREATE_AND_RETURN_EXPR(rename_expr, sctx, loc, aSourceExpr, aTargetExpr);
+  CREATE_AND_RETURN_EXPR(rename_expr, sctx, udf, loc, aSourceExpr, aTargetExpr);
 }
 
 
@@ -662,112 +650,126 @@
 
 transform_expr* ExprManager::create_transform_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc)
 {
-  CREATE_AND_RETURN_EXPR(transform_expr, sctx, loc);
+  CREATE_AND_RETURN_EXPR(transform_expr, sctx, udf, loc);
 }
 
 
 block_expr* ExprManager::create_block_expr(
     static_context* sctx,
+    user_function* udf,
     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);
+  sctx, udf, loc, allowLastUpdating, seq, assignedVars);
 }
 
 
 apply_expr* ExprManager::create_apply_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* inExpr,
     bool discardXDM)
 {
-  CREATE_AND_RETURN_EXPR(apply_expr, sctx, loc, inExpr, discardXDM);
+  CREATE_AND_RETURN_EXPR(apply_expr, sctx, udf, loc, inExpr, discardXDM);
 }
 
 
 var_decl_expr* ExprManager::create_var_decl_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     var_expr* varExpr,
     expr* initExpr)
 {
-  CREATE_AND_RETURN_EXPR(var_decl_expr, sctx, loc, varExpr, initExpr);
+  CREATE_AND_RETURN_EXPR(var_decl_expr, sctx, udf, loc, varExpr, initExpr);
 }
 
 
 var_set_expr* ExprManager::create_var_set_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     var_expr* varExpr,
     expr* setExpr)
 {
-  CREATE_AND_RETURN_EXPR(var_set_expr, sctx, loc, varExpr, setExpr);
+  CREATE_AND_RETURN_EXPR(var_set_expr, sctx, udf, loc, varExpr, setExpr);
 }
 
 
 exit_expr* ExprManager::create_exit_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* inExpr)
 {
-  CREATE_AND_RETURN_EXPR(exit_expr, sctx, loc, inExpr);
+  CREATE_AND_RETURN_EXPR(exit_expr, sctx, udf, loc, inExpr);
 }
 
 
 exit_catcher_expr* ExprManager::create_exit_catcher_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* inExpr,
     std::vector<expr*>& exitExprs)
 {
-  CREATE_AND_RETURN_EXPR(exit_catcher_expr, sctx, loc, inExpr, exitExprs);
+  CREATE_AND_RETURN_EXPR(exit_catcher_expr, sctx, udf, loc, inExpr, exitExprs);
 }
 
 
 flowctl_expr* ExprManager::create_flowctl_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     flowctl_expr::action action)
 {
-  CREATE_AND_RETURN_EXPR(flowctl_expr, sctx, loc, action);
+  CREATE_AND_RETURN_EXPR(flowctl_expr, sctx, udf, loc, action);
 }
 
 
 while_expr* ExprManager::create_while_expr(
-      static_context* sctx, const QueryLoc& loc, expr* body)
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc,
+    expr* body)
 {
-  CREATE_AND_RETURN_EXPR(while_expr, sctx, loc, body);
+  CREATE_AND_RETURN_EXPR(while_expr, sctx, udf, loc, body);
 }
 
 
 ////////////////////////////////////////////////////////////////////////////////
 
 relpath_expr* ExprManager::create_relpath_expr(
-     static_context* sctx,
-     const QueryLoc& loc)
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc)
 {
-  CREATE_AND_RETURN_EXPR(relpath_expr, sctx, loc);
+  CREATE_AND_RETURN_EXPR(relpath_expr, sctx, udf, loc);
 }
 
 
 axis_step_expr* ExprManager::create_axis_step_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc)
 {
-  CREATE_AND_RETURN_EXPR(axis_step_expr, sctx, loc);
+  CREATE_AND_RETURN_EXPR(axis_step_expr, sctx, udf, loc);
 }
 
 
 match_expr* ExprManager::create_match_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc)
 {
-  CREATE_AND_RETURN_EXPR(match_expr, sctx, loc);
+  CREATE_AND_RETURN_EXPR(match_expr, sctx, udf, loc);
 }
 
 
@@ -776,92 +778,105 @@
 dynamic_function_invocation_expr*
 ExprManager::create_dynamic_function_invocation_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* anExpr,
     const std::vector<expr*>& args)
 {
-  CREATE_AND_RETURN_EXPR(dynamic_function_invocation_expr, sctx, loc, anExpr, args);
+  CREATE_AND_RETURN_EXPR(dynamic_function_invocation_expr, sctx, udf, loc, anExpr, args);
 }
 
 
 function_item_expr* ExprManager::create_function_item_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const store::Item* aQName,
     function* f,
     uint32_t aArity)
 {
-  CREATE_AND_RETURN_EXPR(function_item_expr, sctx, loc, aQName, f, aArity);
+  CREATE_AND_RETURN_EXPR(function_item_expr, sctx, udf, loc, aQName, f, aArity);
 }
 
 
 function_item_expr* ExprManager::create_function_item_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc)
 {
-  CREATE_AND_RETURN_EXPR(function_item_expr, sctx, loc);
+  CREATE_AND_RETURN_EXPR(function_item_expr, sctx, udf, loc);
 }
 
 
 ftcontains_expr* ExprManager::create_ftcontains_expr(
     static_context* sctx,
+    user_function* udf,
     QueryLoc const& loc,
     expr* range,
     ftnode *ftselection,
     expr* ftignore)
 {
-  CREATE_AND_RETURN_EXPR(ftcontains_expr, sctx, loc, range, ftselection, ftignore);
+  CREATE_AND_RETURN_EXPR(ftcontains_expr, sctx, udf, loc, range, ftselection, ftignore);
 }
 
 
 ////////////////////////////////////////////////////////////////////////////////
 
 //this calls the static create_seq within fo_expr
-fo_expr* ExprManager::create_seq(static_context* sctx, const QueryLoc& loc)
+fo_expr* ExprManager::create_seq(
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc)
 {
   //TODO make fo_expr use this factory to generate everything
-  return fo_expr::create_seq(theCCB, sctx, loc);
+  return fo_expr::create_seq(theCCB, sctx, udf, loc);
 }
 
 
 fo_expr* ExprManager::create_fo_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f,
     expr* arg)
 {
-  CREATE_AND_RETURN_EXPR(fo_expr, sctx, loc, f, arg);
+  CREATE_AND_RETURN_EXPR(fo_expr, sctx, udf, loc, f, arg);
 }
 
 
 fo_expr* ExprManager::create_fo_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f,
     expr* arg1,
     expr* arg2)
 {
-  CREATE_AND_RETURN_EXPR(fo_expr, sctx, loc, f, arg1, arg2);
+  CREATE_AND_RETURN_EXPR(fo_expr, sctx, udf, loc, f, arg1, arg2);
 }
 
 
 fo_expr* ExprManager::create_fo_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f,
     const std::vector<expr*>& args)
 {
-  CREATE_AND_RETURN_EXPR(fo_expr, sctx, loc, f, args);
+  CREATE_AND_RETURN_EXPR(fo_expr, sctx, udf, loc, f, args);
 }
 
+
 fo_expr* ExprManager::create_fo_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f)
 {
 
-  CREATE_AND_RETURN_EXPR(fo_expr, sctx, loc, f);
+  CREATE_AND_RETURN_EXPR(fo_expr, sctx, udf, loc, f);
 }
+
 ////////////////////////////////////////////////////////////////////////////////
 
 for_clause* ExprManager::create_for_clause(
@@ -877,6 +892,7 @@
           sctx, theCCB, loc, varExpr, domainExpr, posVarExpr, scoreVarExpr, isOuter);
 }
 
+
 let_clause* ExprManager::create_let_clause(
     static_context* sctx,
     const QueryLoc& loc,
@@ -887,6 +903,7 @@
   CREATE_AND_RETURN(let_clause, sctx, theCCB, loc, varExpr, domainExpr, lazy);
 }
 
+
 window_clause* ExprManager::create_window_clause(
     static_context* sctx,
     const QueryLoc& loc,
@@ -901,16 +918,18 @@
           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)
+    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,
@@ -921,40 +940,54 @@
   CREATE_AND_RETURN(group_clause, sctx, theCCB,  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)
+    static_context* sctx,
+    const QueryLoc& loc,
+    bool stable,
+    const std::vector<OrderModifier>& modifiers,
+    const std::vector<expr*>& orderingExprs)
 {
   CREATE_AND_RETURN(orderby_clause, sctx, theCCB, loc, stable, modifiers, orderingExprs);
 }
 
+
 materialize_clause* ExprManager::create_materialize_clause(
-      static_context* sctx, const QueryLoc& loc)
+    static_context* sctx,
+    const QueryLoc& loc)
 {
   CREATE_AND_RETURN(materialize_clause, sctx, theCCB, loc);
 }
 
+
 count_clause* ExprManager::create_count_clause(
-      static_context* sctx, const QueryLoc& loc, var_expr* var)
+    static_context* sctx,
+    const QueryLoc& loc,
+    var_expr* var)
 {
   CREATE_AND_RETURN(count_clause, sctx, theCCB, loc, var);
 }
 
+
 where_clause* ExprManager::create_where_clause(
-      static_context* sctx, const QueryLoc& loc, expr* where)
+    static_context* sctx,
+    const QueryLoc& loc,
+    expr* where)
 {
   CREATE_AND_RETURN(where_clause, sctx, theCCB, loc, where);
 }
 
+
 flwor_expr* ExprManager::create_flwor_expr(
-      static_context* sctx, const QueryLoc& loc, bool general)
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc,
+    bool general)
 {
-  CREATE_AND_RETURN_EXPR(flwor_expr, sctx, loc, general);
+  CREATE_AND_RETURN_EXPR(flwor_expr, sctx, udf, loc, general);
 }
 
+
 pragma* ExprManager::create_pragma(
     const store::Item_t& name,
     const zstring& lit)

=== modified file 'src/compiler/expression/expr_manager.h'
--- src/compiler/expression/expr_manager.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/expr_manager.h	2012-10-09 10:29:25 +0000
@@ -31,6 +31,7 @@
 
 class CompilerCB;
 
+
 class ExprManager
 {
 private:
@@ -75,6 +76,7 @@
 public:
   if_expr* create_if_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* cond_expr,
       expr* then_expr,
@@ -82,12 +84,14 @@
 
   order_expr* create_order_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       order_expr::order_type_t,
       expr*);
 
   validate_expr* create_validate_expr(
       static_context*,
+      user_function* udf,
       const QueryLoc&,
       ParseConstants::validation_mode_t,
       const store::Item_t& aTypeName,
@@ -96,12 +100,14 @@
 
   cast_expr* create_cast_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*,
       xqtref_t);
 
   treat_expr* create_treat_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* input,
       const xqtref_t& type,
@@ -112,6 +118,7 @@
 
   promote_expr* create_promote_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* input,
       const xqtref_t& type,
@@ -120,12 +127,14 @@
 
   castable_expr* create_castable_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*,
       xqtref_t);
 
   instanceof_expr* create_instanceof_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*,
       xqtref_t,
@@ -133,6 +142,7 @@
 
   name_cast_expr* create_name_cast_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*,
       const namespace_context*,
@@ -140,12 +150,14 @@
 
   doc_expr* create_doc_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr* content,
       bool copyNodes);
 
   elem_expr* create_elem_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr* qnameExpr,
       expr* attrs,
@@ -155,6 +167,7 @@
 
   elem_expr* create_elem_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr* qnameExpr,
       expr* content,
@@ -163,64 +176,76 @@
 
   attr_expr* create_attr_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* aQNameExpr,
       expr* aValueExpr);
 
   text_expr* create_text_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       text_expr::text_constructor_type,
       expr*);
 
   pi_expr* create_pi_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*,
       expr*);
 
   const_expr* create_const_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       zstring& sval);
 
   const_expr* create_const_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       const std::string& sval);
 
   const_expr* create_const_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       const char* sval);
 
   const_expr* create_const_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       xs_integer);
 
   const_expr* create_const_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       xs_decimal);
 
   const_expr* create_const_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       xs_double);
 
   const_expr* create_const_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       xs_boolean);
 
   const_expr* create_const_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       store::Item_t);
 
   const_expr* create_const_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       const char* ns,
       const char* pre,
@@ -228,10 +253,12 @@
 
   extension_expr* create_extension_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&);
 
   extension_expr* create_extension_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*);
 
@@ -239,23 +266,29 @@
 
   trycatch_expr* create_trycatch_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr* tryExpr);
 
   wrapper_expr* create_wrapper_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* wrapped);
 
+#if 0
   function_trace_expr* create_function_trace_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* aChild);
+#endif
 
   function_trace_expr* create_function_trace_expr(expr* aExpr);
 
   eval_expr* create_eval_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* e,
       expr_script_kind_t scriptingKind,
@@ -264,6 +297,7 @@
 #ifdef ZORBA_WITH_DEBUGGER
   debugger_expr* create_debugger_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* aChild,
       namespace_context* nsCtx,
@@ -274,11 +308,12 @@
 
   var_expr* create_var_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       var_expr::var_kind k,
       store::Item* name);
 
-  var_expr* create_var_expr(const var_expr& source);
+  var_expr* create_var_expr(user_function* udf, const var_expr& source);
 
 ////////////////////////////////////////////////////////////////////////////////
 
@@ -286,17 +321,20 @@
 
   json_array_expr* create_json_array_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* content);
 
   json_object_expr* create_json_object_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* content,
       bool accumulate);
 
   json_direct_object_expr* create_json_direct_object_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       std::vector<expr*>& names,
       std::vector<expr*>& values);
@@ -307,6 +345,7 @@
 
   insert_expr* create_insert_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       store::UpdateConsts::InsertType,
       expr* aSourceExpr,
@@ -314,11 +353,13 @@
 
   delete_expr* create_delete_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*);
 
   replace_expr* create_replace_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       store::UpdateConsts::ReplaceType aType,
       expr*,
@@ -326,6 +367,7 @@
 
   rename_expr* create_rename_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*,
       expr*);
@@ -334,10 +376,12 @@
 
   transform_expr* create_transform_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc);
 
   block_expr* create_block_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       bool allowLastUpdating,
       std::vector<expr*>& seq,
@@ -345,61 +389,79 @@
 
   apply_expr* create_apply_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* inExpr,
       bool discardXDM);
 
   var_decl_expr* create_var_decl_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       var_expr* varExpr,
       expr* initExpr);
 
   var_set_expr* create_var_set_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       var_expr* varExpr,
       expr* setExpr);
 
   exit_expr* create_exit_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* inExpr);
 
   exit_catcher_expr* create_exit_catcher_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* inExpr,
       std::vector<expr*>& exitExprs);
 
   flowctl_expr* create_flowctl_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       flowctl_expr::action action);
 
   while_expr* create_while_expr(
       static_context* sctx,
+      user_function* udf,
       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&);
+  relpath_expr* create_relpath_expr(
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc& loc);
+
+  axis_step_expr* create_axis_step_expr(
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&);
+
+  match_expr* create_match_expr(
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&);
 
 ////////////////////////////////////////////////////////////////////////////////
 
   dynamic_function_invocation_expr* create_dynamic_function_invocation_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* anExpr,
       const std::vector<expr*>& args);
 
   function_item_expr* create_function_item_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       const store::Item* aQName,
       function* f,
@@ -407,10 +469,12 @@
 
   function_item_expr* create_function_item_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc);
 
   ftcontains_expr* create_ftcontains_expr(
       static_context*,
+      user_function* udf,
       QueryLoc const&,
       expr* range,
       ftnode *ftselection,
@@ -419,16 +483,21 @@
 ////////////////////////////////////////////////////////////////////////////////
 
   //this calls the static create_seq within fo_expr
-  fo_expr* create_seq(static_context* sctx, const QueryLoc &);
+  fo_expr* create_seq(
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc &);
 
   fo_expr* create_fo_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       const function* f,
       expr* arg);
 
   fo_expr* create_fo_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       const function* f,
       expr* arg1,
@@ -436,12 +505,14 @@
 
   fo_expr* create_fo_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       const function* f,
       const std::vector<expr*>& args);
 
   fo_expr* create_fo_expr(
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f);
 
@@ -510,6 +581,7 @@
 
   flwor_expr* create_flwor_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       bool general);
  
@@ -524,17 +596,20 @@
 
 json_array_expr* create_json_array_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* content);
 
 json_object_expr* create_json_object_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* content,
       bool accumulate);
 
 json_direct_object_expr* create_json_direct_object_expr(
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       std::vector<expr*>& names,
       std::vector<expr*>& values);

=== modified file 'src/compiler/expression/flwor_expr.cpp'
--- src/compiler/expression/flwor_expr.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/flwor_expr.cpp	2012-10-09 10:29:25 +0000
@@ -107,6 +107,7 @@
       {
         theDomainExpr = theCCB->theEM->
         create_treat_expr(theDomainExpr->get_sctx(),
+                          theDomainExpr->get_udf(),
                           theDomainExpr->get_loc(),
                           theDomainExpr,
                           varType,
@@ -173,11 +174,13 @@
                          *declaredType));
           }
 
-          domainExpr = theCCB->theEM->create_treat_expr(sctx,
-                                            loc,
-                                            domainExpr,
-                                            declaredType,
-                                            TreatIterator::TYPE_MATCH);
+          domainExpr = theCCB->theEM->
+          create_treat_expr(sctx,
+                            domainExpr->get_udf(),
+                            loc,
+                            domainExpr,
+                            declaredType,
+                            TreatIterator::TYPE_MATCH);
 
           set_expr(domainExpr);
         }
@@ -225,18 +228,18 @@
 }
 
 
-flwor_clause* for_clause::clone(expr::substitution_t& subst) const
+flwor_clause* for_clause::clone(user_function* udf, expr::substitution_t& subst) const
 {
-  expr* domainCopy = theDomainExpr->clone(subst);
+  expr* domainCopy = theDomainExpr->clone(udf, subst);
 
-  var_expr* varCopy = theCCB->theEM->create_var_expr(*theVarExpr);
+  var_expr* varCopy = theCCB->theEM->create_var_expr(udf, *theVarExpr);
   subst[theVarExpr] = varCopy;
 
   var_expr* posvarCopy = NULL;
   var_expr* pos_var_ptr = thePosVarExpr;
   if (pos_var_ptr)
   {
-    posvarCopy = theCCB->theEM->create_var_expr(*pos_var_ptr);
+    posvarCopy = theCCB->theEM->create_var_expr(udf, *pos_var_ptr);
     subst[pos_var_ptr] = posvarCopy;
   }
 
@@ -244,17 +247,17 @@
   var_expr* score_var_ptr = theScoreVarExpr;
   if (score_var_ptr)
   {
-    scorevarCopy = theCCB->theEM->create_var_expr(*score_var_ptr);
+    scorevarCopy = theCCB->theEM->create_var_expr(udf, *score_var_ptr);
     subst[score_var_ptr] = scorevarCopy;
   }
 
   return theCCB->theEM->create_for_clause(theContext,
-                        get_loc(),
-                        varCopy,
-                        domainCopy,
-                        posvarCopy,
-                        scorevarCopy,
-                        theAllowingEmpty);
+                                          get_loc(),
+                                          varCopy,
+                                          domainCopy,
+                                          posvarCopy,
+                                          scorevarCopy,
+                                          theAllowingEmpty);
 }
 
 
@@ -298,11 +301,13 @@
           ERROR_PARAMS(ZED(BadType_23o), *domainType, ZED(NoTreatAs_4), *declaredType));
         }
 
-        domainExpr = theCCB->theEM->create_treat_expr(sctx,
-                                    loc,
-                                    domainExpr,
-                                    declaredType,
-                                    TreatIterator::TYPE_MATCH);
+        domainExpr = theCCB->theEM->
+        create_treat_expr(sctx,
+                          domainExpr->get_udf(),
+                          loc,
+                          domainExpr,
+                          declaredType,
+                          TreatIterator::TYPE_MATCH);
 
         set_expr(domainExpr);
       }
@@ -332,11 +337,11 @@
 }
 
 
-flwor_clause* let_clause::clone(expr::substitution_t& subst) const
+flwor_clause* let_clause::clone(user_function* udf, expr::substitution_t& subst) const
 {
-  expr* domainCopy = theDomainExpr->clone(subst);
+  expr* domainCopy = theDomainExpr->clone(udf, subst);
 
-  var_expr* varCopy = theCCB->theEM->create_var_expr(*theVarExpr);
+  var_expr* varCopy = theCCB->theEM->create_var_expr(udf, *theVarExpr);
   subst[theVarExpr] = varCopy;
 
 #if 0
@@ -350,10 +355,10 @@
 #endif
 
   return theCCB->theEM->create_let_clause(theContext,
-                        get_loc(),
-                        varCopy,
-                        domainCopy,
-                        theLazyEval);
+                                          get_loc(),
+                                          varCopy,
+                                          domainCopy,
+                                          theLazyEval);
 }
 
 
@@ -403,6 +408,7 @@
       {
         domainExpr = theCCB->theEM->
         create_treat_expr(sctx,
+                          domainExpr->get_udf(),
                           loc,
                           domainExpr,
                           varType,
@@ -441,21 +447,23 @@
 }
 
 
-flwor_clause* window_clause::clone(expr::substitution_t& subst) const
+flwor_clause* window_clause::clone(
+    user_function* udf,
+    expr::substitution_t& subst) const
 {
-  expr* domainCopy = theDomainExpr->clone(subst);
+  expr* domainCopy = theDomainExpr->clone(udf, subst);
 
-  var_expr* varCopy = theCCB->theEM->create_var_expr(*theVarExpr);
+  var_expr* varCopy = theCCB->theEM->create_var_expr(udf, *theVarExpr);
   subst[theVarExpr] = varCopy;
 
   flwor_wincond* cloneStartCond = NULL;
   flwor_wincond* cloneStopCond = NULL;
 
   if (theWinStartCond != NULL)
-    cloneStartCond = theWinStartCond->clone(subst);
+    cloneStartCond = theWinStartCond->clone(udf, subst);
 
   if (theWinStopCond != NULL)
-    cloneStopCond = theWinStopCond->clone(subst);
+    cloneStopCond = theWinStopCond->clone(udf, subst);
 
   return theCCB->theEM->create_window_clause(theContext,
                                              get_loc(),
@@ -493,15 +501,17 @@
 
     xqtref_t condType = theCondExpr->get_return_type();
 
-    if(!TypeOps::is_equal(tm,
+    if (!TypeOps::is_equal(tm,
                           *condType,
                           *GENV_TYPESYSTEM.BOOLEAN_TYPE_ONE,
                           theCondExpr->get_loc()))
     {
-      theCondExpr = theCCB->theEM->create_fo_expr(theCondExpr->get_sctx(),
-                                theCondExpr->get_loc(),
-                                GET_BUILTIN_FUNCTION(FN_BOOLEAN_1),
-                                theCondExpr);
+      theCondExpr = theCCB->theEM->
+      create_fo_expr(theCondExpr->get_sctx(),
+                     theCondExpr->get_udf(),
+                     theCondExpr->get_loc(),
+                     GET_BUILTIN_FUNCTION(FN_BOOLEAN_1),
+                     theCondExpr);
     }
   }
 }
@@ -514,14 +524,15 @@
 
 
 flwor_wincond::vars::vars()
-:
-posvar(NULL),
-curr(NULL),
-prev(NULL),
-next(NULL)
+  :
+  posvar(NULL),
+  curr(NULL),
+  prev(NULL),
+  next(NULL)
 {
 }
 
+
 flwor_wincond::vars::~vars()
 {
 //  set_flwor_clause(NULL);
@@ -539,33 +550,34 @@
 
 void flwor_wincond::vars::clone(
     ExprManager* mgr,
+    user_function* udf,
     flwor_wincond::vars& cloneVars,
     expr::substitution_t& subst) const
 {
   if (posvar != NULL)
   {
-    var_expr* varCopy = mgr->create_var_expr(*posvar);
+    var_expr* varCopy = mgr->create_var_expr(udf, *posvar);
     subst[posvar] = varCopy;
     cloneVars.posvar = varCopy;
   }
 
   if (curr != NULL)
   {
-    var_expr* varCopy = mgr->create_var_expr(*curr);
+    var_expr* varCopy = mgr->create_var_expr(udf, *curr);
     subst[curr] = varCopy;
     cloneVars.curr = varCopy;
   }
 
   if (prev != NULL)
   {
-    var_expr* varCopy = mgr->create_var_expr(*prev);
+    var_expr* varCopy = mgr->create_var_expr(udf, *prev);
     subst[prev] = varCopy;
     cloneVars.prev = varCopy;
   }
 
   if (next != NULL)
   {
-    var_expr* varCopy = mgr->create_var_expr(*next);
+    var_expr* varCopy = mgr->create_var_expr(udf, *next);
     subst[next] = varCopy;
     cloneVars.next = varCopy;
   }
@@ -579,21 +591,23 @@
 }
 
 
-flwor_wincond* flwor_wincond::clone(expr::substitution_t& subst) const
+flwor_wincond* flwor_wincond::clone(
+    user_function* udf,
+    expr::substitution_t& subst) const
 {
   flwor_wincond::vars cloneInVars;
   flwor_wincond::vars cloneOutVars;
 
-  theInputVars.clone(theCCB->theEM, cloneInVars, subst);
-  theOutputVars.clone(theCCB->theEM, cloneOutVars, subst);
+  theInputVars.clone(theCCB->theEM, udf, cloneInVars, subst);
+  theOutputVars.clone(theCCB->theEM, udf, cloneOutVars, subst);
 
-  expr* cloneCondExpr = theCondExpr->clone(subst);
+  expr* cloneCondExpr = theCondExpr->clone(udf, subst);
 
   return theCCB->theEM->create_flwor_wincond(NULL,
-                           theIsOnly,
-                           cloneInVars,
-                           cloneOutVars,
-                           cloneCondExpr);
+                                             theIsOnly,
+                                             cloneInVars,
+                                             cloneOutVars,
+                                             cloneCondExpr);
 }
 
 
@@ -663,7 +677,9 @@
 }
 
 
-flwor_clause* group_clause::clone(expr::substitution_t& subst) const
+flwor_clause* group_clause::clone(
+    user_function* udf,
+    expr::substitution_t& subst) const
 {
   csize numGroupVars = theGroupVars.size();
   csize numNonGroupVars = theNonGroupVars.size();
@@ -680,23 +696,29 @@
 
   for (csize i = 0; i < numGroupVars; ++i)
   {
-    cloneGroupVars[i].first = theGroupVars[i].first->clone(subst);
-    cloneGroupVars[i].second = exprMgr->create_var_expr(*theGroupVars[i].second);
+    cloneGroupVars[i].first = theGroupVars[i].first->clone(udf, subst);
+
+    cloneGroupVars[i].second = exprMgr->
+    create_var_expr(udf, *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 = exprMgr->create_var_expr(*theNonGroupVars[i].second);
+    cloneNonGroupVars[i].first = theNonGroupVars[i].first->clone(udf, subst);
+
+    cloneNonGroupVars[i].second = exprMgr->
+    create_var_expr(udf, *theNonGroupVars[i].second);
+
     subst[theNonGroupVars[i].second] = cloneNonGroupVars[i].second;
   }
 
   return theCCB->theEM->create_group_clause(theContext,
-                          get_loc(),
-                          cloneGroupVars,
-                          cloneNonGroupVars,
-                          theCollations);
+                                            get_loc(),
+                                            cloneGroupVars,
+                                            cloneNonGroupVars,
+                                            theCollations);
 }
 
 
@@ -726,7 +748,9 @@
 }
 
 
-flwor_clause* orderby_clause::clone(expr::substitution_t& subst) const
+flwor_clause* orderby_clause::clone(
+    user_function* udf,
+    expr::substitution_t& subst) const
 {
   csize numColumns = num_columns();
 
@@ -734,14 +758,14 @@
 
   for (csize i = 0; i < numColumns; ++i)
   {
-    cloneExprs[i] = theOrderingExprs[i]->clone(subst);
+    cloneExprs[i] = theOrderingExprs[i]->clone(udf, subst);
   }
 
   return theCCB->theEM->create_orderby_clause(theContext,
-                            get_loc(),
-                            theStableOrder,
-                            theModifiers,
-                            cloneExprs);
+                                              get_loc(),
+                                              theStableOrder,
+                                              theModifiers,
+                                              cloneExprs);
 }
 
 
@@ -758,7 +782,9 @@
 }
 
 
-flwor_clause* materialize_clause::clone(expr::substitution_t& subst) const
+flwor_clause* materialize_clause::clone(
+    user_function* udf,
+    expr::substitution_t& subst) const
 {
   // we will reach here under the following scenario:
   // 1. We do plan seriazation
@@ -792,11 +818,13 @@
 }
 
 
-flwor_clause* count_clause::clone(expr::substitution_t& subst) const
+flwor_clause* count_clause::clone(
+    user_function* udf,
+    expr::substitution_t& subst) const
 {
   ExprManager* exprMgr = theVarExpr->get_ccb()->theEM;
 
-  var_expr* cloneVar = exprMgr->create_var_expr(*theVarExpr);
+  var_expr* cloneVar = exprMgr->create_var_expr(udf, *theVarExpr);
   subst[theVarExpr] = cloneVar;
 
   return theCCB->theEM->create_count_clause(theContext, get_loc(), cloneVar);
@@ -825,9 +853,11 @@
 }
 
 
-flwor_clause* where_clause::clone(expr::substitution_t& subst) const
+flwor_clause* where_clause::clone(
+    user_function* udf,
+    expr::substitution_t& subst) const
 {
-  expr* cloneExpr = theWhereExpr->clone(subst);
+  expr* cloneExpr = theWhereExpr->clone(udf, subst);
 
   return theCCB->theEM->create_where_clause(theContext, get_loc(), cloneExpr);
 }
@@ -839,10 +869,11 @@
 flwor_expr::flwor_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     bool general)
   :
-  expr(ccb, sctx, loc, (general ? gflwor_expr_kind : flwor_expr_kind)),
+  expr(ccb, sctx, udf, loc, (general ? gflwor_expr_kind : flwor_expr_kind)),
   theIsGeneral(general),
   theHasSequentialClauses(false),
   theReturnExpr(NULL)
@@ -1167,27 +1198,5 @@
 }
 
 
-/*******************************************************************************
-
-********************************************************************************/
-expr* flwor_expr::cloneImpl(substitution_t& subst) const
-{
-  ulong numClauses = num_clauses();
-
-  flwor_expr* cloneFlwor = theCCB->theEM->create_flwor_expr(theSctx, get_loc(), theIsGeneral);
-
-  for (ulong i = 0; i < numClauses; ++i)
-  {
-    flwor_clause* cloneClause = theClauses[i]->clone(subst);
-
-    cloneFlwor->add_clause(cloneClause, false);
-  }
-
-  cloneFlwor->set_return_expr(theReturnExpr->clone(subst));
-
-  return cloneFlwor;
-}
-
-
 } // namespace zorba
 /* vim:set et sw=2 ts=2: */

=== modified file 'src/compiler/expression/flwor_expr.h'
--- src/compiler/expression/flwor_expr.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/flwor_expr.h	2012-10-09 10:29:25 +0000
@@ -105,7 +105,9 @@
 
   virtual var_expr* get_score_var() const { return NULL; }
 
-  virtual flwor_clause* clone(expr::substitution_t& substitution) const = 0;
+  virtual flwor_clause* clone(
+      user_function* udf,
+      expr::substitution_t& substitution) const = 0;
 };
 
 
@@ -207,7 +209,7 @@
 
   void set_score_var(var_expr* v);
 
-  flwor_clause* clone(expr::substitution_t& substitution) const;
+  flwor_clause* clone(user_function* udf, expr::substitution_t& substitution) const;
 
   std::ostream& put(std::ostream&) const;
 };
@@ -247,7 +249,7 @@
 
   bool lazyEval() const { return theLazyEval; }
 
-  flwor_clause* clone(expr::substitution_t& substitution) const;
+  flwor_clause* clone(user_function* udf, expr::substitution_t& substitution) const;
 
   std::ostream& put(std::ostream&) const;
 };
@@ -303,7 +305,7 @@
 
   bool lazyEval() const { return theLazyEval; }
 
-  flwor_clause* clone(expr::substitution_t& substitution) const;
+  flwor_clause* clone(user_function* udf, expr::substitution_t& substitution) const;
 
   std::ostream& put(std::ostream&) const;
 };
@@ -354,10 +356,16 @@
     var_expr* next;
 
     vars();
+
     ~vars();
+
     void set_flwor_clause(flwor_clause* c);
 
-    void clone(ExprManager* mgr, vars& cloneVars, expr::substitution_t& subst) const;
+    void clone(
+      ExprManager* mgr,
+      user_function* udf,
+      vars& cloneVars,
+      expr::substitution_t& subst) const;
 
     std::ostream& put(std::ostream&) const;
   };
@@ -394,7 +402,7 @@
 
   void set_flwor_clause(flwor_clause *);
 
-  flwor_wincond* clone(expr::substitution_t& substitution) const;
+  flwor_wincond* clone(user_function* udf, expr::substitution_t& substitution) const;
 
   std::ostream& put(std::ostream&) const;
 };
@@ -484,7 +492,7 @@
 
   expr* get_input_for_nongroup_var(const var_expr* var);
 
-  flwor_clause* clone(expr::substitution_t& substitution) const;
+  flwor_clause* clone(user_function* udf, expr::substitution_t& substitution) const;
 
   std::ostream& put(std::ostream&) const;
 };
@@ -552,7 +560,7 @@
 
   void set_column_expr(csize i, expr* e) { theOrderingExprs[i] = e; }
 
-  flwor_clause* clone(expr::substitution_t& substitution) const;
+  flwor_clause* clone(user_function* udf, expr::substitution_t& substitution) const;
 
   std::ostream& put(std::ostream&) const;
 };
@@ -572,7 +580,7 @@
   materialize_clause(static_context* sctx, CompilerCB* ccb, const QueryLoc& loc);
 
 public:
-  flwor_clause* clone(expr::substitution_t& substitution) const;
+  flwor_clause* clone(user_function* udf, expr::substitution_t& substitution) const;
 
   std::ostream& put(std::ostream&) const;
 };
@@ -597,7 +605,7 @@
 
   var_expr* get_var() const { return theVarExpr; }
 
-  flwor_clause* clone(expr::substitution_t& substitution) const;
+  flwor_clause* clone(user_function* udf, expr::substitution_t& substitution) const;
 };
 
 
@@ -619,7 +627,7 @@
 
   void set_expr(expr* where);
 
-  flwor_clause* clone(expr::substitution_t& substitution) const;
+  flwor_clause* clone(user_function* udf, expr::substitution_t& substitution) const;
 };
 
 
@@ -665,7 +673,12 @@
   expr          * theReturnExpr;
 
 protected:
-  flwor_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, bool general);
+  flwor_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc& loc,
+      bool general);
 
 public:
   bool is_general() const { return theIsGeneral; }
@@ -704,8 +717,6 @@
 
   void get_vars_defined(std::vector<var_expr*>& varExprs) const;
 
-  expr* cloneImpl(substitution_t& substitution) const;
-
   // The following 5 methods are for the simple flwor only. They should be
   // removed eventually.
   expr* get_where() const;

=== modified file 'src/compiler/expression/fo_expr.cpp'
--- src/compiler/expression/fo_expr.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/fo_expr.cpp	2012-10-09 10:29:25 +0000
@@ -55,11 +55,15 @@
   UnionExpr, and IntersectExceptExpr.
 ********************************************************************************/
 
-fo_expr* fo_expr::create_seq(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc)
+fo_expr* fo_expr::create_seq(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc)
 {
   function* f = BuiltinFunctionLibrary::getFunction(FunctionConsts::OP_CONCATENATE_N);
 
-  std::auto_ptr<fo_expr> fo(ccb->theEM->create_fo_expr(sctx, loc, f));
+  std::auto_ptr<fo_expr> fo(ccb->theEM->create_fo_expr(sctx, udf, loc, f));
 
   return fo.release();
 }
@@ -68,10 +72,11 @@
 fo_expr::fo_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f)
   :
-  expr(ccb, sctx, loc, fo_expr_kind),
+  expr(ccb, sctx, udf, loc, fo_expr_kind),
   theFunction(const_cast<function*>(f))
 {
   // This method is private and it is to be used only by the clone method
@@ -83,11 +88,12 @@
 fo_expr::fo_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f,
     expr* arg)
   :
-  expr(ccb, sctx, loc, fo_expr_kind),
+  expr(ccb, sctx, udf, loc, fo_expr_kind),
   theFunction(const_cast<function*>(f))
 {
   assert(f != NULL);
@@ -101,12 +107,13 @@
 fo_expr::fo_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f,
     expr* arg1,
     expr* arg2)
   :
-  expr(ccb, sctx, loc, fo_expr_kind),
+  expr(ccb, sctx, udf, loc, fo_expr_kind),
   theFunction(const_cast<function*>(f))
 {
   assert(f != NULL);
@@ -121,11 +128,12 @@
 fo_expr::fo_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f,
     const std::vector<expr*>& args)
   :
-  expr(ccb, sctx, loc, fo_expr_kind),
+  expr(ccb, sctx, udf, loc, fo_expr_kind),
   theArgs(args),
   theFunction(const_cast<function*>(f))
 {
@@ -273,29 +281,6 @@
 }
 
 
-expr* fo_expr::cloneImpl(substitution_t& subst) const
-{
-  if (get_func()->getKind() == FunctionConsts::STATIC_COLLECTIONS_DML_COLLECTION_1)
-  {
-    expr::subst_iter_t i = subst.find(this);
-
-    if (i != subst.end())
-      return i->second;
-  }
-
-  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));
-
-  fo->theScriptingKind  = theScriptingKind;
-
-  return fo.release();
-}
-
-
 }
 
 /* vim:set et sw=2 ts=2: */

=== modified file 'src/compiler/expression/fo_expr.h'
--- src/compiler/expression/fo_expr.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/fo_expr.h	2012-10-09 10:29:25 +0000
@@ -45,12 +45,24 @@
 public:
 
 protected:
-  static fo_expr* create_seq(CompilerCB* ccb, static_context* sctx, const QueryLoc&);
+  static fo_expr* create_seq(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&);
 
 protected:
   fo_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc,
+    const function* f);
+
+  fo_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f,
     expr* arg);
@@ -58,6 +70,7 @@
   fo_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f,
     expr* arg1,
@@ -66,6 +79,7 @@
   fo_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const function* f,
     const std::vector<expr*>& args);
@@ -95,8 +109,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;

=== modified file 'src/compiler/expression/ft_expr.cpp'
--- src/compiler/expression/ft_expr.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/ft_expr.cpp	2012-10-09 10:29:25 +0000
@@ -35,12 +35,13 @@
 ftcontains_expr::ftcontains_expr(
   CompilerCB* ccb,
   static_context* sctx,
+  user_function* udf,
   QueryLoc const &loc,
   expr* range,
   ftnode *ftselection,
   expr* ftignore
 ) :
-  expr(ccb, sctx, loc, ft_expr_kind ),
+  expr(ccb, sctx, udf, loc, ft_expr_kind ),
   range_( range ),
   ftselection_( ftselection ),
   ftignore_( ftignore )
@@ -50,6 +51,7 @@
   compute_scripting_kind();
 }
 
+
 void ftcontains_expr::accept( expr_visitor &v ) {
   if ( v.begin_visit( *this ) ) {
     EV_ACCEPT( range_, v );
@@ -59,16 +61,9 @@
   v.end_visit( *this );
 }
 
-expr* ftcontains_expr::cloneImpl( substitution_t &s ) const {
-  return theCCB->theEM->create_ftcontains_expr(
-    theSctx, get_loc(),
-    range_->clone( s ),
-    ftselection_->clone( s ).release(),
-    ftignore_ == NULL ? 0 : ftignore_->clone( s )
-  );
-}
 
-void ftcontains_expr::compute_scripting_kind() {
+void ftcontains_expr::compute_scripting_kind() 
+{
   checkSimpleExpr(range_);
 
   theScriptingKind = SIMPLE_EXPR;

=== modified file 'src/compiler/expression/ft_expr.h'
--- src/compiler/expression/ft_expr.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/ft_expr.h	2012-10-09 10:29:25 +0000
@@ -29,6 +29,7 @@
  */
 class ftcontains_expr : public expr
 {
+  friend class expr;
   friend class ExprIterator;
   friend class ExprManager;
 
@@ -36,6 +37,7 @@
   ftcontains_expr(
     CompilerCB* ccb,
     static_context*,
+    user_function*,
     QueryLoc const&,
     expr* range,
     ftnode *ftselection,
@@ -43,8 +45,6 @@
   );
 
 public:
-  expr* cloneImpl( substitution_t& ) const;
-
   void compute_scripting_kind();
 
   expr* get_range() const { return range_; }

=== modified file 'src/compiler/expression/ftnode.cpp'
--- src/compiler/expression/ftnode.cpp	2012-09-19 21:16:15 +0000
+++ src/compiler/expression/ftnode.cpp	2012-10-09 10:29:25 +0000
@@ -171,37 +171,60 @@
 ///////////////////////////////////////////////////////////////////////////////
 
 template<typename PointerType>
-inline PointerType clone_ptr( PointerType p, expr::substitution_t &s ) {
-  return static_cast<PointerType>( p->clone( s ).release() );
+inline PointerType clone_ptr(
+    PointerType p,
+    user_function* udf,
+    expr::substitution_t &s )
+{
+  return static_cast<PointerType>( p->clone( udf, s ).release() );
 }
 
+
 template<>
-inline expr* clone_ptr( expr* p, expr::substitution_t &s ) {
-  return static_cast<expr*>( p->clone( s ) );
+inline expr* clone_ptr( expr* p, user_function* udf, expr::substitution_t &s ) {
+  return static_cast<expr*>( p->clone(udf, s) );
 }
 
+
 template<class RCHandleValueType>
-inline RCHandleValueType* clone_ptr( rchandle<RCHandleValueType> const &p,
-                                     expr::substitution_t &s ) {
-  return static_cast<RCHandleValueType*>( p->clone( s ).release() );
+inline RCHandleValueType* clone_ptr( 
+    rchandle<RCHandleValueType> const &p,
+    user_function* udf,
+    expr::substitution_t &s )
+{
+  return static_cast<RCHandleValueType*>( p->clone(udf, s).release() );
 }
 
+
 template<typename PointerType>
-inline PointerType clone_ptr_if( PointerType p, expr::substitution_t &s ) {
-  return p ? clone_ptr( p, s ) : nullptr;
+inline PointerType clone_ptr_if(
+    PointerType p,
+    user_function* udf,
+    expr::substitution_t &s )
+{
+  return p ? clone_ptr( p, udf, s ) : nullptr;
 }
 
+
 template<class RCHandleValueType>
-inline RCHandleValueType* clone_ptr_if( rchandle<RCHandleValueType> const &p,
-                                        expr::substitution_t &s ) {
-  return p.isNull() ? nullptr : clone_ptr( p, s );
+inline RCHandleValueType* clone_ptr_if(
+    rchandle<RCHandleValueType> const &p,
+    user_function* udf,
+    expr::substitution_t &s )
+{
+  return p.isNull() ? nullptr : clone_ptr( p, udf, s );
 }
 
+
 template<class ContainerType>
-void clone_list( ContainerType const &from, ContainerType *to,
-                 expr::substitution_t &s ) {
+void clone_list(
+    ContainerType const &from,
+    ContainerType *to,
+    user_function* udf,
+    expr::substitution_t &s )
+{
   FOR_EACH( typename ContainerType, i, from )
-    to->push_back( clone_ptr( *i, s ) );
+    to->push_back( clone_ptr( *i, udf, s ) );
 }
 
 ///////////////////////////////////////////////////////////////////////////////
@@ -221,9 +244,9 @@
   END_VISIT( v );
 }
 
-ftnode_t ftand::clone( expr::substitution_t &s ) const {
+ftnode_t ftand::clone(user_function* udf, expr::substitution_t &s ) const {
   ftnode_list_t copy;
-  clone_list( get_node_list(), &copy, s );
+  clone_list( get_node_list(), &copy, udf, s );
   return new ftand( get_loc(), copy );
 }
 
@@ -251,7 +274,7 @@
   END_VISIT( v );
 }
 
-ftnode_t ftcase_option::clone( expr::substitution_t& ) const {
+ftnode_t ftcase_option::clone(user_function* udf, expr::substitution_t& ) const {
   return new ftcase_option( get_loc(), mode_ );
 }
 
@@ -279,7 +302,7 @@
   END_VISIT( v );
 }
 
-ftnode_t ftcontent_filter::clone( expr::substitution_t &s ) const {
+ftnode_t ftcontent_filter::clone(user_function* udf,  expr::substitution_t &s ) const {
   return new ftcontent_filter( get_loc(), mode_ );
 }
 
@@ -308,7 +331,7 @@
   END_VISIT( v );
 }
 
-ftnode_t ftdiacritics_option::clone( expr::substitution_t& ) const {
+ftnode_t ftdiacritics_option::clone(user_function* udf,  expr::substitution_t& ) const {
   return new ftdiacritics_option( get_loc(), mode_ );
 }
 
@@ -345,8 +368,8 @@
   END_VISIT( v );
 }
 
-ftnode_t ftdistance_filter::clone( expr::substitution_t &s ) const {
-  return new ftdistance_filter( get_loc(), clone_ptr_if( range_, s ), unit_ );
+ftnode_t ftdistance_filter::clone(user_function* udf,  expr::substitution_t &s ) const {
+  return new ftdistance_filter( get_loc(), clone_ptr_if( range_, udf, s ), unit_ );
 }
 
 ostream& ftdistance_filter::put( ostream &o ) const {
@@ -384,9 +407,9 @@
   END_VISIT( v );
 }
 
-ftnode_t ftextension_selection::clone( expr::substitution_t &s ) const {
+ftnode_t ftextension_selection::clone(user_function* udf,  expr::substitution_t &s ) const {
   return new ftextension_selection(
-    get_loc(), pragmas_, clone_ptr_if( ftselection_, s )
+             get_loc(), pragmas_, clone_ptr_if( ftselection_, udf, s )
   );
 }
 
@@ -418,7 +441,7 @@
   END_VISIT( v );
 }
 
-ftnode_t ftextension_option::clone( expr::substitution_t& ) const {
+ftnode_t ftextension_option::clone(user_function* udf,  expr::substitution_t& ) const {
   return new ftextension_option( get_loc(), qname_, val_ );
 }
 
@@ -475,7 +498,7 @@
   END_VISIT( v );
 }
 
-ftnode_t ftlanguage_option::clone( expr::substitution_t& ) const {
+ftnode_t ftlanguage_option::clone(user_function* udf,  expr::substitution_t& ) const {
   return new ftlanguage_option( get_loc(), lang_ );
 }
 
@@ -508,30 +531,28 @@
   END_VISIT( v );
 }
 
-ftnode_t ftmatch_options::clone( expr::substitution_t &s ) const {
+ftnode_t ftmatch_options::clone(user_function* udf,  expr::substitution_t &s ) const {
   unique_ptr<ftmatch_options> p( new ftmatch_options( get_loc() ) );
   if ( case_option_ )
-    p->set_case_option( clone_ptr( case_option_, s ) );
+    p->set_case_option( clone_ptr( case_option_, udf, s ) );
   if ( diacritics_option_ )
-    p->set_diacritics_option(
-      clone_ptr( diacritics_option_, s )
-    );
+    p->set_diacritics_option( clone_ptr( diacritics_option_, udf, s ) );
 
   FOR_EACH( ftextension_option_list_t, i, extension_options_ )
-    p->add_extension_option( clone_ptr( *i, s ) );
+    p->add_extension_option( clone_ptr( *i, udf, s ) );
   if ( current_extension_options_ != &extension_options_ )
     p->set_extension_options( current_extension_options_ );
 
   if ( language_option_ )
-    p->set_language_option( clone_ptr( language_option_, s ) );
+    p->set_language_option( clone_ptr( language_option_, udf, s ) );
   if ( stem_option_ )
-    p->set_stem_option( clone_ptr( stem_option_, s ) );
+    p->set_stem_option( clone_ptr( stem_option_, udf, s ) );
   if ( stop_word_option_ )
-    p->set_stop_word_option( clone_ptr( stop_word_option_, s ) );
+    p->set_stop_word_option( clone_ptr( stop_word_option_, udf, s ) );
   if ( thesaurus_option_ )
-    p->set_thesaurus_option( clone_ptr( thesaurus_option_, s ) );
+    p->set_thesaurus_option( clone_ptr( thesaurus_option_, udf, s ) );
   if ( wild_card_option_ )
-    p->set_wild_card_option( clone_ptr( wild_card_option_, s ) );
+    p->set_wild_card_option( clone_ptr( wild_card_option_, udf, s ) );
   return p.release();
 }
 
@@ -589,9 +610,9 @@
   END_VISIT( v );
 }
 
-ftnode_t ftmild_not::clone( expr::substitution_t &s ) const {
+ftnode_t ftmild_not::clone(user_function* udf,  expr::substitution_t &s ) const {
   ftnode_list_t copy;
-  clone_list( get_node_list(), &copy, s );
+  clone_list( get_node_list(), &copy, udf, s );
   return new ftmild_not( get_loc(), copy );
 }
 
@@ -631,9 +652,9 @@
   END_VISIT( v );
 }
 
-ftnode_t ftor::clone( expr::substitution_t &s ) const {
+ftnode_t ftor::clone(user_function* udf,  expr::substitution_t &s ) const {
   ftnode_list_t copy;
-  clone_list( get_node_list(), &copy, s );
+  clone_list( get_node_list(), &copy, udf, s );
   return new ftor( get_loc(), copy );
 }
 
@@ -657,7 +678,7 @@
   END_VISIT( v );
 }
 
-ftnode_t ftorder_filter::clone( expr::substitution_t &s ) const {
+ftnode_t ftorder_filter::clone(user_function* udf,  expr::substitution_t &s ) const {
   return new ftorder_filter( get_loc() );
 }
 
@@ -701,14 +722,14 @@
   END_VISIT( v );
 }
 
-ftnode_t ftprimary_with_options::clone( expr::substitution_t &s ) const {
+ftnode_t ftprimary_with_options::clone(user_function* udf,  expr::substitution_t &s ) const {
   unique_ptr<ftprimary_with_options> p(
     new ftprimary_with_options( get_loc() )
   );
-  p->set_match_options( clone_ptr( match_options_, s ) );
-  p->set_primary( clone_ptr( primary_, s ) );
+  p->set_match_options( clone_ptr( match_options_, udf, s ) );
+  p->set_primary( clone_ptr( primary_, udf, s ) );
   if ( weight_ )
-    p->set_weight( clone_ptr( weight_, s ) );
+    p->set_weight( clone_ptr( weight_, udf, s ) );
   return p.release();
 }
 
@@ -757,11 +778,11 @@
   END_VISIT( v );
 }
 
-ftnode_t ftrange::clone( expr::substitution_t &s ) const {
+ftnode_t ftrange::clone(user_function* udf,  expr::substitution_t &s ) const {
   return new ftrange(
     get_loc(), mode_,
-    clone_ptr( expr1_, s ),
-    clone_ptr_if( expr2_, s )
+    clone_ptr( expr1_, udf, s ),
+    clone_ptr_if( expr2_, udf, s )
   );
   // TODO: do PlanIter_t's have to be cloned?
 }
@@ -796,7 +817,7 @@
   END_VISIT( v );
 }
 
-ftnode_t ftscope_filter::clone( expr::substitution_t &s ) const {
+ftnode_t ftscope_filter::clone(user_function* udf,  expr::substitution_t &s ) const {
   return new ftscope_filter( get_loc(), scope_, unit_ );
 }
 
@@ -853,8 +874,8 @@
   END_VISIT( v );
 }
 
-ftnode_t ftselection::clone( expr::substitution_t &s ) const {
-  return new ftselection( get_loc(), ftor_->clone( s ).release(), list_ );
+ftnode_t ftselection::clone(user_function* udf,  expr::substitution_t &s ) const {
+  return new ftselection( get_loc(), ftor_->clone( udf, s ).release(), list_ );
 }
 
 ostream& ftselection::put( ostream &o ) const {
@@ -884,7 +905,7 @@
   END_VISIT( v );
 }
 
-ftnode_t ftstem_option::clone( expr::substitution_t& ) const {
+ftnode_t ftstem_option::clone(user_function* udf,  expr::substitution_t& ) const {
   return new ftstem_option( get_loc(), mode_ );
 }
 
@@ -918,7 +939,7 @@
   END_VISIT( v );
 }
 
-ftnode_t ftstop_words::clone( expr::substitution_t& ) const {
+ftnode_t ftstop_words::clone(user_function* udf,  expr::substitution_t& ) const {
   return new ftstop_words( get_loc(), uri_, list_, mode_ );
 }
 
@@ -970,9 +991,9 @@
   END_VISIT( v );
 }
 
-ftnode_t ftstop_word_option::clone( expr::substitution_t &s ) const {
+ftnode_t ftstop_word_option::clone(user_function* udf,  expr::substitution_t &s ) const {
   list_t copy;
-  clone_list( stop_words_, &copy, s );
+  clone_list( stop_words_, &copy, udf, s );
   return new ftstop_word_option( get_loc(), copy, mode_ );
 }
 
@@ -1018,9 +1039,9 @@
   END_VISIT( v );
 }
 
-ftnode_t ftthesaurus_id::clone( expr::substitution_t &s ) const {
+ftnode_t ftthesaurus_id::clone(user_function* udf,  expr::substitution_t &s ) const {
   return new ftthesaurus_id(
-    get_loc(), uri_, relationship_, clone_ptr_if( levels_, s )
+         get_loc(), uri_, relationship_, clone_ptr_if( levels_, udf, s )
   );
 }
 
@@ -1065,11 +1086,11 @@
   END_VISIT( v );
 }
 
-ftnode_t ftthesaurus_option::clone( expr::substitution_t &s ) const {
+ftnode_t ftthesaurus_option::clone(user_function* udf,  expr::substitution_t &s ) const {
   thesaurus_id_list_t copy;
-  clone_list( thesaurus_id_list_, &copy, s );
+  clone_list( thesaurus_id_list_, &copy, udf, s );
   return new ftthesaurus_option(
-    get_loc(), clone_ptr_if( default_tid_, s ), copy, no_thesaurus_
+         get_loc(), clone_ptr_if( default_tid_, udf, s ), copy, no_thesaurus_
   );
 }
 
@@ -1104,8 +1125,8 @@
   END_VISIT( v );
 }
 
-ftnode_t ftunary_not::clone( expr::substitution_t &s ) const {
-  return new ftunary_not( get_loc(), subnode_->clone( s ).release() );
+ftnode_t ftunary_not::clone(user_function* udf,  expr::substitution_t &s ) const {
+  return new ftunary_not( get_loc(), subnode_->clone( udf, s ).release() );
 }
 
 ostream& ftunary_not::put( ostream &o ) const {
@@ -1130,8 +1151,8 @@
   END_VISIT( v );
 }
 
-ftnode_t ftweight::clone( expr::substitution_t &s ) const {
-  return new ftweight( get_loc(), weight_expr_->clone( s ) );
+ftnode_t ftweight::clone(user_function* udf,  expr::substitution_t &s ) const {
+  return new ftweight( get_loc(), weight_expr_->clone( udf, s ) );
 }
 
 ostream& ftweight::put( ostream &o ) const {
@@ -1160,7 +1181,7 @@
   END_VISIT( v );
 }
 
-ftnode_t ftwild_card_option::clone( expr::substitution_t &s ) const {
+ftnode_t ftwild_card_option::clone(user_function* udf,  expr::substitution_t &s ) const {
   return new ftwild_card_option( get_loc(), mode_ );
 }
 
@@ -1193,10 +1214,8 @@
   END_VISIT( v );
 }
 
-ftnode_t ftwindow_filter::clone( expr::substitution_t &s ) const {
-  return new ftwindow_filter(
-    get_loc(), window_expr_->clone( s ), unit_
-  );
+ftnode_t ftwindow_filter::clone(user_function* udf,  expr::substitution_t &s ) const {
+  return new ftwindow_filter(get_loc(), window_expr_->clone( udf, s ), unit_ );
 }
 
 ostream& ftwindow_filter::put( ostream &o ) const {
@@ -1231,8 +1250,8 @@
   END_VISIT( v );
 }
 
-ftnode_t ftwords::clone( expr::substitution_t &s ) const {
-  return new ftwords( get_loc(), value_expr_->clone( s ), mode_ );
+ftnode_t ftwords::clone(user_function* udf,  expr::substitution_t &s ) const {
+  return new ftwords( get_loc(), value_expr_->clone( udf, s ), mode_ );
 }
 
 ostream& ftwords::put( ostream &o ) const {
@@ -1274,9 +1293,10 @@
   END_VISIT( v );
 }
 
-ftnode_t ftwords_times::clone( expr::substitution_t &s ) const {
-  return new ftwords_times(
-    get_loc(), clone_ptr( ftwords_, s ), clone_ptr_if( fttimes_, s )
+ftnode_t ftwords_times::clone(user_function* udf,  expr::substitution_t &s ) const {
+  return new ftwords_times(get_loc(),
+                           clone_ptr( ftwords_, udf, s ),
+                           clone_ptr_if( fttimes_, udf, s )
   );
 }
 

=== modified file 'src/compiler/expression/ftnode.h'
--- src/compiler/expression/ftnode.h	2012-09-19 21:16:15 +0000
+++ src/compiler/expression/ftnode.h	2012-10-09 10:29:25 +0000
@@ -44,8 +44,11 @@
   void serialize( serialization::Archiver& );
 
   virtual ft_visit_result::type accept( ftnode_visitor& ) = 0;
-  virtual ftnode_t clone( expr::substitution_t& ) const = 0;
+
+  virtual ftnode_t clone(user_function*, expr::substitution_t& ) const = 0;
+
   QueryLoc const& get_loc() const { return loc_; }
+
   virtual std::ostream& put( std::ostream& ) const = 0;
 
 protected:
@@ -85,7 +88,7 @@
   );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ft_case_mode::type get_mode() const { return mode_; }
   std::ostream& put( std::ostream& ) const;
 
@@ -107,7 +110,7 @@
   );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ft_diacritics_mode::type get_mode() const { return mode_; }
   std::ostream& put( std::ostream& ) const;
 
@@ -130,7 +133,7 @@
   );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   rchandle<QName> const& get_qname() const { return qname_; }
   zstring const& get_val() const { return val_; }
   std::ostream& put( std::ostream& ) const;
@@ -159,7 +162,7 @@
   );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   locale::iso639_1::type get_language() const { return lang_; }
   std::ostream& put( std::ostream& ) const;
 
@@ -181,7 +184,7 @@
   );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ft_stem_mode::type get_mode() const { return mode_; }
   std::ostream& put( std::ostream& ) const;
 
@@ -207,7 +210,7 @@
   );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   zstring const& get_uri() const { return uri_; }
   list_t const& get_list() const { return list_; }
   ft_stop_words_unex::type get_mode() const { return mode_; }
@@ -246,7 +249,7 @@
   ~ftstop_word_option();
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ft_stop_words_mode::type get_mode() const { return mode_; }
   list_t const& get_stop_words() const { return stop_words_; }
   std::ostream& put( std::ostream& ) const;
@@ -273,7 +276,7 @@
   ~ftthesaurus_id();
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   zstring const& get_uri() const { return uri_; }
   zstring const& get_relationship() const { return relationship_; }
   ftrange const* get_levels() const { return levels_; }
@@ -310,7 +313,7 @@
   }
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   bool no_thesaurus() const { return no_thesaurus_; }
   std::ostream& put( std::ostream& ) const;
 
@@ -334,7 +337,7 @@
   );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ft_wild_card_mode::type get_mode() const { return mode_; }
   std::ostream& put( std::ostream& ) const;
 
@@ -355,7 +358,7 @@
   ftmatch_options( QueryLoc const& );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
 
   ftcase_option const* get_case_option() const {
     return case_option_.getp();
@@ -462,7 +465,7 @@
   ftweight( QueryLoc const&, expr* const &weight_expr );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   expr** get_weight_expr() { return &weight_expr_; }
   PlanIter_t get_weight_iter() const { return weight_iter_; }
   std::ostream& put( std::ostream& ) const;
@@ -501,7 +504,7 @@
   ~ftprimary_with_options();
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ftprimary const* get_primary() const { return primary_; }
   ftweight* get_weight() { return weight_; }
   ftmatch_options const* get_match_options() const { return match_options_; }
@@ -543,7 +546,7 @@
   ~ftextension_selection();
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   rchandle<PragmaList> const& get_pragmas() const { return pragmas_; }
   ftselection const* get_ftselection() const { return ftselection_; }
   std::ostream& put( std::ostream& ) const;
@@ -570,7 +573,7 @@
   ~ftselection();
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ftpos_filter_list_t const& get_ftpos_filter_list() const { return list_; }
   ftnode const* get_ftor() const { return ftor_; };
   std::ostream& put( std::ostream& ) const;
@@ -595,7 +598,7 @@
   ~ftwords_times();
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ftwords const* get_words() const { return ftwords_; }
   ftrange const* get_times() const { return fttimes_; }
   std::ostream& put( std::ostream& ) const;
@@ -627,7 +630,7 @@
   ftcontent_filter( QueryLoc const&, ft_content_mode::type );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ft_content_mode::type get_mode() const { return mode_; }
   std::ostream& put( std::ostream& ) const;
 
@@ -646,7 +649,7 @@
   ~ftdistance_filter();
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ftrange const* get_range() const { return range_; }
   ft_unit::type get_unit() const { return unit_; }
   std::ostream& put( std::ostream& ) const;
@@ -666,7 +669,7 @@
   ftorder_filter( QueryLoc const& );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   std::ostream& put( std::ostream& ) const;
 };
 
@@ -680,7 +683,7 @@
   ftscope_filter( QueryLoc const&, ft_scope::type, ft_big_unit::type );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ft_scope::type get_scope() const { return scope_; }
   ft_big_unit::type get_unit() const { return unit_; }
   std::ostream& put( std::ostream& ) const;
@@ -700,7 +703,7 @@
   ftwindow_filter( QueryLoc const&, expr* const&, ft_unit::type );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ft_unit::type get_unit() const { return unit_; }
   expr** get_window_expr() { return &window_expr_; }
   PlanIter_t get_window_iter() const { return window_iter_; }
@@ -751,7 +754,7 @@
   ftand( QueryLoc const&, ftnode_list_t& );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   std::ostream& put( std::ostream& ) const;
 };
 
@@ -765,7 +768,7 @@
   ftmild_not( QueryLoc const&, ftnode_list_t& );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   std::ostream& put( std::ostream& ) const;
 };
 
@@ -779,7 +782,7 @@
   ftor( QueryLoc const&, ftnode_list_t& );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   std::ostream& put( std::ostream& ) const;
 };
 
@@ -794,7 +797,7 @@
   ~ftunary_not();
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   ftnode const* get_subnode() const { return subnode_; }
   std::ostream& put( std::ostream& ) const;
 
@@ -818,7 +821,7 @@
   );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   expr** get_expr1() { return &expr1_; }
   expr** get_expr2() { return &expr2_; }
   PlanIter_t get_plan_iter1() const { return iter1_; }
@@ -853,7 +856,7 @@
   );
 
   ft_visit_result::type accept( ftnode_visitor& );
-  ftnode_t clone( expr::substitution_t& ) const;
+  ftnode_t clone(user_function*, expr::substitution_t& ) const;
   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_; }

=== modified file 'src/compiler/expression/function_item_expr.cpp'
--- src/compiler/expression/function_item_expr.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/function_item_expr.cpp	2012-10-09 10:29:25 +0000
@@ -33,11 +33,12 @@
 dynamic_function_invocation_expr::dynamic_function_invocation_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* anExpr,
     const std::vector<expr*>& args)
   :
-  expr(ccb, sctx, loc, dynamic_function_invocation_expr_kind),
+  expr(ccb, sctx, udf, loc, dynamic_function_invocation_expr_kind),
   theExpr(anExpr),
   theArgs(args)
 {
@@ -56,23 +57,6 @@
 }
 
 
-expr* dynamic_function_invocation_expr::cloneImpl(substitution_t& s) const
-{
-  checked_vector<expr*> lNewArgs;
-  for (checked_vector<expr*>::const_iterator lIter = theArgs.begin();
-       lIter != theArgs.end();
-       ++lIter)
-  {
-    lNewArgs.push_back((*lIter)->clone(s));
-  }
-
-  return theCCB->theEM->create_dynamic_function_invocation_expr(theSctx,
-                                              get_loc(),
-                                              theExpr->clone(s),
-                                              lNewArgs);
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
@@ -83,12 +67,13 @@
 function_item_expr::function_item_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     const store::Item* aQName,
     function* f,
     uint32_t aArity)
   :
-  expr(ccb, sctx, loc, function_item_expr_kind),
+  expr(ccb, sctx, udf, loc, function_item_expr_kind),
   theQName(const_cast<store::Item*>(aQName)),
   theFunction(f),
   theArity(aArity)
@@ -101,9 +86,10 @@
 function_item_expr::function_item_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc)
   :
-  expr(ccb, sctx, loc, function_item_expr_kind),
+  expr(ccb, sctx, udf, loc, function_item_expr_kind),
   theQName(0),
   theFunction(NULL),
   theArity(0)
@@ -144,27 +130,5 @@
 }
 
 
-expr* function_item_expr::cloneImpl(substitution_t& s) const
-{
-  std::auto_ptr<function_item_expr> lNewExpr(
-      theCCB->theEM->create_function_item_expr(theSctx,
-                             get_loc(),
-                             theFunction->getName(),
-                             theFunction.getp(),
-                             theArity)
-  );
-
-  std::vector<expr*> lNewVariables;
-  for (std::vector<expr*>::const_iterator lIter = theScopedVariables.begin();
-       lIter != theScopedVariables.end();
-       ++lIter)
-  {
-    lNewExpr->add_variable((*lIter)->clone(s));
-  }
-
-  return lNewExpr.release();
-}
-
-
 }//end of namespace
 /* vim:set et sw=2 ts=2: */

=== modified file 'src/compiler/expression/function_item_expr.h'
--- src/compiler/expression/function_item_expr.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/function_item_expr.h	2012-10-09 10:29:25 +0000
@@ -48,6 +48,7 @@
   dynamic_function_invocation_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* anExpr,
       const std::vector<expr*>& args);
@@ -59,8 +60,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream& os) const;
@@ -116,6 +115,7 @@
   function_item_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       const store::Item* aQName,
       function* f,
@@ -124,6 +124,7 @@
   function_item_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc);
 
 public:
@@ -143,8 +144,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream& os) const;

=== modified file 'src/compiler/expression/json_exprs.cpp'
--- src/compiler/expression/json_exprs.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/json_exprs.cpp	2012-10-09 10:29:25 +0000
@@ -33,10 +33,11 @@
 json_array_expr::json_array_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* content)
   :
-  expr(ccb, sctx, loc, json_array_expr_kind),
+  expr(ccb, sctx, udf, loc, json_array_expr_kind),
   theContentExpr(content)
 {
   compute_scripting_kind();
@@ -60,15 +61,6 @@
 }
 
 
-expr* json_array_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->
-         create_json_array_expr(theSctx,
-                                get_loc(),
-                                theContentExpr->clone(subst));
-}
-
-
 /*******************************************************************************
   SimpleObjectUnion ::= "{|" Expr? "|}"
 
@@ -79,11 +71,12 @@
 json_object_expr::json_object_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* content,
     bool accumulate)
   :
-  expr(ccb, sctx, loc, json_object_expr_kind),
+  expr(ccb, sctx, udf, loc, json_object_expr_kind),
   theContentExpr(content),
   theAccumulate(accumulate)
 {
@@ -108,17 +101,6 @@
 }
 
 
-expr* json_object_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->
-         create_json_object_expr(theSctx,
-                                 get_loc(),
-                                 (theContentExpr ?
-                                  theContentExpr->clone(subst) : NULL),
-                                 theAccumulate);
-}
-
-
 /*******************************************************************************
   DirectObjectConstructor ::= "{" PairConstructor ("," PairConstructor )* "}"
 
@@ -130,11 +112,12 @@
 json_direct_object_expr::json_direct_object_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     std::vector<expr*>& names,
     std::vector<expr*>& values)
   :
-  expr(ccb, sctx, loc, json_direct_object_expr_kind)
+  expr(ccb, sctx, udf, loc, json_direct_object_expr_kind)
 {
   assert(names.size() == values.size());
 
@@ -175,33 +158,6 @@
 }
 
 
-expr* json_direct_object_expr::cloneImpl(substitution_t& subst) const
-{
-  std::vector<expr*> names;
-  std::vector<expr*> values;
-
-  names.reserve(theNames.size());
-  values.reserve(theValues.size());
-
-  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));
-  }
-
-  ite = theValues.begin();
-  end = theValues.end();
-  for (; ite != end; ++ite)
-  {
-    values.push_back((*ite)->clone(subst));
-  }
-
-  return theCCB->theEM->
-         create_json_direct_object_expr(theSctx, get_loc(), names, values);
-}
-
-
 }
 #endif // ZORBA_WITH_JSON
 

=== modified file 'src/compiler/expression/json_exprs.h'
--- src/compiler/expression/json_exprs.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/json_exprs.h	2012-10-09 10:29:25 +0000
@@ -35,6 +35,7 @@
 ********************************************************************************/
 class json_array_expr : public expr
 {
+  friend class expr;
   friend class ExprIterator;
   friend class ExprManager;
 
@@ -45,6 +46,7 @@
   json_array_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* content);
 
@@ -53,8 +55,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -70,6 +70,7 @@
 ********************************************************************************/
 class json_object_expr : public expr
 {
+  friend class expr;
   friend class ExprIterator;
   friend class ExprManager;
 
@@ -81,6 +82,7 @@
   json_object_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* content,
       bool accumulate);
@@ -92,8 +94,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -110,6 +110,7 @@
 ********************************************************************************/
 class json_direct_object_expr : public expr
 {
+  friend class expr;
   friend class ExprIterator;
   friend class ExprManager;
 
@@ -121,6 +122,7 @@
   json_direct_object_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       std::vector<expr*>& names,
       std::vector<expr*>& values);
@@ -134,8 +136,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;

=== modified file 'src/compiler/expression/path_expr.cpp'
--- src/compiler/expression/path_expr.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/path_expr.cpp	2012-10-09 10:29:25 +0000
@@ -42,9 +42,13 @@
   RelativPathExpr ::= "/" | ("/" | "//")?  StepExpr (("/" | "//") StepExpr)*
 
 ********************************************************************************/
-relpath_expr::relpath_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc)
+relpath_expr::relpath_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc)
   :
-  expr(ccb, sctx, loc, relpath_expr_kind)
+  expr(ccb, sctx, udf, loc, relpath_expr_kind)
 {
   theScriptingKind = SIMPLE_EXPR;
 }
@@ -100,28 +104,18 @@
 }
 
 
-expr* relpath_expr::cloneImpl(substitution_t& subst) const
-{
-  std::auto_ptr<relpath_expr> re(theCCB->theEM->create_relpath_expr(theSctx, get_loc()));
-
-  for (unsigned i = 0; i < size(); ++i)
-  {
-    re->add_back((*this)[i]->clone(subst));
-  }
-
-  return re.release();
-}
-
-
-
 /*******************************************************************************
 
   AxisStep ::= Axis NodeTest Predicate*
 
 ********************************************************************************/
-axis_step_expr::axis_step_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc)
+axis_step_expr::axis_step_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc)
   :
-  expr(ccb, sctx, loc, axis_step_expr_kind),
+  expr(ccb, sctx, udf, loc, axis_step_expr_kind),
   theReverseOrder(false)
 {
   compute_scripting_kind();
@@ -148,16 +142,6 @@
 }
 
 
-expr* axis_step_expr::cloneImpl(substitution_t& subst) const
-{
-  axis_step_expr* ae = theCCB->theEM->create_axis_step_expr(theSctx, get_loc());
-  ae->setAxis(getAxis());
-  ae->setTest(getTest());
-  ae->theReverseOrder = theReverseOrder;
-  return ae;
-}
-
-
 /*******************************************************************************
 
   [78] NodeTest ::= KindTest | NameTest
@@ -170,9 +154,13 @@
                      PITest | CommentTest | TextTest | AnyKindTest
 
 ********************************************************************************/
-match_expr::match_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc)
+match_expr::match_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc)
   :
-  expr(ccb, sctx, loc, match_expr_kind),
+  expr(ccb, sctx, udf, loc, match_expr_kind),
   theDocTestKind(match_no_test),
   theWildKind(match_no_wild),
   theQName(NULL),
@@ -220,20 +208,6 @@
 }
 
 
-expr* match_expr::cloneImpl(substitution_t& subst) const
-{
-  match_expr* me = theCCB->theEM->create_match_expr(theSctx, get_loc());
-  me->setTestKind(getTestKind());
-  me->setDocTestKind(getDocTestKind());
-  me->setWildName(getWildName());
-  me->setWildKind(getWildKind());
-  me->setQName(getQName());
-  me->setTypeName(getTypeName());
-  me->setNilledAllowed(getNilledAllowed());
-  return me;
-}
-
-
 }
 
 /* vim:set et sw=2 ts=2: */

=== modified file 'src/compiler/expression/path_expr.h'
--- src/compiler/expression/path_expr.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/path_expr.h	2012-10-09 10:29:25 +0000
@@ -59,7 +59,11 @@
   std::vector<expr*> theSteps;
 
 protected:
-  relpath_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc);
+  relpath_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc& loc);
 
 public:
   size_t size() const { return theSteps.size(); }
@@ -78,8 +82,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t &) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -113,7 +115,11 @@
   static bool is_reverse_axis(axis_kind_t kind);
 
 protected:
-  axis_step_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&);
+  axis_step_expr(
+     CompilerCB* ccb,
+     static_context* sctx,
+     user_function* udf,
+     const QueryLoc&);
 
 public:
   axis_kind_t getAxis() const { return theAxis; }
@@ -135,8 +141,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t &) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -177,7 +181,11 @@
   bool              theNilledAllowed;
 
 protected:
-  match_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&);
+  match_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&);
 
 public:
   match_test_t getTestKind() const { return theTestKind; }
@@ -213,8 +221,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t &) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;

=== modified file 'src/compiler/expression/script_exprs.cpp'
--- src/compiler/expression/script_exprs.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/script_exprs.cpp	2012-10-09 10:29:25 +0000
@@ -47,12 +47,13 @@
 block_expr::block_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     bool allowLastUpdating,
     std::vector<expr*>& seq,
     std::vector<var_expr*>* assignedVars)
   :
-  expr(ccb, sctx, loc, block_expr_kind),
+  expr(ccb, sctx, udf, loc, block_expr_kind),
   theArgs(seq)
 {
   compute_scripting_kind2(assignedVars, allowLastUpdating);
@@ -166,27 +167,18 @@
 }
 
 
-expr* block_expr::cloneImpl(substitution_t& subst) const
-{
-  checked_vector<expr*> seq2;
-  for (csize i = 0; i < theArgs.size(); ++i)
-    seq2.push_back(theArgs[i]->clone(subst));
-
-  return theCCB->theEM->create_block_expr(theSctx, get_loc(), true, seq2, NULL);
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
 apply_expr::apply_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* inExpr,
     bool discardXDM)
   :
-  expr(ccb, sctx, loc, apply_expr_kind),
+  expr(ccb, sctx, udf, loc, apply_expr_kind),
   theExpr(inExpr),
   theDiscardXDM(discardXDM)
 {
@@ -205,23 +197,18 @@
 }
 
 
-expr* apply_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_apply_expr(theSctx, get_loc(), theExpr->clone(subst), theDiscardXDM);
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
 var_decl_expr::var_decl_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     var_expr* varExpr,
     expr* initExpr)
   :
-  expr(ccb, sctx, loc, var_decl_expr_kind),
+  expr(ccb, sctx, udf, loc, var_decl_expr_kind),
   theVarExpr(varExpr),
   theInitExpr(initExpr)
 {
@@ -262,29 +249,18 @@
 }
 
 
-expr* var_decl_expr::cloneImpl(substitution_t& s) const
-{
-  var_expr* varCopy = theCCB->theEM->create_var_expr(*theVarExpr);
-  s[theVarExpr] = varCopy;
-
-  return theCCB->theEM->create_var_decl_expr(theSctx,
-                           get_loc(),
-                           varCopy,
-                           (theInitExpr ? theInitExpr->clone(s) : NULL));
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
 var_set_expr::var_set_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     var_expr* varExpr,
     expr* setExpr)
   :
-  expr(ccb, sctx, loc, var_set_expr_kind),
+  expr(ccb, sctx, udf, loc, var_set_expr_kind),
   theVarExpr(varExpr),
   theExpr(setExpr)
 {
@@ -319,29 +295,17 @@
 }
 
 
-expr* var_set_expr::cloneImpl(substitution_t& s) const
-{
-  expr* varClone = theVarExpr->clone(s);
-
-  ZORBA_ASSERT(varClone->get_expr_kind() == var_expr_kind);
-
-  return theCCB->theEM->create_var_set_expr(theSctx,
-                          get_loc(),
-                          static_cast<var_expr*>(varClone),
-                          theExpr->clone(s));
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
 exit_expr::exit_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* inExpr)
   :
-  expr(ccb, sctx, loc, exit_expr_kind),
+  expr(ccb, sctx, udf, loc, exit_expr_kind),
   theExpr(inExpr),
   theCatcherExpr(NULL)
 {
@@ -368,27 +332,18 @@
 }
 
 
-expr* exit_expr::cloneImpl(substitution_t& subst) const
-{
-  expr* clone = theCCB->theEM->create_exit_expr(theSctx, get_loc(), get_expr()->clone(subst));
-
-  subst[this] = clone;
-
-  return clone;
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
 exit_catcher_expr::exit_catcher_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* inExpr,
     std::vector<expr*>& exitExprs)
   :
-  expr(ccb, sctx, loc, exit_catcher_expr_kind),
+  expr(ccb, sctx, udf, loc, exit_catcher_expr_kind),
   theExpr(inExpr)
 {
   theExitExprs.swap(exitExprs);
@@ -438,31 +393,17 @@
 }
 
 
-expr* exit_catcher_expr::cloneImpl(substitution_t& subst) const
-{
-  expr* clonedInput = get_expr()->clone(subst);
-
-  std::vector<expr*> clonedExits;
-  std::vector<expr*>::const_iterator ite = theExitExprs.begin();
-  std::vector<expr*>::const_iterator end = theExitExprs.end();
-  for (; ite != end; ++ite)
-  {
-    assert(subst.find(*ite) != subst.end());
-
-    clonedExits.push_back(subst[*ite]);
-  }
-
-  return theCCB->theEM->create_exit_catcher_expr(theSctx, get_loc(), clonedInput, clonedExits);
-}
-
-
-
 /*******************************************************************************
 
 ********************************************************************************/
-flowctl_expr::flowctl_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, enum action action)
+flowctl_expr::flowctl_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc,
+    enum action action)
   :
-  expr(ccb, sctx, loc, flowctl_expr_kind),
+  expr(ccb, sctx, udf, loc, flowctl_expr_kind),
   theAction(action)
 {
   compute_scripting_kind();
@@ -479,18 +420,17 @@
 }
 
 
-expr* flowctl_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_flowctl_expr(theSctx, get_loc(), get_action());
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
-while_expr::while_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, expr* body)
+while_expr::while_expr(
+    CompilerCB* ccb,
+    static_context* sctx,
+    user_function* udf,
+    const QueryLoc& loc,
+    expr* body)
   :
-  expr(ccb, sctx, loc, while_expr_kind),
+  expr(ccb, sctx, udf, loc, while_expr_kind),
   theBody(body)
 {
   compute_scripting_kind();
@@ -523,12 +463,5 @@
     theScriptingKind = SIMPLE_EXPR;
 }
 
-
-expr* while_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_while_expr(theSctx, get_loc(), get_body()->clone(subst));
-}
-
-
 }
 /* vim:set et sw=2 ts=2: */

=== modified file 'src/compiler/expression/script_exprs.h'
--- src/compiler/expression/script_exprs.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/script_exprs.h	2012-10-09 10:29:25 +0000
@@ -114,6 +114,7 @@
   block_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       bool allowLastUpdating,
       std::vector<expr*>& seq,
@@ -130,8 +131,6 @@
 
   expr* operator[](csize i) { return theArgs[i]; }
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -162,6 +161,7 @@
   apply_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* inExpr,
       bool discardXDM);
@@ -173,8 +173,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -223,6 +221,7 @@
   var_decl_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       var_expr* varExpr,
       expr* initExpr);
@@ -236,8 +235,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -269,6 +266,7 @@
   var_set_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       var_expr* varExpr,
       expr* setExpr);
@@ -282,8 +280,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -308,6 +304,7 @@
   exit_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* inExpr);
 
@@ -320,8 +317,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -356,6 +351,7 @@
   exit_catcher_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       expr* inExpr,
       std::vector<expr*>& exitExprs);
@@ -379,8 +375,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -403,13 +397,16 @@
   enum action theAction;
 
 protected:
-  flowctl_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, enum action action);
+  flowctl_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc& loc,
+      enum action action);
 
 public:
   enum action get_action() const { return theAction; }
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void compute_scripting_kind();
 
   void accept(expr_visitor&);
@@ -435,15 +432,18 @@
   expr* theBody;
 
 protected:
-  while_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc, expr* body);
+  while_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc& loc,
+      expr* body);
 
 public:
   expr* get_body() const { return theBody; }
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;

=== modified file 'src/compiler/expression/update_exprs.cpp'
--- src/compiler/expression/update_exprs.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/update_exprs.cpp	2012-10-09 10:29:25 +0000
@@ -41,12 +41,13 @@
 update_expr_base::update_expr_base(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr_kind_t kind,
     expr* targetExpr,
     expr* sourceExpr)
   :
-  expr(ccb, sctx, loc, kind),
+  expr(ccb, sctx, udf, loc, kind),
   theTargetExpr(targetExpr),
   theSourceExpr(sourceExpr)
 {
@@ -71,44 +72,30 @@
 insert_expr::insert_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     store::UpdateConsts::InsertType aType,
     expr* sourceExpr,
     expr* targetExpr)
   :
-  update_expr_base(ccb, sctx, loc, insert_expr_kind, targetExpr, sourceExpr),
+  update_expr_base(ccb, sctx, udf, loc, insert_expr_kind, targetExpr, sourceExpr),
   theType(aType)
 {
 }
 
 
-expr* insert_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_insert_expr(theSctx,
-                         get_loc(),
-                         getType(),
-                         getSourceExpr()->clone(subst),
-                         getTargetExpr()->clone(subst));
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
 delete_expr::delete_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* targetExpr)
   :
-  update_expr_base(ccb, sctx, loc, delete_expr_kind, targetExpr, NULL)
-{
-}
-
-
-expr* delete_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_delete_expr(theSctx, get_loc(), getTargetExpr()->clone(subst));
+  update_expr_base(ccb, sctx, udf, loc, delete_expr_kind, targetExpr, NULL)
+{
 }
 
 
@@ -118,48 +105,31 @@
 replace_expr::replace_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     store::UpdateConsts::ReplaceType aType,
     expr* targetExpr,
     expr* replaceExpr)
   :
-  update_expr_base(ccb, sctx, loc, replace_expr_kind, targetExpr, replaceExpr),
+  update_expr_base(ccb, sctx, udf, loc, replace_expr_kind, targetExpr, replaceExpr),
   theType(aType)
 {
 }
 
 
-expr* replace_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_replace_expr(theSctx,
-                          get_loc(),
-                          getType(),
-                          getTargetExpr()->clone(subst),
-                          getReplaceExpr()->clone(subst));
-}
-
-
 /*******************************************************************************
 
 ********************************************************************************/
 rename_expr::rename_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     expr* targetExpr,
     expr* nameExpr)
   :
-  update_expr_base(ccb, sctx, loc, rename_expr_kind, targetExpr, nameExpr)
-{
-}
-
-
-expr* rename_expr::cloneImpl(substitution_t& subst) const
-{
-  return theCCB->theEM->create_rename_expr(theSctx,
-                         get_loc(),
-                         getTargetExpr()->clone(subst),
-                         getNameExpr()->clone(subst));
+  update_expr_base(ccb, sctx, udf, loc, rename_expr_kind, targetExpr, nameExpr)
+{
 }
 
 
@@ -183,13 +153,15 @@
 }
 
 
-copy_clause* copy_clause::clone(expr::substitution_t& subst) const
+copy_clause* copy_clause::clone(
+    user_function* udf,
+    expr::substitution_t& subst) const
 {
   ZORBA_ASSERT(theVar && theExpr);
 
-  expr* domainCopy = theExpr->clone(subst);
+  expr* domainCopy = theExpr->clone(udf, subst);
 
-  var_expr* varCopy = theExpr->get_ccb()->theEM->create_var_expr(*theVar);
+  var_expr* varCopy = theExpr->get_ccb()->theEM->create_var_expr(udf, *theVar);
 
   subst[theVar] = varCopy;
 
@@ -200,9 +172,10 @@
 transform_expr::transform_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc)
   :
-  expr(ccb, sctx, loc, transform_expr_kind)
+  expr(ccb, sctx, udf, loc, transform_expr_kind)
 {
   theScriptingKind = SIMPLE_EXPR;
 }
@@ -247,26 +220,5 @@
 }
 
 
-expr* transform_expr::cloneImpl(substitution_t& subst) const 
-{
-  ZORBA_ASSERT(theModifyExpr && theReturnExpr);
-
-  transform_expr* cloneExpr =
-    theCCB->theEM->create_transform_expr(theSctx, get_loc());
-
-  for (std::vector<copy_clause*>::const_iterator lIter = theCopyClauses.begin();
-       lIter != theCopyClauses.end();
-       ++lIter)
-  {
-    cloneExpr->add_back((*lIter)->clone(subst));
-  }
-
-  cloneExpr->setModifyExpr(theModifyExpr->clone(subst));
-  cloneExpr->setReturnExpr(theReturnExpr->clone(subst));
-
-  return cloneExpr;
-}
-
-
 } /* namespace zorba */
 /* vim:set et sw=2 ts=2: */

=== modified file 'src/compiler/expression/update_exprs.h'
--- src/compiler/expression/update_exprs.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/update_exprs.h	2012-10-09 10:29:25 +0000
@@ -45,12 +45,13 @@
 
 public:
   update_expr_base(
-    CompilerCB* ccb,
-    static_context* sctx,
-    const QueryLoc&,
-    expr_kind_t kind,
-    expr* targetExpr,
-    expr* sourceExpr);
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      expr_kind_t kind,
+      expr* targetExpr,
+      expr* sourceExpr);
 
   expr* getTargetExpr() const { return theTargetExpr; }
 
@@ -75,40 +76,17 @@
 
 protected:
   insert_expr(
-    CompilerCB* ccb,
-    static_context* sctx,
-    const QueryLoc&,
-    store::UpdateConsts::InsertType,
-    expr* aSourceExpr,
-    expr* aTargetExpr);
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      store::UpdateConsts::InsertType,
+      expr* aSourceExpr,
+      expr* aTargetExpr);
 
 public:
   store::UpdateConsts::InsertType getType() const { return theType; }
   
-  expr* cloneImpl(substitution_t& s) const;
-
-  void accept(expr_visitor&);
-
-  std::ostream& put(std::ostream&) const;
-};
-
-
-/*******************************************************************************
-
-********************************************************************************/
-class delete_expr : public update_expr_base
-{
-  friend class ExprIterator;
-  friend class expr;
-  friend class ExprManager;
-
-
-protected:
-  delete_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc&, expr*);
-
-public:
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -129,18 +107,44 @@
 
 protected:
   replace_expr(
-    CompilerCB* ccb,
-    static_context* sctx,
-    const QueryLoc&,
-    store::UpdateConsts::ReplaceType aType,
-    expr*,
-    expr*);
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      store::UpdateConsts::ReplaceType aType,
+      expr*,
+      expr*);
 
 public:
   store::UpdateConsts::ReplaceType getType() const { return theType; }
 
   expr* getReplaceExpr() const { return theSourceExpr; }
 
+  void accept(expr_visitor&);
+
+  std::ostream& put(std::ostream&) const;
+};
+
+
+/*******************************************************************************
+
+********************************************************************************/
+class delete_expr : public update_expr_base
+{
+  friend class ExprIterator;
+  friend class expr;
+  friend class ExprManager;
+
+
+protected:
+  delete_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc&,
+      expr*);
+
+public:
   expr* cloneImpl(substitution_t& s) const;
 
   void accept(expr_visitor&);
@@ -162,6 +166,7 @@
   rename_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc&,
       expr*,
       expr*);
@@ -169,8 +174,6 @@
 public:
 	expr* getNameExpr() const { return theSourceExpr; }
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
@@ -206,7 +209,7 @@
 
   expr* getExpr() const { return theExpr; }
 
-  copy_clause* clone(expr::substitution_t& s) const;
+  copy_clause* clone(user_function* udf, expr::substitution_t& s) const;
 
   std::ostream& put(std::ostream&) const;
 };
@@ -224,7 +227,11 @@
   expr                     * theReturnExpr;
 
 protected:
-  transform_expr(CompilerCB* ccb, static_context* sctx, const QueryLoc& loc);
+  transform_expr(
+      CompilerCB* ccb,
+      static_context* sctx,
+      user_function* udf,
+      const QueryLoc& loc);
 
 public:
   expr* getModifyExpr() const { return theModifyExpr; }
@@ -249,8 +256,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& s) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;

=== modified file 'src/compiler/expression/var_expr.cpp'
--- src/compiler/expression/var_expr.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/var_expr.cpp	2012-10-09 10:29:25 +0000
@@ -70,11 +70,12 @@
 var_expr::var_expr(
     CompilerCB* ccb,
     static_context* sctx,
+    user_function* udf,
     const QueryLoc& loc,
     var_kind k,
     store::Item* name)
   :
-  expr(ccb, sctx, loc, var_expr_kind),
+  expr(ccb, sctx, udf, loc, var_expr_kind),
   theUniqueId(0),
   theVarKind(k),
   theName(name),
@@ -82,7 +83,6 @@
   theFlworClause(NULL),
   theCopyClause(NULL),
   theParamPos(0),
-  theUDF(NULL),
   theVarInfo(NULL),
   theIsExternal(false),
   theIsPrivate(false),
@@ -98,7 +98,7 @@
 /*******************************************************************************
 
 ********************************************************************************/
-var_expr::var_expr(const var_expr& source)
+var_expr::var_expr(user_function* udf, const var_expr& source)
   :
   expr(source),
   theUniqueId(0),
@@ -108,13 +108,13 @@
   theFlworClause(NULL),
   theCopyClause(NULL),
   theParamPos(source.theParamPos),
-  theUDF(source.theUDF),
   theVarInfo(NULL),
   theIsExternal(source.theIsExternal),
   theIsPrivate(source.theIsPrivate),
   theIsMutable(source.theIsMutable),
   theHasInitializer(source.theHasInitializer)
 {
+  theUDF = udf;
 }
 
 
@@ -337,20 +337,6 @@
 /*******************************************************************************
 
 ********************************************************************************/
-expr* var_expr::cloneImpl(expr::substitution_t& subst) const
-{
-  expr::subst_iter_t i = subst.find(this);
-
-  if (i == subst.end())
-    return const_cast<var_expr*>(this);
-
-  return i->second;
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
 void var_expr::accept(expr_visitor& v)
 {
   if (v.begin_visit(*this))

=== modified file 'src/compiler/expression/var_expr.h'
--- src/compiler/expression/var_expr.h	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/var_expr.h	2012-10-09 10:29:25 +0000
@@ -89,10 +89,6 @@
   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.
-
   theSetExprs:
   ------------
   For global and local vars, this vector contains a pointer to the var_decl_expr
@@ -165,8 +161,6 @@
 
   csize                 theParamPos;
 
-  user_function       * theUDF;
-
   std::vector<expr*>    theSetExprs;
 
   VarInfo             * theVarInfo;
@@ -186,11 +180,12 @@
   var_expr(
       CompilerCB* ccb,
       static_context* sctx,
+      user_function* udf,
       const QueryLoc& loc,
       var_kind k,
       store::Item* name);
 
-  var_expr(const var_expr& source);
+  var_expr(user_function* udf, const var_expr& source);
 
   virtual ~var_expr();
 
@@ -249,10 +244,6 @@
 
   void set_param_pos(csize pos) { theParamPos = pos; }
 
-  user_function* get_udf() const { return theUDF; }
-
-  void set_udf(const user_function* udf) { theUDF = const_cast<user_function*>(udf); }
-
   void add_set_expr(expr* e) { theSetExprs.push_back(e); }
 
   void remove_set_expr(expr* e);
@@ -269,8 +260,6 @@
 
   void compute_scripting_kind();
 
-  expr* cloneImpl(substitution_t& subst) const;
-
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;

=== modified file 'src/compiler/rewriter/framework/rewriter_context.cpp'
--- src/compiler/rewriter/framework/rewriter_context.cpp	2012-09-19 21:16:15 +0000
+++ src/compiler/rewriter/framework/rewriter_context.cpp	2012-10-09 10:29:25 +0000
@@ -92,7 +92,7 @@
   std::string varname = ss.str();
   store::Item_t qname;
   GENV_ITEMFACTORY->createQName(qname, "", "", varname.c_str());
-  var_expr* var = theEM->create_var_expr(sctx, loc, kind, qname);
+  var_expr* var = theEM->create_var_expr(sctx, theUDF, loc, kind, qname);
 
   return var;
 }

=== modified file 'src/compiler/translator/translator.cpp'
--- src/compiler/translator/translator.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/translator/translator.cpp	2012-10-09 10:29:25 +0000
@@ -168,6 +168,12 @@
 /*******************************************************************************
 
 ********************************************************************************/
+#define CREATE(kind) theExprManager->create_##kind##_expr
+
+
+/*******************************************************************************
+
+********************************************************************************/
 #define ZANN_CONTAINS( ann ) theAnnotations->contains(AnnotationInternal::ann)
 
 
@@ -196,8 +202,9 @@
 
 #define DOT_REF                                             \
   theExprManager->create_wrapper_expr(theRootSctx,          \
-                   loc,                                     \
-                   lookup_ctx_var(DOT_VARNAME, loc))
+                                      theUDF,               \
+                                      loc,                  \
+                                      lookup_ctx_var(DOT_VARNAME, loc))
 
 namespace translator_ns
 {
@@ -584,6 +591,8 @@
   ulong                                  thePrintDepth;
   int                                    theScopeDepth;
 
+  user_function                        * theUDF;
+
   std::list<GlobalBinding>               thePrologVars;
 
   PrologGraph                            thePrologGraph;
@@ -601,7 +610,7 @@
 
   int                                    theTempVarCounter;
 
-  std::stack<expr*>                     theNodeStack;
+  std::stack<expr*>                      theNodeStack;
 
 #ifndef ZORBA_NO_FULL_TEXT
   std::stack<ftnode*>                    theFTNodeStack;
@@ -609,7 +618,7 @@
 
   std::stack<xqtref_t>                   theTypeStack;
 
-  std::vector<flwor_clause*>            theFlworClausesStack;
+  std::vector<flwor_clause*>             theFlworClausesStack;
 
   std::vector<const parsenode*>          theTryStack;
 
@@ -674,6 +683,7 @@
   theNSCtx(new namespace_context(theSctx)),
   thePrintDepth(0),
   theScopeDepth(0),
+  theUDF(NULL),
   thePrologGraph(rootSctx),
   theHaveUpdatingExitExprs(false),
   theHaveSequentialExitExprs(false),
@@ -1082,7 +1092,8 @@
     var_expr::var_kind kind,
     xqtref_t type = NULL)
 {
-  var_expr* e = theExprManager->create_var_expr(theRootSctx, loc, kind, qname);
+  var_expr* e = theExprManager->
+  create_var_expr(theRootSctx, theUDF, loc, kind, qname);
 
   if (kind == var_expr::pos_var ||
       kind == var_expr::count_var ||
@@ -1339,7 +1350,7 @@
 ********************************************************************************/
 fo_expr* create_empty_seq(const QueryLoc& loc)
 {
-  return theExprManager->create_seq(theRootSctx, loc);
+  return theExprManager->create_seq(theRootSctx, theUDF, loc);
 }
 
 
@@ -1476,6 +1487,7 @@
 expr* wrap_in_atomization(expr* e)
 {
   return theExprManager->create_fo_expr(theRootSctx,
+                                        theUDF,
                                         e->get_loc(),
                                         GET_BUILTIN_FUNCTION(FN_DATA_1),
                                         e);
@@ -1494,6 +1506,7 @@
   e = wrap_in_atomization(e);
 
   return theExprManager->create_promote_expr(theRootSctx,
+                                             theUDF,
                                              e->get_loc(),
                                              e,
                                              type,
@@ -1523,6 +1536,7 @@
   else
   {
     return theExprManager->create_treat_expr(theRootSctx,
+                                             theUDF,
                                              e->get_loc(),
                                              e,
                                              type,
@@ -1539,6 +1553,7 @@
 fo_expr* wrap_in_enclosed_expr(expr* contentExpr, const QueryLoc& loc)
 {
   return theExprManager->create_fo_expr(theRootSctx,
+                                        theUDF,
                                         loc,
                                         GET_BUILTIN_FUNCTION(OP_ENCLOSED_1),
                                         contentExpr);
@@ -1551,6 +1566,7 @@
 expr* wrap_in_bev(expr * e)
 {
   fo_expr* fo = theExprManager->create_fo_expr(theRootSctx,
+                                               theUDF,
                                                e->get_loc(),
                                                GET_BUILTIN_FUNCTION(FN_BOOLEAN_1),
                                                e);
@@ -1586,10 +1602,13 @@
     fkind = FunctionConsts::OP_SORT_DISTINCT_NODES_ASC_1;
   }
 
-  fo_expr* dos = theExprManager->create_fo_expr(theRootSctx,
-                                      expr->get_loc(),
-                                      BuiltinFunctionLibrary::getFunction(fkind),
-                                      expr);
+  fo_expr* dos = theExprManager->
+  create_fo_expr(theRootSctx,
+                 theUDF,
+                 expr->get_loc(),
+                 BuiltinFunctionLibrary::getFunction(fkind),
+                 expr);
+
   normalize_fo(dos);
 
   return &*dos;
@@ -1604,10 +1623,8 @@
 {
   assert (lv->get_kind () == var_expr::let_var);
 
-  return theExprManager->create_let_clause(theRootSctx,
-                                           e->get_loc(),
-                                           lv,
-                                           e);
+  return theExprManager->
+  create_let_clause(theRootSctx, e->get_loc(), lv, e);
 }
 
 
@@ -1648,11 +1665,8 @@
     assert(pv->get_kind() == var_expr::pos_var);
   }
 
-  return theExprManager->create_for_clause(theRootSctx,
-                                           e->get_loc(),
-                                           fv,
-                                           e,
-                                           pv);
+  return theExprManager->
+  create_for_clause(theRootSctx, e->get_loc(), fv, e, pv);
 }
 
 
@@ -1704,9 +1718,8 @@
     var_expr* lv,
     expr* retExpr)
 {
-  flwor_expr* fe = theExprManager->create_flwor_expr(theRootSctx,
-                                                     lv->get_loc(),
-                                                     false);
+  flwor_expr* fe = theExprManager->
+  create_flwor_expr(theRootSctx, theUDF, lv->get_loc(), false);
 
   fe->add_clause(wrap_in_letclause(domExpr, lv));
 
@@ -1738,7 +1751,8 @@
 
   push_scope();
 
-  flwor_expr* flworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
+  flwor_expr* flworExpr = theExprManager->
+  create_flwor_expr(theRootSctx, theUDF, loc, false);
 
   if (withContextSize)
   {
@@ -1746,15 +1760,16 @@
     let_clause* lcInputSeq = wrap_in_letclause(inputExpr);
 
     // compute the size of the input seq
-    fo_expr* countExpr = theExprManager->create_fo_expr(theRootSctx,
-                                              loc,
-                                              GET_BUILTIN_FUNCTION(FN_COUNT_1),
-                                              lcInputSeq->get_var());
+    fo_expr* countExpr = theExprManager->
+    create_fo_expr(theRootSctx,
+                   theUDF,
+                   loc,
+                   GET_BUILTIN_FUNCTION(FN_COUNT_1),
+                   lcInputSeq->get_var());
+
     normalize_fo(countExpr);
 
-    let_clause* lcLast = wrap_in_letclause(countExpr,
-                                            loc,
-                                            LAST_IDX_VARNAME);
+    let_clause* lcLast = wrap_in_letclause(countExpr, loc, LAST_IDX_VARNAME);
 
     // Iterate over the input seq
     for_clause* fcDot = wrap_in_forclause(lcInputSeq->get_var(),
@@ -1804,11 +1819,13 @@
 #ifdef ZORBA_WITH_DEBUGGER
   if (theCCB->theDebuggerCommons != NULL)
   {
-    std::auto_ptr<debugger_expr> lExpr(theExprManager->create_debugger_expr(theSctx,
-                                                         aLoc,
-                                                         aExpr,
-                                                         theNSCtx,
-                                                         aIsVarDeclaration));
+    std::auto_ptr<debugger_expr> lExpr(theExprManager->
+    create_debugger_expr(theSctx,
+                         theUDF,
+                         aLoc,
+                         aExpr,
+                         theNSCtx,
+                         aIsVarDeclaration));
 
     // add the breakable expression in the debugger commons as a possible
     // breakpoint location
@@ -1840,9 +1857,12 @@
                                       var_expr::eval_var,
                                       NULL);
 
-      expr* argExpr = theExprManager->create_wrapper_expr(theRootSctx,
-                                        lBreakable.getLocation(),
-                                        argVar);
+      expr* argExpr = theExprManager->
+      create_wrapper_expr(theRootSctx,
+                          theUDF,
+                          lBreakable.getLocation(),
+                          argVar);
+
       lExpr->add_var(evalVar, argExpr);
     }
 
@@ -2028,11 +2048,16 @@
   if (initExpr != NULL && varType != NULL && !b.is_extern())
   {
     initExpr = theExprManager->
-    create_treat_expr(theRootSctx, loc, initExpr, varType, TreatIterator::TYPE_MATCH);
+    create_treat_expr(theRootSctx,
+                      theUDF,
+                      loc,
+                      initExpr,
+                      varType,
+                      TreatIterator::TYPE_MATCH);
   }
 
   expr* declExpr = theExprManager->
-  create_var_decl_expr(theRootSctx, loc, varExpr, initExpr);
+  create_var_decl_expr(theRootSctx, theUDF, loc, varExpr, initExpr);
 
   stmts.push_back(declExpr);
 
@@ -2040,10 +2065,15 @@
   if (varType != NULL && b.is_extern())
   {
     expr* getExpr = theExprManager->
-    create_fo_expr(theRootSctx, loc, varGet, varExpr);
+    create_fo_expr(theRootSctx, theUDF, loc, varGet, varExpr);
 
     expr* treatExpr = theExprManager->
-    create_treat_expr(theRootSctx, loc, getExpr, varType, TreatIterator::TYPE_MATCH);
+    create_treat_expr(theRootSctx,
+                      theUDF,
+                      loc,
+                      getExpr,
+                      varType,
+                      TreatIterator::TYPE_MATCH);
 
     stmts.push_back(treatExpr);
   }
@@ -2092,11 +2122,13 @@
       args.push_back(program);
     }
 
-    block_expr* res = theExprManager->create_block_expr(theRootSctx,
-                                     program->get_loc(),
-                                     theCCB->theIsEval,
-                                     args,
-                                     &theAssignedVars[0]);
+    block_expr* res = theExprManager->
+    create_block_expr(theRootSctx,
+                      theUDF,
+                      program->get_loc(),
+                      theCCB->theIsEval,
+                      args,
+                      &theAssignedVars[0]);
 
     assert(theAssignedVars[0].empty());
 
@@ -2292,11 +2324,12 @@
 
   store::Item_t qname;
   return theExprManager->create_validate_expr(theRootSctx,
-                           lLoc,
-                           ParseConstants::val_strict,
-                           qname,
-                           aExpr,
-                           theSctx->get_typemanager());
+                                              theUDF,
+                                              lLoc,
+                                              ParseConstants::val_strict,
+                                              qname,
+                                              aExpr,
+                                              theSctx->get_typemanager());
 }
 
 
@@ -3649,10 +3682,14 @@
   // is not bound to a namespace).
   store::Item_t qnameItem;
   expand_function_qname(qnameItem, v.get_name(), v.get_name()->get_location());
+
   function* f = theSctx->lookup_fn(qnameItem, v.get_param_count(), false);
 
   assert(f);
 
+  if (f->isUdf())
+    theUDF = static_cast<user_function*>(f);
+
   thePrologGraph.addFuncVertex(f);
   theCurrentPrologVFDecl = PrologGraphVertex(f);
 
@@ -3689,6 +3726,8 @@
   {
     udf = dynamic_cast<user_function *>(lFunc);
 
+    assert(udf == theUDF);
+
     body = pop_nodestack();
 
     wrap_in_debugger_expr(body, v.get_name()->get_location());
@@ -3772,7 +3811,8 @@
 
     if (udf->isExiting())
     {
-      body = theExprManager->create_exit_catcher_expr(theRootSctx, loc, body, theExitExprs);
+      body = theExprManager->
+      create_exit_catcher_expr(theRootSctx, theUDF, loc, body, theExitExprs);
     }
 
     // Wrap the UDF body to the type-related expr that enforce the declared
@@ -3815,6 +3855,8 @@
   }
 
   pop_scope();
+
+  theUDF = NULL;
 }
 
 
@@ -3827,7 +3869,9 @@
 
   if (v.size() > 0)
   {
-    flwor_expr* flwor = theExprManager->create_flwor_expr(theRootSctx, loc, false);
+    flwor_expr* flwor = theExprManager->
+    create_flwor_expr(theRootSctx, theUDF, loc, false);
+
     push_nodestack(flwor);
   }
   return no_state;
@@ -3871,12 +3915,7 @@
   if (inUDFBody())
   {
     //lc->setLazyEval(!f->isSequential());
-
-    const user_function* udf =
-    static_cast<const user_function*>(theCurrentPrologVFDecl.getFunction());
-
     arg_var->set_param_pos(flwor->num_clauses());
-    arg_var->set_udf(udf);
   }
   else
   {
@@ -4545,10 +4584,12 @@
   // and not allow the domain expr to return duplicate nodes.
   if (index->isGeneral())
   {
-    domainExpr = theExprManager->create_fo_expr(theRootSctx,
-                             domainExpr->get_loc(),
-                             GET_BUILTIN_FUNCTION(OP_CHECK_DISTINCT_NODES_1),
-                             domainExpr);
+    domainExpr = theExprManager->
+    create_fo_expr(theRootSctx,
+                   theUDF,
+                   domainExpr->get_loc(),
+                   GET_BUILTIN_FUNCTION(OP_CHECK_DISTINCT_NODES_1),
+                   domainExpr);
   }
 
   std::string msg = "Domain expr for index " + index->getName()->getStringValue().str();
@@ -4679,10 +4720,12 @@
     {
       // Eliminate duplicate key values, as they don't play any role in a
       // general comparison predicate.
-      keyExpr = theExprManager->create_fo_expr(theRootSctx,
-                            keyExpr->get_loc(),
-                            GET_BUILTIN_FUNCTION(FN_DISTINCT_VALUES_1),
-                            keyExpr);
+      keyExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     keyExpr->get_loc(),
+                     GET_BUILTIN_FUNCTION(FN_DISTINCT_VALUES_1),
+                     keyExpr);
     }
 
     std::string collationUri;
@@ -4811,17 +4854,19 @@
 
     // "example:coll1"
     expr* qnameStrExpr = theExprManager->
-    create_const_expr(theRootSctx, loc, ic.getCollName()->get_qname().str());
+    create_const_expr(theRootSctx, theUDF, loc, ic.getCollName()->get_qname().str());
 
     zstring prefixStr = ic.getCollName()->get_prefix();
     zstring uriStr;
     theSctx->lookup_ns(uriStr, prefixStr, loc);
 
-    expr* uriStrExpr = theExprManager->create_const_expr(theRootSctx, loc, uriStr);
+    expr* uriStrExpr = theExprManager->
+    create_const_expr(theRootSctx, theUDF, loc, uriStr);
 
     // fn:QName("uri", "example:coll1")
     fo_expr* qnameExpr = theExprManager->
     create_fo_expr(theRootSctx,
+                   theUDF,
                    loc,
                    GET_BUILTIN_FUNCTION(FN_QNAME_2),
                    uriStrExpr,
@@ -4834,7 +4879,7 @@
     argColl.push_back(qnameExpr);
 
     fo_expr* collExpr = theExprManager->
-    create_fo_expr(theRootSctx, loc, fn_collection, argColl);
+    create_fo_expr(theRootSctx, theUDF, loc, fn_collection, argColl);
 
     // $x
     const QName* varQName = ic.getCollVarName();
@@ -4844,7 +4889,9 @@
     let_clause* lc = theExprManager->
     create_let_clause(theRootSctx, loc, varExpr, collExpr);
 
-    flwor_expr* flworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
+    flwor_expr* flworExpr = theExprManager->
+    create_flwor_expr(theRootSctx, theUDF, loc, false);
+
     flworExpr->add_clause(lc);
     // flworExpr-> return clause to be set in end_visitor
 
@@ -4885,27 +4932,34 @@
       dynamic_cast<const ICCollUniqueKeyCheck&>(v);
 
     // "org:employees"
-    expr* qnameStrExpr = theExprManager->create_const_expr(theRootSctx,
-                                         loc,
-                                         ic.getCollName()->get_qname().str());
+    expr* qnameStrExpr = theExprManager->
+    create_const_expr(theRootSctx,
+                      theUDF,
+                      loc,
+                      ic.getCollName()->get_qname().str());
 
     zstring prefixStr = ic.getCollName()->get_prefix();
     zstring uriStr;
     theSctx->lookup_ns(uriStr, prefixStr, loc);
 
-    expr* uriStrExpr = theExprManager->create_const_expr(theRootSctx, loc, uriStr);
+    expr* uriStrExpr = theExprManager->
+    create_const_expr(theRootSctx, theUDF, loc, uriStr);
 
     // fn:QName("org-uri", "org:employees")
-    fo_expr* qnameExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                      GET_BUILTIN_FUNCTION(FN_QNAME_2),
-                                      uriStrExpr, qnameStrExpr);
-
+    fo_expr* qnameExpr = theExprManager->
+    create_fo_expr(theRootSctx,
+                   theUDF,
+                   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*> argColl;
     argColl.push_back(qnameExpr);
-    fo_expr* collExpr = theExprManager->create_fo_expr(theRootSctx, loc, fn_collection, argColl);
+    fo_expr* collExpr = theExprManager->
+    create_fo_expr(theRootSctx, theUDF, loc, fn_collection, argColl);
 
     // $x
     const QName* varQName = ic.getNodeVarName();
@@ -4915,8 +4969,14 @@
     // every $x_ in $x satisfies exists ...
     // every is implemented as a flowr expr
     push_scope();
-    flwor_expr* evFlworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
-    evFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx, loc, true));
+
+    flwor_expr* evFlworExpr = theExprManager->
+    create_flwor_expr(theRootSctx, theUDF, loc, false);
+
+    evFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx,
+                                                                   theUDF,
+                                                                   loc,
+                                                                   true));
 
     // $x_ in dc:collection( xs:QName("org:employees") )
     var_expr* evVarExpr = bind_var(loc,
@@ -4937,13 +4997,11 @@
                                   var_expr::let_var,
                                   NULL);
 
-    let_clause* letClause = theExprManager->create_let_clause(theRootSctx,
-                                           loc,
-                                           varExpr,
-                                           collExpr);
+    let_clause* letClause = theExprManager->
+    create_let_clause(theRootSctx, loc, varExpr, collExpr);
 
-    flwor_expr* flworExpr = theExprManager->create_flwor_expr(theRootSctx,
-                                                              loc, false);
+    flwor_expr* flworExpr = theExprManager->
+    create_flwor_expr(theRootSctx, theUDF, loc, false);
 
 
 
@@ -4978,33 +5036,43 @@
       dynamic_cast<const ICCollForeachNode&>(v);
 
     // "org:transactions"
-    expr* qnameStrExpr = theExprManager->create_const_expr(theRootSctx, loc,
-                                         ic.getCollName()->get_qname().str());
+    expr* qnameStrExpr = theExprManager->
+    create_const_expr(theRootSctx, theUDF, loc, ic.getCollName()->get_qname().str());
 
     zstring prefixStr = ic.getCollName()->get_prefix();
     zstring uriStr;
     theSctx->lookup_ns(uriStr, prefixStr, loc);
 
-    expr* uriStrExpr = theExprManager->create_const_expr(theRootSctx, loc, uriStr);
+    expr* uriStrExpr = theExprManager->
+    create_const_expr(theRootSctx, theUDF, loc, uriStr);
 
     // fn:QName("org-uri", "org:transactions")
-    fo_expr* qnameExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                      GET_BUILTIN_FUNCTION(FN_QNAME_2),
-                                      uriStrExpr, qnameStrExpr);
+    fo_expr* qnameExpr = theExprManager->
+    create_fo_expr(theRootSctx,
+                   theUDF,
+                   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*> argColl;
     argColl.push_back(qnameExpr);
-    fo_expr* collExpr = theExprManager->create_fo_expr(theRootSctx, loc, fn_collection, argColl);
+    fo_expr* collExpr = theExprManager->
+    create_fo_expr(theRootSctx, theUDF, loc, fn_collection, argColl);
 
     // every $x_ in $x satisfies exists ...
     // every is implemented as a flowr expr
     //push_scope();
-    flwor_expr* evFlworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
-    evFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx, loc, true));
-
+    flwor_expr* evFlworExpr = theExprManager->
+    create_flwor_expr(theRootSctx, theUDF, loc, false);
+    
+    evFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx,
+                                                                   theUDF,
+                                                                   loc,
+                                                                   true));
     // $x
     const QName* varQName = ic.getCollVarName();
 
@@ -5050,74 +5118,96 @@
 
     // TO part
     // "org:employees"
-    expr* toQnameStrExpr = theExprManager->create_const_expr(theRootSctx, loc,
-                                           ic.getToCollName()->get_qname().str());
+    expr* toQnameStrExpr = theExprManager->
+    create_const_expr(theRootSctx, theUDF, loc, ic.getToCollName()->get_qname().str());
+
     zstring toPrefixStr = ic.getToCollName()->get_prefix();
     zstring toUriStr;
     theSctx->lookup_ns(toUriStr, toPrefixStr, loc);
 
-    expr* toUriStrExpr = theExprManager->create_const_expr(theRootSctx, loc, toUriStr);
+    expr* toUriStrExpr = theExprManager->
+    create_const_expr(theRootSctx, theUDF, loc, toUriStr);
 
     // xs:QName("org:employees")
-    fo_expr* toQnameExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                        GET_BUILTIN_FUNCTION(FN_QNAME_2),
-                                        toUriStrExpr, toQnameStrExpr);
+    fo_expr* toQnameExpr = theExprManager->
+    create_fo_expr(theRootSctx,
+                   theUDF,
+                   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*> toArgColl;
     toArgColl.push_back(toQnameExpr);
-    fo_expr* toCollExpr = theExprManager->create_fo_expr(theRootSctx, loc, toFnCollection,
-                                       toArgColl);
+    fo_expr* toCollExpr = theExprManager->
+    create_fo_expr(theRootSctx, theUDF, loc, toFnCollection, toArgColl);
 
     // some $y in dc:collection( xs:QName("org:employees") )
     // satisfies ... eq ...
     // implemented using flowr
-    flwor_expr* someFlworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
-    someFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx, loc, true));
-
+    flwor_expr* someFlworExpr = theExprManager->
+    create_flwor_expr(theRootSctx, theUDF, loc, false);
+    
+    someFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx,
+                                                                     theUDF,
+                                                                     loc,
+                                                                     true));
     // $y
     const QName* toVarQName = ic.getToNodeVarName();
     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,
-                                                toVarExpr,
-                                                NULL));
-
+    someFlworExpr->add_clause(wrap_in_forclause(toCollExpr, toVarExpr, NULL));
 
     // FROM part
     // "org:transactions"
-    expr* fromQnameStrExpr = theExprManager->create_const_expr(theRootSctx, loc,
-                                             ic.getFromCollName()->get_qname().str());
+    expr* fromQnameStrExpr = theExprManager->
+    create_const_expr(theRootSctx,
+                      theUDF,
+                      loc,
+                      ic.getFromCollName()->get_qname().str());
 
     zstring fromPrefixStr = ic.getFromCollName()->get_prefix();
     zstring fromUriStr;
     theSctx->lookup_ns(fromUriStr, fromPrefixStr, loc);
 
-    expr* fromUriStrExpr = theExprManager->create_const_expr(theRootSctx, loc, fromUriStr);
+    expr* fromUriStrExpr = theExprManager->
+    create_const_expr(theRootSctx, theUDF, loc, fromUriStr);
 
     // fn:QName("org-uri", "org:transactions")
-    fo_expr* fromQnameExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                          GET_BUILTIN_FUNCTION(FN_QNAME_2),
-                                          fromUriStrExpr, fromQnameStrExpr);
+    fo_expr* fromQnameExpr = theExprManager->
+    create_fo_expr(theRootSctx,
+                   theUDF,
+                   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*> fromArgColl;
     fromArgColl.push_back(fromQnameExpr);
-    fo_expr* fromCollExpr = theExprManager->create_fo_expr(theRootSctx,
-                                         loc,
-                                         fromFnCollection,
-                                         fromArgColl);
+    fo_expr* fromCollExpr = theExprManager->
+    create_fo_expr(theRootSctx,
+                   theUDF,
+                   loc,
+                   fromFnCollection,
+                   fromArgColl);
 
     // every $x in dc:collection( xs:QName("org:transactions") )
     // satisfies ...
     // implemented using flowr
-    flwor_expr* evFlworExpr = theExprManager->create_flwor_expr(theRootSctx, loc, false);
-    evFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx, loc, true));
+    flwor_expr* evFlworExpr = theExprManager->
+      create_flwor_expr(theRootSctx, theUDF, loc, false);
+
+    evFlworExpr->set_return_expr(theExprManager->create_const_expr(theRootSctx,
+                                                                   theUDF,
+                                                                   loc,
+                                                                   true));
 
     // $x
     const QName* fromVarQName = ic.getFromNodeVarName();
@@ -5218,57 +5308,73 @@
       expr* atomizedUniKeyExpr = wrap_in_atomization(uniKeyExpr);
 
       // exists( $x/@id )
-      expr* existsExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                      GET_BUILTIN_FUNCTION(FN_EXISTS_1),
-                                      uniKeyExpr);
-
-#if 0
-      zstring commentStr("#trace fnExists");
-      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, comentExpr);
-#endif
-
+      expr* existsExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(FN_EXISTS_1),
+                     uniKeyExpr);
 
       // every ... satisfies evTestExpr
-      fo_expr* fnNotExpr = theExprManager->create_fo_expr(theRootSctx,
-                                        loc,
-                                        GET_BUILTIN_FUNCTION(FN_NOT_1),
-                                        existsExpr);
+      fo_expr* fnNotExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(FN_NOT_1),
+                     existsExpr);
 
       evFlworExpr->add_where(fnNotExpr);
 
-      fo_expr* everyExpr = theExprManager->create_fo_expr(theRootSctx,
-                                        loc,
-                                        GET_BUILTIN_FUNCTION(FN_EMPTY_1),
-                                        evFlworExpr);
+      fo_expr* everyExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(FN_EMPTY_1),
+                     evFlworExpr);
 
       // functx:are-distinct-values( $x/@id )
       // implemented as count(distinct-values($seq)) = count($seq)
       //distinct-values($seq)
-      fo_expr* distinctValuesExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                 GET_BUILTIN_FUNCTION(FN_DISTINCT_VALUES_1),
-                                                 atomizedUniKeyExpr);
-
+      fo_expr* distinctValuesExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(FN_DISTINCT_VALUES_1),
+                     atomizedUniKeyExpr);
+      
       // count($sec)
-      fo_expr* countSecExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                           GET_BUILTIN_FUNCTION(FN_COUNT_1),
-                                           atomizedUniKeyExpr);
+      fo_expr* countSecExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(FN_COUNT_1),
+                     atomizedUniKeyExpr);
+
       // count(distinct-values($sec))
-      fo_expr* countDVExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                          GET_BUILTIN_FUNCTION(FN_COUNT_1),
-                                          distinctValuesExpr);
+      fo_expr* countDVExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(FN_COUNT_1),
+                     distinctValuesExpr);
 
       // countDV = countSec
-      fo_expr* equalExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                        GET_BUILTIN_FUNCTION(OP_EQUAL_2),
-                                        countDVExpr, countSecExpr);
+      fo_expr* equalExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(OP_EQUAL_2),
+                     countDVExpr,
+                     countSecExpr);
+
       // (...) and (...)
-      fo_expr* andExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                      GET_BUILTIN_FUNCTION(OP_AND_N),
-                                      everyExpr, equalExpr);
+      fo_expr* andExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(OP_AND_N),
+                     everyExpr,
+                     equalExpr);
 
       flworExpr->set_return_expr(andExpr);
 
@@ -5302,19 +5408,23 @@
         dynamic_cast<flwor_expr*>(pop_nodestack());
 
       // fn:not
-      fo_expr* fnNotExpr = theExprManager->create_fo_expr(theRootSctx,
-                                        loc,
-                                        GET_BUILTIN_FUNCTION(FN_NOT_1),
-                                        evTestExpr);
+      fo_expr* fnNotExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(FN_NOT_1),
+                     evTestExpr);
 
       // where not( exists($x/sale gt 0) )
       evFlworExpr->add_where(fnNotExpr);
 
       // fn:empty
-      fo_expr* emptyExpr = theExprManager->create_fo_expr(theRootSctx,
-                                        loc,
-                                        GET_BUILTIN_FUNCTION(FN_EMPTY_1),
-                                        evFlworExpr);
+      fo_expr* emptyExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(FN_EMPTY_1),
+                     evFlworExpr);
 
       body = emptyExpr;
     }
@@ -5338,11 +5448,14 @@
 
       // maybe add fn:data ?
       // $y/id eq $x//sale/empid
-      fo_expr* eqExpr = theExprManager->create_fo_expr(theRootSctx,
-                                     loc,
-                                     GET_BUILTIN_FUNCTION(OP_VALUE_EQUAL_2),
-                                     toKeyExpr,
-                                     fromKeyExpr);
+      fo_expr* eqExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(OP_VALUE_EQUAL_2),
+                     toKeyExpr,
+                     fromKeyExpr);
+
       normalize_fo(eqExpr);
 
       expr* someTestExpr = eqExpr;
@@ -5350,22 +5463,29 @@
       someFlworExpr->add_where(someTestExpr);
 
       // fn:exists
-      fo_expr* fnExistsExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                           GET_BUILTIN_FUNCTION(FN_EXISTS_1),
-                                           someFlworExpr);
+      fo_expr* fnExistsExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(FN_EXISTS_1),
+                     someFlworExpr);
       // fn:not()
-      fo_expr* evFnNotExpr = theExprManager->create_fo_expr(theRootSctx,
-                                          loc,
-                                          GET_BUILTIN_FUNCTION(FN_NOT_1),
-                                          fnExistsExpr);
+      fo_expr* evFnNotExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(FN_NOT_1),
+                     fnExistsExpr);
 
       evFlworExpr->add_where(evFnNotExpr);
 
       // fn:empty
-      fo_expr* fnEmptyExpr = theExprManager->create_fo_expr(theRootSctx,
-                                        loc,
-                                        GET_BUILTIN_FUNCTION(FN_EMPTY_1),
-                                        evFlworExpr);
+      fo_expr* fnEmptyExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(FN_EMPTY_1),
+                     evFlworExpr);
 
 
       body = fnEmptyExpr;
@@ -5485,9 +5605,10 @@
   if (program->is_updating() && !theCCB->theIsEval)
   {
     program = theExprManager->create_apply_expr(theRootSctx,
-                             program->get_loc(),
-                             program,
-                             false); // don't discard XDM
+                                                theUDF,
+                                                program->get_loc(),
+                                                program,
+                                                false); // don't discard XDM
   }
 
   push_nodestack(program);
@@ -5578,7 +5699,9 @@
 
   // push a dummy block_expr in the node stack so that local var decls can
   // assert that their parent is a block expr.
-  expr* dummyBlock = theExprManager->create_block_expr(theRootSctx, loc, false, stmts, NULL);
+  expr* dummyBlock = theExprManager->
+  create_block_expr(theRootSctx, theUDF, loc, false, stmts, NULL);
+
   push_nodestack(dummyBlock);
 
   push_scope();
@@ -5618,7 +5741,8 @@
         }
         else
         {
-          childExpr = theExprManager->create_apply_expr(theRootSctx, loc, childExpr, false);
+          childExpr = theExprManager->
+          create_apply_expr(theRootSctx, theUDF, loc, childExpr, false);
         }
       }
 
@@ -5650,10 +5774,11 @@
   std::vector<var_expr*>& lastAssignedVars = theAssignedVars[numScopes];
 
   expr* blockExpr = theExprManager->create_block_expr(theRootSctx,
-                                    loc,
-                                    allowLastUpdating,
-                                    stmts,
-                                    &lastAssignedVars);
+                                                      theUDF,
+                                                      loc,
+                                                      allowLastUpdating,
+                                                      stmts,
+                                                      &lastAssignedVars);
 
   push_nodestack(blockExpr);
 
@@ -5802,12 +5927,17 @@
 
   if (varType != NULL)
     valueExpr = theExprManager->create_treat_expr(theRootSctx,
+                                                  theUDF,
                                                   loc,
                                                   valueExpr,
                                                   varType,
                                                   TreatIterator::TYPE_MATCH);
 
-  push_nodestack(theExprManager->create_var_set_expr(theRootSctx, loc, ve, valueExpr));
+  push_nodestack(theExprManager->create_var_set_expr(theRootSctx,
+                                                     theUDF,
+                                                     loc,
+                                                     ve,
+                                                     valueExpr));
 
   theAssignedVars.back().push_back(ve);
 }
@@ -5828,9 +5958,10 @@
   expr* param = pop_nodestack();
 
   push_nodestack(theExprManager->create_apply_expr(theRootSctx,
-                                param->get_loc(),
-                                param,
-                                true)); // discard XDM
+                                                   theUDF,
+                                                   param->get_loc(),
+                                                   param,
+                                                   true)); // discard XDM
 
   TRACE_VISIT_OUT();
 }
@@ -5859,7 +5990,8 @@
 
     if (!inUDFBody() && !theCCB->theIsEval)
     {
-      childExpr = theExprManager->create_apply_expr(theRootSctx, loc, childExpr, false);
+      childExpr = theExprManager->
+      create_apply_expr(theRootSctx, theUDF, loc, childExpr, false);
     }
   }
   else if (childExpr->is_sequential())
@@ -5867,7 +5999,8 @@
     theHaveSequentialExitExprs = true;
   }
 
-  expr* exitExpr = theExprManager->create_exit_expr(theRootSctx, loc, childExpr);
+  expr* exitExpr = theExprManager->
+  create_exit_expr(theRootSctx, theUDF, loc, childExpr);
 
   if (inUDFBody())
   {
@@ -5904,10 +6037,10 @@
   expr* condExpr = pop_nodestack();
 
   expr* breakExpr = theExprManager->
-  create_flowctl_expr(theRootSctx, loc, flowctl_expr::BREAK);
+  create_flowctl_expr(theRootSctx, theUDF, loc, flowctl_expr::BREAK);
 
   condExpr = theExprManager->
-  create_if_expr(theRootSctx, loc, condExpr, create_empty_seq(loc), breakExpr);
+  create_if_expr(theRootSctx, theUDF, loc, condExpr, create_empty_seq(loc), breakExpr);
 
   block_expr* seqBody = NULL;
 
@@ -5917,9 +6050,9 @@
   stmts.push_back(bodyExpr);
 
   seqBody = theExprManager->
-  create_block_expr(bodyExpr->get_sctx(), loc, false, stmts, NULL);
+  create_block_expr(bodyExpr->get_sctx(), theUDF, loc, false, stmts, NULL);
 
-  push_nodestack(theExprManager->create_while_expr(theRootSctx, loc, seqBody));
+  push_nodestack(theExprManager->create_while_expr(theRootSctx, theUDF, loc, seqBody));
 
   theInWhileStack.pop();
 }
@@ -5965,7 +6098,7 @@
     ZORBA_FATAL(false, "");
   }
 
-  push_nodestack(theExprManager->create_flowctl_expr(theRootSctx, loc, a));
+  push_nodestack(CREATE(flowctl)(theRootSctx, theUDF, loc, a));
 }
 
 
@@ -5996,10 +6129,9 @@
     args.push_back(e);
   }
 
-  fo_expr* concatExpr = theExprManager->create_fo_expr(theRootSctx,
-                                                        loc,
-                                                        op_concatenate,
-                                                        args);
+  fo_expr* concatExpr = theExprManager->
+  create_fo_expr(theRootSctx, theUDF, loc, op_concatenate, args);
+
   normalize_fo(concatExpr);
 
   push_nodestack(concatExpr);
@@ -6083,7 +6215,8 @@
     ERROR_PARAMS(ZED(XPST0003_XQueryVersionAtLeast30_2), theSctx->xquery_version()));
   }
 
-  flwor_expr* flwor = theExprManager->create_flwor_expr(theRootSctx, loc, v.is_general());
+  flwor_expr* flwor = theExprManager->
+  create_flwor_expr(theRootSctx, theUDF, loc, v.is_general());
 
   expr* retExpr = pop_nodestack();
 
@@ -6267,12 +6400,12 @@
   }
 
   for_clause* fc = theExprManager->create_for_clause(theRootSctx,
-                                  loc,
-                                  varExpr,
-                                  domainExpr,
-                                  posVarExpr,
-                                  NULL,
-                                  v.get_allowing_empty());
+                                                     loc,
+                                                     varExpr,
+                                                     domainExpr,
+                                                     posVarExpr,
+                                                     NULL,
+                                                     v.get_allowing_empty());
 
   theFlworClausesStack.push_back(fc);
 }
@@ -6355,9 +6488,9 @@
   var_expr* varExpr = bind_var(loc, varName, var_expr::let_var, type);
 
   let_clause* clause = theExprManager->create_let_clause(theRootSctx,
-                                      loc,
-                                      varExpr,
-                                      domainExpr);
+                                                         loc,
+                                                         varExpr,
+                                                         domainExpr);
 
   theFlworClausesStack.push_back(clause);
 }
@@ -6419,12 +6552,12 @@
                                      window_clause::sliding_window);
 
   window_clause* clause = theExprManager->create_window_clause(theRootSctx,
-                                            v.get_location(),
-                                            winKind,
-                                            NULL,
-                                            windowDomainExpr,
-                                            NULL,
-                                            NULL);
+                                                               v.get_location(),
+                                                               winKind,
+                                                               NULL,
+                                                               windowDomainExpr,
+                                                               NULL,
+                                                               NULL);
 
   theFlworClausesStack.push_back(clause);
 
@@ -6492,11 +6625,11 @@
       pop_wincond_vars(vars, inputCondVarExprs[i]);
 
       conds[i] = theExprManager->create_flwor_wincond(
-                                   theSctx,
-                                   cond->is_only(),
-                                   inputCondVarExprs[i],
-                                   outputCondVarExprs[i],
-                                   condExpr);
+                                                      theSctx,
+                                                      cond->is_only(),
+                                                      inputCondVarExprs[i],
+                                                      outputCondVarExprs[i],
+                                                      condExpr);
     }
     else
     {
@@ -6792,7 +6925,7 @@
       if (inputExpr->get_expr_kind() == var_expr_kind)
       {
         inputExpr = theExprManager->
-        create_wrapper_expr(theRootSctx, specLoc, inputExpr);
+        create_wrapper_expr(theRootSctx, theUDF, specLoc, inputExpr);
       }
 
       inputExpr = wrap_in_atomization(inputExpr);
@@ -6845,7 +6978,7 @@
     bind_var(ngVar, theSctx);
 
     expr* inputExpr =
-    theExprManager->create_wrapper_expr(theRootSctx, loc, inputVar);
+    theExprManager->create_wrapper_expr(theRootSctx, theUDF, loc, inputVar);
 
     nongrouping_rebind.push_back(std::pair<expr*, var_expr*>(inputExpr, ngVar));
   }
@@ -6976,11 +7109,13 @@
     orderExprs[i] = orderExpr;
   }
 
-  orderby_clause* clause = theExprManager->create_orderby_clause(theRootSctx,
-                                              loc,
-                                              v.get_stable_bit(),
-                                              modifiers,
-                                              orderExprs);
+  orderby_clause* clause = theExprManager->
+  create_orderby_clause(theRootSctx,
+                        loc,
+                        v.get_stable_bit(),
+                        modifiers,
+                        orderExprs);
+
   theFlworClausesStack.push_back(clause);
 }
 
@@ -7093,9 +7228,9 @@
   wrap_in_debugger_expr(whereExpr, whereExpr->get_loc());
 
   where_clause* clause = theExprManager->create_where_clause(theRootSctx,
-                                          loc,
-                                          whereExpr);
-
+                                                             loc,
+                                                             whereExpr);
+  
   theFlworClausesStack.push_back(clause);
 }
 
@@ -7120,8 +7255,8 @@
   var_expr* varExpr = bind_var(loc, v.get_varname(), var_expr::count_var, NULL);
 
   count_clause* clause = theExprManager->create_count_clause(theRootSctx,
-                                          loc,
-                                          varExpr);
+                                                             loc,
+                                                             varExpr);
 
   theFlworClausesStack.push_back(clause);
 }
@@ -7196,18 +7331,21 @@
   //          then $atomv cast as xs:string
   //          else $atomv
   //     return NULL]
-  static_cast<flwor_expr*>(atomizedFlwor)->set_return_expr(
-    theExprManager->create_if_expr(theRootSctx,
-                loc,
-                theExprManager->create_instanceof_expr(theRootSctx,
-                                    loc,
-                                    atomv,
-                                    theRTM.UNTYPED_ATOMIC_TYPE_ONE),
-                theExprManager->create_cast_expr(theRootSctx,
-                              loc,
-                              atomv,
-                              theRTM.STRING_TYPE_ONE),
-                atomv));
+  static_cast<flwor_expr*>(atomizedFlwor)->set_return_expr(theExprManager->
+    create_if_expr(theRootSctx,
+                   theUDF,
+                   loc,
+                   theExprManager->create_instanceof_expr(theRootSctx,
+                                                          theUDF,
+                                                          loc,
+                                                          atomv,
+                                                          theRTM.UNTYPED_ATOMIC_TYPE_ONE),
+                   theExprManager->create_cast_expr(theRootSctx,
+                                                    theUDF,
+                                                    loc,
+                                                    atomv,
+                                                    theRTM.STRING_TYPE_ONE),
+                   atomv));
 
   // flworExpr = [let $sv := atomizedFlwor return NULL]
   var_expr* sv = create_temp_var(v.get_switch_expr()->get_location(), var_expr::let_var);
@@ -7240,11 +7378,14 @@
 
       expr* operandExpr = pop_nodestack();
       operandExpr = wrap_in_atomization(operandExpr);
-      operandExpr = theExprManager->create_fo_expr(theRootSctx, loc,
-                                GET_BUILTIN_FUNCTION(OP_ATOMIC_VALUES_EQUIVALENT_2),
-                                sv,
-                                operandExpr);
-
+      operandExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(OP_ATOMIC_VALUES_EQUIVALENT_2),
+                     sv,
+                     operandExpr);
+      
       condOperands.push_back(operandExpr);
     } // for
 
@@ -7254,17 +7395,20 @@
     }
     else if (condOperands.size() > 1)
     {
-      condExpr = theExprManager->create_fo_expr(theRootSctx,
-                             loc,
-                             GET_BUILTIN_FUNCTION(OP_OR_N),
-                             condOperands);
+      condExpr = theExprManager->
+      create_fo_expr(theRootSctx,
+                     theUDF,
+                     loc,
+                     GET_BUILTIN_FUNCTION(OP_OR_N),
+                     condOperands);
     }
 
     switchCaseClause->get_return_expr()->accept(*this);
     expr* caseReturnExpr = pop_nodestack();
 
     // retExpr = [if (condExpr) then caseReturnExpr else retExpr]
-    retExpr = theExprManager->create_if_expr(theRootSctx, loc, condExpr, caseReturnExpr, retExpr);
+    retExpr = theExprManager->
+    create_if_expr(theRootSctx, theUDF, loc, condExpr, caseReturnExpr, retExpr);
 
   } // for
 
@@ -7429,11 +7573,13 @@
 
       caseVar = bind_var(loc, varname, var_expr::let_var);
 
-      expr* treatExpr = theExprManager->create_treat_expr(theRootSctx,
-                                        loc,
-                                        sv,
-                                        type,
-                                        TreatIterator::TREAT_EXPR);
+      expr* treatExpr = theExprManager->
+      create_treat_expr(theRootSctx,
+                        theUDF,
+                        loc,
+                        sv,
+                        type,
+                        TreatIterator::TREAT_EXPR);
 
       // clauseExpr = [let $caseVar := treat_as($sv, caseType) return NULL]
       clauseExpr = wrap_in_let_flwor(treatExpr, caseVar, NULL);
@@ -7456,9 +7602,9 @@
     }
 
     // retExpr = [if (instance_of($sv, type)) then clauseExpr else retExpr]
-    retExpr = theExprManager->create_if_expr(theRootSctx,
+    retExpr = theExprManager->create_if_expr(theRootSctx, theUDF,
                           loc,
-                          theExprManager->create_instanceof_expr(theRootSctx, loc, &*sv, type),
+                          theExprManager->create_instanceof_expr(theRootSctx, theUDF, loc, &*sv, type),
                           clauseExpr,
                           retExpr);
   }
@@ -7545,7 +7691,7 @@
   wrap_in_debugger_expr(t_h, t_h->get_loc());
   wrap_in_debugger_expr(c_h, c_h->get_loc());
 
-  if_expr* ifExpr = theExprManager->create_if_expr(theRootSctx, loc, c_h, t_h, e_h);
+  if_expr* ifExpr = theExprManager->create_if_expr(theRootSctx, theUDF, loc, c_h, t_h, e_h);
 
   push_nodestack(ifExpr);
 }
@@ -7596,7 +7742,7 @@
 
   expr* tryExpr = pop_nodestack();
 
-  trycatch_expr* tce = theExprManager->create_trycatch_expr(theRootSctx, loc, tryExpr);
+  trycatch_expr* tce = theExprManager->create_trycatch_expr(theRootSctx, theUDF, loc, tryExpr);
 
   push_nodestack(tce);
 
@@ -7707,9 +7853,9 @@
 {
   TRACE_VISIT();
 
-  flwor_expr* flwor(theExprManager->create_flwor_expr(theRootSctx, loc, false));
+  flwor_expr* flwor(theExprManager->create_flwor_expr(theRootSctx, theUDF, loc, false));
 
-  flwor->set_return_expr(theExprManager->create_const_expr(theRootSctx, loc, true));
+  flwor->set_return_expr(theExprManager->create_const_expr(theRootSctx, theUDF, loc, true));
 
   push_nodestack(flwor);
 
@@ -7725,7 +7871,7 @@
 
   if (v.get_qmode() == ParseConstants::quant_every)
   {
-    fo_expr* uw = theExprManager->create_fo_expr(theRootSctx,
+    fo_expr* uw = theExprManager->create_fo_expr(theRootSctx, theUDF,
                                        v.get_expr()->get_location(),
                                        GET_BUILTIN_FUNCTION(FN_NOT_1),
                                        testExpr);
@@ -7746,7 +7892,7 @@
 
   flworExpr->add_where(testExpr);
 
-  fo_expr* quant = theExprManager->create_fo_expr(theRootSctx,
+  fo_expr* quant = theExprManager->create_fo_expr(theRootSctx, theUDF,
                                         loc,
                                         v.get_qmode() == ParseConstants::quant_every ?
                                         GET_BUILTIN_FUNCTION(FN_EMPTY_1) :
@@ -7865,7 +8011,7 @@
     args.push_back(e1);
   }
 
-  fo_expr* fo = theExprManager->create_fo_expr(theRootSctx, loc, GET_BUILTIN_FUNCTION(OP_OR_N), args);
+  fo_expr* fo = theExprManager->create_fo_expr(theRootSctx, theUDF, loc, GET_BUILTIN_FUNCTION(OP_OR_N), args);
 
   push_nodestack(fo);
 }
@@ -7930,7 +8076,7 @@
     args.push_back(e1);
   }
 
-  fo_expr* fo = theExprManager->create_fo_expr(theRootSctx, loc, GET_BUILTIN_FUNCTION(OP_AND_N), args);
+  fo_expr* fo = theExprManager->create_fo_expr(theRootSctx, theUDF, loc, GET_BUILTIN_FUNCTION(OP_AND_N), args);
 
   push_nodestack(fo);
 }
@@ -8024,7 +8170,7 @@
   expr* e1 = pop_nodestack();
   expr* e2 = pop_nodestack();
 
-  fo_expr* fo = theExprManager->create_fo_expr(theRootSctx, loc, f, e2, e1);
+  fo_expr* fo = theExprManager->create_fo_expr(theRootSctx, theUDF, loc, f, e2, e1);
 
   normalize_fo(fo);
 
@@ -8095,7 +8241,7 @@
   expr* e1 = pop_nodestack();
   expr* e2 = pop_nodestack();
 
-  fo_expr* e = theExprManager->create_fo_expr(theRootSctx, loc, GET_BUILTIN_FUNCTION(OP_TO_2), e2, e1);
+  fo_expr* e = theExprManager->create_fo_expr(theRootSctx, theUDF, loc, GET_BUILTIN_FUNCTION(OP_TO_2), e2, e1);
 
   normalize_fo(e);
 
@@ -8131,7 +8277,7 @@
     break;
   }
 
-  fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx, loc, func, e2, e1);
+  fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx, theUDF, loc, func, e2, e1);
 
   normalize_fo(foExpr);
 
@@ -8172,7 +8318,7 @@
     break;
   }
 
-  fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx, loc, f, e2, e1);
+  fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx, theUDF, loc, f, e2, e1);
 
   normalize_fo(foExpr);
 
@@ -8196,7 +8342,7 @@
   expr* e1 = pop_nodestack();
   expr* e2 = pop_nodestack();
 
-  fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx,
+  fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx, theUDF,
                                 loc,
                                 GET_BUILTIN_FUNCTION(OP_UNION_2),
                                 e2,
@@ -8206,7 +8352,7 @@
 
   // Union is implemented by a concat iterator, so we have to do node sorting
   // and duplicate elimi
-  push_nodestack(theExprManager->create_fo_expr(theRootSctx,
+  push_nodestack(theExprManager->create_fo_expr(theRootSctx, theUDF,
                              loc,
                              GET_BUILTIN_FUNCTION(OP_SORT_DISTINCT_NODES_ASC_1),
                              foExpr));
@@ -8241,11 +8387,11 @@
     break;
   }
 
-  fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx, loc, f, e2, e1);
+  fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx, theUDF, loc, f, e2, e1);
 
   normalize_fo(foExpr);
 
-  push_nodestack(theExprManager->create_fo_expr(theRootSctx,
+  push_nodestack(theExprManager->create_fo_expr(theRootSctx, theUDF,
                              loc,
                              GET_BUILTIN_FUNCTION(OP_SORT_DISTINCT_NODES_ASC_1),
                              foExpr));
@@ -8265,7 +8411,7 @@
 {
   TRACE_VISIT_OUT();
 
-  push_nodestack(theExprManager->create_instanceof_expr(theRootSctx,
+  push_nodestack(theExprManager->create_instanceof_expr(theRootSctx, theUDF,
                                      loc,
                                      pop_nodestack(),
                                      pop_tstack()));
@@ -8285,7 +8431,7 @@
 {
   TRACE_VISIT_OUT();
 
-  push_nodestack(theExprManager->create_treat_expr(theRootSctx,
+  push_nodestack(theExprManager->create_treat_expr(theRootSctx, theUDF,
                                 loc,
                                 pop_nodestack(),
                                 pop_tstack(),
@@ -8361,9 +8507,9 @@
       assert(castLiteral != NULL || ! isCast);
 
       if (isCast)
-        return theExprManager->create_const_expr(theRootSctx, loc, castLiteral);
+        return theExprManager->create_const_expr(theRootSctx, theUDF, loc, castLiteral);
       else
-        return theExprManager->create_const_expr(theRootSctx, loc, castLiteral != NULL);
+        return theExprManager->create_const_expr(theRootSctx, theUDF, loc, castLiteral != NULL);
     }
     else
     {
@@ -8378,20 +8524,20 @@
         // cast_expr() in order to allow dynamically computed strings to be cast
         // to xs:QName.
         return theExprManager->
-               create_cast_expr(theRootSctx, loc, wrap_in_atomization(node), qnameType);
+               create_cast_expr(theRootSctx, theUDF, loc, wrap_in_atomization(node), qnameType);
       else
         return theExprManager->
-               create_instanceof_expr(theRootSctx, loc, node, qnameType);
+               create_instanceof_expr(theRootSctx, theUDF, loc, node, qnameType);
     }
   }
   else
   {
     if (isCast)
       return theExprManager->
-             create_cast_expr(theRootSctx, loc, wrap_in_atomization(node), type);
+             create_cast_expr(theRootSctx, theUDF, loc, wrap_in_atomization(node), type);
     else
       return theExprManager->
-             create_castable_expr(theRootSctx, loc, wrap_in_atomization(node), type);
+             create_castable_expr(theRootSctx, theUDF, loc, wrap_in_atomization(node), type);
   }
 }
 
@@ -8428,7 +8574,7 @@
 
   expr* e1 = pop_nodestack();
 
-  fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx,
+  fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx, theUDF,
                                 loc,
                                 (v.get_signlist()->get_sign() ?
                                  GET_BUILTIN_FUNCTION(OP_UNARY_PLUS_1) :
@@ -8484,7 +8630,7 @@
                                   v.get_type_name()->get_localname().c_str());
   }
 
-  push_nodestack(theExprManager->create_validate_expr(theRootSctx,
+  push_nodestack(theExprManager->create_validate_expr(theRootSctx, theUDF,
                                    loc,
                                    v.get_valmode(),
                                    qname,
@@ -8794,19 +8940,19 @@
 
               if (lLocal == "true")
               {
-                push_nodestack(theExprManager->create_const_expr(theRootSctx, loc, true));
+                push_nodestack(theExprManager->create_const_expr(theRootSctx, theUDF, loc, true));
                 return (void*)1;
               }
               else if (lLocal == "false")
               {
-                push_nodestack(theExprManager->create_const_expr(theRootSctx, loc, false));
+                push_nodestack(theExprManager->create_const_expr(theRootSctx, theUDF, loc, false));
                 return (void*)1;
               }
               else if (lLocal == "null")
               {
                 store::Item_t lNull;
                 GENV_ITEMFACTORY->createJSONNull(lNull);
-                push_nodestack(theExprManager->create_const_expr(theRootSctx, loc, lNull));
+                push_nodestack(theExprManager->create_const_expr(theRootSctx, theUDF, loc, lNull));
                 return (void*)1;
               }
             }
@@ -8827,7 +8973,7 @@
   // In cases 2, 3, and 4 create a new empty relpath_expr
   if (pe_type != ParseConstants::path_leading_lone_slash)
   {
-    pathExpr = theExprManager->create_relpath_expr(theRootSctx, loc);
+    pathExpr = theExprManager->create_relpath_expr(theRootSctx, theUDF, loc);
   }
 
   // If path expr starts with / or // (cases 1, 2, or 3), create an expr
@@ -8841,9 +8987,9 @@
 
   if (pe_type != ParseConstants::path_relative)
   {
-    relpath_expr* ctx_path_expr = theExprManager->create_relpath_expr(theRootSctx, loc);
+    relpath_expr* ctx_path_expr = theExprManager->create_relpath_expr(theRootSctx, theUDF, loc);
 
-    expr* sourceExpr = theExprManager->create_treat_expr(theRootSctx,
+    expr* sourceExpr = theExprManager->create_treat_expr(theRootSctx, theUDF,
                                        loc,
                                        DOT_REF,
                                        GENV_TYPESYSTEM.ANY_NODE_TYPE_ONE,
@@ -8851,15 +8997,15 @@
 
     ctx_path_expr->add_back(sourceExpr);
 
-    match_expr* me = theExprManager->create_match_expr(theRootSctx, loc);
+    match_expr* me = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
     me->setTestKind(match_anykind_test);
-    axis_step_expr* ase = theExprManager->create_axis_step_expr(theRootSctx, loc);
+    axis_step_expr* ase = theExprManager->create_axis_step_expr(theRootSctx, theUDF, loc);
     ase->setAxis(axis_kind_self);
     ase->setTest(me);
 
     ctx_path_expr->add_back(&*ase);
 
-    fo_expr* fnroot = theExprManager->create_fo_expr(theRootSctx,
+    fo_expr* fnroot = theExprManager->create_fo_expr(theRootSctx, theUDF,
                                    loc,
                                    GET_BUILTIN_FUNCTION(FN_ROOT_1),
                                    ctx_path_expr);
@@ -8876,7 +9022,7 @@
     else
     {
       // case 1
-      expr* result = theExprManager->create_treat_expr(theRootSctx,
+      expr* result = theExprManager->create_treat_expr(theRootSctx, theUDF,
                                      loc,
                                      fnroot,
                                      GENV_TYPESYSTEM.DOCUMENT_TYPE_ONE,
@@ -8916,7 +9062,7 @@
   else
   {
     fo_expr* checkExpr =
-      theExprManager->create_fo_expr(theRootSctx,
+      theExprManager->create_fo_expr(theRootSctx, theUDF,
                   arg2->get_loc(),
                   GET_BUILTIN_FUNCTION(OP_EITHER_NODES_OR_ATOMICS_1),
                   arg2);
@@ -8967,7 +9113,7 @@
     // then the input expr to the this path expr is "treat . as node()"
     if (axisStep != NULL)
     {
-      expr* sourceExpr = theExprManager->create_treat_expr(theRootSctx,
+      expr* sourceExpr = theExprManager->create_treat_expr(theRootSctx, theUDF,
                                          loc,
                                          DOT_REF,
                                          GENV_TYPESYSTEM.ANY_NODE_TYPE_ONE,
@@ -9054,7 +9200,7 @@
           errKind = TreatIterator::PATH_DOT;
       }
 
-      expr* sourceExpr = theExprManager->create_treat_expr(theRootSctx,
+      expr* sourceExpr = theExprManager->create_treat_expr(theRootSctx, theUDF,
                                          stepExpr->get_loc(),
                                          stepExpr,
                                          GENV_TYPESYSTEM.ANY_NODE_TYPE_STAR,
@@ -9085,7 +9231,7 @@
     flworExpr->set_return_expr(stepExpr);
     pop_scope();
 
-    pathExpr = theExprManager->create_relpath_expr(theRootSctx, loc);
+    pathExpr = theExprManager->create_relpath_expr(theRootSctx, theUDF, loc);
 
     expr* sourceExpr = flworExpr;
 
@@ -9108,8 +9254,8 @@
   // Convert // to /descendant-or-self::node()/
   if (rpe.get_step_type() == ParseConstants::st_slashslash)
   {
-    axis_step_expr* ase = theExprManager->create_axis_step_expr(theRootSctx, loc);
-    match_expr* me = theExprManager->create_match_expr(theRootSctx, loc);
+    axis_step_expr* ase = theExprManager->create_axis_step_expr(theRootSctx, theUDF, loc);
+    match_expr* me = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
     me->setTestKind(match_anykind_test);
     ase->setAxis(axis_kind_descendant_or_self);
     ase->setTest(me);
@@ -9202,7 +9348,7 @@
 {
   TRACE_VISIT();
 
-  axis_step_expr* ase = theExprManager->create_axis_step_expr(theRootSctx, loc);
+  axis_step_expr* ase = theExprManager->create_axis_step_expr(theRootSctx, theUDF, loc);
   push_nodestack(ase);
 
   theNodeSortStack.top().theNumSteps++;
@@ -9258,8 +9404,8 @@
   //
   // The flworExpr as well as the $$predInput varExpr are pushed to the nodestack.
   const for_clause* fcOuterDot = static_cast<const for_clause*>(flworExpr->get_clause(0));
-  relpath_expr* predPathExpr = theExprManager->create_relpath_expr(theRootSctx, loc);
-  predPathExpr->add_back(theExprManager->create_wrapper_expr(theRootSctx, loc, fcOuterDot->get_var()));
+  relpath_expr* predPathExpr = theExprManager->create_relpath_expr(theRootSctx, theUDF, loc);
+  predPathExpr->add_back(theExprManager->create_wrapper_expr(theRootSctx, theUDF, loc, fcOuterDot->get_var()));
   predPathExpr->add_back(axisExpr);
 
   expr* predInputExpr = predPathExpr;
@@ -9490,7 +9636,7 @@
   if ((axisExpr = dynamic_cast<axis_step_expr *>(top)) != NULL)
   {
     // Construct name-test match expr
-    match_expr* matchExpr = theExprManager->create_match_expr(theRootSctx, loc);;
+    match_expr* matchExpr = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
     matchExpr->setTestKind(match_name_test);
 
     if (v.getQName() != NULL)
@@ -9780,6 +9926,7 @@
 
         fo_expr* pointExpr = theExprManager->
         create_fo_expr(sourceExpr->get_sctx(),
+                       theUDF,
                        sourceExpr->get_loc(),
                        GET_BUILTIN_FUNCTION(OP_ZORBA_SEQUENCE_POINT_ACCESS_2),
                        sourceExpr,
@@ -9793,6 +9940,7 @@
 
         fo_expr* pointExpr = theExprManager->
         create_fo_expr(sourceExpr->get_sctx(),
+                       theUDF,
                        sourceExpr->get_loc(),
                        GET_BUILTIN_FUNCTION(OP_ZORBA_SEQUENCE_POINT_ACCESS_2),
                        sourceExpr,
@@ -9814,6 +9962,7 @@
       // return if ($$dot eq $$predVar) then $$dot else ()
       fo_expr* eqExpr = theExprManager->
       create_fo_expr(theRootSctx,
+                     theUDF,
                      loc,
                      GET_BUILTIN_FUNCTION(OP_VALUE_EQUAL_2),
                      lookup_ctx_var(DOT_POS_VARNAME, loc),
@@ -9822,7 +9971,7 @@
       normalize_fo(eqExpr);
 
       expr* retExpr = theExprManager->
-      create_if_expr(theRootSctx, loc, eqExpr, DOT_REF, create_empty_seq(loc));
+      create_if_expr(theRootSctx, theUDF, loc, eqExpr, DOT_REF, create_empty_seq(loc));
 
       flworExpr->set_return_expr(retExpr);
 
@@ -9855,21 +10004,22 @@
   std::vector<expr*> condOperands(3);
 
   condOperands[0] = theExprManager->
-  create_instanceof_expr(theRootSctx, loc, predvar, rtm.DECIMAL_TYPE_QUESTION, true);
+  create_instanceof_expr(theRootSctx, theUDF, loc, predvar, rtm.DECIMAL_TYPE_QUESTION, true);
 
   condOperands[1] = theExprManager->
-  create_instanceof_expr(theRootSctx, loc, predvar, rtm.DOUBLE_TYPE_QUESTION, true);
+  create_instanceof_expr(theRootSctx, theUDF, loc, predvar, rtm.DOUBLE_TYPE_QUESTION, true);
 
   condOperands[2] = theExprManager->
-  create_instanceof_expr(theRootSctx, loc, predvar, rtm.FLOAT_TYPE_QUESTION, true);
+  create_instanceof_expr(theRootSctx, theUDF, loc, predvar, rtm.FLOAT_TYPE_QUESTION, true);
 
   condExpr = theExprManager->
-  create_fo_expr(theRootSctx, loc, GET_BUILTIN_FUNCTION(OP_OR_N), condOperands);
+  create_fo_expr(theRootSctx, theUDF, loc, GET_BUILTIN_FUNCTION(OP_OR_N), condOperands);
 
   // If so: return $dot if the value of the pred expr is equal to the value
   // of $dot_pos var, otherwise return the empty seq.
   fo_expr* eqExpr = theExprManager->
   create_fo_expr(theRootSctx,
+                 theUDF,
                  loc,
                  GET_BUILTIN_FUNCTION(OP_VALUE_EQUAL_2),
                  lookup_ctx_var(DOT_POS_VARNAME, loc),
@@ -9878,16 +10028,16 @@
   normalize_fo(eqExpr);
 
   expr* thenExpr = theExprManager->
-  create_if_expr(theRootSctx, loc, eqExpr, DOT_REF, create_empty_seq(loc));
+  create_if_expr(theRootSctx, theUDF, loc, eqExpr, DOT_REF, create_empty_seq(loc));
 
   // Else, return $dot if the the value of the pred expr is true, otherwise
   // return the empty seq.
   expr* elseExpr = theExprManager->
-  create_if_expr(theRootSctx, loc, predvar, DOT_REF, create_empty_seq(loc));
+  create_if_expr(theRootSctx, theUDF, loc, predvar, DOT_REF, create_empty_seq(loc));
 
   // The outer if
   expr* ifExpr = theExprManager->
-  create_if_expr(theRootSctx, loc, condExpr, thenExpr, elseExpr);
+  create_if_expr(theRootSctx, theUDF, loc, condExpr, thenExpr, elseExpr);
 
   flworExpr->set_return_expr(ifExpr);
 
@@ -9955,17 +10105,17 @@
   {
   case ParseConstants::num_integer:
   {
-    push_nodestack(theExprManager->create_const_expr(theRootSctx, loc, v.get<xs_integer>()));
+    push_nodestack(theExprManager->create_const_expr(theRootSctx, theUDF, loc, v.get<xs_integer>()));
     break;
   }
   case ParseConstants::num_decimal:
   {
-    push_nodestack(theExprManager->create_const_expr(theRootSctx, loc, v.get<xs_decimal>()));
+    push_nodestack(theExprManager->create_const_expr(theRootSctx, theUDF, loc, v.get<xs_decimal>()));
     break;
   }
   case ParseConstants::num_double:
   {
-    push_nodestack(theExprManager->create_const_expr(theRootSctx, loc, v.get<xs_double>()));
+    push_nodestack(theExprManager->create_const_expr(theRootSctx, theUDF, loc, v.get<xs_double>()));
     break;
   }
   }
@@ -10002,7 +10152,7 @@
 {
   TRACE_VISIT_OUT();
 
-  push_nodestack(theExprManager->create_const_expr(theRootSctx, loc,v.get_strval().str()));
+  push_nodestack(theExprManager->create_const_expr(theRootSctx, theUDF, loc, v.get_strval().str()));
 }
 
 /*******************************************************************************
@@ -10046,6 +10196,7 @@
 
   expr* concat =
   theExprManager->create_fo_expr(theRootSctx,
+                                 theUDF,
                                  loc,
                                  GET_BUILTIN_FUNCTION(FN_CONCAT_N),
                                  concat_args);
@@ -10139,7 +10290,7 @@
     }
   }
 
-  push_nodestack(theExprManager->create_wrapper_expr(theRootSctx,
+  push_nodestack(theExprManager->create_wrapper_expr(theRootSctx, theUDF,
                                                      loc,
                                                      ve));
 }
@@ -10206,7 +10357,7 @@
 {
   TRACE_VISIT_OUT();
 
-  push_nodestack(theExprManager->create_order_expr(theRootSctx,
+  push_nodestack(theExprManager->create_order_expr(theRootSctx, theUDF,
                                 loc,
                                 order_expr::ordered,
                                 pop_nodestack()));
@@ -10227,7 +10378,7 @@
 {
   TRACE_VISIT_OUT();
 
-  push_nodestack(theExprManager->create_order_expr(theRootSctx,
+  push_nodestack(theExprManager->create_order_expr(theRootSctx, theUDF,
                                 loc,
                                 order_expr::unordered,
                                 pop_nodestack()));
@@ -10381,15 +10532,15 @@
       case FunctionConsts::FN_HEAD_1:
       {
         arguments.push_back(theExprManager->
-                            create_const_expr(theRootSctx, loc, xs_integer::one()));
+                            create_const_expr(theRootSctx, theUDF, loc, xs_integer::one()));
 
         arguments.push_back(theExprManager->
-                            create_const_expr(theRootSctx, loc, xs_integer::one()));
+                            create_const_expr(theRootSctx, theUDF, loc, xs_integer::one()));
 
         function* f = GET_BUILTIN_FUNCTION(OP_ZORBA_SUBSEQUENCE_INT_3);
 
         fo_expr* foExpr = theExprManager->
-        create_fo_expr(theRootSctx, loc, f, arguments);
+        create_fo_expr(theRootSctx, theUDF, loc, f, arguments);
 
         normalize_fo(foExpr);
 
@@ -10399,12 +10550,12 @@
       case FunctionConsts::FN_TAIL_1:
       {
         arguments.push_back(theExprManager->
-                            create_const_expr(theRootSctx, loc, xs_integer(2)));
+                            create_const_expr(theRootSctx, theUDF, loc, xs_integer(2)));
 
         function* f = GET_BUILTIN_FUNCTION(OP_ZORBA_SUBSEQUENCE_INT_2);
 
         fo_expr* foExpr = theExprManager->
-        create_fo_expr(theRootSctx, loc, f, arguments);
+        create_fo_expr(theRootSctx, theUDF, loc, f, arguments);
 
         normalize_fo(foExpr);
 
@@ -10445,7 +10596,7 @@
         }
 
         fo_expr* foExpr = theExprManager->
-        create_fo_expr(theRootSctx, loc, f, arguments);
+        create_fo_expr(theRootSctx, theUDF, loc, f, arguments);
 
         normalize_fo(foExpr);
         push_nodestack(foExpr);
@@ -10481,17 +10632,18 @@
 
         var_expr* tv = create_temp_var(loc, var_expr::let_var);
 
-        expr* nanExpr = theExprManager->create_const_expr(theRootSctx, loc, xs_double::nan());
+        expr* nanExpr = theExprManager->create_const_expr(theRootSctx, theUDF, loc, xs_double::nan());
 
-        expr* condExpr = theExprManager->create_castable_expr(theRootSctx, loc, &*tv, theRTM.DOUBLE_TYPE_ONE);
+        expr* condExpr = theExprManager->create_castable_expr(theRootSctx, theUDF, loc, &*tv, theRTM.DOUBLE_TYPE_ONE);
 
         expr* castExpr = create_cast_expr(loc, tv, theRTM.DOUBLE_TYPE_ONE, true);
 
-        expr* ret = theExprManager->create_if_expr(theRootSctx, loc, condExpr, castExpr, nanExpr);
+        expr* ret = theExprManager->create_if_expr(theRootSctx, theUDF, loc, condExpr, castExpr, nanExpr);
 
         expr* data_expr = wrap_in_atomization(arguments[0]);
 
         push_nodestack(wrap_in_let_flwor(theExprManager->create_treat_expr(theRootSctx,
+                                                                           theUDF,
                                                           loc,
                                                           data_expr,
                                                           theRTM.ANY_ATOMIC_TYPE_QUESTION,
@@ -10512,9 +10664,9 @@
         if (baseuri.empty())
           push_nodestack(create_empty_seq(loc));
         else
-          push_nodestack(theExprManager->create_cast_expr(theRootSctx,
+          push_nodestack(theExprManager->create_cast_expr(theRootSctx, theUDF,
                                        loc,
-                                       theExprManager->create_const_expr(theRootSctx, loc, baseuri),
+                                       theExprManager->create_const_expr(theRootSctx, theUDF, loc, baseuri),
                                        theRTM.ANY_URI_TYPE_ONE));
         return;
       }
@@ -10539,15 +10691,15 @@
         fo_expr* normExpr = NULL;
         fo_expr* tokenExpr = NULL;
         zstring space(" ");
-        const_expr* constExpr = theExprManager->create_const_expr(theRootSctx, loc, space);
+        const_expr* constExpr = theExprManager->create_const_expr(theRootSctx, theUDF, loc, space);
 
-        normExpr = theExprManager->create_fo_expr(theRootSctx,
+        normExpr = theExprManager->create_fo_expr(theRootSctx, theUDF,
                                loc,
                                GET_BUILTIN_FUNCTION(FN_NORMALIZE_SPACE_1),
                                flworVarExpr);
         normalize_fo(normExpr);
 
-        tokenExpr = theExprManager->create_fo_expr(theRootSctx,
+        tokenExpr = theExprManager->create_fo_expr(theRootSctx, theUDF,
                                 loc,
                                 GET_BUILTIN_FUNCTION(FN_TOKENIZE_2),
                                 normExpr,
@@ -10576,7 +10728,7 @@
       case FunctionConsts::FN_RESOLVE_URI_1:
       {
         zstring baseUri = theSctx->get_base_uri();
-        arguments.insert(arguments.begin(), theExprManager->create_const_expr(theRootSctx, loc, baseUri));
+        arguments.insert(arguments.begin(), theExprManager->create_const_expr(theRootSctx, theUDF, loc, baseUri));
         f = GET_BUILTIN_FUNCTION(FN_RESOLVE_URI_2);
         break;
       }
@@ -10623,7 +10775,7 @@
   if (f != NULL && f->getKind() ==  FunctionConsts::FN_APPLY_1)
   {
     expr* applyExpr = theExprManager->
-    create_apply_expr(theRootSctx, loc, arguments[0], false);
+    create_apply_expr(theRootSctx, theUDF, loc, arguments[0], false);
 
     push_nodestack(applyExpr);
     return;
@@ -10715,7 +10867,7 @@
     // Create and normalize the fo expr
     std::reverse(arguments.begin(), arguments.end());
 
-    fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx, loc, f, arguments);
+    fo_expr* foExpr = theExprManager->create_fo_expr(theRootSctx, theUDF, loc, f, arguments);
 
     normalize_fo(foExpr);
 
@@ -10741,7 +10893,7 @@
       {
         FunctionConsts::FunctionKind fkind = FunctionConsts::OP_SORT_DISTINCT_NODES_ASC_1;
 
-        resultExpr = theExprManager->create_fo_expr(theRootSctx,
+        resultExpr = theExprManager->create_fo_expr(theRootSctx, theUDF,
                                  foExpr->get_loc(),
                                  BuiltinFunctionLibrary::getFunction(fkind),
                                  foExpr);
@@ -10789,6 +10941,7 @@
 
         eval_expr* evalExpr = theExprManager->
         create_eval_expr(theRootSctx,
+                         theUDF,
                          loc,
                          foExpr->get_arg(0),
                          scriptingKind,
@@ -10856,7 +11009,7 @@
 
         // create a flwor with LETs to hold the parameters
         flwor_expr* flworExpr = theExprManager->
-        create_flwor_expr(theRootSctx, loc, false);
+        create_flwor_expr(theRootSctx, theUDF, loc, false);
 
         // wrap function's QName
         expr* qnameExpr = wrap_in_type_promotion(arguments[0],
@@ -10899,26 +11052,26 @@
 
         // Expanded QName's namespace URI
         expr* namespaceExpr =
-        theExprManager->create_fo_expr(theRootSctx,
+        theExprManager->create_fo_expr(theRootSctx, theUDF,
                     loc,
                     GET_BUILTIN_FUNCTION(FN_NAMESPACE_URI_FROM_QNAME_1),
                     temp_vars[0]);
 
         namespaceExpr =
-        theExprManager->create_fo_expr(theRootSctx,
+        theExprManager->create_fo_expr(theRootSctx, theUDF,
                     loc,
                     GET_BUILTIN_FUNCTION(FN_STRING_1),
                     namespaceExpr);
 
         // Expanded QName's local name
         expr* localExpr =
-        theExprManager->create_fo_expr(theRootSctx,
+        theExprManager->create_fo_expr(theRootSctx, theUDF,
                     loc,
                     GET_BUILTIN_FUNCTION(FN_LOCAL_NAME_FROM_QNAME_1),
                     temp_vars[0]);
 
         localExpr = theExprManager->
-        create_fo_expr(theRootSctx, loc, GET_BUILTIN_FUNCTION(FN_STRING_1), localExpr);
+        create_fo_expr(theRootSctx, theUDF, loc, GET_BUILTIN_FUNCTION(FN_STRING_1), localExpr);
 
         // qnameExpr := concat("Q{",
         //                     namespaceExpr,
@@ -10926,20 +11079,20 @@
         //                     localExpr,
         //                     "($temp_invoke_var2, $temp_invoke_var3,...)")
         std::vector<expr*> concat_args;
-        concat_args.push_back(theExprManager->create_const_expr(theRootSctx, loc, "Q{"));
+        concat_args.push_back(theExprManager->create_const_expr(theRootSctx, theUDF, loc, "Q{"));
         concat_args.push_back(namespaceExpr);
-        concat_args.push_back(theExprManager->create_const_expr(theRootSctx, loc, "}"));
+        concat_args.push_back(theExprManager->create_const_expr(theRootSctx, theUDF, loc, "}"));
         concat_args.push_back(localExpr);
-        concat_args.push_back(theExprManager->create_const_expr(theRootSctx, loc, query_params));
+        concat_args.push_back(theExprManager->create_const_expr(theRootSctx, theUDF, loc, query_params));
 
         qnameExpr = theExprManager->
-        create_fo_expr(theRootSctx,
+        create_fo_expr(theRootSctx, theUDF,
                        loc,
                        GET_BUILTIN_FUNCTION(FN_CONCAT_N),
                        concat_args);
 
         eval_expr* evalExpr = theExprManager->
-        create_eval_expr(theRootSctx,
+        create_eval_expr(theRootSctx, theUDF,
                          loc,
                          qnameExpr,
                          scriptingKind,
@@ -11056,7 +11209,7 @@
       func = GET_BUILTIN_FUNCTION(OP_ZORBA_JSON_ITEM_ACCESSOR_2);
     }
 
-    accessorExpr = theExprManager->create_fo_expr(theRootSctx,
+    accessorExpr = theExprManager->create_fo_expr(theRootSctx, theUDF,
                                                   loc,
                                                   func,
                                                   flworVarExpr,
@@ -11081,7 +11234,7 @@
   }
 
   expr* dynFuncInvocation =
-  theExprManager->create_dynamic_function_invocation_expr(theRootSctx,
+  theExprManager->create_dynamic_function_invocation_expr(theRootSctx, theUDF,
                                                           loc,
                                                           sourceExpr,
                                                           arguments);
@@ -11150,13 +11303,12 @@
       var_expr* argVar = create_temp_var(loc, var_expr::arg_var);
 
       argVar->set_param_pos(i);
-      argVar->set_udf(udf);
 
       udfArgs[i] = argVar;
       foArgs[i] = argVar;
     }
 
-    expr* body = theExprManager->create_fo_expr(theRootSctx, loc, fn, foArgs);
+    expr* body = theExprManager->create_fo_expr(theRootSctx, theUDF, loc, fn, foArgs);
 
     udf->setArgVars(udfArgs);
     udf->setBody(body);
@@ -11164,7 +11316,7 @@
     fn = udf;
   }
 
-  expr* fiExpr = theExprManager->create_function_item_expr(theRootSctx, loc, fn->getName(), fn, arity);
+  expr* fiExpr = theExprManager->create_function_item_expr(theRootSctx, theUDF, loc, fn->getName(), fn, arity);
 
   push_nodestack(fiExpr);
 }
@@ -11180,11 +11332,8 @@
 
   if ( !theSctx->is_feature_set(feature::hof) )
   {
-    throw XQUERY_EXCEPTION(
-      zerr::ZXQP0050_FEATURE_NOT_AVAILABLE,
-      ERROR_PARAMS( "higher-order functions (hof)" ),
-      ERROR_LOC( v.get_location() )
-    );
+    RAISE_ERROR(zerr::ZXQP0050_FEATURE_NOT_AVAILABLE, loc,
+    ERROR_PARAMS("higher-order functions (hof)"));
   }
 
   // Get the in-scope vars of the scope before opening the new scope for the
@@ -11194,7 +11343,7 @@
 
   push_scope();
 
-  function_item_expr* fiExpr = theExprManager->create_function_item_expr(theRootSctx, loc);
+  function_item_expr* fiExpr = theExprManager->create_function_item_expr(theRootSctx, theUDF, loc);
 
   push_nodestack(fiExpr);
 
@@ -11217,7 +11366,7 @@
   }
   else
   {
-    flwor = theExprManager->create_flwor_expr(theRootSctx, loc, false);
+    flwor = theExprManager->create_flwor_expr(theRootSctx, theUDF, loc, false);
   }
 
   // Handle inscope variables. For each inscope var, a let binding is added to
@@ -11403,7 +11552,7 @@
     contentExpr = pop_nodestack();
   }
 
-  push_nodestack(theExprManager->create_json_array_expr(theRootSctx, loc, contentExpr));
+  push_nodestack(theExprManager->create_json_array_expr(theRootSctx, theUDF, loc, contentExpr));
 #endif
 }
 
@@ -11437,6 +11586,7 @@
 
     contentExpr = theExprManager->
     create_treat_expr(theRootSctx,
+                      theUDF,
                       contentExpr->get_loc(),
                       contentExpr,
                       GENV_TYPESYSTEM.JSON_OBJECT_TYPE_STAR,
@@ -11446,7 +11596,7 @@
   }
 
   expr* jo = theExprManager->
-  create_json_object_expr(theRootSctx, loc, contentExpr, v.get_accumulate());
+  create_json_object_expr(theRootSctx, theUDF, loc, contentExpr, v.get_accumulate());
 
   push_nodestack(jo);
 #endif
@@ -11483,7 +11633,7 @@
   }
 
   expr* jo = theExprManager->
-  create_json_direct_object_expr(theRootSctx, loc, names, values);
+  create_json_direct_object_expr(theRootSctx, theUDF, loc, names, values);
 
   push_nodestack(jo);
 #endif
@@ -11539,12 +11689,14 @@
 
   nameExpr = theExprManager->
   create_cast_expr(theRootSctx,
+                   theUDF,
                    nameExpr->get_loc(),
                    nameExpr,
                    GENV_TYPESYSTEM.STRING_TYPE_ONE);
 
   valueExpr = theExprManager->
   create_fo_expr(theRootSctx,
+                 theUDF,
                  valueExpr->get_loc(),
                  GET_BUILTIN_FUNCTION(OP_ZORBA_JSON_BOX_1),
                  valueExpr);
@@ -11634,12 +11786,12 @@
   store::Item_t qnameItem;
   expand_elem_qname(qnameItem, v.get_elem_name(), loc);
 
-  nameExpr = theExprManager->create_const_expr(theRootSctx, loc, qnameItem);
+  nameExpr = theExprManager->create_const_expr(theRootSctx, theUDF, loc, qnameItem);
 
   bool copyNodes = (theCCB->theConfig.opt_level < CompilerCB::config::O1 ||
                     !Properties::instance()->noCopyOptim());
 
-  push_nodestack(theExprManager->create_elem_expr(theRootSctx,
+  push_nodestack(theExprManager->create_elem_expr(theRootSctx, theUDF,
                                loc,
                                nameExpr,
                                attrExpr,
@@ -11711,7 +11863,7 @@
     }
 
     fo_expr* expr_list =
-    theExprManager->create_fo_expr(theRootSctx, loc, op_concatenate, args);
+    theExprManager->create_fo_expr(theRootSctx, theUDF, loc, op_concatenate, args);
 
     normalize_fo(expr_list);
 
@@ -11852,7 +12004,7 @@
     store::Item_t qnameItem;
     expand_no_default_qname(qnameItem, qname, qname->get_location());
 
-    expr* nameExpr = theExprManager->create_const_expr(theRootSctx, loc, qnameItem);
+    expr* nameExpr = theExprManager->create_const_expr(theRootSctx, theUDF, loc, qnameItem);
 
     fo_expr* foExpr = NULL;
     if ((foExpr = dynamic_cast<fo_expr*>(valueExpr)) != NULL &&
@@ -11865,7 +12017,7 @@
       valueExpr = wrap_in_atomization(valueExpr);
     }
 
-    expr* attrExpr = theExprManager->create_attr_expr(theRootSctx, loc, nameExpr, valueExpr);
+    expr* attrExpr = theExprManager->create_attr_expr(theRootSctx, theUDF, loc, nameExpr, valueExpr);
 
     push_nodestack(attrExpr);
   }
@@ -11904,7 +12056,7 @@
   else
   {
     fo_expr* expr_list = theExprManager->
-    create_fo_expr(theRootSctx, loc, op_concatenate, args);
+    create_fo_expr(theRootSctx, theUDF, loc, op_concatenate, args);
 
     normalize_fo(expr_list);
 
@@ -11938,9 +12090,9 @@
   {
     if (!v.isStripped())
     {
-      expr* content = theExprManager->create_const_expr(theRootSctx, loc, v.get_elem_content().str());
+      expr* content = theExprManager->create_const_expr(theRootSctx, theUDF, loc, v.get_elem_content().str());
 
-      push_nodestack(theExprManager->create_text_expr(theRootSctx, loc,
+      push_nodestack(theExprManager->create_text_expr(theRootSctx, theUDF, loc,
                                    text_expr::text_constructor,
                                    content));
     }
@@ -12044,8 +12196,8 @@
   // Skip empty CDATA sections
   if(!lCDATA_content.empty())
   {
-    expr* content = theExprManager->create_const_expr(theRootSctx, loc, lCDATA_content);
-    push_nodestack(theExprManager->create_text_expr(theRootSctx, loc, text_expr::text_constructor, content));
+    expr* content = theExprManager->create_const_expr(theRootSctx, theUDF, loc, lCDATA_content);
+    push_nodestack(theExprManager->create_text_expr(theRootSctx, theUDF, loc, text_expr::text_constructor, content));
   }
 }
 
@@ -12081,7 +12233,7 @@
   else if (args.size() > 1)
   {
     fo_expr* expr_list = theExprManager->
-    create_fo_expr(theRootSctx, loc, op_concatenate, args);
+    create_fo_expr(theRootSctx, theUDF, loc, op_concatenate, args);
 
     normalize_fo(expr_list);
 
@@ -12124,7 +12276,7 @@
 {
   if (cc == NULL)
   {
-    push_nodestack(theExprManager->create_const_expr (theRootSctx, loc, content));
+    push_nodestack(theExprManager->create_const_expr (theRootSctx, theUDF, loc, content));
   }
   else
   {
@@ -12203,7 +12355,7 @@
         curRef++;
     }
 
-    expr* lConstExpr = theExprManager->create_const_expr(theRootSctx, loc, content);
+    expr* lConstExpr = theExprManager->create_const_expr(theRootSctx, theUDF, loc, content);
     push_nodestack(lConstExpr);
     break;
   }
@@ -12212,7 +12364,7 @@
     // we always create a text node here because if we are in an attribute, we atomice
     // the text node into its string value
     zstring content("{");
-    expr* lConstExpr = theExprManager->create_const_expr(theRootSctx, loc, content);
+    expr* lConstExpr = theExprManager->create_const_expr(theRootSctx, theUDF, loc, content);
     push_nodestack ( lConstExpr );
     break;
   }
@@ -12221,7 +12373,7 @@
     // we always create a text node here because if we are in an attribute, we atomice
     // the text node into its string value
     zstring content("}");
-    expr* lConstExpr = theExprManager->create_const_expr(theRootSctx, loc, content);
+    expr* lConstExpr = theExprManager->create_const_expr(theRootSctx, theUDF, loc, content);
     push_nodestack ( lConstExpr );
     break;
   }
@@ -12244,8 +12396,8 @@
   TRACE_VISIT_OUT();
 
   zstring str = v.get_comment().str();
-  expr* content = theExprManager->create_const_expr (theRootSctx, loc, str);
-  push_nodestack (theExprManager->create_text_expr(theRootSctx, loc,
+  expr* content = theExprManager->create_const_expr (theRootSctx, theUDF, loc, str);
+  push_nodestack (theExprManager->create_text_expr(theRootSctx, theUDF, loc,
                                 text_expr::comment_constructor,
                                 content));
 }
@@ -12268,10 +12420,10 @@
   if (target_upper == "XML")
     RAISE_ERROR(err::XPST0003, loc, ERROR_PARAMS(ZED(XPST0003_PiTarget)));
 
-  expr* target = theExprManager->create_const_expr(theRootSctx, loc, target_str);
-  expr* content = theExprManager->create_const_expr(theRootSctx, loc, v.get_pi_content().str());
+  expr* target = theExprManager->create_const_expr(theRootSctx, theUDF, loc, target_str);
+  expr* content = theExprManager->create_const_expr(theRootSctx, theUDF, loc, v.get_pi_content().str());
 
-  push_nodestack(theExprManager->create_pi_expr(theRootSctx, loc, target,  content));
+  push_nodestack(theExprManager->create_pi_expr(theRootSctx, theUDF, loc, target,  content));
 }
 
 
@@ -12292,7 +12444,7 @@
   bool copyNodes = (theCCB->theConfig.opt_level < CompilerCB::config::O1 ||
                     !Properties::instance()->noCopyOptim());
 
-  push_nodestack(theExprManager->create_doc_expr(theRootSctx, loc, lEnclosed, copyNodes));
+  push_nodestack(theExprManager->create_doc_expr(theRootSctx, theUDF, loc, lEnclosed, copyNodes));
 }
 
 
@@ -12325,14 +12477,14 @@
     store::Item_t qnameItem;
     expand_elem_qname(qnameItem, constQName, loc);
 
-    nameExpr = theExprManager->create_const_expr(theRootSctx, loc, qnameItem);
+    nameExpr = theExprManager->create_const_expr(theRootSctx, theUDF, loc, qnameItem);
   }
   else
   {
     nameExpr = pop_nodestack();
 
     expr* atomExpr = wrap_in_atomization(nameExpr);
-    nameExpr = theExprManager->create_name_cast_expr(theRootSctx,
+    nameExpr = theExprManager->create_name_cast_expr(theRootSctx, theUDF,
                                                      loc,
                                                      atomExpr,
                                                      theNSCtx,
@@ -12342,7 +12494,7 @@
   bool copyNodes = (theCCB->theConfig.opt_level < CompilerCB::config::O1 ||
                     !Properties::instance()->noCopyOptim());
 
-  push_nodestack(theExprManager->create_elem_expr(theRootSctx,
+  push_nodestack(theExprManager->create_elem_expr(theRootSctx, theUDF,
                                                   loc,
                                                   nameExpr,
                                                   contentExpr,
@@ -12379,20 +12531,20 @@
     store::Item_t qnameItem;
     expand_no_default_qname(qnameItem, constQName, constQName->get_location());
 
-    nameExpr = theExprManager->create_const_expr(theRootSctx, loc, qnameItem);
+    nameExpr = theExprManager->create_const_expr(theRootSctx, theUDF, loc, qnameItem);
   }
   else
   {
     nameExpr = pop_nodestack();
     expr* atomExpr = wrap_in_atomization(nameExpr);
-    nameExpr = theExprManager->create_name_cast_expr(theRootSctx,
+    nameExpr = theExprManager->create_name_cast_expr(theRootSctx, theUDF,
                                                      loc,
                                                      atomExpr,
                                                      theNSCtx,
                                                      true);
   }
 
-  attrExpr = theExprManager->create_attr_expr(theRootSctx, loc, nameExpr, valueExpr);
+  attrExpr = theExprManager->create_attr_expr(theRootSctx, theUDF, loc, nameExpr, valueExpr);
 
   push_nodestack(attrExpr);
 }
@@ -12412,7 +12564,7 @@
 
   fo_expr* enclosedExpr = wrap_in_enclosed_expr(inputExpr, loc);
 
-  expr* textExpr = theExprManager->create_text_expr(theRootSctx, loc,
+  expr* textExpr = theExprManager->create_text_expr(theRootSctx, theUDF, loc,
                                                      text_expr::comment_constructor,
                                                      enclosedExpr);
 
@@ -12454,8 +12606,8 @@
   }
 
   expr* e = (v.get_target_expr () != NULL ?
-              theExprManager->create_pi_expr(theRootSctx, loc, target, content) :
-              theExprManager->create_pi_expr(theRootSctx, loc, theExprManager->create_const_expr(theRootSctx, loc, v.get_target().str()), content));
+              theExprManager->create_pi_expr(theRootSctx, theUDF, loc, target, content) :
+              theExprManager->create_pi_expr(theRootSctx, theUDF, loc, theExprManager->create_const_expr(theRootSctx, theUDF, loc, v.get_target().str()), content));
 
   push_nodestack (e);
 }
@@ -12475,7 +12627,7 @@
 
   fo_expr* enclosedExpr = wrap_in_enclosed_expr(inputExpr, loc);
 
-  expr* textExpr = theExprManager->create_text_expr(theRootSctx,
+  expr* textExpr = theExprManager->create_text_expr(theRootSctx, theUDF,
                                                      loc,
                                                      text_expr::text_constructor,
                                                      enclosedExpr);
@@ -12732,7 +12884,7 @@
     dynamic_cast<axis_step_expr*>(peek_nodestk_or_null());
   if (axisExpr != NULL)
   {
-    match_expr* me = theExprManager->create_match_expr(theRootSctx, loc);
+    match_expr* me = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
     me->setTestKind(match_anykind_test);
     axisExpr->setTest(me);
   }
@@ -12769,7 +12921,7 @@
   {
     if (axisExpr != NULL)
     {
-      match = theExprManager->create_match_expr(theRootSctx, loc);
+      match = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
       match->setTestKind(match_doc_test);
 
       axisExpr->setTest(match);
@@ -12853,7 +13005,7 @@
 
   if (axisExpr != NULL)
   {
-    match_expr* me = theExprManager->create_match_expr(theRootSctx, loc);
+    match_expr* me = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
     me->setTestKind(match_elem_test);
     me->setQName(elemNameItem);
     me->setTypeName(typeNameItem);
@@ -12901,7 +13053,7 @@
     store::Item_t typeQNameItem;
     CTX_TM->get_schema_element_typename(elemQNameItem, typeQNameItem, loc);
 
-    match_expr* match = theExprManager->create_match_expr(theRootSctx, loc);
+    match_expr* match = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
     match->setTestKind(match_xs_elem_test);
     match->setQName(elemQNameItem);
     match->setTypeName(typeQNameItem);
@@ -12975,7 +13127,7 @@
     dynamic_cast<axis_step_expr*> (peek_nodestk_or_null());
   if (axisExpr != NULL)
   {
-    match_expr* match = theExprManager->create_match_expr(theRootSctx, loc);
+    match_expr* match = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
     match->setTestKind(match_attr_test);
 
     if (attrName != NULL)
@@ -13018,7 +13170,7 @@
     store::Item_t typeQNameItem;
     CTX_TM->get_schema_attribute_typename(attrQNameItem, typeQNameItem, loc);
 
-    match_expr* match = theExprManager->create_match_expr(theRootSctx, loc);
+    match_expr* match = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
     match->setTestKind(match_xs_attr_test);
     match->setQName(attrQNameItem);
     match->setTypeName(typeQNameItem);
@@ -13067,7 +13219,7 @@
     dynamic_cast<axis_step_expr*> (peek_nodestk_or_null ());
   if (axisExpr != NULL)
   {
-    match_expr* match = theExprManager->create_match_expr(theRootSctx, loc);
+    match_expr* match = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
     match->setTestKind(match_text_test);
     axisExpr->setTest(match);
   }
@@ -13094,7 +13246,7 @@
     dynamic_cast<axis_step_expr*> (peek_nodestk_or_null ());
   if (axisExpr != NULL)
   {
-    match_expr* match = theExprManager->create_match_expr(theRootSctx, loc);
+    match_expr* match = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
     match->setTestKind(match_comment_test);
     axisExpr->setTest(match);
   }
@@ -13148,7 +13300,7 @@
 
   if (axisExpr != NULL)
   {
-    match_expr* match = theExprManager->create_match_expr(theRootSctx, loc);
+    match_expr* match = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
     match->setTestKind(match_pi_test);
     if (target != "")
       match->setQName(qname);
@@ -13291,12 +13443,13 @@
   args[0] = targetExpr;
   args[1] = theExprManager->create_json_object_expr(
       theRootSctx,
+      theUDF,
       loc,
       contentExpr,
       false);
 
   expr* updExpr = theExprManager->
-  create_fo_expr(theRootSctx,
+  create_fo_expr(theRootSctx, theUDF,
                  loc,
                  GET_BUILTIN_FUNCTION(OP_ZORBA_JSON_OBJECT_INSERT_2),
                  args);
@@ -13347,7 +13500,7 @@
   args[2] = sourceExpr;
 
   fo_expr* updExpr = theExprManager->
-  create_fo_expr(theRootSctx,
+  create_fo_expr(theRootSctx, theUDF,
                  loc,
                  GET_BUILTIN_FUNCTION(OP_ZORBA_JSON_ARRAY_INSERT_3),
                  args);
@@ -13387,7 +13540,7 @@
                                   NULL);
 
   fo_expr* updExpr = theExprManager->
-  create_fo_expr(theRootSctx,
+  create_fo_expr(theRootSctx, theUDF,
                  loc,
                  GET_BUILTIN_FUNCTION(OP_ZORBA_JSON_ARRAY_APPEND_2),
                  targetExpr,
@@ -13443,7 +13596,7 @@
                                   NULL);
 
   fo_expr* updExpr = theExprManager->
-  create_fo_expr(theRootSctx,
+  create_fo_expr(theRootSctx, theUDF,
                  loc,
                  GET_BUILTIN_FUNCTION(OP_ZORBA_JSON_DELETE_2),
                  targetExpr,
@@ -13489,13 +13642,13 @@
                                    PromoteIterator::JSONIQ_SELECTOR, // JNUP0007
                                    NULL);
 
-  args[2] = theExprManager->create_fo_expr(theRootSctx,
+  args[2] = theExprManager->create_fo_expr(theRootSctx, theUDF,
                                            valueExpr->get_loc(),
                                            GET_BUILTIN_FUNCTION(OP_ZORBA_JSON_BOX_1),
                                            valueExpr);
 
   fo_expr* updExpr = theExprManager->
-  create_fo_expr(theRootSctx,
+  create_fo_expr(theRootSctx, theUDF,
                  loc,
                  GET_BUILTIN_FUNCTION(OP_ZORBA_JSON_REPLACE_VALUE_3),
                  args);
@@ -13544,7 +13697,7 @@
                                    PromoteIterator::JSONIQ_OBJECT_SELECTOR); // JNUP0007
 
   fo_expr* updExpr = theExprManager->
-  create_fo_expr(theRootSctx,
+  create_fo_expr(theRootSctx, theUDF,
                  loc,
                  GET_BUILTIN_FUNCTION(OP_ZORBA_JSON_RENAME_3),
                  args);
@@ -13569,7 +13722,7 @@
 
   expr* lTarget = pop_nodestack();
 
-  expr* aDelete = theExprManager->create_delete_expr(theRootSctx, loc, lTarget);
+  expr* aDelete = theExprManager->create_delete_expr(theRootSctx, theUDF, loc, lTarget);
   push_nodestack(aDelete);
 }
 
@@ -13589,7 +13742,7 @@
   lSource = wrap_in_enclosed_expr(lSource, loc);
 
   expr* lInsert = theExprManager->
-  create_insert_expr(theRootSctx, loc, v.getType(), lSource, lTarget);
+  create_insert_expr(theRootSctx, theUDF, loc, v.getType(), lSource, lTarget);
 
   push_nodestack(lInsert);
 }
@@ -13614,10 +13767,10 @@
   // we are not going to generate a NameCastIterator, because we don't always know at
   // compile time whether the target will an element or an attribute node.
   nameExpr = theExprManager->
-  create_name_cast_expr(theRootSctx, loc, nameExpr, theNSCtx, false);
+  create_name_cast_expr(theRootSctx, theUDF, loc, nameExpr, theNSCtx, false);
 
   expr* renameExpr = theExprManager->
-  create_rename_expr(theRootSctx, loc, targetExpr, nameExpr);
+  create_rename_expr(theRootSctx, theUDF, loc, targetExpr, nameExpr);
 
   push_nodestack(renameExpr);
 }
@@ -13642,7 +13795,7 @@
   }
 
   expr* lReplace = theExprManager->
-  create_replace_expr(theRootSctx, loc, v.getType(), lTarget, lReplacement);
+  create_replace_expr(theRootSctx, theUDF, loc, v.getType(), lTarget, lReplacement);
 
   push_nodestack(lReplace);
 }
@@ -13653,7 +13806,7 @@
   TRACE_VISIT();
 
   transform_expr* transformExpr =
-  theExprManager->create_transform_expr(theRootSctx, loc);
+  theExprManager->create_transform_expr(theRootSctx, theUDF, loc);
 
   push_nodestack(transformExpr);
 
@@ -13862,7 +14015,7 @@
   ZORBA_ASSERT( range );
 
   ftcontains_expr *const e =
-    theExprManager->create_ftcontains_expr( theRootSctx, loc, range, selection, ftignore );
+    theExprManager->create_ftcontains_expr(theRootSctx, theUDF, loc, range, selection, ftignore );
   push_nodestack( e );
 #endif /* ZORBA_NO_FULL_TEXT */
 }


Follow ups