genjs.ml 42 KB

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