]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/cppbind/cppbind_test.cxx
cppbind.Ghost: more member overloads.
[simgear.git] / simgear / nasal / cppbind / cppbind_test.cxx
1 #include <simgear/math/SGMath.hxx>
2
3 #include "Ghost.hxx"
4 #include "NasalHash.hxx"
5 #include "NasalString.hxx"
6 #include <simgear/structure/map.hxx>
7
8 #include <boost/shared_ptr.hpp>
9 #include <boost/weak_ptr.hpp>
10
11 #include <cstring>
12 #include <iostream>
13
14 #define VERIFY(a) \
15   if( !(a) ) \
16   { \
17     std::cerr << "failed: line " << __LINE__ << ": " << #a << std::endl; \
18     return 1; \
19   }
20
21 enum MyEnum
22 {
23   ENUM_FIRST,
24   ENUM_ANOTHER,
25   ENUM_LAST
26 };
27 struct Base
28 {
29   naRef member(const nasal::CallContext&) { return naNil(); }
30   virtual ~Base(){};
31
32   std::string getString() const { return ""; }
33   void setString(const std::string&) {}
34   void constVoidFunc() const {}
35   size_t test1Arg(const std::string& str) const { return str.length(); }
36   bool test2Args(const std::string& s, bool c) { return c && s.empty(); }
37
38   std::string var;
39   const std::string& getVar() const { return var; }
40   void setVar(const std::string v) { var = v; }
41
42   unsigned long getThis() const { return (unsigned long)this; }
43   bool genericSet(const std::string& key, const std::string& val)
44   {
45     return key == "test";
46   }
47   bool genericGet(const std::string& key, std::string& val_out) const
48   {
49     if( key != "get_test" )
50       return false;
51
52     val_out = "generic-get";
53     return true;
54   }
55 };
56
57 void baseVoidFunc(Base& b) {}
58 void baseConstVoidFunc(const Base& b) {}
59 size_t baseFunc2Args(Base& b, int x, const std::string& s) { return x + s.size(); }
60 std::string testPtr(Base& b) { return b.getString(); }
61 void baseFuncCallContext(const Base&, const nasal::CallContext&) {}
62
63 struct Derived:
64   public Base
65 {
66   int _x;
67   int getX() const { return _x; }
68   void setX(int x) { _x = x; }
69 };
70
71 naRef f_derivedGetRandom(const Derived&, naContext)
72 {
73   return naNil();
74 }
75 void f_derivedSetX(Derived& d, naContext, naRef r)
76 {
77   d._x = static_cast<int>(naNumValue(r).num);
78 }
79
80 struct DoubleDerived:
81   public Derived
82 {
83
84 };
85
86 typedef boost::shared_ptr<Base> BasePtr;
87 typedef std::vector<BasePtr> BaseVec;
88
89 struct DoubleDerived2:
90   public Derived
91 {
92   const BasePtr& getBase() const{return _base;}
93   BasePtr _base;
94   BaseVec doSomeBaseWork(const BaseVec& v) { return v; }
95 };
96
97 class SGReferenceBasedClass:
98   public SGReferenced
99 {
100
101 };
102
103 class SGWeakReferenceBasedClass:
104   public SGWeakReferenced
105 {
106
107 };
108
109 typedef boost::shared_ptr<Derived> DerivedPtr;
110 typedef boost::shared_ptr<DoubleDerived> DoubleDerivedPtr;
111 typedef boost::shared_ptr<DoubleDerived2> DoubleDerived2Ptr;
112 typedef SGSharedPtr<SGReferenceBasedClass> SGRefBasedPtr;
113 typedef SGSharedPtr<SGWeakReferenceBasedClass> SGWeakRefBasedPtr;
114
115 typedef boost::weak_ptr<Derived> DerivedWeakPtr;
116
117 naRef derivedFreeMember(Derived&, const nasal::CallContext&) { return naNil(); }
118 naRef f_derivedGetX(const Derived& d, naContext c)
119 {
120   return nasal::to_nasal(c, d.getX());
121 }
122 naRef f_freeFunction(nasal::CallContext c) { return c.requireArg<naRef>(0); }
123
124 int main(int argc, char* argv[])
125 {
126   naContext c = naNewContext();
127   naRef r;
128
129   using namespace nasal;
130
131   r = to_nasal(c, ENUM_ANOTHER);
132   VERIFY( from_nasal<int>(c, r) == ENUM_ANOTHER );
133
134   r = to_nasal(c, "Test");
135   VERIFY( strncmp("Test", naStr_data(r), naStr_len(r)) == 0 );
136   VERIFY( from_nasal<std::string>(c, r) == "Test" );
137
138   r = to_nasal(c, std::string("Test"));
139   VERIFY( strncmp("Test", naStr_data(r), naStr_len(r)) == 0 );
140   VERIFY( from_nasal<std::string>(c, r) == "Test" );
141
142   r = to_nasal(c, 42);
143   VERIFY( naNumValue(r).num == 42 );
144   VERIFY( from_nasal<int>(c, r) == 42 );
145
146   r = to_nasal(c, 4.2f);
147   VERIFY( naNumValue(r).num == 4.2f );
148   VERIFY( from_nasal<float>(c, r) == 4.2f );
149
150   float test_data[3] = {0, 4, 2};
151   r = to_nasal(c, test_data);
152
153   SGVec2f vec(0,2);
154   r = to_nasal(c, vec);
155   VERIFY( from_nasal<SGVec2f>(c, r) == vec );
156
157   std::vector<int> std_vec;
158   r = to_nasal(c, std_vec);
159
160   r = to_nasal(c, "string");
161   try
162   {
163     from_nasal<int>(c, r);
164
165     std::cerr << "failed: Expected bad_nasal_cast to be thrown" << std::endl;
166     return 1;
167   }
168   catch(nasal::bad_nasal_cast&)
169   {}
170
171   Hash hash(c);
172   hash.set("vec", r);
173   hash.set("vec2", vec);
174   hash.set("name", "my-name");
175   hash.set("string", std::string("blub"));
176   hash.set("func", &f_freeFunction);
177
178   r = to_nasal(c, hash);
179   VERIFY( naIsHash(r) );
180
181   simgear::StringMap string_map = from_nasal<simgear::StringMap>(c, r);
182   VERIFY( string_map.at("vec") == "string" )
183   VERIFY( string_map.at("name") == "my-name" )
184   VERIFY( string_map.at("string") == "blub" )
185
186   VERIFY( hash.get<std::string>("name") == "my-name" );
187   VERIFY( naIsString(hash.get("name")) );
188
189   Hash mod = hash.createHash("mod");
190   mod.set("parent", hash);
191
192
193   // 'func' is a C++ function registered to Nasal and now converted back to C++
194   boost::function<int (int)> f = hash.get<int (int)>("func");
195   VERIFY( f );
196   VERIFY( f(3) == 3 );
197
198   boost::function<std::string (int)> fs = hash.get<std::string (int)>("func");
199   VERIFY( fs );
200   VERIFY( fs(14) == "14" );
201
202   typedef boost::function<void (int)> FuncVoidInt;
203   FuncVoidInt fvi = hash.get<FuncVoidInt>("func");
204   VERIFY( fvi );
205   fvi(123);
206
207   typedef boost::function<std::string (const std::string&, int, float)> FuncMultiArg;
208   FuncMultiArg fma = hash.get<FuncMultiArg>("func");
209   VERIFY( fma );
210   VERIFY( fma("test", 3, .5) == "test" );
211
212   typedef boost::function<naRef (naRef)> naRefMemFunc;
213   naRefMemFunc fmem = hash.get<naRefMemFunc>("func");
214   VERIFY( fmem );
215   naRef ret = fmem(hash.get_naRef()),
216         hash_ref = hash.get_naRef();
217   VERIFY( naIsIdentical(ret, hash_ref) );
218
219   // Check if nasal::Me gets passed as self/me and remaining arguments are
220   // passed on to function
221   typedef boost::function<int (Me, int)> MeIntFunc;
222   MeIntFunc fmeint = hash.get<MeIntFunc>("func");
223   VERIFY( fmeint(naNil(), 5) == 5 );
224
225   //----------------------------------------------------------------------------
226   // Test exposing classes to Nasal
227   //----------------------------------------------------------------------------
228
229   Ghost<BasePtr>::init("BasePtr")
230     .method("member", &Base::member)
231     .method("strlen", &Base::test1Arg)
232     .member("str", &Base::getString, &Base::setString)
233     .method("str_m", &Base::getString)
234     .method("void", &Base::constVoidFunc)
235     .member("var_r", &Base::getVar)
236     .member("var_w", &Base::setVar)
237     .member("var", &Base::getVar, &Base::setVar)
238     .method("void", &baseVoidFunc)
239     .method("void_c", &baseConstVoidFunc)
240     .method("int2args", &baseFunc2Args)
241     .method("bool2args", &Base::test2Args)
242     .method("str_ptr", &testPtr)
243     .method("this", &Base::getThis)
244     ._set(&Base::genericSet)
245     ._get(&Base::genericGet);
246   Ghost<DerivedPtr>::init("DerivedPtr")
247     .bases<BasePtr>()
248     .member("x", &Derived::getX, &Derived::setX)
249     .member("x_alternate", &f_derivedGetX)
250     .member("x_mixed", &f_derivedGetRandom, &Derived::setX)
251     .member("x_mixed2", &Derived::getX, &f_derivedSetX)
252     .member("x_w", &f_derivedSetX)
253     .method("free_fn", &derivedFreeMember)
254     .method("free_member", &derivedFreeMember)
255     .method("baseDoIt", &baseFuncCallContext);
256   Ghost<DoubleDerivedPtr>::init("DoubleDerivedPtr")
257     .bases<DerivedPtr>();
258   Ghost<DoubleDerived2Ptr>::init("DoubleDerived2Ptr")
259     .bases< Ghost<DerivedPtr> >()
260     .member("base", &DoubleDerived2::getBase)
261     .method("doIt", &DoubleDerived2::doSomeBaseWork);
262
263   Ghost<DerivedWeakPtr>::init("DerivedWeakPtr");
264   Ghost<SGRefBasedPtr>::init("SGRefBasedPtr");
265   Ghost<SGWeakRefBasedPtr>::init("SGWeakRefBasedPtr");
266
267   SGWeakRefBasedPtr weak_ptr(new SGWeakReferenceBasedClass());
268   naRef nasal_ref = to_nasal(c, weak_ptr),
269         nasal_ptr = to_nasal(c, weak_ptr.get());
270
271   VERIFY( naIsGhost(nasal_ref) );
272   VERIFY( naIsGhost(nasal_ptr) );
273
274   SGWeakRefBasedPtr ptr1 = from_nasal<SGWeakRefBasedPtr>(c, nasal_ref),
275                     ptr2 = from_nasal<SGWeakRefBasedPtr>(c, nasal_ptr);
276
277   VERIFY( weak_ptr == ptr1 );
278   VERIFY( weak_ptr == ptr2 );
279
280
281   VERIFY( Ghost<BasePtr>::isInit() );
282   nasal::to_nasal(c, DoubleDerived2Ptr());
283
284   BasePtr d( new Derived );
285   naRef derived = to_nasal(c, d);
286   VERIFY( naIsGhost(derived) );
287   VERIFY( std::string("DerivedPtr") == naGhost_type(derived)->name );
288
289   // Get member function from ghost...
290   naRef thisGetter = naNil();
291   VERIFY( naMember_get(c, derived, to_nasal(c, "this"), &thisGetter) );
292   VERIFY( naIsFunc(thisGetter) );
293
294   // ...and check if it really gets passed the correct instance
295   typedef boost::function<unsigned long (Me)> MemFunc;
296   MemFunc fGetThis = from_nasal<MemFunc>(c, thisGetter);
297   VERIFY( fGetThis );
298   VERIFY( fGetThis(derived) == (unsigned long)d.get() );
299
300   BasePtr d2( new DoubleDerived );
301   derived = to_nasal(c, d2);
302   VERIFY( naIsGhost(derived) );
303   VERIFY( std::string("DoubleDerivedPtr") ==  naGhost_type(derived)->name );
304
305   BasePtr d3( new DoubleDerived2 );
306   derived = to_nasal(c, d3);
307   VERIFY( naIsGhost(derived) );
308   VERIFY( std::string("DoubleDerived2Ptr") ==  naGhost_type(derived)->name );
309
310   SGRefBasedPtr ref_based( new SGReferenceBasedClass );
311   naRef na_ref_based = to_nasal(c, ref_based.get());
312   VERIFY( naIsGhost(na_ref_based) );
313   VERIFY(    from_nasal<SGReferenceBasedClass*>(c, na_ref_based)
314           == ref_based.get() );
315   VERIFY( from_nasal<SGRefBasedPtr>(c, na_ref_based) == ref_based );
316
317   VERIFY( Ghost<BasePtr>::isBaseOf(derived) );
318   VERIFY( Ghost<DerivedPtr>::isBaseOf(derived) );
319   VERIFY( Ghost<DoubleDerived2Ptr>::isBaseOf(derived) );
320
321   VERIFY( from_nasal<BasePtr>(c, derived) == d3 );
322   VERIFY( from_nasal<BasePtr>(c, derived) != d2 );
323   VERIFY(    from_nasal<DerivedPtr>(c, derived)
324           == boost::dynamic_pointer_cast<Derived>(d3) );
325   VERIFY(    from_nasal<DoubleDerived2Ptr>(c, derived)
326           == boost::dynamic_pointer_cast<DoubleDerived2>(d3) );
327   VERIFY( !from_nasal<DoubleDerivedPtr>(c, derived) );
328
329   std::map<std::string, BasePtr> instances;
330   VERIFY( naIsHash(to_nasal(c, instances)) );
331
332   std::map<std::string, DerivedPtr> instances_d;
333   VERIFY( naIsHash(to_nasal(c, instances_d)) );
334
335   std::map<std::string, int> int_map;
336   VERIFY( naIsHash(to_nasal(c, int_map)) );
337
338   std::map<std::string, std::vector<int> > int_vector_map;
339   VERIFY( naIsHash(to_nasal(c, int_vector_map)) );
340
341   simgear::StringMap dict =
342     simgear::StringMap("hello", "value")
343                       ("key2", "value2");
344   naRef na_dict = to_nasal(c, dict);
345   VERIFY( naIsHash(na_dict) );
346   VERIFY( Hash(na_dict, c).get<std::string>("key2") == "value2" );
347
348   // Check converting to Ghost if using Nasal hashes with actual ghost inside
349   // the hashes parents vector
350   std::vector<naRef> parents;
351   parents.push_back(hash.get_naRef());
352   parents.push_back(derived);
353
354   Hash obj(c);
355   obj.set("parents", parents);
356   VERIFY( from_nasal<BasePtr>(c, obj.get_naRef()) == d3 );
357
358   // Check recursive parents (aka parent-of-parent)
359   std::vector<naRef> parents2;
360   parents2.push_back(obj.get_naRef());
361   Hash derived_obj(c);
362   derived_obj.set("parents", parents2);
363   VERIFY( from_nasal<BasePtr>(c, derived_obj.get_naRef()) == d3 );
364
365   std::vector<naRef> nasal_objects;
366   nasal_objects.push_back( Ghost<BasePtr>::create(c, d) );
367   nasal_objects.push_back( Ghost<BasePtr>::create(c, d2) );
368   nasal_objects.push_back( Ghost<BasePtr>::create(c, d3) );
369   naRef obj_vec = to_nasal(c, nasal_objects);
370
371   std::vector<BasePtr> objects = from_nasal<std::vector<BasePtr> >(c, obj_vec);
372   VERIFY( objects[0] == d );
373   VERIFY( objects[1] == d2 );
374   VERIFY( objects[2] == d3 );
375
376   {
377     // Calling fallback setter for unset values
378     const char* src_code = "me.test = 3;";
379     int errLine = -1;
380     naRef code = naParseCode( c, to_nasal(c, "source.nas"), 0,
381                               (char*)src_code, strlen(src_code),
382                               &errLine );
383     ret = naCallMethod(code, derived, 0, 0, naNil());
384
385     VERIFY( !naGetError(c) ) // TODO real error check (this seems to always
386                              //      return 0...
387     VERIFY( from_nasal<int>(c, ret) == 3 )
388   }
389   {
390     // Calling generic (fallback) getter
391     const char* src_code = "var a = me.get_test;";
392     int errLine = -1;
393     naRef code = naParseCode( c, to_nasal(c, "source.nas"), 0,
394                               (char*)src_code, strlen(src_code),
395                               &errLine );
396     ret = naCallMethod(code, derived, 0, 0, naNil());
397
398     VERIFY( !naGetError(c) ) // TODO real error check (this seems to always
399                              //      return 0...
400     VERIFY( from_nasal<std::string>(c, ret) == "generic-get" );
401   }
402
403   //----------------------------------------------------------------------------
404   // Test nasal::CallContext
405   //----------------------------------------------------------------------------
406
407
408   int int_vec[] = {1,2,3};
409   std::map<std::string, std::string> map;
410   naRef args[] = {
411     to_nasal(c, std::string("test-arg")),
412     to_nasal(c, 4),
413     to_nasal(c, int_vec),
414     to_nasal(c, map)
415   };
416   CallContext cc(c, sizeof(args)/sizeof(args[0]), args);
417   VERIFY( cc.requireArg<std::string>(0) == "test-arg" );
418   VERIFY( cc.getArg<std::string>(0) == "test-arg" );
419   VERIFY( cc.getArg<std::string>(10) == "" );
420   VERIFY( cc.isString(0) );
421   VERIFY( !cc.isNumeric(0) );
422   VERIFY( !cc.isVector(0) );
423   VERIFY( !cc.isHash(0) );
424   VERIFY( !cc.isGhost(0) );
425   VERIFY( cc.isNumeric(1) );
426   VERIFY( cc.isVector(2) );
427   VERIFY( cc.isHash(3) );
428
429   naRef args_vec = nasal::to_nasal(c, args);
430   VERIFY( naIsVector(args_vec) );
431
432   //----------------------------------------------------------------------------
433   // Test nasal::String
434   //----------------------------------------------------------------------------
435
436   String string( to_nasal(c, "Test") );
437   VERIFY( from_nasal<std::string>(c, string.get_naRef()) == "Test" );
438   VERIFY( string.c_str() == std::string("Test") );
439   VERIFY( string.starts_with(string) );
440   VERIFY( string.starts_with(String(c, "T")) );
441   VERIFY( string.starts_with(String(c, "Te")) );
442   VERIFY( string.starts_with(String(c, "Tes")) );
443   VERIFY( string.starts_with(String(c, "Test")) );
444   VERIFY( !string.starts_with(String(c, "Test1")) );
445   VERIFY( !string.starts_with(String(c, "bb")) );
446   VERIFY( !string.starts_with(String(c, "bbasdasdafasd")) );
447   VERIFY( string.ends_with(String(c, "t")) );
448   VERIFY( string.ends_with(String(c, "st")) );
449   VERIFY( string.ends_with(String(c, "est")) );
450   VERIFY( string.ends_with(String(c, "Test")) );
451   VERIFY( !string.ends_with(String(c, "1Test")) );
452   VERIFY( !string.ends_with(String(c, "abc")) );
453   VERIFY( !string.ends_with(String(c, "estasdasd")) );
454   VERIFY( string.find('e') == 1 );
455   VERIFY( string.find('9') == String::npos );
456   VERIFY( string.find_first_of(String(c, "st")) == 2 );
457   VERIFY( string.find_first_of(String(c, "st"), 3) == 3 );
458   VERIFY( string.find_first_of(String(c, "xyz")) == String::npos );
459   VERIFY( string.find_first_not_of(String(c, "Tst")) == 1 );
460   VERIFY( string.find_first_not_of(String(c, "Tse"), 2) == 3 );
461   VERIFY( string.find_first_not_of(String(c, "abc")) == 0 );
462   VERIFY( string.find_first_not_of(String(c, "abc"), 20) == String::npos );
463
464   naFreeContext(c);
465
466   return 0;
467 }