Boot.hx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. /*
  2. * Copyright (C)2005-2012 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. // Bit and Table must be imported for basic Haxe datatypes to work.
  24. import lua.Bit;
  25. import lua.Table;
  26. import lua.Thread;
  27. import haxe.io.Path;
  28. import haxe.Constraints.Function;
  29. using lua.PairTools;
  30. @:dox(hide)
  31. class Boot {
  32. // Used temporarily for bind()
  33. static var _;
  34. static var _fid = 0;
  35. public static var platformBigEndian = NativeStringTools.byte(NativeStringTools.dump(function(){}),7) > 0;
  36. public static var hiddenFields = [
  37. "__id__", "hx__closures", "super",
  38. "prototype", "__fields__", "__ifields__", "__class__", "__properties__"
  39. ];
  40. static function __unhtml(s : String)
  41. return s.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;");
  42. /*
  43. Binds a function definition to the given instance
  44. */
  45. @:keep
  46. public static function bind(o:Dynamic, m: Function) : Function{
  47. if (m == null) return null;
  48. // if (m.__id.__ == nil) m.__id__ = _fid + 1;
  49. var f: Function = null;
  50. if ( o.hx__closures__ == null ) o.hx__closures__ = {};
  51. else untyped f = o.hx__closures__[m];
  52. if (f == null){
  53. f = untyped __lua__("function(...) return m(o, ...) end");
  54. untyped o.hx__closures__[m] = f;
  55. }
  56. return f;
  57. }
  58. /*
  59. Indicates if the given object is a class.
  60. */
  61. static inline public function isClass(o:Dynamic) : Bool {
  62. if (Lua.type(o) != "table") return false;
  63. else return untyped __define_feature__("lua.Boot.isClass", o.__name__);
  64. }
  65. /*
  66. Indicates if the given object is a enum.
  67. */
  68. static inline public function isEnum(e:Dynamic) : Bool {
  69. if (Lua.type(e) != "table") return false;
  70. else return untyped __define_feature__("lua.Boot.isEnum", e.__ename__);
  71. }
  72. /*
  73. Returns the class of a given object, and defines the getClass feature
  74. for the given class.
  75. */
  76. static inline public function getClass(o:Dynamic) : Dynamic {
  77. if (Std.is(o, Array)) return Array;
  78. else {
  79. var cl = untyped __define_feature__("lua.Boot.getClass", o.__class__);
  80. if (cl != null) return cl;
  81. else return null;
  82. }
  83. }
  84. /*
  85. Indicates if the given object is an instance of the given Type
  86. */
  87. @:ifFeature("typed_catch")
  88. private static function __instanceof(o : Dynamic, cl : Dynamic) {
  89. if( cl == null ) return false;
  90. switch( cl ) {
  91. case Int:
  92. // TODO: matching js behavior here, but js behavior clamps. Is that correct?
  93. return (Lua.type(o) == "number" && clamp(o) == o);
  94. case Float:
  95. return Lua.type(o) == "number";
  96. case Bool:
  97. return Lua.type(o) == "boolean";
  98. case String:
  99. return Lua.type(o) == "string";
  100. case Thread:
  101. return Lua.type(o) == "thread";
  102. case UserData:
  103. return Lua.type(o) == "userdata";
  104. case Array:
  105. return Lua.type(o) == "table"
  106. && untyped o.__enum__ == null
  107. && lua.Lua.getmetatable(o) != null
  108. && lua.Lua.getmetatable(o).__index == untyped Array.prototype;
  109. case Table:
  110. return Lua.type(o) == "table";
  111. case Dynamic:
  112. return true;
  113. default: {
  114. if ( o!= null && Lua.type(o) == "table" && Lua.type(cl) == "table"){
  115. // first check if o is instance of cl
  116. if (inheritsFrom(o, cl)) return true;
  117. // do not use isClass/isEnum here, perform raw checks
  118. untyped __feature__("Class.*",if( cl == Class && o.__name__ != null ) return true);
  119. untyped __feature__("Enum.*",if( cl == Enum && o.__ename__ != null ) return true);
  120. // last chance, is it an enum instance?
  121. return o.__enum__ == cl;
  122. } else {
  123. return false;
  124. }
  125. }
  126. }
  127. }
  128. /*
  129. Indicates if the given object inherits from the given class
  130. */
  131. static function inheritsFrom(o:Dynamic, cl:Class<Dynamic>) : Bool {
  132. while (Lua.getmetatable(o) != null && Lua.getmetatable(o).__index != null){
  133. if (Lua.getmetatable(o).__index == untyped cl.prototype) return true;
  134. o = Lua.getmetatable(o).__index;
  135. }
  136. return false;
  137. }
  138. @:ifFeature("typed_cast")
  139. private static function __cast(o : Dynamic, t : Dynamic) {
  140. if (__instanceof(o, t)) return o;
  141. else throw "Cannot cast " +Std.string(o) + " to " +Std.string(t);
  142. }
  143. /*
  144. Helper method to generate a string representation of an enum
  145. */
  146. static function printEnum(o:Array<Dynamic>, s : String){
  147. if (o.length == 2){
  148. return o[0];
  149. } else {
  150. // parameterized enums are arrays
  151. var str = o[0] + "(";
  152. s += "\t";
  153. for (i in 2...o.length){
  154. if( i != 2 )
  155. str += "," + __string_rec(o[i],s);
  156. else
  157. str += __string_rec(o[i],s);
  158. }
  159. return str + ")";
  160. }
  161. }
  162. /*
  163. Helper method to generate a string representation of a class
  164. */
  165. static inline function printClass(c:Table<String,Dynamic>, s : String) : String {
  166. return '{${printClassRec(c,'',s)}}';
  167. }
  168. /*
  169. Helper method to generate a string representation of a class
  170. */
  171. static function printClassRec(c:Table<String,Dynamic>, result='', s : String) : String {
  172. c.pairsEach(function(k,v){
  173. if (result != "")
  174. result += ", ";
  175. result += '$k: ${__string_rec(v, s + "\t")}';
  176. });
  177. return result;
  178. }
  179. /*
  180. Generate a string representation for arbitrary object.
  181. */
  182. @:ifFeature("has_enum")
  183. static function __string_rec(o : Dynamic, s:String = "") {
  184. return switch(untyped __type__(o)){
  185. case "nil": "null";
  186. case "number" : {
  187. if (o == std.Math.POSITIVE_INFINITY) "Infinity";
  188. else if (o == std.Math.NEGATIVE_INFINITY) "-Infinity";
  189. else if (o != o) "NaN";
  190. else untyped tostring(o);
  191. }
  192. case "boolean" : untyped tostring(o);
  193. case "string" : o;
  194. case "userdata": "<userdata>";
  195. case "function": "<function>";
  196. case "thread" : "<thread>";
  197. case "table": {
  198. if (o.__enum__ != null) printEnum(o,s);
  199. else if (o.toString != null && !__instanceof(o,Array)) o.toString();
  200. else if (__instanceof(o, Array)) {
  201. if (s.length > 5) "[...]"
  202. else '[${[for (i in cast(o,Array<Dynamic>)) __string_rec(i,s+1)].join(",")}]';
  203. } else if (s.length > 5){
  204. "{...}";
  205. }
  206. else if (Reflect.hasField(o,"__tostring")) Lua.tostring(o);
  207. else if (Reflect.hasField(o,"__class__")) printClass(o,s+"\t");
  208. else if (Lua.next(o) == null) "{}";
  209. else {
  210. var fields = Reflect.fields(o);
  211. var buffer = new StringBuf();
  212. var first = true;
  213. buffer.add("{ ");
  214. for (f in fields){
  215. if (first) first = false;
  216. else buffer.add(", ");
  217. buffer.add('${s}${Std.string(f)} : ${untyped Std.string(o[f])}');
  218. }
  219. buffer.add(" }");
  220. buffer.toString();
  221. }
  222. };
  223. default : {
  224. throw "Unknown Lua type";
  225. null;
  226. }
  227. }
  228. }
  229. /*
  230. Define an array from the given table
  231. */
  232. public inline static function defArray<T>(tab: Table<Int,T>, ?length : Int) : Array<T> {
  233. if (length == null) length = Table.maxn(tab) + 1; // maxn doesn't count 0 index
  234. return untyped _hx_tabArray(tab, length);
  235. }
  236. /*
  237. Create a Haxe object from the given table structure
  238. */
  239. public inline static function tableToObject<T>(t:Table<String,T>) : Dynamic<T> {
  240. return untyped _hx_o(t);
  241. }
  242. /*
  243. Get Date object as string representation
  244. */
  245. public static function dateStr( date : std.Date ) : String {
  246. var m = date.getMonth() + 1;
  247. var d = date.getDate();
  248. var h = date.getHours();
  249. var mi = date.getMinutes();
  250. var s = date.getSeconds();
  251. return date.getFullYear()
  252. +"-"+(if( m < 10 ) "0"+m else ""+m)
  253. +"-"+(if( d < 10 ) "0"+d else ""+d)
  254. +" "+(if( h < 10 ) "0"+h else ""+h)
  255. +":"+(if( mi < 10 ) "0"+mi else ""+mi)
  256. +":"+(if( s < 10 ) "0"+s else ""+s);
  257. }
  258. /*
  259. A 32 bit clamp function for integers
  260. */
  261. public inline static function clamp(x:Int){
  262. return untyped _hx_bit_clamp(x);
  263. }
  264. /*
  265. Create a standard date object from a lua string representation
  266. */
  267. public static function strDate( s : String ) : std.Date {
  268. switch( s.length ) {
  269. case 8: // hh:mm:ss
  270. var k = s.split(":");
  271. var t = lua.Os.time({
  272. year : 0,
  273. month : 1,
  274. day : 1,
  275. hour : Std.parseInt(k[0]),
  276. min : Std.parseInt(k[1]),
  277. sec : Std.parseInt(k[2])
  278. });
  279. return std.Date.fromTime(t);
  280. case 10: // YYYY-MM-DD
  281. var k = s.split("-");
  282. return new std.Date(Std.parseInt(k[0]), Std.parseInt(k[1]) - 1, Std.parseInt(k[2]),0,0,0);
  283. case 19: // YYYY-MM-DD hh:mm:ss
  284. var k = s.split(" ");
  285. var y = k[0].split("-");
  286. var t = k[1].split(":");
  287. return new std.Date(cast y[0],Std.parseInt(y[1]) - 1, Std.parseInt(y[2]),Std.parseInt(t[0]),Std.parseInt(t[1]),Std.parseInt(t[2]));
  288. default:
  289. throw "Invalid date format : " + s;
  290. }
  291. }
  292. /*
  293. Create an empty table.
  294. */
  295. public inline static function createTable<K,V>() : Table<K,V> {
  296. return untyped __lua__("{}");
  297. }
  298. /*
  299. Returns a shell escaped version of "cmd" along with any args
  300. */
  301. public static function shellEscapeCmd(cmd : String, ?args : Array<String>){
  302. if (args != null) {
  303. switch (Sys.systemName()) {
  304. case "Windows":
  305. cmd = [
  306. for (a in [StringTools.replace(cmd, "/", "\\")].concat(args))
  307. StringTools.quoteWinArg(a, true)
  308. ].join(" ");
  309. case _:
  310. cmd = [cmd].concat(args).map(StringTools.quoteUnixArg).join(" ");
  311. }
  312. }
  313. return cmd;
  314. }
  315. /*
  316. Returns a temp file path that can be used for reading and writing
  317. */
  318. public static function tempFile() : String {
  319. switch (Sys.systemName()){
  320. case "Windows" : return Path.join([Os.getenv("TMP"), Os.tmpname()]);
  321. default : return Os.tmpname();
  322. }
  323. }
  324. public static function __init__(){
  325. // anonymous to instance method wrapper
  326. haxe.macro.Compiler.includeFile("lua/_lua/_hx_function_to_instance_function.lua");
  327. // static to instance class wrapper
  328. haxe.macro.Compiler.includeFile("lua/_lua/_hx_static_to_instance_function.lua");
  329. }
  330. }