/* Copyright (c) 1997-2010
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Darmstadt, Germany)
   http://www.polymake.de

   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.
--------------------------------------------------------------------------------
   $Project: polymake $$Id: wrappers.h 9539 2010-03-08 00:43:21Z gawrilow $
*/

#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 T>
   struct is_lvalue : bool2type<attrib<T>::is_reference && !attrib<T>::is_const> {};

   template <typename T>
   struct is_mutable : bool2type<pm::is_mutable<T>::value && !object_traits<T>::is_always_const> {};

   template <typename type_list, int i>
   struct TypeList_helper {
      static const int next= i+1 < list_length<type_list>::value ? i+1 : i;
      typedef TypeList_helper<type_list,next> recurse_down;
      typedef typename n_th<type_list,i>::type T;

      static SV** _do_push(SV **stack)
      {
	 pm_perl_sync_stack(stack);
	 SV *Tproto=type_cache<T>::get_proto();
	 if (!Tproto) return 0;
	 stack=pm_perl_push_arg(stack, Tproto);
	 return next>i ? recurse_down::_do_push(stack) : stack;
      }

      static void _do_flags(SV *arr)
      {
	 type_cache<typename attrib<T>::minus_const_ref>::get_proto();
	 if (is_lvalue<T>::value) {
	    Value lvalue_arg;
	    lvalue_arg << i;
	    pm_perl_AV_push(arr, static_cast<ScalarBase&>(lvalue_arg).get());
	 }
	 if (next>i) recurse_down::_do_flags(arr);
      }

      static void _do_types(SV *arr)
      {
	 typedef typename access<T>::type Type;
	 pm_perl_AV_push(arr, pm_perl_newSVstri_shared(typeid(Type).name(), 0, attrib<Type>::is_const));
	 if (next>i) recurse_down::_do_types(arr);
      }

      static void _do_provide(SV *arr)
      {
	 SV *arg_proto=type_cache<typename attrib<T>::minus_const_ref>::get_proto();
	 pm_perl_AV_push(arr, arg_proto ? pm_perl_incr_SV(arg_proto) : pm_perl_undef());
	 if (next>i) recurse_down::_do_provide(arr);
      }
   };

   template <int i>
   struct TypeList_helper<void,i> {
      static SV** _do_push(SV **stack) { return stack; }
      static void _do_flags(SV*) {}
      static void _do_types(SV*) {}
      static void _do_provide(SV*) {}
   };

   template <typename Fptr>
   class TypeListUtils {
      typedef typename list2cons<Fptr>::type type_list;

      static SV* _do_flags()
      {
	 ArrayBase ret(1+list_accumulate_unary<list_count, is_lvalue, type_list>::value);
	 Value void_result;
	 void_result << (identical<typename list2cons<Fptr>::return_type, void>::value ||
			 identical<typename list2cons<Fptr>::return_type, ListReturn>::value);
	 ret.push(void_result);
	 TypeList_helper<type_list,0>::_do_flags(ret.get());
	 return ret.get();
      }

      static SV* _do_types()
      {
	 ArrayBase ret(list_length<type_list>::value);
	 TypeList_helper<type_list,0>::_do_types(ret.get());
	 return ret.get();
      }

      static SV* _do_provide()
      {
	 ArrayBase ret(list_length<type_list>::value);
	 TypeList_helper<type_list,0>::_do_provide(ret.get());
	 return ret.get();
      }

   public:
      // a pointer to a routine pushing the mangled names on the perl stack
      static SV** (*push())(SV **stack) { return &TypeList_helper<type_list,0>::_do_push; }

      // build an array with void-return and arg-is-lvalue flags;
      // the signature of this function has to be compatible with wrapper_type
      static SV* get_flags(SV**, char*)
      {
	 static SV* ret=_do_flags();
	 return ret;
      }

      // build an array with mangled names
      static SV* get_types(int =0)
      {
	 static SV* ret=_do_types();
	 return ret;
      }

      // the same, but with prescribed text for the first element
      static SV* get_types(const char *first_arg_name)
      {
	 ArrayBase arr(list_length<type_list>::value);
	 pm_perl_AV_push(arr.get(), pm_perl_newSVstr_shared(first_arg_name,0));
	 static const int next= list_length<type_list>::value > 1;
	 if (next) TypeList_helper<type_list,next>::_do_types(arr.get());
	 return arr.get();
      }

      // instantiate the perl-side descriptors of all types in type_list
      static SV* provide()
      {
	 static SV* ret=_do_provide();
	 return ret;
      }
   };

   template <typename Wrapper>
   struct WrapperBase {
      template <size_t nl, size_t fl, typename first_arg> static
      void register_it(const char (&name)[nl], const char (&file)[fl], first_arg arg0)
      {
	 pm_perl_register_func(&Wrapper::call, name, nl-1, file, fl-1, TypeListUtils<typename Wrapper::arg_list>::get_types(arg0), 0, 0);
      }
   };

   template <typename Typelist>
   struct DisabledFunction {
      template <size_t nl, size_t fl>
      DisabledFunction(const char (&name)[nl], const char (&file)[fl])
      {
	 pm_perl_register_disabled_func(name, nl-1, file, fl-1, TypeListUtils<Typelist>::get_types(0));
      }
   };

   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_masquerade<T>::value)>
   class Copy {
      static SV* _do(void* place, const T* src)
      {
	 try {
	    new(place) T(*src);
	 }
	 WrapperEpilogue(0);
      }
   public:
      static copy_constructor_type func() { return reinterpret_cast<copy_constructor_type>(&_do); }
   };

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

   template <typename T, bool _and_enable=true, bool _enable=_and_enable && is_mutable<T>::value>
   class Assign {
      static SV* _do(T* dst, SV* sv, value_flags flags)
      {
	 try {
	    Value src(sv, flags);
	    src >> *dst;
	 }
	 WrapperEpilogue(0);
      }
   public:
      static assignment_type func() { return reinterpret_cast<assignment_type>(&_do); }
   };

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

   template <typename T, bool _enable=is_printable<T>::value>
   class ToString {
   protected:
      static SV* _do(const T* src)
      {
	 Value ret;
	 try {
	    ostream my_stream(static_cast<ScalarBase&>(ret).get());
	    PlainPrinter<> printer(my_stream);
	    printer << *src;
	 }
	 WrapperEpilogue(ret.get_temp());
      }
   public:
      static conv_to_SV_type func() { return reinterpret_cast<conv_to_SV_type>(&_do); }
   };

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

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

   template <typename T, typename _serialized=typename object_traits<T>::serialized>
   class Serialized : public True {
   protected:
      static const bool assign_via_serialized = is_mutable<T>::value && is_mutable<_serialized>::value &&
                                                !io_test::has_generic_input_operator<ValueInput<>,T>::value;

      static SV* _assign(T *dst, SV *sv, value_flags flags)
      {
	 try {
	    Value src(sv, flags);
	    src >> object_traits<T>::serialize(*dst);
	 }
	 WrapperEpilogue(0);
      }

      static SV* _conv(const T *src, const char *frame_upper_bound)
      {
	 Value ret(value_flags(value_allow_non_persistent | value_read_only));
	 try {
	    ret.put(object_traits<T>::serialize(*src), 0, frame_upper_bound, 0);
	 }
	 WrapperEpilogue(ret.get_temp());
      }

      static assignment_type assign(False) { return Assign<T>::func(); }
      static assignment_type assign(True) { return reinterpret_cast<assignment_type>(&_assign); }
   public:
      static assignment_type assign() { return assign(bool2type<assign_via_serialized>()); }
      static conv_to_SV_type conv() { return reinterpret_cast<conv_to_SV_type>(&_conv); }
      static provide_type provide() { return &type_cache<typename deref<_serialized>::type>::provide; }
   };

   template <typename Base, typename E, typename Params>
   class Serialized<sparse_elem_proxy<Base,E,Params>, void> : public False {
   protected:
      static SV* _conv(const sparse_elem_proxy<Base,E,Params> *src, const char*)
      {
	 Value ret;
	 try {
	    ret << src->get();
	 }
	 WrapperEpilogue(ret.get_temp());
      }
   public:
      static assignment_type assign() { return 0; }
      static conv_to_SV_type conv() { return reinterpret_cast<conv_to_SV_type>(&_conv); }
      static provide_type provide() { return 0; }
   };

   template <typename T>
   class Serialized<T, void> : public False {
   public:
      static assignment_type assign() { return 0; }
      static conv_to_SV_type conv() { return 0; }
      static provide_type provide() { return 0; }
   };

   template <typename T>
   class Builtin {
   protected:
      static const bool is_assignable=io_test::has_std_input_operator<T>::value;
   public:
      static SV* register_it(const char *name, size_t l)
      {
	 return
	 pm_perl_register_builtin(
	    name, l, typeid(T).name(),
	    pm_perl_create_builtin_vtbl(
	       &typeid(T), sizeof(T), list_contains<primitive_lvalues,T>::value,
	       Copy<T>::func(),
	       Assign<T, is_assignable>::func(),
	       Destroy<T>::func())
	 );
      }

      Builtin(const char *name, size_t l)
      {
	 register_it(name,l);
      }

      template <size_t l>
      Builtin(const char (&name)[l])
      {
	 register_it(name,l-1);
      }
   };

   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:
      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=0)
      {
	 return
	 pm_perl_register_class(
	    name, namelen, someref,
	    typeid(T).name(), typeid(typename const_equivalent<T>::type).name(),
	    is_mutable<T>::value,
	    class_is_scalar,
	    pm_perl_create_scalar_vtbl(
	       &typeid(T), sizeof(T),
	       Copy<T>::func(),
	       Assign<T>::func(),
	       Destroy<T>::func(),
	       ToString<T>::func(),
	       Serialized<T>::conv(),
	       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 {
   public:
      static SV* register_it(const char* name, size_t namelen, SV *someref=0)
      {
	 return
	 pm_perl_register_class(
	    name, namelen, someref,
	    typeid(T).name(), typeid(typename const_equivalent<T>::type).name(),
	    is_mutable<T>::value,
	    Serialized<T>::value ? class_kind(class_is_opaque | class_is_serializable) : class_is_opaque,
	    pm_perl_create_opaque_vtbl(
	       &typeid(T), sizeof(T),
	       Serialized<T>::assign(),
	       Destroy<T>::func(),
	       ToString<T>::func(),
	       Serialized<T>::conv(),
	       Serialized<T>::provide())
	 );
      }
   };

   template <typename T>
   class OpaqueClassRegistrator<T, true> {
   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));
	 try {
	    ret.put_lval(**it, 0, frame_upper_bound, 0);
	 }
	 WrapperEpilogue(ret.get_temp());
      }

      static SV* incr(T* it)
      {
	 try {
	    ++(*it);
	 }
	 WrapperEpilogue(0);
      }

      static int at_end(const T* it)
      {
	 return it->at_end();
      }
   public:
      static SV* register_it(const char* name, size_t namelen, SV *someref=0)
      {
	 return
	 pm_perl_register_class(
	    name, namelen, someref, typeid(T).name(), typeid(T).name(),
	    true,
	    class_is_opaque,
	    pm_perl_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, typename Category=typename container_traits<typename serialized_of<T>::type>::category,
	     bool _obscure=serialized_of<T>::obscure>
   class ContainerClassRegistrator {
   public:
      typedef serialized_of<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,
	                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::serialize(*obj).size();
      }

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

      static SV* do_resize(T* obj, int n)
      {
	 try {
	    helper::serialize(*obj).resize(n);
	 }
	 WrapperEpilogue(0);
      }

      static SV* fixed_size(T* obj, int n)
      {
	 try {
	    if (get_dim(helper::serialize(*obj)) != n)
	       throw std::runtime_error("size mismatch");
	 }
	 WrapperEpilogue(0);
      }

      static SV* clear_by_resize(T* obj, int)
      {
	 try {
	    helper::serialize(*obj).clear();
	 }
	 WrapperEpilogue(0);
      }

      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 SV* push_back(T *obj, iterator *it, int, SV *src)
      {
	 try {
	    Value v(src);
	    typename Obj::value_type x;
	    v >> x;
	    check_insertion(helper::serialize(*obj), x,
			    bool2type<check_container_feature<Obj,sparse_compatible>::value>());
	    helper::serialize(*obj).insert(*it, x);
	 }
	 WrapperEpilogue(0);
      }

      static SV* insert(T *obj, iterator*, int, SV *src)
      {
	 try {
	    Value v(src);
	    typename item4insertion<typename Obj::value_type>::type x;
	    v >> x;
	    check_insertion(helper::serialize(*obj), x,
			    bool2type<check_container_feature<Obj,sparse_compatible>::value>());
	    helper::serialize(*obj).insert(x);
	 }
	 WrapperEpilogue(0);
      }

      static SV* do_store(T*, iterator *it, int, SV *src)
      {
	 try {
	    Value v(src, value_not_trusted);
	    v >> non_const(**it);
	    ++(*it);
         }
	 WrapperEpilogue(0);
      }

      static SV* store_sparse(T *obj, iterator *it, int index, SV *src)
      {
	 try {
	    Value v(src, value_not_trusted);
	    typename Obj::value_type x;
	    v >> x;
	    conv<typename Obj::value_type, bool> non_zero;
	    if (non_zero(x)) {
	       if (!it->at_end() && it->index()==index) {
		  **it=x; ++(*it);
	       } else {
		  helper::serialize(*obj).insert(*it,index,x);
	       }
	    } else {
	       if (!it->at_end() && it->index()==index)
		  helper::serialize(*obj).erase((*it)++);
	    }
	 }
	 WrapperEpilogue(0);
      }

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

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

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

	 static SV* deref(ObjPtr, Iterator *it, int, SV *dst, const char *frame_upper_bound)
	 {
	    try {
	       Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent | (non_const ? 0 : value_read_only)));
	       pv.put_lval(**it, 0, frame_upper_bound, 0);
	       ++(*it);
	    }
	    WrapperEpilogue(0);
	 }

	 static SV* deref_pair(ObjPtr, Iterator *it, int i, SV *dst, const char *frame_upper_bound)
	 {
	    try {
	       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));
		     pv.put((*it)->first, 0, frame_upper_bound, 0);
		  }
	       } else {
		  // i==1: fetch value
		  Value pv(dst, value_flags(value_allow_non_persistent | (non_const ? 0 : value_read_only)));
		  pv.put((*it)->second, 0, frame_upper_bound, 0);
	       }
	    }
	    WrapperEpilogue(0);
	 }
      };

      template <typename Iterator>
      struct do_sparse {
	 static SV* deref(T *obj, Iterator *it, int index, SV *dst, const char*)
	 {
	    try {
	       Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent));
	       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::serialize(*obj), *it, index));
	       if (x.exists()) ++(*it);
	       pv.put(x,0,0,0);
	    }
	    WrapperEpilogue(0);
	 }
      };

      template <typename Iterator>
      struct do_const_sparse {
	 static SV* deref(const T*, Iterator *it, int index, SV *dst, const char* frame_upper_bound)
	 {
	    try {
	       Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent | value_read_only));
	       if (!it->at_end() && index==it->index()) {
		  pv.put_lval(**it, 0, frame_upper_bound, 0);
		  ++(*it);
	       } else {
		  operations::clear<typename Obj::value_type> zero;
		  pv.put_lval(zero(), 0, frame_upper_bound, 0);
	       }
	    }
	    WrapperEpilogue(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>(&do_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(False) { return 0; }

      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>(&do_store);
      }
      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 0; }

      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=pm_perl_create_container_vtbl( &typeid(T), sizeof(T), object_traits<T>::total_dimension,
						 Copy<T>::func(),
						 Assign<T>::func(),
						 Destroy<T>::func(),
						 ToString<T>::func(),
						 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>()) );
	 pm_perl_it_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, SV *someref, SV *vtbl)
      {
	 return 
	 pm_perl_register_class(name, namelen, someref,
				typeid(T).name(), typeid(typename const_equivalent<T>::type).name(),
				is_mutable<T>::value,
				is_associative   ? class_kind(class_is_container | class_is_assoc_container) :
				is_sparse_native ? class_kind(class_is_container | class_is_sparse_container) :
				like_set         ? class_kind(class_is_container | class_is_set)
				                 : class_is_container,
				vtbl);
      }

   public:
      static SV* register_it(const char* name, size_t namelen, SV *someref=0)
      {
	 return register_me(name,namelen,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();
	 pm_perl_it_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=0)
      {
	 return super::register_me(name,namelen,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 SV* do_random(T *obj, char*, int index, SV *dst, const char *frame_upper_bound)
      {
	 try {
	    Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent));
	    pv.put_lval(serialized_of<T>::serialize(*obj)[index], 0, frame_upper_bound, 0);
	 }
	 WrapperEpilogue(0);
      }

      static SV* crandom(const T *obj, char*, int index, SV *dst, const char *frame_upper_bound)
      {
	 try {
	    Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent | value_read_only));
	    pv.put_lval(serialized_of<T>::serialize(*obj)[index], 0, frame_upper_bound, 0);
	 }
	 WrapperEpilogue(0);
      }

      static SV* random_sparse(T *obj, char*, int index, SV *dst, const char*)
      {
	 try {
	    Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent));
	    pv.put(super::helper::serialize(*obj)[index],0,0,0);
	 }
	 WrapperEpilogue(0);
      }

      static container_access_type random(False, True)
      {
	 return reinterpret_cast<container_access_type>(&do_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=0)
      {
	 SV *vtbl=super::create_vtbl();
	 pm_perl_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,someref,vtbl);
      }
   };

   template <typename T, typename Category>
   class ContainerClassRegistrator<T, Category, true> {
   public:
      static SV* register_it(const char* name, size_t namelen, SV *someref=0)
      {
	 return
	 pm_perl_register_class(
	    name, namelen, someref, typeid(T).name(), typeid(T).name(), false, class_is_opaque,
            pm_perl_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 SV* do_get(T *obj, SV *dst, const char *frame_upper_bound)
      {
	 try {
	    Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent));
	    pv.put_lval(visit_n_th(serialized_of<T>::serialize(*obj), int2type<n>()), 0, frame_upper_bound, 0);
	 }
	 WrapperEpilogue(0);
      }

      static SV* cget(const T *obj, SV *dst, const char *frame_upper_bound)
      {
	 try {
	    Value pv(dst, value_flags(value_expect_lval | value_allow_non_persistent | value_read_only));
	    pv.put_lval(visit_n_th(serialized_of<T>::serialize(*obj), int2type<n>()), 0, frame_upper_bound, 0);
	 }
	 WrapperEpilogue(0);
      }

      static SV* do_store(T *obj, SV *src)
      {
	 try {
	    Value v(src, value_not_trusted);
	    v >> visit_n_th(serialized_of<T>::serialize(*obj), int2type<n>());
	 }
	 WrapperEpilogue(0);
      }

      static void* get(True)  { return reinterpret_cast<void*>(&do_get); }
      static void* get(False) { return reinterpret_cast<void*>(&cget); }
      static void* store(True)  { return reinterpret_cast<void*>(&do_store); }
      static void* store(False) { return 0; }

      static void init(void **gets)
      {
	 *gets++=get(bool2type<allow_non_const_access>());
	 *gets++=get(False());
	 *gets++=store(bool2type<allow_non_const_access>());
	 CompositeClassRegistrator<T,n+1,l>::init(gets);
      }
   };

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

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

   template <typename T>
   class ClassRegistrator<T, is_composite> {
   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=0)
      {
	 return
	 pm_perl_register_class(name, namelen, someref,
				typeid(T).name(), typeid(typename const_equivalent<T>::type).name(),
				is_mutable<T>::value,
				class_is_composite,
				pm_perl_create_composite_vtbl(
				   &typeid(T), sizeof(T), object_traits<T>::total_dimension,
				   Copy<T>::func(),
				   Assign<T>::func(),
				   Destroy<T>::func(),
				   ToString<T>::func(),
				   &TypeListUtils<elements>::provide,
				   list_length<elements>::value,
				   &CompositeClassRegistrator<T>::init)
	 );
      }
   };
} }
namespace polymake { namespace perl_bindings {
   template <typename T>
   class Class : public pm::perl::ClassRegistrator<T> {
   public:
      Class(const char *name, size_t l)
      {
	 pm::perl::ClassRegistrator<T>::register_it(name,l);
      }

      template <size_t l>
      Class(const char (&name)[l])
      {
	 pm::perl::ClassRegistrator<T>::register_it(name,l-1);
      }
   };
} }
namespace pm { namespace perl {
   class ClassTemplate {
   public:
      ClassTemplate(const char *name, size_t l)
      {
	 pm_perl_register_class_template(name,l);
      }

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

   template <typename TypeList, size_t pkgl, bool exact_match> inline
   SV4recognize<exact_match>* get_type(const char (&pkg)[pkgl], bool2type<exact_match>)
   {
      return static_cast<SV4recognize<exact_match>*>(get_type(pkg,pkgl-1,TypeListUtils<TypeList>::push(),exact_match));
   }

   struct EmbeddedRule {
      template <size_t l>
      EmbeddedRule(const char *file, int line, const char (&text)[l])
      {
	 pm_perl_add_rules(file,line,text,l-1);
      }
   };

   struct Function {
      template <typename Fptr, size_t fl>
      Function(Fptr *fptr, const char (&file)[fl], int line, const char* text)
      {
	 const int i=pm_perl_register_func(&TypeListUtils<Fptr>::get_flags, 0, 0, file, fl-1, TypeListUtils<Fptr>::get_types(),
					   (void*)fptr, typeid(type2type<Fptr>).name());
	 pm_perl_add_rules_v(file,line,text,i);
      }
   };

   template <typename T>
   struct EmbeddedPropertyType : protected type_cache<T> {

      // stack[0] is the function wrapper descriptor, the interesting arguments start at [1]
      static SV* register_it(SV **stack, char*)
      {
	 ArrayBase ret(2);
	 try {
	    type_infos ti;
	    ti.descr=ClassRegistrator<T>::register_it(0,1,stack[1]);
	    ti.proto=pm_perl_copy(stack[1]);
	    ti.allow_magic_storage=true;
	    type_cache<T>::get(&ti);

	    SV *super=recognize(recognizer_bait(0), (T*)0, (T*)0);
	    ret.push(super ? super : pm_perl_undef());
	    ret.push(field_names(recognizer_bait(0), (T*)0));
	 }
	 WrapperEpilogue(ret.get_temp());
      }

      template <size_t nl, size_t fl>
      EmbeddedPropertyType(const char (&name)[nl], const char (&file)[fl])
      {
	 pm_perl_register_embedded_property_type(name,nl-1,&register_it,file,fl-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 {
      typedef cons<Target,Source> arg_list;

      static void call(Target& dst, const Value& src)
      {
	 dst=src.get<Source>();
      }

      template <size_t fl>
      Operator_assign(const char (&file)[fl], int=0)
      {
	 pm_perl_register_func(reinterpret_cast<wrapper_type>(&call),
			       "=ass", 4, file, fl-1, TypeListUtils<arg_list>::get_types(), 0, 0);
      }
   };

   template <typename Target, typename Source>
   struct Operator_assign<Target, Source, false> {
      typedef cons<Target,Source> arg_list;

      template <size_t fl>
      Operator_assign(const char (&file)[fl], int=0)
      {
	 pm_perl_register_disabled_func("=ass", 4, file, fl-1, TypeListUtils<arg_list>::get_types());
      }
   };

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

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

      template <size_t fl>
      Operator_convert(const char (&file)[fl], int=0)
      {
	 pm_perl_register_func(reinterpret_cast<wrapper_type>(&call),
			       ".cnv", 4, file, fl-1, TypeListUtils<arg_list>::get_types(), 0, 0);
      }
   };

   template <typename Target, typename Source>
   struct Operator_convert<Target, Source, false> {
      typedef cons<Target,Source> arg_list;

      template <size_t fl>
      Operator_convert(const char (&file)[fl], int=0)
      {
	 pm_perl_register_disabled_func(".cnv", 4, file, fl-1, TypeListUtils<arg_list>::get_types());
      }
   };

   Wrapper4UnaryOperator(-, neg);
   Wrapper4UnaryOperator(!, not);
   Wrapper4UnaryOperator(~, com);
   Wrapper4UnaryOperator(static_cast<bool>, boo);

   Wrapper4BinaryOperator(+, add);
   Wrapper4BinaryOperator(-, sub);
   Wrapper4BinaryOperator(*, mul);
   Wrapper4BinaryOperator(/, div);
   Wrapper4BinaryOperator(%, mod);
   Wrapper4BinaryOperator(&, and);
   Wrapper4BinaryOperator(|, _or);
   Wrapper4BinaryOperator(^, xor);
   Wrapper4BinaryOperator(<<, lsh);
   Wrapper4BinaryOperator(>>, 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, 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
// End:
