genpy.ml 85 KB

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