codegen.ml 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516
  1. (*
  2. * Haxe Compiler
  3. * Copyright (c)2005-2008 Nicolas Cannasse
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. *)
  19. open Ast
  20. open Type
  21. open Common
  22. open Typecore
  23. (* -------------------------------------------------------------------------- *)
  24. (* TOOLS *)
  25. let field e name t p =
  26. mk (TField (e,name)) t p
  27. let fcall e name el ret p =
  28. let ft = tfun (List.map (fun e -> e.etype) el) ret in
  29. mk (TCall (field e name ft p,el)) ret p
  30. let mk_parent e =
  31. mk (TParenthesis e) e.etype e.epos
  32. let string com str p =
  33. mk (TConst (TString str)) com.basic.tstring p
  34. let binop op a b t p =
  35. mk (TBinop (op,a,b)) t p
  36. let index com e index t p =
  37. mk (TArray (e,mk (TConst (TInt (Int32.of_int index))) com.basic.tint p)) t p
  38. let concat e1 e2 =
  39. let e = (match e1.eexpr, e2.eexpr with
  40. | TBlock el1, TBlock el2 -> TBlock (el1@el2)
  41. | TBlock el, _ -> TBlock (el @ [e2])
  42. | _, TBlock el -> TBlock (e1 :: el)
  43. | _ , _ -> TBlock [e1;e2]
  44. ) in
  45. mk e e2.etype (punion e1.epos e2.epos)
  46. let type_constant com c p =
  47. let t = com.basic in
  48. match c with
  49. | Int s ->
  50. if String.length s > 10 && String.sub s 0 2 = "0x" then error "Invalid hexadecimal integer" p;
  51. (try
  52. mk (TConst (TInt (Int32.of_string s))) t.tint p
  53. with
  54. _ -> mk (TConst (TFloat s)) t.tfloat p)
  55. | Float f -> mk (TConst (TFloat f)) t.tfloat p
  56. | String s -> mk (TConst (TString s)) t.tstring p
  57. | Ident "true" -> mk (TConst (TBool true)) t.tbool p
  58. | Ident "false" -> mk (TConst (TBool false)) t.tbool p
  59. | Ident "null" -> mk (TConst TNull) (t.tnull (mk_mono())) p
  60. | Ident t -> error ("Invalid constant : " ^ t) p
  61. | Regexp _ -> error "Invalid constant" p
  62. let rec type_constant_value com (e,p) =
  63. match e with
  64. | EConst c ->
  65. type_constant com c p
  66. | EParenthesis e ->
  67. type_constant_value com e
  68. | EObjectDecl el ->
  69. mk (TObjectDecl (List.map (fun (n,e) -> n, type_constant_value com e) el)) (TAnon { a_fields = PMap.empty; a_status = ref Closed }) p
  70. | EArrayDecl el ->
  71. mk (TArrayDecl (List.map (type_constant_value com) el)) (com.basic.tarray t_dynamic) p
  72. | _ ->
  73. error "Constant value expected" p
  74. let rec has_properties c =
  75. List.exists (fun f ->
  76. match f.cf_kind with
  77. | Var { v_read = AccCall _ } -> true
  78. | Var { v_write = AccCall _ } -> true
  79. | _ -> false
  80. ) c.cl_ordered_fields || (match c.cl_super with Some (c,_) -> has_properties c | _ -> false)
  81. let get_properties fields =
  82. List.fold_left (fun acc f ->
  83. let acc = (match f.cf_kind with
  84. | Var { v_read = AccCall getter } -> ("get_" ^ f.cf_name , getter) :: acc
  85. | _ -> acc) in
  86. match f.cf_kind with
  87. | Var { v_write = AccCall setter } -> ("set_" ^ f.cf_name , setter) :: acc
  88. | _ -> acc
  89. ) [] fields
  90. let add_property_field com c =
  91. let p = c.cl_pos in
  92. let props = get_properties (c.cl_ordered_statics @ c.cl_ordered_fields) in
  93. match props with
  94. | [] -> ()
  95. | _ ->
  96. let fields,values = List.fold_left (fun (fields,values) (n,v) ->
  97. let cf = mk_field n com.basic.tstring p in
  98. PMap.add n cf fields,(n, string com v p) :: values
  99. ) (PMap.empty,[]) props in
  100. let t = mk_anon fields in
  101. let e = mk (TObjectDecl values) t p in
  102. let cf = mk_field "__properties__" t p in
  103. cf.cf_expr <- Some e;
  104. c.cl_statics <- PMap.add cf.cf_name cf c.cl_statics;
  105. c.cl_ordered_statics <- cf :: c.cl_ordered_statics
  106. (* -------------------------------------------------------------------------- *)
  107. (* REMOTING PROXYS *)
  108. let extend_remoting ctx c t p async prot =
  109. if c.cl_super <> None then error "Cannot extend several classes" p;
  110. (* remove forbidden packages *)
  111. let rules = ctx.com.package_rules in
  112. ctx.com.package_rules <- PMap.foldi (fun key r acc -> match r with Forbidden -> acc | _ -> PMap.add key r acc) rules PMap.empty;
  113. (* parse module *)
  114. let path = (t.tpackage,t.tname) in
  115. let new_name = (if async then "Async_" else "Remoting_") ^ t.tname in
  116. (* check if the proxy already exists *)
  117. let t = (try
  118. Typeload.load_type_def ctx p { tpackage = fst path; tname = new_name; tparams = []; tsub = None }
  119. with
  120. Error (Module_not_found _,p2) when p == p2 ->
  121. (* build it *)
  122. Common.log ctx.com ("Building proxy for " ^ s_type_path path);
  123. let file, decls = (try
  124. Typeload.parse_module ctx path p
  125. with
  126. | 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
  127. | e -> ctx.com.package_rules <- rules; raise e) in
  128. ctx.com.package_rules <- rules;
  129. let base_fields = [
  130. { 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) };
  131. { 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 = [] } };
  132. ] in
  133. let tvoid = CTPath { tpackage = []; tname = "Void"; tparams = []; tsub = None } in
  134. let build_field is_public acc f =
  135. if f.cff_name = "new" then
  136. acc
  137. else match f.cff_kind with
  138. | FFun fd when (is_public || List.mem APublic f.cff_access) && not (List.mem AStatic f.cff_access) ->
  139. 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;
  140. let eargs = [EArrayDecl (List.map (fun (a,_,_,_) -> (EConst (Ident a),p)) fd.f_args),p] in
  141. let ftype = (match fd.f_type with Some (CTPath { tpackage = []; tname = "Void" }) -> None | _ -> fd.f_type) in
  142. let fargs, eargs = if async then match ftype with
  143. | Some tret -> fd.f_args @ ["__callb",true,Some (CTFunction ([tret],tvoid)),None], eargs @ [EConst (Ident "__callb"),p]
  144. | _ -> fd.f_args, eargs @ [EConst (Ident "null"),p]
  145. else
  146. fd.f_args, eargs
  147. in
  148. let id = (EConst (String f.cff_name), p) in
  149. let id = if prot then id else ECall ((EConst (Ident "__unprotect__"),p),[id]),p in
  150. let expr = ECall (
  151. (EField (
  152. (ECall ((EField ((EConst (Ident "__cnx"),p),"resolve"),p),[id]),p),
  153. "call")
  154. ,p),eargs),p
  155. in
  156. let expr = if async || ftype = None then expr else (EReturn (Some expr),p) in
  157. let fd = {
  158. f_params = fd.f_params;
  159. f_args = fargs;
  160. f_type = if async then None else ftype;
  161. f_expr = Some (EBlock [expr],p);
  162. } in
  163. { cff_name = f.cff_name; cff_pos = p; cff_doc = None; cff_meta = []; cff_access = [APublic]; cff_kind = FFun fd } :: acc
  164. | _ -> acc
  165. in
  166. let decls = List.map (fun d ->
  167. match d with
  168. | EClass c, p when c.d_name = t.tname ->
  169. let is_public = List.mem HExtern c.d_flags || List.mem HInterface c.d_flags in
  170. let fields = List.rev (List.fold_left (build_field is_public) base_fields c.d_data) in
  171. (EClass { c with d_flags = []; d_name = new_name; d_data = fields },p)
  172. | _ -> d
  173. ) decls in
  174. let m = Typeload.type_module ctx (t.tpackage,new_name) file decls p in
  175. add_dependency ctx.current m;
  176. try
  177. List.find (fun tdecl -> snd (t_path tdecl) = new_name) m.m_types
  178. with Not_found ->
  179. error ("Module " ^ s_type_path path ^ " does not define type " ^ t.tname) p
  180. ) in
  181. match t with
  182. | TClassDecl c2 when c2.cl_types = [] -> c.cl_super <- Some (c2,[]);
  183. | _ -> error "Remoting proxy must be a class without parameters" p
  184. (* -------------------------------------------------------------------------- *)
  185. (* HAXE.RTTI.GENERIC *)
  186. let rec build_generic ctx c p tl =
  187. let pack = fst c.cl_path in
  188. let recurse = ref false in
  189. let rec check_recursive t =
  190. match follow t with
  191. | TInst (c,tl) ->
  192. if c.cl_kind = KTypeParameter then recurse := true;
  193. List.iter check_recursive tl;
  194. | _ ->
  195. ()
  196. in
  197. let name = String.concat "_" (snd c.cl_path :: (List.map (fun t ->
  198. check_recursive t;
  199. let path = (match follow t with
  200. | TInst (c,_) -> c.cl_path
  201. | TEnum (e,_) -> e.e_path
  202. | TMono _ -> error "Type parameter must be explicit when creating a haxe.rtti.Generic instance" p
  203. | _ -> error "Type parameter must be a class or enum instance" p
  204. ) in
  205. match path with
  206. | [] , name -> name
  207. | l , name -> String.concat "_" l ^ "_" ^ name
  208. ) tl)) in
  209. if !recurse then
  210. TInst (c,tl) (* build a normal instance *)
  211. else try
  212. Typeload.load_instance ctx { tpackage = pack; tname = name; tparams = []; tsub = None } p false
  213. with Error(Module_not_found path,_) when path = (pack,name) ->
  214. let m = (try Hashtbl.find ctx.g.modules (Hashtbl.find ctx.g.types_module c.cl_path) with Not_found -> assert false) in
  215. let ctx = { ctx with local_types = m.m_types @ ctx.local_types } in
  216. let mg = {
  217. m_id = alloc_mid();
  218. m_path = (pack,name);
  219. m_types = [];
  220. m_extra = module_extra (s_type_path (pack,name)) m.m_extra.m_sign 0. MFake;
  221. } in
  222. let cg = mk_class mg (pack,name) c.cl_pos in
  223. mg.m_types <- [TClassDecl cg];
  224. Hashtbl.add ctx.g.modules mg.m_path mg;
  225. add_dependency mg m;
  226. add_dependency ctx.current mg;
  227. let rec loop l1 l2 =
  228. match l1, l2 with
  229. | [] , [] -> []
  230. | (x,TLazy f) :: l1, _ -> loop ((x,(!f)()) :: l1) l2
  231. | (_,t1) :: l1 , t2 :: l2 -> (t1,t2) :: loop l1 l2
  232. | _ -> assert false
  233. in
  234. let subst = loop c.cl_types tl in
  235. let rec build_type t =
  236. match t with
  237. | TInst ({ cl_kind = KGeneric } as c2,tl2) ->
  238. (* maybe loop, or generate cascading generics *)
  239. let _, _, f = ctx.g.do_build_instance ctx (TClassDecl c2) p in
  240. f (List.map build_type tl2)
  241. | _ ->
  242. try List.assq t subst with Not_found -> Type.map build_type t
  243. in
  244. let vars = Hashtbl.create 0 in
  245. let build_var v =
  246. try
  247. Hashtbl.find vars v.v_id
  248. with Not_found ->
  249. let v2 = alloc_var v.v_name (build_type v.v_type) in
  250. Hashtbl.add vars v.v_id v2;
  251. v2
  252. in
  253. let rec build_expr e = map_expr_type build_expr build_type build_var e in
  254. let build_field f =
  255. let t = build_type f.cf_type in
  256. { f with cf_type = t; cf_expr = (match f.cf_expr with None -> None | Some e -> Some (build_expr e)) }
  257. in
  258. if c.cl_init <> None || c.cl_dynamic <> None then error "This class can't be generic" p;
  259. if c.cl_ordered_statics <> [] then error "A generic class can't have static fields" p;
  260. cg.cl_super <- (match c.cl_super with
  261. | None -> None
  262. | Some (cs,pl) ->
  263. (match apply_params c.cl_types tl (TInst (cs,pl)) with
  264. | TInst (cs,pl) when cs.cl_kind = KGeneric ->
  265. (match build_generic ctx cs p pl with
  266. | TInst (cs,pl) -> Some (cs,pl)
  267. | _ -> assert false)
  268. | TInst (cs,pl) -> Some (cs,pl)
  269. | _ -> assert false)
  270. );
  271. cg.cl_kind <- KGenericInstance (c,tl);
  272. cg.cl_interface <- c.cl_interface;
  273. cg.cl_constructor <- (match c.cl_constructor, c.cl_super with
  274. | None, None -> None
  275. | Some c, _ -> Some (build_field c)
  276. | _ -> error "Please define a constructor for this class in order to use haxe.rtti.Generic" c.cl_pos
  277. );
  278. cg.cl_implements <- List.map (fun (i,tl) ->
  279. (match follow (build_type (TInst (i, List.map build_type tl))) with
  280. | TInst (i,tl) -> i, tl
  281. | _ -> assert false)
  282. ) c.cl_implements;
  283. cg.cl_ordered_fields <- List.map (fun f ->
  284. let f = build_field f in
  285. cg.cl_fields <- PMap.add f.cf_name f cg.cl_fields;
  286. f
  287. ) c.cl_ordered_fields;
  288. TInst (cg,[])
  289. (* -------------------------------------------------------------------------- *)
  290. (* HAXE.XML.PROXY *)
  291. let extend_xml_proxy ctx c t file p =
  292. let t = Typeload.load_complex_type ctx p t in
  293. let file = (try Common.find_file ctx.com file with Not_found -> file) in
  294. add_dependency c.cl_module (create_fake_module ctx file);
  295. let used = ref PMap.empty in
  296. let print_results() =
  297. PMap.iter (fun id used ->
  298. if not used then ctx.com.warning (id ^ " is not used") p;
  299. ) (!used)
  300. in
  301. let check_used = Common.defined ctx.com "check-xml-proxy" in
  302. if check_used then ctx.g.hook_generate <- print_results :: ctx.g.hook_generate;
  303. try
  304. let rec loop = function
  305. | Xml.Element (_,attrs,childs) ->
  306. (try
  307. let id = List.assoc "id" attrs in
  308. if PMap.mem id c.cl_fields then error ("Duplicate id " ^ id) p;
  309. let t = if not check_used then t else begin
  310. used := PMap.add id false (!used);
  311. let ft() = used := PMap.add id true (!used); t in
  312. TLazy (ref ft)
  313. end in
  314. let f = {
  315. cf_name = id;
  316. cf_type = t;
  317. cf_public = true;
  318. cf_pos = p;
  319. cf_doc = None;
  320. cf_meta = no_meta;
  321. cf_kind = Var { v_read = AccResolve; v_write = AccNo };
  322. cf_params = [];
  323. cf_expr = None;
  324. cf_overloads = [];
  325. } in
  326. c.cl_fields <- PMap.add id f c.cl_fields;
  327. with
  328. Not_found -> ());
  329. List.iter loop childs;
  330. | Xml.PCData _ -> ()
  331. in
  332. loop (Xml.parse_file file)
  333. with
  334. | Xml.Error e -> error ("XML error " ^ Xml.error e) p
  335. | Xml.File_not_found f -> error ("XML File not found : " ^ f) p
  336. (* -------------------------------------------------------------------------- *)
  337. (* BUILD META DATA OBJECT *)
  338. let build_metadata com t =
  339. let api = com.basic in
  340. let p, meta, fields, statics = (match t with
  341. | TClassDecl c ->
  342. 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
  343. let statics = List.map (fun f -> f.cf_name,f.cf_meta) c.cl_ordered_statics in
  344. (c.cl_pos, ["",c.cl_meta],fields,statics)
  345. | TEnumDecl e ->
  346. (e.e_pos, ["",e.e_meta],List.map (fun n -> n, (PMap.find n e.e_constrs).ef_meta) e.e_names, [])
  347. | TTypeDecl t ->
  348. (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 [] | _ -> []),[])
  349. ) in
  350. let filter l =
  351. let l = List.map (fun (n,ml) -> n, List.filter (fun (m,_,_) -> m.[0] <> ':') ml) l in
  352. List.filter (fun (_,ml) -> ml <> []) l
  353. in
  354. let meta, fields, statics = filter meta, filter fields, filter statics in
  355. let make_meta_field ml =
  356. let h = Hashtbl.create 0 in
  357. mk (TObjectDecl (List.map (fun (f,el,p) ->
  358. if Hashtbl.mem h f then error ("Duplicate metadata '" ^ f ^ "'") p;
  359. Hashtbl.add h f ();
  360. f, mk (match el with [] -> TConst TNull | _ -> TArrayDecl (List.map (type_constant_value com) el)) (api.tarray t_dynamic) p
  361. ) ml)) (api.tarray t_dynamic) p
  362. in
  363. let make_meta l =
  364. mk (TObjectDecl (List.map (fun (f,ml) -> f,make_meta_field ml) l)) t_dynamic p
  365. in
  366. if meta = [] && fields = [] && statics = [] then
  367. None
  368. else
  369. let meta_obj = [] in
  370. let meta_obj = (if fields = [] then meta_obj else ("fields",make_meta fields) :: meta_obj) in
  371. let meta_obj = (if statics = [] then meta_obj else ("statics",make_meta statics) :: meta_obj) in
  372. let meta_obj = (try ("obj", make_meta_field (List.assoc "" meta)) :: meta_obj with Not_found -> meta_obj) in
  373. Some (mk (TObjectDecl meta_obj) t_dynamic p)
  374. (* -------------------------------------------------------------------------- *)
  375. (* MACRO TYPE *)
  376. let build_macro_type ctx pl p =
  377. let path, field, args = (match pl with
  378. | [TInst ({ cl_kind = KExpr (ECall (e,args),_) },_)]
  379. | [TInst ({ cl_kind = KExpr (EArrayDecl [ECall (e,args),_],_) },_)] ->
  380. let rec loop e =
  381. match fst e with
  382. | EField (e,f) -> f :: loop e
  383. | EConst (Ident i) -> [i]
  384. | _ -> error "Invalid macro call" p
  385. in
  386. (match loop e with
  387. | meth :: cl :: path -> (List.rev path,cl), meth, args
  388. | _ -> error "Invalid macro call" p)
  389. | _ ->
  390. error "MacroType require a single expression call parameter" p
  391. ) in
  392. let old = ctx.ret in
  393. let t = (match ctx.g.do_macro ctx MMacroType path field args p with
  394. | None -> mk_mono()
  395. | Some _ -> ctx.ret
  396. ) in
  397. ctx.ret <- old;
  398. t
  399. (* -------------------------------------------------------------------------- *)
  400. (* API EVENTS *)
  401. let build_instance ctx mtype p =
  402. match mtype with
  403. | TClassDecl c ->
  404. let ft = (fun pl ->
  405. match c.cl_kind with
  406. | KGeneric ->
  407. let r = exc_protect ctx (fun r ->
  408. let t = mk_mono() in
  409. r := (fun() -> t);
  410. unify_raise ctx (build_generic ctx c p pl) t p;
  411. t
  412. ) in
  413. delay ctx (fun() -> ignore ((!r)()));
  414. TLazy r
  415. | KMacroType ->
  416. let r = exc_protect ctx (fun r ->
  417. let t = mk_mono() in
  418. r := (fun() -> t);
  419. unify_raise ctx (build_macro_type ctx pl p) t p;
  420. t
  421. ) in
  422. delay ctx (fun() -> ignore ((!r)()));
  423. TLazy r
  424. | _ ->
  425. TInst (c,pl)
  426. ) in
  427. c.cl_types , c.cl_path , ft
  428. | TEnumDecl e ->
  429. e.e_types , e.e_path , (fun t -> TEnum (e,t))
  430. | TTypeDecl t ->
  431. t.t_types , t.t_path , (fun tl -> TType(t,tl))
  432. let on_inherit ctx c p h =
  433. match h with
  434. | HExtends { tpackage = ["haxe";"remoting"]; tname = "Proxy"; tparams = [TPType(CTPath t)] } ->
  435. extend_remoting ctx c t p false true;
  436. false
  437. | HExtends { tpackage = ["haxe";"remoting"]; tname = "AsyncProxy"; tparams = [TPType(CTPath t)] } ->
  438. extend_remoting ctx c t p true true;
  439. false
  440. | HExtends { tpackage = ["mt"]; tname = "AsyncProxy"; tparams = [TPType(CTPath t)] } ->
  441. extend_remoting ctx c t p true false;
  442. false
  443. | HImplements { tpackage = ["haxe";"rtti"]; tname = "Generic"; tparams = [] } ->
  444. if c.cl_types <> [] then c.cl_kind <- KGeneric;
  445. false
  446. | HExtends { tpackage = ["haxe";"xml"]; tname = "Proxy"; tparams = [TPExpr(EConst (String file),p);TPType t] } ->
  447. extend_xml_proxy ctx c t file p;
  448. true
  449. | _ ->
  450. true
  451. (* -------------------------------------------------------------------------- *)
  452. (* FINAL GENERATION *)
  453. (*
  454. Adds member field initializations as assignments to the constructor
  455. *)
  456. let add_field_inits com c =
  457. let ethis = mk (TConst TThis) (TInst (c,List.map snd c.cl_types)) c.cl_pos in
  458. (* TODO: we have to find a variable name which is not used in any of the functions *)
  459. let v = alloc_var "_g" ethis.etype in
  460. let rec can_init_inline cf e = match com.platform,e.eexpr with
  461. | Flash8,_ -> true
  462. | Flash,_ when Common.defined com "as3" && (match cf.cf_kind with Var _ -> true | Method _ -> false) -> true
  463. | Php, TTypeExpr _ -> false
  464. | Php,_ ->
  465. (match cf.cf_kind with Var({v_write = AccCall _}) -> false | _ -> true)
  466. | _ -> false
  467. in
  468. let need_this = ref false in
  469. let inits,fields = List.fold_left (fun (inits,fields) cf ->
  470. match cf.cf_kind,cf.cf_expr with
  471. | Var _, Some e when can_init_inline cf e -> (inits, cf :: fields)
  472. | Var _, Some _ -> (cf :: inits, cf :: fields)
  473. | Method MethDynamic, Some e when Common.defined com "as3" ->
  474. (* we move the initialization of dynamic functions to the constructor and also solve the
  475. 'this' problem along the way *)
  476. let rec use_this v e = match e.eexpr with
  477. | TConst TThis ->
  478. need_this := true;
  479. mk (TLocal v) v.v_type e.epos
  480. | _ -> Type.map_expr (use_this v) e
  481. in
  482. let e = Type.map_expr (use_this v) e in
  483. let cf = {cf with cf_expr = Some e} in
  484. (* if the method is an override, we have to remove the class field to not get invalid overrides *)
  485. let fields = if List.mem cf.cf_name c.cl_overrides then begin
  486. c.cl_fields <- PMap.remove cf.cf_name c.cl_fields;
  487. fields
  488. end else
  489. cf :: fields
  490. in
  491. (cf :: inits, fields)
  492. | _ -> (inits, cf :: fields)
  493. ) ([],[]) c.cl_ordered_fields in
  494. c.cl_ordered_fields <- fields;
  495. match inits with
  496. | [] -> ()
  497. | _ ->
  498. let el = List.map (fun cf ->
  499. match cf.cf_expr with
  500. | None -> assert false
  501. | Some e ->
  502. let lhs = mk (TField(ethis,cf.cf_name)) e.etype e.epos in
  503. cf.cf_expr <- None;
  504. let eassign = mk (TBinop(OpAssign,lhs,e)) lhs.etype e.epos in
  505. if Common.defined com "as3" then begin
  506. let echeck = mk (TBinop(OpEq,lhs,(mk (TConst TNull) lhs.etype e.epos))) com.basic.tbool e.epos in
  507. mk (TIf(echeck,eassign,None)) eassign.etype e.epos
  508. end else
  509. eassign;
  510. ) inits in
  511. let el = if !need_this then (mk (TVars([v, Some ethis])) ethis.etype ethis.epos) :: el else el in
  512. match c.cl_constructor with
  513. | None ->
  514. let ct = TFun([],com.basic.tvoid) in
  515. let ce = mk (TFunction {
  516. tf_args = [];
  517. tf_type = com.basic.tvoid;
  518. tf_expr = mk (TBlock el) com.basic.tvoid c.cl_pos;
  519. }) ct c.cl_pos in
  520. let ctor = mk_field "new" ct c.cl_pos in
  521. ctor.cf_kind <- Method MethNormal;
  522. c.cl_constructor <- Some { ctor with cf_expr = Some ce };
  523. | Some cf ->
  524. match cf.cf_expr with
  525. | Some { eexpr = TFunction f } ->
  526. let bl = match f.tf_expr with {eexpr = TBlock b } -> b | x -> [x] in
  527. let ce = mk (TFunction {f with tf_expr = mk (TBlock (el @ bl)) com.basic.tvoid c.cl_pos }) cf.cf_type cf.cf_pos in
  528. c.cl_constructor <- Some {cf with cf_expr = Some ce }
  529. | _ ->
  530. assert false
  531. let rec has_rtti c =
  532. List.exists (function (t,pl) ->
  533. match t, pl with
  534. | { cl_path = ["haxe";"rtti"],"Infos" },[] -> true
  535. | _ -> false
  536. ) c.cl_implements || (match c.cl_super with None -> false | Some (c,_) -> has_rtti c)
  537. let restore c =
  538. let meta = c.cl_meta and path = c.cl_path and ext = c.cl_extern in
  539. let fl = c.cl_fields and ofl = c.cl_ordered_fields and st = c.cl_statics and ost = c.cl_ordered_statics in
  540. (fun() ->
  541. c.cl_meta <- meta;
  542. c.cl_extern <- ext;
  543. c.cl_path <- path;
  544. c.cl_fields <- fl;
  545. c.cl_ordered_fields <- ofl;
  546. c.cl_statics <- st;
  547. c.cl_ordered_statics <- ost;
  548. )
  549. let on_generate ctx t =
  550. match t with
  551. | TClassDecl c ->
  552. if c.cl_private then begin
  553. let rpath = (fst c.cl_module.m_path,"_" ^ snd c.cl_module.m_path) in
  554. if Hashtbl.mem ctx.g.types_module rpath then error ("This private class name will clash with " ^ s_type_path rpath) c.cl_pos;
  555. end;
  556. c.cl_restore <- restore c;
  557. List.iter (fun m ->
  558. match m with
  559. | ":native",[Ast.EConst (Ast.String name),p],mp ->
  560. c.cl_meta <- (":realPath",[Ast.EConst (Ast.String (s_type_path c.cl_path)),p],mp) :: c.cl_meta;
  561. c.cl_path <- parse_path name;
  562. | _ -> ()
  563. ) c.cl_meta;
  564. if has_rtti c && not (PMap.mem "__rtti" c.cl_statics) then begin
  565. let f = mk_field "__rtti" ctx.t.tstring c.cl_pos in
  566. let str = Genxml.gen_type_string ctx.com t in
  567. f.cf_expr <- Some (mk (TConst (TString str)) f.cf_type c.cl_pos);
  568. c.cl_ordered_statics <- f :: c.cl_ordered_statics;
  569. c.cl_statics <- PMap.add f.cf_name f c.cl_statics;
  570. end;
  571. let do_remove f =
  572. (not ctx.in_macro && f.cf_kind = Method MethMacro) || has_meta ":extern" f.cf_meta
  573. in
  574. List.iter (fun f ->
  575. if do_remove f then begin
  576. c.cl_statics <- PMap.remove f.cf_name c.cl_statics;
  577. c.cl_ordered_statics <- List.filter (fun f2 -> f != f2) c.cl_ordered_statics;
  578. end
  579. ) c.cl_ordered_statics;
  580. List.iter (fun f ->
  581. if do_remove f then begin
  582. c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  583. c.cl_ordered_fields <- List.filter (fun f2 -> f != f2) c.cl_ordered_fields;
  584. end
  585. ) c.cl_ordered_fields;
  586. add_field_inits ctx.com c;
  587. (match build_metadata ctx.com t with
  588. | None -> ()
  589. | Some e ->
  590. let f = mk_field "__meta__" t_dynamic c.cl_pos in
  591. f.cf_expr <- Some e;
  592. c.cl_ordered_statics <- f :: c.cl_ordered_statics;
  593. c.cl_statics <- PMap.add f.cf_name f c.cl_statics);
  594. c.cl_implements <- List.filter (fun (c,_) -> not (has_meta ":remove" c.cl_meta)) c.cl_implements;
  595. | TEnumDecl e ->
  596. List.iter (fun m ->
  597. match m with
  598. | ":native",[Ast.EConst (Ast.String name),p],mp ->
  599. e.e_meta <- (":realPath",[Ast.EConst (Ast.String (s_type_path e.e_path)),p],mp) :: e.e_meta;
  600. e.e_path <- parse_path name;
  601. | _ -> ()
  602. ) e.e_meta;
  603. | _ ->
  604. ()
  605. (* -------------------------------------------------------------------------- *)
  606. (* LOCAL VARIABLES USAGE *)
  607. type usage =
  608. | Block of ((usage -> unit) -> unit)
  609. | Loop of ((usage -> unit) -> unit)
  610. | Function of ((usage -> unit) -> unit)
  611. | Declare of tvar
  612. | Use of tvar
  613. let rec local_usage f e =
  614. match e.eexpr with
  615. | TLocal v ->
  616. f (Use v)
  617. | TVars l ->
  618. List.iter (fun (v,e) ->
  619. (match e with None -> () | Some e -> local_usage f e);
  620. f (Declare v);
  621. ) l
  622. | TFunction tf ->
  623. let cc f =
  624. List.iter (fun (v,_) -> f (Declare v)) tf.tf_args;
  625. local_usage f tf.tf_expr;
  626. in
  627. f (Function cc)
  628. | TBlock l ->
  629. f (Block (fun f -> List.iter (local_usage f) l))
  630. | TFor (v,it,e) ->
  631. local_usage f it;
  632. f (Loop (fun f ->
  633. f (Declare v);
  634. local_usage f e;
  635. ))
  636. | TWhile _ ->
  637. f (Loop (fun f ->
  638. iter (local_usage f) e
  639. ))
  640. | TTry (e,catchs) ->
  641. local_usage f e;
  642. List.iter (fun (v,e) ->
  643. f (Block (fun f ->
  644. f (Declare v);
  645. local_usage f e;
  646. ))
  647. ) catchs;
  648. | TMatch (e,_,cases,def) ->
  649. local_usage f e;
  650. List.iter (fun (_,vars,e) ->
  651. let cc f =
  652. (match vars with
  653. | None -> ()
  654. | Some l -> List.iter (function None -> () | Some v -> f (Declare v)) l);
  655. local_usage f e;
  656. in
  657. f (Block cc)
  658. ) cases;
  659. (match def with None -> () | Some e -> local_usage f e);
  660. | _ ->
  661. iter (local_usage f) e
  662. (* -------------------------------------------------------------------------- *)
  663. (* BLOCK VARIABLES CAPTURE *)
  664. (*
  665. For some platforms, it will simply mark the variables which are used in closures
  666. using the v_capture flag so it can be processed in a more optimized
  667. For Flash/JS platforms, it will ensure that variables used in loop sub-functions
  668. have an unique scope. It transforms the following expression :
  669. for( x in array )
  670. funs.push(function() return x++);
  671. Into the following :
  672. for( _x in array ) {
  673. var x = [_x];
  674. funs.push(function(x) { function() return x[0]++; }(x));
  675. }
  676. *)
  677. let captured_vars com e =
  678. let t = com.basic in
  679. let rec mk_init av v pos =
  680. mk (TVars [av,Some (mk (TArrayDecl [mk (TLocal v) v.v_type pos]) av.v_type pos)]) t.tvoid pos
  681. and mk_var v used =
  682. alloc_var v.v_name (PMap.find v.v_id used)
  683. and wrap used e =
  684. match e.eexpr with
  685. | TVars vl ->
  686. let vl = List.map (fun (v,ve) ->
  687. if PMap.mem v.v_id used then
  688. v, Some (mk (TArrayDecl (match ve with None -> [] | Some e -> [wrap used e])) v.v_type e.epos)
  689. else
  690. v, (match ve with None -> None | Some e -> Some (wrap used e))
  691. ) vl in
  692. { e with eexpr = TVars vl }
  693. | TLocal v when PMap.mem v.v_id used ->
  694. mk (TArray ({ e with etype = v.v_type },mk (TConst (TInt 0l)) t.tint e.epos)) e.etype e.epos
  695. | TFor (v,it,expr) when PMap.mem v.v_id used ->
  696. let vtmp = mk_var v used in
  697. let it = wrap used it in
  698. let expr = wrap used expr in
  699. mk (TFor (vtmp,it,concat (mk_init v vtmp e.epos) expr)) e.etype e.epos
  700. | TTry (expr,catchs) ->
  701. let catchs = List.map (fun (v,e) ->
  702. let e = wrap used e in
  703. try
  704. let vtmp = mk_var v used in
  705. vtmp, concat (mk_init v vtmp e.epos) e
  706. with Not_found ->
  707. v, e
  708. ) catchs in
  709. mk (TTry (wrap used expr,catchs)) e.etype e.epos
  710. | TMatch (expr,enum,cases,def) ->
  711. let cases = List.map (fun (il,vars,e) ->
  712. let pos = e.epos in
  713. let e = ref (wrap used e) in
  714. let vars = match vars with
  715. | None -> None
  716. | Some l ->
  717. Some (List.map (fun v ->
  718. match v with
  719. | Some v when PMap.mem v.v_id used ->
  720. let vtmp = mk_var v used in
  721. e := concat (mk_init v vtmp pos) !e;
  722. Some vtmp
  723. | _ -> v
  724. ) l)
  725. in
  726. il, vars, !e
  727. ) cases in
  728. let def = match def with None -> None | Some e -> Some (wrap used e) in
  729. mk (TMatch (wrap used expr,enum,cases,def)) e.etype e.epos
  730. | TFunction f ->
  731. (*
  732. list variables that are marked as used, but also used in that
  733. function and which are not declared inside it !
  734. *)
  735. let fused = ref PMap.empty in
  736. let tmp_used = ref used in
  737. let rec browse = function
  738. | Block f | Loop f | Function f -> f browse
  739. | Use v ->
  740. if PMap.mem v.v_id !tmp_used then fused := PMap.add v.v_id v !fused;
  741. | Declare v ->
  742. tmp_used := PMap.remove v.v_id !tmp_used
  743. in
  744. local_usage browse e;
  745. let vars = PMap.fold (fun v acc -> v :: acc) !fused [] in
  746. (* in case the variable has been marked as used in a parallel scope... *)
  747. let fexpr = ref (wrap used f.tf_expr) in
  748. let fargs = List.map (fun (v,o) ->
  749. if PMap.mem v.v_id used then
  750. let vtmp = mk_var v used in
  751. fexpr := concat (mk_init v vtmp e.epos) !fexpr;
  752. vtmp, o
  753. else
  754. v, o
  755. ) f.tf_args in
  756. let e = { e with eexpr = TFunction { f with tf_args = fargs; tf_expr = !fexpr } } in
  757. (match com.platform with
  758. | Cpp | Java | Cs -> e
  759. | _ ->
  760. mk (TCall (
  761. mk_parent (mk (TFunction {
  762. tf_args = List.map (fun v -> v, None) vars;
  763. tf_type = e.etype;
  764. tf_expr = mk_block (mk (TReturn (Some e)) e.etype e.epos);
  765. }) (TFun (List.map (fun v -> v.v_name,false,v.v_type) vars,e.etype)) e.epos),
  766. List.map (fun v -> mk (TLocal v) v.v_type e.epos) vars)
  767. ) e.etype e.epos)
  768. | _ ->
  769. map_expr (wrap used) e
  770. and do_wrap used e =
  771. if PMap.is_empty used then
  772. e
  773. else
  774. let used = PMap.map (fun v ->
  775. let vt = v.v_type in
  776. v.v_type <- t.tarray vt;
  777. v.v_capture <- true;
  778. vt
  779. ) used in
  780. wrap used e
  781. and out_loop e =
  782. match e.eexpr with
  783. | TFor _ | TWhile _ ->
  784. (*
  785. collect variables that are declared in loop but used in subfunctions
  786. *)
  787. let vars = ref PMap.empty in
  788. let used = ref PMap.empty in
  789. let depth = ref 0 in
  790. let rec collect_vars in_loop = function
  791. | Block f ->
  792. let old = !vars in
  793. f (collect_vars in_loop);
  794. vars := old;
  795. | Loop f ->
  796. let old = !vars in
  797. f (collect_vars true);
  798. vars := old;
  799. | Function f ->
  800. incr depth;
  801. f (collect_vars false);
  802. decr depth;
  803. | Declare v ->
  804. if in_loop then vars := PMap.add v.v_id !depth !vars;
  805. | Use v ->
  806. try
  807. let d = PMap.find v.v_id !vars in
  808. if d <> !depth then used := PMap.add v.v_id v !used;
  809. with Not_found ->
  810. ()
  811. in
  812. local_usage (collect_vars false) e;
  813. do_wrap !used e
  814. | _ ->
  815. map_expr out_loop e
  816. and all_vars e =
  817. let vars = ref PMap.empty in
  818. let used = ref PMap.empty in
  819. let depth = ref 0 in
  820. let rec collect_vars = function
  821. | Block f ->
  822. let old = !vars in
  823. f collect_vars;
  824. vars := old;
  825. | Loop f ->
  826. let old = !vars in
  827. f collect_vars;
  828. vars := old;
  829. | Function f ->
  830. incr depth;
  831. f collect_vars;
  832. decr depth;
  833. | Declare v ->
  834. vars := PMap.add v.v_id !depth !vars;
  835. | Use v ->
  836. try
  837. let d = PMap.find v.v_id !vars in
  838. if d <> !depth then used := PMap.add v.v_id v !used;
  839. with Not_found -> ()
  840. in
  841. local_usage collect_vars e;
  842. !used
  843. in
  844. match com.platform with
  845. | Php | Cross ->
  846. e
  847. | Neko ->
  848. (*
  849. this could be optimized to take into account only vars
  850. that are actually modified in closures or *after* closure
  851. declaration.
  852. *)
  853. let used = all_vars e in
  854. PMap.iter (fun _ v -> v.v_capture <- true) used;
  855. e
  856. | Cs | Java ->
  857. let used = all_vars e in
  858. PMap.iter (fun _ v -> v.v_capture <- true) used;
  859. do_wrap used e
  860. | Cpp ->
  861. do_wrap (all_vars e) e
  862. | Flash8 | Flash ->
  863. let used = all_vars e in
  864. PMap.iter (fun _ v -> v.v_capture <- true) used;
  865. out_loop e
  866. | Js ->
  867. out_loop e
  868. (* -------------------------------------------------------------------------- *)
  869. (* RENAME LOCAL VARS *)
  870. let rename_local_vars com e =
  871. let as3 = Common.defined com "as3" || com.platform = Cs in (* C# demands a similar behavior than AS3 *)
  872. let no_scope = com.platform = Js || com.platform = Java || as3 in
  873. let vars = ref PMap.empty in
  874. let all_vars = ref PMap.empty in
  875. let vtemp = alloc_var "~" t_dynamic in
  876. let rebuild_vars = ref false in
  877. let rebuild m =
  878. PMap.fold (fun v acc -> PMap.add v.v_name v acc) m PMap.empty
  879. in
  880. let save() =
  881. let old = !vars in
  882. if as3 then (fun() -> ()) else (fun() -> vars := if !rebuild_vars then rebuild old else old)
  883. in
  884. let rename v =
  885. let count = ref 1 in
  886. while PMap.mem (v.v_name ^ string_of_int !count) (!vars) do
  887. incr count;
  888. done;
  889. v.v_name <- v.v_name ^ string_of_int !count;
  890. in
  891. let declare v =
  892. (* chop escape char for all local variables generated *)
  893. 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);
  894. (try
  895. let v2 = PMap.find v.v_name (!vars) in
  896. (*
  897. block_vars will create some wrapper-functions that are declaring
  898. the same variable twice. In that case do not perform a rename since
  899. we are sure it's actually the same variable
  900. *)
  901. if v == v2 then raise Not_found;
  902. rename v;
  903. with Not_found ->
  904. ());
  905. vars := PMap.add v.v_name v !vars;
  906. if no_scope then all_vars := PMap.add v.v_name v !all_vars;
  907. in
  908. let check t =
  909. match (t_infos t).mt_path with
  910. | [], name | name :: _, _ ->
  911. let vars = if no_scope then all_vars else vars in
  912. (try
  913. let v = PMap.find name !vars in
  914. if v == vtemp then raise Not_found; (* ignore *)
  915. rename v;
  916. rebuild_vars := true;
  917. vars := PMap.add v.v_name v !vars
  918. with Not_found ->
  919. ());
  920. vars := PMap.add name vtemp !vars
  921. in
  922. let check_type t =
  923. match follow t with
  924. | TInst (c,_) -> check (TClassDecl c)
  925. | TEnum (e,_) -> check (TEnumDecl e)
  926. | TType (t,_) -> check (TTypeDecl t)
  927. | TMono _ | TLazy _ | TAnon _ | TDynamic _ | TFun _ -> ()
  928. in
  929. let rec loop e =
  930. match e.eexpr with
  931. | TVars l ->
  932. List.iter (fun (v,e) ->
  933. if no_scope then declare v;
  934. (match e with None -> () | Some e -> loop e);
  935. if not no_scope then declare v;
  936. ) l
  937. | TFunction tf ->
  938. let old = save() in
  939. List.iter (fun (v,_) -> declare v) tf.tf_args;
  940. loop tf.tf_expr;
  941. old()
  942. | TBlock el ->
  943. let old = save() in
  944. List.iter loop el;
  945. old()
  946. | TFor (v,it,e) ->
  947. loop it;
  948. let old = save() in
  949. declare v;
  950. loop e;
  951. old()
  952. | TTry (e,catchs) ->
  953. loop e;
  954. List.iter (fun (v,e) ->
  955. let old = save() in
  956. declare v;
  957. check_type v.v_type;
  958. loop e;
  959. old()
  960. ) catchs;
  961. | TMatch (e,_,cases,def) ->
  962. loop e;
  963. List.iter (fun (_,vars,e) ->
  964. let old = save() in
  965. (match vars with
  966. | None -> ()
  967. | Some l -> List.iter (function None -> () | Some v -> declare v) l);
  968. loop e;
  969. old();
  970. ) cases;
  971. (match def with None -> () | Some e -> loop e);
  972. | TTypeExpr t ->
  973. check t
  974. | TEnumField (e,_) ->
  975. check (TEnumDecl e)
  976. | TNew (c,_,_) ->
  977. Type.iter loop e;
  978. check (TClassDecl c);
  979. | TCast (e,Some t) ->
  980. loop e;
  981. check t;
  982. | _ ->
  983. Type.iter loop e
  984. in
  985. loop e;
  986. e
  987. (* -------------------------------------------------------------------------- *)
  988. (* CHECK LOCAL VARS INIT *)
  989. let check_local_vars_init e =
  990. let intersect vl1 vl2 =
  991. PMap.mapi (fun v t -> t && PMap.find v vl2) vl1
  992. in
  993. let join vars cvars =
  994. List.iter (fun v -> vars := intersect !vars v) cvars
  995. in
  996. let restore vars old_vars declared =
  997. (* restore variables declared in this block to their previous state *)
  998. vars := List.fold_left (fun acc v ->
  999. try PMap.add v (PMap.find v old_vars) acc with Not_found -> PMap.remove v acc
  1000. ) !vars declared;
  1001. in
  1002. let declared = ref [] in
  1003. let rec loop vars e =
  1004. match e.eexpr with
  1005. | TLocal v ->
  1006. let init = (try PMap.find v.v_id !vars with Not_found -> true) in
  1007. if not init then error ("Local variable " ^ v.v_name ^ " used without being initialized") e.epos;
  1008. | TVars vl ->
  1009. List.iter (fun (v,eo) ->
  1010. match eo with
  1011. | None ->
  1012. declared := v.v_id :: !declared;
  1013. vars := PMap.add v.v_id false !vars
  1014. | Some e ->
  1015. loop vars e
  1016. ) vl
  1017. | TBlock el ->
  1018. let old = !declared in
  1019. let old_vars = !vars in
  1020. declared := [];
  1021. List.iter (loop vars) el;
  1022. restore vars old_vars (List.rev !declared);
  1023. declared := old;
  1024. | TBinop (OpAssign,{ eexpr = TLocal v },e) when PMap.mem v.v_id !vars ->
  1025. loop vars e;
  1026. vars := PMap.add v.v_id true !vars
  1027. | TIf (e1,e2,eo) ->
  1028. loop vars e1;
  1029. let vbase = !vars in
  1030. loop vars e2;
  1031. (match eo with
  1032. | None -> vars := vbase
  1033. | Some e ->
  1034. let v1 = !vars in
  1035. vars := vbase;
  1036. loop vars e;
  1037. vars := intersect !vars v1)
  1038. | TWhile (cond,e,flag) ->
  1039. (match flag with
  1040. | NormalWhile ->
  1041. loop vars cond;
  1042. let old = !vars in
  1043. loop vars e;
  1044. vars := old;
  1045. | DoWhile ->
  1046. loop vars e;
  1047. loop vars cond)
  1048. | TTry (e,catches) ->
  1049. let cvars = List.map (fun (v,e) ->
  1050. let old = !vars in
  1051. loop vars e;
  1052. let v = !vars in
  1053. vars := old;
  1054. v
  1055. ) catches in
  1056. loop vars e;
  1057. join vars cvars;
  1058. | TSwitch (e,cases,def) ->
  1059. loop vars e;
  1060. let cvars = List.map (fun (ec,e) ->
  1061. let old = !vars in
  1062. List.iter (loop vars) ec;
  1063. vars := old;
  1064. loop vars e;
  1065. let v = !vars in
  1066. vars := old;
  1067. v
  1068. ) cases in
  1069. (match def with
  1070. | None -> ()
  1071. | Some e ->
  1072. loop vars e;
  1073. join vars cvars)
  1074. | TMatch (e,_,cases,def) ->
  1075. loop vars e;
  1076. let old = !vars in
  1077. let cvars = List.map (fun (_,vl,e) ->
  1078. vars := old;
  1079. loop vars e;
  1080. restore vars old [];
  1081. !vars
  1082. ) cases in
  1083. (match def with None -> () | Some e -> vars := old; loop vars e);
  1084. join vars cvars
  1085. (* mark all reachable vars as initialized, since we don't exit the block *)
  1086. | TBreak | TContinue | TReturn None ->
  1087. vars := PMap.map (fun _ -> true) !vars
  1088. | TThrow e | TReturn (Some e) ->
  1089. loop vars e;
  1090. vars := PMap.map (fun _ -> true) !vars
  1091. | _ ->
  1092. Type.iter (loop vars) e
  1093. in
  1094. loop (ref PMap.empty) e;
  1095. e
  1096. (* -------------------------------------------------------------------------- *)
  1097. (* POST PROCESS *)
  1098. let pp_counter = ref 1
  1099. let post_process types filters =
  1100. (* ensure that we don't process twice the same (cached) module *)
  1101. List.iter (fun t ->
  1102. let m = (t_infos t).mt_module.m_extra in
  1103. if m.m_processed = 0 then m.m_processed <- !pp_counter;
  1104. if m.m_processed = !pp_counter then
  1105. match t with
  1106. | TClassDecl c ->
  1107. let process_field f =
  1108. match f.cf_expr with
  1109. | None -> ()
  1110. | Some e ->
  1111. f.cf_expr <- Some (List.fold_left (fun e f -> f e) e filters)
  1112. in
  1113. List.iter process_field c.cl_ordered_fields;
  1114. List.iter process_field c.cl_ordered_statics;
  1115. (match c.cl_constructor with
  1116. | None -> ()
  1117. | Some f -> process_field f);
  1118. (match c.cl_init with
  1119. | None -> ()
  1120. | Some e ->
  1121. c.cl_init <- Some (List.fold_left (fun e f -> f e) e filters));
  1122. | TEnumDecl _ -> ()
  1123. | TTypeDecl _ -> ()
  1124. ) types;
  1125. incr pp_counter
  1126. (* -------------------------------------------------------------------------- *)
  1127. (* STACK MANAGEMENT EMULATION *)
  1128. type stack_context = {
  1129. stack_var : string;
  1130. stack_exc_var : string;
  1131. stack_pos_var : string;
  1132. stack_pos : pos;
  1133. stack_expr : texpr;
  1134. stack_pop : texpr;
  1135. stack_save_pos : texpr;
  1136. stack_restore : texpr list;
  1137. stack_push : tclass -> string -> texpr;
  1138. stack_return : texpr -> texpr;
  1139. }
  1140. let stack_context_init com stack_var exc_var pos_var tmp_var use_add p =
  1141. let t = com.basic in
  1142. let st = t.tarray t.tstring in
  1143. let stack_var = alloc_var stack_var st in
  1144. let exc_var = alloc_var exc_var st in
  1145. let pos_var = alloc_var pos_var t.tint in
  1146. let stack_e = mk (TLocal stack_var) st p in
  1147. let exc_e = mk (TLocal exc_var) st p in
  1148. let stack_pop = fcall stack_e "pop" [] t.tstring p in
  1149. let stack_push c m =
  1150. fcall stack_e "push" [
  1151. if use_add then
  1152. binop OpAdd (string com (s_type_path c.cl_path ^ "::") p) (string com m p) t.tstring p
  1153. else
  1154. string com (s_type_path c.cl_path ^ "::" ^ m) p
  1155. ] t.tvoid p
  1156. in
  1157. let stack_return e =
  1158. let tmp = alloc_var tmp_var e.etype in
  1159. mk (TBlock [
  1160. mk (TVars [tmp, Some e]) t.tvoid e.epos;
  1161. stack_pop;
  1162. mk (TReturn (Some (mk (TLocal tmp) e.etype e.epos))) e.etype e.epos
  1163. ]) e.etype e.epos
  1164. in
  1165. {
  1166. stack_var = stack_var.v_name;
  1167. stack_exc_var = exc_var.v_name;
  1168. stack_pos_var = pos_var.v_name;
  1169. stack_pos = p;
  1170. stack_expr = stack_e;
  1171. stack_pop = stack_pop;
  1172. stack_save_pos = mk (TVars [pos_var, Some (field stack_e "length" t.tint p)]) t.tvoid p;
  1173. stack_push = stack_push;
  1174. stack_return = stack_return;
  1175. stack_restore = [
  1176. binop OpAssign exc_e (mk (TArrayDecl []) st p) st p;
  1177. mk (TWhile (
  1178. mk_parent (binop OpGte (field stack_e "length" t.tint p) (mk (TLocal pos_var) t.tint p) t.tbool p),
  1179. fcall exc_e "unshift" [fcall stack_e "pop" [] t.tstring p] t.tvoid p,
  1180. NormalWhile
  1181. )) t.tvoid p;
  1182. fcall stack_e "push" [index com exc_e 0 t.tstring p] t.tvoid p
  1183. ];
  1184. }
  1185. let stack_init com use_add =
  1186. stack_context_init com "$s" "$e" "$spos" "$tmp" use_add null_pos
  1187. let rec stack_block_loop ctx e =
  1188. match e.eexpr with
  1189. | TFunction _ ->
  1190. e
  1191. | TReturn None | TReturn (Some { eexpr = TConst _ }) | TReturn (Some { eexpr = TLocal _ }) ->
  1192. mk (TBlock [
  1193. ctx.stack_pop;
  1194. e;
  1195. ]) e.etype e.epos
  1196. | TReturn (Some e) ->
  1197. ctx.stack_return (stack_block_loop ctx e)
  1198. | TTry (v,cases) ->
  1199. let v = stack_block_loop ctx v in
  1200. let cases = List.map (fun (v,e) ->
  1201. let e = stack_block_loop ctx e in
  1202. let e = (match (mk_block e).eexpr with
  1203. | TBlock l -> mk (TBlock (ctx.stack_restore @ l)) e.etype e.epos
  1204. | _ -> assert false
  1205. ) in
  1206. v , e
  1207. ) cases in
  1208. mk (TTry (v,cases)) e.etype e.epos
  1209. | _ ->
  1210. map_expr (stack_block_loop ctx) e
  1211. let stack_block ctx c m e =
  1212. match (mk_block e).eexpr with
  1213. | TBlock l ->
  1214. mk (TBlock (
  1215. ctx.stack_push c m ::
  1216. ctx.stack_save_pos ::
  1217. List.map (stack_block_loop ctx) l
  1218. @ [ctx.stack_pop]
  1219. )) e.etype e.epos
  1220. | _ ->
  1221. assert false
  1222. (* -------------------------------------------------------------------------- *)
  1223. (* FIX OVERRIDES *)
  1224. (*
  1225. on some platforms which doesn't support type parameters, we must have the
  1226. exact same type for overriden/implemented function as the original one
  1227. *)
  1228. let rec find_field c f =
  1229. try
  1230. (match c.cl_super with
  1231. | None ->
  1232. raise Not_found
  1233. | Some (c,_) ->
  1234. find_field c f)
  1235. with Not_found -> try
  1236. let rec loop = function
  1237. | [] ->
  1238. raise Not_found
  1239. | (c,_) :: l ->
  1240. try
  1241. find_field c f
  1242. with
  1243. Not_found -> loop l
  1244. in
  1245. loop c.cl_implements
  1246. with Not_found ->
  1247. let f = PMap.find f.cf_name c.cl_fields in
  1248. (match f.cf_kind with Var { v_read = AccRequire _ } -> raise Not_found | _ -> ());
  1249. f
  1250. let fix_override com c f fd =
  1251. c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  1252. let f2 = (try Some (find_field c f) with Not_found -> None) in
  1253. let f = (match f2,fd with
  1254. | Some (f2), Some(fd) ->
  1255. let targs, tret = (match follow f2.cf_type with TFun (args,ret) -> args, ret | _ -> assert false) in
  1256. let changed_args = ref [] in
  1257. let prefix = "_tmp_" in
  1258. let nargs = List.map2 (fun ((v,c) as cur) (_,_,t2) ->
  1259. try
  1260. type_eq EqStrict v.v_type t2;
  1261. cur
  1262. with Unify_error _ ->
  1263. let v2 = alloc_var (prefix ^ v.v_name) t2 in
  1264. changed_args := (v,v2) :: !changed_args;
  1265. v2,c
  1266. ) fd.tf_args targs in
  1267. let fd2 = {
  1268. tf_args = nargs;
  1269. tf_type = tret;
  1270. tf_expr = (match List.rev !changed_args with
  1271. | [] -> fd.tf_expr
  1272. | args ->
  1273. let e = fd.tf_expr in
  1274. let el = (match e.eexpr with TBlock el -> el | _ -> [e]) in
  1275. let p = (match el with [] -> e.epos | e :: _ -> e.epos) in
  1276. let v = mk (TVars (List.map (fun (v,v2) ->
  1277. (v,Some (mk (TCast (mk (TLocal v2) v2.v_type p,None)) v.v_type p))
  1278. ) args)) com.basic.tvoid p in
  1279. { e with eexpr = TBlock (v :: el) }
  1280. );
  1281. } in
  1282. let targs = List.map (fun(v,c) -> (v.v_name, Option.is_some c, v.v_type)) nargs in
  1283. let fde = (match f.cf_expr with None -> assert false | Some e -> e) in
  1284. { f with cf_expr = Some { fde with eexpr = TFunction fd2 }; cf_type = TFun(targs,tret) }
  1285. | Some(f2), None when c.cl_interface ->
  1286. let targs, tret = (match follow f2.cf_type with TFun (args,ret) -> args, ret | _ -> assert false) in
  1287. { f with cf_type = TFun(targs,tret) }
  1288. | _ ->
  1289. f
  1290. ) in
  1291. c.cl_fields <- PMap.add f.cf_name f c.cl_fields;
  1292. f
  1293. let fix_overrides com t =
  1294. match t with
  1295. | TClassDecl c ->
  1296. c.cl_ordered_fields <- List.map (fun f ->
  1297. match f.cf_expr, f.cf_kind with
  1298. | Some { eexpr = TFunction fd }, Method (MethNormal | MethInline) ->
  1299. fix_override com c f (Some fd)
  1300. | None, Method (MethNormal | MethInline) when c.cl_interface ->
  1301. fix_override com c f None
  1302. | _ ->
  1303. f
  1304. ) c.cl_ordered_fields
  1305. | _ ->
  1306. ()
  1307. (*
  1308. PHP does not allow abstract classes extending other abstract classes to override any fields, so these duplicates
  1309. must be removed from the child interface
  1310. *)
  1311. let fix_abstract_inheritance com t =
  1312. match t with
  1313. | TClassDecl c when c.cl_interface ->
  1314. c.cl_ordered_fields <- List.filter (fun f ->
  1315. let b = try (find_field c f) == f
  1316. with Not_found -> false in
  1317. if not b then c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  1318. b;
  1319. ) c.cl_ordered_fields
  1320. | _ -> ()
  1321. (* -------------------------------------------------------------------------- *)
  1322. (* MISC FEATURES *)
  1323. let rec is_volatile t =
  1324. match t with
  1325. | TMono r ->
  1326. (match !r with
  1327. | Some t -> is_volatile t
  1328. | _ -> false)
  1329. | TLazy f ->
  1330. is_volatile (!f())
  1331. | TType (t,tl) ->
  1332. (match t.t_path with
  1333. | ["mt";"flash"],"Volatile" -> true
  1334. | _ -> is_volatile (apply_params t.t_types tl t.t_type))
  1335. | _ ->
  1336. false
  1337. let set_default ctx a c p =
  1338. let t = a.v_type in
  1339. let ve = mk (TLocal a) t p in
  1340. let cond = TBinop (OpEq,ve,mk (TConst TNull) t p) in
  1341. 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
  1342. let bytes_serialize data =
  1343. let b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%:" in
  1344. let tbl = Array.init (String.length b64) (fun i -> String.get b64 i) in
  1345. let str = Base64.str_encode ~tbl data in
  1346. "s" ^ string_of_int (String.length str) ^ ":" ^ str
  1347. (*
  1348. Tells if the constructor might be called without any issue whatever its parameters
  1349. *)
  1350. let rec constructor_side_effects e =
  1351. match e.eexpr with
  1352. | TBinop (op,_,_) when op <> OpAssign ->
  1353. true
  1354. | TUnop _ | TArray _ | TField _ | TCall _ | TNew _ | TFor _ | TWhile _ | TSwitch _ | TMatch _ | TReturn _ | TThrow _ | TClosure _ ->
  1355. true
  1356. | TBinop _ | TTry _ | TIf _ | TBlock _ | TVars _
  1357. | TFunction _ | TArrayDecl _ | TObjectDecl _
  1358. | TParenthesis _ | TTypeExpr _ | TEnumField _ | TLocal _
  1359. | TConst _ | TContinue | TBreak | TCast _ ->
  1360. try
  1361. Type.iter (fun e -> if constructor_side_effects e then raise Exit) e;
  1362. false;
  1363. with Exit ->
  1364. true
  1365. (*
  1366. Make a dump of the full typed AST of all types
  1367. *)
  1368. let dump_types com =
  1369. let s_type = s_type (Type.print_context()) in
  1370. let params = function [] -> "" | l -> Printf.sprintf "<%s>" (String.concat "," (List.map (fun (n,t) -> n ^ " : " ^ s_type t) l)) in
  1371. let rec create acc = function
  1372. | [] -> ()
  1373. | d :: l ->
  1374. let dir = String.concat "/" (List.rev (d :: acc)) in
  1375. if not (Sys.file_exists dir) then Unix.mkdir dir 0o755;
  1376. create (d :: acc) l
  1377. in
  1378. List.iter (fun mt ->
  1379. let path = Type.t_path mt in
  1380. let dir = "dump" :: fst path in
  1381. create [] dir;
  1382. let ch = open_out (String.concat "/" dir ^ "/" ^ snd path ^ ".dump") in
  1383. let buf = Buffer.create 0 in
  1384. let print fmt = Printf.kprintf (fun s -> Buffer.add_string buf s) fmt in
  1385. (match mt with
  1386. | Type.TClassDecl c ->
  1387. let print_field stat f =
  1388. 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);
  1389. print "(%s) : %s" (s_kind f.cf_kind) (s_type f.cf_type);
  1390. (match f.cf_expr with
  1391. | None -> ()
  1392. | Some e -> print "\n\n\t = %s" (Type.s_expr s_type e));
  1393. print ";\n\n";
  1394. in
  1395. 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);
  1396. (match c.cl_super with None -> () | Some (c,pl) -> print " extends %s" (s_type (TInst (c,pl))));
  1397. List.iter (fun (c,pl) -> print " implements %s" (s_type (TInst (c,pl)))) c.cl_implements;
  1398. (match c.cl_dynamic with None -> () | Some t -> print " implements Dynamic<%s>" (s_type t));
  1399. (match c.cl_array_access with None -> () | Some t -> print " implements ArrayAccess<%s>" (s_type t));
  1400. print "{\n";
  1401. (match c.cl_constructor with
  1402. | None -> ()
  1403. | Some f -> print_field false f);
  1404. List.iter (print_field false) c.cl_ordered_fields;
  1405. List.iter (print_field true) c.cl_ordered_statics;
  1406. print "}";
  1407. | Type.TEnumDecl e ->
  1408. 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);
  1409. List.iter (fun n ->
  1410. let f = PMap.find n e.e_constrs in
  1411. print "\t%s : %s;\n" f.ef_name (s_type f.ef_type);
  1412. ) e.e_names;
  1413. print "}"
  1414. | Type.TTypeDecl t ->
  1415. 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);
  1416. );
  1417. output_string ch (Buffer.contents buf);
  1418. close_out ch
  1419. ) com.types
  1420. (*
  1421. Build a default safe-cast expression :
  1422. { var $t = <e>; if( Std.is($t,<t>) ) $t else throw "Class cast error"; }
  1423. *)
  1424. let default_cast ?(vtmp="$t") com e texpr t p =
  1425. let api = com.basic in
  1426. let mk_texpr = function
  1427. | TClassDecl c -> TAnon { a_fields = PMap.empty; a_status = ref (Statics c) }
  1428. | TEnumDecl e -> TAnon { a_fields = PMap.empty; a_status = ref (EnumStatics e) }
  1429. | TTypeDecl _ -> assert false
  1430. in
  1431. let vtmp = alloc_var vtmp e.etype in
  1432. let var = mk (TVars [vtmp,Some e]) api.tvoid p in
  1433. let vexpr = mk (TLocal vtmp) e.etype p in
  1434. let texpr = mk (TTypeExpr texpr) (mk_texpr texpr) p in
  1435. let std = (try List.find (fun t -> t_path t = ([],"Std")) com.types with Not_found -> assert false) in
  1436. let std = mk (TTypeExpr std) (mk_texpr std) p in
  1437. let is = mk (TField (std,"is")) (tfun [t_dynamic;t_dynamic] api.tbool) p in
  1438. let is = mk (TCall (is,[vexpr;texpr])) api.tbool p in
  1439. let exc = mk (TThrow (mk (TConst (TString "Class cast error")) api.tstring p)) t p in
  1440. let check = mk (TIf (mk_parent is,mk (TCast (vexpr,None)) t p,Some exc)) t p in
  1441. mk (TBlock [var;check;vexpr]) t p