Boot.hx 12 KB

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