Boot.hx 12 KB

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