/* Copyright (c) 1997-2015
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
   http://www.polymake.org

   This program is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version: http://www.gnu.org/licenses/gpl.txt.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
--------------------------------------------------------------------------------
*/

#ifndef POLYMAKE_PERL_WRAPPERS_H
#define POLYMAKE_PERL_WRAPPERS_H

/* The following classes are designed to be used in the files automatically generated by polymake.
   If you use them in the manually written code, you are doing it on your own risk!

   The changes in syntax and contents must be concerted with the corresponding routines
   in the package Polymake::Core::CPlusPlus
*/

namespace pm { namespace perl {

template <typename Given, typename Target>
class access {
public:
   typedef Target type;
   typedef Target return_type;
   typedef typename attrib<type>::minus_const value_type;

   static return_type get(const Value& v)
   {
      return static_cast<Target>(static_cast<Given>(v));
   }
};

template <typename Target>
class access<Target, Target> {
public:
   typedef Target type;
   typedef Target return_type;
   typedef typename attrib<type>::minus_const value_type;

   static return_type get(const Value& v)
   {
      return static_cast<Target>(v);
   }
};

template <>
class access<std::string, std::string> {
public:
   typedef std::string type;
   typedef std::string return_type;
   typedef std::string value_type;

   static return_type get(const Value& v)
   {
      std::string x;
      v.retrieve(x);
      return x;
   }
};

template <>
class access<const std::string, const std::string>
   : public access<std::string, std::string> {
public:
   typedef const std::string type;
};

template <typename Given>
class access<Given, std::string>
   : public access<std::string, std::string> {};

template <typename Given>
class access<Given, const std::string>
   : public access<const std::string, const std::string> {};

template <typename Target>
struct canned_may_be_missing : False {};

template <typename E, typename SharedParams>
struct canned_may_be_missing< pm::Array<E, SharedParams> > : True {};

// TODO: add a declaration for representative of HashMaps when CPlusPlus.pm learns to generate them for anonymous hash maps

template <typename Given, typename Target, bool _try_conv>
class access_canned<Given, Target, _try_conv, true> {
public:
   typedef Target type;
   typedef typename inherit_const<Target&, Given>::type return_type;
   typedef typename attrib<type>::minus_const value_type;
   typedef typename attrib<Given>::minus_const given_value_type;

   static return_type get(const Value& v)
   {
      const Value::canned_data_t canned=Value::get_canned_data(v.sv);
      const bool maybe_missing=_try_conv || canned_may_be_missing<typename attrib<Given>::minus_const>::value;

      if (!maybe_missing || canned.second) {
         if (identical<value_type, given_value_type>::value) {
            if (!_try_conv || *canned.first == typeid(value_type))
               return *reinterpret_cast<type*>(canned.second);
         } else {
            if (!_try_conv || *canned.first == typeid(given_value_type))
               return convert_input(v, canned, identical<value_type, given_value_type>());
         }

         if (wrapper_type conversion=type_cache<value_type>::get_conversion_constructor(v.sv)) {
            // It is a wrapper for new<T0>(T1), it expects the prototype at stack[0] and the argument at stack[1]
            SV* mini_stack[2]={ NULL, v.sv };
            if (SV* ret=conversion(mini_stack, reinterpret_cast<char*>(&mini_stack)))
               return *reinterpret_cast<value_type*>(Value::get_canned_data(ret).second);
            else
               throw exception();
         }
      }

      return parse_input(v, bool2type<maybe_missing>());
   }

private:
   static return_type parse_input(const Value& v, True)
   {
      Value temp_can;
      value_type* value=new(temp_can.allocate_canned(type_cache<value_type>::get_descr())) value_type;
      v >> *value;
      const_cast<Value&>(v).sv=temp_can.get_temp();
      return *value;
   }

   static return_type convert_input(const Value& v, const Value::canned_data_t& canned, False)
   {
      Value temp_can;
      value_type* value=new(temp_can.allocate_canned(type_cache<value_type>::get_descr())) value_type(*reinterpret_cast<Given*>(canned.second));
      const_cast<Value&>(v).sv=temp_can.get_temp();
      return *value;
   }

   static return_type parse_input(const Value& v, False)
   {
      // should never happen
      return *reinterpret_cast<value_type*>(0);
   }

   static return_type convert_input(const Value& v, const Value::canned_data_t& canned, True)
   {
      // should never happen
      return *reinterpret_cast<value_type*>(0);
   }
};

template <typename Target, bool _try_conv>
class access_canned<Target, Target, _try_conv, false> {
public:
   typedef typename inherit_const<typename Unwary<typename attrib<Target>::minus_const>::type, Target>::type type;
   typedef Target& return_type;
   typedef typename attrib<type>::minus_const value_type;

   static return_type get(const Value& v)
   {
      return wary(access_canned<type, type, _try_conv, true>::get(v));
   }
};

template <typename Given, typename Target, bool _try_conv>
class access_canned<Given, Target, _try_conv, false> {
public:
   typedef typename inherit_const<Target, Given>::type type;
   typedef typename inherit_const<Wary<Target>, Given>::type& return_type;
   typedef typename Unwary<typename attrib<Given>::minus_const>::type given_value_type;
   typedef typename inherit_const<given_value_type, Given>::type given_type;
   typedef typename attrib<type>::minus_const value_type;

   static return_type get(const Value& v)
   {
      return wary(access_canned<given_type, Target, _try_conv, true>::get(v));
   }
};

template <typename Given, typename Target>
class access<TryCanned<Given>, Target> : public access_canned<Given, Target, true> {};

template <typename Given, typename Target>
class access<Canned<Given>, Target> : public access_canned<Given, Target, false> {};

template <typename Given>
class access<TryCanned<Given>, TryCanned<Given> > : public access_canned<Given, Given, true> {};

template <typename Given>
class access<Canned<Given>, Canned<Given> > : public access_canned<Given, Given, false> {};

template <typename Target>
class access< Enum<Target>, Enum<Target> > {
public:
   typedef const Target type;
   typedef Target return_type;
   typedef Target value_type;

   static return_type get(const Value& v)
   {
      return Target(v.enum_value());
   }
};

class FunctionBase {
protected:
   static
   int register_func(wrapper_type wrapper, const char* sig, size_t siglen, const char* file, size_t filelen, int line,
                     SV* arg_types, SV* cross_apps, void* func_ptr=NULL, const char* func_ptr_type=NULL);

   static
   int register_func(wrapper_type wrapper, const char* sig, size_t siglen, const char* file, size_t filelen, int line,
                     SV* arg_types, int=0)
   {
      return register_func(wrapper, sig, siglen, file, filelen, line, arg_types, NULL, NULL, NULL);
   }

   static
   void add_rules(const char* file, int line, const char* text, ...);
};

class Function : protected FunctionBase {
public:
   template <typename Fptr, size_t filelen>
   Function(Fptr* fptr, const char (&file)[filelen], int line, const char* text)
   {
      const int i=register_func(&TypeListUtils<Fptr>::get_flags, NULL, 0, file, filelen-1, line,
                                TypeListUtils<Fptr>::get_types(), NULL, (void*)fptr, typeid(type2type<Fptr>).name());
      add_rules(file, line, text, i);
   }
};

template <typename Wrapper>
class WrapperBase : protected FunctionBase {
public:
   template <size_t namelen, size_t filelen> static
   void register_it(const char (&name)[namelen], const char (&file)[filelen], int line, const char* arg0)
   {
      register_func(&Wrapper::call, name, namelen-1, file, filelen-1, line,
                    TypeListUtils<typename Wrapper::arg_list>::get_types(arg0));
   }

   template <size_t namelen, size_t filelen, typename _app_list> static
   void register_it(const char (&name)[namelen], const char (&file)[filelen], int line, _app_list cross_apps)
   {
      register_func(&Wrapper::call, name, namelen-1, file, filelen-1, line,
                    TypeListUtils<typename Wrapper::arg_list>::get_types(), cross_apps);
   }
};

template <typename T, bool _enable=!(has_trivial_destructor<T>::value || is_masquerade<T>::value)>
class Destroy {
   static void _do(T* dst)
   {
      dst->~T();
   }
public:
   static destructor_type func() { return reinterpret_cast<destructor_type>(&_do); }
};

template <typename T>
class Destroy<T, false> {
public:
   static destructor_type func() { return 0; }
};

template <typename T, bool _enable=(identical<T,typename object_traits<T>::persistent_type>::value && is_mutable<T>::value && !is_masquerade<T>::value)>
class Copy {
   static void construct(void* place, const T* src)
   {
      new(place) T(*src);
   }
public:
   static copy_constructor_type func() { return reinterpret_cast<copy_constructor_type>(&construct); }
};

template <typename T>
class Copy<T, false> {
public:
   static copy_constructor_type func() { return NULL; }
};

template <typename T>
struct assign_helper {
   static const bool value=is_mutable<T>::value && is_parseable_or_serializable<T>::value;
};

template <typename Base, typename E, typename Params>
struct assign_helper< sparse_elem_proxy<Base, E, Params> > : assign_helper<E> {};

template <>
struct assign_helper<Value> : False {};

template <typename T, bool _enable=assign_helper<T>::value>
class Assign {
protected:
   static void assign(T* dst, SV* sv, value_flags flags)
   {
      Value src(sv, flags);
      src >> *dst;
   }
public:
   static assignment_type func() { return reinterpret_cast<assignment_type>(&assign); }
};

template <typename Base, typename E, typename Params>
class Assign<sparse_elem_proxy<Base, E, Params>, true>
   : protected Assign<E> {
protected:
   static void assign(sparse_elem_proxy<Base, E, Params>* dst, SV* sv, value_flags flags)
   {
      E x;
      Assign<E>::assign(&x, sv, flags);
      *dst = x;
   }
public:
   static assignment_type func() { return reinterpret_cast<assignment_type>(&assign); }
};

template <typename T>
class Assign<T, false> {
public:
   static assignment_type func() { return NULL; }
};


template <typename T>
struct to_string_helper : is_printable<T> {};

template <typename Base, typename E, typename Params>
struct to_string_helper< sparse_elem_proxy<Base, E, Params> > : to_string_helper<E> {};

template <typename T, bool _enable=to_string_helper<T>::value>
class ToString {
protected:
   static SV* _to_string(const T& src)
   {
      Value ret;
      ostream my_stream(ret);
      PlainPrinter<> printer(my_stream);
      printer << src;
      return ret.get_temp();
   }
   static SV* to_string(const T* src) { return _to_string(*src); }
public:
   static conv_to_SV_type func() { return reinterpret_cast<conv_to_SV_type>(&to_string); }
};

template <typename Base, typename E, typename Params>
class ToString<sparse_elem_proxy<Base, E, Params>, true>
   : protected ToString<E> {
protected:
   static SV* to_string(const sparse_elem_proxy<Base, E, Params>* src)
   {
      return ToString<E>::_to_string(src->get());
   }
public:
   static conv_to_SV_type func() { return reinterpret_cast<conv_to_SV_type>(&to_string); }
};

class Unprintable {
protected:
   static SV* to_string(const char*, const char*);
public:
   static conv_to_SV_type func() { return &to_string; }
};

template <typename T>
class ToString<T, false> : public Unprintable {};

template <typename T>
struct serializable_helper : has_serialized<T> {};

template <typename Base, typename E, typename Params>
struct serializable_helper< sparse_elem_proxy<Base, E, Params> > : has_serialized<E> {};

template <typename T, bool _enable=serializable_helper<T>::value>
class Serializable {
protected:
   static SV* _conv(const T* src, const char* frame_upper_bound)
   {
      Value ret(value_flags(value_allow_non_persistent | value_read_only));
      ret.put(serialize(*src), frame_upper_bound, 0);
      return ret.get_temp();
   }
public:
   static const class_kind flag_value=class_is_serializable;
   static conv_to_SV_type conv() { return reinterpret_cast<conv_to_SV_type>(&_conv); }
   static provide_type provide() { return &type_cache< Serialized<T> >::provide; }
};

template <typename Base, typename E, typename Params>
class Serializable<sparse_elem_proxy<Base, E, Params>, true>
   : public Serializable<E> {
protected:
   static SV* _conv(const sparse_elem_proxy<Base, E, Params>* src, const char* frame_upper_bound)
   {
      return Serializable<E>::_conv(&serialize(src->get()), frame_upper_bound);
   }

public:
   static conv_to_SV_type conv() { return reinterpret_cast<conv_to_SV_type>(&_conv); }
};

template <typename T>
class Serializable<T, false> {
public:
   static const class_kind flag_value=class_kind(0);
   static conv_to_SV_type conv() { return NULL; }
   static provide_type provide() { return NULL; }
};

template <typename Base, typename E, typename Params>
class Serializable<sparse_elem_proxy<Base, E, Params>, false>
   : public Serializable<E> {
protected:
   static SV* _conv(const sparse_elem_proxy<Base, E, Params>* src, const char*)
   {
      Value ret;
      ret << src->get();
      return ret.get_temp();
   }

public:
   static conv_to_SV_type conv() { return reinterpret_cast<conv_to_SV_type>(&_conv); }
};

class ClassRegistratorBase {
protected:
   static
   SV* register_class(const char* name, size_t namelen, const char* file, size_t filelen, int line,
                      SV* someref,
                      const char* typeid_name, const char* const_typeid_name,
                      bool is_mutable, class_kind kind,
                      SV* vtbl_sv);

   static
   SV* create_builtin_vtbl(
      const std::type_info& type,
      size_t obj_size,
      int primitive_lvalue,
      copy_constructor_type copy_constructor,
      assignment_type assignment,
      destructor_type destructor
   );

   static
   SV* create_scalar_vtbl(
      const std::type_info& type,
      size_t obj_size,
      copy_constructor_type copy_constructor,
      assignment_type assignment,
      destructor_type destructor,
      conv_to_SV_type to_string,
      conv_to_SV_type to_serialized,
      provide_type provide_serialized_type,
      conv_to_int_type to_int,
      conv_to_double_type to_double
   );

   static
   SV* create_iterator_vtbl(
      const std::type_info& type,
      size_t obj_size,
      copy_constructor_type copy_constructor,
      destructor_type destructor,
      iterator_deref_type deref,
      iterator_incr_type incr,
      conv_to_int_type at_end
   );

   static
   SV* create_opaque_vtbl(
      const std::type_info& type,
      size_t obj_size,
      copy_constructor_type copy_constructor,
      assignment_type assignment,
      destructor_type destructor,
      conv_to_SV_type to_string,
      conv_to_SV_type to_serialized,
      provide_type provide_serialized_type
   );

   static
   SV* create_container_vtbl(
      const std::type_info& type,
      size_t obj_size, int total_dimension, int own_dimension,
      copy_constructor_type copy_constructor,
      assignment_type assignment,
      destructor_type destructor,
      conv_to_SV_type to_string,
      conv_to_SV_type to_serialized,
      provide_type provide_serialized_type,
      conv_to_int_type size,
      container_resize_type resize,
      container_store_type store_at_ref,
      provide_type provide_key_type,
      provide_type provide_value_type
   );

   static
   void fill_iterator_access_vtbl(
      SV* vtbl, int i,
      size_t it_size, size_t cit_size,
      destructor_type it_destructor,
      destructor_type cit_destructor,
      container_begin_type begin,
      container_begin_type cbegin,
      container_access_type deref,
      container_access_type cderef
   );

   static
   void fill_random_access_vtbl(
      SV* vtbl,
      container_access_type random,
      container_access_type crandom
   );

   static
   SV* create_composite_vtbl(
      const std::type_info& type,
      size_t obj_size, int obj_dimension,
      copy_constructor_type copy_constructor,
      assignment_type assignment,
      destructor_type destructor,
      conv_to_SV_type to_string,
      conv_to_SV_type to_serialized,
      provide_type provide_serialized_type,
      int n_elems,
      provide_type provide_elem_types,
      provide_type provide_field_names,
      void (*fill)(composite_access_vtbl*)
   );
};

template <typename T>
class Builtin : protected ClassRegistratorBase {
public:
   static
   SV* register_it(const char* name, size_t namelen, const char* file=NULL, size_t filelen=0, int line=0)
   {
      const char* const typeid_name=typeid(T).name();
      return register_class(
         name, namelen, file, filelen, line,
         NULL,
         typeid_name, typeid_name,
         false, class_is_scalar,
         create_builtin_vtbl(
            typeid(T), sizeof(T), list_contains<primitive_lvalues,T>::value,
            Copy<T>::func(),
            Assign<T>::func(),
            Destroy<T>::func()
         )
      );
   }

   template <size_t namelen, size_t filelen>
   Builtin(const char (&name)[namelen], const char (&file)[filelen], int line)
   {
      register_it(name, namelen-1, file, filelen-1, line);
   }
};

template <typename T, typename Model=typename object_traits<T>::model>
class ClassRegistrator;

template <>
class ClassRegistrator<Scalar,is_opaque> {};
template <>
class ClassRegistrator<Array,is_container> {};

template <typename T>
class ClassRegistrator<T, is_scalar> : protected ClassRegistratorBase {
protected:
   template <typename Target>
   struct do_conv {
      static Target func(const T* obj)
      {
         conv<T,Target> c;
         return c(*obj);
      }
   };

public:
   static SV* register_it(const char* name, size_t namelen, SV* someref, const char* file=NULL, size_t filelen=0, int line=0)
   {
      return register_class(
         name, namelen, file, filelen, line, someref,
         typeid(T).name(), typeid(typename const_equivalent<T>::type).name(),
         is_mutable<T>::value,
         class_kind(class_is_scalar | Serializable<T>::flag_value),
         create_scalar_vtbl(
            typeid(T), sizeof(T),
            Copy<T>::func(),
            Assign<T>::func(),
            Destroy<T>::func(),
            ToString<T>::func(),
            Serializable<T>::conv(),
            Serializable<T>::provide(),
            reinterpret_cast<conv_to_int_type>(&do_conv<int>::func),
            reinterpret_cast<conv_to_double_type>(&do_conv<double>::func)
         )
      );
   }
};

template <typename T, bool _is_iterator=check_iterator_feature<T,end_sensitive>::value>
class OpaqueClassRegistrator : protected ClassRegistratorBase {
public:
   static SV* register_it(const char* name, size_t namelen, SV* someref, const char* file=NULL, size_t filelen=0, int line=0)
   {
      return register_class(
         name, namelen, file, filelen, line, someref,
         typeid(T).name(), typeid(typename const_equivalent<T>::type).name(),
         is_mutable<T>::value,
         class_kind(class_is_opaque | Serializable<T>::flag_value),
         create_opaque_vtbl(
            typeid(T), sizeof(T),
            Copy<T>::func(),
            Assign<T>::func(),
            Destroy<T>::func(),
            ToString<T>::func(),
            Serializable<T>::conv(),
            Serializable<T>::provide()
         )
      );
   }
};

template <typename T>
class OpaqueClassRegistrator<T, true> : protected ClassRegistratorBase {
protected:
   static const bool read_only=attrib<typename iterator_traits<T>::reference>::is_const;

   static SV* deref(const T* it, const char* frame_upper_bound)
   {
      Value ret(value_flags(read_only ? value_expect_lval | value_allow_non_persistent | value_read_only
                                      : value_expect_lval | value_allow_non_persistent));
      ret.put_lval(**it, frame_upper_bound, 0, 0, (char*)0);
      return ret.get_temp();
   }

   static void incr(T* it)
   {
      ++(*it);
   }

   static int at_end(const T* it)
   {
      return it->at_end();
   }
public:
   static SV* register_it(const char* name, size_t namelen, SV* someref, const char* file=NULL, size_t filelen=0, int line=0)
   {
      return register_class(
         name, namelen, file, filelen, line, someref,
         typeid(T).name(), typeid(T).name(),
         true,
         class_is_opaque,
         create_iterator_vtbl(
            typeid(T), sizeof(T),
            Copy<T>::func(),
            Destroy<T>::func(),
            reinterpret_cast<iterator_deref_type>(&deref),
            reinterpret_cast<iterator_incr_type>(&incr),
            reinterpret_cast<conv_to_int_type>(&at_end)
         )
      );
   }
};

template <typename T>
class ClassRegistrator<T, is_opaque>
   : public OpaqueClassRegistrator<T> {};

template <typename T, bool _enabled=true, bool _is_mutable=!object_traits<T>::is_always_const>
struct input_mode : io_test::input_mode<T,false> {};

template <typename T, bool _is_mutable>
struct input_mode<T,false,_is_mutable> {
   typedef False type;
};

template <typename T, bool _enabled>
struct input_mode<T,_enabled,false> {
   typedef False type;
};

template <typename T, int _dim=object_traits<T>::dimension>
struct container_helper;

template <typename T>
struct container_helper<T, 1> {
   typedef T type;
   static type& streamline(T& x) { return x; }
   static const type& streamline(const T& x) { return x; }
};

template <typename T>
struct container_helper<T, 2> {
   typedef Rows<T> type;
   static type& streamline(T& x) { return rows(x); }
   static const type& streamline(const T& x) { return rows(x); }
};

template <typename T, typename Category=typename container_traits<typename container_helper<T>::type>::category,
          bool _obscure=obscure_type<T>::value>
class ContainerClassRegistrator : protected ClassRegistratorBase {
public:
   typedef container_helper<T> helper;
   typedef typename helper::type Obj;
   static const bool
        is_associative=is_assoc_container<Obj>::value,
             is_sparse=check_container_feature<Obj,sparse>::value,
      is_sparse_native=check_container_feature<T,sparse>::value ||
                       io_test::unknown_columns<T>::value==0,   // enforce the cols= attribute in XML representation
              like_set=list_contains< list(is_set, is_unordered_set), typename object_traits<Obj>::generic_tag>::value;
   typedef typename if_else<is_associative, end_sensitive, void>::type iterator_feature;
   typedef typename ensure_features<Obj, iterator_feature>::iterator iterator;
   typedef typename ensure_features<Obj, iterator_feature>::const_iterator const_iterator;

   static const bool allow_non_const_access= !object_traits<T>::is_always_const &&
                                             !identical<iterator,const_iterator>::value &&
                                             !attrib<typename iterator_traits<iterator>::reference>::is_const &&
                                             !object_traits<typename iterator_traits<iterator>::value_type>::is_always_const;

   typedef bool2type<allow_non_const_access> non_const_access;
protected:
   static int do_size(const T* obj)
   {
      return helper::streamline(*obj).size();
   }

   static int dim(const T* obj)
   {
      return helper::streamline(*obj).dim();
   }

   static void _resize(T* obj, int n)
   {
      helper::streamline(*obj).resize(n);
   }

   static void fixed_size(T* obj, int n)
   {
      if (get_dim(helper::streamline(*obj)) != n)
         throw std::runtime_error("size mismatch");
   }

   static void clear_by_resize(T* obj, int)
   {
      helper::streamline(*obj).clear();
   }

   template <typename E>
   static void check_insertion(const Obj&, const E&, False) {}

   static void check_insertion(const Obj& obj, int x, True)
   {
      if (x<0 || x>=obj.dim())
         throw std::runtime_error("element out of range");
   }

   static void push_back(T* obj, iterator* it, int, SV* src)
   {
      typename Obj::value_type x;
      Value v(src);
      v >> x;
      check_insertion(helper::streamline(*obj), x,
                      bool2type<check_container_feature<Obj,sparse_compatible>::value>());
      helper::streamline(*obj).insert(*it, x);
   }

   static void insert(T* obj, iterator*, int, SV* src)
   {
      typedef typename item4insertion<typename Obj::value_type>::type item_type;
      item_type x=item_type();
      Value v(src);
      v >> x;
      check_insertion(helper::streamline(*obj), x,
                      bool2type<check_container_feature<Obj,sparse_compatible>::value>());
      helper::streamline(*obj).insert(x);
   }

   static void store_dense(T*, iterator* it, int, SV* src)
   {
      Value v(src, value_not_trusted);
      v >> non_const(**it);
      ++(*it);
   }

   static void store_sparse(T* obj, iterator* it, int index, SV* src)
   {
      Value v(src, value_not_trusted);
      typename Obj::value_type x;
      v >> x;
      if (!is_zero(x)) {
         if (!it->at_end() && it->index()==index) {
            **it=x; ++(*it);
         } else {
            helper::streamline(*obj).insert(*it,index,x);
         }
      } else {
         if (!it->at_end() && it->index()==index)
            helper::streamline(*obj).erase((*it)++);
      }
   }

   template <typename Iterator, bool non_const>
   struct do_it {
      typedef typename assign_const<T, !non_const>::type* ObjPtr;

      static void begin(void* it_place, ObjPtr obj)
      {
         new(it_place) Iterator(ensure(helper::streamline(*obj), (iterator_feature*)0).begin());
      }

      static void rbegin(void* it_place, ObjPtr obj)
      {
         new(it_place) Iterator(ensure(helper::streamline(*obj), (iterator_feature*)0).rbegin());
      }

      static void deref(ObjPtr, Iterator* it, int, SV* dst, SV* container_sv, const char* frame_upper_bound)
      {
         Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent | (non_const ? 0 : value_read_only)), 1);
         pv.put_lval(**it, frame_upper_bound, 0, 0, (nothing*)0)->store_anchor(container_sv);
         ++(*it);
      }

      static void deref_pair(ObjPtr, Iterator* it, int i, SV* dst, SV* container_sv, const char* frame_upper_bound)
      {
         if (i<=0) {
            // i==-1: FIRSTKEY;  i==0: NEXTKEY
            if (i==0) ++(*it);
            if (!it->at_end()) {
               Value pv(dst, value_flags(value_read_only | value_allow_non_persistent), 1);
               pv.put((*it)->first, frame_upper_bound, 0)->store_anchor(container_sv);
            }
         } else {
            // i==1: fetch value
            Value pv(dst, value_flags(value_allow_non_persistent | (non_const ? 0 : value_read_only)), 1);
            pv.put((*it)->second, frame_upper_bound, 0)->store_anchor(container_sv);
         }
      }
   };

   template <typename Iterator>
   struct do_sparse {
      static void deref(T* obj, Iterator* it, int index, SV* dst, SV* container_sv, const char*)
      {
         Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent), 1);
         sparse_elem_proxy< sparse_proxy_it_base<Obj,Iterator>, typename Obj::value_type, typename Obj::reference::parameters >
            x(sparse_proxy_it_base<Obj,Iterator>(helper::streamline(*obj), *it, index));
         if (x.exists()) ++(*it);
         pv.put(x, 0, 0)->store_anchor(container_sv);
      }
   };

   template <typename Iterator>
   struct do_const_sparse {
      static void deref(const T*, Iterator* it, int index, SV* dst, SV* container_sv, const char* frame_upper_bound)
      {
         Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent | value_read_only), 1);
         if (!it->at_end() && index==it->index()) {
            pv.put_lval(**it, frame_upper_bound, 0, 0, (nothing*)0)->store_anchor(container_sv);
            ++(*it);
         } else {
            pv.put_lval(zero_value<typename Obj::value_type>(), frame_upper_bound, 0, 0, (nothing*)0);
         }
      }
   };

   static conv_to_int_type size(False) { return reinterpret_cast<conv_to_int_type>(&do_size); }
   static conv_to_int_type size(True)  { return reinterpret_cast<conv_to_int_type>(&dim); }

   static container_resize_type resize(io_test::as_list<Obj>)
   {
      return reinterpret_cast<container_resize_type>(&clear_by_resize);
   }
   static container_resize_type resize(io_test::as_set)
   {
      return reinterpret_cast<container_resize_type>(&clear_by_resize);
   }
   template <bool _allow_sparse>
   static container_resize_type resize(io_test::as_array<1,_allow_sparse>)
   {
      return reinterpret_cast<container_resize_type>(&_resize);
   }
   template <bool _allow_sparse>
   static container_resize_type resize(io_test::as_array<0,_allow_sparse>)
   {
      return reinterpret_cast<container_resize_type>(&fixed_size);
   }
   static container_resize_type resize(io_test::as_sparse<-1>) { return NULL; }
   static container_resize_type resize(False) { return NULL; }

   static container_store_type store_at_ref(io_test::as_list<Obj>)
   {
      return reinterpret_cast<container_store_type>(&push_back);
   }
   static container_store_type store_at_ref(io_test::as_set)
   {
      return reinterpret_cast<container_store_type>(&insert);
   }
   template <int _resizeable, bool _allow_sparse>
   static container_store_type store_at_ref(io_test::as_array<_resizeable, _allow_sparse>)
   {
      return reinterpret_cast<container_store_type>(&store_dense);
   }
   template <int _resizeable>
   static container_store_type store_at_ref(io_test::as_sparse<_resizeable>)
   {
      return reinterpret_cast<container_store_type>(&store_sparse);
   }
   static container_store_type store_at_ref(False) { return NULL; }

   static destructor_type it_destructor(True) { return Destroy<iterator>::func(); }
   static destructor_type it_destructor(False) { return Destroy<const_iterator>::func(); }

   static container_begin_type begin(True)
   {
      return reinterpret_cast<container_begin_type>(&do_it<iterator, true>::begin);
   }
   static container_begin_type begin(False)
   {
      return reinterpret_cast<container_begin_type>(&do_it<const_iterator, false>::begin);
   }

   static container_access_type deref(False,False,True)
   {
      return reinterpret_cast<container_access_type>(&do_it<iterator, true>::deref);
   }
   static container_access_type deref(False,False,False)
   {
      return reinterpret_cast<container_access_type>(&do_it<const_iterator, false>::deref);
   }
   static container_access_type deref(True,False,True)
   {
      return reinterpret_cast<container_access_type>(&do_it<iterator, true>::deref_pair);
   }
   static container_access_type deref(True,False,False)
   {
      return reinterpret_cast<container_access_type>(&do_it<const_iterator, false>::deref_pair);
   }
   static container_access_type deref(False,True,True)
   {
      return reinterpret_cast<container_access_type>(&do_sparse<iterator>::deref);
   }
   static container_access_type deref(False,True,False)
   {
      return reinterpret_cast<container_access_type>(&do_const_sparse<const_iterator>::deref);
   }

   static provide_type provide_key_type(True)
   {
      return &type_cache<typename T::key_type>::provide;
   }
   static provide_type provide_key_type(False)
   {
      return &type_cache<typename object_traits<typename T::value_type>::persistent_type>::provide;
   }
   static provide_type provide_value_type(True)
   {
      return &type_cache<typename T::mapped_type>::provide;
   }
   static provide_type provide_value_type(False)
   {
      return &type_cache<typename object_traits<typename Obj::value_type>::persistent_type>::provide;
   }

   static SV* create_vtbl()
   {
      SV* vtbl=create_container_vtbl(
         typeid(T), sizeof(T),
         object_traits<T>::total_dimension, object_traits<T>::dimension,
         Copy<T>::func(),
         Assign<T>::func(),
         Destroy<T>::func(),
         ToString<T>::func(),
         Serializable<T>::conv(),
         Serializable<T>::provide(),
         size(bool2type<is_sparse>()),
         resize(typename input_mode<Obj>::type()),
         store_at_ref(typename input_mode<Obj, !is_associative>::type()),
         provide_key_type(bool2type<is_associative>()),
         provide_value_type(bool2type<is_associative>())
      );
      fill_iterator_access_vtbl(
         vtbl, 0,
         sizeof(iterator), sizeof(const_iterator),
         it_destructor(non_const_access()),
         it_destructor(False()),
         begin(non_const_access()),
         begin(False()),
         deref(bool2type<is_associative>(), bool2type<is_sparse>(), non_const_access()),
         deref(bool2type<is_associative>(), bool2type<is_sparse>(), False())
      );
      return vtbl;
   }

   static SV* register_me(const char* name, size_t namelen, const char* file, size_t filelen, int line, SV* someref, SV* vtbl)
   {
      return register_class(
         name, namelen, file, filelen, line, someref,
         typeid(T).name(), typeid(typename const_equivalent<T>::type).name(),
         is_mutable<T>::value,
         class_kind(class_is_container | Serializable<T>::flag_value |
                    (is_associative   ? class_is_assoc_container :
                     is_sparse_native ? class_is_sparse_container :
                     like_set         ? class_is_set : 0)),
         vtbl);
   }

public:
   static SV* register_it(const char* name, size_t namelen, SV* someref, const char* file=NULL, size_t filelen=0, int line=0)
   {
      return register_me(name, namelen, file, filelen, line, someref, create_vtbl());
   }
};

template <typename T>
class ContainerClassRegistrator<T, bidirectional_iterator_tag, false>
   : public ContainerClassRegistrator<T, forward_iterator_tag, false> {
   typedef ContainerClassRegistrator<T, forward_iterator_tag, false> super;
public:
   typedef typename super::Obj::reverse_iterator reverse_iterator;
   typedef typename super::Obj::const_reverse_iterator const_reverse_iterator;
protected:
   static container_begin_type rbegin(True)
   {
      return reinterpret_cast<container_begin_type>(&super::template do_it<reverse_iterator, true>::rbegin);
   }
   static container_begin_type rbegin(False)
   {
      return reinterpret_cast<container_begin_type>(&super::template do_it<const_reverse_iterator, false>::rbegin);
   }

   static container_access_type rderef(False,True)
   {
      return reinterpret_cast<container_access_type>(&super::template do_it<reverse_iterator, true>::deref);
   }
   static container_access_type rderef(False,False)
   {
      return reinterpret_cast<container_access_type>(&super::template do_it<const_reverse_iterator, false>::deref);
   }
   static container_access_type rderef(True,True)
   {
      return reinterpret_cast<container_access_type>(&super::template do_sparse<reverse_iterator>::deref);
   }
   static container_access_type rderef(True,False)
   {
      return reinterpret_cast<container_access_type>(&super::template do_const_sparse<const_reverse_iterator>::deref);
   }

   static destructor_type rit_destructor(True) { return Destroy<reverse_iterator>::func(); }
   static destructor_type rit_destructor(False) { return Destroy<const_reverse_iterator>::func(); }
public:
   static SV* create_vtbl(False)
   {
      SV* vtbl=super::create_vtbl();
      super::fill_iterator_access_vtbl(
         vtbl, 2,
         sizeof(reverse_iterator), sizeof(const_reverse_iterator),
         rit_destructor(typename super::non_const_access()),
         rit_destructor(False()),
         rbegin(typename super::non_const_access()),
         rbegin(False()),
         rderef(bool2type<super::is_sparse>(), typename super::non_const_access()),
         rderef(bool2type<super::is_sparse>(), False())
      );
      return vtbl;
   }

   static SV* create_vtbl(True)
   {
      return super::create_vtbl();
   }
   static SV* create_vtbl()
   {
      return create_vtbl(bool2type<super::is_associative>());
   }
public:
   static SV* register_it(const char* name, size_t namelen, SV* someref, const char* file=NULL, size_t filelen=0, int line=0)
   {
      return super::register_me(name, namelen, file, filelen, line, someref, create_vtbl());
   }
};

template <typename T>
class ContainerClassRegistrator<T, random_access_iterator_tag, false>
   : public ContainerClassRegistrator<T, bidirectional_iterator_tag, false> {
   typedef ContainerClassRegistrator<T, bidirectional_iterator_tag, false> super;
protected:
   static void _random(T* obj, char*, int index, SV* dst, SV* container_sv, const char* frame_upper_bound)
   {
      index=index_within_range(super::helper::streamline(*obj), index);
      Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent), 1);
      pv.put_lval(super::helper::streamline(*obj)[index], frame_upper_bound, 0, 0, (nothing*)0)->store_anchor(container_sv);
   }

   static void crandom(const T* obj, char*, int index, SV* dst, SV* container_sv, const char* frame_upper_bound)
   {
      index=index_within_range(super::helper::streamline(*obj), index);
      Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent | value_read_only), 1);
      pv.put_lval(super::helper::streamline(*obj)[index], frame_upper_bound, 0, 0, (nothing*)0)->store_anchor(container_sv);
   }

   static void random_sparse(T* obj, char*, int index, SV* dst, SV* container_sv, const char*)
   {
      index=index_within_range(super::helper::streamline(*obj), index);
      Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent), 1);
      pv.put(super::helper::streamline(*obj)[index], 0, 0)->store_anchor(container_sv);
   }

   static container_access_type random(False, True)
   {
      return reinterpret_cast<container_access_type>(&_random);
   }
   static container_access_type random(True, True)
   {
      return reinterpret_cast<container_access_type>(&random_sparse);
   }
   template <typename _is_sparse>
   static container_access_type random(_is_sparse, False)
   {
      return reinterpret_cast<container_access_type>(&crandom);
   }
public:
   static SV* register_it(const char* name, size_t namelen, SV* someref, const char* file=NULL, size_t filelen=0, int line=0)
   {
      SV* vtbl=super::create_vtbl();
      super::fill_random_access_vtbl(
         vtbl,
         random(bool2type<super::is_sparse>(), typename super::non_const_access()),
         random(bool2type<super::is_sparse>(), False())
      );
      return super::register_me(name, namelen, file, filelen, line, someref, vtbl);
   }
};

template <typename T, typename Category>
class ContainerClassRegistrator<T, Category, true> : protected ClassRegistratorBase {
public:
   static SV* register_it(const char* name, size_t namelen, SV* someref, const char* file=NULL, size_t filelen=0, int line=0)
   {
      return register_class(
         name, namelen, file, filelen, line, someref,
         typeid(T).name(), typeid(T).name(),
         false, class_is_opaque,
         create_builtin_vtbl(
            typeid(T), sizeof(T),
            0, 0, 0, Destroy<T>::func()
         )
      );
   }
};

template <typename T>
class ClassRegistrator<T, is_container>
   : public ContainerClassRegistrator<T> {};

template <typename T, int n=0, int l=list_length<typename object_traits<T>::elements>::value>
struct CompositeClassRegistrator {
   typedef typename n_th<typename object_traits<T>::elements, n>::type member_type;
   static const bool allow_non_const_access = !attrib<member_type>::is_const &&
                                              !object_traits<typename deref<member_type>::type>::is_always_const;

   static void _get(T* obj, SV* dst, SV* container_sv, const char* frame_upper_bound)
   {
      Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent), 1);
      pv.put_lval(visit_n_th(*obj, int2type<n>()), frame_upper_bound, 0, 0, (nothing*)0)->store_anchor(container_sv);
   }

   static void cget(const T* obj, SV* dst, SV* container_sv, const char* frame_upper_bound)
   {
      Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent | value_read_only), 1);
      pv.put_lval(visit_n_th(*obj, int2type<n>()), frame_upper_bound, 0, 0, (nothing*)0)->store_anchor(container_sv);
   }

   static void _store(T* obj, SV* src)
   {
      Value v(src, value_not_trusted);
      v >> visit_n_th(*obj, int2type<n>());
   }

   static composite_access_type get(True)  { return reinterpret_cast<composite_access_type>(&_get); }
   static composite_access_type get(False) { return reinterpret_cast<composite_access_type>(&cget); }
   static composite_store_type store(True)  { return reinterpret_cast<composite_store_type>(&_store); }
   static composite_store_type store(False) { return NULL; }

   static void init(composite_access_vtbl* acct)
   {
      acct->get[0]=get(bool2type<allow_non_const_access>());
      acct->get[1]=get(False());
      acct->store=store(bool2type<allow_non_const_access>());
      CompositeClassRegistrator<T,n+1,l>::init(++acct);
   }

   static SV* provide_field_names() { return field_names(recognizer_bait(0), (T*)0); }
};

template <typename T, int l>
struct CompositeClassRegistrator<T,l,l> {
   static void init(composite_access_vtbl*) {}
};

template <typename T>
struct get_persistent_type {
   typedef typename object_traits<T>::persistent_type type;
};

template <typename T>
class ClassRegistrator<T, is_composite> : protected ClassRegistratorBase {
public:
   typedef typename list_transform_unary<get_persistent_type, typename object_traits<T>::elements>::type elements;

   static SV* register_it(const char* name, size_t namelen, SV* someref, const char* file=NULL, size_t filelen=0, int line=0)
   {
      return register_class(
         name, namelen, file, filelen, line, someref,
         typeid(T).name(), typeid(typename const_equivalent<T>::type).name(),
         is_mutable<T>::value,
         class_kind(class_is_composite | Serializable<T>::flag_value),
         create_composite_vtbl(
            typeid(T), sizeof(T), object_traits<T>::total_dimension,
            Copy<T>::func(),
            Assign<T>::func(),
            Destroy<T>::func(),
            ToString<T>::func(),
            Serializable<T>::conv(),
            Serializable<T>::provide(),
            list_length<elements>::value,
            &TypeListUtils<elements>::provide_types,
            &CompositeClassRegistrator<T>::provide_field_names,
            &CompositeClassRegistrator<T>::init
         )
      );
   }
};

} }
namespace polymake { namespace perl_bindings {

template <typename T>
class Class : public pm::perl::ClassRegistrator<T> {
public:
   template <size_t namelen, size_t filelen>
   Class(const char (&name)[namelen], const char (&file)[filelen], int line)
   {
      pm::perl::ClassRegistrator<T>::register_it(name, namelen-1, 0, file, filelen-1, line);
   }
};

} }
namespace pm { namespace perl {

class ClassTemplate {
private:
   static void register_class(const char* name, size_t l);
public:
   ClassTemplate(const char* name, size_t l)
   {
      register_class(name,l);
   }

   template <size_t nl>
   ClassTemplate(const char (&name)[nl])
   {
      register_class(name,nl-1);
   }
};

SV* get_parameterized_type(const char* pkg, size_t pkgl, bool exact_match);

template <typename TypeList, size_t pkgl, bool exact_match> inline
SV* get_parameterized_type(const char (&pkg)[pkgl], bool2type<exact_match>)
{
   Stack stack(true, 1+TypeListUtils<TypeList>::type_cnt);
   if (TypeListUtils<TypeList>::push_types(stack)) {
      return get_parameterized_type(pkg, pkgl-1, exact_match);
   } else {
      stack.cancel();
      return NULL;
   }
}

class EmbeddedRule {
protected:
   EmbeddedRule() {}

   static
   void add(const char* file, int line, const char* text, size_t l);
public:
   template <size_t l>
   EmbeddedRule(const char* file, int line, const char (&text)[l])
   {
      add(file,line,text,l-1);
   }
};

template <typename Source, typename Target>
struct assignable_to : pm::assignable_to<typename access<Source>::type, Target> {};

template <typename Source, typename Target,
          bool _implicitly=pm::convertible_to<typename access<Source>::type, Target>::value,
          bool _isomorphic=isomorphic_types<typename access<Source>::value_type, Target>::value &&
                           assignable_to<Source,Target>::value,
          typename discr=typename isomorphic_types<typename access<Source>::value_type, Target>::discriminant>
struct convertible_to : bool2type<_implicitly> {};

// two isomorphic types belong to the same generic family and assignable:
// there is a good chance to have an explicit conversion constructor too
template <typename Source, typename Target, typename Tag>
struct convertible_to<Source, Target, false, true, cons<Tag,Tag> > : True {};

template <typename Target, typename Source, bool _enabled=assignable_to<Source,Target>::value>
struct Operator_assign;

template <typename Target, typename Source>
struct Operator_assign<Target, Source, true>
   : protected FunctionBase {

   typedef cons<Target,Source> arg_list;

   static void call(Target& dst, const Value& src)
   {
      if (MaybeWary<Target>::value && (src.get_flags() & value_not_trusted))
         maybe_wary(dst)=src.get<Source>();
      else
         dst=src.get<Source>();
   }

   template <size_t filelen, typename _app_list>
   Operator_assign(const char (&file)[filelen], int line, _app_list cross_apps)
   {
      register_func(reinterpret_cast<wrapper_type>(&call),
                    "=ass", 4, file, filelen-1, line, TypeListUtils<arg_list>::get_types(), cross_apps);
   }
};

template <typename Target, typename Source, bool _enabled=convertible_to<Source,Target>::value>
struct Operator_convert;

template <typename Target, typename Source>
struct Operator_convert<Target, Source, true>
   : protected FunctionBase {

   typedef cons<Target,Source> arg_list;

   static Target call(const Value& src)
   {
      return Target(src.get<Source>());
   }

   template <size_t filelen, typename _app_list>
   Operator_convert(const char (&file)[filelen], int line, _app_list cross_apps)
   {
      register_func(reinterpret_cast<wrapper_type>(&call),
                    ".cnv", 4, file, filelen-1, line, TypeListUtils<arg_list>::get_types(), cross_apps);
   }
};

Wrapper4UnaryOperator(-, neg);
Wrapper4UnaryOperator(~, com);

Wrapper4UnaryAnchOperator(-, neg);
Wrapper4UnaryAnchOperator(~, com);

Wrapper4BinaryOperator(+, add);
Wrapper4BinaryOperator(-, sub);
Wrapper4BinaryOperator(*, mul);
Wrapper4BinaryOperator(/, div);
Wrapper4BinaryOperator(%, mod);
Wrapper4BinaryOperator(&, and);
Wrapper4BinaryOperator(|, _or);
Wrapper4BinaryOperator(^, xor);
Wrapper4BinaryOperator(<<, lsh);
Wrapper4BinaryOperator(>>, rsh);

Wrapper4BinaryAnchOperator(+, add);
Wrapper4BinaryAnchOperator(-, sub);
Wrapper4BinaryAnchOperator(*, mul);
Wrapper4BinaryAnchOperator(/, div);
Wrapper4BinaryAnchOperator(%, mod);
Wrapper4BinaryAnchOperator(&, and);
Wrapper4BinaryAnchOperator(|, _or);
Wrapper4BinaryAnchOperator(^, xor);
Wrapper4BinaryAnchOperator(<<, lsh);
Wrapper4BinaryAnchOperator(>>, rsh);

Wrapper4UnaryAssignOperator(++, inc);
Wrapper4UnaryAssignOperator(--, dec);

Wrapper4BinaryAssignOperator(+=, add);
Wrapper4BinaryAssignOperator(-=, sub);
Wrapper4BinaryAssignOperator(*=, mul);
Wrapper4BinaryAssignOperator(/=, div);
Wrapper4BinaryAssignOperator(%=, mod);
Wrapper4BinaryAssignOperator(&=, and);
Wrapper4BinaryAssignOperator(|=, _or);
Wrapper4BinaryAssignOperator(^=, xor);
Wrapper4BinaryAssignOperator(<<=, lsh);
Wrapper4BinaryAssignOperator(>>=, rsh);

Wrapper4BinaryOperator(==, _eq);
Wrapper4BinaryOperator(!=, _ne);
Wrapper4BinaryOperator(<, _lt);
Wrapper4BinaryOperator(<=, _le);
Wrapper4BinaryOperator(>, _gt);
Wrapper4BinaryOperator(>=, _ge);

template <typename Arg0>
WrapperStart( Operator_Unary_boo, ".boo", Arg0 ) {
   Value arg0(stack[0]);
   WrapperReturn( !is_zero( arg0.get<Arg0>() ) );
};

template <typename Arg0>
WrapperStart( Operator_Unary_not, ".not", Arg0 ) {
   Value arg0(stack[0]);
   WrapperReturn( is_zero( arg0.get<Arg0>() ) );
};

template <typename Arg0, typename Arg1>
WrapperStart( Operator_Binary_brk, ":brk", Arg0,Arg1 ) {
   Value arg0(stack[0]), arg1(stack[1]);
   WrapperReturnLvalue( Arg0, arg0.get<Arg0>() [ arg1.get<Arg1>() ] );
};

} }

#endif // POLYMAKE_PERL_WRAPPERS_H

// Local Variables:
// mode:C++
// c-basic-offset:3
// indent-tabs-mode:nil
// End:
