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]);
175 * Class for exposing C++ objects to Nasal
178 * // Example class to be exposed to Nasal
186 * void doSomethingElse(const nasal::CallContext& ctx);
188 * typedef boost::shared_ptr<MyClass> MyClassPtr;
190 * std::string myOtherFreeMember(int num);
192 * void exposeClasses()
194 * // Register a nasal ghost type for MyClass. This needs to be done only
195 * // once before creating the first ghost instance. The exposed class needs
196 * // to be wrapped inside a shared pointer, eg. boost::shared_ptr.
197 * Ghost<MyClassPtr>::init("MyClass")
198 * // Members can be exposed by getters and setters
199 * .member("x", &MyClass::getX, &MyClass::setX)
200 * // For readonly variables only pass a getter
201 * .member("x_readonly", &MyClass::getX)
202 * // It is also possible to expose writeonly members
203 * .member("x_writeonly", &MyClass::setX)
204 * // Methods can be nearly anything callable and accepting a reference
205 * // to an instance of the class type. (member functions, free functions
206 * // and anything else bindable using boost::function and boost::bind)
207 * .method("myMember", &MyClass::myMember)
208 * .method("doSomething", &MyClass::doSomethingElse)
209 * .method("other", &myOtherFreeMember);
215 public internal::GhostMetadata
217 BOOST_STATIC_ASSERT( internal::has_element_type<T>::value );
220 typedef typename T::element_type raw_type;
222 typedef naRef (raw_type::*member_func_t)(const CallContext&);
223 typedef naRef (*free_func_t)(raw_type&, const CallContext&);
224 typedef boost::function<naRef(naContext, raw_type&)> getter_t;
225 typedef boost::function<void(naContext, raw_type&, naRef)> setter_t;
226 typedef boost::function<naRef(raw_type&, const CallContext&)> method_t;
227 typedef boost::shared_ptr<internal::MethodHolder> MethodHolderPtr;
230 public internal::MethodHolder
237 explicit MethodHolder(const method_t& method):
242 virtual naRef get_naRef(naContext c)
244 if( naIsNil(_naRef) )
246 _naRef = naNewFunc(c, naNewCCodeU(c, &MethodHolder::call, this));
256 static naRef call( naContext c,
262 MethodHolder* holder = static_cast<MethodHolder*>(user_data);
264 naRuntimeError(c, "invalid method holder!");
266 return holder->_method
268 requireObject(c, me),
269 CallContext(c, argc, args)
275 * A ghost member. Can consist either of getter and/or setter functions
276 * for exposing a data variable or a single callable function.
283 member_t( const getter_t& getter,
284 const setter_t& setter,
285 const MethodHolderPtr& func = MethodHolderPtr() ):
291 explicit member_t(const MethodHolderPtr& func):
297 MethodHolderPtr func;
300 typedef std::map<std::string, member_t> MemberMap;
303 * Register a new ghost type.
305 * @note Only intialize each ghost type once!
307 * @param name Descriptive name of the ghost type.
309 static Ghost& init(const std::string& name)
311 assert( !getSingletonPtr() );
313 getSingletonHolder().reset( new Ghost(name) );
314 return *getSingletonPtr();
318 * Register a base class for this ghost. The base class needs to be
319 * registers on its own before it can be used as base class.
321 * @tparam BaseGhost Type of base class already wrapped into Ghost class
325 * Ghost<MyBasePtr>::init("MyBase");
326 * Ghost<MyClassPtr>::init("MyClass")
327 * .bases<Ghost<MyBasePtr> >();
330 template<class BaseGhost>
331 typename boost::enable_if
333 boost::is_base_of<GhostMetadata, BaseGhost>,
340 boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value
343 BaseGhost* base = BaseGhost::getSingletonPtr();
347 // Both ways of retrieving the address of a static member function
348 // should be legal but not all compilers know this.
349 // g++-4.4.7+ has been tested to work with both versions
350 #if defined(GCC_VERSION) && GCC_VERSION < 40407
351 // The old version of g++ used on Jenkins (16.11.2012) only compiles
353 &getTypeFor<BaseGhost>
355 // VS (2008, 2010, ... ?) only allow this version.
356 &Ghost::getTypeFor<BaseGhost>
360 // Replace any getter that is not available in the current class.
361 // TODO check if this is the correct behavior of function overriding
362 for( typename BaseGhost::MemberMap::const_iterator member =
363 base->_members.begin();
364 member != base->_members.end();
367 if( _members.find(member->first) == _members.end() )
368 _members[member->first] = member_t
370 member->second.getter,
371 member->second.setter,
380 * Register a base class for this ghost. The base class needs to be
381 * registers on its own before it can be used as base class.
383 * @tparam Base Type of base class (Base as used in Ghost<BasePtr>)
386 * Ghost<MyBasePtr>::init("MyBase");
387 * Ghost<MyClassPtr>::init("MyClass")
388 * .bases<MyBasePtr>();
392 typename boost::disable_if
394 boost::is_base_of<GhostMetadata, Base>,
401 boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value
404 return bases< Ghost<Base> >();
408 * Register an existing Nasal class/hash as base class for this ghost.
410 * @param parent Nasal hash/class
412 Ghost& bases(const naRef& parent)
414 addNasalBase(parent);
419 * Register a member variable by passing a getter and/or setter method.
421 * @param field Name of member
422 * @param getter Getter for variable
423 * @param setter Setter for variable (Pass 0 to prevent write access)
426 template<class Ret, class Param>
427 Ghost& member( const std::string& field,
428 Ret (raw_type::*getter)() const,
429 void (raw_type::*setter)(Param) )
434 // Getter signature: naRef(naContext, raw_type&)
435 m.getter = boost::bind
437 to_nasal_ptr<Ret>::get(),
439 boost::bind(getter, _2)
445 // Setter signature: void(naContext, raw_type&, naRef)
446 m.setter = boost::bind
450 boost::bind(from_nasal_ptr<Param>::get(), _1, _3)
454 return member(field, m.getter, m.setter);
458 * Register a read only member variable.
460 * @param field Name of member
461 * @param getter Getter for variable
464 Ghost& member( const std::string& field,
465 Ret (raw_type::*getter)() const )
467 return member<Ret, Ret>(field, getter, 0);
471 * Register a write only member variable.
473 * @param field Name of member
474 * @param setter Setter for variable
477 Ghost& member( const std::string& field,
478 void (raw_type::*setter)(Var) )
480 return member<Var, Var>(field, 0, setter);
484 * Register a member variable by passing a getter and/or setter method.
486 * @param field Name of member
487 * @param getter Getter for variable
488 * @param setter Setter for variable (Pass empty to prevent write access)
491 Ghost& member( const std::string& field,
492 const getter_t& getter,
493 const setter_t& setter = setter_t() )
495 if( !getter.empty() || !setter.empty() )
496 _members[field] = member_t(getter, setter);
502 "Member '" << field << "' requires a getter or setter"
508 * Register anything that accepts an object instance and a
509 * nasal::CallContext and returns naRef as method.
515 * naRef myMethod(const nasal::CallContext& ctx);
518 * Ghost<MyClassPtr>::init("Test")
519 * .method("myMethod", &MyClass::myMethod);
522 Ghost& method(const std::string& name, const method_t& func)
524 _members[name].func.reset( new MethodHolder(func) );
529 * Register anything that accepts an object instance and a
530 * nasal::CallContext whith automatic conversion of the return type to
535 * void doIt(const MyClass& c, const nasal::CallContext& ctx);
537 * Ghost<MyClassPtr>::init("Test")
538 * .method("doIt", &doIt);
544 const std::string& name,
545 const boost::function<Ret (raw_type&, const CallContext&)>& func
548 return method(name, boost::bind(method_invoker<Ret>, func, _1, _2));
551 #define BOOST_PP_ITERATION_LIMITS (0, 9)
552 #define BOOST_PP_FILENAME_1 <simgear/nasal/cppbind/detail/functor_templates.hxx>
553 #include BOOST_PP_ITERATE()
555 // TODO use variadic template when supporting C++11
556 // TODO check if default constructor exists
557 // static naRef create( naContext c )
559 // return makeGhost(c, createInstance());
563 * Create a Nasal instance of this ghost.
565 * @param c Active Nasal context
566 * @param a1 Parameter used for creating new instance
569 static naRef create( naContext c, const A1& a1 )
571 return makeGhost(c, createInstance(a1));
575 * Nasal callback for creating a new instance of this ghost.
577 static naRef f_create(naContext c, naRef me, int argc, naRef* args)
582 static bool isBaseOf(naGhostType* ghost_type)
587 return getSingletonPtr()->GhostMetadata::isBaseOf(ghost_type);
590 static bool isBaseOf(naRef obj)
592 return isBaseOf( naGhost_type(obj) );
596 * Convert Nasal object to C++ object. To get a valid object the passed
597 * Nasal objects has to be derived class of the target class (Either
598 * derived in C++ or in Nasal using a 'parents' vector)
600 static pointer fromNasal(naContext c, naRef me)
602 // Check if it's a ghost and if it can be converted
603 if( isBaseOf( naGhost_type(me) ) )
604 return getPtr( naGhost_ptr(me) );
606 // Now if it is derived from a ghost (hash with ghost in parent vector)
607 else if( naIsHash(me) )
609 naRef na_parents = naHash_cget(me, const_cast<char*>("parents"));
610 if( !naIsVector(na_parents) )
612 SG_LOG(SG_NASAL, SG_DEBUG, "Missing 'parents' vector for ghost");
616 typedef std::vector<naRef> naRefs;
617 naRefs parents = from_nasal<naRefs>(c, na_parents);
618 for( naRefs::const_iterator parent = parents.begin();
619 parent != parents.end();
622 pointer ptr = fromNasal(c, *parent);
636 typedef naGhostType* (*type_checker_t)(const raw_type*);
637 typedef std::vector<type_checker_t> DerivedList;
638 DerivedList _derived_types;
641 * Create a shared pointer on the heap to handle the reference counting
642 * for the passed shared pointer while it is used in Nasal space.
644 static pointer* createInstance(const pointer& ptr)
646 return ptr ? new pointer(ptr) : 0;
649 static pointer getPtr(void* ptr)
652 return *static_cast<pointer*>(ptr);
657 static raw_type* getRawPtr(void* ptr)
660 return static_cast<pointer*>(ptr)->get();
665 static raw_type* getRawPtr(const pointer& ptr)
670 void addDerived( const internal::GhostMetadata* derived_meta,
671 const type_checker_t& derived_info )
673 GhostMetadata::addDerived(derived_meta);
674 _derived_types.push_back(derived_info);
677 template<class BaseGhost>
679 typename boost::enable_if
680 < boost::is_polymorphic<typename BaseGhost::raw_type>,
683 getTypeFor(const typename BaseGhost::raw_type* base)
685 // Check first if passed pointer can by converted to instance of class
688 < typename BaseGhost::raw_type,
689 typename Ghost::raw_type
691 && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
694 // Now check if we can further downcast to one of our derived classes.
695 for( typename DerivedList::reverse_iterator
696 derived = getSingletonPtr()->_derived_types.rbegin();
697 derived != getSingletonPtr()->_derived_types.rend();
700 naGhostType* ghost_type =
701 (*derived)( static_cast<const typename Ghost::raw_type*>(base) );
706 // If base is not an instance of any derived class, this class has to
707 // be the dynamic type.
708 return &getSingletonPtr()->_ghost_type;
711 template<class BaseGhost>
713 typename boost::disable_if
714 < boost::is_polymorphic<typename BaseGhost::raw_type>,
717 getTypeFor(const typename BaseGhost::raw_type* base)
719 // For non polymorphic classes there is no possibility to get the actual
720 // dynamic type, therefore we can only use its static type.
721 return &BaseGhost::getSingletonPtr()->_ghost_type;
724 static Ghost* getSingletonPtr()
726 return getSingletonHolder().get();
729 static raw_type& requireObject(naContext c, naRef me)
731 raw_type* obj = getRawPtr( fromNasal(c, me) );
732 naGhostType* ghost_type = naGhost_type(me);
738 "method called on object of wrong type: is '%s' expected '%s'",
739 ghost_type ? ghost_type->name : "unknown",
740 getSingletonPtr()->_ghost_type.name
747 * Invoke a method which returns a value and convert it to Nasal.
751 typename boost::disable_if<boost::is_void<Ret>, naRef>::type
754 const boost::function<Ret (raw_type&, const CallContext&)>& func,
756 const CallContext& ctx
759 return (*to_nasal_ptr<Ret>::get())(ctx.c, func(obj, ctx));
763 * Invoke a method which returns void and "convert" it to nil.
767 typename boost::enable_if<boost::is_void<Ret>, naRef>::type
770 const boost::function<Ret (raw_type&, const CallContext&)>& func,
772 const CallContext& ctx
780 * Extract argument by index from nasal::CallContext and convert to given
785 typename boost::disable_if<
786 boost::is_same<Arg, const CallContext&>,
787 typename from_nasal_ptr<Arg>::return_type
789 arg_from_nasal(const CallContext& ctx, size_t index)
791 return ctx.requireArg<Arg>(index);
795 * Specialization to pass through nasal::CallContext.
799 typename boost::enable_if<
800 boost::is_same<Arg, const CallContext&>,
801 typename from_nasal_ptr<Arg>::return_type
803 arg_from_nasal(const CallContext& ctx, size_t)
808 typedef std::auto_ptr<Ghost> GhostPtr;
811 explicit Ghost(const std::string& name):
812 GhostMetadata( name )
814 _ghost_type.destroy = &destroyGhost;
815 _ghost_type.name = _name.c_str();
816 _ghost_type.get_member = &getMember;
817 _ghost_type.set_member = &setMember;
820 static GhostPtr& getSingletonHolder()
822 static GhostPtr instance;
826 static naRef makeGhost(naContext c, void *ptr)
830 // We are wrapping shared pointers to already existing objects which
831 // will then be hold be a new shared pointer. We therefore have to
832 // check for the dynamic type of the object as it might differ from
833 // the passed static type.
834 naGhostType* ghost_type = getTypeFor<Ghost>( getRawPtr(ptr) );
837 return naNewGhost2(c, ghost_type, ptr);
844 static void destroyGhost(void *ptr)
846 delete static_cast<pointer*>(ptr);
850 * Callback for retrieving a ghost member.
852 static const char* getMember(naContext c, void* g, naRef key, naRef* out)
854 const std::string key_str = nasal::from_nasal<std::string>(c, key);
855 if( key_str == "parents" )
857 if( getSingletonPtr()->_parents.empty() )
860 *out = getSingletonPtr()->getParents(c);
864 typename MemberMap::iterator member =
865 getSingletonPtr()->_members.find(key_str);
867 if( member == getSingletonPtr()->_members.end() )
870 if( member->second.func )
871 *out = member->second.func->get_naRef(c);
872 else if( !member->second.getter.empty() )
873 *out = member->second.getter(c, *getRawPtr(g));
875 return "Read-protected member";
881 * Callback for writing to a ghost member.
883 static void setMember(naContext c, void* g, naRef field, naRef val)
885 const std::string key = nasal::from_nasal<std::string>(c, field);
886 typename MemberMap::iterator member =
887 getSingletonPtr()->_members.find(key);
889 if( member == getSingletonPtr()->_members.end() )
890 naRuntimeError(c, "ghost: No such member: %s", key.c_str());
891 else if( member->second.setter.empty() )
892 naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
893 else if( member->second.func )
894 naRuntimeError(c, "ghost: Write to function: %s", key.c_str());
896 member->second.setter(c, *getRawPtr(g), val);
902 #endif /* SG_NASAL_GHOST_HXX_ */