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