Boot.hx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. /*
  2. * Copyright (C)2005-2019 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is 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
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package lua;
  23. import haxe.SysTools;
  24. @:dox(hide)
  25. class Boot {
  26. // Used temporarily for bind()
  27. static var _:Dynamic;
  28. static var _fid = 0;
  29. static var Max_Int32 = 2147483647;
  30. static var Min_Int32 = -2147483648;
  31. // A max stack size to respect for unpack operations
  32. public static var MAXSTACKSIZE(default, null) = 1000;
  33. public static var platformBigEndian = NativeStringTools.byte(NativeStringTools.dump(function() {}), 7) > 0;
  34. static var hiddenFields:Table<String,
  35. Bool> = untyped __lua__("{__id__=true, hx__closures=true, super=true, prototype=true, __fields__=true, __ifields__=true, __class__=true, __properties__=true}");
  36. static function __unhtml(s:String)
  37. return s.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;");
  38. /**
  39. Indicates if the given object is a class.
  40. **/
  41. static inline public function isClass(o:Dynamic):Bool {
  42. if (Lua.type(o) != "table")
  43. return false;
  44. else
  45. return untyped __define_feature__("lua.Boot.isClass", o.__name__);
  46. }
  47. /**
  48. Indicates if the given object is a enum.
  49. **/
  50. static inline public function isEnum(e:Dynamic):Bool {
  51. if (Lua.type(e) != "table")
  52. return false;
  53. else
  54. return untyped __define_feature__("lua.Boot.isEnum", e.__ename__);
  55. }
  56. /**
  57. Returns the class of a given object, and defines the getClass feature
  58. for the given class.
  59. **/
  60. static inline public function getClass(o:Dynamic):Class<Dynamic> {
  61. if (Std.is(o, Array))
  62. return Array;
  63. else if (Std.is(o, String))
  64. return String;
  65. else {
  66. var cl = untyped __define_feature__("lua.Boot.getClass", o.__class__);
  67. if (cl != null)
  68. return cl;
  69. else
  70. return null;
  71. }
  72. }
  73. /**
  74. Indicates if the given object is an instance of the given Type
  75. **/
  76. @:ifFeature("typed_catch")
  77. private static function __instanceof(o:Dynamic, cl:Dynamic) {
  78. if (cl == null)
  79. return false;
  80. switch (cl) {
  81. case Int:
  82. return (Lua.type(o) == "number" && clampInt32(o) == o);
  83. case Float:
  84. return Lua.type(o) == "number";
  85. case Bool:
  86. return Lua.type(o) == "boolean";
  87. case String:
  88. return Lua.type(o) == "string";
  89. case Thread:
  90. return Lua.type(o) == "thread";
  91. case UserData:
  92. return Lua.type(o) == "userdata";
  93. case Array:
  94. return isArray(o);
  95. case Table:
  96. return Lua.type(o) == "table";
  97. case Dynamic:
  98. return o != null;
  99. default:
  100. {
  101. if (o != null && Lua.type(o) == "table" && Lua.type(cl) == "table") {
  102. if (extendsOrImplements(getClass(o), cl))
  103. return true;
  104. // We've exhausted standard inheritance checks. Check for simple Class/Enum eqauality
  105. // Also, do not use isClass/isEnum here, perform raw checks
  106. untyped __feature__("Class.*", if (cl == Class && o.__name__ != null) return true);
  107. untyped __feature__("Enum.*", if (cl == Enum && o.__ename__ != null) return true);
  108. // last chance, is it an enum instance?
  109. return o.__enum__ == cl;
  110. } else {
  111. return false;
  112. }
  113. }
  114. }
  115. }
  116. static function isArray(o:Dynamic):Bool {
  117. return Lua.type(o) == "table"
  118. && untyped o.__enum__ == null && Lua.getmetatable(o) != null && Lua.getmetatable(o).__index == untyped Array.prototype;
  119. }
  120. /**
  121. Indicates if the given object inherits from the given class
  122. **/
  123. static function inheritsFrom(o:Dynamic, cl:Class<Dynamic>):Bool {
  124. while (Lua.getmetatable(o) != null && Lua.getmetatable(o).__index != null) {
  125. if (Lua.getmetatable(o).__index == untyped cl.prototype)
  126. return true;
  127. o = Lua.getmetatable(o).__index;
  128. }
  129. return false;
  130. }
  131. @:ifFeature("typed_cast")
  132. private static function __cast(o:Dynamic, t:Dynamic) {
  133. if (o == null || __instanceof(o, t))
  134. return o;
  135. else
  136. throw "Cannot cast " + Std.string(o) + " to " + Std.string(t);
  137. }
  138. /**
  139. Helper method to generate a string representation of an enum
  140. **/
  141. static function printEnum(o:Array<Dynamic>, s:String) {
  142. if (o.length == 2) {
  143. return o[0];
  144. } else {
  145. // parameterized enums are arrays
  146. var str = o[0] + "(";
  147. s += "\t";
  148. for (i in 2...o.length) {
  149. if (i != 2)
  150. str += "," + __string_rec(o[i], s);
  151. else
  152. str += __string_rec(o[i], s);
  153. }
  154. return str + ")";
  155. }
  156. }
  157. /**
  158. Helper method to generate a string representation of a class
  159. **/
  160. static inline function printClass(c:Table<String, Dynamic>, s:String):String {
  161. return '{${printClassRec(c, '', s)}}';
  162. }
  163. /**
  164. Helper method to generate a string representation of a class
  165. **/
  166. static function printClassRec(c:Table<String, Dynamic>, result = '', s:String):String {
  167. var f = Boot.__string_rec;
  168. untyped __lua__("for k,v in pairs(c) do if result ~= '' then result = result .. ', ' end result = result .. k .. ':' .. f(v, s.. '\t') end");
  169. return result;
  170. }
  171. /**
  172. Generate a string representation for arbitrary object.
  173. **/
  174. @:ifFeature("has_enum")
  175. static function __string_rec(o:Dynamic, s:String = "") {
  176. if (s.length >= 5)
  177. return "<...>";
  178. return switch (untyped __type__(o)) {
  179. case "nil": "null";
  180. case "number": {
  181. if (o == std.Math.POSITIVE_INFINITY)
  182. "Infinity";
  183. else if (o == std.Math.NEGATIVE_INFINITY)
  184. "-Infinity";
  185. else if (o == 0)
  186. "0";
  187. else if (o != o)
  188. "NaN";
  189. else
  190. untyped tostring(o);
  191. }
  192. case "boolean": untyped tostring(o);
  193. case "string": o;
  194. case "userdata": {
  195. var mt = lua.Lua.getmetatable(o);
  196. if (mt != null && mt.__tostring != null) {
  197. lua.Lua.tostring(o);
  198. } else {
  199. "<userdata>";
  200. }
  201. }
  202. case "function": "<function>";
  203. case "thread": "<thread>";
  204. case "table": {
  205. if (o.__enum__ != null)
  206. printEnum(o, s);
  207. else if (o.toString != null && !isArray(o))
  208. o.toString();
  209. else if (isArray(o)) {
  210. var o2:Array<Dynamic> = untyped o;
  211. if (s.length > 5)
  212. "[...]"
  213. else
  214. '[${[for (i in o2) __string_rec(i, s + 1)].join(",")}]';
  215. } else if (o.__class__ != null)
  216. printClass(o, s + "\t");
  217. else {
  218. var fields = fieldIterator(o);
  219. var buffer:Table<Int, String> = Table.create();
  220. var first = true;
  221. Table.insert(buffer, "{ ");
  222. for (f in fields) {
  223. if (first)
  224. first = false;
  225. else
  226. Table.insert(buffer, ", ");
  227. Table.insert(buffer, '${Std.string(f)} : ${untyped __string_rec(o[f], s + "\t")}');
  228. }
  229. Table.insert(buffer, " }");
  230. Table.concat(buffer, "");
  231. }
  232. };
  233. default: {
  234. throw "Unknown Lua type";
  235. null;
  236. }
  237. }
  238. }
  239. /**
  240. Define an array from the given table
  241. **/
  242. public inline static function defArray<T>(tab:Table<Int, T>, ?length:Int):Array<T> {
  243. if (length == null) {
  244. length = TableTools.maxn(tab);
  245. if (length > 0) {
  246. var head = tab[1];
  247. Table.remove(tab, 1);
  248. tab[0] = head;
  249. return untyped _hx_tab_array(tab, length);
  250. } else {
  251. return [];
  252. }
  253. } else {
  254. return untyped _hx_tab_array(tab, length);
  255. }
  256. }
  257. /**
  258. Create a Haxe object from the given table structure
  259. **/
  260. public inline static function tableToObject<T>(t:Table<String, T>):Dynamic<T> {
  261. return untyped _hx_o(t);
  262. }
  263. /**
  264. Get Date object as string representation
  265. **/
  266. public static function dateStr(date:std.Date):String {
  267. var m = date.getMonth() + 1;
  268. var d = date.getDate();
  269. var h = date.getHours();
  270. var mi = date.getMinutes();
  271. var s = date.getSeconds();
  272. return date.getFullYear() + "-" + (if (m < 10) "0" + m else "" + m) + "-" + (if (d < 10) "0" + d else "" + d) + " "
  273. + (if (h < 10) "0" + h else "" + h) + ":" + (if (mi < 10) "0" + mi else "" + mi) + ":" + (if (s < 10) "0" + s else "" + s);
  274. }
  275. /**
  276. A 32 bit clamp function for numbers
  277. **/
  278. public inline static function clampInt32(x:Float) {
  279. return untyped _hx_bit_clamp(x);
  280. }
  281. /**
  282. Create a standard date object from a lua string representation
  283. **/
  284. public static function strDate(s:String):std.Date {
  285. switch (s.length) {
  286. case 8: // hh:mm:ss
  287. var k = s.split(":");
  288. return std.Date.fromTime(Lua.tonumber(k[0]) * 3600000. + Lua.tonumber(k[1]) * 60000. + Lua.tonumber(k[2]) * 1000.);
  289. case 10: // YYYY-MM-DD
  290. var k = s.split("-");
  291. return new std.Date(Lua.tonumber(k[0]), Lua.tonumber(k[1]) - 1, Lua.tonumber(k[2]), 0, 0, 0);
  292. case 19: // YYYY-MM-DD hh:mm:ss
  293. var k = s.split(" ");
  294. var y = k[0].split("-");
  295. var t = k[1].split(":");
  296. return new std.Date(Lua.tonumber(y[0]), Lua.tonumber(y[1]) - 1, Lua.tonumber(y[2]), Lua.tonumber(t[0]), Lua.tonumber(t[1]), Lua.tonumber(t[2]));
  297. default:
  298. throw "Invalid date format : " + s;
  299. }
  300. }
  301. /**
  302. Helper method to determine if class cl1 extends, implements, or otherwise equals cl2
  303. **/
  304. public static function extendsOrImplements(cl1:Class<Dynamic>, cl2:Class<Dynamic>):Bool {
  305. if (cl1 == null || cl2 == null)
  306. return false;
  307. else if (cl1 == cl2)
  308. return true;
  309. else if (untyped cl1.__interfaces__ != null) {
  310. var intf = untyped cl1.__interfaces__;
  311. for (i in 1...(TableTools.maxn(intf) + 1)) {
  312. // check each interface, including extended interfaces
  313. if (extendsOrImplements(intf[i], cl2))
  314. return true;
  315. }
  316. }
  317. // check standard inheritance
  318. return extendsOrImplements(untyped cl1.__super__, cl2);
  319. }
  320. /**
  321. Returns a shell escaped version of "cmd" along with any args
  322. **/
  323. public static function shellEscapeCmd(cmd:String, ?args:Array<String>) {
  324. if (args != null) {
  325. switch (Sys.systemName()) {
  326. case "Windows":
  327. cmd = [
  328. for (a in [StringTools.replace(cmd, "/", "\\")].concat(args))
  329. SysTools.quoteWinArg(a, true)
  330. ].join(" ");
  331. case _:
  332. cmd = [cmd].concat(args).map(SysTools.quoteUnixArg).join(" ");
  333. }
  334. }
  335. return cmd;
  336. }
  337. /**
  338. Returns a temp file path that can be used for reading and writing
  339. **/
  340. public static function tempFile():String {
  341. switch (Sys.systemName()) {
  342. case "Windows":
  343. return haxe.io.Path.join([Os.getenv("TMP"), Os.tmpname()]);
  344. default:
  345. return Os.tmpname();
  346. }
  347. }
  348. public static function fieldIterator(o:Table<String, Dynamic>):Iterator<String> {
  349. if (Lua.type(o) != "table") {
  350. return {
  351. next: function() return null,
  352. hasNext: function() return false
  353. }
  354. }
  355. var tbl:Table<String, String> = cast(untyped o.__fields__ != null) ? o.__fields__ : o;
  356. var cur = Lua.pairs(tbl).next;
  357. var next_valid = function(tbl, val) {
  358. while (hiddenFields[untyped val] != null) {
  359. val = cur(tbl, val).index;
  360. }
  361. return val;
  362. }
  363. var cur_val = next_valid(tbl, cur(tbl, null).index);
  364. return {
  365. next: function() {
  366. var ret = cur_val;
  367. cur_val = next_valid(tbl, cur(tbl, cur_val).index);
  368. return ret;
  369. },
  370. hasNext: function() return cur_val != null
  371. }
  372. }
  373. static var os_patterns = [
  374. 'Windows' => ['windows', '^mingw', '^cygwin'],
  375. 'Linux' => ['linux'],
  376. 'Mac' => ['mac', 'darwin', 'osx'],
  377. 'BSD' => ['bsd$'],
  378. 'Solaris' => ['SunOS']
  379. ];
  380. public static function systemName():String {
  381. var os:String = null;
  382. if (untyped jit != null && untyped jit.os != null) {
  383. os = untyped jit.os;
  384. os = os.toLowerCase();
  385. } else {
  386. var popen_status:Bool = false;
  387. var popen_result:lua.FileHandle = null;
  388. untyped __lua__("popen_status, popen_result = pcall(_G.io.popen, '')");
  389. if (popen_status) {
  390. popen_result.close();
  391. os = lua.Io.popen('uname -s', 'r').read('*l').toLowerCase();
  392. } else {
  393. os = lua.Os.getenv('OS').toLowerCase();
  394. }
  395. }
  396. for (k in os_patterns.keys()) {
  397. for (p in os_patterns.get(k)) {
  398. if (lua.NativeStringTools.match(os, p) != null) {
  399. return k;
  400. }
  401. }
  402. }
  403. return null;
  404. }
  405. }