2 /// Expose C++ objects to Nasal as ghosts
4 // Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com>
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Library General Public
8 // License as published by the Free Software Foundation; either
9 // version 2 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Library General Public License for more details.
16 // You should have received a copy of the GNU Library General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 #ifndef SG_NASAL_GHOST_HXX_
21 #define SG_NASAL_GHOST_HXX_
23 #include "NasalCallContext.hxx"
25 #include <simgear/debug/logstream.hxx>
27 #include <boost/bind.hpp>
28 #include <boost/call_traits.hpp>
29 #include <boost/function.hpp>
30 #include <boost/lambda/lambda.hpp>
31 #include <boost/mpl/has_xxx.hpp>
32 #include <boost/preprocessor/iteration/iterate.hpp>
33 #include <boost/shared_ptr.hpp>
34 #include <boost/utility/enable_if.hpp>
39 * Bindings between C++ and the Nasal scripting language
47 * Metadata for Ghost object types
53 * Add a nasal base class to the ghost. Will be available in the ghosts
56 void addNasalBase(const naRef& parent)
58 assert( naIsHash(parent) );
59 _parents.push_back(parent);
62 bool isBaseOf(naGhostType* ghost_type) const
64 if( ghost_type == &_ghost_type )
67 for( DerivedList::const_iterator derived = _derived_classes.begin();
68 derived != _derived_classes.end();
71 if( (*derived)->isBaseOf(ghost_type) )
80 typedef std::vector<const GhostMetadata*> DerivedList;
82 const std::string _name;
83 naGhostType _ghost_type;
84 DerivedList _derived_classes;
85 std::vector<naRef> _parents;
87 explicit GhostMetadata(const std::string& name):
93 void addDerived(const GhostMetadata* derived)
96 _derived_classes.push_back(derived);
102 "Ghost::addDerived: " <<_ghost_type.name << " -> " << derived->_name
106 naRef getParents(naContext c)
108 return nasal::to_nasal(c, _parents);
113 * Hold callable method and convert to Nasal function if required.
118 virtual ~MethodHolder() {}
119 virtual naRef get_naRef(naContext c) = 0;
122 BOOST_MPL_HAS_XXX_TRAIT_DEF(element_type)
127 typedef typename boost::remove_cv<
128 typename boost::remove_reference<T>::type
132 template<class T1, class T2>
133 struct reduced_is_same:
134 public boost::is_same<typename reduced_type<T1>::type, T2>
139 * Class for exposing C++ objects to Nasal
142 * // Example class to be exposed to Nasal
150 * void doSomethingElse(const nasal::CallContext& ctx);
152 * typedef boost::shared_ptr<MyClass> MyClassPtr;
154 * std::string myOtherFreeMember(int num);
156 * void exposeClasses()
158 * // Register a nasal ghost type for MyClass. This needs to be done only
159 * // once before creating the first ghost instance. The exposed class needs
160 * // to be wrapped inside a shared pointer, eg. boost::shared_ptr.
161 * Ghost<MyClassPtr>::init("MyClass")
162 * // Members can be exposed by getters and setters
163 * .member("x", &MyClass::getX, &MyClass::setX)
164 * // For readonly variables only pass a getter
165 * .member("x_readonly", &MyClass::getX)
166 * // It is also possible to expose writeonly members
167 * .member("x_writeonly", &MyClass::setX)
168 * // Methods can be nearly anything callable and accepting a reference
169 * // to an instance of the class type. (member functions, free functions
170 * // and anything else bindable using boost::function and boost::bind)
171 * .method("myMember", &MyClass::myMember)
172 * .method("doSomething", &MyClass::doSomethingElse)
173 * .method("other", &myOtherFreeMember);
179 public internal::GhostMetadata
181 BOOST_STATIC_ASSERT( internal::has_element_type<T>::value );
184 typedef typename T::element_type raw_type;
186 typedef naRef (raw_type::*member_func_t)(const CallContext&);
187 typedef naRef (*free_func_t)(raw_type&, const CallContext&);
188 typedef boost::function<naRef(naContext, raw_type&)> getter_t;
189 typedef boost::function<void(naContext, raw_type&, naRef)> setter_t;
190 typedef boost::function<naRef(raw_type&, const CallContext&)> method_t;
191 typedef boost::shared_ptr<internal::MethodHolder> MethodHolderPtr;
194 public internal::MethodHolder
201 explicit MethodHolder(const method_t& method):
206 virtual naRef get_naRef(naContext c)
208 if( naIsNil(_naRef) )
210 _naRef = naNewFunc(c, naNewCCodeU(c, &MethodHolder::call, this));
220 static naRef call( naContext c,
226 MethodHolder* holder = static_cast<MethodHolder*>(user_data);
228 naRuntimeError(c, "invalid method holder!");
230 return holder->_method
232 requireObject(c, me),
233 CallContext(c, argc, args)
239 * A ghost member. Can consist either of getter and/or setter functions
240 * for exposing a data variable or a single callable function.
247 member_t( const getter_t& getter,
248 const setter_t& setter,
249 const MethodHolderPtr& func = MethodHolderPtr() ):
255 explicit member_t(const MethodHolderPtr& func):
261 MethodHolderPtr func;
264 typedef std::map<std::string, member_t> MemberMap;
267 * Register a new ghost type.
269 * @note Only intialize each ghost type once!
271 * @param name Descriptive name of the ghost type.
273 static Ghost& init(const std::string& name)
275 assert( !getSingletonPtr() );
277 getSingletonHolder().reset( new Ghost(name) );
278 return *getSingletonPtr();
282 * Check whether ghost type has already been initialized.
286 return getSingletonPtr();
290 * Register a base class for this ghost. The base class needs to be
291 * registers on its own before it can be used as base class.
293 * @tparam BaseGhost Type of base class already wrapped into Ghost class
297 * Ghost<MyBasePtr>::init("MyBase");
298 * Ghost<MyClassPtr>::init("MyClass")
299 * .bases<Ghost<MyBasePtr> >();
302 template<class BaseGhost>
303 typename boost::enable_if
305 boost::is_base_of<GhostMetadata, BaseGhost>,
312 boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value
315 BaseGhost* base = BaseGhost::getSingletonPtr();
319 // Both ways of retrieving the address of a static member function
320 // should be legal but not all compilers know this.
321 // g++-4.4.7+ has been tested to work with both versions
322 #if defined(GCC_VERSION) && GCC_VERSION < 40407
323 // The old version of g++ used on Jenkins (16.11.2012) only compiles
325 &getTypeFor<BaseGhost>
327 // VS (2008, 2010, ... ?) only allow this version.
328 &Ghost::getTypeFor<BaseGhost>
332 // Replace any getter that is not available in the current class.
333 // TODO check if this is the correct behavior of function overriding
334 for( typename BaseGhost::MemberMap::const_iterator member =
335 base->_members.begin();
336 member != base->_members.end();
339 if( _members.find(member->first) == _members.end() )
340 _members[member->first] = member_t
342 member->second.getter,
343 member->second.setter,
352 * Register a base class for this ghost. The base class needs to be
353 * registers on its own before it can be used as base class.
355 * @tparam Base Type of base class (Base as used in Ghost<BasePtr>)
358 * Ghost<MyBasePtr>::init("MyBase");
359 * Ghost<MyClassPtr>::init("MyClass")
360 * .bases<MyBasePtr>();
364 typename boost::disable_if
366 boost::is_base_of<GhostMetadata, Base>,
373 boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value
376 return bases< Ghost<Base> >();
380 * Register an existing Nasal class/hash as base class for this ghost.
382 * @param parent Nasal hash/class
384 Ghost& bases(const naRef& parent)
386 addNasalBase(parent);
391 * Register a member variable by passing a getter and/or setter method.
393 * @param field Name of member
394 * @param getter Getter for variable
395 * @param setter Setter for variable (Pass 0 to prevent write access)
398 template<class Ret, class Param>
399 Ghost& member( const std::string& field,
400 Ret (raw_type::*getter)() const,
401 void (raw_type::*setter)(Param) )
403 return member(field, to_getter(getter), to_setter(setter));
407 * Register a read only member variable.
409 * @param field Name of member
410 * @param getter Getter for variable
413 Ghost& member( const std::string& field,
414 Ret (raw_type::*getter)() const )
416 return member(field, to_getter(getter), setter_t());
420 * Register a write only member variable.
422 * @param field Name of member
423 * @param setter Setter for variable
426 Ghost& member( const std::string& field,
427 void (raw_type::*setter)(Var) )
429 return member(field, getter_t(), to_setter(setter));
433 * Register a member variable by passing a getter and/or setter method.
435 * @param field Name of member
436 * @param getter Getter for variable
437 * @param setter Setter for variable (Pass empty to prevent write access)
440 Ghost& member( const std::string& field,
441 const getter_t& getter,
442 const setter_t& setter = setter_t() )
444 if( !getter.empty() || !setter.empty() )
445 _members[field] = member_t(getter, setter);
451 "Member '" << field << "' requires a getter or setter"
457 * Register anything that accepts an object instance and a
458 * nasal::CallContext and returns naRef as method.
464 * naRef myMethod(const nasal::CallContext& ctx);
467 * Ghost<MyClassPtr>::init("Test")
468 * .method("myMethod", &MyClass::myMethod);
471 Ghost& method(const std::string& name, const method_t& func)
473 _members[name].func.reset( new MethodHolder(func) );
478 * Register anything that accepts an object instance and a
479 * nasal::CallContext whith automatic conversion of the return type to
484 * void doIt(const MyClass& c, const nasal::CallContext& ctx);
486 * Ghost<MyClassPtr>::init("Test")
487 * .method("doIt", &doIt);
493 const std::string& name,
494 const boost::function<Ret (raw_type&, const CallContext&)>& func
497 return method(name, boost::bind(method_invoker<Ret>, func, _1, _2));
500 #define BOOST_PP_ITERATION_LIMITS (0, 9)
501 #define BOOST_PP_FILENAME_1 <simgear/nasal/cppbind/detail/functor_templates.hxx>
502 #include BOOST_PP_ITERATE()
504 // TODO use variadic template when supporting C++11
505 // TODO check if default constructor exists
506 // static naRef create( naContext c )
508 // return makeGhost(c, createInstance());
512 * Create a Nasal instance of this ghost.
514 * @param c Active Nasal context
515 * @param a1 Parameter used for creating new instance
518 static naRef create( naContext c, const A1& a1 )
520 return makeGhost(c, createInstance(a1));
524 * Nasal callback for creating a new instance of this ghost.
526 static naRef f_create(naContext c, naRef me, int argc, naRef* args)
531 static bool isBaseOf(naGhostType* ghost_type)
536 return getSingletonPtr()->GhostMetadata::isBaseOf(ghost_type);
539 static bool isBaseOf(naRef obj)
541 return isBaseOf( naGhost_type(obj) );
545 * Convert Nasal object to C++ object. To get a valid object the passed
546 * Nasal objects has to be derived class of the target class (Either
547 * derived in C++ or in Nasal using a 'parents' vector)
549 static pointer fromNasal(naContext c, naRef me)
551 // Check if it's a ghost and if it can be converted
552 if( isBaseOf( naGhost_type(me) ) )
553 return getPtr( naGhost_ptr(me) );
555 // Now if it is derived from a ghost (hash with ghost in parent vector)
556 else if( naIsHash(me) )
558 naRef na_parents = naHash_cget(me, const_cast<char*>("parents"));
559 if( !naIsVector(na_parents) )
561 SG_LOG(SG_NASAL, SG_DEBUG, "Missing 'parents' vector for ghost");
565 typedef std::vector<naRef> naRefs;
566 naRefs parents = from_nasal<naRefs>(c, na_parents);
567 for( naRefs::const_iterator parent = parents.begin();
568 parent != parents.end();
571 pointer ptr = fromNasal(c, *parent);
585 typedef naGhostType* (*type_checker_t)(const raw_type*);
586 typedef std::vector<type_checker_t> DerivedList;
587 DerivedList _derived_types;
590 * Create a shared pointer on the heap to handle the reference counting
591 * for the passed shared pointer while it is used in Nasal space.
593 static pointer* createInstance(const pointer& ptr)
595 return ptr.get() ? new pointer(ptr) : 0;
598 static pointer getPtr(void* ptr)
601 return *static_cast<pointer*>(ptr);
606 static raw_type* getRawPtr(void* ptr)
609 return static_cast<pointer*>(ptr)->get();
614 static raw_type* getRawPtr(const pointer& ptr)
619 void addDerived( const internal::GhostMetadata* derived_meta,
620 const type_checker_t& derived_info )
622 GhostMetadata::addDerived(derived_meta);
623 _derived_types.push_back(derived_info);
626 template<class BaseGhost>
628 typename boost::enable_if
629 < boost::is_polymorphic<typename BaseGhost::raw_type>,
632 getTypeFor(const typename BaseGhost::raw_type* base)
634 // Check first if passed pointer can by converted to instance of class
637 < typename BaseGhost::raw_type,
638 typename Ghost::raw_type
640 && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
643 // Now check if we can further downcast to one of our derived classes.
644 for( typename DerivedList::reverse_iterator
645 derived = getSingletonPtr()->_derived_types.rbegin();
646 derived != getSingletonPtr()->_derived_types.rend();
649 naGhostType* ghost_type =
650 (*derived)( static_cast<const typename Ghost::raw_type*>(base) );
655 // If base is not an instance of any derived class, this class has to
656 // be the dynamic type.
657 return &getSingletonPtr()->_ghost_type;
660 template<class BaseGhost>
662 typename boost::disable_if
663 < boost::is_polymorphic<typename BaseGhost::raw_type>,
666 getTypeFor(const typename BaseGhost::raw_type* base)
668 // For non polymorphic classes there is no possibility to get the actual
669 // dynamic type, therefore we can only use its static type.
670 return &BaseGhost::getSingletonPtr()->_ghost_type;
673 static Ghost* getSingletonPtr()
675 return getSingletonHolder().get();
678 static raw_type& requireObject(naContext c, naRef me)
680 raw_type* obj = getRawPtr( fromNasal(c, me) );
681 naGhostType* ghost_type = naGhost_type(me);
687 "method called on object of wrong type: is '%s' expected '%s'",
688 ghost_type ? ghost_type->name : "unknown",
689 getSingletonPtr()->_ghost_type.name
696 getter_t to_getter(Ret (raw_type::*getter)() const)
698 typedef typename boost::call_traits<Ret>::param_type param_type;
699 naRef(*to_nasal_)(naContext, param_type) = &to_nasal;
701 // Getter signature: naRef(naContext, raw_type&)
706 boost::bind(getter, _2)
710 template<class Param>
711 setter_t to_setter(void (raw_type::*setter)(Param))
713 // Setter signature: void(naContext, raw_type&, naRef)
718 boost::bind(from_nasal_ptr<Param>::get(), _1, _3)
724 * Invoke a method which returns a value and convert it to Nasal.
728 typename boost::disable_if<boost::is_void<Ret>, naRef>::type
731 const boost::function<Ret (raw_type&, const CallContext&)>& func,
733 const CallContext& ctx
736 return (*to_nasal_ptr<Ret>::get())(ctx.c, func(obj, ctx));
740 * Invoke a method which returns void and "convert" it to nil.
744 typename boost::enable_if<boost::is_void<Ret>, naRef>::type
747 const boost::function<Ret (raw_type&, const CallContext&)>& func,
749 const CallContext& ctx
757 * Extract argument by index from nasal::CallContext and convert to given
762 typename boost::disable_if<
763 internal::reduced_is_same<Arg, CallContext>,
764 typename from_nasal_ptr<Arg>::return_type
766 arg_from_nasal(const CallContext& ctx, size_t index)
768 return ctx.requireArg<Arg>(index);
772 * Specialization to pass through nasal::CallContext.
776 typename boost::enable_if<
777 internal::reduced_is_same<Arg, CallContext>,
778 typename from_nasal_ptr<Arg>::return_type
780 arg_from_nasal(const CallContext& ctx, size_t)
782 // Either const CallContext& or CallContext, non-const reference
783 // does not make sense.
784 BOOST_STATIC_ASSERT( (!boost::is_same<Arg, CallContext&>::value) );
788 typedef std::auto_ptr<Ghost> GhostPtr;
791 explicit Ghost(const std::string& name):
792 GhostMetadata( name )
794 _ghost_type.destroy = &destroyGhost;
795 _ghost_type.name = _name.c_str();
796 _ghost_type.get_member = &getMember;
797 _ghost_type.set_member = &setMember;
800 static GhostPtr& getSingletonHolder()
802 static GhostPtr instance;
806 static naRef makeGhost(naContext c, void *ptr)
810 // We are wrapping shared pointers to already existing objects which
811 // will then be hold be a new shared pointer. We therefore have to
812 // check for the dynamic type of the object as it might differ from
813 // the passed static type.
814 naGhostType* ghost_type = getTypeFor<Ghost>( getRawPtr(ptr) );
817 return naNewGhost2(c, ghost_type, ptr);
824 static void destroyGhost(void *ptr)
826 delete static_cast<pointer*>(ptr);
830 * Callback for retrieving a ghost member.
832 static const char* getMember(naContext c, void* g, naRef key, naRef* out)
834 const std::string key_str = nasal::from_nasal<std::string>(c, key);
835 if( key_str == "parents" )
837 if( getSingletonPtr()->_parents.empty() )
840 *out = getSingletonPtr()->getParents(c);
844 typename MemberMap::iterator member =
845 getSingletonPtr()->_members.find(key_str);
847 if( member == getSingletonPtr()->_members.end() )
850 if( member->second.func )
851 *out = member->second.func->get_naRef(c);
852 else if( !member->second.getter.empty() )
853 *out = member->second.getter(c, *getRawPtr(g));
855 return "Read-protected member";
861 * Callback for writing to a ghost member.
863 static void setMember(naContext c, void* g, naRef field, naRef val)
865 const std::string key = nasal::from_nasal<std::string>(c, field);
866 typename MemberMap::iterator member =
867 getSingletonPtr()->_members.find(key);
869 if( member == getSingletonPtr()->_members.end() )
870 naRuntimeError(c, "ghost: No such member: %s", key.c_str());
871 else if( member->second.setter.empty() )
872 naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
873 else if( member->second.func )
874 naRuntimeError(c, "ghost: Write to function: %s", key.c_str());
876 member->second.setter(c, *getRawPtr(g), val);
883 * Convert every shared pointer to a ghost.
885 // Needs to be outside any namespace to mark ADL work
887 typename boost::enable_if<
888 nasal::internal::has_element_type<
889 typename nasal::internal::reduced_type<T>::type
893 to_nasal_helper(naContext c, T ptr)
895 return nasal::Ghost<T>::create(c, ptr);
899 * Convert nasal ghosts/hashes to shared pointer (of a ghost)
902 typename boost::enable_if<
903 nasal::internal::has_element_type<
904 typename nasal::internal::reduced_type<T>::type
908 from_nasal_helper(naContext c, naRef ref, const T*)
910 return nasal::Ghost<T>::fromNasal(c, ref);
913 #endif /* SG_NASAL_GHOST_HXX_ */