optimizer.ml 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671
  1. (*
  2. The Haxe Compiler
  3. Copyright (C) 2005-2015 Haxe Foundation
  4. This program is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU General Public License
  6. as published by the Free Software Foundation; either version 2
  7. of the License, or (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  15. *)
  16. open Ast
  17. open Type
  18. open Common
  19. open Typecore
  20. (* ---------------------------------------------------------------------- *)
  21. (* API OPTIMIZATIONS *)
  22. (* tells if an expression causes side effects. This does not account for potential null accesses (fields/arrays/ops) *)
  23. let has_side_effect e =
  24. let rec loop e =
  25. match e.eexpr with
  26. | TConst _ | TLocal _ | TTypeExpr _ | TFunction _ -> ()
  27. | TCall ({ eexpr = TField(_,FStatic({ cl_path = ([],"Std") },{ cf_name = "string" })) },args) -> Type.iter loop e
  28. | TNew _ | TCall _ | TBinop ((OpAssignOp _ | OpAssign),_,_) | TUnop ((Increment|Decrement),_,_) -> raise Exit
  29. | TReturn _ | TBreak | TContinue | TThrow _ | TCast (_,Some _) -> raise Exit
  30. | TArray _ | TEnumParameter _ | TCast (_,None) | TBinop _ | TUnop _ | TParenthesis _ | TMeta _ | TWhile _ | TFor _
  31. | TField _ | TIf _ | TTry _ | TSwitch _ | TArrayDecl _ | TBlock _ | TObjectDecl _ | TVar _ -> Type.iter loop e
  32. in
  33. try
  34. loop e; false
  35. with Exit ->
  36. true
  37. let rec is_exhaustive e1 = match e1.eexpr with
  38. | TMeta((Meta.Exhaustive,_,_),_) -> true
  39. | TMeta(_, e1) | TParenthesis e1 -> is_exhaustive e1
  40. | _ -> false
  41. let mk_untyped_call name p params =
  42. {
  43. eexpr = TCall({ eexpr = TLocal(alloc_unbound_var name t_dynamic); etype = t_dynamic; epos = p }, params);
  44. etype = t_dynamic;
  45. epos = p;
  46. }
  47. let api_inline2 com c field params p =
  48. match c.cl_path, field, params with
  49. | ([],"Type"),"enumIndex",[{ eexpr = TField (_,FEnum (en,f)) }] -> (match com.platform with
  50. | Cs when en.e_extern && not (Meta.has Meta.HxGen en.e_meta) ->
  51. (* We don't want to optimize enums from external sources; as they might change unexpectedly *)
  52. (* and since native C# enums don't have the concept of index - they have rather a value, *)
  53. (* which can't be mapped to a native API - this kind of substitution is dangerous *)
  54. None
  55. | _ ->
  56. Some (mk (TConst (TInt (Int32.of_int f.ef_index))) com.basic.tint p))
  57. | ([],"Type"),"enumIndex",[{ eexpr = TCall({ eexpr = TField (_,FEnum (en,f)) },pl) }] when List.for_all (fun e -> not (has_side_effect e)) pl ->
  58. (match com.platform with
  59. | Cs when en.e_extern && not (Meta.has Meta.HxGen en.e_meta) ->
  60. (* see comment above *)
  61. None
  62. | _ ->
  63. Some (mk (TConst (TInt (Int32.of_int f.ef_index))) com.basic.tint p))
  64. | ([],"Std"),"int",[{ eexpr = TConst (TInt _) } as e] ->
  65. Some { e with epos = p }
  66. | ([],"String"),"fromCharCode",[{ eexpr = TConst (TInt i) }] when i > 0l && i < 128l ->
  67. Some (mk (TConst (TString (String.make 1 (char_of_int (Int32.to_int i))))) com.basic.tstring p)
  68. | ([],"Std"),"string",[{ eexpr = TConst c } as e] ->
  69. (match c with
  70. | TString s ->
  71. Some { e with epos = p }
  72. | TInt i ->
  73. Some { eexpr = TConst (TString (Int32.to_string i)); epos = p; etype = com.basic.tstring }
  74. | TBool b ->
  75. Some { eexpr = TConst (TString (if b then "true" else "false")); epos = p; etype = com.basic.tstring }
  76. | _ ->
  77. None)
  78. | ([],"Std"),"string",[{ eexpr = TIf (_,{ eexpr = TConst (TString _)},Some { eexpr = TConst (TString _) }) } as e] ->
  79. Some e
  80. | ([],"Std"),"string",[{ eexpr = TLocal v | TField({ eexpr = TLocal v },_) } as ev] when (com.platform = Js || com.platform = Flash) && not (Meta.has Meta.CompilerGenerated v.v_meta) ->
  81. let pos = ev.epos in
  82. let stringv() =
  83. let to_str = mk (TBinop (Ast.OpAdd, mk (TConst (TString "")) com.basic.tstring pos, ev)) com.basic.tstring pos in
  84. if com.platform = Js || is_nullable ev.etype then
  85. let chk_null = mk (TBinop (Ast.OpEq, ev, mk (TConst TNull) t_dynamic pos)) com.basic.tbool pos in
  86. mk (TIf (chk_null, mk (TConst (TString "null")) com.basic.tstring pos, Some to_str)) com.basic.tstring pos
  87. else
  88. to_str
  89. in
  90. (match follow ev.etype with
  91. | TInst ({ cl_path = [],"String" }, []) ->
  92. Some (stringv())
  93. | TAbstract ({ a_path = [],"Float" }, []) ->
  94. Some (stringv())
  95. | TAbstract ({ a_path = [],"Int" }, []) ->
  96. Some (stringv())
  97. | TAbstract ({ a_path = [],"UInt" }, []) ->
  98. Some (stringv())
  99. | TAbstract ({ a_path = [],"Bool" }, []) ->
  100. Some (stringv())
  101. | _ ->
  102. None)
  103. | ([],"Std"),"int",[{ eexpr = TConst (TFloat f) }] ->
  104. let f = float_of_string f in
  105. (match classify_float f with
  106. | FP_infinite | FP_nan ->
  107. None
  108. | _ when f <= Int32.to_float Int32.min_int -. 1. || f >= Int32.to_float Int32.max_int +. 1. ->
  109. None (* out range, keep platform-specific behavior *)
  110. | _ ->
  111. Some { eexpr = TConst (TInt (Int32.of_float f)); etype = com.basic.tint; epos = p })
  112. | ([],"Math"),"ceil",[{ eexpr = TConst (TFloat f) }] ->
  113. let f = float_of_string f in
  114. (match classify_float f with
  115. | FP_infinite | FP_nan ->
  116. None
  117. | _ when f <= Int32.to_float Int32.min_int -. 1. || f >= Int32.to_float Int32.max_int ->
  118. None (* out range, keep platform-specific behavior *)
  119. | _ ->
  120. Some { eexpr = TConst (TInt (Int32.of_float (ceil f))); etype = com.basic.tint; epos = p })
  121. | ([],"Math"),"floor",[{ eexpr = TConst (TFloat f) }] ->
  122. let f = float_of_string f in
  123. (match classify_float f with
  124. | FP_infinite | FP_nan ->
  125. None
  126. | _ when f <= Int32.to_float Int32.min_int || f >= Int32.to_float Int32.max_int +. 1. ->
  127. None (* out range, keep platform-specific behavior *)
  128. | _ ->
  129. Some { eexpr = TConst (TInt (Int32.of_float (floor f))); etype = com.basic.tint; epos = p })
  130. | (["cs"],"Lib"),("fixed" | "checked" | "unsafe"),[e] ->
  131. Some (mk_untyped_call ("__" ^ field ^ "__") p [e])
  132. | (["cs"],"Lib"),("lock"),[obj;block] ->
  133. Some (mk_untyped_call ("__lock__") p [obj;mk_block block])
  134. | (["java"],"Lib"),("lock"),[obj;block] ->
  135. Some (mk_untyped_call ("__lock__") p [obj;mk_block block])
  136. | _ ->
  137. None
  138. let api_inline ctx c field params p = match c.cl_path, field, params with
  139. | ([],"Std"),"is",[o;t] | (["js"],"Boot"),"__instanceof",[o;t] when ctx.com.platform = Js ->
  140. let mk_local ctx n t pos =
  141. mk (TLocal (try
  142. PMap.find n ctx.locals
  143. with _ ->
  144. let v = add_local ctx n t in
  145. v.v_meta <- [Meta.Unbound,[],p];
  146. v
  147. )) t pos in
  148. let tstring = ctx.com.basic.tstring in
  149. let tbool = ctx.com.basic.tbool in
  150. let tint = ctx.com.basic.tint in
  151. let is_trivial e =
  152. match e.eexpr with
  153. | TConst _ | TLocal _ -> true
  154. | _ -> false
  155. in
  156. let typeof t =
  157. let tof = mk_local ctx "__typeof__" (tfun [o.etype] tstring) p in
  158. let tof = mk (TCall (tof, [o])) tstring p in
  159. mk (TBinop (Ast.OpEq, tof, (mk (TConst (TString t)) tstring p))) tbool p
  160. in
  161. (match t.eexpr with
  162. (* generate simple typeof checks for basic types *)
  163. | TTypeExpr (TClassDecl ({ cl_path = [],"String" })) -> Some (typeof "string")
  164. | TTypeExpr (TAbstractDecl ({ a_path = [],"Bool" })) -> Some (typeof "boolean")
  165. | TTypeExpr (TAbstractDecl ({ a_path = [],"Float" })) -> Some (typeof "number")
  166. | TTypeExpr (TAbstractDecl ({ a_path = [],"Int" })) when is_trivial o ->
  167. (* generate (o|0) === o check *)
  168. let teq = mk_local ctx "__strict_eq__" (tfun [tint; tint] tbool) p in
  169. let lhs = mk (TBinop (Ast.OpOr, o, mk (TConst (TInt Int32.zero)) tint p)) tint p in
  170. Some (mk (TCall (teq, [lhs; o])) tbool p)
  171. | TTypeExpr (TClassDecl ({ cl_path = [],"Array" })) ->
  172. (* generate (o instanceof Array) && o.__enum__ == null check *)
  173. let iof = mk_local ctx "__instanceof__" (tfun [o.etype;t.etype] tbool) p in
  174. let iof = mk (TCall (iof, [o; t])) tbool p in
  175. let enum = mk (TField (o, FDynamic "__enum__")) (mk_mono()) p in
  176. let null = mk (TConst TNull) (mk_mono()) p in
  177. let not_enum = mk (TBinop (Ast.OpEq, enum, null)) tbool p in
  178. Some (mk (TBinop (Ast.OpBoolAnd, iof, not_enum)) tbool p)
  179. | _ ->
  180. None)
  181. | (["cs" | "java"],"Lib"),("nativeArray"),[{ eexpr = TArrayDecl args } as edecl; _]
  182. | (["haxe";"ds";"_Vector"],"Vector_Impl_"),("fromArrayCopy"),[{ eexpr = TArrayDecl args } as edecl] -> (try
  183. let platf = match ctx.com.platform with
  184. | Cs -> "cs"
  185. | Java -> "java"
  186. | _ -> raise Exit
  187. in
  188. let mpath = if field = "fromArrayCopy" then
  189. (["haxe";"ds"],"Vector")
  190. else
  191. ([platf],"NativeArray")
  192. in
  193. let m = ctx.g.do_load_module ctx mpath null_pos in
  194. let main = List.find (function | TClassDecl _ | TAbstractDecl _ -> true | _ -> false) m.m_types in
  195. let t = match follow edecl.etype, main with
  196. | TInst({ cl_path = [],"Array" }, [t]), TClassDecl(cl) ->
  197. TInst(cl,[t])
  198. | TInst({ cl_path = [],"Array" }, [t]), TAbstractDecl(a) ->
  199. TAbstract(a,[t])
  200. | _ -> assert false
  201. in
  202. Some ({ (mk_untyped_call "__array__" p args) with etype = t })
  203. with | Exit ->
  204. None)
  205. | _ ->
  206. api_inline2 ctx.com c field params p
  207. (* ---------------------------------------------------------------------- *)
  208. (* INLINING *)
  209. type in_local = {
  210. i_var : tvar;
  211. i_subst : tvar;
  212. mutable i_captured : bool;
  213. mutable i_write : bool;
  214. mutable i_read : int;
  215. mutable i_force_temp : bool;
  216. }
  217. let inline_default_config cf t =
  218. (* type substitution on both class and function type parameters *)
  219. let rec get_params c pl =
  220. match c.cl_super with
  221. | None -> c.cl_params, pl
  222. | Some (csup,spl) ->
  223. let spl = (match apply_params c.cl_params pl (TInst (csup,spl)) with
  224. | TInst (_,pl) -> pl
  225. | _ -> assert false
  226. ) in
  227. let ct, cpl = get_params csup spl in
  228. c.cl_params @ ct, pl @ cpl
  229. in
  230. let tparams = (match follow t with
  231. | TInst (c,pl) -> get_params c pl
  232. | _ -> ([],[]))
  233. in
  234. let pmonos = List.map (fun _ -> mk_mono()) cf.cf_params in
  235. let tmonos = snd tparams @ pmonos in
  236. let tparams = fst tparams @ cf.cf_params in
  237. tparams <> [], apply_params tparams tmonos
  238. let rec type_inline ctx cf f ethis params tret config p ?(self_calling_closure=false) force =
  239. (* perform some specific optimization before we inline the call since it's not possible to detect at final optimization time *)
  240. try
  241. let cl = (match follow ethis.etype with
  242. | TInst (c,_) -> c
  243. | TAnon a -> (match !(a.a_status) with Statics c -> c | _ -> raise Exit)
  244. | _ -> raise Exit
  245. ) in
  246. (match api_inline ctx cl cf.cf_name params p with
  247. | None -> raise Exit
  248. | Some e -> Some e)
  249. with Exit ->
  250. let has_params,map_type = match config with Some config -> config | None -> inline_default_config cf ethis.etype in
  251. (* locals substitution *)
  252. let locals = Hashtbl.create 0 in
  253. let local v =
  254. try
  255. Hashtbl.find locals v.v_id
  256. with Not_found ->
  257. let v' = alloc_var v.v_name v.v_type in
  258. if Meta.has Meta.Unbound v.v_meta then v'.v_meta <- [Meta.Unbound,[],p];
  259. let i = {
  260. i_var = v;
  261. i_subst = v';
  262. i_captured = false;
  263. i_write = false;
  264. i_force_temp = false;
  265. i_read = 0;
  266. } in
  267. i.i_subst.v_meta <- v.v_meta;
  268. Hashtbl.add locals v.v_id i;
  269. Hashtbl.add locals i.i_subst.v_id i;
  270. i
  271. in
  272. let in_local_fun = ref false in
  273. let read_local v =
  274. let l = try
  275. Hashtbl.find locals v.v_id
  276. with Not_found ->
  277. (* make sure to duplicate unbound inline variable to prevent dependency leak when unifying monomorph *)
  278. if has_meta Meta.Unbound v.v_meta then local v else
  279. {
  280. i_var = v;
  281. i_subst = v;
  282. i_captured = false;
  283. i_write = false;
  284. i_force_temp = false;
  285. i_read = 0;
  286. }
  287. in
  288. if !in_local_fun then l.i_captured <- true;
  289. l
  290. in
  291. (* use default values for null/unset arguments *)
  292. let rec loop pl al first =
  293. match pl, al with
  294. | _, [] -> []
  295. | e :: pl, (v, opt) :: al ->
  296. (*
  297. if we pass a Null<T> var to an inlined method that needs a T.
  298. we need to force a local var to be created on some platforms.
  299. *)
  300. if ctx.com.config.pf_static && not (is_nullable v.v_type) && is_null e.etype then (local v).i_force_temp <- true;
  301. (*
  302. if we cast from Dynamic, create a local var as well to do the cast
  303. once and allow DCE to perform properly.
  304. *)
  305. if v.v_type != t_dynamic && follow e.etype == t_dynamic then (local v).i_write <- true;
  306. (match e.eexpr, opt with
  307. | TConst TNull , Some c -> mk (TConst c) v.v_type e.epos
  308. (*
  309. This is really weird and should be reviewed again. The problem is that we cannot insert a TCast here because
  310. the abstract `this` value could be written to, which is not possible if it is wrapped in a cast.
  311. The original problem here is that we do not generate a temporary variable and thus mute the type of the
  312. `this` variable, which leads to unification errors down the line. See issues #2236 and #3713.
  313. *)
  314. (* | _ when first && (Meta.has Meta.Impl cf.cf_meta) -> {e with etype = v.v_type} *)
  315. | _ -> e) :: loop pl al false
  316. | [], (v,opt) :: al ->
  317. (mk (TConst (match opt with None -> TNull | Some c -> c)) v.v_type p) :: loop [] al false
  318. in
  319. (*
  320. Build the expr/var subst list
  321. *)
  322. let ethis = (match ethis.eexpr with TConst TSuper -> { ethis with eexpr = TConst TThis } | _ -> ethis) in
  323. let vthis = alloc_var "_this" ethis.etype in
  324. let inlined_vars = List.map2 (fun e (v,_) ->
  325. let l = local v in
  326. if has_side_effect e then l.i_force_temp <- true; (* force tmp var *)
  327. l, e
  328. ) (ethis :: loop params f.tf_args true) ((vthis,None) :: f.tf_args) in
  329. let inlined_vars = List.rev inlined_vars in
  330. (*
  331. here, we try to eliminate final returns from the expression tree.
  332. However, this is not entirely correct since we don't yet correctly propagate
  333. the type of returned expressions upwards ("return" expr itself being Dynamic).
  334. We also substitute variables with fresh ones that might be renamed at later stage.
  335. *)
  336. let opt f = function
  337. | None -> None
  338. | Some e -> Some (f e)
  339. in
  340. let has_vars = ref false in
  341. let in_loop = ref false in
  342. let cancel_inlining = ref false in
  343. let has_return_value = ref false in
  344. let ret_val = (match follow f.tf_type with TAbstract ({ a_path = ([],"Void") },[]) -> false | _ -> true) in
  345. let map_pos = if self_calling_closure then (fun e -> e) else (fun e -> { e with epos = p }) in
  346. let rec map term e =
  347. let po = e.epos in
  348. let e = map_pos e in
  349. match e.eexpr with
  350. | TLocal v ->
  351. let l = read_local v in
  352. l.i_read <- l.i_read + (if !in_loop then 2 else 1);
  353. (* never inline a function which contain a delayed macro because its bound
  354. to its variables and not the calling method *)
  355. if v.v_name = "__dollar__delay_call" then cancel_inlining := true;
  356. let e = { e with eexpr = TLocal l.i_subst } in
  357. if Meta.has Meta.This v.v_meta then mk (TCast(e,None)) v.v_type e.epos else e
  358. | TConst TThis ->
  359. let l = read_local vthis in
  360. l.i_read <- l.i_read + (if !in_loop then 2 else 1);
  361. { e with eexpr = TLocal l.i_subst }
  362. | TVar (v,eo) ->
  363. has_vars := true;
  364. { e with eexpr = TVar ((local v).i_subst,opt (map false) eo)}
  365. | TReturn eo when not !in_local_fun ->
  366. if not term then error "Cannot inline a not final return" po;
  367. (match eo with
  368. | None -> mk (TConst TNull) f.tf_type p
  369. | Some e ->
  370. has_return_value := true;
  371. map term e)
  372. | TFor (v,e1,e2) ->
  373. let i = local v in
  374. let e1 = map false e1 in
  375. let old = !in_loop in
  376. in_loop := true;
  377. let e2 = map false e2 in
  378. in_loop := old;
  379. { e with eexpr = TFor (i.i_subst,e1,e2) }
  380. | TWhile (cond,eloop,flag) ->
  381. let cond = map false cond in
  382. let old = !in_loop in
  383. in_loop := true;
  384. let eloop = map false eloop in
  385. in_loop := old;
  386. { e with eexpr = TWhile (cond,eloop,flag) }
  387. | TSwitch (e1,cases,def) when term ->
  388. let term = term && (def <> None || is_exhaustive e1) in
  389. let cases = List.map (fun (el,e) ->
  390. let el = List.map (map false) el in
  391. el, map term e
  392. ) cases in
  393. let def = opt (map term) def in
  394. { e with eexpr = TSwitch (map false e1,cases,def); etype = if ret_val then unify_min ctx ((List.map snd cases) @ (match def with None -> [] | Some e -> [e])) else e.etype }
  395. | TTry (e1,catches) ->
  396. { e with eexpr = TTry (map term e1,List.map (fun (v,e) ->
  397. let lv = (local v).i_subst in
  398. let e = map term e in
  399. lv,e
  400. ) catches); etype = if term && ret_val then unify_min ctx (e1::List.map snd catches) else e.etype }
  401. | TBlock l ->
  402. let old = save_locals ctx in
  403. let t = ref e.etype in
  404. let rec has_term_return e =
  405. let rec loop e =
  406. let r = match e.eexpr with
  407. | TReturn _ -> true
  408. | TIf (_,_,None) | TSwitch (_,_,None) | TFor _ | TWhile (_,_,NormalWhile) -> false (* we might not enter this code at all *)
  409. | TTry (a, catches) -> List.for_all has_term_return (a :: List.map snd catches)
  410. | TIf (cond,a,Some b) -> has_term_return cond || (has_term_return a && has_term_return b)
  411. | TSwitch (cond,cases,Some def) -> has_term_return cond || List.for_all has_term_return (def :: List.map snd cases)
  412. | TBinop (OpBoolAnd,a,b) -> has_term_return a && has_term_return b
  413. | _ -> Type.iter loop e; false
  414. in
  415. if r then raise Exit
  416. in
  417. try loop e; false with Exit -> true
  418. in
  419. let rec loop = function
  420. | [] when term ->
  421. t := mk_mono();
  422. [mk (TConst TNull) (!t) p]
  423. | [] -> []
  424. | [e] ->
  425. let e = map term e in
  426. if term then t := e.etype;
  427. [e]
  428. | ({ eexpr = TIf (cond,e1,None) } as e) :: l when term && has_term_return e1 ->
  429. loop [{ e with eexpr = TIf (cond,e1,Some (mk (TBlock l) e.etype e.epos)); epos = punion e.epos (match List.rev l with e :: _ -> e.epos | [] -> assert false) }]
  430. | e :: l ->
  431. let e = map false e in
  432. e :: loop l
  433. in
  434. let l = loop l in
  435. old();
  436. { e with eexpr = TBlock l; etype = !t }
  437. | TIf (econd,eif,Some eelse) when term ->
  438. let econd = map false econd in
  439. let eif = map term eif in
  440. let eelse = map term eelse in
  441. { e with eexpr = TIf(econd,eif,Some eelse); etype = if ret_val then unify_min ctx [eif;eelse] else e.etype }
  442. | TParenthesis e1 ->
  443. let e1 = map term e1 in
  444. mk (TParenthesis e1) e1.etype e.epos
  445. | TUnop ((Increment|Decrement) as op,flag,({ eexpr = TLocal v } as e1)) ->
  446. let l = read_local v in
  447. l.i_write <- true;
  448. {e with eexpr = TUnop(op,flag,{e1 with eexpr = TLocal l.i_subst})}
  449. | TBinop ((OpAssign | OpAssignOp _) as op,({ eexpr = TLocal v } as e1),e2) ->
  450. let l = read_local v in
  451. l.i_write <- true;
  452. let e2 = map false e2 in
  453. {e with eexpr = TBinop(op,{e1 with eexpr = TLocal l.i_subst},e2)}
  454. | TObjectDecl fl ->
  455. let fl = List.map (fun (s,e) -> s,map false e) fl in
  456. begin match follow e.etype with
  457. | TAnon an when (match !(an.a_status) with Const -> true | _ -> false) ->
  458. {e with eexpr = TObjectDecl fl; etype = TAnon { an with a_status = ref Closed}}
  459. | _ ->
  460. {e with eexpr = TObjectDecl fl}
  461. end
  462. | TFunction f ->
  463. (match f.tf_args with [] -> () | _ -> has_vars := true);
  464. let old = save_locals ctx and old_fun = !in_local_fun in
  465. let args = List.map (function(v,c) -> (local v).i_subst, c) f.tf_args in
  466. in_local_fun := true;
  467. let expr = map false f.tf_expr in
  468. in_local_fun := old_fun;
  469. old();
  470. { e with eexpr = TFunction { tf_args = args; tf_expr = expr; tf_type = f.tf_type } }
  471. | TConst TSuper ->
  472. error "Cannot inline function containing super" po
  473. | TMeta(m,e1) ->
  474. let e1 = map term e1 in
  475. {e with eexpr = TMeta(m,e1)}
  476. | _ ->
  477. Type.map_expr (map false) e
  478. in
  479. let e = map true f.tf_expr in
  480. (*
  481. if variables are not written and used with a const value, let's substitute
  482. with the actual value, either create a temp var
  483. *)
  484. let subst = ref PMap.empty in
  485. let is_constant e =
  486. let rec loop e =
  487. match e.eexpr with
  488. | TLocal _
  489. | TConst TThis (* not really, but should not be move inside a function body *)
  490. -> raise Exit
  491. | TField (_,FEnum _)
  492. | TTypeExpr _
  493. | TConst _ -> ()
  494. | _ ->
  495. Type.iter loop e
  496. in
  497. try loop e; true with Exit -> false
  498. in
  499. let is_writable e =
  500. match e.eexpr with
  501. | TField _ | TEnumParameter _ | TLocal _ | TArray _ -> true
  502. | _ -> false
  503. in
  504. let force = ref force in
  505. let vars = List.fold_left (fun acc (i,e) ->
  506. let flag = not i.i_force_temp && (match e.eexpr with
  507. | TLocal v when Meta.has Meta.This v.v_meta -> true
  508. | TLocal _ | TConst _ -> not i.i_write
  509. | TFunction _ -> if i.i_write then error "Cannot modify a closure parameter inside inline method" p; true
  510. | _ -> not i.i_write && i.i_read <= 1
  511. ) in
  512. let flag = flag && (not i.i_captured || is_constant e) in
  513. (* force inlining if we modify 'this' *)
  514. if i.i_write && (Meta.has Meta.This i.i_var.v_meta) then force := true;
  515. (* force inlining of 'this' variable if it is written *)
  516. let flag = if not flag && (Meta.has Meta.This i.i_var.v_meta) && i.i_write then begin
  517. if not (is_writable e) then error "Cannot modify the abstract value, store it into a local first" p;
  518. true
  519. end else flag in
  520. if flag then begin
  521. subst := PMap.add i.i_subst.v_id e !subst;
  522. acc
  523. end else
  524. (i.i_subst,Some e) :: acc
  525. ) [] inlined_vars in
  526. let subst = !subst in
  527. let rec inline_params e =
  528. match e.eexpr with
  529. | TLocal v -> (try PMap.find v.v_id subst with Not_found -> e)
  530. | _ -> Type.map_expr inline_params e
  531. in
  532. let e = (if PMap.is_empty subst then e else inline_params e) in
  533. let init = match vars with [] -> None | l -> Some l in
  534. (*
  535. If we have local variables and returning a value, then this will result in
  536. unoptimized JS code, so let's instead skip inlining.
  537. This could be fixed with better post process code cleanup (planed)
  538. *)
  539. if !cancel_inlining || (not (Common.defined ctx.com Define.Analyzer) && Common.platform ctx.com Js && not !force && (init <> None || !has_vars)) then
  540. None
  541. else
  542. let wrap e =
  543. (* we can't mute the type of the expression because it is not correct to do so *)
  544. let etype = if has_params then map_type e.etype else e.etype in
  545. (* if the expression is "untyped" and we don't want to unify it accidentally ! *)
  546. try (match follow e.etype with
  547. | TMono _ | TInst ({cl_kind = KTypeParameter _ },_) ->
  548. (match follow tret with
  549. | TAbstract ({ a_path = [],"Void" },_) -> e
  550. | _ -> raise (Unify_error []))
  551. | _ ->
  552. type_eq (if ctx.com.config.pf_static then EqDoNotFollowNull else EqStrict) etype tret;
  553. e)
  554. with Unify_error _ ->
  555. mk (TCast (e,None)) tret e.epos
  556. in
  557. let e = (match e.eexpr, init with
  558. | _, None when not !has_return_value ->
  559. {e with etype = tret}
  560. | TBlock [e] , None -> wrap e
  561. | _ , None -> wrap e
  562. | TBlock l, Some vl ->
  563. let el_v = List.map (fun (v,eo) -> mk (TVar (v,eo)) ctx.t.tvoid e.epos) vl in
  564. mk (TBlock (el_v @ l)) tret e.epos
  565. | _, Some vl ->
  566. let el_v = List.map (fun (v,eo) -> mk (TVar (v,eo)) ctx.t.tvoid e.epos) vl in
  567. mk (TBlock (el_v @ [e])) tret e.epos
  568. ) in
  569. let inline_meta e meta = match meta with
  570. | Meta.Deprecated,_,_ -> mk (TMeta(meta,e)) e.etype e.epos
  571. | _ -> e
  572. in
  573. let e = List.fold_left inline_meta e cf.cf_meta in
  574. (* we need to replace type-parameters that were used in the expression *)
  575. if not has_params then
  576. Some e
  577. else
  578. let mt = map_type cf.cf_type in
  579. let unify_func () = unify_raise ctx mt (TFun (List.map (fun e -> "",false,e.etype) params,tret)) p in
  580. (match follow ethis.etype with
  581. | TAnon a -> (match !(a.a_status) with
  582. | Statics {cl_kind = KAbstractImpl a } when Meta.has Meta.Impl cf.cf_meta ->
  583. if cf.cf_name <> "_new" then begin
  584. (* the first argument must unify with a_this for abstract implementation functions *)
  585. let tb = (TFun(("",false,map_type a.a_this) :: List.map (fun e -> "",false,e.etype) (List.tl params),tret)) in
  586. unify_raise ctx mt tb p
  587. end
  588. | _ -> unify_func())
  589. | _ -> unify_func());
  590. (*
  591. this is very expensive since we are building the substitution list for
  592. every expression, but hopefully in such cases the expression size is small
  593. *)
  594. let vars = Hashtbl.create 0 in
  595. let map_var v =
  596. if not (Hashtbl.mem vars v.v_id) then begin
  597. Hashtbl.add vars v.v_id ();
  598. v.v_type <- map_type v.v_type;
  599. end;
  600. v
  601. in
  602. let rec map_expr_type e = Type.map_expr_type map_expr_type map_type map_var e in
  603. Some (map_expr_type e)
  604. (* ---------------------------------------------------------------------- *)
  605. (* LOOPS *)
  606. let rec optimize_for_loop ctx (i,pi) e1 e2 p =
  607. let t_void = ctx.t.tvoid in
  608. let t_int = ctx.t.tint in
  609. let lblock el = Some (mk (TBlock el) t_void p) in
  610. let mk_field e n =
  611. TField (e,try quick_field e.etype n with Not_found -> assert false)
  612. in
  613. let gen_int_iter pt f_get f_length =
  614. let i = add_local ctx i pt in
  615. let index = gen_local ctx t_int in
  616. let arr, avars = (match e1.eexpr with
  617. | TLocal _ -> e1, None
  618. | _ ->
  619. let atmp = gen_local ctx e1.etype in
  620. mk (TLocal atmp) e1.etype e1.epos, (Some (atmp,Some e1))
  621. ) in
  622. let iexpr = mk (TLocal index) t_int p in
  623. let e2 = type_expr ctx e2 NoValue in
  624. let aget = mk (TVar (i,Some (f_get arr iexpr pt p))) t_void pi in
  625. let incr = mk (TUnop (Increment,Prefix,iexpr)) t_int p in
  626. let block = match e2.eexpr with
  627. | TBlock el -> mk (TBlock (aget :: incr :: el)) t_void e2.epos
  628. | _ -> mk (TBlock [aget;incr;e2]) t_void p
  629. in
  630. let ivar = Some (mk (TConst (TInt 0l)) t_int p) in
  631. let elength = f_length arr p in
  632. let el = [mk (TWhile (
  633. mk (TBinop (OpLt, iexpr, elength)) ctx.t.tbool p,
  634. block,
  635. NormalWhile
  636. )) t_void p;
  637. ] in
  638. let el = match avars with None -> el | Some (v,eo) -> (mk (TVar (v,eo)) t_void p) :: el in
  639. let el = (mk (TVar (index,ivar)) t_void p) :: el in
  640. lblock el
  641. in
  642. let get_next_array_element arr iexpr pt p =
  643. (mk (TArray (arr,iexpr)) pt p)
  644. in
  645. let get_array_length arr p =
  646. mk (mk_field arr "length") ctx.com.basic.tint p
  647. in
  648. match e1.eexpr, follow e1.etype with
  649. | TNew ({ cl_path = ([],"IntIterator") },[],[i1;i2]) , _ ->
  650. let max = (match i1.eexpr , i2.eexpr with
  651. | TConst (TInt a), TConst (TInt b) when Int32.compare b a < 0 -> error "Range operator can't iterate backwards" p
  652. | _, TConst _ | _ , TLocal _ -> None
  653. | _ -> Some (gen_local ctx t_int)
  654. ) in
  655. let tmp = gen_local ctx t_int in
  656. let i = add_local ctx i t_int in
  657. let rec check e =
  658. match e.eexpr with
  659. | TBinop (OpAssign,{ eexpr = TLocal l },_)
  660. | TBinop (OpAssignOp _,{ eexpr = TLocal l },_)
  661. | TUnop (Increment,_,{ eexpr = TLocal l })
  662. | TUnop (Decrement,_,{ eexpr = TLocal l }) when l == i ->
  663. error "Loop variable cannot be modified" e.epos
  664. | _ ->
  665. Type.iter check e
  666. in
  667. let e2 = type_expr ctx e2 NoValue in
  668. check e2;
  669. let etmp = mk (TLocal tmp) t_int p in
  670. let incr = mk (TUnop (Increment,Postfix,etmp)) t_int p in
  671. let init = mk (TVar (i,Some incr)) t_void pi in
  672. let block = match e2.eexpr with
  673. | TBlock el -> mk (TBlock (init :: el)) t_void e2.epos
  674. | _ -> mk (TBlock [init;e2]) t_void p
  675. in
  676. (*
  677. force locals to be of Int type (to prevent Int/UInt issues)
  678. *)
  679. let i2 = match follow i2.etype with
  680. | TAbstract ({ a_path = ([],"Int") }, []) -> i2
  681. | _ -> { i2 with eexpr = TCast(i2, None); etype = t_int }
  682. in
  683. (match max with
  684. | None ->
  685. lblock [
  686. mk (TVar (tmp,Some i1)) t_void p;
  687. mk (TWhile (
  688. mk (TBinop (OpLt, etmp, i2)) ctx.t.tbool p,
  689. block,
  690. NormalWhile
  691. )) t_void p;
  692. ]
  693. | Some max ->
  694. lblock [
  695. mk (TVar (tmp,Some i1)) t_void p;
  696. mk (TVar (max,Some i2)) t_void p;
  697. mk (TWhile (
  698. mk (TBinop (OpLt, etmp, mk (TLocal max) t_int p)) ctx.t.tbool p,
  699. block,
  700. NormalWhile
  701. )) t_void p;
  702. ])
  703. | TArrayDecl el, TInst({ cl_path = [],"Array" },[pt]) when false ->
  704. begin try
  705. let num_expr = ref 0 in
  706. let rec loop e = match fst e with
  707. | EContinue | EBreak ->
  708. raise Exit
  709. | _ ->
  710. incr num_expr;
  711. Ast.map_expr loop e
  712. in
  713. ignore(loop e2);
  714. let v = add_local ctx i pt in
  715. let e2 = type_expr ctx e2 NoValue in
  716. let cost = (List.length el) * !num_expr in
  717. let max_cost = try
  718. int_of_string (Common.defined_value ctx.com Define.LoopUnrollMaxCost)
  719. with Not_found ->
  720. 250
  721. in
  722. if cost > max_cost then raise Exit;
  723. let eloc = mk (TLocal v) v.v_type p in
  724. let el = List.map (fun e ->
  725. let e_assign = mk (TBinop(OpAssign,eloc,e)) e.etype e.epos in
  726. concat e_assign e2
  727. ) el in
  728. let ev = mk (TVar(v, None)) ctx.t.tvoid p in
  729. Some (mk (TBlock (ev :: el)) ctx.t.tvoid p)
  730. with Exit ->
  731. gen_int_iter pt get_next_array_element get_array_length
  732. end
  733. | _ , TInst({ cl_path = [],"Array" },[pt])
  734. | _ , TInst({ cl_path = ["flash"],"Vector" },[pt]) ->
  735. gen_int_iter pt get_next_array_element get_array_length
  736. | _ , TInst({ cl_array_access = Some pt } as c,pl) when (try match follow (PMap.find "length" c.cl_fields).cf_type with TAbstract ({ a_path = [],"Int" },[]) -> true | _ -> false with Not_found -> false) && not (PMap.mem "iterator" c.cl_fields) ->
  737. gen_int_iter (apply_params c.cl_params pl pt) get_next_array_element get_array_length
  738. | _, TAbstract({a_impl = Some c} as a,tl) ->
  739. begin try
  740. let cf_length = PMap.find "get_length" c.cl_statics in
  741. let get_length e p =
  742. make_static_call ctx c cf_length (apply_params a.a_params tl) [e] ctx.com.basic.tint p
  743. in
  744. begin match follow cf_length.cf_type with
  745. | TFun(_,tr) ->
  746. begin match follow tr with
  747. | TAbstract({a_path = [],"Int"},_) -> ()
  748. | _ -> raise Not_found
  749. end
  750. | _ ->
  751. raise Not_found
  752. end;
  753. begin try
  754. (* first try: do we have an @:arrayAccess getter field? *)
  755. let todo = mk (TConst TNull) ctx.t.tint p in
  756. let cf,_,r,_,_ = (!find_array_access_raise_ref) ctx a tl todo None p in
  757. let get_next e_base e_index t p =
  758. make_static_call ctx c cf (apply_params a.a_params tl) [e_base;e_index] r p
  759. in
  760. gen_int_iter r get_next get_length
  761. with Not_found ->
  762. (* second try: do we have @:arrayAccess on the abstract itself? *)
  763. if not (Meta.has Meta.ArrayAccess a.a_meta) then raise Not_found;
  764. (* let's allow this only for core-type abstracts *)
  765. if not (Meta.has Meta.CoreType a.a_meta) then raise Not_found;
  766. (* in which case we assume that a singular type parameter is the element type *)
  767. let t = match tl with [t] -> t | _ -> raise Not_found in
  768. gen_int_iter t get_next_array_element get_length
  769. end with Not_found ->
  770. None
  771. end
  772. | _ , TInst ({ cl_kind = KGenericInstance ({ cl_path = ["haxe";"ds"],"GenericStack" },[t]) } as c,[]) ->
  773. let tcell = (try (PMap.find "head" c.cl_fields).cf_type with Not_found -> assert false) in
  774. let i = add_local ctx i t in
  775. let cell = gen_local ctx tcell in
  776. let cexpr = mk (TLocal cell) tcell p in
  777. let e2 = type_expr ctx e2 NoValue in
  778. let evar = mk (TVar (i,Some (mk (mk_field cexpr "elt") t p))) t_void pi in
  779. let enext = mk (TBinop (OpAssign,cexpr,mk (mk_field cexpr "next") tcell p)) tcell p in
  780. let block = match e2.eexpr with
  781. | TBlock el -> mk (TBlock (evar :: enext :: el)) t_void e2.epos
  782. | _ -> mk (TBlock [evar;enext;e2]) t_void p
  783. in
  784. lblock [
  785. mk (TVar (cell,Some (mk (mk_field e1 "head") tcell p))) t_void p;
  786. mk (TWhile (
  787. mk (TBinop (OpNotEq, cexpr, mk (TConst TNull) tcell p)) ctx.t.tbool p,
  788. block,
  789. NormalWhile
  790. )) t_void p
  791. ]
  792. | _ ->
  793. None
  794. let optimize_for_loop_iterator ctx v e1 e2 p =
  795. let c,tl = (match follow e1.etype with TInst (c,pl) -> c,pl | _ -> raise Exit) in
  796. let _, _, fhasnext = (try raw_class_field (fun cf -> apply_params c.cl_params tl cf.cf_type) c tl "hasNext" with Not_found -> raise Exit) in
  797. if fhasnext.cf_kind <> Method MethInline then raise Exit;
  798. let tmp = gen_local ctx e1.etype in
  799. let eit = mk (TLocal tmp) e1.etype p in
  800. let ehasnext = make_call ctx (mk (TField (eit,FInstance (c, tl, fhasnext))) (TFun([],ctx.t.tbool)) p) [] ctx.t.tbool p in
  801. let enext = mk (TVar (v,Some (make_call ctx (mk (TField (eit,quick_field_dynamic eit.etype "next")) (TFun ([],v.v_type)) p) [] v.v_type p))) ctx.t.tvoid p in
  802. let eblock = (match e2.eexpr with
  803. | TBlock el -> { e2 with eexpr = TBlock (enext :: el) }
  804. | _ -> mk (TBlock [enext;e2]) ctx.t.tvoid p
  805. ) in
  806. mk (TBlock [
  807. mk (TVar (tmp,Some e1)) ctx.t.tvoid p;
  808. mk (TWhile (ehasnext,eblock,NormalWhile)) ctx.t.tvoid p
  809. ]) ctx.t.tvoid p
  810. (* ---------------------------------------------------------------------- *)
  811. (* SANITIZE *)
  812. (*
  813. makes sure that when an AST get generated to source code, it will not
  814. generate expressions that evaluate differently. It is then necessary to
  815. add parenthesises around some binary expressions when the AST does not
  816. correspond to the natural operand priority order for the platform
  817. *)
  818. (*
  819. this is the standard C++ operator precedence, which is also used by both JS and PHP
  820. *)
  821. let standard_precedence op =
  822. let left = true and right = false in
  823. match op with
  824. | OpMult | OpDiv | OpMod -> 5, left
  825. | OpAdd | OpSub -> 6, left
  826. | OpShl | OpShr | OpUShr -> 7, left
  827. | OpLt | OpLte | OpGt | OpGte -> 8, left
  828. | OpEq | OpNotEq -> 9, left
  829. | OpAnd -> 10, left
  830. | OpXor -> 11, left
  831. | OpOr -> 12, left
  832. | OpInterval -> 13, right (* haxe specific *)
  833. | OpBoolAnd -> 14, left
  834. | OpBoolOr -> 15, left
  835. | OpArrow -> 16, left
  836. | OpAssignOp OpAssign -> 17, right (* mimics ?: *)
  837. | OpAssign | OpAssignOp _ -> 18, right
  838. let rec need_parent e =
  839. match e.eexpr with
  840. | TConst _ | TLocal _ | TArray _ | TField _ | TEnumParameter _ | TParenthesis _ | TMeta _ | TCall _ | TNew _ | TTypeExpr _ | TObjectDecl _ | TArrayDecl _ -> false
  841. | TCast (e,None) -> need_parent e
  842. | TCast _ | TThrow _ | TReturn _ | TTry _ | TSwitch _ | TFor _ | TIf _ | TWhile _ | TBinop _ | TContinue | TBreak
  843. | TBlock _ | TVar _ | TFunction _ | TUnop _ -> true
  844. let sanitize_expr com e =
  845. let parent e =
  846. match e.eexpr with
  847. | TParenthesis _ -> e
  848. | _ -> mk (TParenthesis e) e.etype e.epos
  849. in
  850. let block e =
  851. match e.eexpr with
  852. | TBlock _ -> e
  853. | _ -> mk (TBlock [e]) e.etype e.epos
  854. in
  855. let complex e =
  856. (* complex expressions are the one that once generated to source consists in several expressions *)
  857. match e.eexpr with
  858. | TVar _ (* needs to be put into blocks *)
  859. | TFor _ (* a temp var is needed for holding iterator *)
  860. | TCall ({ eexpr = TLocal { v_name = "__js__" } },_) (* we never know *)
  861. -> block e
  862. | _ -> e
  863. in
  864. (* tells if the printed expresssion ends with an if without else *)
  865. let rec has_if e =
  866. match e.eexpr with
  867. | TIf (_,_,None) -> true
  868. | TWhile (_,e,NormalWhile) -> has_if e
  869. | TFor (_,_,e) -> has_if e
  870. | _ -> false
  871. in
  872. match e.eexpr with
  873. | TConst TNull ->
  874. if com.config.pf_static && not (is_nullable e.etype) then begin
  875. let rec loop t = match follow t with
  876. | TMono _ -> () (* in these cases the null will cast to default value *)
  877. | TFun _ -> () (* this is a bit a particular case, maybe flash-specific actually *)
  878. (* TODO: this should use get_underlying_type, but we do not have access to Codegen here. *)
  879. | TAbstract(a,tl) when not (Meta.has Meta.CoreType a.a_meta) -> loop (apply_params a.a_params tl a.a_this)
  880. | _ -> com.error ("On static platforms, null can't be used as basic type " ^ s_type (print_context()) e.etype) e.epos
  881. in
  882. loop e.etype
  883. end;
  884. e
  885. | TBinop (op,e1,e2) ->
  886. let swap op1 op2 =
  887. let p1, left1 = standard_precedence op1 in
  888. let p2, _ = standard_precedence op2 in
  889. left1 && p1 <= p2
  890. in
  891. let rec loop ee left =
  892. match ee.eexpr with
  893. | TBinop (op2,_,_) -> if left then not (swap op2 op) else swap op op2
  894. | TIf _ -> if left then not (swap (OpAssignOp OpAssign) op) else swap op (OpAssignOp OpAssign)
  895. | TCast (e,None) -> loop e left
  896. | _ -> false
  897. in
  898. let e1 = if loop e1 true then parent e1 else e1 in
  899. let e2 = if loop e2 false then parent e2 else e2 in
  900. { e with eexpr = TBinop (op,e1,e2) }
  901. | TUnop (op,mode,e1) ->
  902. let rec loop ee =
  903. match ee.eexpr with
  904. | TBinop _ | TIf _ | TUnop _ -> parent e1
  905. | TCast (e,None) -> loop e
  906. | _ -> e1
  907. in
  908. { e with eexpr = TUnop (op,mode,loop e1)}
  909. | TIf (e1,e2,eelse) ->
  910. let e1 = parent e1 in
  911. let e2 = (if (eelse <> None && has_if e2) || (match e2.eexpr with TIf _ -> true | _ -> false) then block e2 else complex e2) in
  912. let eelse = (match eelse with None -> None | Some e -> Some (complex e)) in
  913. { e with eexpr = TIf (e1,e2,eelse) }
  914. | TWhile (e1,e2,flag) ->
  915. let e1 = parent e1 in
  916. let e2 = complex e2 in
  917. { e with eexpr = TWhile (e1,e2,flag) }
  918. | TFor (v,e1,e2) ->
  919. let e2 = complex e2 in
  920. { e with eexpr = TFor (v,e1,e2) }
  921. | TFunction f ->
  922. let f = (match f.tf_expr.eexpr with
  923. | TBlock _ -> f
  924. | _ -> { f with tf_expr = block f.tf_expr }
  925. ) in
  926. { e with eexpr = TFunction f }
  927. | TCall (e2,args) ->
  928. if need_parent e2 then { e with eexpr = TCall(parent e2,args) } else e
  929. | TEnumParameter (e2,ef,i) ->
  930. if need_parent e2 then { e with eexpr = TEnumParameter(parent e2,ef,i) } else e
  931. | TField (e2,f) ->
  932. if need_parent e2 then { e with eexpr = TField(parent e2,f) } else e
  933. | TArray (e1,e2) ->
  934. if need_parent e1 then { e with eexpr = TArray(parent e1,e2) } else e
  935. | TTry (e1,catches) ->
  936. let e1 = block e1 in
  937. let catches = List.map (fun (v,e) -> v, block e) catches in
  938. { e with eexpr = TTry (e1,catches) }
  939. | TSwitch (e1,cases,def) ->
  940. let e1 = parent e1 in
  941. let cases = List.map (fun (el,e) -> el, complex e) cases in
  942. let def = (match def with None -> None | Some e -> Some (complex e)) in
  943. { e with eexpr = TSwitch (e1,cases,def) }
  944. | _ ->
  945. e
  946. let reduce_expr com e =
  947. match e.eexpr with
  948. | TSwitch (_,cases,_) ->
  949. List.iter (fun (cl,_) ->
  950. List.iter (fun e ->
  951. match e.eexpr with
  952. | TCall ({ eexpr = TField (_,FEnum _) },_) -> error "Not-constant enum in switch cannot be matched" e.epos
  953. | _ -> ()
  954. ) cl
  955. ) cases;
  956. e
  957. | TBlock l ->
  958. (match List.rev l with
  959. | [] -> e
  960. | ec :: l ->
  961. (* remove all no-ops : not-final constants in blocks *)
  962. match List.filter (fun e -> match e.eexpr with
  963. | TConst _
  964. | TBlock []
  965. | TObjectDecl [] ->
  966. false
  967. | _ ->
  968. true
  969. ) l with
  970. | [] -> ec
  971. | l -> { e with eexpr = TBlock (List.rev (ec :: l)) })
  972. | TParenthesis ec ->
  973. { ec with epos = e.epos }
  974. | TTry (e,[]) ->
  975. e
  976. | _ ->
  977. e
  978. let rec sanitize com e =
  979. sanitize_expr com (reduce_expr com (Type.map_expr (sanitize com) e))
  980. (* ---------------------------------------------------------------------- *)
  981. (* REDUCE *)
  982. let optimize_binop e op e1 e2 =
  983. let is_float t =
  984. match follow t with
  985. | TAbstract({ a_path = [],"Float" },_) -> true
  986. | _ -> false
  987. in
  988. let is_numeric t =
  989. match follow t with
  990. | TAbstract({ a_path = [],("Float"|"Int") },_) -> true
  991. | _ -> false
  992. in
  993. let check_float op f1 f2 =
  994. let f = op f1 f2 in
  995. let fstr = float_repres f in
  996. if (match classify_float f with FP_nan | FP_infinite -> false | _ -> float_of_string fstr = f) then { e with eexpr = TConst (TFloat fstr) } else e
  997. in
  998. (match e1.eexpr, e2.eexpr with
  999. | TConst (TInt 0l) , _ when op = OpAdd && is_numeric e2.etype -> e2
  1000. | TConst (TInt 1l) , _ when op = OpMult -> e2
  1001. | TConst (TFloat v) , _ when op = OpAdd && float_of_string v = 0. && is_float e2.etype -> e2
  1002. | TConst (TFloat v) , _ when op = OpMult && float_of_string v = 1. && is_float e2.etype -> e2
  1003. | _ , TConst (TInt 0l) when (match op with OpAdd -> is_numeric e1.etype | OpSub | OpShr | OpShl -> true | _ -> false) -> e1 (* bits operations might cause overflow *)
  1004. | _ , TConst (TInt 1l) when op = OpMult -> e1
  1005. | _ , TConst (TFloat v) when (match op with OpAdd | OpSub -> float_of_string v = 0. && is_float e1.etype | _ -> false) -> e1 (* bits operations might cause overflow *)
  1006. | _ , TConst (TFloat v) when op = OpMult && float_of_string v = 1. && is_float e1.etype -> e1
  1007. | TConst TNull, TConst TNull ->
  1008. (match op with
  1009. | OpEq -> { e with eexpr = TConst (TBool true) }
  1010. | OpNotEq -> { e with eexpr = TConst (TBool false) }
  1011. | _ -> e)
  1012. | TFunction _, TConst TNull ->
  1013. (match op with
  1014. | OpEq -> { e with eexpr = TConst (TBool false) }
  1015. | OpNotEq -> { e with eexpr = TConst (TBool true) }
  1016. | _ -> e)
  1017. | TConst TNull, TFunction _ ->
  1018. (match op with
  1019. | OpEq -> { e with eexpr = TConst (TBool false) }
  1020. | OpNotEq -> { e with eexpr = TConst (TBool true) }
  1021. | _ -> e)
  1022. | TConst (TInt a), TConst (TInt b) ->
  1023. let opt f = try { e with eexpr = TConst (TInt (f a b)) } with Exit -> e in
  1024. let check_overflow f =
  1025. opt (fun a b ->
  1026. let v = f (Int64.of_int32 a) (Int64.of_int32 b) in
  1027. let iv = Int64.to_int32 v in
  1028. if Int64.compare (Int64.of_int32 iv) v <> 0 then raise Exit;
  1029. iv
  1030. )
  1031. in
  1032. let ebool t =
  1033. { e with eexpr = TConst (TBool (t (Int32.compare a b) 0)) }
  1034. in
  1035. (match op with
  1036. | OpAdd -> check_overflow Int64.add
  1037. | OpSub -> check_overflow Int64.sub
  1038. | OpMult -> check_overflow Int64.mul
  1039. | OpDiv -> check_float ( /. ) (Int32.to_float a) (Int32.to_float b)
  1040. | OpAnd -> opt Int32.logand
  1041. | OpOr -> opt Int32.logor
  1042. | OpXor -> opt Int32.logxor
  1043. | OpShl -> opt (fun a b -> Int32.shift_left a (Int32.to_int b))
  1044. | OpShr -> opt (fun a b -> Int32.shift_right a (Int32.to_int b))
  1045. | OpUShr -> opt (fun a b -> Int32.shift_right_logical a (Int32.to_int b))
  1046. | OpEq -> ebool (=)
  1047. | OpNotEq -> ebool (<>)
  1048. | OpGt -> ebool (>)
  1049. | OpGte -> ebool (>=)
  1050. | OpLt -> ebool (<)
  1051. | OpLte -> ebool (<=)
  1052. | _ -> e)
  1053. | TConst ((TFloat _ | TInt _) as ca), TConst ((TFloat _ | TInt _) as cb) ->
  1054. let fa = (match ca with
  1055. | TFloat a -> float_of_string a
  1056. | TInt a -> Int32.to_float a
  1057. | _ -> assert false
  1058. ) in
  1059. let fb = (match cb with
  1060. | TFloat b -> float_of_string b
  1061. | TInt b -> Int32.to_float b
  1062. | _ -> assert false
  1063. ) in
  1064. let fop op = check_float op fa fb in
  1065. let ebool t =
  1066. { e with eexpr = TConst (TBool (t (compare fa fb) 0)) }
  1067. in
  1068. (match op with
  1069. | OpAdd -> fop (+.)
  1070. | OpDiv -> fop (/.)
  1071. | OpSub -> fop (-.)
  1072. | OpMult -> fop ( *. )
  1073. | OpEq -> ebool (=)
  1074. | OpNotEq -> ebool (<>)
  1075. | OpGt -> ebool (>)
  1076. | OpGte -> ebool (>=)
  1077. | OpLt -> ebool (<)
  1078. | OpLte -> ebool (<=)
  1079. | _ -> e)
  1080. | TConst (TBool a), TConst (TBool b) ->
  1081. let ebool f =
  1082. { e with eexpr = TConst (TBool (f a b)) }
  1083. in
  1084. (match op with
  1085. | OpEq -> ebool (=)
  1086. | OpNotEq -> ebool (<>)
  1087. | OpBoolAnd -> ebool (&&)
  1088. | OpBoolOr -> ebool (||)
  1089. | _ -> e)
  1090. | TConst a, TConst b when op = OpEq || op = OpNotEq ->
  1091. let ebool b =
  1092. { e with eexpr = TConst (TBool (if op = OpEq then b else not b)) }
  1093. in
  1094. (match a, b with
  1095. | TInt a, TFloat b | TFloat b, TInt a -> ebool (Int32.to_float a = float_of_string b)
  1096. | _ -> ebool (a = b))
  1097. | TConst (TBool a), _ ->
  1098. (match op with
  1099. | OpBoolAnd -> if a then e2 else { e with eexpr = TConst (TBool false) }
  1100. | OpBoolOr -> if a then { e with eexpr = TConst (TBool true) } else e2
  1101. | _ -> e)
  1102. | _ , TConst (TBool a) ->
  1103. (match op with
  1104. | OpBoolAnd when a -> e1
  1105. | OpBoolOr when not a -> e1
  1106. | _ -> e)
  1107. | TField (_,FEnum (e1,f1)), TField (_,FEnum (e2,f2)) when e1 == e2 ->
  1108. (match op with
  1109. | OpEq -> { e with eexpr = TConst (TBool (f1 == f2)) }
  1110. | OpNotEq -> { e with eexpr = TConst (TBool (f1 != f2)) }
  1111. | _ -> e)
  1112. | _, TCall ({ eexpr = TField (_,FEnum _) },_) | TCall ({ eexpr = TField (_,FEnum _) },_), _ ->
  1113. (match op with
  1114. | OpAssign -> e
  1115. | _ ->
  1116. error "You cannot directly compare enums with arguments. Use either 'switch' or 'Type.enumEq'" e.epos)
  1117. | _ ->
  1118. e)
  1119. let optimize_unop e op flag esub =
  1120. match op, esub.eexpr with
  1121. | Not, (TConst (TBool f) | TParenthesis({eexpr = TConst (TBool f)})) -> { e with eexpr = TConst (TBool (not f)) }
  1122. | Neg, TConst (TInt i) -> { e with eexpr = TConst (TInt (Int32.neg i)) }
  1123. | NegBits, TConst (TInt i) -> { e with eexpr = TConst (TInt (Int32.lognot i)) }
  1124. | Neg, TConst (TFloat f) ->
  1125. let v = 0. -. float_of_string f in
  1126. let vstr = float_repres v in
  1127. if float_of_string vstr = v then
  1128. { e with eexpr = TConst (TFloat vstr) }
  1129. else
  1130. e
  1131. | _ -> e
  1132. let rec reduce_loop ctx e =
  1133. let e = Type.map_expr (reduce_loop ctx) e in
  1134. sanitize_expr ctx.com (match e.eexpr with
  1135. | TIf ({ eexpr = TConst (TBool t) },e1,e2) ->
  1136. (if t then e1 else match e2 with None -> { e with eexpr = TBlock [] } | Some e -> e)
  1137. | TWhile ({ eexpr = TConst (TBool false) },sub,flag) ->
  1138. (match flag with
  1139. | NormalWhile -> { e with eexpr = TBlock [] } (* erase sub *)
  1140. | DoWhile -> e) (* we cant remove while since sub can contain continue/break *)
  1141. | TBinop (op,e1,e2) ->
  1142. optimize_binop e op e1 e2
  1143. | TUnop (op,flag,esub) ->
  1144. optimize_unop e op flag esub
  1145. | TCall ({ eexpr = TField ({ eexpr = TTypeExpr (TClassDecl c) },field) },params) ->
  1146. (match api_inline ctx c (field_name field) params e.epos with
  1147. | None -> reduce_expr ctx e
  1148. | Some e -> reduce_loop ctx e)
  1149. | TCall ({ eexpr = TFunction func } as ef,el) ->
  1150. let cf = mk_field "" ef.etype e.epos in
  1151. let ethis = mk (TConst TThis) t_dynamic e.epos in
  1152. let rt = (match follow ef.etype with TFun (_,rt) -> rt | _ -> assert false) in
  1153. let inl = (try type_inline ctx cf func ethis el rt None e.epos ~self_calling_closure:true false with Error (Custom _,_) -> None) in
  1154. (match inl with
  1155. | None -> reduce_expr ctx e
  1156. | Some e -> reduce_loop ctx e)
  1157. | TCall ({ eexpr = TField (o,FClosure (c,cf)) } as f,el) ->
  1158. let fmode = (match c with None -> FAnon cf | Some (c,tl) -> FInstance (c,tl,cf)) in
  1159. { e with eexpr = TCall ({ f with eexpr = TField (o,fmode) },el) }
  1160. | TSwitch (e1,[[{eexpr = TConst (TBool true)}],{eexpr = TConst (TBool true)}],Some ({eexpr = TConst (TBool false)})) ->
  1161. (* introduced by extractors in some cases *)
  1162. e1
  1163. | _ ->
  1164. reduce_expr ctx e)
  1165. let reduce_expression ctx e =
  1166. if ctx.com.foptimize then reduce_loop ctx e else e
  1167. let rec make_constant_expression ctx ?(concat_strings=false) e =
  1168. let e = reduce_loop ctx e in
  1169. match e.eexpr with
  1170. | TConst _ -> Some e
  1171. | TBinop ((OpAdd|OpSub|OpMult|OpDiv|OpMod) as op,e1,e2) -> (match make_constant_expression ctx e1,make_constant_expression ctx e2 with
  1172. | Some ({eexpr = TConst (TString s1)}), Some ({eexpr = TConst (TString s2)}) when concat_strings ->
  1173. Some (mk (TConst (TString (s1 ^ s2))) ctx.com.basic.tstring (punion e1.epos e2.epos))
  1174. | Some e1, Some e2 -> Some (mk (TBinop(op, e1, e2)) e.etype e.epos)
  1175. | _ -> None)
  1176. | TCast (e1, None) ->
  1177. (match make_constant_expression ctx e1 with
  1178. | None -> None
  1179. | Some e1 -> Some {e with eexpr = TCast(e1,None)})
  1180. | TParenthesis e1 ->
  1181. begin match make_constant_expression ctx ~concat_strings e1 with
  1182. | None -> None
  1183. | Some e1 -> Some {e with eexpr = TParenthesis e1}
  1184. end
  1185. | TMeta(m,e1) ->
  1186. begin match make_constant_expression ctx ~concat_strings e1 with
  1187. | None -> None
  1188. | Some e1 -> Some {e with eexpr = TMeta(m,e1)}
  1189. end
  1190. | TTypeExpr _ -> Some e
  1191. (* try to inline static function calls *)
  1192. | TCall ({ etype = TFun(_,ret); eexpr = TField (_,FStatic (c,cf)) },el) ->
  1193. (try
  1194. let func = match cf.cf_expr with Some ({eexpr = TFunction func}) -> func | _ -> raise Not_found in
  1195. let ethis = mk (TConst TThis) t_dynamic e.epos in
  1196. let inl = (try type_inline ctx cf func ethis el ret None e.epos false with Error (Custom _,_) -> None) in
  1197. (match inl with
  1198. | None -> None
  1199. | Some e -> make_constant_expression ctx e)
  1200. with Not_found -> None)
  1201. | _ -> None
  1202. (* ---------------------------------------------------------------------- *)
  1203. (* INLINE CONSTRUCTORS *)
  1204. (*
  1205. First pass :
  1206. We will look at local variables in the form var v = new ....
  1207. we only capture the ones which have constructors marked as inlined
  1208. then we make sure that these locals are no more referenced except for fields accesses
  1209. Second pass :
  1210. We replace the variables by their fields lists, and the corresponding fields accesses as well
  1211. *)
  1212. type inline_kind =
  1213. | IKCtor of tfunc * tclass_field * tclass * t list * texpr list * texpr list
  1214. | IKArray of texpr list * t
  1215. | IKStructure of (string * texpr) list
  1216. | IKNone
  1217. let inline_constructors ctx e =
  1218. let vars = ref PMap.empty in
  1219. let is_valid_ident s =
  1220. try
  1221. if String.length s = 0 then raise Exit;
  1222. begin match String.unsafe_get s 0 with
  1223. | 'a'..'z' | 'A'..'Z' | '_' -> ()
  1224. | _ -> raise Exit
  1225. end;
  1226. for i = 1 to String.length s - 1 do
  1227. match String.unsafe_get s i with
  1228. | 'a'..'z' | 'A'..'Z' | '_' -> ()
  1229. | '0'..'9' when i > 0 -> ()
  1230. | _ -> raise Exit
  1231. done;
  1232. true
  1233. with Exit ->
  1234. false
  1235. in
  1236. let rec get_inline_ctor_info e = match e.eexpr with
  1237. | TNew ({ cl_constructor = Some ({ cf_kind = Method MethInline; cf_expr = Some { eexpr = TFunction f } } as cst) } as c,tl,pl) ->
  1238. IKCtor (f,cst,c,tl,pl,[])
  1239. | TObjectDecl [] | TArrayDecl [] ->
  1240. IKNone
  1241. | TArrayDecl el ->
  1242. begin match follow e.etype with
  1243. | TInst({cl_path = [],"Array"},[t]) ->
  1244. IKArray(el,t)
  1245. | _ ->
  1246. IKNone
  1247. end
  1248. | TObjectDecl fl ->
  1249. if (List.exists (fun (s,_) -> not (is_valid_ident s)) fl) then
  1250. IKNone
  1251. else
  1252. IKStructure fl
  1253. | TCast(e,None) | TParenthesis e ->
  1254. get_inline_ctor_info e
  1255. | TBlock el ->
  1256. begin match List.rev el with
  1257. | e :: el ->
  1258. begin match get_inline_ctor_info e with
  1259. | IKCtor(f,cst,c,tl,pl,e_init) ->
  1260. IKCtor(f,cst,c,tl,pl,(List.rev el) @ e_init)
  1261. | _ ->
  1262. IKNone
  1263. end
  1264. | [] ->
  1265. IKNone
  1266. end
  1267. | _ ->
  1268. IKNone
  1269. in
  1270. let check_field v s e t =
  1271. let (a,b,fields,c,d) = PMap.find (-v.v_id) !vars in
  1272. if not (List.exists (fun (s2,_,_) -> s = s2) fields) then
  1273. vars := PMap.add (-v.v_id) (a,b,(s,e,t) :: fields,c,d) !vars
  1274. in
  1275. let cancel v =
  1276. v.v_id <- -v.v_id;
  1277. (* error if the constructor is extern *)
  1278. (match PMap.find v.v_id !vars with
  1279. | _,_,_,true,p ->
  1280. display_error ctx "Extern constructor could not be inlined" p;
  1281. error "Variable is used here" e.epos
  1282. | _ -> ());
  1283. vars := PMap.remove v.v_id !vars;
  1284. in
  1285. let rec skip_to_var e = match e.eexpr with
  1286. | TLocal v when v.v_id < 0 -> Some v
  1287. (* | TCast(e1,None) | TMeta(_,e1) | TParenthesis(e1) -> skip_to_var e1 *)
  1288. | _ -> None
  1289. in
  1290. let rec find_locals e =
  1291. match e.eexpr with
  1292. | TVar (v,eo) ->
  1293. Type.iter find_locals e;
  1294. begin match eo with
  1295. | Some n ->
  1296. begin match get_inline_ctor_info n with
  1297. | IKCtor (f,cst,c,tl,pl,el_init) when type_iseq v.v_type n.etype ->
  1298. (* inline the constructor *)
  1299. (match (try type_inline ctx cst f (mk (TLocal v) (TInst (c,tl)) n.epos) pl ctx.t.tvoid None n.epos true with Error (Custom _,_) -> None) with
  1300. | None -> ()
  1301. | Some ecst ->
  1302. let assigns = ref [] in
  1303. (* add field inits here because the filter has not run yet (issue #2336) *)
  1304. List.iter (fun cf -> match cf.cf_kind,cf.cf_expr with
  1305. | Var _,Some e -> assigns := (cf.cf_name,e,cf.cf_type) :: !assigns
  1306. | _ -> ()
  1307. ) c.cl_ordered_fields;
  1308. (* make sure we only have v.field = expr calls *)
  1309. let rec get_assigns e =
  1310. match e.eexpr with
  1311. | TBlock el ->
  1312. List.iter get_assigns el
  1313. | TBinop (OpAssign, { eexpr = TField ({ eexpr = TLocal vv },FInstance(_,_,cf)); etype = t }, e) when v == vv ->
  1314. assigns := (cf.cf_name,e,t) :: !assigns
  1315. | _ ->
  1316. raise Exit
  1317. in
  1318. try
  1319. get_assigns ecst;
  1320. (* mark variable as candidate for inlining *)
  1321. vars := PMap.add v.v_id (v,el_init,List.rev !assigns,c.cl_extern || Meta.has Meta.Extern cst.cf_meta,n.epos) !vars;
  1322. v.v_id <- -v.v_id; (* mark *)
  1323. (* recurse with the constructor code which will be inlined here *)
  1324. find_locals ecst
  1325. with Exit ->
  1326. ())
  1327. | IKArray (el,t) ->
  1328. vars := PMap.add v.v_id (v,[],ExtList.List.mapi (fun i e -> string_of_int i,e,t) el, false, n.epos) !vars;
  1329. v.v_id <- -v.v_id;
  1330. | IKStructure fl ->
  1331. vars := PMap.add v.v_id (v,[],List.map (fun (s,e) -> s,e,e.etype) fl, false, n.epos) !vars;
  1332. v.v_id <- -v.v_id;
  1333. | _ ->
  1334. ()
  1335. end
  1336. | _ -> ()
  1337. end
  1338. | TField(e1, (FInstance(_, _, {cf_kind = Var _; cf_name = s}) | FAnon({cf_kind = Var _; cf_name = s}))) ->
  1339. (match skip_to_var e1 with None -> find_locals e1 | Some _ -> ())
  1340. | TArray (e1,{eexpr = TConst (TInt i)}) ->
  1341. begin match skip_to_var e1 with
  1342. | None -> find_locals e1
  1343. | Some v ->
  1344. let (_,_,fields,_,_) = PMap.find (-v.v_id) !vars in
  1345. let i = Int32.to_int i in
  1346. if i < 0 || i >= List.length fields then cancel v
  1347. end
  1348. | TBinop((OpAssign | OpAssignOp _),e1,e2) ->
  1349. begin match e1.eexpr with
  1350. | TArray ({eexpr = TLocal v},{eexpr = TConst (TInt i)}) when v.v_id < 0 ->
  1351. check_field v (Int32.to_string i) e2 e2.etype
  1352. | TField({eexpr = TLocal v}, (FInstance(_, _, {cf_kind = Var _; cf_name = s}) | FAnon({cf_kind = Var _; cf_name = s}))) when v.v_id < 0 ->
  1353. check_field v s e2 e2.etype
  1354. | _ ->
  1355. find_locals e1
  1356. end;
  1357. find_locals e2
  1358. | TLocal v when v.v_id < 0 ->
  1359. cancel v
  1360. | _ ->
  1361. Type.iter find_locals e
  1362. in
  1363. find_locals e;
  1364. let vars = !vars in
  1365. if PMap.is_empty vars then
  1366. e
  1367. else begin
  1368. let vfields = PMap.map (fun (v,el_init,assigns,_,_) ->
  1369. (List.fold_left (fun (acc,map) (name,e,t) ->
  1370. let vf = alloc_var (v.v_name ^ "_" ^ name) t in
  1371. ((vf,e) :: acc, PMap.add name vf map)
  1372. ) ([],PMap.empty) assigns),el_init
  1373. ) vars in
  1374. let el_b = ref [] in
  1375. let append e = el_b := e :: !el_b in
  1376. let inline_field c cf v =
  1377. let (_, vars),el_init = PMap.find (-v.v_id) vfields in
  1378. (try
  1379. let v = PMap.find cf.cf_name vars in
  1380. mk (TLocal v) v.v_type e.epos
  1381. with Not_found ->
  1382. if (c.cl_path = ([],"Array") && cf.cf_name = "length") then begin
  1383. (* this can only occur for inlined array declarations, so we can use the statically known length here (issue #2568)*)
  1384. let l = PMap.fold (fun _ i -> i + 1) vars 0 in
  1385. mk (TConst (TInt (Int32.of_int l))) ctx.t.tint e.epos
  1386. end else
  1387. (* the variable was not set in the constructor, assume null *)
  1388. mk (TConst TNull) e.etype e.epos)
  1389. in
  1390. let inline_anon_field cf v =
  1391. let (_, vars),_ = PMap.find (-v.v_id) vfields in
  1392. (try
  1393. let v = PMap.find cf.cf_name vars in
  1394. mk (TLocal v) v.v_type e.epos
  1395. with Not_found ->
  1396. (* this could happen in untyped code, assume null *)
  1397. mk (TConst TNull) e.etype e.epos)
  1398. in
  1399. let inline_array_access i v =
  1400. let (_, vars),_ = PMap.find (-v.v_id) vfields in
  1401. (try
  1402. let v = PMap.find (Int32.to_string i) vars in
  1403. mk (TLocal v) v.v_type e.epos
  1404. with Not_found ->
  1405. (* probably out-of-bounds, assume null *)
  1406. mk (TConst TNull) e.etype e.epos)
  1407. in
  1408. let rec subst e =
  1409. match e.eexpr with
  1410. | TBlock el ->
  1411. let old = !el_b in
  1412. el_b := [];
  1413. List.iter (fun e -> append (subst e)) el;
  1414. let n = !el_b in
  1415. el_b := old;
  1416. {e with eexpr = TBlock (List.rev n)}
  1417. | TVar (v,Some e) when v.v_id < 0 ->
  1418. let (vars, _),el_init = PMap.find (-v.v_id) vfields in
  1419. List.iter (fun e ->
  1420. append (subst e)
  1421. ) el_init;
  1422. let (v_first,e_first),vars = match vars with
  1423. | v :: vl -> v,vl
  1424. | [] -> assert false
  1425. in
  1426. List.iter (fun (v,e) -> append (mk (TVar(v,Some (subst e))) ctx.t.tvoid e.epos)) (List.rev vars);
  1427. mk (TVar (v_first, Some (subst e_first))) ctx.t.tvoid e.epos
  1428. | TField (e1,FInstance (c,_,cf)) ->
  1429. begin match skip_to_var e1 with
  1430. | None -> Type.map_expr subst e
  1431. | Some v -> inline_field c cf v
  1432. end
  1433. | TArray (e1,{eexpr = TConst (TInt i)}) ->
  1434. begin match skip_to_var e1 with
  1435. | None -> Type.map_expr subst e
  1436. | Some v -> inline_array_access i v
  1437. end
  1438. | TField (e1,FAnon(cf)) ->
  1439. begin match skip_to_var e1 with
  1440. | None -> Type.map_expr subst e
  1441. | Some v -> inline_anon_field cf v
  1442. end
  1443. | _ ->
  1444. Type.map_expr subst e
  1445. in
  1446. let e = (try subst e with Not_found -> assert false) in
  1447. PMap.iter (fun _ (v,_,_,_,_) -> v.v_id <- -v.v_id) vars;
  1448. e
  1449. end
  1450. (* ---------------------------------------------------------------------- *)
  1451. (* COMPLETION *)
  1452. exception Return of Ast.expr
  1453. type compl_locals = {
  1454. mutable r : (string, (complex_type option * (int * Ast.expr * compl_locals) option)) PMap.t;
  1455. }
  1456. let optimize_completion_expr e =
  1457. let iid = ref 0 in
  1458. let typing_side_effect = ref false in
  1459. let locals : compl_locals = { r = PMap.empty } in
  1460. let save() = let old = locals.r in (fun() -> locals.r <- old) in
  1461. let get_local n = PMap.find n locals.r in
  1462. let maybe_typed e =
  1463. match fst e with
  1464. | EConst (Ident "null") -> false
  1465. | _ -> true
  1466. in
  1467. let decl n t e =
  1468. typing_side_effect := true;
  1469. locals.r <- PMap.add n (t,(match e with Some e when maybe_typed e -> incr iid; Some (!iid,e,{ r = locals.r }) | _ -> None)) locals.r
  1470. in
  1471. let rec loop e =
  1472. let p = snd e in
  1473. match fst e with
  1474. | EConst (Ident n) ->
  1475. (try
  1476. (match get_local n with
  1477. | Some _ , _ -> ()
  1478. | _ -> typing_side_effect := true)
  1479. with Not_found ->
  1480. ());
  1481. e
  1482. | EBinop (OpAssign,(EConst (Ident n),_),esub) ->
  1483. (try
  1484. (match get_local n with
  1485. | None, None when maybe_typed esub -> decl n None (Some esub)
  1486. | _ -> ())
  1487. with Not_found ->
  1488. ());
  1489. map e
  1490. | EVars vl ->
  1491. let vl = List.map (fun (v,t,e) ->
  1492. let e = (match e with None -> None | Some e -> Some (loop e)) in
  1493. decl v t e;
  1494. (v,t,e)
  1495. ) vl in
  1496. (EVars vl,p)
  1497. | EBlock el ->
  1498. let old = save() in
  1499. let told = ref (!typing_side_effect) in
  1500. let el = List.fold_left (fun acc e ->
  1501. typing_side_effect := false;
  1502. let e = loop e in
  1503. if !typing_side_effect then begin told := true; e :: acc end else acc
  1504. ) [] el in
  1505. old();
  1506. typing_side_effect := !told;
  1507. (EBlock (List.rev el),p)
  1508. | EFunction (v,f) ->
  1509. (match v with
  1510. | None -> ()
  1511. | Some name ->
  1512. decl name None (Some e));
  1513. let old = save() in
  1514. List.iter (fun (n,_,t,e) -> decl n t e) f.f_args;
  1515. let e = map e in
  1516. old();
  1517. e
  1518. | EFor ((EIn ((EConst (Ident n),_) as id,it),p),efor) ->
  1519. let it = loop it in
  1520. let old = save() in
  1521. let etmp = (EConst (Ident "$tmp"),p) in
  1522. decl n None (Some (EBlock [
  1523. (EVars ["$tmp",None,None],p);
  1524. (EFor ((EIn (id,it),p),(EBinop (OpAssign,etmp,(EConst (Ident n),p)),p)),p);
  1525. etmp
  1526. ],p));
  1527. let efor = loop efor in
  1528. old();
  1529. (EFor ((EIn (id,it),p),efor),p)
  1530. | EReturn _ ->
  1531. typing_side_effect := true;
  1532. map e
  1533. | ESwitch (e,cases,def) ->
  1534. let e = loop e in
  1535. let cases = List.map (fun (el,eg,eo) -> match eo with
  1536. | None ->
  1537. el,eg,eo
  1538. | Some e ->
  1539. let el = List.map loop el in
  1540. let old = save() in
  1541. List.iter (fun e ->
  1542. match fst e with
  1543. | ECall (_,pl) ->
  1544. List.iter (fun p ->
  1545. match fst p with
  1546. | EConst (Ident i) -> decl i None None (* sadly *)
  1547. | _ -> ()
  1548. ) pl
  1549. | _ -> ()
  1550. ) el;
  1551. let e = loop e in
  1552. old();
  1553. el, eg, Some e
  1554. ) cases in
  1555. let def = match def with
  1556. | None -> None
  1557. | Some None -> Some None
  1558. | Some (Some e) -> Some (Some (loop e))
  1559. in
  1560. (ESwitch (e,cases,def),p)
  1561. | ETry (et,cl) ->
  1562. let et = loop et in
  1563. let cl = List.map (fun (n,t,e) ->
  1564. let old = save() in
  1565. decl n (Some t) None;
  1566. let e = loop e in
  1567. old();
  1568. n, t, e
  1569. ) cl in
  1570. (ETry (et,cl),p)
  1571. | EDisplay (s,call) ->
  1572. typing_side_effect := true;
  1573. let tmp_locals = ref [] in
  1574. let tmp_hlocals = ref PMap.empty in
  1575. let rec subst_locals locals e =
  1576. match fst e with
  1577. | EConst (Ident n) ->
  1578. let p = snd e in
  1579. (try
  1580. (match PMap.find n locals.r with
  1581. | Some t , _ -> (ECheckType ((EConst (Ident "null"),p),t),p)
  1582. | _, Some (id,e,lc) ->
  1583. let name = (try
  1584. PMap.find id (!tmp_hlocals)
  1585. with Not_found ->
  1586. let e = subst_locals lc e in
  1587. let name = "$tmp_" ^ string_of_int id in
  1588. tmp_locals := (name,None,Some e) :: !tmp_locals;
  1589. tmp_hlocals := PMap.add id name !tmp_hlocals;
  1590. name
  1591. ) in
  1592. (EConst (Ident name),p)
  1593. | None, None ->
  1594. (* we can't replace the var *)
  1595. raise Exit)
  1596. with Not_found ->
  1597. (* not found locals are most likely to be member/static vars *)
  1598. e)
  1599. | EFunction (_,f) ->
  1600. Ast.map_expr (subst_locals { r = PMap.foldi (fun n i acc -> if List.exists (fun (a,_,_,_) -> a = n) f.f_args then acc else PMap.add n i acc) locals.r PMap.empty }) e
  1601. | EObjectDecl [] ->
  1602. (* this probably comes from { | completion so we need some context} *)
  1603. raise Exit
  1604. | _ ->
  1605. Ast.map_expr (subst_locals locals) e
  1606. in
  1607. (try
  1608. let e = subst_locals locals s in
  1609. let e = (EBlock [(EVars (List.rev !tmp_locals),p);(EDisplay (e,call),p)],p) in
  1610. raise (Return e)
  1611. with Exit ->
  1612. map e)
  1613. | EDisplayNew _ ->
  1614. raise (Return e)
  1615. | _ ->
  1616. map e
  1617. and map e =
  1618. Ast.map_expr loop e
  1619. in
  1620. (try loop e with Return e -> e)
  1621. (* ---------------------------------------------------------------------- *)