JSFunctionWriter.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. //
  2. // Copyright (c) 2014-2016 THUNDERBEAST GAMES LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Atomic/IO/FileSystem.h>
  23. #include "../JSBind.h"
  24. #include "../JSBModule.h"
  25. #include "../JSBPackage.h"
  26. #include "../JSBEnum.h"
  27. #include "../JSBClass.h"
  28. #include "../JSBFunction.h"
  29. #include "JSFunctionWriter.h"
  30. namespace ToolCore
  31. {
  32. JSFunctionWriter::JSFunctionWriter(JSBFunction *function) : JSBFunctionWriter(function)
  33. {
  34. }
  35. void JSFunctionWriter::WriteParameterMarshal(String& source)
  36. {
  37. // generate args
  38. const Vector<JSBFunctionType*>& parameters = function_->GetParameters();
  39. int cparam = 0;
  40. if (parameters.Size())
  41. {
  42. for (unsigned int i = 0; i < parameters.Size(); i++, cparam++)
  43. {
  44. JSBFunctionType * ptype = parameters.At(i);
  45. // ignore "Context" parameters
  46. if (ptype->type_->asClassType())
  47. {
  48. JSBClassType* classType = ptype->type_->asClassType();
  49. JSBClass* klass = classType->class_;
  50. if (klass->GetName() == "Context")
  51. {
  52. cparam--;
  53. continue;
  54. }
  55. }
  56. String pstring = ptype->ToArgString(cparam);
  57. const String& init = ptype->initializer_;
  58. if (ptype->type_->asClassType())
  59. {
  60. JSBClassType* classType = ptype->type_->asClassType();
  61. JSBClass* klass = classType->class_;
  62. if (!klass->IsNumberArray())
  63. {
  64. if (init.Length())
  65. {
  66. source.AppendWithFormat("%s = duk_get_top(ctx) >= %i ? js_to_class_instance<%s>(ctx, %i, 0) : %s;\n",
  67. pstring.CString(), cparam + 1, klass->GetNativeName().CString(), cparam, init.CString());
  68. }
  69. else
  70. {
  71. source.AppendWithFormat("%s = js_to_class_instance<%s>(ctx, %i, 0);\n",
  72. pstring.CString(), klass->GetNativeName().CString(), cparam);
  73. }
  74. }
  75. else
  76. {
  77. int elements = klass->GetNumberArrayElements();
  78. String elementType = klass->GetArrayElementType();
  79. source.AppendWithFormat("%s arrayData%i[%i];\n", elementType.CString(), cparam, elements);
  80. if (init.Length())
  81. {
  82. source.AppendWithFormat("const %s& defaultArg%i = %s;\n", klass->GetNativeName().CString(), cparam, init.CString());
  83. source.AppendWithFormat("if (duk_get_top(ctx) >= %i) {\n", cparam + 1);
  84. }
  85. for (int j = 0; j < elements; j++)
  86. {
  87. source.AppendWithFormat("duk_get_prop_index(ctx, %i, %i);\n", cparam, j);
  88. source.AppendWithFormat("arrayData%i[%i] = (%s) duk_to_number(ctx, -1);\n", cparam, j, elementType.CString());
  89. }
  90. source.AppendWithFormat("duk_pop_n(ctx, %i);\n", elements);
  91. if (init.Length())
  92. {
  93. source.Append("}\n");
  94. source.AppendWithFormat("%s __arg%i(duk_get_top(ctx) >= %i ? (const %s *) arrayData%i : defaultArg%i.Data());\n",
  95. klass->GetNativeName().CString(), cparam, cparam + 1, elementType.CString(), cparam, cparam);
  96. }
  97. else
  98. {
  99. source.AppendWithFormat("%s __arg%i(arrayData%i);\n", klass->GetNativeName().CString(), cparam, cparam);
  100. }
  101. }
  102. }
  103. else if (ptype->type_->asStringType() || ptype->type_->asStringHashType())
  104. {
  105. if (init.Length())
  106. {
  107. source.AppendWithFormat("%s = duk_get_top(ctx) >= %i ? duk_to_string(ctx, %i) : %s;\n", pstring.CString(), cparam + 1, cparam, init.CString());
  108. }
  109. else
  110. {
  111. source.AppendWithFormat("%s = duk_to_string(ctx, %i);\n", pstring.CString(), cparam);
  112. }
  113. }
  114. else if (ptype->type_->asHeapPtrType())
  115. {
  116. if (init.Length())
  117. {
  118. source.AppendWithFormat("%s = duk_get_top(ctx) >= %i ? duk_get_heapptr(ctx, %i) : %s;\n", pstring.CString(), cparam + 1, cparam, init.CString());
  119. }
  120. else
  121. {
  122. source.AppendWithFormat("%s = duk_get_heapptr(ctx, %i);\n", pstring.CString(), cparam);
  123. }
  124. }
  125. else if (ptype->type_->asPrimitiveType())
  126. {
  127. JSBPrimitiveType* prtype = ptype->type_->asPrimitiveType();
  128. if (prtype->kind_ == JSBPrimitiveType::Bool)
  129. {
  130. if (init.Length())
  131. {
  132. source.AppendWithFormat("bool __arg%i = duk_get_top(ctx) >= %i ? (duk_to_boolean(ctx, %i) ? true : false) : %s;\n",
  133. cparam, cparam + 1, cparam, init.CString());
  134. }
  135. else
  136. {
  137. source.AppendWithFormat("bool __arg%i = duk_to_boolean(ctx, %i) ? true : false;\n", cparam, cparam);
  138. }
  139. }
  140. else
  141. {
  142. if (init.Length())
  143. {
  144. source.AppendWithFormat("double __arg%i = duk_get_top(ctx) >= %i ? (duk_to_number(ctx, %i)) : %s;\n",
  145. cparam, cparam + 1, cparam, init.CString());
  146. }
  147. else
  148. {
  149. source.AppendWithFormat("double __arg%i = duk_to_number(ctx, %i);\n", cparam, cparam);
  150. }
  151. }
  152. }
  153. else if (ptype->type_->asEnumType())
  154. {
  155. JSBEnumType* etype = ptype->type_->asEnumType();
  156. if (init.Length())
  157. {
  158. source.AppendWithFormat("%s __arg%i = duk_get_top(ctx) >= %i ? ((%s) ((int) duk_to_number(ctx, %i))) : %s;\n", etype->enum_->GetName().CString(),
  159. cparam, cparam + 1, etype->enum_->GetName().CString(), cparam, init.CString());
  160. }
  161. else
  162. {
  163. source.AppendWithFormat("%s __arg%i = (%s) ((int)duk_to_number(ctx, %i));\n", etype->enum_->GetName().CString(),
  164. cparam, etype->enum_->GetName().CString(), cparam);
  165. }
  166. }
  167. else if (ptype->type_->asVectorType())
  168. {
  169. JSBVectorType* vtype = ptype->type_->asVectorType();
  170. if (vtype->isVariantVector_)
  171. {
  172. // variant vector arguments
  173. source.AppendWithFormat("VariantVector __arg%i;\nScriptVector* __scriptVectorArg%i = js_to_class_instance<ScriptVector>(ctx, %i, 0);\n", cparam, cparam, cparam);
  174. if (!function_->HasMutatedReturn())
  175. source.AppendWithFormat("__scriptVectorArg%i->AdaptToVector(__arg%i);\n", cparam, cparam);
  176. }
  177. else if (ptype->isConst_)
  178. {
  179. // JS/TS side needs work for vector parameters, right now we support const (read only)
  180. // Vector of String/StringHash
  181. source.AppendWithFormat("%s __arg%i;\n", vtype->ToString().CString(), cparam);
  182. source.AppendWithFormat("if (duk_get_top(ctx) >= %i)\n{\n", cparam + 1);
  183. source.AppendWithFormat("duk_require_object_coercible(ctx, %i);\n", cparam);
  184. source.AppendWithFormat("unsigned sz = duk_get_length(ctx, %i);\n", cparam);
  185. source.AppendWithFormat("for (unsigned i = 0; i < sz; i++)\n{\n");
  186. source.AppendWithFormat("duk_get_prop_index(ctx, 2, i);\n");
  187. if (vtype->vectorType_->asStringType() || vtype->vectorType_->asStringHashType() )
  188. {
  189. source.AppendWithFormat("__arg%i.Push(duk_get_string(ctx, -1));\n", cparam);
  190. }
  191. source.AppendWithFormat("duk_pop(ctx);\n");
  192. source.AppendWithFormat("\n}\n");
  193. source.AppendWithFormat("\n}\n");
  194. }
  195. }
  196. }
  197. }
  198. }
  199. void JSFunctionWriter::WriteConstructor(String& source)
  200. {
  201. // TODO: refactor this
  202. if (function_->name_ == "RefCounted")
  203. {
  204. source.Append("// finalizer may be called more than once\n" \
  205. "static int jsb_finalizer_RefCounted(duk_context *ctx)\n" \
  206. "{\n" \
  207. "JSVM* vm = JSVM::GetJSVM(ctx);\n" \
  208. \
  209. "duk_get_prop_index(ctx, 0, JS_INSTANCE_INDEX_FINALIZED);\n" \
  210. \
  211. "if (!duk_is_boolean(ctx, -1))\n" \
  212. "{\n" \
  213. "RefCounted* ref = vm->GetObjectPtr(duk_get_heapptr(ctx, 0));\n" \
  214. "vm->RemoveObject(ref);\n" \
  215. "ref->ReleaseRef();\n" \
  216. "duk_push_boolean(ctx, 1);\n" \
  217. "duk_put_prop_index(ctx, 0, JS_INSTANCE_INDEX_FINALIZED);\n" \
  218. "}\n" \
  219. \
  220. "return 0;\n" \
  221. "}\n");
  222. }
  223. JSBClass* klass = function_->class_;
  224. JSBClass* base = klass->GetBaseClass();
  225. // Constructor
  226. source.AppendWithFormat("duk_ret_t jsb_constructor_%s(duk_context* ctx)\n{\n", klass->GetName().CString());
  227. source.Append( "\nJSVM* vm = JSVM::GetJSVM(ctx);\n" \
  228. "duk_push_this(ctx);\n" \
  229. "void *ptr = duk_get_heapptr(ctx, -1);\n" \
  230. "duk_pop(ctx);\n\n");
  231. source.Append(" if (!vm->GetObjectPtr(ptr, true))\n {\n");
  232. if (!klass->IsAbstract() && !klass->IsNumberArray())
  233. {
  234. String marshal;
  235. WriteParameterMarshal(marshal);
  236. String sparams;
  237. int cparam = 0;
  238. const Vector<JSBFunctionType*>& parameters = function_->GetParameters();
  239. for (unsigned i = 0; i < parameters.Size(); i++, cparam++)
  240. {
  241. JSBFunctionType * ptype = parameters.At(i);
  242. String sarg;
  243. if (ptype->type_->asClassType())
  244. {
  245. JSBClassType* classType = ptype->type_->asClassType();
  246. JSBClass* klass = classType->class_;
  247. if (klass->GetName() == "Context")
  248. {
  249. sarg = "vm->GetContext()";
  250. cparam--;
  251. }
  252. }
  253. if (!sarg.Length())
  254. {
  255. sarg.AppendWithFormat("__arg%i", cparam);
  256. }
  257. sparams += sarg;
  258. if (i + 1 < parameters.Size())
  259. sparams += ", ";
  260. }
  261. source.AppendWithFormat("if (!duk_get_top(ctx) || !duk_is_pointer(ctx, 0))\n"\
  262. "{\n"\
  263. "%s\n"\
  264. "%s* native = new %s(%s);\n" \
  265. "vm->AddObject(ptr, native, INSTANTIATION_JAVASCRIPT);\n"\
  266. "}\n" \
  267. "else if (duk_is_pointer(ctx, 0))\n" \
  268. "{\n" \
  269. "RefCounted* rc = (RefCounted*) duk_get_pointer(ctx, 0);\n" \
  270. "vm->AddObject(ptr, rc, rc->GetInstantiationType());\n" \
  271. "}\n", marshal.CString(), klass->GetNativeName().CString(), klass->GetNativeName().CString(), sparams.CString());
  272. }
  273. else
  274. {
  275. if (klass->IsAbstract())
  276. source.Append("assert(0); // abstract class new'd\n");
  277. if (klass->IsNumberArray())
  278. source.Append("assert(0); // number array class new'd\n");
  279. }
  280. source.Append(" }\n");
  281. if (base)
  282. {
  283. String basePackage = base->GetModule()->GetPackage()->GetName();
  284. source.AppendWithFormat(" js_constructor_basecall(ctx, \"%s\", \"%s\");\n", basePackage.CString(), base->GetName().CString());
  285. }
  286. if (function_->name_ == "RefCounted")
  287. {
  288. source.Append("duk_push_this(ctx);\n "\
  289. "duk_push_c_function(ctx, jsb_finalizer_RefCounted, 1);\n "\
  290. "duk_set_finalizer(ctx, -2);\n "\
  291. "duk_pop(ctx);\n");
  292. }
  293. source += " return 0;";
  294. source += "\n}\n";
  295. }
  296. void JSFunctionWriter::WriteFunction(String& source)
  297. {
  298. JSBClass* klass = function_->class_;
  299. source.AppendWithFormat("static int jsb_class_%s_%s(duk_context* ctx)\n{\n", klass->GetName().CString(), function_->name_.CString());
  300. WriteParameterMarshal(source);
  301. if (!function_->IsStatic())
  302. {
  303. source.Append("duk_push_this(ctx);\n");
  304. source.AppendWithFormat("%s* native = js_to_class_instance<%s>(ctx, -1, 0);\n", klass->GetNativeName().CString(), klass->GetNativeName().CString());
  305. }
  306. // declare return value;
  307. bool returnDeclared = false;
  308. JSBFunctionType* returnType = function_->returnType_;
  309. if (returnType)
  310. {
  311. if (returnType->type_->asStringType())
  312. {
  313. returnDeclared = true;
  314. source.Append("const String& retValue = ");
  315. }
  316. else if (returnType->type_->asPrimitiveType())
  317. {
  318. returnDeclared = true;
  319. JSBPrimitiveType* prtype = returnType->type_->asPrimitiveType();
  320. if (prtype->kind_ == JSBPrimitiveType::Bool)
  321. {
  322. source.Append("bool retValue = ");
  323. }
  324. else
  325. {
  326. source.Append("double retValue = ");
  327. }
  328. }
  329. else if (returnType->type_->asClassType())
  330. {
  331. JSBClassType* klassType = returnType->type_->asClassType();
  332. if (returnType->isTemplate_)
  333. {
  334. returnDeclared = true;
  335. source.AppendWithFormat("SharedPtr<%s> object = ", klassType->class_->GetNativeName().CString());
  336. }
  337. else if (klassType->class_->IsObject())
  338. {
  339. returnDeclared = true;
  340. source.Append("const Object* object = ");
  341. }
  342. else if (klassType->class_->IsNumberArray())
  343. {
  344. returnDeclared = true;
  345. if (returnType->isReference_)
  346. source.AppendWithFormat("const %s& retValue = ", klassType->class_->GetName().CString());
  347. else
  348. source.AppendWithFormat(" %s retValue = ", klassType->class_->GetName().CString());
  349. }
  350. else
  351. {
  352. returnDeclared = true;
  353. source.Append("const RefCounted* object = ");
  354. }
  355. }
  356. else if (returnType->type_->asEnumType())
  357. {
  358. JSBEnumType* enumType = returnType->type_->asEnumType();
  359. returnDeclared = true;
  360. source.AppendWithFormat("%s retValue = ", enumType->enum_->GetName().CString());
  361. }
  362. else if (returnType->type_->asVectorType())
  363. {
  364. returnDeclared = true;
  365. JSBVectorType* vtype = returnType->type_->asVectorType();
  366. source.AppendWithFormat("const %s& retValue = ", vtype->ToString().CString());
  367. }
  368. }
  369. const Vector<JSBFunctionType*>& parameters = function_->GetParameters();
  370. if (function_->IsStatic())
  371. {
  372. source.AppendWithFormat("%s::%s(", klass->GetNativeName().CString(), function_->name_.CString());
  373. }
  374. else
  375. {
  376. if (function_->HasMutatedReturn())
  377. {
  378. source.AppendWithFormat("__arg%i = native->%s(", parameters.Size() - 1, function_->name_.CString());
  379. }
  380. else
  381. {
  382. source.AppendWithFormat("native->%s(", function_->name_.CString());
  383. }
  384. }
  385. unsigned numParams = parameters.Size();
  386. if (numParams && function_->HasMutatedReturn())
  387. numParams--;
  388. for (unsigned int i = 0; i < numParams; i++)
  389. {
  390. source.AppendWithFormat("__arg%i", i);
  391. if (i != numParams - 1)
  392. {
  393. source += ", ";
  394. }
  395. }
  396. source += ");\n";
  397. if (!returnDeclared)
  398. {
  399. if (function_->HasMutatedReturn())
  400. {
  401. // this handles the VariantVector case currently, can be expanded
  402. source.AppendWithFormat("__scriptVectorArg%i->AdaptFromVector(__arg%i);\n", parameters.Size() - 1, parameters.Size() - 1);
  403. }
  404. source += "return 0;\n";
  405. }
  406. else
  407. {
  408. if (returnType->type_->asStringType())
  409. {
  410. source.Append("duk_push_string(ctx, retValue.CString());\n");
  411. }
  412. else if (returnType->type_->asPrimitiveType())
  413. {
  414. JSBPrimitiveType* prtype = returnType->type_->asPrimitiveType();
  415. if (prtype->kind_ == JSBPrimitiveType::Bool)
  416. {
  417. source.Append("duk_push_boolean(ctx, retValue ? 1 : 0);\n");
  418. }
  419. else
  420. {
  421. source.Append("duk_push_number(ctx, retValue);\n");
  422. }
  423. }
  424. else if (returnType->type_->asClassType())
  425. {
  426. JSBClassType* klassType = returnType->type_->asClassType();
  427. if (klassType->class_->IsObject())
  428. {
  429. returnDeclared = true;
  430. source.Append("js_push_class_object_instance(ctx, object);\n");
  431. }
  432. else if (klassType->class_->IsNumberArray())
  433. {
  434. returnDeclared = true;
  435. String elementType = klassType->class_->GetArrayElementType();
  436. source.AppendWithFormat("const %s* arrayData = retValue.Data();\n", elementType.CString());
  437. source.Append("duk_push_array(ctx);\n");
  438. for (int i = 0; i < klassType->class_->GetNumberArrayElements(); i++)
  439. {
  440. source.AppendWithFormat("duk_push_number(ctx, arrayData[%i]);\n", i);
  441. source.AppendWithFormat("duk_put_prop_index(ctx, -2, %i);\n", i);
  442. }
  443. }
  444. else
  445. {
  446. returnDeclared = true;
  447. source.AppendWithFormat("js_push_class_object_instance(ctx, object, \"%s\");\n", klassType->class_->GetName().CString());
  448. }
  449. }
  450. else if (returnType->type_->asEnumType())
  451. {
  452. returnDeclared = true;
  453. source.Append("duk_push_number(ctx, (double) retValue);\n");
  454. }
  455. else if (returnType->type_->asVectorType())
  456. {
  457. JSBType* vectorType = returnType->type_->asVectorType()->vectorType_;
  458. source.Append("duk_push_array(ctx);\n");
  459. source.Append("for (unsigned i = 0; i < retValue.Size(); i++)\n{\n");
  460. if (vectorType->asClassType())
  461. {
  462. source.AppendWithFormat("js_push_class_object_instance(ctx, retValue[i], \"%s\");\n", vectorType->asClassType()->class_->GetName().CString());
  463. }
  464. else
  465. {
  466. source.Append("duk_push_string(ctx, retValue[i].CString());\n");
  467. }
  468. source.Append("duk_put_prop_index(ctx, -2, i);\n}\n");
  469. }
  470. source += "return 1;\n";
  471. }
  472. source.Append("}\n");
  473. }
  474. void JSFunctionWriter::GenerateSource(String& sourceOut)
  475. {
  476. String source = "";
  477. if (function_->IsConstructor())
  478. {
  479. WriteConstructor(source);
  480. }
  481. else
  482. {
  483. WriteFunction(source);
  484. }
  485. sourceOut += source;
  486. }
  487. }