codegen.ml 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296
  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 } -> ("get_" ^ f.cf_name , "get_" ^ f.cf_name) :: acc
  86. | _ -> acc) in
  87. match f.cf_kind with
  88. | Var { v_write = AccCall } -> ("set_" ^ f.cf_name , "set_" ^ f.cf_name) :: 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 =
  245. match e.eexpr with
  246. | TField(e1, FInstance({cl_kind = KGeneric},cf)) ->
  247. build_expr {e with eexpr = TField(e1,quick_field_dynamic (generic_substitute_type gctx (e1.etype)) cf.cf_name)}
  248. | _ -> map_expr_type build_expr (generic_substitute_type gctx) build_var e
  249. in
  250. build_expr e
  251. let has_ctor_constraint c = match c.cl_kind with
  252. | KTypeParameter tl ->
  253. List.exists (fun t -> match follow t with
  254. | TAnon a when PMap.mem "new" a.a_fields -> true
  255. | _ -> false
  256. ) tl;
  257. | _ -> false
  258. let rec build_generic ctx c p tl =
  259. let pack = fst c.cl_path in
  260. let recurse = ref false in
  261. let rec check_recursive t =
  262. match follow t with
  263. | TInst (c2,tl) ->
  264. (match c2.cl_kind with
  265. | KTypeParameter tl ->
  266. if not (Typeload.is_generic_parameter ctx c2) && has_ctor_constraint c2 then
  267. error "Type parameters with a constructor cannot be used non-generically" p;
  268. recurse := true
  269. | _ -> ());
  270. List.iter check_recursive tl;
  271. | _ ->
  272. ()
  273. in
  274. List.iter check_recursive tl;
  275. let gctx = try make_generic ctx c.cl_types tl p with Generic_Exception (msg,p) -> error msg p in
  276. let name = (snd c.cl_path) ^ "_" ^ gctx.name in
  277. if !recurse then begin
  278. TInst (c,tl) (* build a normal instance *)
  279. end else try
  280. Typeload.load_instance ctx { tpackage = pack; tname = name; tparams = []; tsub = None } p false
  281. with Error(Module_not_found path,_) when path = (pack,name) ->
  282. let m = (try Hashtbl.find ctx.g.modules (Hashtbl.find ctx.g.types_module c.cl_path) with Not_found -> assert false) in
  283. let ctx = { ctx with m = { ctx.m with module_types = m.m_types @ ctx.m.module_types } } in
  284. c.cl_build(); (* make sure the super class is already setup *)
  285. let mg = {
  286. m_id = alloc_mid();
  287. m_path = (pack,name);
  288. m_types = [];
  289. m_extra = module_extra (s_type_path (pack,name)) m.m_extra.m_sign 0. MFake;
  290. } in
  291. gctx.mg <- Some mg;
  292. let cg = mk_class mg (pack,name) c.cl_pos in
  293. mg.m_types <- [TClassDecl cg];
  294. Hashtbl.add ctx.g.modules mg.m_path mg;
  295. add_dependency mg m;
  296. add_dependency ctx.m.curmod mg;
  297. (* ensure that type parameters are set in dependencies *)
  298. let dep_stack = ref [] in
  299. let rec loop t =
  300. if not (List.memq t !dep_stack) then begin
  301. dep_stack := t :: !dep_stack;
  302. match t with
  303. | TInst (c,tl) -> add_dep c.cl_module tl
  304. | TEnum (e,tl) -> add_dep e.e_module tl
  305. | TType (t,tl) -> add_dep t.t_module tl
  306. | TAbstract (a,tl) -> add_dep a.a_module tl
  307. | TMono r ->
  308. (match !r with
  309. | None -> ()
  310. | Some t -> loop t)
  311. | TLazy f ->
  312. loop ((!f)());
  313. | TDynamic t2 ->
  314. if t == t2 then () else loop t2
  315. | TAnon a ->
  316. PMap.iter (fun _ f -> loop f.cf_type) a.a_fields
  317. | TFun (args,ret) ->
  318. List.iter (fun (_,_,t) -> loop t) args;
  319. loop ret
  320. end
  321. and add_dep m tl =
  322. add_dependency mg m;
  323. List.iter loop tl
  324. in
  325. List.iter loop tl;
  326. let delays = ref [] in
  327. let build_field f =
  328. let t = generic_substitute_type gctx f.cf_type in
  329. let f = { f with cf_type = t} in
  330. (* delay the expression mapping to make sure all cf_type fields are set correctly first *)
  331. (delays := (fun () ->
  332. try (match f.cf_expr with None -> () | Some e -> f.cf_expr <- Some (generic_substitute_expr gctx e))
  333. with Unify_error l -> error (error_msg (Unify l)) f.cf_pos) :: !delays);
  334. f
  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. let find_class subst =
  342. let rec loop subst = match subst with
  343. | (TInst(c,[]),t) :: subst when c == cs -> t
  344. | _ :: subst -> loop subst
  345. | [] -> raise Not_found
  346. in
  347. try
  348. if pl <> [] then raise Not_found;
  349. let t = loop subst in
  350. (* extended type parameter: concrete type must have a constructor, but generic base class must not have one *)
  351. begin match follow t,c.cl_constructor with
  352. | TInst({cl_constructor = None} as cs,_),None -> error ("Cannot use " ^ (s_type_path cs.cl_path) ^ " as type parameter because it is extended and has no constructor") p
  353. | _,Some cf -> error "Generics extending type parameters cannot have constructors" cf.cf_pos
  354. | _ -> ()
  355. end;
  356. t
  357. with Not_found ->
  358. apply_params c.cl_types tl (TInst(cs,pl))
  359. in
  360. let ts = follow (find_class gctx.subst) in
  361. let cs,pl = Typeload.check_extends ctx c ts p in
  362. match cs.cl_kind with
  363. | KGeneric ->
  364. (match build_generic ctx cs p pl with
  365. | TInst (cs,pl) -> Some (cs,pl)
  366. | _ -> assert false)
  367. | _ -> Some(cs,pl)
  368. );
  369. Typeload.add_constructor ctx cg p;
  370. cg.cl_kind <- KGenericInstance (c,tl);
  371. cg.cl_interface <- c.cl_interface;
  372. cg.cl_constructor <- (match cg.cl_constructor, c.cl_constructor, c.cl_super with
  373. | Some ctor, _, _ -> Some ctor
  374. | None, None, None -> None
  375. | None, Some c, _ -> Some (build_field c)
  376. | _ -> error "Please define a constructor for this class in order to use it as generic" c.cl_pos
  377. );
  378. cg.cl_implements <- List.map (fun (i,tl) ->
  379. (match follow (generic_substitute_type gctx (TInst (i, List.map (generic_substitute_type gctx) tl))) with
  380. | TInst (i,tl) -> i, tl
  381. | _ -> assert false)
  382. ) c.cl_implements;
  383. cg.cl_ordered_fields <- List.map (fun f ->
  384. let f = build_field f in
  385. cg.cl_fields <- PMap.add f.cf_name f cg.cl_fields;
  386. f
  387. ) c.cl_ordered_fields;
  388. List.iter (fun f -> f()) !delays;
  389. TInst (cg,[])
  390. (* -------------------------------------------------------------------------- *)
  391. (* HAXE.XML.PROXY *)
  392. let extend_xml_proxy ctx c t file p =
  393. let t = Typeload.load_complex_type ctx p t in
  394. let file = (try Common.find_file ctx.com file with Not_found -> file) in
  395. add_dependency c.cl_module (create_fake_module ctx file);
  396. let used = ref PMap.empty in
  397. let print_results() =
  398. PMap.iter (fun id used ->
  399. if not used then ctx.com.warning (id ^ " is not used") p;
  400. ) (!used)
  401. in
  402. let check_used = Common.defined ctx.com Define.CheckXmlProxy in
  403. if check_used then ctx.g.hook_generate <- print_results :: ctx.g.hook_generate;
  404. try
  405. let rec loop = function
  406. | Xml.Element (_,attrs,childs) ->
  407. (try
  408. let id = List.assoc "id" attrs in
  409. if PMap.mem id c.cl_fields then error ("Duplicate id " ^ id) p;
  410. let t = if not check_used then t else begin
  411. used := PMap.add id false (!used);
  412. let ft() = used := PMap.add id true (!used); t in
  413. TLazy (ref ft)
  414. end in
  415. let f = {
  416. cf_name = id;
  417. cf_type = t;
  418. cf_public = true;
  419. cf_pos = p;
  420. cf_doc = None;
  421. cf_meta = no_meta;
  422. cf_kind = Var { v_read = AccResolve; v_write = AccNo };
  423. cf_params = [];
  424. cf_expr = None;
  425. cf_overloads = [];
  426. } in
  427. c.cl_fields <- PMap.add id f c.cl_fields;
  428. with
  429. Not_found -> ());
  430. List.iter loop childs;
  431. | Xml.PCData _ -> ()
  432. in
  433. loop (Xml.parse_file file)
  434. with
  435. | Xml.Error e -> error ("XML error " ^ Xml.error e) p
  436. | Xml.File_not_found f -> error ("XML File not found : " ^ f) p
  437. (* -------------------------------------------------------------------------- *)
  438. (* BUILD META DATA OBJECT *)
  439. let build_metadata com t =
  440. let api = com.basic in
  441. let p, meta, fields, statics = (match t with
  442. | TClassDecl c ->
  443. 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
  444. let statics = List.map (fun f -> f.cf_name,f.cf_meta) c.cl_ordered_statics in
  445. (c.cl_pos, ["",c.cl_meta],fields,statics)
  446. | TEnumDecl e ->
  447. (e.e_pos, ["",e.e_meta],List.map (fun n -> n, (PMap.find n e.e_constrs).ef_meta) e.e_names, [])
  448. | TTypeDecl t ->
  449. (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 [] | _ -> []),[])
  450. | TAbstractDecl a ->
  451. (a.a_pos, ["",a.a_meta],[],[])
  452. ) in
  453. let filter l =
  454. 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
  455. List.filter (fun (_,ml) -> ml <> []) l
  456. in
  457. let meta, fields, statics = filter meta, filter fields, filter statics in
  458. let make_meta_field ml =
  459. let h = Hashtbl.create 0 in
  460. mk (TObjectDecl (List.map (fun (f,el,p) ->
  461. if Hashtbl.mem h f then error ("Duplicate metadata '" ^ f ^ "'") p;
  462. Hashtbl.add h f ();
  463. f, mk (match el with [] -> TConst TNull | _ -> TArrayDecl (List.map (type_constant_value com) el)) (api.tarray t_dynamic) p
  464. ) ml)) (api.tarray t_dynamic) p
  465. in
  466. let make_meta l =
  467. mk (TObjectDecl (List.map (fun (f,ml) -> f,make_meta_field ml) l)) t_dynamic p
  468. in
  469. if meta = [] && fields = [] && statics = [] then
  470. None
  471. else
  472. let meta_obj = [] in
  473. let meta_obj = (if fields = [] then meta_obj else ("fields",make_meta fields) :: meta_obj) in
  474. let meta_obj = (if statics = [] then meta_obj else ("statics",make_meta statics) :: meta_obj) in
  475. let meta_obj = (try ("obj", make_meta_field (List.assoc "" meta)) :: meta_obj with Not_found -> meta_obj) in
  476. Some (mk (TObjectDecl meta_obj) t_dynamic p)
  477. (* -------------------------------------------------------------------------- *)
  478. (* MACRO TYPE *)
  479. let build_macro_type ctx pl p =
  480. let path, field, args = (match pl with
  481. | [TInst ({ cl_kind = KExpr (ECall (e,args),_) },_)]
  482. | [TInst ({ cl_kind = KExpr (EArrayDecl [ECall (e,args),_],_) },_)] ->
  483. let rec loop e =
  484. match fst e with
  485. | EField (e,f) -> f :: loop e
  486. | EConst (Ident i) -> [i]
  487. | _ -> error "Invalid macro call" p
  488. in
  489. (match loop e with
  490. | meth :: cl :: path -> (List.rev path,cl), meth, args
  491. | _ -> error "Invalid macro call" p)
  492. | _ ->
  493. error "MacroType require a single expression call parameter" p
  494. ) in
  495. let old = ctx.ret in
  496. let t = (match ctx.g.do_macro ctx MMacroType path field args p with
  497. | None -> mk_mono()
  498. | Some _ -> ctx.ret
  499. ) in
  500. ctx.ret <- old;
  501. t
  502. (* -------------------------------------------------------------------------- *)
  503. (* API EVENTS *)
  504. let build_instance ctx mtype p =
  505. match mtype with
  506. | TClassDecl c ->
  507. if ctx.pass > PBuildClass then c.cl_build();
  508. let ft = (fun pl ->
  509. match c.cl_kind with
  510. | KGeneric ->
  511. let r = exc_protect ctx (fun r ->
  512. let t = mk_mono() in
  513. r := (fun() -> t);
  514. unify_raise ctx (build_generic ctx c p pl) t p;
  515. t
  516. ) "build_generic" in
  517. delay ctx PForce (fun() -> ignore ((!r)()));
  518. TLazy r
  519. | KMacroType ->
  520. let r = exc_protect ctx (fun r ->
  521. let t = mk_mono() in
  522. r := (fun() -> t);
  523. unify_raise ctx (build_macro_type ctx pl p) t p;
  524. t
  525. ) "macro_type" in
  526. delay ctx PForce (fun() -> ignore ((!r)()));
  527. TLazy r
  528. | _ ->
  529. TInst (c,pl)
  530. ) in
  531. c.cl_types , c.cl_path , ft
  532. | TEnumDecl e ->
  533. e.e_types , e.e_path , (fun t -> TEnum (e,t))
  534. | TTypeDecl t ->
  535. t.t_types , t.t_path , (fun tl -> TType(t,tl))
  536. | TAbstractDecl a ->
  537. a.a_types, a.a_path, (fun tl -> TAbstract(a,tl))
  538. let on_inherit ctx c p h =
  539. match h with
  540. | HExtends { tpackage = ["haxe";"remoting"]; tname = "Proxy"; tparams = [TPType(CTPath t)] } ->
  541. extend_remoting ctx c t p false true;
  542. false
  543. | HExtends { tpackage = ["haxe";"remoting"]; tname = "AsyncProxy"; tparams = [TPType(CTPath t)] } ->
  544. extend_remoting ctx c t p true true;
  545. false
  546. | HExtends { tpackage = ["mt"]; tname = "AsyncProxy"; tparams = [TPType(CTPath t)] } ->
  547. extend_remoting ctx c t p true false;
  548. false
  549. | HExtends { tpackage = ["haxe";"xml"]; tname = "Proxy"; tparams = [TPExpr(EConst (String file),p);TPType t] } ->
  550. extend_xml_proxy ctx c t file p;
  551. true
  552. | _ ->
  553. true
  554. (* -------------------------------------------------------------------------- *)
  555. (* FINAL GENERATION *)
  556. (* Saves a class state so it can be restored later, e.g. after DCE or native path rewrite *)
  557. let save_class_state ctx t = match t with
  558. | TClassDecl c ->
  559. let meta = c.cl_meta and path = c.cl_path and ext = c.cl_extern in
  560. let fl = c.cl_fields and ofl = c.cl_ordered_fields and st = c.cl_statics and ost = c.cl_ordered_statics in
  561. let cst = c.cl_constructor and over = c.cl_overrides in
  562. let oflk = List.map (fun f -> f.cf_kind,f.cf_expr,f.cf_type) ofl in
  563. let ostk = List.map (fun f -> f.cf_kind,f.cf_expr,f.cf_type) ost in
  564. c.cl_restore <- (fun() ->
  565. c.cl_meta <- meta;
  566. c.cl_extern <- ext;
  567. c.cl_path <- path;
  568. c.cl_fields <- fl;
  569. c.cl_ordered_fields <- ofl;
  570. c.cl_statics <- st;
  571. c.cl_ordered_statics <- ost;
  572. c.cl_constructor <- cst;
  573. c.cl_overrides <- over;
  574. (* DCE might modify the cf_kind, so let's restore it as well *)
  575. List.iter2 (fun f (k,e,t) -> f.cf_kind <- k; f.cf_expr <- e; f.cf_type <- t;) ofl oflk;
  576. List.iter2 (fun f (k,e,t) -> f.cf_kind <- k; f.cf_expr <- e; f.cf_type <- t;) ost ostk;
  577. )
  578. | _ ->
  579. ()
  580. (* Checks if a private class' path clashes with another path *)
  581. let check_private_path ctx t = match t with
  582. | TClassDecl c when c.cl_private ->
  583. let rpath = (fst c.cl_module.m_path,"_" ^ snd c.cl_module.m_path) in
  584. if Hashtbl.mem ctx.g.types_module rpath then error ("This private class name will clash with " ^ s_type_path rpath) c.cl_pos;
  585. | _ ->
  586. ()
  587. (* Removes generic base classes *)
  588. let is_removable_class c = c.cl_kind = KGeneric && (has_ctor_constraint c || Meta.has Meta.Remove c.cl_meta)
  589. let remove_generic_base ctx t = match t with
  590. | TClassDecl c when is_removable_class c ->
  591. c.cl_extern <- true
  592. | _ ->
  593. ()
  594. (* Rewrites class or enum paths if @:native metadata is set *)
  595. let apply_native_paths ctx t =
  596. let get_real_path meta path =
  597. let (_,e,mp) = Meta.get Meta.Native meta in
  598. match e with
  599. | [Ast.EConst (Ast.String name),p] ->
  600. (Meta.RealPath,[Ast.EConst (Ast.String (s_type_path path)),p],mp),parse_path name
  601. | _ ->
  602. error "String expected" mp
  603. in
  604. try
  605. (match t with
  606. | TClassDecl c ->
  607. let meta,path = get_real_path c.cl_meta c.cl_path in
  608. c.cl_meta <- meta :: c.cl_meta;
  609. c.cl_path <- path;
  610. | TEnumDecl e ->
  611. let meta,path = get_real_path e.e_meta e.e_path in
  612. e.e_meta <- meta :: e.e_meta;
  613. e.e_path <- path;
  614. | TAbstractDecl a ->
  615. let meta,path = get_real_path a.a_meta a.a_path in
  616. a.a_meta <- meta :: a.a_meta;
  617. a.a_path <- path;
  618. | _ ->
  619. ())
  620. with Not_found ->
  621. ()
  622. (* Adds the __rtti field if required *)
  623. let add_rtti ctx t =
  624. let rec has_rtti c =
  625. Meta.has Meta.Rtti c.cl_meta || match c.cl_super with None -> false | Some (csup,_) -> has_rtti csup
  626. in
  627. match t with
  628. | TClassDecl c when has_rtti c && not (PMap.mem "__rtti" c.cl_statics) ->
  629. let f = mk_field "__rtti" ctx.t.tstring c.cl_pos in
  630. let str = Genxml.gen_type_string ctx.com t in
  631. f.cf_expr <- Some (mk (TConst (TString str)) f.cf_type c.cl_pos);
  632. c.cl_ordered_statics <- f :: c.cl_ordered_statics;
  633. c.cl_statics <- PMap.add f.cf_name f c.cl_statics;
  634. | _ ->
  635. ()
  636. (* Removes extern and macro fields, also checks for Void fields *)
  637. let is_removable_field ctx f =
  638. Meta.has Meta.Extern f.cf_meta || Meta.has Meta.Generic f.cf_meta
  639. || (match f.cf_kind with
  640. | Var {v_read = AccRequire (s,_)} -> true
  641. | Method MethMacro -> not ctx.in_macro
  642. | _ -> false)
  643. let remove_extern_fields ctx t = match t with
  644. | TClassDecl c ->
  645. if not (Common.defined ctx.com Define.DocGen) then begin
  646. c.cl_ordered_fields <- List.filter (fun f ->
  647. let b = is_removable_field ctx f in
  648. if b then c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  649. not b
  650. ) c.cl_ordered_fields;
  651. c.cl_ordered_statics <- List.filter (fun f ->
  652. let b = is_removable_field ctx f in
  653. if b then c.cl_statics <- PMap.remove f.cf_name c.cl_statics;
  654. not b
  655. ) c.cl_ordered_statics;
  656. end
  657. | _ ->
  658. ()
  659. (* Adds member field initializations as assignments to the constructor *)
  660. let add_field_inits ctx t =
  661. let apply c =
  662. let ethis = mk (TConst TThis) (TInst (c,List.map snd c.cl_types)) c.cl_pos in
  663. (* TODO: we have to find a variable name which is not used in any of the functions *)
  664. let v = alloc_var "_g" ethis.etype in
  665. let need_this = ref false in
  666. let inits,fields = List.fold_left (fun (inits,fields) cf ->
  667. match cf.cf_kind,cf.cf_expr with
  668. | Var _, Some _ ->
  669. if ctx.com.config.pf_can_init_member cf then (inits, cf :: fields) else (cf :: inits, cf :: fields)
  670. | Method MethDynamic, Some e when Common.defined ctx.com Define.As3 ->
  671. (* TODO : this would have a better place in genSWF9 I think - NC *)
  672. (* we move the initialization of dynamic functions to the constructor and also solve the
  673. 'this' problem along the way *)
  674. let rec use_this v e = match e.eexpr with
  675. | TConst TThis ->
  676. need_this := true;
  677. mk (TLocal v) v.v_type e.epos
  678. | _ -> Type.map_expr (use_this v) e
  679. in
  680. let e = Type.map_expr (use_this v) e in
  681. let cf2 = {cf with cf_expr = Some e} in
  682. (* if the method is an override, we have to remove the class field to not get invalid overrides *)
  683. let fields = if List.memq cf c.cl_overrides then begin
  684. c.cl_fields <- PMap.remove cf.cf_name c.cl_fields;
  685. fields
  686. end else
  687. cf2 :: fields
  688. in
  689. (cf2 :: inits, fields)
  690. | _ -> (inits, cf :: fields)
  691. ) ([],[]) c.cl_ordered_fields in
  692. c.cl_ordered_fields <- (List.rev fields);
  693. match inits with
  694. | [] -> ()
  695. | _ ->
  696. let el = List.map (fun cf ->
  697. match cf.cf_expr with
  698. | None -> assert false
  699. | Some e ->
  700. let lhs = mk (TField(ethis,FInstance (c,cf))) cf.cf_type e.epos in
  701. cf.cf_expr <- None;
  702. let eassign = mk (TBinop(OpAssign,lhs,e)) e.etype e.epos in
  703. if Common.defined ctx.com Define.As3 then begin
  704. let echeck = mk (TBinop(OpEq,lhs,(mk (TConst TNull) lhs.etype e.epos))) ctx.com.basic.tbool e.epos in
  705. mk (TIf(echeck,eassign,None)) eassign.etype e.epos
  706. end else
  707. eassign;
  708. ) inits in
  709. let el = if !need_this then (mk (TVars([v, Some ethis])) ethis.etype ethis.epos) :: el else el in
  710. match c.cl_constructor with
  711. | None ->
  712. let ct = TFun([],ctx.com.basic.tvoid) in
  713. let ce = mk (TFunction {
  714. tf_args = [];
  715. tf_type = ctx.com.basic.tvoid;
  716. tf_expr = mk (TBlock el) ctx.com.basic.tvoid c.cl_pos;
  717. }) ct c.cl_pos in
  718. let ctor = mk_field "new" ct c.cl_pos in
  719. ctor.cf_kind <- Method MethNormal;
  720. c.cl_constructor <- Some { ctor with cf_expr = Some ce };
  721. | Some cf ->
  722. match cf.cf_expr with
  723. | Some { eexpr = TFunction f } ->
  724. let bl = match f.tf_expr with {eexpr = TBlock b } -> b | x -> [x] in
  725. 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
  726. c.cl_constructor <- Some {cf with cf_expr = Some ce }
  727. | _ ->
  728. assert false
  729. in
  730. match t with
  731. | TClassDecl c ->
  732. apply c
  733. | _ ->
  734. ()
  735. (* Adds the __meta__ field if required *)
  736. let add_meta_field ctx t = match t with
  737. | TClassDecl c ->
  738. (match build_metadata ctx.com t with
  739. | None -> ()
  740. | Some e ->
  741. let f = mk_field "__meta__" t_dynamic c.cl_pos in
  742. f.cf_expr <- Some e;
  743. c.cl_ordered_statics <- f :: c.cl_ordered_statics;
  744. c.cl_statics <- PMap.add f.cf_name f c.cl_statics)
  745. | _ ->
  746. ()
  747. (* Removes interfaces tagged with @:remove metadata *)
  748. let check_remove_metadata ctx t = match t with
  749. | TClassDecl c ->
  750. c.cl_implements <- List.filter (fun (c,_) -> not (Meta.has Meta.Remove c.cl_meta)) c.cl_implements;
  751. | _ ->
  752. ()
  753. (* Checks for Void class fields *)
  754. let check_void_field ctx t = match t with
  755. | TClassDecl c ->
  756. let check f =
  757. match follow f.cf_type with TAbstract({a_path=[],"Void"},_) -> error "Fields of type Void are not allowed" f.cf_pos | _ -> ();
  758. in
  759. List.iter check c.cl_ordered_fields;
  760. List.iter check c.cl_ordered_statics;
  761. | _ ->
  762. ()
  763. (* Promotes type parameters of abstracts to their implementation fields *)
  764. let promote_abstract_parameters ctx t = match t with
  765. | TClassDecl ({cl_kind = KAbstractImpl a} as c) when a.a_types <> [] ->
  766. List.iter (fun f ->
  767. List.iter (fun (n,t) -> match t with
  768. | TInst({cl_kind = KTypeParameter _; cl_path=p,n} as cp,[]) when not (List.mem_assoc n f.cf_params) ->
  769. let path = List.rev ((snd c.cl_path) :: List.rev (fst c.cl_path)),n in
  770. f.cf_params <- (n,TInst({cp with cl_path = path},[])) :: f.cf_params
  771. | _ ->
  772. ()
  773. ) a.a_types;
  774. ) c.cl_ordered_statics;
  775. | _ ->
  776. ()
  777. (*
  778. Pushes complex right-hand side expression inwards.
  779. return { exprs; value; } -> { exprs; return value; }
  780. x = { exprs; value; } -> { exprs; x = value; }
  781. var x = { exprs; value; } -> { var x; exprs; x = value; }
  782. *)
  783. let promote_complex_rhs ctx e =
  784. let rec is_complex e = match e.eexpr with
  785. | TBlock _ | TSwitch _ | TIf _ | TTry _ -> true
  786. | TBinop(_,e1,e2) -> is_complex e1 || is_complex e2
  787. | TParenthesis e | TMeta(_,e) -> is_complex e
  788. | _ -> false
  789. in
  790. let rec loop f e = match e.eexpr with
  791. | TBlock(el) ->
  792. begin match List.rev el with
  793. | elast :: el -> {e with eexpr = TBlock(block (List.rev ((loop f elast) :: el)))}
  794. | [] -> e
  795. end
  796. | TSwitch(es,cases,edef) ->
  797. {e with eexpr = TSwitch(es,List.map (fun (el,e) -> List.map find el,loop f e) cases,match edef with None -> None | Some e -> Some (loop f e))}
  798. | TIf(eif,ethen,eelse) ->
  799. {e with eexpr = TIf(find eif, loop f ethen, match eelse with None -> None | Some e -> Some (loop f e))}
  800. | TTry(e1,el) ->
  801. {e with eexpr = TTry(loop f e1, List.map (fun (el,e) -> el,loop f e) el)}
  802. | TParenthesis e1 when not (Common.defined ctx Define.As3) ->
  803. {e with eexpr = TParenthesis(loop f e1)}
  804. | TMeta(m,e1) ->
  805. { e with eexpr = TMeta(m,loop f e1)}
  806. | TReturn _ | TThrow _ ->
  807. find e
  808. | TCast(e1,None) when ctx.config.pf_ignore_unsafe_cast ->
  809. loop f e1
  810. | _ ->
  811. f (find e)
  812. and block el =
  813. let r = ref [] in
  814. List.iter (fun e ->
  815. match e.eexpr with
  816. | TVars(vl) ->
  817. List.iter (fun (v,eo) ->
  818. match eo with
  819. | Some e when is_complex e ->
  820. r := (loop (fun e -> mk (TBinop(OpAssign,mk (TLocal v) v.v_type e.epos,e)) v.v_type e.epos) e)
  821. :: ((mk (TVars [v,None]) ctx.basic.tvoid e.epos))
  822. :: !r
  823. | Some e ->
  824. r := (mk (TVars [v,Some (find e)]) ctx.basic.tvoid e.epos) :: !r
  825. | None -> r := (mk (TVars [v,None]) ctx.basic.tvoid e.epos) :: !r
  826. ) vl
  827. | _ -> r := (find e) :: !r
  828. ) el;
  829. List.rev !r
  830. and find e = match e.eexpr with
  831. | TReturn (Some e1) -> loop (fun e -> {e with eexpr = TReturn (Some e)}) e1
  832. | TBinop(OpAssign, ({eexpr = TLocal _ | TField _ | TArray _} as e1), e2) -> loop (fun er -> {e with eexpr = TBinop(OpAssign, e1, er)}) e2
  833. | TBlock(el) -> {e with eexpr = TBlock (block el)}
  834. | _ -> Type.map_expr find e
  835. in
  836. find e
  837. (* -------------------------------------------------------------------------- *)
  838. (* LOCAL VARIABLES USAGE *)
  839. type usage =
  840. | Block of ((usage -> unit) -> unit)
  841. | Loop of ((usage -> unit) -> unit)
  842. | Function of ((usage -> unit) -> unit)
  843. | Declare of tvar
  844. | Use of tvar
  845. let rec local_usage f e =
  846. match e.eexpr with
  847. | TLocal v ->
  848. f (Use v)
  849. | TVars l ->
  850. List.iter (fun (v,e) ->
  851. (match e with None -> () | Some e -> local_usage f e);
  852. f (Declare v);
  853. ) l
  854. | TFunction tf ->
  855. let cc f =
  856. List.iter (fun (v,_) -> f (Declare v)) tf.tf_args;
  857. local_usage f tf.tf_expr;
  858. in
  859. f (Function cc)
  860. | TBlock l ->
  861. f (Block (fun f -> List.iter (local_usage f) l))
  862. | TFor (v,it,e) ->
  863. local_usage f it;
  864. f (Loop (fun f ->
  865. f (Declare v);
  866. local_usage f e;
  867. ))
  868. | TWhile _ ->
  869. f (Loop (fun f ->
  870. iter (local_usage f) e
  871. ))
  872. | TTry (e,catchs) ->
  873. local_usage f e;
  874. List.iter (fun (v,e) ->
  875. f (Block (fun f ->
  876. f (Declare v);
  877. local_usage f e;
  878. ))
  879. ) catchs;
  880. | TPatMatch dt ->
  881. List.iter (fun (v,eo) ->
  882. f (Declare v);
  883. match eo with None -> () | Some e -> local_usage f e
  884. ) dt.dt_var_init;
  885. let rec fdt dt = match dt with
  886. | DTBind(bl,dt) ->
  887. List.iter (fun ((v,_),e) ->
  888. f (Declare v);
  889. local_usage f e
  890. ) bl;
  891. fdt dt
  892. | DTExpr e -> local_usage f e
  893. | DTGuard(e,dt1,dt2) ->
  894. local_usage f e;
  895. fdt dt1;
  896. (match dt2 with None -> () | Some dt -> fdt dt)
  897. | DTSwitch(e,cl,dto) ->
  898. local_usage f e;
  899. List.iter (fun (e,dt) ->
  900. local_usage f e;
  901. fdt dt
  902. ) cl;
  903. (match dto with None -> () | Some dt -> fdt dt)
  904. | DTGoto _ -> ()
  905. in
  906. Array.iter fdt dt.dt_dt_lookup
  907. | _ ->
  908. iter (local_usage f) e
  909. (* -------------------------------------------------------------------------- *)
  910. (* BLOCK VARIABLES CAPTURE *)
  911. (*
  912. For some platforms, it will simply mark the variables which are used in closures
  913. using the v_capture flag so it can be processed in a more optimized
  914. For Flash/JS platforms, it will ensure that variables used in loop sub-functions
  915. have an unique scope. It transforms the following expression :
  916. for( x in array )
  917. funs.push(function() return x++);
  918. Into the following :
  919. for( _x in array ) {
  920. var x = [_x];
  921. funs.push(function(x) { function() return x[0]++; }(x));
  922. }
  923. *)
  924. let captured_vars com e =
  925. let t = com.basic in
  926. let rec mk_init av v pos =
  927. mk (TVars [av,Some (mk (TArrayDecl [mk (TLocal v) v.v_type pos]) av.v_type pos)]) t.tvoid pos
  928. and mk_var v used =
  929. alloc_var v.v_name (PMap.find v.v_id used)
  930. and wrap used e =
  931. match e.eexpr with
  932. | TVars vl ->
  933. let vl = List.map (fun (v,ve) ->
  934. if PMap.mem v.v_id used then
  935. v, Some (mk (TArrayDecl (match ve with None -> [] | Some e -> [wrap used e])) v.v_type e.epos)
  936. else
  937. v, (match ve with None -> None | Some e -> Some (wrap used e))
  938. ) vl in
  939. { e with eexpr = TVars vl }
  940. | TLocal v when PMap.mem v.v_id used ->
  941. mk (TArray ({ e with etype = v.v_type },mk (TConst (TInt 0l)) t.tint e.epos)) e.etype e.epos
  942. | TFor (v,it,expr) when PMap.mem v.v_id used ->
  943. let vtmp = mk_var v used in
  944. let it = wrap used it in
  945. let expr = wrap used expr in
  946. mk (TFor (vtmp,it,concat (mk_init v vtmp e.epos) expr)) e.etype e.epos
  947. | TTry (expr,catchs) ->
  948. let catchs = List.map (fun (v,e) ->
  949. let e = wrap used e in
  950. try
  951. let vtmp = mk_var v used in
  952. vtmp, concat (mk_init v vtmp e.epos) e
  953. with Not_found ->
  954. v, e
  955. ) catchs in
  956. mk (TTry (wrap used expr,catchs)) e.etype e.epos
  957. (* TODO: find out this does *)
  958. (* | TMatch (expr,enum,cases,def) ->
  959. let cases = List.map (fun (il,vars,e) ->
  960. let pos = e.epos in
  961. let e = ref (wrap used e) in
  962. let vars = match vars with
  963. | None -> None
  964. | Some l ->
  965. Some (List.map (fun v ->
  966. match v with
  967. | Some v when PMap.mem v.v_id used ->
  968. let vtmp = mk_var v used in
  969. e := concat (mk_init v vtmp pos) !e;
  970. Some vtmp
  971. | _ -> v
  972. ) l)
  973. in
  974. il, vars, !e
  975. ) cases in
  976. let def = match def with None -> None | Some e -> Some (wrap used e) in
  977. mk (TMatch (wrap used expr,enum,cases,def)) e.etype e.epos *)
  978. | TFunction f ->
  979. (*
  980. list variables that are marked as used, but also used in that
  981. function and which are not declared inside it !
  982. *)
  983. let fused = ref PMap.empty in
  984. let tmp_used = ref used in
  985. let rec browse = function
  986. | Block f | Loop f | Function f -> f browse
  987. | Use v ->
  988. if PMap.mem v.v_id !tmp_used then fused := PMap.add v.v_id v !fused;
  989. | Declare v ->
  990. tmp_used := PMap.remove v.v_id !tmp_used
  991. in
  992. local_usage browse e;
  993. let vars = PMap.fold (fun v acc -> v :: acc) !fused [] in
  994. (* in case the variable has been marked as used in a parallel scope... *)
  995. let fexpr = ref (wrap used f.tf_expr) in
  996. let fargs = List.map (fun (v,o) ->
  997. if PMap.mem v.v_id used then
  998. let vtmp = mk_var v used in
  999. fexpr := concat (mk_init v vtmp e.epos) !fexpr;
  1000. vtmp, o
  1001. else
  1002. v, o
  1003. ) f.tf_args in
  1004. let e = { e with eexpr = TFunction { f with tf_args = fargs; tf_expr = !fexpr } } in
  1005. (*
  1006. Create a new function scope to make sure that the captured loop variable
  1007. will not be overwritten in next loop iteration
  1008. *)
  1009. if com.config.pf_capture_policy = CPLoopVars then
  1010. mk (TCall (
  1011. mk_parent (mk (TFunction {
  1012. tf_args = List.map (fun v -> v, None) vars;
  1013. tf_type = e.etype;
  1014. tf_expr = mk_block (mk (TReturn (Some e)) e.etype e.epos);
  1015. }) (TFun (List.map (fun v -> v.v_name,false,v.v_type) vars,e.etype)) e.epos),
  1016. List.map (fun v -> mk (TLocal v) v.v_type e.epos) vars)
  1017. ) e.etype e.epos
  1018. else
  1019. e
  1020. | _ ->
  1021. map_expr (wrap used) e
  1022. and do_wrap used e =
  1023. if PMap.is_empty used then
  1024. e
  1025. else
  1026. let used = PMap.map (fun v ->
  1027. let vt = v.v_type in
  1028. v.v_type <- t.tarray vt;
  1029. v.v_capture <- true;
  1030. vt
  1031. ) used in
  1032. wrap used e
  1033. and out_loop e =
  1034. match e.eexpr with
  1035. | TFor _ | TWhile _ ->
  1036. (*
  1037. collect variables that are declared in loop but used in subfunctions
  1038. *)
  1039. let vars = ref PMap.empty in
  1040. let used = ref PMap.empty in
  1041. let depth = ref 0 in
  1042. let rec collect_vars in_loop = function
  1043. | Block f ->
  1044. let old = !vars in
  1045. f (collect_vars in_loop);
  1046. vars := old;
  1047. | Loop f ->
  1048. let old = !vars in
  1049. f (collect_vars true);
  1050. vars := old;
  1051. | Function f ->
  1052. incr depth;
  1053. f (collect_vars false);
  1054. decr depth;
  1055. | Declare v ->
  1056. if in_loop then vars := PMap.add v.v_id !depth !vars;
  1057. | Use v ->
  1058. try
  1059. let d = PMap.find v.v_id !vars in
  1060. if d <> !depth then used := PMap.add v.v_id v !used;
  1061. with Not_found ->
  1062. ()
  1063. in
  1064. local_usage (collect_vars false) e;
  1065. do_wrap !used e
  1066. | _ ->
  1067. map_expr out_loop e
  1068. and all_vars e =
  1069. let vars = ref PMap.empty in
  1070. let used = ref PMap.empty in
  1071. let depth = ref 0 in
  1072. let rec collect_vars = function
  1073. | Block f ->
  1074. let old = !vars in
  1075. f collect_vars;
  1076. vars := old;
  1077. | Loop f ->
  1078. let old = !vars in
  1079. f collect_vars;
  1080. vars := old;
  1081. | Function f ->
  1082. incr depth;
  1083. f collect_vars;
  1084. decr depth;
  1085. | Declare v ->
  1086. vars := PMap.add v.v_id !depth !vars;
  1087. | Use v ->
  1088. try
  1089. let d = PMap.find v.v_id !vars in
  1090. if d <> !depth then used := PMap.add v.v_id v !used;
  1091. with Not_found -> ()
  1092. in
  1093. local_usage collect_vars e;
  1094. !used
  1095. in
  1096. (* mark all capture variables - also used in rename_local_vars at later stage *)
  1097. let captured = all_vars e in
  1098. PMap.iter (fun _ v -> v.v_capture <- true) captured;
  1099. match com.config.pf_capture_policy with
  1100. | CPNone -> e
  1101. | CPWrapRef -> do_wrap captured e
  1102. | CPLoopVars -> out_loop e
  1103. (* -------------------------------------------------------------------------- *)
  1104. (* RENAME LOCAL VARS *)
  1105. let rename_local_vars com e =
  1106. let cfg = com.config in
  1107. let all_scope = (not cfg.pf_captured_scope) || (not cfg.pf_locals_scope) in
  1108. let vars = ref PMap.empty in
  1109. let all_vars = ref PMap.empty in
  1110. let vtemp = alloc_var "~" t_dynamic in
  1111. let rebuild_vars = ref false in
  1112. let rebuild m =
  1113. PMap.fold (fun v acc -> PMap.add v.v_name v acc) m PMap.empty
  1114. in
  1115. let save() =
  1116. let old = !vars in
  1117. if cfg.pf_unique_locals then (fun() -> ()) else (fun() -> vars := if !rebuild_vars then rebuild old else old)
  1118. in
  1119. let rename vars v =
  1120. let count = ref 1 in
  1121. while PMap.mem (v.v_name ^ string_of_int !count) vars do
  1122. incr count;
  1123. done;
  1124. v.v_name <- v.v_name ^ string_of_int !count;
  1125. in
  1126. let declare v p =
  1127. (match follow v.v_type with
  1128. | TAbstract ({a_path = [],"Void"},_) -> error "Arguments and variables of type Void are not allowed" p
  1129. | _ -> ());
  1130. (* chop escape char for all local variables generated *)
  1131. 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);
  1132. let look_vars = (if not cfg.pf_captured_scope && v.v_capture then !all_vars else !vars) in
  1133. (try
  1134. let v2 = PMap.find v.v_name look_vars in
  1135. (*
  1136. block_vars will create some wrapper-functions that are declaring
  1137. the same variable twice. In that case do not perform a rename since
  1138. we are sure it's actually the same variable
  1139. *)
  1140. if v == v2 then raise Not_found;
  1141. rename look_vars v;
  1142. with Not_found ->
  1143. ());
  1144. vars := PMap.add v.v_name v !vars;
  1145. if all_scope then all_vars := PMap.add v.v_name v !all_vars;
  1146. in
  1147. (*
  1148. This is quite a rare case, when a local variable would otherwise prevent
  1149. accessing a type because it masks the type value or the package name.
  1150. *)
  1151. let check t =
  1152. match (t_infos t).mt_path with
  1153. | [], name | name :: _, _ ->
  1154. let vars = if cfg.pf_locals_scope then vars else all_vars in
  1155. (try
  1156. let v = PMap.find name !vars in
  1157. if v == vtemp then raise Not_found; (* ignore *)
  1158. rename (!vars) v;
  1159. rebuild_vars := true;
  1160. vars := PMap.add v.v_name v !vars
  1161. with Not_found ->
  1162. ());
  1163. vars := PMap.add name vtemp !vars
  1164. in
  1165. let check_type t =
  1166. match follow t with
  1167. | TInst (c,_) -> check (TClassDecl c)
  1168. | TEnum (e,_) -> check (TEnumDecl e)
  1169. | TType (t,_) -> check (TTypeDecl t)
  1170. | TAbstract (a,_) -> check (TAbstractDecl a)
  1171. | TMono _ | TLazy _ | TAnon _ | TDynamic _ | TFun _ -> ()
  1172. in
  1173. let rec loop e =
  1174. match e.eexpr with
  1175. | TVars l ->
  1176. List.iter (fun (v,eo) ->
  1177. if not cfg.pf_locals_scope then declare v e.epos;
  1178. (match eo with None -> () | Some e -> loop e);
  1179. if cfg.pf_locals_scope then declare v e.epos;
  1180. ) l
  1181. | TFunction tf ->
  1182. let old = save() in
  1183. List.iter (fun (v,_) -> declare v e.epos) tf.tf_args;
  1184. loop tf.tf_expr;
  1185. old()
  1186. | TBlock el ->
  1187. let old = save() in
  1188. List.iter loop el;
  1189. old()
  1190. | TFor (v,it,e1) ->
  1191. loop it;
  1192. let old = save() in
  1193. declare v e.epos;
  1194. loop e1;
  1195. old()
  1196. | TTry (e,catchs) ->
  1197. loop e;
  1198. List.iter (fun (v,e) ->
  1199. let old = save() in
  1200. declare v e.epos;
  1201. check_type v.v_type;
  1202. loop e;
  1203. old()
  1204. ) catchs;
  1205. | TPatMatch dt ->
  1206. let rec fdt dt = match dt with
  1207. | DTSwitch(e,cl,dto) ->
  1208. loop e;
  1209. List.iter (fun (_,dt) ->
  1210. let old = save() in
  1211. fdt dt;
  1212. old();
  1213. ) cl;
  1214. (match dto with None -> () | Some dt ->
  1215. let old = save() in
  1216. fdt dt;
  1217. old())
  1218. | DTBind(bl,dt) ->
  1219. List.iter (fun ((v,p),e) ->
  1220. declare v e.epos
  1221. ) bl;
  1222. fdt dt
  1223. | DTExpr e -> loop e;
  1224. | DTGuard(e,dt1,dt2) ->
  1225. loop e;
  1226. fdt dt1;
  1227. (match dt2 with None -> () | Some dt -> fdt dt)
  1228. | DTGoto _ ->
  1229. ()
  1230. in
  1231. Array.iter fdt dt.dt_dt_lookup
  1232. | TTypeExpr t ->
  1233. check t
  1234. | TNew (c,_,_) ->
  1235. Type.iter loop e;
  1236. check (TClassDecl c);
  1237. | TCast (e,Some t) ->
  1238. loop e;
  1239. check t;
  1240. | _ ->
  1241. Type.iter loop e
  1242. in
  1243. declare (alloc_var "this" t_dynamic) Ast.null_pos; (* force renaming of 'this' vars in abstract *)
  1244. loop e;
  1245. e
  1246. (* -------------------------------------------------------------------------- *)
  1247. (* CHECK LOCAL VARS INIT *)
  1248. let check_local_vars_init e =
  1249. let intersect vl1 vl2 =
  1250. PMap.mapi (fun v t -> t && PMap.find v vl2) vl1
  1251. in
  1252. let join vars cvars =
  1253. List.iter (fun v -> vars := intersect !vars v) cvars
  1254. in
  1255. let restore vars old_vars declared =
  1256. (* restore variables declared in this block to their previous state *)
  1257. vars := List.fold_left (fun acc v ->
  1258. try PMap.add v (PMap.find v old_vars) acc with Not_found -> PMap.remove v acc
  1259. ) !vars declared;
  1260. in
  1261. let declared = ref [] in
  1262. let rec loop vars e =
  1263. match e.eexpr with
  1264. | TLocal v ->
  1265. let init = (try PMap.find v.v_id !vars with Not_found -> true) in
  1266. if not init then begin
  1267. if v.v_name = "this" then error "Missing this = value" e.epos
  1268. else error ("Local variable " ^ v.v_name ^ " used without being initialized") e.epos
  1269. end
  1270. | TVars vl ->
  1271. List.iter (fun (v,eo) ->
  1272. match eo with
  1273. | None ->
  1274. declared := v.v_id :: !declared;
  1275. vars := PMap.add v.v_id false !vars
  1276. | Some e ->
  1277. loop vars e
  1278. ) vl
  1279. | TBlock el ->
  1280. let old = !declared in
  1281. let old_vars = !vars in
  1282. declared := [];
  1283. List.iter (loop vars) el;
  1284. restore vars old_vars (List.rev !declared);
  1285. declared := old;
  1286. | TBinop (OpAssign,{ eexpr = TLocal v },e) when PMap.mem v.v_id !vars ->
  1287. loop vars e;
  1288. vars := PMap.add v.v_id true !vars
  1289. | TIf (e1,e2,eo) ->
  1290. loop vars e1;
  1291. let vbase = !vars in
  1292. loop vars e2;
  1293. (match eo with
  1294. | None -> vars := vbase
  1295. | Some e ->
  1296. let v1 = !vars in
  1297. vars := vbase;
  1298. loop vars e;
  1299. vars := intersect !vars v1)
  1300. | TWhile (cond,e,flag) ->
  1301. (match flag with
  1302. | NormalWhile ->
  1303. loop vars cond;
  1304. let old = !vars in
  1305. loop vars e;
  1306. vars := old;
  1307. | DoWhile ->
  1308. loop vars e;
  1309. loop vars cond)
  1310. | TTry (e,catches) ->
  1311. let cvars = List.map (fun (v,e) ->
  1312. let old = !vars in
  1313. loop vars e;
  1314. let v = !vars in
  1315. vars := old;
  1316. v
  1317. ) catches in
  1318. loop vars e;
  1319. join vars cvars;
  1320. | TSwitch (e,cases,def) ->
  1321. loop vars e;
  1322. let cvars = List.map (fun (ec,e) ->
  1323. let old = !vars in
  1324. List.iter (loop vars) ec;
  1325. vars := old;
  1326. loop vars e;
  1327. let v = !vars in
  1328. vars := old;
  1329. v
  1330. ) cases in
  1331. (match def with
  1332. | None when (match e.eexpr with TMeta((Meta.Exhaustive,_,_),_) | TParenthesis({eexpr = TMeta((Meta.Exhaustive,_,_),_)}) -> true | _ -> false) ->
  1333. (match cvars with
  1334. | cv :: cvars ->
  1335. PMap.iter (fun i b -> if b then vars := PMap.add i b !vars) cv;
  1336. join vars cvars
  1337. | [] -> ())
  1338. | None -> ()
  1339. | Some e ->
  1340. loop vars e;
  1341. join vars cvars)
  1342. | TPatMatch dt ->
  1343. let cvars = ref [] in
  1344. let rec fdt dt = match dt with
  1345. | DTExpr e ->
  1346. let old = !vars in
  1347. loop vars e;
  1348. restore vars old [];
  1349. cvars := !vars :: !cvars
  1350. | DTSwitch(e,cl,dto) ->
  1351. loop vars e;
  1352. List.iter (fun (_,dt) -> fdt dt) cl;
  1353. (match dto with None -> () | Some dt -> fdt dt)
  1354. | DTGuard(e,dt1,dt2) ->
  1355. fdt dt1;
  1356. (match dt2 with None -> () | Some dt -> fdt dt)
  1357. | DTBind(_,dt) -> fdt dt
  1358. | DTGoto _ -> ()
  1359. in
  1360. Array.iter fdt dt.dt_dt_lookup;
  1361. join vars !cvars
  1362. (* mark all reachable vars as initialized, since we don't exit the block *)
  1363. | TBreak | TContinue | TReturn None ->
  1364. vars := PMap.map (fun _ -> true) !vars
  1365. | TThrow e | TReturn (Some e) ->
  1366. loop vars e;
  1367. vars := PMap.map (fun _ -> true) !vars
  1368. | _ ->
  1369. Type.iter (loop vars) e
  1370. in
  1371. loop (ref PMap.empty) e;
  1372. e
  1373. (* -------------------------------------------------------------------------- *)
  1374. (* ABSTRACT CASTS *)
  1375. module Abstract = struct
  1376. let find_to ab pl b = List.find (Type.unify_to_field ab pl b) ab.a_to
  1377. let find_from ab pl a b = List.find (Type.unify_from_field ab pl a b) ab.a_from
  1378. let cast_stack = ref []
  1379. let get_underlying_type a pl =
  1380. try
  1381. if not (Meta.has Meta.MultiType a.a_meta) then raise Not_found;
  1382. let m = mk_mono() in
  1383. let _ = find_to a pl m in
  1384. follow m
  1385. with Not_found ->
  1386. apply_params a.a_types pl a.a_this
  1387. let make_static_call ctx c cf a pl args t p =
  1388. let ta = TAnon { a_fields = c.cl_statics; a_status = ref (Statics c) } in
  1389. let ethis = mk (TTypeExpr (TClassDecl c)) ta p in
  1390. let monos = List.map (fun _ -> mk_mono()) cf.cf_params in
  1391. let map t = apply_params a.a_types pl (apply_params cf.cf_params monos t) in
  1392. let ef = mk (TField (ethis,(FStatic (c,cf)))) (map cf.cf_type) p in
  1393. make_call ctx ef args (map t) p
  1394. let rec do_check_cast ctx tleft eright p =
  1395. let tright = follow eright.etype in
  1396. let tleft = follow tleft in
  1397. if tleft == tright then eright else
  1398. let recurse cf f =
  1399. if cf == ctx.curfield || List.mem cf !cast_stack then error "Recursive implicit cast" p;
  1400. cast_stack := cf :: !cast_stack;
  1401. let r = f() in
  1402. cast_stack := List.tl !cast_stack;
  1403. r
  1404. in
  1405. try (match tright,tleft with
  1406. | (TAbstract({a_impl = Some c1} as a1,pl1) as t1),(TAbstract({a_impl = Some c2} as a2,pl2) as t2) ->
  1407. if a1 == a2 then
  1408. eright
  1409. else begin
  1410. let c,cfo,a,pl = try
  1411. if Meta.has Meta.MultiType a1.a_meta then raise Not_found;
  1412. c1,snd (find_to a1 pl1 t2),a1,pl1
  1413. with Not_found ->
  1414. if Meta.has Meta.MultiType a2.a_meta then raise Not_found;
  1415. c2,snd (find_from a2 pl2 t1 t2),a2,pl2
  1416. in
  1417. match cfo with
  1418. | None -> eright
  1419. | Some cf ->
  1420. recurse cf (fun () -> make_static_call ctx c cf a pl [eright] tleft p)
  1421. end
  1422. | TDynamic _,_ | _,TDynamic _ | _, TMono _ | TMono _, _ ->
  1423. eright
  1424. | TAbstract({a_impl = Some c} as a,pl),t2 when not (Meta.has Meta.MultiType a.a_meta) ->
  1425. begin match find_to a pl t2 with
  1426. | tcf,None ->
  1427. let tcf = apply_params a.a_types pl tcf in
  1428. if type_iseq tcf tleft then eright else do_check_cast ctx tcf eright p
  1429. | _,Some cf ->
  1430. recurse cf (fun () -> make_static_call ctx c cf a pl [eright] tleft p)
  1431. end
  1432. | t1,(TAbstract({a_impl = Some c} as a,pl) as t2) when not (Meta.has Meta.MultiType a.a_meta) ->
  1433. begin match find_from a pl t1 t2 with
  1434. | tcf,None ->
  1435. let tcf = apply_params a.a_types pl tcf in
  1436. if type_iseq tcf tleft then eright else do_check_cast ctx tcf eright p
  1437. | _,Some cf ->
  1438. recurse cf (fun () -> make_static_call ctx c cf a pl [eright] tleft p)
  1439. end
  1440. | _ ->
  1441. eright)
  1442. with Not_found ->
  1443. eright
  1444. let check_cast ctx tleft eright p =
  1445. if ctx.com.display then eright else do_check_cast ctx tleft eright p
  1446. let find_multitype_specialization a pl p =
  1447. let m = mk_mono() in
  1448. let at = apply_params a.a_types pl a.a_this in
  1449. let _,cfo =
  1450. try find_to a pl m
  1451. with Not_found ->
  1452. let st = s_type (print_context()) at in
  1453. if has_mono at then
  1454. error ("Type parameters of multi type abstracts must be known (for " ^ st ^ ")") p
  1455. else
  1456. error ("Abstract " ^ (s_type_path a.a_path) ^ " has no @:to function that accepts " ^ st) p;
  1457. in
  1458. match cfo with
  1459. | None -> assert false
  1460. | Some cf -> cf, follow m
  1461. let handle_abstract_casts ctx e =
  1462. let rec loop ctx e = match e.eexpr with
  1463. | TNew({cl_kind = KAbstractImpl a} as c,pl,el) ->
  1464. (* a TNew of an abstract implementation is only generated if it is a multi type abstract *)
  1465. let cf,m = find_multitype_specialization a pl e.epos in
  1466. let e = make_static_call ctx c cf a pl ((mk (TConst TNull) (TAbstract(a,pl)) e.epos) :: el) m e.epos in
  1467. {e with etype = m}
  1468. | TCall(e1, el) ->
  1469. begin try
  1470. begin match e1.eexpr with
  1471. | TField(e2,fa) ->
  1472. begin match follow e2.etype with
  1473. | TAbstract(a,pl) when Meta.has Meta.MultiType a.a_meta ->
  1474. let m = get_underlying_type a pl in
  1475. let fname = field_name fa in
  1476. let el = List.map (loop ctx) el in
  1477. begin try
  1478. let ef = mk (TField({e2 with etype = m},quick_field m fname)) e1.etype e2.epos in
  1479. make_call ctx ef el e.etype e.epos
  1480. with Not_found ->
  1481. (* quick_field raises Not_found if m is an abstract, we have to replicate the 'using' call here *)
  1482. match follow m with
  1483. | TAbstract({a_impl = Some c} as a,pl) ->
  1484. let cf = PMap.find fname c.cl_statics in
  1485. make_static_call ctx c cf a pl (e2 :: el) e.etype e.epos
  1486. | _ -> raise Not_found
  1487. end
  1488. | _ -> raise Not_found
  1489. end
  1490. | _ ->
  1491. raise Not_found
  1492. end
  1493. with Not_found ->
  1494. Type.map_expr (loop ctx) e
  1495. end
  1496. | _ ->
  1497. Type.map_expr (loop ctx) e
  1498. in
  1499. loop ctx e
  1500. end
  1501. module PatternMatchConversion = struct
  1502. type cctx = {
  1503. ctx : typer;
  1504. mutable eval_stack : ((tvar * pos) * texpr) list list;
  1505. dt_lookup : dt array;
  1506. }
  1507. let is_declared cctx v =
  1508. let rec loop sl = match sl with
  1509. | stack :: sl ->
  1510. List.exists (fun ((v2,_),_) -> v == v2) stack || loop sl
  1511. | [] ->
  1512. false
  1513. in
  1514. loop cctx.eval_stack
  1515. let group_cases cases =
  1516. let dt_eq dt1 dt2 = match dt1,dt2 with
  1517. | DTGoto i1, DTGoto i2 when i1 = i2 -> true
  1518. (* TODO equal bindings *)
  1519. | _ -> false
  1520. in
  1521. match List.rev cases with
  1522. | [] -> []
  1523. | [con,dt] -> [[con],dt]
  1524. | (con,dt) :: cases ->
  1525. let tmp,ldt,cases = List.fold_left (fun (tmp,ldt,acc) (con,dt) ->
  1526. if dt_eq dt ldt then
  1527. (con :: tmp,dt,acc)
  1528. else
  1529. ([con],dt,(tmp,ldt) :: acc)
  1530. ) ([con],dt,[]) cases in
  1531. match tmp with
  1532. | [] -> cases
  1533. | tmp -> ((tmp,ldt) :: cases)
  1534. let rec convert_dt cctx dt =
  1535. match dt with
  1536. | DTBind (bl,dt) ->
  1537. cctx.eval_stack <- bl :: cctx.eval_stack;
  1538. let e = convert_dt cctx dt in
  1539. cctx.eval_stack <- List.tl cctx.eval_stack;
  1540. let vl,el = List.fold_left (fun (vl,el) ((v,p),e) ->
  1541. if is_declared cctx v then
  1542. vl, (mk (TBinop(OpAssign,mk (TLocal v) v.v_type p,e)) e.etype e.epos) :: el
  1543. else
  1544. ((v,Some e) :: vl), el
  1545. ) ([],[e]) bl in
  1546. mk (TBlock
  1547. ((mk (TVars (vl)) cctx.ctx.t.tvoid e.epos)
  1548. :: el)
  1549. ) e.etype e.epos
  1550. | DTGoto i ->
  1551. convert_dt cctx (cctx.dt_lookup.(i))
  1552. | DTExpr e ->
  1553. e
  1554. | DTGuard(e,dt1,dt2) ->
  1555. let ethen = convert_dt cctx dt1 in
  1556. mk (TIf(e,ethen,match dt2 with None -> None | Some dt -> Some (convert_dt cctx dt))) ethen.etype (punion e.epos ethen.epos)
  1557. | DTSwitch({eexpr = TMeta((Meta.Exhaustive,_,_),_)},[_,dt],None) ->
  1558. convert_dt cctx dt
  1559. | DTSwitch(e_st,cl,dto) ->
  1560. let def = match dto with None -> None | Some dt -> Some (convert_dt cctx dt) in
  1561. let cases = group_cases cl in
  1562. let cases = List.map (fun (cl,dt) -> cl,convert_dt cctx dt) cases in
  1563. mk (TSwitch(e_st,cases,def)) (mk_mono()) e_st.epos
  1564. let to_typed_ast ctx dt p =
  1565. let first = dt.dt_dt_lookup.(dt.dt_first) in
  1566. let cctx = {
  1567. ctx = ctx;
  1568. dt_lookup = dt.dt_dt_lookup;
  1569. eval_stack = [];
  1570. } in
  1571. let e = convert_dt cctx first in
  1572. let e = { e with epos = p; etype = dt.dt_type} in
  1573. if dt.dt_var_init = [] then
  1574. e
  1575. else begin
  1576. mk (TBlock [
  1577. mk (TVars dt.dt_var_init) t_dynamic e.epos;
  1578. e;
  1579. ]) dt.dt_type e.epos
  1580. end
  1581. end
  1582. (* -------------------------------------------------------------------------- *)
  1583. (* USAGE *)
  1584. let detect_usage com =
  1585. let usage = ref [] in
  1586. List.iter (fun t -> match t with
  1587. | TClassDecl c ->
  1588. let rec expr e = match e.eexpr with
  1589. | TField(_,fa) ->
  1590. (match extract_field fa with
  1591. | Some cf when Meta.has Meta.Usage cf.cf_meta ->
  1592. let p = {e.epos with pmin = e.epos.pmax - (String.length cf.cf_name)} in
  1593. usage := p :: !usage;
  1594. | _ -> ());
  1595. Type.iter expr e
  1596. | _ -> Type.iter expr e
  1597. in
  1598. let field cf = match cf.cf_expr with None -> () | Some e -> expr e in
  1599. (match c.cl_constructor with None -> () | Some cf -> field cf);
  1600. (match c.cl_init with None -> () | Some e -> expr e);
  1601. List.iter field c.cl_ordered_statics;
  1602. List.iter field c.cl_ordered_fields;
  1603. | _ -> ()
  1604. ) com.types;
  1605. let usage = List.sort (fun p1 p2 ->
  1606. let c = compare p1.pfile p2.pfile in
  1607. if c <> 0 then c else compare p1.pmin p2.pmin
  1608. ) !usage in
  1609. raise (Typecore.DisplayPosition usage)
  1610. (* -------------------------------------------------------------------------- *)
  1611. (* POST PROCESS *)
  1612. let pp_counter = ref 1
  1613. let post_process ctx filters t =
  1614. (* ensure that we don't process twice the same (cached) module *)
  1615. let m = (t_infos t).mt_module.m_extra in
  1616. if m.m_processed = 0 then m.m_processed <- !pp_counter;
  1617. if m.m_processed = !pp_counter then
  1618. match t with
  1619. | TClassDecl c when is_removable_class c -> ()
  1620. | TClassDecl c ->
  1621. let process_field f =
  1622. match f.cf_expr with
  1623. | Some e when not (is_removable_field ctx f) ->
  1624. Abstract.cast_stack := f :: !Abstract.cast_stack;
  1625. f.cf_expr <- Some (List.fold_left (fun e f -> f e) e filters);
  1626. Abstract.cast_stack := List.tl !Abstract.cast_stack;
  1627. | _ -> ()
  1628. in
  1629. List.iter process_field c.cl_ordered_fields;
  1630. List.iter process_field c.cl_ordered_statics;
  1631. (match c.cl_constructor with
  1632. | None -> ()
  1633. | Some f -> process_field f);
  1634. (match c.cl_init with
  1635. | None -> ()
  1636. | Some e ->
  1637. c.cl_init <- Some (List.fold_left (fun e f -> f e) e filters));
  1638. | TEnumDecl _ -> ()
  1639. | TTypeDecl _ -> ()
  1640. | TAbstractDecl _ -> ()
  1641. let post_process_end() =
  1642. incr pp_counter
  1643. (* -------------------------------------------------------------------------- *)
  1644. (* STACK MANAGEMENT EMULATION *)
  1645. type stack_context = {
  1646. stack_var : string;
  1647. stack_exc_var : string;
  1648. stack_pos_var : string;
  1649. stack_pos : pos;
  1650. stack_expr : texpr;
  1651. stack_pop : texpr;
  1652. stack_save_pos : texpr;
  1653. stack_restore : texpr list;
  1654. stack_push : tclass -> string -> texpr;
  1655. stack_return : texpr -> texpr;
  1656. }
  1657. let stack_context_init com stack_var exc_var pos_var tmp_var use_add p =
  1658. let t = com.basic in
  1659. let st = t.tarray t.tstring in
  1660. let stack_var = alloc_var stack_var st in
  1661. let exc_var = alloc_var exc_var st in
  1662. let pos_var = alloc_var pos_var t.tint in
  1663. let stack_e = mk (TLocal stack_var) st p in
  1664. let exc_e = mk (TLocal exc_var) st p in
  1665. let stack_pop = fcall stack_e "pop" [] t.tstring p in
  1666. let stack_push c m =
  1667. fcall stack_e "push" [
  1668. if use_add then
  1669. binop OpAdd (string com (s_type_path c.cl_path ^ "::") p) (string com m p) t.tstring p
  1670. else
  1671. string com (s_type_path c.cl_path ^ "::" ^ m) p
  1672. ] t.tvoid p
  1673. in
  1674. let stack_return e =
  1675. let tmp = alloc_var tmp_var e.etype in
  1676. mk (TBlock [
  1677. mk (TVars [tmp, Some e]) t.tvoid e.epos;
  1678. stack_pop;
  1679. mk (TReturn (Some (mk (TLocal tmp) e.etype e.epos))) e.etype e.epos
  1680. ]) e.etype e.epos
  1681. in
  1682. {
  1683. stack_var = stack_var.v_name;
  1684. stack_exc_var = exc_var.v_name;
  1685. stack_pos_var = pos_var.v_name;
  1686. stack_pos = p;
  1687. stack_expr = stack_e;
  1688. stack_pop = stack_pop;
  1689. stack_save_pos = mk (TVars [pos_var, Some (field stack_e "length" t.tint p)]) t.tvoid p;
  1690. stack_push = stack_push;
  1691. stack_return = stack_return;
  1692. stack_restore = [
  1693. binop OpAssign exc_e (mk (TArrayDecl []) st p) st p;
  1694. mk (TWhile (
  1695. mk_parent (binop OpGte (field stack_e "length" t.tint p) (mk (TLocal pos_var) t.tint p) t.tbool p),
  1696. fcall exc_e "unshift" [fcall stack_e "pop" [] t.tstring p] t.tvoid p,
  1697. NormalWhile
  1698. )) t.tvoid p;
  1699. fcall stack_e "push" [index com exc_e 0 t.tstring p] t.tvoid p
  1700. ];
  1701. }
  1702. let stack_init com use_add =
  1703. stack_context_init com "$s" "$e" "$spos" "$tmp" use_add null_pos
  1704. let rec stack_block_loop ctx e =
  1705. match e.eexpr with
  1706. | TFunction _ ->
  1707. e
  1708. | TReturn None | TReturn (Some { eexpr = TConst _ }) | TReturn (Some { eexpr = TLocal _ }) ->
  1709. mk (TBlock [
  1710. ctx.stack_pop;
  1711. e;
  1712. ]) e.etype e.epos
  1713. | TReturn (Some e) ->
  1714. ctx.stack_return (stack_block_loop ctx e)
  1715. | TTry (v,cases) ->
  1716. let v = stack_block_loop ctx v in
  1717. let cases = List.map (fun (v,e) ->
  1718. let e = stack_block_loop ctx e in
  1719. let e = (match (mk_block e).eexpr with
  1720. | TBlock l -> mk (TBlock (ctx.stack_restore @ l)) e.etype e.epos
  1721. | _ -> assert false
  1722. ) in
  1723. v , e
  1724. ) cases in
  1725. mk (TTry (v,cases)) e.etype e.epos
  1726. | _ ->
  1727. map_expr (stack_block_loop ctx) e
  1728. let stack_block ctx c m e =
  1729. match (mk_block e).eexpr with
  1730. | TBlock l ->
  1731. mk (TBlock (
  1732. ctx.stack_push c m ::
  1733. ctx.stack_save_pos ::
  1734. List.map (stack_block_loop ctx) l
  1735. @ [ctx.stack_pop]
  1736. )) e.etype e.epos
  1737. | _ ->
  1738. assert false
  1739. (* -------------------------------------------------------------------------- *)
  1740. (* FIX OVERRIDES *)
  1741. (*
  1742. on some platforms which doesn't support type parameters, we must have the
  1743. exact same type for overriden/implemented function as the original one
  1744. *)
  1745. let rec find_field c f =
  1746. try
  1747. (match c.cl_super with
  1748. | None ->
  1749. raise Not_found
  1750. | Some ( {cl_path = (["cpp"],"FastIterator")}, _ ) ->
  1751. raise Not_found (* This is a strongly typed 'extern' and the usual rules don't apply *)
  1752. | Some (c,_) ->
  1753. find_field c f)
  1754. with Not_found -> try
  1755. let rec loop = function
  1756. | [] ->
  1757. raise Not_found
  1758. | (c,_) :: l ->
  1759. try
  1760. find_field c f
  1761. with
  1762. Not_found -> loop l
  1763. in
  1764. loop c.cl_implements
  1765. with Not_found ->
  1766. let f = PMap.find f.cf_name c.cl_fields in
  1767. (match f.cf_kind with Var { v_read = AccRequire _ } -> raise Not_found | _ -> ());
  1768. f
  1769. let fix_override com c f fd =
  1770. let f2 = (try Some (find_field c f) with Not_found -> None) in
  1771. match f2,fd with
  1772. | Some (f2), Some(fd) ->
  1773. let targs, tret = (match follow f2.cf_type with TFun (args,ret) -> args, ret | _ -> assert false) in
  1774. let changed_args = ref [] in
  1775. let prefix = "_tmp_" in
  1776. let nargs = List.map2 (fun ((v,c) as cur) (_,_,t2) ->
  1777. try
  1778. type_eq EqStrict v.v_type t2;
  1779. cur
  1780. with Unify_error _ ->
  1781. let v2 = alloc_var (prefix ^ v.v_name) t2 in
  1782. changed_args := (v,v2) :: !changed_args;
  1783. v2,c
  1784. ) fd.tf_args targs in
  1785. let fd2 = {
  1786. tf_args = nargs;
  1787. tf_type = tret;
  1788. tf_expr = (match List.rev !changed_args with
  1789. | [] -> fd.tf_expr
  1790. | args ->
  1791. let e = fd.tf_expr in
  1792. let el = (match e.eexpr with TBlock el -> el | _ -> [e]) in
  1793. let p = (match el with [] -> e.epos | e :: _ -> e.epos) in
  1794. let v = mk (TVars (List.map (fun (v,v2) ->
  1795. (v,Some (mk (TCast (mk (TLocal v2) v2.v_type p,None)) v.v_type p))
  1796. ) args)) com.basic.tvoid p in
  1797. { e with eexpr = TBlock (v :: el) }
  1798. );
  1799. } in
  1800. (* as3 does not allow wider visibility, so the base method has to be made public *)
  1801. if Common.defined com Define.As3 && f.cf_public then f2.cf_public <- true;
  1802. let targs = List.map (fun(v,c) -> (v.v_name, Option.is_some c, v.v_type)) nargs in
  1803. let fde = (match f.cf_expr with None -> assert false | Some e -> e) in
  1804. f.cf_expr <- Some { fde with eexpr = TFunction fd2 };
  1805. f.cf_type <- TFun(targs,tret);
  1806. | Some(f2), None when c.cl_interface ->
  1807. let targs, tret = (match follow f2.cf_type with TFun (args,ret) -> args, ret | _ -> assert false) in
  1808. f.cf_type <- TFun(targs,tret)
  1809. | _ ->
  1810. ()
  1811. let fix_overrides com t =
  1812. match t with
  1813. | TClassDecl c ->
  1814. (* overrides can be removed from interfaces *)
  1815. if c.cl_interface then
  1816. c.cl_ordered_fields <- List.filter (fun f ->
  1817. try
  1818. if find_field c f == f then raise Not_found;
  1819. c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  1820. false;
  1821. with Not_found ->
  1822. true
  1823. ) c.cl_ordered_fields;
  1824. List.iter (fun f ->
  1825. match f.cf_expr, f.cf_kind with
  1826. | Some { eexpr = TFunction fd }, Method (MethNormal | MethInline) ->
  1827. fix_override com c f (Some fd)
  1828. | None, Method (MethNormal | MethInline) when c.cl_interface ->
  1829. fix_override com c f None
  1830. | _ ->
  1831. ()
  1832. ) c.cl_ordered_fields
  1833. | _ ->
  1834. ()
  1835. (*
  1836. PHP does not allow abstract classes extending other abstract classes to override any fields, so these duplicates
  1837. must be removed from the child interface
  1838. *)
  1839. let fix_abstract_inheritance com t =
  1840. match t with
  1841. | TClassDecl c when c.cl_interface ->
  1842. c.cl_ordered_fields <- List.filter (fun f ->
  1843. let b = try (find_field c f) == f
  1844. with Not_found -> false in
  1845. if not b then c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  1846. b;
  1847. ) c.cl_ordered_fields
  1848. | _ -> ()
  1849. (* -------------------------------------------------------------------------- *)
  1850. (* MISC FEATURES *)
  1851. let rec is_volatile t =
  1852. match t with
  1853. | TMono r ->
  1854. (match !r with
  1855. | Some t -> is_volatile t
  1856. | _ -> false)
  1857. | TLazy f ->
  1858. is_volatile (!f())
  1859. | TType (t,tl) ->
  1860. (match t.t_path with
  1861. | ["mt";"flash"],"Volatile" -> true
  1862. | _ -> is_volatile (apply_params t.t_types tl t.t_type))
  1863. | _ ->
  1864. false
  1865. let set_default ctx a c p =
  1866. let t = a.v_type in
  1867. let ve = mk (TLocal a) t p in
  1868. let cond = TBinop (OpEq,ve,mk (TConst TNull) t p) in
  1869. 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
  1870. let bytes_serialize data =
  1871. let b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%:" in
  1872. let tbl = Array.init (String.length b64) (fun i -> String.get b64 i) in
  1873. let str = Base64.str_encode ~tbl data in
  1874. "s" ^ string_of_int (String.length str) ^ ":" ^ str
  1875. (*
  1876. Tells if the constructor might be called without any issue whatever its parameters
  1877. *)
  1878. let rec constructor_side_effects e =
  1879. match e.eexpr with
  1880. | TBinop (op,_,_) when op <> OpAssign ->
  1881. true
  1882. | TField (_,FEnum _) ->
  1883. false
  1884. | TUnop _ | TArray _ | TField _ | TEnumParameter _ | TCall _ | TNew _ | TFor _ | TWhile _ | TSwitch _ | TPatMatch _ | TReturn _ | TThrow _ ->
  1885. true
  1886. | TBinop _ | TTry _ | TIf _ | TBlock _ | TVars _
  1887. | TFunction _ | TArrayDecl _ | TObjectDecl _
  1888. | TParenthesis _ | TTypeExpr _ | TLocal _ | TMeta _
  1889. | TConst _ | TContinue | TBreak | TCast _ ->
  1890. try
  1891. Type.iter (fun e -> if constructor_side_effects e then raise Exit) e;
  1892. false;
  1893. with Exit ->
  1894. true
  1895. (*
  1896. Make a dump of the full typed AST of all types
  1897. *)
  1898. let rec create_dumpfile acc = function
  1899. | [] -> assert false
  1900. | d :: [] ->
  1901. let ch = open_out (String.concat "/" (List.rev (d :: acc)) ^ ".dump") in
  1902. let buf = Buffer.create 0 in
  1903. buf, (fun () ->
  1904. output_string ch (Buffer.contents buf);
  1905. close_out ch)
  1906. | d :: l ->
  1907. let dir = String.concat "/" (List.rev (d :: acc)) in
  1908. if not (Sys.file_exists dir) then Unix.mkdir dir 0o755;
  1909. create_dumpfile (d :: acc) l
  1910. let dump_types com =
  1911. let s_type = s_type (Type.print_context()) in
  1912. let params = function [] -> "" | l -> Printf.sprintf "<%s>" (String.concat "," (List.map (fun (n,t) -> n ^ " : " ^ s_type t) l)) in
  1913. 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
  1914. List.iter (fun mt ->
  1915. let path = Type.t_path mt in
  1916. let buf,close = create_dumpfile [] ("dump" :: (Common.platform_name com.platform) :: fst path @ [snd path]) in
  1917. let print fmt = Printf.kprintf (fun s -> Buffer.add_string buf s) fmt in
  1918. (match mt with
  1919. | Type.TClassDecl c ->
  1920. let rec print_field stat f =
  1921. 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);
  1922. print "(%s) : %s" (s_kind f.cf_kind) (s_type f.cf_type);
  1923. (match f.cf_expr with
  1924. | None -> ()
  1925. | Some e -> print "\n\n\t = %s" (s_expr s_type e));
  1926. print ";\n\n";
  1927. List.iter (fun f -> print_field stat f) f.cf_overloads
  1928. in
  1929. 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);
  1930. (match c.cl_super with None -> () | Some (c,pl) -> print " extends %s" (s_type (TInst (c,pl))));
  1931. List.iter (fun (c,pl) -> print " implements %s" (s_type (TInst (c,pl)))) c.cl_implements;
  1932. (match c.cl_dynamic with None -> () | Some t -> print " implements Dynamic<%s>" (s_type t));
  1933. (match c.cl_array_access with None -> () | Some t -> print " implements ArrayAccess<%s>" (s_type t));
  1934. print "{\n";
  1935. (match c.cl_constructor with
  1936. | None -> ()
  1937. | Some f -> print_field false f);
  1938. List.iter (print_field false) c.cl_ordered_fields;
  1939. List.iter (print_field true) c.cl_ordered_statics;
  1940. print "}";
  1941. | Type.TEnumDecl e ->
  1942. 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);
  1943. List.iter (fun n ->
  1944. let f = PMap.find n e.e_constrs in
  1945. print "\t%s : %s;\n" f.ef_name (s_type f.ef_type);
  1946. ) e.e_names;
  1947. print "}"
  1948. | Type.TTypeDecl t ->
  1949. 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);
  1950. | Type.TAbstractDecl a ->
  1951. print "%sabstract %s%s {}" (if a.a_private then "private " else "") (s_type_path path) (params a.a_types);
  1952. );
  1953. close();
  1954. ) com.types
  1955. let dump_dependencies com =
  1956. let buf,close = create_dumpfile [] ["dump";Common.platform_name com.platform;".dependencies"] in
  1957. let print fmt = Printf.kprintf (fun s -> Buffer.add_string buf s) fmt in
  1958. let dep = Hashtbl.create 0 in
  1959. List.iter (fun m ->
  1960. print "%s:\n" m.m_extra.m_file;
  1961. PMap.iter (fun _ m2 ->
  1962. print "\t%s\n" (m2.m_extra.m_file);
  1963. let l = try Hashtbl.find dep m2.m_extra.m_file with Not_found -> [] in
  1964. Hashtbl.replace dep m2.m_extra.m_file (m :: l)
  1965. ) m.m_extra.m_deps;
  1966. ) com.Common.modules;
  1967. close();
  1968. let buf,close = create_dumpfile [] ["dump";Common.platform_name com.platform;".dependants"] in
  1969. let print fmt = Printf.kprintf (fun s -> Buffer.add_string buf s) fmt in
  1970. Hashtbl.iter (fun n ml ->
  1971. print "%s:\n" n;
  1972. List.iter (fun m ->
  1973. print "\t%s\n" (m.m_extra.m_file);
  1974. ) ml;
  1975. ) dep;
  1976. close()
  1977. (*
  1978. Build a default safe-cast expression :
  1979. { var $t = <e>; if( Std.is($t,<t>) ) $t else throw "Class cast error"; }
  1980. *)
  1981. let default_cast ?(vtmp="$t") com e texpr t p =
  1982. let api = com.basic in
  1983. let mk_texpr = function
  1984. | TClassDecl c -> TAnon { a_fields = PMap.empty; a_status = ref (Statics c) }
  1985. | TEnumDecl e -> TAnon { a_fields = PMap.empty; a_status = ref (EnumStatics e) }
  1986. | TAbstractDecl a -> TAnon { a_fields = PMap.empty; a_status = ref (AbstractStatics a) }
  1987. | TTypeDecl _ -> assert false
  1988. in
  1989. let vtmp = alloc_var vtmp e.etype in
  1990. let var = mk (TVars [vtmp,Some e]) api.tvoid p in
  1991. let vexpr = mk (TLocal vtmp) e.etype p in
  1992. let texpr = mk (TTypeExpr texpr) (mk_texpr texpr) p in
  1993. let std = (try List.find (fun t -> t_path t = ([],"Std")) com.types with Not_found -> assert false) in
  1994. let fis = (try
  1995. let c = (match std with TClassDecl c -> c | _ -> assert false) in
  1996. FStatic (c, PMap.find "is" c.cl_statics)
  1997. with Not_found ->
  1998. assert false
  1999. ) in
  2000. let std = mk (TTypeExpr std) (mk_texpr std) p in
  2001. let is = mk (TField (std,fis)) (tfun [t_dynamic;t_dynamic] api.tbool) p in
  2002. let is = mk (TCall (is,[vexpr;texpr])) api.tbool p in
  2003. let exc = mk (TThrow (mk (TConst (TString "Class cast error")) api.tstring p)) t p in
  2004. let check = mk (TIf (mk_parent is,mk (TCast (vexpr,None)) t p,Some exc)) t p in
  2005. mk (TBlock [var;check;vexpr]) t p
  2006. (** Overload resolution **)
  2007. module Overloads =
  2008. struct
  2009. let rec simplify_t t = match t with
  2010. | TInst _ | TEnum _ | TAbstract({ a_impl = None }, _) ->
  2011. t
  2012. | TAbstract(a,tl) -> simplify_t (Abstract.get_underlying_type a tl)
  2013. | TType(({ t_path = [],"Null" } as t), [t2]) -> (match simplify_t t2 with
  2014. | (TAbstract({ a_impl = None }, _) | TEnum _ as t2) -> TType(t, [simplify_t t2])
  2015. | t2 -> t2)
  2016. | TType(t, tl) ->
  2017. simplify_t (apply_params t.t_types tl t.t_type)
  2018. | TMono r -> (match !r with
  2019. | Some t -> simplify_t t
  2020. | None -> t_dynamic)
  2021. | TAnon _ -> t_dynamic
  2022. | TDynamic _ -> t
  2023. | TLazy f -> simplify_t (!f())
  2024. | TFun _ -> t
  2025. (* rate type parameters *)
  2026. let rate_tp tlfun tlarg =
  2027. let acc = ref 0 in
  2028. List.iter2 (fun f a -> if not (type_iseq f a) then incr acc) tlfun tlarg;
  2029. !acc
  2030. let rec rate_conv cacc tfun targ =
  2031. match simplify_t tfun, simplify_t targ with
  2032. | TInst({ cl_interface = true } as cf, tlf), TInst(ca, tla) ->
  2033. (* breadth-first *)
  2034. let stack = ref [0,ca,tla] in
  2035. let cur = ref (0, ca,tla) in
  2036. let rec loop () =
  2037. match !stack with
  2038. | [] -> (let acc, ca, tla = !cur in match ca.cl_super with
  2039. | None -> raise Not_found
  2040. | Some (sup,tls) ->
  2041. cur := (acc+1,sup,List.map (apply_params ca.cl_types tla) tls);
  2042. stack := [!cur];
  2043. loop())
  2044. | (acc,ca,tla) :: _ when ca == cf ->
  2045. acc,tla
  2046. | (acc,ca,tla) :: s ->
  2047. stack := s @ List.map (fun (c,tl) -> (acc+1,c,List.map (apply_params ca.cl_types tla) tl)) ca.cl_implements;
  2048. loop()
  2049. in
  2050. let acc, tla = loop() in
  2051. (cacc + acc, rate_tp tlf tla)
  2052. | TInst(cf,tlf), TInst(ca,tla) ->
  2053. let rec loop acc ca tla =
  2054. if cf == ca then
  2055. acc, tla
  2056. else match ca.cl_super with
  2057. | None -> raise Not_found
  2058. | Some(sup,stl) ->
  2059. loop (acc+1) sup (List.map (apply_params ca.cl_types tla) stl)
  2060. in
  2061. let acc, tla = loop 0 ca tla in
  2062. (cacc + acc, rate_tp tlf tla)
  2063. | TEnum(ef,tlf), TEnum(ea, tla) ->
  2064. if ef != ea then raise Not_found;
  2065. (cacc, rate_tp tlf tla)
  2066. | TDynamic _, TDynamic _ ->
  2067. (cacc, 0)
  2068. | TDynamic _, _ ->
  2069. (max_int, 0) (* a function with dynamic will always be worst of all *)
  2070. | TAbstract({ a_impl = None }, _), TDynamic _ ->
  2071. (cacc + 2, 0) (* a dynamic to a basic type will have an "unboxing" penalty *)
  2072. | _, TDynamic _ ->
  2073. (cacc + 1, 0)
  2074. | TAbstract(af,tlf), TAbstract(aa,tla) ->
  2075. (if af == aa then
  2076. (cacc, rate_tp tlf tla)
  2077. else
  2078. let ret = ref None in
  2079. if List.exists (fun (t,_) -> try
  2080. ret := Some (rate_conv (cacc+1) (apply_params af.a_types tlf t) targ);
  2081. true
  2082. with | Not_found ->
  2083. false
  2084. ) af.a_from then
  2085. Option.get !ret
  2086. else
  2087. if List.exists (fun (t,_) -> try
  2088. ret := Some (rate_conv (cacc+1) tfun (apply_params aa.a_types tla t));
  2089. true
  2090. with | Not_found ->
  2091. false
  2092. ) aa.a_to then
  2093. Option.get !ret
  2094. else
  2095. raise Not_found)
  2096. | TType({ t_path = [], "Null" }, [tf]), TType({ t_path = [], "Null" }, [ta]) ->
  2097. rate_conv (cacc+0) tf ta
  2098. | TType({ t_path = [], "Null" }, [tf]), ta ->
  2099. rate_conv (cacc+1) tf ta
  2100. | tf, TType({ t_path = [], "Null" }, [ta]) ->
  2101. rate_conv (cacc+1) tf ta
  2102. | TFun _, TFun _ -> (* unify will make sure they are compatible *)
  2103. cacc,0
  2104. | tfun,targ ->
  2105. raise Not_found
  2106. let is_best arg1 arg2 =
  2107. (List.for_all2 (fun v1 v2 ->
  2108. v1 <= v2)
  2109. arg1 arg2) && (List.exists2 (fun v1 v2 ->
  2110. v1 < v2)
  2111. arg1 arg2)
  2112. let rec rm_duplicates acc ret = match ret with
  2113. | [] -> acc
  2114. | ( el, t ) :: ret when List.exists (fun (_,t2) -> type_iseq t t2) acc ->
  2115. rm_duplicates acc ret
  2116. | r :: ret ->
  2117. rm_duplicates (r :: acc) ret
  2118. let s_options rated =
  2119. String.concat ",\n" (List.map (fun ((_,t),rate) ->
  2120. "( " ^ (String.concat "," (List.map (fun (i,i2) -> string_of_int i ^ ":" ^ string_of_int i2) rate)) ^ " ) => " ^ (s_type (print_context()) t)
  2121. ) rated)
  2122. let count_optionals elist =
  2123. List.fold_left (fun acc (_,is_optional) -> if is_optional then acc + 1 else acc) 0 elist
  2124. let rec fewer_optionals acc compatible = match acc, compatible with
  2125. | _, [] -> acc
  2126. | [], c :: comp -> fewer_optionals [c] comp
  2127. | (elist_acc, _) :: _, ((elist, _) as cur) :: comp ->
  2128. let acc_opt = count_optionals elist_acc in
  2129. let comp_opt = count_optionals elist in
  2130. if acc_opt = comp_opt then
  2131. fewer_optionals (cur :: acc) comp
  2132. else if acc_opt < comp_opt then
  2133. fewer_optionals acc comp
  2134. else
  2135. fewer_optionals [cur] comp
  2136. let reduce_compatible compatible = match fewer_optionals [] (rm_duplicates [] compatible) with
  2137. | [] -> [] | [v] -> [v]
  2138. | compatible ->
  2139. (* convert compatible into ( rate * compatible_type ) list *)
  2140. let rec mk_rate acc elist args = match elist, args with
  2141. | [], [] -> acc
  2142. | (_,true) :: elist, _ :: args -> mk_rate acc elist args
  2143. | (e,false) :: elist, (n,o,t) :: args ->
  2144. mk_rate (rate_conv 0 t e.etype :: acc) elist args
  2145. | _ -> assert false
  2146. in
  2147. let rated = ref [] in
  2148. List.iter (function
  2149. | (elist,TFun(args,ret)) -> (try
  2150. rated := ( (elist,TFun(args,ret)), mk_rate [] elist args ) :: !rated
  2151. with | Not_found -> ())
  2152. | _ -> assert false
  2153. ) compatible;
  2154. let rec loop best rem = match best, rem with
  2155. | _, [] -> best
  2156. | [], r1 :: rem -> loop [r1] rem
  2157. | (bover, bargs) :: b1, (rover, rargs) :: rem ->
  2158. if is_best bargs rargs then
  2159. loop best rem
  2160. else if is_best rargs bargs then
  2161. loop (loop b1 [rover,rargs]) rem
  2162. else (* equally specific *)
  2163. loop ( (rover,rargs) :: best ) rem
  2164. in
  2165. List.map fst (loop [] !rated)
  2166. end;;