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