genjs.ml 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  1. (*
  2. * Copyright (C)2005-2013 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. open Ast
  23. open Type
  24. open Common
  25. type pos = Ast.pos
  26. type sourcemap = {
  27. sources : (string) DynArray.t;
  28. sources_hash : (string, int) Hashtbl.t;
  29. mappings : Rbuffer.t;
  30. mutable source_last_line : int;
  31. mutable source_last_col : int;
  32. mutable source_last_file : int;
  33. mutable print_comma : bool;
  34. mutable output_last_col : int;
  35. mutable output_current_col : int;
  36. }
  37. type ctx = {
  38. com : Common.context;
  39. buf : Rbuffer.t;
  40. packages : (string list,unit) Hashtbl.t;
  41. smap : sourcemap;
  42. js_modern : bool;
  43. js_flatten : bool;
  44. mutable current : tclass;
  45. mutable statics : (tclass * string * texpr) list;
  46. mutable inits : texpr list;
  47. mutable tabs : string;
  48. mutable in_value : tvar option;
  49. mutable in_loop : bool;
  50. mutable handle_break : bool;
  51. mutable id_counter : int;
  52. mutable type_accessor : module_type -> string;
  53. mutable separator : bool;
  54. mutable found_expose : bool;
  55. }
  56. type object_store = {
  57. os_name : string;
  58. mutable os_fields : object_store list;
  59. }
  60. let get_exposed ctx path meta =
  61. if not ctx.js_modern then []
  62. else try
  63. let (_, args, pos) = Meta.get Meta.Expose meta in
  64. (match args with
  65. | [ EConst (String s), _ ] -> [s]
  66. | [] -> [path]
  67. | _ -> error "Invalid @:expose parameters" pos)
  68. with Not_found -> []
  69. let dot_path = Ast.s_type_path
  70. let flat_path (p,s) =
  71. (* Replace _ with _$ in paths to prevent name collisions. *)
  72. let escape str = String.concat "_$" (ExtString.String.nsplit str "_") in
  73. match p with
  74. | [] -> escape s
  75. | _ -> String.concat "_" (List.map escape p) ^ "_" ^ (escape s)
  76. let s_path ctx = if ctx.js_flatten then flat_path else dot_path
  77. let kwds =
  78. let h = Hashtbl.create 0 in
  79. List.iter (fun s -> Hashtbl.add h s ()) [
  80. "abstract"; "as"; "boolean"; "break"; "byte"; "case"; "catch"; "char"; "class"; "continue"; "const";
  81. "debugger"; "default"; "delete"; "do"; "double"; "else"; "enum"; "export"; "extends"; "false"; "final";
  82. "finally"; "float"; "for"; "function"; "goto"; "if"; "implements"; "import"; "in"; "instanceof"; "int";
  83. "interface"; "is"; "let"; "long"; "namespace"; "native"; "new"; "null"; "package"; "private"; "protected";
  84. "public"; "return"; "short"; "static"; "super"; "switch"; "synchronized"; "this"; "throw"; "throws";
  85. "transient"; "true"; "try"; "typeof"; "use"; "var"; "void"; "volatile"; "while"; "with"; "yield"
  86. ];
  87. h
  88. (* Identifiers Haxe reserves to make the JS output cleaner. These can still be used in untyped code (TLocal),
  89. but are escaped upon declaration. *)
  90. let kwds2 =
  91. let h = Hashtbl.create 0 in
  92. List.iter (fun s -> Hashtbl.add h s ()) [
  93. (* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects *)
  94. "Infinity"; "NaN"; "decodeURI"; "decodeURIComponent"; "encodeURI"; "encodeURIComponent";
  95. "escape"; "eval"; "isFinite"; "isNaN"; "parseFloat"; "parseInt"; "undefined"; "unescape";
  96. "JSON"; "Number"; "Object"; "console"; "window"; "require";
  97. ];
  98. h
  99. let valid_js_ident s =
  100. String.length s > 0 && try
  101. for i = 0 to String.length s - 1 do
  102. match String.unsafe_get s i with
  103. | 'a'..'z' | 'A'..'Z' | '$' | '_' -> ()
  104. | '0'..'9' when i > 0 -> ()
  105. | _ -> raise Exit
  106. done;
  107. true
  108. with Exit ->
  109. false
  110. let field s = if Hashtbl.mem kwds s || not (valid_js_ident s) then "[\"" ^ s ^ "\"]" else "." ^ s
  111. let ident s = if Hashtbl.mem kwds s then "$" ^ s else s
  112. let check_var_declaration v = if Hashtbl.mem kwds2 v.v_name then v.v_name <- "$" ^ v.v_name
  113. let anon_field s = if Hashtbl.mem kwds s || not (valid_js_ident s) then "'" ^ s ^ "'" else s
  114. let static_field s =
  115. match s with
  116. | "length" | "name" -> ".$" ^ s
  117. | s -> field s
  118. let has_feature ctx = Common.has_feature ctx.com
  119. let add_feature ctx = Common.add_feature ctx.com
  120. let handle_newlines ctx str =
  121. if ctx.com.debug then
  122. let rec loop from =
  123. try begin
  124. let next = String.index_from str from '\n' + 1 in
  125. Rbuffer.add_char ctx.smap.mappings ';';
  126. ctx.smap.output_last_col <- 0;
  127. ctx.smap.print_comma <- false;
  128. loop next
  129. end with Not_found ->
  130. ctx.smap.output_current_col <- String.length str - from
  131. in
  132. loop 0
  133. else ()
  134. let spr ctx s =
  135. ctx.separator <- false;
  136. handle_newlines ctx s;
  137. Rbuffer.add_string ctx.buf s
  138. let print ctx =
  139. ctx.separator <- false;
  140. Printf.kprintf (fun s -> begin
  141. handle_newlines ctx s;
  142. Rbuffer.add_string ctx.buf s
  143. end)
  144. let unsupported p = error "This expression cannot be compiled to Javascript" p
  145. let add_mapping ctx e =
  146. if not ctx.com.debug || e.epos.pmin < 0 then () else
  147. let pos = e.epos in
  148. let smap = ctx.smap in
  149. let file = try
  150. Hashtbl.find smap.sources_hash pos.pfile
  151. with Not_found ->
  152. let length = DynArray.length smap.sources in
  153. Hashtbl.replace smap.sources_hash pos.pfile length;
  154. DynArray.add smap.sources pos.pfile;
  155. length
  156. in
  157. let line, col = Lexer.find_pos pos in
  158. let line = line - 1 in
  159. let col = col - 1 in
  160. if smap.source_last_file != file || smap.source_last_line != line || smap.source_last_col != col then begin
  161. if smap.print_comma then
  162. Rbuffer.add_char smap.mappings ','
  163. else
  164. smap.print_comma <- true;
  165. let base64_vlq number =
  166. let encode_digit digit =
  167. let chars = [|
  168. 'A';'B';'C';'D';'E';'F';'G';'H';'I';'J';'K';'L';'M';'N';'O';'P';
  169. 'Q';'R';'S';'T';'U';'V';'W';'X';'Y';'Z';'a';'b';'c';'d';'e';'f';
  170. 'g';'h';'i';'j';'k';'l';'m';'n';'o';'p';'q';'r';'s';'t';'u';'v';
  171. 'w';'x';'y';'z';'0';'1';'2';'3';'4';'5';'6';'7';'8';'9';'+';'/'
  172. |] in
  173. Array.unsafe_get chars digit
  174. in
  175. let to_vlq number =
  176. if number < 0 then
  177. ((-number) lsl 1) + 1
  178. else
  179. number lsl 1
  180. in
  181. let rec loop vlq =
  182. let shift = 5 in
  183. let base = 1 lsl shift in
  184. let mask = base - 1 in
  185. let continuation_bit = base in
  186. let digit = vlq land mask in
  187. let next = vlq asr shift in
  188. Rbuffer.add_char smap.mappings (encode_digit (
  189. if next > 0 then digit lor continuation_bit else digit));
  190. if next > 0 then loop next else ()
  191. in
  192. loop (to_vlq number)
  193. in
  194. base64_vlq (smap.output_current_col - smap.output_last_col);
  195. base64_vlq (file - smap.source_last_file);
  196. base64_vlq (line - smap.source_last_line);
  197. base64_vlq (col - smap.source_last_col);
  198. smap.source_last_file <- file;
  199. smap.source_last_line <- line;
  200. smap.source_last_col <- col;
  201. smap.output_last_col <- smap.output_current_col
  202. end
  203. let write_mappings ctx =
  204. let basefile = Filename.basename ctx.com.file in
  205. print ctx "\n//# sourceMappingURL=%s.map" basefile;
  206. let channel = open_out_bin (ctx.com.file ^ ".map") in
  207. let sources = DynArray.to_list ctx.smap.sources in
  208. let to_url file =
  209. ExtString.String.map (fun c -> if c == '\\' then '/' else c) (Common.get_full_path file)
  210. in
  211. output_string channel "{\n";
  212. output_string channel "\"version\":3,\n";
  213. output_string channel ("\"file\":\"" ^ (String.concat "\\\\" (ExtString.String.nsplit basefile "\\")) ^ "\",\n");
  214. output_string channel ("\"sourceRoot\":\"file:///\",\n");
  215. output_string channel ("\"sources\":[" ^
  216. (String.concat "," (List.map (fun s -> "\"" ^ to_url s ^ "\"") sources)) ^
  217. "],\n");
  218. if Common.defined ctx.com Define.SourceMapContent then begin
  219. output_string channel ("\"sourcesContent\":[" ^
  220. (String.concat "," (List.map (fun s -> try "\"" ^ Ast.s_escape (Std.input_file ~bin:true s) ^ "\"" with _ -> "null") sources)) ^
  221. "],\n");
  222. end;
  223. output_string channel "\"names\":[],\n";
  224. output_string channel "\"mappings\":\"";
  225. Rbuffer.output_buffer channel ctx.smap.mappings;
  226. output_string channel "\"\n";
  227. output_string channel "}";
  228. close_out channel
  229. let newline ctx =
  230. match Rbuffer.nth ctx.buf (Rbuffer.length ctx.buf - 1) with
  231. | '}' | '{' | ':' when not ctx.separator -> print ctx "\n%s" ctx.tabs
  232. | _ -> print ctx ";\n%s" ctx.tabs
  233. let newprop ctx =
  234. match Rbuffer.nth ctx.buf (Rbuffer.length ctx.buf - 1) with
  235. | '{' -> print ctx "\n%s" ctx.tabs
  236. | _ -> print ctx "\n%s," ctx.tabs
  237. let semicolon ctx =
  238. match Rbuffer.nth ctx.buf (Rbuffer.length ctx.buf - 1) with
  239. | '}' when not ctx.separator -> ()
  240. | _ -> spr ctx ";"
  241. let rec concat ctx s f = function
  242. | [] -> ()
  243. | [x] -> f x
  244. | x :: l ->
  245. f x;
  246. spr ctx s;
  247. concat ctx s f l
  248. let fun_block ctx f p =
  249. let e = List.fold_left (fun e (a,c) ->
  250. match c with
  251. | None | Some TNull -> e
  252. | Some c -> Type.concat (Codegen.set_default ctx.com a c p) e
  253. ) f.tf_expr f.tf_args in
  254. e
  255. let open_block ctx =
  256. let oldt = ctx.tabs in
  257. ctx.tabs <- "\t" ^ ctx.tabs;
  258. (fun() -> ctx.tabs <- oldt)
  259. let rec has_return e =
  260. match e.eexpr with
  261. | TBlock [] -> false
  262. | TBlock el -> has_return (List.hd (List.rev el))
  263. | TReturn _ -> true
  264. | _ -> false
  265. let rec iter_switch_break in_switch e =
  266. match e.eexpr with
  267. | TFunction _ | TWhile _ | TFor _ -> ()
  268. | TSwitch _ when not in_switch -> iter_switch_break true e
  269. | TBreak when in_switch -> raise Exit
  270. | _ -> iter (iter_switch_break in_switch) e
  271. let handle_break ctx e =
  272. let old = ctx.in_loop, ctx.handle_break in
  273. ctx.in_loop <- true;
  274. try
  275. iter_switch_break false e;
  276. ctx.handle_break <- false;
  277. (fun() ->
  278. ctx.in_loop <- fst old;
  279. ctx.handle_break <- snd old;
  280. )
  281. with
  282. Exit ->
  283. spr ctx "try {";
  284. let b = open_block ctx in
  285. newline ctx;
  286. ctx.handle_break <- true;
  287. (fun() ->
  288. b();
  289. ctx.in_loop <- fst old;
  290. ctx.handle_break <- snd old;
  291. newline ctx;
  292. spr ctx "} catch( e ) { if( e != \"__break__\" ) throw e; }";
  293. )
  294. let this ctx = match ctx.in_value with None -> "this" | Some _ -> "$this"
  295. let is_dynamic_iterator ctx e =
  296. let check x =
  297. has_feature ctx "HxOverrides.iter" && (match follow x.etype with
  298. | TInst ({ cl_path = [],"Array" },_)
  299. | TInst ({ cl_kind = KTypeParameter _}, _)
  300. | TAnon _
  301. | TDynamic _
  302. | TMono _ ->
  303. true
  304. | _ -> false
  305. )
  306. in
  307. match e.eexpr with
  308. | TField (x,f) when field_name f = "iterator" -> check x
  309. | _ ->
  310. false
  311. let gen_constant ctx p = function
  312. | TInt i -> print ctx "%ld" i
  313. | TFloat s -> spr ctx s
  314. | TString s -> print ctx "\"%s\"" (Ast.s_escape s)
  315. | TBool b -> spr ctx (if b then "true" else "false")
  316. | TNull -> spr ctx "null"
  317. | TThis -> spr ctx (this ctx)
  318. | TSuper -> assert false
  319. let rec gen_call ctx e el in_value =
  320. match e.eexpr , el with
  321. | TConst TSuper , params ->
  322. (match ctx.current.cl_super with
  323. | None -> error "Missing api.setCurrentClass" e.epos
  324. | Some (c,_) ->
  325. print ctx "%s.call(%s" (ctx.type_accessor (TClassDecl c)) (this ctx);
  326. List.iter (fun p -> print ctx ","; gen_value ctx p) params;
  327. spr ctx ")";
  328. );
  329. | TField ({ eexpr = TConst TSuper },f) , params ->
  330. (match ctx.current.cl_super with
  331. | None -> error "Missing api.setCurrentClass" e.epos
  332. | Some (c,_) ->
  333. let name = field_name f in
  334. print ctx "%s.prototype%s.call(%s" (ctx.type_accessor (TClassDecl c)) (field name) (this ctx);
  335. List.iter (fun p -> print ctx ","; gen_value ctx p) params;
  336. spr ctx ")";
  337. );
  338. | TCall (x,_) , el when (match x.eexpr with TLocal { v_name = "__js__" } -> false | _ -> true) ->
  339. spr ctx "(";
  340. gen_value ctx e;
  341. spr ctx ")";
  342. spr ctx "(";
  343. concat ctx "," (gen_value ctx) el;
  344. spr ctx ")";
  345. | TLocal { v_name = "__new__" }, { eexpr = TConst (TString cl) } :: params ->
  346. print ctx "new %s(" cl;
  347. concat ctx "," (gen_value ctx) params;
  348. spr ctx ")";
  349. | TLocal { v_name = "__new__" }, e :: params ->
  350. spr ctx "new ";
  351. gen_value ctx e;
  352. spr ctx "(";
  353. concat ctx "," (gen_value ctx) params;
  354. spr ctx ")";
  355. | TLocal { v_name = "__js__" }, [{ eexpr = TConst (TString "this") }] ->
  356. spr ctx (this ctx)
  357. | TLocal { v_name = "__js__" }, [{ eexpr = TConst (TString code) }] ->
  358. spr ctx (String.concat "\n" (ExtString.String.nsplit code "\r\n"))
  359. | TLocal { v_name = "__js__" }, { eexpr = TConst (TString code); epos = p } :: tl ->
  360. Codegen.interpolate_code ctx.com code tl (spr ctx) (gen_expr ctx) p
  361. | TLocal { v_name = "__instanceof__" }, [o;t] ->
  362. spr ctx "(";
  363. gen_value ctx o;
  364. print ctx " instanceof ";
  365. gen_value ctx t;
  366. spr ctx ")";
  367. | TLocal { v_name = "__typeof__" }, [o] ->
  368. spr ctx "typeof(";
  369. gen_value ctx o;
  370. spr ctx ")";
  371. | TLocal { v_name = "__strict_eq__" } , [x;y] ->
  372. (* add extra parenthesis here because of operator precedence *)
  373. spr ctx "((";
  374. gen_value ctx x;
  375. spr ctx ") === ";
  376. gen_value ctx y;
  377. spr ctx ")";
  378. | TLocal { v_name = "__strict_neq__" } , [x;y] ->
  379. (* add extra parenthesis here because of operator precedence *)
  380. spr ctx "((";
  381. gen_value ctx x;
  382. spr ctx ") !== ";
  383. gen_value ctx y;
  384. spr ctx ")";
  385. | TLocal ({v_name = "__define_feature__"}), [_;e] ->
  386. gen_expr ctx e
  387. | TLocal { v_name = "__feature__" }, { eexpr = TConst (TString f) } :: eif :: eelse ->
  388. (if has_feature ctx f then
  389. gen_value ctx eif
  390. else match eelse with
  391. | [] -> ()
  392. | e :: _ -> gen_value ctx e)
  393. | TLocal { v_name = "__resources__" }, [] ->
  394. spr ctx "[";
  395. concat ctx "," (fun (name,data) ->
  396. spr ctx "{ ";
  397. spr ctx "name : ";
  398. gen_constant ctx e.epos (TString name);
  399. spr ctx ", data : ";
  400. gen_constant ctx e.epos (TString (Codegen.bytes_serialize data));
  401. spr ctx "}"
  402. ) (Hashtbl.fold (fun name data acc -> (name,data) :: acc) ctx.com.resources []);
  403. spr ctx "]";
  404. | TLocal { v_name = "`trace" }, [e;infos] ->
  405. if has_feature ctx "haxe.Log.trace" then begin
  406. let t = (try List.find (fun t -> t_path t = (["haxe"],"Log")) ctx.com.types with _ -> assert false) in
  407. spr ctx (ctx.type_accessor t);
  408. spr ctx ".trace(";
  409. gen_value ctx e;
  410. spr ctx ",";
  411. gen_value ctx infos;
  412. spr ctx ")";
  413. end else begin
  414. spr ctx "console.log(";
  415. gen_value ctx e;
  416. spr ctx ")";
  417. end
  418. | _ ->
  419. gen_value ctx e;
  420. spr ctx "(";
  421. concat ctx "," (gen_value ctx) el;
  422. spr ctx ")"
  423. and gen_expr ctx e =
  424. add_mapping ctx e;
  425. match e.eexpr with
  426. | TConst c -> gen_constant ctx e.epos c
  427. | TLocal v -> spr ctx (ident v.v_name)
  428. | TArray (e1,{ eexpr = TConst (TString s) }) when valid_js_ident s && (match e1.eexpr with TConst (TInt _|TFloat _) -> false | _ -> true) ->
  429. gen_value ctx e1;
  430. spr ctx (field s)
  431. | TArray (e1,e2) ->
  432. gen_value ctx e1;
  433. spr ctx "[";
  434. gen_value ctx e2;
  435. spr ctx "]";
  436. | TBinop (op,{ eexpr = TField (x,f) },e2) when field_name f = "iterator" ->
  437. gen_value ctx x;
  438. spr ctx (field "iterator");
  439. print ctx " %s " (Ast.s_binop op);
  440. gen_value ctx e2;
  441. | TBinop (op,e1,e2) ->
  442. gen_value ctx e1;
  443. print ctx " %s " (Ast.s_binop op);
  444. gen_value ctx e2;
  445. | TField (x,f) when field_name f = "iterator" && is_dynamic_iterator ctx e ->
  446. add_feature ctx "use.$iterator";
  447. print ctx "$iterator(";
  448. gen_value ctx x;
  449. print ctx ")";
  450. | TField (x,FClosure (Some ({cl_path=[],"Array"},_), {cf_name="push"})) ->
  451. (* see https://github.com/HaxeFoundation/haxe/issues/1997 *)
  452. add_feature ctx "use.$arrayPushClosure";
  453. print ctx "$arrayPushClosure(";
  454. gen_value ctx x;
  455. print ctx ")"
  456. | TField (x,FClosure (_,f)) ->
  457. add_feature ctx "use.$bind";
  458. (match x.eexpr with
  459. | TConst _ | TLocal _ ->
  460. print ctx "$bind(";
  461. gen_value ctx x;
  462. print ctx ",";
  463. gen_value ctx x;
  464. print ctx "%s)" (field f.cf_name)
  465. | _ ->
  466. print ctx "($_=";
  467. gen_value ctx x;
  468. print ctx ",$bind($_,$_%s))" (field f.cf_name))
  469. | TEnumParameter (x,_,i) ->
  470. gen_value ctx x;
  471. print ctx "[%i]" (i + 2)
  472. | TField ({ eexpr = TConst (TInt _ | TFloat _) } as x,f) ->
  473. gen_expr ctx { e with eexpr = TField(mk (TParenthesis x) x.etype x.epos,f) }
  474. | TField (x, (FInstance(_,_,f) | FStatic(_,f) | FAnon(f))) when Meta.has Meta.SelfCall f.cf_meta ->
  475. gen_value ctx x;
  476. | TField (x,f) ->
  477. gen_value ctx x;
  478. let name = field_name f in
  479. spr ctx (match f with FStatic _ -> static_field name | FEnum _ | FInstance _ | FAnon _ | FDynamic _ | FClosure _ -> field name)
  480. | TTypeExpr t ->
  481. spr ctx (ctx.type_accessor t)
  482. | TParenthesis e ->
  483. spr ctx "(";
  484. gen_value ctx e;
  485. spr ctx ")";
  486. | TMeta (_,e) ->
  487. gen_expr ctx e
  488. | TReturn eo ->
  489. if ctx.in_value <> None then unsupported e.epos;
  490. (match eo with
  491. | None ->
  492. spr ctx "return"
  493. | Some e ->
  494. spr ctx "return ";
  495. gen_value ctx e);
  496. | TBreak ->
  497. if not ctx.in_loop then unsupported e.epos;
  498. if ctx.handle_break then spr ctx "throw \"__break__\"" else spr ctx "break"
  499. | TContinue ->
  500. if not ctx.in_loop then unsupported e.epos;
  501. spr ctx "continue"
  502. | TBlock el ->
  503. print ctx "{";
  504. let bend = open_block ctx in
  505. List.iter (gen_block_element ctx) el;
  506. bend();
  507. newline ctx;
  508. print ctx "}";
  509. | TFunction f ->
  510. let old = ctx.in_value, ctx.in_loop in
  511. ctx.in_value <- None;
  512. ctx.in_loop <- false;
  513. print ctx "function(%s) " (String.concat "," (List.map ident (List.map arg_name f.tf_args)));
  514. gen_expr ctx (fun_block ctx f e.epos);
  515. ctx.in_value <- fst old;
  516. ctx.in_loop <- snd old;
  517. ctx.separator <- true
  518. | TCall (e,el) ->
  519. gen_call ctx e el false
  520. | TArrayDecl el ->
  521. spr ctx "[";
  522. concat ctx "," (gen_value ctx) el;
  523. spr ctx "]"
  524. | TThrow e ->
  525. spr ctx "throw ";
  526. gen_value ctx e;
  527. | TVar (v,eo) ->
  528. spr ctx "var ";
  529. check_var_declaration v;
  530. spr ctx (ident v.v_name);
  531. begin match eo with
  532. | None -> ()
  533. | Some e ->
  534. spr ctx " = ";
  535. gen_value ctx e
  536. end
  537. | TNew ({ cl_path = [],"Array" },_,[]) ->
  538. print ctx "[]"
  539. | TNew (c,_,el) ->
  540. (match c.cl_constructor with
  541. | Some cf when Meta.has Meta.SelfCall cf.cf_meta -> ()
  542. | _ -> print ctx "new ");
  543. print ctx "%s(" (ctx.type_accessor (TClassDecl c));
  544. concat ctx "," (gen_value ctx) el;
  545. spr ctx ")"
  546. | TIf (cond,e,eelse) ->
  547. spr ctx "if";
  548. gen_value ctx cond;
  549. spr ctx " ";
  550. gen_expr ctx e;
  551. (match eelse with
  552. | None -> ()
  553. | Some e2 ->
  554. (match e.eexpr with
  555. | TObjectDecl _ -> ctx.separator <- false
  556. | _ -> ());
  557. semicolon ctx;
  558. spr ctx " else ";
  559. gen_expr ctx e2);
  560. | TUnop (op,Ast.Prefix,e) ->
  561. spr ctx (Ast.s_unop op);
  562. gen_value ctx e
  563. | TUnop (op,Ast.Postfix,e) ->
  564. gen_value ctx e;
  565. spr ctx (Ast.s_unop op)
  566. | TWhile (cond,e,Ast.NormalWhile) ->
  567. let handle_break = handle_break ctx e in
  568. spr ctx "while";
  569. gen_value ctx cond;
  570. spr ctx " ";
  571. gen_expr ctx e;
  572. handle_break();
  573. | TWhile (cond,e,Ast.DoWhile) ->
  574. let handle_break = handle_break ctx e in
  575. spr ctx "do ";
  576. gen_expr ctx e;
  577. semicolon ctx;
  578. spr ctx " while";
  579. gen_value ctx cond;
  580. handle_break();
  581. | TObjectDecl fields ->
  582. spr ctx "{ ";
  583. concat ctx ", " (fun (f,e) -> (match e.eexpr with
  584. | TMeta((Meta.QuotedField,_,_),e) -> print ctx "'%s' : " f;
  585. | _ -> print ctx "%s : " (anon_field f));
  586. gen_value ctx e
  587. ) fields;
  588. spr ctx "}";
  589. ctx.separator <- true
  590. | TFor (v,it,e) ->
  591. check_var_declaration v;
  592. let handle_break = handle_break ctx e in
  593. let it = ident (match it.eexpr with
  594. | TLocal v -> v.v_name
  595. | _ ->
  596. let id = ctx.id_counter in
  597. ctx.id_counter <- ctx.id_counter + 1;
  598. let name = "$it" ^ string_of_int id in
  599. print ctx "var %s = " name;
  600. gen_value ctx it;
  601. newline ctx;
  602. name
  603. ) in
  604. print ctx "while( %s.hasNext() ) {" it;
  605. let bend = open_block ctx in
  606. newline ctx;
  607. print ctx "var %s = %s.next()" (ident v.v_name) it;
  608. gen_block_element ctx e;
  609. bend();
  610. newline ctx;
  611. spr ctx "}";
  612. handle_break();
  613. | TTry (e,catchs) ->
  614. spr ctx "try ";
  615. gen_expr ctx e;
  616. let vname = (match catchs with [(v,_)] -> check_var_declaration v; v.v_name | _ ->
  617. let id = ctx.id_counter in
  618. ctx.id_counter <- ctx.id_counter + 1;
  619. "$e" ^ string_of_int id
  620. ) in
  621. print ctx " catch( %s ) {" vname;
  622. let bend = open_block ctx in
  623. let last = ref false in
  624. let else_block = ref false in
  625. List.iter (fun (v,e) ->
  626. if !last then () else
  627. let t = (match follow v.v_type with
  628. | TEnum (e,_) -> Some (TEnumDecl e)
  629. | TInst (c,_) -> Some (TClassDecl c)
  630. | TAbstract (a,_) -> Some (TAbstractDecl a)
  631. | TFun _
  632. | TLazy _
  633. | TType _
  634. | TAnon _ ->
  635. assert false
  636. | TMono _
  637. | TDynamic _ ->
  638. None
  639. ) in
  640. match t with
  641. | None ->
  642. last := true;
  643. if !else_block then print ctx "{";
  644. if vname <> v.v_name then begin
  645. newline ctx;
  646. print ctx "var %s = %s" v.v_name vname;
  647. end;
  648. gen_block_element ctx e;
  649. if !else_block then begin
  650. newline ctx;
  651. print ctx "}";
  652. end
  653. | Some t ->
  654. if not !else_block then newline ctx;
  655. print ctx "if( %s.__instanceof(%s," (ctx.type_accessor (TClassDecl { null_class with cl_path = ["js"],"Boot" })) vname;
  656. gen_value ctx (mk (TTypeExpr t) (mk_mono()) e.epos);
  657. spr ctx ") ) {";
  658. let bend = open_block ctx in
  659. if vname <> v.v_name then begin
  660. newline ctx;
  661. print ctx "var %s = %s" v.v_name vname;
  662. end;
  663. gen_block_element ctx e;
  664. bend();
  665. newline ctx;
  666. spr ctx "} else ";
  667. else_block := true
  668. ) catchs;
  669. if not !last then print ctx "throw(%s)" vname;
  670. bend();
  671. newline ctx;
  672. spr ctx "}";
  673. | TSwitch (e,cases,def) ->
  674. spr ctx "switch";
  675. gen_value ctx e;
  676. spr ctx " {";
  677. newline ctx;
  678. List.iter (fun (el,e2) ->
  679. List.iter (fun e ->
  680. match e.eexpr with
  681. | TConst(c) when c = TNull ->
  682. spr ctx "case null: case undefined:";
  683. | _ ->
  684. spr ctx "case ";
  685. gen_value ctx e;
  686. spr ctx ":"
  687. ) el;
  688. let bend = open_block ctx in
  689. gen_block_element ctx e2;
  690. if not (has_return e2) then begin
  691. newline ctx;
  692. print ctx "break";
  693. end;
  694. bend();
  695. newline ctx;
  696. ) cases;
  697. (match def with
  698. | None -> ()
  699. | Some e ->
  700. spr ctx "default:";
  701. let bend = open_block ctx in
  702. gen_block_element ctx e;
  703. bend();
  704. newline ctx;
  705. );
  706. spr ctx "}"
  707. | TCast (e,None) ->
  708. gen_expr ctx e
  709. | TCast (e1,Some t) ->
  710. print ctx "%s.__cast(" (ctx.type_accessor (TClassDecl { null_class with cl_path = ["js"],"Boot" }));
  711. gen_expr ctx e1;
  712. spr ctx " , ";
  713. spr ctx (ctx.type_accessor t);
  714. spr ctx ")"
  715. and gen_block_element ?(after=false) ctx e =
  716. match e.eexpr with
  717. | TBlock el ->
  718. List.iter (gen_block_element ~after ctx) el
  719. | TCall ({ eexpr = TLocal { v_name = "__feature__" } }, { eexpr = TConst (TString f) } :: eif :: eelse) ->
  720. if has_feature ctx f then
  721. gen_block_element ~after ctx eif
  722. else (match eelse with
  723. | [] -> ()
  724. | [e] -> gen_block_element ~after ctx e
  725. | _ -> assert false)
  726. | TFunction _ ->
  727. gen_block_element ~after ctx (mk (TParenthesis e) e.etype e.epos)
  728. | TObjectDecl fl ->
  729. List.iter (fun (_,e) -> gen_block_element ~after ctx e) fl
  730. | _ ->
  731. if not after then newline ctx;
  732. gen_expr ctx e;
  733. if after then newline ctx
  734. and gen_value ctx e =
  735. add_mapping ctx e;
  736. let assign e =
  737. mk (TBinop (Ast.OpAssign,
  738. mk (TLocal (match ctx.in_value with None -> assert false | Some v -> v)) t_dynamic e.epos,
  739. e
  740. )) e.etype e.epos
  741. in
  742. let value() =
  743. let old = ctx.in_value, ctx.in_loop in
  744. let r = alloc_var "$r" t_dynamic in
  745. ctx.in_value <- Some r;
  746. ctx.in_loop <- false;
  747. spr ctx "(function($this) ";
  748. spr ctx "{";
  749. let b = open_block ctx in
  750. newline ctx;
  751. spr ctx "var $r";
  752. newline ctx;
  753. (fun() ->
  754. newline ctx;
  755. spr ctx "return $r";
  756. b();
  757. newline ctx;
  758. spr ctx "}";
  759. ctx.in_value <- fst old;
  760. ctx.in_loop <- snd old;
  761. print ctx "(%s))" (this ctx)
  762. )
  763. in
  764. match e.eexpr with
  765. | TConst _
  766. | TLocal _
  767. | TArray _
  768. | TBinop _
  769. | TField _
  770. | TEnumParameter _
  771. | TTypeExpr _
  772. | TParenthesis _
  773. | TObjectDecl _
  774. | TArrayDecl _
  775. | TNew _
  776. | TUnop _
  777. | TFunction _ ->
  778. gen_expr ctx e
  779. | TMeta (_,e1) ->
  780. gen_value ctx e1
  781. | TCall (e,el) ->
  782. gen_call ctx e el true
  783. | TReturn _
  784. | TBreak
  785. | TContinue ->
  786. unsupported e.epos
  787. | TCast (e1, None) ->
  788. gen_value ctx e1
  789. | TCast (e1, Some t) ->
  790. print ctx "%s.__cast(" (ctx.type_accessor (TClassDecl { null_class with cl_path = ["js"],"Boot" }));
  791. gen_value ctx e1;
  792. spr ctx " , ";
  793. spr ctx (ctx.type_accessor t);
  794. spr ctx ")"
  795. | TVar _
  796. | TFor _
  797. | TWhile _
  798. | TThrow _ ->
  799. (* value is discarded anyway *)
  800. let v = value() in
  801. gen_expr ctx e;
  802. v()
  803. | TBlock [e] ->
  804. gen_value ctx e
  805. | TBlock el ->
  806. let v = value() in
  807. let rec loop = function
  808. | [] ->
  809. spr ctx "return null";
  810. | [e] ->
  811. gen_expr ctx (assign e);
  812. | e :: l ->
  813. gen_expr ctx e;
  814. newline ctx;
  815. loop l
  816. in
  817. loop el;
  818. v();
  819. | TIf (cond,e,eo) ->
  820. (* remove parenthesis unless it's an operation with higher precedence than ?: *)
  821. let cond = (match cond.eexpr with
  822. | TParenthesis { eexpr = TBinop ((Ast.OpAssign | Ast.OpAssignOp _),_,_) | TIf _ } -> cond
  823. | TParenthesis e -> e
  824. | _ -> cond
  825. ) in
  826. gen_value ctx cond;
  827. spr ctx "?";
  828. gen_value ctx e;
  829. spr ctx ":";
  830. (match eo with
  831. | None -> spr ctx "null"
  832. | Some e -> gen_value ctx e);
  833. | TSwitch (cond,cases,def) ->
  834. let v = value() in
  835. gen_expr ctx (mk (TSwitch (cond,
  836. List.map (fun (e1,e2) -> (e1,assign e2)) cases,
  837. match def with None -> None | Some e -> Some (assign e)
  838. )) e.etype e.epos);
  839. v()
  840. | TTry (b,catchs) ->
  841. let v = value() in
  842. let block e = mk (TBlock [e]) e.etype e.epos in
  843. gen_expr ctx (mk (TTry (block (assign b),
  844. List.map (fun (v,e) -> v, block (assign e)) catchs
  845. )) e.etype e.epos);
  846. v()
  847. let generate_package_create ctx (p,_) =
  848. let rec loop acc = function
  849. | [] -> ()
  850. | p :: l when Hashtbl.mem ctx.packages (p :: acc) -> loop (p :: acc) l
  851. | p :: l ->
  852. Hashtbl.add ctx.packages (p :: acc) ();
  853. (match acc with
  854. | [] ->
  855. if ctx.js_modern then
  856. print ctx "var %s = {}" p
  857. else
  858. print ctx "var %s = %s || {}" p p
  859. | _ ->
  860. let p = String.concat "." (List.rev acc) ^ (field p) in
  861. if ctx.js_modern then
  862. print ctx "%s = {}" p
  863. else
  864. print ctx "if(!%s) %s = {}" p p
  865. );
  866. ctx.separator <- true;
  867. newline ctx;
  868. loop (p :: acc) l
  869. in
  870. match p with
  871. | [] -> print ctx "var "
  872. | _ -> loop [] p
  873. let check_field_name c f =
  874. match f.cf_name with
  875. | "prototype" | "__proto__" | "constructor" ->
  876. error ("The field name '" ^ f.cf_name ^ "' is not allowed in JS") (match f.cf_expr with None -> c.cl_pos | Some e -> e.epos);
  877. | _ -> ()
  878. let gen_class_static_field ctx c f =
  879. match f.cf_expr with
  880. | None | Some { eexpr = TConst TNull } when not (has_feature ctx "Type.getClassFields") ->
  881. ()
  882. | None when is_extern_field f ->
  883. ()
  884. | None ->
  885. print ctx "%s%s = null" (s_path ctx c.cl_path) (static_field f.cf_name);
  886. newline ctx
  887. | Some e ->
  888. match e.eexpr with
  889. | TFunction _ ->
  890. let path = (s_path ctx c.cl_path) ^ (static_field f.cf_name) in
  891. let dot_path = (dot_path c.cl_path) ^ (static_field f.cf_name) in
  892. ctx.id_counter <- 0;
  893. print ctx "%s = " path;
  894. (match (get_exposed ctx dot_path f.cf_meta) with [s] -> print ctx "$hx_exports.%s = " s | _ -> ());
  895. gen_value ctx e;
  896. newline ctx;
  897. | _ ->
  898. ctx.statics <- (c,f.cf_name,e) :: ctx.statics
  899. let can_gen_class_field ctx = function
  900. | { cf_expr = (None | Some { eexpr = TConst TNull }) } when not (has_feature ctx "Type.getInstanceFields") ->
  901. false
  902. | f ->
  903. not (is_extern_field f)
  904. let gen_class_field ctx c f =
  905. check_field_name c f;
  906. match f.cf_expr with
  907. | None ->
  908. newprop ctx;
  909. print ctx "%s: " (anon_field f.cf_name);
  910. print ctx "null";
  911. | Some e ->
  912. newprop ctx;
  913. print ctx "%s: " (anon_field f.cf_name);
  914. ctx.id_counter <- 0;
  915. gen_value ctx e;
  916. ctx.separator <- false
  917. let generate_class___name__ ctx c =
  918. if has_feature ctx "js.Boot.isClass" then begin
  919. let p = s_path ctx c.cl_path in
  920. print ctx "%s.__name__ = " p;
  921. if has_feature ctx "Type.getClassName" then
  922. print ctx "[%s]" (String.concat "," (List.map (fun s -> Printf.sprintf "\"%s\"" (Ast.s_escape s)) (fst c.cl_path @ [snd c.cl_path])))
  923. else
  924. print ctx "true";
  925. newline ctx;
  926. end
  927. let generate_class ctx c =
  928. ctx.current <- c;
  929. ctx.id_counter <- 0;
  930. (match c.cl_path with
  931. | [],"Function" -> error "This class redefine a native one" c.cl_pos
  932. | _ -> ());
  933. let p = s_path ctx c.cl_path in
  934. let hxClasses = has_feature ctx "Type.resolveClass" in
  935. if ctx.js_flatten then
  936. print ctx "var "
  937. else
  938. generate_package_create ctx c.cl_path;
  939. if ctx.js_modern || not hxClasses then
  940. print ctx "%s = " p
  941. else
  942. print ctx "%s = $hxClasses[\"%s\"] = " p (dot_path c.cl_path);
  943. (match (get_exposed ctx (dot_path c.cl_path) c.cl_meta) with [s] -> print ctx "$hx_exports.%s = " s | _ -> ());
  944. (match c.cl_kind with
  945. | KAbstractImpl _ ->
  946. (* abstract implementations only contain static members and don't need to have constructor functions *)
  947. print ctx "{}"; ctx.separator <- true
  948. | _ ->
  949. (match c.cl_constructor with
  950. | Some { cf_expr = Some e } -> gen_expr ctx e
  951. | _ -> (print ctx "function() { }"); ctx.separator <- true)
  952. );
  953. newline ctx;
  954. if ctx.js_modern && hxClasses then begin
  955. print ctx "$hxClasses[\"%s\"] = %s" (dot_path c.cl_path) p;
  956. newline ctx;
  957. end;
  958. generate_class___name__ ctx c;
  959. (match c.cl_implements with
  960. | [] -> ()
  961. | l ->
  962. print ctx "%s.__interfaces__ = [%s]" p (String.concat "," (List.map (fun (i,_) -> ctx.type_accessor (TClassDecl i)) l));
  963. newline ctx;
  964. );
  965. let gen_props props =
  966. String.concat "," (List.map (fun (p,v) -> p ^":\""^v^"\"") props) in
  967. let has_property_reflection =
  968. (has_feature ctx "Reflect.getProperty") || (has_feature ctx "Reflect.setProperty") in
  969. if has_property_reflection then begin
  970. (match Codegen.get_properties c.cl_ordered_statics with
  971. | [] -> ()
  972. | props ->
  973. print ctx "%s.__properties__ = {%s}" p (gen_props props);
  974. newline ctx);
  975. end;
  976. List.iter (gen_class_static_field ctx c) c.cl_ordered_statics;
  977. let has_class = has_feature ctx "js.Boot.getClass" && (c.cl_super <> None || c.cl_ordered_fields <> [] || c.cl_constructor <> None) in
  978. let has_prototype = c.cl_super <> None || has_class || List.exists (can_gen_class_field ctx) c.cl_ordered_fields in
  979. if has_prototype then begin
  980. (match c.cl_super with
  981. | None -> print ctx "%s.prototype = {" p;
  982. | Some (csup,_) ->
  983. let psup = ctx.type_accessor (TClassDecl csup) in
  984. print ctx "%s.__super__ = %s" p psup;
  985. newline ctx;
  986. print ctx "%s.prototype = $extend(%s.prototype,{" p psup;
  987. );
  988. let bend = open_block ctx in
  989. List.iter (fun f -> if can_gen_class_field ctx f then gen_class_field ctx c f) c.cl_ordered_fields;
  990. if has_class then begin
  991. newprop ctx;
  992. print ctx "__class__: %s" p;
  993. end;
  994. if has_property_reflection then begin
  995. let props = Codegen.get_properties c.cl_ordered_fields in
  996. (match c.cl_super with
  997. | _ when props = [] -> ()
  998. | Some (csup,_) when Codegen.has_properties csup ->
  999. newprop ctx;
  1000. let psup = s_path ctx csup.cl_path in
  1001. print ctx "__properties__: $extend(%s.prototype.__properties__,{%s})" psup (gen_props props)
  1002. | _ ->
  1003. newprop ctx;
  1004. print ctx "__properties__: {%s}" (gen_props props));
  1005. end;
  1006. bend();
  1007. print ctx "\n}";
  1008. (match c.cl_super with None -> ctx.separator <- true | _ -> print ctx ")");
  1009. newline ctx
  1010. end
  1011. let generate_enum ctx e =
  1012. let p = s_path ctx e.e_path in
  1013. let ename = List.map (fun s -> Printf.sprintf "\"%s\"" (Ast.s_escape s)) (fst e.e_path @ [snd e.e_path]) in
  1014. if ctx.js_flatten then
  1015. print ctx "var "
  1016. else
  1017. generate_package_create ctx e.e_path;
  1018. print ctx "%s = " p;
  1019. if has_feature ctx "Type.resolveEnum" then print ctx "$hxClasses[\"%s\"] = " (dot_path e.e_path);
  1020. print ctx "{";
  1021. if has_feature ctx "js.Boot.isEnum" then print ctx " __ename__ : %s," (if has_feature ctx "Type.getEnumName" then "[" ^ String.concat "," ename ^ "]" else "true");
  1022. print ctx " __constructs__ : [%s] }" (String.concat "," (List.map (fun s -> Printf.sprintf "\"%s\"" s) e.e_names));
  1023. ctx.separator <- true;
  1024. newline ctx;
  1025. List.iter (fun n ->
  1026. let f = PMap.find n e.e_constrs in
  1027. print ctx "%s%s = " p (field f.ef_name);
  1028. (match f.ef_type with
  1029. | TFun (args,_) ->
  1030. let sargs = String.concat "," (List.map (fun (n,_,_) -> ident n) args) in
  1031. print ctx "function(%s) { var $x = [\"%s\",%d,%s]; $x.__enum__ = %s;" sargs f.ef_name f.ef_index sargs p;
  1032. if has_feature ctx "may_print_enum" then
  1033. spr ctx " $x.toString = $estr;";
  1034. spr ctx " return $x; }";
  1035. ctx.separator <- true;
  1036. | _ ->
  1037. print ctx "[\"%s\",%d]" f.ef_name f.ef_index;
  1038. newline ctx;
  1039. if has_feature ctx "may_print_enum" then begin
  1040. print ctx "%s%s.toString = $estr" p (field f.ef_name);
  1041. newline ctx;
  1042. end;
  1043. print ctx "%s%s.__enum__ = %s" p (field f.ef_name) p;
  1044. );
  1045. newline ctx
  1046. ) e.e_names;
  1047. if has_feature ctx "Type.allEnums" then begin
  1048. let ctors_without_args = List.filter (fun s ->
  1049. let ef = PMap.find s e.e_constrs in
  1050. match follow ef.ef_type with
  1051. | TFun _ -> false
  1052. | _ -> true
  1053. ) e.e_names in
  1054. print ctx "%s.__empty_constructs__ = [%s]" p (String.concat "," (List.map (fun s -> Printf.sprintf "%s.%s" p s) ctors_without_args));
  1055. newline ctx
  1056. end;
  1057. match Codegen.build_metadata ctx.com (TEnumDecl e) with
  1058. | None -> ()
  1059. | Some e ->
  1060. print ctx "%s.__meta__ = " p;
  1061. gen_expr ctx e;
  1062. newline ctx
  1063. let generate_static ctx (c,f,e) =
  1064. print ctx "%s%s = " (s_path ctx c.cl_path) (static_field f);
  1065. gen_value ctx e;
  1066. newline ctx
  1067. let generate_require ctx path meta =
  1068. let _, args, mp = Meta.get Meta.JsRequire meta in
  1069. let p = (s_path ctx path) in
  1070. if ctx.js_flatten then
  1071. spr ctx "var "
  1072. else
  1073. generate_package_create ctx path;
  1074. (match args with
  1075. | [(EConst(String(module_name)),_)] ->
  1076. print ctx "%s = require(\"%s\")" p module_name
  1077. | [(EConst(String(module_name)),_) ; (EConst(String(object_path)),_)] ->
  1078. print ctx "%s = require(\"%s\").%s" p module_name object_path
  1079. | _ ->
  1080. error "Unsupported @:jsRequire format" mp);
  1081. newline ctx
  1082. let generate_type ctx = function
  1083. | TClassDecl c ->
  1084. (match c.cl_init with
  1085. | None -> ()
  1086. | Some e ->
  1087. ctx.inits <- e :: ctx.inits);
  1088. (* Special case, want to add Math.__name__ only when required, handle here since Math is extern *)
  1089. let p = s_path ctx c.cl_path in
  1090. if p = "Math" then generate_class___name__ ctx c;
  1091. (* Another special case for Std because we do not want to generate it if it's empty. *)
  1092. if p = "Std" && c.cl_ordered_statics = [] then
  1093. ()
  1094. else if not c.cl_extern then
  1095. generate_class ctx c
  1096. else if Meta.has Meta.JsRequire c.cl_meta && is_directly_used ctx.com c.cl_meta then
  1097. generate_require ctx c.cl_path c.cl_meta
  1098. else if not ctx.js_flatten && Meta.has Meta.InitPackage c.cl_meta then
  1099. (match c.cl_path with
  1100. | ([],_) -> ()
  1101. | _ -> generate_package_create ctx c.cl_path)
  1102. | TEnumDecl e when e.e_extern ->
  1103. if Meta.has Meta.JsRequire e.e_meta && is_directly_used ctx.com e.e_meta then
  1104. generate_require ctx e.e_path e.e_meta
  1105. | TEnumDecl e -> generate_enum ctx e
  1106. | TTypeDecl _ | TAbstractDecl _ -> ()
  1107. let set_current_class ctx c =
  1108. ctx.current <- c
  1109. let alloc_ctx com =
  1110. let ctx = {
  1111. com = com;
  1112. buf = Rbuffer.create 16000;
  1113. packages = Hashtbl.create 0;
  1114. smap = {
  1115. source_last_line = 0;
  1116. source_last_col = 0;
  1117. source_last_file = 0;
  1118. print_comma = false;
  1119. output_last_col = 0;
  1120. output_current_col = 0;
  1121. sources = DynArray.create();
  1122. sources_hash = Hashtbl.create 0;
  1123. mappings = Rbuffer.create 16;
  1124. };
  1125. js_modern = not (Common.defined com Define.JsClassic);
  1126. js_flatten = not (Common.defined com Define.JsUnflatten);
  1127. statics = [];
  1128. inits = [];
  1129. current = null_class;
  1130. tabs = "";
  1131. in_value = None;
  1132. in_loop = false;
  1133. handle_break = false;
  1134. id_counter = 0;
  1135. type_accessor = (fun _ -> assert false);
  1136. separator = false;
  1137. found_expose = false;
  1138. } in
  1139. ctx.type_accessor <- (fun t ->
  1140. let p = t_path t in
  1141. match t with
  1142. | TClassDecl ({ cl_extern = true } as c) when not (Meta.has Meta.JsRequire c.cl_meta)
  1143. -> dot_path p
  1144. | TEnumDecl ({ e_extern = true } as e) when not (Meta.has Meta.JsRequire e.e_meta)
  1145. -> dot_path p
  1146. | _ -> s_path ctx p);
  1147. ctx
  1148. let gen_single_expr ctx e expr =
  1149. if expr then gen_expr ctx e else gen_value ctx e;
  1150. let str = Rbuffer.unsafe_contents ctx.buf in
  1151. Rbuffer.reset ctx.buf;
  1152. ctx.id_counter <- 0;
  1153. str
  1154. let generate com =
  1155. let t = Common.timer "generate js" in
  1156. (match com.js_gen with
  1157. | Some g -> g()
  1158. | None ->
  1159. let ctx = alloc_ctx com in
  1160. if has_feature ctx "Class" || has_feature ctx "Type.getClassName" then add_feature ctx "js.Boot.isClass";
  1161. if has_feature ctx "Enum" || has_feature ctx "Type.getEnumName" then add_feature ctx "js.Boot.isEnum";
  1162. let exposed = List.concat (List.map (fun t ->
  1163. match t with
  1164. | TClassDecl c ->
  1165. let path = dot_path c.cl_path in
  1166. let class_exposed = get_exposed ctx path c.cl_meta in
  1167. let static_exposed = List.map (fun f ->
  1168. get_exposed ctx (path ^ static_field f.cf_name) f.cf_meta
  1169. ) c.cl_ordered_statics in
  1170. List.concat (class_exposed :: static_exposed)
  1171. | _ -> []
  1172. ) com.types) in
  1173. let anyExposed = exposed <> [] in
  1174. let exportMap = ref (PMap.create String.compare) in
  1175. let exposedObject = { os_name = ""; os_fields = [] } in
  1176. let toplevelExposed = ref [] in
  1177. List.iter (fun path -> (
  1178. let parts = ExtString.String.nsplit path "." in
  1179. let rec loop p pre = match p with
  1180. | f :: g :: ls ->
  1181. let path = match pre with "" -> f | pre -> (pre ^ "." ^ f) in
  1182. if not (PMap.exists path !exportMap) then (
  1183. let elts = { os_name = f; os_fields = [] } in
  1184. exportMap := PMap.add path elts !exportMap;
  1185. let cobject = match pre with "" -> exposedObject | pre -> PMap.find pre !exportMap in
  1186. cobject.os_fields <- elts :: cobject.os_fields
  1187. );
  1188. loop (g :: ls) path;
  1189. | f :: [] when pre = "" ->
  1190. toplevelExposed := f :: !toplevelExposed;
  1191. | _ -> ()
  1192. in loop parts "";
  1193. )) exposed;
  1194. let closureArgs = [] in
  1195. let closureArgs = if (anyExposed && not (Common.defined com Define.ShallowExpose)) then
  1196. (
  1197. "$hx_exports",
  1198. (* TODO(bruno): Remove runtime branching when standard node haxelib is available *)
  1199. "typeof window != \"undefined\" ? window : exports"
  1200. ) :: closureArgs
  1201. else
  1202. closureArgs
  1203. in
  1204. (* Provide console for environments that may not have it. *)
  1205. let closureArgs = if (not (Common.defined com Define.JsEs5)) then
  1206. (
  1207. "console",
  1208. "typeof console != \"undefined\" ? console : {log:function(){}}"
  1209. ) :: closureArgs
  1210. else
  1211. closureArgs
  1212. in
  1213. if Common.raw_defined com "nodejs" then
  1214. (* Add node globals to pseudo-keywords, so they are not shadowed by local vars *)
  1215. List.iter (fun s -> Hashtbl.replace kwds2 s ()) [ "global"; "process"; "__filename"; "__dirname"; "module" ];
  1216. if ctx.js_modern then begin
  1217. (* Additional ES5 strict mode keywords. *)
  1218. List.iter (fun s -> Hashtbl.replace kwds s ()) [ "arguments"; "eval" ];
  1219. (* Wrap output in a closure *)
  1220. if (anyExposed && (Common.defined com Define.ShallowExpose)) then (
  1221. print ctx "var $hx_exports = $hx_exports || {}";
  1222. ctx.separator <- true;
  1223. newline ctx
  1224. );
  1225. print ctx "(function (%s) { \"use strict\"" (String.concat ", " (List.map fst closureArgs));
  1226. newline ctx;
  1227. let rec print_obj f root = (
  1228. let path = root ^ "." ^ f.os_name in
  1229. print ctx "%s = %s || {}" path path;
  1230. ctx.separator <- true;
  1231. newline ctx;
  1232. concat ctx ";" (fun g -> print_obj g path) f.os_fields
  1233. )
  1234. in
  1235. List.iter (fun f -> print_obj f "$hx_exports") exposedObject.os_fields;
  1236. end;
  1237. (* If ctx.js_modern, console is defined in closureArgs. *)
  1238. if (not ctx.js_modern) && (not (Common.defined com Define.JsEs5)) then
  1239. spr ctx "var console = Function(\"return typeof console != 'undefined' ? console : {log:function(){}}\")();\n";
  1240. (* TODO: fix $estr *)
  1241. let vars = [] in
  1242. let vars = (if has_feature ctx "Type.resolveClass" || has_feature ctx "Type.resolveEnum" then ("$hxClasses = " ^ (if ctx.js_modern then "{}" else "$hxClasses || {}")) :: vars else vars) in
  1243. let vars = if has_feature ctx "may_print_enum"
  1244. then ("$estr = function() { return " ^ (ctx.type_accessor (TClassDecl { null_class with cl_path = ["js"],"Boot" })) ^ ".__string_rec(this,''); }") :: vars
  1245. else vars in
  1246. (match List.rev vars with
  1247. | [] -> ()
  1248. | vl ->
  1249. print ctx "var %s" (String.concat "," vl);
  1250. ctx.separator <- true;
  1251. newline ctx
  1252. );
  1253. if List.exists (function TClassDecl { cl_extern = false; cl_super = Some _ } -> true | _ -> false) com.types then begin
  1254. print ctx "function $extend(from, fields) {
  1255. function Inherit() {} Inherit.prototype = from; var proto = new Inherit();
  1256. for (var name in fields) proto[name] = fields[name];
  1257. if( fields.toString !== Object.prototype.toString ) proto.toString = fields.toString;
  1258. return proto;
  1259. }
  1260. ";
  1261. end;
  1262. List.iter (generate_type ctx) com.types;
  1263. let rec chk_features e =
  1264. if is_dynamic_iterator ctx e then add_feature ctx "use.$iterator";
  1265. match e.eexpr with
  1266. | TField (_,FClosure _) ->
  1267. add_feature ctx "use.$bind"
  1268. | _ ->
  1269. Type.iter chk_features e
  1270. in
  1271. List.iter chk_features ctx.inits;
  1272. List.iter (fun (_,_,e) -> chk_features e) ctx.statics;
  1273. if has_feature ctx "use.$iterator" then begin
  1274. add_feature ctx "use.$bind";
  1275. print ctx "function $iterator(o) { if( o instanceof Array ) return function() { return HxOverrides.iter(o); }; return typeof(o.iterator) == 'function' ? $bind(o,o.iterator) : o.iterator; }";
  1276. newline ctx;
  1277. end;
  1278. if has_feature ctx "use.$bind" then begin
  1279. print ctx "var $_, $fid = 0";
  1280. newline ctx;
  1281. print ctx "function $bind(o,m) { if( m == null ) return null; if( m.__id__ == null ) m.__id__ = $fid++; var f; if( o.hx__closures__ == null ) o.hx__closures__ = {}; else f = o.hx__closures__[m.__id__]; if( f == null ) { f = function(){ return f.method.apply(f.scope, arguments); }; f.scope = o; f.method = m; o.hx__closures__[m.__id__] = f; } return f; }";
  1282. newline ctx;
  1283. end;
  1284. if has_feature ctx "use.$arrayPushClosure" then begin
  1285. print ctx "function $arrayPushClosure(a) {";
  1286. print ctx " return function(x) { a.push(x); }; ";
  1287. print ctx "}";
  1288. newline ctx
  1289. end;
  1290. List.iter (gen_block_element ~after:true ctx) (List.rev ctx.inits);
  1291. List.iter (generate_static ctx) (List.rev ctx.statics);
  1292. (match com.main with
  1293. | None -> ()
  1294. | Some e -> gen_expr ctx e; newline ctx);
  1295. if ctx.js_modern then begin
  1296. print ctx "})(%s)" (String.concat ", " (List.map snd closureArgs));
  1297. newline ctx;
  1298. if (anyExposed && (Common.defined com Define.ShallowExpose)) then (
  1299. List.iter (fun f ->
  1300. print ctx "var %s = $hx_exports.%s" f.os_name f.os_name;
  1301. ctx.separator <- true;
  1302. newline ctx
  1303. ) exposedObject.os_fields;
  1304. List.iter (fun f ->
  1305. print ctx "var %s = $hx_exports.%s" f f;
  1306. ctx.separator <- true;
  1307. newline ctx
  1308. ) !toplevelExposed
  1309. );
  1310. end;
  1311. if com.debug then write_mappings ctx else (try Sys.remove (com.file ^ ".map") with _ -> ());
  1312. let ch = open_out_bin com.file in
  1313. Rbuffer.output_buffer ch ctx.buf;
  1314. close_out ch);
  1315. t()