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/preprocessor/iteration/iterate.hpp>
34 #include <boost/shared_ptr.hpp>
35 #include <boost/utility/enable_if.hpp>
40 * Bindings between C++ and the Nasal scripting language
48 * Metadata for Ghost object types
54 * Add a nasal base class to the ghost. Will be available in the ghosts
57 void addNasalBase(const naRef& parent)
59 assert( naIsHash(parent) );
60 _parents.push_back(parent);
63 bool isBaseOf(naGhostType* ghost_type) const
65 if( ghost_type == &_ghost_type )
68 for( DerivedList::const_iterator derived = _derived_classes.begin();
69 derived != _derived_classes.end();
72 if( (*derived)->isBaseOf(ghost_type) )
81 typedef std::vector<const GhostMetadata*> DerivedList;
83 const std::string _name;
84 naGhostType _ghost_type;
85 DerivedList _derived_classes;
86 std::vector<naRef> _parents;
88 explicit GhostMetadata(const std::string& name):
94 void addDerived(const GhostMetadata* derived)
97 _derived_classes.push_back(derived);
103 "Ghost::addDerived: " <<_ghost_type.name << " -> " << derived->_name
107 naRef getParents(naContext c)
109 return nasal::to_nasal(c, _parents);
114 * Hold callable method and convert to Nasal function if required.
119 virtual ~MethodHolder() {}
120 virtual naRef get_naRef(naContext c) = 0;
123 BOOST_MPL_HAS_XXX_TRAIT_DEF(element_type)
127 * Context passed to a function/method being called from Nasal
131 CallContext(naContext c, size_t argc, naRef* args):
138 * Get the argument with given index if it exists. Otherwise returns the
139 * passed default value.
141 * @tparam T Type of argument (converted using ::from_nasal)
142 * @param index Index of requested argument
143 * @param def Default value returned if too few arguments available
146 typename from_nasal_ptr<T>::return_type
147 getArg(size_t index, const T& def = T()) const
152 return (*from_nasal_ptr<T>::get())(c, args[index]);
156 * Get the argument with given index. Raises a Nasal runtime error if there
157 * are to few arguments available.
160 typename from_nasal_ptr<T>::return_type
161 requireArg(size_t index) const
164 naRuntimeError(c, "Missing required arg #%d", index);
166 return (*from_nasal_ptr<T>::get())(c, args[index]);
170 naRef to_nasal(T arg) const
172 return nasal::to_nasal(c, arg);
181 * Class for exposing C++ objects to Nasal
184 * // Example class to be exposed to Nasal
192 * void doSomethingElse(const nasal::CallContext& ctx);
194 * typedef boost::shared_ptr<MyClass> MyClassPtr;
196 * std::string myOtherFreeMember(int num);
198 * void exposeClasses()
200 * // Register a nasal ghost type for MyClass. This needs to be done only
201 * // once before creating the first ghost instance. The exposed class needs
202 * // to be wrapped inside a shared pointer, eg. boost::shared_ptr.
203 * Ghost<MyClassPtr>::init("MyClass")
204 * // Members can be exposed by getters and setters
205 * .member("x", &MyClass::getX, &MyClass::setX)
206 * // For readonly variables only pass a getter
207 * .member("x_readonly", &MyClass::getX)
208 * // It is also possible to expose writeonly members
209 * .member("x_writeonly", &MyClass::setX)
210 * // Methods can be nearly anything callable and accepting a reference
211 * // to an instance of the class type. (member functions, free functions
212 * // and anything else bindable using boost::function and boost::bind)
213 * .method("myMember", &MyClass::myMember)
214 * .method("doSomething", &MyClass::doSomethingElse)
215 * .method("other", &myOtherFreeMember);
221 public internal::GhostMetadata
223 BOOST_STATIC_ASSERT( internal::has_element_type<T>::value );
226 typedef typename T::element_type raw_type;
228 typedef naRef (raw_type::*member_func_t)(const CallContext&);
229 typedef naRef (*free_func_t)(raw_type&, const CallContext&);
230 typedef boost::function<naRef(naContext, raw_type&)> getter_t;
231 typedef boost::function<void(naContext, raw_type&, naRef)> setter_t;
232 typedef boost::function<naRef(raw_type&, const CallContext&)> method_t;
233 typedef boost::shared_ptr<internal::MethodHolder> MethodHolderPtr;
236 public internal::MethodHolder
243 explicit MethodHolder(const method_t& method):
248 virtual naRef get_naRef(naContext c)
250 if( naIsNil(_naRef) )
252 _naRef = naNewFunc(c, naNewCCodeU(c, &MethodHolder::call, this));
262 static naRef call( naContext c,
268 MethodHolder* holder = static_cast<MethodHolder*>(user_data);
270 naRuntimeError(c, "invalid method holder!");
272 return holder->_method
274 requireObject(c, me),
275 CallContext(c, argc, args)
281 * A ghost member. Can consist either of getter and/or setter functions
282 * for exposing a data variable or a single callable function.
289 member_t( const getter_t& getter,
290 const setter_t& setter,
291 const MethodHolderPtr& func = MethodHolderPtr() ):
297 explicit member_t(const MethodHolderPtr& func):
303 MethodHolderPtr func;
306 typedef std::map<std::string, member_t> MemberMap;
309 * Register a new ghost type.
311 * @note Only intialize each ghost type once!
313 * @param name Descriptive name of the ghost type.
315 static Ghost& init(const std::string& name)
317 assert( !getSingletonPtr() );
319 getSingletonHolder().reset( new Ghost(name) );
320 return *getSingletonPtr();
324 * Register a base class for this ghost. The base class needs to be
325 * registers on its own before it can be used as base class.
327 * @tparam BaseGhost Type of base class already wrapped into Ghost class
331 * Ghost<MyBasePtr>::init("MyBase");
332 * Ghost<MyClassPtr>::init("MyClass")
333 * .bases<Ghost<MyBasePtr> >();
336 template<class BaseGhost>
337 typename boost::enable_if
339 boost::is_base_of<GhostMetadata, BaseGhost>,
346 boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value
349 BaseGhost* base = BaseGhost::getSingletonPtr();
353 // Both ways of retrieving the address of a static member function
354 // should be legal but not all compilers know this.
355 // g++-4.4.7+ has been tested to work with both versions
356 #if defined(GCC_VERSION) && GCC_VERSION < 40407
357 // The old version of g++ used on Jenkins (16.11.2012) only compiles
359 &getTypeFor<BaseGhost>
361 // VS (2008, 2010, ... ?) only allow this version.
362 &Ghost::getTypeFor<BaseGhost>
366 // Replace any getter that is not available in the current class.
367 // TODO check if this is the correct behavior of function overriding
368 for( typename BaseGhost::MemberMap::const_iterator member =
369 base->_members.begin();
370 member != base->_members.end();
373 if( _members.find(member->first) == _members.end() )
374 _members[member->first] = member_t
376 member->second.getter,
377 member->second.setter,
386 * Register a base class for this ghost. The base class needs to be
387 * registers on its own before it can be used as base class.
389 * @tparam Base Type of base class (Base as used in Ghost<BasePtr>)
392 * Ghost<MyBasePtr>::init("MyBase");
393 * Ghost<MyClassPtr>::init("MyClass")
394 * .bases<MyBasePtr>();
398 typename boost::disable_if
400 boost::is_base_of<GhostMetadata, Base>,
407 boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value
410 return bases< Ghost<Base> >();
414 * Register an existing Nasal class/hash as base class for this ghost.
416 * @param parent Nasal hash/class
418 Ghost& bases(const naRef& parent)
420 addNasalBase(parent);
425 * Register a member variable by passing a getter and/or setter method.
427 * @param field Name of member
428 * @param getter Getter for variable
429 * @param setter Setter for variable (Pass 0 to prevent write access)
432 template<class Ret, class Param>
433 Ghost& member( const std::string& field,
434 Ret (raw_type::*getter)() const,
435 void (raw_type::*setter)(Param) )
437 return member(field, to_getter(getter), to_setter(setter));
441 * Register a read only member variable.
443 * @param field Name of member
444 * @param getter Getter for variable
447 Ghost& member( const std::string& field,
448 Ret (raw_type::*getter)() const )
450 return member(field, to_getter(getter), setter_t());
454 * Register a write only member variable.
456 * @param field Name of member
457 * @param setter Setter for variable
460 Ghost& member( const std::string& field,
461 void (raw_type::*setter)(Var) )
463 return member(field, getter_t(), to_setter(setter));
467 * Register a member variable by passing a getter and/or setter method.
469 * @param field Name of member
470 * @param getter Getter for variable
471 * @param setter Setter for variable (Pass empty to prevent write access)
474 Ghost& member( const std::string& field,
475 const getter_t& getter,
476 const setter_t& setter = setter_t() )
478 if( !getter.empty() || !setter.empty() )
479 _members[field] = member_t(getter, setter);
485 "Member '" << field << "' requires a getter or setter"
491 * Register anything that accepts an object instance and a
492 * nasal::CallContext and returns naRef as method.
498 * naRef myMethod(const nasal::CallContext& ctx);
501 * Ghost<MyClassPtr>::init("Test")
502 * .method("myMethod", &MyClass::myMethod);
505 Ghost& method(const std::string& name, const method_t& func)
507 _members[name].func.reset( new MethodHolder(func) );
512 * Register anything that accepts an object instance and a
513 * nasal::CallContext whith automatic conversion of the return type to
518 * void doIt(const MyClass& c, const nasal::CallContext& ctx);
520 * Ghost<MyClassPtr>::init("Test")
521 * .method("doIt", &doIt);
527 const std::string& name,
528 const boost::function<Ret (raw_type&, const CallContext&)>& func
531 return method(name, boost::bind(method_invoker<Ret>, func, _1, _2));
534 #define BOOST_PP_ITERATION_LIMITS (0, 9)
535 #define BOOST_PP_FILENAME_1 <simgear/nasal/cppbind/detail/functor_templates.hxx>
536 #include BOOST_PP_ITERATE()
538 // TODO use variadic template when supporting C++11
539 // TODO check if default constructor exists
540 // static naRef create( naContext c )
542 // return makeGhost(c, createInstance());
546 * Create a Nasal instance of this ghost.
548 * @param c Active Nasal context
549 * @param a1 Parameter used for creating new instance
552 static naRef create( naContext c, const A1& a1 )
554 return makeGhost(c, createInstance(a1));
558 * Nasal callback for creating a new instance of this ghost.
560 static naRef f_create(naContext c, naRef me, int argc, naRef* args)
565 static bool isBaseOf(naGhostType* ghost_type)
570 return getSingletonPtr()->GhostMetadata::isBaseOf(ghost_type);
573 static bool isBaseOf(naRef obj)
575 return isBaseOf( naGhost_type(obj) );
579 * Convert Nasal object to C++ object. To get a valid object the passed
580 * Nasal objects has to be derived class of the target class (Either
581 * derived in C++ or in Nasal using a 'parents' vector)
583 static pointer fromNasal(naContext c, naRef me)
585 // Check if it's a ghost and if it can be converted
586 if( isBaseOf( naGhost_type(me) ) )
587 return getPtr( naGhost_ptr(me) );
589 // Now if it is derived from a ghost (hash with ghost in parent vector)
590 else if( naIsHash(me) )
592 naRef na_parents = naHash_cget(me, const_cast<char*>("parents"));
593 if( !naIsVector(na_parents) )
595 SG_LOG(SG_NASAL, SG_DEBUG, "Missing 'parents' vector for ghost");
599 typedef std::vector<naRef> naRefs;
600 naRefs parents = from_nasal<naRefs>(c, na_parents);
601 for( naRefs::const_iterator parent = parents.begin();
602 parent != parents.end();
605 pointer ptr = fromNasal(c, *parent);
619 typedef naGhostType* (*type_checker_t)(const raw_type*);
620 typedef std::vector<type_checker_t> DerivedList;
621 DerivedList _derived_types;
624 * Create a shared pointer on the heap to handle the reference counting
625 * for the passed shared pointer while it is used in Nasal space.
627 static pointer* createInstance(const pointer& ptr)
629 return ptr ? new pointer(ptr) : 0;
632 static pointer getPtr(void* ptr)
635 return *static_cast<pointer*>(ptr);
640 static raw_type* getRawPtr(void* ptr)
643 return static_cast<pointer*>(ptr)->get();
648 static raw_type* getRawPtr(const pointer& ptr)
653 void addDerived( const internal::GhostMetadata* derived_meta,
654 const type_checker_t& derived_info )
656 GhostMetadata::addDerived(derived_meta);
657 _derived_types.push_back(derived_info);
660 template<class BaseGhost>
662 typename boost::enable_if
663 < boost::is_polymorphic<typename BaseGhost::raw_type>,
666 getTypeFor(const typename BaseGhost::raw_type* base)
668 // Check first if passed pointer can by converted to instance of class
671 < typename BaseGhost::raw_type,
672 typename Ghost::raw_type
674 && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
677 // Now check if we can further downcast to one of our derived classes.
678 for( typename DerivedList::reverse_iterator
679 derived = getSingletonPtr()->_derived_types.rbegin();
680 derived != getSingletonPtr()->_derived_types.rend();
683 naGhostType* ghost_type =
684 (*derived)( static_cast<const typename Ghost::raw_type*>(base) );
689 // If base is not an instance of any derived class, this class has to
690 // be the dynamic type.
691 return &getSingletonPtr()->_ghost_type;
694 template<class BaseGhost>
696 typename boost::disable_if
697 < boost::is_polymorphic<typename BaseGhost::raw_type>,
700 getTypeFor(const typename BaseGhost::raw_type* base)
702 // For non polymorphic classes there is no possibility to get the actual
703 // dynamic type, therefore we can only use its static type.
704 return &BaseGhost::getSingletonPtr()->_ghost_type;
707 static Ghost* getSingletonPtr()
709 return getSingletonHolder().get();
712 static raw_type& requireObject(naContext c, naRef me)
714 raw_type* obj = getRawPtr( fromNasal(c, me) );
715 naGhostType* ghost_type = naGhost_type(me);
721 "method called on object of wrong type: is '%s' expected '%s'",
722 ghost_type ? ghost_type->name : "unknown",
723 getSingletonPtr()->_ghost_type.name
730 getter_t to_getter(Ret (raw_type::*getter)() const)
732 typedef typename boost::call_traits<Ret>::param_type param_type;
733 naRef(*to_nasal_)(naContext, param_type) = &to_nasal;
735 // Getter signature: naRef(naContext, raw_type&)
740 boost::bind(getter, _2)
744 template<class Param>
745 setter_t to_setter(void (raw_type::*setter)(Param))
747 // Setter signature: void(naContext, raw_type&, naRef)
752 boost::bind(from_nasal_ptr<Param>::get(), _1, _3)
758 * Invoke a method which returns a value and convert it to Nasal.
762 typename boost::disable_if<boost::is_void<Ret>, naRef>::type
765 const boost::function<Ret (raw_type&, const CallContext&)>& func,
767 const CallContext& ctx
770 return (*to_nasal_ptr<Ret>::get())(ctx.c, func(obj, ctx));
774 * Invoke a method which returns void and "convert" it to nil.
778 typename boost::enable_if<boost::is_void<Ret>, naRef>::type
781 const boost::function<Ret (raw_type&, const CallContext&)>& func,
783 const CallContext& ctx
791 * Extract argument by index from nasal::CallContext and convert to given
796 typename boost::disable_if<
797 boost::is_same<Arg, const CallContext&>,
798 typename from_nasal_ptr<Arg>::return_type
800 arg_from_nasal(const CallContext& ctx, size_t index)
802 return ctx.requireArg<Arg>(index);
806 * Specialization to pass through nasal::CallContext.
810 typename boost::enable_if<
811 boost::is_same<Arg, const CallContext&>,
812 typename from_nasal_ptr<Arg>::return_type
814 arg_from_nasal(const CallContext& ctx, size_t)
819 typedef std::auto_ptr<Ghost> GhostPtr;
822 explicit Ghost(const std::string& name):
823 GhostMetadata( name )
825 _ghost_type.destroy = &destroyGhost;
826 _ghost_type.name = _name.c_str();
827 _ghost_type.get_member = &getMember;
828 _ghost_type.set_member = &setMember;
831 static GhostPtr& getSingletonHolder()
833 static GhostPtr instance;
837 static naRef makeGhost(naContext c, void *ptr)
841 // We are wrapping shared pointers to already existing objects which
842 // will then be hold be a new shared pointer. We therefore have to
843 // check for the dynamic type of the object as it might differ from
844 // the passed static type.
845 naGhostType* ghost_type = getTypeFor<Ghost>( getRawPtr(ptr) );
848 return naNewGhost2(c, ghost_type, ptr);
855 static void destroyGhost(void *ptr)
857 delete static_cast<pointer*>(ptr);
861 * Callback for retrieving a ghost member.
863 static const char* getMember(naContext c, void* g, naRef key, naRef* out)
865 const std::string key_str = nasal::from_nasal<std::string>(c, key);
866 if( key_str == "parents" )
868 if( getSingletonPtr()->_parents.empty() )
871 *out = getSingletonPtr()->getParents(c);
875 typename MemberMap::iterator member =
876 getSingletonPtr()->_members.find(key_str);
878 if( member == getSingletonPtr()->_members.end() )
881 if( member->second.func )
882 *out = member->second.func->get_naRef(c);
883 else if( !member->second.getter.empty() )
884 *out = member->second.getter(c, *getRawPtr(g));
886 return "Read-protected member";
892 * Callback for writing to a ghost member.
894 static void setMember(naContext c, void* g, naRef field, naRef val)
896 const std::string key = nasal::from_nasal<std::string>(c, field);
897 typename MemberMap::iterator member =
898 getSingletonPtr()->_members.find(key);
900 if( member == getSingletonPtr()->_members.end() )
901 naRuntimeError(c, "ghost: No such member: %s", key.c_str());
902 else if( member->second.setter.empty() )
903 naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
904 else if( member->second.func )
905 naRuntimeError(c, "ghost: Write to function: %s", key.c_str());
907 member->second.setter(c, *getRawPtr(g), val);
913 #endif /* SG_NASAL_GHOST_HXX_ */