← 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:
reduced include dependencies on the compiler + various optimizer optimizations

Requested reviews:
  Markos Zaharioudakis (markos-za)

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

reduced include dependencies on the compiler + various optimizer optimizations
-- 
https://code.launchpad.net/~zorba-coders/zorba/markos-scratch/+merge/131166
Your team Zorba Coders is subscribed to branch lp:zorba.
=== modified file 'ChangeLog'
--- ChangeLog	2012-10-23 21:07:15 +0000
+++ ChangeLog	2012-10-24 11:34:21 +0000
@@ -8,6 +8,7 @@
 
 Optimizations:
   * Optimized the MarkExpr and EliminateFlworVariables rules of the optimizer
+  * Optimized the MarkFreeVars optimizer rule
 
 Bug Fixes/Other Changes:
   * Fixed mustCopyInputNodes() method of no-copy, and jsoniq functions.

=== modified file 'src/compiler/api/compilercb.cpp'
--- src/compiler/api/compilercb.cpp	2012-10-12 09:05:54 +0000
+++ src/compiler/api/compilercb.cpp	2012-10-24 11:34:21 +0000
@@ -17,6 +17,7 @@
 
 #include "compiler/api/compilercb.h"
 #include "compiler/expression/expr_base.h"
+#include "compiler/expression/expr_manager.h"
 
 #ifdef ZORBA_WITH_DEBUGGER
 #include "debugger/debugger_commons.h"

=== modified file 'src/compiler/api/compilercb.h'
--- src/compiler/api/compilercb.h	2012-10-12 09:05:54 +0000
+++ src/compiler/api/compilercb.h	2012-10-24 11:34:21 +0000
@@ -29,19 +29,21 @@
 // without having the definition of static_context availble.
 # include "context/static_context.h"
 #endif
+
 #include "compiler/expression/pragma.h"
 
 #include "zorbaserialization/class_serializer.h"
 
-#include "compiler/expression/mem_manager.h"
-#include "compiler/expression/expr_manager.h"
 
-namespace zorba {
+namespace zorba 
+{
 
 #ifdef ZORBA_WITH_DEBUGGER
 class DebuggerCommons;
 #endif
 class static_context;
+class ExprManager;
+
 
 /*******************************************************************************
   There is one CompilerCB per query plus one CompilerCB per invocation of an
@@ -233,8 +235,6 @@
 
   ExprManager* getExprManager() const { return theEM; }
 
-  MemoryManager& getMemoryManager() const { return theEM->getMemory(); }
-
   //
   // Pragmas
   //

=== modified file 'src/compiler/codegen/plan_visitor.cpp'
--- src/compiler/codegen/plan_visitor.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/codegen/plan_visitor.cpp	2012-10-24 11:34:21 +0000
@@ -31,6 +31,7 @@
 #include "system/globalenv.h"
 #include "system/properties.h"
 
+#include "compiler/expression/expr_manager.h"
 #include "compiler/api/compilercb.h"
 #include "compiler/codegen/plan_visitor.h"
 #include "compiler/expression/expr.h"
@@ -896,7 +897,9 @@
           {
             ++numForClauses;
 
-            if (c->get_expr()->is_sequential())
+            const for_clause* fc = static_cast<const for_clause*>(c);
+
+            if (fc->get_expr()->is_sequential())
             {
               // TODO: do not convert to general flwor if the whole flwor consists
               // of a single FOR followed by RETURN.
@@ -907,7 +910,9 @@
           }
           else if (c->get_kind() == flwor_clause::let_clause)
           {
-            if (c->get_expr()->is_sequential())
+            const let_clause* lc = static_cast<const let_clause*>(c);
+
+            if (lc->get_expr()->is_sequential())
             {
               if (numForClauses > 0)
               {
@@ -933,7 +938,7 @@
       {
         materialize_clause* mat =
         theCCB->theEM->create_materialize_clause(v.get_sctx(),
-                                            v.get_return_expr()->get_loc());
+                                                 v.get_return_expr()->get_loc());
 
         v.add_clause(mat);
         ++numClauses;
@@ -960,14 +965,17 @@
         case flwor_clause::let_clause:
         case flwor_clause::window_clause:
         {
+          expr* domExpr = static_cast<const forletwin_clause*>(c)->get_expr();
+
           if (k == flwor_clause::for_clause || k == flwor_clause::window_clause)
           {
-            xqtref_t domainType = c->get_expr()->get_return_type();
+            xqtref_t domainType = domExpr->get_return_type();
+
             if (domainType->get_quantifier() != TypeConstants::QUANT_ONE)
               ++numForClauses;
           }
 
-          if (c->get_expr()->is_sequential())
+          if (domExpr->is_sequential())
           {
             if (k == flwor_clause::for_clause ||
                 k == flwor_clause::window_clause ||
@@ -981,12 +989,12 @@
                   v.get_clause(i-1)->get_kind() != flwor_clause::order_clause &&
                   v.get_clause(i-1)->get_kind() != flwor_clause::group_clause)
               {
-                orderby_clause* mat =
-                theCCB->theEM->create_orderby_clause(v.get_sctx(),
-                                   c->get_loc(),
-                                   true,
-                                   modifiers,
-                                   orderingExprs);
+                orderby_clause* mat = theCCB->theEM->
+                create_orderby_clause(v.get_sctx(),
+                                      c->get_loc(),
+                                      true,
+                                      modifiers,
+                                      orderingExprs);
 
                 v.add_clause(i, mat);
                 ++i;
@@ -997,12 +1005,12 @@
                   (i < numClauses - 1 &&
                    v.get_clause(i+1)->get_kind() != flwor_clause::group_clause))
               {
-                orderby_clause* mat =
-                theCCB->theEM->create_orderby_clause(v.get_sctx(),
-                                   c->get_loc(),
-                                   true,
-                                   modifiers,
-                                   orderingExprs);
+                orderby_clause* mat = theCCB->theEM->
+                create_orderby_clause(v.get_sctx(),
+                                      c->get_loc(),
+                                      true,
+                                      modifiers,
+                                      orderingExprs);
 
                 v.add_clause(i+1, mat);
                 ++numClauses;
@@ -1032,12 +1040,12 @@
           lastClause->get_kind() != flwor_clause::order_clause &&
           lastClause->get_kind() != flwor_clause::group_clause)
       {
-        orderby_clause* mat =
-        theCCB->theEM->create_orderby_clause(v.get_sctx(),
-                           v.get_return_expr()->get_loc(),
-                           true,
-                           modifiers,
-                           orderingExprs);
+        orderby_clause* mat = theCCB->theEM->
+        create_orderby_clause(v.get_sctx(),
+                              v.get_return_expr()->get_loc(),
+                              true,
+                              modifiers,
+                              orderingExprs);
 
         v.add_clause(mat);
         ++numClauses;
@@ -1566,7 +1574,7 @@
 
     return new flwor::WindowIterator(sctx,
                                      var->get_loc(),
-                                     wc->get_winkind() == window_clause::tumbling_window ? flwor::WindowIterator::TUMBLING : flwor::WindowIterator::SLIDING,
+                                     wc->get_winkind() == tumbling_window ? flwor::WindowIterator::TUMBLING : flwor::WindowIterator::SLIDING,
                                      PREV_ITER,
                                      domainIter,
                                      var->get_name(),
@@ -2272,10 +2280,10 @@
   enum FlowCtlException::action a;
   switch (v.get_action())
   {
-  case flowctl_expr::BREAK:
+  case FLOW_BREAK:
     a = FlowCtlException::BREAK;
     break;
-  case flowctl_expr::CONTINUE:
+  case FLOW_CONTINUE:
     a = FlowCtlException::CONTINUE;
     break;
   default:
@@ -3022,7 +3030,7 @@
 
   theConstructorsStack.push(&v);
 
-  if (v.get_type() == text_expr::text_constructor)
+  if (v.get_type() == text_constructor)
     theEnclosedContextStack.push(TEXT_CONTENT);
   else
     theEnclosedContextStack.push(ATTRIBUTE_CONTENT);
@@ -3049,11 +3057,11 @@
 
   switch (v.get_type())
   {
-  case text_expr::text_constructor:
+  case text_constructor:
     push_itstack(new TextIterator(sctx, qloc, content, isRoot));
     break;
 
-  case text_expr::comment_constructor:
+  case comment_constructor:
     push_itstack(new CommentIterator(sctx, qloc, content, isRoot));
     break;
 

=== modified file 'src/compiler/expression/expr.cpp'
--- src/compiler/expression/expr.cpp	2012-10-22 15:10:23 +0000
+++ src/compiler/expression/expr.cpp	2012-10-24 11:34:21 +0000
@@ -174,12 +174,12 @@
     static_context* sctx,
     user_function* udf,
     const QueryLoc& loc,
-    order_type_t type,
-    expr* inExpr)
+    DocOrderMode type,
+    expr* input)
   :
   expr(ccb, sctx, udf, loc, order_expr_kind),
-  theType(type),
-  theExpr(inExpr)
+  theInput(input),
+  theType(type)
 {
   compute_scripting_kind();
 }
@@ -187,7 +187,7 @@
 
 void order_expr::compute_scripting_kind()
 {
-  theScriptingKind = theExpr->get_scripting_detail();
+  theScriptingKind = theInput->get_scripting_detail();
 
   if (is_vacuous())
     theScriptingKind = SIMPLE_EXPR;
@@ -204,14 +204,14 @@
     const QueryLoc& loc,
     enum ParseConstants::validation_mode_t mode,
     const store::Item_t& typeName,
-    expr* inExpr,
+    expr* input,
     rchandle<TypeManager> typemgr)
   :
   expr(ccb, sctx, udf, loc, validate_expr_kind),
+  theInput(input),
   theMode(mode),
   theTypeName(typeName),
-  theTypeMgr(typemgr),
-  theExpr(inExpr)
+  theTypeMgr(typemgr)
 {
   compute_scripting_kind();
 }
@@ -219,9 +219,9 @@
 
 void validate_expr::compute_scripting_kind()
 {
-  checkNonUpdating(theExpr);
+  checkNonUpdating(theInput);
 
-  theScriptingKind = theExpr->get_scripting_detail();
+  theScriptingKind = theInput->get_scripting_detail();
 
   if (is_vacuous())
     theScriptingKind = SIMPLE_EXPR;
@@ -266,7 +266,7 @@
     const xqtref_t& type)
   :
   expr(ccb, sctx, udf, loc, kind),
-  theInputExpr(input),
+  theInput(input),
   theTargetType(type)
 {
   assert(type != NULL);
@@ -290,9 +290,9 @@
 
 void cast_or_castable_base_expr::compute_scripting_kind()
 {
-  checkNonUpdating(theInputExpr);
+  checkNonUpdating(theInput);
 
-  theScriptingKind = theInputExpr->get_scripting_detail();
+  theScriptingKind = theInput->get_scripting_detail();
 
   if (is_vacuous())
     theScriptingKind = SIMPLE_EXPR;
@@ -355,7 +355,7 @@
     const QueryLoc& loc,
     expr* inputExpr,
     const xqtref_t& type,
-    TreatIterator::ErrorKind err,
+    TreatErrorKind err,
     bool check_prime,
     store::Item* qname)
   :
@@ -378,7 +378,7 @@
     const QueryLoc& loc,
     expr* input,
     const xqtref_t& type,
-    PromoteIterator::ErrorKind err,
+    PromoteErrorKind err,
     store::Item* qname)
   :
   cast_base_expr(ccb, sctx, udf, loc, promote_expr_kind, input, type),
@@ -663,7 +663,7 @@
     static_context* sctx,
     user_function* udf,
     const QueryLoc& loc,
-    text_constructor_type type_arg,
+    TextConstructorType type_arg,
     expr* content)
   :
   expr(ccb, sctx, udf, loc, text_expr_kind),
@@ -743,10 +743,10 @@
     static_context* sctx,
     user_function* udf,
     const QueryLoc& loc,
-    expr* wrapped)
+    expr* input)
   :
   expr(ccb, sctx, udf, loc, wrapper_expr_kind),
-  theWrappedExpr(wrapped)
+  theInput(input)
 {
   compute_scripting_kind();
 }
@@ -754,7 +754,7 @@
 
 void wrapper_expr::compute_scripting_kind()
 {
-  theScriptingKind = theWrappedExpr->get_scripting_detail();
+  theScriptingKind = theInput->get_scripting_detail();
 }
 
 
@@ -1105,6 +1105,14 @@
 }
 
 
+void eval_expr::add_var(var_expr* var)
+{
+  theOuterVarNames.push_back(var->get_name());
+  theOuterVarTypes.push_back(var->get_return_type());
+  theArgs.push_back(var);
+}
+
+
 #ifdef ZORBA_WITH_DEBUGGER
 /*******************************************************************************
 
@@ -1131,6 +1139,13 @@
   theScriptingKind = theExpr->get_scripting_detail();
 }
 
+
+void debugger_expr::add_var(var_expr* var, expr* arg)
+{
+  theVars.push_back(var);
+  theArgs.push_back(arg);
+}
+
 #endif
 
 
@@ -1142,10 +1157,10 @@
     static_context* sctx,
     user_function* udf,
     const QueryLoc& loc,
-    expr* aChild)
+    expr* input)
   :
-  expr(ccb, sctx, udf, loc, aChild->get_expr_kind()),
-  theExpr(aChild),
+  expr(ccb, sctx, udf, loc, function_trace_expr_kind),
+  theInput(input),
   theFunctionArity(0)
 {
   bool modified;
@@ -1154,14 +1169,14 @@
 }
 
 
-function_trace_expr::function_trace_expr(user_function* udf, expr* aExpr)
+function_trace_expr::function_trace_expr(user_function* udf, expr* input)
   :
-  expr(aExpr->get_ccb(),
-       aExpr->get_sctx(),
+  expr(input->get_ccb(),
+       input->get_sctx(),
        udf,
-       aExpr->get_loc(),
+       input->get_loc(),
        function_trace_expr_kind),
-  theExpr(aExpr),
+  theInput(input),
   theFunctionArity(0)
 {
   bool modified;
@@ -1177,7 +1192,7 @@
 
 void function_trace_expr::compute_scripting_kind()
 {
-  theScriptingKind = theExpr->get_scripting_detail();
+  theScriptingKind = theInput->get_scripting_detail();
 }
 
 

=== modified file 'src/compiler/expression/expr.h'
--- src/compiler/expression/expr.h	2012-10-09 14:06:08 +0000
+++ src/compiler/expression/expr.h	2012-10-24 11:34:21 +0000
@@ -28,7 +28,7 @@
 
 #include "functions/signature.h"
 
-#include "compiler/expression/var_expr.h"
+#include "compiler/expression/expr_base.h"
 
 #include "context/static_context.h"
 #include "context/namespace_context.h"
@@ -37,7 +37,6 @@
 
 #include "store/api/item.h"
 
-#include "runtime/core/sequencetypes.h"
 
 namespace zorba
 {
@@ -48,6 +47,7 @@
 class signature;
 class pragma;
 
+
 /*******************************************************************************
   [68] IfExpr ::= "if" "(" Expr ")" "then" ExprSingle "else" ExprSingle
 ********************************************************************************/
@@ -96,16 +96,9 @@
   friend class ExprIterator;
   friend class expr;
 
-public:
-  enum order_type_t
-  {
-    ordered,
-    unordered
-  };
-
 protected:
-  order_type_t   theType;
-  expr         * theExpr;
+  expr         * theInput;
+  DocOrderMode   theType;
 
 protected:
   order_expr(
@@ -113,13 +106,13 @@
       static_context* sctx,
       user_function* udf,
       const QueryLoc&,
-      order_type_t,
+      DocOrderMode,
       expr*);
 
 public:
-  order_type_t get_type() const { return theType; }
+  expr* get_input() const { return theInput; }
 
-  expr* get_expr() const { return theExpr; }
+  DocOrderMode get_type() const { return theType; }
 
   void compute_scripting_kind();
 
@@ -139,10 +132,10 @@
   friend class expr;
 
 protected:
-  ParseConstants::validation_mode_t theMode;
-  store::Item_t                     theTypeName;
-  rchandle<TypeManager>             theTypeMgr;
-  expr                            * theExpr;
+  expr                             * theInput;
+  ParseConstants::validation_mode_t  theMode;
+  store::Item_t                      theTypeName;
+  rchandle<TypeManager>              theTypeMgr;
 
 protected:
   validate_expr(
@@ -156,7 +149,7 @@
       rchandle<TypeManager>);
 
 public:
-  expr* get_expr() const { return theExpr; }
+  expr* get_input() const { return theInput; }
 
   const store::Item* get_type_name() const { return theTypeName; }
 
@@ -205,7 +198,7 @@
   friend class expr;
 
 protected:
-  expr     * theInputExpr;
+  expr     * theInput;
   xqtref_t   theTargetType;
 
 protected:
@@ -219,7 +212,7 @@
       const xqtref_t& type);
 
 public:
-  expr* get_input() const { return theInputExpr; }
+  expr* get_input() const { return theInput; }
 
   xqtref_t get_target_type() const;
 
@@ -297,9 +290,9 @@
   friend class expr;
 
 protected:
-  TreatIterator::ErrorKind theErrorKind;
-  bool                     theCheckPrime;
-  store::Item_t            theQName;
+  TreatErrorKind  theErrorKind;
+  bool            theCheckPrime;
+  store::Item_t   theQName;
 
 protected:
   treat_expr(
@@ -309,12 +302,12 @@
       const QueryLoc&,
       expr*,
       const xqtref_t&,
-      TreatIterator::ErrorKind err,
+      TreatErrorKind err,
       bool check_prime = true,
       store::Item* qname = NULL);
 
 public:
-  TreatIterator::ErrorKind get_err() const { return theErrorKind; }
+  TreatErrorKind get_err() const { return theErrorKind; }
 
   bool get_check_prime() const { return theCheckPrime; }
 
@@ -375,8 +368,8 @@
   friend class expr;
 
 protected:
-  PromoteIterator::ErrorKind theErrorKind;
-  store::Item_t              theQName;
+  PromoteErrorKind theErrorKind;
+  store::Item_t    theQName;
 
 protected:
   promote_expr(
@@ -386,11 +379,11 @@
       const QueryLoc& loc,
       expr* input,
       const xqtref_t& type,
-      PromoteIterator::ErrorKind err,
+      PromoteErrorKind err,
       store::Item* qname);
 
 public:
-  PromoteIterator::ErrorKind get_err() const { return theErrorKind; }
+  PromoteErrorKind get_err() const { return theErrorKind; }
 
   void set_qname(const store::Item_t& qname) { theQName = qname; }
 
@@ -504,8 +497,8 @@
   friend class expr;
 
 private:
-  expr*             theInputExpr;
-  bool               theIsAttrName;
+  expr  * theInputExpr;
+  bool    theIsAttrName;
 
 protected:
   name_cast_expr(
@@ -541,7 +534,7 @@
 
 protected:
   expr  * theContent;
-  bool     theCopyInputNodes;
+  bool    theCopyInputNodes;
 
 protected:
   doc_expr(
@@ -713,16 +706,9 @@
   friend class ExprIterator;
   friend class expr;
 
-public:
-  typedef enum
-  {
-    text_constructor,
-    comment_constructor
-  } text_constructor_type;
-
 protected:
-  text_constructor_type   type;
-  expr                  * theContentExpr;
+  TextConstructorType   type;
+  expr                * theContentExpr;
 
 protected:
   text_expr(
@@ -730,13 +716,13 @@
       static_context* sctx,
       user_function* udf,
       const QueryLoc&,
-      text_constructor_type,
+      TextConstructorType,
       expr*);
 
 public:
   expr* get_text() const { return theContentExpr; }
 
-  text_constructor_type get_type() const { return type; }
+  TextConstructorType get_type() const { return type; }
 
   void compute_scripting_kind();
 
@@ -1040,7 +1026,7 @@
   friend class ExprManager;
 
 protected:
-  expr  * theWrappedExpr;
+  expr    * theInput;
 
 protected:
   wrapper_expr(
@@ -1051,9 +1037,9 @@
       expr* wrapped);
 
 public:
-  expr* get_expr() const { return theWrappedExpr; }
+  expr* get_input() const { return theInput; }
 
-  void set_expr(expr* e) { theWrappedExpr = e;}
+  void set_expr(expr* e) { theInput = e;}
 
   void compute_scripting_kind();
 
@@ -1073,11 +1059,11 @@
   friend class ExprManager;
 
 protected:
-  expr*        theExpr;
-  store::Item_t theFunctionName;
-  QueryLoc      theFunctionLocation;
-  QueryLoc      theFunctionCallLocation;
-  unsigned int  theFunctionArity;
+  expr         * theInput;
+  store::Item_t  theFunctionName;
+  QueryLoc       theFunctionLocation;
+  QueryLoc       theFunctionCallLocation;
+  unsigned int   theFunctionArity;
 
 protected:
   function_trace_expr(
@@ -1094,14 +1080,14 @@
 public:
   virtual ~function_trace_expr();
 
+  expr* get_input() const { return theInput; }
+
   void compute_scripting_kind();
 
   void accept(expr_visitor&);
 
   std::ostream& put(std::ostream&) const;
 
-  expr* get_expr() const { return theExpr; }
-
   void setFunctionName(store::Item_t aFunctionName)
   {
     theFunctionName = aFunctionName;
@@ -1215,12 +1201,7 @@
 
   const std::vector<xqtref_t>& get_var_types() const { return theOuterVarTypes; }
 
-  void add_var(var_expr* var)
-  {
-    theOuterVarNames.push_back(var->get_name());
-    theOuterVarTypes.push_back(var->get_return_type());
-    theArgs.push_back(var);
-  }
+  void add_var(var_expr* var);
 
   expr_script_kind_t get_inner_scripting_kind() const;
 
@@ -1288,11 +1269,7 @@
 
   const var_expr* get_var(csize i) const { return theVars[i]; }
 
-  void add_var(var_expr* var, expr* arg)
-  {
-    theVars.push_back(var);
-    theArgs.push_back(arg);
-  }
+  void add_var(var_expr* var, expr* arg);
 
   void compute_scripting_kind();
 };

=== modified file 'src/compiler/expression/expr_base.cpp'
--- src/compiler/expression/expr_base.cpp	2012-10-22 15:10:23 +0000
+++ src/compiler/expression/expr_base.cpp	2012-10-24 11:34:21 +0000
@@ -20,6 +20,7 @@
 #include "compiler/expression/fo_expr.h"
 #include "compiler/expression/flwor_expr.h"
 #include "compiler/expression/path_expr.h"
+#include "compiler/expression/script_exprs.h"
 #include "compiler/expression/expr_iter.h"
 #include "compiler/expression/expr_visitor.h"
 #include "compiler/expression/expr_manager.h"
@@ -155,6 +156,7 @@
   // This is the default. The constructors for certain exprs set different values.
   setNonDiscardable(ANNOTATION_FALSE);
   setUnfoldable(ANNOTATION_FALSE);
+  setContainsRecursiveCall(ANNOTATION_FALSE);
   setConstructsNodes(ANNOTATION_FALSE);
   setDereferencesNodes(ANNOTATION_FALSE);
 }
@@ -766,8 +768,7 @@
 
   while (kind == wrapper_expr_kind)
   {
-    const wrapper_expr* wrapperExpr = static_cast<const wrapper_expr*>(currExpr);
-    currExpr = wrapperExpr->get_expr();
+    currExpr = static_cast<const wrapper_expr*>(currExpr)->get_input();
     kind = currExpr->get_expr_kind();
   }
 
@@ -834,14 +835,14 @@
 
   case order_expr_kind:
   {
-    const order_expr* orderExpr = static_cast<const order_expr *>(this);
-    return orderExpr->get_expr()->is_map_internal(e, found);
+    return static_cast<const order_expr*>(this)->get_input()->
+           is_map_internal(e, found);
   }
 
   case wrapper_expr_kind:
   {
-    const wrapper_expr* wrapperExpr = static_cast<const wrapper_expr *>(this);
-    return wrapperExpr->get_expr()->is_map_internal(e, found);
+    return static_cast<const wrapper_expr*>(this)->get_input()->
+           is_map_internal(e, found);
   }
 
   case const_expr_kind:
@@ -896,7 +897,9 @@
         if (found)
           break;
 
-        if (clause->get_expr()->is_map_internal(e, found) && found)
+        const for_clause* fc = static_cast<const for_clause*>(clause);
+
+        if (fc->get_expr()->is_map_internal(e, found) && found)
         {
           break;
         }
@@ -908,12 +911,25 @@
         break;
       }
       case flwor_clause::let_clause:
+      {
+        if (found)
+          break;
+
+        const let_clause* lc = static_cast<const let_clause*>(clause);
+
+        if (lc->get_expr()->contains_expr(e))
+          return false;
+
+        break;
+      }
       case flwor_clause::where_clause:
       {
         if (found)
           break;
 
-        if (clause->get_expr()->contains_expr(e))
+        const where_clause* wc = static_cast<const where_clause*>(clause);
+
+        if (wc->get_expr()->contains_expr(e))
           return false;
 
         break;
@@ -923,10 +939,11 @@
         if (found)
           break;
 
-        if (clause->get_expr()->contains_expr(e))
-          return false;
-
         const window_clause* wc = static_cast<const window_clause*>(clause);
+
+        if (wc->get_expr()->contains_expr(e))
+          return false;
+
         flwor_wincond* startCond = wc->get_win_start();
         flwor_wincond* stopCond = wc->get_win_stop();
 

=== modified file 'src/compiler/expression/expr_base.h'
--- src/compiler/expression/expr_base.h	2012-10-22 15:10:23 +0000
+++ src/compiler/expression/expr_base.h	2012-10-24 11:34:21 +0000
@@ -124,7 +124,6 @@
 ********************************************************************************/
 class expr
 {
-  friend class expr_iterator_data;
   friend class ExprIterator;
   friend class forletwin_clause;
   friend class for_clause;

=== modified file 'src/compiler/expression/expr_clone.cpp'
--- src/compiler/expression/expr_clone.cpp	2012-10-09 12:56:08 +0000
+++ src/compiler/expression/expr_clone.cpp	2012-10-24 11:34:21 +0000
@@ -24,6 +24,7 @@
 #include "compiler/expression/json_exprs.h"
 #include "compiler/expression/function_item_expr.h"
 #include "compiler/expression/ft_expr.h"
+#include "compiler/expression/ftnode.h"
 #include "compiler/expression/expr_manager.h"
 
 #include "compiler/api/compilercb.h"
@@ -462,7 +463,7 @@
                          theLoc,
                          e->get_valmode(),
                          const_cast<store::Item*>(e->get_type_name()),
-                         e->get_expr()->clone(udf, subst),
+                         e->get_input()->clone(udf, subst),
                          e->get_typemgr());
 
     break;
@@ -502,7 +503,7 @@
                       udf,
                       theLoc,
                       e->get_type(),
-                      e->get_expr()->clone(udf, subst));
+                      e->get_input()->clone(udf, subst));
     break;
   }
 #ifndef ZORBA_NO_FULL_TEXT
@@ -734,9 +735,9 @@
   {
     const wrapper_expr* e = static_cast<const wrapper_expr*>(this);
 
-    expr* wrappedClone = e->theWrappedExpr->clone(udf, subst);
+    expr* wrappedClone = e->theInput->clone(udf, subst);
 
-    if (e->theWrappedExpr->get_expr_kind() == var_expr_kind &&
+    if (e->theInput->get_expr_kind() == var_expr_kind &&
         wrappedClone->get_expr_kind() != var_expr_kind)
     {
       newExpr = wrappedClone;
@@ -753,7 +754,7 @@
     const function_trace_expr* e = static_cast<const function_trace_expr*>(this);
 
     function_trace_expr* cloneExpr = theCCB->theEM->
-    create_function_trace_expr(udf, e->theExpr->clone(udf, subst));
+    create_function_trace_expr(udf, e->theInput->clone(udf, subst));
 
     cloneExpr->theFunctionName = e->theFunctionName;
     cloneExpr->theFunctionLocation = e->theFunctionLocation;

=== modified file 'src/compiler/expression/expr_consts.h'
--- src/compiler/expression/expr_consts.h	2012-09-19 21:16:15 +0000
+++ src/compiler/expression/expr_consts.h	2012-10-24 11:34:21 +0000
@@ -21,6 +21,65 @@
 {
 
 
+enum PromoteErrorKind
+{
+  PROMOTE_FUNC_RETURN,
+  PROMOTE_FUNC_PARAM,
+  PROMOTE_TYPE_PROMOTION,
+  PROMOTE_JSONIQ_ARRAY_SELECTOR,
+  PROMOTE_JSONIQ_OBJECT_SELECTOR,
+  PROMOTE_JSONIQ_SELECTOR
+};
+
+
+enum TreatErrorKind
+{
+  TREAT_FUNC_RETURN,
+  TREAT_FUNC_PARAM,
+  TREAT_TYPE_MATCH,
+  TREAT_EXPR,
+  TREAT_INDEX_DOMAIN,
+  TREAT_INDEX_KEY,
+  TREAT_PATH_STEP,
+  TREAT_PATH_DOT,
+  TREAT_MULTI_VALUED_GROUPING_KEY,
+  TREAT_JSONIQ_VALUE,
+  TREAT_JSONIQ_UPDATE_TARGET,
+  TREAT_JSONIQ_OBJECT_UPDATE_TARGET,
+  TREAT_JSONIQ_OBJECT_UPDATE_CONTENT,
+  TREAT_JSONIQ_ARRAY_UPDATE_TARGET,
+  TREAT_JSONIQ_OBJECT_UPDATE_VALUE
+};
+
+
+enum WindowKind
+{
+  tumbling_window,
+  sliding_window
+};
+
+
+enum TextConstructorType
+{
+  text_constructor,
+  comment_constructor
+};
+
+
+enum FlowCtlAction
+{
+  FLOW_BREAK,
+  FLOW_CONTINUE
+};
+
+
+enum DocOrderMode
+{
+  doc_ordered,
+  doc_unordered
+};
+
+
 enum axis_kind_t
 {
   axis_kind_self = 0,

=== modified file 'src/compiler/expression/expr_iter.cpp'
--- src/compiler/expression/expr_iter.cpp	2012-10-22 15:10:23 +0000
+++ src/compiler/expression/expr_iter.cpp	2012-10-24 11:34:21 +0000
@@ -94,12 +94,6 @@
 
 void ExprIterator::next()
 {
-  flwor_clause* c = NULL;
-  window_clause* wc = NULL;
-  orderby_clause* oc = NULL;
-  group_clause* gc = NULL;
-  flwor_wincond* wincond = NULL;
-
   switch (theExpr->get_expr_kind())
   {
   case flwor_expr_kind:
@@ -107,6 +101,223 @@
   {
     flwor_expr* flworExpr = static_cast<flwor_expr*>(theExpr);
 
+#if 0
+    switch (theState)
+    {
+    case 0:
+    {
+      theClausesIter = flworExpr->theClauses.begin();
+      theClausesEnd = flworExpr->theClauses.end();
+
+      if (theClausesIter == theClausesEnd)
+      {
+        theIsDone = true;
+        theState = 10;
+        return;
+      }
+
+      flwor_clause* c = *theClausesIter;
+
+      switch (c->get_kind())
+      {
+      case flwor_clause::for_clause:
+      case flwor_clause::let_clause:
+      {
+        theCurrentChild = &(static_cast<forletwin_clause *>(c)->theDomainExpr);
+
+        ++theClausesIter;
+        theState = 1;
+        return;
+      }
+      case flwor_clause::window_clause:
+      {
+        theCurrentChild = &(static_cast<forletwin_clause *>(c)->theDomainExpr);
+
+        theWincondIter = 0;
+        theState = 2;
+        return;
+      }
+      case flwor_clause::where_clause:
+      {
+        theCurrentChild = &(static_cast<where_clause *>(c)->theWhereExpr);
+
+        ++theClausesIter;
+        theState = 1;
+        return;
+      }
+      case flwor_clause::count_clause:
+      {
+        ++theClausesIter;
+        break;
+      }
+      default:
+        ZORBA_ASSERT(false);
+      }
+    }
+    case 1:
+    {
+nextclause:
+
+      while(theClausesIter != theClausesEnd)
+      {
+        flwor_clause* c = *theClausesIter;
+
+        switch (c->get_kind())
+        {
+        case flwor_clause::for_clause:
+        case flwor_clause::let_clause:
+        {
+          theCurrentChild = &(static_cast<forletwin_clause *>(c)->theDomainExpr);
+          ++theClausesIter;
+          return;
+        }
+        case flwor_clause::window_clause:
+        {
+          window_clause* wc = static_cast<window_clause *>(*theClausesIter);
+
+          theCurrentChild = &(wc->theDomainExpr);
+
+          theState = 2;
+          theWincondIter = 0;
+          return;
+        }
+
+        case flwor_clause::where_clause:
+        {
+          theCurrentChild = &(static_cast<where_clause *>(c)->theWhereExpr);
+          ++theClausesIter;
+          return;
+        }
+
+        case flwor_clause::order_clause:
+        {
+          orderby_clause* oc = static_cast<orderby_clause *>(c);
+
+          theArgsIter = oc->theOrderingExprs.begin();
+          theArgsEnd = oc->theOrderingExprs.end();
+          
+          theCurrentChild = &(*theArgsIter);
+          
+          ++theArgsIter;
+          theState = 3;
+          return;
+        }
+
+        case flwor_clause::group_clause:
+        {
+          group_clause* gc = static_cast<group_clause *>(c);
+
+          theGroupVarsIter = gc->theGroupVars.begin();
+          theGroupVarsEnd = gc->theGroupVars.end();
+          theNonGroupVarsIter = gc->theNonGroupVars.begin();
+          theNonGroupVarsEnd = gc->theNonGroupVars.end();
+
+          theCurrentChild = &((*theGroupVarsIter).first);
+
+          ++theGroupVarsIter;
+          theState = 4;
+          return;
+        }
+
+        case flwor_clause::count_clause:
+        {
+          ++theClausesIter;
+          break;
+        }
+
+        default:
+        {
+          ZORBA_ASSERT(false);
+        }
+        }
+      } // while
+
+      theCurrentChild = &(flworExpr->theReturnExpr);
+      theState = 10;
+      return;
+    }
+
+    case 2:
+    {
+      while (theWincondIter < 2)
+      {
+        window_clause* wc = static_cast<window_clause *>(*theClausesIter);
+            
+        flwor_wincond* wincond = (theWincondIter == 0 ?
+                                  wc->theWinStartCond :
+                                  wc->theWinStopCond );
+        if (wincond != 0)
+        {
+          theCurrentChild = &(wincond->theCondExpr);
+          ++theWincondIter;
+          return;
+        }
+
+        ++theWincondIter;
+      }
+
+      theState = 1;
+      ++theClausesIter;
+      goto nextclause;
+    }
+
+    case 3:
+    {
+      while (theArgsIter != theArgsEnd)
+      {
+        theCurrentChild = &(*theArgsIter);
+        ++theArgsIter;
+        return;
+      }
+      
+      theState = 1;
+      ++theClausesIter;
+      goto nextclause;
+    }
+
+    case 4:
+    {
+      while (theGroupVarsIter != theGroupVarsEnd)
+      {
+        theCurrentChild = &((*theGroupVarsIter).first);
+
+        ++theGroupVarsIter;
+        return;
+      }
+
+      theState = 5;
+    }
+
+    case 5:
+    {
+      while (theNonGroupVarsIter != theNonGroupVarsEnd)
+      {
+        theCurrentChild = &((*theNonGroupVarsIter).first);
+
+        ++theNonGroupVarsIter;
+        return;
+      }
+
+      theState = 1;
+      ++theClausesIter;
+      goto nextclause;
+    }
+
+    default:
+    {
+      theIsDone = true;
+      return;
+    }
+    }
+
+#else
+
+    flwor_clause* c = NULL;
+    window_clause* wc = NULL;
+    orderby_clause* oc = NULL;
+    group_clause* gc = NULL;
+    flwor_wincond* wincond = NULL;
+
     EXPR_ITER_BEGIN();
 
     theClausesBegin = flworExpr->theClauses.begin();
@@ -127,6 +338,11 @@
         EXPR_ITER_NEXT(static_cast<let_clause *>(c)->theDomainExpr);
       }
 
+      else if (c->get_kind() == flwor_clause::where_clause)
+      {
+        EXPR_ITER_NEXT(static_cast<where_clause *>(c)->theWhereExpr);
+      }
+
       else if (c->get_kind() == flwor_clause::window_clause)
       {
         for (theWincondIter = 0; theWincondIter < 2; ++theWincondIter)
@@ -146,11 +362,6 @@
         EXPR_ITER_NEXT(wc->theDomainExpr);
       }
 
-      else if (c->get_kind() == flwor_clause::where_clause)
-      {
-        EXPR_ITER_NEXT(static_cast<where_clause *>(c)->theWhereExpr);
-      }
-
       else if (c->get_kind() == flwor_clause::group_clause)
       {
         gc = static_cast<group_clause *>(c);
@@ -188,7 +399,8 @@
 
       if (theClausesEnd != flworExpr->theClauses.end())
       {
-        ulong pos = (ulong)(theClausesIter - theClausesBegin);
+        ZORBA_ASSERT(0);
+        csize pos = (theClausesIter - theClausesBegin);
         if (pos >= flworExpr->num_clauses())
           break;
 
@@ -200,86 +412,55 @@
     EXPR_ITER_NEXT(flworExpr->theReturnExpr);
 
     EXPR_ITER_END();
-    break;
+#endif
+    return;
   }
 
   case relpath_expr_kind:
   {
     EXPR_ITER_BEGIN();
 
-    {
-      relpath_expr* pathExpr = static_cast<relpath_expr*>(theExpr);
-      theArgsIter = pathExpr->theSteps.begin();
-      theArgsEnd = pathExpr->theSteps.end();
-    }
-
+    theArgsIter = static_cast<relpath_expr*>(theExpr)->theSteps.begin();
+    theArgsEnd = static_cast<relpath_expr*>(theExpr)->theSteps.end();
     for (; theArgsIter != theArgsEnd; ++theArgsIter)
     {
       EXPR_ITER_NEXT(*theArgsIter);
     }
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case axis_step_expr_kind:
   {
-    axis_step_expr* axisExpr = static_cast<axis_step_expr*>(theExpr);
-
     EXPR_ITER_BEGIN();
-
-    EXPR_ITER_NEXT(axisExpr->theNodeTest);
-
+    EXPR_ITER_NEXT(static_cast<axis_step_expr*>(theExpr)->theNodeTest);
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case match_expr_kind:
-  {
-    theIsDone = true;
-    break;
-  }
-
   case var_expr_kind:
-  {
-    theIsDone = true;
-    break;
-  }
-
-  case wrapper_expr_kind:
-  {
-    wrapper_expr* wrapperExpr = static_cast<wrapper_expr*>(theExpr);
-
-    EXPR_ITER_BEGIN();
-
-    EXPR_ITER_NEXT(wrapperExpr->theWrappedExpr);
-
-    EXPR_ITER_END();
-    break;
-  }
-
   case const_expr_kind:
+  case flowctl_expr_kind:
   {
     theIsDone = true;
-    break;
+    return;
   }
 
-
   case fo_expr_kind:
   {
-    fo_expr* foExpr = static_cast<fo_expr*>(theExpr);
-
     EXPR_ITER_BEGIN();
 
-    theArgsIter = foExpr->theArgs.begin();
-    theArgsEnd = foExpr->theArgs.end();
+    theArgsIter = static_cast<fo_expr*>(theExpr)->theArgs.begin();
+    theArgsEnd = static_cast<fo_expr*>(theExpr)->theArgs.end();
     for (; theArgsIter != theArgsEnd; ++theArgsIter)
     {
       EXPR_ITER_NEXT(*theArgsIter);
     }
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case cast_expr_kind:
@@ -288,27 +469,55 @@
   case instanceof_expr_kind:
   case castable_expr_kind:
   {
-    cast_or_castable_base_expr* castExpr =
-    static_cast<cast_or_castable_base_expr*>(theExpr);
-
-    EXPR_ITER_BEGIN();
-
-    EXPR_ITER_NEXT(castExpr->theInputExpr);
-
-    EXPR_ITER_END();
-    break;
+    EXPR_ITER_BEGIN();
+    EXPR_ITER_NEXT(static_cast<cast_or_castable_base_expr*>(theExpr)->theInput);
+    EXPR_ITER_END();
+    return;
+  }
+
+  case wrapper_expr_kind:
+  {
+    EXPR_ITER_BEGIN();
+    EXPR_ITER_NEXT(static_cast<wrapper_expr*>(theExpr)->theInput);
+    EXPR_ITER_END();
+    return;
+  }
+
+  case function_trace_expr_kind:
+  {
+    EXPR_ITER_BEGIN();
+    EXPR_ITER_NEXT(static_cast<function_trace_expr*>(theExpr)->theInput);
+    EXPR_ITER_END();
+    return;
+  }
+
+  case order_expr_kind:
+  {
+    if (theState == 0)
+    {
+      theCurrentChild = &(static_cast<order_expr*>(theExpr)->theInput);
+      theState = 1;
+      return;
+    }
+
+    theIsDone = true;
+    return;
+  }
+
+  case validate_expr_kind:
+  {
+    EXPR_ITER_BEGIN();
+    EXPR_ITER_NEXT(static_cast<validate_expr*>(theExpr)->theInput);
+    EXPR_ITER_END();
+    return;
   }
 
   case name_cast_expr_kind:
   {
-    name_cast_expr* nameCastExpr = static_cast<name_cast_expr*>(theExpr);
-
     EXPR_ITER_BEGIN();
-
-    EXPR_ITER_NEXT(nameCastExpr->theInputExpr);
-
+    EXPR_ITER_NEXT(static_cast<name_cast_expr*>(theExpr)->theInputExpr);
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case doc_expr_kind:
@@ -321,7 +530,7 @@
       EXPR_ITER_NEXT(docExpr->theContent);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case elem_expr_kind:
@@ -339,7 +548,7 @@
       EXPR_ITER_NEXT(elemExpr->theContent);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case attr_expr_kind:
@@ -354,7 +563,7 @@
       EXPR_ITER_NEXT(attrExpr->theValueExpr);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case text_expr_kind:
@@ -366,7 +575,7 @@
     EXPR_ITER_NEXT(textExpr->theContentExpr);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case pi_expr_kind:
@@ -374,12 +583,10 @@
     pi_expr* piExpr = static_cast<pi_expr*>(theExpr);
 
     EXPR_ITER_BEGIN();
-
     EXPR_ITER_NEXT(piExpr->theTargetExpr);
     EXPR_ITER_NEXT(piExpr->theContentExpr);
-
     EXPR_ITER_END();
-    break;
+    return;
   }
 
 #ifdef ZORBA_WITH_JSON
@@ -393,7 +600,7 @@
         EXPR_ITER_NEXT(e->theContentExpr);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case json_object_expr_kind:
@@ -406,7 +613,7 @@
         EXPR_ITER_NEXT(e->theContentExpr);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case json_direct_object_expr_kind:
@@ -430,7 +637,7 @@
     }
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
 #endif
@@ -446,31 +653,7 @@
     EXPR_ITER_NEXT(ifExpr->theElseExpr);
 
     EXPR_ITER_END();
-    break;
-  }
-
-  case order_expr_kind:
-  {
-    order_expr* ordExpr = static_cast<order_expr*>(theExpr);
-
-    EXPR_ITER_BEGIN();
-
-    EXPR_ITER_NEXT(ordExpr->theExpr);
-
-    EXPR_ITER_END();
-    break;
-  }
-
-  case validate_expr_kind:
-  {
-    validate_expr* valExpr = static_cast<validate_expr*>(theExpr);
-
-    EXPR_ITER_BEGIN();
-
-    EXPR_ITER_NEXT(valExpr->theExpr);
-
-    EXPR_ITER_END();
-    break;
+    return;
   }
 
   case extension_expr_kind:
@@ -478,11 +661,9 @@
     extension_expr* extExpr = static_cast<extension_expr*>(theExpr);
 
     EXPR_ITER_BEGIN();
-
     EXPR_ITER_NEXT(extExpr->theExpr);
-
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case trycatch_expr_kind:
@@ -501,7 +682,7 @@
     }
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case function_item_expr_kind:
@@ -518,7 +699,7 @@
     }
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case dynamic_function_invocation_expr_kind:
@@ -538,7 +719,7 @@
     }
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case insert_expr_kind:
@@ -551,7 +732,7 @@
     EXPR_ITER_NEXT(insExpr->theTargetExpr);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case delete_expr_kind:
@@ -563,7 +744,7 @@
     EXPR_ITER_NEXT(delExpr->theTargetExpr);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case replace_expr_kind:
@@ -576,7 +757,7 @@
     EXPR_ITER_NEXT(repExpr->theSourceExpr);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case rename_expr_kind:
@@ -589,7 +770,7 @@
     EXPR_ITER_NEXT(renExpr->theSourceExpr);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case transform_expr_kind:
@@ -609,7 +790,7 @@
     EXPR_ITER_NEXT(trfExpr->theReturnExpr);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case block_expr_kind:
@@ -626,7 +807,7 @@
     }
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case apply_expr_kind:
@@ -635,7 +816,7 @@
     EXPR_ITER_BEGIN();
     EXPR_ITER_NEXT(applyExpr->theExpr);
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case var_decl_expr_kind:
@@ -648,7 +829,7 @@
       EXPR_ITER_NEXT(varDeclExpr->theInitExpr);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case var_set_expr_kind:
@@ -657,13 +838,7 @@
     EXPR_ITER_BEGIN();
     EXPR_ITER_NEXT(varSetExpr->theExpr);
     EXPR_ITER_END();
-    break;
-  }
-
-  case flowctl_expr_kind:
-  {
-    theIsDone = true;
-    break;
+    return;
   }
 
   case while_expr_kind:
@@ -671,11 +846,9 @@
     while_expr* whileExpr = static_cast<while_expr*>(theExpr);
 
     EXPR_ITER_BEGIN();
-
     EXPR_ITER_NEXT(whileExpr->theBody);
-
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case exit_expr_kind:
@@ -683,11 +856,9 @@
     exit_expr* exitExpr = static_cast<exit_expr*>(theExpr);
 
     EXPR_ITER_BEGIN();
-
     EXPR_ITER_NEXT(exitExpr->theExpr);
-
     EXPR_ITER_END();
-    break;
+    return;
   }
 
   case exit_catcher_expr_kind:
@@ -699,7 +870,7 @@
     EXPR_ITER_NEXT(catcherExpr->theExpr);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
 #ifndef ZORBA_NO_FULL_TEXT
@@ -723,7 +894,7 @@
       EXPR_ITER_NEXT(ftExpr->ftignore_);
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 #endif /* ZORBA_NO_FULL_TEXT */
 
@@ -743,7 +914,7 @@
     }
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 
 #ifdef ZORBA_WITH_DEBUGGER
@@ -763,19 +934,10 @@
     }
 
     EXPR_ITER_END();
-    break;
+    return;
   }
 #endif
 
-  case function_trace_expr_kind:
-  {
-    function_trace_expr* dummyExpr = static_cast<function_trace_expr*>(theExpr);
-    EXPR_ITER_BEGIN();
-    EXPR_ITER_NEXT(dummyExpr->theExpr);
-    EXPR_ITER_END();
-    break;
-  }
-
   default:
   {
     ZORBA_ASSERT(false);

=== modified file 'src/compiler/expression/expr_manager.cpp'
--- src/compiler/expression/expr_manager.cpp	2012-10-09 14:06:08 +0000
+++ src/compiler/expression/expr_manager.cpp	2012-10-24 11:34:21 +0000
@@ -179,7 +179,7 @@
     static_context* sctx,
     user_function* udf,
     const QueryLoc& loc,
-    order_expr::order_type_t order,
+    DocOrderMode order,
     expr* exp)
 {
   CREATE_AND_RETURN_EXPR(order_expr, sctx, udf, loc, order, exp);
@@ -216,7 +216,7 @@
     const QueryLoc& loc,
     expr* treated,
     const xqtref_t& type,
-    TreatIterator::ErrorKind err,
+    TreatErrorKind err,
     bool check_prime,
     store::Item* qname)
 {
@@ -231,7 +231,7 @@
     const QueryLoc& loc,
     expr* promoted,
     const xqtref_t& type,
-    PromoteIterator::ErrorKind err,
+    PromoteErrorKind err,
     store::Item* qname)
 {
   CREATE_AND_RETURN_EXPR(promote_expr, sctx, udf, loc, promoted, type, err, qname);
@@ -329,7 +329,7 @@
     static_context* sctx,
     user_function* udf,
     const QueryLoc& loc,
-    text_expr::text_constructor_type textType,
+    TextConstructorType textType,
     expr* text)
 {
   CREATE_AND_RETURN_EXPR(text_expr, sctx, udf, loc, textType, text);
@@ -538,10 +538,15 @@
     static_context* sctx,
     user_function* udf,
     const QueryLoc& loc,
-    var_expr::var_kind k,
+    ulong varKind,
     store::Item* name)
 {
-  CREATE_AND_RETURN_EXPR(var_expr, sctx, udf, loc, k, name);
+  CREATE_AND_RETURN_EXPR(var_expr,
+                         sctx,
+                         udf,
+                         loc,
+                         static_cast<var_expr::var_kind>(varKind),
+                         name);
 }
 
 
@@ -729,7 +734,7 @@
     static_context* sctx,
     user_function* udf,
     const QueryLoc& loc,
-    flowctl_expr::action action)
+    FlowCtlAction action)
 {
   CREATE_AND_RETURN_EXPR(flowctl_expr, sctx, udf, loc, action);
 }
@@ -908,7 +913,7 @@
 window_clause* ExprManager::create_window_clause(
     static_context* sctx,
     const QueryLoc& loc,
-    window_clause::window_t winKind,
+    WindowKind winKind,
     var_expr* varExpr,
     expr* domainExpr,
     flwor_wincond* winStart,
@@ -935,7 +940,7 @@
     static_context* sctx,
     const QueryLoc& loc,
     const flwor_clause::rebind_list_t& gvars,
-    flwor_clause::rebind_list_t ngvars,
+    const flwor_clause::rebind_list_t& ngvars,
     const std::vector<std::string>& collations)
 {
   CREATE_AND_RETURN(group_clause, sctx, theCCB,  loc, gvars, ngvars, collations);

=== modified file 'src/compiler/expression/expr_manager.h'
--- src/compiler/expression/expr_manager.h	2012-10-09 14:06:08 +0000
+++ src/compiler/expression/expr_manager.h	2012-10-24 11:34:21 +0000
@@ -19,17 +19,37 @@
 #define ZORBA_COMPILER_EXPRMANAGER_H
 
 #include "expr_classes.h"
-#include "expr.h"
-#include "script_exprs.h"
-#include "flwor_expr.h"
-#include "ftnode.h"
-
+#include "expr_consts.h"
+#include "expr_utils.h"
 #include "mem_manager.h"
 
+#include "compiler/parser/parse_constants.h"
+
+#include "zorbatypes/schema_types.h"
+
+#include "store/api/update_consts.h"
+
+
 namespace zorba
 {
 
 class CompilerCB;
+class expr;
+class var_expr;
+class catch_clause;
+class pragma;
+class flwor_clause;
+class flwor_wincond;
+class copy_clause;
+class window_clause;
+class group_clause;
+class where_clause;
+class count_clause;
+class orderby_clause;
+class materialize_clause;
+struct flwor_wincond_vars;
+class ftnode;
+
 
 
 class ExprManager
@@ -86,7 +106,7 @@
       static_context* sctx,
       user_function* udf,
       const QueryLoc& loc,
-      order_expr::order_type_t,
+      DocOrderMode,
       expr*);
 
   validate_expr* create_validate_expr(
@@ -111,7 +131,7 @@
       const QueryLoc& loc,
       expr* input,
       const xqtref_t& type,
-      TreatIterator::ErrorKind err,
+      TreatErrorKind err,
       bool check_prime = true,
       store::Item* qnname = NULL);
 
@@ -122,7 +142,7 @@
       const QueryLoc& loc,
       expr* input,
       const xqtref_t& type,
-      PromoteIterator::ErrorKind err,
+      PromoteErrorKind err,
       store::Item* qname);
 
   castable_expr* create_castable_expr(
@@ -185,7 +205,7 @@
       static_context* sctx,
       user_function* udf,
       const QueryLoc&,
-      text_expr::text_constructor_type,
+      TextConstructorType,
       expr*);
 
   pi_expr* create_pi_expr(
@@ -312,7 +332,7 @@
       static_context* sctx,
       user_function* udf,
       const QueryLoc& loc,
-      var_expr::var_kind k,
+      ulong varKind,
       store::Item* name);
 
   var_expr* create_var_expr(user_function* udf, const var_expr& source);
@@ -427,7 +447,7 @@
       static_context* sctx,
       user_function* udf,
       const QueryLoc& loc,
-      flowctl_expr::action action);
+      FlowCtlAction action);
 
   while_expr* create_while_expr(
       static_context* sctx,
@@ -479,7 +499,7 @@
       user_function* udf,
       QueryLoc const&,
       expr* range,
-      ftnode *ftselection,
+      ftnode* ftselection,
       expr* ftignore);
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -539,7 +559,7 @@
   window_clause* create_window_clause(
       static_context* sctx,
       const QueryLoc& loc,
-      window_clause::window_t winKind,
+      WindowKind winKind,
       var_expr* varExpr,
       expr* domainExpr,
       flwor_wincond* winStart,
@@ -549,15 +569,15 @@
   flwor_wincond* create_flwor_wincond(
       static_context* sctx,
       bool isOnly,
-      const flwor_wincond::vars& in_vars,
-      const flwor_wincond::vars& out_vars,
+      const flwor_wincond_vars& in_vars,
+      const flwor_wincond_vars& out_vars,
       expr* cond);
 
   group_clause* create_group_clause(
       static_context* sctx,
       const QueryLoc& loc,
-      const flwor_clause::rebind_list_t& gvars,
-      flwor_clause::rebind_list_t ngvars,
+      const var_rebind_list_t& gvars,
+      const var_rebind_list_t& ngvars,
       const std::vector<std::string>& collations);
 
   orderby_clause * create_orderby_clause (

=== modified file 'src/compiler/expression/expr_put.cpp'
--- src/compiler/expression/expr_put.cpp	2012-10-08 12:09:36 +0000
+++ src/compiler/expression/expr_put.cpp	2012-10-24 11:34:21 +0000
@@ -154,9 +154,9 @@
   get_expr()->put(os);
   return os;
 #else
-  if (get_expr()->get_expr_kind() == var_expr_kind)
+  if (get_input()->get_expr_kind() == var_expr_kind)
   {
-    const var_expr* varExpr = static_cast<const var_expr*>(get_expr());
+    const var_expr* varExpr = static_cast<const var_expr*>(get_input());
 
     BEGIN_PUT_NO_EOL(var_ref) ;
     put_qname(varExpr->get_name(), os);
@@ -165,8 +165,8 @@
   }
   else
   {
-    BEGIN_PUT( wrapper_expr );
-    get_expr()->put(os);
+    BEGIN_PUT(wrapper_expr);
+    get_input()->put(os);
     END_PUT();
   }
 #endif
@@ -440,7 +440,7 @@
 {
   os << indent << "promote_expr " << theTargetType->toString()
      << expr_addr (this) << " [\n" << inc_indent;
-  theInputExpr->put(os);
+  theInput->put(os);
   END_PUT();
 }
 
@@ -491,7 +491,7 @@
 ostream& function_trace_expr::put(ostream& os) const
 {
   BEGIN_PUT(function_trace_expr);
-  theExpr->put(os);
+  theInput->put(os);
   END_PUT();
 }
 
@@ -599,28 +599,28 @@
 ostream& instanceof_expr::put( ostream& os) const
 {
   BEGIN_PUT1( instanceof_expr, theTargetType->toString() );
-  theInputExpr->put(os);
+  theInput->put(os);
   END_PUT();
 }
 
 ostream& treat_expr::put( ostream& os) const
 {
   BEGIN_PUT1( treat_expr, theTargetType->toString() );
-  theInputExpr->put(os);
+  theInput->put(os);
   END_PUT();
 }
 
 ostream& castable_expr::put( ostream& os) const
 {
   BEGIN_PUT1( castable_expr, theTargetType->toString() );
-  theInputExpr->put(os);
+  theInput->put(os);
   END_PUT();
 }
 
 ostream& cast_expr::put( ostream& os) const
 {
   BEGIN_PUT1( cast_expr, theTargetType->toString() );
-  theInputExpr->put(os);
+  theInput->put(os);
   END_PUT();
 }
 
@@ -643,7 +643,7 @@
   case ParseConstants::val_typename: os << "typename\n"; break;
   default: os << "??\n";
   }
-  theExpr->put(os) << endl;
+  theInput->put(os) << endl;
   END_PUT();
 }
 
@@ -796,16 +796,16 @@
 
 ostream& order_expr::put(ostream& os) const
 {
-  os << indent << "order_expr" << expr_addr (this) << "\n" << inc_indent
+  os << indent << "order_expr" << expr_addr(this) << "\n" << inc_indent
      << indent << "[ ";
 
   switch (theType)
   {
-  case ordered: os << "ordered\n"; break;
-  case unordered: os << "unordered\n"; break;
+  case doc_ordered: os << "ordered\n"; break;
+  case doc_unordered: os << "unordered\n"; break;
   default: os << "??\n";
   }
-  theExpr->put(os) << endl;
+  theInput->put(os) << endl;
   END_PUT();
 }
 

=== modified file 'src/compiler/expression/expr_type.cpp'
--- src/compiler/expression/expr_type.cpp	2012-10-16 13:08:12 +0000
+++ src/compiler/expression/expr_type.cpp	2012-10-24 11:34:21 +0000
@@ -105,14 +105,6 @@
     break;
   }
 
-  case order_expr_kind:
-  {
-    order_expr* e = static_cast<order_expr*>(this);
-
-    newType = e->theExpr->get_return_type();
-    break;
-  }
-
   case validate_expr_kind:
   {
     theType = rtm.ANY_NODE_TYPE_ONE;
@@ -332,7 +324,7 @@
   {
     cast_expr* e = static_cast<cast_expr*>(this);
 
-    xqtref_t argType = e->theInputExpr->get_return_type();
+    xqtref_t argType = e->theInput->get_return_type();
     TypeConstants::quantifier_t argQuant = argType->get_quantifier();
     TypeConstants::quantifier_t targetQuant = e->theTargetType->get_quantifier();
 
@@ -378,7 +370,7 @@
   {
     promote_expr* e = static_cast<promote_expr*>(this);
 
-    xqtref_t in_type = e->theInputExpr->get_return_type();
+    xqtref_t in_type = e->theInput->get_return_type();
     xqtref_t in_ptype = TypeOps::prime_type(tm, *in_type);
     xqtref_t target_ptype = TypeOps::prime_type(tm, *e->theTargetType);
 
@@ -490,7 +482,7 @@
 
     switch (e->type)
     {
-    case text_expr::text_constructor:
+    case text_constructor:
     {
       xqtref_t t = e->get_text()->get_return_type();
 
@@ -504,7 +496,7 @@
       break;
     }
 
-    case text_expr::comment_constructor:
+    case comment_constructor:
       nodeKind = store::StoreConsts::commentNode;
       break;
 
@@ -702,15 +694,19 @@
 
   case function_trace_expr_kind:
   {
-    function_trace_expr* e = static_cast<function_trace_expr*>(this);
-    newType = e->theExpr->get_return_type();
+    newType = static_cast<function_trace_expr*>(this)->theInput->get_return_type();
+    break;
+  }
+
+  case order_expr_kind:
+  {
+    newType = static_cast<order_expr*>(this)->theInput->get_return_type();
     break;
   }
 
   case wrapper_expr_kind:
   {
-    wrapper_expr* e = static_cast<wrapper_expr*>(this);
-    newType = e->theWrappedExpr->get_return_type();
+    newType = static_cast<wrapper_expr*>(this)->theInput->get_return_type();
     break;
   }
 

=== modified file 'src/compiler/expression/expr_utils.h'
--- src/compiler/expression/expr_utils.h	2012-09-19 21:16:15 +0000
+++ src/compiler/expression/expr_utils.h	2012-10-24 11:34:21 +0000
@@ -22,6 +22,9 @@
 namespace zorba 
 {
 
+class expr;
+class var_expr;
+
 /******************************************************************************
   Used by the orderspecs of an order by clause, and by the keyspecs of an
   index declaration.
@@ -47,6 +50,11 @@
 };
 
 
+/******************************************************************************
+
+********************************************************************************/
+typedef std::vector<std::pair<expr*, var_expr*> > var_rebind_list_t;
+
 }
 #endif
 

=== modified file 'src/compiler/expression/flwor_expr.cpp'
--- src/compiler/expression/flwor_expr.cpp	2012-10-22 15:10:23 +0000
+++ src/compiler/expression/flwor_expr.cpp	2012-10-24 11:34:21 +0000
@@ -25,6 +25,7 @@
 #include "compiler/expression/fo_expr.h"
 #include "compiler/expression/expr.h"
 #include "compiler/expression/expr_visitor.h"
+#include "compiler/expression/expr_manager.h"
 
 #include "compiler/api/compilercb.h"
 
@@ -111,7 +112,7 @@
                           theDomainExpr->get_loc(),
                           theDomainExpr,
                           varType,
-                          TreatIterator::TYPE_MATCH);
+                          TREAT_TYPE_MATCH);
       }
     }
   }
@@ -180,7 +181,7 @@
                             loc,
                             domainExpr,
                             declaredType,
-                            TreatIterator::TYPE_MATCH);
+                            TREAT_TYPE_MATCH);
 
           set_expr(domainExpr);
         }
@@ -307,7 +308,7 @@
                           loc,
                           domainExpr,
                           declaredType,
-                          TreatIterator::TYPE_MATCH);
+                          TREAT_TYPE_MATCH);
 
         set_expr(domainExpr);
       }
@@ -370,7 +371,7 @@
     static_context* sctx,
     CompilerCB* ccb,
     const QueryLoc& loc,
-    window_t winKind,
+    WindowKind winKind,
     var_expr* varExpr,
     expr* domainExpr,
     flwor_wincond* winStart,
@@ -412,7 +413,7 @@
                           loc,
                           domainExpr,
                           varType,
-                          TreatIterator::TYPE_MATCH);
+                          TREAT_TYPE_MATCH);
 
         set_expr(domainExpr);
       }
@@ -523,7 +524,7 @@
 }
 
 
-flwor_wincond::vars::vars()
+flwor_wincond_vars::flwor_wincond_vars()
   :
   posvar(NULL),
   curr(NULL),
@@ -533,13 +534,13 @@
 }
 
 
-flwor_wincond::vars::~vars()
+flwor_wincond_vars::~flwor_wincond_vars()
 {
 //  set_flwor_clause(NULL);
 }
 
 
-void flwor_wincond::vars::set_flwor_clause(flwor_clause* c)
+void flwor_wincond_vars::set_flwor_clause(flwor_clause* c)
 {
   if (posvar != NULL) posvar->set_flwor_clause(c);
   if (curr != NULL) curr->set_flwor_clause(c);
@@ -548,7 +549,7 @@
 }
 
 
-void flwor_wincond::vars::clone(
+void flwor_wincond_vars::clone(
     ExprManager* mgr,
     user_function* udf,
     flwor_wincond::vars& cloneVars,
@@ -619,7 +620,7 @@
      CompilerCB* ccb,
      const QueryLoc& loc,
      const rebind_list_t& gvars,
-     rebind_list_t ngvars,
+     const rebind_list_t& ngvars,
      const std::vector<std::string>& collations)
   :
   flwor_clause(sctx, ccb, loc, flwor_clause::group_clause),
@@ -808,6 +809,8 @@
   flwor_clause(sctx, ccb, loc, flwor_clause::count_clause),
   theVarExpr(var)
 {
+  if (theVarExpr != NULL)
+    theVarExpr->set_flwor_clause(this);
 }
 
 

=== modified file 'src/compiler/expression/flwor_expr.h'
--- src/compiler/expression/flwor_expr.h	2012-10-22 15:10:23 +0000
+++ src/compiler/expression/flwor_expr.h	2012-10-24 11:34:21 +0000
@@ -51,7 +51,7 @@
   friend class ExprManager;
 
 public:
-  typedef std::vector<std::pair<expr*, var_expr*> > rebind_list_t;
+  typedef var_rebind_list_t rebind_list_t;
 
   typedef enum
   {
@@ -98,8 +98,6 @@
 
   flwor_expr* get_flwor_expr() const { return theFlworExpr; }
 
-  virtual expr* get_expr() const { return NULL; }
-
   virtual void set_expr(expr* v) { }
 
   virtual var_expr* get_pos_var() const { return NULL; }
@@ -271,11 +269,8 @@
   friend class ExprManager;
   friend class ExprIterator;
 
-public:
-  typedef enum { tumbling_window, sliding_window } window_t;
-
 protected:
-  window_t         theWindowKind;
+  WindowKind       theWindowKind;
   flwor_wincond  * theWinStartCond;
   flwor_wincond  * theWinStopCond;
   bool             theLazyEval;
@@ -285,7 +280,7 @@
         static_context* sctx,
         CompilerCB* ccb,
         const QueryLoc& loc,
-        window_t winKind,
+        WindowKind winKind,
         var_expr* varExpr,
         expr* domainExpr,
         flwor_wincond* winStart,
@@ -295,7 +290,7 @@
 public:
   ~window_clause();
 
-  window_t get_winkind() const { return theWindowKind; }
+  WindowKind get_winkind() const { return theWindowKind; }
 
   flwor_wincond* get_win_start() const { return theWinStartCond; }
 
@@ -317,6 +312,32 @@
 
 /***************************************************************************//**
 
+********************************************************************************/
+struct flwor_wincond_vars
+{
+  var_expr* posvar;
+  var_expr* curr;
+  var_expr* prev;
+  var_expr* next;
+
+  flwor_wincond_vars();
+
+  ~flwor_wincond_vars();
+
+  void set_flwor_clause(flwor_clause* c);
+
+  void clone(
+      ExprManager* mgr,
+      user_function* udf,
+      flwor_wincond_vars& cloneVars,
+      expr::substitution_t& subst) const;
+
+  std::ostream& put(std::ostream&) const;
+};
+
+
+/***************************************************************************//**
+
   Class flwor_wincond represents a start/stop condition of a window clause.
 
   - Syntax:
@@ -353,27 +374,7 @@
   friend class ExprIterator;
 
 public:
-  struct vars
-  {
-    var_expr* posvar;
-    var_expr* curr;
-    var_expr* prev;
-    var_expr* next;
-
-    vars();
-
-    ~vars();
-
-    void set_flwor_clause(flwor_clause* c);
-
-    void clone(
-      ExprManager* mgr,
-      user_function* udf,
-      vars& cloneVars,
-      expr::substitution_t& subst) const;
-
-    std::ostream& put(std::ostream&) const;
-  };
+  typedef flwor_wincond_vars vars;
 
 protected:
   bool         theIsOnly;
@@ -456,7 +457,7 @@
       CompilerCB* ccb,
       const QueryLoc& loc,
       const rebind_list_t& gvars,
-      rebind_list_t ngvars,
+      const rebind_list_t& ngvars,
       const std::vector<std::string>& collations);
 
 public:

=== modified file 'src/compiler/expression/fo_expr.cpp'
--- src/compiler/expression/fo_expr.cpp	2012-10-09 14:06:08 +0000
+++ src/compiler/expression/fo_expr.cpp	2012-10-24 11:34:21 +0000
@@ -19,6 +19,7 @@
 
 #include "compiler/expression/fo_expr.h"
 #include "compiler/expression/expr_visitor.h"
+#include "compiler/expression/expr_manager.h"
 
 #include "compiler/api/compilercb.h"
 

=== modified file 'src/compiler/expression/fo_expr.h'
--- src/compiler/expression/fo_expr.h	2012-10-09 14:06:08 +0000
+++ src/compiler/expression/fo_expr.h	2012-10-24 11:34:21 +0000
@@ -118,30 +118,6 @@
 };
 
 
-////////// The following expressions in the AST "decay" into an fo_expr ///////
-
-typedef fo_expr additive_expr;
-
-typedef fo_expr and_expr;
-
-typedef fo_expr comparison_expr;
-
-typedef fo_expr enclosed_expr;
-
-typedef fo_expr intersect_except_expr;
-
-typedef fo_expr multiplicative_expr;
-
-typedef fo_expr or_expr;
-
-typedef fo_expr quantified_expr;
-
-typedef fo_expr range_expr;
-
-typedef fo_expr unary_expr;
-
-typedef fo_expr union_expr;
-
 } // namespace zorba
 
 #endif

=== modified file 'src/compiler/expression/ftnode.h'
--- src/compiler/expression/ftnode.h	2012-10-09 14:06:08 +0000
+++ src/compiler/expression/ftnode.h	2012-10-24 11:34:21 +0000
@@ -20,13 +20,17 @@
 #include <zorba/locale.h>
 
 #include "common/shared_types.h"
+
 #include "compiler/expression/expr_base.h"
 #include "compiler/expression/ftnode_classes.h"
 #include "compiler/parser/ft_types.h"
 #include "compiler/parser/parse_constants.h"
 #include "compiler/parsetree/parsenodes.h"
+
 #include "runtime/base/plan_iterator.h"
+
 #include "util/cxx_util.h"
+
 #include "zorbatypes/rchandle.h"
 #include "zorbatypes/zstring.h"
 

=== modified file 'src/compiler/expression/script_exprs.cpp'
--- src/compiler/expression/script_exprs.cpp	2012-10-09 14:06:08 +0000
+++ src/compiler/expression/script_exprs.cpp	2012-10-24 11:34:21 +0000
@@ -26,7 +26,7 @@
 #include "functions/function.h"
 
 #include "diagnostics/assert.h"
-
+#include "diagnostics/xquery_diagnostics.h"
 
 namespace zorba
 {
@@ -401,7 +401,7 @@
     static_context* sctx,
     user_function* udf,
     const QueryLoc& loc,
-    enum action action)
+    FlowCtlAction action)
   :
   expr(ccb, sctx, udf, loc, flowctl_expr_kind),
   theAction(action)

=== modified file 'src/compiler/expression/script_exprs.h'
--- src/compiler/expression/script_exprs.h	2012-10-09 14:06:08 +0000
+++ src/compiler/expression/script_exprs.h	2012-10-24 11:34:21 +0000
@@ -390,11 +390,8 @@
   friend class ExprIterator;
   friend class expr;
 
-public:
-  enum action { BREAK, CONTINUE };
-
 protected:
-  enum action theAction;
+  FlowCtlAction theAction;
 
 protected:
   flowctl_expr(
@@ -402,10 +399,10 @@
       static_context* sctx,
       user_function* udf,
       const QueryLoc& loc,
-      enum action action);
+      FlowCtlAction action);
 
 public:
-  enum action get_action() const { return theAction; }
+  FlowCtlAction get_action() const { return theAction; }
 
   void compute_scripting_kind();
 

=== modified file 'src/compiler/expression/update_exprs.cpp'
--- src/compiler/expression/update_exprs.cpp	2012-10-22 15:10:23 +0000
+++ src/compiler/expression/update_exprs.cpp	2012-10-24 11:34:21 +0000
@@ -18,6 +18,7 @@
 #include "compiler/expression/update_exprs.h"
 #include "compiler/expression/var_expr.h"
 #include "compiler/expression/expr_visitor.h"
+#include "compiler/expression/expr_manager.h"
 
 #include "compiler/api/compilercb.h"
 

=== modified file 'src/compiler/rewriter/framework/rewriter.h'
--- src/compiler/rewriter/framework/rewriter.h	2012-09-19 21:16:15 +0000
+++ src/compiler/rewriter/framework/rewriter.h	2012-10-24 11:34:21 +0000
@@ -29,12 +29,10 @@
 {
 public:
   Rewriter() {}
+
   virtual ~Rewriter() { }
 
   virtual bool rewrite(RewriterContext& rCtx) = 0;
-
-protected:
-  CompilerCB::config::opt_level_t theOptLevel;
 };
 
 }

=== modified file 'src/compiler/rewriter/rewriters/default_optimizer.cpp'
--- src/compiler/rewriter/rewriters/default_optimizer.cpp	2012-10-19 20:42:38 +0000
+++ src/compiler/rewriter/rewriters/default_optimizer.cpp	2012-10-24 11:34:21 +0000
@@ -36,8 +36,6 @@
 public:
   FoldRules()
   {
-    //ADD_RULE(MarkExpensiveOps);
-    // Most rules try to update the freevars annotations, but for now let's stay on the safe side
     ADD_RULE(MarkExprs);
     ADD_RULE(MarkFreeVars);
     ADD_RULE(FoldConst(false));
@@ -65,7 +63,6 @@
 
   SingletonRuleMajorDriver<EliminateTypeEnforcingOperations> driverTypeRules;
   SingletonRuleMajorDriver<EliminateExtraneousPathSteps> driverPathSimplify;
-  //SingletonRuleMajorDriver<ReplaceExprWithConstantOneWhenPossible> driverExprSimplify;
   RuleOnceDriver<EliminateUnusedLetVars> driverEliminateVars;
   RuleOnceDriver<MarkProducerNodeProps> driverMarkProducerNodeProps;
   RuleOnceDriver<MarkConsumerNodeProps> driverMarkConsumerNodeProps;

=== modified file 'src/compiler/rewriter/rules/flwor_rules.cpp'
--- src/compiler/rewriter/rules/flwor_rules.cpp	2012-10-22 15:10:23 +0000
+++ src/compiler/rewriter/rules/flwor_rules.cpp	2012-10-24 11:34:21 +0000
@@ -23,6 +23,7 @@
 #include "compiler/rewriter/tools/expr_tools.h"
 
 #include "compiler/expression/flwor_expr.h"
+#include "compiler/expression/script_exprs.h"
 #include "compiler/expression/expr_iter.h"
 #include "compiler/expression/expr.h"
 
@@ -239,19 +240,22 @@
 
       if (clause->get_kind() == flwor_clause::where_clause)
       {
-        whereExpr = clause->get_expr();
+        whereExpr = static_cast<where_clause*>(clause)->get_expr();
         const expr::FreeVars& whereVars = whereExpr->getFreeVars();
 
-        if (myVars.empty())
-          flwor.get_vars(myVars);
-
-        expr::FreeVars diff;
-        std::set_intersection(myVars.begin(),
-                              myVars.end(),
-                              whereVars.begin(),
-                              whereVars.end(),
-                              std::inserter(diff, diff.begin()));
-        if (diff.empty())
+        csize k = 0;
+        expr::FreeVars::const_iterator ite = whereVars.begin();
+        expr::FreeVars::const_iterator end = whereVars.end();
+        for (; ite != end; ++ite)
+        {
+          flwor_clause* vc = (*ite)->get_flwor_clause();
+          if (vc != NULL && vc->get_flwor_expr() == flworp)
+            break;
+
+          ++k;
+        }
+
+        if (k == whereVars.size())
         {
           flwor.remove_clause(i);
 
@@ -522,7 +526,7 @@
     }
     else if (clause->get_kind() == flwor_clause::where_clause)
     {
-      expr* whereExpr = clause->get_expr();
+      expr* whereExpr = static_cast<where_clause*>(clause)->get_expr();
 
       //TODO: Consider case where both whereExpr and whereCond ar AND ops
       if (whereCond == NULL)
@@ -638,7 +642,7 @@
   }
   case wrapper_expr_kind:
   {
-    return is_trivial_expr(static_cast<const wrapper_expr*>(e)->get_expr());
+    return is_trivial_expr(static_cast<const wrapper_expr*>(e)->get_input());
   }
   default:
     return false;
@@ -709,10 +713,6 @@
           domExpr->get_return_type()->max_card() >= 2)
         return false;
 
-      // test rbkt/zorba/extern/5890.xq illustrates why this check is needed
-      //if (hasNodeConstr && fc.get_expr()->contains_node_construction())
-      //  return false;
-
       break;
     }
     case flwor_clause::where_clause:
@@ -722,9 +722,11 @@
 
       assert(varQuant == TypeConstants::QUANT_ONE);
 
-      if (std::find(refpath.begin(), refpath.end(), clause->get_expr()) != refpath.end())
+      expr* whereExpr = static_cast<const where_clause*>(clause)->get_expr();
+
+      if (std::find(refpath.begin(), refpath.end(), whereExpr) != refpath.end())
       {
-        referencingExpr = clause->get_expr();
+        referencingExpr = whereExpr;
         break;
       }
 
@@ -1324,7 +1326,7 @@
       if (clause->get_kind() != flwor_clause::where_clause)
         continue;
 
-      expr* whereExpr = clause->get_expr();
+      expr* whereExpr = static_cast<where_clause*>(clause)->get_expr();
 
       expr* posExpr = NULL;
       var_expr* posVar = NULL;
@@ -1807,24 +1809,22 @@
   {
     bool merge = false;
     flwor_expr* nestedFlwor = NULL;
-    ulong numNestedClauses;
+    csize numNestedClauses;
 
     flwor_clause* c = flwor->get_clause(i);
 
-    expr* domainExpr = c->get_expr();
-
-    if (domainExpr != NULL &&
-        domainExpr->get_expr_kind() == flwor_expr_kind &&
-        !domainExpr->is_sequential())
+    if (c->get_kind() == flwor_clause::let_clause)
     {
-      nestedFlwor = static_cast<flwor_expr*>(c->get_expr());
-      numNestedClauses = nestedFlwor->num_clauses();
+      expr* domainExpr = static_cast<let_clause*>(c)->get_expr();
 
-      if (c->get_kind() == flwor_clause::let_clause)
+      if (domainExpr->get_expr_kind() == flwor_expr_kind &&
+          !domainExpr->is_sequential())
       {
+        nestedFlwor = static_cast<flwor_expr*>(domainExpr);
+        numNestedClauses = nestedFlwor->num_clauses();
         merge = true;
 
-        for (ulong j = 0; j < numNestedClauses; ++j)
+        for (csize j = 0; j < numNestedClauses; ++j)
         {
           flwor_clause* nestedClause = nestedFlwor->get_clause(j);
           flwor_clause::ClauseKind nestedClauseKind = nestedClause->get_kind();
@@ -1832,7 +1832,7 @@
           if (nestedClauseKind == flwor_clause::for_clause)
           {
             xqtref_t nestedDomainType =
-              nestedClause->get_expr()->get_return_type();
+            static_cast<for_clause*>(nestedClause)->get_expr()->get_return_type();
 
             if (nestedDomainType->get_quantifier() != TypeConstants::QUANT_ONE)
             {
@@ -1847,12 +1847,20 @@
           }
         }
       }
-      else if (c->get_kind() == flwor_clause::for_clause &&
-               c->get_pos_var() == NULL)
+    }
+    else if (c->get_kind() == flwor_clause::for_clause &&
+             static_cast<for_clause*>(c)->get_pos_var() == NULL)
+    {
+      expr* domainExpr = static_cast<for_clause*>(c)->get_expr();
+
+      if (domainExpr->get_expr_kind() == flwor_expr_kind &&
+          !domainExpr->is_sequential())
       {
+        nestedFlwor = static_cast<flwor_expr*>(domainExpr);
+        numNestedClauses = nestedFlwor->num_clauses();
         merge = true;
 
-        for (ulong j = 0; j < numNestedClauses; ++j)
+        for (csize j = 0; j < numNestedClauses; ++j)
         {
           flwor_clause* nestedClause = nestedFlwor->get_clause(j);
           flwor_clause::ClauseKind nestedClauseKind = nestedClause->get_kind();

=== modified file 'src/compiler/rewriter/rules/fold_rules.cpp'
--- src/compiler/rewriter/rules/fold_rules.cpp	2012-10-22 15:10:23 +0000
+++ src/compiler/rewriter/rules/fold_rules.cpp	2012-10-24 11:34:21 +0000
@@ -51,8 +51,6 @@
 
 namespace zorba {
 
-static void remove_wincond_vars(const flwor_wincond*, expr::FreeVars&);
-
 static bool standalone_expr(expr*);
 
 static bool already_folded(expr*, RewriterContext&);
@@ -236,84 +234,82 @@
     iter.next();
   }
 
+  switch (node->get_expr_kind())
+  {
+  case fo_expr_kind:
+  {
+    fo_expr* fo = static_cast<fo_expr *>(node);
+    function* f = fo->get_func();
+        
+    if (!f->isUdf())
+    {
+      if (FunctionConsts::FN_ERROR_0 <= f->getKind() &&
+          f->getKind() <= FunctionConsts::FN_TRACE_2)
+      {
+        curNonDiscardable = ANNOTATION_TRUE_FIXED;
+        curUnfoldable = ANNOTATION_TRUE_FIXED;
+      }
+      else if (f->getKind() == FunctionConsts::FN_ZORBA_REF_NODE_BY_REFERENCE_1)
+      {
+        curDereferencesNodes = ANNOTATION_TRUE;
+      }
+      
+      // Do not fold functions that always require access to the dynamic context,
+      // or may need to access the implicit timezone (which is also in the dynamic
+      // constext).
+      if (saveUnfoldable != ANNOTATION_TRUE_FIXED &&
+          (f->accessesDynCtx() ||
+           maybe_needs_implicit_timezone(fo) ||
+           !f->isDeterministic()))
+      {
+        curUnfoldable = ANNOTATION_TRUE_FIXED;
+      }
+    }
+    else if (theIsLocal)
+    {
+      curUnfoldable = saveUnfoldable;
+      curDereferencesNodes = saveDereferencesNodes;
+      curConstructsNodes = saveConstructsNodes;
+    }
+    else
+    {
+      if (saveUnfoldable != ANNOTATION_TRUE_FIXED &&
+          (f->accessesDynCtx() || !f->isDeterministic()))
+      {
+        curUnfoldable = ANNOTATION_TRUE_FIXED;
+      }
+      
+      if (static_cast<user_function*>(f)->dereferencesNodes())
+        curDereferencesNodes = ANNOTATION_TRUE;
+      
+      if (static_cast<user_function*>(f)->constructsNodes())
+        curConstructsNodes = ANNOTATION_TRUE;
+    }
+    
+    break;
+  }
+  
+  case var_expr_kind:
+  {
+    var_expr::var_kind varKind = static_cast<var_expr *>(node)->get_kind();
+    
+    if (varKind == var_expr::prolog_var || varKind == var_expr::local_var)
+      curUnfoldable = ANNOTATION_TRUE_FIXED;
+    
+    break;
+  }
+  
+  default:
+  {
+    break;
+  }
+  }
+
   if (node->is_sequential())
   {
     curNonDiscardable = ANNOTATION_TRUE_FIXED;
     curUnfoldable = ANNOTATION_TRUE_FIXED;
   }
-  else
-  {
-    switch (node->get_expr_kind())
-    {
-    case fo_expr_kind:
-    {
-      fo_expr* fo = static_cast<fo_expr *>(node);
-      function* f = fo->get_func();
-        
-      if (!f->isUdf())
-      {
-        if (FunctionConsts::FN_ERROR_0 <= f->getKind() &&
-            f->getKind() <= FunctionConsts::FN_TRACE_2)
-        {
-          curNonDiscardable = ANNOTATION_TRUE_FIXED;
-          curUnfoldable = ANNOTATION_TRUE_FIXED;
-        }
-        else if (f->getKind() == FunctionConsts::FN_ZORBA_REF_NODE_BY_REFERENCE_1)
-        {
-          curDereferencesNodes = ANNOTATION_TRUE;
-        }
-
-        // Do not fold functions that always require access to the dynamic context,
-        // or may need to access the implicit timezone (which is also in the dynamic
-        // constext).
-        if (saveUnfoldable != ANNOTATION_TRUE_FIXED &&
-            (f->accessesDynCtx() ||
-             maybe_needs_implicit_timezone(fo) ||
-             !f->isDeterministic()))
-        {
-          curUnfoldable = ANNOTATION_TRUE_FIXED;
-        }
-      }
-      else if (theIsLocal)
-      {
-        curUnfoldable = saveUnfoldable;
-        curDereferencesNodes = saveDereferencesNodes;
-        curConstructsNodes = saveConstructsNodes;
-      }
-      else
-      {
-        if (saveUnfoldable != ANNOTATION_TRUE_FIXED &&
-            (f->accessesDynCtx() || !f->isDeterministic()))
-        {
-          curUnfoldable = ANNOTATION_TRUE_FIXED;
-        }
-
-        if (static_cast<user_function*>(f)->dereferencesNodes())
-          curDereferencesNodes = ANNOTATION_TRUE;
-
-        if (static_cast<user_function*>(f)->constructsNodes())
-          curConstructsNodes = ANNOTATION_TRUE;
-      }
-      
-      break;
-    }
-    
-    case var_expr_kind:
-    {
-      var_expr::var_kind varKind = static_cast<var_expr *>(node)->get_kind();
-        
-      if (varKind == var_expr::prolog_var || varKind == var_expr::local_var)
-        curUnfoldable = ANNOTATION_TRUE_FIXED;
-    
-      break;
-    }
-
-    default:
-    {
-      break;
-    }
-    }
-  }
 
   if (saveNonDiscardable != curNonDiscardable &&
       saveNonDiscardable != ANNOTATION_TRUE_FIXED)
@@ -382,134 +378,79 @@
   For each expr E, collect all the variables that are referenced directly by E
   and its subexpressions.
 ********************************************************************************/
-
-RULE_REWRITE_PRE(MarkFreeVars)
-{
-  return NULL;
-}
-
-RULE_REWRITE_POST(MarkFreeVars)
+expr* MarkFreeVars::apply(RewriterContext& rCtx, expr* node, bool& modified)
 {
   expr::FreeVars& freevars = node->getFreeVars();
 
   freevars.clear();
 
-  if (node->get_expr_kind() == var_expr_kind)
+  switch (node->get_expr_kind())
+  {
+  case var_expr_kind:
   {
     var_expr* v = static_cast<var_expr *>(node);
     freevars.insert(v);
-  }
-  else
-  {
-    // Get the free vars of each child expr and add them to the free vars of the
-    // parent.
-    ExprIterator iter(node);
-    while (!iter.done())
-    {
-      expr* e = **iter;
-
+
+    break;
+  }
+  // Get the free vars of each child expr and add them to the free vars of the
+  // parent. But in case of a flwor expr, do not add any variables defined by
+  // the flwor expr itself
+
+  case flwor_expr_kind:
+  case gflwor_expr_kind:
+  {
+    flwor_expr* flwor = static_cast<flwor_expr *> (node);
+
+    ExprIterator iter(node);
+    while (!iter.done())
+    {
+      expr* e = **iter;
+        
+      apply(rCtx, e, modified);
+
+      const expr::FreeVars& kfv = e->getFreeVars();
+
+      expr::FreeVars::const_iterator ite = kfv.begin();
+      expr::FreeVars::const_iterator end = kfv.end();
+      for (; ite != end; ++ite)
+      {
+        flwor_clause* c = (*ite)->get_flwor_clause();
+        if (c != NULL && c->get_flwor_expr() == flwor)
+          continue;
+        
+        freevars.insert(*ite);
+      }
+      
+      iter.next();
+    }
+
+    break;
+  }
+  default:
+  {
+    ExprIterator iter(node);
+
+    while (!iter.done())
+    {
+      expr* e = **iter;
+
+      apply(rCtx, e, modified);
+        
       const expr::FreeVars& kfv = e->getFreeVars();
       std::copy(kfv.begin(),
                 kfv.end(),
                 inserter(freevars, freevars.begin()));
-
+      
       iter.next();
     }
-
-    // For a flwor expr, remove the vars defined by the flwor expr itself from
-    // the flwor free vars .
-    if (node->get_expr_kind() == flwor_expr_kind ||
-        node->get_expr_kind() == gflwor_expr_kind)
-    {
-      flwor_expr* flwor = dynamic_cast<flwor_expr *> (node);
-      for (flwor_expr::clause_list_t::const_iterator i = flwor->clause_begin();
-           i != flwor->clause_end();
-           ++i)
-      {
-        const flwor_clause* c = *i;
-
-        if (c->get_kind() == flwor_clause::for_clause)
-        {
-          const for_clause* fc = static_cast<const for_clause *>(c);
-
-          freevars.erase(fc->get_var());
-          if (fc->get_pos_var() != NULL)
-            freevars.erase(fc->get_pos_var());
-        }
-        else if (c->get_kind() == flwor_clause::let_clause)
-        {
-          const let_clause* lc = static_cast<const let_clause *>(c);
-
-          freevars.erase(lc->get_var());
-        }
-        else if (c->get_kind() == flwor_clause::window_clause)
-        {
-          const window_clause* wc = static_cast<const window_clause *>(c);
-
-          freevars.erase(wc->get_var());
-
-          flwor_wincond* startCond = wc->get_win_start();
-          flwor_wincond* stopCond = wc->get_win_stop();
-
-          if (startCond != NULL)
-            remove_wincond_vars(startCond, freevars);
-
-          if (stopCond != NULL)
-            remove_wincond_vars(stopCond, freevars);
-        }
-        else if (c->get_kind() == flwor_clause::group_clause)
-        {
-          const group_clause* gc = static_cast<const group_clause *>(c);
-
-          const flwor_clause::rebind_list_t& gvars = gc->get_grouping_vars();
-          csize numGroupVars = gvars.size();
-
-          for (csize i = 0; i < numGroupVars; ++i)
-          {
-            freevars.erase(gvars[i].second);
-          }
-
-          const flwor_clause::rebind_list_t& ngvars = gc->get_nongrouping_vars();
-          csize numNonGroupVars = ngvars.size();
-
-          for (csize i = 0; i < numNonGroupVars; ++i)
-          {
-            freevars.erase(ngvars[i].second);
-          }
-        }
-        else if (c->get_kind() == flwor_clause::count_clause)
-        {
-          const count_clause* cc = static_cast<const count_clause *>(c);
-
-          freevars.erase(cc->get_var());
-        }
-      }
-    }
+  }
   }
 
   return NULL;
 }
 
 
-static void remove_wincond_vars(
-    const flwor_wincond* cond,
-    expr::FreeVars& freevars)
-{
-  const flwor_wincond::vars& inVars = cond->get_in_vars();
-  const flwor_wincond::vars& outVars = cond->get_out_vars();
-
-  freevars.erase(inVars.posvar);
-  freevars.erase(inVars.curr);
-  freevars.erase(inVars.prev);
-  freevars.erase(inVars.next);
-
-  freevars.erase(outVars.posvar);
-  freevars.erase(outVars.curr);
-  freevars.erase(outVars.prev);
-  freevars.erase(outVars.next);
-}
-
-
 /*******************************************************************************
   Execute const exprs that return at most one item as a result. Replace such
   exprs by either a const_expr whose value is the returned item, or an empty
@@ -1014,7 +955,7 @@
 
       if (c->get_kind() == flwor_clause::for_clause)
       {
-        return c->get_expr();
+        return static_cast<for_clause*>(c)->get_expr();
       }
       else
       {

=== modified file 'src/compiler/rewriter/rules/hoist_rules.cpp'
--- src/compiler/rewriter/rules/hoist_rules.cpp	2012-10-20 21:29:37 +0000
+++ src/compiler/rewriter/rules/hoist_rules.cpp	2012-10-24 11:34:21 +0000
@@ -564,7 +564,7 @@
       k == axis_step_expr_kind ||
       k == match_expr_kind ||
       (k == wrapper_expr_kind &&
-       non_hoistable(static_cast<const wrapper_expr*>(e)->get_expr())) ||
+       non_hoistable(static_cast<const wrapper_expr*>(e)->get_input())) ||
       is_already_hoisted(e) ||
       is_enclosed_expr(e) ||
       e->containsRecursiveCall() ||

=== modified file 'src/compiler/rewriter/rules/index_join_rule.cpp'
--- src/compiler/rewriter/rules/index_join_rule.cpp	2012-10-10 13:05:50 +0000
+++ src/compiler/rewriter/rules/index_join_rule.cpp	2012-10-24 11:34:21 +0000
@@ -736,9 +736,9 @@
   {
     wrapper_expr* wrapper = reinterpret_cast<wrapper_expr*>(subExpr);
 
-    if (wrapper->get_expr()->get_expr_kind() == var_expr_kind)
+    if (wrapper->get_input()->get_expr_kind() == var_expr_kind)
     {
-      var_expr* var = reinterpret_cast<var_expr*>(wrapper->get_expr());
+      var_expr* var = reinterpret_cast<var_expr*>(wrapper->get_input());
       long varid = -1;
 
       if (rCtx.theVarIdMap->find(var) != rCtx.theVarIdMap->end())

=== modified file 'src/compiler/rewriter/rules/nodeid_rules.cpp'
--- src/compiler/rewriter/rules/nodeid_rules.cpp	2012-10-16 13:24:49 +0000
+++ src/compiler/rewriter/rules/nodeid_rules.cpp	2012-10-24 11:34:21 +0000
@@ -122,7 +122,7 @@
 
     order_expr* orderExpr = static_cast<order_expr *>(node);
 
-    rCtx.theIsInOrderedMode = (orderExpr->get_type() == order_expr::ordered ?
+    rCtx.theIsInOrderedMode = (orderExpr->get_type() == doc_ordered ?
                                true : false);
     break;
   }
@@ -278,17 +278,17 @@
 
   case wrapper_expr_kind :
   {
-    wrapper_expr* we = static_cast<wrapper_expr *>(node);
-    pushdown_ignores_sorted_nodes(node, we->get_expr());
-    pushdown_ignores_duplicate_nodes(node, we->get_expr());
+    wrapper_expr* e = static_cast<wrapper_expr *>(node);
+    pushdown_ignores_sorted_nodes(node, e->get_input());
+    pushdown_ignores_duplicate_nodes(node, e->get_input());
     break;
   }
 
   case function_trace_expr_kind :
   {
-    function_trace_expr* fte = static_cast<function_trace_expr*>(node);
-    pushdown_ignores_sorted_nodes(node, fte->get_expr());
-    pushdown_ignores_duplicate_nodes(node, fte->get_expr());
+    function_trace_expr* e = static_cast<function_trace_expr *>(node);
+    pushdown_ignores_sorted_nodes(node, e->get_input());
+    pushdown_ignores_duplicate_nodes(node, e->get_input());
     break;
   }
 
@@ -892,7 +892,7 @@
   {
     validate_expr* e = static_cast<validate_expr *>(node);
     std::vector<expr*> sources;
-    theSourceFinder->findNodeSources(e->get_expr(), sources);
+    theSourceFinder->findNodeSources(e->get_input(), sources);
     markSources(sources);
     break;
   }

=== modified file 'src/compiler/rewriter/rules/path_rules.cpp'
--- src/compiler/rewriter/rules/path_rules.cpp	2012-09-19 21:16:15 +0000
+++ src/compiler/rewriter/rules/path_rules.cpp	2012-10-24 11:34:21 +0000
@@ -26,22 +26,22 @@
 
 RULE_REWRITE_PRE(EliminateExtraneousPathSteps)
 {
-  relpath_expr* re = dynamic_cast<relpath_expr *>(node);
-  if (re != NULL)
+  if (node->get_expr_kind() == relpath_expr_kind)
   {
+    relpath_expr* re = static_cast<relpath_expr *>(node);
     csize numSteps = re->size();
 
-    for (csize i = 0; i < numSteps - 1; i++)
+    for (csize i = 1; i < numSteps - 1; ++i)
     {
-      axis_step_expr* axisStep = dynamic_cast<axis_step_expr*>((*re)[i]);
-
-      if (axisStep != NULL &&
-          axisStep->getAxis() == axis_kind_descendant_or_self &&
+      assert((*re)[i]->get_expr_kind() == axis_step_expr_kind);
+
+      axis_step_expr* axisStep = static_cast<axis_step_expr*>((*re)[i]);
+
+      if (axisStep->getAxis() == axis_kind_descendant_or_self &&
           axisStep->getTest()->getTestKind() == match_anykind_test)
       {
-        axis_step_expr* nextStep = dynamic_cast<axis_step_expr*>((*re)[i+1]);
-        if (nextStep != NULL &&
-            nextStep->getAxis() == axis_kind_child)
+        axis_step_expr* nextStep = static_cast<axis_step_expr*>((*re)[i+1]);
+        if (nextStep->getAxis() == axis_kind_child)
         {
           nextStep->setAxis(axis_kind_descendant);
           (*re).erase(i);
@@ -53,7 +53,7 @@
 
     if (numSteps == 1)
     {
-      return (*re) [0];
+      return (*re)[0];
     }
   }
 

=== modified file 'src/compiler/rewriter/rules/ruleset.h'
--- src/compiler/rewriter/rules/ruleset.h	2012-10-19 20:42:38 +0000
+++ src/compiler/rewriter/rules/ruleset.h	2012-10-24 11:34:21 +0000
@@ -47,10 +47,10 @@
 
 PREPOST_RULE(MergeFLWOR);
 
+  //PREPOST_RULE(MarkFreeVars);
+
 PREPOST_RULE(EliminateExtraneousPathSteps);
 
-PREPOST_RULE(MarkFreeVars);
-
 PREPOST_RULE(InlineFunctions);
 
 PREPOST_RULE(PartialEval);
@@ -100,6 +100,22 @@
   expr* apply(RewriterContext& rCtx, expr* node, bool& modified);
 };
 
+#if 1
+/*******************************************************************************
+
+********************************************************************************/
+class MarkFreeVars : public RewriteRule
+{
+public:
+  MarkFreeVars()
+    :
+    RewriteRule(RewriteRule::MarkFreeVars, "MarkFreeVars")
+  {
+  }
+
+  expr* apply(RewriterContext& rCtx, expr* node, bool& modified);
+};
+#endif
 
 /*******************************************************************************
 

=== modified file 'src/compiler/rewriter/rules/type_rules.cpp'
--- src/compiler/rewriter/rules/type_rules.cpp	2012-10-10 13:05:50 +0000
+++ src/compiler/rewriter/rules/type_rules.cpp	2012-10-24 11:34:21 +0000
@@ -188,7 +188,7 @@
                                            node->get_loc(),
                                            arg,
                                            target_type,
-                                           TreatIterator::TYPE_MATCH,
+                                           TREAT_TYPE_MATCH,
                                            false); // do not check the prime types
     }
 
@@ -268,7 +268,7 @@
                               argExpr->get_loc(),
                               argExpr,
                               rtm.DOUBLE_TYPE_STAR,
-                              PromoteIterator::FUNC_PARAM,
+                              PROMOTE_FUNC_PARAM,
                               replacement->getName());
 
           fo->set_arg(0, promoteExpr);
@@ -570,7 +570,7 @@
                                          arg->get_loc(),
                                          arg,
                                          t,
-                                         PromoteIterator::FUNC_PARAM,
+                                         PROMOTE_FUNC_PARAM,
                                          fn->getName());
 }
 

=== modified file 'src/compiler/rewriter/tools/dataflow_annotations.cpp'
--- src/compiler/rewriter/tools/dataflow_annotations.cpp	2012-10-12 09:05:54 +0000
+++ src/compiler/rewriter/tools/dataflow_annotations.cpp	2012-10-24 11:34:21 +0000
@@ -110,16 +110,32 @@
   case while_expr_kind:         // TODO
     break;
 
+  case promote_expr_kind:
+  case castable_expr_kind:
+  case instanceof_expr_kind:
+  {
+    default_walk(e);
+    cast_or_castable_base_expr* ue = static_cast<cast_or_castable_base_expr*>(e);
+    PROPOGATE_SORTED_NODES(ue->get_input(), e);
+    PROPOGATE_DISTINCT_NODES(ue->get_input(), e);
+    break;
+  }
+
   case wrapper_expr_kind:
-    compute_wrapper_expr(static_cast<wrapper_expr *>(e));
+  {
+    default_walk(e);
+    wrapper_expr* ue = static_cast<wrapper_expr*>(e);
+    PROPOGATE_SORTED_NODES(ue->get_input(), e);
+    PROPOGATE_DISTINCT_NODES(ue->get_input(), e);
     break;
+  }
 
   case function_trace_expr_kind:
   {
     default_walk(e);
-    function_trace_expr* fte = static_cast<function_trace_expr*>(e);
-    PROPOGATE_SORTED_NODES(fte->get_expr(), e);
-    PROPOGATE_DISTINCT_NODES(fte->get_expr(), e);
+    function_trace_expr* ue = static_cast<function_trace_expr*>(e);
+    PROPOGATE_SORTED_NODES(ue->get_input(), e);
+    PROPOGATE_DISTINCT_NODES(ue->get_input(), e);
     break;
   }
 
@@ -136,10 +152,6 @@
     compute_trycatch_expr(static_cast<trycatch_expr *>(e));
     break;
 
-  case promote_expr_kind:
-    compute_promote_expr(static_cast<promote_expr *>(e));
-    break;
-
   case if_expr_kind:
     compute_if_expr(static_cast<if_expr *>(e));
     break;
@@ -148,18 +160,10 @@
     compute_fo_expr(static_cast<fo_expr *>(e));
     break;
 
-  case instanceof_expr_kind:
-    compute_instanceof_expr(static_cast<instanceof_expr *>(e));
-    break;
-
   case treat_expr_kind:
     compute_treat_expr(static_cast<treat_expr *>(e));
     break;
 
-  case castable_expr_kind:
-    compute_castable_expr(static_cast<castable_expr *>(e));
-    break;
-
   case cast_expr_kind:
     compute_cast_expr(static_cast<cast_expr *>(e));
     break;
@@ -336,17 +340,6 @@
 /*******************************************************************************
 
 ********************************************************************************/
-void DataflowAnnotationsComputer::compute_wrapper_expr(wrapper_expr* e)
-{
-  default_walk(e);
-  PROPOGATE_SORTED_NODES(e->get_expr(), e);
-  PROPOGATE_DISTINCT_NODES(e->get_expr(), e);
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
 void DataflowAnnotationsComputer::compute_var_expr(var_expr* e)
 {
   if (!generic_compute(e))
@@ -451,17 +444,6 @@
 /*******************************************************************************
 
 ********************************************************************************/
-void DataflowAnnotationsComputer::compute_promote_expr(promote_expr* e)
-{
-  default_walk(e);
-  PROPOGATE_SORTED_NODES(e->get_input(), e);
-  PROPOGATE_DISTINCT_NODES(e->get_input(), e);
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
 void DataflowAnnotationsComputer::compute_if_expr(if_expr* e)
 {
   default_walk(e);
@@ -540,17 +522,6 @@
 /*******************************************************************************
 
 ********************************************************************************/
-void DataflowAnnotationsComputer::compute_instanceof_expr(instanceof_expr *e)
-{
-  default_walk(e);
-  PROPOGATE_SORTED_NODES(e->get_input(), e);
-  PROPOGATE_DISTINCT_NODES(e->get_input(), e);
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
 void DataflowAnnotationsComputer::compute_treat_expr(treat_expr *e)
 {
   default_walk(e);
@@ -565,17 +536,6 @@
 /*******************************************************************************
 
 ********************************************************************************/
-void DataflowAnnotationsComputer::compute_castable_expr(castable_expr *e)
-{
-  default_walk(e);
-  PROPOGATE_SORTED_NODES(e->get_input(), e);
-  PROPOGATE_DISTINCT_NODES(e->get_input(), e);
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
 void DataflowAnnotationsComputer::compute_cast_expr(cast_expr* e)
 {
   default_walk(e);
@@ -601,8 +561,8 @@
   default_walk(e);
   if (!generic_compute(e))
   {
-    PROPOGATE_SORTED_NODES(e->get_expr(), e);
-    PROPOGATE_DISTINCT_NODES(e->get_expr(), e);
+    PROPOGATE_SORTED_NODES(e->get_input(), e);
+    PROPOGATE_DISTINCT_NODES(e->get_input(), e);
   }
 }
 

=== modified file 'src/compiler/rewriter/tools/dataflow_annotations.h'
--- src/compiler/rewriter/tools/dataflow_annotations.h	2012-10-12 09:05:54 +0000
+++ src/compiler/rewriter/tools/dataflow_annotations.h	2012-10-24 11:34:21 +0000
@@ -38,15 +38,12 @@
 private:
   void compute_var_decl_expr(var_decl_expr* e);
   void compute_block_expr(block_expr* e);
-  void compute_wrapper_expr(wrapper_expr* e);
   void compute_var_expr(var_expr* e);
   void compute_var_set_expr(var_set_expr* e);
   void compute_flwor_expr(flwor_expr* e);
   void compute_trycatch_expr(trycatch_expr* e);
-  void compute_promote_expr(promote_expr* e);
   void compute_if_expr(if_expr* e);
   void compute_fo_expr(fo_expr* e);
-  void compute_instanceof_expr(instanceof_expr* e);
   void compute_treat_expr(treat_expr* e);
   void compute_castable_expr(castable_expr* e);
   void compute_cast_expr(cast_expr* e);

=== modified file 'src/compiler/rewriter/tools/expr_tools.cpp'
--- src/compiler/rewriter/tools/expr_tools.cpp	2012-10-22 15:10:23 +0000
+++ src/compiler/rewriter/tools/expr_tools.cpp	2012-10-24 11:34:21 +0000
@@ -188,7 +188,7 @@
   {
     wrapper_expr* wrapper = reinterpret_cast<wrapper_expr*>(e);
 
-    if (wrapper->get_expr() == oldVar)
+    if (wrapper->get_input() == oldVar)
     {
       wrapper->set_expr(newVar);
       return;

=== modified file 'src/compiler/translator/translator.cpp'
--- src/compiler/translator/translator.cpp	2012-10-23 19:08:52 +0000
+++ src/compiler/translator/translator.cpp	2012-10-24 11:34:21 +0000
@@ -1463,7 +1463,7 @@
       {
         argExpr = wrap_in_type_promotion(argExpr,
                                          paramType,
-                                         PromoteIterator::FUNC_PARAM,
+                                         PROMOTE_FUNC_PARAM,
                                          func->getName());
       }
       else
@@ -1471,7 +1471,7 @@
         argExpr = wrap_in_type_match(argExpr,
                                      paramType,
                                      loc,
-                                     TreatIterator::FUNC_PARAM,
+                                     TREAT_FUNC_PARAM,
                                      func->getName());
       }
     }
@@ -1500,7 +1500,7 @@
 expr* wrap_in_type_promotion(
     expr* e,
     const xqtref_t& type,
-    PromoteIterator::ErrorKind errorKind,
+    PromoteErrorKind errorKind,
     store::Item* qname = NULL)
 {
   e = wrap_in_atomization(e);
@@ -1522,7 +1522,7 @@
     expr* e,
     const xqtref_t& type,
     const QueryLoc& loc,
-    TreatIterator::ErrorKind errorKind,
+    TreatErrorKind errorKind,
     store::Item_t qname = NULL)
 {
   TypeManager* tm = e->get_type_manager();
@@ -2053,7 +2053,7 @@
                       loc,
                       initExpr,
                       varType,
-                      TreatIterator::TYPE_MATCH);
+                      TREAT_TYPE_MATCH);
   }
 
   expr* declExpr = theExprManager->
@@ -2073,7 +2073,7 @@
                       loc,
                       getExpr,
                       varType,
-                      TreatIterator::TYPE_MATCH);
+                      TREAT_TYPE_MATCH);
 
     stmts.push_back(treatExpr);
   }
@@ -3823,7 +3823,7 @@
     {
       body = wrap_in_type_promotion(body,
                                     returnType,
-                                    PromoteIterator::FUNC_RETURN,
+                                    PROMOTE_FUNC_RETURN,
                                     udf->getName());
 
       body->set_loc(v.get_return_type()->get_location());
@@ -3833,7 +3833,7 @@
       body = wrap_in_type_match(body,
                                 returnType,
                                 loc,
-                                TreatIterator::FUNC_RETURN,
+                                TREAT_FUNC_RETURN,
                                 udf->getName());
     }
 
@@ -4540,13 +4540,13 @@
   domainExpr = wrap_in_type_match(domainExpr,
                                   theRTM.STRUCTURED_ITEM_TYPE_STAR,
                                   loc,
-                                  TreatIterator::INDEX_DOMAIN,
+                                  TREAT_INDEX_DOMAIN,
                                   index->getName());
 #else
   domainExpr = wrap_in_type_match(domainExpr,
                                   theRTM.ANY_NODE_TYPE_STAR,
                                   loc,
-                                  TreatIterator::INDEX_DOMAIN,
+                                  TREAT_INDEX_DOMAIN,
                                   index->getName());
 #endif
 
@@ -4718,7 +4718,7 @@
       keyExpr = wrap_in_type_match(keyExpr,
                                    type,
                                    loc,
-                                   TreatIterator::INDEX_KEY,
+                                   TREAT_INDEX_KEY,
                                    index->getName());
 
       keyTypes[i] = ptype->getBaseBuiltinType();
@@ -5941,7 +5941,7 @@
                                                   loc,
                                                   valueExpr,
                                                   varType,
-                                                  TreatIterator::TYPE_MATCH);
+                                                  TREAT_TYPE_MATCH);
 
   push_nodestack(theExprManager->create_var_set_expr(theRootSctx,
                                                      theUDF,
@@ -6047,7 +6047,7 @@
   expr* condExpr = pop_nodestack();
 
   expr* breakExpr = theExprManager->
-  create_flowctl_expr(theRootSctx, theUDF, loc, flowctl_expr::BREAK);
+  create_flowctl_expr(theRootSctx, theUDF, loc, FLOW_BREAK);
 
   condExpr = theExprManager->
   create_if_expr(theRootSctx, theUDF, loc, condExpr, create_empty_seq(loc), breakExpr);
@@ -6082,7 +6082,7 @@
 {
   TRACE_VISIT_OUT();
 
-  enum flowctl_expr::action a;
+  FlowCtlAction a;
 
   switch (v.get_action())
   {
@@ -6092,7 +6092,7 @@
     {
       RAISE_ERROR_NO_PARAMS(zerr::XSST0009, loc);
     }
-    a = flowctl_expr::BREAK;
+    a = FLOW_BREAK;
     break;
   }
   case FlowCtlStatement::CONTINUE:
@@ -6101,7 +6101,7 @@
     {
       RAISE_ERROR_NO_PARAMS(zerr::XSST0010, loc);
     }
-    a = flowctl_expr::CONTINUE;
+    a = FLOW_CONTINUE;
     break;
   }
   default:
@@ -6557,9 +6557,9 @@
   // Pop the window the domain expr.
   expr* windowDomainExpr = pop_nodestack();
 
-  window_clause::window_t winKind = (v.get_wintype() == WindowClause::tumbling_window ?
-                                     window_clause::tumbling_window :
-                                     window_clause::sliding_window);
+  WindowKind winKind = (v.get_wintype() == WindowClause::tumbling_window ?
+                        tumbling_window :
+                        sliding_window);
 
   window_clause* clause = theExprManager->create_window_clause(theRootSctx,
                                                                v.get_location(),
@@ -6943,7 +6943,7 @@
       inputExpr = wrap_in_type_match(inputExpr,
                                      theRTM.ANY_ATOMIC_TYPE_QUESTION,
                                      specLoc,
-                                     TreatIterator::MULTI_VALUED_GROUPING_KEY);
+                                     TREAT_MULTI_VALUED_GROUPING_KEY);
 
       // We need to do this to handle grouping vars with same names but
       // different collations.
@@ -7589,7 +7589,7 @@
                         loc,
                         sv,
                         type,
-                        TreatIterator::TREAT_EXPR);
+                        TREAT_EXPR);
 
       // clauseExpr = [let $caseVar := treat_as($sv, caseType) return NULL]
       clauseExpr = wrap_in_let_flwor(treatExpr, caseVar, NULL);
@@ -8421,10 +8421,10 @@
 {
   TRACE_VISIT_OUT();
 
-  push_nodestack(theExprManager->create_instanceof_expr(theRootSctx, theUDF,
-                                     loc,
-                                     pop_nodestack(),
-                                     pop_tstack()));
+  push_nodestack(CREATE(instanceof)(theRootSctx, theUDF,
+                                    loc,
+                                    pop_nodestack(),
+                                    pop_tstack()));
 }
 
 
@@ -8441,11 +8441,11 @@
 {
   TRACE_VISIT_OUT();
 
-  push_nodestack(theExprManager->create_treat_expr(theRootSctx, theUDF,
-                                loc,
-                                pop_nodestack(),
-                                pop_tstack(),
-                                TreatIterator::TREAT_EXPR));
+  push_nodestack(CREATE(treat)(theRootSctx, theUDF,
+                               loc,
+                               pop_nodestack(),
+                               pop_tstack(),
+                               TREAT_EXPR));
 }
 
 
@@ -9003,22 +9003,23 @@
                                        loc,
                                        DOT_REF,
                                        GENV_TYPESYSTEM.ANY_NODE_TYPE_ONE,
-                                       TreatIterator::PATH_DOT);
+                                       TREAT_PATH_DOT);
 
     ctx_path_expr->add_back(sourceExpr);
 
-    match_expr* me = theExprManager->create_match_expr(theRootSctx, theUDF, loc);
+    match_expr* me = CREATE(match)(theRootSctx, theUDF, loc);
     me->setTestKind(match_anykind_test);
-    axis_step_expr* ase = theExprManager->create_axis_step_expr(theRootSctx, theUDF, loc);
+    axis_step_expr* ase = CREATE(axis_step)(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, theUDF,
-                                   loc,
-                                   BUILTIN_FUNC(FN_ROOT_1),
-                                   ctx_path_expr);
+    fo_expr* fnroot = CREATE(fo)(theRootSctx,
+                                 theUDF,
+                                 loc,
+                                 BUILTIN_FUNC(FN_ROOT_1),
+                                 ctx_path_expr);
     normalize_fo(fnroot);
 
     if (pathExpr != NULL)
@@ -9032,11 +9033,12 @@
     else
     {
       // case 1
-      expr* result = theExprManager->create_treat_expr(theRootSctx, theUDF,
-                                     loc,
-                                     fnroot,
-                                     GENV_TYPESYSTEM.DOCUMENT_TYPE_ONE,
-                                     TreatIterator::TREAT_EXPR);
+      expr* result = CREATE(treat)(theRootSctx,
+                                   theUDF,
+                                   loc,
+                                   fnroot,
+                                   GENV_TYPESYSTEM.DOCUMENT_TYPE_ONE,
+                                   TREAT_EXPR);
       push_nodestack(result);
     }
   }
@@ -9127,7 +9129,7 @@
                                          loc,
                                          DOT_REF,
                                          GENV_TYPESYSTEM.ANY_NODE_TYPE_ONE,
-                                         TreatIterator::PATH_DOT);
+                                         TREAT_PATH_DOT);
       pathExpr->add_back(sourceExpr);
 
       if (axisStep->get_predicate_list() == NULL)
@@ -9200,14 +9202,13 @@
 #ifdef NODE_SORT_OPT
     if (pathExpr->size() == 0)
     {
-      TreatIterator::ErrorKind errKind = TreatIterator::PATH_STEP;
+      TreatErrorKind errKind = TREAT_PATH_STEP;
 
       if (stepExpr->get_expr_kind() == wrapper_expr_kind)
       {
-        wrapper_expr* tmp = static_cast<wrapper_expr*>(stepExpr);
         var_expr* dotVar = lookup_var(DOT_VARNAME, loc, zerr::ZXQP0000_NO_ERROR);
-        if (tmp->get_expr() == dotVar)
-          errKind = TreatIterator::PATH_DOT;
+        if (static_cast<wrapper_expr*>(stepExpr)->get_input() == dotVar)
+          errKind = TREAT_PATH_DOT;
       }
 
       expr* sourceExpr = theExprManager->create_treat_expr(theRootSctx, theUDF,
@@ -10369,7 +10370,7 @@
 
   push_nodestack(theExprManager->create_order_expr(theRootSctx, theUDF,
                                 loc,
-                                order_expr::ordered,
+                                doc_ordered,
                                 pop_nodestack()));
 }
 
@@ -10390,7 +10391,7 @@
 
   push_nodestack(theExprManager->create_order_expr(theRootSctx, theUDF,
                                 loc,
-                                order_expr::unordered,
+                                doc_unordered,
                                 pop_nodestack()));
 }
 
@@ -10642,22 +10643,26 @@
 
         var_expr* tv = create_temp_var(loc, var_expr::let_var);
 
-        expr* nanExpr = theExprManager->create_const_expr(theRootSctx, theUDF, loc, xs_double::nan());
+        expr* nanExpr = CREATE(const)(theRootSctx, theUDF, loc, xs_double::nan());
 
-        expr* condExpr = theExprManager->create_castable_expr(theRootSctx, theUDF, loc, &*tv, theRTM.DOUBLE_TYPE_ONE);
+        expr* condExpr = CREATE(castable)(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, theUDF, loc, condExpr, castExpr, nanExpr);
+        expr* ret = CREATE(if)(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,
-                                                          TreatIterator::TYPE_MATCH),
+        push_nodestack(wrap_in_let_flwor(CREATE(treat)(theRootSctx,
+                                                       theUDF,
+                                                       loc,
+                                                       data_expr,
+                                                       theRTM.ANY_ATOMIC_TYPE_QUESTION,
+                                                       TREAT_TYPE_MATCH),
                                            tv,
                                            ret));
         return;
@@ -10665,19 +10670,21 @@
       case FunctionConsts::FN_STATIC_BASE_URI_0:
       {
         if (numArgs != 0)
+        {
           RAISE_ERROR(err::XPST0017, loc,
           ERROR_PARAMS("fn:static-base-uri",
                        ZED(FunctionUndeclared_3),
                        numArgs));
+        }
 
         zstring baseuri = theSctx->get_base_uri();
         if (baseuri.empty())
           push_nodestack(create_empty_seq(loc));
         else
-          push_nodestack(theExprManager->create_cast_expr(theRootSctx, theUDF,
-                                       loc,
-                                       theExprManager->create_const_expr(theRootSctx, theUDF, loc, baseuri),
-                                       theRTM.ANY_URI_TYPE_ONE));
+          push_nodestack(CREATE(cast)(theRootSctx, theUDF,
+                                      loc,
+                                      CREATE(const)(theRootSctx, theUDF, loc, baseuri),
+                                      theRTM.ANY_URI_TYPE_ONE));
         return;
       }
       case FunctionConsts::FN_ID_1:
@@ -10890,7 +10897,7 @@
       resultExpr = wrap_in_type_match(foExpr,
                                       resultType,
                                       loc,
-                                      TreatIterator::FUNC_RETURN,
+                                      TREAT_FUNC_RETURN,
                                       f->getName());
     }
 
@@ -11024,7 +11031,7 @@
         // wrap function's QName
         expr* qnameExpr = wrap_in_type_promotion(arguments[0],
                                                  theRTM.QNAME_TYPE_ONE,
-                                                 PromoteIterator::TYPE_PROMOTION);
+                                                 PROMOTE_TYPE_PROMOTION);
 
         for (csize i = 0; i < numArgs ; ++i)
         {
@@ -11487,11 +11494,11 @@
   // Wrap the body in appropriate type op.
   if (TypeOps::is_builtin_simple(CTX_TM, *returnType))
   {
-    body = wrap_in_type_promotion(body, returnType, PromoteIterator::TYPE_PROMOTION);
+    body = wrap_in_type_promotion(body, returnType, PROMOTE_TYPE_PROMOTION);
   }
   else
   {
-    body = wrap_in_type_match(body, returnType, loc, TreatIterator::TYPE_MATCH);
+    body = wrap_in_type_match(body, returnType, loc, TREAT_TYPE_MATCH);
   }
 
   // Make the body be the return expr of the flwor that binds the function params.
@@ -11608,19 +11615,21 @@
   {
     contentExpr = pop_nodestack();
 
-    contentExpr = theExprManager->
-    create_treat_expr(theRootSctx,
-                      theUDF,
-                      contentExpr->get_loc(),
-                      contentExpr,
-                      GENV_TYPESYSTEM.JSON_OBJECT_TYPE_STAR,
-                      TreatIterator::TYPE_MATCH,
-                      true,
-                      NULL);
+    contentExpr = CREATE(treat)(theRootSctx,
+                                theUDF,
+                                contentExpr->get_loc(),
+                                contentExpr,
+                                GENV_TYPESYSTEM.JSON_OBJECT_TYPE_STAR,
+                                TREAT_TYPE_MATCH,
+                                true,
+                                NULL);
   }
 
-  expr* jo = theExprManager->
-  create_json_object_expr(theRootSctx, theUDF, loc, contentExpr, v.get_accumulate());
+  expr* jo = CREATE(json_object)(theRootSctx,
+                                 theUDF,
+                                 loc,
+                                 contentExpr,
+                                 v.get_accumulate());
 
   push_nodestack(jo);
 #endif
@@ -12114,11 +12123,9 @@
   {
     if (!v.isStripped())
     {
-      expr* content = theExprManager->create_const_expr(theRootSctx, theUDF, loc, v.get_elem_content().str());
+      expr* content = CREATE(const)(theRootSctx, theUDF, loc, v.get_elem_content().str());
 
-      push_nodestack(theExprManager->create_text_expr(theRootSctx, theUDF, loc,
-                                   text_expr::text_constructor,
-                                   content));
+      push_nodestack(CREATE(text)(theRootSctx, theUDF, loc, text_constructor, content));
     }
   }
 }
@@ -12146,6 +12153,7 @@
 void check_boundary_whitespace(const DirElemContent& v)
 {
   v.setIsStripped(false);
+
   if (theSctx->boundary_space_mode() == StaticContextConsts::strip_space)
   {
     bool lPrevIsBoundary = translator_ns::pop_stack (theIsWSBoundaryStack);
@@ -12220,8 +12228,8 @@
   // Skip empty CDATA sections
   if(!lCDATA_content.empty())
   {
-    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));
+    expr* content = CREATE(const)(theRootSctx, theUDF, loc, lCDATA_content);
+    push_nodestack(CREATE(text)(theRootSctx, theUDF, loc, text_constructor, content));
   }
 }
 
@@ -12397,7 +12405,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, theUDF, loc, content);
+    expr* lConstExpr = CREATE(const)(theRootSctx, theUDF, loc, content);
     push_nodestack ( lConstExpr );
     break;
   }
@@ -12420,10 +12428,13 @@
   TRACE_VISIT_OUT();
 
   zstring str = v.get_comment().str();
-  expr* content = theExprManager->create_const_expr (theRootSctx, theUDF, loc, str);
-  push_nodestack (theExprManager->create_text_expr(theRootSctx, theUDF, loc,
-                                text_expr::comment_constructor,
-                                content));
+  expr* content = CREATE(const)(theRootSctx, theUDF, loc, str);
+
+  push_nodestack (CREATE(text)(theRootSctx,
+                               theUDF,
+                               loc,
+                               comment_constructor,
+                               content));
 }
 
 
@@ -12589,8 +12600,8 @@
   fo_expr* enclosedExpr = wrap_in_enclosed_expr(inputExpr, loc);
 
   expr* textExpr = theExprManager->create_text_expr(theRootSctx, theUDF, loc,
-                                                     text_expr::comment_constructor,
-                                                     enclosedExpr);
+                                                    comment_constructor,
+                                                    enclosedExpr);
 
   push_nodestack(textExpr);
 }
@@ -12653,7 +12664,7 @@
 
   expr* textExpr = theExprManager->create_text_expr(theRootSctx, theUDF,
                                                      loc,
-                                                     text_expr::text_constructor,
+                                                     text_constructor,
                                                      enclosedExpr);
 
   push_nodestack(textExpr);
@@ -13454,29 +13465,24 @@
   targetExpr = wrap_in_type_match(targetExpr,
                                   rtm.JSON_OBJECT_TYPE_ONE,
                                   loc,
-                                  TreatIterator::JSONIQ_OBJECT_UPDATE_TARGET, // JNUP0008
+                                  TREAT_JSONIQ_OBJECT_UPDATE_TARGET, // JNUP0008
                                   NULL);
 
   contentExpr = wrap_in_type_match(contentExpr,
                                   rtm.JSON_OBJECT_TYPE_STAR,
                                   loc,
-                                  TreatIterator::JSONIQ_OBJECT_UPDATE_CONTENT, // JNUP0019
+                                  TREAT_JSONIQ_OBJECT_UPDATE_CONTENT, // JNUP0019
                                   NULL);
 
   std::vector<expr*> args(2);
   args[0] = targetExpr;
-  args[1] = theExprManager->create_json_object_expr(
-      theRootSctx,
-      theUDF,
-      loc,
-      contentExpr,
-      false);
+  args[1] = CREATE(json_object)(theRootSctx, theUDF, loc, contentExpr, false);
 
-  expr* updExpr = theExprManager->
-  create_fo_expr(theRootSctx, theUDF,
-                 loc,
-                 BUILTIN_FUNC(OP_ZORBA_JSON_OBJECT_INSERT_2),
-                 args);
+  expr* updExpr = CREATE(fo)(theRootSctx,
+                             theUDF,
+                             loc,
+                             BUILTIN_FUNC(OP_ZORBA_JSON_OBJECT_INSERT_2),
+                             args);
 
   push_nodestack(updExpr);
 #endif
@@ -13510,12 +13516,12 @@
 
   posExpr = wrap_in_type_promotion(posExpr,
                                    rtm.INTEGER_TYPE_ONE,
-                                   PromoteIterator::JSONIQ_ARRAY_SELECTOR); // JNUP0007
+                                   PROMOTE_JSONIQ_ARRAY_SELECTOR); // JNUP0007
 
   targetExpr = wrap_in_type_match(targetExpr,
                                   rtm.JSON_ARRAY_TYPE_ONE,
                                   loc,
-                                  TreatIterator::JSONIQ_ARRAY_UPDATE_TARGET, // JNUP0008
+                                  TREAT_JSONIQ_ARRAY_UPDATE_TARGET, // JNUP0008
                                   NULL);
 
   std::vector<expr*> args(3);
@@ -13560,15 +13566,15 @@
   targetExpr = wrap_in_type_match(targetExpr,
                                   theRTM.JSON_ARRAY_TYPE_ONE,
                                   loc,
-                                  TreatIterator::JSONIQ_ARRAY_UPDATE_TARGET, // JNUP0008
+                                  TREAT_JSONIQ_ARRAY_UPDATE_TARGET, // JNUP0008
                                   NULL);
 
-  fo_expr* updExpr = theExprManager->
-  create_fo_expr(theRootSctx, theUDF,
-                 loc,
-                 BUILTIN_FUNC(OP_ZORBA_JSON_ARRAY_APPEND_2),
-                 targetExpr,
-                 contentExpr);
+  fo_expr* updExpr = CREATE(fo)(theRootSctx,
+                                theUDF,
+                                loc,
+                                BUILTIN_FUNC(OP_ZORBA_JSON_ARRAY_APPEND_2),
+                                targetExpr,
+                                contentExpr);
 
   normalize_fo(updExpr);
 
@@ -13610,13 +13616,13 @@
 
   selExpr = wrap_in_type_promotion(selExpr,
                                    theRTM.ANY_ATOMIC_TYPE_ONE,
-                                   PromoteIterator::JSONIQ_SELECTOR, // JNUP0007
+                                   PROMOTE_JSONIQ_SELECTOR, // JNUP0007
                                    NULL);
 
   targetExpr = wrap_in_type_match(targetExpr,
                                   theRTM.JSON_ITEM_TYPE_ONE,
                                   loc,
-                                  TreatIterator::JSONIQ_UPDATE_TARGET, // JNUP0008
+                                  TREAT_JSONIQ_UPDATE_TARGET, // JNUP0008
                                   NULL);
 
   fo_expr* updExpr = theExprManager->
@@ -13658,12 +13664,12 @@
   args[0] = wrap_in_type_match(targetExpr,
                                theRTM.JSON_ITEM_TYPE_ONE,
                                loc,
-                               TreatIterator::JSONIQ_UPDATE_TARGET, // JNUP0008
+                               TREAT_JSONIQ_UPDATE_TARGET, // JNUP0008
                                NULL);
 
   args[1] = wrap_in_type_promotion(selExpr,
                                    theRTM.ANY_ATOMIC_TYPE_ONE,
-                                   PromoteIterator::JSONIQ_SELECTOR, // JNUP0007
+                                   PROMOTE_JSONIQ_SELECTOR, // JNUP0007
                                    NULL);
 
   args[2] = theExprManager->create_fo_expr(theRootSctx, theUDF,
@@ -13709,22 +13715,22 @@
   args[0] = wrap_in_type_match(targetExpr,
                                theRTM.JSON_OBJECT_TYPE_ONE,
                                loc,
-                               TreatIterator::JSONIQ_OBJECT_UPDATE_TARGET, // JNUP0008
+                               TREAT_JSONIQ_OBJECT_UPDATE_TARGET, // JNUP0008
                                NULL);
 
   args[1] = wrap_in_type_promotion(nameExpr,
                                    theRTM.STRING_TYPE_ONE,
-                                   PromoteIterator::JSONIQ_OBJECT_SELECTOR); // JNUP0007
+                                   PROMOTE_JSONIQ_OBJECT_SELECTOR); // JNUP0007
 
   args[2] = wrap_in_type_promotion(newNameExpr,
                                    theRTM.STRING_TYPE_ONE,
-                                   PromoteIterator::JSONIQ_OBJECT_SELECTOR); // JNUP0007
+                                   PROMOTE_JSONIQ_OBJECT_SELECTOR); // JNUP0007
 
-  fo_expr* updExpr = theExprManager->
-  create_fo_expr(theRootSctx, theUDF,
-                 loc,
-                 BUILTIN_FUNC(OP_ZORBA_JSON_RENAME_3),
-                 args);
+  fo_expr* updExpr = CREATE(fo)(theRootSctx,
+                                theUDF,
+                                loc,
+                                BUILTIN_FUNC(OP_ZORBA_JSON_RENAME_3),
+                                args);
 
   push_nodestack(updExpr);
 #endif
@@ -14142,7 +14148,7 @@
   push_nodestack( wrap_in_type_match(e,
                                      theRTM.ANY_NODE_TYPE_STAR,
                                      e->get_loc(),
-                                     TreatIterator::TYPE_MATCH));
+                                     TREAT_TYPE_MATCH));
 #endif /* ZORBA_NO_FULL_TEXT */
 }
 
@@ -14319,12 +14325,12 @@
   if ( e1 ) {
     e1 = wrap_in_type_promotion(e1,
                                 theRTM.INTEGER_TYPE_ONE,
-                                PromoteIterator::TYPE_PROMOTION);
+                                PROMOTE_TYPE_PROMOTION);
   }
   if ( e2 ) {
     e2 = wrap_in_type_promotion(e2,
                                 theRTM.INTEGER_TYPE_ONE,
-                                PromoteIterator::TYPE_PROMOTION);
+                                PROMOTE_TYPE_PROMOTION);
   }
 
   ftrange *const r = new ftrange( loc, v.get_mode(), e1, e2 );
@@ -14584,7 +14590,7 @@
   expr* e( pop_nodestack() );
   e = wrap_in_type_promotion(e,
                              theRTM.DOUBLE_TYPE_ONE,
-                             PromoteIterator::TYPE_PROMOTION);
+                             PROMOTE_TYPE_PROMOTION);
   push_ftstack( new ftweight( loc, e ) );
 #endif /* ZORBA_NO_FULL_TEXT */
 }
@@ -14620,7 +14626,7 @@
   expr* e( pop_nodestack() );
   e = wrap_in_type_promotion(e,
                              theRTM.INTEGER_TYPE_ONE,
-                             PromoteIterator::TYPE_PROMOTION);
+                             PROMOTE_TYPE_PROMOTION);
   push_ftstack( new ftwindow_filter( loc, e, v.get_unit()->get_unit() ) );
 #endif /* ZORBA_NO_FULL_TEXT */
 }
@@ -14637,7 +14643,7 @@
   expr* e( pop_nodestack() );
   e = wrap_in_type_promotion(e,
                              theRTM.STRING_TYPE_STAR,
-                             PromoteIterator::TYPE_PROMOTION);
+                             PROMOTE_TYPE_PROMOTION);
   push_ftstack( new ftwords( loc, e, v.get_any_all_option()->get_option() ) );
 #endif /* ZORBA_NO_FULL_TEXT */
 }

=== modified file 'src/compiler/xqddf/value_index.cpp'
--- src/compiler/xqddf/value_index.cpp	2012-10-22 15:10:23 +0000
+++ src/compiler/xqddf/value_index.cpp	2012-10-24 11:34:21 +0000
@@ -29,6 +29,7 @@
 #include "compiler/expression/script_exprs.h"
 #include "compiler/expression/expr.h"
 #include "compiler/expression/expr_iter.h"
+#include "compiler/expression/expr_manager.h"
 #include "compiler/codegen/plan_visitor.h"
 
 #include "runtime/base/plan_iterator.h"

=== modified file 'src/functions/func_booleans_impl.cpp'
--- src/functions/func_booleans_impl.cpp	2012-10-10 13:05:50 +0000
+++ src/functions/func_booleans_impl.cpp	2012-10-24 11:34:21 +0000
@@ -47,10 +47,9 @@
     :
     function(sig, kind)
   {
+    setFlag(FunctionConsts::IsComparison);
   }
 
-  bool isComparisonFunction() const { return true; }
-
   virtual const char* comparison_name() const { return ""; }
 
   virtual function* toValueComp(static_context *) const { return NULL; }

=== modified file 'src/functions/func_collections_impl.cpp'
--- src/functions/func_collections_impl.cpp	2012-10-16 13:08:47 +0000
+++ src/functions/func_collections_impl.cpp	2012-10-24 11:34:21 +0000
@@ -25,6 +25,9 @@
 #include "compiler/expression/pragma.h"
 #include "compiler/api/compilercb.h"
 
+#include "zorbamisc/ns_consts.h"
+
+
 namespace zorba
 {
 

=== modified file 'src/functions/func_sequences_impl.cpp'
--- src/functions/func_sequences_impl.cpp	2012-10-15 13:35:59 +0000
+++ src/functions/func_sequences_impl.cpp	2012-10-24 11:34:21 +0000
@@ -32,6 +32,7 @@
 
 #include "compiler/expression/expr.h"
 #include "compiler/expression/fo_expr.h"
+#include "compiler/expression/var_expr.h"
 #include "compiler/expression/path_expr.h"
 
 #include "types/typeops.h"
@@ -43,6 +44,148 @@
 /*******************************************************************************
 
 ********************************************************************************/
+xqtref_t fn_unordered::getReturnType(const fo_expr* caller) const
+{
+  return caller->get_arg(0)->get_return_type();
+}
+
+
+BoolAnnotationValue fn_unordered::ignoresSortedNodes(expr* fo, csize input) const
+{
+  return ANNOTATION_TRUE;
+}
+
+
+BoolAnnotationValue fn_unordered::ignoresDuplicateNodes(expr* fo, csize input) const
+{
+  return fo->getIgnoresDuplicateNodes();
+}
+
+
+PlanIter_t fn_unordered::codegen(
+    CompilerCB* /*cb*/,
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& argv,
+    expr& ) const
+{
+  return argv[0];
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+xqtref_t fn_exactly_one_noraise::getReturnType(const fo_expr* caller) const
+{
+  TypeManager* tm = caller->get_type_manager();
+
+  xqtref_t srcType = caller->get_arg(0)->get_return_type();
+
+  if (theRaiseError)
+    return TypeOps::prime_type(tm, *srcType);
+  else
+    return function::getReturnType(caller);
+}
+
+
+PlanIter_t fn_exactly_one_noraise::codegen(
+    CompilerCB* aCb,
+    static_context* aSctx,
+    const QueryLoc& aLoc,
+    std::vector<PlanIter_t>& aArgs,
+    expr& aAnn) const
+{
+  return new FnExactlyOneIterator(aSctx,
+                                  aLoc,
+                                  aArgs,
+                                  theRaiseError,
+                                  testFlag(FunctionConsts::DoDistinct));
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+PlanIter_t fn_union::codegen(
+    CompilerCB* /*cb*/,
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& argv,
+    expr& ann) const
+{
+  return new FnConcatIterator(sctx, loc, argv);
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+BoolAnnotationValue fn_intersect::ignoresSortedNodes(expr* fo, csize input) const 
+{
+  if (input == 0)
+    return fo->getIgnoresSortedNodes();
+  
+  return ANNOTATION_TRUE;
+}
+
+
+BoolAnnotationValue fn_intersect::ignoresDuplicateNodes(expr* fo, csize input) const 
+{
+  if (input == 0)
+    return fo->getIgnoresDuplicateNodes();
+
+  return ANNOTATION_TRUE;
+}
+
+
+PlanIter_t fn_intersect::codegen(
+    CompilerCB* /*cb*/,
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& argv,
+    expr& ann) const
+{
+  return new HashSemiJoinIterator(sctx, loc, argv);
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
+BoolAnnotationValue fn_except::ignoresSortedNodes(expr* fo, csize input) const 
+{
+  if (input == 0)
+    return fo->getIgnoresSortedNodes();
+  
+  return ANNOTATION_TRUE;
+}
+
+
+BoolAnnotationValue fn_except::ignoresDuplicateNodes(expr* fo, csize input) const 
+{
+  if (input == 0)
+    return fo->getIgnoresDuplicateNodes();
+  
+  return ANNOTATION_TRUE;
+}
+
+
+PlanIter_t fn_except::codegen(
+    CompilerCB* /*cb*/,
+    static_context* sctx,
+    const QueryLoc& loc,
+    std::vector<PlanIter_t>& argv,
+    expr& ann) const
+{
+  // TODO: use SortAntiJoinIterator when available (trac ticket 254)
+  return new HashSemiJoinIterator(sctx, loc, argv, true);
+}
+
+
+/*******************************************************************************
+
+********************************************************************************/
 xqtref_t op_concatenate::getReturnType(const fo_expr* caller) const
 {
   TypeManager* tm = caller->get_type_manager();
@@ -608,32 +751,6 @@
 /*******************************************************************************
 
 ********************************************************************************/
-BoolAnnotationValue fn_unordered::ignoresSortedNodes(expr* fo, csize input) const
-{
-  return ANNOTATION_TRUE;
-}
-
-
-BoolAnnotationValue fn_unordered::ignoresDuplicateNodes(expr* fo, csize input) const
-{
-  return fo->getIgnoresDuplicateNodes();
-}
-
-
-PlanIter_t fn_unordered::codegen(
-    CompilerCB* /*cb*/,
-    static_context* sctx,
-    const QueryLoc& loc,
-    std::vector<PlanIter_t>& argv,
-    expr& ) const
-{
-  return argv[0];
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
 xqtref_t fn_zero_or_one::getReturnType(const fo_expr* caller) const
 {
   TypeManager* tm = caller->get_type_manager();
@@ -693,37 +810,6 @@
 /*******************************************************************************
 
 ********************************************************************************/
-xqtref_t fn_exactly_one_noraise::getReturnType(const fo_expr* caller) const
-{
-  TypeManager* tm = caller->get_type_manager();
-
-  xqtref_t srcType = caller->get_arg(0)->get_return_type();
-
-  if (theRaiseError)
-    return TypeOps::prime_type(tm, *srcType);
-  else
-    return function::getReturnType(caller);
-}
-
-
-PlanIter_t fn_exactly_one_noraise::codegen(
-    CompilerCB* aCb,
-    static_context* aSctx,
-    const QueryLoc& aLoc,
-    std::vector<PlanIter_t>& aArgs,
-    expr& aAnn) const
-{
-  return new FnExactlyOneIterator(aSctx,
-                                  aLoc,
-                                  aArgs,
-                                  theRaiseError,
-                                  testFlag(FunctionConsts::DoDistinct));
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
 bool fn_deep_equal::mustCopyInputNodes(expr* fo, csize producer) const
 {
   return (producer < 2 &&
@@ -734,60 +820,6 @@
 /*******************************************************************************
 
 ********************************************************************************/
-PlanIter_t fn_union::codegen(
-    CompilerCB* /*cb*/,
-    static_context* sctx,
-    const QueryLoc& loc,
-    std::vector<PlanIter_t>& argv,
-    expr& ann) const
-{
-  return new FnConcatIterator(sctx, loc, argv);
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
-PlanIter_t fn_intersect::codegen(
-    CompilerCB* /*cb*/,
-    static_context* sctx,
-    const QueryLoc& loc,
-    std::vector<PlanIter_t>& argv,
-    expr& ann) const
-{
-#if 0  // we can't access PRODUCES_* from the inputs, must rethink
-  bool distinct = ann.get_annotation (Annotations::IGNORES_DUP_NODES) != TSVAnnotationValue::TRUE_VAL;
-  bool sort = ann.get_annotation (Annotations::IGNORES_SORTED_NODES) != TSVAnnotationValue::TRUE_VAL;
-
-  std::vector<PlanIter_t> inputs;
-  for (std::vector<PlanIter_t>::iterator i = argv.begin ();
-       i != argv.end (); i++)
-    inputs.push_back (new NodeSortIterator (loc, *i, true, distinct, false));
-  return new SortSemiJoinIterator(loc, inputs);
-#endif
-
-  return new HashSemiJoinIterator(sctx, loc, argv);
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
-PlanIter_t fn_except::codegen(
-    CompilerCB* /*cb*/,
-    static_context* sctx,
-    const QueryLoc& loc,
-    std::vector<PlanIter_t>& argv,
-    expr& ann) const
-{
-  // TODO: use SortAntiJoinIterator when available (trac ticket 254)
-  return new HashSemiJoinIterator(sctx, loc, argv, true);
-}
-
-
-/*******************************************************************************
-
-********************************************************************************/
 BoolAnnotationValue fn_count::ignoresSortedNodes(expr* fo, csize input) const
 {
   return ANNOTATION_TRUE;

=== modified file 'src/functions/func_sequences_impl.h'
--- src/functions/func_sequences_impl.h	2012-09-19 21:16:15 +0000
+++ src/functions/func_sequences_impl.h	2012-10-24 11:34:21 +0000
@@ -21,9 +21,8 @@
 
 #include "functions/function_impl.h"
 
-#include "compiler/expression/fo_expr.h"
-
-namespace zorba {
+namespace zorba
+{
 
 void populate_context_sequences_impl(static_context* sctx);
 
@@ -40,10 +39,7 @@
   {
   }
 
-  xqtref_t getReturnType(const fo_expr* caller) const
-  {
-    return caller->get_arg(0)->get_return_type();
-  }
+  xqtref_t getReturnType(const fo_expr* caller) const;
 
   bool isMap(csize input) const
   {
@@ -206,21 +202,9 @@
     return producer == 0;
   }
 
-  BoolAnnotationValue ignoresSortedNodes(expr* fo, csize input) const 
-  {
-    if (input == 0)
-      return fo->getIgnoresSortedNodes();
-
-    return ANNOTATION_TRUE;
-  }
-
-  BoolAnnotationValue ignoresDuplicateNodes(expr* fo, csize input) const 
-  {
-    if (input == 0)
-      return fo->getIgnoresDuplicateNodes();
-
-    return ANNOTATION_TRUE;
-  }
+  BoolAnnotationValue ignoresSortedNodes(expr* fo, csize input) const; 
+
+  BoolAnnotationValue ignoresDuplicateNodes(expr* fo, csize input) const;
 
   bool propagatesInputNodes(expr* fo, csize input) const
   {
@@ -258,21 +242,9 @@
     return  producer == 0;
   }
 
-  BoolAnnotationValue ignoresSortedNodes(expr* fo, csize input) const 
-  {
-    if (input == 0)
-      return fo->getIgnoresSortedNodes();
-
-    return ANNOTATION_TRUE;
-  }
-
-  BoolAnnotationValue ignoresDuplicateNodes(expr* fo, csize input) const 
-  {
-    if (input == 0)
-      return fo->getIgnoresDuplicateNodes();
-
-    return ANNOTATION_TRUE;
-  }
+  BoolAnnotationValue ignoresSortedNodes(expr* fo, csize input) const;
+
+  BoolAnnotationValue ignoresDuplicateNodes(expr* fo, csize input) const;
 
   bool propagatesInputNodes(expr* fo, csize input) const
   {

=== modified file 'src/functions/function.h'
--- src/functions/function.h	2012-10-08 12:09:36 +0000
+++ src/functions/function.h	2012-10-24 11:34:21 +0000
@@ -145,6 +145,8 @@
       resetFlag(FunctionConsts::isPrivate);
   }
 
+  bool isComparisonFunction() const { return testFlag(FunctionConsts::IsComparison); }
+
   bool isDeterministic() const
   {
     // Note: For udfs, the flag is set before the udf is optimized (see call
@@ -201,8 +203,6 @@
     return ArithmeticConsts::UNKNOWN;
   }
 
-  virtual bool isComparisonFunction() const { return false; }
-
   virtual bool isValueComparisonFunction() const { return false; }
 
   virtual bool isGeneralComparisonFunction() const { return false; }

=== modified file 'src/functions/function_consts.h'
--- src/functions/function_consts.h	2012-10-20 21:29:37 +0000
+++ src/functions/function_consts.h	2012-10-24 11:34:21 +0000
@@ -271,7 +271,8 @@
   mustCopyInputNodes   = 128,
   AccessesDynCtx       = 256,
   ConstructsNodes      = 512,
-  DereferencesNodes    = 1024
+  DereferencesNodes    = 1024,
+  IsComparison         = 2048
 } AnnotationFlags;
 
 };

=== modified file 'src/functions/udf.h'
--- src/functions/udf.h	2012-10-20 21:29:37 +0000
+++ src/functions/udf.h	2012-10-24 11:34:21 +0000
@@ -19,12 +19,14 @@
 
 #include "functions/function.h"
 
-#include "compiler/expression/expr_base.h"
+//#include "compiler/expression/expr_base.h"
 
 
 namespace zorba
 {
 
+  class expr;
+
   namespace store
   {
     class Index;

=== modified file 'src/runtime/core/sequencetypes.cpp'
--- src/runtime/core/sequencetypes.cpp	2012-10-08 12:09:36 +0000
+++ src/runtime/core/sequencetypes.cpp	2012-10-24 11:34:21 +0000
@@ -355,7 +355,7 @@
     const QueryLoc& loc,
     PlanIter_t& child,
     const xqtref_t& promoteType,
-    ErrorKind err,
+    PromoteErrorKind err,
     store::Item_t qname)
   :
   UnaryBaseIterator<PromoteIterator, PlanIteratorState>(sctx, loc, child),
@@ -379,7 +379,7 @@
 
   ar & thePromoteType;
   SERIALIZE_ENUM(TypeConstants::quantifier_t, theQuantifier);
-  SERIALIZE_ENUM(ErrorKind, theErrorKind);
+  SERIALIZE_ENUM(PromoteErrorKind, theErrorKind);
   ar & theQName;
 }
 
@@ -463,7 +463,7 @@
 
   switch (theErrorKind)
   {
-  case FUNC_RETURN:
+  case PROMOTE_FUNC_RETURN:
   {
     assert(theQName != NULL);
 
@@ -472,7 +472,7 @@
                  valueType, targetType, theQName->getStringValue()));
     break;
   }
-  case FUNC_PARAM:
+  case PROMOTE_FUNC_PARAM:
   {
     assert(theQName != NULL);
 
@@ -481,26 +481,26 @@
                  valueType, targetType, theQName->getStringValue()));
     break;
   }
-  case TYPE_PROMOTION:
+  case PROMOTE_TYPE_PROMOTION:
   {
     RAISE_ERROR(err::XPTY0004, loc, 
     ERROR_PARAMS(ZED(XPTY0004_TypePromotion), valueType, targetType));
     break;
   }
 #ifdef ZORBA_WITH_JSON
-  case JSONIQ_ARRAY_SELECTOR:
+  case PROMOTE_JSONIQ_ARRAY_SELECTOR:
   {
     RAISE_ERROR(jerr::JNUP0007, loc,
     ERROR_PARAMS(ZED(JNUP0007_Array), valueType));
     break;
   }
-  case JSONIQ_OBJECT_SELECTOR:
+  case PROMOTE_JSONIQ_OBJECT_SELECTOR:
   {
     RAISE_ERROR(jerr::JNUP0007, loc,
     ERROR_PARAMS(ZED(JNUP0007_Object), valueType));
     break;
   }
-  case JSONIQ_SELECTOR:
+  case PROMOTE_JSONIQ_SELECTOR:
   {
     RAISE_ERROR(jerr::JNUP0007, loc,
     ERROR_PARAMS(ZED(JNUP0007_ObjectArray), valueType));
@@ -528,7 +528,7 @@
     PlanIter_t& child,
     const xqtref_t& treatType,
     bool checkPrime,
-    ErrorKind errorKind,
+    TreatErrorKind errorKind,
     store::Item_t qname)
   :
   UnaryBaseIterator<TreatIterator, PlanIteratorState>(sctx, loc, child),
@@ -549,7 +549,7 @@
   ar & theTreatType;
   SERIALIZE_ENUM(TypeConstants::quantifier_t, theQuantifier);
   ar & theCheckPrime;
-  SERIALIZE_ENUM(ErrorKind, theErrorKind);
+  SERIALIZE_ENUM(TreatErrorKind, theErrorKind);
   ar & theQName;
 }
 
@@ -665,7 +665,7 @@
 
   switch (theErrorKind)
   {
-  case FUNC_RETURN:
+  case TREAT_FUNC_RETURN:
   {
     assert(theQName != NULL);
 
@@ -674,7 +674,7 @@
                  valueType, targetType, theQName->getStringValue()));
     break;
   }
-  case FUNC_PARAM:
+  case TREAT_FUNC_PARAM:
   {
     assert(theQName != NULL);
 
@@ -683,7 +683,7 @@
                  valueType, targetType, theQName->getStringValue()));
     break;
   }
-  case TYPE_MATCH:
+  case TREAT_TYPE_MATCH:
   {
     RAISE_ERROR(err::XPTY0004, loc, 
     ERROR_PARAMS(ZED(XPTY0004_TypeMatch), valueType, targetType));
@@ -694,65 +694,65 @@
     RAISE_ERROR(err::XPDY0050, loc, ERROR_PARAMS(valueType, targetType));
     break;
   }
-  case INDEX_DOMAIN:
+  case TREAT_INDEX_DOMAIN:
   {
     RAISE_ERROR(zerr::ZDTY0010_INDEX_DOMAIN_TYPE_ERROR, loc,
     ERROR_PARAMS(theQName->getStringValue()));
     break;
   }
-  case INDEX_KEY:
+  case TREAT_INDEX_KEY:
   {
     RAISE_ERROR(zerr::ZDTY0011_INDEX_KEY_TYPE_ERROR, loc,
     ERROR_PARAMS(valueType, targetType, theQName->getStringValue()));
     break;
   }
-  case PATH_STEP:
+  case TREAT_PATH_STEP:
   {
     RAISE_ERROR_NO_PARAMS(err::XPTY0019, loc);
     break;
   }
-  case PATH_DOT:
+  case TREAT_PATH_DOT:
   {
     RAISE_ERROR_NO_PARAMS(err::XPTY0020, loc);
     break;
   }
-  case MULTI_VALUED_GROUPING_KEY:
+  case TREAT_MULTI_VALUED_GROUPING_KEY:
   {
     RAISE_ERROR(err::XPTY0004, loc,
     ERROR_PARAMS(ZED(XPTY0004_MultiValuedGroupingKey)));
     break;
   }
 #ifdef ZORBA_WITH_JSON
-  case JSONIQ_VALUE:
+  case TREAT_JSONIQ_VALUE:
   {
     RAISE_ERROR_NO_PARAMS(jerr::JNTY0002, loc);
     break;
   }
-  case JSONIQ_UPDATE_TARGET:
+  case TREAT_JSONIQ_UPDATE_TARGET:
   {
     RAISE_ERROR(jerr::JNUP0008, loc,
     ERROR_PARAMS(ZED(JNUP0008_ObjectArray), valueType));
     break;
   }
-  case JSONIQ_OBJECT_UPDATE_TARGET:
+  case TREAT_JSONIQ_OBJECT_UPDATE_TARGET:
   {
     RAISE_ERROR(jerr::JNUP0008, loc,
     ERROR_PARAMS(ZED(JNUP0008_Object), valueType));
     break;
   }
-  case JSONIQ_OBJECT_UPDATE_CONTENT:
+  case TREAT_JSONIQ_OBJECT_UPDATE_CONTENT:
   {
     RAISE_ERROR(jerr::JNUP0019, loc,
     ERROR_PARAMS(ZED(JNUP0019), valueType));
     break;
   }
-  case JSONIQ_ARRAY_UPDATE_TARGET:
+  case TREAT_JSONIQ_ARRAY_UPDATE_TARGET:
   {
     RAISE_ERROR(jerr::JNUP0008, loc,
     ERROR_PARAMS(ZED(JNUP0008_Array), valueType));
     break;
   }
-  case JSONIQ_OBJECT_UPDATE_VALUE:
+  case TREAT_JSONIQ_OBJECT_UPDATE_VALUE:
   {
     RAISE_ERROR_NO_PARAMS(jerr::JNUP0017, loc);
     break;

=== modified file 'src/runtime/core/sequencetypes.h'
--- src/runtime/core/sequencetypes.h	2012-10-08 12:09:36 +0000
+++ src/runtime/core/sequencetypes.h	2012-10-24 11:34:21 +0000
@@ -24,6 +24,8 @@
 
 #include "types/typeconstants.h"
 
+#include "compiler/expression/expr_consts.h"
+
 namespace zorba 
 {
 
@@ -143,21 +145,10 @@
 {
   friend class PrinterVisitor;
 
-public:
-  typedef enum
-  {
-    FUNC_RETURN,
-    FUNC_PARAM,
-    TYPE_PROMOTION,
-    JSONIQ_ARRAY_SELECTOR,
-    JSONIQ_OBJECT_SELECTOR,
-    JSONIQ_SELECTOR
-  } ErrorKind;
-
 private:
   xqtref_t                    thePromoteType;
   TypeConstants::quantifier_t theQuantifier;
-  ErrorKind                   theErrorKind;
+  PromoteErrorKind            theErrorKind;
   store::Item_t								theQName; 
 
 public:
@@ -173,7 +164,7 @@
       const QueryLoc& loc,
       PlanIter_t& child,
       const xqtref_t& promoteType,
-      ErrorKind err,
+      PromoteErrorKind err,
       store::Item_t qname = NULL);
 
   ~PromoteIterator();
@@ -202,31 +193,11 @@
 {
   friend class PrinterVisitor;
 
-public:
-  typedef enum
-  {
-    FUNC_RETURN,
-    FUNC_PARAM,
-    TYPE_MATCH,
-    TREAT_EXPR,
-    INDEX_DOMAIN,
-    INDEX_KEY,
-    PATH_STEP,
-    PATH_DOT,
-    MULTI_VALUED_GROUPING_KEY,
-    JSONIQ_VALUE,
-    JSONIQ_UPDATE_TARGET,
-    JSONIQ_OBJECT_UPDATE_TARGET,
-    JSONIQ_OBJECT_UPDATE_CONTENT,
-    JSONIQ_ARRAY_UPDATE_TARGET,
-    JSONIQ_OBJECT_UPDATE_VALUE
-  } ErrorKind;
-
 private:
   xqtref_t                    theTreatType;
   TypeConstants::quantifier_t theQuantifier;
   bool                        theCheckPrime;
-  ErrorKind                   theErrorKind;
+  TreatErrorKind              theErrorKind;
   store::Item_t								theQName;
 
 public:
@@ -243,7 +214,7 @@
       PlanIter_t& child,
       const xqtref_t& treatType,
       bool check_prime,
-      ErrorKind errorKind,
+      TreatErrorKind errorKind,
       store::Item_t qname);
 
   void accept(PlanIterVisitor& v) const;

=== modified file 'src/runtime/eval/eval.cpp'
--- src/runtime/eval/eval.cpp	2012-10-12 09:05:54 +0000
+++ src/runtime/eval/eval.cpp	2012-10-24 11:34:21 +0000
@@ -30,6 +30,7 @@
 #include "compiler/api/compilercb.h"
 #include "compiler/api/compiler_api.h"
 #include "compiler/expression/var_expr.h"
+#include "compiler/expression/expr_manager.h"
 
 #include "context/dynamic_context.h"
 #include "context/static_context.h"

=== modified file 'src/runtime/function_item/function_item.cpp'
--- src/runtime/function_item/function_item.cpp	2012-10-09 14:06:08 +0000
+++ src/runtime/function_item/function_item.cpp	2012-10-24 11:34:21 +0000
@@ -21,6 +21,7 @@
 
 #include "compiler/api/compilercb.h"
 #include "compiler/expression/function_item_expr.h"
+#include "compiler/expression/expr_manager.h"
 
 #include "functions/signature.h"
 #include "functions/udf.h"

=== modified file 'src/runtime/json/jsoniq_functions_impl.cpp'
--- src/runtime/json/jsoniq_functions_impl.cpp	2012-10-16 14:30:02 +0000
+++ src/runtime/json/jsoniq_functions_impl.cpp	2012-10-24 11:34:21 +0000
@@ -40,6 +40,7 @@
 #include "zorba/internal/diagnostic.h"
 
 #include "context/static_context.h"
+#include "context/namespace_context.h"
 
 #include "types/casting.h"
 #include "types/typeimpl.h"


Follow ups