optimizer.ml 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. (*
  2. * Copyright (C)2005-2013 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. *)
  22. open Ast
  23. open Type
  24. open Common
  25. open Typecore
  26. (* ---------------------------------------------------------------------- *)
  27. (* API OPTIMIZATIONS *)
  28. let has_side_effect e =
  29. let rec loop e =
  30. match e.eexpr with
  31. | TConst _ | TLocal _ | TField (_,FEnum _) | TTypeExpr _ | TFunction _ -> ()
  32. | TMatch _ | TNew _ | TCall _ | TField _ | TArray _ | TBinop ((OpAssignOp _ | OpAssign),_,_) | TUnop ((Increment|Decrement),_,_) -> raise Exit
  33. | TReturn _ | TBreak | TContinue | TThrow _ | TCast (_,Some _) -> raise Exit
  34. | TCast (_,None) | TBinop _ | TUnop _ | TParenthesis _ | TWhile _ | TFor _ | TIf _ | TTry _ | TSwitch _ | TArrayDecl _ | TVars _ | TBlock _ | TObjectDecl _ -> Type.iter loop e
  35. in
  36. try
  37. loop e; false
  38. with Exit ->
  39. true
  40. let api_inline ctx c field params p =
  41. match c.cl_path, field, params with
  42. | ([],"Type"),"enumIndex",[{ eexpr = TField (_,FEnum (en,f)) }] ->
  43. Some (mk (TConst (TInt (Int32.of_int f.ef_index))) ctx.t.tint p)
  44. | ([],"Type"),"enumIndex",[{ eexpr = TCall({ eexpr = TField (_,FEnum (en,f)) },pl) }] when List.for_all (fun e -> not (has_side_effect e)) pl ->
  45. Some (mk (TConst (TInt (Int32.of_int f.ef_index))) ctx.t.tint p)
  46. | ([],"Std"),"int",[{ eexpr = TConst (TInt _) } as e] ->
  47. Some { e with epos = p }
  48. | ([],"String"),"fromCharCode",[{ eexpr = TConst (TInt i) }] when i > 0l && i < 128l ->
  49. Some (mk (TConst (TString (String.make 1 (char_of_int (Int32.to_int i))))) ctx.t.tstring p)
  50. | ([],"Std"),"string",[{ eexpr = TConst c } as e] ->
  51. (match c with
  52. | TString s ->
  53. Some { e with epos = p }
  54. | TInt i ->
  55. Some { eexpr = TConst (TString (Int32.to_string i)); epos = p; etype = ctx.t.tstring }
  56. | TBool b ->
  57. Some { eexpr = TConst (TString (if b then "true" else "false")); epos = p; etype = ctx.t.tstring }
  58. | _ ->
  59. None)
  60. | ([],"Std"),"int",[{ eexpr = TConst (TFloat f) }] ->
  61. let f = float_of_string f in
  62. (match classify_float f with
  63. | FP_infinite | FP_nan ->
  64. None
  65. | _ when f <= Int32.to_float Int32.min_int -. 1. || f >= Int32.to_float Int32.max_int +. 1. ->
  66. None (* out range, keep platform-specific behavior *)
  67. | _ ->
  68. Some { eexpr = TConst (TInt (Int32.of_float f)); etype = ctx.t.tint; epos = p })
  69. | _ ->
  70. None
  71. (* ---------------------------------------------------------------------- *)
  72. (* INLINING *)
  73. type in_local = {
  74. i_var : tvar;
  75. i_subst : tvar;
  76. mutable i_captured : bool;
  77. mutable i_write : bool;
  78. mutable i_read : int;
  79. }
  80. let inline_default_config cf t =
  81. (* type substitution on both class and function type parameters *)
  82. let rec get_params c pl =
  83. match c.cl_super with
  84. | None -> c.cl_types, pl
  85. | Some (csup,spl) ->
  86. let spl = (match apply_params c.cl_types pl (TInst (csup,spl)) with
  87. | TInst (_,pl) -> pl
  88. | _ -> assert false
  89. ) in
  90. let ct, cpl = get_params csup spl in
  91. c.cl_types @ ct, pl @ cpl
  92. in
  93. let tparams = (match follow t with
  94. | TInst (c,pl) -> get_params c pl
  95. | _ -> ([],[]))
  96. in
  97. let pmonos = List.map (fun _ -> mk_mono()) cf.cf_params in
  98. let tmonos = snd tparams @ pmonos in
  99. let tparams = fst tparams @ cf.cf_params in
  100. tparams <> [], apply_params tparams tmonos
  101. let rec type_inline ctx cf f ethis params tret config p force =
  102. (* perform some specific optimization before we inline the call since it's not possible to detect at final optimization time *)
  103. try
  104. let cl = (match follow ethis.etype with
  105. | TInst (c,_) -> c
  106. | TAnon a -> (match !(a.a_status) with Statics c -> c | _ -> raise Exit)
  107. | _ -> raise Exit
  108. ) in
  109. (match api_inline ctx cl cf.cf_name params p with
  110. | None -> raise Exit
  111. | Some e -> Some e)
  112. with Exit ->
  113. let has_params,map_type = match config with Some config -> config | None -> inline_default_config cf ethis.etype in
  114. (* locals substitution *)
  115. let locals = Hashtbl.create 0 in
  116. let local v =
  117. try
  118. Hashtbl.find locals v.v_id
  119. with Not_found ->
  120. let i = {
  121. i_var = v;
  122. i_subst = alloc_var v.v_name v.v_type;
  123. i_captured = false;
  124. i_write = false;
  125. i_read = 0;
  126. } in
  127. Hashtbl.add locals v.v_id i;
  128. Hashtbl.add locals i.i_subst.v_id i;
  129. i
  130. in
  131. let read_local v =
  132. try
  133. Hashtbl.find locals v.v_id
  134. with Not_found ->
  135. {
  136. i_var = v;
  137. i_subst = v;
  138. i_captured = false;
  139. i_write = false;
  140. i_read = 0;
  141. }
  142. in
  143. (* use default values for null/unset arguments *)
  144. let rec loop pl al =
  145. match pl, al with
  146. | _, [] -> []
  147. | e :: pl, (v, opt) :: al ->
  148. (*
  149. if we pass a Null<T> var to an inlined method that needs a T.
  150. we need to force a local var to be created on some platforms.
  151. *)
  152. if ctx.com.config.pf_static && not (is_nullable v.v_type) && is_null e.etype then (local v).i_write <- true;
  153. (*
  154. if we cast from Dynamic, create a local var as well to do the cast
  155. once and allow DCE to perform properly.
  156. *)
  157. if v.v_type != t_dynamic && follow e.etype == t_dynamic then (local v).i_write <- true;
  158. (match e.eexpr, opt with
  159. | TConst TNull , Some c -> mk (TConst c) v.v_type e.epos
  160. | _ -> e) :: loop pl al
  161. | [], (v,opt) :: al ->
  162. mk (TConst (match opt with None -> TNull | Some c -> c)) v.v_type p :: loop [] al
  163. in
  164. (*
  165. Build the expr/var subst list
  166. *)
  167. let ethis = (match ethis.eexpr with TConst TSuper -> { ethis with eexpr = TConst TThis } | _ -> ethis) in
  168. let vthis = alloc_var "_this" ethis.etype in
  169. let inlined_vars = List.map2 (fun e (v,_) -> local v, e) (ethis :: loop params f.tf_args) ((vthis,None) :: f.tf_args) in
  170. (*
  171. here, we try to eliminate final returns from the expression tree.
  172. However, this is not entirely correct since we don't yet correctly propagate
  173. the type of returned expressions upwards ("return" expr itself being Dynamic).
  174. We also substitute variables with fresh ones that might be renamed at later stage.
  175. *)
  176. let opt f = function
  177. | None -> None
  178. | Some e -> Some (f e)
  179. in
  180. let has_vars = ref false in
  181. let in_loop = ref false in
  182. let in_local_fun = ref false in
  183. let cancel_inlining = ref false in
  184. let has_return_value = ref false in
  185. let ret_val = (match follow f.tf_type with TEnum ({ e_path = ([],"Void") },[]) | TAbstract ({ a_path = ([],"Void") },[]) -> false | _ -> true) in
  186. let rec map term e =
  187. let po = e.epos in
  188. let e = { e with epos = p } in
  189. match e.eexpr with
  190. | TLocal v ->
  191. let l = read_local v in
  192. if !in_local_fun then l.i_captured <- true;
  193. l.i_read <- l.i_read + (if !in_loop then 2 else 1);
  194. (* never inline a function which contain a delayed macro because its bound
  195. to its variables and not the calling method *)
  196. if v.v_name = "__dollar__delay_call" then cancel_inlining := true;
  197. { e with eexpr = TLocal l.i_subst }
  198. | TConst TThis ->
  199. let l = read_local vthis in
  200. l.i_read <- l.i_read + (if !in_loop then 2 else 1);
  201. { e with eexpr = TLocal l.i_subst }
  202. | TVars vl ->
  203. has_vars := true;
  204. let vl = List.map (fun (v,e) ->
  205. (local v).i_subst,opt (map false) e
  206. ) vl in
  207. { e with eexpr = TVars vl }
  208. | TReturn eo when not !in_local_fun ->
  209. if not term then error "Cannot inline a not final return" po;
  210. (match eo with
  211. | None -> mk (TConst TNull) f.tf_type p
  212. | Some e -> has_return_value := true;
  213. (* we can omit unsafe casts to retain the real type, the cast will be added back later anyway *)
  214. (match e.eexpr with
  215. | TCast(e1,None) -> map term e1
  216. | _ -> map term e))
  217. | TFor (v,e1,e2) ->
  218. let i = local v in
  219. let e1 = map false e1 in
  220. let old = !in_loop in
  221. in_loop := true;
  222. let e2 = map false e2 in
  223. in_loop := old;
  224. { e with eexpr = TFor (i.i_subst,e1,e2) }
  225. | TWhile (cond,eloop,flag) ->
  226. let cond = map false cond in
  227. let old = !in_loop in
  228. in_loop := true;
  229. let eloop = map false eloop in
  230. in_loop := old;
  231. { e with eexpr = TWhile (cond,eloop,flag) }
  232. | TMatch (v,en,cases,def) ->
  233. let term = term && def <> None in
  234. let cases = List.map (fun (i,vl,e) ->
  235. let vl = opt (List.map (fun v -> opt (fun v -> (local v).i_subst) v)) vl in
  236. i, vl, map term e
  237. ) cases in
  238. let def = opt (map term) def in
  239. { e with eexpr = TMatch (map false v,en,cases,def); etype = if term && ret_val then unify_min ctx ((List.map (fun (_,_,e) -> e) cases) @ (match def with None -> [] | Some e -> [e])) else e.etype }
  240. | TSwitch (e1,cases,def) when term ->
  241. let term = term && def <> None in
  242. let cases = List.map (fun (el,e) ->
  243. let el = List.map (map false) el in
  244. el, map term e
  245. ) cases in
  246. let def = opt (map term) def in
  247. { 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 }
  248. | TTry (e1,catches) ->
  249. { e with eexpr = TTry (map term e1,List.map (fun (v,e) ->
  250. let lv = (local v).i_subst in
  251. let e = map term e in
  252. lv,e
  253. ) catches); etype = if term && ret_val then unify_min ctx (e1::List.map snd catches) else e.etype }
  254. | TBlock l ->
  255. let old = save_locals ctx in
  256. let t = ref e.etype in
  257. let rec loop = function
  258. | [] when term ->
  259. t := mk_mono();
  260. [mk (TConst TNull) (!t) p]
  261. | [] -> []
  262. | [e] ->
  263. let e = map term e in
  264. if term then t := e.etype;
  265. [e]
  266. | e :: l ->
  267. let e = map false e in
  268. e :: loop l
  269. in
  270. let l = loop l in
  271. old();
  272. { e with eexpr = TBlock l; etype = !t }
  273. | TIf (econd,eif,Some eelse) when term ->
  274. let econd = map false econd in
  275. let eif = map term eif in
  276. let eelse = map term eelse in
  277. { e with eexpr = TIf(econd,eif,Some eelse); etype = if ret_val then unify_min ctx [eif;eelse] else e.etype }
  278. | TParenthesis e1 ->
  279. let e1 = map term e1 in
  280. mk (TParenthesis e1) e1.etype e.epos
  281. | TUnop ((Increment|Decrement),_,{ eexpr = TLocal v }) ->
  282. (read_local v).i_write <- true;
  283. Type.map_expr (map false) e
  284. | TBinop ((OpAssign | OpAssignOp _),{ eexpr = TLocal v },_) ->
  285. (read_local v).i_write <- true;
  286. Type.map_expr (map false) e;
  287. | TFunction f ->
  288. (match f.tf_args with [] -> () | _ -> has_vars := true);
  289. let old = save_locals ctx and old_fun = !in_local_fun in
  290. let args = List.map (function(v,c) -> (local v).i_subst, c) f.tf_args in
  291. in_local_fun := true;
  292. let expr = map false f.tf_expr in
  293. in_local_fun := old_fun;
  294. old();
  295. { e with eexpr = TFunction { tf_args = args; tf_expr = expr; tf_type = f.tf_type } }
  296. | TConst TSuper ->
  297. error "Cannot inline function containing super" po
  298. | _ ->
  299. Type.map_expr (map false) e
  300. in
  301. let e = map true f.tf_expr in
  302. (*
  303. if variables are not written and used with a const value, let's substitute
  304. with the actual value, either create a temp var
  305. *)
  306. let subst = ref PMap.empty in
  307. let is_constant e =
  308. let rec loop e =
  309. match e.eexpr with
  310. | TLocal _
  311. | TConst TThis (* not really, but should not be move inside a function body *)
  312. -> raise Exit
  313. | TField (_,FEnum _)
  314. | TTypeExpr _
  315. | TConst _ -> ()
  316. | _ ->
  317. Type.iter loop e
  318. in
  319. try loop e; true with Exit -> false
  320. in
  321. let is_writable e =
  322. match e.eexpr with
  323. | TField _ | TLocal _ | TArray _ -> true
  324. | _ -> false
  325. in
  326. let force = ref force in
  327. let vars = List.fold_left (fun acc (i,e) ->
  328. let flag = (match e.eexpr with
  329. | TLocal { v_name = "this" } -> true
  330. | TLocal _ | TConst _ -> not i.i_write
  331. | TFunction _ -> if i.i_write then error "Cannot modify a closure parameter inside inline method" p; true
  332. | _ -> not i.i_write && i.i_read <= 1
  333. ) in
  334. let flag = flag && (not i.i_captured || is_constant e) in
  335. (* force inlining if we modify 'this' *)
  336. if i.i_write && i.i_var.v_name = "this" then force := true;
  337. (* force inlining of 'this' variable if the expression is writable *)
  338. let flag = if not flag && i.i_var.v_name = "this" then begin
  339. if i.i_write && not (is_writable e) then error "Cannot modify the abstract value, store it into a local first" p;
  340. true
  341. end else flag in
  342. if flag then begin
  343. subst := PMap.add i.i_subst.v_id e !subst;
  344. acc
  345. end else
  346. (i.i_subst,Some e) :: acc
  347. ) [] inlined_vars in
  348. let subst = !subst in
  349. let rec inline_params e =
  350. match e.eexpr with
  351. | TLocal v -> (try PMap.find v.v_id subst with Not_found -> e)
  352. | _ -> Type.map_expr inline_params e
  353. in
  354. let e = (if PMap.is_empty subst then e else inline_params e) in
  355. let init = (match vars with [] -> None | l -> Some (mk (TVars (List.rev l)) ctx.t.tvoid p)) in
  356. (*
  357. If we have local variables and returning a value, then this will result in
  358. unoptimized JS code, so let's instead skip inlining.
  359. This could be fixed with better post process code cleanup (planed)
  360. *)
  361. if !cancel_inlining || (Common.platform ctx.com Js && not !force && (init <> None || !has_vars)) then
  362. None
  363. else
  364. let wrap e =
  365. (* we can't mute the type of the expression because it is not correct to do so *)
  366. (try
  367. let etype = if has_params then map_type e.etype else e.etype in
  368. (* if the expression is "untyped" and we don't want to unify it accidentally ! *)
  369. (match follow e.etype with
  370. | TMono _ ->
  371. (match follow tret with
  372. | TEnum ({ e_path = [],"Void" },_) | TAbstract ({ a_path = [],"Void" },_) -> e
  373. | _ -> raise (Unify_error []))
  374. | _ -> try
  375. type_eq EqStrict etype tret;
  376. e
  377. with Unify_error _ when (match ctx.com.platform with Cpp -> true | Flash when Common.defined ctx.com Define.As3 -> true | _ -> false) ->
  378. (* try to detect upcasts: in that case we may use a safe cast *)
  379. Type.unify tret etype;
  380. let ct = match follow tret with
  381. | TInst(c,_) -> Some (TClassDecl c)
  382. | _ -> None
  383. in
  384. mk (TCast (e,ct)) tret e.epos)
  385. with Unify_error _ ->
  386. mk (TCast (e,None)) tret e.epos)
  387. in
  388. let e = (match e.eexpr, init with
  389. | _, None when not !has_return_value ->
  390. {e with etype = tret}
  391. | TBlock [e] , None -> wrap e
  392. | _ , None -> wrap e
  393. | TBlock l, Some init -> mk (TBlock (init :: l)) tret e.epos
  394. | _, Some init -> mk (TBlock [init;e]) tret e.epos
  395. ) in
  396. (* we need to replace type-parameters that were used in the expression *)
  397. if not has_params then
  398. Some e
  399. else
  400. let mt = map_type cf.cf_type in
  401. let unify_func () = unify_raise ctx mt (TFun (List.map (fun e -> "",false,e.etype) params,tret)) p in
  402. (match follow ethis.etype with
  403. | TAnon a -> (match !(a.a_status) with
  404. | Statics {cl_kind = KAbstractImpl a } when Meta.has Meta.Impl cf.cf_meta ->
  405. if cf.cf_name <> "_new" then begin
  406. (* the first argument must unify with a_this for abstract implementation functions *)
  407. let tb = (TFun(("",false,map_type a.a_this) :: List.map (fun e -> "",false,e.etype) (List.tl params),tret)) in
  408. unify_raise ctx mt tb p
  409. end
  410. | _ -> unify_func())
  411. | _ -> unify_func());
  412. (*
  413. this is very expensive since we are building the substitution list for
  414. every expression, but hopefully in such cases the expression size is small
  415. *)
  416. let vars = Hashtbl.create 0 in
  417. let map_var v =
  418. if not (Hashtbl.mem vars v.v_id) then begin
  419. Hashtbl.add vars v.v_id ();
  420. v.v_type <- map_type v.v_type;
  421. end;
  422. v
  423. in
  424. let rec map_expr_type e = Type.map_expr_type map_expr_type map_type map_var e in
  425. Some (map_expr_type e)
  426. (* ---------------------------------------------------------------------- *)
  427. (* LOOPS *)
  428. let optimize_for_loop ctx i e1 e2 p =
  429. let t_void = ctx.t.tvoid in
  430. let t_int = ctx.t.tint in
  431. let lblock el = Some (mk (TBlock el) t_void p) in
  432. let mk_field e n =
  433. TField (e,try quick_field e.etype n with Not_found -> assert false)
  434. in
  435. let gen_int_iter pt =
  436. let i = add_local ctx i pt in
  437. let index = gen_local ctx t_int in
  438. let arr, avars = (match e1.eexpr with
  439. | TLocal _ -> e1, []
  440. | _ ->
  441. let atmp = gen_local ctx e1.etype in
  442. mk (TLocal atmp) e1.etype e1.epos, [atmp,Some e1]
  443. ) in
  444. let iexpr = mk (TLocal index) t_int p in
  445. let e2 = type_expr ctx e2 NoValue in
  446. let aget = mk (TVars [i,Some (mk (TArray (arr,iexpr)) pt p)]) t_void p in
  447. let incr = mk (TUnop (Increment,Prefix,iexpr)) t_int p in
  448. let block = match e2.eexpr with
  449. | TBlock el -> mk (TBlock (aget :: incr :: el)) t_void e2.epos
  450. | _ -> mk (TBlock [aget;incr;e2]) t_void p
  451. in
  452. let ivar = index, Some (mk (TConst (TInt 0l)) t_int p) in
  453. lblock [
  454. mk (TVars (ivar :: avars)) t_void p;
  455. mk (TWhile (
  456. mk (TBinop (OpLt, iexpr, mk (mk_field arr "length") t_int p)) ctx.t.tbool p,
  457. block,
  458. NormalWhile
  459. )) t_void p;
  460. ]
  461. in
  462. match e1.eexpr, follow e1.etype with
  463. | TNew ({ cl_path = ([],"IntIterator") },[],[i1;i2]) , _ ->
  464. let max = (match i1.eexpr , i2.eexpr with
  465. | TConst (TInt a), TConst (TInt b) when Int32.compare b a < 0 -> error "Range operate can't iterate backwards" p
  466. | _, TConst _ | _ , TLocal _ -> None
  467. | _ -> Some (gen_local ctx t_int)
  468. ) in
  469. let tmp = gen_local ctx t_int in
  470. let i = add_local ctx i t_int in
  471. let rec check e =
  472. match e.eexpr with
  473. | TBinop (OpAssign,{ eexpr = TLocal l },_)
  474. | TBinop (OpAssignOp _,{ eexpr = TLocal l },_)
  475. | TUnop (Increment,_,{ eexpr = TLocal l })
  476. | TUnop (Decrement,_,{ eexpr = TLocal l }) when l == i ->
  477. error "Loop variable cannot be modified" e.epos
  478. | _ ->
  479. Type.iter check e
  480. in
  481. let e2 = type_expr ctx e2 NoValue in
  482. check e2;
  483. let etmp = mk (TLocal tmp) t_int p in
  484. let incr = mk (TUnop (Increment,Postfix,etmp)) t_int p in
  485. let init = mk (TVars [i,Some incr]) t_void p in
  486. let block = match e2.eexpr with
  487. | TBlock el -> mk (TBlock (init :: el)) t_void e2.epos
  488. | _ -> mk (TBlock [init;e2]) t_void p
  489. in
  490. (*
  491. force locals to be of Int type (to prevent Int/UInt issues)
  492. *)
  493. let i2 = match i2.etype with
  494. | TInst({ cl_path = ([],"Int") }, []) | TAbstract ({ a_path = ([],"Int") }, []) -> i2
  495. | _ -> { i2 with eexpr = TCast(i2, None); etype = t_int }
  496. in
  497. (match max with
  498. | None ->
  499. lblock [
  500. mk (TVars [tmp,Some i1]) t_void p;
  501. mk (TWhile (
  502. mk (TBinop (OpLt, etmp, i2)) ctx.t.tbool p,
  503. block,
  504. NormalWhile
  505. )) t_void p;
  506. ]
  507. | Some max ->
  508. lblock [
  509. mk (TVars [tmp,Some i1;max,Some i2]) t_void p;
  510. mk (TWhile (
  511. mk (TBinop (OpLt, etmp, mk (TLocal max) t_int p)) ctx.t.tbool p,
  512. block,
  513. NormalWhile
  514. )) t_void p;
  515. ])
  516. | _ , TInst({ cl_path = [],"Array" },[pt])
  517. | _ , TInst({ cl_path = ["flash"],"Vector" },[pt]) ->
  518. gen_int_iter pt
  519. | _ , 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) ->
  520. gen_int_iter (apply_params c.cl_types pl pt)
  521. | _ , TInst ({ cl_kind = KGenericInstance ({ cl_path = ["haxe";"ds"],"GenericStack" },[t]) } as c,[]) ->
  522. let tcell = (try (PMap.find "head" c.cl_fields).cf_type with Not_found -> assert false) in
  523. let i = add_local ctx i t in
  524. let cell = gen_local ctx tcell in
  525. let cexpr = mk (TLocal cell) tcell p in
  526. let e2 = type_expr ctx e2 NoValue in
  527. let evar = mk (TVars [i,Some (mk (mk_field cexpr "elt") t p)]) t_void p in
  528. let enext = mk (TBinop (OpAssign,cexpr,mk (mk_field cexpr "next") tcell p)) tcell p in
  529. let block = match e2.eexpr with
  530. | TBlock el -> mk (TBlock (evar :: enext :: el)) t_void e2.epos
  531. | _ -> mk (TBlock [evar;enext;e2]) t_void p
  532. in
  533. lblock [
  534. mk (TVars [cell,Some (mk (mk_field e1 "head") tcell p)]) t_void p;
  535. mk (TWhile (
  536. mk (TBinop (OpNotEq, cexpr, mk (TConst TNull) tcell p)) ctx.t.tbool p,
  537. block,
  538. NormalWhile
  539. )) t_void p
  540. ]
  541. | _ ->
  542. None
  543. (* ---------------------------------------------------------------------- *)
  544. (* SANITIZE *)
  545. (*
  546. makes sure that when an AST get generated to source code, it will not
  547. generate expressions that evaluate differently. It is then necessary to
  548. add parenthesises around some binary expressions when the AST does not
  549. correspond to the natural operand priority order for the platform
  550. *)
  551. (*
  552. this is the standard C++ operator precedence, which is also used by both JS and PHP
  553. *)
  554. let standard_precedence op =
  555. let left = true and right = false in
  556. match op with
  557. | OpMult | OpDiv | OpMod -> 5, left
  558. | OpAdd | OpSub -> 6, left
  559. | OpShl | OpShr | OpUShr -> 7, left
  560. | OpLt | OpLte | OpGt | OpGte -> 8, left
  561. | OpEq | OpNotEq -> 9, left
  562. | OpAnd -> 10, left
  563. | OpXor -> 11, left
  564. | OpOr -> 12, left
  565. | OpInterval -> 13, right (* haxe specific *)
  566. | OpBoolAnd -> 14, left
  567. | OpBoolOr -> 15, left
  568. | OpArrow -> 16, left
  569. | OpAssignOp OpAssign -> 17, right (* mimics ?: *)
  570. | OpAssign | OpAssignOp _ -> 18, right
  571. let rec need_parent e =
  572. match e.eexpr with
  573. | TConst _ | TLocal _ | TArray _ | TField _ | TParenthesis _ | TCall _ | TNew _ | TTypeExpr _ | TObjectDecl _ | TArrayDecl _ -> false
  574. | TCast (e,None) -> need_parent e
  575. | TCast _ | TThrow _ | TReturn _ | TTry _ | TMatch _ | TSwitch _ | TFor _ | TIf _ | TWhile _ | TBinop _ | TContinue | TBreak
  576. | TBlock _ | TVars _ | TFunction _ | TUnop _ -> true
  577. let rec add_final_return e t =
  578. let def_return p =
  579. let c = (match follow t with
  580. | TInst ({ cl_path = [],"Int" },_) -> TInt 0l
  581. | TInst ({ cl_path = [],"Float" },_) -> TFloat "0."
  582. | TEnum ({ e_path = [],"Bool" },_) -> TBool false
  583. | TAbstract ({ a_path = [],"Int" },_) -> TInt 0l
  584. | TAbstract ({ a_path = [],"Float" },_) -> TFloat "0."
  585. | TAbstract ({ a_path = [],"Bool" },_) -> TBool false
  586. | _ -> TNull
  587. ) in
  588. { eexpr = TReturn (Some { eexpr = TConst c; epos = p; etype = t }); etype = t; epos = p }
  589. in
  590. match e.eexpr with
  591. | TBlock el ->
  592. (match List.rev el with
  593. | [] -> e
  594. | elast :: el ->
  595. match add_final_return elast t with
  596. | { eexpr = TBlock el2 } -> { e with eexpr = TBlock ((List.rev el) @ el2) }
  597. | elast -> { e with eexpr = TBlock (List.rev (elast :: el)) })
  598. | TReturn _ ->
  599. e
  600. | _ ->
  601. { e with eexpr = TBlock [e;def_return e.epos] }
  602. let sanitize_expr com e =
  603. let parent e =
  604. match e.eexpr with
  605. | TParenthesis _ -> e
  606. | _ -> mk (TParenthesis e) e.etype e.epos
  607. in
  608. let block e =
  609. match e.eexpr with
  610. | TBlock _ -> e
  611. | _ -> mk (TBlock [e]) e.etype e.epos
  612. in
  613. let complex e =
  614. (* complex expressions are the one that once generated to source consists in several expressions *)
  615. match e.eexpr with
  616. | TVars _ (* needs to be put into blocks *)
  617. | TFor _ (* a temp var is needed for holding iterator *)
  618. | TMatch _ (* a temp var is needed for holding enum *)
  619. | TCall ({ eexpr = TLocal { v_name = "__js__" } },_) (* we never know *)
  620. -> block e
  621. | _ -> e
  622. in
  623. (* tells if the printed expresssion ends with an if without else *)
  624. let rec has_if e =
  625. match e.eexpr with
  626. | TIf (_,_,None) -> true
  627. | TWhile (_,e,NormalWhile) -> has_if e
  628. | TFor (_,_,e) -> has_if e
  629. | _ -> false
  630. in
  631. match e.eexpr with
  632. | TConst TNull ->
  633. if com.config.pf_static && not (is_nullable e.etype) then
  634. (match follow e.etype with
  635. | TMono _ -> () (* in these cases the null will cast to default value *)
  636. | TFun _ -> () (* this is a bit a particular case, maybe flash-specific actually *)
  637. | _ -> com.error ("On static platforms, null can't be used as basic type " ^ s_type (print_context()) e.etype) e.epos);
  638. e
  639. | TBinop (op,e1,e2) ->
  640. let swap op1 op2 =
  641. let p1, left1 = standard_precedence op1 in
  642. let p2, _ = standard_precedence op2 in
  643. left1 && p1 <= p2
  644. in
  645. let rec loop ee left =
  646. match ee.eexpr with
  647. | TBinop (op2,_,_) -> if left then not (swap op2 op) else swap op op2
  648. | TIf _ -> if left then not (swap (OpAssignOp OpAssign) op) else swap op (OpAssignOp OpAssign)
  649. | TCast (e,None) -> loop e left
  650. | _ -> false
  651. in
  652. let e1 = if loop e1 true then parent e1 else e1 in
  653. let e2 = if loop e2 false then parent e2 else e2 in
  654. { e with eexpr = TBinop (op,e1,e2) }
  655. | TUnop (op,mode,e2) ->
  656. let rec loop ee =
  657. match ee.eexpr with
  658. | TBinop _ | TIf _ -> parent e2
  659. | TCast (e,None) -> loop e
  660. | _ -> e2
  661. in
  662. { e with eexpr = TUnop (op,mode,loop e2) }
  663. | TIf (e1,e2,eelse) ->
  664. let e1 = parent e1 in
  665. let e2 = (if (eelse <> None && has_if e2) || (match e2.eexpr with TIf _ -> true | _ -> false) then block e2 else complex e2) in
  666. let eelse = (match eelse with None -> None | Some e -> Some (complex e)) in
  667. { e with eexpr = TIf (e1,e2,eelse) }
  668. | TWhile (e1,e2,flag) ->
  669. let e1 = parent e1 in
  670. let e2 = complex e2 in
  671. { e with eexpr = TWhile (e1,e2,flag) }
  672. | TFor (v,e1,e2) ->
  673. let e2 = complex e2 in
  674. { e with eexpr = TFor (v,e1,e2) }
  675. | TFunction f ->
  676. let f = (match follow f.tf_type with
  677. | TEnum ({ e_path = [],"Void" },[]) | TAbstract ({ a_path = [],"Void" },[]) -> f
  678. | t ->
  679. if com.config.pf_add_final_return then { f with tf_expr = add_final_return f.tf_expr t } else f
  680. ) in
  681. let f = (match f.tf_expr.eexpr with
  682. | TBlock _ -> f
  683. | _ -> { f with tf_expr = block f.tf_expr }
  684. ) in
  685. { e with eexpr = TFunction f }
  686. | TCall (e2,args) ->
  687. if need_parent e2 then { e with eexpr = TCall(parent e2,args) } else e
  688. | TField (e2,f) ->
  689. if need_parent e2 then { e with eexpr = TField(parent e2,f) } else e
  690. | TArray (e1,e2) ->
  691. if need_parent e1 then { e with eexpr = TArray(parent e1,e2) } else e
  692. | TTry (e1,catches) ->
  693. let e1 = block e1 in
  694. let catches = List.map (fun (v,e) -> v, block e) catches in
  695. { e with eexpr = TTry (e1,catches) }
  696. | TSwitch (e1,cases,def) ->
  697. let e1 = parent e1 in
  698. let cases = List.map (fun (el,e) -> el, complex e) cases in
  699. let def = (match def with None -> None | Some e -> Some (complex e)) in
  700. { e with eexpr = TSwitch (e1,cases,def) }
  701. | TMatch (e1, en, cases, def) ->
  702. let e1 = parent e1 in
  703. let cases = List.map (fun (el,vars,e) -> el, vars, complex e) cases in
  704. let def = (match def with None -> None | Some e -> Some (complex e)) in
  705. { e with eexpr = TMatch (e1,en,cases,def) }
  706. | _ ->
  707. e
  708. let reduce_expr ctx e =
  709. match e.eexpr with
  710. | TSwitch (_,cases,_) ->
  711. List.iter (fun (cl,_) ->
  712. List.iter (fun e ->
  713. match e.eexpr with
  714. | TCall ({ eexpr = TField (_,FEnum _) },_) -> error "Not-constant enum in switch cannot be matched" e.epos
  715. | _ -> ()
  716. ) cl
  717. ) cases;
  718. e
  719. | TBlock l ->
  720. (match List.rev l with
  721. | [] -> e
  722. | ec :: l ->
  723. (* remove all no-ops : not-final constants in blocks *)
  724. match List.filter (fun e -> match e.eexpr with
  725. | TConst _
  726. | TBlock []
  727. | TObjectDecl [] ->
  728. false
  729. | _ ->
  730. true
  731. ) l with
  732. | [] -> { ec with epos = e.epos }
  733. | l -> { e with eexpr = TBlock (List.rev (ec :: l)) })
  734. | TParenthesis ec ->
  735. { ec with epos = e.epos }
  736. | TTry (e,[]) ->
  737. e
  738. | _ ->
  739. e
  740. let rec sanitize ctx e =
  741. sanitize_expr ctx.com (reduce_expr ctx (Type.map_expr (sanitize ctx) e))
  742. (* ---------------------------------------------------------------------- *)
  743. (* REDUCE *)
  744. let rec reduce_loop ctx e =
  745. let is_float t =
  746. match follow t with
  747. | TAbstract({ a_path = [],"Float" },_) -> true
  748. | TInst ({ cl_path = ([],"Float") },_) -> true
  749. | _ -> false
  750. in
  751. let is_numeric t =
  752. match follow t with
  753. | TAbstract({ a_path = [],("Float"|"Int") },_) -> true
  754. | TInst ({ cl_path = ([],("Float" | "Int")) },_) -> true
  755. | _ -> false
  756. in
  757. let e = Type.map_expr (reduce_loop ctx) e in
  758. let check_float op f1 f2 =
  759. let f = op f1 f2 in
  760. let fstr = string_of_float f in
  761. 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
  762. in
  763. sanitize_expr ctx.com (match e.eexpr with
  764. | TIf ({ eexpr = TConst (TBool t) },e1,e2) ->
  765. (if t then e1 else match e2 with None -> { e with eexpr = TBlock [] } | Some e -> e)
  766. | TWhile ({ eexpr = TConst (TBool false) },sub,flag) ->
  767. (match flag with
  768. | NormalWhile -> { e with eexpr = TBlock [] } (* erase sub *)
  769. | DoWhile -> e) (* we cant remove while since sub can contain continue/break *)
  770. | TBinop (op,e1,e2) ->
  771. (match e1.eexpr, e2.eexpr with
  772. | TConst (TInt 0l) , _ when op = OpAdd && is_numeric e2.etype -> e2
  773. | TConst (TInt 1l) , _ when op = OpMult -> e2
  774. | TConst (TFloat v) , _ when op = OpAdd && float_of_string v = 0. && is_float e2.etype -> e2
  775. | TConst (TFloat v) , _ when op = OpMult && float_of_string v = 1. && is_float e2.etype -> e2
  776. | _ , TConst (TInt 0l) when (match op with OpAdd -> is_numeric e1.etype | OpSub | OpShr | OpShl -> true | _ -> false) -> e1 (* bits operations might cause overflow *)
  777. | _ , TConst (TInt 1l) when op = OpMult -> e1
  778. | _ , 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 *)
  779. | _ , TConst (TFloat v) when op = OpMult && float_of_string v = 1. && is_float e1.etype -> e1
  780. | TConst TNull, TConst TNull ->
  781. (match op with
  782. | OpEq -> { e with eexpr = TConst (TBool true) }
  783. | OpNotEq -> { e with eexpr = TConst (TBool false) }
  784. | _ -> e)
  785. | TConst (TInt a), TConst (TInt b) ->
  786. let opt f = try { e with eexpr = TConst (TInt (f a b)) } with Exit -> e in
  787. let check_overflow f =
  788. opt (fun a b ->
  789. let v = f (Int64.of_int32 a) (Int64.of_int32 b) in
  790. let iv = Int64.to_int32 v in
  791. if Int64.compare (Int64.of_int32 iv) v <> 0 then raise Exit;
  792. iv
  793. )
  794. in
  795. let ebool t =
  796. { e with eexpr = TConst (TBool (t (Int32.compare a b) 0)) }
  797. in
  798. (match op with
  799. | OpAdd -> check_overflow Int64.add
  800. | OpSub -> check_overflow Int64.sub
  801. | OpMult -> check_overflow Int64.mul
  802. | OpDiv -> check_float ( /. ) (Int32.to_float a) (Int32.to_float b)
  803. | OpAnd -> opt Int32.logand
  804. | OpOr -> opt Int32.logor
  805. | OpXor -> opt Int32.logxor
  806. | OpShl -> opt (fun a b -> Int32.shift_left a (Int32.to_int b))
  807. | OpShr -> opt (fun a b -> Int32.shift_right a (Int32.to_int b))
  808. | OpUShr -> opt (fun a b -> Int32.shift_right_logical a (Int32.to_int b))
  809. | OpEq -> ebool (=)
  810. | OpNotEq -> ebool (<>)
  811. | OpGt -> ebool (>)
  812. | OpGte -> ebool (>=)
  813. | OpLt -> ebool (<)
  814. | OpLte -> ebool (<=)
  815. | _ -> e)
  816. | TConst ((TFloat _ | TInt _) as ca), TConst ((TFloat _ | TInt _) as cb) ->
  817. let fa = (match ca with
  818. | TFloat a -> float_of_string a
  819. | TInt a -> Int32.to_float a
  820. | _ -> assert false
  821. ) in
  822. let fb = (match cb with
  823. | TFloat b -> float_of_string b
  824. | TInt b -> Int32.to_float b
  825. | _ -> assert false
  826. ) in
  827. let fop op = check_float op fa fb in
  828. let ebool t =
  829. { e with eexpr = TConst (TBool (t (compare fa fb) 0)) }
  830. in
  831. (match op with
  832. | OpAdd -> fop (+.)
  833. | OpDiv -> fop (/.)
  834. | OpSub -> fop (-.)
  835. | OpMult -> fop ( *. )
  836. | OpEq -> ebool (=)
  837. | OpNotEq -> ebool (<>)
  838. | OpGt -> ebool (>)
  839. | OpGte -> ebool (>=)
  840. | OpLt -> ebool (<)
  841. | OpLte -> ebool (<=)
  842. | _ -> e)
  843. | TConst (TBool a), TConst (TBool b) ->
  844. let ebool f =
  845. { e with eexpr = TConst (TBool (f a b)) }
  846. in
  847. (match op with
  848. | OpEq -> ebool (=)
  849. | OpNotEq -> ebool (<>)
  850. | OpBoolAnd -> ebool (&&)
  851. | OpBoolOr -> ebool (||)
  852. | _ -> e)
  853. | TConst a, TConst b when op = OpEq || op = OpNotEq ->
  854. let ebool b =
  855. { e with eexpr = TConst (TBool (if op = OpEq then b else not b)) }
  856. in
  857. (match a, b with
  858. | TInt a, TFloat b | TFloat b, TInt a -> ebool (Int32.to_float a = float_of_string b)
  859. | _ -> ebool (a = b))
  860. | TConst (TBool a), _ ->
  861. (match op with
  862. | OpBoolAnd -> if a then e2 else { e with eexpr = TConst (TBool false) }
  863. | OpBoolOr -> if a then { e with eexpr = TConst (TBool true) } else e2
  864. | _ -> e)
  865. | _ , TConst (TBool a) ->
  866. (match op with
  867. | OpBoolAnd when a -> e1
  868. | OpBoolOr when not a -> e1
  869. | _ -> e)
  870. | TField (_,FEnum (e1,f1)), TField (_,FEnum (e2,f2)) when e1 == e2 ->
  871. (match op with
  872. | OpEq -> { e with eexpr = TConst (TBool (f1 == f2)) }
  873. | OpNotEq -> { e with eexpr = TConst (TBool (f1 != f2)) }
  874. | _ -> e)
  875. | _, TCall ({ eexpr = TField (_,FEnum _) },_) | TCall ({ eexpr = TField (_,FEnum _) },_), _ ->
  876. (match op with
  877. | OpAssign -> e
  878. | _ ->
  879. error "You cannot directly compare enums with arguments. Use either 'switch' or 'Type.enumEq'" e.epos)
  880. | _ ->
  881. e)
  882. | TUnop (op,flag,esub) ->
  883. (match op, esub.eexpr with
  884. | Not, TConst (TBool f) -> { e with eexpr = TConst (TBool (not f)) }
  885. | Neg, TConst (TInt i) -> { e with eexpr = TConst (TInt (Int32.neg i)) }
  886. | NegBits, TConst (TInt i) -> { e with eexpr = TConst (TInt (Int32.lognot i)) }
  887. | Neg, TConst (TFloat f) ->
  888. let v = 0. -. float_of_string f in
  889. let vstr = string_of_float v in
  890. if float_of_string vstr = v then
  891. { e with eexpr = TConst (TFloat vstr) }
  892. else
  893. e
  894. | _ -> e
  895. )
  896. | TCall ({ eexpr = TField ({ eexpr = TTypeExpr (TClassDecl c) },field) },params) ->
  897. (match api_inline ctx c (field_name field) params e.epos with
  898. | None -> reduce_expr ctx e
  899. | Some e -> reduce_loop ctx e)
  900. | TCall ({ eexpr = TFunction func } as ef,el) ->
  901. let cf = mk_field "" ef.etype e.epos in
  902. let ethis = mk (TConst TThis) t_dynamic e.epos in
  903. let rt = (match follow ef.etype with TFun (_,rt) -> rt | _ -> assert false) in
  904. let inl = (try type_inline ctx cf func ethis el rt None e.epos false with Error (Custom _,_) -> None) in
  905. (match inl with
  906. | None -> reduce_expr ctx e
  907. | Some e -> reduce_loop ctx e)
  908. | TCall ({ eexpr = TField (o,FClosure (c,cf)) } as f,el) ->
  909. let fmode = (match c with None -> FAnon cf | Some c -> FInstance (c,cf)) in
  910. { e with eexpr = TCall ({ f with eexpr = TField (o,fmode) },el) }
  911. | _ ->
  912. reduce_expr ctx e)
  913. let reduce_expression ctx e =
  914. if ctx.com.foptimize then reduce_loop ctx e else e
  915. let rec make_constant_expression ctx e =
  916. let e = ctx.g.do_optimize ctx e in
  917. match e.eexpr with
  918. | TConst _ -> Some e
  919. | TBinop ((OpAdd|OpSub|OpMult|OpDiv|OpMod) as op,e1,e2) -> (match make_constant_expression ctx e1,make_constant_expression ctx e2 with
  920. | Some e1, Some e2 -> Some (mk (TBinop(op, e1, e2)) e.etype e.epos)
  921. | _ -> None)
  922. | TParenthesis e -> Some e
  923. | TTypeExpr _ -> Some e
  924. (* try to inline static function calls *)
  925. | TCall ({ etype = TFun(_,ret); eexpr = TField (_,FStatic (c,cf)) },el) ->
  926. (try
  927. let func = match cf.cf_expr with Some ({eexpr = TFunction func}) -> func | _ -> raise Not_found in
  928. let ethis = mk (TConst TThis) t_dynamic e.epos in
  929. let inl = (try type_inline ctx cf func ethis el ret None e.epos false with Error (Custom _,_) -> None) in
  930. (match inl with
  931. | None -> None
  932. | Some e -> make_constant_expression ctx e)
  933. with Not_found -> None)
  934. | _ -> None
  935. (* ---------------------------------------------------------------------- *)
  936. (* COMPLETION *)
  937. exception Return of Ast.expr
  938. type compl_locals = {
  939. mutable r : (string, (complex_type option * (int * Ast.expr * compl_locals) option)) PMap.t;
  940. }
  941. let optimize_completion_expr e =
  942. let iid = ref 0 in
  943. let typing_side_effect = ref false in
  944. let locals : compl_locals = { r = PMap.empty } in
  945. let save() = let old = locals.r in (fun() -> locals.r <- old) in
  946. let get_local n = PMap.find n locals.r in
  947. let maybe_typed e =
  948. match fst e with
  949. | EConst (Ident "null") -> false
  950. | _ -> true
  951. in
  952. let decl n t e =
  953. typing_side_effect := true;
  954. 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
  955. in
  956. let rec loop e =
  957. let p = snd e in
  958. match fst e with
  959. | EConst (Ident n) ->
  960. (try
  961. (match get_local n with
  962. | Some _ , _ -> ()
  963. | _ -> typing_side_effect := true)
  964. with Not_found ->
  965. ());
  966. e
  967. | EBinop (OpAssign,(EConst (Ident n),_),esub) ->
  968. (try
  969. (match get_local n with
  970. | None, None when maybe_typed esub -> decl n None (Some esub)
  971. | _ -> ())
  972. with Not_found ->
  973. ());
  974. map e
  975. | EVars vl ->
  976. let vl = List.map (fun (v,t,e) ->
  977. let e = (match e with None -> None | Some e -> Some (loop e)) in
  978. decl v t e;
  979. (v,t,e)
  980. ) vl in
  981. (EVars vl,p)
  982. | EBlock el ->
  983. let old = save() in
  984. let told = ref (!typing_side_effect) in
  985. let el = List.fold_left (fun acc e ->
  986. typing_side_effect := false;
  987. let e = loop e in
  988. if !typing_side_effect then begin told := true; e :: acc end else acc
  989. ) [] el in
  990. old();
  991. typing_side_effect := !told;
  992. (EBlock (List.rev el),p)
  993. | EFunction (v,f) ->
  994. (match v with
  995. | None -> ()
  996. | Some name ->
  997. decl name None (Some e));
  998. let old = save() in
  999. List.iter (fun (n,_,t,e) -> decl n t e) f.f_args;
  1000. let e = map e in
  1001. old();
  1002. e
  1003. | EFor ((EIn ((EConst (Ident n),_) as id,it),p),efor) ->
  1004. let it = loop it in
  1005. let old = save() in
  1006. let etmp = (EConst (Ident "$tmp"),p) in
  1007. decl n None (Some (EBlock [
  1008. (EVars ["$tmp",None,None],p);
  1009. (EFor ((EIn (id,it),p),(EBinop (OpAssign,etmp,(EConst (Ident n),p)),p)),p);
  1010. etmp
  1011. ],p));
  1012. let efor = loop efor in
  1013. old();
  1014. (EFor ((EIn (id,it),p),efor),p)
  1015. | EReturn _ ->
  1016. typing_side_effect := true;
  1017. map e
  1018. | ESwitch (e,cases,def) ->
  1019. let e = loop e in
  1020. let cases = List.map (fun (el,eg,eo) -> match eo with
  1021. | None ->
  1022. el,eg,eo
  1023. | Some e ->
  1024. let el = List.map loop el in
  1025. let old = save() in
  1026. List.iter (fun e ->
  1027. match fst e with
  1028. | ECall (_,pl) ->
  1029. List.iter (fun p ->
  1030. match fst p with
  1031. | EConst (Ident i) -> decl i None None (* sadly *)
  1032. | _ -> ()
  1033. ) pl
  1034. | _ -> ()
  1035. ) el;
  1036. let e = loop e in
  1037. old();
  1038. el, eg, Some e
  1039. ) cases in
  1040. let def = match def with
  1041. | None -> None
  1042. | Some None -> Some None
  1043. | Some (Some e) -> Some (Some (loop e))
  1044. in
  1045. (ESwitch (e,cases,def),p)
  1046. | ETry (et,cl) ->
  1047. let et = loop et in
  1048. let cl = List.map (fun (n,t,e) ->
  1049. let old = save() in
  1050. decl n (Some t) None;
  1051. let e = loop e in
  1052. old();
  1053. n, t, e
  1054. ) cl in
  1055. (ETry (et,cl),p)
  1056. | EDisplay (s,call) ->
  1057. typing_side_effect := true;
  1058. let tmp_locals = ref [] in
  1059. let tmp_hlocals = ref PMap.empty in
  1060. let rec subst_locals locals e =
  1061. match fst e with
  1062. | EConst (Ident n) ->
  1063. let p = snd e in
  1064. (try
  1065. (match PMap.find n locals.r with
  1066. | Some t , _ -> (ECheckType ((EConst (Ident "null"),p),t),p)
  1067. | _, Some (id,e,lc) ->
  1068. let name = (try
  1069. PMap.find id (!tmp_hlocals)
  1070. with Not_found ->
  1071. let e = subst_locals lc e in
  1072. let name = "$tmp_" ^ string_of_int id in
  1073. tmp_locals := (name,None,Some e) :: !tmp_locals;
  1074. tmp_hlocals := PMap.add id name !tmp_hlocals;
  1075. name
  1076. ) in
  1077. (EConst (Ident name),p)
  1078. | None, None ->
  1079. (* we can't replace the var *)
  1080. raise Exit)
  1081. with Not_found ->
  1082. (* not found locals are most likely to be member/static vars *)
  1083. e)
  1084. | _ ->
  1085. Ast.map_expr (subst_locals locals) e
  1086. in
  1087. (try
  1088. let e = subst_locals locals s in
  1089. let e = (EBlock [(EVars (List.rev !tmp_locals),p);(EDisplay (e,call),p)],p) in
  1090. raise (Return e)
  1091. with Exit ->
  1092. map e)
  1093. | EDisplayNew _ ->
  1094. raise (Return e)
  1095. | _ ->
  1096. map e
  1097. and map e =
  1098. Ast.map_expr loop e
  1099. in
  1100. (try loop e with Return e -> e)
  1101. let optimize_completion c fields =
  1102. let cp = !Parser.resume_display in
  1103. List.map (fun f ->
  1104. if cp.pmin = 0 || (f.cff_pos.pmin <= cp.pmin && f.cff_pos.pmax >= cp.pmax) then
  1105. let k = try (match f.cff_kind with
  1106. | FVar (t,Some e) -> FVar (t,Some (optimize_completion_expr e))
  1107. | FFun fn -> (match optimize_completion_expr (EFunction (None,fn),f.cff_pos) with (EFunction (None,fn),_) -> FFun fn | e -> FFun({ fn with f_expr = Some e; f_args = []; }))
  1108. | k -> k
  1109. ) with Exit -> f.cff_kind in
  1110. { f with cff_kind = k }
  1111. else
  1112. f
  1113. ) fields
  1114. (* ---------------------------------------------------------------------- *)