codegen.ml 65 KB

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