Boot.hx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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 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 != o) "NaN";
  165. else untyped tostring(o);
  166. }
  167. case "boolean" : untyped tostring(o);
  168. case "string" : o;
  169. case "userdata": "<userdata>";
  170. case "function": "<function>";
  171. case "thread" : "<thread>";
  172. case "table": {
  173. if (o.__enum__ != null) printEnum(o,s);
  174. else if (o.toString != null && !isArray(o)) o.toString();
  175. else if (isArray(o)) {
  176. var o2 : Array<Dynamic> = untyped o;
  177. if (s.length > 5) "[...]"
  178. else '[${[for (i in o2) __string_rec(i,s+1)].join(",")}]';
  179. }
  180. else if (o.__class__ != null) printClass(o,s+"\t");
  181. else {
  182. var fields = fieldIterator(o);
  183. var buffer:Table<Int,String> = Table.create();
  184. var first = true;
  185. Table.insert(buffer,"{ ");
  186. for (f in fields){
  187. if (first) first = false;
  188. else Table.insert(buffer,", ");
  189. Table.insert(buffer,'${Std.string(f)} : ${untyped Std.string(o[f])}');
  190. }
  191. Table.insert(buffer, " }");
  192. Table.concat(buffer, "");
  193. }
  194. };
  195. default : {
  196. throw "Unknown Lua type";
  197. null;
  198. }
  199. }
  200. }
  201. /*
  202. Define an array from the given table
  203. */
  204. public inline static function defArray<T>(tab: Table<Int,T>, ?length : Int) : Array<T> {
  205. if (length == null) length = TableTools.maxn(tab) + 1; // maxn doesn't count 0 index
  206. return untyped _hx_tab_array(tab, length);
  207. }
  208. /*
  209. Create a Haxe object from the given table structure
  210. */
  211. public inline static function tableToObject<T>(t:Table<String,T>) : Dynamic<T> {
  212. return untyped _hx_o(t);
  213. }
  214. /*
  215. Get Date object as string representation
  216. */
  217. public static function dateStr( date : std.Date ) : String {
  218. var m = date.getMonth() + 1;
  219. var d = date.getDate();
  220. var h = date.getHours();
  221. var mi = date.getMinutes();
  222. var s = date.getSeconds();
  223. return date.getFullYear()
  224. +"-"+(if( m < 10 ) "0"+m else ""+m)
  225. +"-"+(if( d < 10 ) "0"+d else ""+d)
  226. +" "+(if( h < 10 ) "0"+h else ""+h)
  227. +":"+(if( mi < 10 ) "0"+mi else ""+mi)
  228. +":"+(if( s < 10 ) "0"+s else ""+s);
  229. }
  230. /*
  231. A 32 bit clamp function for numbers
  232. */
  233. public inline static function clamp(x:Float){
  234. return untyped __define_feature__("lua.Boot.clamp", _hx_bit_clamp(x));
  235. }
  236. /*
  237. Create a standard date object from a lua string representation
  238. */
  239. public static function strDate( s : String ) : std.Date {
  240. switch( s.length ) {
  241. case 8: // hh:mm:ss
  242. var k = s.split(":");
  243. var t = lua.Os.time({
  244. year : 0,
  245. month : 1,
  246. day : 1,
  247. hour : Lua.tonumber(k[0]),
  248. min : Lua.tonumber(k[1]),
  249. sec : Lua.tonumber(k[2])
  250. });
  251. return std.Date.fromTime(t);
  252. case 10: // YYYY-MM-DD
  253. var k = s.split("-");
  254. return new std.Date(Lua.tonumber(k[0]), Lua.tonumber(k[1]) - 1, Lua.tonumber(k[2]),0,0,0);
  255. case 19: // YYYY-MM-DD hh:mm:ss
  256. var k = s.split(" ");
  257. var y = k[0].split("-");
  258. var t = k[1].split(":");
  259. 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]));
  260. default:
  261. throw "Invalid date format : " + s;
  262. }
  263. }
  264. /*
  265. Helper method to determine if class cl1 extends, implements, or otherwise equals cl2
  266. */
  267. public static function extendsOrImplements(cl1 : Class<Dynamic>, cl2 : Class<Dynamic>) : Bool {
  268. if (cl1 == null || cl2 == null) return false;
  269. else if (cl1 == cl2) return true;
  270. else if (untyped cl1.__interfaces__ != null) {
  271. var intf = untyped cl1.__interfaces__;
  272. for (i in 1...( TableTools.maxn(intf) + 1)){
  273. // check each interface, including extended interfaces
  274. if (extendsOrImplements(intf[i], cl2)) return true;
  275. }
  276. }
  277. // check standard inheritance
  278. return extendsOrImplements(untyped cl1.__super__, cl2);
  279. }
  280. /*
  281. Returns a shell escaped version of "cmd" along with any args
  282. */
  283. public static function shellEscapeCmd(cmd : String, ?args : Array<String>){
  284. if (args != null) {
  285. switch (Sys.systemName()) {
  286. case "Windows":
  287. cmd = [
  288. for (a in [StringTools.replace(cmd, "/", "\\")].concat(args))
  289. StringTools.quoteWinArg(a, true)
  290. ].join(" ");
  291. case _:
  292. cmd = [cmd].concat(args).map(StringTools.quoteUnixArg).join(" ");
  293. }
  294. }
  295. return cmd;
  296. }
  297. /*
  298. Returns a temp file path that can be used for reading and writing
  299. */
  300. public static function tempFile() : String {
  301. switch (Sys.systemName()){
  302. case "Windows" : return haxe.io.Path.join([Os.getenv("TMP"), Os.tmpname()]);
  303. default : return Os.tmpname();
  304. }
  305. }
  306. public static function fieldIterator( o : Table<String,Dynamic>) : Iterator<String> {
  307. if (Lua.type(o) != "table") {
  308. return {
  309. next : function() return null,
  310. hasNext : function() return false
  311. }
  312. }
  313. var tbl : Table<String,String> = cast (untyped o.__fields__ != null) ? o.__fields__ : o;
  314. var cur = Lua.pairs(tbl).next;
  315. var next_valid = function(tbl, val){
  316. while (hiddenFields[untyped val] != null){
  317. val = cur(tbl, val).index;
  318. }
  319. return val;
  320. }
  321. var cur_val = next_valid(tbl, cur(tbl, null).index);
  322. return {
  323. next : function(){
  324. var ret = cur_val;
  325. cur_val = next_valid(tbl, cur(tbl, cur_val).index);
  326. return ret;
  327. },
  328. hasNext : function() return cur_val != null
  329. }
  330. }
  331. static var os_patterns = [
  332. 'Windows' => ['windows','^mingw','^cygwin'],
  333. 'Linux' => ['linux'],
  334. 'Mac' => ['mac','darwin'],
  335. 'BSD' => ['bsd$'],
  336. 'Solaris' => ['SunOS']
  337. ];
  338. public static function systemName() : String {
  339. var os : String = null;
  340. if (untyped jit != null && untyped jit.os != null ){
  341. os = untyped jit.os;
  342. os = os.toLowerCase();
  343. } else {
  344. var popen_status : Bool = false;
  345. var popen_result : lua.FileHandle = null;
  346. untyped __lua__("popen_status, popen_result = pcall(_G.io.popen, '')");
  347. if (popen_status) {
  348. popen_result.close;
  349. os = lua.Io.popen('uname -s','r').read('*l').toLowerCase();
  350. } else {
  351. os = lua.Os.getenv('OS').toLowerCase();
  352. }
  353. }
  354. for (k in os_patterns.keys()){
  355. for (p in os_patterns.get(k)) {
  356. if (lua.NativeStringTools.match(os,p) != null){
  357. return k;
  358. }
  359. }
  360. }
  361. return null;
  362. }
  363. }