codegen.ml 67 KB

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