Boot.hx 12 KB

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