typeload.ml 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322
  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. Build module structure : should be atomic - no type loading is possible
  28. *)
  29. let make_module ctx mpath file tdecls loadp =
  30. let decls = ref [] in
  31. let make_path name priv =
  32. if List.exists (fun (t,_) -> snd (t_path t) = name) !decls then error ("Type name " ^ name ^ " is already defined in this module") loadp;
  33. if priv then (fst mpath @ ["_" ^ snd mpath], name) else (fst mpath, name)
  34. in
  35. let m = {
  36. m_id = alloc_mid();
  37. m_path = mpath;
  38. m_types = [];
  39. m_extra = module_extra (Common.unique_full_path file) (Common.get_signature ctx.com) (file_time file) (if ctx.in_macro then MMacro else MCode);
  40. } in
  41. let pt = ref None in
  42. let rec make_decl acc decl =
  43. let p = snd decl in
  44. let acc = (match fst decl with
  45. | EImport _ | EUsing _ ->
  46. (match !pt with
  47. | None -> acc
  48. | Some pt ->
  49. display_error ctx "import and using may not appear after a type declaration" p;
  50. error "Previous type declaration found here" pt)
  51. | EClass d ->
  52. pt := Some p;
  53. let priv = List.mem HPrivate d.d_flags in
  54. let path = make_path d.d_name priv in
  55. let c = mk_class m path p in
  56. c.cl_module <- m;
  57. c.cl_private <- priv;
  58. c.cl_doc <- d.d_doc;
  59. c.cl_meta <- d.d_meta;
  60. decls := (TClassDecl c, decl) :: !decls;
  61. acc
  62. | EEnum d ->
  63. pt := Some p;
  64. let priv = List.mem EPrivate d.d_flags in
  65. let path = make_path d.d_name priv in
  66. let e = {
  67. e_path = path;
  68. e_module = m;
  69. e_pos = p;
  70. e_doc = d.d_doc;
  71. e_meta = d.d_meta;
  72. e_types = [];
  73. e_private = priv;
  74. e_extern = List.mem EExtern d.d_flags;
  75. e_constrs = PMap.empty;
  76. e_names = [];
  77. } in
  78. decls := (TEnumDecl e, decl) :: !decls;
  79. acc
  80. | ETypedef d ->
  81. pt := Some p;
  82. let priv = List.mem EPrivate d.d_flags in
  83. let path = make_path d.d_name priv in
  84. let t = {
  85. t_path = path;
  86. t_module = m;
  87. t_pos = p;
  88. t_doc = d.d_doc;
  89. t_private = priv;
  90. t_types = [];
  91. t_type = mk_mono();
  92. t_meta = d.d_meta;
  93. } in
  94. decls := (TTypeDecl t, decl) :: !decls;
  95. acc
  96. | EAbstract d ->
  97. let priv = List.mem APrivAbstract d.d_flags in
  98. let path = make_path d.d_name priv in
  99. let a = {
  100. a_path = path;
  101. a_private = priv;
  102. a_module = m;
  103. a_pos = p;
  104. a_doc = d.d_doc;
  105. a_types = [];
  106. a_meta = d.d_meta;
  107. a_from = [];
  108. a_to = [];
  109. a_ops = [];
  110. a_unops = [];
  111. a_impl = None;
  112. a_array = [];
  113. a_this = mk_mono();
  114. } in
  115. decls := (TAbstractDecl a, decl) :: !decls;
  116. match d.d_data with
  117. | [] -> acc
  118. | fields ->
  119. let rec loop = function
  120. | [] ->
  121. let params = List.map (fun t -> TPType (CTPath { tname = t.tp_name; tparams = []; tsub = None; tpackage = [] })) d.d_params in
  122. CTPath { tpackage = []; tname = d.d_name; tparams = params; tsub = None }
  123. | AIsType t :: _ -> t
  124. | _ :: l -> loop l
  125. in
  126. let this_t = loop d.d_flags in
  127. let fields = List.map (fun f ->
  128. let stat = List.mem AStatic f.cff_access in
  129. let p = f.cff_pos in
  130. match f.cff_kind with
  131. | FProp (("get" | "never"),("set" | "never"),_,_) ->
  132. (* TODO: hack to avoid issues with abstract property generation on As3 *)
  133. if Common.defined ctx.com Define.As3 then f.cff_meta <- (Meta.Extern,[],p) :: f.cff_meta;
  134. { f with cff_access = AStatic :: f.cff_access; cff_meta = (Meta.Impl,[],p) :: f.cff_meta }
  135. | FProp _ when not stat ->
  136. display_error ctx "Member property accessors must be get/set or never" p;
  137. f
  138. | FVar _ when not stat ->
  139. display_error ctx "Cannot declare member variable in abstract" p;
  140. f
  141. | FFun fu when f.cff_name = "new" && not stat ->
  142. let init p = (EVars ["this",Some this_t,None],p) in
  143. let ret p = (EReturn (Some (EConst (Ident "this"),p)),p) in
  144. if Meta.has Meta.MultiType a.a_meta then begin
  145. if List.mem AInline f.cff_access then error "MultiType constructors cannot be inline" f.cff_pos;
  146. if fu.f_expr <> None then error "MultiType constructors cannot have a body" f.cff_pos;
  147. end;
  148. let fu = {
  149. fu with
  150. f_expr = (match fu.f_expr with
  151. | None -> if Meta.has Meta.MultiType a.a_meta then Some (EConst (Ident "null"),p) else None
  152. | Some (EBlock [EBinop (OpAssign,(EConst (Ident "this"),_),e),_],_ | EBinop (OpAssign,(EConst (Ident "this"),_),e),_) ->
  153. Some (EReturn (Some e), pos e)
  154. | Some (EBlock el,p) -> Some (EBlock (init p :: el @ [ret p]),p)
  155. | Some e -> Some (EBlock [init p;e;ret p],p)
  156. );
  157. f_type = Some this_t;
  158. } in
  159. { f with cff_name = "_new"; cff_access = AStatic :: f.cff_access; cff_kind = FFun fu; cff_meta = (Meta.Impl,[],p) :: f.cff_meta }
  160. | FFun fu when not stat ->
  161. if Meta.has Meta.From f.cff_meta then error "@:from cast functions must be static" f.cff_pos;
  162. let fu = { fu with f_args = ("this",false,Some this_t,None) :: fu.f_args } in
  163. { f with cff_kind = FFun fu; cff_access = AStatic :: f.cff_access; cff_meta = (Meta.Impl,[],p) :: f.cff_meta }
  164. | _ ->
  165. f
  166. ) fields in
  167. let acc = make_decl acc (EClass { d_name = d.d_name ^ "_Impl_"; d_flags = [HPrivate]; d_data = fields; d_doc = None; d_params = []; d_meta = [] },p) in
  168. (match !decls with
  169. | (TClassDecl c,_) :: _ ->
  170. (try c.cl_meta <- (Meta.get Meta.Build a.a_meta) :: c.cl_meta with Not_found -> ());
  171. a.a_impl <- Some c;
  172. c.cl_kind <- KAbstractImpl a
  173. | _ -> assert false);
  174. acc
  175. ) in
  176. decl :: acc
  177. in
  178. let tdecls = List.fold_left make_decl [] tdecls in
  179. let decls = List.rev !decls in
  180. m.m_types <- List.map fst decls;
  181. m, decls, List.rev tdecls
  182. let parse_file com file p =
  183. let ch = (try open_in_bin file with _ -> error ("Could not open " ^ file) p) in
  184. let t = Common.timer "parsing" in
  185. Lexer.init file;
  186. incr stats.s_files_parsed;
  187. let data = (try Parser.parse com (Lexing.from_channel ch) with e -> close_in ch; t(); raise e) in
  188. close_in ch;
  189. t();
  190. Common.log com ("Parsed " ^ file);
  191. data
  192. let parse_hook = ref parse_file
  193. let type_module_hook = ref (fun _ _ _ -> None)
  194. let type_function_params_rec = ref (fun _ _ _ _ -> assert false)
  195. let return_partial_type = ref false
  196. let type_function_param ctx t e opt p =
  197. if opt then
  198. let e = (match e with None -> Some (EConst (Ident "null"),p) | _ -> e) in
  199. ctx.t.tnull t, e
  200. else
  201. t, e
  202. let type_var_field ctx t e stat p =
  203. if stat then ctx.curfun <- FunStatic;
  204. let e = type_expr ctx e (WithType t) in
  205. unify ctx e.etype t p;
  206. match t with
  207. | TType ({ t_path = ([],"UInt") },[]) | TAbstract ({ a_path = ([],"UInt") },[]) when stat -> { e with etype = t }
  208. | _ -> e
  209. let apply_macro ctx mode path el p =
  210. let cpath, meth = (match List.rev (ExtString.String.nsplit path ".") with
  211. | meth :: name :: pack -> (List.rev pack,name), meth
  212. | _ -> error "Invalid macro path" p
  213. ) in
  214. ctx.g.do_macro ctx mode cpath meth el p
  215. (** since load_type_def and load_instance are used in PASS2, they should not access the structure of a type **)
  216. (*
  217. load a type or a subtype definition
  218. *)
  219. let rec load_type_def ctx p t =
  220. let no_pack = t.tpackage = [] in
  221. let tname = (match t.tsub with None -> t.tname | Some n -> n) in
  222. try
  223. if t.tsub <> None then raise Not_found;
  224. List.find (fun t2 ->
  225. let tp = t_path t2 in
  226. tp = (t.tpackage,tname) || (no_pack && snd tp = tname)
  227. ) (ctx.m.curmod.m_types @ ctx.m.module_types)
  228. with
  229. Not_found ->
  230. let next() =
  231. let t, m = (try
  232. t, ctx.g.do_load_module ctx (t.tpackage,t.tname) p
  233. with Error (Module_not_found _,p2) as e when p == p2 ->
  234. match t.tpackage with
  235. | "std" :: l ->
  236. let t = { t with tpackage = l } in
  237. t, ctx.g.do_load_module ctx (t.tpackage,t.tname) p
  238. | _ -> raise e
  239. ) in
  240. let tpath = (t.tpackage,tname) in
  241. try
  242. List.find (fun t -> not (t_infos t).mt_private && t_path t = tpath) m.m_types
  243. with
  244. Not_found -> raise (Error (Type_not_found (m.m_path,tname),p))
  245. in
  246. (* lookup in wildcard imported packages *)
  247. try
  248. if not no_pack then raise Exit;
  249. let rec loop = function
  250. | [] -> raise Exit
  251. | wp :: l ->
  252. try
  253. load_type_def ctx p { t with tpackage = wp }
  254. with
  255. | Error (Module_not_found _,p2)
  256. | Error (Type_not_found _,p2) when p == p2 -> loop l
  257. in
  258. loop ctx.m.wildcard_packages
  259. with Exit ->
  260. (* lookup in our own package - and its upper packages *)
  261. let rec loop = function
  262. | [] -> raise Exit
  263. | (_ :: lnext) as l ->
  264. try
  265. load_type_def ctx p { t with tpackage = List.rev l }
  266. with
  267. | Error (Module_not_found _,p2)
  268. | Error (Type_not_found _,p2) when p == p2 -> loop lnext
  269. in
  270. try
  271. if not no_pack then raise Exit;
  272. (match fst ctx.m.curmod.m_path with
  273. | [] -> raise Exit
  274. | x :: _ ->
  275. (* this can occur due to haxe remoting : a module can be
  276. already defined in the "js" package and is not allowed
  277. to access the js classes *)
  278. try
  279. (match PMap.find x ctx.com.package_rules with
  280. | Forbidden -> raise Exit
  281. | _ -> ())
  282. with Not_found -> ());
  283. loop (List.rev (fst ctx.m.curmod.m_path));
  284. with
  285. Exit -> next()
  286. let check_param_constraints ctx types t pl c p =
  287. match follow t with
  288. | TMono _ -> ()
  289. | _ ->
  290. let ctl = (match c.cl_kind with KTypeParameter l -> l | _ -> []) in
  291. List.iter (fun ti ->
  292. let ti = apply_params types pl ti in
  293. let ti = (match follow ti with
  294. | TInst ({ cl_kind = KGeneric }as c,pl) ->
  295. (* if we solve a generic contraint, let's substitute with the actual generic instance before unifying *)
  296. let _,_, f = ctx.g.do_build_instance ctx (TClassDecl c) p in
  297. f pl
  298. | _ -> ti
  299. ) in
  300. unify ctx t ti p
  301. ) ctl
  302. (* build an instance from a full type *)
  303. let rec load_instance ctx t p allow_no_params =
  304. try
  305. if t.tpackage <> [] || t.tsub <> None then raise Not_found;
  306. let pt = List.assoc t.tname ctx.type_params in
  307. if t.tparams <> [] then error ("Class type parameter " ^ t.tname ^ " can't have parameters") p;
  308. pt
  309. with Not_found ->
  310. let mt = load_type_def ctx p t in
  311. let is_generic = match mt with TClassDecl {cl_kind = KGeneric} -> true | _ -> false in
  312. let types , path , f = ctx.g.do_build_instance ctx mt p in
  313. if allow_no_params && t.tparams = [] then begin
  314. let pl = ref [] in
  315. pl := List.map (fun (name,t) ->
  316. match follow t with
  317. | TInst (c,_) ->
  318. let t = mk_mono() in
  319. if c.cl_kind <> KTypeParameter [] || is_generic then delay ctx PCheckConstraint (fun() -> check_param_constraints ctx types t (!pl) c p);
  320. t;
  321. | _ -> assert false
  322. ) types;
  323. f (!pl)
  324. end else if path = ([],"Dynamic") then
  325. match t.tparams with
  326. | [] -> t_dynamic
  327. | [TPType t] -> TDynamic (load_complex_type ctx p t)
  328. | _ -> error "Too many parameters for Dynamic" p
  329. else begin
  330. if List.length types <> List.length t.tparams then error ("Invalid number of type parameters for " ^ s_type_path path) p;
  331. let tparams = List.map (fun t ->
  332. match t with
  333. | TPExpr e ->
  334. let name = (match fst e with
  335. | EConst (String s) -> "S" ^ s
  336. | EConst (Int i) -> "I" ^ i
  337. | EConst (Float f) -> "F" ^ f
  338. | _ -> "Expr"
  339. ) in
  340. let c = mk_class null_module ([],name) p in
  341. c.cl_kind <- KExpr e;
  342. TInst (c,[])
  343. | TPType t -> load_complex_type ctx p t
  344. ) t.tparams in
  345. let params = List.map2 (fun t (name,t2) ->
  346. let isconst = (match t with TInst ({ cl_kind = KExpr _ },_) -> true | _ -> false) in
  347. if isconst <> (name = "Const") && t != t_dynamic then error (if isconst then "Constant value unexpected here" else "Constant value excepted as type parameter") p;
  348. match follow t2 with
  349. | TInst ({ cl_kind = KTypeParameter [] }, []) when not is_generic ->
  350. t
  351. | TInst (c,[]) ->
  352. let r = exc_protect ctx (fun r ->
  353. r := (fun() -> t);
  354. delay ctx PCheckConstraint (fun() -> check_param_constraints ctx types t tparams c p);
  355. t
  356. ) "constraint" in
  357. delay ctx PForce (fun () -> ignore(!r()));
  358. TLazy r
  359. | _ -> assert false
  360. ) tparams types in
  361. f params
  362. end
  363. (*
  364. build an instance from a complex type
  365. *)
  366. and load_complex_type ctx p t =
  367. match t with
  368. | CTParent t -> load_complex_type ctx p t
  369. | CTPath t -> load_instance ctx t p false
  370. | CTOptional _ -> error "Optional type not allowed here" p
  371. | CTExtend (t,l) ->
  372. (match load_complex_type ctx p (CTAnonymous l) with
  373. | TAnon a ->
  374. let rec loop t =
  375. match follow t with
  376. | TInst (c,tl) ->
  377. let c2 = mk_class null_module (fst c.cl_path,"+" ^ snd c.cl_path) p in
  378. c2.cl_private <- true;
  379. PMap.iter (fun f _ ->
  380. try
  381. ignore(class_field c f);
  382. error ("Cannot redefine field " ^ f) p
  383. with
  384. Not_found -> ()
  385. ) a.a_fields;
  386. (* do NOT tag as extern - for protect *)
  387. c2.cl_kind <- KExtension (c,tl);
  388. c2.cl_super <- Some (c,tl);
  389. c2.cl_fields <- a.a_fields;
  390. TInst (c2,[])
  391. | TMono _ ->
  392. error "Loop found in cascading signatures definitions. Please change order/import" p
  393. | TAnon a2 ->
  394. PMap.iter (fun f _ ->
  395. if PMap.mem f a2.a_fields then error ("Cannot redefine field " ^ f) p
  396. ) a.a_fields;
  397. mk_anon (PMap.foldi PMap.add a.a_fields a2.a_fields)
  398. | _ -> error "Can only extend classes and structures" p
  399. in
  400. let i = load_instance ctx t p false in
  401. let tr = ref None in
  402. let t = TMono tr in
  403. let r = exc_protect ctx (fun r ->
  404. r := (fun _ -> t);
  405. tr := Some (loop i);
  406. t
  407. ) "constraint" in
  408. delay ctx PForce (fun () -> ignore(!r()));
  409. TLazy r
  410. | _ -> assert false)
  411. | CTAnonymous l ->
  412. let rec loop acc f =
  413. let n = f.cff_name in
  414. let p = f.cff_pos in
  415. if PMap.mem n acc then error ("Duplicate field declaration : " ^ n) p;
  416. let topt = function
  417. | None -> error ("Explicit type required for field " ^ n) p
  418. | Some t -> load_complex_type ctx p t
  419. in
  420. let no_expr = function
  421. | None -> ()
  422. | Some (_,p) -> error "Expression not allowed here" p
  423. in
  424. let pub = ref true in
  425. let dyn = ref false in
  426. let params = ref [] in
  427. List.iter (fun a ->
  428. match a with
  429. | APublic -> ()
  430. | APrivate -> pub := false;
  431. | ADynamic when (match f.cff_kind with FFun _ -> true | _ -> false) -> dyn := true
  432. | AStatic | AOverride | AInline | ADynamic | AMacro -> error ("Invalid access " ^ Ast.s_access a) p
  433. ) f.cff_access;
  434. let t , access = (match f.cff_kind with
  435. | FVar (Some (CTPath({tpackage=[];tname="Void"})), _) | FProp (_,_,Some (CTPath({tpackage=[];tname="Void"})),_) ->
  436. error "Fields of type Void are not allowed in structures" p
  437. | FVar (t, e) ->
  438. no_expr e;
  439. topt t, Var { v_read = AccNormal; v_write = AccNormal }
  440. | FFun fd ->
  441. params := (!type_function_params_rec) ctx fd f.cff_name p;
  442. no_expr fd.f_expr;
  443. let old = ctx.type_params in
  444. ctx.type_params <- !params @ old;
  445. let args = List.map (fun (name,o,t,e) -> no_expr e; name, o, topt t) fd.f_args in
  446. let t = TFun (args,topt fd.f_type), Method (if !dyn then MethDynamic else MethNormal) in
  447. ctx.type_params <- old;
  448. t
  449. | FProp (i1,i2,t,e) ->
  450. no_expr e;
  451. let access m get =
  452. match m with
  453. | "null" -> AccNo
  454. | "never" -> AccNever
  455. | "default" -> AccNormal
  456. | "dynamic" -> AccCall
  457. | "get" when get -> AccCall
  458. | "set" when not get -> AccCall
  459. | x when get && x = "get_" ^ n -> AccCall
  460. | x when not get && x = "set_" ^ n -> AccCall
  461. | _ ->
  462. error "Custom property access is no longer supported in Haxe 3" f.cff_pos;
  463. in
  464. let t = (match t with None -> error "Type required for structure property" p | Some t -> t) in
  465. load_complex_type ctx p t, Var { v_read = access i1 true; v_write = access i2 false }
  466. ) in
  467. let cf = {
  468. cf_name = n;
  469. cf_type = t;
  470. cf_pos = p;
  471. cf_public = !pub;
  472. cf_kind = access;
  473. cf_params = !params;
  474. cf_expr = None;
  475. cf_doc = f.cff_doc;
  476. cf_meta = f.cff_meta;
  477. cf_overloads = [];
  478. } in
  479. init_meta_overloads ctx cf;
  480. PMap.add n cf acc
  481. in
  482. mk_anon (List.fold_left loop PMap.empty l)
  483. | CTFunction (args,r) ->
  484. match args with
  485. | [CTPath { tpackage = []; tparams = []; tname = "Void" }] ->
  486. TFun ([],load_complex_type ctx p r)
  487. | _ ->
  488. TFun (List.map (fun t ->
  489. let t, opt = (match t with CTOptional t -> t, true | _ -> t,false) in
  490. "",opt,load_complex_type ctx p t
  491. ) args,load_complex_type ctx p r)
  492. and init_meta_overloads ctx cf =
  493. let overloads = ref [] in
  494. cf.cf_meta <- List.filter (fun m ->
  495. match m with
  496. | (Meta.Overload,[(EFunction (fname,f),p)],_) ->
  497. if fname <> None then error "Function name must not be part of @:overload" p;
  498. (match f.f_expr with Some (EBlock [], _) -> () | _ -> error "Overload must only declare an empty method body {}" p);
  499. let old = ctx.type_params in
  500. (match cf.cf_params with
  501. | [] -> ()
  502. | l -> ctx.type_params <- List.filter (fun t -> not (List.mem t l)) ctx.type_params);
  503. let params = (!type_function_params_rec) ctx f cf.cf_name p in
  504. ctx.type_params <- params @ ctx.type_params;
  505. let topt = function None -> error "Explicit type required" p | Some t -> load_complex_type ctx p t in
  506. let args = List.map (fun (a,opt,t,_) -> a,opt,topt t) f.f_args in
  507. overloads := (args,topt f.f_type, params) :: !overloads;
  508. ctx.type_params <- old;
  509. false
  510. | (Meta.Overload,[],_) when ctx.com.config.pf_overload ->
  511. let topt (n,_,t) = match t with | TMono t when !t = None -> error ("Explicit type required for overload functions\nFor function argument '" ^ n ^ "'") cf.cf_pos | _ -> () in
  512. (match follow cf.cf_type with
  513. | TFun (args,_) -> List.iter topt args
  514. | _ -> () (* could be a variable *));
  515. true
  516. | (Meta.Overload,[],p) ->
  517. error "This platform does not support this kind of overload declaration. Try @:overload(function()... {}) instead" p
  518. | (Meta.Overload,_,p) ->
  519. error "Invalid @:overload metadata format" p
  520. | _ ->
  521. true
  522. ) cf.cf_meta;
  523. cf.cf_overloads <- List.map (fun (args,ret,params) -> { cf with cf_type = TFun (args,ret); cf_params = params }) (List.rev !overloads)
  524. let hide_types ctx =
  525. let old_m = ctx.m in
  526. let old_type_params = ctx.type_params in
  527. ctx.m <- {
  528. curmod = ctx.g.std;
  529. module_types = [];
  530. module_using = [];
  531. module_globals = PMap.empty;
  532. wildcard_packages = [];
  533. };
  534. ctx.type_params <- [];
  535. (fun() ->
  536. ctx.m <- old_m;
  537. ctx.type_params <- old_type_params;
  538. )
  539. (*
  540. load a type while ignoring the current imports or local types
  541. *)
  542. let load_core_type ctx name =
  543. let show = hide_types ctx in
  544. let t = load_instance ctx { tpackage = []; tname = name; tparams = []; tsub = None; } null_pos false in
  545. show();
  546. t
  547. let t_iterator ctx =
  548. let show = hide_types ctx in
  549. match load_type_def ctx null_pos { tpackage = []; tname = "Iterator"; tparams = []; tsub = None } with
  550. | TTypeDecl t ->
  551. show();
  552. if List.length t.t_types <> 1 then assert false;
  553. let pt = mk_mono() in
  554. apply_params t.t_types [pt] t.t_type, pt
  555. | _ ->
  556. assert false
  557. (*
  558. load either a type t or Null<Unknown> if not defined
  559. *)
  560. let load_type_opt ?(opt=false) ctx p t =
  561. let t = (match t with None -> mk_mono() | Some t -> load_complex_type ctx p t) in
  562. if opt then ctx.t.tnull t else t
  563. (* ---------------------------------------------------------------------- *)
  564. (* Structure check *)
  565. let valid_redefinition ctx f1 t1 f2 t2 =
  566. let valid t1 t2 =
  567. Type.unify t1 t2;
  568. if is_null t1 <> is_null t2 then raise (Unify_error [Cannot_unify (t1,t2)]);
  569. in
  570. let t1, t2 = (match f1.cf_params, f2.cf_params with
  571. | [], [] -> t1, t2
  572. | l1, l2 when List.length l1 = List.length l2 ->
  573. let to_check = ref [] in
  574. let monos = List.map2 (fun (name,p1) (_,p2) ->
  575. (match follow p1, follow p2 with
  576. | TInst ({ cl_kind = KTypeParameter ct1 } as c1,pl1), TInst ({ cl_kind = KTypeParameter ct2 } as c2,pl2) ->
  577. (match ct1, ct2 with
  578. | [], [] -> ()
  579. | _, _ when List.length ct1 = List.length ct2 ->
  580. (* if same constraints, they are the same type *)
  581. let check monos =
  582. List.iter2 (fun t1 t2 ->
  583. try
  584. let t1 = apply_params l1 monos (apply_params c1.cl_types pl1 t1) in
  585. let t2 = apply_params l2 monos (apply_params c2.cl_types pl2 t2) in
  586. type_eq EqStrict t1 t2
  587. with Unify_error l ->
  588. raise (Unify_error (Unify_custom "Constraints differ" :: l))
  589. ) ct1 ct2
  590. in
  591. to_check := check :: !to_check;
  592. | _ ->
  593. raise (Unify_error [Unify_custom "Different number of constraints"]))
  594. | _ -> ());
  595. TInst (mk_class null_module ([],name) Ast.null_pos,[])
  596. ) l1 l2 in
  597. List.iter (fun f -> f monos) !to_check;
  598. apply_params l1 monos t1, apply_params l2 monos t2
  599. | _ ->
  600. (* ignore type params, will create other errors later *)
  601. t1, t2
  602. ) in
  603. match follow t1, follow t2 with
  604. | TFun (args1,r1) , TFun (args2,r2) when List.length args1 = List.length args2 -> (try
  605. List.iter2 (fun (n,o1,a1) (_,o2,a2) ->
  606. if o1 <> o2 then raise (Unify_error [Not_matching_optional n]);
  607. (try valid a2 a1 with Unify_error _ -> raise (Unify_error [Cannot_unify(a1,a2)]))
  608. ) args1 args2;
  609. valid r1 r2
  610. with Unify_error l ->
  611. raise (Unify_error (Cannot_unify (t1,t2) :: l)))
  612. | _ , _ ->
  613. (* in case args differs, or if an interface var *)
  614. type_eq EqStrict t1 t2;
  615. if is_null t1 <> is_null t2 then raise (Unify_error [Cannot_unify (t1,t2)])
  616. let copy_meta meta_src meta_target sl =
  617. let meta = ref meta_target in
  618. List.iter (fun (m,e,p) ->
  619. if List.mem m sl then meta := (m,e,p) :: !meta
  620. ) meta_src;
  621. !meta
  622. (** retrieves all overloads from class c and field i, as (Type.t * tclass_field) list *)
  623. let rec get_overloads c i =
  624. let ret = try
  625. let f = PMap.find i c.cl_fields in
  626. List.filter (fun (_,f) -> not (List.memq f c.cl_overrides)) ((f.cf_type, f) :: (List.map (fun f -> f.cf_type, f) f.cf_overloads))
  627. with | Not_found -> []
  628. in
  629. match c.cl_super with
  630. | None when c.cl_interface ->
  631. let ifaces = List.concat (List.map (fun (c,tl) ->
  632. List.map (fun (t,f) -> apply_params c.cl_types tl t, f) (get_overloads c i)
  633. ) c.cl_implements) in
  634. ret @ ifaces
  635. | None -> ret
  636. | Some (c,tl) ->
  637. ret @ ( List.map (fun (t,f) -> apply_params c.cl_types tl t, f) (get_overloads c i) )
  638. let same_overload_args t1 t2 f1 f2 =
  639. if List.length f1.cf_params <> List.length f2.cf_params then
  640. false
  641. else
  642. let rec follow_skip_null t = match t with
  643. | TMono r ->
  644. (match !r with
  645. | Some t -> follow_skip_null t
  646. | _ -> t)
  647. | TLazy f ->
  648. follow_skip_null (!f())
  649. | TType ({ t_path = [],"Null" } as t, [p]) ->
  650. TType(t,[follow p])
  651. | TType (t,tl) ->
  652. follow_skip_null (apply_params t.t_types tl t.t_type)
  653. | _ -> t
  654. in
  655. let same_arg t1 t2 =
  656. let t1 = follow_skip_null t1 in
  657. let t2 = follow_skip_null t2 in
  658. match follow_skip_null t1, follow_skip_null t2 with
  659. | TType _, TType _ -> type_iseq t1 t2
  660. | TType _, _
  661. | _, TType _ -> false
  662. | _ -> type_iseq t1 t2
  663. in
  664. match follow (apply_params f1.cf_params (List.map (fun (_,t) -> t) f2.cf_params) t1), follow t2 with
  665. | TFun(a1,_), TFun(a2,_) ->
  666. (try
  667. List.for_all2 (fun (_,_,t1) (_,_,t2) ->
  668. same_arg t1 t2) a1 a2
  669. with | Invalid_argument("List.for_all2") ->
  670. false)
  671. | _ -> assert false
  672. let check_overloads ctx c =
  673. (* check if field with same signature was declared more than once *)
  674. List.iter (fun f ->
  675. if Meta.has Meta.Overload f.cf_meta then
  676. List.iter (fun f2 ->
  677. try
  678. ignore (List.find (fun f3 -> f3 != f2 && same_overload_args f2.cf_type f3.cf_type f2 f3) (f :: f.cf_overloads));
  679. display_error ctx ("Another overloaded field of same signature was already declared : " ^ f2.cf_name) f2.cf_pos
  680. with | Not_found -> ()
  681. ) (f :: f.cf_overloads)) (c.cl_ordered_fields @ c.cl_ordered_statics)
  682. let check_overriding ctx c =
  683. let p = c.cl_pos in
  684. match c.cl_super with
  685. | None ->
  686. (match c.cl_overrides with
  687. | [] -> ()
  688. | i :: _ ->
  689. display_error ctx ("Field " ^ i.cf_name ^ " is declared 'override' but doesn't override any field") p)
  690. | Some (csup,params) ->
  691. PMap.iter (fun i f ->
  692. let check_field f get_super_field is_overload = try
  693. let p = f.cf_pos in
  694. (if is_overload && not (Meta.has Meta.Overload f.cf_meta) then
  695. display_error ctx ("Missing @:overload declaration for field " ^ i) p);
  696. let t, f2 = get_super_field csup i in
  697. (* allow to define fields that are not defined for this platform version in superclass *)
  698. (match f2.cf_kind with
  699. | Var { v_read = AccRequire _ } -> raise Not_found;
  700. | _ -> ());
  701. if ctx.com.config.pf_overload && (Meta.has Meta.Overload f2.cf_meta && not (Meta.has Meta.Overload f.cf_meta)) then
  702. display_error ctx ("Field " ^ i ^ " should be declared with @:overload since it was already declared as @:overload in superclass") p
  703. else if not (List.memq f c.cl_overrides) then
  704. display_error ctx ("Field " ^ i ^ " should be declared with 'override' since it is inherited from superclass") p
  705. else if not f.cf_public && f2.cf_public then
  706. display_error ctx ("Field " ^ i ^ " has less visibility (public/private) than superclass one") p
  707. else (match f.cf_kind, f2.cf_kind with
  708. | _, Method MethInline ->
  709. display_error ctx ("Field " ^ i ^ " is inlined and cannot be overridden") p
  710. | a, b when a = b -> ()
  711. | Method MethInline, Method MethNormal ->
  712. () (* allow to redefine a method as inlined *)
  713. | _ ->
  714. display_error ctx ("Field " ^ i ^ " has different property access than in superclass") p);
  715. try
  716. let t = apply_params csup.cl_types params t in
  717. valid_redefinition ctx f f.cf_type f2 t
  718. with
  719. Unify_error l ->
  720. display_error ctx ("Field " ^ i ^ " overloads parent class with different or incomplete type") p;
  721. display_error ctx (error_msg (Unify l)) p;
  722. with
  723. Not_found ->
  724. if List.memq f c.cl_overrides then
  725. let msg = if is_overload then
  726. ("Field " ^ i ^ " is declared 'override' but no compatible overload was found")
  727. else
  728. ("Field " ^ i ^ " is declared 'override' but doesn't override any field")
  729. in
  730. display_error ctx msg p
  731. in
  732. if ctx.com.config.pf_overload && Meta.has Meta.Overload f.cf_meta then begin
  733. let overloads = get_overloads csup i in
  734. List.iter (fun (t,f2) ->
  735. (* check if any super class fields are vars *)
  736. match f2.cf_kind with
  737. | Var _ ->
  738. display_error ctx ("A variable named '" ^ f2.cf_name ^ "' was already declared in a superclass") f.cf_pos
  739. | _ -> ()
  740. ) overloads;
  741. List.iter (fun f ->
  742. (* find the exact field being overridden *)
  743. check_field f (fun csup i ->
  744. List.find (fun (t,f2) ->
  745. same_overload_args f.cf_type (apply_params csup.cl_types params t) f f2
  746. ) overloads
  747. ) true
  748. ) f.cf_overloads
  749. end else
  750. check_field f (fun csup i ->
  751. let _, t, f2 = raw_class_field (fun f -> f.cf_type) csup i in
  752. t, f2) false
  753. ) c.cl_fields
  754. let class_field_no_interf c i =
  755. try
  756. let f = PMap.find i c.cl_fields in
  757. f.cf_type , f
  758. with Not_found ->
  759. match c.cl_super with
  760. | None ->
  761. raise Not_found
  762. | Some (c,tl) ->
  763. (* rec over class_field *)
  764. let _, t , f = raw_class_field (fun f -> f.cf_type) c i in
  765. apply_params c.cl_types tl t , f
  766. let rec check_interface ctx c intf params =
  767. let p = c.cl_pos in
  768. let rec check_field i f =
  769. (if ctx.com.config.pf_overload then
  770. List.iter (function
  771. | f2 when f != f2 ->
  772. check_field i f2
  773. | _ -> ()) f.cf_overloads);
  774. let is_overload = ref false in
  775. try
  776. let t2, f2 = class_field_no_interf c i in
  777. let t2, f2 =
  778. if ctx.com.config.pf_overload && (f2.cf_overloads <> [] || Meta.has Meta.Overload f2.cf_meta) then
  779. let overloads = get_overloads c i in
  780. is_overload := true;
  781. let t = (apply_params intf.cl_types params f.cf_type) in
  782. List.find (fun (t1,f1) -> same_overload_args t t1 f f1) overloads
  783. else
  784. t2, f2
  785. in
  786. ignore(follow f2.cf_type); (* force evaluation *)
  787. let p = (match f2.cf_expr with None -> p | Some e -> e.epos) in
  788. let mkind = function
  789. | MethNormal | MethInline -> 0
  790. | MethDynamic -> 1
  791. | MethMacro -> 2
  792. in
  793. if f.cf_public && not f2.cf_public then
  794. display_error ctx ("Field " ^ i ^ " should be public as requested by " ^ s_type_path intf.cl_path) p
  795. else if not (unify_kind f2.cf_kind f.cf_kind) || not (match f.cf_kind, f2.cf_kind with Var _ , Var _ -> true | Method m1, Method m2 -> mkind m1 = mkind m2 | _ -> false) then
  796. display_error ctx ("Field " ^ i ^ " has different property access than in " ^ s_type_path intf.cl_path ^ " (" ^ s_kind f2.cf_kind ^ " should be " ^ s_kind f.cf_kind ^ ")") p
  797. else try
  798. valid_redefinition ctx f2 t2 f (apply_params intf.cl_types params f.cf_type)
  799. with
  800. Unify_error l ->
  801. display_error ctx ("Field " ^ i ^ " has different type than in " ^ s_type_path intf.cl_path) p;
  802. display_error ctx (error_msg (Unify l)) p;
  803. with
  804. | Not_found when not c.cl_interface ->
  805. let msg = if !is_overload then
  806. let ctx = print_context() in
  807. let args = match follow f.cf_type with | TFun(args,_) -> String.concat ", " (List.map (fun (n,o,t) -> (if o then "?" else "") ^ n ^ " : " ^ (s_type ctx t)) args) | _ -> assert false in
  808. "No suitable overload for " ^ i ^ "( " ^ args ^ " ), as needed by " ^ s_type_path intf.cl_path ^ " was found"
  809. else
  810. ("Field " ^ i ^ " needed by " ^ s_type_path intf.cl_path ^ " is missing")
  811. in
  812. display_error ctx msg p
  813. | Not_found -> ()
  814. in
  815. PMap.iter check_field intf.cl_fields;
  816. List.iter (fun (i2,p2) ->
  817. check_interface ctx c i2 (List.map (apply_params intf.cl_types params) p2)
  818. ) intf.cl_implements
  819. let check_interfaces ctx c =
  820. match c.cl_path with
  821. | "Proxy" :: _ , _ -> ()
  822. | _ ->
  823. List.iter (fun (intf,params) -> check_interface ctx c intf params) c.cl_implements
  824. let rec return_flow ctx e =
  825. let error() = display_error ctx "A return is missing here" e.epos; raise Exit in
  826. let return_flow = return_flow ctx in
  827. match e.eexpr with
  828. | TReturn _ | TThrow _ -> ()
  829. | TParenthesis e ->
  830. return_flow e
  831. | TBlock el ->
  832. let rec loop = function
  833. | [] -> error()
  834. | [e] -> return_flow e
  835. | { eexpr = TReturn _ } :: _ | { eexpr = TThrow _ } :: _ -> ()
  836. | _ :: l -> loop l
  837. in
  838. loop el
  839. | TIf (_,e1,Some e2) ->
  840. return_flow e1;
  841. return_flow e2;
  842. | TSwitch (v,cases,Some e) ->
  843. List.iter (fun (_,e) -> return_flow e) cases;
  844. return_flow e
  845. | TSwitch (e,cases,None) when (match follow e.etype with TEnum _ -> true | _ -> false) ->
  846. List.iter (fun (_,e) -> return_flow e) cases;
  847. | TMatch (_,_,cases,def) ->
  848. List.iter (fun (_,_,e) -> return_flow e) cases;
  849. (match def with None -> () | Some e -> return_flow e)
  850. | TTry (e,cases) ->
  851. return_flow e;
  852. List.iter (fun (_,e) -> return_flow e) cases;
  853. | TWhile({eexpr = (TConst (TBool true))},e,_) ->
  854. (* a special case for "inifite" while loops that have no break *)
  855. let rec loop e = match e.eexpr with
  856. (* ignore nested loops to not accidentally get one of its breaks *)
  857. | TWhile _ | TFor _ -> ()
  858. | TBreak -> error()
  859. | _ -> Type.iter loop e
  860. in
  861. loop e
  862. | _ ->
  863. error()
  864. (* ---------------------------------------------------------------------- *)
  865. (* PASS 1 & 2 : Module and Class Structure *)
  866. let set_heritance ctx c herits p =
  867. let ctx = { ctx with curclass = c; type_params = c.cl_types; } in
  868. let process_meta csup =
  869. List.iter (fun m ->
  870. match m with
  871. | Meta.Final, _, _ -> if not (Meta.has Meta.Hack c.cl_meta || (match c.cl_kind with KTypeParameter _ -> true | _ -> false)) then error "Cannot extend a final class" p;
  872. | Meta.AutoBuild, el, p -> c.cl_meta <- (Meta.Build,el,p) :: m :: c.cl_meta
  873. | _ -> ()
  874. ) csup.cl_meta
  875. in
  876. let has_interf = ref false in
  877. let rec loop = function
  878. | HPrivate | HExtern | HInterface ->
  879. ()
  880. | HExtends t ->
  881. if c.cl_super <> None then error "Cannot extend several classes" p;
  882. let t = load_instance ctx t p false in
  883. (match follow t with
  884. | TInst ({ cl_path = [],"Array" },_)
  885. | TInst ({ cl_path = [],"String" },_)
  886. | TInst ({ cl_path = [],"Date" },_)
  887. | TInst ({ cl_path = [],"Xml" },_) when ((not (platform ctx.com Cpp)) && (match c.cl_path with ("mt" | "flash") :: _ , _ -> false | _ -> true)) ->
  888. error "Cannot extend basic class" p;
  889. | TInst (csup,params) ->
  890. csup.cl_build();
  891. if is_parent c csup then error "Recursive class" p;
  892. process_meta csup;
  893. (* interface extends are listed in cl_implements ! *)
  894. if c.cl_interface then begin
  895. if not csup.cl_interface then error "Cannot extend by using a class" p;
  896. c.cl_implements <- (csup,params) :: c.cl_implements
  897. end else begin
  898. if csup.cl_interface then error "Cannot extend by using an interface" p;
  899. c.cl_super <- Some (csup,params)
  900. end
  901. | _ -> error "Should extend by using a class" p)
  902. | HImplements t ->
  903. let t = load_instance ctx t p false in
  904. (match follow t with
  905. | TInst ({ cl_path = [],"ArrayAccess"; cl_extern = true; },[t]) ->
  906. if c.cl_array_access <> None then error "Duplicate array access" p;
  907. c.cl_array_access <- Some t
  908. | TInst (intf,params) ->
  909. intf.cl_build();
  910. if is_parent c intf then error "Recursive class" p;
  911. if c.cl_interface then error "Interfaces cannot implement another interface (use extends instead)" p;
  912. if not intf.cl_interface then error "You can only implements an interface" p;
  913. process_meta intf;
  914. c.cl_implements <- (intf, params) :: c.cl_implements;
  915. if not !has_interf then begin
  916. delay ctx PForce (fun() -> check_interfaces ctx c);
  917. has_interf := true;
  918. end
  919. | TDynamic t ->
  920. if c.cl_dynamic <> None then error "Cannot have several dynamics" p;
  921. c.cl_dynamic <- Some t
  922. | _ -> error "Should implement by using an interface" p)
  923. in
  924. (*
  925. resolve imports before calling build_inheritance, since it requires full paths.
  926. that means that typedefs are not working, but that's a fair limitation
  927. *)
  928. let rec resolve_imports t =
  929. match t.tpackage with
  930. | _ :: _ -> t
  931. | [] ->
  932. try
  933. let find = List.find (fun lt -> snd (t_path lt) = t.tname) in
  934. let lt = try find ctx.m.curmod.m_types with Not_found -> find ctx.m.module_types in
  935. { t with tpackage = fst (t_path lt) }
  936. with
  937. Not_found -> t
  938. in
  939. let herits = List.map (function
  940. | HExtends t -> HExtends (resolve_imports t)
  941. | HImplements t -> HImplements (resolve_imports t)
  942. | h -> h
  943. ) herits in
  944. List.iter loop (List.filter (ctx.g.do_inherit ctx c p) herits)
  945. let rec type_type_params ctx path get_params p tp =
  946. let n = tp.tp_name in
  947. let c = mk_class ctx.m.curmod (fst path @ [snd path],n) p in
  948. c.cl_types <- List.map (type_type_params ctx c.cl_path get_params p) tp.tp_params;
  949. let t = TInst (c,List.map snd c.cl_types) in
  950. match tp.tp_constraints with
  951. | [] ->
  952. c.cl_kind <- KTypeParameter [];
  953. n, t
  954. | _ ->
  955. let r = exc_protect ctx (fun r ->
  956. r := (fun _ -> error "Recursive constraint parameter is not allowed" p);
  957. let ctx = { ctx with type_params = ctx.type_params @ get_params() } in
  958. let constr = List.map (load_complex_type ctx p) tp.tp_constraints in
  959. List.iter (fun t -> ignore(follow t)) constr; (* force other constraints evaluation to check recursion *)
  960. c.cl_kind <- KTypeParameter constr;
  961. r := (fun _ -> t);
  962. t
  963. ) "constraint" in
  964. delay ctx PForce (fun () -> ignore(!r()));
  965. n, TLazy r
  966. let type_function_params ctx fd fname p =
  967. let params = ref [] in
  968. params := List.map (fun tp ->
  969. type_type_params ctx ([],fname) (fun() -> !params) p tp
  970. ) fd.f_params;
  971. !params
  972. let type_function ctx args ret fmode f do_display p =
  973. let locals = save_locals ctx in
  974. let fargs = List.map (fun (n,c,t) ->
  975. let c = (match c with
  976. | None -> None
  977. | Some e ->
  978. let p = pos e in
  979. let e = ctx.g.do_optimize ctx (type_expr ctx e (WithType t)) in
  980. unify ctx e.etype t p;
  981. match e.eexpr with
  982. | TConst c -> Some c
  983. | _ -> display_error ctx "Parameter default value should be constant" p; None
  984. ) in
  985. add_local ctx n t, c
  986. ) args in
  987. let old_ret = ctx.ret in
  988. let old_fun = ctx.curfun in
  989. let old_opened = ctx.opened in
  990. ctx.curfun <- fmode;
  991. ctx.ret <- ret;
  992. ctx.opened <- [];
  993. let e = match f.f_expr with None -> error "Function body required" p | Some e -> e in
  994. let e = if not do_display then type_expr ctx e NoValue else try
  995. type_expr ctx (Optimizer.optimize_completion_expr e) NoValue
  996. with DisplayTypes [TMono _] | Parser.TypePath (_,None) ->
  997. type_expr ctx e NoValue
  998. in
  999. let rec loop e =
  1000. match e.eexpr with
  1001. | TReturn (Some _) -> raise Exit
  1002. | TFunction _ -> ()
  1003. | _ -> Type.iter loop e
  1004. in
  1005. let have_ret = (try loop e; false with Exit -> true) in
  1006. if have_ret then
  1007. (try return_flow ctx e with Exit -> ())
  1008. else (try type_eq EqStrict ret ctx.t.tvoid with Unify_error _ -> display_error ctx ("Missing return " ^ (s_type (print_context()) ret)) p);
  1009. let rec loop e =
  1010. match e.eexpr with
  1011. | TCall ({ eexpr = TConst TSuper },_) -> raise Exit
  1012. | TFunction _ -> ()
  1013. | _ -> Type.iter loop e
  1014. in
  1015. let has_super_constr() =
  1016. match ctx.curclass.cl_super with
  1017. | None -> false
  1018. | Some (csup,_) ->
  1019. try ignore(get_constructor (fun f->f.cf_type) csup); true with Not_found -> false
  1020. in
  1021. if fmode = FunConstructor && has_super_constr() then
  1022. (try
  1023. loop e;
  1024. display_error ctx "Missing super constructor call" p
  1025. with
  1026. Exit -> ());
  1027. locals();
  1028. let e = match ctx.curfun, ctx.vthis with
  1029. | (FunMember|FunConstructor), Some v ->
  1030. let ev = mk (TVars [v,Some (mk (TConst TThis) ctx.tthis p)]) ctx.t.tvoid p in
  1031. (match e.eexpr with
  1032. | TBlock l -> { e with eexpr = TBlock (ev::l) }
  1033. | _ -> mk (TBlock [ev;e]) e.etype p)
  1034. | _ -> e
  1035. in
  1036. List.iter (fun r -> r := Closed) ctx.opened;
  1037. ctx.ret <- old_ret;
  1038. ctx.curfun <- old_fun;
  1039. ctx.opened <- old_opened;
  1040. e , fargs
  1041. let init_core_api ctx c =
  1042. let ctx2 = (match ctx.g.core_api with
  1043. | None ->
  1044. let com2 = Common.clone ctx.com in
  1045. com2.defines <- PMap.empty;
  1046. Common.define com2 Define.CoreApi;
  1047. Common.define com2 Define.Sys;
  1048. if ctx.in_macro then Common.define com2 Define.Macro;
  1049. com2.class_path <- ctx.com.std_path;
  1050. let ctx2 = ctx.g.do_create com2 in
  1051. ctx.g.core_api <- Some ctx2;
  1052. ctx2
  1053. | Some c ->
  1054. c
  1055. ) in
  1056. let t = load_instance ctx2 { tpackage = fst c.cl_path; tname = snd c.cl_path; tparams = []; tsub = None; } c.cl_pos true in
  1057. flush_pass ctx2 PFinal "core_final";
  1058. match t with
  1059. | TInst (ccore,_) ->
  1060. (match c.cl_doc with
  1061. | None -> c.cl_doc <- ccore.cl_doc
  1062. | Some _ -> ());
  1063. let compare_fields f f2 =
  1064. let p = (match f2.cf_expr with None -> c.cl_pos | Some e -> e.epos) in
  1065. (try
  1066. type_eq EqCoreType (apply_params ccore.cl_types (List.map snd c.cl_types) f.cf_type) f2.cf_type
  1067. with Unify_error l ->
  1068. display_error ctx ("Field " ^ f.cf_name ^ " has different type than in core type") p;
  1069. display_error ctx (error_msg (Unify l)) p);
  1070. if f2.cf_public <> f.cf_public then error ("Field " ^ f.cf_name ^ " has different visibility than core type") p;
  1071. (match f2.cf_doc with
  1072. | None -> f2.cf_doc <- f.cf_doc
  1073. | Some _ -> ());
  1074. if f2.cf_kind <> f.cf_kind then begin
  1075. match f2.cf_kind, f.cf_kind with
  1076. | Method MethInline, Method MethNormal -> () (* allow to add 'inline' *)
  1077. | Method MethNormal, Method MethInline -> () (* allow to disable 'inline' *)
  1078. | _ ->
  1079. error ("Field " ^ f.cf_name ^ " has different property access than core type") p;
  1080. end;
  1081. (match follow f.cf_type, follow f2.cf_type with
  1082. | TFun (pl1,_), TFun (pl2,_) ->
  1083. if List.length pl1 != List.length pl2 then error "Argument count mismatch" p;
  1084. List.iter2 (fun (n1,_,_) (n2,_,_) ->
  1085. if n1 <> n2 then error ("Method parameter name '" ^ n2 ^ "' should be '" ^ n1 ^ "'") p;
  1086. ) pl1 pl2;
  1087. | _ -> ());
  1088. in
  1089. let check_fields fcore fl =
  1090. PMap.iter (fun i f ->
  1091. if not f.cf_public then () else
  1092. let f2 = try PMap.find f.cf_name fl with Not_found -> error ("Missing field " ^ i ^ " required by core type") c.cl_pos in
  1093. compare_fields f f2;
  1094. ) fcore;
  1095. PMap.iter (fun i f ->
  1096. let p = (match f.cf_expr with None -> c.cl_pos | Some e -> e.epos) in
  1097. if f.cf_public && not (Meta.has Meta.Hack f.cf_meta) && not (PMap.mem f.cf_name fcore) && not (List.memq f c.cl_overrides) then error ("Public field " ^ i ^ " is not part of core type") p;
  1098. ) fl;
  1099. in
  1100. check_fields ccore.cl_fields c.cl_fields;
  1101. check_fields ccore.cl_statics c.cl_statics;
  1102. (match ccore.cl_constructor, c.cl_constructor with
  1103. | None, None -> ()
  1104. | Some { cf_public = false }, _ -> ()
  1105. | Some f, Some f2 -> compare_fields f f2
  1106. | None, Some { cf_public = false } -> ()
  1107. | _ -> error "Constructor differs from core type" c.cl_pos)
  1108. | _ -> assert false
  1109. let patch_class ctx c fields =
  1110. let h = (try Some (Hashtbl.find ctx.g.type_patches c.cl_path) with Not_found -> None) in
  1111. match h with
  1112. | None -> fields
  1113. | Some (h,hcl) ->
  1114. c.cl_meta <- c.cl_meta @ hcl.tp_meta;
  1115. let rec loop acc = function
  1116. | [] -> acc
  1117. | f :: l ->
  1118. (* patch arguments types *)
  1119. (match f.cff_kind with
  1120. | FFun ff ->
  1121. let param ((n,opt,t,e) as p) =
  1122. try
  1123. let t2 = (try Hashtbl.find h (("$" ^ f.cff_name ^ "__" ^ n),false) with Not_found -> Hashtbl.find h (("$" ^ n),false)) in
  1124. n, opt, t2.tp_type, e
  1125. with Not_found ->
  1126. p
  1127. in
  1128. f.cff_kind <- FFun { ff with f_args = List.map param ff.f_args }
  1129. | _ -> ());
  1130. (* other patches *)
  1131. match (try Some (Hashtbl.find h (f.cff_name,List.mem AStatic f.cff_access)) with Not_found -> None) with
  1132. | None -> loop (f :: acc) l
  1133. | Some { tp_remove = true } -> loop acc l
  1134. | Some p ->
  1135. f.cff_meta <- f.cff_meta @ p.tp_meta;
  1136. (match p.tp_type with
  1137. | None -> ()
  1138. | Some t ->
  1139. f.cff_kind <- match f.cff_kind with
  1140. | FVar (_,e) -> FVar (Some t,e)
  1141. | FProp (get,set,_,eo) -> FProp (get,set,Some t,eo)
  1142. | FFun f -> FFun { f with f_type = Some t });
  1143. loop (f :: acc) l
  1144. in
  1145. List.rev (loop [] fields)
  1146. let rec string_list_of_expr_path (e,p) =
  1147. match e with
  1148. | EConst (Ident i) -> [i]
  1149. | EField (e,f) -> f :: string_list_of_expr_path e
  1150. | _ -> error "Invalid path" p
  1151. let build_module_def ctx mt meta fvars context_init fbuild =
  1152. let rec loop = function
  1153. | (Meta.Build,args,p) :: l ->
  1154. let epath, el = (match args with
  1155. | [ECall (epath,el),p] -> epath, el
  1156. | _ -> error "Invalid build parameters" p
  1157. ) in
  1158. let s = try String.concat "." (List.rev (string_list_of_expr_path epath)) with Error (_,p) -> error "Build call parameter must be a class path" p in
  1159. if ctx.in_macro then error "You cannot use @:build inside a macro : make sure that your enum is not used in macro" p;
  1160. let old = ctx.g.get_build_infos in
  1161. ctx.g.get_build_infos <- (fun() -> Some (mt, fvars()));
  1162. context_init();
  1163. let r = try apply_macro ctx MBuild s el p with e -> ctx.g.get_build_infos <- old; raise e in
  1164. ctx.g.get_build_infos <- old;
  1165. (match r with
  1166. | None -> error "Build failure" p
  1167. | Some e -> fbuild e; loop l)
  1168. | _ :: l -> loop l
  1169. | [] -> ()
  1170. in
  1171. (* let errors go through to prevent resume if build fails *)
  1172. loop meta
  1173. let init_class ctx c p context_init herits fields =
  1174. let ctx = {
  1175. ctx with
  1176. curclass = c;
  1177. type_params = c.cl_types;
  1178. pass = PBuildClass;
  1179. tthis = (match c.cl_kind with
  1180. | KAbstractImpl a ->
  1181. (match a.a_this with
  1182. | TMono r when !r = None -> TAbstract (a,List.map snd c.cl_types)
  1183. | t -> t)
  1184. | _ -> TInst (c,List.map snd c.cl_types));
  1185. on_error = (fun ctx msg ep ->
  1186. ctx.com.error msg ep;
  1187. (* macros expressions might reference other code, let's recall which class we are actually compiling *)
  1188. if ep.pfile <> c.cl_pos.pfile then ctx.com.error "Defined in this class" c.cl_pos
  1189. );
  1190. } in
  1191. incr stats.s_classes_built;
  1192. let fields = patch_class ctx c fields in
  1193. let fields = ref fields in
  1194. let get_fields() = !fields in
  1195. build_module_def ctx (TClassDecl c) c.cl_meta get_fields context_init (fun (e,p) ->
  1196. match e with
  1197. | EVars [_,Some (CTAnonymous f),None] ->
  1198. List.iter (fun f ->
  1199. if List.mem AMacro f.cff_access then
  1200. (match ctx.g.macros with
  1201. | Some (_,mctx) when Hashtbl.mem mctx.g.types_module c.cl_path ->
  1202. (* assume that if we had already a macro with the same name, it has not been changed during the @:build operation *)
  1203. if not (List.exists (fun f2 -> f2.cff_name = f.cff_name && List.mem AMacro f2.cff_access) (!fields)) then
  1204. error "Class build macro cannot return a macro function when the class has already been compiled into the macro context" p
  1205. | _ -> ())
  1206. ) f;
  1207. fields := f
  1208. | _ -> error "Class build macro must return a single variable with anonymous fields" p
  1209. );
  1210. let fields = !fields in
  1211. let core_api = Meta.has Meta.CoreApi c.cl_meta in
  1212. let is_class_macro = Meta.has Meta.Macro c.cl_meta in
  1213. if is_class_macro then display_error ctx "Macro classes are no longer allowed in haxe 3" p;
  1214. let fields, herits = if is_class_macro && not ctx.in_macro then begin
  1215. c.cl_extern <- true;
  1216. List.filter (fun f -> List.mem AStatic f.cff_access) fields, []
  1217. end else fields, herits in
  1218. if core_api && not ctx.com.display then delay ctx PForce (fun() -> init_core_api ctx c);
  1219. let rec extends_public c =
  1220. Meta.has Meta.PublicFields c.cl_meta ||
  1221. match c.cl_super with
  1222. | None -> false
  1223. | Some (c,_) -> extends_public c
  1224. in
  1225. let extends_public = extends_public c in
  1226. let is_public access parent =
  1227. if List.mem APrivate access then
  1228. false
  1229. else if List.mem APublic access then
  1230. true
  1231. else match parent with
  1232. | Some { cf_public = p } -> p
  1233. | _ -> c.cl_extern || c.cl_interface || extends_public
  1234. in
  1235. let rec get_parent c name =
  1236. match c.cl_super with
  1237. | None -> None
  1238. | Some (csup,_) ->
  1239. try
  1240. Some (PMap.find name csup.cl_fields)
  1241. with
  1242. Not_found -> get_parent csup name
  1243. in
  1244. let type_opt ctx p t =
  1245. match t with
  1246. | None when c.cl_extern || c.cl_interface ->
  1247. display_error ctx "Type required for extern classes and interfaces" p;
  1248. t_dynamic
  1249. | None when core_api ->
  1250. display_error ctx "Type required for core api classes" p;
  1251. t_dynamic
  1252. | _ ->
  1253. load_type_opt ctx p t
  1254. in
  1255. let rec has_field f = function
  1256. | None -> false
  1257. | Some (c,_) ->
  1258. PMap.exists f c.cl_fields || has_field f c.cl_super || List.exists (fun i -> has_field f (Some i)) c.cl_implements
  1259. in
  1260. (match c.cl_super with None -> () | Some _ -> delay ctx PForce (fun() -> check_overriding ctx c));
  1261. if ctx.com.config.pf_overload then delay ctx PForce (fun() -> check_overloads ctx c);
  1262. (* ----------------------- COMPLETION ----------------------------- *)
  1263. let display_file = if ctx.com.display then Common.unique_full_path p.pfile = (!Parser.resume_display).pfile else false in
  1264. let cp = !Parser.resume_display in
  1265. let delayed_expr = ref [] in
  1266. let rec is_full_type t =
  1267. match t with
  1268. | TFun (args,ret) -> is_full_type ret && List.for_all (fun (_,_,t) -> is_full_type t) args
  1269. | TMono r -> (match !r with None -> false | Some t -> is_full_type t)
  1270. | TAbstract _ | TInst _ | TEnum _ | TLazy _ | TDynamic _ | TAnon _ | TType _ -> true
  1271. in
  1272. let bind_type ctx cf r p macro =
  1273. if ctx.com.display then begin
  1274. let cp = !Parser.resume_display in
  1275. if display_file && (cp.pmin = 0 || (p.pmin <= cp.pmin && p.pmax >= cp.pmax)) then begin
  1276. if macro && not ctx.in_macro then
  1277. (* force macro system loading of this class in order to get completion *)
  1278. delay ctx PTypeField (fun() -> ignore(ctx.g.do_macro ctx MExpr c.cl_path cf.cf_name [] p))
  1279. else begin
  1280. cf.cf_type <- TLazy r;
  1281. delayed_expr := (ctx,r) :: !delayed_expr;
  1282. end
  1283. end else begin
  1284. if not (is_full_type cf.cf_type) then cf.cf_type <- TLazy r;
  1285. end
  1286. end else if macro && not ctx.in_macro then
  1287. ()
  1288. else begin
  1289. cf.cf_type <- TLazy r;
  1290. delayed_expr := (ctx,r) :: !delayed_expr;
  1291. end
  1292. in
  1293. let bind_var ctx cf e stat inline =
  1294. let p = cf.cf_pos in
  1295. if not stat && has_field cf.cf_name c.cl_super then error ("Redefinition of variable " ^ cf.cf_name ^ " in subclass is not allowed") p;
  1296. let t = cf.cf_type in
  1297. match e with
  1298. | None -> ()
  1299. | Some e ->
  1300. let r = exc_protect ctx (fun r ->
  1301. if not !return_partial_type then begin
  1302. r := (fun() -> t);
  1303. context_init();
  1304. if ctx.com.verbose then Common.log ctx.com ("Typing " ^ (if ctx.in_macro then "macro " else "") ^ s_type_path c.cl_path ^ "." ^ cf.cf_name);
  1305. let e = type_var_field ctx t e stat p in
  1306. let e = (match cf.cf_kind with
  1307. | Var v when c.cl_extern || Meta.has Meta.Extern cf.cf_meta ->
  1308. if not stat then begin
  1309. display_error ctx "Extern non-static variables may not be initialized" p;
  1310. e
  1311. end else if v.v_read <> AccInline then begin
  1312. display_error ctx "Extern non-inline variables may not be initialized" p;
  1313. e
  1314. end else begin
  1315. match Optimizer.make_constant_expression ctx e with
  1316. | Some e -> e
  1317. | None -> display_error ctx "Extern variable initialization must be a constant value" p; e
  1318. end
  1319. | Var v when not stat || (v.v_read = AccInline) ->
  1320. let e = match Optimizer.make_constant_expression ctx e with Some e -> e | None -> display_error ctx "Variable initialization must be a constant value" p; e in
  1321. e
  1322. | _ ->
  1323. e
  1324. ) in
  1325. cf.cf_expr <- Some e;
  1326. cf.cf_type <- t;
  1327. end;
  1328. t
  1329. ) "bind_var" in
  1330. bind_type ctx cf r (snd e) false
  1331. in
  1332. (* ----------------------- FIELD INIT ----------------------------- *)
  1333. let loop_cf f =
  1334. let name = f.cff_name in
  1335. let p = f.cff_pos in
  1336. let stat = List.mem AStatic f.cff_access in
  1337. let extern = Meta.has Meta.Extern f.cff_meta || c.cl_extern in
  1338. let allow_inline() =
  1339. match c.cl_kind, f.cff_kind with
  1340. | KAbstractImpl _, _ -> true
  1341. |_, FFun _ -> ctx.g.doinline || extern
  1342. | _ -> true
  1343. in
  1344. let inline = List.mem AInline f.cff_access && allow_inline() in
  1345. let override = List.mem AOverride f.cff_access in
  1346. let is_macro = Meta.has Meta.Macro f.cff_meta in
  1347. if is_macro then ctx.com.warning "@:macro should now be 'macro' accessor'" p;
  1348. let is_macro = is_macro || List.mem AMacro f.cff_access in
  1349. List.iter (fun acc ->
  1350. match (acc, f.cff_kind) with
  1351. | APublic, _ | APrivate, _ | AStatic, _ -> ()
  1352. | ADynamic, FFun _ | AOverride, FFun _ | AMacro, FFun _ | AInline, FFun _ | AInline, FVar _ -> ()
  1353. | _, FVar _ -> error ("Invalid accessor '" ^ Ast.s_access acc ^ "' for variable " ^ name) p
  1354. | _, FProp _ -> error ("Invalid accessor '" ^ Ast.s_access acc ^ "' for property " ^ name) p
  1355. ) f.cff_access;
  1356. if override then (match c.cl_super with None -> error "Invalid override: class has no super class" p | _ -> ());
  1357. (* build the per-field context *)
  1358. let ctx = {
  1359. ctx with
  1360. pass = PBuildClass; (* will be set later to PTypeExpr *)
  1361. } in
  1362. match f.cff_kind with
  1363. | FVar (t,e) ->
  1364. if inline && not stat then error "Inline variable must be static" p;
  1365. if inline && e = None then error "Inline variable must be initialized" p;
  1366. let t = (match t with
  1367. | None when not stat && e = None ->
  1368. error ("Type required for member variable " ^ name) p;
  1369. | None ->
  1370. mk_mono()
  1371. | Some t ->
  1372. let old = ctx.type_params in
  1373. if stat then ctx.type_params <- [];
  1374. let t = load_complex_type ctx p t in
  1375. if stat then ctx.type_params <- old;
  1376. t
  1377. ) in
  1378. let cf = {
  1379. cf_name = name;
  1380. cf_doc = f.cff_doc;
  1381. cf_meta = f.cff_meta;
  1382. cf_type = t;
  1383. cf_pos = f.cff_pos;
  1384. cf_kind = Var (if inline then { v_read = AccInline ; v_write = AccNever } else { v_read = AccNormal; v_write = AccNormal });
  1385. cf_expr = None;
  1386. cf_public = is_public f.cff_access None;
  1387. cf_params = [];
  1388. cf_overloads = [];
  1389. } in
  1390. ctx.curfield <- cf;
  1391. bind_var ctx cf e stat inline;
  1392. f, false, cf
  1393. | FFun fd ->
  1394. let params = type_function_params ctx fd f.cff_name p in
  1395. if inline && c.cl_interface then error "You can't declare inline methods in interfaces" p;
  1396. let is_macro = is_macro || (is_class_macro && stat) in
  1397. let f, stat, fd = if not is_macro || stat then
  1398. f, stat, fd
  1399. else if ctx.in_macro then
  1400. (* non-static macros methods are turned into static when we are running the macro *)
  1401. { f with cff_access = AStatic :: f.cff_access }, true, fd
  1402. else
  1403. (* remove display of first argument which will contain the "this" expression *)
  1404. f, stat, { fd with f_args = match fd.f_args with [] -> [] | _ :: l -> l }
  1405. in
  1406. let fd = if not is_macro then
  1407. fd
  1408. else if ctx.in_macro then
  1409. let texpr = CTPath { tpackage = ["haxe";"macro"]; tname = "Expr"; tparams = []; tsub = None } in
  1410. {
  1411. f_params = fd.f_params;
  1412. f_type = (match fd.f_type with None -> Some texpr | t -> t);
  1413. f_args = List.map (fun (a,o,t,e) -> a,o,(match t with None -> Some texpr | _ -> t),e) fd.f_args;
  1414. f_expr = fd.f_expr;
  1415. }
  1416. else
  1417. let tdyn = Some (CTPath { tpackage = []; tname = "Dynamic"; tparams = []; tsub = None }) in
  1418. let to_dyn = function
  1419. | { tpackage = ["haxe";"macro"]; tname = "Expr"; tsub = Some ("ExprOf"); tparams = [TPType t] } -> Some t
  1420. | { tpackage = []; tname = ("ExprOf"); tsub = None; tparams = [TPType t] } -> Some t
  1421. | { tpackage = ["haxe"]; tname = ("PosInfos"); tsub = None; tparams = [] } -> error "haxe.PosInfos is not allowed on macro functions, use Context.currentPos() instead" p
  1422. | _ -> tdyn
  1423. in
  1424. {
  1425. f_params = fd.f_params;
  1426. f_type = (match fd.f_type with Some (CTPath t) -> to_dyn t | _ -> tdyn);
  1427. f_args = List.map (fun (a,o,t,_) -> a,o,(match t with Some (CTPath t) -> to_dyn t | _ -> tdyn),None) fd.f_args;
  1428. f_expr = None;
  1429. }
  1430. in
  1431. let parent = (if not stat then get_parent c name else None) in
  1432. let dynamic = List.mem ADynamic f.cff_access || (match parent with Some { cf_kind = Method MethDynamic } -> true | _ -> false) in
  1433. if inline && dynamic then error "You can't have both 'inline' and 'dynamic'" p;
  1434. ctx.type_params <- (match c.cl_kind with
  1435. | KAbstractImpl a when Meta.has Meta.Impl f.cff_meta || Meta.has Meta.From f.cff_meta || Meta.has Meta.MultiType a.a_meta && Meta.has Meta.To f.cff_meta ->
  1436. params @ a.a_types
  1437. | _ ->
  1438. if stat then params else params @ ctx.type_params);
  1439. let constr = (name = "new") in
  1440. let ret = if constr then ctx.t.tvoid else type_opt ctx p fd.f_type in
  1441. let args = List.map (fun (name,opt,t,c) ->
  1442. let t, c = type_function_param ctx (type_opt ctx p t) c opt p in
  1443. name, c, t
  1444. ) fd.f_args in
  1445. let t = TFun (fun_args args,ret) in
  1446. if constr && c.cl_interface then error "An interface cannot have a constructor" p;
  1447. if c.cl_interface && not stat && fd.f_expr <> None then error "An interface method cannot have a body" p;
  1448. if constr then (match fd.f_type with
  1449. | None | Some (CTPath { tpackage = []; tname = "Void" }) -> ()
  1450. | _ -> error "A class constructor can't have a return value" p
  1451. );
  1452. let cf = {
  1453. cf_name = name;
  1454. cf_doc = f.cff_doc;
  1455. cf_meta = f.cff_meta;
  1456. cf_type = t;
  1457. cf_pos = f.cff_pos;
  1458. cf_kind = Method (if is_macro then MethMacro else if inline then MethInline else if dynamic then MethDynamic else MethNormal);
  1459. cf_expr = None;
  1460. cf_public = is_public f.cff_access parent;
  1461. cf_params = params;
  1462. cf_overloads = [];
  1463. } in
  1464. let do_bind = ref (not (cf.cf_name <> "__init__" && (c.cl_extern && not inline) || c.cl_interface)) in
  1465. (match c.cl_kind with
  1466. | KAbstractImpl a ->
  1467. let m = mk_mono() in
  1468. let ta = TAbstract(a, List.map (fun _ -> mk_mono()) a.a_types) in
  1469. let tthis = if Meta.has Meta.Impl f.cff_meta || Meta.has Meta.To f.cff_meta then monomorphs a.a_types a.a_this else a.a_this in
  1470. if Meta.has Meta.From f.cff_meta then begin
  1471. (* the return type of a from-function must be the abstract, not the underlying type *)
  1472. (try unify_raise ctx t (tfun [m] ta) f.cff_pos with Error (Unify l,p) -> error (error_msg (Unify l)) p);
  1473. a.a_from <- (follow m, Some cf) :: a.a_from
  1474. end else if Meta.has Meta.To f.cff_meta then begin
  1475. (* the first argument of a to-function must be the underlying type, not the abstract *)
  1476. (try unify_raise ctx t (tfun [tthis] m) f.cff_pos with Error (Unify l,p) -> error (error_msg (Unify l)) p);
  1477. (* multitype @:to functions must unify with a_this *)
  1478. if Meta.has Meta.MultiType a.a_meta then delay ctx PFinal (fun () -> unify ctx m tthis f.cff_pos);
  1479. if not (Meta.has Meta.Impl cf.cf_meta) then cf.cf_meta <- (Meta.Impl,[],cf.cf_pos) :: cf.cf_meta;
  1480. a.a_to <- (follow m, Some cf) :: a.a_to
  1481. end else if Meta.has Meta.ArrayAccess f.cff_meta then begin
  1482. a.a_array <- cf :: a.a_array;
  1483. end else if f.cff_name = "_new" && Meta.has Meta.MultiType a.a_meta then
  1484. do_bind := false
  1485. else (try match Meta.get Meta.Op cf.cf_meta with
  1486. | _,[EBinop(op,_,_),_],_ ->
  1487. let targ = if Meta.has Meta.Impl f.cff_meta then tthis else ta in
  1488. let left_eq = type_iseq t (tfun [targ;m] (mk_mono())) in
  1489. let right_eq = type_iseq t (tfun [mk_mono();targ] (mk_mono())) in
  1490. if not (left_eq || right_eq) then error ("The left or right argument type must be " ^ (s_type (print_context()) targ)) f.cff_pos;
  1491. if right_eq && Meta.has Meta.Commutative f.cff_meta then error ("@:commutative is only allowed if the right argument is not " ^ (s_type (print_context()) targ)) f.cff_pos;
  1492. a.a_ops <- (op,cf) :: a.a_ops;
  1493. if fd.f_expr = None then do_bind := false;
  1494. | _,[EUnop(op,flag,_),_],_ ->
  1495. let targ = if Meta.has Meta.Impl f.cff_meta then tthis else ta in
  1496. (try type_eq EqStrict t (tfun [targ] (mk_mono())) with Unify_error l -> raise (Error ((Unify l),f.cff_pos)));
  1497. a.a_unops <- (op,flag,cf) :: a.a_unops;
  1498. if fd.f_expr = None then do_bind := false;
  1499. | _ -> ()
  1500. with Not_found -> ())
  1501. | _ ->
  1502. ());
  1503. init_meta_overloads ctx cf;
  1504. ctx.curfield <- cf;
  1505. let r = exc_protect ctx (fun r ->
  1506. if not !return_partial_type then begin
  1507. r := (fun() -> t);
  1508. context_init();
  1509. incr stats.s_methods_typed;
  1510. if ctx.com.verbose then Common.log ctx.com ("Typing " ^ (if ctx.in_macro then "macro " else "") ^ s_type_path c.cl_path ^ "." ^ name);
  1511. let fmode = (match c.cl_kind with
  1512. | KAbstractImpl _ ->
  1513. (match args with
  1514. | ("this",_,_) :: _ -> FunMemberAbstract
  1515. | _ when name = "_new" -> FunMemberAbstract
  1516. | _ -> FunStatic)
  1517. | _ ->
  1518. if constr then FunConstructor else if stat then FunStatic else FunMember
  1519. ) in
  1520. let display_field = f.cff_pos.pmin <= cp.pmin && f.cff_pos.pmax >= cp.pmax in
  1521. let e , fargs = type_function ctx args ret fmode fd display_field p in
  1522. let f = {
  1523. tf_args = fargs;
  1524. tf_type = ret;
  1525. tf_expr = e;
  1526. } in
  1527. if stat && name = "__init__" then
  1528. (match e.eexpr with
  1529. | TBlock [] | TBlock [{ eexpr = TConst _ }] | TConst _ | TObjectDecl [] -> ()
  1530. | _ -> c.cl_init <- Some e);
  1531. cf.cf_expr <- Some (mk (TFunction f) t p);
  1532. cf.cf_type <- t;
  1533. end;
  1534. t
  1535. ) "type_fun" in
  1536. if !do_bind then bind_type ctx cf r (match fd.f_expr with Some e -> snd e | None -> f.cff_pos) is_macro;
  1537. f, constr, cf
  1538. | FProp (get,set,t,eo) ->
  1539. (match c.cl_kind with
  1540. | KAbstractImpl a when Meta.has Meta.Impl f.cff_meta ->
  1541. ctx.type_params <- a.a_types;
  1542. | _ -> ());
  1543. let ret = (match t, eo with
  1544. | None, None -> error "Property must either define a type or a default value" p;
  1545. | None, _ -> mk_mono()
  1546. | Some t, _ -> load_complex_type ctx p t
  1547. ) in
  1548. let t_get,t_set = match c.cl_kind with
  1549. | KAbstractImpl a ->
  1550. if Meta.has Meta.IsVar f.cff_meta then error "Abstract properties cannot be real variables" f.cff_pos;
  1551. let ta = apply_params a.a_types (List.map snd a.a_types) a.a_this in
  1552. tfun [ta] ret, tfun [ta;ret] ret
  1553. | _ -> tfun [] ret, tfun [ret] ret
  1554. in
  1555. let check_method m t req_name =
  1556. if ctx.com.display then () else
  1557. try
  1558. let _, t2, f = (if stat then let f = PMap.find m c.cl_statics in Some c, f.cf_type, f else class_field c m) in
  1559. (match f.cf_kind with
  1560. | Method MethMacro ->
  1561. display_error ctx "Macro methods cannot be used as property accessor" p;
  1562. display_error ctx "Accessor method is here" f.cf_pos;
  1563. | _ -> ());
  1564. unify_raise ctx t2 t f.cf_pos;
  1565. (match req_name with None -> () | Some n -> display_error ctx ("Please use " ^ n ^ " to name your property access method") f.cf_pos);
  1566. with
  1567. | Error (Unify l,p) -> raise (Error (Stack (Custom ("In method " ^ m ^ " required by property " ^ name),Unify l),p))
  1568. | Not_found ->
  1569. if req_name <> None then display_error ctx "Custom property accessor is no longer supported, please use get/set" p else
  1570. if not (c.cl_interface || c.cl_extern) then display_error ctx ("Method " ^ m ^ " required by property " ^ name ^ " is missing") p
  1571. in
  1572. let get = (match get with
  1573. | "null" -> AccNo
  1574. | "dynamic" -> AccCall
  1575. | "never" -> AccNever
  1576. | "default" -> AccNormal
  1577. | _ ->
  1578. let get = if get = "get" then "get_" ^ name else get in
  1579. delay ctx PForce (fun() -> check_method get t_get (if get <> "get" && get <> "get_" ^ name then Some ("get_" ^ name) else None));
  1580. AccCall
  1581. ) in
  1582. let set = (match set with
  1583. | "null" ->
  1584. (* standard flash library read-only variables can't be accessed for writing, even in subclasses *)
  1585. if c.cl_extern && (match c.cl_path with "flash" :: _ , _ -> true | _ -> false) && ctx.com.platform = Flash then
  1586. AccNever
  1587. else
  1588. AccNo
  1589. | "never" -> AccNever
  1590. | "dynamic" -> AccCall
  1591. | "default" -> AccNormal
  1592. | _ ->
  1593. let set = if set = "set" then "set_" ^ name else set in
  1594. delay ctx PForce (fun() -> check_method set t_set (if set <> "set" && set <> "set_" ^ name then Some ("set_" ^ name) else None));
  1595. AccCall
  1596. ) in
  1597. if set = AccNormal && (match get with AccCall -> true | _ -> false) then error "Unsupported property combination" p;
  1598. let cf = {
  1599. cf_name = name;
  1600. cf_doc = f.cff_doc;
  1601. cf_meta = f.cff_meta;
  1602. cf_pos = f.cff_pos;
  1603. cf_kind = Var { v_read = get; v_write = set };
  1604. cf_expr = None;
  1605. cf_type = ret;
  1606. cf_public = is_public f.cff_access None;
  1607. cf_params = [];
  1608. cf_overloads = [];
  1609. } in
  1610. ctx.curfield <- cf;
  1611. bind_var ctx cf eo stat inline;
  1612. f, false, cf
  1613. in
  1614. let rec check_require = function
  1615. | [] -> None
  1616. | (Meta.Require,conds,_) :: l ->
  1617. let rec loop = function
  1618. | [] -> check_require l
  1619. | [EConst (String _),_] -> check_require l
  1620. | (EConst (Ident i),_) :: l ->
  1621. if not (Common.raw_defined ctx.com i) then
  1622. Some (i,(match List.rev l with (EConst (String msg),_) :: _ -> Some msg | _ -> None))
  1623. else
  1624. loop l
  1625. | _ -> error "Invalid require identifier" p
  1626. in
  1627. loop conds
  1628. | _ :: l ->
  1629. check_require l
  1630. in
  1631. let cl_req = check_require c.cl_meta in
  1632. List.iter (fun f ->
  1633. let p = f.cff_pos in
  1634. try
  1635. let fd , constr, f = loop_cf f in
  1636. let is_static = List.mem AStatic fd.cff_access in
  1637. if (is_static || constr) && c.cl_interface && f.cf_name <> "__init__" then error "You can't declare static fields in interfaces" p;
  1638. let req = check_require fd.cff_meta in
  1639. let req = (match req with None -> if is_static || constr then cl_req else None | _ -> req) in
  1640. (match req with
  1641. | None -> ()
  1642. | Some r -> f.cf_kind <- Var { v_read = AccRequire (fst r, snd r); v_write = AccRequire (fst r, snd r) });
  1643. if constr then begin
  1644. match c.cl_constructor with
  1645. | None ->
  1646. c.cl_constructor <- Some f
  1647. | Some ctor when ctx.com.config.pf_overload ->
  1648. if Meta.has Meta.Overload f.cf_meta && Meta.has Meta.Overload ctor.cf_meta then
  1649. ctor.cf_overloads <- f :: ctor.cf_overloads
  1650. else if Meta.has Meta.Overload f.cf_meta <> Meta.has Meta.Overload ctor.cf_meta then
  1651. display_error ctx ("If using overloaded constructors, all constructors must be declared with @:overload") (if Meta.has Meta.Overload f.cf_meta then ctor.cf_pos else f.cf_pos)
  1652. | Some ctor ->
  1653. display_error ctx "Duplicate constructor" p
  1654. end else if not is_static || f.cf_name <> "__init__" then begin
  1655. let dup = if is_static then PMap.exists f.cf_name c.cl_fields || has_field f.cf_name c.cl_super else PMap.exists f.cf_name c.cl_statics in
  1656. if dup then error ("Same field name can't be use for both static and instance : " ^ f.cf_name) p;
  1657. if List.mem AOverride fd.cff_access then c.cl_overrides <- f :: c.cl_overrides;
  1658. let is_var f = match f.cf_kind with | Var _ -> true | _ -> false in
  1659. if PMap.mem f.cf_name (if is_static then c.cl_statics else c.cl_fields) then
  1660. if ctx.com.config.pf_overload && Meta.has Meta.Overload f.cf_meta && not (is_var f) then
  1661. let mainf = PMap.find f.cf_name (if is_static then c.cl_statics else c.cl_fields) in
  1662. if is_var mainf then display_error ctx "Cannot declare a variable with same name as a method" mainf.cf_pos;
  1663. (if not (Meta.has Meta.Overload mainf.cf_meta) then display_error ctx ("Overloaded methods must have @:overload metadata") mainf.cf_pos);
  1664. mainf.cf_overloads <- f :: mainf.cf_overloads
  1665. else
  1666. display_error ctx ("Duplicate class field declaration : " ^ f.cf_name) p
  1667. else
  1668. if is_static then begin
  1669. c.cl_statics <- PMap.add f.cf_name f c.cl_statics;
  1670. c.cl_ordered_statics <- f :: c.cl_ordered_statics;
  1671. end else begin
  1672. c.cl_fields <- PMap.add f.cf_name f c.cl_fields;
  1673. c.cl_ordered_fields <- f :: c.cl_ordered_fields;
  1674. end;
  1675. end
  1676. with Error (Custom str,p2) when p = p2 ->
  1677. display_error ctx str p
  1678. ) fields;
  1679. (match c.cl_kind with
  1680. | KAbstractImpl a ->
  1681. a.a_to <- List.rev a.a_to;
  1682. a.a_from <- List.rev a.a_from;
  1683. a.a_ops <- List.rev a.a_ops;
  1684. a.a_unops <- List.rev a.a_unops;
  1685. | _ -> ());
  1686. c.cl_ordered_statics <- List.rev c.cl_ordered_statics;
  1687. c.cl_ordered_fields <- List.rev c.cl_ordered_fields;
  1688. (*
  1689. make sure a default contructor with same access as super one will be added to the class structure at some point.
  1690. *)
  1691. let rec add_constructor c =
  1692. match c.cl_constructor, c.cl_super with
  1693. | None, Some ({ cl_constructor = Some cfsup } as csup,cparams) when not c.cl_extern ->
  1694. let cf = {
  1695. cfsup with
  1696. cf_pos = p;
  1697. cf_meta = [];
  1698. cf_doc = None;
  1699. cf_expr = None;
  1700. } in
  1701. let r = exc_protect ctx (fun r ->
  1702. let t = mk_mono() in
  1703. r := (fun() -> t);
  1704. let ctx = { ctx with
  1705. curfield = cf;
  1706. pass = PTypeField;
  1707. } in
  1708. ignore (follow cfsup.cf_type); (* make sure it's typed *)
  1709. (if ctx.com.config.pf_overload then List.iter (fun cf -> ignore (follow cf.cf_type)) cf.cf_overloads);
  1710. let args = (match cfsup.cf_expr with
  1711. | Some { eexpr = TFunction f } ->
  1712. List.map (fun (v,def) ->
  1713. (*
  1714. let's optimize a bit the output by not always copying the default value
  1715. into the inherited constructor when it's not necessary for the platform
  1716. *)
  1717. match ctx.com.platform, def with
  1718. | _, Some _ when not ctx.com.config.pf_static -> v, (Some TNull)
  1719. | Flash, Some (TString _) -> v, (Some TNull)
  1720. | Cpp, Some (TString _) -> v, def
  1721. | Cpp, Some _ -> { v with v_type = ctx.t.tnull v.v_type }, (Some TNull)
  1722. | _ -> v, def
  1723. ) f.tf_args
  1724. | _ ->
  1725. match follow cfsup.cf_type with
  1726. | TFun (args,_) -> List.map (fun (n,o,t) -> alloc_var n (if o then ctx.t.tnull t else t), if o then Some TNull else None) args
  1727. | _ -> assert false
  1728. ) in
  1729. let p = c.cl_pos in
  1730. let vars = List.map (fun (v,def) -> alloc_var v.v_name (apply_params csup.cl_types cparams v.v_type), def) args in
  1731. let super_call = mk (TCall (mk (TConst TSuper) (TInst (csup,cparams)) p,List.map (fun (v,_) -> mk (TLocal v) v.v_type p) vars)) ctx.t.tvoid p in
  1732. let constr = mk (TFunction {
  1733. tf_args = vars;
  1734. tf_type = ctx.t.tvoid;
  1735. tf_expr = super_call;
  1736. }) (TFun (List.map (fun (v,c) -> v.v_name, c <> None, v.v_type) vars,ctx.t.tvoid)) p in
  1737. cf.cf_expr <- Some constr;
  1738. cf.cf_type <- t;
  1739. unify ctx t constr.etype p;
  1740. t
  1741. ) "add_constructor" in
  1742. cf.cf_type <- TLazy r;
  1743. c.cl_constructor <- Some cf;
  1744. delay ctx PForce (fun() -> ignore((!r)()));
  1745. | _ ->
  1746. (* nothing to do *)
  1747. ()
  1748. in
  1749. (* add_constructor does not deal with overloads correctly *)
  1750. if not ctx.com.config.pf_overload then
  1751. add_constructor c;
  1752. (* check overloaded constructors *)
  1753. (if ctx.com.config.pf_overload then match c.cl_constructor with
  1754. | Some ctor ->
  1755. List.iter (fun f ->
  1756. try
  1757. (* TODO: consider making a broader check, and treat some types, like TAnon and type parameters as Dynamic *)
  1758. ignore(List.find (fun f2 -> f != f2 && same_overload_args f.cf_type f2.cf_type f f2) (ctor :: ctor.cf_overloads));
  1759. display_error ctx ("Another overloaded field of same signature was already declared : " ^ f.cf_name) f.cf_pos;
  1760. with Not_found -> ()
  1761. ) (ctor :: ctor.cf_overloads)
  1762. | _ -> ());
  1763. (* push delays in reverse order so they will be run in correct order *)
  1764. List.iter (fun (ctx,r) ->
  1765. ctx.pass <- PTypeField;
  1766. delay ctx PTypeField (fun() -> ignore((!r)()))
  1767. ) !delayed_expr
  1768. let resolve_typedef t =
  1769. match t with
  1770. | TClassDecl _ | TEnumDecl _ | TAbstractDecl _ -> t
  1771. | TTypeDecl td ->
  1772. match follow td.t_type with
  1773. | TEnum (e,_) -> TEnumDecl e
  1774. | TInst (c,_) -> TClassDecl c
  1775. | TAbstract (a,_) -> TAbstractDecl a
  1776. | _ -> t
  1777. let add_module ctx m p =
  1778. let decl_type t =
  1779. let t = t_infos t in
  1780. try
  1781. let m2 = Hashtbl.find ctx.g.types_module t.mt_path in
  1782. if m.m_path <> m2 && String.lowercase (s_type_path m2) = String.lowercase (s_type_path m.m_path) then error ("Module " ^ s_type_path m2 ^ " is loaded with a different case than " ^ s_type_path m.m_path) p;
  1783. error ("Type name " ^ s_type_path t.mt_path ^ " is redefined from module " ^ s_type_path m2) p
  1784. with
  1785. Not_found ->
  1786. Hashtbl.add ctx.g.types_module t.mt_path m.m_path
  1787. in
  1788. List.iter decl_type m.m_types;
  1789. Hashtbl.add ctx.g.modules m.m_path m
  1790. (*
  1791. In this pass, we can access load and access other modules types, but we cannot follow them or access their structure
  1792. since they have not been setup. We also build a context_init list that will be evaluated the first time we evaluate
  1793. an expression into the context
  1794. *)
  1795. let rec init_module_type ctx context_init do_init (decl,p) =
  1796. let get_type name =
  1797. try List.find (fun t -> snd (t_infos t).mt_path = name) ctx.m.curmod.m_types with Not_found -> assert false
  1798. in
  1799. match decl with
  1800. | EImport (path,mode) ->
  1801. let rec loop acc = function
  1802. | x :: l when is_lower_ident (fst x) -> loop (x::acc) l
  1803. | rest -> List.rev acc, rest
  1804. in
  1805. let pack, rest = loop [] path in
  1806. (match rest with
  1807. | [] ->
  1808. (match mode with
  1809. | IAll ->
  1810. ctx.m.wildcard_packages <- List.map fst pack :: ctx.m.wildcard_packages
  1811. | _ ->
  1812. (match List.rev path with
  1813. | [] -> assert false
  1814. | (_,p) :: _ -> error "Module name must start with an uppercase letter" p))
  1815. | (tname,p2) :: rest ->
  1816. let p1 = (match pack with [] -> p2 | (_,p1) :: _ -> p1) in
  1817. let p = punion p1 p2 in
  1818. let md = ctx.g.do_load_module ctx (List.map fst pack,tname) p in
  1819. let types = md.m_types in
  1820. let no_private t = not (t_infos t).mt_private in
  1821. let chk_private t p = if (t_infos t).mt_private then error "You can't import a private type" p in
  1822. let has_name name t = snd (t_infos t).mt_path = name in
  1823. let get_type tname =
  1824. let t = (try List.find (has_name tname) types with Not_found -> error (string_error tname (List.map (fun mt -> snd (t_infos mt).mt_path) types) ("Module " ^ s_type_path md.m_path ^ " does not define type " ^ tname)) p) in
  1825. chk_private t p;
  1826. t
  1827. in
  1828. let rebind t name =
  1829. let _, _, f = ctx.g.do_build_instance ctx t p in
  1830. (* create a temp private typedef, does not register it in module *)
  1831. TTypeDecl {
  1832. t_path = (fst md.m_path @ ["_" ^ snd md.m_path],name);
  1833. t_module = md;
  1834. t_pos = p;
  1835. t_private = true;
  1836. t_doc = None;
  1837. t_meta = [];
  1838. t_types = (t_infos t).mt_types;
  1839. t_type = f (List.map snd (t_infos t).mt_types);
  1840. }
  1841. in
  1842. let add_static_init t name s =
  1843. let name = (match name with None -> s | Some n -> n) in
  1844. match resolve_typedef t with
  1845. | TClassDecl c ->
  1846. c.cl_build();
  1847. ignore(PMap.find s c.cl_statics);
  1848. ctx.m.module_globals <- PMap.add name (TClassDecl c,s) ctx.m.module_globals
  1849. | TEnumDecl e ->
  1850. ignore(PMap.find s e.e_constrs);
  1851. ctx.m.module_globals <- PMap.add name (TEnumDecl e,s) ctx.m.module_globals
  1852. | _ ->
  1853. raise Not_found
  1854. in
  1855. (match mode with
  1856. | INormal | IAsName _ ->
  1857. let name = (match mode with IAsName n -> Some n | _ -> None) in
  1858. (match rest with
  1859. | [] ->
  1860. (match name with
  1861. | None ->
  1862. ctx.m.module_types <- List.filter no_private types @ ctx.m.module_types
  1863. | Some newname ->
  1864. ctx.m.module_types <- rebind (get_type tname) newname :: ctx.m.module_types);
  1865. | [tsub,p2] ->
  1866. let p = punion p1 p2 in
  1867. (try
  1868. let tsub = List.find (has_name tsub) types in
  1869. chk_private tsub p;
  1870. ctx.m.module_types <- (match name with None -> tsub | Some n -> rebind tsub n) :: ctx.m.module_types
  1871. with Not_found ->
  1872. (* this might be a static property, wait later to check *)
  1873. let tmain = get_type tname in
  1874. context_init := (fun() ->
  1875. try
  1876. add_static_init tmain name tsub
  1877. with Not_found ->
  1878. error (s_type_path (t_infos tmain).mt_path ^ " has no field or subtype " ^ tsub) p
  1879. ) :: !context_init)
  1880. | (tsub,p2) :: (fname,p3) :: rest ->
  1881. (match rest with
  1882. | [] -> ()
  1883. | (n,p) :: _ -> error ("Unexpected " ^ n) p);
  1884. let tsub = get_type tsub in
  1885. context_init := (fun() ->
  1886. try
  1887. add_static_init tsub name fname
  1888. with Not_found ->
  1889. error (s_type_path (t_infos tsub).mt_path ^ " has no field " ^ fname) (punion p p3)
  1890. ) :: !context_init;
  1891. )
  1892. | IAll ->
  1893. let t = (match rest with
  1894. | [] -> get_type tname
  1895. | [tsub,_] -> get_type tsub
  1896. | _ :: (n,p) :: _ -> error ("Unexpected " ^ n) p
  1897. ) in
  1898. context_init := (fun() ->
  1899. match resolve_typedef t with
  1900. | TClassDecl c
  1901. | TAbstractDecl {a_impl = Some c} ->
  1902. c.cl_build();
  1903. PMap.iter (fun _ cf -> if not (has_meta Meta.NoImportGlobal cf.cf_meta) then ctx.m.module_globals <- PMap.add cf.cf_name (TClassDecl c,cf.cf_name) ctx.m.module_globals) c.cl_statics
  1904. | TEnumDecl e ->
  1905. PMap.iter (fun _ c -> if not (has_meta Meta.NoImportGlobal c.ef_meta) then ctx.m.module_globals <- PMap.add c.ef_name (TEnumDecl e,c.ef_name) ctx.m.module_globals) e.e_constrs
  1906. | _ ->
  1907. error "No statics to import from this type" p
  1908. ) :: !context_init
  1909. ))
  1910. | EUsing t ->
  1911. (* do the import first *)
  1912. let types = (match t.tsub with
  1913. | None ->
  1914. let md = ctx.g.do_load_module ctx (t.tpackage,t.tname) p in
  1915. let types = List.filter (fun t -> not (t_infos t).mt_private) md.m_types in
  1916. ctx.m.module_types <- types @ ctx.m.module_types;
  1917. types
  1918. | Some _ ->
  1919. let t = load_type_def ctx p t in
  1920. ctx.m.module_types <- t :: ctx.m.module_types;
  1921. [t]
  1922. ) in
  1923. (* delay the using since we need to resolve typedefs *)
  1924. let filter_classes types =
  1925. let rec loop acc types = match types with
  1926. | td :: l ->
  1927. (match resolve_typedef td with
  1928. | TClassDecl c ->
  1929. loop (c :: acc) l
  1930. | td ->
  1931. loop acc l)
  1932. | [] ->
  1933. acc
  1934. in
  1935. loop [] types
  1936. in
  1937. context_init := (fun() -> ctx.m.module_using <- filter_classes types @ ctx.m.module_using) :: !context_init
  1938. | EClass d ->
  1939. let c = (match get_type d.d_name with TClassDecl c -> c | _ -> assert false) in
  1940. let herits = d.d_flags in
  1941. if Meta.has Meta.Generic c.cl_meta && c.cl_types <> [] then c.cl_kind <- KGeneric;
  1942. if c.cl_path = (["haxe";"macro"],"MacroType") then c.cl_kind <- KMacroType;
  1943. c.cl_extern <- List.mem HExtern herits;
  1944. c.cl_interface <- List.mem HInterface herits;
  1945. let build() =
  1946. c.cl_build <- (fun()->());
  1947. set_heritance ctx c herits p;
  1948. init_class ctx c p do_init d.d_flags d.d_data
  1949. in
  1950. ctx.pass <- PBuildClass;
  1951. ctx.curclass <- c;
  1952. c.cl_build <- make_pass ctx build;
  1953. ctx.pass <- PBuildModule;
  1954. ctx.curclass <- null_class;
  1955. delay ctx PBuildClass (fun() -> c.cl_build());
  1956. | EEnum d ->
  1957. let e = (match get_type d.d_name with TEnumDecl e -> e | _ -> assert false) in
  1958. let ctx = { ctx with type_params = e.e_types } in
  1959. let h = (try Some (Hashtbl.find ctx.g.type_patches e.e_path) with Not_found -> None) in
  1960. (match h with
  1961. | None -> ()
  1962. | Some (h,hcl) ->
  1963. Hashtbl.iter (fun _ _ -> error "Field type patch not supported for enums" e.e_pos) h;
  1964. e.e_meta <- e.e_meta @ hcl.tp_meta);
  1965. let constructs = ref d.d_data in
  1966. let get_constructs() =
  1967. List.map (fun c ->
  1968. {
  1969. cff_name = c.ec_name;
  1970. cff_doc = c.ec_doc;
  1971. cff_meta = c.ec_meta;
  1972. cff_pos = c.ec_pos;
  1973. cff_access = [];
  1974. cff_kind = (match c.ec_args, c.ec_params with
  1975. | [], [] -> FVar (c.ec_type,None)
  1976. | _ -> FFun { f_params = c.ec_params; f_type = c.ec_type; f_expr = None; f_args = List.map (fun (n,o,t) -> n,o,Some t,None) c.ec_args });
  1977. }
  1978. ) (!constructs)
  1979. in
  1980. let init () = List.iter (fun f -> f()) !context_init in
  1981. build_module_def ctx (TEnumDecl e) e.e_meta get_constructs init (fun (e,p) ->
  1982. match e with
  1983. | EVars [_,Some (CTAnonymous fields),None] ->
  1984. constructs := List.map (fun f ->
  1985. let args, params, t = (match f.cff_kind with
  1986. | FVar (t,None) -> [], [], t
  1987. | FFun { f_params = pl; f_type = t; f_expr = (None|Some (EBlock [],_)); f_args = al } ->
  1988. let al = List.map (fun (n,o,t,_) -> match t with None -> error "Missing function parameter type" f.cff_pos | Some t -> n,o,t) al in
  1989. al, pl, t
  1990. | _ ->
  1991. error "Invalid enum constructor in @:build result" p
  1992. ) in
  1993. {
  1994. ec_name = f.cff_name;
  1995. ec_doc = f.cff_doc;
  1996. ec_meta = f.cff_meta;
  1997. ec_pos = f.cff_pos;
  1998. ec_args = args;
  1999. ec_params = params;
  2000. ec_type = t;
  2001. }
  2002. ) fields
  2003. | _ -> error "Enum build macro must return a single variable with anonymous object fields" p
  2004. );
  2005. let et = TEnum (e,List.map snd e.e_types) in
  2006. let names = ref [] in
  2007. let index = ref 0 in
  2008. List.iter (fun c ->
  2009. let p = c.ec_pos in
  2010. let params = ref [] in
  2011. params := List.map (fun tp -> type_type_params ctx ([],c.ec_name) (fun() -> !params) c.ec_pos tp) c.ec_params;
  2012. let params = !params in
  2013. let ctx = { ctx with type_params = params @ ctx.type_params } in
  2014. let rt = (match c.ec_type with
  2015. | None -> et
  2016. | Some t ->
  2017. let t = load_complex_type ctx p t in
  2018. (match follow t with
  2019. | TEnum (te,_) when te == e ->
  2020. ()
  2021. | _ ->
  2022. error "Explicit enum type must be of the same enum type" p);
  2023. t
  2024. ) in
  2025. let t = (match c.ec_args with
  2026. | [] -> rt
  2027. | l ->
  2028. let pnames = ref PMap.empty in
  2029. TFun (List.map (fun (s,opt,t) ->
  2030. (match t with CTPath({tpackage=[];tname="Void"}) -> error "Arguments of type Void are not allowed in enum constructors" c.ec_pos | _ -> ());
  2031. if PMap.mem s (!pnames) then error ("Duplicate parameter '" ^ s ^ "' in enum constructor " ^ c.ec_name) p;
  2032. pnames := PMap.add s () (!pnames);
  2033. s, opt, load_type_opt ~opt ctx p (Some t)
  2034. ) l, rt)
  2035. ) in
  2036. if PMap.mem c.ec_name e.e_constrs then error ("Duplicate constructor " ^ c.ec_name) p;
  2037. e.e_constrs <- PMap.add c.ec_name {
  2038. ef_name = c.ec_name;
  2039. ef_type = t;
  2040. ef_pos = p;
  2041. ef_doc = c.ec_doc;
  2042. ef_index = !index;
  2043. ef_params = params;
  2044. ef_meta = c.ec_meta;
  2045. } e.e_constrs;
  2046. incr index;
  2047. names := c.ec_name :: !names;
  2048. ) (!constructs);
  2049. e.e_names <- List.rev !names;
  2050. e.e_extern <- e.e_extern
  2051. | ETypedef d ->
  2052. let t = (match get_type d.d_name with TTypeDecl t -> t | _ -> assert false) in
  2053. let ctx = { ctx with type_params = t.t_types } in
  2054. let tt = load_complex_type ctx p d.d_data in
  2055. (*
  2056. we exceptionnaly allow follow here because we don't care the type we get as long as it's not our own
  2057. *)
  2058. if t.t_type == follow tt then error "Recursive typedef is not allowed" p;
  2059. (match t.t_type with
  2060. | TMono r ->
  2061. (match !r with
  2062. | None -> r := Some tt;
  2063. | Some _ -> assert false);
  2064. | _ -> assert false);
  2065. | EAbstract d ->
  2066. let a = (match get_type d.d_name with TAbstractDecl a -> a | _ -> assert false) in
  2067. let ctx = { ctx with type_params = a.a_types } in
  2068. let is_type = ref false in
  2069. let load_type t from =
  2070. let t = load_complex_type ctx p t in
  2071. if not (Meta.has Meta.CoreType a.a_meta) then begin
  2072. if !is_type then begin
  2073. delay ctx PFinal (fun () ->
  2074. let at = monomorphs a.a_types a.a_this in
  2075. (try (if from then Type.unify t at else Type.unify at t) with Unify_error _ -> error "You can only declare from/to with compatible types" p)
  2076. );
  2077. end else
  2078. error "Missing underlying type declaration or @:coreType declaration" p;
  2079. end;
  2080. t
  2081. in
  2082. List.iter (function
  2083. | AFromType t -> a.a_from <- (load_type t true, None) :: a.a_from
  2084. | AToType t -> a.a_to <- (load_type t false, None) :: a.a_to
  2085. | AIsType t ->
  2086. if a.a_impl = None then error "Abstracts with underlying type must have an implementation" a.a_pos;
  2087. let at = load_complex_type ctx p t in
  2088. (match at with TAbstract(a2,_) when a == a2 -> error "Abstract underlying type cannot be recursive" a.a_pos | _ -> ());
  2089. a.a_this <- at;
  2090. is_type := true;
  2091. | APrivAbstract -> ()
  2092. ) d.d_flags;
  2093. if not !is_type && (match a.a_impl with Some _ -> true | None -> not (Meta.has Meta.CoreType a.a_meta)) then
  2094. error "Abstract is missing underlying type declaration" a.a_pos
  2095. let type_module ctx m file tdecls p =
  2096. let m, decls, tdecls = make_module ctx m file tdecls p in
  2097. add_module ctx m p;
  2098. (* define the per-module context for the next pass *)
  2099. let ctx = {
  2100. com = ctx.com;
  2101. g = ctx.g;
  2102. t = ctx.t;
  2103. m = {
  2104. curmod = m;
  2105. module_types = ctx.g.std.m_types;
  2106. module_using = [];
  2107. module_globals = PMap.empty;
  2108. wildcard_packages = [];
  2109. };
  2110. meta = [];
  2111. pass = PBuildModule;
  2112. on_error = (fun ctx msg p -> ctx.com.error msg p);
  2113. macro_depth = ctx.macro_depth;
  2114. curclass = null_class;
  2115. curfield = null_field;
  2116. tthis = ctx.tthis;
  2117. ret = ctx.ret;
  2118. locals = PMap.empty;
  2119. type_params = [];
  2120. curfun = FunStatic;
  2121. untyped = false;
  2122. in_super_call = false;
  2123. in_macro = ctx.in_macro;
  2124. in_display = false;
  2125. in_loop = false;
  2126. opened = [];
  2127. vthis = None;
  2128. } in
  2129. (* here is an additional PASS 1 phase, which define the type parameters for all module types.
  2130. Constraints are handled lazily (no other type is loaded) because they might be recursive anyway *)
  2131. List.iter (fun d ->
  2132. match d with
  2133. | (TClassDecl c, (EClass d, p)) ->
  2134. c.cl_types <- List.map (type_type_params ctx c.cl_path (fun() -> c.cl_types) p) d.d_params;
  2135. | (TEnumDecl e, (EEnum d, p)) ->
  2136. e.e_types <- List.map (type_type_params ctx e.e_path (fun() -> e.e_types) p) d.d_params;
  2137. | (TTypeDecl t, (ETypedef d, p)) ->
  2138. t.t_types <- List.map (type_type_params ctx t.t_path (fun() -> t.t_types) p) d.d_params;
  2139. | (TAbstractDecl a, (EAbstract d, p)) ->
  2140. a.a_types <- List.map (type_type_params ctx a.a_path (fun() -> a.a_types) p) d.d_params;
  2141. | _ ->
  2142. assert false
  2143. ) decls;
  2144. (* setup module types *)
  2145. let context_init = ref [] in
  2146. let do_init() =
  2147. match !context_init with
  2148. | [] -> ()
  2149. | l -> context_init := []; List.iter (fun f -> f()) (List.rev l)
  2150. in
  2151. List.iter (init_module_type ctx context_init do_init) tdecls;
  2152. m
  2153. let resolve_module_file com m remap p =
  2154. let forbid = ref false in
  2155. let file = (match m with
  2156. | [] , name -> name
  2157. | x :: l , name ->
  2158. let x = (try
  2159. match PMap.find x com.package_rules with
  2160. | Forbidden -> forbid := true; x
  2161. | Directory d -> d
  2162. | Remap d -> remap := d :: l; d
  2163. with Not_found -> x
  2164. ) in
  2165. String.concat "/" (x :: l) ^ "/" ^ name
  2166. ) ^ ".hx" in
  2167. let file = Common.find_file com file in
  2168. let file = (match String.lowercase (snd m) with
  2169. | "con" | "aux" | "prn" | "nul" | "com1" | "com2" | "com3" | "lpt1" | "lpt2" | "lpt3" when Sys.os_type = "Win32" ->
  2170. (* these names are reserved by the OS - old DOS legacy, such files cannot be easily created but are reported as visible *)
  2171. if (try (Unix.stat file).Unix.st_size with _ -> 0) > 0 then file else raise Not_found
  2172. | _ -> file
  2173. ) in
  2174. if !forbid then begin
  2175. let _, decls = (!parse_hook) com file p in
  2176. let meta = (match decls with
  2177. | (EClass d,_) :: _ -> d.d_meta
  2178. | (EEnum d,_) :: _ -> d.d_meta
  2179. | (EAbstract d,_) :: _ -> d.d_meta
  2180. | (ETypedef d,_) :: _ -> d.d_meta
  2181. | _ -> []
  2182. ) in
  2183. if not (Meta.has Meta.NoPackageRestrict meta) then begin
  2184. let x = (match fst m with [] -> assert false | x :: _ -> x) in
  2185. raise (Forbid_package ((x,m,p),[],if Common.defined com Define.Macro then "macro" else platform_name com.platform));
  2186. end;
  2187. end;
  2188. file
  2189. let parse_module ctx m p =
  2190. let remap = ref (fst m) in
  2191. let file = resolve_module_file ctx.com m remap p in
  2192. let pack, decls = (!parse_hook) ctx.com file p in
  2193. if pack <> !remap then begin
  2194. let spack m = if m = [] then "<empty>" else String.concat "." m in
  2195. if p == Ast.null_pos then
  2196. display_error ctx ("Invalid commandline class : " ^ s_type_path m ^ " should be " ^ s_type_path (pack,snd m)) p
  2197. else
  2198. display_error ctx ("Invalid package : " ^ spack (fst m) ^ " should be " ^ spack pack) p
  2199. end;
  2200. file, if !remap <> fst m then
  2201. (* build typedefs to redirect to real package *)
  2202. List.rev (List.fold_left (fun acc (t,p) ->
  2203. let build f d =
  2204. let priv = List.mem f d.d_flags in
  2205. (ETypedef {
  2206. d_name = d.d_name;
  2207. d_doc = None;
  2208. d_meta = [];
  2209. d_params = d.d_params;
  2210. d_flags = if priv then [EPrivate] else [];
  2211. d_data = CTPath (if priv then { tpackage = []; tname = "Dynamic"; tparams = []; tsub = None; } else
  2212. {
  2213. tpackage = !remap;
  2214. tname = d.d_name;
  2215. tparams = List.map (fun tp ->
  2216. TPType (CTPath { tpackage = []; tname = tp.tp_name; tparams = []; tsub = None; })
  2217. ) d.d_params;
  2218. tsub = None;
  2219. });
  2220. },p) :: acc
  2221. in
  2222. match t with
  2223. | EClass d -> build HPrivate d
  2224. | EEnum d -> build EPrivate d
  2225. | ETypedef d -> build EPrivate d
  2226. | EAbstract d -> build APrivAbstract d
  2227. | EImport _ | EUsing _ -> acc
  2228. ) [(EImport (List.map (fun s -> s,null_pos) (!remap @ [snd m]),INormal),null_pos)] decls)
  2229. else
  2230. decls
  2231. let load_module ctx m p =
  2232. let m2 = (try
  2233. Hashtbl.find ctx.g.modules m
  2234. with
  2235. Not_found ->
  2236. match !type_module_hook ctx m p with
  2237. | Some m -> m
  2238. | None ->
  2239. let file, decls = (try
  2240. parse_module ctx m p
  2241. with Not_found ->
  2242. let rec loop = function
  2243. | [] ->
  2244. raise (Error (Module_not_found m,p))
  2245. | load :: l ->
  2246. match load m p with
  2247. | None -> loop l
  2248. | Some (file,(_,a)) -> file, a
  2249. in
  2250. loop ctx.com.load_extern_type
  2251. ) in
  2252. try
  2253. type_module ctx m file decls p
  2254. with Forbid_package (inf,pl,pf) when p <> Ast.null_pos ->
  2255. raise (Forbid_package (inf,p::pl,pf))
  2256. ) in
  2257. add_dependency ctx.m.curmod m2;
  2258. if ctx.pass = PTypeField then flush_pass ctx PBuildClass "load_module";
  2259. m2
  2260. ;;
  2261. type_function_params_rec := type_function_params