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 "from_nasal.hxx"
24 #include "to_nasal.hxx"
26 #include <simgear/debug/logstream.hxx>
28 #include <boost/bind.hpp>
29 #include <boost/call_traits.hpp>
30 #include <boost/function.hpp>
31 #include <boost/lambda/lambda.hpp>
32 #include <boost/mpl/has_xxx.hpp>
33 #include <boost/utility/enable_if.hpp>
38 * Bindings between C++ and the Nasal scripting language
46 * Metadata for Ghost object types
52 * Add a nasal base class to the ghost. Will be available in the ghosts
55 void addNasalBase(const naRef& parent)
57 assert( naIsHash(parent) );
58 _parents.push_back(parent);
61 bool isBaseOf(naGhostType* ghost_type) const
63 if( ghost_type == &_ghost_type )
66 for( DerivedList::const_iterator derived = _derived_classes.begin();
67 derived != _derived_classes.end();
70 if( (*derived)->isBaseOf(ghost_type) )
79 typedef std::vector<const GhostMetadata*> DerivedList;
81 const std::string _name;
82 naGhostType _ghost_type;
83 DerivedList _derived_classes;
84 std::vector<naRef> _parents;
86 explicit GhostMetadata(const std::string& name):
92 void addDerived(const GhostMetadata* derived)
95 _derived_classes.push_back(derived);
101 "Ghost::addDerived: " <<_ghost_type.name << " -> " << derived->_name
105 naRef getParents(naContext c)
107 return nasal::to_nasal(c, _parents);
111 BOOST_MPL_HAS_XXX_TRAIT_DEF(element_type)
115 * Context passed to a function/method being called from Nasal
119 CallContext(naContext c, size_t argc, naRef* args):
126 * Get the argument with given index if it exists. Otherwise returns the
127 * passed default value.
129 * @tparam T Type of argument (converted using ::from_nasal)
130 * @param index Index of requested argument
131 * @param def Default value returned if too few arguments available
134 T getArg(size_t index, const T& def = T()) const
139 return from_nasal<T>(c, args[index]);
143 * Get the argument with given index. Raises a Nasal runtime error if there
144 * are to few arguments available.
147 T requireArg(size_t index) const
150 naRuntimeError(c, "Missing required arg #%d", index);
152 return from_nasal<T>(c, args[index]);
161 * Class for exposing C++ objects to Nasal
164 * // Example class to be exposed to Nasal
171 * naRef myMember(naContext c, int argc, naRef* args);
173 * typedef boost::shared_ptr<MyClass> MyClassPtr;
175 * void exposeClasses()
177 * // Register a nasal ghost type for MyClass. This needs to be done only
178 * // once before creating the first ghost instance. The exposed class needs
179 * // to be wrapped inside a shared pointer, eg. boost::shared_ptr.
180 * Ghost<MyClassPtr>::init("MyClass")
181 * // Members can be exposed by getters and setters
182 * .member("x", &MyClass::getX, &MyClass::setX)
183 * // For readonly variables only pass a getter
184 * .member("x_readonly", &MyClass::getX)
185 * // It is also possible to expose writeonly members
186 * .member("x_writeonly", &MyClass::setX)
187 * // Methods use a slightly different syntax - The pointer to the member
188 * // function has to be passed as template argument
189 * .method<&MyClass::myMember>("myMember");
195 public internal::GhostMetadata
197 BOOST_STATIC_ASSERT( internal::has_element_type<T>::value );
200 typedef typename T::element_type raw_type;
202 typedef naRef (raw_type::*member_func_t)(const CallContext&);
203 typedef naRef (*free_func_t)(raw_type&, const CallContext&);
204 typedef boost::function<naRef(naContext, raw_type&)> getter_t;
205 typedef boost::function<void(naContext, raw_type&, naRef)> setter_t;
206 typedef boost::function<naRef(raw_type&, const CallContext&)> method_t;
207 typedef boost::shared_ptr<method_t> method_ptr;
210 * A ghost member. Can consist either of getter and/or setter functions
211 * for exposing a data variable or a single callable function.
219 member_t( const getter_t& getter,
220 const setter_t& setter,
221 naCFunction func = 0 ):
227 member_t(naCFunction func):
236 typedef std::map<std::string, member_t> MemberMap;
239 * Register a new ghost type.
241 * @note Only intialize each ghost type once!
243 * @param name Descriptive name of the ghost type.
245 static Ghost& init(const std::string& name)
247 assert( !getSingletonPtr() );
249 getSingletonHolder().reset( new Ghost(name) );
250 return *getSingletonPtr();
254 * Register a base class for this ghost. The base class needs to be
255 * registers on its own before it can be used as base class.
257 * @tparam BaseGhost Type of base class already wrapped into Ghost class
261 * Ghost<MyBasePtr>::init("MyBase");
262 * Ghost<MyClassPtr>::init("MyClass")
263 * .bases<Ghost<MyBasePtr> >();
266 template<class BaseGhost>
267 typename boost::enable_if
269 boost::is_base_of<GhostMetadata, BaseGhost>,
276 boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value
279 BaseGhost* base = BaseGhost::getSingletonPtr();
283 // Both ways of retrieving the address of a static member function
284 // should be legal but not all compilers know this.
285 // g++-4.4.7+ has been tested to work with both versions
286 #if defined(GCC_VERSION) && GCC_VERSION < 40407
287 // The old version of g++ used on Jenkins (16.11.2012) only compiles
289 &getTypeFor<BaseGhost>
291 // VS (2008, 2010, ... ?) only allow this version.
292 &Ghost::getTypeFor<BaseGhost>
296 // Replace any getter that is not available in the current class.
297 // TODO check if this is the correct behavior of function overriding
298 for( typename BaseGhost::MemberMap::const_iterator member =
299 base->_members.begin();
300 member != base->_members.end();
303 if( _members.find(member->first) == _members.end() )
304 _members[member->first] = member_t
306 member->second.getter,
307 member->second.setter,
316 * Register a base class for this ghost. The base class needs to be
317 * registers on its own before it can be used as base class.
319 * @tparam Base Type of base class (Base as used in Ghost<BasePtr>)
322 * Ghost<MyBasePtr>::init("MyBase");
323 * Ghost<MyClassPtr>::init("MyClass")
324 * .bases<MyBasePtr>();
328 typename boost::disable_if
330 boost::is_base_of<GhostMetadata, Base>,
337 boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value
340 return bases< Ghost<Base> >();
344 * Register an existing Nasal class/hash as base class for this ghost.
346 * @param parent Nasal hash/class
348 Ghost& bases(const naRef& parent)
350 addNasalBase(parent);
355 * Register a member variable by passing a getter and/or setter method.
357 * @param field Name of member
358 * @param getter Getter for variable
359 * @param setter Setter for variable (Pass 0 to prevent write access)
362 template<class Ret, class Param>
363 Ghost& member( const std::string& field,
364 Ret (raw_type::*getter)() const,
365 void (raw_type::*setter)(Param) )
370 typedef typename boost::call_traits<Ret>::param_type param_type;
371 naRef (*to_nasal_)(naContext, param_type) = &nasal::to_nasal;
373 // Getter signature: naRef(naContext, raw_type&)
374 m.getter = boost::bind(to_nasal_, _1, boost::bind(getter, _2));
379 typename boost::remove_const
380 < typename boost::remove_reference<Param>::type
382 (*from_nasal_)(naContext, naRef) = &nasal::from_nasal;
384 // Setter signature: void(naContext, raw_type&, naRef)
385 m.setter = boost::bind(setter, _2, boost::bind(from_nasal_, _1, _3));
388 return member(field, m.getter, m.setter);
392 * Register a read only member variable.
394 * @param field Name of member
395 * @param getter Getter for variable
398 Ghost& member( const std::string& field,
399 Ret (raw_type::*getter)() const )
401 return member<Ret, Ret>(field, getter, 0);
405 * Register a write only member variable.
407 * @param field Name of member
408 * @param setter Setter for variable
411 Ghost& member( const std::string& field,
412 void (raw_type::*setter)(Var) )
414 return member<Var, Var>(field, 0, setter);
418 * Register a member variable by passing a getter and/or setter method.
420 * @param field Name of member
421 * @param getter Getter for variable
422 * @param setter Setter for variable (Pass empty to prevent write access)
425 Ghost& member( const std::string& field,
426 const getter_t& getter,
427 const setter_t& setter = setter_t() )
429 if( !getter.empty() || !setter.empty() )
430 _members[field] = member_t(getter, setter);
436 "Member '" << field << "' requires a getter or setter"
442 * Register a member function.
444 * @note Because only function pointers can be registered as Nasal
445 * functions it is needed to pass the function pointer as template
446 * argument. This allows us to create a separate instance of the
447 * MemberFunctionWrapper for each registered function and therefore
448 * provides us with the needed static functions to be passed on to
451 * @tparam func Pointer to member function being registered.
457 * naRef myMethod(naContext c, int argc, naRef* args);
460 * Ghost<MyClassPtr>::init("Test")
461 * .method<&MyClass::myMethod>("myMethod");
464 template<member_func_t func>
465 Ghost& method(const std::string& name)
467 _members[name].func = &MemberFunctionWrapper<func>::call;
472 * Invoke a method which returns a value and convert it to Nasal.
476 typename boost::disable_if<boost::is_void<Ret>, naRef>::type
479 const boost::function<Ret (raw_type&, const CallContext&)>& func,
481 const CallContext& ctx
484 typedef typename boost::call_traits<Ret>::param_type param_type;
485 naRef (*to_nasal_)(naContext, param_type) = &nasal::to_nasal;
487 return to_nasal_(ctx.c, func(obj, ctx));
491 * Invoke a method which returns void and "convert" it to nil.
495 typename boost::enable_if<boost::is_void<Ret>, naRef>::type
498 const boost::function<void (raw_type&, const CallContext&)>& func,
500 const CallContext& ctx
508 * Bind any callable entity as method callable from Nasal
510 * Does not really register method yet!!!
515 const std::string& name,
516 const boost::function<Ret (raw_type&, const CallContext&)>& func
519 // _members[name].func.reset
521 new method_t( boost::bind(method_invoker<Ret>, func, _1, _2) );
529 typedef boost::function<Ret (raw_type&, const CallContext&)> type;
533 * Bind member function as method callable from Nasal
535 * Does not really register method yet!!!
538 Ghost& method( const std::string& name,
539 Ret (raw_type::*fn)() const )
544 typename method_raw<Ret>::type(boost::bind(fn, _1))
549 * Register a free function as member function. The object instance is
550 * passed as additional first argument.
552 * @tparam func Pointer to free function being registered.
554 * @note Due to a severe bug in Visual Studio it is not possible to create
555 * a specialization of #method for free function pointers and
556 * member function pointers at the same time. Do overcome this
557 * limitation we had to use a different name for this function.
561 * naRef myMethod(MyClass& obj, naContext c, int argc, naRef* args);
563 * Ghost<MyClassPtr>::init("Test")
564 * .method_func<&myMethod>("myMethod");
567 template<free_func_t func>
568 Ghost& method_func(const std::string& name)
570 _members[name].func = &FreeFunctionWrapper<func>::call;
574 // TODO use variadic template when supporting C++11
576 * Create a Nasal instance of this ghost.
578 * @param c Active Nasal context
580 // TODO check if default constructor exists
581 // static naRef create( naContext c )
583 // return makeGhost(c, createInstance());
587 * Create a Nasal instance of this ghost.
589 * @param c Active Nasal context
590 * @param a1 Parameter used for creating new instance
593 static naRef create( naContext c, const A1& a1 )
595 return makeGhost(c, createInstance(a1));
599 * Nasal callback for creating a new instance of this ghost.
601 static naRef f_create(naContext c, naRef me, int argc, naRef* args)
606 static bool isBaseOf(naGhostType* ghost_type)
611 return getSingletonPtr()->GhostMetadata::isBaseOf(ghost_type);
614 static bool isBaseOf(naRef obj)
616 return isBaseOf( naGhost_type(obj) );
620 * Convert Nasal object to C++ object. To get a valid object the passed
621 * Nasal objects has to be derived class of the target class (Either
622 * derived in C++ or in Nasal using a 'parents' vector)
624 static pointer fromNasal(naContext c, naRef me)
626 // Check if it's a ghost and if it can be converted
627 if( isBaseOf( naGhost_type(me) ) )
628 return getPtr( naGhost_ptr(me) );
630 // Now if it is derived from a ghost (hash with ghost in parent vector)
631 else if( naIsHash(me) )
633 naRef na_parents = naHash_cget(me, const_cast<char*>("parents"));
634 if( !naIsVector(na_parents) )
636 SG_LOG(SG_NASAL, SG_DEBUG, "Missing 'parents' vector for ghost");
640 typedef std::vector<naRef> naRefs;
641 naRefs parents = from_nasal<naRefs>(c, na_parents);
642 for( naRefs::const_iterator parent = parents.begin();
643 parent != parents.end();
646 pointer ptr = fromNasal(c, *parent);
660 typedef naGhostType* (*type_checker_t)(const raw_type*);
661 typedef std::vector<type_checker_t> DerivedList;
662 DerivedList _derived_types;
665 * Create a shared pointer on the heap to handle the reference counting
666 * for the passed shared pointer while it is used in Nasal space.
668 static pointer* createInstance(const pointer& ptr)
670 return ptr ? new pointer(ptr) : 0;
673 static pointer getPtr(void* ptr)
676 return *static_cast<pointer*>(ptr);
681 static raw_type* getRawPtr(void* ptr)
684 return static_cast<pointer*>(ptr)->get();
689 static raw_type* getRawPtr(const pointer& ptr)
694 void addDerived( const internal::GhostMetadata* derived_meta,
695 const type_checker_t& derived_info )
697 GhostMetadata::addDerived(derived_meta);
698 _derived_types.push_back(derived_info);
701 template<class BaseGhost>
703 typename boost::enable_if
704 < boost::is_polymorphic<typename BaseGhost::raw_type>,
707 getTypeFor(const typename BaseGhost::raw_type* base)
709 // Check first if passed pointer can by converted to instance of class
712 < typename BaseGhost::raw_type,
713 typename Ghost::raw_type
715 && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
718 // Now check if we can further downcast to one of our derived classes.
719 for( typename DerivedList::reverse_iterator
720 derived = getSingletonPtr()->_derived_types.rbegin();
721 derived != getSingletonPtr()->_derived_types.rend();
724 naGhostType* ghost_type =
725 (*derived)( static_cast<const typename Ghost::raw_type*>(base) );
730 // If base is not an instance of any derived class, this class has to
731 // be the dynamic type.
732 return &getSingletonPtr()->_ghost_type;
735 template<class BaseGhost>
737 typename boost::disable_if
738 < boost::is_polymorphic<typename BaseGhost::raw_type>,
741 getTypeFor(const typename BaseGhost::raw_type* base)
743 // For non polymorphic classes there is no possibility to get the actual
744 // dynamic type, therefore we can only use its static type.
745 return &BaseGhost::getSingletonPtr()->_ghost_type;
748 static Ghost* getSingletonPtr()
750 return getSingletonHolder().get();
753 static raw_type& requireObject(naContext c, naRef me)
755 raw_type* obj = getRawPtr( fromNasal(c, me) );
756 naGhostType* ghost_type = naGhost_type(me);
762 "method called on object of wrong type: is '%s' expected '%s'",
763 ghost_type ? ghost_type->name : "unknown",
764 getSingletonPtr()->_ghost_type.name
771 * Wrapper class to enable registering pointers to member functions as
772 * Nasal function callbacks. We need to use the function pointer as
773 * template parameter to ensure every registered function gets a static
774 * function which can be passed to Nasal.
776 template<member_func_t func>
777 struct MemberFunctionWrapper
780 * Called from Nasal upon invocation of the according registered
781 * function. Forwards the call to the passed object instance.
783 static naRef call(naContext c, naRef me, int argc, naRef* args)
785 return (requireObject(c, me).*func)(CallContext(c, argc, args));
790 * Wrapper class to enable registering pointers to free functions (only
791 * external linkage). We need to use the function pointer as template
792 * parameter to ensure every registered function gets a static function
793 * which can be passed to Nasal. Even though we just wrap another simple
794 * function pointer this intermediate step is need to be able to retrieve
795 * the object the function call belongs to and pass it along as argument.
797 template<free_func_t func>
798 struct FreeFunctionWrapper
801 * Called from Nasal upon invocation of the according registered
802 * function. Forwards the call to the passed function pointer and passes
803 * the required parameters.
805 static naRef call(naContext c, naRef me, int argc, naRef* args)
807 return func(requireObject(c, me), CallContext(c, argc, args));
811 typedef std::auto_ptr<Ghost> GhostPtr;
814 explicit Ghost(const std::string& name):
815 GhostMetadata( name )
817 _ghost_type.destroy = &destroyGhost;
818 _ghost_type.name = _name.c_str();
819 _ghost_type.get_member = &getMember;
820 _ghost_type.set_member = &setMember;
823 static GhostPtr& getSingletonHolder()
825 static GhostPtr instance;
829 static naRef makeGhost(naContext c, void *ptr)
833 // We are wrapping shared pointers to already existing objects which
834 // will then be hold be a new shared pointer. We therefore have to
835 // check for the dynamic type of the object as it might differ from
836 // the passed static type.
837 naGhostType* ghost_type = getTypeFor<Ghost>( getRawPtr(ptr) );
840 return naNewGhost2(c, ghost_type, ptr);
847 static void destroyGhost(void *ptr)
849 delete static_cast<pointer*>(ptr);
853 * Callback for retrieving a ghost member.
855 static const char* getMember(naContext c, void* g, naRef key, naRef* out)
857 const std::string key_str = nasal::from_nasal<std::string>(c, key);
858 if( key_str == "parents" )
860 if( getSingletonPtr()->_parents.empty() )
863 *out = getSingletonPtr()->getParents(c);
867 typename MemberMap::iterator member =
868 getSingletonPtr()->_members.find(key_str);
870 if( member == getSingletonPtr()->_members.end() )
873 if( member->second.func )
874 *out = nasal::to_nasal(c, member->second.func);
875 else if( !member->second.getter.empty() )
876 *out = member->second.getter(c, *getRawPtr(g));
878 return "Read-protected member";
884 * Callback for writing to a ghost member.
886 static void setMember(naContext c, void* g, naRef field, naRef val)
888 const std::string key = nasal::from_nasal<std::string>(c, field);
889 typename MemberMap::iterator member =
890 getSingletonPtr()->_members.find(key);
892 if( member == getSingletonPtr()->_members.end() )
893 naRuntimeError(c, "ghost: No such member: %s", key.c_str());
894 if( member->second.setter.empty() )
895 naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
897 member->second.setter(c, *getRawPtr(g), val);
903 #endif /* SG_NASAL_GHOST_HXX_ */