genjs.ml 44 KB

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