2
0

Boot.hx 12 KB

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