]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/cppbind/cppbind_test.cxx
Fix for old versions of Boost.
[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   VERIFY( hash.size() == 5 )
179   for(Hash::const_iterator it = hash.begin(); it != hash.end(); ++it)
180     VERIFY( hash.get<std::string>(it->getKey()) == it->getValue<std::string>() )
181
182   Hash::iterator it1, it2;
183   Hash::const_iterator it3 = it1, it4(it2);
184   it1 = it2;
185   it3 = it2;
186
187   r = to_nasal(c, hash);
188   VERIFY( naIsHash(r) );
189
190   simgear::StringMap string_map = from_nasal<simgear::StringMap>(c, r);
191   VERIFY( string_map.at("vec") == "string" )
192   VERIFY( string_map.at("name") == "my-name" )
193   VERIFY( string_map.at("string") == "blub" )
194
195   VERIFY( hash.get<std::string>("name") == "my-name" );
196   VERIFY( naIsString(hash.get("name")) );
197
198   Hash mod = hash.createHash("mod");
199   mod.set("parent", hash);
200
201
202   // 'func' is a C++ function registered to Nasal and now converted back to C++
203   boost::function<int (int)> f = hash.get<int (int)>("func");
204   VERIFY( f );
205   VERIFY( f(3) == 3 );
206
207   boost::function<std::string (int)> fs = hash.get<std::string (int)>("func");
208   VERIFY( fs );
209   VERIFY( fs(14) == "14" );
210
211   typedef boost::function<void (int)> FuncVoidInt;
212   FuncVoidInt fvi = hash.get<FuncVoidInt>("func");
213   VERIFY( fvi );
214   fvi(123);
215
216   typedef boost::function<std::string (const std::string&, int, float)> FuncMultiArg;
217   FuncMultiArg fma = hash.get<FuncMultiArg>("func");
218   VERIFY( fma );
219   VERIFY( fma("test", 3, .5) == "test" );
220
221   typedef boost::function<naRef (naRef)> naRefMemFunc;
222   naRefMemFunc fmem = hash.get<naRefMemFunc>("func");
223   VERIFY( fmem );
224   naRef ret = fmem(hash.get_naRef()),
225         hash_ref = hash.get_naRef();
226   VERIFY( naIsIdentical(ret, hash_ref) );
227
228   // Check if nasal::Me gets passed as self/me and remaining arguments are
229   // passed on to function
230   typedef boost::function<int (Me, int)> MeIntFunc;
231   MeIntFunc fmeint = hash.get<MeIntFunc>("func");
232   VERIFY( fmeint(naNil(), 5) == 5 );
233
234   //----------------------------------------------------------------------------
235   // Test exposing classes to Nasal
236   //----------------------------------------------------------------------------
237
238   Ghost<BasePtr>::init("BasePtr")
239     .method("member", &Base::member)
240     .method("strlen", &Base::test1Arg)
241     .member("str", &Base::getString, &Base::setString)
242     .method("str_m", &Base::getString)
243     .method("void", &Base::constVoidFunc)
244     .member("var_r", &Base::getVar)
245     .member("var_w", &Base::setVar)
246     .member("var", &Base::getVar, &Base::setVar)
247     .method("void", &baseVoidFunc)
248     .method("void_c", &baseConstVoidFunc)
249     .method("int2args", &baseFunc2Args)
250     .method("bool2args", &Base::test2Args)
251     .method("str_ptr", &testPtr)
252     .method("this", &Base::getThis)
253     ._set(&Base::genericSet)
254     ._get(&Base::genericGet);
255   Ghost<DerivedPtr>::init("DerivedPtr")
256     .bases<BasePtr>()
257     .member("x", &Derived::getX, &Derived::setX)
258     .member("x_alternate", &f_derivedGetX)
259     .member("x_mixed", &f_derivedGetRandom, &Derived::setX)
260     .member("x_mixed2", &Derived::getX, &f_derivedSetX)
261     .member("x_w", &f_derivedSetX)
262     .method("free_fn", &derivedFreeMember)
263     .method("free_member", &derivedFreeMember)
264     .method("baseDoIt", &baseFuncCallContext);
265   Ghost<DoubleDerivedPtr>::init("DoubleDerivedPtr")
266     .bases<DerivedPtr>();
267   Ghost<DoubleDerived2Ptr>::init("DoubleDerived2Ptr")
268     .bases< Ghost<DerivedPtr> >()
269     .member("base", &DoubleDerived2::getBase)
270     .method("doIt", &DoubleDerived2::doSomeBaseWork);
271
272   Ghost<SGRefBasedPtr>::init("SGRefBasedPtr");
273   Ghost<SGWeakRefBasedPtr>::init("SGWeakRefBasedPtr");
274
275   SGWeakRefBasedPtr weak_ptr(new SGWeakReferenceBasedClass());
276   naRef nasal_ref = to_nasal(c, weak_ptr),
277         nasal_ptr = to_nasal(c, weak_ptr.get());
278
279   VERIFY( naIsGhost(nasal_ref) );
280   VERIFY( naIsGhost(nasal_ptr) );
281
282   SGWeakRefBasedPtr ptr1 = from_nasal<SGWeakRefBasedPtr>(c, nasal_ref),
283                     ptr2 = from_nasal<SGWeakRefBasedPtr>(c, nasal_ptr);
284
285   VERIFY( weak_ptr == ptr1 );
286   VERIFY( weak_ptr == ptr2 );
287
288
289   VERIFY( Ghost<BasePtr>::isInit() );
290   nasal::to_nasal(c, DoubleDerived2Ptr());
291
292   BasePtr d( new Derived );
293   naRef derived = to_nasal(c, d);
294   VERIFY( naIsGhost(derived) );
295   VERIFY( std::string("DerivedPtr") == naGhost_type(derived)->name );
296
297   // Get member function from ghost...
298   naRef thisGetter = naNil();
299   VERIFY( naMember_get(c, derived, to_nasal(c, "this"), &thisGetter) );
300   VERIFY( naIsFunc(thisGetter) );
301
302   // ...and check if it really gets passed the correct instance
303   typedef boost::function<unsigned long (Me)> MemFunc;
304   MemFunc fGetThis = from_nasal<MemFunc>(c, thisGetter);
305   VERIFY( fGetThis );
306   VERIFY( fGetThis(derived) == (unsigned long)d.get() );
307
308   BasePtr d2( new DoubleDerived );
309   derived = to_nasal(c, d2);
310   VERIFY( naIsGhost(derived) );
311   VERIFY( std::string("DoubleDerivedPtr") ==  naGhost_type(derived)->name );
312
313   BasePtr d3( new DoubleDerived2 );
314   derived = to_nasal(c, d3);
315   VERIFY( naIsGhost(derived) );
316   VERIFY( std::string("DoubleDerived2Ptr") ==  naGhost_type(derived)->name );
317
318   SGRefBasedPtr ref_based( new SGReferenceBasedClass );
319   naRef na_ref_based = to_nasal(c, ref_based.get());
320   VERIFY( naIsGhost(na_ref_based) );
321   VERIFY(    from_nasal<SGReferenceBasedClass*>(c, na_ref_based)
322           == ref_based.get() );
323   VERIFY( from_nasal<SGRefBasedPtr>(c, na_ref_based) == ref_based );
324
325   VERIFY( Ghost<BasePtr>::isBaseOf(derived) );
326   VERIFY( Ghost<DerivedPtr>::isBaseOf(derived) );
327   VERIFY( Ghost<DoubleDerived2Ptr>::isBaseOf(derived) );
328
329   VERIFY( from_nasal<BasePtr>(c, derived) == d3 );
330   VERIFY( from_nasal<BasePtr>(c, derived) != d2 );
331   VERIFY(    from_nasal<DerivedPtr>(c, derived)
332           == boost::dynamic_pointer_cast<Derived>(d3) );
333   VERIFY(    from_nasal<DoubleDerived2Ptr>(c, derived)
334           == boost::dynamic_pointer_cast<DoubleDerived2>(d3) );
335   VERIFY( !from_nasal<DoubleDerivedPtr>(c, derived) );
336
337   std::map<std::string, BasePtr> instances;
338   VERIFY( naIsHash(to_nasal(c, instances)) );
339
340   std::map<std::string, DerivedPtr> instances_d;
341   VERIFY( naIsHash(to_nasal(c, instances_d)) );
342
343   std::map<std::string, int> int_map;
344   VERIFY( naIsHash(to_nasal(c, int_map)) );
345
346   std::map<std::string, std::vector<int> > int_vector_map;
347   VERIFY( naIsHash(to_nasal(c, int_vector_map)) );
348
349   simgear::StringMap dict =
350     simgear::StringMap("hello", "value")
351                       ("key2", "value2");
352   naRef na_dict = to_nasal(c, dict);
353   VERIFY( naIsHash(na_dict) );
354   VERIFY( Hash(na_dict, c).get<std::string>("key2") == "value2" );
355
356   // Check converting to Ghost if using Nasal hashes with actual ghost inside
357   // the hashes parents vector
358   std::vector<naRef> parents;
359   parents.push_back(hash.get_naRef());
360   parents.push_back(derived);
361
362   Hash obj(c);
363   obj.set("parents", parents);
364   VERIFY( from_nasal<BasePtr>(c, obj.get_naRef()) == d3 );
365
366   // Check recursive parents (aka parent-of-parent)
367   std::vector<naRef> parents2;
368   parents2.push_back(obj.get_naRef());
369   Hash derived_obj(c);
370   derived_obj.set("parents", parents2);
371   VERIFY( from_nasal<BasePtr>(c, derived_obj.get_naRef()) == d3 );
372
373   std::vector<naRef> nasal_objects;
374   nasal_objects.push_back( Ghost<BasePtr>::makeGhost(c, d) );
375   nasal_objects.push_back( Ghost<BasePtr>::makeGhost(c, d2) );
376   nasal_objects.push_back( Ghost<BasePtr>::makeGhost(c, d3) );
377   naRef obj_vec = to_nasal(c, nasal_objects);
378
379   std::vector<BasePtr> objects = from_nasal<std::vector<BasePtr> >(c, obj_vec);
380   VERIFY( objects[0] == d );
381   VERIFY( objects[1] == d2 );
382   VERIFY( objects[2] == d3 );
383
384   {
385     // Calling fallback setter for unset values
386     const char* src_code = "me.test = 3;";
387     int errLine = -1;
388     naRef code = naParseCode( c, to_nasal(c, "source.nas"), 0,
389                               (char*)src_code, strlen(src_code),
390                               &errLine );
391     ret = naCallMethod(code, derived, 0, 0, naNil());
392
393     VERIFY( !naGetError(c) ) // TODO real error check (this seems to always
394                              //      return 0...
395     VERIFY( from_nasal<int>(c, ret) == 3 )
396   }
397   {
398     // Calling generic (fallback) getter
399     const char* src_code = "var a = me.get_test;";
400     int errLine = -1;
401     naRef code = naParseCode( c, to_nasal(c, "source.nas"), 0,
402                               (char*)src_code, strlen(src_code),
403                               &errLine );
404     ret = naCallMethod(code, derived, 0, 0, naNil());
405
406     VERIFY( !naGetError(c) ) // TODO real error check (this seems to always
407                              //      return 0...
408     VERIFY( from_nasal<std::string>(c, ret) == "generic-get" );
409   }
410
411   //----------------------------------------------------------------------------
412   // Test nasal::CallContext
413   //----------------------------------------------------------------------------
414
415
416   int int_vec[] = {1,2,3};
417   std::map<std::string, std::string> map;
418   naRef args[] = {
419     to_nasal(c, std::string("test-arg")),
420     to_nasal(c, 4),
421     to_nasal(c, int_vec),
422     to_nasal(c, map)
423   };
424   CallContext cc(c, sizeof(args)/sizeof(args[0]), args);
425   VERIFY( cc.requireArg<std::string>(0) == "test-arg" );
426   VERIFY( cc.getArg<std::string>(0) == "test-arg" );
427   VERIFY( cc.getArg<std::string>(10) == "" );
428   VERIFY( cc.isString(0) );
429   VERIFY( !cc.isNumeric(0) );
430   VERIFY( !cc.isVector(0) );
431   VERIFY( !cc.isHash(0) );
432   VERIFY( !cc.isGhost(0) );
433   VERIFY( cc.isNumeric(1) );
434   VERIFY( cc.isVector(2) );
435   VERIFY( cc.isHash(3) );
436
437   naRef args_vec = nasal::to_nasal(c, args);
438   VERIFY( naIsVector(args_vec) );
439
440   //----------------------------------------------------------------------------
441   // Test nasal::String
442   //----------------------------------------------------------------------------
443
444   String string( to_nasal(c, "Test") );
445   VERIFY( from_nasal<std::string>(c, string.get_naRef()) == "Test" );
446   VERIFY( string.c_str() == std::string("Test") );
447   VERIFY( string.starts_with(string) );
448   VERIFY( string.starts_with(String(c, "T")) );
449   VERIFY( string.starts_with(String(c, "Te")) );
450   VERIFY( string.starts_with(String(c, "Tes")) );
451   VERIFY( string.starts_with(String(c, "Test")) );
452   VERIFY( !string.starts_with(String(c, "Test1")) );
453   VERIFY( !string.starts_with(String(c, "bb")) );
454   VERIFY( !string.starts_with(String(c, "bbasdasdafasd")) );
455   VERIFY( string.ends_with(String(c, "t")) );
456   VERIFY( string.ends_with(String(c, "st")) );
457   VERIFY( string.ends_with(String(c, "est")) );
458   VERIFY( string.ends_with(String(c, "Test")) );
459   VERIFY( !string.ends_with(String(c, "1Test")) );
460   VERIFY( !string.ends_with(String(c, "abc")) );
461   VERIFY( !string.ends_with(String(c, "estasdasd")) );
462   VERIFY( string.find('e') == 1 );
463   VERIFY( string.find('9') == String::npos );
464   VERIFY( string.find_first_of(String(c, "st")) == 2 );
465   VERIFY( string.find_first_of(String(c, "st"), 3) == 3 );
466   VERIFY( string.find_first_of(String(c, "xyz")) == String::npos );
467   VERIFY( string.find_first_not_of(String(c, "Tst")) == 1 );
468   VERIFY( string.find_first_not_of(String(c, "Tse"), 2) == 3 );
469   VERIFY( string.find_first_not_of(String(c, "abc")) == 0 );
470   VERIFY( string.find_first_not_of(String(c, "abc"), 20) == String::npos );
471
472   naFreeContext(c);
473
474   return 0;
475 }