codegen.ml 67 KB

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