]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/cppbind/Ghost.hxx
2d6720977ee1151fe62c46c6d5785c6978343fe4
[simgear.git] / simgear / nasal / cppbind / Ghost.hxx
1 ///@file
2 /// Expose C++ objects to Nasal as ghosts
3 ///
4 // Copyright (C) 2012  Thomas Geymayer <tomgey@gmail.com>
5 //
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.
10 //
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.
15 //
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
19
20 #ifndef SG_NASAL_GHOST_HXX_
21 #define SG_NASAL_GHOST_HXX_
22
23 #include "from_nasal.hxx"
24 #include "to_nasal.hxx"
25
26 #include <simgear/debug/logstream.hxx>
27
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>
34
35 #include <map>
36
37 /**
38  * Bindings between C++ and the Nasal scripting language
39  */
40 namespace nasal
41 {
42
43   namespace internal
44   {
45     /**
46      * Metadata for Ghost object types
47      */
48     class GhostMetadata
49     {
50       public:
51         /**
52          * Add a nasal base class to the ghost. Will be available in the ghosts
53          * parents array.
54          */
55         void addNasalBase(const naRef& parent)
56         {
57           assert( naIsHash(parent) );
58           _parents.push_back(parent);
59         }
60
61         bool isBaseOf(naGhostType* ghost_type) const
62         {
63           if( ghost_type == &_ghost_type )
64             return true;
65
66           for( DerivedList::const_iterator derived = _derived_classes.begin();
67                                            derived != _derived_classes.end();
68                                          ++derived )
69           {
70             if( (*derived)->isBaseOf(ghost_type) )
71               return true;
72           }
73
74           return false;
75         }
76
77       protected:
78
79         typedef std::vector<const GhostMetadata*> DerivedList;
80
81         const std::string   _name;
82         naGhostType         _ghost_type;
83         DerivedList         _derived_classes;
84         std::vector<naRef>  _parents;
85
86         explicit GhostMetadata(const std::string& name):
87           _name(name)
88         {
89
90         }
91
92         void addDerived(const GhostMetadata* derived)
93         {
94           assert(derived);
95           _derived_classes.push_back(derived);
96
97           SG_LOG
98           (
99             SG_NASAL,
100             SG_INFO,
101             "Ghost::addDerived: " <<_ghost_type.name << " -> " << derived->_name
102           );
103         }
104
105         naRef getParents(naContext c)
106         {
107           return nasal::to_nasal(c, _parents);
108         }
109     };
110
111     BOOST_MPL_HAS_XXX_TRAIT_DEF(element_type)
112   }
113
114   /**
115    * Context passed to a function/method being called from Nasal
116    */
117   struct CallContext
118   {
119     CallContext(naContext c, size_t argc, naRef* args):
120       c(c),
121       argc(argc),
122       args(args)
123     {}
124
125     /**
126      * Get the argument with given index if it exists. Otherwise returns the
127      * passed default value.
128      *
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
132      */
133     template<class T>
134     T getArg(size_t index, const T& def = T()) const
135     {
136       if( index >= argc )
137         return def;
138
139       return from_nasal<T>(c, args[index]);
140     }
141
142     /**
143      * Get the argument with given index. Raises a Nasal runtime error if there
144      * are to few arguments available.
145      */
146     template<class T>
147     T requireArg(size_t index) const
148     {
149       if( index >= argc )
150         naRuntimeError(c, "Missing required arg #%d", index);
151
152       return from_nasal<T>(c, args[index]);
153     }
154
155     naContext   c;
156     size_t      argc;
157     naRef      *args;
158   };
159
160   /**
161    * Class for exposing C++ objects to Nasal
162    *
163    * @code{cpp}
164    * // Example class to be exposed to Nasal
165    * class MyClass
166    * {
167    *   public:
168    *     void setX(int x);
169    *     int getX() const;
170    *
171    *     naRef myMember(naContext c, int argc, naRef* args);
172    * }
173    * typedef boost::shared_ptr<MyClass> MyClassPtr;
174    *
175    * void exposeClasses()
176    * {
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");
190    * }
191    * @endcode
192    */
193   template<class T>
194   class Ghost:
195     public internal::GhostMetadata
196   {
197       BOOST_STATIC_ASSERT( internal::has_element_type<T>::value );
198
199     public:
200       typedef typename T::element_type                            raw_type;
201       typedef T                                                   pointer;
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
207       /**
208        * A ghost member. Can consist either of getter and/or setter functions
209        * for exposing a data variable or a single callable function.
210        */
211       struct member_t
212       {
213         member_t():
214           func(0)
215         {}
216
217         member_t( const getter_t& getter,
218                   const setter_t& setter,
219                   naCFunction func = 0 ):
220           getter( getter ),
221           setter( setter ),
222           func( func )
223         {}
224
225         member_t(naCFunction func):
226           func( func )
227         {}
228
229         getter_t    getter;
230         setter_t    setter;
231         naCFunction func;
232       };
233
234       typedef std::map<std::string, member_t> MemberMap;
235
236       /**
237        * Register a new ghost type.
238        *
239        * @note Only intialize each ghost type once!
240        *
241        * @param name    Descriptive name of the ghost type.
242        */
243       static Ghost& init(const std::string& name)
244       {
245         assert( !getSingletonPtr() );
246
247         getSingletonHolder().reset( new Ghost(name) );
248         return *getSingletonPtr();
249       }
250
251       /**
252        * Register a base class for this ghost. The base class needs to be
253        * registers on its own before it can be used as base class.
254        *
255        * @tparam BaseGhost  Type of base class already wrapped into Ghost class
256        *                    (Ghost<BasePtr>)
257        *
258        * @code{cpp}
259        * Ghost<MyBasePtr>::init("MyBase");
260        * Ghost<MyClassPtr>::init("MyClass")
261        *   .bases<Ghost<MyBasePtr> >();
262        * @endcode
263        */
264       template<class BaseGhost>
265       typename boost::enable_if
266         <
267           boost::is_base_of<GhostMetadata, BaseGhost>,
268           Ghost
269         >::type&
270       bases()
271       {
272         BOOST_STATIC_ASSERT
273         ((
274           boost::is_base_of<typename BaseGhost::raw_type, raw_type>::value
275         ));
276
277         BaseGhost* base = BaseGhost::getSingletonPtr();
278         base->addDerived
279         (
280           this,
281           // Both ways of retrieving the address of a static member function
282           // should be legal but not all compilers know this.
283           // g++-4.4.7+ has been tested to work with both versions
284 #if defined(GCC_VERSION) && GCC_VERSION < 40407
285           // The old version of g++ used on Jenkins (16.11.2012) only compiles
286           // this version.
287           &getTypeFor<BaseGhost>
288 #else
289           // VS (2008, 2010, ... ?) only allow this version.
290           &Ghost::getTypeFor<BaseGhost>
291 #endif
292         );
293
294         // Replace any getter that is not available in the current class.
295         // TODO check if this is the correct behavior of function overriding
296         for( typename BaseGhost::MemberMap::const_iterator member =
297                base->_members.begin();
298                member != base->_members.end();
299              ++member )
300         {
301           if( _members.find(member->first) == _members.end() )
302             _members[member->first] = member_t
303             (
304               member->second.getter,
305               member->second.setter,
306               member->second.func
307             );
308         }
309
310         return *this;
311       }
312
313       /**
314        * Register a base class for this ghost. The base class needs to be
315        * registers on its own before it can be used as base class.
316        *
317        * @tparam Base   Type of base class (Base as used in Ghost<BasePtr>)
318        *
319        * @code{cpp}
320        * Ghost<MyBasePtr>::init("MyBase");
321        * Ghost<MyClassPtr>::init("MyClass")
322        *   .bases<MyBasePtr>();
323        * @endcode
324        */
325       template<class Base>
326       typename boost::disable_if
327         <
328           boost::is_base_of<GhostMetadata, Base>,
329           Ghost
330         >::type&
331       bases()
332       {
333         BOOST_STATIC_ASSERT
334         ((
335           boost::is_base_of<typename Ghost<Base>::raw_type, raw_type>::value
336         ));
337
338         return bases< Ghost<Base> >();
339       }
340
341       /**
342        * Register an existing Nasal class/hash as base class for this ghost.
343        *
344        * @param parent  Nasal hash/class
345        */
346       Ghost& bases(const naRef& parent)
347       {
348         addNasalBase(parent);
349         return *this;
350       }
351
352       /**
353        * Register a member variable by passing a getter and/or setter method.
354        *
355        * @param field   Name of member
356        * @param getter  Getter for variable
357        * @param setter  Setter for variable (Pass 0 to prevent write access)
358        *
359        */
360       template<class Ret, class Param>
361       Ghost& member( const std::string& field,
362                      Ret (raw_type::*getter)() const,
363                      void (raw_type::*setter)(Param) )
364       {
365         member_t m;
366         if( getter )
367         {
368           typedef typename boost::call_traits<Ret>::param_type param_type;
369           naRef (*to_nasal_)(naContext, param_type) = &nasal::to_nasal;
370
371           // Getter signature: naRef(naContext, raw_type&)
372           m.getter = boost::bind(to_nasal_, _1, boost::bind(getter, _2));
373         }
374
375         if( setter )
376         {
377           typename boost::remove_reference<Param>::type
378           (*from_nasal_)(naContext, naRef) = &nasal::from_nasal;
379
380           // Setter signature: void(naContext, raw_type&, naRef)
381           m.setter = boost::bind(setter, _2, boost::bind(from_nasal_, _1, _3));
382         }
383
384         return member(field, m.getter, m.setter);
385       }
386
387       /**
388        * Register a read only member variable.
389        *
390        * @param field   Name of member
391        * @param getter  Getter for variable
392        */
393       template<class Ret>
394       Ghost& member( const std::string& field,
395                      Ret (raw_type::*getter)() const )
396       {
397         return member<Ret, Ret>(field, getter, 0);
398       }
399
400       /**
401        * Register a write only member variable.
402        *
403        * @param field   Name of member
404        * @param setter  Setter for variable
405        */
406       template<class Var>
407       Ghost& member( const std::string& field,
408                      void (raw_type::*setter)(Var) )
409       {
410         return member<Var, Var>(field, 0, setter);
411       }
412
413       /**
414        * Register a member variable by passing a getter and/or setter method.
415        *
416        * @param field   Name of member
417        * @param getter  Getter for variable
418        * @param setter  Setter for variable (Pass empty to prevent write access)
419        *
420        */
421       Ghost& member( const std::string& field,
422                      const getter_t& getter,
423                      const setter_t& setter = setter_t() )
424       {
425         if( !getter.empty() || !setter.empty() )
426           _members[field] = member_t(getter, setter);
427         else
428           SG_LOG
429           (
430             SG_NASAL,
431             SG_WARN,
432             "Member '" << field << "' requires a getter or setter"
433           );
434         return *this;
435       }
436
437       /**
438        * Register a member function.
439        *
440        * @note Because only function pointers can be registered as Nasal
441        *       functions it is needed to pass the function pointer as template
442        *       argument. This allows us to create a separate instance of the
443        *       MemberFunctionWrapper for each registered function and therefore
444        *       provides us with the needed static functions to be passed on to
445        *       Nasal.
446        *
447        * @tparam func   Pointer to member function being registered.
448        *
449        * @code{cpp}
450        * class MyClass
451        * {
452        *   public:
453        *     naRef myMethod(naContext c, int argc, naRef* args);
454        * }
455        *
456        * Ghost<MyClassPtr>::init("Test")
457        *   .method<&MyClass::myMethod>("myMethod");
458        * @endcode
459        */
460       template<member_func_t func>
461       Ghost& method(const std::string& name)
462       {
463         _members[name].func = &MemberFunctionWrapper<func>::call;
464         return *this;
465       }
466
467       /**
468        * Register a free function as member function. The object instance is
469        * passed as additional first argument.
470        *
471        * @tparam func   Pointer to free function being registered.
472        *
473        * @note Due to a severe bug in Visual Studio it is not possible to create
474        *       a specialization of #method for free function pointers and
475        *       member function pointers at the same time. Do overcome this
476        *       limitation we had to use a different name for this function.
477        *
478        * @code{cpp}
479        * class MyClass;
480        * naRef myMethod(MyClass& obj, naContext c, int argc, naRef* args);
481        *
482        * Ghost<MyClassPtr>::init("Test")
483        *   .method_func<&myMethod>("myMethod");
484        * @endcode
485        */
486       template<free_func_t func>
487       Ghost& method_func(const std::string& name)
488       {
489         _members[name].func = &FreeFunctionWrapper<func>::call;
490         return *this;
491       }
492
493       // TODO use variadic template when supporting C++11
494       /**
495        * Create a Nasal instance of this ghost.
496        *
497        * @param c   Active Nasal context
498        */
499       // TODO check if default constructor exists
500 //      static naRef create( naContext c )
501 //      {
502 //        return makeGhost(c, createInstance());
503 //      }
504
505       /**
506        * Create a Nasal instance of this ghost.
507        *
508        * @param c   Active Nasal context
509        * @param a1  Parameter used for creating new instance
510        */
511       template<class A1>
512       static naRef create( naContext c, const A1& a1 )
513       {
514         return makeGhost(c, createInstance(a1));
515       }
516
517       /**
518        * Nasal callback for creating a new instance of this ghost.
519        */
520       static naRef f_create(naContext c, naRef me, int argc, naRef* args)
521       {
522         return create(c);
523       }
524
525       static bool isBaseOf(naGhostType* ghost_type)
526       {
527         if( !ghost_type )
528           return false;
529
530         return getSingletonPtr()->GhostMetadata::isBaseOf(ghost_type);
531       }
532
533       static bool isBaseOf(naRef obj)
534       {
535         return isBaseOf( naGhost_type(obj) );
536       }
537
538       /**
539        * Convert Nasal object to C++ object. To get a valid object the passed
540        * Nasal objects has to be derived class of the target class (Either
541        * derived in C++ or in Nasal using a 'parents' vector)
542        */
543       static pointer fromNasal(naContext c, naRef me)
544       {
545         // Check if it's a ghost and if it can be converted
546         if( isBaseOf( naGhost_type(me) ) )
547           return getPtr( naGhost_ptr(me) );
548
549         // Now if it is derived from a ghost (hash with ghost in parent vector)
550         else if( naIsHash(me) )
551         {
552           naRef na_parents = naHash_cget(me, const_cast<char*>("parents"));
553           if( !naIsVector(na_parents) )
554           {
555             SG_LOG(SG_NASAL, SG_DEBUG, "Missing 'parents' vector for ghost");
556             return pointer();
557           }
558
559           typedef std::vector<naRef> naRefs;
560           naRefs parents = from_nasal<naRefs>(c, na_parents);
561           for( naRefs::const_iterator parent = parents.begin();
562                                       parent != parents.end();
563                                     ++parent )
564           {
565             pointer ptr = fromNasal(c, *parent);
566             if( ptr )
567               return ptr;
568           }
569         }
570
571         return pointer();
572       }
573
574     private:
575
576       template<class>
577       friend class Ghost;
578
579       typedef naGhostType* (*type_checker_t)(const raw_type*);
580       typedef std::vector<type_checker_t> DerivedList;
581       DerivedList _derived_types;
582
583       /**
584        * Create a shared pointer on the heap to handle the reference counting
585        * for the passed shared pointer while it is used in Nasal space.
586        */
587       static pointer* createInstance(const pointer& ptr)
588       {
589         return ptr ? new pointer(ptr) : 0;
590       }
591
592       static pointer getPtr(void* ptr)
593       {
594         if( ptr )
595           return *static_cast<pointer*>(ptr);
596         else
597           return pointer();
598       }
599
600       static raw_type* getRawPtr(void* ptr)
601       {
602         if( ptr )
603           return static_cast<pointer*>(ptr)->get();
604         else
605           return 0;
606       }
607
608       static raw_type* getRawPtr(const pointer& ptr)
609       {
610         return ptr.get();
611       }
612
613       void addDerived( const internal::GhostMetadata* derived_meta,
614                        const type_checker_t& derived_info )
615       {
616         GhostMetadata::addDerived(derived_meta);
617         _derived_types.push_back(derived_info);
618       }
619
620       template<class BaseGhost>
621       static
622       typename boost::enable_if
623         < boost::is_polymorphic<typename BaseGhost::raw_type>,
624           naGhostType*
625         >::type
626       getTypeFor(const typename BaseGhost::raw_type* base)
627       {
628         // Check first if passed pointer can by converted to instance of class
629         // this ghost wraps.
630         if(   !boost::is_same
631                  < typename BaseGhost::raw_type,
632                    typename Ghost::raw_type
633                  >::value
634             && dynamic_cast<const typename Ghost::raw_type*>(base) != base )
635           return 0;
636
637         // Now check if we can further downcast to one of our derived classes.
638         for( typename DerivedList::reverse_iterator
639                derived = getSingletonPtr()->_derived_types.rbegin();
640                derived != getSingletonPtr()->_derived_types.rend();
641              ++derived )
642         {
643           naGhostType* ghost_type =
644             (*derived)( static_cast<const typename Ghost::raw_type*>(base) );
645           if( ghost_type )
646             return ghost_type;
647         }
648
649         // If base is not an instance of any derived class, this class has to
650         // be the dynamic type.
651         return &getSingletonPtr()->_ghost_type;
652       }
653
654       template<class BaseGhost>
655       static
656       typename boost::disable_if
657         < boost::is_polymorphic<typename BaseGhost::raw_type>,
658           naGhostType*
659         >::type
660       getTypeFor(const typename BaseGhost::raw_type* base)
661       {
662         // For non polymorphic classes there is no possibility to get the actual
663         // dynamic type, therefore we can only use its static type.
664         return &BaseGhost::getSingletonPtr()->_ghost_type;
665       }
666
667       static Ghost* getSingletonPtr()
668       {
669         return getSingletonHolder().get();
670       }
671
672       static raw_type& requireObject(naContext c, naRef me)
673       {
674         raw_type* obj = getRawPtr( fromNasal(c, me) );
675         naGhostType* ghost_type = naGhost_type(me);
676
677         if( !obj )
678           naRuntimeError
679           (
680             c,
681             "method called on object of wrong type: is '%s' expected '%s'",
682             ghost_type ? ghost_type->name : "unknown",
683             getSingletonPtr()->_ghost_type.name
684           );
685
686         return *obj;
687       }
688
689       /**
690        * Wrapper class to enable registering pointers to member functions as
691        * Nasal function callbacks. We need to use the function pointer as
692        * template parameter to ensure every registered function gets a static
693        * function which can be passed to Nasal.
694        */
695       template<member_func_t func>
696       struct MemberFunctionWrapper
697       {
698         /**
699          * Called from Nasal upon invocation of the according registered
700          * function. Forwards the call to the passed object instance.
701          */
702         static naRef call(naContext c, naRef me, int argc, naRef* args)
703         {
704           return (requireObject(c, me).*func)(CallContext(c, argc, args));
705         }
706       };
707
708       /**
709        * Wrapper class to enable registering pointers to free functions (only
710        * external linkage). We need to use the function pointer as template
711        * parameter to ensure every registered function gets a static function
712        * which can be passed to Nasal. Even though we just wrap another simple
713        * function pointer this intermediate step is need to be able to retrieve
714        * the object the function call belongs to and pass it along as argument.
715        */
716       template<free_func_t func>
717       struct FreeFunctionWrapper
718       {
719         /**
720          * Called from Nasal upon invocation of the according registered
721          * function. Forwards the call to the passed function pointer and passes
722          * the required parameters.
723          */
724         static naRef call(naContext c, naRef me, int argc, naRef* args)
725         {
726           return func(requireObject(c, me), CallContext(c, argc, args));
727         }
728       };
729
730       typedef std::auto_ptr<Ghost> GhostPtr;
731       MemberMap _members;
732
733       explicit Ghost(const std::string& name):
734         GhostMetadata( name )
735       {
736         _ghost_type.destroy = &destroyGhost;
737         _ghost_type.name = _name.c_str();
738         _ghost_type.get_member = &getMember;
739         _ghost_type.set_member = &setMember;
740       }
741
742       static GhostPtr& getSingletonHolder()
743       {
744         static GhostPtr instance;
745         return instance;
746       }
747
748       static naRef makeGhost(naContext c, void *ptr)
749       {
750         if( getRawPtr(ptr) )
751         {
752           // We are wrapping shared pointers to already existing objects which
753           // will then be hold be a new shared pointer. We therefore have to
754           // check for the dynamic type of the object as it might differ from
755           // the passed static type.
756           naGhostType* ghost_type = getTypeFor<Ghost>( getRawPtr(ptr) );
757
758           if( ghost_type )
759             return naNewGhost2(c, ghost_type, ptr);
760         }
761
762         destroyGhost(ptr);
763         return naNil();
764       }
765
766       static void destroyGhost(void *ptr)
767       {
768         delete static_cast<pointer*>(ptr);
769       }
770
771       /**
772        * Callback for retrieving a ghost member.
773        */
774       static const char* getMember(naContext c, void* g, naRef key, naRef* out)
775       {
776         const std::string key_str = nasal::from_nasal<std::string>(c, key);
777         if( key_str == "parents" )
778         {
779           if( getSingletonPtr()->_parents.empty() )
780             return 0;
781
782           *out = getSingletonPtr()->getParents(c);
783           return "";
784         }
785
786         typename MemberMap::iterator member =
787           getSingletonPtr()->_members.find(key_str);
788
789         if( member == getSingletonPtr()->_members.end() )
790           return 0;
791
792         if( member->second.func )
793           *out = nasal::to_nasal(c, member->second.func);
794         else if( !member->second.getter.empty() )
795           *out = member->second.getter(c, *getRawPtr(g));
796         else
797           return "Read-protected member";
798
799         return "";
800       }
801
802       /**
803        * Callback for writing to a ghost member.
804        */
805       static void setMember(naContext c, void* g, naRef field, naRef val)
806       {
807         const std::string key = nasal::from_nasal<std::string>(c, field);
808         typename MemberMap::iterator member =
809           getSingletonPtr()->_members.find(key);
810
811         if( member == getSingletonPtr()->_members.end() )
812           naRuntimeError(c, "ghost: No such member: %s", key.c_str());
813         if( member->second.setter.empty() )
814           naRuntimeError(c, "ghost: Write protected member: %s", key.c_str());
815
816         member->second.setter(c, *getRawPtr(g), val);
817       }
818   };
819
820 } // namespace nasal
821
822 #endif /* SG_NASAL_GHOST_HXX_ */