genpy.ml 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448
  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. module Utils = struct
  20. let class_of_module_type mt = match mt with
  21. | TClassDecl c -> c
  22. | _ -> failwith ("Not a class: " ^ (s_type_path (t_infos mt).mt_path))
  23. let find_type com path =
  24. try
  25. List.find (fun mt -> match mt with
  26. | TAbstractDecl _ -> false
  27. | _ -> (t_infos mt).mt_path = path
  28. ) com.types
  29. with Not_found ->
  30. error (Printf.sprintf "Could not find type %s\n" (s_type_path path)) null_pos
  31. let mk_static_field c cf p =
  32. let ta = TAnon { a_fields = c.cl_statics; a_status = ref (Statics c) } in
  33. let ethis = mk (TTypeExpr (TClassDecl c)) ta p in
  34. let t = monomorphs cf.cf_params cf.cf_type in
  35. mk (TField (ethis,(FStatic (c,cf)))) t p
  36. let mk_static_call c cf el p =
  37. let ef = mk_static_field c cf p in
  38. let tr = match follow ef.etype with
  39. | TFun(args,tr) -> tr
  40. | _ -> assert false
  41. in
  42. mk (TCall(ef,el)) tr p
  43. let resolve_static_field c n =
  44. try
  45. PMap.find n c.cl_statics
  46. with Not_found ->
  47. failwith (Printf.sprintf "Class %s has no field %s" (s_type_path c.cl_path) n)
  48. let mk_static_field_2 c n p =
  49. mk_static_field c (resolve_static_field c n) p
  50. let mk_static_call_2 c n el p =
  51. mk_static_call c (resolve_static_field c n) el p
  52. end
  53. module KeywordHandler = struct
  54. let kwds =
  55. let h = Hashtbl.create 0 in
  56. List.iter (fun s -> Hashtbl.add h s ()) [
  57. "and"; "as"; "assert"; "break"; "class"; "continue"; "def"; "del"; "elif"; "else"; "except"; "exec"; "finally"; "for";
  58. "from"; "global"; "if"; "import"; "in"; "is"; "lambda"; "not"; "or"; "pass"; " raise"; "return"; "try"; "while";
  59. "with"; "yield"; "None"; "True"; "False";
  60. ];
  61. h
  62. let kwds2 =
  63. let h = Hashtbl.create 0 in
  64. List.iter (fun s -> Hashtbl.add h s ()) [
  65. "len"; "int"; "float"; "list"; "bool"; "str"; "isinstance"; "print"; "min"; "max";
  66. "hasattr"; "getattr"; "setattr"; "delattr"; "callable"; "type"; "ord"; "chr"; "iter"; "map"; "filter";
  67. "tuple"; "dict"; "set"; "bytes"; "bytearray"
  68. ];
  69. h
  70. let handle_keywords s =
  71. let l = String.length s in
  72. if Hashtbl.mem kwds s then
  73. "_hx_" ^ s
  74. (*
  75. handle special __ underscore behaviour (creates private fields for objects) for fields but only if the field doesn't
  76. end with at least one underscores like __iter__ because these are special fields
  77. *)
  78. else if l > 2 && String.sub s 0 2 = "__" && String.sub s (l - 1) 1 <> "_" then
  79. "_hx_" ^ s
  80. else s
  81. let check_var_declaration v =
  82. if Hashtbl.mem kwds2 v.v_name then v.v_name <- "_hx_" ^ v.v_name
  83. end
  84. module Transformer = struct
  85. type adjusted_expr = {
  86. a_expr : texpr;
  87. a_blocks : texpr list;
  88. a_next_id : unit -> string;
  89. a_is_value : bool;
  90. }
  91. let como = ref None
  92. let t_bool = ref t_dynamic
  93. let t_void = ref t_dynamic
  94. let t_string = ref t_dynamic
  95. let t_int = ref t_dynamic
  96. let c_reflect = ref (fun () -> null_class)
  97. let init com =
  98. como := Some com;
  99. t_bool := com.basic.tbool;
  100. t_void := com.basic.tvoid;
  101. t_string := com.basic.tstring;
  102. t_int := com.basic.tint;
  103. c_reflect := fun () -> Utils.class_of_module_type (Utils.find_type com ([],"Reflect"))
  104. and debug_expr e =
  105. let s_type = Type.s_type (print_context()) in
  106. let s = Type.s_expr_pretty " " s_type e in
  107. Printf.printf "%s\n" s
  108. and debug_expr_with_type e =
  109. let s_type = Type.s_type (print_context()) in
  110. let es = Type.s_expr_pretty " " s_type e in
  111. let t = s_type e.etype in
  112. Printf.printf "%s : %s\n" es t
  113. and debug_type t =
  114. let s_type = Type.s_type (print_context()) in
  115. let t = s_type t in
  116. Printf.printf "%s\n" t
  117. let new_counter () =
  118. let n = ref (-1) in
  119. (fun () ->
  120. incr n;
  121. Printf.sprintf "_hx_local_%i" !n
  122. )
  123. let to_expr ae =
  124. match ae.a_blocks with
  125. | [] ->
  126. ae.a_expr
  127. | el ->
  128. match ae.a_expr.eexpr with
  129. | TBlock el2 ->
  130. { ae.a_expr with eexpr = TBlock (el @ el2) }
  131. | _ ->
  132. { ae.a_expr with eexpr = TBlock (el @ [ae.a_expr])}
  133. let lift_expr ?(is_value = false) ?(next_id = None) ?(blocks = []) e =
  134. let next_id = match next_id with
  135. | None ->
  136. new_counter()
  137. | Some f ->
  138. f
  139. in
  140. {
  141. a_expr = e;
  142. a_blocks = blocks;
  143. a_next_id = next_id;
  144. a_is_value = is_value
  145. }
  146. let lift_expr1 is_value next_id blocks e =
  147. lift_expr ~is_value:is_value ~next_id:(Some next_id) ~blocks:blocks e
  148. let to_tvar ?(capture = false) n t =
  149. alloc_var n t
  150. (* { v_name = n; v_type = t; v_id = 0; v_capture = capture; v_extra = None; v_meta = [] } *)
  151. let create_non_local n pos =
  152. let s = "nonlocal " ^ (KeywordHandler.handle_keywords n) in
  153. (* TODO: this is a hack... *)
  154. let id = mk (TLocal (to_tvar "python_Syntax._pythonCode" t_dynamic ) ) !t_void pos in
  155. let id2 = mk (TLocal( to_tvar s t_dynamic )) !t_void pos in
  156. mk (TCall(id, [id2])) t_dynamic pos
  157. let to_tlocal_expr ?(capture = false) n t p =
  158. mk (TLocal (to_tvar ~capture:capture n t)) t p
  159. let check_unification e t = match follow e.etype,follow t with
  160. | TAnon an1, TAnon an2 ->
  161. PMap.iter (fun s cf ->
  162. if not (PMap.mem s an1.a_fields) then an1.a_fields <- PMap.add s cf an1.a_fields
  163. ) an2.a_fields;
  164. e
  165. | _ ->
  166. e
  167. let dynamic_field_read e s t =
  168. let e = Utils.mk_static_call_2 ((!c_reflect)()) "field" [e;mk (TConst (TString s)) !t_string e.epos] e.epos in
  169. { e with etype = t }
  170. let dynamic_field_write e1 s e2 =
  171. Utils.mk_static_call_2 ((!c_reflect)()) "setField" [e1;mk (TConst (TString s)) !t_string e1.epos;e2] e1.epos
  172. let dynamic_field_read_write next_id e1 s op e2 t =
  173. let id = next_id() in
  174. let temp_var = to_tvar id e1.etype in
  175. let temp_var_def = mk (TVar(temp_var,Some e1)) e1.etype e1.epos in
  176. let temp_local = mk (TLocal temp_var) e1.etype e1.epos in
  177. let e_field = dynamic_field_read temp_local s t in
  178. let e_op = mk (TBinop(op,e_field,e2)) e_field.etype e_field.epos in
  179. let e_set_field = dynamic_field_write temp_local s e_op in
  180. mk (TBlock [
  181. temp_var_def;
  182. e_set_field;
  183. ]) e_set_field.etype e_set_field.epos
  184. let add_non_locals_to_func e = match e.eexpr with
  185. | TFunction tf ->
  186. let cur = ref PMap.empty in
  187. let save () =
  188. let prev = !cur in
  189. (fun () ->
  190. cur := prev
  191. )
  192. in
  193. let declare v =
  194. cur := PMap.add v.v_id v !cur;
  195. in
  196. List.iter (fun (v,_) -> declare v) tf.tf_args;
  197. let non_locals = Hashtbl.create 0 in
  198. let rec it e = match e.eexpr with
  199. | TVar(v,e1) ->
  200. begin match e1 with
  201. | Some e ->
  202. maybe_continue e
  203. | None ->
  204. ()
  205. end;
  206. declare v;
  207. | TTry(e1,catches) ->
  208. it e1;
  209. List.iter (fun (v,e) ->
  210. let restore = save() in
  211. declare v;
  212. it e;
  213. restore()
  214. ) catches;
  215. | TBinop( (OpAssign | OpAssignOp(_)), { eexpr = TLocal v }, e2) ->
  216. if not (PMap.mem v.v_id !cur) then
  217. Hashtbl.add non_locals v.v_id v;
  218. maybe_continue e2;
  219. | TFunction _ ->
  220. ()
  221. | _ ->
  222. Type.iter it e
  223. and maybe_continue e = match e.eexpr with
  224. | TFunction _ ->
  225. ()
  226. | _ ->
  227. it e
  228. in
  229. it tf.tf_expr;
  230. let el = Hashtbl.fold (fun k v acc ->
  231. (create_non_local v.v_name e.epos) :: acc
  232. ) non_locals [] in
  233. let el = tf.tf_expr :: el in
  234. let tf = { tf with tf_expr = { tf.tf_expr with eexpr = TBlock(List.rev el)}} in
  235. {e with eexpr = TFunction tf}
  236. | _ ->
  237. assert false
  238. let rec transform_function tf ae is_value =
  239. let p = tf.tf_expr.epos in
  240. let assigns = List.fold_left (fun acc (v,value) -> match value with
  241. | None | Some TNull ->
  242. acc
  243. | Some ct ->
  244. let a_local = mk (TLocal v) v.v_type p in
  245. let a_null = mk (TConst TNull) v.v_type p in
  246. let a_cmp = mk (TBinop(OpEq,a_local,a_null)) !t_bool p in
  247. let a_value = mk (TConst(ct)) v.v_type p in
  248. let a_assign = mk (TBinop(OpAssign,a_local,a_value)) v.v_type p in
  249. let a_if = mk (TIf(a_cmp,a_assign,None)) !t_void p in
  250. a_if :: acc
  251. ) [] tf.tf_args in
  252. let body = match assigns with
  253. | [] ->
  254. tf.tf_expr
  255. | _ ->
  256. let eb = mk (TBlock (List.rev assigns)) t_dynamic p in
  257. Type.concat eb tf.tf_expr
  258. in
  259. let e1 = to_expr (transform_expr ~next_id:(Some ae.a_next_id) body) in
  260. let fn = mk (TFunction({
  261. tf_expr = e1;
  262. tf_args = tf.tf_args;
  263. tf_type = tf.tf_type;
  264. })) ae.a_expr.etype p in
  265. let fn = add_non_locals_to_func fn in
  266. if is_value then begin
  267. let new_name = ae.a_next_id() in
  268. let new_var = alloc_var new_name tf.tf_type in
  269. let new_local = mk (TLocal new_var) fn.etype p in
  270. let def = mk (TVar(new_var,Some fn)) fn.etype p in
  271. lift_expr1 false ae.a_next_id [def] new_local
  272. end else
  273. lift_expr fn
  274. and transform_var_expr ae eo v =
  275. let b,new_expr = match eo with
  276. | None ->
  277. [],None
  278. | Some e1 ->
  279. let f = transform_expr1 true ae.a_next_id [] e1 in
  280. let b = f.a_blocks in
  281. b,Some(f.a_expr)
  282. in
  283. let e = mk (TVar(v,new_expr)) ae.a_expr.etype ae.a_expr.epos in
  284. lift_expr ~next_id:(Some ae.a_next_id) ~blocks:b e
  285. and transform_expr ?(is_value = false) ?(next_id = None) ?(blocks = []) (e : texpr) : adjusted_expr =
  286. transform1 (lift_expr ~is_value ~next_id ~blocks e)
  287. and transform_expr1 is_value next_id blocks e =
  288. transform_expr ~is_value ~next_id:(Some next_id) ~blocks e
  289. and transform_exprs_to_block el tb is_value p next_id =
  290. match el with
  291. | [e] ->
  292. transform_expr ~is_value ~next_id:(Some next_id) e
  293. | _ ->
  294. let size = List.length el in
  295. let res = DynArray.create () in
  296. ExtList.List.iteri (fun i e ->
  297. (* this removes len(x) calls which are reproduced by the inlined return
  298. of Array.push even if the value is not used *)
  299. let is_removable_statement e = (not is_value || i < size-1) &&
  300. match e.eexpr with
  301. | TField(_, FInstance({cl_path = [],"list"},_,{ cf_name = "length" })) -> true
  302. | _ -> false
  303. in
  304. if not (is_removable_statement e) then
  305. let ae = transform_expr ~is_value ~next_id:(Some next_id) e in
  306. List.iter (DynArray.add res) ae.a_blocks;
  307. DynArray.add res ae.a_expr
  308. else
  309. ()
  310. ) el;
  311. lift_expr (mk (TBlock (DynArray.to_list res)) tb p)
  312. and transform_switch ae is_value e1 cases edef =
  313. let case_functions = ref [] in
  314. let case_to_if (el,e) eelse =
  315. let val_reversed = List.rev el in
  316. let mk_eq e = mk (TBinop(OpEq,e1,e)) !t_bool (punion e1.epos e.epos) in
  317. let cond = match val_reversed with
  318. | [] ->
  319. assert false
  320. | [e] ->
  321. mk_eq e
  322. | e :: el ->
  323. List.fold_left (fun eelse e -> mk (TBinop(OpBoolOr,eelse,mk_eq e)) !t_bool (punion eelse.epos e.epos)) (mk_eq e) el
  324. in
  325. let eif = if is_value then begin
  326. let name = ae.a_next_id() in
  327. let func = exprs_to_func [e] name ae in
  328. case_functions := !case_functions @ func.a_blocks;
  329. let call = func.a_expr in
  330. mk (TIf(cond,call,eelse)) ae.a_expr.etype ae.a_expr.epos
  331. end else
  332. mk (TIf(cond,e,eelse)) ae.a_expr.etype e.epos
  333. in
  334. eif
  335. in
  336. let rev_cases = List.rev cases in
  337. let edef = Some (match edef with
  338. | None ->
  339. mk (TBlock []) ae.a_expr.etype ae.a_expr.epos
  340. | Some e ->
  341. e)
  342. in
  343. let res = match rev_cases,edef with
  344. | [],Some edef ->
  345. edef
  346. | [],None ->
  347. (* I don't think that can happen? *)
  348. assert false
  349. | [case],_ ->
  350. case_to_if case edef
  351. | case :: cases,_ ->
  352. List.fold_left (fun acc case -> case_to_if case (Some acc)) (case_to_if case edef) cases
  353. in
  354. let res = if is_value then
  355. mk (TBlock ((List.rev (res :: !case_functions)))) res.etype res.epos
  356. else
  357. res
  358. in
  359. forward_transform res ae
  360. and transform_string_switch ae is_value e1 cases edef =
  361. let length_map = Hashtbl.create 0 in
  362. List.iter (fun (el,e) ->
  363. List.iter (fun es ->
  364. match es.eexpr with
  365. | TConst (TString s) ->
  366. let l = UTF8.length s in
  367. let sl = try
  368. Hashtbl.find length_map l
  369. with Not_found ->
  370. let sl = ref [] in
  371. Hashtbl.replace length_map l sl;
  372. sl
  373. in
  374. sl := ([es],e) :: !sl;
  375. | _ ->
  376. ()
  377. ) el
  378. ) cases;
  379. if Hashtbl.length length_map < 2 then
  380. transform_switch ae is_value e1 cases edef
  381. else
  382. let mk_eq e1 e2 = mk (TBinop(OpEq,e1,e2)) !t_bool (punion e1.epos e2.epos) in
  383. let mk_or e1 e2 = mk (TBinop(OpOr,e1,e2)) !t_bool (punion e1.epos e2.epos) in
  384. let mk_if (el,e) eo =
  385. let eif = List.fold_left (fun eacc e -> mk_or eacc (mk_eq e1 e)) (mk_eq e1 (List.hd el)) (List.tl el) in
  386. mk (TIf(Codegen.mk_parent eif,e,eo)) e.etype e.epos
  387. in
  388. let cases = Hashtbl.fold (fun i el acc ->
  389. let eint = mk (TConst (TInt (Int32.of_int i))) !t_int e1.epos in
  390. let fs = match List.fold_left (fun eacc ec -> Some (mk_if ec eacc)) edef !el with Some e -> e | None -> assert false in
  391. ([eint],fs) :: acc
  392. ) length_map [] in
  393. let c_string = match !t_string with TInst(c,_) -> c | _ -> assert false in
  394. let cf_length = PMap.find "length" c_string.cl_fields in
  395. let ef = mk (TField(e1,FInstance(c_string,[],cf_length))) !t_int e1.epos in
  396. let res_var = alloc_var (ae.a_next_id()) ef.etype in
  397. let res_local = {ef with eexpr = TLocal res_var} in
  398. let var_expr = {ef with eexpr = TVar(res_var,Some ef)} in
  399. let e = mk (TBlock [
  400. var_expr;
  401. mk (TSwitch(res_local,cases,edef)) ae.a_expr.etype e1.epos
  402. ]) ae.a_expr.etype e1.epos in
  403. forward_transform e ae
  404. and transform_op_assign_op ae e1 op one is_value post =
  405. let e1_ = transform_expr e1 ~is_value:true ~next_id:(Some ae.a_next_id) in
  406. let handle_as_local temp_local =
  407. let ex = ae.a_expr in
  408. let res_var = alloc_var (ae.a_next_id()) ex.etype in
  409. let res_local = {ex with eexpr = TLocal res_var} in
  410. let plus = {ex with eexpr = TBinop(op,temp_local,one)} in
  411. let var_expr = {ex with eexpr = TVar(res_var,Some temp_local)} in
  412. let assign_expr = {ex with eexpr = TBinop(OpAssign,e1_.a_expr,plus)} in
  413. let blocks = if post then
  414. [var_expr;assign_expr;res_local]
  415. else
  416. [assign_expr;temp_local]
  417. in
  418. (* TODO: block is ignored in the else case? *)
  419. let block = e1_.a_blocks @ blocks in
  420. if is_value then begin
  421. let f = exprs_to_func block (ae.a_next_id()) ae in
  422. lift_expr f.a_expr ~is_value:true ~next_id:(Some ae.a_next_id) ~blocks:f.a_blocks
  423. end else begin
  424. let block = e1_.a_blocks @ [assign_expr] in
  425. transform_exprs_to_block block ex.etype false ex.epos ae.a_next_id
  426. end
  427. in
  428. match e1_.a_expr.eexpr with
  429. | TArray({eexpr = TLocal _},{eexpr = TLocal _})
  430. | TField({eexpr = TLocal _},_)
  431. | TLocal _ ->
  432. handle_as_local e1_.a_expr
  433. | TArray(e1,e2) ->
  434. let id = ae.a_next_id() in
  435. let temp_var_l = alloc_var id e1.etype in
  436. let temp_local_l = {e1 with eexpr = TLocal temp_var_l} in
  437. let temp_var_l = {e1 with eexpr = TVar(temp_var_l,Some e1)} in
  438. let id = ae.a_next_id() in
  439. let temp_var_r = alloc_var id e2.etype in
  440. let temp_local_r = {e2 with eexpr = TLocal temp_var_r} in
  441. let temp_var_r = {e2 with eexpr = TVar(temp_var_r,Some e2)} in
  442. let id = ae.a_next_id() in
  443. let temp_var = alloc_var id e1_.a_expr.etype in
  444. let temp_local = {e1_.a_expr with eexpr = TLocal temp_var} in
  445. let temp_var_expr = {e1_.a_expr with eexpr = TArray(temp_local_l,temp_local_r)} in
  446. let temp_var = {e1_.a_expr with eexpr = TVar(temp_var,Some temp_var_expr)} in
  447. let plus = {ae.a_expr with eexpr = TBinop(op,temp_local,one)} in
  448. let assign_expr = {ae.a_expr with eexpr = TBinop(OpAssign,temp_var_expr,plus)} in
  449. let block = e1_.a_blocks @ [temp_var_l;temp_var_r;temp_var;assign_expr;if post then temp_local else temp_var_expr] in
  450. if is_value then begin
  451. let f = exprs_to_func block (ae.a_next_id()) ae in
  452. lift_expr f.a_expr ~is_value:true ~next_id:(Some ae.a_next_id) ~blocks:f.a_blocks
  453. end else
  454. transform_exprs_to_block block ae.a_expr.etype false ae.a_expr.epos ae.a_next_id
  455. | TField(e1,fa) ->
  456. let temp_var_l = alloc_var (ae.a_next_id()) e1.etype in
  457. let temp_local_l = {e1 with eexpr = TLocal temp_var_l} in
  458. let temp_var_l = {e1 with eexpr = TVar(temp_var_l,Some e1)} in
  459. let temp_var = alloc_var (ae.a_next_id()) e1_.a_expr.etype in
  460. let temp_local = {e1_.a_expr with eexpr = TLocal temp_var} in
  461. let temp_var_expr = {e1_.a_expr with eexpr = TField(temp_local_l,fa)} in
  462. let temp_var = {e1_.a_expr with eexpr = TVar(temp_var,Some temp_var_expr)} in
  463. let plus = {ae.a_expr with eexpr = TBinop(op,temp_local,one)} in
  464. let assign_expr = {ae.a_expr with eexpr = TBinop(OpAssign,temp_var_expr,plus)} in
  465. let block = e1_.a_blocks @ [temp_var_l;temp_var;assign_expr;if post then temp_local else temp_var_expr] in
  466. if is_value then begin
  467. let f = exprs_to_func block (ae.a_next_id()) ae in
  468. lift_expr f.a_expr ~is_value:true ~next_id:(Some ae.a_next_id) ~blocks:f.a_blocks
  469. end else
  470. transform_exprs_to_block block ae.a_expr.etype false ae.a_expr.epos ae.a_next_id
  471. | _ ->
  472. debug_expr e1_.a_expr;
  473. assert false
  474. and var_to_treturn_expr ?(capture = false) n t p =
  475. let x = mk (TLocal (to_tvar ~capture:capture n t)) t p in
  476. mk (TReturn (Some x)) t p
  477. and exprs_to_func exprs name base =
  478. let convert_return_expr (expr:texpr) =
  479. match expr.eexpr with
  480. | TWhile(_,_,_) ->
  481. let ret = { expr with eexpr = TReturn (None) } in
  482. [expr; ret]
  483. | TFunction(f) ->
  484. let ret = var_to_treturn_expr name f.tf_type f.tf_expr.epos in
  485. [expr;ret]
  486. | TBinop(OpAssign, l, r) ->
  487. let r = { l with eexpr = TReturn(Some l) } in
  488. [expr; r]
  489. | x ->
  490. let ret_expr = { expr with eexpr = TReturn( Some(expr) )} in
  491. [ret_expr]
  492. in
  493. let def =
  494. (let ex = match exprs with
  495. | [] -> assert false
  496. | [x] ->
  497. (let exs = convert_return_expr x in
  498. match exs with
  499. | [] -> assert false
  500. | [x] -> x
  501. | x ->
  502. match List.rev x with
  503. | x::xs ->
  504. mk (TBlock exs) x.etype base.a_expr.epos
  505. | _ -> assert false)
  506. | x ->
  507. match List.rev x with
  508. | x::xs ->
  509. (let ret = x in
  510. let tail = List.rev xs in
  511. let block = tail @ (convert_return_expr ret) in
  512. match List.rev block with
  513. | x::_ ->
  514. mk (TBlock block) x.etype base.a_expr.epos
  515. | _ -> assert false)
  516. | _ -> assert false
  517. in
  518. let f1 = { tf_args = []; tf_type = TFun([],ex.etype); tf_expr = ex} in
  519. let fexpr = mk (TFunction f1) ex.etype ex.epos in
  520. let fvar = to_tvar name fexpr.etype in
  521. let f = add_non_locals_to_func fexpr in
  522. let assign = { ex with eexpr = TVar(fvar, Some(f))} in
  523. let call_expr = (mk (TLocal fvar) fexpr.etype ex.epos ) in
  524. let substitute = mk (TCall(call_expr, [])) ex.etype ex.epos in
  525. lift_expr ~blocks:[assign] substitute)
  526. in
  527. match exprs with
  528. | [{ eexpr = TFunction({ tf_args = []} as f) } as x] ->
  529. let l = to_tlocal_expr name f.tf_type f.tf_expr.epos in
  530. let substitute = mk (TCall(l, [])) f.tf_type f.tf_expr.epos in
  531. lift_expr ~blocks:[x] substitute
  532. | _ -> def
  533. and transform_call is_value e params ae =
  534. let trans is_value blocks e = transform_expr1 is_value ae.a_next_id blocks e in
  535. let trans1 e params =
  536. let e = trans true [] e in
  537. let blocks = e.a_blocks @ (List.flatten (List.map (fun (p) -> p.a_blocks) params)) in
  538. let params = List.map (fun (p) -> p.a_expr) params in
  539. let e = { ae.a_expr with eexpr = TCall(e.a_expr, params) } in
  540. lift_expr ~blocks:blocks e
  541. in
  542. match e, params with
  543. (* the foreach block should not be handled as a value *)
  544. | ({ eexpr = TField(_, FStatic({cl_path = ["python";],"Syntax"},{ cf_name = "_foreach" }))} as e, [e1;e2;e3]) ->
  545. trans1 e [trans true [] e1; trans true [] e2; trans false [] e3]
  546. | (e, params) ->
  547. trans1 e (List.map (trans true []) params)
  548. and transform1 ae : adjusted_expr =
  549. let trans is_value blocks e = transform_expr1 is_value ae.a_next_id blocks e in
  550. let lift is_value blocks e = lift_expr1 is_value ae.a_next_id blocks e in
  551. let a_expr = ae.a_expr in
  552. match ae.a_is_value,ae.a_expr.eexpr with
  553. | (is_value,TBlock [x]) ->
  554. trans is_value [] x
  555. | (false,TBlock []) ->
  556. lift_expr a_expr
  557. | (true,TBlock []) ->
  558. lift_expr (mk (TConst TNull) ae.a_expr.etype ae.a_expr.epos)
  559. | (false,TBlock el) ->
  560. transform_exprs_to_block el ae.a_expr.etype false ae.a_expr.epos ae.a_next_id
  561. | (true,TBlock el) ->
  562. let name = ae.a_next_id() in
  563. let block,tr = match List.rev el with
  564. | e :: el ->
  565. List.rev ((mk (TReturn (Some e)) t_dynamic e.epos) :: el),e.etype
  566. | [] ->
  567. assert false
  568. in
  569. let my_block = transform_exprs_to_block block tr false ae.a_expr.epos ae.a_next_id in
  570. let fn = mk (TFunction {
  571. tf_args = [];
  572. tf_type = tr;
  573. tf_expr = my_block.a_expr;
  574. }) ae.a_expr.etype ae.a_expr.epos in
  575. let t_var = alloc_var name ae.a_expr.etype in
  576. let f = add_non_locals_to_func fn in
  577. let fn_assign = mk (TVar (t_var,Some f)) ae.a_expr.etype ae.a_expr.epos in
  578. let ev = mk (TLocal t_var) ae.a_expr.etype ae.a_expr.epos in
  579. let substitute = mk (TCall(ev,[])) ae.a_expr.etype ae.a_expr.epos in
  580. lift_expr ~blocks:[fn_assign] substitute
  581. | (is_value,TFunction(f)) ->
  582. transform_function f ae is_value
  583. | (_,TVar(v,None)) ->
  584. transform_var_expr ae None v
  585. | (false, TVar(v,Some({ eexpr = TUnop((Increment | Decrement as unop),post_fix,({eexpr = TLocal _ | TField({eexpr = TConst TThis},_)} as ve))} as e1))) ->
  586. let one = {e1 with eexpr = TConst (TInt (Int32.of_int 1))} in
  587. let op = if unop = Increment then OpAdd else OpSub in
  588. let inc = {e1 with eexpr = TBinop(op,ve,one)} in
  589. let inc_assign = {e1 with eexpr = TBinop(OpAssign,ve,inc)} in
  590. let var_assign = {e1 with eexpr = TVar(v,Some ve)} in
  591. if post_fix = Postfix then
  592. lift true [var_assign] inc_assign
  593. else
  594. lift true [inc_assign] var_assign
  595. | (_,TVar(v,eo)) ->
  596. transform_var_expr ae eo v
  597. | (_,TFor(v,e1,e2)) ->
  598. let a1 = trans true [] e1 in
  599. let a2 = to_expr (trans false [] e2) in
  600. let name = (ae.a_next_id ()) in
  601. let t_var = alloc_var name e1.etype in
  602. let mk_local v p = { eexpr = TLocal v; etype = v.v_type; epos = p } in
  603. let ev = mk_local t_var e1.epos in
  604. let ehasnext = mk (TField(ev,quick_field e1.etype "hasNext")) (tfun [] (!t_bool) ) e1.epos in
  605. let ehasnext = mk (TCall(ehasnext,[])) ehasnext.etype ehasnext.epos in
  606. let enext = mk (TField(ev,quick_field e1.etype "next")) (tfun [] v.v_type) e1.epos in
  607. let enext = mk (TCall(enext,[])) v.v_type e1.epos in
  608. let var_assign = mk (TVar (v,Some enext)) v.v_type a_expr.epos in
  609. let ebody = Type.concat var_assign (a2) in
  610. let var_decl = mk (TVar (t_var,Some a1.a_expr)) (!t_void) e1.epos in
  611. let twhile = mk (TWhile((mk (TParenthesis ehasnext) ehasnext.etype ehasnext.epos),ebody,NormalWhile)) (!t_void) e1.epos in
  612. let blocks = a1.a_blocks @ [var_decl] in
  613. lift_expr ~blocks: blocks twhile
  614. | (_,TReturn None) ->
  615. ae
  616. | (_,TReturn (Some ({eexpr = TFunction f} as ef))) ->
  617. let n = ae.a_next_id() in
  618. let e1 = to_expr (trans false [] f.tf_expr) in
  619. let f = mk (TFunction {
  620. tf_args = f.tf_args;
  621. tf_type = f.tf_type;
  622. tf_expr = e1;
  623. }) ef.etype ef.epos in
  624. let f1 = add_non_locals_to_func f in
  625. let var_n = alloc_var n ef.etype in
  626. let f1_assign = mk (TVar(var_n,Some f1)) !t_void f1.epos in
  627. let var_local = mk (TLocal var_n) ef.etype f1.epos in
  628. let er = mk (TReturn (Some var_local)) t_dynamic ae.a_expr.epos in
  629. lift true [f1_assign] er
  630. | (_,TReturn Some(x)) ->
  631. let x1 = trans true [] x in
  632. (match x1.a_blocks with
  633. | [] ->
  634. lift true [] { ae.a_expr with eexpr = TReturn(Some x1.a_expr) }
  635. | blocks ->
  636. let f = exprs_to_func (blocks @ [x1.a_expr]) (ae.a_next_id()) ae in
  637. lift true f.a_blocks {a_expr with eexpr = TReturn (Some f.a_expr)})
  638. | (_, TParenthesis(e1)) ->
  639. let e1 = trans true [] e1 in
  640. let p = { ae.a_expr with eexpr = TParenthesis(e1.a_expr)} in
  641. lift true e1.a_blocks p
  642. | (_, TEnumParameter(e1,ef,i)) ->
  643. let e1 = trans true [] e1 in
  644. let p = { ae.a_expr with eexpr = TEnumParameter(e1.a_expr,ef,i)} in
  645. lift true e1.a_blocks p
  646. | (true, TIf(econd, eif, eelse)) ->
  647. (let econd1 = trans true [] econd in
  648. let eif1 = trans true [] eif in
  649. let eelse1 = match eelse with
  650. | Some x -> Some(trans true [] x)
  651. | None -> None
  652. in
  653. let blocks = [] in
  654. let eif2, blocks =
  655. match eif1.a_blocks with
  656. | [] -> eif1.a_expr, blocks
  657. | x ->
  658. let regular =
  659. let fname = eif1.a_next_id () in
  660. let f = exprs_to_func (List.append eif1.a_blocks [eif1.a_expr]) fname ae in
  661. f.a_expr, List.append blocks f.a_blocks
  662. in
  663. match eif1.a_blocks with
  664. | [{ eexpr = TVar(_, Some({ eexpr = TFunction(_)}))} as b] ->
  665. eif1.a_expr, List.append blocks [b]
  666. | _ -> regular
  667. in
  668. let eelse2, blocks =
  669. match eelse1 with
  670. | None -> None, blocks
  671. | Some({ a_blocks = []} as x) -> Some(x.a_expr), blocks
  672. | Some({ a_blocks = b} as eelse1) ->
  673. let regular =
  674. let fname = eelse1.a_next_id () in
  675. let f = exprs_to_func (List.append eelse1.a_blocks [eelse1.a_expr]) fname ae in
  676. Some(f.a_expr), List.append blocks f.a_blocks
  677. in
  678. match b with
  679. | [{ eexpr = TVar(_, Some({ eexpr = TFunction(f)}))} as b] ->
  680. Some(eelse1.a_expr), List.append blocks [b]
  681. | _ -> regular
  682. in
  683. let blocks = List.append econd1.a_blocks blocks in
  684. let new_if = { ae.a_expr with eexpr = TIf(econd1.a_expr, eif2, eelse2) } in
  685. match blocks with
  686. | [] ->
  687. let meta = Meta.Custom(":ternaryIf"), [], ae.a_expr.epos in
  688. let ternary = { ae.a_expr with eexpr = TMeta(meta, new_if) } in
  689. lift_expr ~blocks:blocks ternary
  690. | b ->
  691. let f = exprs_to_func (List.append blocks [new_if]) (ae.a_next_id ()) ae in
  692. lift_expr ~blocks:f.a_blocks f.a_expr)
  693. | (false, TIf(econd, eif, eelse)) ->
  694. let econd = trans true [] econd in
  695. let eif = to_expr (trans false [] eif) in
  696. let eelse = match eelse with
  697. | Some(x) -> Some(to_expr (trans false [] x))
  698. | None -> None
  699. in
  700. let new_if = { ae.a_expr with eexpr = TIf(econd.a_expr, eif, eelse) } in
  701. lift false econd.a_blocks new_if
  702. | (false, TWhile(econd, e1, NormalWhile)) ->
  703. let econd1 = trans true [] econd in
  704. let e11 = to_expr (trans false [] e1) in
  705. let new_while = mk (TWhile(econd1.a_expr,e11,NormalWhile)) a_expr.etype a_expr.epos in
  706. lift false econd1.a_blocks new_while
  707. | (true, TWhile(econd, ebody, NormalWhile)) ->
  708. let econd = trans true [] econd in
  709. let ebody = to_expr (trans false [] ebody) in
  710. let ewhile = { ae.a_expr with eexpr = TWhile(econd.a_expr, ebody, NormalWhile) } in
  711. let eval = { ae.a_expr with eexpr = TConst(TNull) } in
  712. let f = exprs_to_func (List.append econd.a_blocks [ewhile; eval]) (ae.a_next_id ()) ae in
  713. lift true f.a_blocks f.a_expr
  714. | (false, TWhile(econd, ebody, DoWhile)) ->
  715. let not_expr = { econd with eexpr = TUnop(Not, Prefix, econd) } in
  716. let break_expr = mk TBreak !t_void econd.epos in
  717. let if_expr = mk (TIf(not_expr, break_expr, None)) (!t_void) econd.epos in
  718. let new_e = match ebody.eexpr with
  719. | TBlock(exprs) -> { econd with eexpr = TBlock( List.append exprs [if_expr]) }
  720. | _ -> { econd with eexpr = TBlock( List.append [ebody] [if_expr]) }
  721. in
  722. let true_expr = mk (TConst(TBool(true))) econd.etype ae.a_expr.epos in
  723. let new_expr = { ae.a_expr with eexpr = TWhile( true_expr, new_e, NormalWhile) } in
  724. forward_transform new_expr ae
  725. | (is_value, TSwitch(e, cases, edef)) ->
  726. begin match follow e.etype with
  727. | TInst({cl_path = [],"str"},_) ->
  728. transform_string_switch ae is_value e cases edef
  729. | _ ->
  730. transform_switch ae is_value e cases edef
  731. end
  732. (* anon field access on optional params *)
  733. | (is_value, TField(e,FAnon cf)) when Meta.has Meta.Optional cf.cf_meta ->
  734. let e = dynamic_field_read e cf.cf_name ae.a_expr.etype in
  735. transform_expr ~is_value:is_value e
  736. | (is_value, TBinop(OpAssign,{eexpr = TField(e1,FAnon cf)},e2)) when Meta.has Meta.Optional cf.cf_meta ->
  737. let e = dynamic_field_write e1 cf.cf_name e2 in
  738. transform_expr ~is_value:is_value e
  739. | (is_value, TBinop(OpAssignOp op,{eexpr = TField(e1,FAnon cf); etype = t},e2)) when Meta.has Meta.Optional cf.cf_meta ->
  740. let e = dynamic_field_read_write ae.a_next_id e1 cf.cf_name op e2 t in
  741. transform_expr ~is_value:is_value e
  742. (* TODO we need to deal with Increment, Decrement too!
  743. | (_, TUnop( (Increment | Decrement) as unop, op,{eexpr = TField(e1,FAnon cf)})) when Meta.has Meta.Optional cf.cf_meta ->
  744. let = dynamic_field_read e cf.cf_name in
  745. let e = dynamic_field_read_write_unop ae.a_next_id e1 cf.cf_name unop op in
  746. Printf.printf "dyn read write\n";
  747. transform_expr e
  748. *)
  749. (*
  750. anon field access with non optional members like iterator, length, split must be handled too, we need to Reflect on them too when it's a runtime method
  751. *)
  752. | (is_value, TUnop( (Increment | Decrement) as unop, op, e)) ->
  753. let one = { ae.a_expr with eexpr = TConst(TInt(Int32.of_int(1)))} in
  754. let is_postfix = match op with
  755. | Postfix -> true
  756. | Prefix -> false in
  757. let op = match unop with
  758. | Increment -> OpAdd
  759. | Decrement -> OpSub
  760. | _ -> assert false in
  761. transform_op_assign_op ae e op one is_value is_postfix
  762. | (_, TUnop(op, Prefix, e)) ->
  763. let e1 = trans true [] e in
  764. let r = { a_expr with eexpr = TUnop(op, Prefix, e1.a_expr) } in
  765. lift_expr ~blocks:e1.a_blocks r
  766. | (is_value, TField(e,FDynamic s)) ->
  767. let e = dynamic_field_read e s ae.a_expr.etype in
  768. transform_expr ~is_value:is_value e
  769. | (is_value, TBinop(OpAssign,{eexpr = TField(e1,FDynamic s)},e2)) ->
  770. let e = dynamic_field_write e1 s e2 in
  771. transform_expr ~is_value:is_value e
  772. | (is_value, TBinop(OpAssignOp op,{eexpr = TField(e1,FDynamic s); etype = t},e2)) ->
  773. let e = dynamic_field_read_write ae.a_next_id e1 s op e2 t in
  774. transform_expr ~is_value:is_value e
  775. | (is_value, TField(e1, FClosure(Some ({cl_path = [],("str" | "list")},_),cf))) ->
  776. let e = dynamic_field_read e1 cf.cf_name ae.a_expr.etype in
  777. transform_expr ~is_value:is_value e
  778. | (is_value, TBinop(OpAssign, left, right))->
  779. (let left = trans true [] left in
  780. let right = trans true [] right in
  781. let r = { a_expr with eexpr = TBinop(OpAssign, left.a_expr, right.a_expr)} in
  782. if is_value then
  783. (let blocks = List.concat [left.a_blocks; right.a_blocks; [r]] in
  784. let f = exprs_to_func blocks (ae.a_next_id ()) ae in
  785. lift true f.a_blocks f.a_expr)
  786. else
  787. lift false (List.append left.a_blocks right.a_blocks) r)
  788. | (is_value, TBinop(OpAssignOp(x), left, right)) ->
  789. let right = trans true [] right in
  790. let v = right.a_expr in
  791. let res = transform_op_assign_op ae left x v is_value false in
  792. lift true (List.append right.a_blocks res.a_blocks) res.a_expr
  793. | (_, TBinop(op, left, right))->
  794. (let left = trans true [] left in
  795. let right = trans true [] right in
  796. let r = { a_expr with eexpr = TBinop(op, left.a_expr, right.a_expr)} in
  797. lift false (List.append left.a_blocks right.a_blocks) r)
  798. | (true, TThrow(x)) ->
  799. let block = TBlock([a_expr; { a_expr with eexpr = TConst(TNull) }]) in
  800. let r = { a_expr with eexpr = block } in
  801. forward_transform r ae
  802. | (false, TThrow(x)) ->
  803. let x = trans true [] x in
  804. let r = { a_expr with eexpr = TThrow(x.a_expr)} in
  805. lift false x.a_blocks r
  806. | (_, TNew(c, tp, params)) ->
  807. let params = List.map (trans true []) params in
  808. let blocks = List.flatten (List.map (fun (p) -> p.a_blocks) params) in
  809. let params = List.map (fun (p) -> p.a_expr) params in
  810. let e = { a_expr with eexpr = TNew(c, tp, params) } in
  811. lift false blocks e
  812. | (is_value, TCall(e,params)) ->
  813. transform_call is_value e params ae
  814. | (_, TArray(e1, e2)) ->
  815. let e1 = trans true [] e1 in
  816. let e2 = trans true [] e2 in
  817. let r = { a_expr with eexpr = TArray(e1.a_expr, e2.a_expr)} in
  818. let blocks = List.append e1.a_blocks e2.a_blocks in
  819. lift_expr ~blocks:blocks r
  820. | (false, TTry(etry, catches)) ->
  821. let etry = trans false [] etry in
  822. let catches = List.map (fun(v,e) -> v, trans false [] e) catches in
  823. let blocks = List.flatten (List.map (fun (_,e) -> e.a_blocks) catches) in
  824. let catches = List.map (fun(v,e) -> v, e.a_expr) catches in
  825. let r = { a_expr with eexpr = TTry(etry.a_expr, catches)} in
  826. let blocks = List.append etry.a_blocks blocks in
  827. lift false blocks r
  828. | (true, TTry(etry, catches)) ->
  829. let id = ae.a_next_id () in
  830. let temp_var = to_tvar id a_expr.etype in
  831. let temp_var_def = { a_expr with eexpr = TVar(temp_var, None) } in
  832. let temp_local = { a_expr with eexpr = TLocal(temp_var)} in
  833. let mk_temp_assign right = { a_expr with eexpr = TBinop(OpAssign, temp_local, right)} in
  834. let etry = mk_temp_assign etry in
  835. let catches = List.map (fun (v,e)-> v, mk_temp_assign e) catches in
  836. let new_try = { a_expr with eexpr = TTry(etry, catches)} in
  837. let block = [temp_var_def; new_try; temp_local] in
  838. let new_block = { a_expr with eexpr = TBlock(block)} in
  839. forward_transform new_block ae
  840. | (_, TObjectDecl(fields)) ->
  841. let fields = List.map (fun (name,ex) -> name, trans true [] ex) fields in
  842. let blocks = List.flatten (List.map (fun (_,ex) -> ex.a_blocks) fields) in
  843. let fields = List.map (fun (name,ex) -> name, ex.a_expr) fields in
  844. let r = { a_expr with eexpr = (TObjectDecl(fields) )} in
  845. lift_expr ~blocks r
  846. | (_, TArrayDecl(values)) ->
  847. let values = List.map (trans true []) values in
  848. let blocks = List.flatten (List.map (fun (v) -> v.a_blocks) values) in
  849. let exprs = List.map (fun (v) -> v.a_expr) values in
  850. let r = { a_expr with eexpr = TArrayDecl exprs } in
  851. lift_expr ~blocks:blocks r
  852. | (is_value, TCast(e1,Some mt)) ->
  853. let e = Codegen.default_cast ~vtmp:(ae.a_next_id()) (match !como with Some com -> com | None -> assert false) e1 mt ae.a_expr.etype ae.a_expr.epos in
  854. transform_expr ~is_value:is_value e
  855. | (is_value, TCast(e,None)) ->
  856. let e = trans is_value [] e in
  857. let r = { a_expr with eexpr = TCast(e.a_expr, None)} in
  858. lift_expr ~blocks:e.a_blocks r
  859. | (_, TField(e,f)) ->
  860. let e = trans true [] e in
  861. let r = { a_expr with eexpr = TField(e.a_expr, f) } in
  862. lift_expr ~blocks:e.a_blocks r
  863. | (is_value, TMeta(m, e)) ->
  864. let e = trans is_value [] e in
  865. let r = { a_expr with eexpr = TMeta(m, e.a_expr); etype = e.a_expr.etype } in
  866. lift_expr ~blocks:e.a_blocks r
  867. | ( _, TLocal _ ) -> lift_expr a_expr
  868. | ( _, TConst _ ) -> lift_expr a_expr
  869. | ( _, TTypeExpr _ ) -> lift_expr a_expr
  870. | ( _, TUnop _ ) -> assert false
  871. | ( true, TWhile(econd, ebody, DoWhile) ) ->
  872. let new_expr = trans false [] a_expr in
  873. let f = exprs_to_func (new_expr.a_blocks @ [new_expr.a_expr]) (ae.a_next_id()) ae in
  874. lift_expr ~is_value:true ~blocks:f.a_blocks f.a_expr
  875. | ( _, TBreak ) | ( _, TContinue ) ->
  876. lift_expr a_expr
  877. and transform e =
  878. to_expr (transform1 (lift_expr e))
  879. and forward_transform e base =
  880. transform1 (lift_expr1 base.a_is_value base.a_next_id base.a_blocks e)
  881. let transform_to_value e =
  882. to_expr (transform1 (lift_expr e ~is_value:true))
  883. end
  884. module Printer = struct
  885. type print_context = {
  886. pc_indent : string;
  887. pc_next_anon_func : unit -> string;
  888. pc_debug : bool;
  889. pc_com : Common.context;
  890. }
  891. let has_feature pctx = Common.has_feature pctx.pc_com
  892. let add_feature pctx = Common.add_feature pctx.pc_com
  893. let create_context =
  894. let n = ref (-1) in
  895. (fun indent com debug -> {
  896. pc_indent = indent;
  897. pc_next_anon_func = (fun () -> incr n; Printf.sprintf "anon_%i" !n);
  898. pc_debug = debug;
  899. pc_com = com;
  900. }
  901. )
  902. let tabs = ref ""
  903. let opt o f s = match o with
  904. | None -> ""
  905. | Some v -> s ^ (f v)
  906. (* TODO: both of these are crazy *)
  907. let is_type p t =
  908. (fun r ->
  909. let x = t_infos r in
  910. (String.concat "." (fst x.mt_path)) = p && (snd x.mt_path) = t
  911. )
  912. let is_type1 p s =
  913. (fun t -> match follow t with
  914. | TInst(c,_) -> (is_type p s)(TClassDecl c)
  915. | TAbstract(a,_) -> (is_type p s)(TAbstractDecl a)
  916. | TEnum(en,_) -> (is_type p s)(TEnumDecl en)
  917. | _ -> false
  918. )
  919. let is_underlying_string t = match follow t with
  920. | TAbstract(a,tl) -> (is_type1 "" "str")(Abstract.get_underlying_type a tl)
  921. | _ -> false
  922. let is_underlying_array t = match follow t with
  923. | TAbstract(a,tl) -> (is_type1 "" "list")(Abstract.get_underlying_type a tl)
  924. | _ -> false
  925. let rec is_anon_or_dynamic t = match follow t with
  926. | TAbstract(a,tl) ->
  927. is_anon_or_dynamic (Abstract.get_underlying_type a tl)
  928. | TAnon _ | TDynamic _ -> true
  929. | _ -> false
  930. let handle_keywords s =
  931. KeywordHandler.handle_keywords s
  932. let print_unop = function
  933. | Increment | Decrement -> assert false
  934. | Not -> "not "
  935. | Neg -> "-";
  936. | NegBits -> "~"
  937. let print_binop = function
  938. | OpAdd -> "+"
  939. | OpSub -> "-"
  940. | OpMult -> "*"
  941. | OpDiv -> "/"
  942. | OpAssign -> "="
  943. | OpEq -> "=="
  944. | OpNotEq -> "!="
  945. | OpGt -> ">"
  946. | OpGte -> ">="
  947. | OpLt -> "<"
  948. | OpLte -> "<="
  949. | OpAnd -> "&"
  950. | OpOr -> "|"
  951. | OpXor -> "^"
  952. | OpBoolAnd -> "and"
  953. | OpBoolOr -> "or"
  954. | OpShl -> "<<"
  955. | OpShr -> ">>"
  956. | OpUShr -> ">>"
  957. | OpMod -> "%"
  958. | OpInterval | OpArrow | OpAssignOp _ -> assert false
  959. let print_string s =
  960. Printf.sprintf "\"%s\"" (Ast.s_escape s)
  961. let print_constant = function
  962. | TThis -> "self"
  963. | TNull -> "None"
  964. | TBool(true) -> "True"
  965. | TBool(false) -> "False"
  966. | TString(s) -> print_string s
  967. | TInt(i) -> Int32.to_string i
  968. | TFloat s -> s
  969. | TSuper -> "super"
  970. let print_base_type tp =
  971. try
  972. begin match Meta.get Meta.Native tp.mt_meta with
  973. | _,[EConst(String s),_],_ -> s
  974. | _ -> raise Not_found
  975. end
  976. with Not_found ->
  977. let pack,name = tp.mt_path in
  978. (String.concat "_" pack) ^ (if pack = [] then name else "_" ^ name)
  979. let print_module_type mt = print_base_type (t_infos mt)
  980. let print_metadata (name,_,_) =
  981. Printf.sprintf "@%s" name
  982. let rec remove_outer_parens e = match e.eexpr with
  983. | TParenthesis(e) -> remove_outer_parens e
  984. | TMeta((Meta.Custom ":ternaryIf",_,_),_) -> e
  985. | TMeta(_,e) -> remove_outer_parens e
  986. | _ -> e
  987. let print_args args p =
  988. let had_value = ref false in
  989. let had_var_args = ref false in
  990. let had_kw_args = ref false in
  991. let sl = List.map (fun (v,cto) ->
  992. let check_err () = if !had_var_args || !had_kw_args then error "Arguments after KwArgs/VarArgs are not allowed" p in
  993. KeywordHandler.check_var_declaration v;
  994. let name = handle_keywords v.v_name in
  995. match follow v.v_type with
  996. | TAbstract({a_path = ["python"],"KwArgs"},_) ->
  997. if !had_kw_args then error "Arguments after KwArgs are not allowed" p;
  998. had_kw_args := true;
  999. "**" ^ name
  1000. | TAbstract({a_path = ["python"],"VarArgs"},_) ->
  1001. check_err ();
  1002. had_var_args := true;
  1003. "*" ^ name
  1004. | _ ->
  1005. check_err ();
  1006. name ^ match cto with
  1007. | None when !had_value -> " = None"
  1008. | None -> ""
  1009. | Some ct ->
  1010. had_value := true;
  1011. Printf.sprintf " = %s" (print_constant ct)
  1012. ) args in
  1013. String.concat "," sl
  1014. let rec print_op_assign_right pctx e =
  1015. match e.eexpr with
  1016. | TIf({eexpr = TParenthesis econd},eif,Some eelse)
  1017. | TIf(econd,eif,Some eelse) ->
  1018. Printf.sprintf "%s if %s else %s" (print_expr pctx eif) (print_expr pctx econd) (print_expr pctx eelse)
  1019. | _ ->
  1020. print_expr pctx (remove_outer_parens e)
  1021. and print_var pctx v eo =
  1022. match eo with
  1023. | Some ({eexpr = TFunction tf} as e) ->
  1024. print_function pctx tf (Some v.v_name) e.epos
  1025. | _ ->
  1026. let s_init = match eo with
  1027. | None -> "None"
  1028. | Some e -> print_op_assign_right pctx e
  1029. in
  1030. Printf.sprintf "%s = %s" (handle_keywords v.v_name) s_init
  1031. and print_function pctx tf name p =
  1032. let s_name = match name with
  1033. | None -> pctx.pc_next_anon_func()
  1034. | Some s -> handle_keywords s
  1035. in
  1036. let s_args = print_args tf.tf_args p in
  1037. let s_expr = print_expr {pctx with pc_indent = " " ^ pctx.pc_indent} tf.tf_expr in
  1038. Printf.sprintf "def %s(%s):\n%s %s" s_name s_args pctx.pc_indent s_expr
  1039. and print_tarray_list pctx e1 e2 =
  1040. let s1 = (print_expr pctx e1) in
  1041. let s2 = (print_expr pctx e2) in
  1042. let default = Printf.sprintf "python_internal_ArrayImpl._get(%s, %s)" s1 s2 in
  1043. let handle_index =
  1044. match e2.eexpr with
  1045. | TConst TInt index ->
  1046. if Int32.to_int index >= 0 then
  1047. Printf.sprintf "(%s[%s] if %s < len(%s) else None)" s1 s2 s2 s1
  1048. else
  1049. "None"
  1050. | TLocal _ ->
  1051. Printf.sprintf "(%s[%s] if %s >= 0 and %s < len(%s) else None)" s1 s2 s2 s2 s1
  1052. | _ ->
  1053. default
  1054. in
  1055. match e1.eexpr with
  1056. | TLocal _ -> handle_index
  1057. | TField ({eexpr=(TConst TThis | TLocal _)},_) -> handle_index
  1058. | _ -> default
  1059. and is_safe_string pctx x =
  1060. let follow_parens e = match e.eexpr with
  1061. | TParenthesis e -> e
  1062. | _ -> e
  1063. in
  1064. match (follow_parens x).eexpr with
  1065. | TBinop(OpAdd, e1, e2) -> is_safe_string pctx e1 && is_safe_string pctx e2
  1066. | TCall (e1,_) ->
  1067. let id = print_expr pctx (follow_parens e1) in
  1068. (match id with
  1069. | "Std.string" -> true
  1070. | _ -> false)
  1071. | TConst (TString s) -> true
  1072. | _ -> false
  1073. and print_expr pctx e =
  1074. let indent = pctx.pc_indent in
  1075. let print_expr_indented e = print_expr {pctx with pc_indent = " " ^ pctx.pc_indent} e in
  1076. match e.eexpr with
  1077. | TConst ct ->
  1078. print_constant ct
  1079. | TTypeExpr mt ->
  1080. print_module_type mt
  1081. | (TLocal v | TParenthesis({ eexpr = (TLocal v) })) ->
  1082. handle_keywords v.v_name
  1083. | TEnumParameter(e1,_,index) ->
  1084. Printf.sprintf "%s.params[%i]" (print_expr pctx e1) index
  1085. | TArray(e1,e2) when (is_type1 "" "list")(e1.etype) || is_underlying_array e1.etype ->
  1086. print_tarray_list pctx e1 e2
  1087. | TArray({etype = t} as e1,e2) when is_anon_or_dynamic t ->
  1088. Printf.sprintf "HxOverrides.arrayGet(%s, %s)" (print_expr pctx e1) (print_expr pctx e2)
  1089. | TArray(e1,e2) ->
  1090. Printf.sprintf "%s[%s]" (print_expr pctx e1) (print_expr pctx e2)
  1091. | TBinop(OpAssign, {eexpr = TArray(e1,e2)}, e3) when (is_type1 "" "list")(e1.etype) || is_underlying_array e1.etype ->
  1092. Printf.sprintf "python_internal_ArrayImpl._set(%s, %s, %s)" (print_expr pctx e1) (print_expr pctx e2) (print_expr pctx e3)
  1093. | TBinop(OpAssign,{eexpr = TArray({etype = t} as e1,e2)},e3) when is_anon_or_dynamic t ->
  1094. Printf.sprintf "HxOverrides.arraySet(%s,%s,%s)" (print_expr pctx e1) (print_expr pctx e2) (print_expr pctx e3)
  1095. | TBinop(OpAssign,{eexpr = TArray(e1,e2)},e3) ->
  1096. Printf.sprintf "%s[%s] = %s" (print_expr pctx e1) (print_expr pctx e2) (print_expr pctx (remove_outer_parens e3) )
  1097. | TBinop(OpAssign,{eexpr = TField(ef1,fa)},e2) ->
  1098. Printf.sprintf "%s = %s" (print_field pctx ef1 fa true) (print_op_assign_right pctx e2)
  1099. | TBinop(OpAssign,e1,e2) ->
  1100. Printf.sprintf "%s = %s" (print_expr pctx e1) (print_expr pctx (remove_outer_parens e2))
  1101. | TBinop(op,e1,({eexpr = TBinop(_,_,_)} as e2)) ->
  1102. print_expr pctx { e with eexpr = TBinop(op, e1, { e2 with eexpr = TParenthesis(e2) })}
  1103. | TBinop(OpEq,{eexpr = TCall({eexpr = TLocal {v_name = "__typeof__"}},[e1])},e2) ->
  1104. begin match e2.eexpr with
  1105. | TConst(TString s) ->
  1106. begin match s with
  1107. | "string" -> Printf.sprintf "Std._hx_is(%s, str)" (print_expr pctx e1)
  1108. | "boolean" -> Printf.sprintf "Std._hx_is(%s, bool)" (print_expr pctx e1)
  1109. | "number" -> Printf.sprintf "Std._hx_is(%s, float)" (print_expr pctx e1)
  1110. | _ -> assert false
  1111. end
  1112. | _ ->
  1113. assert false
  1114. end
  1115. | TBinop(OpEq,e1,({eexpr = TConst TNull} as e2)) ->
  1116. Printf.sprintf "(%s is %s)" (print_expr pctx e1) (print_expr pctx e2)
  1117. | TBinop(OpNotEq,e1,({eexpr = TConst TNull} as e2)) ->
  1118. Printf.sprintf "(%s is not %s)" (print_expr pctx e1) (print_expr pctx e2)
  1119. | TBinop(OpEq|OpNotEq as op,e1, e2) ->
  1120. let ops = match op with
  1121. | OpEq -> "is", "==", "HxOverrides.eq"
  1122. | OpNotEq -> "is not", "!=", "not HxOverrides.eq"
  1123. | _ -> assert false
  1124. in
  1125. let third (_,_,x) = x in
  1126. let fst (x,_,_) = x in
  1127. let snd (_,x,_) = x in
  1128. let is_list_or_anon x = begin match x with
  1129. | TInst({cl_path = [],("list")},_) -> true
  1130. | TAnon _ -> true
  1131. | _ -> false
  1132. end in
  1133. let is_const_byte x =
  1134. match x.eexpr with
  1135. | TConst TInt x ->
  1136. let x = Int32.to_int x in
  1137. x >= 0 && x <= 256
  1138. | _ -> false
  1139. in
  1140. (match follow e1.etype, follow e2.etype with
  1141. | TAbstract({a_path = [],("Int")}, _),TAbstract({a_path = [],("Int")}, _) when is_const_byte e2 || is_const_byte e1 ->
  1142. Printf.sprintf "(%s %s %s)" (print_expr pctx e1) (snd ops) (print_expr pctx e2)
  1143. (* the following optimization causes a problem with polygonal unit tests
  1144. see: https://github.com/HaxeFoundation/haxe/issues/2952
  1145. *)
  1146. (* Printf.sprintf "(%s %s %s)" (print_expr pctx e1) (fst ops) (print_expr pctx e2) *)
  1147. | TInst({cl_path = [],("list")},_), _ ->
  1148. Printf.sprintf "(%s %s %s)" (print_expr pctx e1) (fst ops) (print_expr pctx e2)
  1149. | x, _ when is_underlying_array x ->
  1150. Printf.sprintf "(%s %s %s)" (print_expr pctx e1) (fst ops) (print_expr pctx e2)
  1151. | TDynamic _, TDynamic _ ->
  1152. Printf.sprintf "%s(%s,%s)" (third ops) (print_expr pctx e1) (print_expr pctx e2)
  1153. | TDynamic _, x | x, TDynamic _ when is_list_or_anon x ->
  1154. Printf.sprintf "%s(%s,%s)" (third ops) (print_expr pctx e1) (print_expr pctx e2)
  1155. | _,_ -> Printf.sprintf "(%s %s %s)" (print_expr pctx e1) (snd ops) (print_expr pctx e2))
  1156. | TBinop(OpMod,e1,e2) when (is_type1 "" "Int")(e1.etype) && (is_type1 "" "Int")(e2.etype) ->
  1157. (match e1.eexpr with
  1158. | TConst(TInt(x)) when (Int32.to_int x) >= 0 ->
  1159. (* constant optimization *)
  1160. Printf.sprintf "%s %% %s" (print_expr pctx e1) (print_expr pctx e2)
  1161. | _ ->
  1162. Printf.sprintf "HxOverrides.mod(%s, %s)" (print_expr pctx e1) (print_expr pctx e2))
  1163. | TBinop(OpMod,e1,e2) ->
  1164. Printf.sprintf "HxOverrides.modf(%s, %s)" (print_expr pctx e1) (print_expr pctx e2)
  1165. | TBinop(OpUShr,e1,e2) ->
  1166. Printf.sprintf "HxOverrides.rshift(%s, %s)" (print_expr pctx e1) (print_expr pctx e2)
  1167. | TBinop(OpAdd,e1,e2) when (is_type1 "" "str")(e.etype) || is_underlying_string e.etype ->
  1168. let rec safe_string ex =
  1169. match ex.eexpr, ex.etype with
  1170. | e, _ when is_safe_string pctx ex -> print_expr pctx ex
  1171. | TBinop(OpAdd, e1, e2), x when (is_type1 "" "str")(x) -> Printf.sprintf "(%s + %s)" (safe_string e1) (safe_string e2)
  1172. | (TLocal(_)),x when (is_type1 "" "str")(x) ->
  1173. (*
  1174. we could add this pattern too, but is it sideeffect free??
  1175. | TField({ eexpr = TLocal(_)},_)
  1176. *)
  1177. let s = (print_expr pctx ex) in
  1178. Printf.sprintf "(\"null\" if %s is None else %s)" s s
  1179. | _,x when (is_type1 "" "str")(x) -> Printf.sprintf "HxOverrides.stringOrNull(%s)" (print_expr pctx ex)
  1180. | _,_ ->
  1181. if has_feature pctx "Std.string" then
  1182. Printf.sprintf "Std.string(%s)" (print_expr pctx ex)
  1183. else
  1184. Printf.sprintf "str(%s)" (print_expr pctx ex)
  1185. in
  1186. let e1_str = safe_string e1 in
  1187. let e2_str = safe_string e2 in
  1188. Printf.sprintf "(%s + %s)" e1_str e2_str
  1189. | TBinop(OpAdd,e1,e2) when (match follow e.etype with TDynamic _ -> true | _ -> false) ->
  1190. Printf.sprintf "python_Boot._add_dynamic(%s,%s)" (print_expr pctx e1) (print_expr pctx e2)
  1191. | TBinop(op,e1,e2) ->
  1192. Printf.sprintf "(%s %s %s)" (print_expr pctx e1) (print_binop op) (print_expr pctx e2)
  1193. | TField(e1,fa) ->
  1194. print_field pctx e1 fa false
  1195. | TParenthesis e1 ->
  1196. Printf.sprintf "(%s)" (print_expr pctx e1)
  1197. | TObjectDecl fl ->
  1198. let fl2 = ref fl in
  1199. begin match follow e.etype with
  1200. | TAnon an ->
  1201. PMap.iter (fun s cf ->
  1202. if not (List.mem_assoc s fl) then fl2 := (s,null cf.cf_type cf.cf_pos) :: !fl2
  1203. ) an.a_fields
  1204. | _ ->
  1205. ()
  1206. end;
  1207. Printf.sprintf "_hx_AnonObject(%s)" (print_exprs_named pctx ", " !fl2)
  1208. | TArrayDecl el ->
  1209. Printf.sprintf "[%s]" (print_exprs pctx ", " el)
  1210. | TCall(e1,el) ->
  1211. print_call pctx e1 el e
  1212. | TNew(c,_,el) ->
  1213. let id = print_base_type (t_infos (TClassDecl c)) in
  1214. Printf.sprintf "%s(%s)" id (print_exprs pctx ", " el)
  1215. | TUnop(Not,Prefix,e1) ->
  1216. Printf.sprintf "(%s%s)" (print_unop Not) (print_expr pctx e1)
  1217. | TUnop(op,Prefix,e1) ->
  1218. Printf.sprintf "%s%s" (print_unop op) (print_expr pctx e1)
  1219. | TFunction tf ->
  1220. print_function pctx tf None e.epos
  1221. | TVar (v,eo) ->
  1222. KeywordHandler.check_var_declaration v;
  1223. print_var pctx v eo
  1224. | TBlock [] ->
  1225. Printf.sprintf "pass"
  1226. | TBlock [{ eexpr = TBlock _} as b] ->
  1227. print_expr pctx b
  1228. | TBlock el ->
  1229. let old = !tabs in
  1230. tabs := pctx.pc_indent;
  1231. let s = print_block_exprs pctx ("\n" ^ !tabs) pctx.pc_debug el in
  1232. tabs := old;
  1233. Printf.sprintf "%s" s
  1234. | TIf(econd,eif,(Some {eexpr = TIf _} as eelse)) ->
  1235. print_if_else pctx econd eif eelse true
  1236. | TIf(econd,eif,eelse) ->
  1237. print_if_else pctx econd eif eelse false
  1238. | TWhile(econd,e1,NormalWhile) ->
  1239. Printf.sprintf "while %s:\n%s %s" (print_expr pctx (remove_outer_parens econd)) indent (print_expr_indented e1)
  1240. | TWhile(econd,e1,DoWhile) ->
  1241. error "Currently not supported" e.epos
  1242. | TTry(e1,catches) ->
  1243. print_try pctx e1 catches
  1244. | TReturn eo ->
  1245. Printf.sprintf "return%s" (opt eo (print_op_assign_right pctx) " ")
  1246. | TBreak ->
  1247. "break"
  1248. | TContinue ->
  1249. "continue"
  1250. | TThrow e1 ->
  1251. let rec is_native_exception t =
  1252. match Abstract.follow_with_abstracts t with
  1253. | TInst ({ cl_path = [],"BaseException" }, _) ->
  1254. true
  1255. | TInst ({ cl_super = Some csup }, _) ->
  1256. is_native_exception (TInst(fst csup, snd csup))
  1257. | _ ->
  1258. false
  1259. in
  1260. if is_native_exception e1.etype then
  1261. Printf.sprintf "raise %s" (print_expr pctx e1)
  1262. else
  1263. Printf.sprintf "raise _HxException(%s)" (print_expr pctx e1)
  1264. | TCast(e1,None) ->
  1265. print_expr pctx e1
  1266. | TMeta((Meta.Custom ":ternaryIf",_,_),{eexpr = TIf(econd,eif,Some eelse)}) ->
  1267. Printf.sprintf "(%s if %s else %s)" (print_expr pctx eif) (print_expr pctx econd) (print_expr pctx eelse)
  1268. | TMeta(_,e1) ->
  1269. print_expr pctx e1
  1270. | TSwitch _ | TCast(_, Some _) | TFor _ | TUnop(_,Postfix,_) ->
  1271. assert false
  1272. and print_if_else pctx econd eif eelse as_elif =
  1273. let econd1 = match econd.eexpr with
  1274. | TParenthesis e -> e
  1275. | _ -> econd
  1276. in
  1277. let if_str = print_expr {pctx with pc_indent = " " ^ pctx.pc_indent} eif in
  1278. let indent = pctx.pc_indent in
  1279. let else_str = if as_elif then
  1280. opt eelse (print_expr pctx) "el"
  1281. else
  1282. opt eelse (print_expr {pctx with pc_indent = " " ^ pctx.pc_indent}) (Printf.sprintf "else:\n%s " indent)
  1283. in
  1284. let else_str = if else_str = "" then "" else "\n" ^ indent ^ else_str in
  1285. Printf.sprintf "if %s:\n%s %s%s" (print_expr pctx (remove_outer_parens econd1)) indent if_str else_str
  1286. and print_field pctx e1 fa is_assign =
  1287. let obj = match e1.eexpr with
  1288. | TConst TSuper -> "super()"
  1289. | _ -> print_expr pctx e1
  1290. in
  1291. let name = field_name fa in
  1292. let is_extern = (match fa with
  1293. | FInstance(c,_,_) -> c.cl_extern
  1294. | FStatic(c,_) -> c.cl_extern
  1295. | _ -> false)
  1296. in
  1297. let do_default () =
  1298. Printf.sprintf "%s.%s" obj (if is_extern then name else (handle_keywords name))
  1299. in
  1300. let call_override s =
  1301. match s with
  1302. | "iterator" | "toUpperCase" | "toLowerCase" | "pop" | "shift" | "join" | "push" | "map" | "filter" -> true
  1303. | _ -> false
  1304. in
  1305. match fa with
  1306. (* we need to get rid of these cases in the transformer, how is this handled in js *)
  1307. | FInstance(c,_,{cf_name = "length"}) when (is_type "" "list")(TClassDecl c) ->
  1308. Printf.sprintf "len(%s)" (print_expr pctx e1)
  1309. | FInstance(c,_,{cf_name = "length"}) when (is_type "" "str")(TClassDecl c) ->
  1310. Printf.sprintf "len(%s)" (print_expr pctx e1)
  1311. | FStatic(c,{cf_name = "fromCharCode"}) when (is_type "" "str")(TClassDecl c) ->
  1312. Printf.sprintf "HxString.fromCharCode"
  1313. | FStatic({cl_path = ["python";"internal"],"UBuiltins"},{cf_name = s}) ->
  1314. s
  1315. | FInstance _ | FStatic _ ->
  1316. do_default ()
  1317. | FAnon cf when is_assign && call_override(name) ->
  1318. begin match follow cf.cf_type with
  1319. | TFun([],_) ->
  1320. Printf.sprintf "python_lib_FuncTools.partial(HxOverrides.%s, %s)" name obj
  1321. | _ ->
  1322. do_default()
  1323. end
  1324. | _ ->
  1325. do_default()
  1326. and print_try pctx e1 catches =
  1327. let has_catch_all = List.exists (fun (v,_) -> match v.v_type with
  1328. | TDynamic _ -> true
  1329. | _ -> false
  1330. ) catches in
  1331. let has_only_catch_all = has_catch_all && begin match catches with
  1332. | [_] -> true
  1333. | _ -> false
  1334. end in
  1335. let print_catch pctx i (v,e) =
  1336. KeywordHandler.check_var_declaration v;
  1337. let is_empty_expr = begin match e.eexpr with
  1338. | TBlock [] -> true
  1339. | _ -> false
  1340. end in
  1341. let indent = pctx.pc_indent in
  1342. (* Don't generate assignment to catch variable when catch expression is an empty block *)
  1343. let assign = if is_empty_expr then "" else Printf.sprintf "%s = _hx_e1\n%s" v.v_name indent in
  1344. let handle_base_type bt =
  1345. let t = print_base_type bt in
  1346. let print_type_check t_str =
  1347. Printf.sprintf "if isinstance(_hx_e1, %s):\n%s %s %s" t_str indent assign (print_expr {pctx with pc_indent = " " ^ pctx.pc_indent} e)
  1348. in
  1349. let res = match t with
  1350. | "str" -> print_type_check "str"
  1351. | "Bool" -> print_type_check "bool"
  1352. | "Int" -> print_type_check "int"
  1353. | "Float" -> print_type_check "float"
  1354. | t -> print_type_check t
  1355. in
  1356. if i > 0 then
  1357. indent ^ "el" ^ res
  1358. else
  1359. res
  1360. in
  1361. match follow v.v_type with
  1362. | TDynamic _ ->
  1363. begin if has_only_catch_all then
  1364. Printf.sprintf "%s%s" assign (print_expr pctx e)
  1365. else
  1366. (* Dynamic is always the last block *)
  1367. Printf.sprintf "%selse:\n %s%s %s" indent indent assign (print_expr {pctx with pc_indent = " " ^ pctx.pc_indent} e)
  1368. end
  1369. | TInst(c,_) ->
  1370. handle_base_type (t_infos (TClassDecl c))
  1371. | TEnum(en,_) ->
  1372. handle_base_type (t_infos (TEnumDecl en))
  1373. | TAbstract(a,_) ->
  1374. handle_base_type (t_infos (TAbstractDecl a))
  1375. | _ ->
  1376. assert false
  1377. in
  1378. let indent = pctx.pc_indent in
  1379. let print_expr_indented e = print_expr {pctx with pc_indent = " " ^ pctx.pc_indent} e in
  1380. let try_str = Printf.sprintf "try:\n%s %s\n%s" indent (print_expr_indented e1) indent in
  1381. let except = if has_feature pctx "has_throw" then
  1382. Printf.sprintf "except Exception as _hx_e:\n%s _hx_e1 = _hx_e.val if isinstance(_hx_e, _HxException) else _hx_e\n%s " indent indent
  1383. else
  1384. Printf.sprintf "except Exception as _hx_e:\n%s _hx_e1 = _hx_e\n%s " indent indent
  1385. in
  1386. let catch_str = String.concat (Printf.sprintf "\n") (ExtList.List.mapi (fun i catch -> print_catch {pctx with pc_indent = " " ^ pctx.pc_indent} i catch) catches) in
  1387. let except_end = if not has_catch_all then Printf.sprintf "\n%s else:\n%s raise _hx_e" indent indent else "" in
  1388. Printf.sprintf "%s%s%s%s" try_str except catch_str except_end
  1389. and print_call2 pctx e1 el =
  1390. let id = print_expr pctx e1 in
  1391. match id,el with
  1392. | "__define_feature__",[_;e] ->
  1393. print_expr pctx e
  1394. | "super",_ ->
  1395. let s_el = (print_call_args pctx e1 el) in
  1396. Printf.sprintf "super().__init__(%s)" s_el
  1397. | ("python_Syntax._pythonCode"),[({ eexpr = TConst (TString code) } as ecode); {eexpr = TArrayDecl tl}] ->
  1398. let exprs = Array.of_list tl in
  1399. let i = ref 0 in
  1400. let err msg =
  1401. let pos = { ecode.epos with pmin = ecode.epos.pmin + !i } in
  1402. error msg pos
  1403. in
  1404. let regex = Str.regexp "[{}]" in
  1405. let rec loop m = match m with
  1406. | [] -> ""
  1407. | Str.Text txt :: tl ->
  1408. i := !i + String.length txt;
  1409. txt ^ (loop tl)
  1410. | Str.Delim a :: Str.Delim b :: tl when a = b ->
  1411. i := !i + 2;
  1412. a ^ (loop tl)
  1413. | Str.Delim "{" :: Str.Text n :: Str.Delim "}" :: tl ->
  1414. (try
  1415. let expr = Array.get exprs (int_of_string n) in
  1416. let txt = print_expr pctx expr in
  1417. i := !i + 2 + String.length n;
  1418. txt ^ (loop tl)
  1419. with | Failure "int_of_string" ->
  1420. err ("Index expected. Got " ^ n)
  1421. | Invalid_argument _ ->
  1422. err ("Out-of-bounds pythonCode special parameter: " ^ n))
  1423. | Str.Delim x :: _ ->
  1424. err ("Unexpected " ^ x)
  1425. in
  1426. loop (Str.full_split regex code)
  1427. | ("python_Syntax._pythonCode"), [e] ->
  1428. print_expr pctx e
  1429. | "python_Syntax._callNamedUntyped",el ->
  1430. let res,fields = match List.rev el with
  1431. | {eexpr = TObjectDecl fields} :: el ->
  1432. List.rev el,fields
  1433. | _ ->
  1434. assert false
  1435. in
  1436. begin match res with
  1437. | e1 :: [] ->
  1438. Printf.sprintf "%s(%s)" (print_expr pctx e1) (print_params_named pctx ", " fields)
  1439. | e1 :: el ->
  1440. Printf.sprintf "%s(%s, %s)" (print_expr pctx e1) (print_exprs pctx ", " el) (print_params_named pctx ", " fields)
  1441. | [] ->
  1442. Printf.sprintf "%s(%s)" (print_expr pctx e1) (print_params_named pctx ", " fields)
  1443. end
  1444. | "python_Syntax.varArgs",[e1] ->
  1445. "*" ^ (print_expr pctx e1)
  1446. | "python_Syntax.call" ,e1 :: [{eexpr = TArrayDecl el}]->
  1447. Printf.sprintf "%s(%s)" (print_expr pctx e1) (print_exprs pctx ", " el)
  1448. | "python_Syntax.field",[e1;{eexpr = TConst(TString id)}] ->
  1449. Printf.sprintf "%s.%s" (print_expr pctx e1) id
  1450. | "python_Syntax._tuple", [{eexpr = TArrayDecl el}] ->
  1451. (match el with
  1452. | [e] ->
  1453. Printf.sprintf "(%s,)" (print_expr pctx e)
  1454. | _ ->
  1455. Printf.sprintf "(%s)" (print_exprs pctx ", " el))
  1456. | "python_Syntax._arrayAccess", e1 :: {eexpr = TArrayDecl el} :: etrail ->
  1457. let trailing_colon = match etrail with
  1458. | [{eexpr = TConst(TBool(true))}] -> true
  1459. | _ -> false
  1460. in
  1461. Printf.sprintf "%s[%s%s]" (print_expr pctx e1) (print_exprs pctx ":" el) (if trailing_colon then ":" else "")
  1462. | "python_Syntax.isIn",[e1;e2] ->
  1463. Printf.sprintf "%s in %s" (print_expr pctx e1) (print_expr pctx e2)
  1464. | "python_Syntax.delete",[e1] ->
  1465. Printf.sprintf "del %s" (print_expr pctx e1)
  1466. | "python_Syntax.binop",[e0;{eexpr = TConst(TString id)};e2] ->
  1467. Printf.sprintf "(%s %s %s)" (print_expr pctx e0) id (print_expr pctx e2)
  1468. | "python_Syntax.assign",[e0;e1] ->
  1469. Printf.sprintf "%s = %s" (print_expr pctx e0) (print_expr pctx e1)
  1470. | "python_Syntax.arraySet",[e1;e2;e3] ->
  1471. Printf.sprintf "%s[%s] = %s" (print_expr pctx e1) (print_expr pctx e2) (print_expr pctx e3)
  1472. | "python_Syntax._newInstance", e1 :: [{eexpr = TArrayDecl el}] ->
  1473. Printf.sprintf "%s(%s)" (print_expr pctx e1) (print_exprs pctx ", " el)
  1474. | "python_Syntax.opPow", [e1;e2] ->
  1475. Printf.sprintf "(%s ** %s)" (print_expr pctx e1) (print_expr pctx e2)
  1476. | "python_Syntax._foreach",[e1;e2;e3] ->
  1477. let pctx = {pctx with pc_indent = " " ^ pctx.pc_indent} in
  1478. let i = pctx.pc_indent in
  1479. Printf.sprintf "for %s in %s:\n%s%s" (print_expr pctx e1) (print_expr pctx e2) i (print_expr pctx e3)
  1480. | _,el ->
  1481. Printf.sprintf "%s(%s)" id (print_call_args pctx e1 el)
  1482. and print_call pctx e1 el call_expr =
  1483. let get_native_fields t = match follow t with
  1484. | TAnon(a) ->
  1485. let fold f cf acc =
  1486. if Meta.has Meta.Native cf.cf_meta then begin
  1487. let _, args, mp = Meta.get Meta.Native cf.cf_meta in
  1488. match args with
  1489. | [( EConst(String s),_)] -> PMap.add f s acc
  1490. | _ -> acc
  1491. end else acc
  1492. in
  1493. let mapping = PMap.foldi fold a.a_fields PMap.empty in
  1494. mapping
  1495. | _ -> PMap.empty
  1496. in
  1497. let native_fields_str native_fields =
  1498. let fold_dict k v acc =
  1499. let prefix = if acc = "" then "" else "," in
  1500. Printf.sprintf "%s%s\"%s\":\"%s\"" acc prefix (handle_keywords k) v
  1501. in
  1502. PMap.foldi fold_dict native_fields ""
  1503. in
  1504. match e1.eexpr, el with
  1505. | TLocal { v_name = "`trace" }, [e;infos] ->
  1506. if has_feature pctx "haxe.Log.trace" then begin
  1507. "haxe_Log.trace(" ^ (print_expr pctx e) ^ "," ^ (print_expr pctx infos) ^ ")"
  1508. end else if is_safe_string pctx e then
  1509. "print(" ^ (print_expr pctx e) ^ ")"
  1510. else
  1511. "print(str(" ^ (print_expr pctx e) ^ "))"
  1512. | TField(e1,((FAnon {cf_name = (("join" | "push" | "map" | "filter") as s)}) | FDynamic (("join" | "push" | "map" | "filter") as s))), [x] ->
  1513. Printf.sprintf "HxOverrides.%s(%s, %s)" s (print_expr pctx e1) (print_expr pctx x)
  1514. | TField(e1,((FAnon {cf_name = (("iterator" | "toUpperCase" | "toLowerCase" | "pop" | "shift") as s)}) | FDynamic (("iterator" | "toUpperCase" | "toLowerCase" | "pop" | "shift") as s))), [] ->
  1515. Printf.sprintf "HxOverrides.%s(%s)" s (print_expr pctx e1)
  1516. | TField(_, (FStatic({cl_path = ["python"; "_KwArgs"], "KwArgs_Impl_"},{ cf_name="fromT" }))), [e2] ->
  1517. let t = match follow call_expr.etype with
  1518. | TAbstract(_, [t]) -> t
  1519. | _ -> assert false
  1520. in
  1521. let native_fields = get_native_fields t in
  1522. if PMap.is_empty native_fields then
  1523. print_call2 pctx e1 el
  1524. else
  1525. let s1 = native_fields_str native_fields in
  1526. Printf.sprintf "python__KwArgs_KwArgs_Impl_.fromT(HxOverrides.mapKwArgs(%s, {%s}))" (print_expr pctx e2) s1
  1527. | TField(_, (FStatic({cl_path = ["python"; "_KwArgs"], "KwArgs_Impl_"},{ cf_name="toDictHelper" }))), [e2; et] ->
  1528. let native_fields = get_native_fields et.etype in
  1529. if PMap.is_empty native_fields then
  1530. print_call2 pctx e1 el
  1531. else
  1532. let s1 = native_fields_str native_fields in
  1533. Printf.sprintf "python__KwArgs_KwArgs_Impl_.toDictHelper(HxOverrides.reverseMapKwArgs(%s, {%s}), None)" (print_expr pctx e2) s1
  1534. | _,_ ->
  1535. print_call2 pctx e1 el
  1536. and print_call_args pctx e1 el =
  1537. let print_arg pctx i x =
  1538. let e = match x.eexpr, follow x.etype with
  1539. | TConst TNull, TAbstract({a_path = ["python"],"KwArgs"},_) -> "{}"
  1540. | TConst TNull, TAbstract({a_path = ["python"],"VarArgs"},_) -> "[]"
  1541. | _ -> (print_expr pctx x)
  1542. in
  1543. let prefix = match e1.eexpr, follow x.etype with
  1544. (* the should not apply for the instance methods of the abstract itself *)
  1545. | TField(_, FStatic({cl_path = ["python"; "_KwArgs"],"KwArgs_Impl_"},f)), _ when i == 0 && Meta.has Meta.Impl f.cf_meta -> ""
  1546. | TField(_, FStatic({cl_path = ["python"; "_VarArgs"],"VarArgs_Impl_"},f)), _ when i == 0 && Meta.has Meta.Impl f.cf_meta -> ""
  1547. | _, TAbstract({a_path = ["python"],"KwArgs"},_) -> "**"
  1548. | _, TAbstract({a_path = ["python"],"VarArgs"},_) -> "*"
  1549. | _, _ -> ""
  1550. in
  1551. prefix ^ e
  1552. in
  1553. String.concat "," (ExtList.List.mapi (print_arg pctx) el)
  1554. and print_exprs pctx sep el =
  1555. String.concat sep (List.map (print_expr pctx) el)
  1556. and last_debug_comment = ref ("")
  1557. and print_block_exprs pctx sep print_debug_comment el =
  1558. if print_debug_comment then begin
  1559. let el = List.fold_left (fun acc e ->
  1560. let line = Lexer.get_error_line e.epos in
  1561. let debug_line = (Printf.sprintf "# %s:%i" e.epos.pfile line) in
  1562. let res = if (!last_debug_comment) <> debug_line then
  1563. (print_expr pctx e) :: debug_line :: acc
  1564. else
  1565. (print_expr pctx e) :: acc
  1566. in
  1567. last_debug_comment := debug_line;
  1568. res
  1569. ) [] el in
  1570. String.concat sep (List.rev el)
  1571. end else
  1572. print_exprs pctx sep el
  1573. and print_exprs_named pctx sep fl =
  1574. let args = String.concat sep (List.map (fun (s,e) -> Printf.sprintf "'%s': %s" (handle_keywords s) (print_expr pctx e)) fl) in
  1575. Printf.sprintf "{%s}" args
  1576. and print_params_named pctx sep fl =
  1577. let args = String.concat sep (List.map (fun (s,e) -> Printf.sprintf "%s= %s" (handle_keywords s) (print_expr pctx e)) fl) in
  1578. Printf.sprintf "%s" args
  1579. let handle_keywords s =
  1580. KeywordHandler.handle_keywords s
  1581. end
  1582. module Generator = struct
  1583. type context = {
  1584. com : Common.context;
  1585. buf : Buffer.t;
  1586. packages : (string,int) Hashtbl.t;
  1587. mutable static_inits : (unit -> unit) list;
  1588. mutable class_inits : (unit -> unit) list;
  1589. mutable indent_count : int;
  1590. transform_time : float;
  1591. print_time : float;
  1592. }
  1593. let has_feature ctx = Common.has_feature ctx.com
  1594. let add_feature ctx = Common.add_feature ctx.com
  1595. type class_field_infos = {
  1596. cfd_fields : string list;
  1597. cfd_props : string list;
  1598. cfd_methods : string list;
  1599. }
  1600. type import_type =
  1601. | IModule of string
  1602. | IObject of string * string
  1603. let mk_context com = {
  1604. com = com;
  1605. buf = Buffer.create 16000;
  1606. packages = Hashtbl.create 0;
  1607. static_inits = [];
  1608. class_inits = [];
  1609. indent_count = 0;
  1610. transform_time = 0.;
  1611. print_time = 0.;
  1612. }
  1613. (* Transformer interface *)
  1614. let transform_expr e =
  1615. (* let e = Codegen.UnificationCallback.run Transformer.check_unification e in *)
  1616. Transformer.transform e
  1617. let transform_to_value e =
  1618. (* let e = Codegen.UnificationCallback.run Transformer.check_unification e in *)
  1619. Transformer.transform_to_value e
  1620. (* Printer interface *)
  1621. let get_path mt =
  1622. Printer.print_base_type mt
  1623. let tfunc_str f pctx name p =
  1624. Printer.print_function pctx f name p
  1625. let texpr_str e pctx =
  1626. Printer.print_expr pctx e
  1627. let handle_keywords s =
  1628. Printer.handle_keywords s
  1629. (* Helper *)
  1630. let get_full_name mt =
  1631. (* TODO: haxe source is crazy *)
  1632. s_type_path mt.mt_path
  1633. let collect_class_field_data cfl =
  1634. let fields = DynArray.create () in
  1635. let props = DynArray.create () in
  1636. let methods = DynArray.create () in
  1637. List.iter (fun cf ->
  1638. match cf.cf_kind with
  1639. | Var({v_read = AccResolve}) ->
  1640. ()
  1641. | Var _ when is_extern_field cf ->
  1642. ()
  1643. | Var({v_read = AccCall}) ->
  1644. if Meta.has Meta.IsVar cf.cf_meta then
  1645. DynArray.add fields cf.cf_name
  1646. else
  1647. DynArray.add props cf.cf_name
  1648. | Var _ ->
  1649. DynArray.add fields cf.cf_name
  1650. | _ ->
  1651. DynArray.add methods cf.cf_name
  1652. ) cfl;
  1653. {
  1654. cfd_fields = DynArray.to_list fields;
  1655. cfd_props = DynArray.to_list props;
  1656. cfd_methods = DynArray.to_list methods;
  1657. }
  1658. let collect_class_statics_data cfl =
  1659. let fields = DynArray.create () in
  1660. List.iter (fun cf ->
  1661. if not (is_extern_field cf) then
  1662. DynArray.add fields cf.cf_name
  1663. ) cfl;
  1664. DynArray.to_list fields
  1665. let filter_py_metas metas =
  1666. List.filter (fun (n,_,_) -> match n with Meta.Custom ":python" -> true | _ -> false) metas
  1667. let get_members_with_init_expr c =
  1668. List.filter (fun cf -> match cf.cf_kind with
  1669. | Var _ when is_extern_field cf -> false
  1670. | Var _ when cf.cf_expr = None -> true
  1671. | _ -> false
  1672. ) c.cl_ordered_fields
  1673. (* Printing *)
  1674. let spr ctx s =
  1675. Buffer.add_string ctx.buf s
  1676. let spr_line ctx s =
  1677. Buffer.add_string ctx.buf s;
  1678. Buffer.add_string ctx.buf "\n"
  1679. let print ctx =
  1680. Printf.kprintf (fun s -> begin
  1681. Buffer.add_string ctx.buf s
  1682. end)
  1683. let newline ctx =
  1684. if not (Buffer.length ctx.buf = 0) then spr ctx "\n"
  1685. (* Generating functions *)
  1686. let gen_py_metas ctx metas indent =
  1687. List.iter (fun (n,el,_) ->
  1688. match el with
  1689. | [EConst(String s),_] ->
  1690. print ctx "%s@%s\n" indent s
  1691. | _ ->
  1692. assert false
  1693. ) metas
  1694. let gen_expr ctx e field indent =
  1695. let pctx = Printer.create_context (" " ^ indent) ctx.com ctx.com.debug in
  1696. let e = match e.eexpr with
  1697. | TFunction(f) ->
  1698. {e with eexpr = TBlock [e]}
  1699. | _ ->
  1700. e
  1701. in
  1702. let expr2 = transform_to_value e in
  1703. let name = "_hx_init_" ^ (String.concat "_" (ExtString.String.nsplit field ".")) in
  1704. let maybe_split_expr expr2 = match expr2.eexpr with
  1705. | TBlock es when es <> [] && field <> "" ->
  1706. begin match List.rev es with
  1707. | e_last :: el ->
  1708. let new_last = {e_last with eexpr = TReturn (Some e_last)} in
  1709. let new_block = {expr2 with eexpr = TBlock (List.rev (new_last :: el))} in
  1710. let v_name = alloc_var name (tfun [] e_last.etype) in
  1711. let f_name = mk (TLocal v_name) v_name.v_type e_last.epos in
  1712. let call_f = mk (TCall(f_name,[])) e_last.etype e_last.epos in
  1713. Some new_block,call_f
  1714. | _ ->
  1715. assert false
  1716. end
  1717. | _ ->
  1718. None,expr2
  1719. in
  1720. let r = maybe_split_expr expr2 in
  1721. match r with
  1722. | Some e1,e2 ->
  1723. let expr_string_1 = texpr_str e1 pctx in
  1724. let expr_string_2 = texpr_str e2 pctx in
  1725. print ctx "%sdef %s():\n %s" indent name expr_string_1;
  1726. newline ctx;
  1727. print ctx "%s%s = %s" indent field expr_string_2;
  1728. | None,e2 ->
  1729. let expr_string_2 = texpr_str e2 pctx in
  1730. if field = "" then
  1731. spr ctx expr_string_2
  1732. else
  1733. print ctx "%s%s = %s" indent field expr_string_2
  1734. let gen_func_expr ctx e c name metas extra_args indent stat p =
  1735. let pctx = Printer.create_context indent ctx.com ctx.com.debug in
  1736. let e = match e.eexpr with
  1737. | TFunction(f) ->
  1738. let args = List.map (fun s ->
  1739. alloc_var s t_dynamic,None
  1740. ) extra_args in
  1741. {e with eexpr = TFunction {f with tf_args = args @ f.tf_args}}
  1742. | _ ->
  1743. e
  1744. in
  1745. if stat then begin
  1746. newline ctx;
  1747. spr ctx indent;
  1748. spr ctx "@staticmethod\n"
  1749. end;
  1750. let expr1 = transform_expr e in
  1751. let expr_string = match expr1.eexpr with
  1752. | TFunction f ->
  1753. tfunc_str f pctx (Some name) p
  1754. | _ ->
  1755. Printf.sprintf "%s = %s" name (texpr_str expr1 pctx)
  1756. in
  1757. gen_py_metas ctx metas indent;
  1758. spr ctx indent;
  1759. spr ctx expr_string
  1760. let gen_class_constructor ctx c cf =
  1761. let member_inits = get_members_with_init_expr c in
  1762. let py_metas = filter_py_metas cf.cf_meta in
  1763. begin match cf.cf_expr with
  1764. | Some ({eexpr = TFunction f} as ef) ->
  1765. let ethis = mk (TConst TThis) (TInst(c,List.map snd c.cl_params)) cf.cf_pos in
  1766. let assigned_fields = ref [] in
  1767. (* Collect all fields that are assigned to but panic out as soon as `this`,
  1768. `super`, `return` or `throw` appears (regardless of control flow). *)
  1769. let collect_assignments e =
  1770. let rec loop e = match e.eexpr with
  1771. | TBinop(OpAssign,{eexpr = TField({eexpr = TConst TThis}, FInstance(_,_,cf))},e2) ->
  1772. loop e2;
  1773. assigned_fields := cf :: !assigned_fields
  1774. | TConst (TSuper | TThis) | TThrow _ | TReturn _ ->
  1775. raise Exit
  1776. | _ ->
  1777. Type.iter loop e
  1778. in
  1779. try loop e with Exit -> ()
  1780. in
  1781. collect_assignments f.tf_expr;
  1782. let member_data = List.fold_left (fun acc cf ->
  1783. if not (List.memq cf !assigned_fields) then begin
  1784. let ef = mk (TField(ethis,FInstance(c,[],cf))) cf.cf_type cf.cf_pos in (* TODO *)
  1785. let e = mk (TBinop(OpAssign,ef,null ef.etype ef.epos)) ef.etype ef.epos in
  1786. e :: acc
  1787. end else
  1788. acc
  1789. ) [] member_inits in
  1790. let e = concat (mk (TBlock member_data) ctx.com.basic.tvoid cf.cf_pos) f.tf_expr in
  1791. let ef = {ef with eexpr = TFunction {f with tf_expr = e}} in
  1792. cf.cf_expr <- Some ef;
  1793. newline ctx;
  1794. newline ctx;
  1795. gen_func_expr ctx ef c "__init__" py_metas ["self"] " " false cf.cf_pos
  1796. | _ ->
  1797. assert false
  1798. end
  1799. let gen_class_field ctx c p cf =
  1800. let field = handle_keywords cf.cf_name in
  1801. begin match cf.cf_expr with
  1802. | None ->
  1803. ()(* print ctx " # var %s" field *)
  1804. | Some e ->
  1805. newline ctx;
  1806. newline ctx;
  1807. begin match cf.cf_kind with
  1808. | Method _ ->
  1809. let py_metas = filter_py_metas cf.cf_meta in
  1810. gen_func_expr ctx e c field py_metas ["self"] " " false cf.cf_pos;
  1811. | _ ->
  1812. gen_expr ctx e (Printf.sprintf "# var %s" field) " ";
  1813. end
  1814. end
  1815. let gen_class_empty_constructor ctx p cfl =
  1816. if has_feature ctx "Type.createEmptyInstance" then begin
  1817. newline ctx;
  1818. newline ctx;
  1819. print ctx " @staticmethod\n def _hx_empty_init(_hx_o):";
  1820. let found_fields = ref false in
  1821. List.iter (fun cf -> match cf.cf_kind with
  1822. | Var ({v_read = AccResolve | AccCall}) ->
  1823. ()
  1824. | Var _ ->
  1825. found_fields := true;
  1826. newline ctx;
  1827. print ctx " _hx_o.%s = None" (handle_keywords cf.cf_name)
  1828. | _ ->
  1829. ()
  1830. ) cfl;
  1831. if not !found_fields then
  1832. spr ctx " pass"
  1833. end else begin
  1834. newline ctx
  1835. end
  1836. let gen_class_statics ctx c p =
  1837. let methods, other = List.partition (fun cf ->
  1838. match cf.cf_kind with
  1839. | Method _ -> (match cf.cf_expr with Some _ -> true | _ -> false)
  1840. | _ -> false
  1841. ) c.cl_ordered_statics in
  1842. (* generate non methods *)
  1843. let has_empty_static_vars = ref false in
  1844. List.iter (fun cf ->
  1845. let p = get_path (t_infos (TClassDecl c)) in
  1846. let field = handle_keywords cf.cf_name in
  1847. match cf.cf_expr with
  1848. | None ->
  1849. has_empty_static_vars := true;
  1850. newline ctx;
  1851. print ctx " %s = None" field
  1852. | Some e ->
  1853. (let f = fun () ->
  1854. newline ctx;
  1855. gen_expr ctx e (Printf.sprintf "%s.%s" p field) "";
  1856. in
  1857. ctx.static_inits <- f :: ctx.static_inits)
  1858. ) other;
  1859. (* generate static methods *)
  1860. let has_static_methods = ref false in
  1861. List.iter (fun cf ->
  1862. has_static_methods := true;
  1863. let field = handle_keywords cf.cf_name in
  1864. let py_metas = filter_py_metas cf.cf_meta in
  1865. let e = match cf.cf_expr with Some e -> e | _ -> assert false in
  1866. newline ctx;
  1867. gen_func_expr ctx e c field py_metas [] " " true cf.cf_pos;
  1868. ) methods;
  1869. !has_static_methods || !has_empty_static_vars
  1870. let gen_class_init ctx c =
  1871. match c.cl_init with
  1872. | None ->
  1873. ()
  1874. | Some e ->
  1875. let is_math = c.cl_path = ([], "Math") in
  1876. let math_feature = has_feature ctx "Math" in
  1877. let f = if is_math && not math_feature then
  1878. fun () -> ()
  1879. else fun () ->
  1880. let e = transform_expr e in
  1881. newline ctx;
  1882. spr ctx (texpr_str e (Printer.create_context "" ctx.com ctx.com.debug));
  1883. in
  1884. ctx.class_inits <- f :: ctx.class_inits
  1885. let gen_class ctx c =
  1886. if not c.cl_extern then begin
  1887. let is_nativegen = Meta.has Meta.NativeGen c.cl_meta in
  1888. let mt = (t_infos (TClassDecl c)) in
  1889. let p = get_path mt in
  1890. let p_name = get_full_name mt in
  1891. let x = collect_class_field_data c.cl_ordered_fields in
  1892. let p_super = match c.cl_super with
  1893. | None ->
  1894. None
  1895. | Some (csup,_) ->
  1896. Some (get_path (t_infos (TClassDecl csup)))
  1897. in
  1898. let p_interfaces = List.map (fun (c,tl) ->
  1899. get_path (t_infos (TClassDecl c))
  1900. ) c.cl_implements in
  1901. newline ctx;
  1902. newline ctx;
  1903. newline ctx;
  1904. print ctx "class %s" p;
  1905. (match p_super with Some p -> print ctx "(%s)" p | _ -> ());
  1906. spr ctx ":";
  1907. let use_pass = ref true in
  1908. if not is_nativegen then begin
  1909. if has_feature ctx "python._hx_class_name" then begin
  1910. use_pass := false;
  1911. print ctx "\n _hx_class_name = \"%s\"" p_name
  1912. end;
  1913. let print_field names field quote =
  1914. if has_feature ctx ("python." ^ field) then try
  1915. let q s = if quote then "\"" ^ s ^ "\"" else s in
  1916. let s = match names with
  1917. | [] when (match c.cl_super with Some _ -> false | _ -> true) ->
  1918. (* always overwrite parent's class fields *)
  1919. raise Exit
  1920. | _ ->
  1921. "[" ^ (String.concat ", " (List.map q names)) ^ "]"
  1922. in
  1923. use_pass := false;
  1924. print ctx "\n %s = %s" field s
  1925. with Exit -> ()
  1926. in
  1927. (try (
  1928. let real_fields =
  1929. List.filter (fun f -> match f.cf_kind with
  1930. | Method MethDynamic -> raise Exit (* if a class has dynamic method, we can't use __slots__ because python will complain *)
  1931. | Var _ -> not (is_extern_field f)
  1932. | _ -> false
  1933. ) c.cl_ordered_fields
  1934. in
  1935. let field_names = List.map (fun f -> handle_keywords f.cf_name) real_fields in
  1936. let field_names = match c.cl_dynamic with Some _ -> "__dict__" :: field_names | None -> field_names in
  1937. use_pass := false;
  1938. print ctx "\n __slots__ = (";
  1939. (match field_names with
  1940. | [] -> ()
  1941. | [name] -> print ctx "\"%s\"," name
  1942. | names -> print ctx "\"%s\"" (String.concat "\", \"" names));
  1943. print ctx ")";
  1944. ) with Exit -> ());
  1945. print_field x.cfd_fields "_hx_fields" true;
  1946. print_field x.cfd_methods "_hx_methods" true;
  1947. (* TODO: It seems strange to have a separation for member fields but a plain _hx_statics for static ones *)
  1948. print_field (collect_class_statics_data c.cl_ordered_statics) "_hx_statics" true;
  1949. print_field (p_interfaces) "_hx_interfaces" false;
  1950. if has_feature ctx "python._hx_super" then (match p_super with
  1951. | None -> ()
  1952. | Some ps ->
  1953. use_pass := false;
  1954. print ctx "\n _hx_super = %s\n" ps
  1955. );
  1956. end;
  1957. begin match c.cl_constructor with
  1958. | Some cf -> gen_class_constructor ctx c cf;
  1959. | None -> ()
  1960. end;
  1961. List.iter (fun cf -> gen_class_field ctx c p cf) c.cl_ordered_fields;
  1962. let has_inner_static = gen_class_statics ctx c p in
  1963. let has_empty_constructor = match ((Meta.has Meta.NativeGen c.cl_meta) || c.cl_interface), c.cl_ordered_fields with
  1964. | true,_
  1965. | _, [] ->
  1966. false
  1967. | _ ->
  1968. gen_class_empty_constructor ctx p c.cl_ordered_fields;
  1969. has_feature ctx "Type.createEmptyInstance"
  1970. in
  1971. let use_pass = !use_pass && (not has_inner_static) && (not has_empty_constructor) && match x.cfd_methods with
  1972. | [] -> c.cl_constructor = None
  1973. | _ -> c.cl_interface
  1974. in
  1975. if use_pass then spr ctx "\n pass";
  1976. if not is_nativegen then begin
  1977. if has_feature ctx "python._hx_class" then print ctx "\n%s._hx_class = %s" p p;
  1978. if has_feature ctx "python._hx_classes" then print ctx "\n_hx_classes[\"%s\"] = %s" p_name p;
  1979. end
  1980. end;
  1981. gen_class_init ctx c
  1982. let gen_enum_metadata ctx en p =
  1983. let meta = Codegen.build_metadata ctx.com (TEnumDecl en) in
  1984. match meta with
  1985. | None ->
  1986. ()
  1987. | Some e ->
  1988. newline ctx;
  1989. print ctx "%s.__meta__ = " p;
  1990. gen_expr ctx e "" ""
  1991. let gen_enum ctx en =
  1992. let mt = (t_infos (TEnumDecl en)) in
  1993. let p = get_path mt in
  1994. let p_name = get_full_name mt in
  1995. let enum_constructs = PMap.foldi (fun k ef acc -> ef :: acc) en.e_constrs [] in
  1996. let enum_constructs = List.sort (fun a b -> if a.ef_index < b.ef_index then -1 else if a.ef_index > b.ef_index then 1 else 0) enum_constructs in
  1997. newline ctx;
  1998. newline ctx;
  1999. print ctx "class %s(Enum):" p;
  2000. print ctx "\n __slots__ = ()";
  2001. if has_feature ctx "python._hx_class_name" then begin
  2002. print ctx "\n _hx_class_name = \"%s\"" p_name
  2003. end;
  2004. if has_feature ctx "python._hx_constructs" then begin
  2005. let fix = match enum_constructs with [] -> "" | _ -> "\"" in
  2006. let enum_constructs_str = fix ^ (String.concat ("\", \"") (List.map (fun ef -> ef.ef_name) enum_constructs)) ^ fix in
  2007. print ctx "\n _hx_constructs = [%s]" enum_constructs_str;
  2008. end;
  2009. let const_constructors,param_constructors = List.partition (fun ef ->
  2010. match follow ef.ef_type with
  2011. | TFun(_,_) -> false
  2012. | _ -> true
  2013. ) enum_constructs in
  2014. List.iter (fun ef ->
  2015. match follow ef.ef_type with
  2016. | TFun(args, _) ->
  2017. let print_args args =
  2018. let had_optional = ref false in
  2019. let sl = List.map (fun (n,o,_) ->
  2020. let name = handle_keywords n in
  2021. let arg_value = if !had_optional then
  2022. "= None"
  2023. else if o then begin
  2024. had_optional := true;
  2025. " = None"
  2026. end else
  2027. ""
  2028. in
  2029. Printf.sprintf "%s%s" name arg_value
  2030. ) args in
  2031. String.concat "," sl
  2032. in
  2033. let f = handle_keywords ef.ef_name in
  2034. let param_str = print_args args in
  2035. let args_str = String.concat "," (List.map (fun (n,_,_) -> handle_keywords n) args) in
  2036. newline ctx;
  2037. newline ctx;
  2038. print ctx " @staticmethod\n def %s(%s):\n" f param_str;
  2039. print ctx " return %s(\"%s\", %i, [%s])" p ef.ef_name ef.ef_index args_str;
  2040. | _ -> assert false
  2041. ) param_constructors;
  2042. List.iter (fun ef ->
  2043. (* TODO: haxe source has api.quoteString for ef.ef_name *)
  2044. let f = handle_keywords ef.ef_name in
  2045. newline ctx;
  2046. print ctx "%s.%s = %s(\"%s\", %i, list())" p f p ef.ef_name ef.ef_index
  2047. ) const_constructors;
  2048. if has_feature ctx "python._hx_class" then print ctx "\n%s._hx_class = %s" p p;
  2049. if has_feature ctx "python._hx_classes" then print ctx "\n_hx_classes[\"%s\"] = %s" p_name p;
  2050. gen_enum_metadata ctx en p
  2051. let gen_abstract ctx a =
  2052. newline ctx;
  2053. newline ctx;
  2054. newline ctx;
  2055. let mt = (t_infos (TAbstractDecl a)) in
  2056. let p = get_path mt in
  2057. let p_name = get_full_name mt in
  2058. print ctx "class %s:" p;
  2059. let use_pass = ref true in
  2060. if has_feature ctx "python._hx_class_name" then begin
  2061. use_pass := false;
  2062. print ctx "\n _hx_class_name = \"%s\"" p_name
  2063. end;
  2064. (match a.a_impl with
  2065. | Some c ->
  2066. List.iter (fun cf ->
  2067. use_pass := false;
  2068. if cf.cf_name = "_new" then
  2069. gen_class_constructor ctx c cf
  2070. else
  2071. gen_class_field ctx c p cf
  2072. ) c.cl_ordered_statics
  2073. | None -> ());
  2074. if !use_pass then spr ctx "\n pass";
  2075. if has_feature ctx "python._hx_class" then print ctx "\n%s._hx_class = %s" p p;
  2076. if has_feature ctx "python._hx_classes" then print ctx "\n_hx_classes[\"%s\"] = %s" p_name p
  2077. let gen_type ctx mt = match mt with
  2078. | TClassDecl c -> gen_class ctx c
  2079. | TEnumDecl en when not en.e_extern -> gen_enum ctx en
  2080. | TAbstractDecl {a_path = [],"UInt"} -> ()
  2081. | TAbstractDecl {a_path = [],"Enum"} -> ()
  2082. | TAbstractDecl {a_path = [],"EnumValue"} when not (has_feature ctx "has_enum") -> ()
  2083. | TAbstractDecl {a_path = [],"Void"} -> ()
  2084. | TAbstractDecl {a_path = [],"Int"} when not (has_feature ctx "Int.*") -> ()
  2085. | TAbstractDecl {a_path = [],"Float"} when not (has_feature ctx "Float.*") -> ()
  2086. | TAbstractDecl {a_path = [],"Class"} when not (has_feature ctx "Class.*") -> ()
  2087. | TAbstractDecl {a_path = [],"Dynamic"} when not (has_feature ctx "Dynamic.*") -> ()
  2088. | TAbstractDecl {a_path = [],"Bool"} when not (has_feature ctx "Bool.*") -> ()
  2089. | TAbstractDecl a when Meta.has Meta.CoreType a.a_meta -> gen_abstract ctx a
  2090. | _ -> ()
  2091. (* Generator parts *)
  2092. let gen_resources ctx =
  2093. if Hashtbl.length ctx.com.resources > 0 then begin
  2094. let slash_index = try (String.rindex ctx.com.file '/')+1 with Not_found -> 0 in
  2095. let len = String.length ctx.com.file - slash_index in
  2096. let file_name = String.sub ctx.com.file slash_index len in
  2097. newline ctx;
  2098. newline ctx;
  2099. newline ctx;
  2100. spr ctx "def _hx_resources__():";
  2101. spr ctx "\n import inspect";
  2102. spr ctx "\n import sys";
  2103. spr ctx "\n if not hasattr(sys.modules[__name__], '__file__'):";
  2104. print ctx "\n _file = '%s'" file_name;
  2105. spr ctx "\n else:";
  2106. spr ctx "\n _file = __file__";
  2107. spr ctx "\n return {";
  2108. let first = ref true in
  2109. Hashtbl.iter (fun k v ->
  2110. let prefix = if !first then begin
  2111. first := false;
  2112. "";
  2113. end else
  2114. ","
  2115. in
  2116. let k_enc = Codegen.escape_res_name k false in
  2117. print ctx "%s\"%s\": open('%%s.%%s'%%(_file,'%s'),'rb').read()" prefix (Ast.s_escape k) k_enc;
  2118. let f = open_out_bin (ctx.com.file ^ "." ^ k_enc) in
  2119. output_string f v;
  2120. close_out f
  2121. ) ctx.com.resources;
  2122. spr ctx "}"
  2123. end
  2124. let gen_imports ctx =
  2125. let import path meta =
  2126. if Meta.has Meta.PythonImport meta && is_directly_used ctx.com meta then begin
  2127. let _, args, mp = Meta.get Meta.PythonImport meta in
  2128. let class_name = match path with
  2129. | [],name -> name
  2130. | path,name -> (ExtString.String.join "_" path) ^ "_" ^ name
  2131. in
  2132. let import_type,ignore_error = match args with
  2133. | [(EConst(String(module_name)), _)]
  2134. | [(EConst(String(module_name)), _); (EBinop(OpAssign, (EConst(Ident("ignoreError")),_), (EConst(Ident("false")),_)),_)] ->
  2135. IModule module_name, false
  2136. | [(EConst(String(module_name)), _); (EBinop(OpAssign, (EConst(Ident("ignoreError")),_), (EConst(Ident("true")),_)),_)] ->
  2137. IModule module_name,true
  2138. | [(EConst(String(module_name)), _); (EConst(String(object_name)), _)]
  2139. | [(EConst(String(module_name)), _); (EConst(String(object_name)), _); (EBinop(OpAssign, (EConst(Ident("ignoreError")),_), (EConst(Ident("false")),_)),_)] ->
  2140. IObject (module_name,object_name), false
  2141. | [(EConst(String(module_name)), _); (EConst(String(object_name)), _); (EBinop(OpAssign, (EConst(Ident("ignoreError")),_), (EConst(Ident("true")),_)),_)] ->
  2142. IObject (module_name,object_name), true
  2143. | _ ->
  2144. error "Unsupported @:pythonImport format" mp
  2145. in
  2146. let import = match import_type with
  2147. | IModule module_name ->
  2148. (* importing whole module *)
  2149. "import " ^ module_name ^ " as " ^ class_name
  2150. | IObject (module_name,object_name) ->
  2151. if String.contains object_name '.' then
  2152. (* importing nested class *)
  2153. "import " ^ module_name ^ " as _hx_temp_import; " ^ class_name ^ " = _hx_temp_import." ^ object_name ^ "; del _hx_temp_import"
  2154. else
  2155. (* importing a class from a module *)
  2156. "from " ^ module_name ^ " import " ^ object_name ^ " as " ^ class_name
  2157. in
  2158. newline ctx;
  2159. if ignore_error then begin
  2160. spr ctx "try:\n ";
  2161. spr_line ctx import;
  2162. spr ctx "except:\n pass"
  2163. end else
  2164. spr ctx import
  2165. end
  2166. in
  2167. List.iter (fun mt ->
  2168. match mt with
  2169. | TClassDecl c when c.cl_extern -> import c.cl_path c.cl_meta
  2170. | TEnumDecl e when e.e_extern -> import e.e_path e.e_meta
  2171. | _ -> ()
  2172. ) ctx.com.types
  2173. let gen_types ctx =
  2174. let used_paths = Hashtbl.create 0 in
  2175. let find_type path =
  2176. Hashtbl.add used_paths path true;
  2177. Utils.find_type ctx.com path
  2178. in
  2179. let need_anon_for_trace = (has_feature ctx "has_anon_trace") && (has_feature ctx "haxe.Log.trace") in
  2180. if (has_feature ctx "has_anon") || (has_feature ctx "_hx_AnonObject") || (has_feature ctx "has_metadata") || need_anon_for_trace then begin
  2181. let with_body = (has_feature ctx "has_anon") || (has_feature ctx "has_metadata") || need_anon_for_trace in
  2182. newline ctx;
  2183. newline ctx;
  2184. newline ctx;
  2185. spr ctx "class _hx_AnonObject:\n";
  2186. if with_body then begin
  2187. spr ctx " def __init__(self, fields):\n";
  2188. spr ctx " self.__dict__ = fields"
  2189. end else
  2190. spr ctx " pass";
  2191. Hashtbl.add used_paths ([],"_hx_AnonObject") true;
  2192. end;
  2193. if has_feature ctx "python._hx_classes" then begin
  2194. newline ctx;
  2195. newline ctx;
  2196. newline ctx;
  2197. spr ctx "_hx_classes = {}";
  2198. end;
  2199. if has_feature ctx "Boot.*" then
  2200. gen_type ctx (find_type (["python"],"Boot"));
  2201. if has_feature ctx "has_enum" || has_feature ctx "Enum.*" then
  2202. gen_type ctx (find_type ([],"Enum"));
  2203. if has_feature ctx "HxOverrides.*" then
  2204. gen_type ctx (find_type ([],"HxOverrides"));
  2205. List.iter (fun mt ->
  2206. if not (Hashtbl.mem used_paths (t_infos mt).mt_path) then
  2207. gen_type ctx mt
  2208. ) ctx.com.types
  2209. let gen_static_inits ctx =
  2210. newline ctx;
  2211. List.iter (fun f -> f()) (List.rev ctx.static_inits)
  2212. let gen_class_inits ctx =
  2213. newline ctx;
  2214. List.iter (fun f -> f()) (List.rev ctx.class_inits)
  2215. let gen_main ctx =
  2216. match ctx.com.main with
  2217. | None ->
  2218. ()
  2219. | Some e ->
  2220. newline ctx;
  2221. newline ctx;
  2222. gen_expr ctx e "" ""
  2223. (* Entry point *)
  2224. let run com =
  2225. Transformer.init com;
  2226. let ctx = mk_context com in
  2227. Codegen.map_source_header com (fun s -> print ctx "# %s\n" s);
  2228. gen_imports ctx;
  2229. gen_resources ctx;
  2230. gen_types ctx;
  2231. gen_class_inits ctx;
  2232. gen_static_inits ctx;
  2233. gen_main ctx;
  2234. mkdir_from_path com.file;
  2235. let ch = open_out_bin com.file in
  2236. output_string ch (Buffer.contents ctx.buf);
  2237. close_out ch
  2238. end
  2239. let generate com =
  2240. Generator.run com