codegen.ml 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927
  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. (* TOOLS *)
  28. let field e name t p =
  29. mk (TField (e,try quick_field e.etype name with Not_found -> assert false)) t p
  30. let fcall e name el ret p =
  31. let ft = tfun (List.map (fun e -> e.etype) el) ret in
  32. mk (TCall (field e name ft p,el)) ret p
  33. let mk_parent e =
  34. mk (TParenthesis e) e.etype e.epos
  35. let string com str p =
  36. mk (TConst (TString str)) com.basic.tstring p
  37. let binop op a b t p =
  38. mk (TBinop (op,a,b)) t p
  39. let index com e index t p =
  40. mk (TArray (e,mk (TConst (TInt (Int32.of_int index))) com.basic.tint p)) t p
  41. let concat e1 e2 =
  42. let e = (match e1.eexpr, e2.eexpr with
  43. | TBlock el1, TBlock el2 -> TBlock (el1@el2)
  44. | TBlock el, _ -> TBlock (el @ [e2])
  45. | _, TBlock el -> TBlock (e1 :: el)
  46. | _ , _ -> TBlock [e1;e2]
  47. ) in
  48. mk e e2.etype (punion e1.epos e2.epos)
  49. let type_constant com c p =
  50. let t = com.basic in
  51. match c with
  52. | Int s ->
  53. if String.length s > 10 && String.sub s 0 2 = "0x" then error "Invalid hexadecimal integer" p;
  54. (try mk (TConst (TInt (Int32.of_string s))) t.tint p
  55. with _ -> mk (TConst (TFloat s)) t.tfloat p)
  56. | Float f -> mk (TConst (TFloat f)) t.tfloat p
  57. | String s -> mk (TConst (TString s)) t.tstring p
  58. | Ident "true" -> mk (TConst (TBool true)) t.tbool p
  59. | Ident "false" -> mk (TConst (TBool false)) t.tbool p
  60. | Ident "null" -> mk (TConst TNull) (t.tnull (mk_mono())) p
  61. | Ident t -> error ("Invalid constant : " ^ t) p
  62. | Regexp _ -> error "Invalid constant" p
  63. let rec type_constant_value com (e,p) =
  64. match e with
  65. | EConst c ->
  66. type_constant com c p
  67. | EParenthesis e ->
  68. type_constant_value com e
  69. | EObjectDecl el ->
  70. mk (TObjectDecl (List.map (fun (n,e) -> n, type_constant_value com e) el)) (TAnon { a_fields = PMap.empty; a_status = ref Closed }) p
  71. | EArrayDecl el ->
  72. mk (TArrayDecl (List.map (type_constant_value com) el)) (com.basic.tarray t_dynamic) p
  73. | _ ->
  74. error "Constant value expected" p
  75. let rec has_properties c =
  76. List.exists (fun f ->
  77. match f.cf_kind with
  78. | Var { v_read = AccCall _ } -> true
  79. | Var { v_write = AccCall _ } -> true
  80. | _ -> false
  81. ) c.cl_ordered_fields || (match c.cl_super with Some (c,_) -> has_properties c | _ -> false)
  82. let get_properties fields =
  83. List.fold_left (fun acc f ->
  84. let acc = (match f.cf_kind with
  85. | Var { v_read = AccCall getter } -> ("get_" ^ f.cf_name , getter) :: acc
  86. | _ -> acc) in
  87. match f.cf_kind with
  88. | Var { v_write = AccCall setter } -> ("set_" ^ f.cf_name , setter) :: acc
  89. | _ -> acc
  90. ) [] fields
  91. let add_property_field com c =
  92. let p = c.cl_pos in
  93. let props = get_properties (c.cl_ordered_statics @ c.cl_ordered_fields) in
  94. match props with
  95. | [] -> ()
  96. | _ ->
  97. let fields,values = List.fold_left (fun (fields,values) (n,v) ->
  98. let cf = mk_field n com.basic.tstring p in
  99. PMap.add n cf fields,(n, string com v p) :: values
  100. ) (PMap.empty,[]) props in
  101. let t = mk_anon fields in
  102. let e = mk (TObjectDecl values) t p in
  103. let cf = mk_field "__properties__" t p in
  104. cf.cf_expr <- Some e;
  105. c.cl_statics <- PMap.add cf.cf_name cf c.cl_statics;
  106. c.cl_ordered_statics <- cf :: c.cl_ordered_statics
  107. (* -------------------------------------------------------------------------- *)
  108. (* REMOTING PROXYS *)
  109. let extend_remoting ctx c t p async prot =
  110. if c.cl_super <> None then error "Cannot extend several classes" p;
  111. (* remove forbidden packages *)
  112. let rules = ctx.com.package_rules in
  113. ctx.com.package_rules <- PMap.foldi (fun key r acc -> match r with Forbidden -> acc | _ -> PMap.add key r acc) rules PMap.empty;
  114. (* parse module *)
  115. let path = (t.tpackage,t.tname) in
  116. let new_name = (if async then "Async_" else "Remoting_") ^ t.tname in
  117. (* check if the proxy already exists *)
  118. let t = (try
  119. Typeload.load_type_def ctx p { tpackage = fst path; tname = new_name; tparams = []; tsub = None }
  120. with
  121. Error (Module_not_found _,p2) when p == p2 ->
  122. (* build it *)
  123. Common.log ctx.com ("Building proxy for " ^ s_type_path path);
  124. let file, decls = (try
  125. Typeload.parse_module ctx path p
  126. with
  127. | Not_found -> ctx.com.package_rules <- rules; error ("Could not load proxy module " ^ s_type_path path ^ (if fst path = [] then " (try using absolute path)" else "")) p
  128. | e -> ctx.com.package_rules <- rules; raise e) in
  129. ctx.com.package_rules <- rules;
  130. let base_fields = [
  131. { cff_name = "__cnx"; cff_pos = p; cff_doc = None; cff_meta = []; cff_access = []; cff_kind = FVar (Some (CTPath { tpackage = ["haxe";"remoting"]; tname = if async then "AsyncConnection" else "Connection"; tparams = []; tsub = None }),None) };
  132. { cff_name = "new"; cff_pos = p; cff_doc = None; cff_meta = []; cff_access = [APublic]; cff_kind = FFun { f_args = ["c",false,None,None]; f_type = None; f_expr = Some (EBinop (OpAssign,(EConst (Ident "__cnx"),p),(EConst (Ident "c"),p)),p); f_params = [] } };
  133. ] in
  134. let tvoid = CTPath { tpackage = []; tname = "Void"; tparams = []; tsub = None } in
  135. let build_field is_public acc f =
  136. if f.cff_name = "new" then
  137. acc
  138. else match f.cff_kind with
  139. | FFun fd when (is_public || List.mem APublic f.cff_access) && not (List.mem AStatic f.cff_access) ->
  140. if List.exists (fun (_,_,t,_) -> t = None) fd.f_args then error ("Field " ^ f.cff_name ^ " type is not complete and cannot be used by RemotingProxy") p;
  141. let eargs = [EArrayDecl (List.map (fun (a,_,_,_) -> (EConst (Ident a),p)) fd.f_args),p] in
  142. let ftype = (match fd.f_type with Some (CTPath { tpackage = []; tname = "Void" }) -> None | _ -> fd.f_type) in
  143. let fargs, eargs = if async then match ftype with
  144. | Some tret -> fd.f_args @ ["__callb",true,Some (CTFunction ([tret],tvoid)),None], eargs @ [EConst (Ident "__callb"),p]
  145. | _ -> fd.f_args, eargs @ [EConst (Ident "null"),p]
  146. else
  147. fd.f_args, eargs
  148. in
  149. let id = (EConst (String f.cff_name), p) in
  150. let id = if prot then id else ECall ((EConst (Ident "__unprotect__"),p),[id]),p in
  151. let expr = ECall (
  152. (EField (
  153. (ECall ((EField ((EConst (Ident "__cnx"),p),"resolve"),p),[id]),p),
  154. "call")
  155. ,p),eargs),p
  156. in
  157. let expr = if async || ftype = None then expr else (EReturn (Some expr),p) in
  158. let fd = {
  159. f_params = fd.f_params;
  160. f_args = fargs;
  161. f_type = if async then None else ftype;
  162. f_expr = Some (EBlock [expr],p);
  163. } in
  164. { cff_name = f.cff_name; cff_pos = p; cff_doc = None; cff_meta = []; cff_access = [APublic]; cff_kind = FFun fd } :: acc
  165. | _ -> acc
  166. in
  167. let decls = List.map (fun d ->
  168. match d with
  169. | EClass c, p when c.d_name = t.tname ->
  170. let is_public = List.mem HExtern c.d_flags || List.mem HInterface c.d_flags in
  171. let fields = List.rev (List.fold_left (build_field is_public) base_fields c.d_data) in
  172. (EClass { c with d_flags = []; d_name = new_name; d_data = fields },p)
  173. | _ -> d
  174. ) decls in
  175. let m = Typeload.type_module ctx (t.tpackage,new_name) file decls p in
  176. add_dependency ctx.m.curmod m;
  177. try
  178. List.find (fun tdecl -> snd (t_path tdecl) = new_name) m.m_types
  179. with Not_found ->
  180. error ("Module " ^ s_type_path path ^ " does not define type " ^ t.tname) p
  181. ) in
  182. match t with
  183. | TClassDecl c2 when c2.cl_types = [] -> c2.cl_build(); c.cl_super <- Some (c2,[]);
  184. | _ -> error "Remoting proxy must be a class without parameters" p
  185. (* -------------------------------------------------------------------------- *)
  186. (* HAXE.RTTI.GENERIC *)
  187. exception Generic_Exception of string * Ast.pos
  188. type generic_context = {
  189. ctx : typer;
  190. subst : (t * t) list;
  191. name : string;
  192. p : pos;
  193. mutable mg : module_def option;
  194. }
  195. let make_generic ctx ps pt p =
  196. let rec loop l1 l2 =
  197. match l1, l2 with
  198. | [] , [] -> []
  199. | (x,TLazy f) :: l1, _ -> loop ((x,(!f)()) :: l1) l2
  200. | (_,t1) :: l1 , t2 :: l2 -> (t1,t2) :: loop l1 l2
  201. | _ -> assert false
  202. in
  203. let name =
  204. String.concat "_" (List.map2 (fun (s,_) t ->
  205. let path = (match follow t with
  206. | TInst (ct,_) -> ct.cl_path
  207. | TEnum (e,_) -> e.e_path
  208. | TAbstract (a,_) when Meta.has Meta.RuntimeValue a.a_meta -> a.a_path
  209. | TMono _ -> raise (Generic_Exception (("Could not determine type for parameter " ^ s), p))
  210. | t -> raise (Generic_Exception (("Type parameter must be a class or enum instance (found " ^ (s_type (print_context()) t) ^ ")"), p))
  211. ) in
  212. match path with
  213. | [] , name -> name
  214. | l , name -> String.concat "_" l ^ "_" ^ name
  215. ) ps pt)
  216. in
  217. {
  218. ctx = ctx;
  219. subst = loop ps pt;
  220. name = name;
  221. p = p;
  222. mg = None;
  223. }
  224. let rec generic_substitute_type gctx t =
  225. match t with
  226. | TInst ({ cl_kind = KGeneric } as c2,tl2) ->
  227. (* maybe loop, or generate cascading generics *)
  228. let _, _, f = gctx.ctx.g.do_build_instance gctx.ctx (TClassDecl c2) gctx.p in
  229. let t = f (List.map (generic_substitute_type gctx) tl2) in
  230. (match follow t,gctx.mg with TInst(c,_), Some m -> add_dependency m c.cl_module | _ -> ());
  231. t
  232. | _ ->
  233. try List.assq t gctx.subst with Not_found -> Type.map (generic_substitute_type gctx) t
  234. let generic_substitute_expr gctx e =
  235. let vars = Hashtbl.create 0 in
  236. let build_var v =
  237. try
  238. Hashtbl.find vars v.v_id
  239. with Not_found ->
  240. let v2 = alloc_var v.v_name (generic_substitute_type gctx v.v_type) in
  241. Hashtbl.add vars v.v_id v2;
  242. v2
  243. in
  244. let rec build_expr e = map_expr_type build_expr (generic_substitute_type gctx) build_var e in
  245. build_expr e
  246. let is_generic_parameter ctx c =
  247. (* first check field parameters, then class parameters *)
  248. try
  249. ignore (List.assoc (snd c.cl_path) ctx.curfield.cf_params);
  250. Meta.has Meta.Generic ctx.curfield.cf_meta
  251. with Not_found -> try
  252. ignore(List.assoc (snd c.cl_path) ctx.type_params);
  253. (match ctx.curclass.cl_kind with | KGeneric -> true | _ -> false);
  254. with Not_found ->
  255. false
  256. let has_ctor_constraint c = match c.cl_kind with
  257. | KTypeParameter tl ->
  258. List.exists (fun t -> match follow t with
  259. | TAnon a when PMap.mem "new" a.a_fields -> true
  260. | _ -> false
  261. ) tl;
  262. | _ -> false
  263. let rec build_generic ctx c p tl =
  264. let pack = fst c.cl_path in
  265. let recurse = ref false in
  266. let rec check_recursive t =
  267. match follow t with
  268. | TInst (c2,tl) ->
  269. (match c2.cl_kind with
  270. | KTypeParameter tl ->
  271. if not (is_generic_parameter ctx c2) && has_ctor_constraint c2 then
  272. error "Type parameters with a constructor cannot be used non-generically" p;
  273. recurse := true
  274. | _ -> ());
  275. List.iter check_recursive tl;
  276. | _ ->
  277. ()
  278. in
  279. List.iter check_recursive tl;
  280. let gctx = try make_generic ctx c.cl_types tl p with Generic_Exception (msg,p) -> error msg p in
  281. let name = (snd c.cl_path) ^ "_" ^ gctx.name in
  282. if !recurse then begin
  283. TInst (c,tl) (* build a normal instance *)
  284. end else try
  285. Typeload.load_instance ctx { tpackage = pack; tname = name; tparams = []; tsub = None } p false
  286. with Error(Module_not_found path,_) when path = (pack,name) ->
  287. let m = (try Hashtbl.find ctx.g.modules (Hashtbl.find ctx.g.types_module c.cl_path) with Not_found -> assert false) in
  288. let ctx = { ctx with m = { ctx.m with module_types = m.m_types @ ctx.m.module_types } } in
  289. c.cl_build(); (* make sure the super class is already setup *)
  290. let mg = {
  291. m_id = alloc_mid();
  292. m_path = (pack,name);
  293. m_types = [];
  294. m_extra = module_extra (s_type_path (pack,name)) m.m_extra.m_sign 0. MFake;
  295. } in
  296. gctx.mg <- Some mg;
  297. let cg = mk_class mg (pack,name) c.cl_pos in
  298. mg.m_types <- [TClassDecl cg];
  299. Hashtbl.add ctx.g.modules mg.m_path mg;
  300. add_dependency mg m;
  301. add_dependency ctx.m.curmod mg;
  302. (* ensure that type parameters are set in dependencies *)
  303. let dep_stack = ref [] in
  304. let rec loop t =
  305. if not (List.memq t !dep_stack) then begin
  306. dep_stack := t :: !dep_stack;
  307. match t with
  308. | TInst (c,tl) -> add_dep c.cl_module tl
  309. | TEnum (e,tl) -> add_dep e.e_module tl
  310. | TType (t,tl) -> add_dep t.t_module tl
  311. | TAbstract (a,tl) -> add_dep a.a_module tl
  312. | TMono r ->
  313. (match !r with
  314. | None -> ()
  315. | Some t -> loop t)
  316. | TLazy f ->
  317. loop ((!f)());
  318. | TDynamic t2 ->
  319. if t == t2 then () else loop t2
  320. | TAnon a ->
  321. PMap.iter (fun _ f -> loop f.cf_type) a.a_fields
  322. | TFun (args,ret) ->
  323. List.iter (fun (_,_,t) -> loop t) args;
  324. loop ret
  325. end
  326. and add_dep m tl =
  327. add_dependency mg m;
  328. List.iter loop tl
  329. in
  330. List.iter loop tl;
  331. let build_field f =
  332. let t = generic_substitute_type gctx f.cf_type in
  333. try { f with cf_type = t; cf_expr = (match f.cf_expr with None -> None | Some e -> Some (generic_substitute_expr gctx e)) }
  334. with Unify_error l -> error (error_msg (Unify l)) f.cf_pos
  335. in
  336. if c.cl_init <> None || c.cl_dynamic <> None then error "This class can't be generic" p;
  337. if c.cl_ordered_statics <> [] then error "A generic class can't have static fields" p;
  338. cg.cl_super <- (match c.cl_super with
  339. | None -> None
  340. | Some (cs,pl) ->
  341. (match apply_params c.cl_types tl (TInst (cs,pl)) with
  342. | TInst (cs,pl) when cs.cl_kind = KGeneric ->
  343. (match build_generic ctx cs p pl with
  344. | TInst (cs,pl) -> Some (cs,pl)
  345. | _ -> assert false)
  346. | TInst (cs,pl) -> Some (cs,pl)
  347. | _ -> assert false)
  348. );
  349. cg.cl_kind <- KGenericInstance (c,tl);
  350. cg.cl_interface <- c.cl_interface;
  351. cg.cl_constructor <- (match c.cl_constructor, c.cl_super with
  352. | None, None -> None
  353. | Some c, _ -> Some (build_field c)
  354. | _ -> error "Please define a constructor for this class in order to use it as generic" c.cl_pos
  355. );
  356. cg.cl_implements <- List.map (fun (i,tl) ->
  357. (match follow (generic_substitute_type gctx (TInst (i, List.map (generic_substitute_type gctx) tl))) with
  358. | TInst (i,tl) -> i, tl
  359. | _ -> assert false)
  360. ) c.cl_implements;
  361. cg.cl_ordered_fields <- List.map (fun f ->
  362. let f = build_field f in
  363. cg.cl_fields <- PMap.add f.cf_name f cg.cl_fields;
  364. f
  365. ) c.cl_ordered_fields;
  366. TInst (cg,[])
  367. (* -------------------------------------------------------------------------- *)
  368. (* HAXE.XML.PROXY *)
  369. let extend_xml_proxy ctx c t file p =
  370. let t = Typeload.load_complex_type ctx p t in
  371. let file = (try Common.find_file ctx.com file with Not_found -> file) in
  372. add_dependency c.cl_module (create_fake_module ctx file);
  373. let used = ref PMap.empty in
  374. let print_results() =
  375. PMap.iter (fun id used ->
  376. if not used then ctx.com.warning (id ^ " is not used") p;
  377. ) (!used)
  378. in
  379. let check_used = Common.defined ctx.com Define.CheckXmlProxy in
  380. if check_used then ctx.g.hook_generate <- print_results :: ctx.g.hook_generate;
  381. try
  382. let rec loop = function
  383. | Xml.Element (_,attrs,childs) ->
  384. (try
  385. let id = List.assoc "id" attrs in
  386. if PMap.mem id c.cl_fields then error ("Duplicate id " ^ id) p;
  387. let t = if not check_used then t else begin
  388. used := PMap.add id false (!used);
  389. let ft() = used := PMap.add id true (!used); t in
  390. TLazy (ref ft)
  391. end in
  392. let f = {
  393. cf_name = id;
  394. cf_type = t;
  395. cf_public = true;
  396. cf_pos = p;
  397. cf_doc = None;
  398. cf_meta = no_meta;
  399. cf_kind = Var { v_read = AccResolve; v_write = AccNo };
  400. cf_params = [];
  401. cf_expr = None;
  402. cf_overloads = [];
  403. } in
  404. c.cl_fields <- PMap.add id f c.cl_fields;
  405. with
  406. Not_found -> ());
  407. List.iter loop childs;
  408. | Xml.PCData _ -> ()
  409. in
  410. loop (Xml.parse_file file)
  411. with
  412. | Xml.Error e -> error ("XML error " ^ Xml.error e) p
  413. | Xml.File_not_found f -> error ("XML File not found : " ^ f) p
  414. (* -------------------------------------------------------------------------- *)
  415. (* BUILD META DATA OBJECT *)
  416. let build_metadata com t =
  417. let api = com.basic in
  418. let p, meta, fields, statics = (match t with
  419. | TClassDecl c ->
  420. let fields = List.map (fun f -> f.cf_name,f.cf_meta) (c.cl_ordered_fields @ (match c.cl_constructor with None -> [] | Some f -> [{ f with cf_name = "_" }])) in
  421. let statics = List.map (fun f -> f.cf_name,f.cf_meta) c.cl_ordered_statics in
  422. (c.cl_pos, ["",c.cl_meta],fields,statics)
  423. | TEnumDecl e ->
  424. (e.e_pos, ["",e.e_meta],List.map (fun n -> n, (PMap.find n e.e_constrs).ef_meta) e.e_names, [])
  425. | TTypeDecl t ->
  426. (t.t_pos, ["",t.t_meta],(match follow t.t_type with TAnon a -> PMap.fold (fun f acc -> (f.cf_name,f.cf_meta) :: acc) a.a_fields [] | _ -> []),[])
  427. | TAbstractDecl a ->
  428. (a.a_pos, ["",a.a_meta],[],[])
  429. ) in
  430. let filter l =
  431. let l = List.map (fun (n,ml) -> n, ExtList.List.filter_map (fun (m,el,p) -> match m with Meta.Custom s when String.length s > 0 && s.[0] <> ':' -> Some (s,el,p) | _ -> None) ml) l in
  432. List.filter (fun (_,ml) -> ml <> []) l
  433. in
  434. let meta, fields, statics = filter meta, filter fields, filter statics in
  435. let make_meta_field ml =
  436. let h = Hashtbl.create 0 in
  437. mk (TObjectDecl (List.map (fun (f,el,p) ->
  438. if Hashtbl.mem h f then error ("Duplicate metadata '" ^ f ^ "'") p;
  439. Hashtbl.add h f ();
  440. f, mk (match el with [] -> TConst TNull | _ -> TArrayDecl (List.map (type_constant_value com) el)) (api.tarray t_dynamic) p
  441. ) ml)) (api.tarray t_dynamic) p
  442. in
  443. let make_meta l =
  444. mk (TObjectDecl (List.map (fun (f,ml) -> f,make_meta_field ml) l)) t_dynamic p
  445. in
  446. if meta = [] && fields = [] && statics = [] then
  447. None
  448. else
  449. let meta_obj = [] in
  450. let meta_obj = (if fields = [] then meta_obj else ("fields",make_meta fields) :: meta_obj) in
  451. let meta_obj = (if statics = [] then meta_obj else ("statics",make_meta statics) :: meta_obj) in
  452. let meta_obj = (try ("obj", make_meta_field (List.assoc "" meta)) :: meta_obj with Not_found -> meta_obj) in
  453. Some (mk (TObjectDecl meta_obj) t_dynamic p)
  454. (* -------------------------------------------------------------------------- *)
  455. (* MACRO TYPE *)
  456. let build_macro_type ctx pl p =
  457. let path, field, args = (match pl with
  458. | [TInst ({ cl_kind = KExpr (ECall (e,args),_) },_)]
  459. | [TInst ({ cl_kind = KExpr (EArrayDecl [ECall (e,args),_],_) },_)] ->
  460. let rec loop e =
  461. match fst e with
  462. | EField (e,f) -> f :: loop e
  463. | EConst (Ident i) -> [i]
  464. | _ -> error "Invalid macro call" p
  465. in
  466. (match loop e with
  467. | meth :: cl :: path -> (List.rev path,cl), meth, args
  468. | _ -> error "Invalid macro call" p)
  469. | _ ->
  470. error "MacroType require a single expression call parameter" p
  471. ) in
  472. let old = ctx.ret in
  473. let t = (match ctx.g.do_macro ctx MMacroType path field args p with
  474. | None -> mk_mono()
  475. | Some _ -> ctx.ret
  476. ) in
  477. ctx.ret <- old;
  478. t
  479. (* -------------------------------------------------------------------------- *)
  480. (* API EVENTS *)
  481. let build_instance ctx mtype p =
  482. match mtype with
  483. | TClassDecl c ->
  484. if ctx.pass > PBuildClass then c.cl_build();
  485. let ft = (fun pl ->
  486. match c.cl_kind with
  487. | KGeneric ->
  488. let r = exc_protect ctx (fun r ->
  489. let t = mk_mono() in
  490. r := (fun() -> t);
  491. unify_raise ctx (build_generic ctx c p pl) t p;
  492. t
  493. ) "build_generic" in
  494. delay ctx PForce (fun() -> ignore ((!r)()));
  495. TLazy r
  496. | KMacroType ->
  497. let r = exc_protect ctx (fun r ->
  498. let t = mk_mono() in
  499. r := (fun() -> t);
  500. unify_raise ctx (build_macro_type ctx pl p) t p;
  501. t
  502. ) "macro_type" in
  503. delay ctx PForce (fun() -> ignore ((!r)()));
  504. TLazy r
  505. | _ ->
  506. TInst (c,pl)
  507. ) in
  508. c.cl_types , c.cl_path , ft
  509. | TEnumDecl e ->
  510. e.e_types , e.e_path , (fun t -> TEnum (e,t))
  511. | TTypeDecl t ->
  512. t.t_types , t.t_path , (fun tl -> TType(t,tl))
  513. | TAbstractDecl a ->
  514. a.a_types, a.a_path, (fun tl -> TAbstract(a,tl))
  515. let on_inherit ctx c p h =
  516. match h with
  517. | HExtends { tpackage = ["haxe";"remoting"]; tname = "Proxy"; tparams = [TPType(CTPath t)] } ->
  518. extend_remoting ctx c t p false true;
  519. false
  520. | HExtends { tpackage = ["haxe";"remoting"]; tname = "AsyncProxy"; tparams = [TPType(CTPath t)] } ->
  521. extend_remoting ctx c t p true true;
  522. false
  523. | HExtends { tpackage = ["mt"]; tname = "AsyncProxy"; tparams = [TPType(CTPath t)] } ->
  524. extend_remoting ctx c t p true false;
  525. false
  526. | HExtends { tpackage = ["haxe";"xml"]; tname = "Proxy"; tparams = [TPExpr(EConst (String file),p);TPType t] } ->
  527. extend_xml_proxy ctx c t file p;
  528. true
  529. | _ ->
  530. true
  531. (* -------------------------------------------------------------------------- *)
  532. (* FINAL GENERATION *)
  533. (* Saves a class state so it can be restored later, e.g. after DCE or native path rewrite *)
  534. let save_class_state ctx t = match t with
  535. | TClassDecl c ->
  536. let meta = c.cl_meta and path = c.cl_path and ext = c.cl_extern in
  537. let fl = c.cl_fields and ofl = c.cl_ordered_fields and st = c.cl_statics and ost = c.cl_ordered_statics in
  538. let cst = c.cl_constructor and over = c.cl_overrides in
  539. let oflk = List.map (fun f -> f.cf_kind,f.cf_expr,f.cf_type) ofl in
  540. let ostk = List.map (fun f -> f.cf_kind,f.cf_expr,f.cf_type) ost in
  541. c.cl_restore <- (fun() ->
  542. c.cl_meta <- meta;
  543. c.cl_extern <- ext;
  544. c.cl_path <- path;
  545. c.cl_fields <- fl;
  546. c.cl_ordered_fields <- ofl;
  547. c.cl_statics <- st;
  548. c.cl_ordered_statics <- ost;
  549. c.cl_constructor <- cst;
  550. c.cl_overrides <- over;
  551. (* DCE might modify the cf_kind, so let's restore it as well *)
  552. List.iter2 (fun f (k,e,t) -> f.cf_kind <- k; f.cf_expr <- e; f.cf_type <- t;) ofl oflk;
  553. List.iter2 (fun f (k,e,t) -> f.cf_kind <- k; f.cf_expr <- e; f.cf_type <- t;) ost ostk;
  554. )
  555. | _ ->
  556. ()
  557. (* Checks if a private class' path clashes with another path *)
  558. let check_private_path ctx t = match t with
  559. | TClassDecl c when c.cl_private ->
  560. let rpath = (fst c.cl_module.m_path,"_" ^ snd c.cl_module.m_path) in
  561. if Hashtbl.mem ctx.g.types_module rpath then error ("This private class name will clash with " ^ s_type_path rpath) c.cl_pos;
  562. | _ ->
  563. ()
  564. (* Removes generic base classes *)
  565. let remove_generic_base ctx t = match t with
  566. | TClassDecl c when c.cl_kind = KGeneric && has_ctor_constraint c ->
  567. c.cl_extern <- true
  568. | _ ->
  569. ()
  570. (* Rewrites class or enum paths if @:native metadata is set *)
  571. let apply_native_paths ctx t =
  572. let get_real_path meta path =
  573. let (_,e,mp) = Meta.get Meta.Native meta in
  574. match e with
  575. | [Ast.EConst (Ast.String name),p] ->
  576. (Meta.RealPath,[Ast.EConst (Ast.String (s_type_path path)),p],mp),parse_path name
  577. | _ ->
  578. error "String expected" mp
  579. in
  580. try
  581. (match t with
  582. | TClassDecl c ->
  583. let meta,path = get_real_path c.cl_meta c.cl_path in
  584. c.cl_meta <- meta :: c.cl_meta;
  585. c.cl_path <- path;
  586. | TEnumDecl e ->
  587. let meta,path = get_real_path e.e_meta e.e_path in
  588. e.e_meta <- meta :: e.e_meta;
  589. e.e_path <- path;
  590. | _ ->
  591. ())
  592. with Not_found ->
  593. ()
  594. (* Adds the __rtti field if required *)
  595. let add_rtti ctx t =
  596. let rec has_rtti c =
  597. Meta.has Meta.Rtti c.cl_meta || match c.cl_super with None -> false | Some (csup,_) -> has_rtti csup
  598. in
  599. match t with
  600. | TClassDecl c when has_rtti c && not (PMap.mem "__rtti" c.cl_statics) ->
  601. let f = mk_field "__rtti" ctx.t.tstring c.cl_pos in
  602. let str = Genxml.gen_type_string ctx.com t in
  603. f.cf_expr <- Some (mk (TConst (TString str)) f.cf_type c.cl_pos);
  604. c.cl_ordered_statics <- f :: c.cl_ordered_statics;
  605. c.cl_statics <- PMap.add f.cf_name f c.cl_statics;
  606. | _ ->
  607. ()
  608. (* Removes extern and macro fields, also checks for Void fields *)
  609. let remove_extern_fields ctx t = match t with
  610. | TClassDecl c ->
  611. let do_remove f =
  612. (not ctx.in_macro && f.cf_kind = Method MethMacro) || Meta.has Meta.Extern f.cf_meta || Meta.has Meta.Generic f.cf_meta
  613. in
  614. if not (Common.defined ctx.com Define.DocGen) then begin
  615. c.cl_ordered_fields <- List.filter (fun f ->
  616. let b = do_remove f in
  617. if b then c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  618. not b
  619. ) c.cl_ordered_fields;
  620. c.cl_ordered_statics <- List.filter (fun f ->
  621. let b = do_remove f in
  622. if b then c.cl_statics <- PMap.remove f.cf_name c.cl_statics;
  623. not b
  624. ) c.cl_ordered_statics;
  625. end
  626. | _ ->
  627. ()
  628. (* Adds member field initializations as assignments to the constructor *)
  629. let add_field_inits ctx t =
  630. let apply c =
  631. let ethis = mk (TConst TThis) (TInst (c,List.map snd c.cl_types)) c.cl_pos in
  632. (* TODO: we have to find a variable name which is not used in any of the functions *)
  633. let v = alloc_var "_g" ethis.etype in
  634. let need_this = ref false in
  635. let inits,fields = List.fold_left (fun (inits,fields) cf ->
  636. match cf.cf_kind,cf.cf_expr with
  637. | Var _, Some _ ->
  638. if ctx.com.config.pf_can_init_member cf then (inits, cf :: fields) else (cf :: inits, cf :: fields)
  639. | Method MethDynamic, Some e when Common.defined ctx.com Define.As3 ->
  640. (* TODO : this would have a better place in genSWF9 I think - NC *)
  641. (* we move the initialization of dynamic functions to the constructor and also solve the
  642. 'this' problem along the way *)
  643. let rec use_this v e = match e.eexpr with
  644. | TConst TThis ->
  645. need_this := true;
  646. mk (TLocal v) v.v_type e.epos
  647. | _ -> Type.map_expr (use_this v) e
  648. in
  649. let e = Type.map_expr (use_this v) e in
  650. let cf2 = {cf with cf_expr = Some e} in
  651. (* if the method is an override, we have to remove the class field to not get invalid overrides *)
  652. let fields = if List.memq cf c.cl_overrides then begin
  653. c.cl_fields <- PMap.remove cf.cf_name c.cl_fields;
  654. fields
  655. end else
  656. cf2 :: fields
  657. in
  658. (cf2 :: inits, fields)
  659. | _ -> (inits, cf :: fields)
  660. ) ([],[]) c.cl_ordered_fields in
  661. c.cl_ordered_fields <- fields;
  662. match inits with
  663. | [] -> ()
  664. | _ ->
  665. let el = List.map (fun cf ->
  666. match cf.cf_expr with
  667. | None -> assert false
  668. | Some e ->
  669. let lhs = mk (TField(ethis,FInstance (c,cf))) cf.cf_type e.epos in
  670. cf.cf_expr <- None;
  671. let eassign = mk (TBinop(OpAssign,lhs,e)) e.etype e.epos in
  672. if Common.defined ctx.com Define.As3 then begin
  673. let echeck = mk (TBinop(OpEq,lhs,(mk (TConst TNull) lhs.etype e.epos))) ctx.com.basic.tbool e.epos in
  674. mk (TIf(echeck,eassign,None)) eassign.etype e.epos
  675. end else
  676. eassign;
  677. ) inits in
  678. let el = if !need_this then (mk (TVars([v, Some ethis])) ethis.etype ethis.epos) :: el else el in
  679. match c.cl_constructor with
  680. | None ->
  681. let ct = TFun([],ctx.com.basic.tvoid) in
  682. let ce = mk (TFunction {
  683. tf_args = [];
  684. tf_type = ctx.com.basic.tvoid;
  685. tf_expr = mk (TBlock el) ctx.com.basic.tvoid c.cl_pos;
  686. }) ct c.cl_pos in
  687. let ctor = mk_field "new" ct c.cl_pos in
  688. ctor.cf_kind <- Method MethNormal;
  689. c.cl_constructor <- Some { ctor with cf_expr = Some ce };
  690. | Some cf ->
  691. match cf.cf_expr with
  692. | Some { eexpr = TFunction f } ->
  693. let bl = match f.tf_expr with {eexpr = TBlock b } -> b | x -> [x] in
  694. let ce = mk (TFunction {f with tf_expr = mk (TBlock (el @ bl)) ctx.com.basic.tvoid c.cl_pos }) cf.cf_type cf.cf_pos in
  695. c.cl_constructor <- Some {cf with cf_expr = Some ce }
  696. | _ ->
  697. assert false
  698. in
  699. match t with
  700. | TClassDecl c ->
  701. apply c
  702. | _ ->
  703. ()
  704. (* Adds the __meta__ field if required *)
  705. let add_meta_field ctx t = match t with
  706. | TClassDecl c ->
  707. (match build_metadata ctx.com t with
  708. | None -> ()
  709. | Some e ->
  710. let f = mk_field "__meta__" t_dynamic c.cl_pos in
  711. f.cf_expr <- Some e;
  712. c.cl_ordered_statics <- f :: c.cl_ordered_statics;
  713. c.cl_statics <- PMap.add f.cf_name f c.cl_statics)
  714. | _ ->
  715. ()
  716. (* Removes interfaces tagged with @:remove metadata *)
  717. let check_remove_metadata ctx t = match t with
  718. | TClassDecl c ->
  719. c.cl_implements <- List.filter (fun (c,_) -> not (Meta.has Meta.Remove c.cl_meta)) c.cl_implements;
  720. | _ ->
  721. ()
  722. (* Checks for Void class fields *)
  723. let check_void_field ctx t = match t with
  724. | TClassDecl c ->
  725. let check f =
  726. match follow f.cf_type with TAbstract({a_path=[],"Void"},_) -> error "Fields of type Void are not allowed" f.cf_pos | _ -> ();
  727. in
  728. List.iter check c.cl_ordered_fields;
  729. List.iter check c.cl_ordered_statics;
  730. | _ ->
  731. ()
  732. (* Promotes type parameters of abstracts to their implementation fields *)
  733. let promote_abstract_parameters ctx t = match t with
  734. | TClassDecl ({cl_kind = KAbstractImpl a} as c) when a.a_types <> [] ->
  735. List.iter (fun f ->
  736. List.iter (fun (n,t) -> match t with
  737. | TInst({cl_kind = KTypeParameter _; cl_path=p,n} as cp,[]) when not (List.mem_assoc n f.cf_params) ->
  738. let path = List.rev ((snd c.cl_path) :: List.rev (fst c.cl_path)),n in
  739. f.cf_params <- (n,TInst({cp with cl_path = path},[])) :: f.cf_params
  740. | _ ->
  741. ()
  742. ) a.a_types;
  743. ) c.cl_ordered_statics;
  744. | _ ->
  745. ()
  746. (* -------------------------------------------------------------------------- *)
  747. (* LOCAL VARIABLES USAGE *)
  748. type usage =
  749. | Block of ((usage -> unit) -> unit)
  750. | Loop of ((usage -> unit) -> unit)
  751. | Function of ((usage -> unit) -> unit)
  752. | Declare of tvar
  753. | Use of tvar
  754. let rec local_usage f e =
  755. match e.eexpr with
  756. | TLocal v ->
  757. f (Use v)
  758. | TVars l ->
  759. List.iter (fun (v,e) ->
  760. (match e with None -> () | Some e -> local_usage f e);
  761. f (Declare v);
  762. ) l
  763. | TFunction tf ->
  764. let cc f =
  765. List.iter (fun (v,_) -> f (Declare v)) tf.tf_args;
  766. local_usage f tf.tf_expr;
  767. in
  768. f (Function cc)
  769. | TBlock l ->
  770. f (Block (fun f -> List.iter (local_usage f) l))
  771. | TFor (v,it,e) ->
  772. local_usage f it;
  773. f (Loop (fun f ->
  774. f (Declare v);
  775. local_usage f e;
  776. ))
  777. | TWhile _ ->
  778. f (Loop (fun f ->
  779. iter (local_usage f) e
  780. ))
  781. | TTry (e,catchs) ->
  782. local_usage f e;
  783. List.iter (fun (v,e) ->
  784. f (Block (fun f ->
  785. f (Declare v);
  786. local_usage f e;
  787. ))
  788. ) catchs;
  789. | TMatch (e,_,cases,def) ->
  790. local_usage f e;
  791. List.iter (fun (_,vars,e) ->
  792. let cc f =
  793. (match vars with
  794. | None -> ()
  795. | Some l -> List.iter (function None -> () | Some v -> f (Declare v)) l);
  796. local_usage f e;
  797. in
  798. f (Block cc)
  799. ) cases;
  800. (match def with None -> () | Some e -> local_usage f e);
  801. | _ ->
  802. iter (local_usage f) e
  803. (* -------------------------------------------------------------------------- *)
  804. (* BLOCK VARIABLES CAPTURE *)
  805. (*
  806. For some platforms, it will simply mark the variables which are used in closures
  807. using the v_capture flag so it can be processed in a more optimized
  808. For Flash/JS platforms, it will ensure that variables used in loop sub-functions
  809. have an unique scope. It transforms the following expression :
  810. for( x in array )
  811. funs.push(function() return x++);
  812. Into the following :
  813. for( _x in array ) {
  814. var x = [_x];
  815. funs.push(function(x) { function() return x[0]++; }(x));
  816. }
  817. *)
  818. let captured_vars com e =
  819. let t = com.basic in
  820. let rec mk_init av v pos =
  821. mk (TVars [av,Some (mk (TArrayDecl [mk (TLocal v) v.v_type pos]) av.v_type pos)]) t.tvoid pos
  822. and mk_var v used =
  823. alloc_var v.v_name (PMap.find v.v_id used)
  824. and wrap used e =
  825. match e.eexpr with
  826. | TVars vl ->
  827. let vl = List.map (fun (v,ve) ->
  828. if PMap.mem v.v_id used then
  829. v, Some (mk (TArrayDecl (match ve with None -> [] | Some e -> [wrap used e])) v.v_type e.epos)
  830. else
  831. v, (match ve with None -> None | Some e -> Some (wrap used e))
  832. ) vl in
  833. { e with eexpr = TVars vl }
  834. | TLocal v when PMap.mem v.v_id used ->
  835. mk (TArray ({ e with etype = v.v_type },mk (TConst (TInt 0l)) t.tint e.epos)) e.etype e.epos
  836. | TFor (v,it,expr) when PMap.mem v.v_id used ->
  837. let vtmp = mk_var v used in
  838. let it = wrap used it in
  839. let expr = wrap used expr in
  840. mk (TFor (vtmp,it,concat (mk_init v vtmp e.epos) expr)) e.etype e.epos
  841. | TTry (expr,catchs) ->
  842. let catchs = List.map (fun (v,e) ->
  843. let e = wrap used e in
  844. try
  845. let vtmp = mk_var v used in
  846. vtmp, concat (mk_init v vtmp e.epos) e
  847. with Not_found ->
  848. v, e
  849. ) catchs in
  850. mk (TTry (wrap used expr,catchs)) e.etype e.epos
  851. | TMatch (expr,enum,cases,def) ->
  852. let cases = List.map (fun (il,vars,e) ->
  853. let pos = e.epos in
  854. let e = ref (wrap used e) in
  855. let vars = match vars with
  856. | None -> None
  857. | Some l ->
  858. Some (List.map (fun v ->
  859. match v with
  860. | Some v when PMap.mem v.v_id used ->
  861. let vtmp = mk_var v used in
  862. e := concat (mk_init v vtmp pos) !e;
  863. Some vtmp
  864. | _ -> v
  865. ) l)
  866. in
  867. il, vars, !e
  868. ) cases in
  869. let def = match def with None -> None | Some e -> Some (wrap used e) in
  870. mk (TMatch (wrap used expr,enum,cases,def)) e.etype e.epos
  871. | TFunction f ->
  872. (*
  873. list variables that are marked as used, but also used in that
  874. function and which are not declared inside it !
  875. *)
  876. let fused = ref PMap.empty in
  877. let tmp_used = ref used in
  878. let rec browse = function
  879. | Block f | Loop f | Function f -> f browse
  880. | Use v ->
  881. if PMap.mem v.v_id !tmp_used then fused := PMap.add v.v_id v !fused;
  882. | Declare v ->
  883. tmp_used := PMap.remove v.v_id !tmp_used
  884. in
  885. local_usage browse e;
  886. let vars = PMap.fold (fun v acc -> v :: acc) !fused [] in
  887. (* in case the variable has been marked as used in a parallel scope... *)
  888. let fexpr = ref (wrap used f.tf_expr) in
  889. let fargs = List.map (fun (v,o) ->
  890. if PMap.mem v.v_id used then
  891. let vtmp = mk_var v used in
  892. fexpr := concat (mk_init v vtmp e.epos) !fexpr;
  893. vtmp, o
  894. else
  895. v, o
  896. ) f.tf_args in
  897. let e = { e with eexpr = TFunction { f with tf_args = fargs; tf_expr = !fexpr } } in
  898. (*
  899. Create a new function scope to make sure that the captured loop variable
  900. will not be overwritten in next loop iteration
  901. *)
  902. if com.config.pf_capture_policy = CPLoopVars then
  903. mk (TCall (
  904. mk_parent (mk (TFunction {
  905. tf_args = List.map (fun v -> v, None) vars;
  906. tf_type = e.etype;
  907. tf_expr = mk_block (mk (TReturn (Some e)) e.etype e.epos);
  908. }) (TFun (List.map (fun v -> v.v_name,false,v.v_type) vars,e.etype)) e.epos),
  909. List.map (fun v -> mk (TLocal v) v.v_type e.epos) vars)
  910. ) e.etype e.epos
  911. else
  912. e
  913. | _ ->
  914. map_expr (wrap used) e
  915. and do_wrap used e =
  916. if PMap.is_empty used then
  917. e
  918. else
  919. let used = PMap.map (fun v ->
  920. let vt = v.v_type in
  921. v.v_type <- t.tarray vt;
  922. v.v_capture <- true;
  923. vt
  924. ) used in
  925. wrap used e
  926. and out_loop e =
  927. match e.eexpr with
  928. | TFor _ | TWhile _ ->
  929. (*
  930. collect variables that are declared in loop but used in subfunctions
  931. *)
  932. let vars = ref PMap.empty in
  933. let used = ref PMap.empty in
  934. let depth = ref 0 in
  935. let rec collect_vars in_loop = function
  936. | Block f ->
  937. let old = !vars in
  938. f (collect_vars in_loop);
  939. vars := old;
  940. | Loop f ->
  941. let old = !vars in
  942. f (collect_vars true);
  943. vars := old;
  944. | Function f ->
  945. incr depth;
  946. f (collect_vars false);
  947. decr depth;
  948. | Declare v ->
  949. if in_loop then vars := PMap.add v.v_id !depth !vars;
  950. | Use v ->
  951. try
  952. let d = PMap.find v.v_id !vars in
  953. if d <> !depth then used := PMap.add v.v_id v !used;
  954. with Not_found ->
  955. ()
  956. in
  957. local_usage (collect_vars false) e;
  958. do_wrap !used e
  959. | _ ->
  960. map_expr out_loop e
  961. and all_vars e =
  962. let vars = ref PMap.empty in
  963. let used = ref PMap.empty in
  964. let depth = ref 0 in
  965. let rec collect_vars = function
  966. | Block f ->
  967. let old = !vars in
  968. f collect_vars;
  969. vars := old;
  970. | Loop f ->
  971. let old = !vars in
  972. f collect_vars;
  973. vars := old;
  974. | Function f ->
  975. incr depth;
  976. f collect_vars;
  977. decr depth;
  978. | Declare v ->
  979. vars := PMap.add v.v_id !depth !vars;
  980. | Use v ->
  981. try
  982. let d = PMap.find v.v_id !vars in
  983. if d <> !depth then used := PMap.add v.v_id v !used;
  984. with Not_found -> ()
  985. in
  986. local_usage collect_vars e;
  987. !used
  988. in
  989. (* mark all capture variables - also used in rename_local_vars at later stage *)
  990. let captured = all_vars e in
  991. PMap.iter (fun _ v -> v.v_capture <- true) captured;
  992. match com.config.pf_capture_policy with
  993. | CPNone -> e
  994. | CPWrapRef -> do_wrap captured e
  995. | CPLoopVars -> out_loop e
  996. (* -------------------------------------------------------------------------- *)
  997. (* RENAME LOCAL VARS *)
  998. let rename_local_vars com e =
  999. let cfg = com.config in
  1000. let all_scope = (not cfg.pf_captured_scope) || (not cfg.pf_locals_scope) in
  1001. let vars = ref PMap.empty in
  1002. let all_vars = ref PMap.empty in
  1003. let vtemp = alloc_var "~" t_dynamic in
  1004. let rebuild_vars = ref false in
  1005. let rebuild m =
  1006. PMap.fold (fun v acc -> PMap.add v.v_name v acc) m PMap.empty
  1007. in
  1008. let save() =
  1009. let old = !vars in
  1010. if cfg.pf_unique_locals then (fun() -> ()) else (fun() -> vars := if !rebuild_vars then rebuild old else old)
  1011. in
  1012. let rename vars v =
  1013. let count = ref 1 in
  1014. while PMap.mem (v.v_name ^ string_of_int !count) vars do
  1015. incr count;
  1016. done;
  1017. v.v_name <- v.v_name ^ string_of_int !count;
  1018. in
  1019. let declare v p =
  1020. (match follow v.v_type with
  1021. | TAbstract ({a_path = [],"Void"},_) -> error "Arguments and variables of type Void are not allowed" p
  1022. | _ -> ());
  1023. (* chop escape char for all local variables generated *)
  1024. if String.unsafe_get v.v_name 0 = String.unsafe_get gen_local_prefix 0 then v.v_name <- "_g" ^ String.sub v.v_name 1 (String.length v.v_name - 1);
  1025. let look_vars = (if not cfg.pf_captured_scope && v.v_capture then !all_vars else !vars) in
  1026. (try
  1027. let v2 = PMap.find v.v_name look_vars in
  1028. (*
  1029. block_vars will create some wrapper-functions that are declaring
  1030. the same variable twice. In that case do not perform a rename since
  1031. we are sure it's actually the same variable
  1032. *)
  1033. if v == v2 then raise Not_found;
  1034. rename look_vars v;
  1035. with Not_found ->
  1036. ());
  1037. vars := PMap.add v.v_name v !vars;
  1038. if all_scope then all_vars := PMap.add v.v_name v !all_vars;
  1039. in
  1040. (*
  1041. This is quite a rare case, when a local variable would otherwise prevent
  1042. accessing a type because it masks the type value or the package name.
  1043. *)
  1044. let check t =
  1045. match (t_infos t).mt_path with
  1046. | [], name | name :: _, _ ->
  1047. let vars = if cfg.pf_locals_scope then vars else all_vars in
  1048. (try
  1049. let v = PMap.find name !vars in
  1050. if v == vtemp then raise Not_found; (* ignore *)
  1051. rename (!vars) v;
  1052. rebuild_vars := true;
  1053. vars := PMap.add v.v_name v !vars
  1054. with Not_found ->
  1055. ());
  1056. vars := PMap.add name vtemp !vars
  1057. in
  1058. let check_type t =
  1059. match follow t with
  1060. | TInst (c,_) -> check (TClassDecl c)
  1061. | TEnum (e,_) -> check (TEnumDecl e)
  1062. | TType (t,_) -> check (TTypeDecl t)
  1063. | TAbstract (a,_) -> check (TAbstractDecl a)
  1064. | TMono _ | TLazy _ | TAnon _ | TDynamic _ | TFun _ -> ()
  1065. in
  1066. let rec loop e =
  1067. match e.eexpr with
  1068. | TVars l ->
  1069. List.iter (fun (v,eo) ->
  1070. if not cfg.pf_locals_scope then declare v e.epos;
  1071. (match eo with None -> () | Some e -> loop e);
  1072. if cfg.pf_locals_scope then declare v e.epos;
  1073. ) l
  1074. | TFunction tf ->
  1075. let old = save() in
  1076. List.iter (fun (v,_) -> declare v e.epos) tf.tf_args;
  1077. loop tf.tf_expr;
  1078. old()
  1079. | TBlock el ->
  1080. let old = save() in
  1081. List.iter loop el;
  1082. old()
  1083. | TFor (v,it,e1) ->
  1084. loop it;
  1085. let old = save() in
  1086. declare v e.epos;
  1087. loop e1;
  1088. old()
  1089. | TTry (e,catchs) ->
  1090. loop e;
  1091. List.iter (fun (v,e) ->
  1092. let old = save() in
  1093. declare v e.epos;
  1094. check_type v.v_type;
  1095. loop e;
  1096. old()
  1097. ) catchs;
  1098. | TMatch (e,_,cases,def) ->
  1099. loop e;
  1100. List.iter (fun (_,vars,e) ->
  1101. let old = save() in
  1102. (match vars with
  1103. | None -> ()
  1104. | Some l -> List.iter (function None -> () | Some v -> declare v e.epos) l);
  1105. loop e;
  1106. old();
  1107. ) cases;
  1108. (match def with None -> () | Some e -> loop e);
  1109. | TTypeExpr t ->
  1110. check t
  1111. | TNew (c,_,_) ->
  1112. Type.iter loop e;
  1113. check (TClassDecl c);
  1114. | TCast (e,Some t) ->
  1115. loop e;
  1116. check t;
  1117. | _ ->
  1118. Type.iter loop e
  1119. in
  1120. declare (alloc_var "this" t_dynamic) Ast.null_pos; (* force renaming of 'this' vars in abstract *)
  1121. loop e;
  1122. e
  1123. (* -------------------------------------------------------------------------- *)
  1124. (* CHECK LOCAL VARS INIT *)
  1125. let check_local_vars_init e =
  1126. let intersect vl1 vl2 =
  1127. PMap.mapi (fun v t -> t && PMap.find v vl2) vl1
  1128. in
  1129. let join vars cvars =
  1130. List.iter (fun v -> vars := intersect !vars v) cvars
  1131. in
  1132. let restore vars old_vars declared =
  1133. (* restore variables declared in this block to their previous state *)
  1134. vars := List.fold_left (fun acc v ->
  1135. try PMap.add v (PMap.find v old_vars) acc with Not_found -> PMap.remove v acc
  1136. ) !vars declared;
  1137. in
  1138. let declared = ref [] in
  1139. let rec loop vars e =
  1140. match e.eexpr with
  1141. | TLocal v ->
  1142. let init = (try PMap.find v.v_id !vars with Not_found -> true) in
  1143. if not init then begin
  1144. if v.v_name = "this" then error "Missing this = value" e.epos
  1145. else error ("Local variable " ^ v.v_name ^ " used without being initialized") e.epos
  1146. end
  1147. | TVars vl ->
  1148. List.iter (fun (v,eo) ->
  1149. match eo with
  1150. | None ->
  1151. declared := v.v_id :: !declared;
  1152. vars := PMap.add v.v_id false !vars
  1153. | Some e ->
  1154. loop vars e
  1155. ) vl
  1156. | TBlock el ->
  1157. let old = !declared in
  1158. let old_vars = !vars in
  1159. declared := [];
  1160. List.iter (loop vars) el;
  1161. restore vars old_vars (List.rev !declared);
  1162. declared := old;
  1163. | TBinop (OpAssign,{ eexpr = TLocal v },e) when PMap.mem v.v_id !vars ->
  1164. loop vars e;
  1165. vars := PMap.add v.v_id true !vars
  1166. | TIf (e1,e2,eo) ->
  1167. loop vars e1;
  1168. let vbase = !vars in
  1169. loop vars e2;
  1170. (match eo with
  1171. | None -> vars := vbase
  1172. | Some e ->
  1173. let v1 = !vars in
  1174. vars := vbase;
  1175. loop vars e;
  1176. vars := intersect !vars v1)
  1177. | TWhile (cond,e,flag) ->
  1178. (match flag with
  1179. | NormalWhile ->
  1180. loop vars cond;
  1181. let old = !vars in
  1182. loop vars e;
  1183. vars := old;
  1184. | DoWhile ->
  1185. loop vars e;
  1186. loop vars cond)
  1187. | TTry (e,catches) ->
  1188. let cvars = List.map (fun (v,e) ->
  1189. let old = !vars in
  1190. loop vars e;
  1191. let v = !vars in
  1192. vars := old;
  1193. v
  1194. ) catches in
  1195. loop vars e;
  1196. join vars cvars;
  1197. | TSwitch (e,cases,def) ->
  1198. loop vars e;
  1199. let cvars = List.map (fun (ec,e) ->
  1200. let old = !vars in
  1201. List.iter (loop vars) ec;
  1202. vars := old;
  1203. loop vars e;
  1204. let v = !vars in
  1205. vars := old;
  1206. v
  1207. ) cases in
  1208. (match def with
  1209. | None -> ()
  1210. | Some e ->
  1211. loop vars e;
  1212. join vars cvars)
  1213. | TMatch (e,_,cases,def) ->
  1214. loop vars e;
  1215. let old = !vars in
  1216. let cvars = List.map (fun (_,vl,e) ->
  1217. vars := old;
  1218. loop vars e;
  1219. restore vars old [];
  1220. !vars
  1221. ) cases in
  1222. (match def with None -> () | Some e -> vars := old; loop vars e);
  1223. join vars cvars
  1224. (* mark all reachable vars as initialized, since we don't exit the block *)
  1225. | TBreak | TContinue | TReturn None ->
  1226. vars := PMap.map (fun _ -> true) !vars
  1227. | TThrow e | TReturn (Some e) ->
  1228. loop vars e;
  1229. vars := PMap.map (fun _ -> true) !vars
  1230. | _ ->
  1231. Type.iter (loop vars) e
  1232. in
  1233. loop (ref PMap.empty) e;
  1234. e
  1235. (* -------------------------------------------------------------------------- *)
  1236. (* ABSTRACT CASTS *)
  1237. module Abstract = struct
  1238. let find_to ab pl b = List.find (Type.unify_to_field ab pl b) ab.a_to
  1239. let find_from ab pl a b = List.find (Type.unify_from_field ab pl a b) ab.a_from
  1240. let get_underlying_type a pl =
  1241. try
  1242. if not (Meta.has Meta.MultiType a.a_meta) then raise Not_found;
  1243. let m = mk_mono() in
  1244. let _ = find_to a pl m in
  1245. follow m
  1246. with Not_found ->
  1247. apply_params a.a_types pl a.a_this
  1248. let rec make_static_call ctx c cf a pl args t p =
  1249. let ta = TAnon { a_fields = c.cl_statics; a_status = ref (Statics c) } in
  1250. let ethis = mk (TTypeExpr (TClassDecl c)) ta p in
  1251. let monos = List.map (fun _ -> mk_mono()) cf.cf_params in
  1252. let map t = apply_params a.a_types pl (apply_params cf.cf_params monos t) in
  1253. (* TODO: temp RC fix for from-functions to infer type parameters *)
  1254. let tcf = match follow (map cf.cf_type),args with
  1255. | TFun((_,_,ta) :: args,r) as tf,e :: el when Meta.has Meta.From cf.cf_meta ->
  1256. unify ctx e.etype ta p;
  1257. tf
  1258. | t,_ -> t
  1259. in
  1260. let def () =
  1261. let e = mk (TField (ethis,(FStatic (c,cf)))) tcf p in
  1262. mk (TCall(e,args)) (map t) p
  1263. in
  1264. let e = match cf.cf_expr with
  1265. | Some { eexpr = TFunction fd } when cf.cf_kind = Method MethInline ->
  1266. let config = if Meta.has Meta.Impl cf.cf_meta then (Some (a.a_types <> [] || cf.cf_params <> [], map)) else None in
  1267. (match Optimizer.type_inline ctx cf fd ethis args t config p true with
  1268. | Some e -> (match e.eexpr with TCast(e,None) -> e | _ -> e)
  1269. | None ->
  1270. def())
  1271. | _ ->
  1272. def()
  1273. in
  1274. (* TODO: can this cause loops? *)
  1275. loop ctx e
  1276. and check_cast ctx tleft eright p =
  1277. let tright = follow eright.etype in
  1278. let tleft = follow tleft in
  1279. if tleft == tright then eright else
  1280. try (match tright,tleft with
  1281. | (TAbstract({a_impl = Some c1} as a1,pl1) as t1),(TAbstract({a_impl = Some c2} as a2,pl2) as t2) ->
  1282. if a1 == a2 then
  1283. eright
  1284. else begin
  1285. let c,cfo,a,pl = try
  1286. if Meta.has Meta.MultiType a1.a_meta then raise Not_found;
  1287. c1,snd (find_to a1 pl1 t2),a1,pl1
  1288. with Not_found ->
  1289. if Meta.has Meta.MultiType a2.a_meta then raise Not_found;
  1290. c2,snd (find_from a2 pl2 t1 t2),a2,pl2
  1291. in
  1292. match cfo with None -> eright | Some cf -> make_static_call ctx c cf a pl [eright] tleft p
  1293. end
  1294. | TDynamic _,_ | _,TDynamic _ ->
  1295. eright
  1296. | TAbstract({a_impl = Some c} as a,pl),t2 when not (Meta.has Meta.MultiType a.a_meta) ->
  1297. begin match snd (find_to a pl t2) with None -> eright | Some cf -> make_static_call ctx c cf a pl [eright] tleft p end
  1298. | t1,(TAbstract({a_impl = Some c} as a,pl) as t2) when not (Meta.has Meta.MultiType a.a_meta) ->
  1299. begin match snd (find_from a pl t1 t2) with None -> eright | Some cf -> make_static_call ctx c cf a pl [eright] tleft p end
  1300. | _ ->
  1301. eright)
  1302. with Not_found ->
  1303. eright
  1304. and loop ctx e = match e.eexpr with
  1305. | TBinop(OpAssign,e1,e2) ->
  1306. let e2 = check_cast ctx e1.etype (loop ctx e2) e.epos in
  1307. { e with eexpr = TBinop(OpAssign,loop ctx e1,e2) }
  1308. | TVars vl ->
  1309. let vl = List.map (fun (v,eo) -> match eo with
  1310. | None -> (v,eo)
  1311. | Some e ->
  1312. let is_generic_abstract = match e.etype with TAbstract ({a_impl = Some _} as a,_) -> Meta.has Meta.MultiType a.a_meta | _ -> false in
  1313. let e = check_cast ctx v.v_type (loop ctx e) e.epos in
  1314. (* we can rewrite this for better field inference *)
  1315. if is_generic_abstract then v.v_type <- e.etype;
  1316. v, Some e
  1317. ) vl in
  1318. { e with eexpr = TVars vl }
  1319. | TNew({cl_kind = KAbstractImpl a} as c,pl,el) ->
  1320. (* a TNew of an abstract implementation is only generated if it is a generic abstract *)
  1321. let at = apply_params a.a_types pl a.a_this in
  1322. let m = mk_mono() in
  1323. let _,cfo =
  1324. try find_to a pl m
  1325. with Not_found ->
  1326. let st = s_type (print_context()) at in
  1327. if has_mono at then
  1328. error ("Type parameters of multi type abstracts must be known (for " ^ st ^ ")") e.epos
  1329. else
  1330. error ("Abstract " ^ (s_type_path a.a_path) ^ " has no @:to function that accepts " ^ st) e.epos;
  1331. in
  1332. begin match cfo with
  1333. | None -> assert false
  1334. | Some cf ->
  1335. let m = follow m in
  1336. let e = make_static_call ctx c cf a pl ((mk (TConst TNull) at e.epos) :: el) m e.epos in
  1337. {e with etype = m}
  1338. end
  1339. | TCall(e1, el) ->
  1340. let e1 = loop ctx e1 in
  1341. begin try
  1342. begin match e1.eexpr with
  1343. | TField(_,FStatic(_,cf)) when Meta.has Meta.To cf.cf_meta ->
  1344. (* do not recurse over @:to functions to avoid infinite recursion *)
  1345. { e with eexpr = TCall(e1,el)}
  1346. | TField(e2,fa) ->
  1347. begin match follow e2.etype with
  1348. | TAbstract(a,pl) when Meta.has Meta.MultiType a.a_meta ->
  1349. let m = get_underlying_type a pl in
  1350. let fname = field_name fa in
  1351. let el = List.map (loop ctx) el in
  1352. begin try
  1353. let ef = mk (TField({e2 with etype = m},quick_field m fname)) e2.etype e2.epos in
  1354. make_call ctx ef el e.etype e.epos
  1355. with Not_found ->
  1356. (* quick_field raises Not_found if m is an abstract, we have to replicate the 'using' call here *)
  1357. match follow m with
  1358. | TAbstract({a_impl = Some c} as a,pl) ->
  1359. let cf = PMap.find fname c.cl_statics in
  1360. make_static_call ctx c cf a pl (e2 :: el) e.etype e.epos
  1361. | _ -> raise Not_found
  1362. end
  1363. | _ -> raise Not_found
  1364. end
  1365. | _ ->
  1366. raise Not_found
  1367. end
  1368. with Not_found ->
  1369. begin match follow e1.etype with
  1370. | TFun(args,_) ->
  1371. let rec loop2 el tl = match el,tl with
  1372. | [],_ -> []
  1373. | e :: el, [] -> (loop ctx e) :: loop2 el []
  1374. | e :: el, (_,_,t) :: tl ->
  1375. (check_cast ctx t (loop ctx e) e.epos) :: loop2 el tl
  1376. in
  1377. let el = loop2 el args in
  1378. { e with eexpr = TCall(loop ctx e1,el)}
  1379. | _ ->
  1380. Type.map_expr (loop ctx) e
  1381. end
  1382. end
  1383. | TArrayDecl el ->
  1384. begin match e.etype with
  1385. | TInst(_,[t]) ->
  1386. let el = List.map (fun e -> check_cast ctx t (loop ctx e) e.epos) el in
  1387. { e with eexpr = TArrayDecl el}
  1388. | _ ->
  1389. Type.map_expr (loop ctx) e
  1390. end
  1391. | TObjectDecl fl ->
  1392. begin match follow e.etype with
  1393. | TAnon a ->
  1394. let fl = List.map (fun (n,e) ->
  1395. try
  1396. let cf = PMap.find n a.a_fields in
  1397. let e = match e.eexpr with TCast(e1,None) -> e1 | _ -> e in
  1398. (n,check_cast ctx cf.cf_type (loop ctx e) e.epos)
  1399. with Not_found ->
  1400. (n,loop ctx e)
  1401. ) fl in
  1402. { e with eexpr = TObjectDecl fl }
  1403. | _ ->
  1404. Type.map_expr (loop ctx) e
  1405. end
  1406. | _ ->
  1407. Type.map_expr (loop ctx) e
  1408. let handle_abstract_casts ctx e =
  1409. loop ctx e
  1410. end
  1411. (* -------------------------------------------------------------------------- *)
  1412. (* USAGE *)
  1413. let detect_usage com =
  1414. let usage = ref [] in
  1415. List.iter (fun t -> match t with
  1416. | TClassDecl c ->
  1417. let rec expr e = match e.eexpr with
  1418. | TField(_,fa) ->
  1419. (match extract_field fa with
  1420. | Some cf when Meta.has Meta.Usage cf.cf_meta ->
  1421. usage := e.epos :: !usage;
  1422. | _ -> ());
  1423. Type.iter expr e
  1424. | _ -> Type.iter expr e
  1425. in
  1426. let field cf = match cf.cf_expr with None -> () | Some e -> expr e in
  1427. (match c.cl_constructor with None -> () | Some cf -> field cf);
  1428. (match c.cl_init with None -> () | Some e -> expr e);
  1429. List.iter field c.cl_ordered_statics;
  1430. List.iter field c.cl_ordered_fields;
  1431. | _ -> ()
  1432. ) com.types;
  1433. let usage = List.sort (fun p1 p2 -> compare p1.pmin p2.pmin) !usage in
  1434. raise (Typecore.DisplayPosition usage)
  1435. (* -------------------------------------------------------------------------- *)
  1436. (* POST PROCESS *)
  1437. let pp_counter = ref 1
  1438. let post_process filters t =
  1439. (* ensure that we don't process twice the same (cached) module *)
  1440. let m = (t_infos t).mt_module.m_extra in
  1441. if m.m_processed = 0 then m.m_processed <- !pp_counter;
  1442. if m.m_processed = !pp_counter then
  1443. match t with
  1444. | TClassDecl c ->
  1445. let process_field f =
  1446. match f.cf_expr with
  1447. | None -> ()
  1448. | Some e ->
  1449. f.cf_expr <- Some (List.fold_left (fun e f -> f e) e filters)
  1450. in
  1451. List.iter process_field c.cl_ordered_fields;
  1452. List.iter process_field c.cl_ordered_statics;
  1453. (match c.cl_constructor with
  1454. | None -> ()
  1455. | Some f -> process_field f);
  1456. (match c.cl_init with
  1457. | None -> ()
  1458. | Some e ->
  1459. c.cl_init <- Some (List.fold_left (fun e f -> f e) e filters));
  1460. | TEnumDecl _ -> ()
  1461. | TTypeDecl _ -> ()
  1462. | TAbstractDecl _ -> ()
  1463. let post_process_end() =
  1464. incr pp_counter
  1465. (* -------------------------------------------------------------------------- *)
  1466. (* STACK MANAGEMENT EMULATION *)
  1467. type stack_context = {
  1468. stack_var : string;
  1469. stack_exc_var : string;
  1470. stack_pos_var : string;
  1471. stack_pos : pos;
  1472. stack_expr : texpr;
  1473. stack_pop : texpr;
  1474. stack_save_pos : texpr;
  1475. stack_restore : texpr list;
  1476. stack_push : tclass -> string -> texpr;
  1477. stack_return : texpr -> texpr;
  1478. }
  1479. let stack_context_init com stack_var exc_var pos_var tmp_var use_add p =
  1480. let t = com.basic in
  1481. let st = t.tarray t.tstring in
  1482. let stack_var = alloc_var stack_var st in
  1483. let exc_var = alloc_var exc_var st in
  1484. let pos_var = alloc_var pos_var t.tint in
  1485. let stack_e = mk (TLocal stack_var) st p in
  1486. let exc_e = mk (TLocal exc_var) st p in
  1487. let stack_pop = fcall stack_e "pop" [] t.tstring p in
  1488. let stack_push c m =
  1489. fcall stack_e "push" [
  1490. if use_add then
  1491. binop OpAdd (string com (s_type_path c.cl_path ^ "::") p) (string com m p) t.tstring p
  1492. else
  1493. string com (s_type_path c.cl_path ^ "::" ^ m) p
  1494. ] t.tvoid p
  1495. in
  1496. let stack_return e =
  1497. let tmp = alloc_var tmp_var e.etype in
  1498. mk (TBlock [
  1499. mk (TVars [tmp, Some e]) t.tvoid e.epos;
  1500. stack_pop;
  1501. mk (TReturn (Some (mk (TLocal tmp) e.etype e.epos))) e.etype e.epos
  1502. ]) e.etype e.epos
  1503. in
  1504. {
  1505. stack_var = stack_var.v_name;
  1506. stack_exc_var = exc_var.v_name;
  1507. stack_pos_var = pos_var.v_name;
  1508. stack_pos = p;
  1509. stack_expr = stack_e;
  1510. stack_pop = stack_pop;
  1511. stack_save_pos = mk (TVars [pos_var, Some (field stack_e "length" t.tint p)]) t.tvoid p;
  1512. stack_push = stack_push;
  1513. stack_return = stack_return;
  1514. stack_restore = [
  1515. binop OpAssign exc_e (mk (TArrayDecl []) st p) st p;
  1516. mk (TWhile (
  1517. mk_parent (binop OpGte (field stack_e "length" t.tint p) (mk (TLocal pos_var) t.tint p) t.tbool p),
  1518. fcall exc_e "unshift" [fcall stack_e "pop" [] t.tstring p] t.tvoid p,
  1519. NormalWhile
  1520. )) t.tvoid p;
  1521. fcall stack_e "push" [index com exc_e 0 t.tstring p] t.tvoid p
  1522. ];
  1523. }
  1524. let stack_init com use_add =
  1525. stack_context_init com "$s" "$e" "$spos" "$tmp" use_add null_pos
  1526. let rec stack_block_loop ctx e =
  1527. match e.eexpr with
  1528. | TFunction _ ->
  1529. e
  1530. | TReturn None | TReturn (Some { eexpr = TConst _ }) | TReturn (Some { eexpr = TLocal _ }) ->
  1531. mk (TBlock [
  1532. ctx.stack_pop;
  1533. e;
  1534. ]) e.etype e.epos
  1535. | TReturn (Some e) ->
  1536. ctx.stack_return (stack_block_loop ctx e)
  1537. | TTry (v,cases) ->
  1538. let v = stack_block_loop ctx v in
  1539. let cases = List.map (fun (v,e) ->
  1540. let e = stack_block_loop ctx e in
  1541. let e = (match (mk_block e).eexpr with
  1542. | TBlock l -> mk (TBlock (ctx.stack_restore @ l)) e.etype e.epos
  1543. | _ -> assert false
  1544. ) in
  1545. v , e
  1546. ) cases in
  1547. mk (TTry (v,cases)) e.etype e.epos
  1548. | _ ->
  1549. map_expr (stack_block_loop ctx) e
  1550. let stack_block ctx c m e =
  1551. match (mk_block e).eexpr with
  1552. | TBlock l ->
  1553. mk (TBlock (
  1554. ctx.stack_push c m ::
  1555. ctx.stack_save_pos ::
  1556. List.map (stack_block_loop ctx) l
  1557. @ [ctx.stack_pop]
  1558. )) e.etype e.epos
  1559. | _ ->
  1560. assert false
  1561. (* -------------------------------------------------------------------------- *)
  1562. (* FIX OVERRIDES *)
  1563. (*
  1564. on some platforms which doesn't support type parameters, we must have the
  1565. exact same type for overriden/implemented function as the original one
  1566. *)
  1567. let rec find_field c f =
  1568. try
  1569. (match c.cl_super with
  1570. | None ->
  1571. raise Not_found
  1572. | Some (c,_) ->
  1573. find_field c f)
  1574. with Not_found -> try
  1575. let rec loop = function
  1576. | [] ->
  1577. raise Not_found
  1578. | (c,_) :: l ->
  1579. try
  1580. find_field c f
  1581. with
  1582. Not_found -> loop l
  1583. in
  1584. loop c.cl_implements
  1585. with Not_found ->
  1586. let f = PMap.find f.cf_name c.cl_fields in
  1587. (match f.cf_kind with Var { v_read = AccRequire _ } -> raise Not_found | _ -> ());
  1588. f
  1589. let fix_override com c f fd =
  1590. let f2 = (try Some (find_field c f) with Not_found -> None) in
  1591. match f2,fd with
  1592. | Some (f2), Some(fd) ->
  1593. let targs, tret = (match follow f2.cf_type with TFun (args,ret) -> args, ret | _ -> assert false) in
  1594. let changed_args = ref [] in
  1595. let prefix = "_tmp_" in
  1596. let nargs = List.map2 (fun ((v,c) as cur) (_,_,t2) ->
  1597. try
  1598. type_eq EqStrict v.v_type t2;
  1599. cur
  1600. with Unify_error _ ->
  1601. let v2 = alloc_var (prefix ^ v.v_name) t2 in
  1602. changed_args := (v,v2) :: !changed_args;
  1603. v2,c
  1604. ) fd.tf_args targs in
  1605. let fd2 = {
  1606. tf_args = nargs;
  1607. tf_type = tret;
  1608. tf_expr = (match List.rev !changed_args with
  1609. | [] -> fd.tf_expr
  1610. | args ->
  1611. let e = fd.tf_expr in
  1612. let el = (match e.eexpr with TBlock el -> el | _ -> [e]) in
  1613. let p = (match el with [] -> e.epos | e :: _ -> e.epos) in
  1614. let v = mk (TVars (List.map (fun (v,v2) ->
  1615. (v,Some (mk (TCast (mk (TLocal v2) v2.v_type p,None)) v.v_type p))
  1616. ) args)) com.basic.tvoid p in
  1617. { e with eexpr = TBlock (v :: el) }
  1618. );
  1619. } in
  1620. (* as3 does not allow wider visibility, so the base method has to be made public *)
  1621. if Common.defined com Define.As3 && f.cf_public then f2.cf_public <- true;
  1622. let targs = List.map (fun(v,c) -> (v.v_name, Option.is_some c, v.v_type)) nargs in
  1623. let fde = (match f.cf_expr with None -> assert false | Some e -> e) in
  1624. f.cf_expr <- Some { fde with eexpr = TFunction fd2 };
  1625. f.cf_type <- TFun(targs,tret);
  1626. | Some(f2), None when c.cl_interface ->
  1627. let targs, tret = (match follow f2.cf_type with TFun (args,ret) -> args, ret | _ -> assert false) in
  1628. f.cf_type <- TFun(targs,tret)
  1629. | _ ->
  1630. ()
  1631. let fix_overrides com t =
  1632. match t with
  1633. | TClassDecl c ->
  1634. (* overrides can be removed from interfaces *)
  1635. if c.cl_interface then
  1636. c.cl_ordered_fields <- List.filter (fun f ->
  1637. try
  1638. if find_field c f == f then raise Not_found;
  1639. c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  1640. false;
  1641. with Not_found ->
  1642. true
  1643. ) c.cl_ordered_fields;
  1644. List.iter (fun f ->
  1645. match f.cf_expr, f.cf_kind with
  1646. | Some { eexpr = TFunction fd }, Method (MethNormal | MethInline) ->
  1647. fix_override com c f (Some fd)
  1648. | None, Method (MethNormal | MethInline) when c.cl_interface ->
  1649. fix_override com c f None
  1650. | _ ->
  1651. ()
  1652. ) c.cl_ordered_fields
  1653. | _ ->
  1654. ()
  1655. (*
  1656. PHP does not allow abstract classes extending other abstract classes to override any fields, so these duplicates
  1657. must be removed from the child interface
  1658. *)
  1659. let fix_abstract_inheritance com t =
  1660. match t with
  1661. | TClassDecl c when c.cl_interface ->
  1662. c.cl_ordered_fields <- List.filter (fun f ->
  1663. let b = try (find_field c f) == f
  1664. with Not_found -> false in
  1665. if not b then c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  1666. b;
  1667. ) c.cl_ordered_fields
  1668. | _ -> ()
  1669. (* -------------------------------------------------------------------------- *)
  1670. (* MISC FEATURES *)
  1671. let rec is_volatile t =
  1672. match t with
  1673. | TMono r ->
  1674. (match !r with
  1675. | Some t -> is_volatile t
  1676. | _ -> false)
  1677. | TLazy f ->
  1678. is_volatile (!f())
  1679. | TType (t,tl) ->
  1680. (match t.t_path with
  1681. | ["mt";"flash"],"Volatile" -> true
  1682. | _ -> is_volatile (apply_params t.t_types tl t.t_type))
  1683. | _ ->
  1684. false
  1685. let set_default ctx a c p =
  1686. let t = a.v_type in
  1687. let ve = mk (TLocal a) t p in
  1688. let cond = TBinop (OpEq,ve,mk (TConst TNull) t p) in
  1689. mk (TIf (mk_parent (mk cond ctx.basic.tbool p), mk (TBinop (OpAssign,ve,mk (TConst c) t p)) t p,None)) ctx.basic.tvoid p
  1690. let bytes_serialize data =
  1691. let b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%:" in
  1692. let tbl = Array.init (String.length b64) (fun i -> String.get b64 i) in
  1693. let str = Base64.str_encode ~tbl data in
  1694. "s" ^ string_of_int (String.length str) ^ ":" ^ str
  1695. (*
  1696. Tells if the constructor might be called without any issue whatever its parameters
  1697. *)
  1698. let rec constructor_side_effects e =
  1699. match e.eexpr with
  1700. | TBinop (op,_,_) when op <> OpAssign ->
  1701. true
  1702. | TField (_,FEnum _) ->
  1703. false
  1704. | TUnop _ | TArray _ | TField _ | TCall _ | TNew _ | TFor _ | TWhile _ | TSwitch _ | TMatch _ | TReturn _ | TThrow _ ->
  1705. true
  1706. | TBinop _ | TTry _ | TIf _ | TBlock _ | TVars _
  1707. | TFunction _ | TArrayDecl _ | TObjectDecl _
  1708. | TParenthesis _ | TTypeExpr _ | TLocal _
  1709. | TConst _ | TContinue | TBreak | TCast _ ->
  1710. try
  1711. Type.iter (fun e -> if constructor_side_effects e then raise Exit) e;
  1712. false;
  1713. with Exit ->
  1714. true
  1715. (*
  1716. Make a dump of the full typed AST of all types
  1717. *)
  1718. let rec create_dumpfile acc = function
  1719. | [] -> assert false
  1720. | d :: [] ->
  1721. let ch = open_out (String.concat "/" (List.rev (d :: acc)) ^ ".dump") in
  1722. let buf = Buffer.create 0 in
  1723. buf, (fun () ->
  1724. output_string ch (Buffer.contents buf);
  1725. close_out ch)
  1726. | d :: l ->
  1727. let dir = String.concat "/" (List.rev (d :: acc)) in
  1728. if not (Sys.file_exists dir) then Unix.mkdir dir 0o755;
  1729. create_dumpfile (d :: acc) l
  1730. let dump_types com =
  1731. let s_type = s_type (Type.print_context()) in
  1732. let params = function [] -> "" | l -> Printf.sprintf "<%s>" (String.concat "," (List.map (fun (n,t) -> n ^ " : " ^ s_type t) l)) in
  1733. let s_expr = try if Common.defined_value com Define.Dump = "pretty" then Type.s_expr_pretty "\t" else Type.s_expr with Not_found -> Type.s_expr in
  1734. List.iter (fun mt ->
  1735. let path = Type.t_path mt in
  1736. let buf,close = create_dumpfile [] ("dump" :: (Common.platform_name com.platform) :: fst path @ [snd path]) in
  1737. let print fmt = Printf.kprintf (fun s -> Buffer.add_string buf s) fmt in
  1738. (match mt with
  1739. | Type.TClassDecl c ->
  1740. let print_field stat f =
  1741. print "\t%s%s%s%s" (if stat then "static " else "") (if f.cf_public then "public " else "") f.cf_name (params f.cf_params);
  1742. print "(%s) : %s" (s_kind f.cf_kind) (s_type f.cf_type);
  1743. (match f.cf_expr with
  1744. | None -> ()
  1745. | Some e -> print "\n\n\t = %s" (s_expr s_type e));
  1746. print ";\n\n";
  1747. in
  1748. print "%s%s%s %s%s" (if c.cl_private then "private " else "") (if c.cl_extern then "extern " else "") (if c.cl_interface then "interface" else "class") (s_type_path path) (params c.cl_types);
  1749. (match c.cl_super with None -> () | Some (c,pl) -> print " extends %s" (s_type (TInst (c,pl))));
  1750. List.iter (fun (c,pl) -> print " implements %s" (s_type (TInst (c,pl)))) c.cl_implements;
  1751. (match c.cl_dynamic with None -> () | Some t -> print " implements Dynamic<%s>" (s_type t));
  1752. (match c.cl_array_access with None -> () | Some t -> print " implements ArrayAccess<%s>" (s_type t));
  1753. print "{\n";
  1754. (match c.cl_constructor with
  1755. | None -> ()
  1756. | Some f -> print_field false f);
  1757. List.iter (print_field false) c.cl_ordered_fields;
  1758. List.iter (print_field true) c.cl_ordered_statics;
  1759. print "}";
  1760. | Type.TEnumDecl e ->
  1761. print "%s%senum %s%s {\n" (if e.e_private then "private " else "") (if e.e_extern then "extern " else "") (s_type_path path) (params e.e_types);
  1762. List.iter (fun n ->
  1763. let f = PMap.find n e.e_constrs in
  1764. print "\t%s : %s;\n" f.ef_name (s_type f.ef_type);
  1765. ) e.e_names;
  1766. print "}"
  1767. | Type.TTypeDecl t ->
  1768. print "%stype %s%s = %s" (if t.t_private then "private " else "") (s_type_path path) (params t.t_types) (s_type t.t_type);
  1769. | Type.TAbstractDecl a ->
  1770. print "%sabstract %s%s {}" (if a.a_private then "private " else "") (s_type_path path) (params a.a_types);
  1771. );
  1772. close();
  1773. ) com.types
  1774. let dump_dependencies com =
  1775. let buf,close = create_dumpfile [] ["dump";Common.platform_name com.platform;".dependencies"] in
  1776. let print fmt = Printf.kprintf (fun s -> Buffer.add_string buf s) fmt in
  1777. let dep = Hashtbl.create 0 in
  1778. List.iter (fun m ->
  1779. print "%s:\n" m.m_extra.m_file;
  1780. PMap.iter (fun _ m2 ->
  1781. print "\t%s\n" (m2.m_extra.m_file);
  1782. let l = try Hashtbl.find dep m2.m_extra.m_file with Not_found -> [] in
  1783. Hashtbl.replace dep m2.m_extra.m_file (m :: l)
  1784. ) m.m_extra.m_deps;
  1785. ) com.Common.modules;
  1786. close();
  1787. let buf,close = create_dumpfile [] ["dump";Common.platform_name com.platform;".dependants"] in
  1788. let print fmt = Printf.kprintf (fun s -> Buffer.add_string buf s) fmt in
  1789. Hashtbl.iter (fun n ml ->
  1790. print "%s:\n" n;
  1791. List.iter (fun m ->
  1792. print "\t%s\n" (m.m_extra.m_file);
  1793. ) ml;
  1794. ) dep;
  1795. close()
  1796. (*
  1797. Build a default safe-cast expression :
  1798. { var $t = <e>; if( Std.is($t,<t>) ) $t else throw "Class cast error"; }
  1799. *)
  1800. let default_cast ?(vtmp="$t") com e texpr t p =
  1801. let api = com.basic in
  1802. let mk_texpr = function
  1803. | TClassDecl c -> TAnon { a_fields = PMap.empty; a_status = ref (Statics c) }
  1804. | TEnumDecl e -> TAnon { a_fields = PMap.empty; a_status = ref (EnumStatics e) }
  1805. | TAbstractDecl a -> TAnon { a_fields = PMap.empty; a_status = ref (AbstractStatics a) }
  1806. | TTypeDecl _ -> assert false
  1807. in
  1808. let vtmp = alloc_var vtmp e.etype in
  1809. let var = mk (TVars [vtmp,Some e]) api.tvoid p in
  1810. let vexpr = mk (TLocal vtmp) e.etype p in
  1811. let texpr = mk (TTypeExpr texpr) (mk_texpr texpr) p in
  1812. let std = (try List.find (fun t -> t_path t = ([],"Std")) com.types with Not_found -> assert false) in
  1813. let fis = (try
  1814. let c = (match std with TClassDecl c -> c | _ -> assert false) in
  1815. FStatic (c, PMap.find "is" c.cl_statics)
  1816. with Not_found ->
  1817. assert false
  1818. ) in
  1819. let std = mk (TTypeExpr std) (mk_texpr std) p in
  1820. let is = mk (TField (std,fis)) (tfun [t_dynamic;t_dynamic] api.tbool) p in
  1821. let is = mk (TCall (is,[vexpr;texpr])) api.tbool p in
  1822. let exc = mk (TThrow (mk (TConst (TString "Class cast error")) api.tstring p)) t p in
  1823. let check = mk (TIf (mk_parent is,mk (TCast (vexpr,None)) t p,Some exc)) t p in
  1824. mk (TBlock [var;check;vexpr]) t p