Boot.hx 12 KB

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