CSFunctionWriter.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. //
  2. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  3. // LICENSE: Atomic Game Engine Editor and Tools EULA
  4. // Please see LICENSE_ATOMIC_EDITOR_AND_TOOLS.md in repository root for
  5. // license information: https://github.com/AtomicGameEngine/AtomicGameEngine
  6. //
  7. #include <Atomic/IO/FileSystem.h>
  8. #include "../JSBind.h"
  9. #include "../JSBModule.h"
  10. #include "../JSBPackage.h"
  11. #include "../JSBEnum.h"
  12. #include "../JSBClass.h"
  13. #include "../JSBFunction.h"
  14. #include "CSTypeHelper.h"
  15. #include "CSFunctionWriter.h"
  16. /*
  17. *
  18. C# getters/setters
  19. local instance storage so we're not constantly creating managed Vector3, etc
  20. Vector2/Vector3/BoundingBox, etc C# structs so assign by value
  21. Object lifetime
  22. C# enum of module types for type info?
  23. C# version of push class instance?
  24. new instance from C# needs constructor
  25. wrapping does not, wrapping doesn't use constructors at all (JS needs this for prototype)
  26. Store GCHandle to keep an object alive (Component, UI) C# side?
  27. typedef const void* ClassID;
  28. which changed based on address, so need register at startup
  29. so at package startup time, need to setup mapping between
  30. IntPtr and C# class, we also need to be able to new a class
  31. instance with existing native or create a native when new'ing from C#
  32. IntPtr to RefCounted native side is the "ID", like JSHeapPtr
  33. Lifetime:
  34. // you cannot derive from native engine classes, other than script components
  35. a C# instance can be new'd, handed to native, stored in native, the C# side could be GC'd
  36. future access to this instance would be a new instance
  37. */
  38. /*
  39. // struct marshal Vector2, Vector3, BoundingBox, etc
  40. // RefCounted*
  41. // primitive bool, int, uint, float, double
  42. // String
  43. RefCounted* csb_Node_Constructor()
  44. {
  45. return new Node(NETCore::GetContext());
  46. }
  47. void csb_Node_GetPosition(Node* self, Vector3* out)
  48. {
  49. *out = self->GetPosition();
  50. }
  51. void csb_Node_SetPosition(Node* self, Vector3*__arg0)
  52. {
  53. self->SetPosition(*__arg0);
  54. }
  55. void csb_Node_SetPosition(Node* self, Vector3*__arg0)
  56. {
  57. self->SetPosition(*__arg0);
  58. }
  59. bool csb_Audio_Play(Audio* self)
  60. {
  61. bool retValue = self->Play();
  62. return retValue;
  63. }
  64. const RefCounted* csb_Node_GetParent(Node* self)
  65. {
  66. const RefCounted* retValue = self->GetParent();
  67. return RefCounted;
  68. }
  69. RefCounted* csb_ObjectAnimation_Constructor()
  70. {
  71. return new ObjectAnimation(NETCore::GetContext());
  72. }
  73. */
  74. namespace ToolCore
  75. {
  76. CSFunctionWriter::CSFunctionWriter(JSBFunction *function) : JSBFunctionWriter(function)
  77. {
  78. }
  79. void CSFunctionWriter::WriteNativeParameterMarshal(String& source)
  80. {
  81. }
  82. void CSFunctionWriter::WriteNativeConstructor(String& source)
  83. {
  84. }
  85. void CSFunctionWriter::GenNativeCallParameters(String& sig)
  86. {
  87. JSBClass* klass = function_->GetClass();
  88. Vector<JSBFunctionType*>& parameters = function_->GetParameters();
  89. Vector<String> args;
  90. if (parameters.Size())
  91. {
  92. for (unsigned int i = 0; i < parameters.Size(); i++)
  93. {
  94. JSBFunctionType* ptype = parameters.At(i);
  95. // ignore "Context" parameters
  96. if (ptype->type_->asClassType())
  97. {
  98. JSBClassType* classType = ptype->type_->asClassType();
  99. JSBClass* klass = classType->class_;
  100. if (klass->GetName() == "Context")
  101. {
  102. continue;
  103. }
  104. if (klass->IsNumberArray())
  105. args.Push(ToString("*%s", ptype->name_.CString()));
  106. else
  107. args.Push(ToString("%s", ptype->name_.CString()));
  108. }
  109. else
  110. {
  111. args.Push(ToString("%s", ptype->name_.CString()));
  112. }
  113. }
  114. }
  115. sig.Join(args, ", ");
  116. }
  117. void CSFunctionWriter::WriteNativeFunction(String& source)
  118. {
  119. JSBClass* klass = function_->GetClass();
  120. JSBPackage* package = klass->GetPackage();
  121. String fname = function_->IsConstructor() ? "Constructor" : function_->GetName();
  122. String returnType;
  123. String functionSig = CSTypeHelper::GetNativeFunctionSignature(function_, returnType);
  124. String line;
  125. line = ToString("ATOMIC_EXPORT_API %s %s\n",
  126. returnType.CString(), functionSig.CString());
  127. source += IndentLine(line);
  128. source += IndentLine("{\n");
  129. Indent();
  130. source += "\n";
  131. bool returnValue = false;
  132. bool sharedPtrReturn = false;
  133. String returnStatement;
  134. if (returnType == "const char*")
  135. {
  136. returnValue = true;
  137. source += IndentLine("static String returnValue;\n");
  138. returnStatement = "returnValue = ";
  139. }
  140. else if (function_->GetReturnClass() && function_->GetReturnClass()->IsNumberArray())
  141. {
  142. returnStatement = "*returnValue = ";
  143. }
  144. else if (function_->GetReturnClass() && function_->GetReturnType()->isSharedPtr_)
  145. {
  146. returnStatement = ToString("SharedPtr<%s> returnValue = ", function_->GetReturnClass()->GetNativeName().CString());
  147. sharedPtrReturn = true;
  148. }
  149. else
  150. {
  151. if (returnType != "void")
  152. {
  153. returnStatement = "return ";
  154. }
  155. }
  156. String callSig;
  157. GenNativeCallParameters(callSig);
  158. if (!function_->isConstructor_)
  159. line = ToString("%sself->%s(%s);\n", returnStatement.CString(), function_->GetName().CString(), callSig.CString());
  160. else
  161. {
  162. if (klass->IsAbstract())
  163. {
  164. line = "return 0; // Abstract Class\n";
  165. }
  166. else if (klass->IsObject())
  167. {
  168. if (callSig.Length())
  169. line = ToString("return new %s(NETCore::GetContext(), %s);\n", klass->GetNativeName().CString(), callSig.CString());
  170. else
  171. line = ToString("return new %s(NETCore::GetContext());\n", klass->GetNativeName().CString());
  172. }
  173. else
  174. {
  175. line = ToString("return new %s(%s);\n", klass->GetNativeName().CString(), callSig.CString());
  176. }
  177. }
  178. source += IndentLine(line);
  179. if (sharedPtrReturn)
  180. {
  181. source += IndentLine("returnValue->AddRef();\n");
  182. source += IndentLine("return returnValue;\n");
  183. }
  184. else if (returnType == "const char*")
  185. {
  186. source += IndentLine("return returnValue.CString();\n");
  187. }
  188. Dedent();
  189. source += IndentLine("}\n");
  190. source += "\n";
  191. }
  192. void CSFunctionWriter::GenerateNativeSource(String& sourceOut)
  193. {
  194. String source = "";
  195. WriteNativeFunction(source);
  196. sourceOut += source;
  197. }
  198. // MANAGED----------------------------------------------------------------------------------------
  199. void CSFunctionWriter::WriteDefaultStructParameters(String& source)
  200. {
  201. for (unsigned i = 0; i < defaultStructParameters_.Size(); i++)
  202. {
  203. const DefaultStructParameter& dparm = defaultStructParameters_[i];
  204. String line = ToString("if (default(%s).Equals(%s)) %s = %s;\n",
  205. dparm.type.CString(), dparm.parameterName.CString(), dparm.parameterName.CString(),
  206. dparm.assignment.CString());
  207. source += IndentLine(line);
  208. }
  209. }
  210. void CSFunctionWriter::WriteManagedPInvokeFunctionSignature(String& source)
  211. {
  212. source += "\n";
  213. // CoreCLR has pinvoke security demand code commented out, so we do not (currently) need this optimization:
  214. // https://github.com/dotnet/coreclr/issues/1605
  215. // line = "[SuppressUnmanagedCodeSecurity]\n";
  216. // source += IndentLine(line);
  217. String line = "[DllImport (Constants.LIBNAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]\n";
  218. source += IndentLine(line);
  219. JSBClass* klass = function_->GetClass();
  220. JSBPackage* package = klass->GetPackage();
  221. String returnType = CSTypeHelper::GetPInvokeTypeString(function_->GetReturnType());
  222. if (returnType == "string")
  223. returnType = "IntPtr";
  224. if (function_->IsConstructor())
  225. returnType = "IntPtr";
  226. Vector<JSBFunctionType*>& parameters = function_->GetParameters();
  227. Vector<String> args;
  228. if (!function_->IsConstructor())
  229. {
  230. args.Push("IntPtr self");
  231. }
  232. if (parameters.Size())
  233. {
  234. for (unsigned int i = 0; i < parameters.Size(); i++)
  235. {
  236. JSBFunctionType* ptype = parameters.At(i);
  237. String name = ptype->name_;
  238. if (name == "object")
  239. name = "_object";
  240. else if (name == "readonly")
  241. name = "readOnly";
  242. else if (name == "params")
  243. name = "parameters";
  244. // ignore "Context" parameters
  245. if (ptype->type_->asClassType())
  246. {
  247. JSBClassType* classType = ptype->type_->asClassType();
  248. JSBClass* klass = classType->class_;
  249. if (klass->GetName() == "Context")
  250. {
  251. continue;
  252. }
  253. if (klass->IsNumberArray())
  254. {
  255. args.Push("ref " + klass->GetName() + " " + name);
  256. }
  257. else
  258. {
  259. args.Push("IntPtr " + name);
  260. }
  261. }
  262. else
  263. {
  264. args.Push(CSTypeHelper::GetPInvokeTypeString(ptype) + " " + name);
  265. }
  266. }
  267. }
  268. if (function_->GetReturnClass())
  269. {
  270. JSBClass* retClass = function_->GetReturnClass();
  271. if (retClass->IsNumberArray())
  272. {
  273. args.Push("ref " + retClass->GetName() + " retValue");
  274. }
  275. }
  276. String pstring;
  277. pstring.Join(args, ", ");
  278. String fname = function_->IsConstructor() ? "Constructor" : function_->GetName();
  279. line = ToString("private static extern %s csb_%s_%s_%s(%s);\n",
  280. returnType.CString(), package->GetName().CString(), klass->GetName().CString(),
  281. fname.CString(), pstring.CString());
  282. source += IndentLine(line);
  283. source += "\n";
  284. }
  285. void CSFunctionWriter::GenManagedFunctionParameters(String& sig)
  286. {
  287. // generate args
  288. Vector<JSBFunctionType*>& parameters = function_->GetParameters();
  289. if (parameters.Size())
  290. {
  291. for (unsigned int i = 0; i < parameters.Size(); i++)
  292. {
  293. JSBFunctionType* ptype = parameters.At(i);
  294. // ignore "Context" parameters
  295. if (ptype->type_->asClassType())
  296. {
  297. JSBClassType* classType = ptype->type_->asClassType();
  298. JSBClass* klass = classType->class_;
  299. if (klass->GetName() == "Context")
  300. {
  301. continue;
  302. }
  303. }
  304. sig += CSTypeHelper::GetManagedTypeString(ptype);
  305. String init = ptype->initializer_;
  306. if (init.Length())
  307. {
  308. init = MapDefaultParameter(ptype);
  309. if (init.Length())
  310. sig += " = " + init;
  311. }
  312. if (i + 1 != parameters.Size())
  313. sig += ", ";
  314. }
  315. }
  316. }
  317. void CSFunctionWriter::WriteManagedConstructor(String& source)
  318. {
  319. JSBClass* klass = function_->GetClass();
  320. JSBPackage* package = klass->GetPackage();
  321. if (klass->GetName() == "RefCounted")
  322. return;
  323. // wrapping constructor
  324. String line;
  325. line = ToString("public %s (IntPtr native) : base (native)\n", klass->GetName().CString());
  326. source += IndentLine(line);
  327. source += IndentLine("{\n");
  328. source += IndentLine("}\n\n");
  329. String sig;
  330. GenManagedFunctionParameters(sig);
  331. line = ToString("public %s (%s)\n", klass->GetName().CString(), sig.CString());
  332. source += IndentLine(line);
  333. source += IndentLine("{\n");
  334. Indent();
  335. WriteDefaultStructParameters(source);
  336. line = ToString("if (typeof(%s) == this.GetType()", klass->GetName().CString());
  337. line += ToString(" || (this.GetType().BaseType == typeof(%s) && !NativeCore.GetNativeType(this.GetType())))\n", klass->GetName().CString());
  338. source += IndentLine(line);
  339. source += IndentLine("{\n");
  340. Indent();
  341. String callSig;
  342. GenPInvokeCallParameters(callSig);
  343. line = ToString("nativeInstance = NativeCore.RegisterNative (csb_%s_%s_Constructor(%s), this);\n",
  344. package->GetName().CString(), klass->GetName().CString(), callSig.CString());
  345. source += IndentLine(line);
  346. Dedent();
  347. source += IndentLine("}\n");
  348. Dedent();
  349. source += IndentLine("}\n");
  350. }
  351. void CSFunctionWriter::GenPInvokeCallParameters(String& sig)
  352. {
  353. // generate args
  354. Vector<JSBFunctionType*>& parameters = function_->GetParameters();
  355. if (parameters.Size())
  356. {
  357. for (unsigned int i = 0; i < parameters.Size(); i++)
  358. {
  359. JSBFunctionType* ptype = parameters.At(i);
  360. // ignore "Context" parameters
  361. if (ptype->type_->asClassType())
  362. {
  363. JSBClassType* classType = ptype->type_->asClassType();
  364. JSBClass* klass = classType->class_;
  365. if (klass->GetName() == "Context")
  366. {
  367. continue;
  368. }
  369. }
  370. String name = ptype->name_;
  371. if (name == "object")
  372. name = "_object";
  373. else if (name == "readonly")
  374. name = "readOnly";
  375. else if (name == "params")
  376. name = "parameters";
  377. if (ptype->type_->asClassType())
  378. {
  379. JSBClass* pclass = ptype->type_->asClassType()->class_;
  380. if (pclass->IsNumberArray())
  381. {
  382. sig += "ref " + name;
  383. }
  384. else
  385. {
  386. sig += name + " == null ? IntPtr.Zero : " + name + ".nativeInstance";
  387. }
  388. }
  389. else
  390. {
  391. sig += name;
  392. }
  393. if (i + 1 != parameters.Size())
  394. sig += ", ";
  395. }
  396. }
  397. // data marshaller
  398. if (function_->GetReturnType() && !CSTypeHelper::IsSimpleReturn(function_->GetReturnType()))
  399. {
  400. if (function_->GetReturnClass()->IsNumberArray())
  401. {
  402. if (sig.Length())
  403. sig += ", ";
  404. JSBClass* klass = function_->GetClass();
  405. sig += ToString("ref %s%sReturnValue", klass->GetName().CString(), function_->GetName().CString());
  406. }
  407. }
  408. }
  409. void CSFunctionWriter::WriteManagedFunction(String& source)
  410. {
  411. JSBClass* klass = function_->GetClass();
  412. JSBPackage* package = klass->GetPackage();
  413. String sig;
  414. String returnType = CSTypeHelper::GetManagedTypeString(function_->GetReturnType());
  415. GenManagedFunctionParameters(sig);
  416. String line = ToString("public %s %s (%s)\n", returnType.CString(), function_->GetName().CString(), sig.CString());
  417. source += IndentLine(line);
  418. source += IndentLine("{\n");
  419. Indent();
  420. WriteDefaultStructParameters(source);
  421. line.Clear();
  422. if (function_->GetReturnType())
  423. {
  424. if (function_->GetReturnType()->type_->asStringType() || function_->GetReturnType()->type_->asStringHashType())
  425. {
  426. line += "return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(";
  427. }
  428. else if (CSTypeHelper::IsSimpleReturn(function_->GetReturnType()))
  429. line += "return ";
  430. else
  431. {
  432. if (function_->GetReturnClass())
  433. {
  434. if (!function_->GetReturnClass()->IsNumberArray())
  435. line += "IntPtr retNativeInstance = ";
  436. }
  437. }
  438. }
  439. String callSig;
  440. GenPInvokeCallParameters(callSig);
  441. line += ToString("csb_%s_%s_%s(nativeInstance",
  442. package->GetName().CString(), klass->GetName().CString(), function_->GetName().CString());
  443. if (callSig.Length())
  444. {
  445. line += ", " + callSig;
  446. }
  447. if (function_->GetReturnType())
  448. {
  449. if (function_->GetReturnType()->type_->asStringType() || function_->GetReturnType()->type_->asStringHashType())
  450. line += ")";
  451. }
  452. line += ");\n";
  453. source += IndentLine(line);
  454. if (function_->GetReturnType() && !CSTypeHelper::IsSimpleReturn(function_->GetReturnType()))
  455. {
  456. if (function_->GetReturnType()->type_->asClassType())
  457. {
  458. JSBClass* retClass = function_->GetReturnClass();
  459. JSBClass* klass = function_->GetClass();
  460. if (retClass->IsNumberArray())
  461. {
  462. line = ToString("return %s%sReturnValue;", klass->GetName().CString(), function_->GetName().CString());
  463. }
  464. else
  465. {
  466. line = ToString("return retNativeInstance == IntPtr.Zero ? null : NativeCore.WrapNative<%s> (retNativeInstance);", retClass->GetName().CString());
  467. }
  468. source += IndentLine(line);
  469. }
  470. }
  471. source+= "\n";
  472. Dedent();
  473. source += IndentLine("}\n");
  474. }
  475. void CSFunctionWriter::GenerateManagedSource(String& sourceOut)
  476. {
  477. String source = "";
  478. Indent();
  479. Indent();
  480. Indent();
  481. if (function_->GetDocString().Length())
  482. {
  483. // monodocer -assembly:NETCore.dll -path:en -pretty
  484. // mdoc export-html -o htmldocs en
  485. source += IndentLine("/// <summary>\n");
  486. source += IndentLine("/// " + function_->GetDocString() + "\n");
  487. source += IndentLine("/// </summary>\n");
  488. }
  489. if (function_->IsConstructor())
  490. WriteManagedConstructor(source);
  491. else
  492. WriteManagedFunction(source);
  493. WriteManagedPInvokeFunctionSignature(source);
  494. // data marshaller
  495. if (function_->GetReturnType() && !CSTypeHelper::IsSimpleReturn(function_->GetReturnType()))
  496. {
  497. if (function_->GetReturnClass())
  498. {
  499. JSBClass* retClass = function_->GetReturnClass();
  500. if (retClass->IsNumberArray())
  501. {
  502. JSBClass* klass = function_->GetClass();
  503. String managedType = CSTypeHelper::GetManagedTypeString(function_->GetReturnType());
  504. String marshal = "private " + managedType + " ";
  505. marshal += ToString("%s%sReturnValue = new %s();\n", klass->GetName().CString(), function_->GetName().CString(), managedType.CString());
  506. sourceOut += IndentLine(marshal);
  507. }
  508. }
  509. }
  510. Dedent();
  511. Dedent();
  512. Dedent();
  513. sourceOut += source;
  514. }
  515. void CSFunctionWriter::GenerateSource(String& sourceOut)
  516. {
  517. }
  518. String CSFunctionWriter::MapDefaultParameter(JSBFunctionType* parameter)
  519. {
  520. String init = parameter->initializer_;
  521. if (!init.Length())
  522. return init;
  523. if (parameter->type_->asClassType())
  524. {
  525. if (init == "0")
  526. return "null";
  527. }
  528. if (parameter->type_->asEnumType())
  529. {
  530. return parameter->type_->asEnumType()->enum_->GetName() + "." + init;
  531. }
  532. if (function_->class_->GetPackage()->ContainsConstant(init))
  533. return "Constants." + init;
  534. if (init == "true" || init == "false")
  535. return init;
  536. if (init == "0.0f")
  537. return init;
  538. if (init == "1.0f")
  539. return init;
  540. if (init == "0.1f")
  541. return init;
  542. if (init == "0")
  543. return init;
  544. if (init == "-1")
  545. return init;
  546. if (init == "\"\\t\"")
  547. return init;
  548. if (init == "NULL")
  549. return "null";
  550. if (init == "M_MAX_UNSIGNED")
  551. return "0xffffffff";
  552. if (init == "String::EMPTY")
  553. return "\"\"";
  554. // this kind of sucks, can't define const structs
  555. // and default parameters need to be const :/
  556. DefaultStructParameter dparm;
  557. dparm.parameterName = parameter->name_;
  558. if (init == "Vector3::ZERO")
  559. {
  560. dparm.type = "Vector3";
  561. dparm.assignment = "Vector3.Zero";
  562. defaultStructParameters_.Push(dparm);
  563. return "default(Vector3)";
  564. }
  565. if (init == "Vector3::ONE")
  566. {
  567. dparm.type = "Vector3";
  568. dparm.assignment = "Vector3.One";
  569. defaultStructParameters_.Push(dparm);
  570. return "default(Vector3)";
  571. }
  572. if (init == "Vector3::UP")
  573. {
  574. dparm.type = "Vector3";
  575. dparm.assignment = "Vector3.Up";
  576. defaultStructParameters_.Push(dparm);
  577. return "default(Vector3)";
  578. }
  579. if (init == "IntVector2::ZERO")
  580. {
  581. dparm.type = "IntVector2";
  582. dparm.assignment = "IntVector2.Zero";
  583. defaultStructParameters_.Push(dparm);
  584. return "default(IntVector2)";
  585. }
  586. if (init == "Quaternion::IDENTITY")
  587. {
  588. dparm.type = "Quaternion";
  589. dparm.assignment = "Quaternion.Identity";
  590. defaultStructParameters_.Push(dparm);
  591. return "default(Quaternion)";
  592. }
  593. LOGINFOF("HEY! %s", init.CString());
  594. return String::EMPTY;
  595. }
  596. }