codegen.ml 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  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 type_constant com c p =
  42. let t = com.basic in
  43. match c with
  44. | Int s ->
  45. if String.length s > 10 && String.sub s 0 2 = "0x" then error "Invalid hexadecimal integer" p;
  46. (try mk (TConst (TInt (Int32.of_string s))) t.tint p
  47. with _ -> mk (TConst (TFloat s)) t.tfloat p)
  48. | Float f -> mk (TConst (TFloat f)) t.tfloat p
  49. | String s -> mk (TConst (TString s)) t.tstring p
  50. | Ident "true" -> mk (TConst (TBool true)) t.tbool p
  51. | Ident "false" -> mk (TConst (TBool false)) t.tbool p
  52. | Ident "null" -> mk (TConst TNull) (t.tnull (mk_mono())) p
  53. | Ident t -> error ("Invalid constant : " ^ t) p
  54. | Regexp _ -> error "Invalid constant" p
  55. let rec type_constant_value com (e,p) =
  56. match e with
  57. | EConst c ->
  58. type_constant com c p
  59. | EParenthesis e ->
  60. type_constant_value com e
  61. | EObjectDecl el ->
  62. mk (TObjectDecl (List.map (fun (n,e) -> n, type_constant_value com e) el)) (TAnon { a_fields = PMap.empty; a_status = ref Closed }) p
  63. | EArrayDecl el ->
  64. mk (TArrayDecl (List.map (type_constant_value com) el)) (com.basic.tarray t_dynamic) p
  65. | _ ->
  66. error "Constant value expected" p
  67. let rec has_properties c =
  68. List.exists (fun f ->
  69. match f.cf_kind with
  70. | Var { v_read = AccCall } -> true
  71. | Var { v_write = AccCall } -> true
  72. | _ when Meta.has Meta.Accessor f.cf_meta -> true
  73. | _ -> false
  74. ) c.cl_ordered_fields || (match c.cl_super with Some (c,_) -> has_properties c | _ -> false)
  75. let get_properties fields =
  76. List.fold_left (fun acc f ->
  77. if Meta.has Meta.Accessor f.cf_meta then
  78. (f.cf_name, f.cf_name) :: acc
  79. else
  80. let acc = (match f.cf_kind with
  81. | Var { v_read = AccCall } -> ("get_" ^ f.cf_name , "get_" ^ f.cf_name) :: acc
  82. | _ -> acc) in
  83. match f.cf_kind with
  84. | Var { v_write = AccCall } -> ("set_" ^ f.cf_name , "set_" ^ f.cf_name) :: acc
  85. | _ -> acc
  86. ) [] fields
  87. let add_property_field com c =
  88. let p = c.cl_pos in
  89. let props = get_properties (c.cl_ordered_statics @ c.cl_ordered_fields) in
  90. match props with
  91. | [] -> ()
  92. | _ ->
  93. let fields,values = List.fold_left (fun (fields,values) (n,v) ->
  94. let cf = mk_field n com.basic.tstring p in
  95. PMap.add n cf fields,(n, string com v p) :: values
  96. ) (PMap.empty,[]) props in
  97. let t = mk_anon fields in
  98. let e = mk (TObjectDecl values) t p in
  99. let cf = mk_field "__properties__" t p in
  100. cf.cf_expr <- Some e;
  101. c.cl_statics <- PMap.add cf.cf_name cf c.cl_statics;
  102. c.cl_ordered_statics <- cf :: c.cl_ordered_statics
  103. (* -------------------------------------------------------------------------- *)
  104. (* REMOTING PROXYS *)
  105. let extend_remoting ctx c t p async prot =
  106. if c.cl_super <> None then error "Cannot extend several classes" p;
  107. (* remove forbidden packages *)
  108. let rules = ctx.com.package_rules in
  109. ctx.com.package_rules <- PMap.foldi (fun key r acc -> match r with Forbidden -> acc | _ -> PMap.add key r acc) rules PMap.empty;
  110. (* parse module *)
  111. let path = (t.tpackage,t.tname) in
  112. let new_name = (if async then "Async_" else "Remoting_") ^ t.tname in
  113. (* check if the proxy already exists *)
  114. let t = (try
  115. Typeload.load_type_def ctx p { tpackage = fst path; tname = new_name; tparams = []; tsub = None }
  116. with
  117. Error (Module_not_found _,p2) when p == p2 ->
  118. (* build it *)
  119. Common.log ctx.com ("Building proxy for " ^ s_type_path path);
  120. let file, decls = (try
  121. Typeload.parse_module ctx path p
  122. with
  123. | 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
  124. | e -> ctx.com.package_rules <- rules; raise e) in
  125. ctx.com.package_rules <- rules;
  126. let base_fields = [
  127. { 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) };
  128. { 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 = [] } };
  129. ] in
  130. let tvoid = CTPath { tpackage = []; tname = "Void"; tparams = []; tsub = None } in
  131. let build_field is_public acc f =
  132. if f.cff_name = "new" then
  133. acc
  134. else match f.cff_kind with
  135. | FFun fd when (is_public || List.mem APublic f.cff_access) && not (List.mem AStatic f.cff_access) ->
  136. 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;
  137. let eargs = [EArrayDecl (List.map (fun (a,_,_,_) -> (EConst (Ident a),p)) fd.f_args),p] in
  138. let ftype = (match fd.f_type with Some (CTPath { tpackage = []; tname = "Void" }) -> None | _ -> fd.f_type) in
  139. let fargs, eargs = if async then match ftype with
  140. | Some tret -> fd.f_args @ ["__callb",true,Some (CTFunction ([tret],tvoid)),None], eargs @ [EConst (Ident "__callb"),p]
  141. | _ -> fd.f_args, eargs @ [EConst (Ident "null"),p]
  142. else
  143. fd.f_args, eargs
  144. in
  145. let id = (EConst (String f.cff_name), p) in
  146. let id = if prot then id else ECall ((EConst (Ident "__unprotect__"),p),[id]),p in
  147. let expr = ECall (
  148. (EField (
  149. (ECall ((EField ((EConst (Ident "__cnx"),p),"resolve"),p),[id]),p),
  150. "call")
  151. ,p),eargs),p
  152. in
  153. let expr = if async || ftype = None then expr else (EReturn (Some expr),p) in
  154. let fd = {
  155. f_params = fd.f_params;
  156. f_args = fargs;
  157. f_type = if async then None else ftype;
  158. f_expr = Some (EBlock [expr],p);
  159. } in
  160. { cff_name = f.cff_name; cff_pos = p; cff_doc = None; cff_meta = []; cff_access = [APublic]; cff_kind = FFun fd } :: acc
  161. | _ -> acc
  162. in
  163. let decls = List.map (fun d ->
  164. match d with
  165. | EClass c, p when c.d_name = t.tname ->
  166. let is_public = List.mem HExtern c.d_flags || List.mem HInterface c.d_flags in
  167. let fields = List.rev (List.fold_left (build_field is_public) base_fields c.d_data) in
  168. (EClass { c with d_flags = []; d_name = new_name; d_data = fields },p)
  169. | _ -> d
  170. ) decls in
  171. let m = Typeload.type_module ctx (t.tpackage,new_name) file decls p in
  172. add_dependency ctx.m.curmod m;
  173. try
  174. List.find (fun tdecl -> snd (t_path tdecl) = new_name) m.m_types
  175. with Not_found ->
  176. error ("Module " ^ s_type_path path ^ " does not define type " ^ t.tname) p
  177. ) in
  178. match t with
  179. | TClassDecl c2 when c2.cl_types = [] -> c2.cl_build(); c.cl_super <- Some (c2,[]);
  180. | _ -> error "Remoting proxy must be a class without parameters" p
  181. (* -------------------------------------------------------------------------- *)
  182. (* HAXE.RTTI.GENERIC *)
  183. exception Generic_Exception of string * Ast.pos
  184. type generic_context = {
  185. ctx : typer;
  186. subst : (t * t) list;
  187. name : string;
  188. p : pos;
  189. mutable mg : module_def option;
  190. }
  191. let make_generic ctx ps pt p =
  192. let rec loop l1 l2 =
  193. match l1, l2 with
  194. | [] , [] -> []
  195. | (x,TLazy f) :: l1, _ -> loop ((x,(!f)()) :: l1) l2
  196. | (_,t1) :: l1 , t2 :: l2 -> (t1,t2) :: loop l1 l2
  197. | _ -> assert false
  198. in
  199. let name =
  200. String.concat "_" (List.map2 (fun (s,_) t ->
  201. let s_type_path_underscore (p,s) = match p with [] -> s | _ -> String.concat "_" p ^ "_" ^ s in
  202. let rec loop top t = match follow t with
  203. | TInst(c,tl) -> (s_type_path_underscore c.cl_path) ^ (loop_tl tl)
  204. | TEnum(en,tl) -> (s_type_path_underscore en.e_path) ^ (loop_tl tl)
  205. | TAbstract(a,tl) -> (s_type_path_underscore a.a_path) ^ (loop_tl tl)
  206. | _ when not top -> "_" (* allow unknown/incompatible types as type parameters to retain old behavior *)
  207. | TMono _ -> raise (Generic_Exception (("Could not determine type for parameter " ^ s), p))
  208. | t -> raise (Generic_Exception (("Type parameter must be a class or enum instance (found " ^ (s_type (print_context()) t) ^ ")"), p))
  209. and loop_tl tl = match tl with
  210. | [] -> ""
  211. | tl -> "_" ^ String.concat "_" (List.map (loop false) tl)
  212. in
  213. loop true t
  214. ) ps pt)
  215. in
  216. {
  217. ctx = ctx;
  218. subst = loop ps pt;
  219. name = name;
  220. p = p;
  221. mg = None;
  222. }
  223. let rec generic_substitute_type gctx t =
  224. match t with
  225. | TInst ({ cl_kind = KGeneric } as c2,tl2) ->
  226. (* maybe loop, or generate cascading generics *)
  227. let _, _, f = gctx.ctx.g.do_build_instance gctx.ctx (TClassDecl c2) gctx.p in
  228. let t = f (List.map (generic_substitute_type gctx) tl2) in
  229. (match follow t,gctx.mg with TInst(c,_), Some m -> add_dependency m c.cl_module | _ -> ());
  230. t
  231. | _ ->
  232. try List.assq t gctx.subst with Not_found -> Type.map (generic_substitute_type gctx) t
  233. let generic_substitute_expr gctx e =
  234. let vars = Hashtbl.create 0 in
  235. let build_var v =
  236. try
  237. Hashtbl.find vars v.v_id
  238. with Not_found ->
  239. let v2 = alloc_var v.v_name (generic_substitute_type gctx v.v_type) in
  240. v2.v_meta <- v.v_meta;
  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 false 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 c, _ -> Some (build_field c)
  374. | Some ctor, _, _ -> Some ctor
  375. | None, None, None -> None
  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 get_macro_path ctx e args p =
  480. let rec loop e =
  481. match fst e with
  482. | EField (e,f) -> f :: loop e
  483. | EConst (Ident i) -> [i]
  484. | _ -> error "Invalid macro call" p
  485. in
  486. let path = match e with
  487. | (EConst(Ident i)),_ ->
  488. let path = try
  489. if not (PMap.mem i ctx.curclass.cl_statics) then raise Not_found;
  490. ctx.curclass.cl_path
  491. with Not_found -> try
  492. (t_infos (fst (PMap.find i ctx.m.module_globals))).mt_path
  493. with Not_found ->
  494. error "Invalid macro call" p
  495. in
  496. i :: (snd path) :: (fst path)
  497. | _ ->
  498. loop e
  499. in
  500. (match path with
  501. | meth :: cl :: path -> (List.rev path,cl), meth, args
  502. | _ -> error "Invalid macro call" p)
  503. let build_macro_type ctx pl p =
  504. let path, field, args = (match pl with
  505. | [TInst ({ cl_kind = KExpr (ECall (e,args),_) },_)]
  506. | [TInst ({ cl_kind = KExpr (EArrayDecl [ECall (e,args),_],_) },_)] ->
  507. get_macro_path ctx e args p
  508. | _ ->
  509. error "MacroType requires a single expression call parameter" p
  510. ) in
  511. let old = ctx.ret in
  512. let t = (match ctx.g.do_macro ctx MMacroType path field args p with
  513. | None -> mk_mono()
  514. | Some _ -> ctx.ret
  515. ) in
  516. ctx.ret <- old;
  517. t
  518. let build_macro_build ctx c pl cfl p =
  519. let path, field, args = match Meta.get Meta.GenericBuild c.cl_meta with
  520. | _,[ECall(e,args),_],_ -> get_macro_path ctx e args p
  521. | _ -> error "genericBuild requires a single expression call parameter" p
  522. in
  523. let old = ctx.ret,ctx.g.get_build_infos in
  524. ctx.g.get_build_infos <- (fun() -> Some (TClassDecl c, pl, cfl));
  525. let t = (match ctx.g.do_macro ctx MMacroType path field args p with
  526. | None -> mk_mono()
  527. | Some _ -> ctx.ret
  528. ) in
  529. ctx.ret <- fst old;
  530. ctx.g.get_build_infos <- snd old;
  531. t
  532. (* -------------------------------------------------------------------------- *)
  533. (* API EVENTS *)
  534. let build_instance ctx mtype p =
  535. match mtype with
  536. | TClassDecl c ->
  537. if ctx.pass > PBuildClass then c.cl_build();
  538. let build f s =
  539. let r = exc_protect ctx (fun r ->
  540. let t = mk_mono() in
  541. r := (fun() -> t);
  542. unify_raise ctx (f()) t p;
  543. t
  544. ) s in
  545. delay ctx PForce (fun() -> ignore ((!r)()));
  546. TLazy r
  547. in
  548. let ft = (fun pl ->
  549. match c.cl_kind with
  550. | KGeneric ->
  551. build (fun () -> build_generic ctx c p pl) "build_generic"
  552. | KMacroType ->
  553. build (fun () -> build_macro_type ctx pl p) "macro_type"
  554. | KGenericBuild cfl ->
  555. build (fun () -> build_macro_build ctx c pl cfl p) "generic_build"
  556. | _ ->
  557. TInst (c,pl)
  558. ) in
  559. c.cl_types , c.cl_path , ft
  560. | TEnumDecl e ->
  561. e.e_types , e.e_path , (fun t -> TEnum (e,t))
  562. | TTypeDecl t ->
  563. t.t_types , t.t_path , (fun tl -> TType(t,tl))
  564. | TAbstractDecl a ->
  565. a.a_types, a.a_path, (fun tl -> TAbstract(a,tl))
  566. let on_inherit ctx c p h =
  567. match h with
  568. | HExtends { tpackage = ["haxe";"remoting"]; tname = "Proxy"; tparams = [TPType(CTPath t)] } ->
  569. extend_remoting ctx c t p false true;
  570. false
  571. | HExtends { tpackage = ["haxe";"remoting"]; tname = "AsyncProxy"; tparams = [TPType(CTPath t)] } ->
  572. extend_remoting ctx c t p true true;
  573. false
  574. | HExtends { tpackage = ["mt"]; tname = "AsyncProxy"; tparams = [TPType(CTPath t)] } ->
  575. extend_remoting ctx c t p true false;
  576. false
  577. | HExtends { tpackage = ["haxe";"xml"]; tname = "Proxy"; tparams = [TPExpr(EConst (String file),p);TPType t] } ->
  578. extend_xml_proxy ctx c t file p;
  579. true
  580. | _ ->
  581. true
  582. (* Promotes type parameters of abstracts to their implementation fields *)
  583. let promote_abstract_parameters ctx t = match t with
  584. | TClassDecl ({cl_kind = KAbstractImpl a} as c) when a.a_types <> [] ->
  585. List.iter (fun f ->
  586. List.iter (fun (n,t) -> match t with
  587. | TInst({cl_kind = KTypeParameter _; cl_path=p,n} as cp,[]) when not (List.mem_assoc n f.cf_params) ->
  588. let path = List.rev ((snd c.cl_path) :: List.rev (fst c.cl_path)),n in
  589. f.cf_params <- (n,TInst({cp with cl_path = path},[])) :: f.cf_params
  590. | _ ->
  591. ()
  592. ) a.a_types;
  593. ) c.cl_ordered_statics;
  594. | _ ->
  595. ()
  596. (* -------------------------------------------------------------------------- *)
  597. (* ABSTRACT CASTS *)
  598. module Abstract = struct
  599. let find_to ab pl b =
  600. if follow b == t_dynamic then
  601. List.find (fun (t,_) -> t == t_dynamic) ab.a_to
  602. else
  603. List.find (Type.unify_to_field ab pl b) ab.a_to
  604. let find_from ab pl a b =
  605. if follow a == t_dynamic then
  606. List.find (fun (t,_) -> t == t_dynamic) ab.a_from
  607. else
  608. List.find (Type.unify_from_field ab pl a b) ab.a_from
  609. let cast_stack = ref []
  610. let underlying_type_stack = ref []
  611. let rec get_underlying_type a pl =
  612. let maybe_recurse t =
  613. underlying_type_stack := a :: !underlying_type_stack;
  614. let t = match follow t with
  615. | TAbstract(a,tl) when not (Meta.has Meta.CoreType a.a_meta) ->
  616. if List.mem a !underlying_type_stack then begin
  617. let s = String.concat " -> " (List.map (fun a -> s_type_path a.a_path) (List.rev (a :: !underlying_type_stack))) in
  618. (* technically this should be done at type declaration level *)
  619. error ("Abstract chain detected: " ^ s) a.a_pos
  620. end;
  621. get_underlying_type a tl
  622. | _ ->
  623. t
  624. in
  625. underlying_type_stack := List.tl !underlying_type_stack;
  626. t
  627. in
  628. try
  629. if not (Meta.has Meta.MultiType a.a_meta) then raise Not_found;
  630. let m = mk_mono() in
  631. let _ = find_to a pl m in
  632. maybe_recurse (follow m)
  633. with Not_found ->
  634. if Meta.has Meta.CoreType a.a_meta then
  635. t_dynamic
  636. else
  637. maybe_recurse (apply_params a.a_types pl a.a_this)
  638. let make_static_call ctx c cf a pl args t p =
  639. make_static_call ctx c cf (apply_params a.a_types pl) args t p
  640. let rec do_check_cast ctx tleft eright p =
  641. let recurse cf f =
  642. if cf == ctx.curfield || List.mem cf !cast_stack then error "Recursive implicit cast" p;
  643. cast_stack := cf :: !cast_stack;
  644. let r = f() in
  645. cast_stack := List.tl !cast_stack;
  646. r
  647. in
  648. let find a tl f =
  649. let tcf,cfo = f() in
  650. match cfo,a.a_impl with
  651. | None,_ ->
  652. let tcf = apply_params a.a_types tl tcf in
  653. if type_iseq tcf tleft then
  654. eright
  655. else
  656. (* TODO: causes Java overload issues *)
  657. (* let eright = mk (TCast(eright,None)) tleft p in *)
  658. do_check_cast ctx tcf eright p
  659. | Some cf,Some c ->
  660. recurse cf (fun () -> make_static_call ctx c cf a tl [eright] tleft p)
  661. | _ ->
  662. assert false
  663. in
  664. if type_iseq tleft eright.etype then
  665. eright
  666. else try
  667. begin match follow eright.etype with
  668. | TAbstract(a,tl) ->
  669. find a tl (fun () -> find_to a tl tleft)
  670. | _ ->
  671. raise Not_found
  672. end
  673. with Not_found -> try
  674. begin match follow tleft with
  675. | TAbstract(a,tl) ->
  676. find a tl (fun () -> find_from a tl eright.etype tleft)
  677. | _ ->
  678. raise Not_found
  679. end
  680. with Not_found ->
  681. eright
  682. let check_cast ctx tleft eright p =
  683. if ctx.com.display <> DMNone then eright else do_check_cast ctx tleft eright p
  684. let find_multitype_specialization a pl p =
  685. let m = mk_mono() in
  686. let tl = match Meta.get Meta.MultiType a.a_meta with
  687. | _,[],_ -> pl
  688. | _,el,_ ->
  689. let relevant = Hashtbl.create 0 in
  690. List.iter (fun e -> match fst e with
  691. | EConst(Ident s) -> Hashtbl.replace relevant s true
  692. | _ -> error "Type parameter expected" (pos e)
  693. ) el;
  694. let tl = List.map2 (fun (n,_) t -> if Hashtbl.mem relevant n || not (has_mono t) then t else t_dynamic) a.a_types pl in
  695. tl
  696. in
  697. let _,cfo =
  698. try find_to a tl m
  699. with Not_found ->
  700. let at = apply_params a.a_types pl a.a_this in
  701. let st = s_type (print_context()) at in
  702. if has_mono at then
  703. error ("Type parameters of multi type abstracts must be known (for " ^ st ^ ")") p
  704. else
  705. error ("Abstract " ^ (s_type_path a.a_path) ^ " has no @:to function that accepts " ^ st) p;
  706. in
  707. match cfo with
  708. | None -> assert false
  709. | Some cf -> cf, follow m
  710. let handle_abstract_casts ctx e =
  711. let rec loop ctx e = match e.eexpr with
  712. | TNew({cl_kind = KAbstractImpl a} as c,pl,el) ->
  713. (* a TNew of an abstract implementation is only generated if it is a multi type abstract *)
  714. let cf,m = find_multitype_specialization a pl e.epos in
  715. let e = make_static_call ctx c cf a pl ((mk (TConst TNull) (TAbstract(a,pl)) e.epos) :: el) m e.epos in
  716. {e with etype = m}
  717. | TCall({eexpr = TField(_,FStatic({cl_path=[],"Std"},{cf_name = "string"}))},[e1]) when (match follow e1.etype with TAbstract({a_impl = Some _},_) -> true | _ -> false) ->
  718. begin match follow e1.etype with
  719. | TAbstract({a_impl = Some c} as a,tl) ->
  720. begin try
  721. let cf = PMap.find "toString" c.cl_statics in
  722. make_static_call ctx c cf a tl [e1] ctx.t.tstring e.epos
  723. with Not_found ->
  724. e
  725. end
  726. | _ ->
  727. assert false
  728. end
  729. | TCall(e1, el) ->
  730. begin try
  731. begin match e1.eexpr with
  732. | TField(e2,fa) ->
  733. begin match follow e2.etype with
  734. | TAbstract(a,pl) when Meta.has Meta.MultiType a.a_meta ->
  735. let m = get_underlying_type a pl in
  736. let fname = field_name fa in
  737. let el = List.map (loop ctx) el in
  738. begin try
  739. let ef = mk (TField({e2 with etype = m},quick_field m fname)) e1.etype e2.epos in
  740. make_call ctx ef el e.etype e.epos
  741. with Not_found ->
  742. (* quick_field raises Not_found if m is an abstract, we have to replicate the 'using' call here *)
  743. match follow m with
  744. | TAbstract({a_impl = Some c} as a,pl) ->
  745. let cf = PMap.find fname c.cl_statics in
  746. make_static_call ctx c cf a pl (e2 :: el) e.etype e.epos
  747. | _ -> raise Not_found
  748. end
  749. | _ -> raise Not_found
  750. end
  751. | _ ->
  752. raise Not_found
  753. end
  754. with Not_found ->
  755. Type.map_expr (loop ctx) e
  756. end
  757. | _ ->
  758. Type.map_expr (loop ctx) e
  759. in
  760. loop ctx e
  761. end
  762. module PatternMatchConversion = struct
  763. type cctx = {
  764. ctx : typer;
  765. mutable eval_stack : ((tvar * pos) * texpr) list list;
  766. dt_lookup : dt array;
  767. }
  768. let is_declared cctx v =
  769. let rec loop sl = match sl with
  770. | stack :: sl ->
  771. List.exists (fun ((v2,_),_) -> v == v2) stack || loop sl
  772. | [] ->
  773. false
  774. in
  775. loop cctx.eval_stack
  776. let group_cases cases =
  777. let dt_eq dt1 dt2 = match dt1,dt2 with
  778. | DTGoto i1, DTGoto i2 when i1 = i2 -> true
  779. (* TODO equal bindings *)
  780. | _ -> false
  781. in
  782. match List.rev cases with
  783. | [] -> []
  784. | [con,dt] -> [[con],dt]
  785. | (con,dt) :: cases ->
  786. let tmp,ldt,cases = List.fold_left (fun (tmp,ldt,acc) (con,dt) ->
  787. if dt_eq dt ldt then
  788. (con :: tmp,dt,acc)
  789. else
  790. ([con],dt,(tmp,ldt) :: acc)
  791. ) ([con],dt,[]) cases in
  792. match tmp with
  793. | [] -> cases
  794. | tmp -> ((tmp,ldt) :: cases)
  795. let rec convert_dt cctx dt =
  796. match dt with
  797. | DTBind (bl,dt) ->
  798. cctx.eval_stack <- bl :: cctx.eval_stack;
  799. let e = convert_dt cctx dt in
  800. cctx.eval_stack <- List.tl cctx.eval_stack;
  801. let vl,el = List.fold_left (fun (vl,el) ((v,p),e) ->
  802. if is_declared cctx v then
  803. vl, (mk (TBinop(OpAssign,mk (TLocal v) v.v_type p,e)) e.etype e.epos) :: el
  804. else
  805. ((v,Some e) :: vl), el
  806. ) ([],[e]) bl in
  807. let el_v = List.map (fun (v,eo) -> mk (TVar (v,eo)) cctx.ctx.t.tvoid e.epos) vl in
  808. mk (TBlock (el_v @ el)) e.etype e.epos
  809. | DTGoto i ->
  810. convert_dt cctx (cctx.dt_lookup.(i))
  811. | DTExpr e ->
  812. e
  813. | DTGuard(e,dt1,dt2) ->
  814. let ethen = convert_dt cctx dt1 in
  815. mk (TIf(e,ethen,match dt2 with None -> None | Some dt -> Some (convert_dt cctx dt))) ethen.etype (punion e.epos ethen.epos)
  816. | DTSwitch({eexpr = TMeta((Meta.Exhaustive,_,_),_)},[_,dt],None) ->
  817. convert_dt cctx dt
  818. | DTSwitch(e_st,cl,dto) ->
  819. let def = match dto with None -> None | Some dt -> Some (convert_dt cctx dt) in
  820. let cases = group_cases cl in
  821. let cases = List.map (fun (cl,dt) -> cl,convert_dt cctx dt) cases in
  822. mk (TSwitch(e_st,cases,def)) (mk_mono()) e_st.epos
  823. let to_typed_ast ctx dt p =
  824. let first = dt.dt_dt_lookup.(dt.dt_first) in
  825. let cctx = {
  826. ctx = ctx;
  827. dt_lookup = dt.dt_dt_lookup;
  828. eval_stack = [];
  829. } in
  830. let e = convert_dt cctx first in
  831. let e = { e with epos = p; etype = dt.dt_type} in
  832. if dt.dt_var_init = [] then
  833. e
  834. else begin
  835. let el_v = List.map (fun (v,eo) -> mk (TVar (v,eo)) cctx.ctx.t.tvoid p) dt.dt_var_init in
  836. mk (TBlock (el_v @ [e])) dt.dt_type e.epos
  837. end
  838. end
  839. (* -------------------------------------------------------------------------- *)
  840. (* USAGE *)
  841. let detect_usage com =
  842. let usage = ref [] in
  843. List.iter (fun t -> match t with
  844. | TClassDecl c ->
  845. let rec expr e = match e.eexpr with
  846. | TField(_,fa) ->
  847. begin match extract_field fa with
  848. | Some cf when Meta.has Meta.Usage cf.cf_meta ->
  849. let p = {e.epos with pmin = e.epos.pmax - (String.length cf.cf_name)} in
  850. usage := p :: !usage;
  851. | _ ->
  852. ()
  853. end;
  854. Type.iter expr e
  855. | TLocal v when Meta.has Meta.Usage v.v_meta ->
  856. usage := e.epos :: !usage
  857. | _ -> Type.iter expr e
  858. in
  859. let field cf = match cf.cf_expr with None -> () | Some e -> expr e in
  860. (match c.cl_constructor with None -> () | Some cf -> field cf);
  861. (match c.cl_init with None -> () | Some e -> expr e);
  862. List.iter field c.cl_ordered_statics;
  863. List.iter field c.cl_ordered_fields;
  864. | _ -> ()
  865. ) com.types;
  866. let usage = List.sort (fun p1 p2 ->
  867. let c = compare p1.pfile p2.pfile in
  868. if c <> 0 then c else compare p1.pmin p2.pmin
  869. ) !usage in
  870. raise (Typecore.DisplayPosition usage)
  871. let update_cache_dependencies com =
  872. let rec check_t m t = match t with
  873. | TInst(c,tl) ->
  874. add_dependency m c.cl_module;
  875. List.iter (check_t m) tl;
  876. | TEnum(en,tl) ->
  877. add_dependency m en.e_module;
  878. List.iter (check_t m) tl;
  879. | TType(t,tl) ->
  880. add_dependency m t.t_module;
  881. List.iter (check_t m) tl;
  882. | TAbstract(a,tl) ->
  883. add_dependency m a.a_module;
  884. List.iter (check_t m) tl;
  885. | TFun(targs,tret) ->
  886. List.iter (fun (_,_,t) -> check_t m t) targs;
  887. check_t m tret;
  888. | TAnon an ->
  889. PMap.iter (fun _ cf -> check_field m cf) an.a_fields
  890. | TMono r ->
  891. (match !r with
  892. | Some t -> check_t m t
  893. | _ -> ())
  894. | TLazy f ->
  895. check_t m (!f())
  896. | TDynamic t ->
  897. if t == t_dynamic then
  898. ()
  899. else
  900. check_t m t
  901. and check_field m cf =
  902. check_t m cf.cf_type
  903. in
  904. List.iter (fun t -> match t with
  905. | TClassDecl c ->
  906. List.iter (check_field c.cl_module) c.cl_ordered_statics;
  907. List.iter (check_field c.cl_module) c.cl_ordered_fields;
  908. (match c.cl_constructor with None -> () | Some cf -> check_field c.cl_module cf);
  909. | _ ->
  910. ()
  911. ) com.types
  912. (* -------------------------------------------------------------------------- *)
  913. (* STACK MANAGEMENT EMULATION *)
  914. type stack_context = {
  915. stack_var : string;
  916. stack_exc_var : string;
  917. stack_pos_var : string;
  918. stack_pos : pos;
  919. stack_expr : texpr;
  920. stack_pop : texpr;
  921. stack_save_pos : texpr;
  922. stack_restore : texpr list;
  923. stack_push : tclass -> string -> texpr;
  924. stack_return : texpr -> texpr;
  925. }
  926. let stack_context_init com stack_var exc_var pos_var tmp_var use_add p =
  927. let t = com.basic in
  928. let st = t.tarray t.tstring in
  929. let stack_var = alloc_var stack_var st in
  930. let exc_var = alloc_var exc_var st in
  931. let pos_var = alloc_var pos_var t.tint in
  932. let stack_e = mk (TLocal stack_var) st p in
  933. let exc_e = mk (TLocal exc_var) st p in
  934. let stack_pop = fcall stack_e "pop" [] t.tstring p in
  935. let stack_push c m =
  936. fcall stack_e "push" [
  937. if use_add then
  938. binop OpAdd (string com (s_type_path c.cl_path ^ "::") p) (string com m p) t.tstring p
  939. else
  940. string com (s_type_path c.cl_path ^ "::" ^ m) p
  941. ] t.tvoid p
  942. in
  943. let stack_return e =
  944. let tmp = alloc_var tmp_var e.etype in
  945. mk (TBlock [
  946. mk (TVar (tmp, Some e)) t.tvoid e.epos;
  947. stack_pop;
  948. mk (TReturn (Some (mk (TLocal tmp) e.etype e.epos))) e.etype e.epos
  949. ]) e.etype e.epos
  950. in
  951. {
  952. stack_var = stack_var.v_name;
  953. stack_exc_var = exc_var.v_name;
  954. stack_pos_var = pos_var.v_name;
  955. stack_pos = p;
  956. stack_expr = stack_e;
  957. stack_pop = stack_pop;
  958. stack_save_pos = mk (TVar (pos_var, Some (field stack_e "length" t.tint p))) t.tvoid p;
  959. stack_push = stack_push;
  960. stack_return = stack_return;
  961. stack_restore = [
  962. binop OpAssign exc_e (mk (TArrayDecl []) st p) st p;
  963. mk (TWhile (
  964. mk_parent (binop OpGte (field stack_e "length" t.tint p) (mk (TLocal pos_var) t.tint p) t.tbool p),
  965. fcall exc_e "unshift" [fcall stack_e "pop" [] t.tstring p] t.tvoid p,
  966. NormalWhile
  967. )) t.tvoid p;
  968. fcall stack_e "push" [index com exc_e 0 t.tstring p] t.tvoid p
  969. ];
  970. }
  971. let stack_init com use_add =
  972. stack_context_init com "$s" "$e" "$spos" "$tmp" use_add null_pos
  973. let rec stack_block_loop ctx e =
  974. match e.eexpr with
  975. | TFunction _ ->
  976. e
  977. | TReturn None | TReturn (Some { eexpr = TConst _ }) | TReturn (Some { eexpr = TLocal _ }) ->
  978. mk (TBlock [
  979. ctx.stack_pop;
  980. e;
  981. ]) e.etype e.epos
  982. | TReturn (Some e) ->
  983. ctx.stack_return (stack_block_loop ctx e)
  984. | TTry (v,cases) ->
  985. let v = stack_block_loop ctx v in
  986. let cases = List.map (fun (v,e) ->
  987. let e = stack_block_loop ctx e in
  988. let e = (match (mk_block e).eexpr with
  989. | TBlock l -> mk (TBlock (ctx.stack_restore @ l)) e.etype e.epos
  990. | _ -> assert false
  991. ) in
  992. v , e
  993. ) cases in
  994. mk (TTry (v,cases)) e.etype e.epos
  995. | _ ->
  996. map_expr (stack_block_loop ctx) e
  997. let stack_block ctx c m e =
  998. match (mk_block e).eexpr with
  999. | TBlock l ->
  1000. mk (TBlock (
  1001. ctx.stack_push c m ::
  1002. ctx.stack_save_pos ::
  1003. List.map (stack_block_loop ctx) l
  1004. @ [ctx.stack_pop]
  1005. )) e.etype e.epos
  1006. | _ ->
  1007. assert false
  1008. (* -------------------------------------------------------------------------- *)
  1009. (* FIX OVERRIDES *)
  1010. (*
  1011. on some platforms which doesn't support type parameters, we must have the
  1012. exact same type for overriden/implemented function as the original one
  1013. *)
  1014. let rec find_field c f =
  1015. try
  1016. (match c.cl_super with
  1017. | None ->
  1018. raise Not_found
  1019. | Some ( {cl_path = (["cpp"],"FastIterator")}, _ ) ->
  1020. raise Not_found (* This is a strongly typed 'extern' and the usual rules don't apply *)
  1021. | Some (c,_) ->
  1022. find_field c f)
  1023. with Not_found -> try
  1024. let rec loop = function
  1025. | [] ->
  1026. raise Not_found
  1027. | (c,_) :: l ->
  1028. try
  1029. find_field c f
  1030. with
  1031. Not_found -> loop l
  1032. in
  1033. loop c.cl_implements
  1034. with Not_found ->
  1035. let f = PMap.find f.cf_name c.cl_fields in
  1036. (match f.cf_kind with Var { v_read = AccRequire _ } -> raise Not_found | _ -> ());
  1037. f
  1038. let fix_override com c f fd =
  1039. let f2 = (try Some (find_field c f) with Not_found -> None) in
  1040. match f2,fd with
  1041. | Some (f2), Some(fd) ->
  1042. let targs, tret = (match follow f2.cf_type with TFun (args,ret) -> args, ret | _ -> assert false) in
  1043. let changed_args = ref [] in
  1044. let prefix = "_tmp_" in
  1045. let nargs = List.map2 (fun ((v,ct) as cur) (_,_,t2) ->
  1046. try
  1047. type_eq EqStrict (monomorphs c.cl_types (monomorphs f.cf_params v.v_type)) t2;
  1048. (* Flash generates type parameters with a single constraint as that constraint type, so we
  1049. have to detect this case and change the variable (issue #2712). *)
  1050. begin match follow v.v_type with
  1051. | TInst({cl_kind = KTypeParameter [tc]} as cp,_) when com.platform = Flash ->
  1052. if List.mem_assoc (snd cp.cl_path) c.cl_types then raise (Unify_error [])
  1053. | _ ->
  1054. ()
  1055. end;
  1056. cur
  1057. with Unify_error _ ->
  1058. let v2 = alloc_var (prefix ^ v.v_name) t2 in
  1059. changed_args := (v,v2) :: !changed_args;
  1060. v2,ct
  1061. ) fd.tf_args targs in
  1062. let fd2 = {
  1063. tf_args = nargs;
  1064. tf_type = tret;
  1065. tf_expr = (match List.rev !changed_args with
  1066. | [] -> fd.tf_expr
  1067. | args ->
  1068. let e = fd.tf_expr in
  1069. let el = (match e.eexpr with TBlock el -> el | _ -> [e]) in
  1070. let p = (match el with [] -> e.epos | e :: _ -> e.epos) in
  1071. let el_v = List.map (fun (v,v2) ->
  1072. mk (TVar (v,Some (mk (TCast (mk (TLocal v2) v2.v_type p,None)) v.v_type p))) com.basic.tvoid p
  1073. ) args in
  1074. { e with eexpr = TBlock (el_v @ el) }
  1075. );
  1076. } in
  1077. (* as3 does not allow wider visibility, so the base method has to be made public *)
  1078. if Common.defined com Define.As3 && f.cf_public then f2.cf_public <- true;
  1079. let targs = List.map (fun(v,c) -> (v.v_name, Option.is_some c, v.v_type)) nargs in
  1080. let fde = (match f.cf_expr with None -> assert false | Some e -> e) in
  1081. f.cf_expr <- Some { fde with eexpr = TFunction fd2 };
  1082. f.cf_type <- TFun(targs,tret);
  1083. | Some(f2), None when c.cl_interface ->
  1084. let targs, tret = (match follow f2.cf_type with TFun (args,ret) -> args, ret | _ -> assert false) in
  1085. f.cf_type <- TFun(targs,tret)
  1086. | _ ->
  1087. ()
  1088. let fix_overrides com t =
  1089. match t with
  1090. | TClassDecl c ->
  1091. (* overrides can be removed from interfaces *)
  1092. if c.cl_interface then
  1093. c.cl_ordered_fields <- List.filter (fun f ->
  1094. try
  1095. if find_field c f == f then raise Not_found;
  1096. c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  1097. false;
  1098. with Not_found ->
  1099. true
  1100. ) c.cl_ordered_fields;
  1101. List.iter (fun f ->
  1102. match f.cf_expr, f.cf_kind with
  1103. | Some { eexpr = TFunction fd }, Method (MethNormal | MethInline) ->
  1104. fix_override com c f (Some fd)
  1105. | None, Method (MethNormal | MethInline) when c.cl_interface ->
  1106. fix_override com c f None
  1107. | _ ->
  1108. ()
  1109. ) c.cl_ordered_fields
  1110. | _ ->
  1111. ()
  1112. (*
  1113. PHP does not allow abstract classes extending other abstract classes to override any fields, so these duplicates
  1114. must be removed from the child interface
  1115. *)
  1116. let fix_abstract_inheritance com t =
  1117. match t with
  1118. | TClassDecl c when c.cl_interface ->
  1119. c.cl_ordered_fields <- List.filter (fun f ->
  1120. let b = try (find_field c f) == f
  1121. with Not_found -> false in
  1122. if not b then c.cl_fields <- PMap.remove f.cf_name c.cl_fields;
  1123. b;
  1124. ) c.cl_ordered_fields
  1125. | _ -> ()
  1126. (* -------------------------------------------------------------------------- *)
  1127. (* MISC FEATURES *)
  1128. let rec is_volatile t =
  1129. match t with
  1130. | TMono r ->
  1131. (match !r with
  1132. | Some t -> is_volatile t
  1133. | _ -> false)
  1134. | TLazy f ->
  1135. is_volatile (!f())
  1136. | TType (t,tl) ->
  1137. (match t.t_path with
  1138. | ["mt";"flash"],"Volatile" -> true
  1139. | _ -> is_volatile (apply_params t.t_types tl t.t_type))
  1140. | _ ->
  1141. false
  1142. let set_default ctx a c p =
  1143. let t = a.v_type in
  1144. let ve = mk (TLocal a) t p in
  1145. let cond = TBinop (OpEq,ve,mk (TConst TNull) t p) in
  1146. 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
  1147. let bytes_serialize data =
  1148. let b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" in
  1149. let tbl = Array.init (String.length b64) (fun i -> String.get b64 i) in
  1150. Base64.str_encode ~tbl data
  1151. (*
  1152. Tells if the constructor might be called without any issue whatever its parameters
  1153. *)
  1154. let rec constructor_side_effects e =
  1155. match e.eexpr with
  1156. | TBinop (op,_,_) when op <> OpAssign ->
  1157. true
  1158. | TField (_,FEnum _) ->
  1159. false
  1160. | TUnop _ | TArray _ | TField _ | TEnumParameter _ | TCall _ | TNew _ | TFor _ | TWhile _ | TSwitch _ | TPatMatch _ | TReturn _ | TThrow _ ->
  1161. true
  1162. | TBinop _ | TTry _ | TIf _ | TBlock _ | TVar _
  1163. | TFunction _ | TArrayDecl _ | TObjectDecl _
  1164. | TParenthesis _ | TTypeExpr _ | TLocal _ | TMeta _
  1165. | TConst _ | TContinue | TBreak | TCast _ ->
  1166. try
  1167. Type.iter (fun e -> if constructor_side_effects e then raise Exit) e;
  1168. false;
  1169. with Exit ->
  1170. true
  1171. (*
  1172. Make a dump of the full typed AST of all types
  1173. *)
  1174. let rec create_dumpfile acc = function
  1175. | [] -> assert false
  1176. | d :: [] ->
  1177. let ch = open_out (String.concat "/" (List.rev (d :: acc)) ^ ".dump") in
  1178. let buf = Buffer.create 0 in
  1179. buf, (fun () ->
  1180. output_string ch (Buffer.contents buf);
  1181. close_out ch)
  1182. | d :: l ->
  1183. let dir = String.concat "/" (List.rev (d :: acc)) in
  1184. if not (Sys.file_exists dir) then Unix.mkdir dir 0o755;
  1185. create_dumpfile (d :: acc) l
  1186. let dump_types com =
  1187. let s_type = s_type (Type.print_context()) in
  1188. let params = function [] -> "" | l -> Printf.sprintf "<%s>" (String.concat "," (List.map (fun (n,t) -> n ^ " : " ^ s_type t) l)) in
  1189. 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
  1190. List.iter (fun mt ->
  1191. let path = Type.t_path mt in
  1192. let buf,close = create_dumpfile [] ("dump" :: (Common.platform_name com.platform) :: fst path @ [snd path]) in
  1193. let print fmt = Printf.kprintf (fun s -> Buffer.add_string buf s) fmt in
  1194. (match mt with
  1195. | Type.TClassDecl c ->
  1196. let rec print_field stat f =
  1197. 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);
  1198. print "(%s) : %s" (s_kind f.cf_kind) (s_type f.cf_type);
  1199. (match f.cf_expr with
  1200. | None -> ()
  1201. | Some e -> print "\n\n\t = %s" (s_expr s_type e));
  1202. print ";\n\n";
  1203. List.iter (fun f -> print_field stat f) f.cf_overloads
  1204. in
  1205. 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);
  1206. (match c.cl_super with None -> () | Some (c,pl) -> print " extends %s" (s_type (TInst (c,pl))));
  1207. List.iter (fun (c,pl) -> print " implements %s" (s_type (TInst (c,pl)))) c.cl_implements;
  1208. (match c.cl_dynamic with None -> () | Some t -> print " implements Dynamic<%s>" (s_type t));
  1209. (match c.cl_array_access with None -> () | Some t -> print " implements ArrayAccess<%s>" (s_type t));
  1210. print "{\n";
  1211. (match c.cl_constructor with
  1212. | None -> ()
  1213. | Some f -> print_field false f);
  1214. List.iter (print_field false) c.cl_ordered_fields;
  1215. List.iter (print_field true) c.cl_ordered_statics;
  1216. print "}";
  1217. | Type.TEnumDecl e ->
  1218. 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);
  1219. List.iter (fun n ->
  1220. let f = PMap.find n e.e_constrs in
  1221. print "\t%s : %s;\n" f.ef_name (s_type f.ef_type);
  1222. ) e.e_names;
  1223. print "}"
  1224. | Type.TTypeDecl t ->
  1225. 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);
  1226. | Type.TAbstractDecl a ->
  1227. print "%sabstract %s%s {}" (if a.a_private then "private " else "") (s_type_path path) (params a.a_types);
  1228. );
  1229. close();
  1230. ) com.types
  1231. let dump_dependencies com =
  1232. let buf,close = create_dumpfile [] ["dump";Common.platform_name com.platform;".dependencies"] in
  1233. let print fmt = Printf.kprintf (fun s -> Buffer.add_string buf s) fmt in
  1234. let dep = Hashtbl.create 0 in
  1235. List.iter (fun m ->
  1236. print "%s:\n" m.m_extra.m_file;
  1237. PMap.iter (fun _ m2 ->
  1238. print "\t%s\n" (m2.m_extra.m_file);
  1239. let l = try Hashtbl.find dep m2.m_extra.m_file with Not_found -> [] in
  1240. Hashtbl.replace dep m2.m_extra.m_file (m :: l)
  1241. ) m.m_extra.m_deps;
  1242. ) com.Common.modules;
  1243. close();
  1244. let buf,close = create_dumpfile [] ["dump";Common.platform_name com.platform;".dependants"] in
  1245. let print fmt = Printf.kprintf (fun s -> Buffer.add_string buf s) fmt in
  1246. Hashtbl.iter (fun n ml ->
  1247. print "%s:\n" n;
  1248. List.iter (fun m ->
  1249. print "\t%s\n" (m.m_extra.m_file);
  1250. ) ml;
  1251. ) dep;
  1252. close()
  1253. (*
  1254. Build a default safe-cast expression :
  1255. { var $t = <e>; if( Std.is($t,<t>) ) $t else throw "Class cast error"; }
  1256. *)
  1257. let default_cast ?(vtmp="$t") com e texpr t p =
  1258. let api = com.basic in
  1259. let mk_texpr = function
  1260. | TClassDecl c -> TAnon { a_fields = PMap.empty; a_status = ref (Statics c) }
  1261. | TEnumDecl e -> TAnon { a_fields = PMap.empty; a_status = ref (EnumStatics e) }
  1262. | TAbstractDecl a -> TAnon { a_fields = PMap.empty; a_status = ref (AbstractStatics a) }
  1263. | TTypeDecl _ -> assert false
  1264. in
  1265. let vtmp = alloc_var vtmp e.etype in
  1266. let var = mk (TVar (vtmp,Some e)) api.tvoid p in
  1267. let vexpr = mk (TLocal vtmp) e.etype p in
  1268. let texpr = mk (TTypeExpr texpr) (mk_texpr texpr) p in
  1269. let std = (try List.find (fun t -> t_path t = ([],"Std")) com.types with Not_found -> assert false) in
  1270. let fis = (try
  1271. let c = (match std with TClassDecl c -> c | _ -> assert false) in
  1272. FStatic (c, PMap.find "is" c.cl_statics)
  1273. with Not_found ->
  1274. assert false
  1275. ) in
  1276. let std = mk (TTypeExpr std) (mk_texpr std) p in
  1277. let is = mk (TField (std,fis)) (tfun [t_dynamic;t_dynamic] api.tbool) p in
  1278. let is = mk (TCall (is,[vexpr;texpr])) api.tbool p in
  1279. let exc = mk (TThrow (mk (TConst (TString "Class cast error")) api.tstring p)) t p in
  1280. let check = mk (TIf (mk_parent is,mk (TCast (vexpr,None)) t p,Some exc)) t p in
  1281. mk (TBlock [var;check;vexpr]) t p
  1282. (** Overload resolution **)
  1283. module Overloads =
  1284. struct
  1285. let rec simplify_t t = match t with
  1286. | TInst _ | TEnum _ | TAbstract({ a_impl = None }, _) ->
  1287. t
  1288. | TAbstract(a,tl) -> simplify_t (Abstract.get_underlying_type a tl)
  1289. | TType(({ t_path = [],"Null" } as t), [t2]) -> (match simplify_t t2 with
  1290. | (TAbstract({ a_impl = None }, _) | TEnum _ as t2) -> TType(t, [simplify_t t2])
  1291. | t2 -> t2)
  1292. | TType(t, tl) ->
  1293. simplify_t (apply_params t.t_types tl t.t_type)
  1294. | TMono r -> (match !r with
  1295. | Some t -> simplify_t t
  1296. | None -> t_dynamic)
  1297. | TAnon _ -> t_dynamic
  1298. | TDynamic _ -> t
  1299. | TLazy f -> simplify_t (!f())
  1300. | TFun _ -> t
  1301. (* rate type parameters *)
  1302. let rate_tp tlfun tlarg =
  1303. let acc = ref 0 in
  1304. List.iter2 (fun f a -> if not (type_iseq f a) then incr acc) tlfun tlarg;
  1305. !acc
  1306. let rec rate_conv cacc tfun targ =
  1307. match simplify_t tfun, simplify_t targ with
  1308. | TInst({ cl_interface = true } as cf, tlf), TInst(ca, tla) ->
  1309. (* breadth-first *)
  1310. let stack = ref [0,ca,tla] in
  1311. let cur = ref (0, ca,tla) in
  1312. let rec loop () =
  1313. match !stack with
  1314. | [] -> (let acc, ca, tla = !cur in match ca.cl_super with
  1315. | None -> raise Not_found
  1316. | Some (sup,tls) ->
  1317. cur := (acc+1,sup,List.map (apply_params ca.cl_types tla) tls);
  1318. stack := [!cur];
  1319. loop())
  1320. | (acc,ca,tla) :: _ when ca == cf ->
  1321. acc,tla
  1322. | (acc,ca,tla) :: s ->
  1323. stack := s @ List.map (fun (c,tl) -> (acc+1,c,List.map (apply_params ca.cl_types tla) tl)) ca.cl_implements;
  1324. loop()
  1325. in
  1326. let acc, tla = loop() in
  1327. (cacc + acc, rate_tp tlf tla)
  1328. | TInst(cf,tlf), TInst(ca,tla) ->
  1329. let rec loop acc ca tla =
  1330. if cf == ca then
  1331. acc, tla
  1332. else match ca.cl_super with
  1333. | None -> raise Not_found
  1334. | Some(sup,stl) ->
  1335. loop (acc+1) sup (List.map (apply_params ca.cl_types tla) stl)
  1336. in
  1337. let acc, tla = loop 0 ca tla in
  1338. (cacc + acc, rate_tp tlf tla)
  1339. | TEnum(ef,tlf), TEnum(ea, tla) ->
  1340. if ef != ea then raise Not_found;
  1341. (cacc, rate_tp tlf tla)
  1342. | TDynamic _, TDynamic _ ->
  1343. (cacc, 0)
  1344. | TDynamic _, _ ->
  1345. (max_int, 0) (* a function with dynamic will always be worst of all *)
  1346. | TAbstract({ a_impl = None }, _), TDynamic _ ->
  1347. (cacc + 2, 0) (* a dynamic to a basic type will have an "unboxing" penalty *)
  1348. | _, TDynamic _ ->
  1349. (cacc + 1, 0)
  1350. | TAbstract(af,tlf), TAbstract(aa,tla) ->
  1351. (if af == aa then
  1352. (cacc, rate_tp tlf tla)
  1353. else
  1354. let ret = ref None in
  1355. if List.exists (fun (t,_) -> try
  1356. ret := Some (rate_conv (cacc+1) (apply_params af.a_types tlf t) targ);
  1357. true
  1358. with | Not_found ->
  1359. false
  1360. ) af.a_from then
  1361. Option.get !ret
  1362. else
  1363. if List.exists (fun (t,_) -> try
  1364. ret := Some (rate_conv (cacc+1) tfun (apply_params aa.a_types tla t));
  1365. true
  1366. with | Not_found ->
  1367. false
  1368. ) aa.a_to then
  1369. Option.get !ret
  1370. else
  1371. raise Not_found)
  1372. | TType({ t_path = [], "Null" }, [tf]), TType({ t_path = [], "Null" }, [ta]) ->
  1373. rate_conv (cacc+0) tf ta
  1374. | TType({ t_path = [], "Null" }, [tf]), ta ->
  1375. rate_conv (cacc+1) tf ta
  1376. | tf, TType({ t_path = [], "Null" }, [ta]) ->
  1377. rate_conv (cacc+1) tf ta
  1378. | TFun _, TFun _ -> (* unify will make sure they are compatible *)
  1379. cacc,0
  1380. | tfun,targ ->
  1381. raise Not_found
  1382. let is_best arg1 arg2 =
  1383. (List.for_all2 (fun v1 v2 ->
  1384. v1 <= v2)
  1385. arg1 arg2) && (List.exists2 (fun v1 v2 ->
  1386. v1 < v2)
  1387. arg1 arg2)
  1388. let rec rm_duplicates acc ret = match ret with
  1389. | [] -> acc
  1390. | ( el, t ) :: ret when List.exists (fun (_,t2) -> type_iseq t t2) acc ->
  1391. rm_duplicates acc ret
  1392. | r :: ret ->
  1393. rm_duplicates (r :: acc) ret
  1394. let s_options rated =
  1395. String.concat ",\n" (List.map (fun ((_,t),rate) ->
  1396. "( " ^ (String.concat "," (List.map (fun (i,i2) -> string_of_int i ^ ":" ^ string_of_int i2) rate)) ^ " ) => " ^ (s_type (print_context()) t)
  1397. ) rated)
  1398. let count_optionals elist =
  1399. List.fold_left (fun acc (_,is_optional) -> if is_optional then acc + 1 else acc) 0 elist
  1400. let rec fewer_optionals acc compatible = match acc, compatible with
  1401. | _, [] -> acc
  1402. | [], c :: comp -> fewer_optionals [c] comp
  1403. | (elist_acc, _) :: _, ((elist, _) as cur) :: comp ->
  1404. let acc_opt = count_optionals elist_acc in
  1405. let comp_opt = count_optionals elist in
  1406. if acc_opt = comp_opt then
  1407. fewer_optionals (cur :: acc) comp
  1408. else if acc_opt < comp_opt then
  1409. fewer_optionals acc comp
  1410. else
  1411. fewer_optionals [cur] comp
  1412. let reduce_compatible compatible = match fewer_optionals [] (rm_duplicates [] compatible) with
  1413. | [] -> [] | [v] -> [v]
  1414. | compatible ->
  1415. (* convert compatible into ( rate * compatible_type ) list *)
  1416. let rec mk_rate acc elist args = match elist, args with
  1417. | [], [] -> acc
  1418. | (_,true) :: elist, _ :: args -> mk_rate acc elist args
  1419. | (e,false) :: elist, (n,o,t) :: args ->
  1420. mk_rate (rate_conv 0 t e.etype :: acc) elist args
  1421. | _ -> assert false
  1422. in
  1423. let rated = ref [] in
  1424. List.iter (function
  1425. | (elist,TFun(args,ret)) -> (try
  1426. rated := ( (elist,TFun(args,ret)), mk_rate [] elist args ) :: !rated
  1427. with | Not_found -> ())
  1428. | _ -> assert false
  1429. ) compatible;
  1430. let rec loop best rem = match best, rem with
  1431. | _, [] -> best
  1432. | [], r1 :: rem -> loop [r1] rem
  1433. | (bover, bargs) :: b1, (rover, rargs) :: rem ->
  1434. if is_best bargs rargs then
  1435. loop best rem
  1436. else if is_best rargs bargs then
  1437. loop (loop b1 [rover,rargs]) rem
  1438. else (* equally specific *)
  1439. loop ( (rover,rargs) :: best ) rem
  1440. in
  1441. List.map fst (loop [] !rated)
  1442. end;;
  1443. module UnificationCallback = struct
  1444. let tf_stack = ref []
  1445. let check_call_params f el tl =
  1446. let rec loop acc el tl = match el,tl with
  1447. | e :: el, (n,_,t) :: tl ->
  1448. loop ((f e t) :: acc) el tl
  1449. | [], [] ->
  1450. acc
  1451. | [],_ ->
  1452. acc
  1453. | e :: el, [] ->
  1454. loop (e :: acc) el []
  1455. in
  1456. List.rev (loop [] el tl)
  1457. let check_call f el t = match follow t with
  1458. | TFun(args,_) ->
  1459. check_call_params f el args
  1460. | _ ->
  1461. el
  1462. let rec run f e =
  1463. let f e t =
  1464. (* TODO: I don't think this should cause errors on Flash target *)
  1465. (* if not (type_iseq e.etype t) then f e t else e *)
  1466. f e t
  1467. in
  1468. let check e = match e.eexpr with
  1469. | TBinop((OpAssign | OpAssignOp _ as op),e1,e2) ->
  1470. let e2 = f e2 e1.etype in
  1471. {e with eexpr = TBinop(op,e1,e2)}
  1472. | TVar(v,Some e) ->
  1473. let eo = Some (f e v.v_type) in
  1474. { e with eexpr = TVar(v,eo) }
  1475. | TCall(e1,el) ->
  1476. let el = check_call f el e1.etype in
  1477. {e with eexpr = TCall(e1,el)}
  1478. | TNew(c,tl,el) ->
  1479. begin try
  1480. let tcf,_ = get_constructor (fun cf -> apply_params c.cl_types tl cf.cf_type) c in
  1481. let el = check_call f el tcf in
  1482. {e with eexpr = TNew(c,tl,el)}
  1483. with Not_found ->
  1484. e
  1485. end
  1486. | TArrayDecl el ->
  1487. begin match follow e.etype with
  1488. | TInst({cl_path=[],"Array"},[t]) -> {e with eexpr = TArrayDecl(List.map (fun e -> f e t) el)}
  1489. | _ -> e
  1490. end
  1491. | TObjectDecl fl ->
  1492. begin match follow e.etype with
  1493. | TAnon an ->
  1494. let fl = List.map (fun (n,e) ->
  1495. let e = try
  1496. let t = (PMap.find n an.a_fields).cf_type in
  1497. f e t
  1498. with Not_found ->
  1499. e
  1500. in
  1501. n,e
  1502. ) fl in
  1503. { e with eexpr = TObjectDecl fl }
  1504. | _ -> e
  1505. end
  1506. | TReturn (Some e1) ->
  1507. begin match !tf_stack with
  1508. | tf :: _ -> { e with eexpr = TReturn (Some (f e1 tf.tf_type))}
  1509. | _ -> e
  1510. end
  1511. | _ ->
  1512. e
  1513. in
  1514. match e.eexpr with
  1515. | TFunction tf ->
  1516. tf_stack := tf :: !tf_stack;
  1517. let etf = {e with eexpr = TFunction({tf with tf_expr = run f tf.tf_expr})} in
  1518. tf_stack := List.tl !tf_stack;
  1519. etf
  1520. | _ ->
  1521. check (Type.map_expr (run f) e)
  1522. end;;
  1523. module DeprecationCheck = struct
  1524. let curclass = ref null_class
  1525. let warned_positions = Hashtbl.create 0
  1526. let print_deprecation_message com meta s p_usage =
  1527. let s = match meta with
  1528. | _,[EConst(String s),_],_ -> s
  1529. | _ -> Printf.sprintf "Usage of this %s is deprecated" s
  1530. in
  1531. if not (Hashtbl.mem warned_positions p_usage) then begin
  1532. Hashtbl.replace warned_positions p_usage true;
  1533. com.warning s p_usage;
  1534. end
  1535. let check_meta com meta s p_usage =
  1536. try
  1537. print_deprecation_message com (Meta.get Meta.Deprecated meta) s p_usage;
  1538. with Not_found ->
  1539. ()
  1540. let check_cf com cf p = check_meta com cf.cf_meta "field" p
  1541. let check_class com c p = if c != !curclass then check_meta com c.cl_meta "class" p
  1542. let check_enum com en p = check_meta com en.e_meta "enum" p
  1543. let check_ef com ef p = check_meta com ef.ef_meta "enum field" p
  1544. let check_typedef com t p = check_meta com t.t_meta "typedef" p
  1545. let check_module_type com mt p = match mt with
  1546. | TClassDecl c -> check_class com c p
  1547. | TEnumDecl en -> check_enum com en p
  1548. | _ -> ()
  1549. let run com =
  1550. let rec expr e = match e.eexpr with
  1551. | TField(e1,fa) ->
  1552. expr e1;
  1553. begin match fa with
  1554. | FStatic(c,cf) | FInstance(c,cf) ->
  1555. check_class com c e.epos;
  1556. check_cf com cf e.epos
  1557. | FAnon cf ->
  1558. check_cf com cf e.epos
  1559. | FClosure(co,cf) ->
  1560. (match co with None -> () | Some c -> check_class com c e.epos);
  1561. check_cf com cf e.epos
  1562. | FEnum(en,ef) ->
  1563. check_enum com en e.epos;
  1564. check_ef com ef e.epos;
  1565. | _ ->
  1566. ()
  1567. end
  1568. | TNew(c,_,el) ->
  1569. List.iter expr el;
  1570. check_class com c e.epos;
  1571. (match c.cl_constructor with None -> () | Some cf -> check_cf com cf e.epos)
  1572. | TTypeExpr(mt) | TCast(_,Some mt) ->
  1573. check_module_type com mt e.epos
  1574. | TMeta((Meta.Deprecated,_,_) as meta,e1) ->
  1575. print_deprecation_message com meta "field" e1.epos;
  1576. expr e1;
  1577. | _ ->
  1578. Type.iter expr e
  1579. in
  1580. List.iter (fun t -> match t with
  1581. | TClassDecl c ->
  1582. curclass := c;
  1583. let field cf = match cf.cf_expr with None -> () | Some e -> expr e in
  1584. (match c.cl_constructor with None -> () | Some cf -> field cf);
  1585. (match c.cl_init with None -> () | Some e -> expr e);
  1586. List.iter field c.cl_ordered_statics;
  1587. List.iter field c.cl_ordered_fields;
  1588. | _ ->
  1589. ()
  1590. ) com.types
  1591. end